text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
export { default as AppWrapper } from './AppWrapper.vue'
export * from './AppWrapperRoute'
export * from './types'
| owncloud/web/packages/web-pkg/src/components/AppTemplates/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/AppTemplates/index.ts",
"repo_id": "owncloud",
"token_count": 38
} | 823 |
<template>
<span class="oc-resource-size" v-text="formattedSize" />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { filesize } from 'filesize'
/**
* Displays a formatted resource size
*/
export default defineComponent({
name: 'ResourceSize',
props: {
/**
* Number of bytes to display as a reasonable resource size string.
* Value can be a non-formatted string or a number.
*/
size: {
type: [String, Number],
required: true
}
},
computed: {
formattedSize() {
const size = parseInt(this.size.toString())
if (isNaN(size)) {
return '?'
}
if (size < 0) {
return '--'
}
const mb = 1048576
return filesize(size, {
round: size < mb ? 0 : 1,
locale: (this.$language?.current || '').split('_')[0]
})
}
}
})
</script>
| owncloud/web/packages/web-pkg/src/components/FilesList/ResourceSize.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/FilesList/ResourceSize.vue",
"repo_id": "owncloud",
"token_count": 366
} | 824 |
<template>
<div
class="no-content-message oc-flex oc-flex-column oc-flex-center oc-flex-middle oc-text-center"
>
<oc-icon :name="icon" type="div" size="xxlarge" :fill-type="iconFillType" class="oc-mb-m" />
<div class="oc-text-muted oc-text-xlarge">
<slot name="message" />
</div>
<div class="oc-text-muted">
<slot name="callToAction" />
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: 'NoContentMessage',
props: {
icon: {
type: String,
required: true
},
iconFillType: {
type: String,
default: 'fill'
}
}
})
</script>
<style>
.no-content-message {
height: 75vh;
}
.space-frontpage .no-content-message {
height: 55vh;
}
</style>
| owncloud/web/packages/web-pkg/src/components/NoContentMessage.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/NoContentMessage.vue",
"repo_id": "owncloud",
"token_count": 344
} | 825 |
<template>
<div class="space_info oc-p-s">
<div class="space_info__body oc-text-overflow oc-flex oc-flex-middle">
<div class="oc-mr-s">
<oc-icon
name="layout-grid"
:size="resource.description ? 'large' : 'medium'"
class="oc-display-block"
/>
</div>
<div>
<h3 data-testid="space-info-name" class="oc-font-semibold oc-m-rm" v-text="resource.name" />
<span data-testid="space-info-subtitle" v-text="resource.description" />
</div>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, inject } from 'vue'
import { Resource } from '@ownclouders/web-client'
export default defineComponent({
name: 'SpaceInfo',
setup() {
return {
resource: inject<Resource>('resource')
}
}
})
</script>
<style lang="scss">
.space_info {
&.sidebar-panel__space_info {
border-bottom: 1px solid var(--oc-color-border);
}
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
grid-gap: 5px;
background-color: var(--oc-color-background-default);
padding: var(--oc-space-small) var(--oc-space-small) 0 var(--oc-space-small);
&__body {
text-align: left;
font-size: var(--oc-font-size-small);
h3 {
font-size: var(--oc-font-size-medium);
}
}
}
</style>
| owncloud/web/packages/web-pkg/src/components/SideBar/Spaces/SpaceInfo.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/SideBar/Spaces/SpaceInfo.vue",
"repo_id": "owncloud",
"token_count": 573
} | 826 |
import {
isLocationCommonActive,
isLocationPublicActive,
isLocationSpacesActive
} from '../../../router'
import { computed, unref } from 'vue'
import { useGettext } from 'vue3-gettext'
import { FileAction, FileActionOptions } from '../types'
import { isProjectSpaceResource } from '@ownclouders/web-client/src/helpers'
import { useRouter } from '../../router'
import { useConfigStore, useClipboardStore, useResourcesStore } from '../../piniaStores'
import { storeToRefs } from 'pinia'
export const useFileActionsCopy = () => {
const configStore = useConfigStore()
const router = useRouter()
const { copyResources } = useClipboardStore()
const language = useGettext()
const { $gettext } = language
const resourcesStore = useResourcesStore()
const { currentFolder } = storeToRefs(resourcesStore)
const isMacOs = computed(() => {
return window.navigator.platform.match('Mac')
})
const copyShortcutString = computed(() => {
if (unref(isMacOs)) {
return $gettext('⌘ + C')
}
return $gettext('Ctrl + C')
})
const handler = ({ resources }: FileActionOptions) => {
if (isLocationCommonActive(router, 'files-common-search')) {
resources = resources.filter((r) => !isProjectSpaceResource(r))
}
copyResources(resources)
}
const actions = computed((): FileAction[] => {
return [
{
name: 'copy',
icon: 'file-copy-2',
handler,
shortcut: unref(copyShortcutString),
label: () => $gettext('Copy'),
isVisible: ({ resources }) => {
if (
!isLocationSpacesActive(router, 'files-spaces-generic') &&
!isLocationPublicActive(router, 'files-public-link') &&
!isLocationCommonActive(router, 'files-common-favorites') &&
!isLocationCommonActive(router, 'files-common-search')
) {
return false
}
if (isLocationSpacesActive(router, 'files-spaces-projects')) {
return false
}
if (resources.length === 0) {
return false
}
if (isLocationPublicActive(router, 'files-public-link')) {
return unref(currentFolder).canCreate()
}
if (
isLocationCommonActive(router, 'files-common-search') &&
resources.every((r) => isProjectSpaceResource(r))
) {
return false
}
if (unref(configStore.options.runningOnEos)) {
// CERNBox does not allow actions above home/project root
const elems = resources[0].path?.split('/').filter(Boolean) || [] //"/eos/project/c/cernbox"
if (isLocationSpacesActive(router, 'files-spaces-generic') && elems.length < 5) {
return false
}
}
// copy can't be restricted in authenticated context, because
// a user always has their home dir with write access
return true
},
componentType: 'button',
class: 'oc-files-actions-copy-trigger'
}
]
})
return {
actions
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsCopy.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsCopy.ts",
"repo_id": "owncloud",
"token_count": 1278
} | 827 |
import {
isLocationCommonActive,
isLocationPublicActive,
isLocationSharesActive,
isLocationSpacesActive
} from '../../../router'
import { useIsFilesAppActive } from '../helpers'
import { useRouter } from '../../router'
import { FileAction, FileActionOptions } from '../types'
import { useIsSearchActive } from '../helpers'
import { computed, unref } from 'vue'
import { useGettext } from 'vue3-gettext'
import { useClientService } from '../../clientService'
import DOMPurify from 'dompurify'
import { useMessages } from '../../piniaStores'
export const useFileActionsOpenShortcut = () => {
const { showErrorMessage } = useMessages()
const router = useRouter()
const { $gettext } = useGettext()
const isFilesAppActive = useIsFilesAppActive()
const isSearchActive = useIsSearchActive()
const clientService = useClientService()
const extractUrl = (fileContents: string) => {
const regex = /URL=(.+)/
const match = fileContents.match(regex)
if (match && match[1]) {
return match[1]
} else {
throw new Error('unable to extract url')
}
}
const handler = async ({ resources, space }: FileActionOptions) => {
try {
const webURL = new URL(window.location.href)
const fileContents = (await clientService.webdav.getFileContents(space, resources[0])).body
let url = extractUrl(fileContents)
// Add protocol if missing
url = url.match(/^http[s]?:\/\//) ? url : `https://${url}`
// Omit possible xss code
url = DOMPurify.sanitize(url, { USE_PROFILES: { html: true } })
if (url.startsWith(webURL.origin)) {
window.location.href = url
return
}
window.open(url)
} catch (e) {
console.error(e)
showErrorMessage({
title: $gettext('Failed to open shortcut'),
errors: [e]
})
}
}
const actions = computed((): FileAction[] => [
{
name: 'open-shortcut',
icon: 'external-link',
handler,
label: () => {
return $gettext('Open shortcut')
},
isVisible: ({ resources }) => {
if (
unref(isFilesAppActive) &&
!unref(isSearchActive) &&
!isLocationSpacesActive(router, 'files-spaces-generic') &&
!isLocationPublicActive(router, 'files-public-link') &&
!isLocationCommonActive(router, 'files-common-favorites') &&
!isLocationCommonActive(router, 'files-common-search') &&
!isLocationSharesActive(router, 'files-shares-with-me') &&
!isLocationSharesActive(router, 'files-shares-with-others') &&
!isLocationSharesActive(router, 'files-shares-via-link')
) {
return false
}
if (resources.length !== 1) {
return false
}
if (resources[0].extension !== 'url') {
return false
}
return resources[0].canDownload()
},
componentType: 'button',
class: 'oc-files-actions-open-short-cut-trigger'
}
])
return {
actions,
// Hack for unit tests
extractUrl
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsOpenShortcut.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsOpenShortcut.ts",
"repo_id": "owncloud",
"token_count": 1237
} | 828 |
import { computed, unref } from 'vue'
import { useGettext } from 'vue3-gettext'
import { SpaceResource } from '@ownclouders/web-client/src'
import { useClientService } from '../../clientService'
import { useRoute } from '../../router'
import { eventBus } from '../../../services'
import { useAbility } from '../../ability'
import { SpaceAction, SpaceActionOptions } from '../types'
import { isProjectSpaceResource } from '@ownclouders/web-client/src/helpers'
import {
useMessages,
useModals,
useResourcesStore,
useSpacesStore,
useUserStore
} from '../../piniaStores'
export const useSpaceActionsDelete = () => {
const { showMessage, showErrorMessage } = useMessages()
const userStore = useUserStore()
const { $gettext, $ngettext } = useGettext()
const ability = useAbility()
const clientService = useClientService()
const route = useRoute()
const { dispatchModal } = useModals()
const spacesStore = useSpacesStore()
const { removeResources } = useResourcesStore()
const filterResourcesToDelete = (resources: SpaceResource[]) => {
return resources.filter(
(r) => isProjectSpaceResource(r) && r.canBeDeleted({ user: userStore.user, ability })
)
}
const deleteSpaces = async (spaces: SpaceResource[]) => {
const client = clientService.graphAuthenticated
const promises = spaces.map((space) =>
client.drives.deleteDrive(space.id.toString()).then(() => {
removeResources([space])
spacesStore.removeSpace(space)
return true
})
)
const results = await Promise.allSettled(promises)
const succeeded = results.filter((r) => r.status === 'fulfilled')
if (succeeded.length) {
const title =
succeeded.length === 1 && spaces.length === 1
? $gettext('Space "%{space}" was deleted successfully', { space: spaces[0].name })
: $ngettext(
'%{spaceCount} space was deleted successfully',
'%{spaceCount} spaces were deleted successfully',
succeeded.length,
{ spaceCount: succeeded.length.toString() },
true
)
showMessage({ title })
}
const failed = results.filter((r) => r.status === 'rejected')
if (failed.length) {
failed.forEach(console.error)
const title =
failed.length === 1 && spaces.length === 1
? $gettext('Failed to delete space "%{space}"', { space: spaces[0].name })
: $ngettext(
'Failed to delete %{spaceCount} space',
'Failed to delete %{spaceCount} spaces',
failed.length,
{ spaceCount: failed.length.toString() },
true
)
showErrorMessage({
title,
errors: (failed as PromiseRejectedResult[]).map((f) => f.reason)
})
}
if (unref(route).name === 'admin-settings-spaces') {
eventBus.publish('app.admin-settings.list.load')
}
}
const handler = ({ resources }: SpaceActionOptions) => {
const allowedResources = filterResourcesToDelete(resources)
if (!allowedResources.length) {
return
}
const message = $ngettext(
'Are you sure you want to delete the selected space?',
'Are you sure you want to delete %{count} selected spaces?',
allowedResources.length,
{ count: allowedResources.length.toString() }
)
dispatchModal({
title: $ngettext(
'Delete Space "%{space}"?',
'Delete %{spaceCount} Spaces?',
allowedResources.length,
{
space: allowedResources[0].name,
spaceCount: allowedResources.length.toString()
}
),
confirmText: $gettext('Delete'),
message: message,
hasInput: false,
onConfirm: () => deleteSpaces(allowedResources)
})
}
const actions = computed((): SpaceAction[] => [
{
name: 'delete',
icon: 'delete-bin',
label: () => $gettext('Delete'),
handler,
isVisible: ({ resources }) => {
return !!filterResourcesToDelete(resources).length
},
componentType: 'button',
class: 'oc-files-actions-delete-trigger'
}
])
return {
actions,
// HACK: exported for unit tests:
deleteSpaces
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsDelete.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsDelete.ts",
"repo_id": "owncloud",
"token_count": 1642
} | 829 |
import { MaybeRef } from '../../utils'
import { LocationQuery } from '../router'
import { SpaceResource } from '@ownclouders/web-client/src/helpers'
import { RouteParams } from 'vue-router'
export interface FileContext {
path: MaybeRef<string>
driveAliasAndItem: MaybeRef<string>
space: MaybeRef<SpaceResource>
item: MaybeRef<string>
itemId: MaybeRef<string>
fileName: MaybeRef<string>
routeName: MaybeRef<string>
routeParams: MaybeRef<RouteParams>
routeQuery: MaybeRef<LocationQuery>
}
| owncloud/web/packages/web-pkg/src/composables/appDefaults/types.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/appDefaults/types.ts",
"repo_id": "owncloud",
"token_count": 164
} | 830 |
export * from './useClientService'
| owncloud/web/packages/web-pkg/src/composables/clientService/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/clientService/index.ts",
"repo_id": "owncloud",
"token_count": 10
} | 831 |
import { unref, Ref } from 'vue'
import { useGetMatchingSpace } from '../spaces'
import { createFileRouteOptions } from '../../helpers/router'
import { createLocationSpaces, createLocationShares } from '../../router'
import { CreateTargetRouteOptions } from '../../helpers/folderLink/types'
import { Resource, SpaceResource } from '@ownclouders/web-client/src'
import { ConfigStore } from '../piniaStores'
export type ResourceRouteResolverOptions = {
configStore?: ConfigStore
targetRouteCallback?: Ref<any>
space?: Ref<SpaceResource>
}
export const useResourceRouteResolver = (
options: ResourceRouteResolverOptions = {},
context?: any
) => {
const targetRouteCallback = options.targetRouteCallback
const { getInternalSpace, getMatchingSpace } = useGetMatchingSpace(options)
const createFolderLink = (createTargetRouteOptions: CreateTargetRouteOptions) => {
if (unref(targetRouteCallback)) {
return unref(targetRouteCallback)(createTargetRouteOptions)
}
const { path, fileId, resource } = createTargetRouteOptions
if (!resource.shareId && !unref(options.space) && !getInternalSpace(resource.storageId)) {
if (path === '/') {
return createLocationShares('files-shares-with-me')
}
// FIXME: This is a hacky way to resolve re-shares, but we don't have other options currently
return { name: 'resolvePrivateLink', params: { fileId } }
}
const space = unref(options.space) || getMatchingSpace(resource)
if (!space) {
return {}
}
return createLocationSpaces(
'files-spaces-generic',
createFileRouteOptions(space, { path, fileId })
)
}
const createFileAction = (resource: Resource) => {
const space = unref(options.space) || getMatchingSpace(resource)
/**
* Triggered when a default action is triggered on a file
* @property {object} resource resource for which the event is triggered
*/
context.emit('fileClick', { space, resources: [resource] })
}
return {
createFileAction,
createFolderLink
}
}
| owncloud/web/packages/web-pkg/src/composables/filesList/useResourceRouteResolver.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/filesList/useResourceRouteResolver.ts",
"repo_id": "owncloud",
"token_count": 661
} | 832 |
export * from './usePasswordPolicyService'
| owncloud/web/packages/web-pkg/src/composables/passwordPolicyService/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/passwordPolicyService/index.ts",
"repo_id": "owncloud",
"token_count": 11
} | 833 |
import { Resource } from '@ownclouders/web-client'
import { ClientService } from '../../../services'
import { CollaboratorShare, LinkShare, SpaceResource } from '@ownclouders/web-client/src/helpers'
import { DriveItemCreateLink, DriveItemInvite } from '@ownclouders/web-client/src/generated'
export interface AddShareOptions {
clientService: ClientService
space: SpaceResource
resource: Resource
options: DriveItemInvite
}
export interface UpdateShareOptions {
clientService: ClientService
space: SpaceResource
resource: Resource
collaboratorShare: CollaboratorShare
options: DriveItemInvite
}
export interface DeleteShareOptions {
clientService: ClientService
space: SpaceResource
resource: Resource
collaboratorShare: CollaboratorShare
loadIndicators?: boolean
}
export interface AddLinkOptions {
clientService: ClientService
space: SpaceResource
resource: Resource
options: DriveItemCreateLink
}
export interface UpdateLinkOptions {
clientService: ClientService
space: SpaceResource
resource: Resource
linkShare: LinkShare
options: Omit<DriveItemCreateLink, '@libre.graph.quickLink'>
}
export interface DeleteLinkOptions {
clientService: ClientService
space: SpaceResource
resource: Resource
linkShare: LinkShare
loadIndicators?: boolean
}
| owncloud/web/packages/web-pkg/src/composables/piniaStores/shares/types.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/shares/types.ts",
"repo_id": "owncloud",
"token_count": 344
} | 834 |
import { useRouter } from './useRouter'
import { Resource, SpaceResource } from '@ownclouders/web-client/src/helpers'
import { createFileRouteOptions } from '../../helpers/router'
import { Router } from 'vue-router'
import { ConfigStore, useConfigStore } from '../piniaStores'
export interface FileRouteReplaceOptions {
router?: Router
configStore?: ConfigStore
}
export const useFileRouteReplace = (options: FileRouteReplaceOptions = {}) => {
const router = options.router || useRouter()
const configStore = options.configStore || useConfigStore()
const replaceInvalidFileRoute = ({
space,
resource,
path,
fileId
}: {
space: SpaceResource
resource: Resource
path: string
fileId?: string | number
}): boolean => {
if (!configStore.options.routing?.idBased) {
return false
}
if (path === resource.path && fileId === resource.fileId) {
return false
}
const routeOptions = createFileRouteOptions(space, resource, { configStore })
router.replace(routeOptions)
return true
}
return {
replaceInvalidFileRoute
}
}
| owncloud/web/packages/web-pkg/src/composables/router/useFileRouteReplace.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/router/useFileRouteReplace.ts",
"repo_id": "owncloud",
"token_count": 364
} | 835 |
import { inject } from 'vue'
export const useService = <T>(name: string): T => inject(name)
| owncloud/web/packages/web-pkg/src/composables/service/useService.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/service/useService.ts",
"repo_id": "owncloud",
"token_count": 30
} | 836 |
export * from './constants'
export * from './useTileSize'
export * from './useViewMode'
| owncloud/web/packages/web-pkg/src/composables/viewMode/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/viewMode/index.ts",
"repo_id": "owncloud",
"token_count": 29
} | 837 |
import { Resource } from '@ownclouders/web-client'
export interface CreateTargetRouteOptions {
path: string
fileId?: string | number
resource: Resource
}
| owncloud/web/packages/web-pkg/src/helpers/folderLink/types.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/folderLink/types.ts",
"repo_id": "owncloud",
"token_count": 45
} | 838 |
import { Resource } from '@ownclouders/web-client'
export const isSameResource = (r1: Resource, r2: Resource): boolean => {
if (!r1 || !r2) {
return false
}
return r1.id === r2.id
}
| owncloud/web/packages/web-pkg/src/helpers/resource/sameResource.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/resource/sameResource.ts",
"repo_id": "owncloud",
"token_count": 73
} | 839 |
enum states {
enter,
exit
}
interface CbackOptions {
element: Element
callCount: number
unobserve: () => void
}
type cback = (options: CbackOptions) => void
type unobserve = (element: Element) => void
interface Cbacks {
onEnter?: cback
onExit?: cback
}
class Target {
private state: states
private observeEnter: boolean
private observeExit: boolean
private onEnterCallCount: number
private onExitCallCount: number
private readonly onEnter?: cback
private readonly onExit?: cback
public readonly threshold: number
public readonly unobserver: unobserve
constructor(unobserver: unobserve, threshold: number, cbacks: Cbacks) {
this.unobserver = unobserver
this.threshold = threshold
this.onEnter = cbacks.onEnter
this.onExit = cbacks.onExit
this.observeEnter = !!cbacks.onEnter
this.observeExit = !!cbacks.onExit
this.onEnterCallCount = 0
this.onExitCallCount = 0
}
public request(state: states, element: Element) {
const sharedProps = {
element: element,
unobserve: () => this.unobserve(state, element)
}
if (state === states.enter && this.observeEnter && this.onEnter) {
this.onEnterCallCount++
this.onEnter({
callCount: this.onEnterCallCount,
...sharedProps
})
} else if (
this.state === states.enter &&
state === states.exit &&
this.observeExit &&
this.onExit
) {
this.onExitCallCount++
this.onExit({
callCount: this.onExitCallCount,
...sharedProps
})
}
this.state = state
}
private unobserve(state: states, element: Element) {
if (state === states.enter) {
this.observeEnter = false
} else if (state === states.exit) {
this.observeExit = false
}
if (!this.observeEnter && !this.observeExit) {
this.unobserver(element)
}
}
}
interface VisibilityObserverOptions {
root?: Element | Document | null
rootMargin?: string
threshold?: number
}
export class VisibilityObserver {
private targets: WeakMap<Element, Target>
private readonly intersectionObserver: IntersectionObserver
private readonly options: VisibilityObserverOptions
constructor(options: VisibilityObserverOptions = {}) {
this.options = {
root: options.root,
rootMargin: options.rootMargin,
threshold: options.threshold || 0
}
this.targets = new WeakMap<Element, Target>()
this.intersectionObserver = new IntersectionObserver(this.trigger.bind(this), this.options)
}
public observe(element: Element, cbacks: Cbacks = {}, threshold?: number): void {
if (!cbacks.onEnter && !cbacks.onExit) {
return
}
this.targets.set(
element,
new Target(this.unobserve.bind(this), threshold || this.options.threshold || 0, {
onEnter: cbacks.onEnter,
onExit: cbacks.onExit
})
)
this.intersectionObserver.observe(element)
}
public unobserve(element: Element): void {
this.targets.delete(element)
this.intersectionObserver.unobserve(element)
}
public disconnect(): void {
this.targets = new WeakMap<Element, Target>()
this.intersectionObserver.disconnect()
}
private trigger(entries: IntersectionObserverEntry[]) {
entries.forEach((entry: IntersectionObserverEntry) => {
const observedElement = this.targets.get(entry.target)
if (!observedElement) {
return
}
observedElement.request(
entry.isIntersecting && entry.intersectionRatio > observedElement.threshold
? states.enter
: states.exit,
entry.target
)
})
}
}
| owncloud/web/packages/web-pkg/src/observer/visibility.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/observer/visibility.ts",
"repo_id": "owncloud",
"token_count": 1365
} | 840 |
export * from './archiver'
export * from './cache'
export * from './client'
export * from './eventBus'
export * from './loadingService'
export * from './preview'
export * from './passwordPolicy'
export * from './uppy'
| owncloud/web/packages/web-pkg/src/services/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/services/index.ts",
"repo_id": "owncloud",
"token_count": 70
} | 841 |
export * from './dirname'
export * from './encodePath'
export * from './objectKeys'
export * from './types'
| owncloud/web/packages/web-pkg/src/utils/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/utils/index.ts",
"repo_id": "owncloud",
"token_count": 36
} | 842 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`ContextActionMenu component > renders the menu with actions 1`] = `
"<div id="oc-files-context-menu">
<oc-list-stub raw="false" id="oc-files-context-actions-action 1" class="oc-files-context-actions oc-pb-s oc-files-context-actions-border"></oc-list-stub>
<oc-list-stub raw="false" id="oc-files-context-actions-action 2" class="oc-files-context-actions oc-pt-s"></oc-list-stub>
</div>"
`;
| owncloud/web/packages/web-pkg/tests/unit/components/ContextActions/__snapshots__/ContextActionMenu.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/ContextActions/__snapshots__/ContextActionMenu.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 173
} | 843 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`ResourceTiles component > renders a footer slot 1`] = `
"<div data-v-67d39700="" id="tiles-view" class="oc-px-m oc-pt-l">
<!--v-if-->
<oc-list data-v-67d39700="" class="oc-tiles oc-flex"> </oc-list>
<!--v-if-->
<div data-v-67d39700="" class="oc-tiles-footer">Hello, ResourceTiles footer!</div>
</div>"
`;
exports[`ResourceTiles component > renders an array of spaces correctly 1`] = `
"<div data-v-67d39700="" id="tiles-view" class="oc-px-m oc-pt-l">
<!--v-if-->
<oc-list data-v-67d39700="" class="oc-tiles oc-flex">
<li data-v-67d39700="" class="oc-tiles-item has-item-context-menu">
<resource-tile-stub data-v-67d39700="" resource="[object Object]" isresourceselected="false" isextensiondisplayed="true" resourceiconsize="xlarge" draggable="false" resourceroute="[object Object]"></resource-tile-stub>
</li>
<li data-v-67d39700="" class="oc-tiles-item has-item-context-menu">
<resource-tile-stub data-v-67d39700="" resource="[object Object]" isresourceselected="false" isextensiondisplayed="true" resourceiconsize="xlarge" draggable="false" resourceroute="[object Object]"></resource-tile-stub>
</li>
<li data-v-67d39700="" class="ghost-tile" aria-hidden="true"></li>
<li data-v-67d39700="" class="ghost-tile" aria-hidden="true"></li>
<li data-v-67d39700="" class="ghost-tile" aria-hidden="true"></li>
<li data-v-67d39700="" class="ghost-tile" aria-hidden="true"></li>
<li data-v-67d39700="" class="ghost-tile" aria-hidden="true"></li>
</oc-list>
<!--v-if-->
<div data-v-67d39700="" class="oc-tiles-footer"></div>
</div>"
`;
| owncloud/web/packages/web-pkg/tests/unit/components/FilesList/__snapshots__/ResourceTiles.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/FilesList/__snapshots__/ResourceTiles.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 669
} | 844 |
import { mock } from 'vitest-mock-extended'
import { unref } from 'vue'
import { useFileActionsCreateNewFile } from '../../../../../src/composables/actions'
import { useModals } from '../../../../../src/composables/piniaStores'
import { SpaceResource } from '@ownclouders/web-client/src'
import { Resource } from '@ownclouders/web-client/src/helpers'
import { FileActionOptions } from '../../../../../src/composables/actions'
import { useFileActions } from '../../../../../src/composables/actions/files/useFileActions'
import { RouteLocation, defaultComponentMocks, getComposableWrapper } from 'web-test-helpers/src'
import { ApplicationFileExtension } from '../../../../../types'
import { useResourcesStore } from '../../../../../src/composables/piniaStores'
vi.mock('../../../../../src/composables/actions/files/useFileActions', async (importOriginal) => ({
...(await importOriginal<any>()),
useFileActions: vi.fn(() => mock<ReturnType<typeof useFileActions>>())
}))
describe('useFileActionsCreateNewFile', () => {
describe('checkFileName', () => {
it.each([
{ input: '', output: 'File name cannot be empty' },
{ input: '/', output: 'File name cannot contain "/"' },
{ input: '.', output: 'File name cannot be equal to "."' },
{ input: '..', output: 'File name cannot be equal to ".."' },
{ input: 'myfile.txt', output: null }
])('should validate file name %s', (data) => {
const space = mock<SpaceResource>({ id: '1' })
getWrapper({
space,
setup: ({ getNameErrorMsg }) => {
const result = getNameErrorMsg(data.input)
expect(result).toBe(data.output)
}
})
})
})
describe('openFile', () => {
it('upserts the resource before opening', () => {
const space = mock<SpaceResource>({ id: '1' })
getWrapper({
space,
setup: ({ openFile }) => {
openFile(mock<Resource>(), null)
const { upsertResource } = useResourcesStore()
expect(upsertResource).toHaveBeenCalled()
}
})
})
})
describe('createNewFileModal', () => {
it('should show modal', () => {
const space = mock<SpaceResource>({ id: '1' })
getWrapper({
space,
setup: async ({ actions }) => {
const { dispatchModal } = useModals()
const fileActionOptions: FileActionOptions = { space, resources: [] } as FileActionOptions
await unref(actions)[0].handler(fileActionOptions)
expect(dispatchModal).toHaveBeenCalled()
}
})
})
})
})
function getWrapper({
resolveCreateFile = true,
space = undefined,
setup
}: {
resolveCreateFile?: boolean
space?: SpaceResource
setup: (instance: ReturnType<typeof useFileActionsCreateNewFile>) => void
}) {
const mocks = {
...defaultComponentMocks({
currentRoute: mock<RouteLocation>({ name: 'files-spaces-generic' })
}),
space
}
mocks.$clientService.webdav.putFileContents.mockImplementation(() => {
if (resolveCreateFile) {
return Promise.resolve({
id: '1',
type: 'folder',
path: '/',
isReceivedShare: vi.fn()
} as Resource)
}
return Promise.reject('error')
})
const currentFolder = mock<Resource>({ id: '1', path: '/' })
return {
wrapper: getComposableWrapper(
() => {
const instance = useFileActionsCreateNewFile({ space })
setup(instance)
},
{
provide: mocks,
mocks,
pluginOptions: {
piniaOptions: {
appsState: {
fileExtensions: [
mock<ApplicationFileExtension>({
extension: '.txt',
newFileMenu: { menuTitle: vi.fn() }
})
]
},
resourcesStore: { currentFolder }
}
}
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCreateNewFile.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCreateNewFile.spec.ts",
"repo_id": "owncloud",
"token_count": 1605
} | 845 |
import { useSpaceActionsDuplicate } from '../../../../../src/composables/actions/spaces'
import { AbilityRule, SpaceResource } from '@ownclouders/web-client/src/helpers'
import { mock } from 'vitest-mock-extended'
import {
defaultComponentMocks,
mockAxiosResolve,
RouteLocation,
getComposableWrapper
} from 'web-test-helpers'
import { unref } from 'vue'
import { ListFilesResult } from '@ownclouders/web-client/src/webdav/listFiles'
import {
useMessages,
useResourcesStore,
useSpacesStore
} from '../../../../../src/composables/piniaStores'
const spaces = [
mock<SpaceResource>({
name: 'Moon',
description: 'To the moon',
type: 'project',
spaceImageData: null,
spaceReadmeData: null,
spaceQuota: { total: Math.pow(10, 9) }
})
]
describe('restore', () => {
describe('isVisible property', () => {
it('should be false when no resource given', () => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [] })).toBe(false)
}
})
})
it('should be false when the space is disabled', () => {
getWrapper({
setup: ({ actions }) => {
expect(
unref(actions)[0].isVisible({
resources: [
mock<SpaceResource>({
disabled: true,
driveType: 'project'
})
]
})
).toBe(false)
}
})
})
it('should be false when the space is no project space', () => {
getWrapper({
setup: ({ actions }) => {
expect(
unref(actions)[0].isVisible({
resources: [
mock<SpaceResource>({
disabled: false,
driveType: 'personal'
})
]
})
).toBe(false)
}
})
})
it('should be false when the current user can not create spaces', () => {
getWrapper({
abilities: [],
setup: ({ actions }) => {
expect(
unref(actions)[0].isVisible({
resources: [mock<SpaceResource>({ disabled: false, driveType: 'project' })]
})
).toBe(false)
}
})
})
it('should be true when the current user can create spaces', () => {
getWrapper({
setup: ({ actions }) => {
expect(
unref(actions)[0].isVisible({
resources: [
mock<SpaceResource>({ name: 'Moon', disabled: false, driveType: 'project' }),
mock<SpaceResource>({ name: 'Sun', disabled: false, driveType: 'project' })
]
})
).toBe(true)
}
})
})
})
describe('method "duplicateSpace"', () => {
it('should show error message on error', () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
getWrapper({
setup: async ({ duplicateSpace }, { clientService }) => {
clientService.graphAuthenticated.drives.createDrive.mockRejectedValue(new Error())
await duplicateSpace(spaces[0])
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalledTimes(1)
}
})
})
it('should show message on success', () => {
getWrapper({
setup: async ({ duplicateSpace }, { clientService }) => {
clientService.graphAuthenticated.drives.createDrive.mockResolvedValue(
mockAxiosResolve({
id: '1',
name: 'Moon (1)',
special: []
})
)
clientService.webdav.listFiles.mockResolvedValue({ children: [] } as ListFilesResult)
await duplicateSpace(spaces[0])
expect(clientService.graphAuthenticated.drives.createDrive).toHaveBeenCalledWith(
{
description: 'To the moon',
name: 'Moon (1)',
quota: {
total: Math.pow(10, 9)
}
},
expect.anything()
)
const spacesStore = useSpacesStore()
expect(spacesStore.upsertSpace).toHaveBeenCalled()
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalled()
}
})
})
it('should upsert a space as resource on the projects page', () => {
getWrapper({
currentRouteName: 'files-spaces-projects',
setup: async ({ duplicateSpace }, { clientService }) => {
clientService.graphAuthenticated.drives.createDrive.mockResolvedValue(
mockAxiosResolve({
id: '1',
name: 'Moon (1)',
special: []
})
)
clientService.webdav.listFiles.mockResolvedValue({ children: [] } as ListFilesResult)
await duplicateSpace(spaces[0])
const { upsertResource } = useResourcesStore()
expect(upsertResource).toHaveBeenCalled()
}
})
})
})
})
function getWrapper({
setup,
abilities = [{ action: 'create-all', subject: 'Drive' }],
currentRouteName = 'files-spaces-generic'
}: {
setup: (
instance: ReturnType<typeof useSpaceActionsDuplicate>,
{
clientService
}: {
clientService: ReturnType<typeof defaultComponentMocks>['$clientService']
}
) => void
abilities?: AbilityRule[]
currentRouteName?: string
}) {
const mocks = defaultComponentMocks({
currentRoute: mock<RouteLocation>({ name: currentRouteName })
})
return {
mocks,
wrapper: getComposableWrapper(
() => {
const instance = useSpaceActionsDuplicate()
setup(instance, { clientService: mocks.$clientService })
},
{
mocks,
provide: mocks,
pluginOptions: { abilities, piniaOptions: { spacesState: { spaces } } }
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsDuplicate.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsDuplicate.spec.ts",
"repo_id": "owncloud",
"token_count": 2703
} | 846 |
import { Key, ModifierKey, useKeyboardActions } from '../../../../src/composables/keyboardActions'
import { getComposableWrapper } from 'web-test-helpers'
import { ref } from 'vue'
describe('useKeyboardActions', () => {
it('should be valid', () => {
expect(useKeyboardActions).toBeDefined()
})
it('should bind keys', () => {
const wrapper = getWrapper()
const { keyboardActions } = wrapper.vm
keyboardActions.bindKeyAction({ primary: Key.A }, () => undefined)
expect(keyboardActions.actions.value.length).toBe(1)
wrapper.unmount()
})
it('should be possible remove keys', () => {
const wrapper = getWrapper()
const { keyboardActions } = wrapper.vm
const keyActionIndex = keyboardActions.bindKeyAction({ primary: Key.A }, () => undefined)
expect(keyboardActions.actions.value.length).toBe(1)
keyboardActions.removeKeyAction(keyActionIndex)
expect(keyboardActions.actions.value.length).toBe(0)
wrapper.unmount()
})
it('should be possible execute callback on key event', () => {
const wrapper = getWrapper()
const { keyboardActions } = wrapper.vm
const counter = ref(0)
const increment = () => {
counter.value += 1
}
// primary key
keyboardActions.bindKeyAction({ primary: Key.A }, increment)
const event = new KeyboardEvent('keydown', { key: 'a' })
document.dispatchEvent(event)
expect(counter.value).toBe(1)
// primary key + modifier
keyboardActions.bindKeyAction({ modifier: ModifierKey.Ctrl, primary: Key.A }, increment)
const eventWithModifier = new KeyboardEvent('keydown', { key: 'a', ctrlKey: true })
document.dispatchEvent(eventWithModifier)
expect(counter.value).toBe(2)
wrapper.unmount()
})
})
function getWrapper() {
return getComposableWrapper(() => {
const keyboardActions = useKeyboardActions()
return { keyboardActions }
})
}
| owncloud/web/packages/web-pkg/tests/unit/composables/keyboardActions/useKeyboardActions.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/keyboardActions/useKeyboardActions.spec.ts",
"repo_id": "owncloud",
"token_count": 649
} | 847 |
import { useUpload } from '../../../../src/composables/upload'
describe('useUpload', () => {
it('should be valid', () => {
expect(useUpload).toBeDefined()
})
})
| owncloud/web/packages/web-pkg/tests/unit/composables/upload/useUpload.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/upload/useUpload.spec.ts",
"repo_id": "owncloud",
"token_count": 61
} | 848 |
import { cloneStateObject } from '../../../src/helpers/store'
describe('cloneStateObject', () => {
it('clones object', () => {
const og = { id: '1', frozen: 'value' }
const cloned = cloneStateObject(og)
cloned.frozen = 'updated'
expect(og.id).toBe('1')
expect(og.frozen).toBe('value')
expect(cloned.id).toBe('1')
expect(cloned.frozen).toBe('updated')
})
it('clones null', () => {
expect(cloneStateObject(null)).toStrictEqual(null)
})
it('throws an error when "undefined" is cloned', () => {
expect(() => {
cloneStateObject(undefined)
}).toThrow('cloneStateObject: cannot clone "undefined"')
})
})
| owncloud/web/packages/web-pkg/tests/unit/helpers/store.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/store.spec.ts",
"repo_id": "owncloud",
"token_count": 257
} | 849 |
<template>
<div class="oc-flex">
<oc-button
v-oc-tooltip="descriptionOrFallback"
type="a"
:href="hrefOrFallback"
target="_blank"
appearance="raw-inverse"
variation="brand"
:aria-label="ariaLabelOrFallback"
aria-describedby="oc-feedback-link-description"
>
<oc-icon name="feedback" />
</oc-button>
<p id="oc-feedback-link-description" class="oc-invisible-sr" v-text="descriptionOrFallback" />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: 'FeedbackLink',
props: {
href: {
type: String,
required: false,
default: null
},
ariaLabel: {
type: String,
required: false,
default: null
},
description: {
type: String,
required: false,
default: null
}
},
computed: {
hrefOrFallback() {
return this.href || 'https://owncloud.com/web-design-feedback'
},
ariaLabelOrFallback() {
return this.ariaLabel || this.$gettext('ownCloud feedback survey')
},
descriptionOrFallback() {
return (
this.description ||
this.$gettext(
"Provide your feedback: We'd like to improve the web design and would be happy to hear your feedback. Thank you! Your ownCloud team."
)
)
}
}
})
</script>
| owncloud/web/packages/web-runtime/src/components/Topbar/FeedbackLink.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/components/Topbar/FeedbackLink.vue",
"repo_id": "owncloud",
"token_count": 578
} | 850 |
import { App } from 'vue'
import { RuntimeApi } from '../types'
export abstract class NextApplication {
protected readonly runtimeApi: RuntimeApi
protected constructor(runtimeApi: RuntimeApi) {
this.runtimeApi = runtimeApi
}
abstract initialize(): Promise<void>
abstract ready(): Promise<void>
abstract mounted(instance: App): Promise<void>
}
| owncloud/web/packages/web-runtime/src/container/application/next.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/container/application/next.ts",
"repo_id": "owncloud",
"token_count": 104
} | 851 |
export const getQueryParam = (paramName: string): string | null => {
const searchParams = new URLSearchParams(window.location.search)
return searchParams.get(paramName)
}
| owncloud/web/packages/web-runtime/src/helpers/url.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/helpers/url.ts",
"repo_id": "owncloud",
"token_count": 52
} | 852 |
import { RouteLocation, RouteLocationNormalizedLoaded, RouteLocationRaw, Router } from 'vue-router'
// type: patch
// temporary patch till we have upgraded web to the latest vue router which make this obsolete
// this takes care that routes like 'foo/bar/baz' which by default would be converted to 'foo%2Fbar%2Fbaz' stay as they are
// should immediately go away and be removed after finalizing the update
// to apply the patch to a route add meta.patchCleanPath = true to it
// to patch needs to be enabled on a route level, to do so add meta.patchCleanPath = true property to the route
// c.f. https://github.com/vuejs/router/issues/1638
export const patchRouter = (router: Router) => {
const cleanPath = (route) =>
[
['%2F', '/'],
['//', '/']
].reduce((path, rule) => path.replaceAll(rule[0], rule[1]), route || '')
const bindResolve = router.resolve.bind(router)
router.resolve = (
raw: RouteLocationRaw,
currentLocation?: RouteLocationNormalizedLoaded
): RouteLocation & {
href: string
} => {
const resolved = bindResolve(raw, currentLocation)
if (resolved.meta?.patchCleanPath !== true) {
return resolved
}
return {
...resolved,
href: cleanPath(resolved.href),
path: cleanPath(resolved.path),
fullPath: cleanPath(resolved.fullPath)
}
}
const routerMethodFactory = (method) => (to) => {
const resolved = router.resolve(to)
if (resolved.meta?.patchCleanPath !== true) {
return method(to)
}
return method({
path: cleanPath(resolved.fullPath),
query: resolved.query
})
}
router.push = routerMethodFactory(router.push.bind(router))
router.replace = routerMethodFactory(router.replace.bind(router))
return router
}
| owncloud/web/packages/web-runtime/src/router/patchCleanPath.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/router/patchCleanPath.ts",
"repo_id": "owncloud",
"token_count": 605
} | 853 |
import SidebarNavItem from 'web-runtime/src/components/SidebarNav/SidebarNavItem.vue'
import sidebarNavItemFixtures from '../../../__fixtures__/sidebarNavItems'
import { defaultPlugins, mount } from 'web-test-helpers'
const exampleNavItem = sidebarNavItemFixtures[0]
const propsData = {
name: exampleNavItem.name,
active: false,
target: exampleNavItem.route.path,
icon: exampleNavItem.icon,
index: '5',
id: '123'
}
describe('OcSidebarNav', () => {
it('renders navItem without toolTip if expanded', () => {
const { wrapper } = getWrapper(false)
expect(wrapper.html()).toMatchSnapshot()
})
it('renders navItem with toolTip if collapsed', () => {
const { wrapper } = getWrapper(true)
expect(wrapper.html()).toMatchSnapshot()
})
})
function getWrapper(collapsed) {
return {
wrapper: mount(SidebarNavItem, {
props: {
...propsData,
collapsed
},
global: {
plugins: [...defaultPlugins()],
stubs: { 'router-link': true }
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/components/SidebarNav/SidebarNavItem.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/SidebarNav/SidebarNavItem.spec.ts",
"repo_id": "owncloud",
"token_count": 393
} | 854 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`User Menu component > when no quota and email is set > the user menu does not contain a quota 1`] = `
"<nav data-v-08f1b1e7="" aria-label="Account menu">
<oc-button-stub data-v-08f1b1e7="" id="_userMenuButton" class="oc-topbar-personal" appearance="raw" aria-label="My Account">
<avatar-image-stub data-v-08f1b1e7="" class="oc-topbar-avatar oc-topbar-personal-avatar oc-flex-inline oc-flex-center oc-flex-middle" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub>
</oc-button-stub>
<oc-drop-stub data-v-08f1b1e7="" drop-id="account-info-container" toggle="#_userMenuButton" mode="click" close-on-click="" padding-size="small" class="oc-overflow-hidden">
<oc-list-stub data-v-08f1b1e7="" class="user-menu-list">
<li data-v-08f1b1e7="" class="profile-info-wrapper oc-pl-s">
<avatar-image-stub data-v-08f1b1e7="" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub> <span data-v-08f1b1e7="" class="profile-info-wrapper"><span data-v-08f1b1e7="" class="oc-display-block">Albert Einstein</span> <span data-v-08f1b1e7="" class="oc-text-small">test@test.de</span></span>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-manage" type="router-link" to="[object Object]" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="settings-4" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Preferences</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" type="router-link" appearance="raw" to="[object Object]">
<oc-icon-stub data-v-08f1b1e7="" name="application" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Settings</span>
</oc-button-stub>
</li>
<!--v-if-->
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-logout" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="logout-box-r" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Log out</span>
</oc-button-stub>
</li>
</oc-list-stub>
<!--v-if-->
</oc-drop-stub>
</nav>"
`;
exports[`User Menu component > when no quota and no email is set > the user menu does not contain a quota 1`] = `
"<nav data-v-08f1b1e7="" aria-label="Account menu">
<oc-button-stub data-v-08f1b1e7="" id="_userMenuButton" class="oc-topbar-personal" appearance="raw" aria-label="My Account">
<avatar-image-stub data-v-08f1b1e7="" class="oc-topbar-avatar oc-topbar-personal-avatar oc-flex-inline oc-flex-center oc-flex-middle" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub>
</oc-button-stub>
<oc-drop-stub data-v-08f1b1e7="" drop-id="account-info-container" toggle="#_userMenuButton" mode="click" close-on-click="" padding-size="small" class="oc-overflow-hidden">
<oc-list-stub data-v-08f1b1e7="" class="user-menu-list">
<li data-v-08f1b1e7="" class="profile-info-wrapper oc-pl-s">
<avatar-image-stub data-v-08f1b1e7="" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub> <span data-v-08f1b1e7="" class="profile-info-wrapper oc-py-xs"><span data-v-08f1b1e7="" class="oc-display-block">Albert Einstein</span>
<!--v-if--></span>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-manage" type="router-link" to="[object Object]" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="settings-4" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Preferences</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" type="router-link" appearance="raw" to="[object Object]">
<oc-icon-stub data-v-08f1b1e7="" name="application" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Settings</span>
</oc-button-stub>
</li>
<!--v-if-->
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-logout" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="logout-box-r" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Log out</span>
</oc-button-stub>
</li>
</oc-list-stub>
<!--v-if-->
</oc-drop-stub>
</nav>"
`;
exports[`User Menu component > when quota and no email is set > renders a navigation without email 1`] = `
"<nav data-v-08f1b1e7="" aria-label="Account menu">
<oc-button-stub data-v-08f1b1e7="" id="_userMenuButton" class="oc-topbar-personal" appearance="raw" aria-label="My Account">
<avatar-image-stub data-v-08f1b1e7="" class="oc-topbar-avatar oc-topbar-personal-avatar oc-flex-inline oc-flex-center oc-flex-middle" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub>
</oc-button-stub>
<oc-drop-stub data-v-08f1b1e7="" drop-id="account-info-container" toggle="#_userMenuButton" mode="click" close-on-click="" padding-size="small" class="oc-overflow-hidden">
<oc-list-stub data-v-08f1b1e7="" class="user-menu-list">
<li data-v-08f1b1e7="" class="profile-info-wrapper oc-pl-s">
<avatar-image-stub data-v-08f1b1e7="" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub> <span data-v-08f1b1e7="" class="profile-info-wrapper oc-py-xs"><span data-v-08f1b1e7="" class="oc-display-block">Albert Einstein</span>
<!--v-if--></span>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-manage" type="router-link" to="[object Object]" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="settings-4" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Preferences</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" type="router-link" appearance="raw" to="[object Object]">
<oc-icon-stub data-v-08f1b1e7="" name="application" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Settings</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="" class="storage-wrapper oc-pl-s">
<oc-icon-stub data-v-08f1b1e7="" name="cloud" fill-type="line" class="oc-p-xs"></oc-icon-stub>
<div data-v-08f1b1e7="" class="oc-width-1-1">
<p data-v-08f1b1e7="" class="oc-my-rm"><span data-v-08f1b1e7="" class="oc-display-block">Personal storage (30% used)</span> <span data-v-08f1b1e7="" class="storage-wrapper-quota oc-text-small">300 B of 1 kB used</span></p>
<oc-progress-stub data-v-08f1b1e7="" max="100" size="small" variation="primary" value="30"></oc-progress-stub>
</div>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-logout" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="logout-box-r" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Log out</span>
</oc-button-stub>
</li>
</oc-list-stub>
<!--v-if-->
</oc-drop-stub>
</nav>"
`;
exports[`User Menu component > when quota is above 80% and below 90% > renders a warning quota progress bar 1`] = `
"<nav data-v-08f1b1e7="" aria-label="Account menu">
<oc-button-stub data-v-08f1b1e7="" id="_userMenuButton" class="oc-topbar-personal" appearance="raw" aria-label="My Account">
<avatar-image-stub data-v-08f1b1e7="" class="oc-topbar-avatar oc-topbar-personal-avatar oc-flex-inline oc-flex-center oc-flex-middle" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub>
</oc-button-stub>
<oc-drop-stub data-v-08f1b1e7="" drop-id="account-info-container" toggle="#_userMenuButton" mode="click" close-on-click="" padding-size="small" class="oc-overflow-hidden">
<oc-list-stub data-v-08f1b1e7="" class="user-menu-list">
<li data-v-08f1b1e7="" class="profile-info-wrapper oc-pl-s">
<avatar-image-stub data-v-08f1b1e7="" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub> <span data-v-08f1b1e7="" class="profile-info-wrapper"><span data-v-08f1b1e7="" class="oc-display-block">Albert Einstein</span> <span data-v-08f1b1e7="" class="oc-text-small">test@test.de</span></span>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-manage" type="router-link" to="[object Object]" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="settings-4" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Preferences</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" type="router-link" appearance="raw" to="[object Object]">
<oc-icon-stub data-v-08f1b1e7="" name="application" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Settings</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="" class="storage-wrapper oc-pl-s">
<oc-icon-stub data-v-08f1b1e7="" name="cloud" fill-type="line" class="oc-p-xs"></oc-icon-stub>
<div data-v-08f1b1e7="" class="oc-width-1-1">
<p data-v-08f1b1e7="" class="oc-my-rm"><span data-v-08f1b1e7="" class="oc-display-block">Personal storage (81% used)</span> <span data-v-08f1b1e7="" class="storage-wrapper-quota oc-text-small">810 B of 1 kB used</span></p>
<oc-progress-stub data-v-08f1b1e7="" max="100" size="small" variation="warning" value="81"></oc-progress-stub>
</div>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-logout" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="logout-box-r" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Log out</span>
</oc-button-stub>
</li>
</oc-list-stub>
<!--v-if-->
</oc-drop-stub>
</nav>"
`;
exports[`User Menu component > when quota is above 90% > renders a danger quota progress bar 1`] = `
"<nav data-v-08f1b1e7="" aria-label="Account menu">
<oc-button-stub data-v-08f1b1e7="" id="_userMenuButton" class="oc-topbar-personal" appearance="raw" aria-label="My Account">
<avatar-image-stub data-v-08f1b1e7="" class="oc-topbar-avatar oc-topbar-personal-avatar oc-flex-inline oc-flex-center oc-flex-middle" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub>
</oc-button-stub>
<oc-drop-stub data-v-08f1b1e7="" drop-id="account-info-container" toggle="#_userMenuButton" mode="click" close-on-click="" padding-size="small" class="oc-overflow-hidden">
<oc-list-stub data-v-08f1b1e7="" class="user-menu-list">
<li data-v-08f1b1e7="" class="profile-info-wrapper oc-pl-s">
<avatar-image-stub data-v-08f1b1e7="" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub> <span data-v-08f1b1e7="" class="profile-info-wrapper"><span data-v-08f1b1e7="" class="oc-display-block">Albert Einstein</span> <span data-v-08f1b1e7="" class="oc-text-small">test@test.de</span></span>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-manage" type="router-link" to="[object Object]" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="settings-4" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Preferences</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" type="router-link" appearance="raw" to="[object Object]">
<oc-icon-stub data-v-08f1b1e7="" name="application" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Settings</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="" class="storage-wrapper oc-pl-s">
<oc-icon-stub data-v-08f1b1e7="" name="cloud" fill-type="line" class="oc-p-xs"></oc-icon-stub>
<div data-v-08f1b1e7="" class="oc-width-1-1">
<p data-v-08f1b1e7="" class="oc-my-rm"><span data-v-08f1b1e7="" class="oc-display-block">Personal storage (91% used)</span> <span data-v-08f1b1e7="" class="storage-wrapper-quota oc-text-small">910 B of 1 kB used</span></p>
<oc-progress-stub data-v-08f1b1e7="" max="100" size="small" variation="danger" value="91"></oc-progress-stub>
</div>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-logout" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="logout-box-r" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Log out</span>
</oc-button-stub>
</li>
</oc-list-stub>
<!--v-if-->
</oc-drop-stub>
</nav>"
`;
exports[`User Menu component > when quota is below 80% > renders a primary quota progress bar 1`] = `
"<nav data-v-08f1b1e7="" aria-label="Account menu">
<oc-button-stub data-v-08f1b1e7="" id="_userMenuButton" class="oc-topbar-personal" appearance="raw" aria-label="My Account">
<avatar-image-stub data-v-08f1b1e7="" class="oc-topbar-avatar oc-topbar-personal-avatar oc-flex-inline oc-flex-center oc-flex-middle" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub>
</oc-button-stub>
<oc-drop-stub data-v-08f1b1e7="" drop-id="account-info-container" toggle="#_userMenuButton" mode="click" close-on-click="" padding-size="small" class="oc-overflow-hidden">
<oc-list-stub data-v-08f1b1e7="" class="user-menu-list">
<li data-v-08f1b1e7="" class="profile-info-wrapper oc-pl-s">
<avatar-image-stub data-v-08f1b1e7="" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub> <span data-v-08f1b1e7="" class="profile-info-wrapper"><span data-v-08f1b1e7="" class="oc-display-block">Albert Einstein</span> <span data-v-08f1b1e7="" class="oc-text-small">test@test.de</span></span>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-manage" type="router-link" to="[object Object]" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="settings-4" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Preferences</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" type="router-link" appearance="raw" to="[object Object]">
<oc-icon-stub data-v-08f1b1e7="" name="application" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Settings</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="" class="storage-wrapper oc-pl-s">
<oc-icon-stub data-v-08f1b1e7="" name="cloud" fill-type="line" class="oc-p-xs"></oc-icon-stub>
<div data-v-08f1b1e7="" class="oc-width-1-1">
<p data-v-08f1b1e7="" class="oc-my-rm"><span data-v-08f1b1e7="" class="oc-display-block">Personal storage (30% used)</span> <span data-v-08f1b1e7="" class="storage-wrapper-quota oc-text-small">300 B of 1 kB used</span></p>
<oc-progress-stub data-v-08f1b1e7="" max="100" size="small" variation="primary" value="30"></oc-progress-stub>
</div>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-logout" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="logout-box-r" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Log out</span>
</oc-button-stub>
</li>
</oc-list-stub>
<!--v-if-->
</oc-drop-stub>
</nav>"
`;
exports[`User Menu component > when quota is not defined > renders no percentag of total and no progress bar 1`] = `
"<nav data-v-08f1b1e7="" aria-label="Account menu">
<oc-button-stub data-v-08f1b1e7="" id="_userMenuButton" class="oc-topbar-personal" appearance="raw" aria-label="My Account">
<avatar-image-stub data-v-08f1b1e7="" class="oc-topbar-avatar oc-topbar-personal-avatar oc-flex-inline oc-flex-center oc-flex-middle" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub>
</oc-button-stub>
<oc-drop-stub data-v-08f1b1e7="" drop-id="account-info-container" toggle="#_userMenuButton" mode="click" close-on-click="" padding-size="small" class="oc-overflow-hidden">
<oc-list-stub data-v-08f1b1e7="" class="user-menu-list">
<li data-v-08f1b1e7="" class="profile-info-wrapper oc-pl-s">
<avatar-image-stub data-v-08f1b1e7="" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub> <span data-v-08f1b1e7="" class="profile-info-wrapper"><span data-v-08f1b1e7="" class="oc-display-block">Albert Einstein</span> <span data-v-08f1b1e7="" class="oc-text-small">test@test.de</span></span>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-manage" type="router-link" to="[object Object]" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="settings-4" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Preferences</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" type="router-link" appearance="raw" to="[object Object]">
<oc-icon-stub data-v-08f1b1e7="" name="application" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Settings</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="" class="storage-wrapper oc-pl-s">
<oc-icon-stub data-v-08f1b1e7="" name="cloud" fill-type="line" class="oc-p-xs"></oc-icon-stub>
<div data-v-08f1b1e7="" class="oc-width-1-1">
<p data-v-08f1b1e7="" class="oc-my-rm"><span data-v-08f1b1e7="" class="oc-display-block">Personal storage</span> <span data-v-08f1b1e7="" class="storage-wrapper-quota oc-text-small">910 B used</span></p>
<!--v-if-->
</div>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-logout" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="logout-box-r" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Log out</span>
</oc-button-stub>
</li>
</oc-list-stub>
<!--v-if-->
</oc-drop-stub>
</nav>"
`;
exports[`User Menu component > when quota is unlimited > renders no percentag of total and no progress bar 1`] = `
"<nav data-v-08f1b1e7="" aria-label="Account menu">
<oc-button-stub data-v-08f1b1e7="" id="_userMenuButton" class="oc-topbar-personal" appearance="raw" aria-label="My Account">
<avatar-image-stub data-v-08f1b1e7="" class="oc-topbar-avatar oc-topbar-personal-avatar oc-flex-inline oc-flex-center oc-flex-middle" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub>
</oc-button-stub>
<oc-drop-stub data-v-08f1b1e7="" drop-id="account-info-container" toggle="#_userMenuButton" mode="click" close-on-click="" padding-size="small" class="oc-overflow-hidden">
<oc-list-stub data-v-08f1b1e7="" class="user-menu-list">
<li data-v-08f1b1e7="" class="profile-info-wrapper oc-pl-s">
<avatar-image-stub data-v-08f1b1e7="" width="32" userid="einstein" user-name="Albert Einstein"></avatar-image-stub> <span data-v-08f1b1e7="" class="profile-info-wrapper"><span data-v-08f1b1e7="" class="oc-display-block">Albert Einstein</span> <span data-v-08f1b1e7="" class="oc-text-small">test@test.de</span></span>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-manage" type="router-link" to="[object Object]" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="settings-4" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Preferences</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" type="router-link" appearance="raw" to="[object Object]">
<oc-icon-stub data-v-08f1b1e7="" name="application" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Settings</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="" class="storage-wrapper oc-pl-s">
<oc-icon-stub data-v-08f1b1e7="" name="cloud" fill-type="line" class="oc-p-xs"></oc-icon-stub>
<div data-v-08f1b1e7="" class="oc-width-1-1">
<p data-v-08f1b1e7="" class="oc-my-rm"><span data-v-08f1b1e7="" class="oc-display-block">Personal storage</span> <span data-v-08f1b1e7="" class="storage-wrapper-quota oc-text-small">300 B used</span></p>
<!--v-if-->
</div>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-logout" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="logout-box-r" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Log out</span>
</oc-button-stub>
</li>
</oc-list-stub>
<!--v-if-->
</oc-drop-stub>
</nav>"
`;
exports[`User Menu component > when user is not logged in > renders a navigation with login button 1`] = `
"<nav data-v-08f1b1e7="" aria-label="Account menu">
<oc-button-stub data-v-08f1b1e7="" id="_userMenuButton" class="oc-topbar-personal" appearance="raw" aria-label="My Account">
<div data-v-08f1b1e7="" data-test-item-name="User Menu login" aria-hidden="true" focusable="false" class="oc-topbar-avatar oc-topbar-unauthenticated-avatar oc-flex-inline oc-flex-center oc-flex-middle"><span class="oc-avatar-item" style="background-color: var(--oc-color-swatch-brand-contrast); --icon-color: var(--oc-color-swatch-brand-default); --width: 32px;"><oc-icon-stub name="user" filltype="line" accessiblelabel="" type="span" size="small" variation="passive" color=""></oc-icon-stub></span></div>
</oc-button-stub>
<oc-drop-stub data-v-08f1b1e7="" drop-id="account-info-container" toggle="#_userMenuButton" mode="click" close-on-click="" padding-size="small" class="oc-overflow-hidden">
<oc-list-stub data-v-08f1b1e7="" class="user-menu-list">
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-manage" type="router-link" to="[object Object]" appearance="raw">
<oc-icon-stub data-v-08f1b1e7="" name="settings-4" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Preferences</span>
</oc-button-stub>
</li>
<li data-v-08f1b1e7="">
<oc-button-stub data-v-08f1b1e7="" id="oc-topbar-account-login" appearance="raw" type="router-link" to="[object Object]">
<oc-icon-stub data-v-08f1b1e7="" name="login-box" fill-type="line" class="oc-p-xs"></oc-icon-stub> <span data-v-08f1b1e7="">Log in</span>
</oc-button-stub>
</li>
</oc-list-stub>
<!--v-if-->
</oc-drop-stub>
</nav>"
`;
| owncloud/web/packages/web-runtime/tests/unit/components/Topbar/__snapshots__/UserMenu.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Topbar/__snapshots__/UserMenu.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 10560
} | 855 |
import { useAuthStore, useConfigStore } from '@ownclouders/web-pkg'
import { mock } from 'vitest-mock-extended'
import { AuthService } from 'web-runtime/src/services/auth/authService'
import { UserManager } from 'web-runtime/src/services/auth/userManager'
import { RouteLocation, createRouter, createTestingPinia } from 'web-test-helpers/src'
const mockUpdateContext = vi.fn()
console.debug = vi.fn()
vi.mock('web-runtime/src/services/auth/userManager')
const initAuthService = ({ authService, configStore = null, router = null }) => {
createTestingPinia()
const authStore = useAuthStore()
configStore = configStore || useConfigStore()
authService.initialize(configStore, null, router, null, null, null, authStore, null)
}
describe('AuthService', () => {
describe('signInCallback', () => {
it.each([
['/', '/', {}],
['/?details=sharing', '/', { details: 'sharing' }],
[
'/external?contextRouteName=files-spaces-personal&fileId=0f897576',
'/external',
{
contextRouteName: 'files-spaces-personal',
fileId: '0f897576'
}
]
])(
'parses query params and passes them explicitly to router.replace: %s => %s %s',
async (url, path, query: any) => {
const authService = new AuthService()
Object.defineProperty(authService, 'userManager', {
value: {
signinRedirectCallback: vi.fn(),
getAndClearPostLoginRedirectUrl: () => url
}
})
const router = createRouter()
const replaceSpy = vi.spyOn(router, 'replace')
initAuthService({ authService, router })
await authService.signInCallback()
expect(replaceSpy).toHaveBeenCalledWith({
path,
query
})
}
)
})
describe('initializeContext', () => {
it('when embed mode is disabled and access_token is present, should call updateContext', async () => {
const authService = new AuthService()
Object.defineProperty(authService, 'userManager', {
value: mock<UserManager>({
getAccessToken: vi.fn().mockResolvedValue('access-token'),
updateContext: mockUpdateContext
})
})
initAuthService({ authService })
await authService.initializeContext(mock<RouteLocation>({}))
expect(mockUpdateContext).toHaveBeenCalledWith('access-token', true)
})
it('when embed mode is disabled and access_token is not present, should not call updateContext', async () => {
const authService = new AuthService()
Object.defineProperty(authService, 'userManager', {
value: mock<UserManager>({
getAccessToken: vi.fn().mockResolvedValue(null),
updateContext: mockUpdateContext
})
})
initAuthService({ authService })
await authService.initializeContext(mock<RouteLocation>({}))
expect(mockUpdateContext).not.toHaveBeenCalled()
})
it('when embed mode is enabled, access_token is present but auth is not delegated, should call updateContext', async () => {
const authService = new AuthService()
Object.defineProperty(authService, 'userManager', {
value: mock<UserManager>({
getAccessToken: vi.fn().mockResolvedValue('access-token'),
updateContext: mockUpdateContext
})
})
initAuthService({ authService })
await authService.initializeContext(mock<RouteLocation>({}))
expect(mockUpdateContext).toHaveBeenCalledWith('access-token', true)
})
it('when embed mode is enabled, access_token is present and auth is delegated, should not call updateContext', async () => {
const authService = new AuthService()
Object.defineProperty(authService, 'userManager', {
value: mock<UserManager>({
getAccessToken: vi.fn().mockResolvedValue('access-token'),
updateContext: mockUpdateContext
})
})
const configStore = useConfigStore()
configStore.options = { embed: { enabled: true, delegateAuthentication: true } }
initAuthService({ authService, configStore })
await authService.initializeContext(mock<RouteLocation>({}))
expect(mockUpdateContext).not.toHaveBeenCalled()
})
it('when embed mode is disabled, access_token is present and auth is delegated, should call updateContext', async () => {
const authService = new AuthService()
Object.defineProperty(authService, 'userManager', {
value: mock<UserManager>({
getAccessToken: vi.fn().mockResolvedValue('access-token'),
updateContext: mockUpdateContext
})
})
initAuthService({ authService })
await authService.initializeContext(mock<RouteLocation>({}))
expect(mockUpdateContext).toHaveBeenCalledWith('access-token', true)
})
})
})
| owncloud/web/packages/web-runtime/tests/unit/services/auth/authService.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/services/auth/authService.spec.ts",
"repo_id": "owncloud",
"token_count": 1801
} | 856 |
import { mock } from 'vitest-mock-extended'
import { ref } from 'vue'
import { Resource } from '../../../web-client/src'
import { FileResource } from '../../../web-client/src/helpers'
import { GetFileContentsResponse } from '../../../web-client/src/webdav/getFileContents'
import { FileContext, useAppDefaults, AppConfigObject } from '../../../web-pkg'
export const useAppDefaultsMock = (
options: Partial<ReturnType<typeof useAppDefaults>> = {}
): ReturnType<typeof useAppDefaults> => {
return {
isPublicLinkContext: ref(false),
currentFileContext: ref(mock<FileContext>()),
applicationConfig: ref(mock<AppConfigObject>()),
closeApp: vi.fn(),
replaceInvalidFileRoute: vi.fn(),
getUrlForResource: vi.fn(),
revokeUrl: vi.fn(),
getFileInfo: vi.fn().mockImplementation(() => mock<Resource>()),
getFileContents: vi.fn().mockImplementation(() => mock<GetFileContentsResponse>({ body: '' })),
putFileContents: vi.fn().mockImplementation(() => mock<FileResource>()),
isFolderLoading: ref(false),
activeFiles: ref([]),
loadFolderForFileContext: vi.fn(),
makeRequest: vi.fn().mockResolvedValue({ status: 200 }),
closed: ref(false),
...options
}
}
| owncloud/web/packages/web-test-helpers/src/mocks/useAppDefaultsMock.ts/0 | {
"file_path": "owncloud/web/packages/web-test-helpers/src/mocks/useAppDefaultsMock.ts",
"repo_id": "owncloud",
"token_count": 422
} | 857 |
const { Logger } = require('nightwatch')
/**
* Determine if an element is currently displayed
* ".isAnyElementVisible" will automatically wait for the element to be visible (until the specified timeout).
* The provided selector may resolve to multiple elements, in that case, it will check if any of them is visible.
* If none of the element from the collection is found or visible,
* by default, an error is thrown but it WILL NOT fail the test.
*
* Usage:
* .isAnyElementVisible(locateStrategy: string, selector: string, callback?: function)
* .isAnyElementVisible({ locateStrategy: string, selector: string, timeout?: number, suppressNotFoundErrors?: boolean }, callback?: function)
* @returns {exports}
*/
module.exports.command = async function (...args) {
const defaultTimeout = 5 * 1000
const defaultLocateStrategy = 'css selector'
const params = {
timeout: defaultTimeout,
suppressNotFoundErrors: false,
callback: null
}
if (args.length > 3) {
throw new Error(`Expected 2 or 3 arguments but got ${args.length}`)
}
if (args[0] instanceof Object && !(args[0] instanceof Array)) {
if (args.length > 2) {
throw new Error(`Expected 2 arguments but got ${args.length}`)
}
params.locateStrategy = args[0].locateStrategy || defaultLocateStrategy
params.selector = args[0].selector
params.timeout = args[0].timeout || defaultTimeout
if (typeof params.suppressNotFoundErrors === 'boolean') {
params.suppressNotFoundErrors = args[0].suppressNotFoundErrors
}
if (args[1]) {
params.callback = args[1]
}
} else {
params.locateStrategy = args[0]
params.selector = args[1]
if (args[2]) {
params.callback = args[2]
}
}
if (!['css selector', 'xpath'].includes(params.locateStrategy)) {
throw new Error(
`Invalid selector type: "${params.locateStrategy}".\n Use either "xpath" or "css selector"`
)
}
if (!params.selector) {
throw new Error(`Element selector is required`)
}
if (params.callback !== null && typeof params.callback !== 'function') {
throw new Error(`${params.callback} is not a function`)
}
const startTime = new Date()
let elapsedTime = new Date()
let result = {
isVisible: false
}
// wait and try until element is visible or timeout
while (elapsedTime - startTime < params.timeout && !result.isVisible) {
await this.elements(params.locateStrategy, params.selector, async (res) => {
result = { ...result, ...res }
if (res.value.length === 0) {
return
}
for (const { ELEMENT } of res.value) {
await this.elementIdDisplayed(ELEMENT, ({ value }) => (result.isVisible = value === true))
if (result.isVisible) {
break
}
}
})
elapsedTime = new Date()
}
if (!params.suppressNotFoundErrors && !result.isVisible) {
Logger.error(
`Timed out while waiting for element '${params.selector}' to be visible for ${params.timeout} milliseconds.`
)
}
params.callback && params.callback(result)
return this
}
| owncloud/web/tests/acceptance/customCommands/isAnyElementVisible.js/0 | {
"file_path": "owncloud/web/tests/acceptance/customCommands/isAnyElementVisible.js",
"repo_id": "owncloud",
"token_count": 1062
} | 858 |
Feature: User can open the details panel for any file or folder
As a user
I want to be able to open the details panel of any file or folder
So that the details of the file or folder are visible to me
Background:
Given these users have been created with default attributes and without skeleton files in the server:
| username |
| Alice |
| Brian |
And user "Alice" has logged in using the webUI
@files_versions-app-required
Scenario: View different areas of the app-sidebar for a file in files page
Given user "Alice" has created file "lorem.txt" in the server
And the user has browsed to the personal page
When the user opens the sidebar for file "lorem.txt" on the webUI
Then the app-sidebar should be visible
And the "details" details panel should be visible
And the "big" preview of thumbnail should be visible in the "details" panel
When the user switches to "actions" panel in details panel using the webUI
Then the "actions" details panel should be visible
And the "small" preview of thumbnail should be visible in the "actions" panel
When the user switches to "people" panel in details panel using the webUI
Then the "people" details panel should be visible
And the "small" preview of thumbnail should be visible in the "people" panel
When the user switches to "versions" panel in details panel using the webUI
Then the "versions" details panel should be visible
And the "small" preview of thumbnail should be visible in the "versions" panel
@files_versions-app-required
Scenario: View different areas of the app-sidebar for a folder in files page
Given user "Alice" has created folder "simple-folder" in the server
And the user has browsed to the personal page
When the user opens the sidebar for folder "simple-folder" on the webUI
Then the app-sidebar should be visible
And the "details" details panel should be visible
And the "big" preview of thumbnail should be visible in the "details" panel
When the user switches to "actions" panel in details panel using the webUI
Then the "actions" details panel should be visible
And the "small" preview of thumbnail should be visible in the "actions" panel
When the user switches to "people" panel in details panel using the webUI
Then the "people" details panel should be visible
And the "small" preview of thumbnail should be visible in the "people" panel
@ocis-reva-issue-106
Scenario: without any share the shared-with-others page should be empty
When the user browses to the shared-with-others page using the webUI
Then there should be no resources listed on the webUI
Scenario: without any share the shared-with-me page should be empty
When the user browses to the shared-with-me page in accepted shares view
Then there should be no resources listed on the webUI
When the user browses to the shared-with-me page in declined shares view
Then there should be no resources listed on the webUI
Scenario: the sidebar is invisible after closing
Given user "Alice" has created file "lorem.txt" in the server
And the user has browsed to the personal page
When the user opens the sidebar for file "lorem.txt" on the webUI
Then the app-sidebar should be visible
When the user closes the app-sidebar using the webUI
Then the app-sidebar should be invisible
@issue-4244
Scenario: the sidebar is invisible after opening the selected folder
Given user "Alice" has created file "simple-folder" in the server
And the user has browsed to the personal page
When the user opens folder "simple-folder" using the webUI
Then the app-sidebar should be invisible
| owncloud/web/tests/acceptance/features/webUIFilesDetails/fileDetails.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUIFilesDetails/fileDetails.feature",
"repo_id": "owncloud",
"token_count": 1025
} | 859 |
@public_link_share-feature-required
Feature: Access public link shares by public
As a public
I want to access links shared by a owncloud user
So that I get access to files on owncloud
Background:
Given user "Alice" has been created with default attributes and without skeleton files in the server
And user "Alice" has created folder "simple-folder" in the server
Scenario: public should be able to access a public link with correct password
Given user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions and password "#Passw0rd" in the server
When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session
Then file "lorem.txt" should be listed on the webUI
Scenario: public should not be able to access a public link with wrong password
Given user "Alice" has shared folder "simple-folder" with link with "read" permissions and password "#Passw0rd" in the server
When the public uses the webUI to access the last public link created by user "Alice" with password "#Passwrd" in a new session
Then the public should not get access to the publicly shared file
Scenario: public creates a folder in the public link
Given user "Alice" has created a public link with following settings in the server
| path | /simple-folder |
| name | public link |
| permissions | read, create |
When the public uses the webUI to access the last public link created by user "Alice" in a new session
And the public creates a folder with the name "public-created-folder" using the webUI
Then folder "public-created-folder" should be listed on the webUI
When the public reloads the current page of the webUI
Then folder "public-created-folder" should be listed on the webUI
And as "Alice" folder "/simple-folder/public-created-folder" should exist in the server
@skipOnOC10 @issue-4582
Scenario: public batch deletes resources in the public link
Given user "Alice" has uploaded file "data.zip" to "simple-folder/data.zip" in the server
And user "Alice" has created folder "simple-folder/simple-empty-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | /simple-folder |
| name | public link |
| permissions | read, create, delete, update |
When the public uses the webUI to access the last public link created by user "Alice" in a new session
And the public marks these files for batch action using the webUI
| name |
| lorem.txt |
| simple-empty-folder |
| data.zip |
And the public batch deletes the marked files using the webUI
Then file "data.zip" should not be listed on the webUI
And folder "simple-empty-folder" should not be listed on the webUI
And file "lorem.txt" should not be listed on the webUI
And as "Alice" folder "/simple-folder/simple-empty-folder" should not exist in the server
And as "Alice" file "/simple-folder/lorem.txt" should not exist in the server
And as "Alice" file "/simple-folder/data.zip" should not exist in the server
Scenario: files are not selected initially in the public share
Given user "Alice" has uploaded file "data.zip" to "simple-folder/data.zip" in the server
And user "Alice" has created folder "simple-folder/simple-empty-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | /simple-folder |
| name | public link |
When the public uses the webUI to access the last public link created by user "Alice" in a new session
Then these files should not be selected on the webUI
| name |
| lorem.txt |
| simple-empty-folder |
| data.zip |
Scenario: public selects files and clear the selection in the public share
Given user "Alice" has uploaded file "data.zip" to "simple-folder/data.zip" in the server
And user "Alice" has created folder "simple-folder/simple-empty-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | /simple-folder |
| name | public link |
When the public uses the webUI to access the last public link created by user "Alice" in a new session
And the public marks these files for batch action using the webUI
| name |
| lorem.txt |
| simple-empty-folder |
| data.zip |
Then these files should be selected on the webUI
| name |
| lorem.txt |
| simple-empty-folder |
| data.zip |
| owncloud/web/tests/acceptance/features/webUISharingPublicBasic/publicLinkPublicActions.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUISharingPublicBasic/publicLinkPublicActions.feature",
"repo_id": "owncloud",
"token_count": 1693
} | 860 |
const {
client,
createSession,
closeSession,
startWebDriver,
stopWebDriver
} = require('nightwatch-api')
const userSettings = require('./userSettings')
module.exports = {
/**
* Navigates to the login page and fills&submits the login form.
*
* @param {userId} userId
* @param {password} [password=null] - If not passed, default password for given `userId` will be used
*/
loginAsUser: async function (userId, password = null) {
await client.page.loginPage().navigate()
await this.fillInAndSubmitLogin(userId, password)
},
/**
* Fills in the login form, assuming that we are on the login page already.
*
* @param userId
* @param password
* @return {Promise<void>}
*/
fillInAndSubmitLogin: async function (userId, password = null) {
password = password || userSettings.getPasswordForUser(userId)
if (client.globals.openid_login) {
await client.page.ocisLoginPage().login(userId, password)
} else {
await client.page.ownCloudLoginPage().login(userId, password)
}
await client.page
.webPage()
.waitForElementVisible('@appContainer')
.api.page.FilesPageElement.filesList()
.waitForLoadingFinished()
.then(() => {
client.globals.currentUser = userId
})
},
/**
*
* Destroy and start a new browser session
*/
startNewSession: async function () {
let env = 'local'
if (process.env.DRONE) {
env = 'drone'
}
await closeSession()
await stopWebDriver()
await startWebDriver({ env })
await createSession({ env })
await client.windowMaximize()
},
/**
*
* @param {string} userId
*/
reLoginAsUser: async function (userId) {
await this.startNewSession()
return this.loginAsUser(userId)
},
logout: function (userId) {
const webPage = client.page.webPage()
return webPage
.navigate()
.waitForElementVisible('@userMenuButton')
.click('@userMenuButton')
.waitForElementVisible('@logoutMenuItem')
.waitForAnimationToFinish()
.click('@logoutMenuItem')
}
}
| owncloud/web/tests/acceptance/helpers/loginHelper.js/0 | {
"file_path": "owncloud/web/tests/acceptance/helpers/loginHelper.js",
"repo_id": "owncloud",
"token_count": 781
} | 861 |
const util = require('util')
const { client } = require('nightwatch-api')
module.exports = {
commands: {
/**
* sets up the xpath for year of expiry date
*
* @param {Date} date
* @returns {{locateStrategy: string, selector: *}}
*/
getSelectorExpiryDateYear: function (date) {
const yearString = date.getFullYear()
return {
selector: util.format(this.elements.dateTimeYearPicker.selector, yearString),
locateStrategy: this.elements.dateTimeYearPicker.locateStrategy
}
},
/**
* sets up the xpath for month of expiry date
*
* @param {Date} date
* @returns {{locateStrategy: string, selector: *}}
*/
getSelectorExpiryDateMonth: function (date) {
const monthString = date.toLocaleString('en', { month: 'short' })
return {
selector: util.format(this.elements.dateTimeMonthPicker.selector, monthString),
locateStrategy: this.elements.dateTimeMonthPicker.locateStrategy
}
},
/**
* sets up the xpath for year of expiry date
*
* @param {Date} date
* @returns {{locateStrategy: string, selector: *}}
*/
getSelectorExpiryDateDay: function (date) {
const formatDate = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }
const dayString = date.getDate()
const fullDateString = date.toLocaleDateString('en', formatDate)
return {
selector: util.format(this.elements.dateTimeDayPicker.selector, dayString, fullDateString),
locateStrategy: this.elements.dateTimeDayPicker.locateStrategy
}
},
/**
* sets provided year in expiry date field on webUI
*
* @param {Date} date
* @returns {Promise<void>}
*/
setExpiryDateYear: function (date) {
const yearSelector = this.getSelectorExpiryDateYear(date)
return this.waitForElementVisible('@datepickerTitle')
.click('@datepickerTitle')
.waitForElementVisible('@datepickerMonthAndYearTitle')
.click('@datepickerMonthAndYearTitle')
.waitForElementVisible(yearSelector)
.click(yearSelector)
.waitForElementVisible('@datepickerTitle')
.click('@datepickerTitle')
.waitForElementNotPresent('@datepickerMonthAndYearTitle')
},
/**
* sets provided month in expiry date field on webUI
*
* @param {Date} date
* @returns {Promise<void>}
*/
setExpiryDateMonth: function (date) {
const monthSelector = this.getSelectorExpiryDateMonth(date)
return this.waitForElementVisible('@datepickerTitle')
.click('@datepickerTitle')
.waitForElementVisible('@datepickerMonthAndYearTitle')
.waitForElementVisible(monthSelector)
.click(monthSelector)
.waitForElementNotPresent('@datepickerMonthAndYearTitle')
},
/**
* sets provided day in expiry date field on webUI
*
* @param {Date} date
* @returns {Promise<void>}
*/
setExpiryDateDay: function (date) {
const daySelector = this.getSelectorExpiryDateDay(date)
return this.waitForElementVisible(daySelector)
.click(daySelector)
.waitForElementNotPresent(daySelector)
},
/**
* checks if the given expiryDate is disabled or not
*
* @param {Date} pastDate provided past date for inspection
*
* @returns {Promise<boolean>}
*/
isExpiryDateDisabled: async function (pastDate) {
let disabled = false
const yearSelector = this.getSelectorExpiryDateYear(pastDate)
const monthSelector = this.getSelectorExpiryDateMonth(pastDate)
const daySelector = this.getSelectorExpiryDateDay(pastDate)
await this.waitForElementVisible('@datepickerTitle')
.click('@datepickerTitle')
.waitForElementVisible('@datepickerMonthAndYearTitle')
.click('@datepickerMonthAndYearTitle')
.waitForElementVisible(yearSelector)
.getAttribute(yearSelector, 'class', (result) => {
if (result.value.includes('is-disabled') === true) {
disabled = true
}
})
if (disabled) {
return disabled
}
await this.waitForElementVisible(yearSelector)
.click(yearSelector)
.waitForElementVisible(monthSelector)
.getAttribute(monthSelector, 'class', (result) => {
if (result.value.includes('is-disabled') === true) {
disabled = true
}
})
if (disabled) {
return disabled
}
await this.waitForElementVisible(monthSelector)
.click(monthSelector)
.waitForElementVisible(daySelector)
.getAttribute(daySelector, 'class', (result) => {
if (result.value.includes('is-disabled') === true) {
disabled = true
}
})
return disabled
},
/**
* a function to move the calendar to the given year
*
* WARN: this function is meant to be used as a script function for executeAsync() command
* so it will only run in a browser context
*
* USAGE: client.executeAsync(moveCalendarYearScript, ['.calendar-id', '2040'])
*/
moveCalendarYearScript: function (selector, dateRange, done) {
return document
.querySelector(selector)
.__datePicker.$refs.calendar.move(new Date(Date.parse(dateRange)))
.then(function () {
done(true)
})
.catch(function (err) {
done(err)
})
},
/**
* sets expiration date on collaborators/public-link shares
*
* @param {string} value - provided date in format YYYY-MM-DD, or empty string to unset date
* @param {string} shareType link|collaborator
* @returns {Promise<boolean>} returns true if succeeds to set provided expiration date
*/
setExpirationDate: async function (
value,
shareType = 'collaborator',
editCollaborator = false
) {
if (value === '') {
return this.click('@publicLinkDeleteExpirationDateButton')
}
const dateToSet = new Date(Date.parse(value))
if (shareType === 'link') {
await client.executeAsync(this.moveCalendarYearScript, [
'.link-expiry-picker:not(.vc-container)',
value
])
} else if (editCollaborator) {
await client.executeAsync(this.moveCalendarYearScript, [
'.collaborator-edit-dropdown-options-list .files-recipient-expiration-datepicker',
value
])
} else {
await client.executeAsync(this.moveCalendarYearScript, [
'.files-recipient-expiration-datepicker',
value
])
}
if (shareType === 'collaborator' || shareType === 'link') {
const disabled = await this.isExpiryDateDisabled(dateToSet)
if (disabled) {
console.log('WARNING: Cannot change expiration date to disabled value!')
await this.api.elements('@datePickerButton', ({ value }) => {
for (const { ELEMENT } of value) {
this.api.elementIdDisplayed(ELEMENT, (result) => {
if (result.value === true) {
this.api.elementIdClick(ELEMENT)
}
})
}
})
return false
}
}
const month = dateToSet.toLocaleString('default', { month: 'long' })
if (month === 'December') {
await this.setExpiryDateMonth(dateToSet).setExpiryDateDay(dateToSet)
return true
}
await this.setExpiryDateYear(dateToSet)
.setExpiryDateMonth(dateToSet)
.setExpiryDateDay(dateToSet)
return true
}
},
elements: {
dateTimeYearPicker: {
selector:
'//span[contains(@class, "vc-nav-item") and @role="button" and normalize-space(.)="%s"]',
locateStrategy: 'xpath'
},
dateTimeMonthPicker: {
selector:
'//span[contains(@class, "vc-nav-item") and @role="button" and normalize-space(.)="%s"]',
locateStrategy: 'xpath'
},
dateTimeDayPicker: {
selector:
'//div[not(contains(@class, "is-not-in-month"))]/span[contains(@class, "vc-day-content vc-focusable") and normalize-space(.)="%s" and @aria-label="%s"]',
locateStrategy: 'xpath'
},
publicLinkDeleteExpirationDateButton: {
selector: '#oc-files-file-link-expire-date-delete'
},
datepickerTitle: {
selector: '.vc-title'
},
datepickerMonthAndYearTitle: {
selector: '.vc-nav-title.vc-grid-focus'
},
datePickerButton: {
selector: 'button[data-testid="recipient-datepicker-btn"]'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/FilesPageElement/expirationDatePicker.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/FilesPageElement/expirationDatePicker.js",
"repo_id": "owncloud",
"token_count": 3689
} | 862 |
const util = require('util')
const xpathHelper = require('../helpers/xpath')
const { join, normalize } = require('../helpers/path')
const { client } = require('nightwatch-api')
module.exports = {
url: function () {
return join(this.api.launchUrl, '/files/list/all')
},
commands: {
/**
* like build-in navigate() but also waits till for the progressbar to appear and disappear
* @param {string} folder - if given navigate to the folder without clicking the links
* @returns {*}
*/
navigateAndWaitTillLoaded: async function (folder = '') {
return await this.navigate(join(this.url(), folder)).waitForElementPresent(
this.page.FilesPageElement.filesList().elements.anyAfterLoading
)
},
/**
*
* @param {string} folder
*/
navigateToFolder: async function (folder) {
await this.page.FilesPageElement.filesList().navigateToFolder(folder)
return this
},
/**
*
* @param {string} resource
*/
navigateToBreadcrumb: function (resource) {
const breadcrumbElement = this.elements.resourceBreadcrumb
const resourceXpath = util.format(
breadcrumbElement.selector,
xpathHelper.buildXpathLiteral(resource)
)
return this.useStrategy(breadcrumbElement)
.waitForElementVisible(resourceXpath)
.click(resourceXpath)
.useCss()
},
/**
* Gets the breadcrumb element selector for the provided combination of clickable
* and non-clickable breadcrumb segments.
* Note: the combination (false,false) is invalid.
*
* @param clickable Whether a clickable breadcrumb is wanted
* @param nonClickable Whether a non-clickable breadcrumb is wanted
* @returns {null|{locateStrategy: string, selector: string}}
*/
getBreadcrumbSelector: function (clickable, nonClickable) {
if (clickable) {
return this.elements.resourceBreadcrumb
} else if (nonClickable) {
return this.elements.resourceBreadcrumbNonClickable
}
return null
},
isCreateFolderVisible: async function () {
let isVisible = false
await this.api.element('@newFileMenuButtonAnyState', (result) => {
isVisible = result.value === 0
})
return isVisible
},
/**
* Create a folder with the given name
*
* @param {string} name to set or null to use default value from dialog
* @param {boolean} expectToSucceed
*/
createFolder: async function (name, expectToSucceed = true) {
await this.waitForElementVisible('@newFileMenuButtonAnyState')
.waitForElementEnabled('@newFileMenuButtonAnyState')
.click('@newFileMenuButton')
.click('@newFolderButton')
.waitForElementVisible('@dialog')
.waitForAnimationToFinish() // wait for transition on the modal to finish
if (name !== null) {
await this.clearValueWithEvent('@dialogInput')
await this.setValue('@dialogInput', name)
}
const timeout = expectToSucceed
? this.api.globals.waitForConditionTimeout
: this.api.globals.waitForNegativeConditionTimeout
await this.click(
{
selector: '@dialogConfirmBtnEnabled',
suppressNotFoundErrors: !expectToSucceed
},
timeout
).waitForAjaxCallsToStartAndFinish()
if (expectToSucceed) {
await this.waitForElementNotPresent('@dialog')
} else {
await this.waitForElementPresent('@dialogBoxInputTextInRed')
// checking if the button is disabled
.waitForElementPresent('@dialogConfirmBtnDisabled')
}
return this
},
/**
* Create a file with the given name
*
* @param {string} name to set or null to use default value from dialog
* @param {boolean} expectToSucceed
*/
createFile: async function (name, expectToSucceed = true) {
await this.waitForElementVisible('@newFileMenuButton')
.click('@newFileMenuButton')
.waitForElementVisible('@newFileButton')
.click('@newFileButton')
.waitForElementVisible('@dialog')
.waitForAnimationToFinish() // wait for transition on the modal to finish
if (name !== null) {
await this.clearValueWithEvent('@dialogInput')
await this.setValue('@dialogInput', name)
}
const timeout = expectToSucceed
? this.api.globals.waitForConditionTimeout
: this.api.globals.waitForNegativeConditionTimeout
await this.click(
{
selector: '@dialogConfirmBtnEnabled',
suppressNotFoundErrors: !expectToSucceed
},
timeout
)
if (expectToSucceed) {
await this.waitForElementNotPresent('@dialog')
} else {
await this.waitForElementPresent('@dialogBoxInputTextInRed')
// checking if the button is disabled
.waitForElementPresent('@dialogConfirmBtnDisabled')
}
return this
},
selectFileForUpload: function (filePath) {
return this.waitForElementVisible('@uploadFilesButton')
.click('@uploadFilesButton')
.waitForElementVisible('@fileUploadButton')
.setValue('@fileUploadInput', filePath)
},
/**
*
* @param {string} filePath
*/
uploadFile: function (filePath) {
return this.selectFileForUpload(filePath)
.waitForElementVisible('@fileUploadStatus')
.closeFileFolderUploadProgress()
},
closeFileFolderUploadProgress: function () {
return this.waitForElementVisible('@filesFoldersUploadProgressClose').click(
'@filesFoldersUploadProgressClose'
)
},
/**
* This uploads a folder that is inside the selenium host,
* not from the server, web or where the test runner is located.
* So, the folder needs to be already there on the machine where the browser is running.
*
* @typedef {import('../customCommands/uploadRemote')} UploadRemote
* We can extract the folder path from the callback of
* [uploadRemote()]{@link UploadRemote.command}, which is similar to the following:
* `/tmp/545cfb7e4b6e6603b2bbef4d69f82627/upload1734400381952243704file/new-lorem.txt`.
* Extract `upload1734400381952243704file` and send it as arg here, otherwise, the whole
* `/tmp/<sessionID>` folder will get uploaded
*
* @see below for working information
*
* @param {string} [folderName] - should be passed in as format "/upload<uniqueId>file" or "upload<uniqueId>file"
*/
uploadSessionFolder: function (folderName = '') {
/*
files uploaded through selenium endpoints are saved in
/tmp/<sessionId>/upload<uniqueId>file/<filename>.
So, we are trying to upload the "/tmp/<sessionId>" (or, if the folderName is set, it's "/tmp/<sessionId>/<folderName>")
folder through web, by setting value on folder input field to that folder, and hopefully,
web gets the `onChange` event and uploads that folder.
*/
const sessionId = this.api.sessionId
folderName = normalize(folderName)
folderName = `/tmp/${sessionId}/${folderName}`
return this.uploadFolder(folderName)
},
/**
* Upload folder which is inside selenium
*
* @param {string} folderName
*/
uploadFolder: function (folderName) {
return this.waitForElementVisible('@uploadFilesButton')
.click('@uploadFilesButton')
.waitForElementVisible('@fileUploadButton')
.setValue('@folderUploadInput', folderName)
.waitForElementVisible('@fileUploadStatus')
.closeFileFolderUploadProgress()
},
/**
* Returns whether files or folders can be created in the current page.
*/
canCreateFiles: async function () {
let canCreate = false
await this.waitForElementVisible('@newFileMenuButtonAnyState').getAttribute(
'@newFileMenuButtonAnyState',
'disabled',
(result) => {
canCreate = result.value === 'true'
}
)
return canCreate
},
checkForNonPresentDeleteButtonInSingleShareView: function () {
return this.waitForElementNotPresent('@deleteSelectedButton')
},
deleteAllCheckedFiles: function () {
return this.waitForElementVisible('@deleteSelectedButton')
.click('@deleteSelectedButton')
.waitForAjaxCallsToStartAndFinish()
},
confirmFileOverwrite: async function () {
await this.waitForAnimationToFinish() // wait for transition on the modal to finish
.waitForElementVisible('@dialogConfirmBtnSecondaryEnabled')
.click('@dialogConfirmBtnSecondaryEnabled')
.waitForElementNotPresent('@dialog')
.waitForAjaxCallsToStartAndFinish()
.waitForElementVisible('@uploadSuccess')
.closeFileFolderUploadProgress()
return this
},
checkForButtonDisabled: function () {
return this.waitForElementVisible('@dialogConfirmBtnDisabled')
},
/**
* Create a md file with the given name
*
* @param {string | null} name to set or null to use default value from dialog
* @param {boolean} expectToSucceed
*/
createMarkdownFile: async function (name, expectToSucceed = true) {
await this.waitForElementVisible('@newFileMenuButton')
.click('@newFileMenuButton')
.waitForElementVisible('@newMdFileButton')
.click('@newMdFileButton')
.waitForElementVisible('@dialog')
if (name !== null) {
await this.clearValueWithEvent('@dialogInput')
await this.setValue('@dialogInput', name)
}
const timeout = expectToSucceed
? this.api.globals.waitForConditionTimeout
: this.api.globals.waitForNegativeConditionTimeout
await this.initAjaxCounters()
.click(
{
selector: '@dialogConfirmBtnEnabled',
suppressNotFoundErrors: !expectToSucceed
},
timeout
)
.waitForOutstandingAjaxCalls()
if (expectToSucceed) {
await this.waitForElementNotPresent('@dialog')
}
return this
},
isRootDirectory: async function () {
return await this.assert.not.elementPresent('@breadcrumb')
},
isSearchBarVisible: async function () {
let searchBar
await this.api.elements('@searchInput', (result) => {
searchBar = result.value
})
return searchBar.length > 0
}
},
elements: {
searchInput: {
selector: 'input.oc-search-input'
},
uploadFilesButton: {
selector: '#upload-menu-btn:not([disabled])'
},
newFileMenuButtonAnyState: {
selector: '#new-file-menu-btn'
},
newFileMenuButton: {
selector: '#new-file-menu-btn:enabled'
},
// covers oc-files-actions-delete-permanent-trigger and oc-files-actions-delete-trigger
deleteSelectedButton: {
selector: '//button[contains(@class, "oc-files-actions-delete-")]',
locateStrategy: 'xpath'
},
newResourceDropdown: {
selector: '#new-file-menu-drop'
},
newFolderButton: {
selector: '#new-folder-btn'
},
newFileButton: {
selector: '#new-file-menu-drop .new-file-btn-txt'
},
newMdFileButton: {
selector: '#new-file-menu-drop .new-file-btn-md'
},
newFolderInput: {
selector: '#new-folder-input'
},
newFileInput: {
selector: '#new-file-input'
},
breadcrumb: {
selector: '#files-breadcrumb li:nth-of-type(2)'
},
breadcrumbMobile: {
selector: '//span[contains(@class, "oc-breadcrumb-drop-label-text") and text()=%s]',
locateStrategy: 'xpath'
},
breadcrumbMobileReferencedToOpenSidebarButton: {
selector:
'//button[@aria-label="Open sidebar to view details"]/ancestor::div//span[contains(@class, "oc-breadcrumb-drop-label-text") and text()=%s]',
locateStrategy: 'xpath'
},
resourceBreadcrumb: {
selector:
'//nav[@id="files-breadcrumb"]//*[(self::a or self::button)]/span[contains(text(),%s)]',
locateStrategy: 'xpath'
},
resourceBreadcrumbNonClickable: {
selector: '//nav[@id="files-breadcrumb"]//span[contains(text(),%s)]',
locateStrategy: 'xpath'
},
fileUploadButton: {
selector: '#files-file-upload-button'
},
fileUploadInput: {
selector: '#files-file-upload-input'
},
folderUploadInput: {
selector: '#files-folder-upload-input'
},
fileUploadProgress: {
selector: '#upload-info'
},
fileUploadStatus: {
selector: '.upload-info-status .upload-info-success, .upload-info-status .upload-info-danger'
},
filesFoldersUploadProgressClose: {
selector: '#upload-info #close-upload-info-btn'
},
dialog: {
selector: '.oc-modal'
},
dialogConfirmBtnEnabled: {
selector: '.oc-modal-body-actions-confirm:enabled'
},
dialogConfirmBtnSecondaryEnabled: {
selector: '.oc-modal-body-actions-secondary:enabled'
},
dialogConfirmBtnDisabled: {
selector: '.oc-modal-body-actions-confirm:disabled'
},
dialogCancelBtn: {
selector: '.oc-modal-body-actions-cancel'
},
dialogInput: {
selector: '.oc-modal-body-input .oc-text-input'
},
clearSelectionBtn: {
selector: '.oc-files-actions-clear-selection-trigger'
},
dialogBoxInputTextInRed: {
selector: '.oc-text-input-danger'
},
uploadSuccess: {
selector: '.upload-info-status .upload-info-success'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/personalPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/personalPage.js",
"repo_id": "owncloud",
"token_count": 5451
} | 863 |
const { client } = require('nightwatch-api')
const { After, Before, Given, Then, When } = require('@cucumber/cucumber')
const httpHelper = require('../helpers/httpHelper')
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const occHelper = require('../helpers/occHelper')
let initialConfigJsonSettings
const getConfigJsonContent = function (fullPathOfConfigFile) {
if (!fs.existsSync(fullPathOfConfigFile)) {
throw Error('Could not find configfile')
}
const rawdata = fs.readFileSync(fullPathOfConfigFile)
return JSON.parse(rawdata)
}
function setconfig(key, subkey, value, configfile) {
const data = getConfigJsonContent(configfile)
if (!data[key]) {
data[key] = {}
}
data[key][subkey] = value
return fs.writeFileSync(configfile, JSON.stringify(data, null, 4))
}
Then(
'the {string} message with header {string} should be displayed on the webUI',
async function (type, message) {
const text = await client.page.webPage().getDisplayedMessage(type, true)
assert.strictEqual(text, message)
}
)
Then(
'the following {word} message should be displayed on the webUI',
async function (type, message) {
const displayedMessage = await client.page.webPage().getDisplayedMessage(type)
assert.strictEqual(displayedMessage, message)
}
)
Then(
'the error message {string} should be displayed on the webUI dialog prompt',
function (message) {
return client.page
.webPage()
.waitForElementVisible('@ocDialogPromptAlert')
.expect.element('@ocDialogPromptAlert')
.text.to.equal(message)
}
)
Then(
'the user should see the following error message on the link resolve page',
function (message) {
return client.page
.publicLinkPasswordPage()
.waitForElementVisible('@linkResolveErrorTitle')
.expect.element('@linkResolveErrorTitle')
.text.to.equal(message)
}
)
When('the user clears all error message from the webUI', function () {
return client.page.webPage().clearAllErrorMessages()
})
Then('no message should be displayed on the webUI', async function () {
const hasMessage = await client.page.webPage().hasErrorMessage(false)
assert.strictEqual(hasMessage, false, 'Expected no messages but a message is displayed.')
return this
})
const getCurrentScenario = function (testCase) {
const scenarios = testCase.gherkinDocument.feature.children
const scenarioName = testCase.pickle.name
let currentScenario = null
for (const scenario of scenarios) {
if (
Object.prototype.hasOwnProperty.call(scenario, 'scenario') &&
scenario.scenario.name === scenarioName
) {
currentScenario = scenario.scenario
break
}
}
return {
...currentScenario,
...testCase.pickle,
getLineNumber: () => currentScenario.location.line,
isScenarioOutline: () => currentScenario.keyword === 'Scenario Outline'
}
}
const getExpectedFails = function () {
let expectedFails = null
let expectedFailureFile = process.env.EXPECTED_FAILURES_FILE || ''
expectedFailureFile = path.parse(expectedFailureFile).base
try {
expectedFails = fs.readFileSync(expectedFailureFile, 'utf8')
} catch (err) {
console.error('Expected failures file not found!')
}
return expectedFails
}
const checkIfExpectedToFail = function (scenarioLine, expectedFails) {
const scenarioLineRegex = new RegExp(scenarioLine)
return scenarioLineRegex.test(expectedFails)
}
After(async function (testCase) {
if (!client.globals.screenshots) {
return
}
// Generate screenshots when the test fails on retry
if (testCase.result.status === 'FAILED' && !testCase.result.willBeRetried) {
const expectedFails = getExpectedFails()
const scenario = getCurrentScenario(testCase)
let featureFile = scenario.uri.replace('features/', '') + ':' + scenario.getLineNumber()
let expectedToFail = checkIfExpectedToFail(featureFile, expectedFails)
if (scenario.isScenarioOutline()) {
// scenario example id
const currentExampleId = scenario.astNodeIds[scenario.astNodeIds.length - 1]
// scenario examples
const examples = scenario.examples[0].tableBody
for (const example of examples) {
if (example.id === currentExampleId) {
featureFile = featureFile.replace(/:[0-9]*/, ':' + example.location.line)
if (!expectedToFail) {
expectedToFail = checkIfExpectedToFail(featureFile, expectedFails)
}
break
}
}
}
if (!expectedToFail) {
console.log('saving screenshot of failed test')
const filename = featureFile.replace('/', '-').replace('.', '_').replace(':', '-L')
await client.saveScreenshot('./reports/screenshots/' + filename + '.png')
}
}
})
Before(function (testCase) {
testCase.pickle.createdFiles = []
if (
typeof process.env.SCREEN_RESOLUTION !== 'undefined' &&
process.env.SCREEN_RESOLUTION.trim() !== ''
) {
const resolution = process.env.SCREEN_RESOLUTION.split('x')
resolution[0] = parseInt(resolution[0])
resolution[1] = parseInt(resolution[1])
if (resolution[0] > 1 && resolution[1] > 1) {
client.resizeWindow(resolution[0], resolution[1])
console.log(
'\nINFO: setting screen resolution to ' + resolution[0] + 'x' + resolution[1] + '\n'
)
} else {
console.warn('\nWARNING: invalid resolution given, running tests in full resolution!\n')
client.maximizeWindow()
}
} else {
client.maximizeWindow()
}
// todo
// console.log(' ' + testCase.sourceLocation.uri + ':' + testCase.sourceLocation.line + '\n')
})
After(async function (testCase) {
if (client.globals.ocis) {
return
}
console.log('\n Result: ' + testCase.result.status + '\n')
// clear file locks
const body = new URLSearchParams()
body.append('global', 'true')
const url = 'apps/testing/api/v1/lockprovisioning'
await httpHelper.deleteOCS(url, 'admin', body)
})
Before(function () {
try {
this.fullPathOfConfigFile = client.globals.webUIConfig
initialConfigJsonSettings = getConfigJsonContent(client.globals.webUIConfig)
} catch (err) {
console.log(
'\x1b[33m%s\x1b[0m',
`\tCould not read config file.\n\tSet correct path of config file in WEB_UI_CONFIG_FILE env variable to fix this.\n\tSome tests may fail as a result.`
)
}
})
Before({ tags: '@disablePreviews' }, () => {
if (!client.globals.ocis) {
occHelper.runOcc(['config:system:set enable_previews --type=boolean --value=false'])
}
})
After(function () {
if (initialConfigJsonSettings) {
fs.writeFileSync(this.fullPathOfConfigFile, JSON.stringify(initialConfigJsonSettings, null, 4))
}
})
| owncloud/web/tests/acceptance/stepDefinitions/generalContext.js/0 | {
"file_path": "owncloud/web/tests/acceptance/stepDefinitions/generalContext.js",
"repo_id": "owncloud",
"token_count": 2372
} | 864 |
{
"id": "ownCloud Infinite Scale Test",
"realm": "oCIS",
"displayName": "ownCloud Infinite Scale",
"notBefore": 0,
"defaultSignatureAlgorithm": "RS256",
"revokeRefreshToken": false,
"refreshTokenMaxReuse": 0,
"accessTokenLifespan": 600,
"accessTokenLifespanForImplicitFlow": 900,
"ssoSessionIdleTimeout": 1800,
"ssoSessionMaxLifespan": 36000,
"ssoSessionIdleTimeoutRememberMe": 0,
"ssoSessionMaxLifespanRememberMe": 0,
"offlineSessionIdleTimeout": 2592000,
"offlineSessionMaxLifespanEnabled": false,
"offlineSessionMaxLifespan": 5184000,
"clientSessionIdleTimeout": 0,
"clientSessionMaxLifespan": 0,
"clientOfflineSessionIdleTimeout": 0,
"clientOfflineSessionMaxLifespan": 0,
"accessCodeLifespan": 60,
"accessCodeLifespanUserAction": 600,
"accessCodeLifespanLogin": 1800,
"actionTokenGeneratedByAdminLifespan": 43200,
"actionTokenGeneratedByUserLifespan": 600,
"oauth2DeviceCodeLifespan": 600,
"oauth2DevicePollingInterval": 5,
"enabled": true,
"sslRequired": "external",
"registrationAllowed": false,
"registrationEmailAsUsername": false,
"rememberMe": false,
"verifyEmail": false,
"loginWithEmailAllowed": true,
"duplicateEmailsAllowed": false,
"resetPasswordAllowed": false,
"editUsernameAllowed": false,
"bruteForceProtected": true,
"permanentLockout": false,
"maxFailureWaitSeconds": 900,
"minimumQuickLoginWaitSeconds": 60,
"waitIncrementSeconds": 60,
"quickLoginCheckMilliSeconds": 1000,
"maxDeltaTimeSeconds": 43200,
"failureFactor": 30,
"roles": {
"realm": [
{
"id": "0bb40fa2-4490-4687-9159-b1d27ec7423a",
"name": "ocisAdmin",
"description": "",
"composite": false,
"clientRole": false,
"containerId": "ownCloud Infinite Scale Test",
"attributes": {}
},
{
"id": "2d576514-4aae-46aa-9d9c-075f55f4d988",
"name": "uma_authorization",
"description": "${role_uma_authorization}",
"composite": false,
"clientRole": false,
"containerId": "ownCloud Infinite Scale Test",
"attributes": {}
},
{
"id": "8c79ff81-c256-48fd-b0b9-795c7941eedf",
"name": "ocisUser",
"description": "",
"composite": false,
"clientRole": false,
"containerId": "ownCloud Infinite Scale Test",
"attributes": {}
},
{
"id": "bd5f5012-48bb-4ea4-bfe6-0623e3ca0552",
"name": "ocisSpaceAdmin",
"description": "",
"composite": false,
"clientRole": false,
"containerId": "ownCloud Infinite Scale Test",
"attributes": {}
},
{
"id": "e2145b30-bf6f-49fb-af3f-1b40168bfcef",
"name": "offline_access",
"description": "${role_offline-access}",
"composite": false,
"clientRole": false,
"containerId": "ownCloud Infinite Scale Test",
"attributes": {}
},
{
"id": "82e13ea7-aac4-4d2c-9fc7-cff8333dbe19",
"name": "default-roles-ocis",
"description": "${role_default-roles}",
"composite": true,
"composites": {
"realm": ["offline_access", "uma_authorization"],
"client": {
"account": ["manage-account", "view-profile"]
}
},
"clientRole": false,
"containerId": "ownCloud Infinite Scale Test",
"attributes": {}
},
{
"id": "7eedfa6d-a2d9-4296-b6db-e75e4e9c0963",
"name": "ocisGuest",
"description": "",
"composite": false,
"clientRole": false,
"containerId": "ownCloud Infinite Scale Test",
"attributes": {}
}
],
"client": {
"realm-management": [
{
"id": "979ce053-a671-4b50-81d5-da4bdf7404c9",
"name": "view-clients",
"description": "${role_view-clients}",
"composite": true,
"composites": {
"client": {
"realm-management": ["query-clients"]
}
},
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "4bec4791-e888-4dac-bc95-71720d5981b9",
"name": "query-users",
"description": "${role_query-users}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "955b4406-b04f-432d-a61a-571675874341",
"name": "manage-authorization",
"description": "${role_manage-authorization}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "baa219af-2773-4d59-b06b-485f10fbbab3",
"name": "view-events",
"description": "${role_view-events}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "f280bc03-d079-478d-be06-3590580b25e9",
"name": "manage-users",
"description": "${role_manage-users}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "db698163-84ad-46c9-958f-bb5f80ae78b5",
"name": "query-clients",
"description": "${role_query-clients}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "36c04d89-abf7-4a2c-a808-8efa9aca1435",
"name": "manage-clients",
"description": "${role_manage-clients}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "06eae953-11d5-4344-b089-ffce1e68d5d8",
"name": "query-realms",
"description": "${role_query-realms}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "afe8aa78-2f06-43a5-8c99-cf68a1f5a86a",
"name": "realm-admin",
"description": "${role_realm-admin}",
"composite": true,
"composites": {
"client": {
"realm-management": [
"view-clients",
"query-users",
"manage-authorization",
"view-events",
"manage-users",
"query-clients",
"manage-clients",
"query-realms",
"impersonation",
"manage-realm",
"manage-identity-providers",
"view-authorization",
"create-client",
"query-groups",
"view-users",
"view-realm",
"view-identity-providers",
"manage-events"
]
}
},
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "22ee128a-b28e-4c6a-aa8e-ad4136d74e1b",
"name": "impersonation",
"description": "${role_impersonation}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "89d4f119-7f87-44d9-8eef-d207304de778",
"name": "manage-realm",
"description": "${role_manage-realm}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "ebffeff4-6794-4003-a2ab-a79eff7d1baa",
"name": "manage-identity-providers",
"description": "${role_manage-identity-providers}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "2361a7ff-d2b3-43f5-b360-ad0e44fba65c",
"name": "view-authorization",
"description": "${role_view-authorization}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "f7bf6d7a-a861-49c6-8f6f-225c18d0a03a",
"name": "create-client",
"description": "${role_create-client}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "34ccce1c-5a7e-4268-8836-2276545be900",
"name": "query-groups",
"description": "${role_query-groups}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "430f7831-8f22-4518-bd15-2998eae45a51",
"name": "view-users",
"description": "${role_view-users}",
"composite": true,
"composites": {
"client": {
"realm-management": ["query-groups", "query-users"]
}
},
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "371a31e6-4494-4b74-b3ea-d030663423ed",
"name": "view-realm",
"description": "${role_view-realm}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "e875775b-7a3e-4a5d-9e4e-376351b78626",
"name": "view-identity-providers",
"description": "${role_view-identity-providers}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
},
{
"id": "3dce7929-ee1f-40cd-9be1-7addcae92cef",
"name": "manage-events",
"description": "${role_manage-events}",
"composite": false,
"clientRole": true,
"containerId": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"attributes": {}
}
],
"web": [],
"security-admin-console": [],
"admin-cli": [],
"account-console": [],
"broker": [
{
"id": "81fad68a-8dd8-4d79-9a8f-206a82460145",
"name": "read-token",
"description": "${role_read-token}",
"composite": false,
"clientRole": true,
"containerId": "002faf0a-716c-4230-81c7-ce22d1eb832c",
"attributes": {}
}
],
"account": [
{
"id": "c49a49da-8ad0-44cb-b518-6d7d72cbe494",
"name": "manage-account",
"description": "${role_manage-account}",
"composite": true,
"composites": {
"client": {
"account": ["manage-account-links"]
}
},
"clientRole": true,
"containerId": "9850adad-7910-4b67-a790-da6444361618",
"attributes": {}
},
{
"id": "9dc2244e-b8a7-44f1-b173-d2b929fedcca",
"name": "view-consent",
"description": "${role_view-consent}",
"composite": false,
"clientRole": true,
"containerId": "9850adad-7910-4b67-a790-da6444361618",
"attributes": {}
},
{
"id": "ce115327-99c9-44d4-ba7d-820397dc11e6",
"name": "manage-account-links",
"description": "${role_manage-account-links}",
"composite": false,
"clientRole": true,
"containerId": "9850adad-7910-4b67-a790-da6444361618",
"attributes": {}
},
{
"id": "2ffdf854-084b-467a-91c6-7f07844efc9a",
"name": "view-groups",
"description": "${role_view-groups}",
"composite": false,
"clientRole": true,
"containerId": "9850adad-7910-4b67-a790-da6444361618",
"attributes": {}
},
{
"id": "8c45ca71-32aa-4547-932d-412da5e371ed",
"name": "view-profile",
"description": "${role_view-profile}",
"composite": false,
"clientRole": true,
"containerId": "9850adad-7910-4b67-a790-da6444361618",
"attributes": {}
},
{
"id": "cbeecf6d-9af8-4746-877b-74800a894c35",
"name": "view-applications",
"description": "${role_view-applications}",
"composite": false,
"clientRole": true,
"containerId": "9850adad-7910-4b67-a790-da6444361618",
"attributes": {}
},
{
"id": "ea798f64-b5f8-417f-9fe0-d3cd9172884f",
"name": "delete-account",
"description": "${role_delete-account}",
"composite": false,
"clientRole": true,
"containerId": "9850adad-7910-4b67-a790-da6444361618",
"attributes": {}
},
{
"id": "e73aaf6d-e67b-491a-9cc3-78c32c82b42c",
"name": "manage-consent",
"description": "${role_manage-consent}",
"composite": true,
"composites": {
"client": {
"account": ["view-consent"]
}
},
"clientRole": true,
"containerId": "9850adad-7910-4b67-a790-da6444361618",
"attributes": {}
}
]
}
},
"groups": [],
"defaultRole": {
"id": "82e13ea7-aac4-4d2c-9fc7-cff8333dbe19",
"name": "default-roles-ocis",
"description": "${role_default-roles}",
"composite": true,
"clientRole": false,
"containerId": "ownCloud Infinite Scale Test"
},
"requiredCredentials": ["password"],
"otpPolicyType": "totp",
"otpPolicyAlgorithm": "HmacSHA1",
"otpPolicyInitialCounter": 0,
"otpPolicyDigits": 6,
"otpPolicyLookAheadWindow": 1,
"otpPolicyPeriod": 30,
"otpPolicyCodeReusable": false,
"otpSupportedApplications": [
"totpAppMicrosoftAuthenticatorName",
"totpAppGoogleName",
"totpAppFreeOTPName"
],
"webAuthnPolicyRpEntityName": "keycloak",
"webAuthnPolicySignatureAlgorithms": ["ES256"],
"webAuthnPolicyRpId": "",
"webAuthnPolicyAttestationConveyancePreference": "not specified",
"webAuthnPolicyAuthenticatorAttachment": "not specified",
"webAuthnPolicyRequireResidentKey": "not specified",
"webAuthnPolicyUserVerificationRequirement": "not specified",
"webAuthnPolicyCreateTimeout": 0,
"webAuthnPolicyAvoidSameAuthenticatorRegister": false,
"webAuthnPolicyAcceptableAaguids": [],
"webAuthnPolicyPasswordlessRpEntityName": "keycloak",
"webAuthnPolicyPasswordlessSignatureAlgorithms": ["ES256"],
"webAuthnPolicyPasswordlessRpId": "",
"webAuthnPolicyPasswordlessAttestationConveyancePreference": "not specified",
"webAuthnPolicyPasswordlessAuthenticatorAttachment": "not specified",
"webAuthnPolicyPasswordlessRequireResidentKey": "not specified",
"webAuthnPolicyPasswordlessUserVerificationRequirement": "not specified",
"webAuthnPolicyPasswordlessCreateTimeout": 0,
"webAuthnPolicyPasswordlessAvoidSameAuthenticatorRegister": false,
"webAuthnPolicyPasswordlessAcceptableAaguids": [],
"users": [
{
"id": "389845cd-65b9-47fc-b723-ba75940bcbd7",
"createdTimestamp": 1611912383386,
"username": "admin",
"enabled": true,
"totp": false,
"emailVerified": true,
"firstName": "Admin",
"lastName": "Admin",
"email": "admin@example.org",
"credentials": [
{
"id": "499e0fbe-1c10-4588-9db4-e8a1012b9246",
"type": "password",
"createdDate": 1611912393787,
"secretData": "{\"value\":\"WUdGHYxGqrEBqg8Y3v+CKCzkzXkboMI6VmpWAYqvD7pIcP9z1zzDTqwlXrVFytoZMpcceT3Xm1hAGh7CZcSoHQ==\",\"salt\":\"pxP1MdkG//50Lv81WsQ5FA==\",\"additionalParameters\":{}}",
"credentialData": "{\"hashIterations\":27500,\"algorithm\":\"pbkdf2-sha256\",\"additionalParameters\":{}}"
}
],
"disableableCredentialTypes": [],
"requiredActions": [],
"realmRoles": ["uma_authorization", "ocisAdmin", "offline_access"],
"clientRoles": {
"account": ["manage-account", "view-profile"]
},
"notBefore": 0,
"groups": []
}
],
"scopeMappings": [
{
"clientScope": "offline_access",
"roles": ["offline_access"]
},
{
"clientScope": "roles",
"roles": ["ocisSpaceAdmin", "ocisGuest", "ocisUser", "ocisAdmin"]
}
],
"clientScopeMappings": {
"account": [
{
"client": "account-console",
"roles": ["manage-account", "view-groups"]
}
]
},
"clients": [
{
"id": "9850adad-7910-4b67-a790-da6444361618",
"clientId": "account",
"name": "${client_account}",
"rootUrl": "${authBaseUrl}",
"baseUrl": "/realms/oCIS/account/",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": ["/realms/oCIS/account/*"],
"webOrigins": [],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": false,
"publicClient": false,
"frontchannelLogout": false,
"protocol": "openid-connect",
"attributes": {
"post.logout.redirect.uris": "+"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": false,
"nodeReRegistrationTimeout": 0,
"defaultClientScopes": [],
"optionalClientScopes": []
},
{
"id": "55bb4cdc-045b-422a-8830-61245949d6aa",
"clientId": "account-console",
"name": "${client_account-console}",
"rootUrl": "${authBaseUrl}",
"baseUrl": "/realms/oCIS/account/",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": ["/realms/oCIS/account/*"],
"webOrigins": [],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": false,
"publicClient": true,
"frontchannelLogout": false,
"protocol": "openid-connect",
"attributes": {
"post.logout.redirect.uris": "+",
"pkce.code.challenge.method": "S256"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": false,
"nodeReRegistrationTimeout": 0,
"protocolMappers": [
{
"id": "9bf413ed-402f-438d-a72c-033f3c45dab2",
"name": "audience resolve",
"protocol": "openid-connect",
"protocolMapper": "oidc-audience-resolve-mapper",
"consentRequired": false,
"config": {}
}
],
"defaultClientScopes": ["web-origins", "acr", "profile", "roles", "email"],
"optionalClientScopes": ["address", "phone", "offline_access", "microprofile-jwt"]
},
{
"id": "2969b8ff-2ab3-4907-aaa7-091a7a627ccb",
"clientId": "admin-cli",
"name": "${client_admin-cli}",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": [],
"webOrigins": [],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": false,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": true,
"serviceAccountsEnabled": false,
"publicClient": true,
"frontchannelLogout": false,
"protocol": "openid-connect",
"attributes": {
"post.logout.redirect.uris": "+"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": false,
"nodeReRegistrationTimeout": 0,
"defaultClientScopes": [],
"optionalClientScopes": []
},
{
"id": "002faf0a-716c-4230-81c7-ce22d1eb832c",
"clientId": "broker",
"name": "${client_broker}",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": [],
"webOrigins": [],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": false,
"publicClient": false,
"frontchannelLogout": false,
"protocol": "openid-connect",
"attributes": {
"post.logout.redirect.uris": "+"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": false,
"nodeReRegistrationTimeout": 0,
"defaultClientScopes": [],
"optionalClientScopes": []
},
{
"id": "7848ee94-cc9b-40db-946f-a86ac73dc9b7",
"clientId": "realm-management",
"name": "${client_realm-management}",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": [],
"webOrigins": [],
"notBefore": 0,
"bearerOnly": true,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": false,
"publicClient": false,
"frontchannelLogout": false,
"protocol": "openid-connect",
"attributes": {
"post.logout.redirect.uris": "+"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": false,
"nodeReRegistrationTimeout": 0,
"defaultClientScopes": [],
"optionalClientScopes": []
},
{
"id": "97264f49-a8c1-4585-99b6-e706339c62f8",
"clientId": "security-admin-console",
"name": "${client_security-admin-console}",
"rootUrl": "${authAdminUrl}",
"baseUrl": "/admin/oCIS/console/",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": ["/admin/oCIS/console/*"],
"webOrigins": ["+"],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": false,
"publicClient": true,
"frontchannelLogout": false,
"protocol": "openid-connect",
"attributes": {
"post.logout.redirect.uris": "+",
"pkce.code.challenge.method": "S256"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": false,
"nodeReRegistrationTimeout": 0,
"protocolMappers": [
{
"id": "96092024-21dd-4d31-a004-2c5b96031da3",
"name": "locale",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "locale",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "locale",
"jsonType.label": "String"
}
}
],
"defaultClientScopes": [],
"optionalClientScopes": []
},
{
"id": "54b18eca-cf79-4263-9db9-2d79f8a1c831",
"clientId": "web",
"name": "",
"description": "",
"rootUrl": "https://ocis:9200",
"adminUrl": "https://ocis:9200",
"baseUrl": "",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": ["https://ocis:9200/*"],
"webOrigins": ["https://ocis:9200"],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": true,
"serviceAccountsEnabled": false,
"publicClient": true,
"frontchannelLogout": false,
"protocol": "openid-connect",
"attributes": {
"saml.assertion.signature": "false",
"saml.force.post.binding": "false",
"saml.multivalued.roles": "false",
"saml.encrypt": "false",
"post.logout.redirect.uris": "+",
"oauth2.device.authorization.grant.enabled": "false",
"backchannel.logout.revoke.offline.tokens": "false",
"saml.server.signature": "false",
"saml.server.signature.keyinfo.ext": "false",
"exclude.session.state.from.auth.response": "false",
"oidc.ciba.grant.enabled": "false",
"backchannel.logout.url": "https://ocis:9200/backchannel_logout",
"backchannel.logout.session.required": "true",
"client_credentials.use_refresh_token": "false",
"saml_force_name_id_format": "false",
"saml.client.signature": "false",
"tls.client.certificate.bound.access.tokens": "false",
"saml.authnstatement": "false",
"display.on.consent.screen": "false",
"saml.onetimeuse.condition": "false"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": true,
"nodeReRegistrationTimeout": -1,
"defaultClientScopes": ["web-origins", "profile", "roles", "email"],
"optionalClientScopes": ["address", "phone", "offline_access", "microprofile-jwt"]
}
],
"clientScopes": [
{
"id": "258e56a8-1eeb-49ea-957b-aff8df4656ba",
"name": "email",
"description": "OpenID Connect built-in scope: email",
"protocol": "openid-connect",
"attributes": {
"include.in.token.scope": "true",
"display.on.consent.screen": "true",
"consent.screen.text": "${emailScopeConsentText}"
},
"protocolMappers": [
{
"id": "068bcfb6-4a17-4c20-b083-ae542a7f76c8",
"name": "email verified",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-property-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "emailVerified",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "email_verified",
"jsonType.label": "boolean"
}
},
{
"id": "c00d6c21-2fd1-435f-9ee9-87e011048cbe",
"name": "email",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-property-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "email",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "email",
"jsonType.label": "String"
}
}
]
},
{
"id": "b3e1e47e-3912-4b55-ba89-b0198e767682",
"name": "address",
"description": "OpenID Connect built-in scope: address",
"protocol": "openid-connect",
"attributes": {
"include.in.token.scope": "true",
"display.on.consent.screen": "true",
"consent.screen.text": "${addressScopeConsentText}"
},
"protocolMappers": [
{
"id": "876baab9-39d1-4845-abb4-561a58aa152d",
"name": "address",
"protocol": "openid-connect",
"protocolMapper": "oidc-address-mapper",
"consentRequired": false,
"config": {
"user.attribute.formatted": "formatted",
"user.attribute.country": "country",
"user.attribute.postal_code": "postal_code",
"userinfo.token.claim": "true",
"user.attribute.street": "street",
"id.token.claim": "true",
"user.attribute.region": "region",
"access.token.claim": "true",
"user.attribute.locality": "locality"
}
}
]
},
{
"id": "9cae7ced-e7d9-4f7b-8e54-7402125f6ead",
"name": "offline_access",
"description": "OpenID Connect built-in scope: offline_access",
"protocol": "openid-connect",
"attributes": {
"consent.screen.text": "${offlineAccessScopeConsentText}",
"display.on.consent.screen": "true"
}
},
{
"id": "8eb1f69b-b941-4185-bca1-f916953f7cf5",
"name": "role_list",
"description": "SAML role list",
"protocol": "saml",
"attributes": {
"consent.screen.text": "${samlRoleListScopeConsentText}",
"display.on.consent.screen": "true"
},
"protocolMappers": [
{
"id": "fb587847-806f-4443-bab0-501efc0f0b46",
"name": "role list",
"protocol": "saml",
"protocolMapper": "saml-role-list-mapper",
"consentRequired": false,
"config": {
"single": "false",
"attribute.nameformat": "Basic",
"attribute.name": "Role"
}
}
]
},
{
"id": "947da1ff-f614-48fc-9ecb-c98cbcfd3390",
"name": "profile",
"description": "OpenID Connect built-in scope: profile",
"protocol": "openid-connect",
"attributes": {
"include.in.token.scope": "true",
"display.on.consent.screen": "true",
"consent.screen.text": "${profileScopeConsentText}"
},
"protocolMappers": [
{
"id": "46fec552-2f92-408a-84cf-ba98bf8e35fd",
"name": "family name",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-property-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "lastName",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "family_name",
"jsonType.label": "String"
}
},
{
"id": "c7ed5458-4d32-423e-8ea1-d112c45045d4",
"name": "middle name",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "middleName",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "middle_name",
"jsonType.label": "String"
}
},
{
"id": "e18d1ce4-3969-4ec1-9941-a27fd7555245",
"name": "picture",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "picture",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "picture",
"jsonType.label": "String"
}
},
{
"id": "dab85a5e-9af8-4fcd-88e4-9d3ae50dd5b6",
"name": "locale",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "locale",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "locale",
"jsonType.label": "String"
}
},
{
"id": "7484f47e-3bb1-48d0-ba64-e8330dcefe6e",
"name": "profile",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "profile",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "profile",
"jsonType.label": "String"
}
},
{
"id": "fcd00995-9693-4803-8f41-c84044be83ed",
"name": "website",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "website",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "website",
"jsonType.label": "String"
}
},
{
"id": "f09e7268-5284-449b-849b-cf8225523584",
"name": "full name",
"protocol": "openid-connect",
"protocolMapper": "oidc-full-name-mapper",
"consentRequired": false,
"config": {
"id.token.claim": "true",
"access.token.claim": "true",
"userinfo.token.claim": "true"
}
},
{
"id": "0317f4b3-3f7b-47ab-88d3-5d6f604d944d",
"name": "nickname",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "nickname",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "nickname",
"jsonType.label": "String"
}
},
{
"id": "db81244c-e739-461b-8822-52ceaa11bdf4",
"name": "updated at",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "updatedAt",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "updated_at",
"jsonType.label": "String"
}
},
{
"id": "c6a16bf9-9370-4dff-a718-be53131bb238",
"name": "gender",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "gender",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "gender",
"jsonType.label": "String"
}
},
{
"id": "32d76647-b542-484c-9062-edc34eb350e0",
"name": "birthdate",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "birthdate",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "birthdate",
"jsonType.label": "String"
}
},
{
"id": "ac6530db-6463-446b-99da-32d5298b5fa0",
"name": "zoneinfo",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "zoneinfo",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "zoneinfo",
"jsonType.label": "String"
}
},
{
"id": "ed10983b-8700-415e-933e-226ce3f397a6",
"name": "given name",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-property-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "firstName",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "given_name",
"jsonType.label": "String"
}
},
{
"id": "8205ccd0-1266-4060-b5df-3a6eb229d91e",
"name": "username",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-property-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "username",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "preferred_username",
"jsonType.label": "String"
}
}
]
},
{
"id": "79713daf-89ca-4ed4-ad97-a88b13ee9a18",
"name": "phone",
"description": "OpenID Connect built-in scope: phone",
"protocol": "openid-connect",
"attributes": {
"include.in.token.scope": "true",
"display.on.consent.screen": "true",
"consent.screen.text": "${phoneScopeConsentText}"
},
"protocolMappers": [
{
"id": "b5f4f5ed-1008-42ba-8b3b-7d8851a2a680",
"name": "phone number",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "phoneNumber",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "phone_number",
"jsonType.label": "String"
}
},
{
"id": "08a246f1-2b4c-4def-af5c-aefc31b4820d",
"name": "phone number verified",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-attribute-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "phoneNumberVerified",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "phone_number_verified",
"jsonType.label": "boolean"
}
}
]
},
{
"id": "0c72b80b-28d5-48d8-b593-c99030aab58d",
"name": "roles",
"description": "OpenID Connect scope for add user roles to the access token",
"protocol": "openid-connect",
"attributes": {
"include.in.token.scope": "false",
"display.on.consent.screen": "true",
"consent.screen.text": "${rolesScopeConsentText}"
},
"protocolMappers": [
{
"id": "bc7f015e-329f-4e99-be6b-72382f4310c7",
"name": "client roles",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-client-role-mapper",
"consentRequired": false,
"config": {
"user.attribute": "foo",
"access.token.claim": "true",
"claim.name": "resource_access.${client_id}.roles",
"jsonType.label": "String",
"multivalued": "true"
}
},
{
"id": "215f645f-ad0b-4523-9ece-f09f69ead5c4",
"name": "audience resolve",
"protocol": "openid-connect",
"protocolMapper": "oidc-audience-resolve-mapper",
"consentRequired": false,
"config": {}
},
{
"id": "4a10b958-d34d-413a-b349-1415d02cdcde",
"name": "realm roles",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-realm-role-mapper",
"consentRequired": false,
"config": {
"access.token.claim": "true",
"claim.name": "roles",
"userinfo.token.claim": "true",
"id.token.claim": "true",
"jsonType.label": "String",
"multivalued": "true"
}
}
]
},
{
"id": "5ce87358-3bca-4874-a6f0-6dccae6209a8",
"name": "web-origins",
"description": "OpenID Connect scope for add allowed web origins to the access token",
"protocol": "openid-connect",
"attributes": {
"include.in.token.scope": "false",
"display.on.consent.screen": "false",
"consent.screen.text": ""
},
"protocolMappers": [
{
"id": "bbd23c51-918d-4ea6-9ac0-db68b512fb0a",
"name": "allowed web origins",
"protocol": "openid-connect",
"protocolMapper": "oidc-allowed-origins-mapper",
"consentRequired": false,
"config": {}
}
]
},
{
"id": "86883395-e439-4cab-9d8d-31d71389969c",
"name": "acr",
"description": "OpenID Connect scope for add acr (authentication context class reference) to the token",
"protocol": "openid-connect",
"attributes": {
"include.in.token.scope": "false",
"display.on.consent.screen": "false"
},
"protocolMappers": [
{
"id": "b849b14b-7c9c-4b7b-9329-c56debefb47c",
"name": "acr loa level",
"protocol": "openid-connect",
"protocolMapper": "oidc-acr-mapper",
"consentRequired": false,
"config": {
"id.token.claim": "true",
"access.token.claim": "true",
"userinfo.token.claim": "true"
}
}
]
},
{
"id": "bdb3e320-76c8-4ad7-9d0f-a08efc060101",
"name": "microprofile-jwt",
"description": "Microprofile - JWT built-in scope",
"protocol": "openid-connect",
"attributes": {
"include.in.token.scope": "true",
"display.on.consent.screen": "false"
},
"protocolMappers": [
{
"id": "1d08316c-493b-42ab-afa3-66f621860661",
"name": "groups",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-realm-role-mapper",
"consentRequired": false,
"config": {
"multivalued": "true",
"userinfo.token.claim": "true",
"user.attribute": "foo",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "groups",
"jsonType.label": "String"
}
},
{
"id": "52061d2d-7a41-4f1d-ba1b-3c4a53e739e4",
"name": "upn",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-property-mapper",
"consentRequired": false,
"config": {
"userinfo.token.claim": "true",
"user.attribute": "username",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "upn",
"jsonType.label": "String"
}
}
]
}
],
"defaultDefaultClientScopes": ["role_list", "profile", "email", "roles", "web-origins", "acr"],
"defaultOptionalClientScopes": ["offline_access", "address", "phone", "microprofile-jwt"],
"browserSecurityHeaders": {
"contentSecurityPolicyReportOnly": "",
"xContentTypeOptions": "nosniff",
"xRobotsTag": "none",
"xFrameOptions": "SAMEORIGIN",
"contentSecurityPolicy": "frame-src 'self'; frame-ancestors 'self'; object-src 'none';",
"xXSSProtection": "1; mode=block",
"strictTransportSecurity": "max-age=31536000; includeSubDomains"
},
"smtpServer": {},
"eventsEnabled": false,
"eventsListeners": ["jboss-logging"],
"enabledEventTypes": [],
"adminEventsEnabled": false,
"adminEventsDetailsEnabled": false,
"identityProviders": [],
"identityProviderMappers": [],
"components": {
"org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy": [
{
"id": "6fc7d765-7da8-4985-ba0b-e83827b04bd3",
"name": "Allowed Client Scopes",
"providerId": "allowed-client-templates",
"subType": "anonymous",
"subComponents": {},
"config": {
"allow-default-scopes": ["true"]
}
},
{
"id": "4682fe74-f3a9-445a-a7ab-557fb532fe6b",
"name": "Consent Required",
"providerId": "consent-required",
"subType": "anonymous",
"subComponents": {},
"config": {}
},
{
"id": "5a9aef85-98a6-4e90-b30f-8aa715e1f5e6",
"name": "Allowed Protocol Mapper Types",
"providerId": "allowed-protocol-mappers",
"subType": "authenticated",
"subComponents": {},
"config": {
"allowed-protocol-mapper-types": [
"oidc-sha256-pairwise-sub-mapper",
"saml-user-property-mapper",
"oidc-full-name-mapper",
"oidc-usermodel-property-mapper",
"oidc-address-mapper",
"saml-user-attribute-mapper",
"oidc-usermodel-attribute-mapper",
"saml-role-list-mapper"
]
}
},
{
"id": "e3eadb04-8862-4567-869c-a76485268159",
"name": "Allowed Client Scopes",
"providerId": "allowed-client-templates",
"subType": "authenticated",
"subComponents": {},
"config": {
"allow-default-scopes": ["true"]
}
},
{
"id": "c46009e5-c8b5-4051-bf7f-7b1481a9aa86",
"name": "Max Clients Limit",
"providerId": "max-clients",
"subType": "anonymous",
"subComponents": {},
"config": {
"max-clients": ["200"]
}
},
{
"id": "c788e6bf-2f57-4a82-b32e-ac8d48a4f676",
"name": "Full Scope Disabled",
"providerId": "scope",
"subType": "anonymous",
"subComponents": {},
"config": {}
},
{
"id": "43edf979-28d2-46c8-9f93-48b3de185570",
"name": "Allowed Protocol Mapper Types",
"providerId": "allowed-protocol-mappers",
"subType": "anonymous",
"subComponents": {},
"config": {
"allowed-protocol-mapper-types": [
"saml-user-property-mapper",
"oidc-address-mapper",
"oidc-usermodel-property-mapper",
"oidc-sha256-pairwise-sub-mapper",
"oidc-usermodel-attribute-mapper",
"saml-role-list-mapper",
"saml-user-attribute-mapper",
"oidc-full-name-mapper"
]
}
}
],
"org.keycloak.keys.KeyProvider": [
{
"id": "0e3d0048-cb16-49c3-8a9a-05d83f0daeca",
"name": "rsa-generated",
"providerId": "rsa-generated",
"subComponents": {},
"config": {
"priority": ["100"]
}
},
{
"id": "f92ecf31-c3c7-4c3b-af20-839fc05bcf99",
"name": "hmac-generated",
"providerId": "hmac-generated",
"subComponents": {},
"config": {
"priority": ["100"],
"algorithm": ["HS256"]
}
},
{
"id": "992dcc80-dc41-4b00-bab8-6ec1c839f3a4",
"name": "aes-generated",
"providerId": "aes-generated",
"subComponents": {},
"config": {
"priority": ["100"]
}
}
]
},
"internationalizationEnabled": false,
"supportedLocales": [],
"authenticationFlows": [
{
"id": "8964f931-b866-4a05-ab1c-89331a566887",
"alias": "Account verification options",
"description": "Method with which to verity the existing account",
"providerId": "basic-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "idp-email-verification",
"authenticatorFlow": false,
"requirement": "ALTERNATIVE",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticatorFlow": true,
"requirement": "ALTERNATIVE",
"priority": 20,
"autheticatorFlow": true,
"flowAlias": "Verify Existing Account by Re-authentication",
"userSetupAllowed": false
}
]
},
{
"id": "404d2769-f3ba-4b5e-b43f-1bca919334f2",
"alias": "Authentication Options",
"description": "Authentication options.",
"providerId": "basic-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "basic-auth",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "basic-auth-otp",
"authenticatorFlow": false,
"requirement": "DISABLED",
"priority": 20,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "auth-spnego",
"authenticatorFlow": false,
"requirement": "DISABLED",
"priority": 30,
"autheticatorFlow": false,
"userSetupAllowed": false
}
]
},
{
"id": "123e5711-1ee5-4f7e-ac9c-64c644daaea9",
"alias": "Browser - Conditional OTP",
"description": "Flow to determine if the OTP is required for the authentication",
"providerId": "basic-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "conditional-user-configured",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "auth-otp-form",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 20,
"autheticatorFlow": false,
"userSetupAllowed": false
}
]
},
{
"id": "be73b7f5-9a66-487c-b7dd-80e0f7ac0c7c",
"alias": "Direct Grant - Conditional OTP",
"description": "Flow to determine if the OTP is required for the authentication",
"providerId": "basic-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "conditional-user-configured",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "direct-grant-validate-otp",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 20,
"autheticatorFlow": false,
"userSetupAllowed": false
}
]
},
{
"id": "597ca917-91fc-4898-a279-cd592af286e3",
"alias": "First broker login - Conditional OTP",
"description": "Flow to determine if the OTP is required for the authentication",
"providerId": "basic-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "conditional-user-configured",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "auth-otp-form",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 20,
"autheticatorFlow": false,
"userSetupAllowed": false
}
]
},
{
"id": "3daadb6b-4d63-4be1-a89e-ec8e41e72afa",
"alias": "Handle Existing Account",
"description": "Handle what to do if there is existing account with same email/username like authenticated identity provider",
"providerId": "basic-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "idp-confirm-link",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticatorFlow": true,
"requirement": "REQUIRED",
"priority": 20,
"autheticatorFlow": true,
"flowAlias": "Account verification options",
"userSetupAllowed": false
}
]
},
{
"id": "5942598c-d7e9-4941-b13e-4a8a75e2c2a3",
"alias": "Reset - Conditional OTP",
"description": "Flow to determine if the OTP should be reset or not. Set to REQUIRED to force.",
"providerId": "basic-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "conditional-user-configured",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "reset-otp",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 20,
"autheticatorFlow": false,
"userSetupAllowed": false
}
]
},
{
"id": "6e4b336e-eb5f-423c-8d32-4ab94d1122e6",
"alias": "User creation or linking",
"description": "Flow for the existing/non-existing user alternatives",
"providerId": "basic-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticatorConfig": "create unique user config",
"authenticator": "idp-create-user-if-unique",
"authenticatorFlow": false,
"requirement": "ALTERNATIVE",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticatorFlow": true,
"requirement": "ALTERNATIVE",
"priority": 20,
"autheticatorFlow": true,
"flowAlias": "Handle Existing Account",
"userSetupAllowed": false
}
]
},
{
"id": "35ac1997-b6af-44ff-ab27-c34f9be32e56",
"alias": "Verify Existing Account by Re-authentication",
"description": "Reauthentication of existing account",
"providerId": "basic-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "idp-username-password-form",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticatorFlow": true,
"requirement": "CONDITIONAL",
"priority": 20,
"autheticatorFlow": true,
"flowAlias": "First broker login - Conditional OTP",
"userSetupAllowed": false
}
]
},
{
"id": "a3473070-fe69-4de1-a0b2-dd54b8a769d5",
"alias": "browser",
"description": "browser based authentication",
"providerId": "basic-flow",
"topLevel": true,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "auth-cookie",
"authenticatorFlow": false,
"requirement": "ALTERNATIVE",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "auth-spnego",
"authenticatorFlow": false,
"requirement": "DISABLED",
"priority": 20,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "identity-provider-redirector",
"authenticatorFlow": false,
"requirement": "ALTERNATIVE",
"priority": 25,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticatorFlow": true,
"requirement": "ALTERNATIVE",
"priority": 30,
"autheticatorFlow": true,
"flowAlias": "forms",
"userSetupAllowed": false
}
]
},
{
"id": "cc714857-b114-4df6-9030-b464bbb3964d",
"alias": "clients",
"description": "Base authentication for clients",
"providerId": "client-flow",
"topLevel": true,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "client-secret",
"authenticatorFlow": false,
"requirement": "ALTERNATIVE",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "client-jwt",
"authenticatorFlow": false,
"requirement": "ALTERNATIVE",
"priority": 20,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "client-secret-jwt",
"authenticatorFlow": false,
"requirement": "ALTERNATIVE",
"priority": 30,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "client-x509",
"authenticatorFlow": false,
"requirement": "ALTERNATIVE",
"priority": 40,
"autheticatorFlow": false,
"userSetupAllowed": false
}
]
},
{
"id": "0ebe891c-1a72-4842-bf29-a9abe9c2a4d2",
"alias": "direct grant",
"description": "OpenID Connect Resource Owner Grant",
"providerId": "basic-flow",
"topLevel": true,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "direct-grant-validate-username",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "direct-grant-validate-password",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 20,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticatorFlow": true,
"requirement": "CONDITIONAL",
"priority": 30,
"autheticatorFlow": true,
"flowAlias": "Direct Grant - Conditional OTP",
"userSetupAllowed": false
}
]
},
{
"id": "d97d5579-b3d4-49c4-a60e-0e1e6b1c9d79",
"alias": "docker auth",
"description": "Used by Docker clients to authenticate against the IDP",
"providerId": "basic-flow",
"topLevel": true,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "docker-http-basic-authenticator",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
}
]
},
{
"id": "009f7c28-0f41-4237-9911-9091c3d751b7",
"alias": "first broker login",
"description": "Actions taken after first broker login with identity provider account, which is not yet linked to any Keycloak account",
"providerId": "basic-flow",
"topLevel": true,
"builtIn": true,
"authenticationExecutions": [
{
"authenticatorConfig": "review profile config",
"authenticator": "idp-review-profile",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticatorFlow": true,
"requirement": "REQUIRED",
"priority": 20,
"autheticatorFlow": true,
"flowAlias": "User creation or linking",
"userSetupAllowed": false
}
]
},
{
"id": "f9911022-b3cf-4d96-9a96-51bc53c437eb",
"alias": "forms",
"description": "Username, password, otp and other auth forms.",
"providerId": "basic-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "auth-username-password-form",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticatorFlow": true,
"requirement": "CONDITIONAL",
"priority": 20,
"autheticatorFlow": true,
"flowAlias": "Browser - Conditional OTP",
"userSetupAllowed": false
}
]
},
{
"id": "8f5fab27-9b06-444d-931b-d03be9e6d4af",
"alias": "http challenge",
"description": "An authentication flow based on challenge-response HTTP Authentication Schemes",
"providerId": "basic-flow",
"topLevel": true,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "no-cookie-redirect",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticatorFlow": true,
"requirement": "REQUIRED",
"priority": 20,
"autheticatorFlow": true,
"flowAlias": "Authentication Options",
"userSetupAllowed": false
}
]
},
{
"id": "c53eb19d-49e9-4252-8a10-4d5c6a12e61b",
"alias": "registration",
"description": "registration flow",
"providerId": "basic-flow",
"topLevel": true,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "registration-page-form",
"authenticatorFlow": true,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": true,
"flowAlias": "registration form",
"userSetupAllowed": false
}
]
},
{
"id": "3b4f48d3-1706-4630-80e0-e0542780a1f7",
"alias": "registration form",
"description": "registration form",
"providerId": "form-flow",
"topLevel": false,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "registration-user-creation",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 20,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "registration-profile-action",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 40,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "registration-password-action",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 50,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "registration-recaptcha-action",
"authenticatorFlow": false,
"requirement": "DISABLED",
"priority": 60,
"autheticatorFlow": false,
"userSetupAllowed": false
}
]
},
{
"id": "5520aa89-cd76-438a-abae-7ccd3a2d7615",
"alias": "reset credentials",
"description": "Reset credentials for a user if they forgot their password or something",
"providerId": "basic-flow",
"topLevel": true,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "reset-credentials-choose-user",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "reset-credential-email",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 20,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticator": "reset-password",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 30,
"autheticatorFlow": false,
"userSetupAllowed": false
},
{
"authenticatorFlow": true,
"requirement": "CONDITIONAL",
"priority": 40,
"autheticatorFlow": true,
"flowAlias": "Reset - Conditional OTP",
"userSetupAllowed": false
}
]
},
{
"id": "cce548d6-9bef-4449-88ea-99b949488fe7",
"alias": "saml ecp",
"description": "SAML ECP Profile Authentication Flow",
"providerId": "basic-flow",
"topLevel": true,
"builtIn": true,
"authenticationExecutions": [
{
"authenticator": "http-basic-authenticator",
"authenticatorFlow": false,
"requirement": "REQUIRED",
"priority": 10,
"autheticatorFlow": false,
"userSetupAllowed": false
}
]
}
],
"authenticatorConfig": [
{
"id": "0848606c-7510-4b09-ba0e-4dc2ef3d63f8",
"alias": "create unique user config",
"config": {
"require.password.update.after.registration": "false"
}
},
{
"id": "91a8dee7-c679-4202-866e-234eb4164cfd",
"alias": "review profile config",
"config": {
"update.profile.on.first.login": "missing"
}
}
],
"requiredActions": [
{
"alias": "CONFIGURE_TOTP",
"name": "Configure OTP",
"providerId": "CONFIGURE_TOTP",
"enabled": true,
"defaultAction": false,
"priority": 10,
"config": {}
},
{
"alias": "terms_and_conditions",
"name": "Terms and Conditions",
"providerId": "terms_and_conditions",
"enabled": false,
"defaultAction": false,
"priority": 20,
"config": {}
},
{
"alias": "UPDATE_PASSWORD",
"name": "Update Password",
"providerId": "UPDATE_PASSWORD",
"enabled": true,
"defaultAction": false,
"priority": 30,
"config": {}
},
{
"alias": "UPDATE_PROFILE",
"name": "Update Profile",
"providerId": "UPDATE_PROFILE",
"enabled": true,
"defaultAction": false,
"priority": 40,
"config": {}
},
{
"alias": "VERIFY_EMAIL",
"name": "Verify Email",
"providerId": "VERIFY_EMAIL",
"enabled": true,
"defaultAction": false,
"priority": 50,
"config": {}
},
{
"alias": "delete_account",
"name": "Delete Account",
"providerId": "delete_account",
"enabled": false,
"defaultAction": false,
"priority": 60,
"config": {}
},
{
"alias": "update_user_locale",
"name": "Update User Locale",
"providerId": "update_user_locale",
"enabled": true,
"defaultAction": false,
"priority": 1000,
"config": {}
}
],
"browserFlow": "browser",
"registrationFlow": "registration",
"directGrantFlow": "direct grant",
"resetCredentialsFlow": "reset credentials",
"clientAuthenticationFlow": "clients",
"dockerAuthenticationFlow": "docker auth",
"attributes": {
"cibaBackchannelTokenDeliveryMode": "poll",
"cibaExpiresIn": "120",
"cibaAuthRequestedUserHint": "login_hint",
"oauth2DeviceCodeLifespan": "600",
"clientOfflineSessionMaxLifespan": "0",
"oauth2DevicePollingInterval": "5",
"clientSessionIdleTimeout": "0",
"parRequestUriLifespan": "60",
"clientSessionMaxLifespan": "0",
"clientOfflineSessionIdleTimeout": "0",
"cibaInterval": "5",
"realmReusableOtpCode": "false"
},
"keycloakVersion": "21.1.0",
"userManagedAccessAllowed": false,
"clientProfiles": {
"profiles": []
},
"clientPolicies": {
"policies": []
}
}
| owncloud/web/tests/drone/ocis_keycloak/ocis-ci-realm.dist.json/0 | {
"file_path": "owncloud/web/tests/drone/ocis_keycloak/ocis-ci-realm.dist.json",
"repo_id": "owncloud",
"token_count": 35198
} | 865 |
Feature: url stability for mobile and desktop client
As a user
I want to work on different docs, sheets, slides etc.., using online office suites like Collabora or OnlyOffice
To make sure that the file can be opened from the mobile and desktop client
# To run this feature we need to run the external app-provider service along with wopi, OnlyOffice, Collabora services
# This is a minimal test for the integration of ocis with different online office suites like Collabora and OnlyOffice
# Check that the file can be opened in collabora or onlyoffice using the url. https://github.com/owncloud/web/issues/9897
Scenario: open office suite files with Collabora and onlyOffice
Given "Admin" creates following users using API
| id |
| Alice |
And "Alice" logs in
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| OpenDocument.odt | OpenDocument Content |
And "Alice" creates the following resources
| resource | type | content |
| MicrosoftWord.docx | Microsoft Word | Microsoft Word Content |
And "Alice" opens the "files" app
# desktop feature
When "Alice" opens the file "OpenDocument.odt" of space "personal" in Collabora through the URL for desktop client
Then "Alice" should see the content "OpenDocument Content" in editor "Collabora"
When "Alice" opens the file "MicrosoftWord.docx" of space "personal" in OnlyOffice through the URL for desktop client
Then "Alice" should see the content "Microsoft Word Content" in editor "OnlyOffice"
# mobile feature
When "Alice" opens the file "OpenDocument.odt" of space "personal" in Collabora through the URL for mobile client
Then "Alice" should see the content "OpenDocument Content" in editor "Collabora"
When "Alice" opens the file "MicrosoftWord.docx" of space "personal" in OnlyOffice through the URL for mobile client
Then "Alice" should see the content "Microsoft Word Content" in editor "OnlyOffice"
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/app-provider/urlJourneys.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/app-provider/urlJourneys.feature",
"repo_id": "owncloud",
"token_count": 627
} | 866 |
Feature: language settings
As a user
I want to be able to use the system with my preferred language
Background:
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
Scenario: system language change
And "Brian" logs in
And "Brian" creates the following folder in personal space using API
| name |
| check_message |
And "Brian" shares the following resource using API
| resource | recipient | type | role |
| check_message | Alice | user | Can edit |
And "Brian" logs out
And "Alice" logs in
And "Alice" opens the user menu
And "Alice" changes the language to "Deutsch - German"
Then "Alice" should see the following account page title "Konto"
When "Alice" logs out
And "Alice" logs in
Then "Alice" should see the following notifications
| message |
| Brian Murphy hat check_message mit Ihnen geteilt |
And "Alice" logs out
Scenario: anonymous user language change
When "Alice" logs in
And "Alice" creates the following folder in personal space using API
| name |
| folderPublic |
And "Alice" uploads the following local file into personal space using API
| localFile | to |
| filesForUpload/lorem.txt | lorem.txt |
And "Alice" opens the "files" app
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | password |
| folderPublic | %public% |
And "Alice" logs out
When "Anonymous" opens the public link "Link"
And "Anonymous" unlocks the public link with password "%public%"
And "Anonymous" opens the user menu
And "Anonymous" changes the language to "Deutsch - German"
Then "Anonymous" should see the following account page title "Konto"
| owncloud/web/tests/e2e/cucumber/features/smoke/languageChange.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/languageChange.feature",
"repo_id": "owncloud",
"token_count": 674
} | 867 |
Feature: spaces.personal
Scenario: unstructured collection of testable space interactions,
once all needed features are there, split this into independent tests.
contains following features:
- ✓ assign role to user
- ✓ create space & internal alias to differentiate multiple spaces with the same name
- ✓ open space
- ✓ rename space
- ✓ change/set space subtitle
- ✓ change/set space description
- ✓ change/set space quota
- ✓ resources & existing resource actions
- ✓ change/set space image
- ✗ trash bin
- ✗ share
- ✗ link
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Alice" logs in
When "Alice" opens the "files" app
And "Alice" navigates to the projects space page
And "Alice" creates the following project spaces
| name | id |
| team | team.1 |
| team2 | team.2 |
# team.1
And "Alice" navigates to the project space "team.1"
And "Alice" updates the space "team.1" name to "developer team"
And "Alice" updates the space "team.1" subtitle to "developer team - subtitle"
And "Alice" updates the space "team.1" description to "developer team - description"
And "Alice" updates the space "team.1" quota to "50"
And "Alice" updates the space "team.1" image to "testavatar.png"
# shared examples
And "Alice" creates the following resources
| resource | type |
| folderPublic | folder |
| folder_to_shared | folder |
And "Alice" uploads the following resources
| resource | to |
| lorem.txt | folderPublic |
| lorem.txt | folder_to_shared |
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | role | password |
| folderPublic | Secret File Drop | %public% |
And "Alice" renames the most recently created public link of resource "folderPublic" to "team.1"
And "Alice" sets the expiration date of the public link named "team.1" of resource "folderPublic" to "+5 days"
# borrowed from share.feature
When "Alice" shares the following resource using the sidebar panel
| resource | recipient | type | role | resourceType |
| folder_to_shared | Brian | user | Can edit | folder |
# team.2
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "team.2"
And "Alice" updates the space "team.2" name to "management team"
And "Alice" updates the space "team.2" subtitle to "management team - subtitle"
And "Alice" updates the space "team.2" description to "management team - description"
And "Alice" updates the space "team.2" quota to "500"
And "Alice" updates the space "team.2" image to "sampleGif.gif"
And "Alice" creates the following resources
| resource | type |
| folderPublic | folder |
And "Alice" uploads the following resources
| resource | to |
| lorem.txt | folderPublic |
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | password |
| folderPublic | %public% |
And "Alice" renames the most recently created public link of resource "folderPublic" to "team.2"
And "Alice" edits the public link named "team.2" of resource "folderPublic" changing role to "Secret File Drop"
And "Alice" sets the expiration date of the public link named "team.2" of resource "folderPublic" to "+5 days"
And "Alice" changes the password of the public link named "team.2" of resource "folderPublic" to "new-strongPass1"
# borrowed from link.feature, all existing resource actions can be reused
When "Anonymous" opens the public link "team.1"
And "Anonymous" unlocks the public link with password "%public%"
And "Anonymous" drop uploads following resources
| resource |
| textfile.txt |
# borrowed from share.feature
And "Brian" logs in
And "Brian" opens the "files" app
And "Brian" navigates to the shared with me page
And "Brian" renames the following resource
| resource | as |
| folder_to_shared/lorem.txt | lorem_new.txt |
And "Brian" uploads the following resource
| resource | to |
| simple.pdf | folder_to_shared |
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "team.1"
And "Alice" updates the space "team.1" image to "testavatar.jpeg"
And "Alice" uploads the following resource
| resource | to | option |
| PARENT/simple.pdf | folder_to_shared | replace |
And "Brian" should not see the version of the file
| resource | to |
| simple.pdf | folder_to_shared |
When "Alice" deletes the following resources using the sidebar panel
| resource | from |
| lorem_new.txt | folder_to_shared |
| folder_to_shared | |
And "Brian" logs out
# alice is done
When "Alice" logs out
# borrowed from link.feature, all existing resource actions can be reused
When "Anonymous" opens the public link "team.2"
And "Anonymous" unlocks the public link with password "new-strongPass1"
And "Anonymous" drop uploads following resources
| resource |
| textfile.txt |
Scenario: members of the space can control the versions of the files
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Alice" logs in
And "Alice" creates the following project space using API
| name | id |
| team | team.1 |
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "team.1"
And "Alice" creates the following resources
| resource | type | content |
| parent/textfile.txt | txtFile | some random content |
When "Alice" uploads the following resources
| resource | to | option |
| textfile.txt | parent | replace |
And "Alice" adds following users to the project space
| user | role | kind |
| Carol | Can view | user |
| Brian | Can edit | user |
And "Alice" logs out
When "Carol" logs in
And "Carol" opens the "files" app
And "Carol" navigates to the projects space page
And "Carol" navigates to the project space "team.1"
And "Carol" should not see the version of the file
| resource | to |
| textfile.txt | parent |
And "Carol" logs out
When "Brian" logs in
And "Brian" opens the "files" app
And "Brian" navigates to the projects space page
And "Brian" navigates to the project space "team.1"
And "Brian" downloads old version of the following resource
| resource | to |
| textfile.txt | parent |
And "Brian" restores following resources
| resource | to | version | openDetailsPanel |
| textfile.txt | parent | 1 | true |
And "Brian" logs out
| owncloud/web/tests/e2e/cucumber/features/spaces/project.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/spaces/project.feature",
"repo_id": "owncloud",
"token_count": 2703
} | 868 |
import { DataTable, When, Then } from '@cucumber/cucumber'
import { expect } from '@playwright/test'
import { World } from '../../environment'
import { objects } from '../../../support'
import { Space } from '../../../support/types'
When(
'{string} navigates to the personal space page',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const pageObject = new objects.applicationFiles.page.spaces.Personal({ page })
await pageObject.navigate()
}
)
When(
'{string} navigates to the projects space page',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const pageObject = new objects.applicationFiles.page.spaces.Projects({ page })
await pageObject.navigate()
}
)
When(
'{string} creates the following project spaces',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
for (const space of stepTable.hashes()) {
await spacesObject.create({ key: space.id || space.name, space: space as unknown as Space })
}
}
)
When(
'{string} navigates to the project space {string}',
async function (this: World, stepUser: string, key: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
await spacesObject.open({ key })
}
)
When(
/^"([^"]*)" (?:changes|updates) the space "([^"]*)" (name|subtitle|description|quota|image) to "([^"]*)"$/,
async function (
this: World,
stepUser: string,
key: string,
attribute: string,
value: string
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
switch (attribute) {
case 'name':
await spacesObject.changeName({ key, value })
break
case 'subtitle':
await spacesObject.changeSubtitle({ key, value })
break
case 'description':
await spacesObject.changeDescription({ value })
break
case 'quota':
await spacesObject.changeQuota({ key, value })
break
case 'image':
await spacesObject.changeSpaceImage({
key,
resource: this.filesEnvironment.getFile({ name: value })
})
break
default:
throw new Error(`${attribute} not implemented`)
}
}
)
When(
'{string} adds following user(s) to the project space',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
for (const { user, role, kind } of stepTable.hashes()) {
const collaborator =
kind === 'user'
? this.usersEnvironment.getUser({ key: user })
: this.usersEnvironment.getGroup({ key: user })
const collaboratorWithRole = {
collaborator,
role
}
await spacesObject.addMembers({ users: [collaboratorWithRole] })
}
}
)
When(
'{string} removes access to following users from the project space',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
for (const { user, role } of stepTable.hashes()) {
const member = {
collaborator: this.usersEnvironment.getUser({ key: user }),
role
}
await spacesObject.removeAccessToMember({ users: [member] })
}
}
)
Then(
'{string} should see folder {string} but should not be able to edit',
async function (this: World, stepUser: string, resource: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
const userCanEdit = await spacesObject.canUserEditResource({ resource })
expect(userCanEdit).toBe(false)
}
)
Then(
'{string} should see file {string} but should not be able to edit',
async function (this: World, stepUser: string, resource: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
const userCanEdit = await spacesObject.canUserEditResource({ resource })
expect(userCanEdit).toBe(false)
}
)
Then(
'{string} should not be able to see space {string}',
async function (this: World, stepUser: string, space: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
await spacesObject.expectThatSpacesIdNotExist(space)
}
)
When(
'{string} reloads the spaces page',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
await spacesObject.reloadPage()
}
)
When(
/^"([^"]*)" navigates to the trashbin(| of the project space "([^"]*)")$/,
async function (this: World, stepUser: string, key: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const pageObject = new objects.applicationFiles.page.trashbin.Overview({ page })
await pageObject.navigate()
if (key) {
const trashbinObject = new objects.applicationFiles.Trashbin({ page })
await trashbinObject.open(key)
}
}
)
When(
'{string} changes the roles of the following users in the project space',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
for (const { user, role } of stepTable.hashes()) {
const member = {
collaborator: this.usersEnvironment.getUser({ key: user }),
role
}
await spacesObject.changeRoles({ users: [member] })
}
}
)
When(
'{string} as project manager removes their own access to the project space',
async function (this: World, stepUser: any): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
await spacesObject.removeAccessToMember({
users: [
{
collaborator: this.usersEnvironment.getUser({ key: stepUser })
}
],
removeOwnSpaceAccess: true
})
}
)
When(
'{string} sets the expiration date of the member {string} of the project space to {string}',
async function (
this: World,
stepUser: string,
memberName: string,
expirationDate: string
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
const member = { collaborator: this.usersEnvironment.getUser({ key: memberName }) }
await spacesObject.addExpirationDate({ member, expirationDate })
}
)
When(
'{string} removes the expiration date of the member {string} of the project space',
async function (this: World, stepUser: string, memberName: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
const member = { collaborator: this.usersEnvironment.getUser({ key: memberName }) }
await spacesObject.removeExpirationDate({ member })
}
)
When(
/^"([^"]*)" downloads the space (?:"[^"]*")$/,
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spacesObject = new objects.applicationFiles.Spaces({ page })
const downloadedResource = await spacesObject.downloadSpace()
expect(downloadedResource).toContain('download.tar')
}
)
| owncloud/web/tests/e2e/cucumber/steps/ui/spaces.ts/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/steps/ui/spaces.ts",
"repo_id": "owncloud",
"token_count": 2800
} | 869 |
import join from 'join-path'
import fetch, { BodyInit, Response } from 'node-fetch'
import { User } from '../types'
import { config } from '../../config'
import { TokenEnvironmentFactory } from '../environment'
export const request = async ({
method,
path,
body,
user,
header = {},
isKeycloakRequest = false
}: {
method: 'POST' | 'DELETE' | 'PUT' | 'GET' | 'MKCOL' | 'PROPFIND' | 'PATCH'
path: string
body?: BodyInit
user?: User
header?: object
isKeycloakRequest?: boolean
}): Promise<Response> => {
const tokenEnvironment = TokenEnvironmentFactory(isKeycloakRequest ? 'keycloak' : null)
const authHeader = {
Authorization: 'Basic ' + Buffer.from(user.id + ':' + user.password).toString('base64')
}
if (!config.basicAuth) {
authHeader.Authorization = 'Bearer ' + tokenEnvironment.getToken({ user }).accessToken
}
const basicHeader = {
'OCS-APIREQUEST': true as any,
...(user.id && authHeader),
...header
}
const baseUrl = isKeycloakRequest ? config.keycloakUrl : config.backendUrl
return await fetch(join(baseUrl, path), {
method,
body,
headers: basicHeader
})
}
export const checkResponseStatus = (response: Response, message = ''): void => {
// response.status >= 200 && response.status < 300
if (!response.ok) {
throw Error(`HTTP Request Failed: ${message}, Status: ${response.status}`)
}
}
| owncloud/web/tests/e2e/support/api/http.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/http.ts",
"repo_id": "owncloud",
"token_count": 462
} | 870 |
export { ActorsEnvironment } from './actor'
export { FilesEnvironment } from './file'
export { LinksEnvironment } from './link'
export { SpacesEnvironment } from './space'
export { UsersEnvironment } from './userManagement'
export { TokenEnvironmentFactory } from './token'
export type { TokenEnvironmentType, TokenProviderType } from './token'
| owncloud/web/tests/e2e/support/environment/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/environment/index.ts",
"repo_id": "owncloud",
"token_count": 86
} | 871 |
import { Page } from '@playwright/test'
export class Spaces {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
async navigate(): Promise<void> {
await this.#page.locator('//a[@data-nav-name="admin-settings-spaces"]').click()
await this.#page.locator('#app-loading-spinner').waitFor({ state: 'detached' })
}
}
| owncloud/web/tests/e2e/support/objects/app-admin-settings/page/spaces.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/page/spaces.ts",
"repo_id": "owncloud",
"token_count": 127
} | 872 |
import { Download, Locator, Page, expect } from '@playwright/test'
import util from 'util'
import path from 'path'
import { resourceExists, waitForResources } from './utils'
import { editor, sidebar } from '../utils'
import { File, Space } from '../../../types'
import { dragDropFiles } from '../../../utils/dragDrop'
import { LinksEnvironment } from '../../../environment'
import { config } from '../../../../config'
import { buildXpathLiteral } from '../../../utils/locator'
const downloadFileButtonSingleShareView = '.oc-files-actions-download-file-trigger'
const downloadFolderButtonSingleShareView = '.oc-files-actions-download-archive-trigger'
const filesView = '#files-view'
const downloadFileButtonSideBar =
'#oc-files-actions-sidebar .oc-files-actions-download-file-trigger'
const downloadFolderButtonSideBar =
'#oc-files-actions-sidebar .oc-files-actions-download-archive-trigger'
const downloadButtonBatchAction = '.oc-files-actions-download-archive-trigger'
const downloadPreviewButton = '#preview-download'
const deleteButtonBatchAction = '.oc-files-actions-delete-trigger'
const createSpaceFromResourceAction = '.oc-files-actions-create-space-from-resource-trigger'
const checkBox = `//*[@data-test-resource-name="%s"]//ancestor::tr//input`
const checkBoxForTrashbin = `//*[@data-test-resource-path="%s"]//ancestor::tr//input`
const filesSelector = '//*[@data-test-resource-name="%s"]'
export const fileRow =
'//ancestor::*[(contains(@class, "oc-tile-card") or contains(@class, "oc-tbody-tr"))]'
export const resourceNameSelector =
':is(#files-files-table, .oc-tiles-item, #files-shared-with-me-accepted-section, .files-table) [data-test-resource-name="%s"]'
// following breadcrumb selectors is passed to buildXpathLiteral function as the content to be inserted might contain quotes
const breadcrumbResourceNameSelector =
'//span[contains(@class, "oc-breadcrumb-item-text") and text()=%s]'
const breadcrumbLastResourceNameSelector = '.oc-breadcrumb-item-text-last'
const breadcrumbResourceSelector = '//*[@id="files-breadcrumb"]//span[text()=%s]//ancestor::li'
const addNewResourceButton = `#new-file-menu-btn`
const createNewFolderButton = '#new-folder-btn'
const createNewTxtFileButton = '.new-file-btn-txt'
const createNewMdFileButton = '.new-file-btn-md'
const createNewDrawioFileButton = '.new-file-btn-drawio'
const createNewOfficeDocumentFileBUtton = '//ul[@id="create-list"]//span[text()="%s"]'
const createNewShortcutButton = '#new-shortcut-btn'
const shortcutResorceInput = '#create-shortcut-modal-url-input'
const saveTextFileInEditorButton = '#app-save-action:visible'
const textEditor = '#text-editor #text-editor-container'
const textEditorPlainTextInput = '#text-editor #text-editor-container .ww-mode .ProseMirror'
const textEditorMarkdownInput = '#text-editor #text-editor-container .md-mode .ProseMirror'
const resourceNameInput = '.oc-modal input'
const resourceUploadButton = '#upload-menu-btn'
const fileUploadInput = '#files-file-upload-input'
const uploadInfoCloseButton = '#close-upload-info-btn'
const uploadErrorCloseButton = '.oc-notification-message-danger button[aria-label="Close"]'
const filesBatchAction = '.files-app-bar-actions .oc-files-actions-%s-trigger'
const pasteButton = '.paste-files-btn'
const breadcrumbRoot = '//nav[contains(@class, "oc-breadcrumb")]/ol/li[1]'
const fileRenameInput = '.oc-text-input'
const deleteButtonSidebar = '#oc-files-actions-sidebar .oc-files-actions-delete-trigger'
const actionConfirmationButton =
'//button[contains(@class,"oc-modal-body-actions-confirm") and text()="%s"]'
const actionSkipButton = '.oc-modal-body-actions-cancel'
const actionSecondaryConfirmationButton = '.oc-modal-body-actions-secondary'
const versionRevertButton = '//*[@data-testid="file-versions-revert-button"]'
const sideBarActionButton =
'//div[contains(@class, "files-side-bar")]//*[contains(@data-testid, "action-handler")]/span[text()="%s"]'
const notificationMessageDialog = '.oc-notification-message-title'
const notificationMessage = '.oc-notification-message'
const permanentDeleteButton = '.oc-files-actions-delete-permanent-trigger'
const restoreResourceButton = '.oc-files-actions-restore-trigger'
const globalSearchInput = '.oc-search-input'
const globalSearchBarFilter = '.oc-search-bar-filter'
const globalSearchDirFilterDropdown =
'//div[@id="files-global-search"]//button[contains(@id, "oc-filter")]'
const globalSearchBarFilterAllFiles = '//*[@data-test-id="all-files"]'
const globalSearchBarFilterCurrentFolder = '//*[@data-test-id="current-folder"]'
const searchList =
'//div[@id="files-global-search-options"]//li[contains(@class,"preview")]//span[@class="oc-resource-name"]'
const globalSearchOptions = '#files-global-search-options'
const loadingSpinner = '#files-global-search-options .loading'
const filesViewOptionButton = '#files-view-options-btn'
const hiddenFilesToggleButton = '//*[@data-testid="files-switch-hidden-files"]//button'
const previewImage = '//main[@id="preview"]//div[contains(@class,"stage_media")]//img'
const drawioSaveButton = '.geBigButton >> text=Save'
const drawioIframe = '#drawio-editor'
const externalEditorIframe = '[name="app-iframe"]'
const tagTableCell =
'//*[@data-test-resource-name="%s"]/ancestor::tr//td[contains(@class, "oc-table-data-cell-tags")]'
const tagInFilesTable = '//*[contains(@class, "oc-tag")]//span[text()="%s"]//ancestor::a'
const tagInDetailsPanel = '//*[@data-testid="tags"]/td//span[text()="%s"]'
const tagInInputForm =
'//span[contains(@class, "tags-select-tag")]//span[text()="%s"]//ancestor::span//button[contains(@class, "vs__deselect")]'
const tagFormInput = '//*[@data-testid="tags"]//input'
const resourcesAsTiles = '#files-view .oc-tiles'
const fileVersionSidebar = '#oc-file-versions-sidebar'
const noLinkMessage = '#web .oc-link-resolve-error-message'
const listItemPageSelector = '//*[contains(@class,"oc-pagination-list-item-page") and text()="%s"]'
const itemsPerPageDropDownOptionSelector =
'//li[contains(@class,"vs__dropdown-option") and text()="%s"]'
const footerTextSelector = '//*[@data-testid="files-list-footer-info"]'
const filesTableRowSelector = 'tbody tr'
const itemsPerPageDropDownSelector = '.vs__actions'
const filesPaginationNavSelector = '.files-pagination'
const uploadInfoSuccessLabelSelector = '.upload-info-label.upload-info-success'
const uploadInfoTitle = '.upload-info-title'
const uploadInfoLabelSelector = '.upload-info-label'
const pauseResumeUploadButton = '#pause-upload-info-btn'
const cancelUploadButton = '#cancel-upload-info-btn'
const uploadPauseTooltip = '//div[text()="Pause upload"]'
const uploadResumeTooltip = '//div[text()="Resume upload"]'
const collaboraEditorSaveSelector = '.notebookbar-shortcuts-bar #save'
const onlyOfficeInnerFrameSelector = '[name="frameEditor"]'
const onlyOfficeSaveButtonSelector = '#slot-btn-dt-save > button'
const collaboraDocTextAreaSelector = '#clipboard-area'
const onlyofficeDocTextAreaSelector = '#area_id'
const collaboraWelcomeModalIframe = '.iframe-welcome-modal'
const onlyOfficeCanvasEditorSelector = '#id_viewer_overlay'
const onlyOfficeCanvasCursorSelector = '#id_target_cursor'
const collaboraCanvasEditorSelector = '.leaflet-layer'
const filesContextMenuAction = 'div[id^="context-menu-drop"] button.oc-files-actions-%s-trigger'
const highlightedFileRowSelector = '#files-space-table tr.oc-table-highlighted'
const emptyTrashbinButtonSelector = '.oc-files-actions-empty-trash-bin-trigger'
const resourceLockIcon =
'//*[@data-test-resource-name="%s"]/ancestor::tr//td//span[@data-test-indicator-type="resource-locked"]'
const sharesNavigationButtonSelector = '.oc-sidebar-nav [data-nav-name="files-shares"]'
const keepBothButton = '.oc-modal-body-actions-confirm'
export const clickResource = async ({
page,
path
}: {
page: Page
path: string
}): Promise<void> => {
const paths = path.split('/')
for (const name of paths) {
// if resource name consists of single or double quotes, add an escape character
const folder = name.replace(/'/g, "\\'").replace(/"/g, '\\"')
const resource = page.locator(util.format(resourceNameSelector, folder))
await Promise.all([
page.waitForResponse((resp) => resp.request().method() === 'PROPFIND'),
resource.click()
])
}
}
export const clickResourceFromBreadcrumb = async ({ page, resource }): Promise<void> => {
const folder = buildXpathLiteral(resource)
const itemId = await page
.locator(util.format(breadcrumbResourceSelector, folder))
.getAttribute('data-item-id')
await Promise.all([
page.waitForResponse(
(resp) =>
(resp.status() === 207 &&
resp.request().method() === 'PROPFIND' &&
resp.url().endsWith(encodeURIComponent(resource))) ||
resp.url().endsWith(itemId) ||
resp.url().endsWith(encodeURIComponent(itemId))
),
page.locator(util.format(breadcrumbResourceNameSelector, folder)).click()
])
await expect(page.locator(breadcrumbLastResourceNameSelector)).toHaveText(resource)
}
/**/
export type createResourceTypes =
| 'folder'
| 'txtFile'
| 'mdFile'
| 'drawioFile'
| 'OpenDocument'
| 'Microsoft Word'
export interface createResourceArgs {
page: Page
name: string
type: createResourceTypes
content?: string
}
export const createSpaceFromFolder = async ({
page,
folderName,
spaceName
}: {
page: Page
folderName: string
spaceName: string
}): Promise<Space> => {
await page.locator(util.format(resourceNameSelector, folderName)).click({ button: 'right' })
await page.locator(createSpaceFromResourceAction).click()
await page.locator(resourceNameInput).fill(spaceName)
const [response] = await Promise.all([
page.waitForResponse(
(resp) =>
resp.status() === 201 &&
resp.request().method() === 'POST' &&
resp.url().endsWith('/drives')
),
page.locator(util.format(actionConfirmationButton, 'Create')).click()
])
await page.locator(notificationMessage).waitFor()
return (await response.json()) as Space
}
export const createSpaceFromSelection = async ({
page,
resources,
spaceName
}: {
page: Page
resources: string[]
spaceName: string
}): Promise<Space> => {
await selectOrDeselectResources({
page,
resources: resources.map((r) => ({ name: r }) as resourceArgs), // prettier-ignore
select: true
})
await page.locator(util.format(resourceNameSelector, resources[0])).click({ button: 'right' })
await page.locator(createSpaceFromResourceAction).click()
await page.locator(resourceNameInput).fill(spaceName)
const [response] = await Promise.all([
page.waitForResponse(
(resp) =>
resp.status() === 201 &&
resp.request().method() === 'POST' &&
resp.url().endsWith('/drives')
),
page.locator(util.format(actionConfirmationButton, 'Create')).click()
])
await page.locator(notificationMessage).waitFor()
return (await response.json()) as Space
}
export const createNewFolder = async ({
page,
resource
}: {
page: Page
resource: string
}): Promise<void> => {
await page.locator(createNewFolderButton).click()
await page.locator(resourceNameInput).fill(resource)
await Promise.all([
page.waitForResponse((resp) => resp.status() === 207 && resp.request().method() === 'PROPFIND'),
page.locator(util.format(actionConfirmationButton, 'Create')).click()
])
}
export const createNewFileOrFolder = async (args: createResourceArgs): Promise<void> => {
const { page, name, type, content } = args
await page.locator(addNewResourceButton).click()
switch (type) {
case 'folder': {
await createNewFolder({ page, resource: name })
break
}
case 'txtFile': {
await page.locator(createNewTxtFileButton).click()
await page.locator(resourceNameInput).fill(name)
await Promise.all([
page.waitForResponse((resp) => resp.status() === 201 && resp.request().method() === 'PUT'),
page.locator(util.format(actionConfirmationButton, 'Create')).click()
])
await editTextDocument({ page, content, name })
break
}
case 'mdFile': {
await page.locator(createNewMdFileButton).click()
await page.locator(resourceNameInput).fill(name)
await Promise.all([
page.waitForResponse((resp) => resp.status() === 201 && resp.request().method() === 'PUT'),
page.locator(util.format(actionConfirmationButton, 'Create')).click()
])
await editTextDocument({ page, content, name })
break
}
case 'drawioFile': {
await page.locator(createNewDrawioFileButton).click()
await page.locator(resourceNameInput).fill(name)
await Promise.all([
page.waitForResponse((resp) => resp.status() === 201 && resp.request().method() === 'PUT'),
page.locator(util.format(actionConfirmationButton, 'Create')).click()
])
await page.waitForLoadState()
await page.frameLocator(drawioIframe).locator(drawioSaveButton).click()
await page.waitForURL('**/draw-io/personal/**')
// TODO: Update to use appTopBar once #8447 is merged
await page.goto(page.url())
break
}
case 'OpenDocument': {
// By Default when OpenDocument is created, it is opened with collabora if both app-provider services are running together
await createDocumentFile(args, 'Collabora')
break
}
case 'Microsoft Word': {
// By Default when Microsoft Word document is created, it is opened with OnlyOffice if both app-provider services are running together
await createDocumentFile(args, 'OnlyOffice')
break
}
}
}
const createDocumentFile = async (
args: createResourceArgs,
editorToOpen: string
): Promise<void> => {
const { page, name, type, content } = args
// for creating office suites documents we need the external app provider services to be ready
// though the service is ready it takes some time for the list of office suites documents to be visible in the dropdown in the webUI
// which requires a retry to check if the service is ready and the office suites documents is visible in the dropdown
const isAppProviderServiceReadyInWebUI = await isAppProviderServiceForOfficeSuitesReadyInWebUI(
page,
type
)
if (isAppProviderServiceReadyInWebUI === false) {
throw new Error(
`The document of type ${type} did not appear in the webUI for ${editorToOpen}. Possible reason could be the app provider service for ${editorToOpen} was not ready yet.`
)
}
await page.locator(util.format(createNewOfficeDocumentFileBUtton, type)).click()
await page.locator(resourceNameInput).fill(name)
await Promise.all([
page.waitForLoadState(),
page.waitForURL('**/external/personal/**'),
page.waitForResponse((resp) => resp.status() === 200 && resp.request().method() === 'POST'),
page.locator(util.format(actionConfirmationButton, 'Create')).click()
])
const editorMainFrame = page.frameLocator(externalEditorIframe)
switch (editorToOpen) {
case 'Collabora':
try {
await editorMainFrame
.locator(collaboraWelcomeModalIframe)
.waitFor({ timeout: config.minTimeout * 1000 })
await page.keyboard.press('Escape')
} catch (e) {
console.log('No welcome modal found. Continue...')
}
await editorMainFrame.locator(collaboraDocTextAreaSelector).fill(content)
const saveLocator = editorMainFrame.locator(collaboraEditorSaveSelector)
await expect(saveLocator).toHaveAttribute('class', /.*savemodified.*/)
await saveLocator.click()
await expect(saveLocator).not.toHaveAttribute('class', /.*savemodified.*/)
break
case 'OnlyOffice':
const innerIframe = editorMainFrame.frameLocator(onlyOfficeInnerFrameSelector)
await innerIframe.locator(onlyofficeDocTextAreaSelector).fill(content)
const saveButtonDisabledLocator = innerIframe.locator(onlyOfficeSaveButtonSelector)
await expect(saveButtonDisabledLocator).toHaveAttribute('disabled', 'disabled')
break
default:
throw new Error(
"Editor should be either 'Collabora' or 'OnlyOffice' but found " + editorToOpen
)
}
}
export const fillContentOfDocument = async ({
page,
text,
editorToOpen
}: {
page: Page
text: string
editorToOpen: string
}): Promise<void> => {
switch (editorToOpen) {
case 'TextEditor':
await page.locator(textEditorPlainTextInput).fill(text)
break
default:
throw new Error("Editor should be 'TextEditor' but found " + editorToOpen)
}
}
export const openAndGetContentOfDocument = async ({
page,
editorToOpen
}: {
page: Page
editorToOpen: string
}): Promise<string> => {
await page.waitForLoadState()
await page.waitForURL('**/external/**')
const editorMainFrame = page.frameLocator(externalEditorIframe)
switch (editorToOpen) {
case 'Collabora':
try {
await editorMainFrame
.locator(collaboraWelcomeModalIframe)
.waitFor({ timeout: config.minTimeout * 1000 })
await page.keyboard.press('Escape')
} catch (e) {
console.log('No welcome modal found. Continue...')
}
await editorMainFrame.locator(collaboraCanvasEditorSelector).click()
break
case 'OnlyOffice':
const innerFrame = editorMainFrame.frameLocator(onlyOfficeInnerFrameSelector)
await innerFrame.locator(onlyOfficeCanvasEditorSelector).click()
await innerFrame.locator(onlyOfficeCanvasCursorSelector).waitFor()
break
default:
throw new Error(
"Editor should be either 'Collabora' or 'OnlyOffice' but found " + editorToOpen
)
}
// copying and getting the value with keyboard requires some
await page.keyboard.press('Control+A', { delay: 200 })
await page.keyboard.press('Control+C', { delay: 200 })
return await page.evaluate(() => navigator.clipboard.readText())
}
const isAppProviderServiceForOfficeSuitesReadyInWebUI = async (page, type) => {
let retry = 1
let isCreateNewOfficeDocumentFileButtonVisible
while (retry <= 5) {
isCreateNewOfficeDocumentFileButtonVisible = await page
.locator(util.format(createNewOfficeDocumentFileBUtton, type))
.isVisible()
if (isCreateNewOfficeDocumentFileButtonVisible === true) {
break
}
await new Promise((resolve) => setTimeout(resolve, 3000))
await page.reload()
await page.locator(addNewResourceButton).click()
retry++
}
return isCreateNewOfficeDocumentFileButtonVisible
}
export const createResources = async (args: createResourceArgs): Promise<void> => {
const { page, name, type, content } = args
const paths = name.split('/')
const resource = paths.pop()
for (const path of paths) {
const resourcesExists = await resourceExists({
page: page,
name: path
})
if (!resourcesExists) {
await page.locator(addNewResourceButton).click()
await createNewFolder({ page, resource: path })
}
await clickResource({ page, path })
}
await createNewFileOrFolder({ page, name: resource, type, content })
}
export const editTextDocument = async ({
page,
name,
content
}: {
page: Page
name: string
content: string
}): Promise<void> => {
const isMarkdownMode = await page.locator(textEditor).getAttribute('data-markdown-mode')
const inputLocator =
isMarkdownMode === 'true' ? textEditorMarkdownInput : textEditorPlainTextInput
await page.locator(inputLocator).fill(content)
await Promise.all([
page.waitForResponse((resp) => resp.status() === 204 && resp.request().method() === 'PUT'),
page.waitForResponse((resp) => resp.status() === 207 && resp.request().method() === 'PROPFIND'),
page.locator(saveTextFileInEditorButton).click()
])
await editor.close(page)
await page.locator(util.format(resourceNameSelector, name)).waitFor()
}
/**/
export interface uploadResourceArgs {
page: Page
resources: File[]
to?: string
option?: string
error?: string
expectToFail?: boolean
}
const performUpload = async (args: uploadResourceArgs): Promise<void> => {
const { page, resources, to, option, error, expectToFail } = args
if (to) {
await clickResource({ page, path: to })
}
await page.locator(resourceUploadButton).click()
let uploadAction: Promise<void> = page
.locator(fileUploadInput)
.setInputFiles(resources.map((file) => file.path))
if (option) {
await uploadAction
switch (option) {
case 'skip': {
await page.locator(actionSkipButton).click()
return
}
case 'merge':
case 'replace': {
uploadAction = page.locator(actionSecondaryConfirmationButton).click()
break
}
case 'keep both': {
uploadAction = page.locator(util.format(actionConfirmationButton, 'Keep both')).click()
break
}
}
}
if (expectToFail) {
expect(await page.locator(notificationMessageDialog).textContent()).toBe(error)
return
}
await Promise.all([
page.waitForResponse(
(resp) =>
[201, 204].includes(resp.status()) &&
['POST', 'PUT', 'PATCH'].includes(resp.request().method())
),
uploadAction
])
}
export const uploadLargeNumberOfResources = async (args: uploadResourceArgs): Promise<void> => {
const { page, resources } = args
await performUpload(args)
await page.locator(uploadInfoCloseButton).waitFor()
await expect(page.locator(uploadInfoSuccessLabelSelector)).toHaveText(
`${resources.length} items uploaded`
)
}
export const uploadResource = async (args: uploadResourceArgs): Promise<void> => {
const { page, resources, option } = args
await performUpload(args)
if (option !== 'skip') {
await page.locator(uploadInfoCloseButton).click()
}
await waitForResources({
page,
names: resources.map((file) => path.basename(file.name))
})
}
export const tryToUploadResource = async (args: uploadResourceArgs): Promise<void> => {
const { page } = args
await performUpload({ ...args, expectToFail: true })
await page.locator(uploadErrorCloseButton).click()
}
export const dropUploadFiles = async (args: uploadResourceArgs): Promise<void> => {
const { page, resources } = args
// waiting to files view
await page.locator(addNewResourceButton).waitFor()
await dragDropFiles(page, resources, filesView)
await page.locator(uploadInfoCloseButton).click()
await Promise.all(
resources.map((file) =>
page.locator(util.format(resourceNameSelector, path.basename(file.name))).waitFor()
)
)
}
// uploads the file without other checks
export const startResourceUpload = (args: uploadResourceArgs): Promise<void> => {
return performUpload(args)
}
const pauseResumeUpload = (page: Page): Promise<void> => {
return page.locator(pauseResumeUploadButton).click()
}
export const pauseResourceUpload = async (page: Page): Promise<void> => {
await pauseResumeUpload(page)
await Promise.all([
page.locator(uploadResumeTooltip).waitFor(),
page.locator(pauseResumeUploadButton).hover()
])
}
export const resumeResourceUpload = async (page: Page): Promise<void> => {
await pauseResumeUpload(page)
await Promise.all([
page.locator(uploadPauseTooltip).waitFor(),
page.locator(pauseResumeUploadButton).hover()
])
await page.locator(uploadInfoSuccessLabelSelector).waitFor()
await page.locator(uploadInfoCloseButton).click()
}
export const cancelResourceUpload = async (page: Page): Promise<void> => {
await page.locator(cancelUploadButton).click()
await expect(page.locator(uploadInfoTitle)).toHaveText('Upload cancelled')
await expect(page.locator(uploadInfoLabelSelector)).toHaveText('0 items uploaded')
}
/**/
interface resourceArgs {
name: string
type?: string
}
export type ActionViaType = 'SIDEBAR_PANEL' | 'BATCH_ACTION' | 'SINGLE_SHARE_VIEW' | 'PREVIEW'
export interface downloadResourcesArgs {
page: Page
resources: resourceArgs[]
folder?: string
via: ActionViaType
}
export const downloadResources = async (args: downloadResourcesArgs): Promise<Download[]> => {
const { page, resources, folder, via } = args
const downloads = []
switch (via) {
case 'SIDEBAR_PANEL': {
if (folder) {
await clickResource({ page, path: folder })
}
for (const resource of resources) {
await sidebar.open({ page, resource: resource.name })
await sidebar.openPanel({ page, name: 'actions' })
const downloadResourceSelector =
resource.type === 'file' ? downloadFileButtonSideBar : downloadFolderButtonSideBar
const [download] = await Promise.all([
page.waitForEvent('download'),
page.locator(downloadResourceSelector).click()
])
await sidebar.close({ page })
downloads.push(download)
}
break
}
case 'BATCH_ACTION': {
await selectOrDeselectResources({ page, resources, folder, select: true })
if (resources.length === 1) {
throw new Error('Single resource cannot be downloaded with batch action')
}
const [download] = await Promise.all([
page.waitForEvent('download'),
page.locator(downloadButtonBatchAction).click()
])
downloads.push(download)
break
}
case 'SINGLE_SHARE_VIEW': {
if (folder) {
await clickResource({ page, path: folder })
}
for (const resource of resources) {
const downloadResourceSelector =
resource.type === 'file'
? downloadFileButtonSingleShareView
: downloadFolderButtonSingleShareView
const [download] = await Promise.all([
page.waitForEvent('download'),
page.locator(downloadResourceSelector).click()
])
downloads.push(download)
}
break
}
case 'PREVIEW': {
const [download] = await Promise.all([
page.waitForEvent('download'),
page.locator(downloadPreviewButton).click()
])
downloads.push(download)
break
}
}
return downloads
}
export type selectResourcesArgs = {
page: Page
resources: resourceArgs[]
folder?: string
select: boolean
}
export const selectOrDeselectResources = async (args: selectResourcesArgs): Promise<void> => {
const { page, folder, resources, select } = args
if (folder) {
await clickResource({ page, path: folder })
}
for (const resource of resources) {
const exists = await resourceExists({
page,
name: resource.name
})
if (exists) {
const resourceCheckbox = page.locator(util.format(checkBox, resource.name))
if (!(await resourceCheckbox.isChecked()) && select) {
await resourceCheckbox.check()
} else if (await resourceCheckbox.isChecked()) {
await resourceCheckbox.uncheck()
}
} else {
throw new Error(`The resource ${resource.name} you are trying to select does not exist`)
}
}
}
/**/
export interface moveOrCopyResourceArgs {
page: Page
resource: string
newLocation: string
action: 'copy' | 'move'
method: string
option?: string
}
export interface moveOrCopyMultipleResourceArgs extends Omit<moveOrCopyResourceArgs, 'resource'> {
resources: string[]
}
export const pasteResource = async (args: moveOrCopyResourceArgs): Promise<void> => {
const { page, resource, newLocation, action, method, option } = args
await page.locator(breadcrumbRoot).click()
const newLocationPath = newLocation.split('/')
for (const path of newLocationPath) {
if (path !== 'Personal') {
await clickResource({ page, path: path })
}
}
if (method === 'dropdown-menu') {
await page.locator(filesView).click({ button: 'right' })
await page.locator(util.format(filesContextMenuAction, 'copy')).click()
} else {
await page.locator(pasteButton).click()
}
if (option) {
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().endsWith(resource) &&
resp.ok &&
resp.request().method() === action.toUpperCase()
),
option === 'replace'
? page.locator(actionSecondaryConfirmationButton).click()
: page.locator(keepBothButton).click()
])
} else {
await waitForResources({
page,
names: [resource]
})
}
}
export const moveOrCopyMultipleResources = async (
args: moveOrCopyMultipleResourceArgs
): Promise<void> => {
const { page, newLocation, action, method, resources } = args
for (const resource of resources) {
await page.locator(util.format(checkBox, resource)).click()
}
const waitForMoveResponses = []
if (['drag-drop-breadcrumb', 'drag-drop'].includes(method)) {
for (const resource of resources) {
waitForMoveResponses.push(
page.waitForResponse(
(resp) =>
resp.url().endsWith(resource) &&
resp.status() === 201 &&
resp.request().method() === 'MOVE'
)
)
}
}
switch (method) {
case 'dropdown-menu': {
// after selecting multiple resources, resources can be copied or moved by clicking on any of the selected resources
await page.locator(highlightedFileRowSelector).first().click({ button: 'right' })
await page.locator(util.format(filesContextMenuAction, action)).click()
await page.locator(breadcrumbRoot).click()
const newLocationPath = newLocation.split('/')
for (const path of newLocationPath) {
if (path !== 'Personal') {
await clickResource({ page, path: path })
}
}
await page.locator(filesView).click({ button: 'right' })
await page.locator(util.format(filesContextMenuAction, 'copy')).click()
break
}
case 'batch-action': {
await page.locator(util.format(filesBatchAction, action)).click()
await page.locator(breadcrumbRoot).click()
const newLocationPath = newLocation.split('/')
for (const path of newLocationPath) {
if (path !== 'Personal') {
await clickResource({ page, path: path })
}
}
await page.locator(pasteButton).click()
break
}
case 'keyboard': {
const keyValue = action === 'copy' ? 'c' : 'x'
await page.keyboard.press(`Control+${keyValue}`)
await page.locator(breadcrumbRoot).click()
const newLocationPath = newLocation.split('/')
for (const path of newLocationPath) {
if (path !== 'Personal') {
await clickResource({ page, path: path })
}
}
await page.keyboard.press('Control+v')
break
}
case 'drag-drop': {
const source = page.locator(highlightedFileRowSelector).first()
const target = page.locator(util.format(resourceNameSelector, newLocation))
await Promise.all([...waitForMoveResponses, source.dragTo(target)])
await target.click()
break
}
case 'drag-drop-breadcrumb': {
const source = page.locator(highlightedFileRowSelector).first()
const target = page.locator(
util.format(breadcrumbResourceNameSelector, buildXpathLiteral(newLocation))
)
await Promise.all([...waitForMoveResponses, source.dragTo(target)])
await target.click()
break
}
}
await waitForResources({
page,
names: resources
})
}
export const moveOrCopyResource = async (args: moveOrCopyResourceArgs): Promise<void> => {
const { page, resource, newLocation, action, method, option } = args
const { dir: resourceDir, base: resourceBase } = path.parse(resource)
if (resourceDir) {
await clickResource({ page, path: resourceDir })
}
switch (method) {
case 'dropdown-menu': {
await page.locator(util.format(resourceNameSelector, resourceBase)).click({ button: 'right' })
await page.locator(util.format(filesContextMenuAction, action)).click()
await pasteResource({ page, resource: resourceBase, newLocation, action, method, option })
break
}
case 'batch-action': {
await page.locator(util.format(checkBox, resourceBase)).click()
await page.locator(util.format(filesBatchAction, action)).click()
await pasteResource({ page, resource: resourceBase, newLocation, action, method, option })
break
}
case 'sidebar-panel': {
await sidebar.open({ page: page, resource: resourceBase })
await sidebar.openPanel({ page: page, name: 'actions' })
const actionButtonType = action === 'copy' ? 'Copy' : 'Cut'
await page.locator(util.format(sideBarActionButton, actionButtonType)).click()
await pasteResource({ page, resource: resourceBase, newLocation, action, method, option })
break
}
case 'keyboard': {
const resourceCheckbox = page.locator(util.format(checkBox, resourceBase))
await resourceCheckbox.check()
const keyValue = action === 'copy' ? 'c' : 'x'
await page.keyboard.press(`Control+${keyValue}`)
await page.locator(breadcrumbRoot).click()
const newLocationPath = newLocation.split('/')
for (const path of newLocationPath) {
if (path !== 'Personal') {
await clickResource({ page, path: path })
}
}
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().endsWith(resource) &&
resp.status() === 201 &&
resp.request().method() === action.toUpperCase()
),
page.keyboard.press('Control+v')
])
break
}
case 'drag-drop': {
const source = page.locator(util.format(resourceNameSelector, resourceBase))
const target = page.locator(util.format(resourceNameSelector, newLocation))
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().endsWith(resource) &&
resp.status() === 201 &&
resp.request().method() === 'MOVE'
),
source.dragTo(target)
])
await Promise.all([
page.locator(util.format(resourceNameSelector, resourceBase)),
page.locator(util.format(resourceNameSelector, newLocation)).click()
])
break
}
case 'drag-drop-breadcrumb': {
const source = page.locator(util.format(resourceNameSelector, resourceBase))
const target = page.locator(
util.format(breadcrumbResourceNameSelector, buildXpathLiteral(newLocation))
)
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().endsWith(resource) &&
resp.status() === 201 &&
resp.request().method() === 'MOVE'
),
source.dragTo(target)
])
await Promise.all([
page.locator(util.format(resourceNameSelector, resourceBase)),
page
.locator(util.format(breadcrumbResourceNameSelector, buildXpathLiteral(newLocation)))
.click()
])
break
}
}
await waitForResources({
page,
names: [resourceBase]
})
}
/**/
export interface renameResourceArgs {
page: Page
resource: string
newName: string
}
export interface resourceTagsArgs {
page: Page
resource: string
tags: string[]
}
export const renameResource = async (args: renameResourceArgs): Promise<void> => {
const { page, resource, newName } = args
const { dir: resourceDir, base: resourceBase } = path.parse(resource)
if (resourceDir) {
await clickResource({ page, path: resourceDir })
}
await page.locator(util.format(resourceNameSelector, resourceBase)).click({ button: 'right' })
await page.locator(util.format(filesContextMenuAction, 'rename')).click()
await page.locator(fileRenameInput).fill(newName)
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().endsWith(resourceBase) &&
resp.status() === 201 &&
resp.request().method() === 'MOVE'
),
page.locator(util.format(actionConfirmationButton, 'Rename')).click()
])
}
/**/
export interface resourceVersionArgs {
page: Page
files: File[]
folder?: string
openDetailsPanel?: boolean
}
export const restoreResourceVersion = async (args: resourceVersionArgs) => {
const { page, files, folder, openDetailsPanel } = args
if (openDetailsPanel) {
const fileName = files.map((file) => path.basename(file.name))
await clickResource({ page, path: folder })
await sidebar.open({ page, resource: fileName[0] })
await sidebar.openPanel({ page, name: 'versions' })
}
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().includes('/v/') && resp.status() === 204 && resp.request().method() === 'COPY'
),
page.locator(versionRevertButton).first().click()
])
}
/**/
export interface deleteResourceArgs {
page: Page
resourcesWithInfo: resourceArgs[]
folder?: string
via: ActionViaType
}
export const deleteResource = async (args: deleteResourceArgs): Promise<void> => {
const { page, resourcesWithInfo, folder, via } = args
switch (via) {
case 'SIDEBAR_PANEL': {
if (folder) {
await clickResource({ page, path: folder })
}
for (const resource of resourcesWithInfo) {
await sidebar.open({ page, resource: resource.name })
await sidebar.openPanel({ page, name: 'actions' })
await page.locator(deleteButtonSidebar).first().click()
await page.waitForResponse(
(resp) =>
resp.url().includes(encodeURIComponent(resource.name)) &&
resp.status() === 204 &&
resp.request().method() === 'DELETE'
)
await sidebar.close({ page })
}
break
}
case 'BATCH_ACTION': {
await selectOrDeselectResources({ page, resources: resourcesWithInfo, folder, select: true })
const deletetedResources = []
if (resourcesWithInfo.length <= 1) {
throw new Error('Single resource or objects cannot be deleted with batch action')
}
await Promise.all([
page.waitForResponse((resp) => {
if (resp.status() === 204 && resp.request().method() === 'DELETE') {
deletetedResources.push(decodeURIComponent(resp.url().split('/').pop()))
}
// waiting for GET response after all the resource are deleted with batch action
return (
resp.url().includes('graph/v1.0/drives') &&
resp.status() === 200 &&
resp.request().method() === 'GET'
)
}),
page.locator(deleteButtonBatchAction).click()
])
// assertion that the resources actually got deleted
expect(deletetedResources.length).toBe(resourcesWithInfo.length)
for (const resource of resourcesWithInfo) {
expect(deletetedResources).toContain(resource.name)
}
break
}
}
}
export interface downloadResourceVersionArgs {
page: Page
files: File[]
folder?: string
}
export const downloadResourceVersion = async (
args: downloadResourceVersionArgs
): Promise<Download[]> => {
const { page, files, folder } = args
const fileName = files.map((file) => path.basename(file.name))
const downloads = []
await clickResource({ page, path: folder })
await sidebar.open({ page, resource: fileName[0] })
await sidebar.openPanel({ page, name: 'versions' })
const [download] = await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().includes('/v/') && resp.status() === 200 && resp.request().method() === 'HEAD'
),
page.waitForEvent('download'),
page.locator('//*[@data-testid="file-versions-download-button"]').first().click()
])
await sidebar.close({ page: page })
downloads.push(download)
return downloads
}
export interface deleteResourceTrashbinArgs {
page: Page
resource: string
}
export interface deleteTrashbinMultipleResourcesArgs
extends Omit<deleteResourceTrashbinArgs, 'resource'> {
resources: string[]
}
export const deleteResourceTrashbin = async (args: deleteResourceTrashbinArgs): Promise<string> => {
const { page, resource } = args
const resourceCheckbox = page.locator(
util.format(checkBoxForTrashbin, `/${resource.replace(/^\/+/, '')}`)
)
await new Promise((resolve) => setTimeout(resolve, 5000))
if (!(await resourceCheckbox.isChecked())) {
await resourceCheckbox.check()
}
await page.locator(permanentDeleteButton).first().click()
await Promise.all([
page.waitForResponse((resp) => resp.status() === 204 && resp.request().method() === 'DELETE'),
page.locator(util.format(actionConfirmationButton, 'Delete')).click()
])
const message = await page.locator(notificationMessageDialog).textContent()
return message.trim().toLowerCase()
}
export const deleteTrashbinMultipleResources = async (
args: deleteTrashbinMultipleResourcesArgs
): Promise<void> => {
const { page, resources } = args
for (const resource of resources) {
await page.locator(util.format(checkBox, resource)).click()
}
await page.locator(permanentDeleteButton).first().click()
await Promise.all([
page.waitForResponse((resp) => resp.status() === 204 && resp.request().method() === 'DELETE'),
page.locator(util.format(actionConfirmationButton, 'Delete')).click()
])
for (const resource of resources) {
await expect(page.locator(util.format(filesSelector, resource))).not.toBeVisible()
}
}
export const emptyTrashbin = async ({ page }): Promise<void> => {
await page.locator(emptyTrashbinButtonSelector).click()
await Promise.all([
page.waitForResponse((resp) => resp.status() === 204 && resp.request().method() === 'DELETE'),
page.locator(util.format(actionConfirmationButton, 'Delete')).click()
])
const message = await page.locator(notificationMessageDialog).textContent()
expect(message).toBe('All deleted files were removed')
}
export const expectThatDeleteButtonIsNotVisible = async (
args: deleteResourceTrashbinArgs
): Promise<void> => {
const { page, resource } = args
const resourceCheckbox = page.locator(
util.format(checkBoxForTrashbin, `/${resource.replace(/^\/+/, '')}`)
)
if (!(await resourceCheckbox.isChecked())) {
await resourceCheckbox.check()
}
const deleteButton = page.locator(permanentDeleteButton)
await expect(deleteButton).not.toBeVisible()
}
export interface restoreResourceTrashbinArgs {
resource: string
page: Page
}
export interface clickTagArgs {
resource: string
tag: string
page: Page
}
export interface createSpaceFromFolderArgs {
folderName: string
spaceName: string
page: Page
}
export interface createSpaceFromSelectionArgs {
resources: string[]
spaceName: string
page: Page
}
export const restoreResourceTrashbin = async (
args: restoreResourceTrashbinArgs
): Promise<string> => {
const { page, resource } = args
const resourceCheckbox = page.locator(
util.format(checkBoxForTrashbin, `/${resource.replace(/^\/+/, '')}`)
)
if (!(await resourceCheckbox.isChecked())) {
await resourceCheckbox.check()
}
await Promise.all([
page.waitForResponse((resp) => resp.status() === 201 && resp.request().method() === 'MOVE'),
page.locator(restoreResourceButton).click()
])
const message = await page.locator(notificationMessageDialog).textContent()
return message.trim().toLowerCase()
}
export const expectThatRestoreResourceButtonVisibility = async (
args: restoreResourceTrashbinArgs
): Promise<void> => {
const { page, resource } = args
const resourceCheckbox = page.locator(
util.format(checkBoxForTrashbin, `/${resource.replace(/^\/+/, '')}`)
)
if (!(await resourceCheckbox.isChecked())) {
await resourceCheckbox.check()
}
const restoreButton = page.locator(restoreResourceButton)
await expect(restoreButton).not.toBeVisible()
}
export const getTagsForResourceVisibilityInFilesTable = async (
args: resourceTagsArgs
): Promise<boolean> => {
const { page, resource, tags } = args
const { dir: resourceDir } = path.parse(resource)
const folderPaths = resource.split('/')
const resourceName = folderPaths.pop()
if (resourceDir) {
await clickResource({ page, path: resourceDir })
}
const tagCellSelector = util.format(tagTableCell, resourceName)
await page.locator(tagCellSelector).waitFor()
const resourceTagCell = page.locator(tagCellSelector)
for (const tag of tags) {
const tagSpan = resourceTagCell.locator(util.format(tagInFilesTable, tag))
const isVisible = await tagSpan.isVisible()
if (!isVisible) {
return false
}
}
return true
}
export const clickResourceTag = async (args: clickTagArgs): Promise<void> => {
const { page, resource, tag } = args
const { dir: resourceDir } = path.parse(resource)
const folderPaths = resource.split('/')
const resourceName = folderPaths.pop()
if (resourceDir) {
await clickResource({ page, path: resourceDir })
}
const tagCellSelector = util.format(tagTableCell, resourceName)
await page.locator(tagCellSelector).waitFor()
const resourceTagCell = page.locator(tagCellSelector)
const tagSpan = resourceTagCell.locator(util.format(tagInFilesTable, tag))
return tagSpan.click()
}
export const getTagsForResourceVisibilityInDetailsPanel = async (
args: resourceTagsArgs
): Promise<boolean> => {
const { page, resource, tags } = args
const { dir: resourceDir } = path.parse(resource)
const folderPaths = resource.split('/')
const resourceName = folderPaths.pop()
if (resourceDir) {
await clickResource({ page, path: resourceDir })
}
await sidebar.open({ page: page, resource: resourceName })
for (const tag of tags) {
const tagSelector = util.format(tagInDetailsPanel, tag)
await page.locator(tagSelector).waitFor()
const tagSpan = page.locator(tagSelector)
const isVisible = await tagSpan.isVisible()
if (!isVisible) {
return false
}
}
return true
}
export type searchFilter = 'all files' | 'current folder'
export interface searchResourceGlobalSearchArgs {
keyword: string
filter?: searchFilter
pressEnter?: boolean
page: Page
}
export const searchResourceGlobalSearch = async (
args: searchResourceGlobalSearchArgs
): Promise<void> => {
const { page, keyword, filter, pressEnter } = args
// .reload() waits nicely for search indexing to be finished
await page.reload()
// select the filter if provided
if (filter) {
await page.locator(globalSearchDirFilterDropdown).click()
await page
.locator(
filter === 'all files' ? globalSearchBarFilterAllFiles : globalSearchBarFilterCurrentFolder
)
.click()
}
await page.locator(globalSearchBarFilter).click()
if (!keyword) {
await page.locator(globalSearchInput).click()
await page.keyboard.press('Enter')
return
}
await Promise.all([
page.waitForResponse((resp) => resp.status() === 207 && resp.request().method() === 'REPORT'),
page.locator(globalSearchInput).fill(keyword)
])
await expect(page.locator(globalSearchOptions)).toBeVisible()
await expect(page.locator(loadingSpinner)).not.toBeVisible()
if (pressEnter) {
await page.keyboard.press('Enter')
}
}
export type displayedResourceType = 'search list' | 'files list' | 'Shares' | 'trashbin'
export interface getDisplayedResourcesArgs {
keyword: displayedResourceType
page: Page
}
export const getDisplayedResourcesFromSearch = async (page): Promise<string[]> => {
const result = await page.locator(searchList).allInnerTexts()
// the result has values like `test\n.txt` so remove new line
return result.map((result) => result.replace('\n', ''))
}
export const getDisplayedResourcesFromFilesList = async (page): Promise<string[]> => {
const files = []
await page.locator('[data-test-resource-path]').first().waitFor()
// wait for tika indexing
await new Promise((resolve) => setTimeout(resolve, 1000))
const result = await page.locator('[data-test-resource-path]')
const count = await result.count()
for (let i = 0; i < count; i++) {
files.push(await result.nth(i).getAttribute('data-test-resource-name'))
}
return files
}
export const getDisplayedResourcesFromShares = async (page): Promise<string[]> => {
const files = []
await page.locator(sharesNavigationButtonSelector).click()
const result = await page.locator('[data-test-resource-path]')
const count = await result.count()
for (let i = 0; i < count; i++) {
files.push(await result.nth(i).getAttribute('data-test-resource-name'))
}
return files
}
export const getDisplayedResourcesFromTrashbin = async (page): Promise<string[]> => {
const files = []
const result = await page.locator('[data-test-resource-path]')
const count = await result.count()
for (let i = 0; i < count; i++) {
files.push(await result.nth(i).getAttribute('data-test-resource-name'))
}
return files
}
export interface switchViewModeArgs {
page: Page
target: 'resource-table' | 'resource-tiles'
}
export const clickViewModeToggle = async (args: switchViewModeArgs): Promise<void> => {
const { page, target } = args
await page.locator(`.viewmode-switch-buttons .${target}`).click()
}
export const expectThatResourcesAreTiles = async (args): Promise<void> => {
const { page } = args
const tiles = page.locator(resourcesAsTiles)
await expect(tiles).toBeVisible()
}
export const showHiddenResources = async (page): Promise<void> => {
await page.locator(filesViewOptionButton).click()
await page.locator(hiddenFilesToggleButton).click()
// close the files view option
await page.locator(filesViewOptionButton).click()
}
export interface editResourcesArgs {
page: Page
name: string
content: string
}
export const editResources = async (args: editResourcesArgs): Promise<void> => {
const { page, name, content } = args
const { dir: resourceDir } = path.parse(name)
const folderPaths = name.split('/')
const resourceName = folderPaths.pop()
if (resourceDir) {
await clickResource({ page, path: resourceDir })
}
await page.locator(util.format(resourceNameSelector, resourceName)).click()
await editTextDocument({ page, content: content, name: resourceName })
}
export const addTagsToResource = async (args: resourceTagsArgs): Promise<void> => {
const { page, resource, tags } = args
const { dir: resourceDir } = path.parse(resource)
const folderPaths = resource.split('/')
const resourceName = folderPaths.pop()
if (resourceDir) {
await clickResource({ page, path: resourceDir })
}
await sidebar.open({ page: page, resource: resourceName })
const inputForm = page.locator(tagFormInput)
for (const tag of tags) {
await inputForm.pressSequentially(tag)
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().endsWith('tags') && resp.status() === 200 && resp.request().method() === 'PUT'
),
page.locator('.vs__dropdown-option').first().press('Enter')
])
}
await sidebar.close({ page })
}
export const removeTagsFromResource = async (args: resourceTagsArgs): Promise<void> => {
const { page, resource, tags } = args
const { dir: resourceDir } = path.parse(resource)
const folderPaths = resource.split('/')
const resourceName = folderPaths.pop()
if (resourceDir) {
await clickResource({ page, path: resourceDir })
}
await sidebar.open({ page: page, resource: resourceName })
for (const tag of tags) {
await page.locator(util.format(tagInInputForm, tag)).click()
}
await sidebar.close({ page })
}
export interface openFileInViewerArgs {
page: Page
name: string
actionType: 'mediaviewer' | 'pdfviewer' | 'texteditor' | 'Collabora' | 'OnlyOffice'
}
export const openFileInViewer = async (args: openFileInViewerArgs): Promise<void> => {
const { page, name, actionType } = args
switch (actionType) {
case 'OnlyOffice':
case 'Collabora':
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().includes(`app_name=${actionType}`) &&
resp.status() === 200 &&
resp.request().method() === 'POST'
),
page.locator(util.format(resourceNameSelector, name)).click()
])
break
case 'mediaviewer': {
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().includes('preview') &&
resp.status() === 200 &&
resp.request().method() === 'GET'
),
page.locator(util.format(resourceNameSelector, name)).click()
])
// in case of error <img> doesn't contain src="blob:https://url"
expect(await page.locator(previewImage).getAttribute('src')).toContain('blob')
break
}
case 'pdfviewer':
case 'texteditor': {
await Promise.all([
page.waitForResponse(
(resp) => resp.status() === 207 && resp.request().method() === 'PROPFIND'
),
page.locator(util.format(resourceNameSelector, name)).click()
])
break
}
}
}
export const checkThatFileVersionIsNotAvailable = async (
args: resourceVersionArgs
): Promise<void> => {
const { page, files, folder } = args
const fileName = files.map((file) => path.basename(file.name))
await clickResource({ page, path: folder })
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().includes('dav/meta') &&
resp.status() === 403 &&
resp.request().method() === 'PROPFIND'
),
sidebar.open({ page, resource: fileName[0] })
])
await sidebar.openPanel({ page, name: 'versions' })
await expect(page.locator(fileVersionSidebar)).toHaveText('No Versions available for this file')
}
export const expectThatPublicLinkIsDeleted = async (args): Promise<void> => {
const { page, url } = args
await Promise.all([
page.waitForResponse((resp) => resp.status() === 404 && resp.request().method() === 'PROPFIND'),
page.goto(url)
])
await expect(page.locator(noLinkMessage)).toHaveText(
'The resource could not be located, it may not exist anymore.'
)
}
export interface changePageArgs {
page: Page
pageNumber: string
}
export const changePage = async (args: changePageArgs): Promise<void> => {
const { page, pageNumber } = args
await page.locator(util.format(listItemPageSelector, pageNumber)).click()
}
export interface changeItemsPerPageArgs {
page: Page
itemsPerPage: string
}
export const changeItemsPerPage = async (args: changeItemsPerPageArgs): Promise<void> => {
const { page, itemsPerPage } = args
await page.locator(filesViewOptionButton).click()
await page.locator(itemsPerPageDropDownSelector).click()
await page.locator(util.format(itemsPerPageDropDownOptionSelector, itemsPerPage)).click()
// close the files view option
await page.locator(filesViewOptionButton).click()
}
export const getFileListFooterText = ({ page }): Promise<string> => {
return page.locator(footerTextSelector).textContent()
}
export interface expectNumberOfResourcesInThePageToBeArgs {
page: Page
numberOfResources: number
}
export const countNumberOfResourcesInThePage = ({ page }): Promise<number> => {
// playwright's default count function is not used here because count only counts
// elements that are visible in the page but in this case we want to get
// all the elements present
return page.evaluate(
([filesTableRowSelector]) => {
return Promise.resolve(document.querySelectorAll(filesTableRowSelector).length)
},
[filesTableRowSelector]
)
}
export const expectPageNumberNotToBeVisible = async ({ page }): Promise<void> => {
await expect(page.locator(filesPaginationNavSelector)).not.toBeVisible()
}
export interface expectFileToBeSelectedArgs {
page: Page
fileName: string
}
export const expectFileToBeSelected = async ({ page, fileName }): Promise<void> => {
await expect(page.locator(util.format(checkBox, fileName))).toBeChecked()
}
export const createShotcut = async (args: shortcutArgs): Promise<void> => {
const { page, resource, name, type } = args
await page.locator(addNewResourceButton).click()
await page.locator(createNewShortcutButton).click()
switch (type) {
case 'folder':
case 'space':
case 'file': {
await page.locator(shortcutResorceInput).fill(resource)
const searchResult = page.locator('#create-shortcut-modal-contextmenu .oc-resource-name')
await expect(searchResult).toHaveText(resource)
await searchResult.click()
break
}
case 'public link':
const link = new LinksEnvironment()
await page.locator(shortcutResorceInput).fill(link.getLink({ name: resource }).url)
break
case 'website': {
await page.locator(shortcutResorceInput).fill(resource)
await page.locator('#create-shortcut-modal-contextmenu').click()
break
}
}
if (name) {
await page.getByLabel('Shortcut name').fill(name)
}
await Promise.all([
page.waitForResponse(
(resp) =>
resp.status() === 201 && resp.request().method() === 'PUT' && resp.url().endsWith('url')
),
page.locator(util.format(actionConfirmationButton, 'Create')).click()
])
}
export interface shortcutArgs {
page: Page
resource: string
name: string
type: shortcutType
}
export type shortcutType = 'folder' | 'file' | 'public link' | 'space' | 'website'
export const openShotcut = async ({
page,
name,
url
}: {
page: Page
name: string
url?: string
}): Promise<void> => {
const resource = page.locator(util.format(resourceNameSelector, name))
if (url) {
const popupPromise = page.waitForEvent('popup')
await resource.click()
const popup = await popupPromise
await popup.waitForURL(url)
} else {
const itemId = await resource.locator(fileRow).getAttribute('data-item-id')
await Promise.all([
page.waitForResponse(
(resp) => resp.url().endsWith(encodeURIComponent(name)) || resp.url().endsWith(itemId)
),
resource.click()
])
}
}
export interface expectFileToBeLockedArgs {
page: Page
resource: string
}
export const getLockLocator = (args: expectFileToBeLockedArgs): Locator => {
const { page, resource } = args
return page.locator(util.format(resourceLockIcon, resource))
}
| owncloud/web/tests/e2e/support/objects/app-files/resource/actions.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/resource/actions.ts",
"repo_id": "owncloud",
"token_count": 20135
} | 873 |
import { Page } from '@playwright/test'
import { locatorUtils } from '../../../utils'
const openForResource = async ({
page,
resource
}: {
page: Page
resource: string
}): Promise<void> => {
await page
.locator(
`//span[@data-test-resource-name="${resource}"]/ancestor::tr[contains(@class, "oc-tbody-tr")]//button[contains(@class, "resource-table-btn-action-dropdown")]`
)
.click()
await page.locator('.oc-files-actions-show-details-trigger').click()
}
export const openPanelForResource = async ({
page,
resource,
panel
}: {
page: Page
resource: string
panel: string
}): Promise<void> => {
await page
.locator(
`//span[@data-test-resource-name="${resource}"]/ancestor::tr[contains(@class, "oc-tbody-tr")]//button[contains(@class, "resource-table-btn-action-dropdown")]`
)
.click()
await page.locator(`.oc-files-actions-show-${panel}-trigger`).click()
}
const openGlobal = async ({ page }: { page: Page }): Promise<void> => {
await page.locator('#files-toggle-sidebar').click()
}
export const open = async ({
page,
resource
}: {
page: Page
resource?: string
}): Promise<void> => {
if (await page.locator('#app-sidebar').count()) {
await close({ page })
}
resource ? await openForResource({ page, resource }) : await openGlobal({ page })
}
export const close = async ({ page }: { page: Page }): Promise<void> => {
const closeButtonSelector = `//div[contains(@class,"sidebar-panel is-active")]//button[contains(@class,"header__close")]`
await page.locator(closeButtonSelector).click()
}
export const openPanel = async ({ page, name }: { page: Page; name: string }): Promise<void> => {
const currentPanel = page.locator('.sidebar-panel.is-active')
const backButton = currentPanel.locator('.header__back')
if (await backButton.count()) {
await backButton.click()
await locatorUtils.waitForEvent(currentPanel, 'transitionend')
}
const panelSelector = page.locator(`#sidebar-panel-${name}-select`)
const nextPanel = page.locator(`#sidebar-panel-${name}`)
await panelSelector.click()
await locatorUtils.waitForEvent(nextPanel, 'transitionend')
}
| owncloud/web/tests/e2e/support/objects/app-files/utils/sidebar.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/utils/sidebar.ts",
"repo_id": "owncloud",
"token_count": 763
} | 874 |
import { BrowserContext, Page } from '@playwright/test'
export interface Link {
name: string
url: string
password?: string
}
export interface Space {
name: string
id: string
}
export interface Actor {
context: BrowserContext
page: Page
close(): Promise<void>
newPage(page: Page): Promise<Page>
}
export interface User {
/**
* actual id, that will be exposed by the graph api
*/
uuid?: string
id: string
displayName: string
password: string
email: string
}
export interface File {
name: string
path: string
}
export interface Me {
id: string
}
export interface Group {
uuid?: string
id: string
displayName: string
}
export interface Token {
userId: string
accessToken: string
refreshToken: string
}
// keycloak realm role
export interface KeycloakRealmRole {
id: string
name: string
}
export interface ApplicationEntity {
appRoles: AppRole[]
displayName: string
id: string
}
export interface AppRole {
displayName: string
id: string
}
| owncloud/web/tests/e2e/support/types.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/types.ts",
"repo_id": "owncloud",
"token_count": 315
} | 875 |
/// <reference types="vite/client" />
import { UppyService } from '@ownclouders/web-pkg'
import { Route, Router } from 'vue-router'
// This file must have at least one export or import on top-level
export {}
declare global {
interface Window {
WEB_APPS_MAP: Record<string, string>
}
}
declare module 'vue' {
interface ComponentCustomProperties {
$uppyService: UppyService
$router: Router
$route: Route
}
interface GlobalComponents {
// https://github.com/LinusBorg/portal-vue/issues/380
Portal: typeof import('portal-vue')['Portal']
PortalTarget: typeof import('portal-vue')['PortalTarget']
}
}
| owncloud/web/web.d.ts/0 | {
"file_path": "owncloud/web/web.d.ts",
"repo_id": "owncloud",
"token_count": 229
} | 876 |





“如果你想搞懂一个漏洞,比较好的方法是:你可以自己先制造出这个漏洞(用代码编写),然后再利用它,最后再修复它”。
<br>
# pikachu
Pikachu是一个带有漏洞的Web应用系统,在这里包含了常见的web安全漏洞。 如果你是一个Web渗透测试学习人员且正发愁没有合适的靶场进行练习,那么Pikachu可能正合你意。<br>
## Pikachu上的漏洞类型列表如下:<br>
* Burt Force(暴力破解漏洞)<br>
* XSS(跨站脚本漏洞)<br>
* CSRF(跨站请求伪造)<br>
* SQL-Inject(SQL注入漏洞)<br>
* RCE(远程命令/代码执行)<br>
* Files Inclusion(文件包含漏洞)<br>
* Unsafe file downloads(不安全的文件下载)<br>
* Unsafe file uploads(不安全的文件上传)<br>
* Over Permisson(越权漏洞)<br>
* ../../../(目录遍历)<br>
* I can see your ABC(敏感信息泄露)<br>
* PHP反序列化漏洞<br>
* XXE(XML External Entity attack)<br>
* 不安全的URL重定向<br>
* SSRF(Server-Side Request Forgery)<br>
* 管理工具<br>
* More...(找找看?..有彩蛋!)<br>
管理工具里面提供了一个简易的xss管理后台,供你测试钓鱼和捞cookie,还可以搞键盘记录!~<br>
后续会持续更新一些新的漏洞进来,也欢迎你提交漏洞案例给我,最新版本请关注pikachu<br>
每类漏洞根据不同的情况又分别设计了不同的子类<br>
同时,为了让这些漏洞变的有意思一些,在Pikachu平台上为每个漏洞都设计了一些小的场景,点击漏洞页面右上角的"提示"可以查看到帮助信息。<br>
## 如何安装和使用
Pikachu使用世界上最好的语言PHP进行开发-_-<br>
数据库使用的是mysql,因此运行Pikachu你需要提前安装好"PHP+MYSQL+中间件(如apache,nginx等)"的基础环境,建议在你的测试环境直接使用 一些集成软件来搭建这些基础环境,比如XAMPP,WAMP等,作为一个搞安全的人,这些东西对你来说应该不是什么难事。接下来:<br>
-->把下载下来的pikachu文件夹放到web服务器根目录下;<br>
-->根据实际情况修改inc/config.inc.php里面的数据库连接配置;<br>
-->访问h ttp://x.x.x.x/pikachu,会有一个红色的热情提示"欢迎使用,pikachu还没有初始化,点击进行初始化安装!",点击即可完成安装。<br>
<br>
<br>
如果阁下对Pikachu使用上有什么疑问,可以在QQ群:532078894(已满),973351978(未满) 咨询,虽然咨询了,也不一定有人回答-_-。
## Docker
使用已有构建:
```bash
docker run -d -p 8765:80 8023/pikachu-expect:latest
```
本地构建:
```bash
如果你熟悉docker,也可以直接用docker部署
docker build -t "pikachu" .
docker run -d -p 8080:80 pikachu
```
## 切记
"少就是多,慢就是快"
## WIKI
[点击进入](https://github.com/zhuifengshaonianhanlu/pikachu/wiki/01:%E6%89%AF%E5%9C%A8%E5%89%8D%E9%9D%A2)
| zhuifengshaonianhanlu/pikachu/README.md/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/README.md",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2089
} | 877 |
<?php
///**
// * Created by runner.han
// * There is nothing new under the sun
// */
ob_start();
if (!isset($PIKA_ROOT_DIR)){
$PIKA_ROOT_DIR = '';
}
//$ACTIVE = array("active open","active","","","");
if (!isset($ACTIVE)){
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "index.php"){
//22 title
$ACTIVE = array("active open","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta charset="utf-8" />
<title>Get the pikachu</title>
<meta name="description" content="overview & stats" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<!-- bootstrap & fontawesome -->
<link rel="stylesheet" href="<?php echo $PIKA_ROOT_DIR;?>assets/css/bootstrap.min.css" / >
<link rel="stylesheet" href="<?php echo $PIKA_ROOT_DIR;?>assets/font-awesome/4.5.0/css/font-awesome.min.css" />
<!-- page specific plugin styles -->
<!-- text fonts -->
<link rel="stylesheet" href="<?php echo $PIKA_ROOT_DIR;?>assets/css/fonts.googleapis.com.css" />
<!-- ace styles -->
<link rel="stylesheet" href="<?php echo $PIKA_ROOT_DIR;?>assets/css/ace.min.css" class="ace-main-stylesheet" id="main-ace-style" />
<!--[if lte IE 9]>
<link rel="stylesheet" href="<?php echo $PIKA_ROOT_DIR;?>assets/css/ace-part2.min.css" class="ace-main-stylesheet" />
<![endif]-->
<link rel="stylesheet" href="<?php echo $PIKA_ROOT_DIR;?>assets/css/ace-skins.min.css" />
<link rel="stylesheet" href="<?php echo $PIKA_ROOT_DIR;?>assets/css/ace-rtl.min.css" />
<!--[if lte IE 9]>
<link rel="stylesheet" href="<?php echo $PIKA_ROOT_DIR;?>assets/css/ace-ie.min.css" />
<![endif]-->
<!-- inline styles related to this page -->
<!-- ace settings handler -->
<script src="<?php echo $PIKA_ROOT_DIR;?>assets/js/ace-extra.min.js"></script>
<!-- HTML5shiv and Respond.js for IE8 to support HTML5 elements and media queries -->
<!--[if lte IE 8]>
<script src="<?php echo $PIKA_ROOT_DIR;?>assets/js/html5shiv.min.js"></script>
<script src="<?php echo $PIKA_ROOT_DIR;?>assets/js/respond.min.js"></script>
<![endif]-->
<script src="<?php echo $PIKA_ROOT_DIR;?>assets/js/jquery-2.1.4.min.js"></script>
<script src="<?php echo $PIKA_ROOT_DIR;?>assets/js/bootstrap.min.js"></script>
</head>
<body class="no-skin">
<div id="navbar" class="navbar navbar-default ace-save-state">
<div class="navbar-container ace-save-state" id="navbar-container">
<div class="navbar-header pull-left">
<a href="<?php echo $PIKA_ROOT_DIR;?>index.php" class="navbar-brand">
<small>
<i class="fa fa-key"></i>
Pikachu 漏洞练习平台 pika~pika~
</small>
</a>
</div>
<div class="navbar-buttons navbar-header pull-right" role="navigation">
<ul class="nav ace-nav">
<li class="light-blue dropdown-modal">
<a data-toggle="dropdown" href="#" class="dropdown-toggle">
<img class="nav-user-photo" src="<?php echo $PIKA_ROOT_DIR;?>assets/images/avatars/pikachu1.png" alt="Jason's Photo" />
<span class="user-info">
<small>欢迎</small>
骚年
</span>
</a>
</li>
</ul>
</div>
</div><!-- /.navbar-container -->
</div>
<div class="main-container ace-save-state" id="main-container">
<script type="text/javascript">
try{ace.settings.loadState('main-container')}catch(e){}
</script>
<div id="sidebar" class="sidebar responsive ace-save-state">
<script type="text/javascript">
try{ace.settings.loadState('sidebar')}catch(e){}
</script>
<ul class="nav nav-list">
<li class="<?php echo $ACTIVE[0];?>">
<a href="<?php echo $PIKA_ROOT_DIR;?>index.php">
<i class="ace-icon glyphicon glyphicon-tags"></i>
<span class="menu-text"> 系统介绍 </span>
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[1];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-lock"></i>
<span class="menu-text">
暴力破解
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[2];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/burteforce/burteforce.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[3];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/burteforce/bf_form.php">
<i class="menu-icon fa fa-caret-right"></i>
基于表单的暴力破解
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[4];?>">
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/burteforce/bf_server.php">
<i class="menu-icon fa fa-caret-right"></i>
验证码绕过(on server)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[5];?>">
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/burteforce/bf_client.php">
<i class="menu-icon fa fa-caret-right"></i>
验证码绕过(on client)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[6];?>">
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/burteforce/bf_token.php">
<i class="menu-icon fa fa-caret-right"></i>
token防爆破?
</a>
<b class="arrow"></b>
</li>
<!-- <li class="--><?php //echo $ACTIVE[7];?><!--">-->
<!-- <a href="#" class="dropdown-toggle">-->
<!-- <i class="menu-icon fa fa-caret-right"></i>-->
<!---->
<!-- test-->
<!-- <b class="arrow fa fa-angle-down"></b>-->
<!-- </a>-->
<!---->
<!-- <b class="arrow"></b>-->
<!---->
<!-- <ul class="submenu">-->
<!-- <li class="--><?php //echo $ACTIVE[7];?><!--">-->
<!-- <a href="top-menu.html">-->
<!-- <i class="menu-icon fa fa-caret-right"></i>-->
<!-- test sun 01-->
<!-- </a>-->
<!---->
<!-- <b class="arrow"></b>-->
<!-- </li>-->
<!---->
<!-- </ul>-->
<!-- </li>-->
</ul>
</li>
<li class="<?php echo $ACTIVE[7];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-indent-left"></i>
<span class="menu-text">
Cross-Site Scripting
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[8];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xss.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[9];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xss_reflected_get.php">
<i class="menu-icon fa fa-caret-right"></i>
反射型xss(get)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[10];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xsspost/post_login.php">
<i class="menu-icon fa fa-caret-right"></i>
反射型xss(post)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[11];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xss_stored.php">
<i class="menu-icon fa fa-caret-right"></i>
存储型xss
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[12];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xss_dom.php">
<i class="menu-icon fa fa-caret-right"></i>
DOM型xss
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[12];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xss_dom_x.php">
<i class="menu-icon fa fa-caret-right"></i>
DOM型xss-x
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[13];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xssblind/xss_blind.php">
<i class="menu-icon fa fa-caret-right"></i>
xss之盲打
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[14];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xss_01.php">
<i class="menu-icon fa fa-caret-right"></i>
xss之过滤
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[15];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xss_02.php">
<i class="menu-icon fa fa-caret-right"></i>
xss之htmlspecialchars
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[16];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xss_03.php">
<i class="menu-icon fa fa-caret-right"></i>
xss之href输出
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[17];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xss/xss_04.php">
<i class="menu-icon fa fa-caret-right"></i>
xss之js输出
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[25];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-share"></i>
<span class="menu-text">
CSRF
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[26];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/csrf/csrf.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[27];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/csrf/csrfget/csrf_get_login.php">
<i class="menu-icon fa fa-caret-right"></i>
CSRF(get)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[28];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/csrf/csrfpost/csrf_post_login.php">
<i class="menu-icon fa fa-caret-right"></i>
CSRF(post)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[29];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/csrf/csrftoken/token_get_login.php">
<i class="menu-icon fa fa-caret-right"></i>
CSRF Token
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[35];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon fa fa-fighter-jet"></i>
<span class="menu-text">
SQL-Inject
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[36];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[37];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli_id.php">
<i class="menu-icon fa fa-caret-right"></i>
数字型注入(post)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[38];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli_str.php">
<i class="menu-icon fa fa-caret-right"></i>
字符型注入(get)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[39];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli_search.php">
<i class="menu-icon fa fa-caret-right"></i>
搜索型注入
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[40];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli_x.php">
<i class="menu-icon fa fa-caret-right"></i>
xx型注入
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[41];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli_iu/sqli_login.php">
<i class="menu-icon fa fa-caret-right"></i>
"insert/update"注入
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[42];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli_del.php">
<i class="menu-icon fa fa-caret-right"></i>
"delete"注入
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[43];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli_header/sqli_header_login.php">
<i class="menu-icon fa fa-caret-right"></i>
"http header"注入
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[44];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli_blind_b.php">
<i class="menu-icon fa fa-caret-right"></i>
盲注(base on boolian)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[45];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli_blind_t.php">
<i class="menu-icon fa fa-caret-right"></i>
盲注(base on time)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[46];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/sqli/sqli_widebyte.php">
<i class="menu-icon fa fa-caret-right"></i>
宽字节注入
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[50];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-pencil"></i>
<span class="menu-text">
RCE
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[51];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/rce/rce.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[52];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/rce/rce_ping.php">
<i class="menu-icon fa fa-caret-right"></i>
exec "ping"
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[53];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/rce/rce_eval.php">
<i class="menu-icon fa fa-caret-right"></i>
exec "evel"
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[55];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-file"></i>
<span class="menu-text">
File Inclusion
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[56];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/fileinclude/fileinclude.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[57];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/fileinclude/fi_local.php">
<i class="menu-icon fa fa-caret-right"></i>
File Inclusion(local)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[58];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/fileinclude/fi_remote.php"">
<i class="menu-icon fa fa-caret-right"></i>
File Inclusion(remote)
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[60];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-download"></i>
<span class="menu-text">
Unsafe Filedownload
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[61];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/unsafedownload/unsafedownload.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[62];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/unsafedownload/down_nba.php">
<i class="menu-icon fa fa-caret-right"></i>
Unsafe Filedownload
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[65];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-upload"></i>
<span class="menu-text">
Unsafe Fileupload
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[66];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/unsafeupload/upload.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[67];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/unsafeupload/clientcheck.php">
<i class="menu-icon fa fa-caret-right"></i>
client check
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[68];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/unsafeupload/servercheck.php">
<i class="menu-icon fa fa-caret-right"></i>
MIME type
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[69];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/unsafeupload/getimagesize.php">
<i class="menu-icon fa fa-caret-right"></i>
getimagesize
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[73];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-text-height"></i>
<span class="menu-text">
Over Permission
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[74];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/overpermission/op.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[75];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/overpermission/op1/op1_login.php">
<i class="menu-icon fa fa-caret-right"></i>
水平越权
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[76];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/overpermission/op2/op2_login.php">
<i class="menu-icon fa fa-caret-right"></i>
垂直越权
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[80];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-align-left"></i>
<span class="menu-text">
../../
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[81];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/dir/dir.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[82];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/dir/dir_list.php">
<i class="menu-icon fa fa-caret-right"></i>
目录遍历
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[85];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-camera"></i>
<span class="menu-text">
敏感信息泄露
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[86];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/infoleak/infoleak.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[87];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/infoleak/findabc.php">
<i class="menu-icon fa fa-caret-right"></i>
IcanseeyourABC
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[90];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-align-left"></i>
<span class="menu-text">
PHP反序列化
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[91];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/unserilization/unserilization.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[92];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/unserilization/unser.php">
<i class="menu-icon fa fa-caret-right"></i>
PHP反序列化漏洞
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[95];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-flag"></i>
<span class="menu-text">
XXE
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[96];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xxe/xxe.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[97];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/xxe/xxe_1.php">
<i class="menu-icon fa fa-caret-right"></i>
XXE漏洞
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[100];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-repeat"></i>
<span class="menu-text">
URL重定向
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[101];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/urlredirect/unsafere.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[102];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/urlredirect/urlredirect.php">
<i class="menu-icon fa fa-caret-right"></i>
不安全的URL跳转
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[105];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon fa fa-exchange"></i>
<span class="menu-text">
SSRF
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[106];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/ssrf/ssrf.php">
<i class="menu-icon fa fa-caret-right"></i>
概述
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[107];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/ssrf/ssrf_curl.php">
<i class="menu-icon fa fa-caret-right"></i>
SSRF(curl)
</a>
<b class="arrow"></b>
</li>
<li class="<?php echo $ACTIVE[108];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>vul/ssrf/ssrf_fgc.php">
<i class="menu-icon fa fa-caret-right"></i>
SSRF(file_get_content)
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="<?php echo $ACTIVE[120];?>">
<a href="#" class="dropdown-toggle">
<i class="ace-icon glyphicon glyphicon-cog"></i>
<span class="menu-text">
管理工具
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="<?php echo $ACTIVE[121];?>" >
<a href="<?php echo $PIKA_ROOT_DIR;?>pkxss/index.php">
<i class="menu-icon fa fa-caret-right"></i>
XSS后台
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
</ul><!-- /.nav-list -->
<div class="sidebar-toggle sidebar-collapse" id="sidebar-collapse">
<i id="sidebar-toggle-icon" class="ace-icon fa fa-angle-double-left ace-save-state" data-icon1="ace-icon fa fa-angle-double-left" data-icon2="ace-icon fa fa-angle-double-right"></i>
</div>
</div>
| zhuifengshaonianhanlu/pikachu/header.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/header.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 22819
} | 878 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
include_once '../inc/config.inc.php';
include_once '../inc/mysql.inc.php';
$link=connect();
//设置允许被跨域访问
header("Access-Control-Allow-Origin:*");
$data = $_POST['datax'];
$query = "insert keypress(data) values('$data')";
$result=mysqli_query($link,$query);
?> | zhuifengshaonianhanlu/pikachu/pkxss/rkeypress/rkserver.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/pkxss/rkeypress/rkserver.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 147
} | 879 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "fi_remote.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','',
'active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.php';
$html1='';
if(!ini_get('allow_url_include')){
$html1.="<p style='color: red'>warning:你的allow_url_include没有打开,请在php.ini中打开了再测试该漏洞,记得修改后,重启中间件服务!</p>";
}
$html2='';
if(!ini_get('allow_url_fopen')){
$html2.="<p style='color: red;'>warning:你的allow_url_fopen没有打开,请在php.ini中打开了再测试该漏洞,重启中间件服务!</p>";
}
$html3='';
if(phpversion()<='5.3.0' && !ini_get('magic_quotes_gpc')){
$html3.="<p style='color: red;'>warning:你的magic_quotes_gpc打开了,请在php.ini中关闭了再测试该漏洞,重启中间件服务!</p>";
}
//远程文件包含漏洞,需要php.ini的配置文件符合相关的配置
$html='';
if(isset($_GET['submit']) && $_GET['filename']!=null){
$filename=$_GET['filename'];
include "$filename";//变量传进来直接包含,没做任何的安全限制
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="fileinclude.php">file include</a>
</li>
<li class="active">远程文件包含</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="先了解一下include()函数的用法吧">
点一下提示~
</a>
</div>
<div class="page-content">
<div id=fi_main>
<p class="fi_title">which NBA player do you like?</p>
<form method="get">
<select name="filename">
<option value="">--------------</option>
<option value="include/file1.php">Kobe bryant</option>
<option value="include/file2.php">Allen Iverson</option>
<option value="include/file3.php">Kevin Durant</option>
<option value="include/file4.php">Tracy McGrady</option>
<option value="include/file5.php">Ray Allen</option>
</select>
<input class="sub" type="submit" name="submit" />
</form>
<?php
echo $html1;
echo $html2;
echo $html3;
echo $html;
?>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/fileinclude/fi_remote.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/fileinclude/fi_remote.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1851
} | 880 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "op.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.php';
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="op.php">over permission</a>
</li>
<li class="active">概述</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<div id="vul_info">
<dd class="vul_detail">
如果使用A用户的权限去操作B用户的数据,A的权限小于B的权限,如果能够成功操作,则称之为越权操作。
越权漏洞形成的原因是后台使用了 不合理的权限校验规则导致的。
</dd>
<dd class="vul_detail">
一般越权漏洞容易出现在权限页面(需要登录的页面)增、删、改、查的的地方,当用户对权限页面内的信息进行这些操作时,后台需要对
对当前用户的权限进行校验,看其是否具备操作的权限,从而给出响应,而如果校验的规则过于简单则容易出现越权漏洞。
</dd>
<dd class="vul_detail_1">
因此,在在权限管理中应该遵守:<br />
1.使用最小权限原则对用户进行赋权;<br />
2.使用合理(严格)的权限校验规则;<br />
3.使用后台登录态作为条件进行权限判断,别动不动就瞎用前端传进来的条件;<br />
</dd>
<dd class="vul_detail_1">
你可以通过“Over permission”对应的测试栏目,来进一步的了解该漏洞。
</dd>
</dl>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/overpermission/op.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/overpermission/op.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1697
} | 881 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "sqli_id.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',);
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.php';
include_once $PIKA_ROOT_DIR."inc/config.inc.php";
include_once $PIKA_ROOT_DIR."inc/function.php";
include_once $PIKA_ROOT_DIR."inc/mysql.inc.php";
$link=connect();
$html='';
if(isset($_POST['submit']) && $_POST['id']!=null){
//这里没有做任何处理,直接拼到select里面去了,形成Sql注入
$id=$_POST['id'];
$query="select username,email from member where id=$id";
$result=execute($link, $query);
//这里如果用==1,会严格一点
if(mysqli_num_rows($result)>=1){
while($data=mysqli_fetch_assoc($result)){
$username=$data['username'];
$email=$data['email'];
$html.="<p class='notice'>hello,{$username} <br />your email is: {$email}</p>";
}
}else{
$html.="<p class='notice'>您输入的user id不存在,请重新输入!</p>";
}
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="sqli.php">sqli</a>
</li>
<li class="active">数字型注入</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="变量类型为数字">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="sqli_main">
<p class="sqli_title">select your userid?</p>
<form class="sqli_id_form" method="post">
<select name="id">
<option value="">---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<input class="sqli_submit" type="submit" name="submit" value="查询" />
</form>
<?php echo $html;?>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_id.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_id.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1651
} | 882 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "upload.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.php';
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="upload.php">unsafe upfileupload</a>
</li>
<li class="active">概述</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<div id="vul_info">
<dl>
<dt class="vul_title">不安全的文件上传漏洞概述</dt>
<dd class="vul_detail">
文件上传功能在web应用系统很常见,比如很多网站注册的时候需要上传头像、上传附件等等。当用户点击上传按钮后,后台会对上传的文件进行判断
比如是否是指定的类型、后缀名、大小等等,然后将其按照设计的格式进行重命名后存储在指定的目录。
如果说后台对上传的文件没有进行任何的安全判断或者判断条件不够严谨,则攻击着可能会上传一些恶意的文件,比如一句话木马,从而导致后台服务器被webshell。
</dd>
<dd class="vul_detail">
所以,在设计文件上传功能时,一定要对传进来的文件进行严格的安全考虑。比如:<br />
--验证文件类型、后缀名、大小;<br />
--验证文件的上传方式;<br />
--对文件进行一定复杂的重命名;<br />
--不要暴露文件上传后的路径;<br />
--等等...<br />
</dd>
<dd class="vul_detail">
你可以通过“Unsafe file upload”对应的测试栏目,来进一步的了解该漏洞。
</dd>
</dl>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/unsafeupload/upload.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/unsafeupload/upload.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1788
} | 883 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$PIKA_ROOT_DIR = "../../../";
include_once $PIKA_ROOT_DIR.'inc/config.inc.php';
include_once $PIKA_ROOT_DIR.'inc/mysql.inc.php';
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "admin_login.php"){
$ACTIVE = array('','','','','','','','active open','','','','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
include_once $PIKA_ROOT_DIR.'header.php';
$link=connect();
$html = "<p>please input username and password!</p>";
if(isset($_POST['submit'])){
if($_POST['username']!=null && $_POST['password']!=null){
//这里没有使用预编译方式,而是使用的拼接SQL,所以需要手动转义防止SQL注入
$username=escape($link, $_POST['username']);
$password=escape($link, $_POST['password']);
$query="select * from users where username='$username' and password=md5('$password')";
$result=execute($link, $query);
if(mysqli_num_rows($result)==1){
$data=mysqli_fetch_assoc($result);
//登录时,生成cookie,1个小时有效期,供其他页面判断
setcookie('ant[uname]',$_POST['username'],time()+3600);
setcookie('ant[pw]',sha1(md5($_POST['password'])),time()+3600);
header("location:admin.php");
// echo '"<script>windows.location.href="xss_reflected_post.php"</script>';
}else{
$html ="<p>username or password error!</p>";
}
}else{
$html ="<p>please input username and password!</p>";
}
}
?>
<div class="main-content" xmlns="http://www.w3.org/1999/html">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="../xss.php">xss</a>
</li>
<li class="active">xssblind admin login</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="后台登录账号admin/123456">
点一下提示~
</a>
</div>
<div class="page-content">
<div class="xss_form">
<div class="xss_form_main">
<h4 class="header blue lighter bigger">
<i class="ace-icon fa fa-coffee green"></i>
Please Enter Your Information
</h4>
<form method="post" action="admin_login.php">
<!-- <fieldset>-->
<label>
<span>
<input type="text" name="username" placeholder="Username" />
<i class="ace-icon fa fa-user"></i>
</span>
</label>
</br>
<label>
<span>
<input type="password" name="password" placeholder="Password" />
<i class="ace-icon fa fa-lock"></i>
</span>
</label>
<div class="space"></div>
<div class="clearfix">
<label><input class="submit" name="submit" type="submit" value="Login" /></label>
<!-- <button type="button" name="submit">-->
<!-- <i class="ace-icon fa fa-key"></i>-->
<!-- <span class="bigger-110">Login</span>-->
<!-- </button>-->
</div>
</form>
<?php echo $html;?>
</div><!-- /.widget-main -->
</div><!-- /.widget-body -->
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR.'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/xss/xssblind/admin_login.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/xss/xssblind/admin_login.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2492
} | 884 |
# 8th Wall Web
8th Wall Web: WebAR for mobile devices!
Built entirely using standards-compliant JavaScript and WebGL, 8th Wall Web is a complete implementation of 8th Wall’s Simultaneous Localization and Mapping (SLAM) engine, hyper-optimized for real-time AR on mobile browsers. Features include World Tracking, Image Targets, Face Effects, Lightship Visual Positioning System (VPS), Sky Effects, Hand Tracking, and more.
- - -
# Resources
* [Getting Started Guide](https://www.8thwall.com/docs/guides/advanced-topics/local-hosting#getting-started)
* [Serving projects over HTTPS](https://www.8thwall.com/docs/guides/advanced-topics/local-hosting#serve-projects-over-https)
* [Documentation](https://www.8thwall.com/docs/web/)
* [8th Wall Website](https://www.8thwall.com)
# Examples
* [A-Frame Examples](https://github.com/8thwall/web/tree/master/examples/aframe) (Recommended to start)
* [Babylon.js Examples](https://github.com/8thwall/web/tree/master/examples/babylonjs)
* [three.js Examples](https://github.com/8thwall/web/tree/master/examples/threejs)
* [Camera Pipeline Examples](https://github.com/8thwall/web/tree/master/examples/camerapipeline)
| 8thwall/web/README.md/0 | {
"file_path": "8thwall/web/README.md",
"repo_id": "8thwall",
"token_count": 371
} | 0 |
/* globals AFRAME */
AFRAME.registerComponent('artgalleryframe', {
schema: {
name: {type: 'string'},
rotated: {type: 'bool'},
metadata: {type: 'string'},
},
init() {
const contents = document.getElementById('contents')
const container = document.getElementById('container')
const {object3D} = this.el
// Hide the image target until it is found
object3D.visible = false
// Metadata comes to the primitive as a string, so we parse and destructure it
const {artist, date, title, wikiTitle} = JSON.parse(this.data.metadata)
const frameEl = document.createElement('a-entity')
frameEl.setAttribute('scale', '0.95 0.95 0.95')
frameEl.setAttribute('gltf-model', '#frame-model')
if (this.data.rotated) {
// Rotate the frame for a landscape target
frameEl.setAttribute('rotation', '0 0 90')
}
this.el.appendChild(frameEl)
// Instantiate the element with information about the painting
const infoDisplay = document.createElement('a-entity')
infoDisplay.setAttribute('info-display', {title, artist, date})
infoDisplay.object3D.position.set(0, this.data.rotated ? -0.4 : -0.5, 0.1)
this.el.appendChild(infoDisplay)
// Use the title of the painting to fetch some info from the Wikipedia API
// If a painting doesn't have a Wikipedia article of its own, we use the painter's article via
// wikiTitle
const apiUrl = 'https://en.wikipedia.org/w/api.php?action=query' +
`&titles=${wikiTitle || title}&format=json&prop=extracts&exintro=1&origin=*`
let pageContent
fetch(apiUrl, {mode: 'cors'})
.then(e => e.json())
.then((data) => {
const page = Object.entries(data.query.pages)[0][1]
pageContent = `<h1>${page.title}</h1>${page.extract}`
})
const tapTarget = document.createElement('a-box')
// Image targets are 3:4 so the target is scaled to match
tapTarget.setAttribute('scale', '0.75 1 0.1')
tapTarget.setAttribute('material', 'opacity: 0; transparent:true')
if (this.data.rotated) {
// Rotate the tap target for a landscape target
tapTarget.setAttribute('rotation', '0 0 90')
}
this.el.appendChild(tapTarget)
tapTarget.addEventListener('click', () => {
// Set the innerHTML of our UI element to the data returned by the API
contents.innerHTML = pageContent
// Removing the collapsed class from container triggers a CSS transition to show the content
container.classList.remove('collapsed')
})
// showImage handles displaying and moving the virtual object to match the image
const showImage = ({detail}) => {
// Updating position/rotation/scale using object3D is more performant than setAttribute
object3D.position.copy(detail.position)
object3D.quaternion.copy(detail.rotation)
object3D.scale.set(detail.scale, detail.scale, detail.scale)
object3D.visible = true
// Add tapTarget as a clickable object
tapTarget.classList.add('cantap')
}
// hideImage handles hiding the virtual object when the image target is lost
const hideImage = () => {
object3D.visible = false
// Remove tapTarget from clickable objects
tapTarget.classList.remove('cantap')
}
// These events are routed and dispatched by xrextras-generate-image-targets
this.el.addEventListener('xrimagefound', showImage)
this.el.addEventListener('xrimageupdated', showImage)
this.el.addEventListener('xrimagelost', hideImage)
},
})
// This component uses the A-Frame text component to display information about a painting
AFRAME.registerComponent('info-display', {
schema: {
title: {default: ''},
artist: {default: ''},
date: {default: ''},
},
init() {
// Limit title to 20 characters
const displayTitle =
this.data.title.length > 20 ? `${this.data.title.substring(0, 17)}...` : this.data.title
const text = `${displayTitle}\n${this.data.artist}, ${this.data.date}`
const textData = {
align: 'left',
width: 0.7,
wrapCount: 22,
value: text,
color: 'white',
}
this.el.setAttribute('text', textData)
// Instantiate a second text object behind the first to achieve an shadow effect
const textShadowEl = document.createElement('a-entity')
textData.color = 'black'
textShadowEl.setAttribute('text', textData)
textShadowEl.object3D.position.z = -0.01
this.el.appendChild(textShadowEl)
},
})
// xrextras-generate-image-targets uses this primitive to populate multiple image targets
AFRAME.registerPrimitive('artgallery-frame', {
defaultComponents: {
artgalleryframe: {},
},
mappings: {
name: 'artgalleryframe.name',
rotated: 'artgalleryframe.rotated',
metadata: 'artgalleryframe.metadata',
},
})
| 8thwall/web/examples/aframe/artgallery/index.js/0 | {
"file_path": "8thwall/web/examples/aframe/artgallery/index.js",
"repo_id": "8thwall",
"token_count": 1705
} | 1 |
import React from 'react'
import {BrowserRouter, Routes, Route} from 'react-router-dom'
import {Scene} from './views/scene'
import {NotFound} from './views/notfound'
const App = () => (
<BrowserRouter>
<Routes>
<Route exact path='/' element={<Scene />} />
<Route path='*' element={<NotFound />} />
</Routes>
</BrowserRouter>
)
export default App
| 8thwall/web/examples/aframe/reactapp/src/App.jsx/0 | {
"file_path": "8thwall/web/examples/aframe/reactapp/src/App.jsx",
"repo_id": "8thwall",
"token_count": 142
} | 2 |
/*
Copyright 2011 Lazar Laszlo (lazarsoft@gmail.com, www.lazarsoft.info)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var qrcode = {};
qrcode.imagedata = null;
qrcode.width = 0;
qrcode.height = 0;
qrcode.qrCodeSymbol = null;
qrcode.debug = false;
qrcode.maxImgSize = 1024*1024;
qrcode.sizeOfDataLengthInfo = [ [ 10, 9, 8, 8 ], [ 12, 11, 16, 10 ], [ 14, 13, 16, 12 ] ];
qrcode.callback = null;
qrcode.vidSuccess = function (stream)
{
qrcode.localstream = stream;
if(qrcode.webkit)
qrcode.video.src = window.webkitURL.createObjectURL(stream);
else
if(qrcode.moz)
{
qrcode.video.mozSrcObject = stream;
qrcode.video.play();
}
else
qrcode.video.src = stream;
qrcode.gUM=true;
qrcode.canvas_qr2 = document.createElement('canvas');
qrcode.canvas_qr2.id = "qr-canvas";
qrcode.qrcontext2 = qrcode.canvas_qr2.getContext('2d');
qrcode.canvas_qr2.width = qrcode.video.videoWidth;
qrcode.canvas_qr2.height = qrcode.video.videoHeight;
setTimeout(qrcode.captureToCanvas, 500);
}
qrcode.vidError = function(error)
{
qrcode.gUM=false;
return;
}
qrcode.captureToCanvas = function()
{
if(qrcode.gUM)
{
try{
if(qrcode.video.videoWidth == 0)
{
setTimeout(qrcode.captureToCanvas, 500);
return;
}
else
{
qrcode.canvas_qr2.width = qrcode.video.videoWidth;
qrcode.canvas_qr2.height = qrcode.video.videoHeight;
}
qrcode.qrcontext2.drawImage(qrcode.video,0,0);
try{
qrcode.decode();
}
catch(e){
console.log(e);
setTimeout(qrcode.captureToCanvas, 500);
};
}
catch(e){
console.log(e);
setTimeout(qrcode.captureToCanvas, 500);
};
}
}
qrcode.setWebcam = function(videoId)
{
var n=navigator;
qrcode.video=document.getElementById(videoId);
var options = true;
if(navigator.mediaDevices && navigator.mediaDevices.enumerateDevices)
{
try{
navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
devices.forEach(function(device) {
console.log("deb1");
if (device.kind === 'videoinput') {
if(device.label.toLowerCase().search("back") >-1)
options=[{'sourceId': device.deviceId}] ;
}
console.log(device.kind + ": " + device.label +
" id = " + device.deviceId);
});
})
}
catch(e)
{
console.log(e);
}
}
else{
console.log("no navigator.mediaDevices.enumerateDevices" );
}
if(n.getUserMedia)
n.getUserMedia({video: options, audio: false}, qrcode.vidSuccess, qrcode.vidError);
else
if(n.webkitGetUserMedia)
{
qrcode.webkit=true;
n.webkitGetUserMedia({video:options, audio: false}, qrcode.vidSuccess, qrcode.vidError);
}
else
if(n.mozGetUserMedia)
{
qrcode.moz=true;
n.mozGetUserMedia({video: options, audio: false}, qrcode.vidSuccess, qrcode.vidError);
}
}
qrcode.decode = function(src){
if(arguments.length==0)
{
if(qrcode.canvas_qr2)
{
var canvas_qr = qrcode.canvas_qr2;
var context = qrcode.qrcontext2;
}
else
{
var canvas_qr = document.getElementById("qr-canvas");
var context = canvas_qr.getContext('2d');
}
qrcode.width = canvas_qr.width;
qrcode.height = canvas_qr.height;
qrcode.imagedata = context.getImageData(0, 0, qrcode.width, qrcode.height);
qrcode.result = qrcode.process(context);
if(qrcode.callback!=null)
qrcode.callback(qrcode.result);
return qrcode.result;
}
else
{
var image = new Image();
image.crossOrigin = "Anonymous";
image.onload=function(){
//var canvas_qr = document.getElementById("qr-canvas");
var canvas_out = document.getElementById("out-canvas");
if(canvas_out!=null)
{
var outctx = canvas_out.getContext('2d');
outctx.clearRect(0, 0, 320, 240);
outctx.drawImage(image, 0, 0, 320, 240);
}
var canvas_qr = document.createElement('canvas');
var context = canvas_qr.getContext('2d');
var nheight = image.height;
var nwidth = image.width;
if(image.width*image.height>qrcode.maxImgSize)
{
var ir = image.width / image.height;
nheight = Math.sqrt(qrcode.maxImgSize/ir);
nwidth=ir*nheight;
}
canvas_qr.width = nwidth;
canvas_qr.height = nheight;
context.drawImage(image, 0, 0, canvas_qr.width, canvas_qr.height );
qrcode.width = canvas_qr.width;
qrcode.height = canvas_qr.height;
try{
qrcode.imagedata = context.getImageData(0, 0, canvas_qr.width, canvas_qr.height);
}catch(e){
qrcode.result = "Cross domain image reading not supported in your browser! Save it to your computer then drag and drop the file!";
if(qrcode.callback!=null)
qrcode.callback(qrcode.result);
return;
}
try
{
qrcode.result = qrcode.process(context);
}
catch(e)
{
console.log(e);
qrcode.result = "error decoding QR Code";
}
if(qrcode.callback!=null)
qrcode.callback(qrcode.result);
}
image.onerror = function ()
{
if(qrcode.callback!=null)
qrcode.callback("Failed to load the image");
}
image.src = src;
}
}
qrcode.isUrl = function(s)
{
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
return regexp.test(s);
}
qrcode.decode_url = function (s)
{
var escaped = "";
try{
escaped = escape( s );
}
catch(e)
{
console.log(e);
escaped = s;
}
var ret = "";
try{
ret = decodeURIComponent( escaped );
}
catch(e)
{
console.log(e);
ret = escaped;
}
return ret;
}
qrcode.decode_utf8 = function ( s )
{
if(qrcode.isUrl(s))
return qrcode.decode_url(s);
else
return s;
}
qrcode.process = function(ctx){
var start = new Date().getTime();
var image = qrcode.grayScaleToBitmap(qrcode.grayscale());
//var image = qrcode.binarize(128);
if(qrcode.debug)
{
for (var y = 0; y < qrcode.height; y++)
{
for (var x = 0; x < qrcode.width; x++)
{
var point = (x * 4) + (y * qrcode.width * 4);
qrcode.imagedata.data[point] = image[x+y*qrcode.width]?0:0;
qrcode.imagedata.data[point+1] = image[x+y*qrcode.width]?0:0;
qrcode.imagedata.data[point+2] = image[x+y*qrcode.width]?255:0;
}
}
ctx.putImageData(qrcode.imagedata, 0, 0);
}
//var finderPatternInfo = new FinderPatternFinder().findFinderPattern(image);
var detector = new Detector(image);
var qRCodeMatrix = detector.detect();
if(qrcode.debug)
{
for (var y = 0; y < qRCodeMatrix.bits.Height; y++)
{
for (var x = 0; x < qRCodeMatrix.bits.Width; x++)
{
var point = (x * 4*2) + (y*2 * qrcode.width * 4);
qrcode.imagedata.data[point] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
qrcode.imagedata.data[point+1] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0;
qrcode.imagedata.data[point+2] = qRCodeMatrix.bits.get_Renamed(x,y)?255:0;
}
}
ctx.putImageData(qrcode.imagedata, 0, 0);
}
var reader = Decoder.decode(qRCodeMatrix.bits);
var data = reader.DataByte;
var str="";
for(var i=0;i<data.length;i++)
{
for(var j=0;j<data[i].length;j++)
str+=String.fromCharCode(data[i][j]);
}
var end = new Date().getTime();
var time = end - start;
console.log(time);
return {
found: true,
foundText: qrcode.decode_utf8(str),
points: qRCodeMatrix.points.map(
({x, y, estimatedModuleSize}) => { return {x, y, size: estimatedModuleSize}}),
}
//alert("Time:" + time + " Code: "+str);
}
qrcode.getPixel = function(x,y){
if (qrcode.width < x) {
throw "point error";
}
if (qrcode.height < y) {
throw "point error";
}
var point = (x * 4) + (y * qrcode.width * 4);
var p = (qrcode.imagedata.data[point]*33 + qrcode.imagedata.data[point + 1]*34 + qrcode.imagedata.data[point + 2]*33)/100;
return p;
}
qrcode.binarize = function(th){
var ret = new Array(qrcode.width*qrcode.height);
for (var y = 0; y < qrcode.height; y++)
{
for (var x = 0; x < qrcode.width; x++)
{
var gray = qrcode.getPixel(x, y);
ret[x+y*qrcode.width] = gray<=th?true:false;
}
}
return ret;
}
qrcode.getMiddleBrightnessPerArea=function(image)
{
var numSqrtArea = 4;
//obtain middle brightness((min + max) / 2) per area
var areaWidth = Math.floor(qrcode.width / numSqrtArea);
var areaHeight = Math.floor(qrcode.height / numSqrtArea);
var ay = 2;
var ax = 2;
var starty = areaHeight * ay
var startx = areaWidth * ax
var startidx = starty * qrcode.width + startx
var min = 0xFF
var max = 0
for (var dy = 0; dy < areaHeight; dy++)
{
var idx = startidx
for (var dx = 0; dx < areaWidth; dx++)
{
var target = image[idx++];
if (target < min)
min = target;
if (target > max)
max = target;
}
startidx += qrcode.width
}
return Math.floor((min + max) / 2);
}
qrcode.grayScaleToBitmap=function(grayScale)
{
var t = qrcode.getMiddleBrightnessPerArea(grayScale);
return grayScale.map((v) => v < t)
}
qrcode.grayscale = function()
{
var buff = new ArrayBuffer(qrcode.width*qrcode.height);
var ret = new Uint8Array(buff);
//var ret = new Array(qrcode.width*qrcode.height);
for (var y = 0; y < qrcode.height; y++)
{
for (var x = 0; x < qrcode.width; x++)
{
var gray = qrcode.getPixel(x, y);
ret[x+y*qrcode.width] = gray;
}
}
return ret;
}
function URShift( number, bits)
{
if (number >= 0)
return number >> bits;
else
return (number >> bits) + (2 << ~bits);
}
| 8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/qrcode.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/qrcode.js",
"repo_id": "8thwall",
"token_count": 5858
} | 3 |
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>8th Wall Web: A-Frame Image Targets</title>
<link rel="stylesheet" type="text/css" href="index.css">
<!-- We've included a slightly modified version of A-Frame, which fixes some polish concerns -->
<script src="//cdn.8thwall.com/web/aframe/8frame-1.3.0.min.js"></script>
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<!-- Landing Pages - see https://www.8thwall.com/docs/web/#landing-pages -->
<script src='//cdn.8thwall.com/web/landing-page/landing-page.js'></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script src="//apps.8thwall.com/xrweb?appKey=XXXXX"></script>
<!-- client code -->
<script src="index.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
</head>
<body>
<!-- If your app only interacts with image targets and not the world, disabling world tracking can
improve speed. -->
<a-scene
antialias="true"
landing-page
xrextras-loading
xrextras-runtime-error
xrweb="disableWorldTracking: true">
<a-assets>
<a-asset-item id="frame-glb" src="frame.glb"></a-asset-item>
</a-assets>
<a-camera position="0 4 10"> </a-camera>
<a-light type="ambient" intensity="1.3"></a-light>
<!-- A 3d object that tracks the image target. -->
<a-entity image-target>
<!-- Display a 3d model of an image frame. -->
<a-entity id="frame" position="0 0 0" scale=".95 .95 1" gltf-model="#frame-glb"></a-entity>
<!-- Add extra lighting to highlight the 3d geometry of the image frame. -->
<a-light type="directional" intensity="1" target="#frame" position="1.5 0.6 2.5"> </a-light>
<!-- Display the image target's name as set in the 8th Wall console. -->
<a-text targetname value="" align="center" width="1.75" position="0 -0.55 0.04"></a-text>
</a-entity>
</a-scene>
</body>
</html>
| 8thwall/web/gettingstarted/aframe-imagetarget/index.html/0 | {
"file_path": "8thwall/web/gettingstarted/aframe-imagetarget/index.html",
"repo_id": "8thwall",
"token_count": 812
} | 4 |
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>8th Wall Web: three.js Image Targets</title>
<link rel="stylesheet" type="text/css" href="index.css">
<!-- THREE.js must be supplied -->
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<!-- Landing Pages - see https://www.8thwall.com/docs/web/#landing-pages -->
<script src='https://cdn.8thwall.com/web/landing-page/landing-page.js'></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXXXXX"></script>
<!-- client code -->
<script src="index.js"></script>
</head>
<body>
<!-- The AR canvas -->
<canvas id="camerafeed"></canvas>
</body>
</html>
| 8thwall/web/gettingstarted/threejs-imagetarget/index.html/0 | {
"file_path": "8thwall/web/gettingstarted/threejs-imagetarget/index.html",
"repo_id": "8thwall",
"token_count": 412
} | 5 |
<!doctype html>
<html>
<head>
<title>XRExtras: A-FRAME</title>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="https://apps.8thwall.com/xrweb?appKey=XXXXXXXX"></script>
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="dist/xrextras.js"></script>
</head>
<body>
<script>
const xrScene = `
<a-scene xrweb xrextras-tap-recenter xrextras-almost-there xrextras-loading xrextras-runtime-error
xrextras-gesture-detector throw-error>
<a-camera position="0 3 3"></a-camera>
<a-box position="0 0.5 -1" material="color: #7611B6;" shadow xrextras-one-finger-rotate></a-box>
<a-box scale="100 2 100" position="0 -1 0" material="shader: shadow" shadow></a-box>
</a-scene>
`
const throwErrorComponent = {
init: function() {
// A pipeline module that throws an error after 300 frames -- illustrates the error
// handinling in xrweb-runtime-error.
const throwerrorPipelineModule = () => {
let frame = 0
return {
name: 'throwerror',
onUpdate: () => {if (++frame > 300) { throw Error('Too many frames!') }},
}
}
const load = () => { XR.addCameraPipelineModule(throwerrorPipelineModule()) }
window.XRExtras && window.XR ? load() : window.addEventListener('xrandextrasloaded', load)
}
}
window.XRExtras.AFrame.loadAFrameForXr({version: 'latest', components: {'throw-error': throwErrorComponent}})
.then(() => document.body.insertAdjacentHTML('beforeend', xrScene))
</script>
</body>
</html>
| 8thwall/web/xrextras/index-aframe.html/0 | {
"file_path": "8thwall/web/xrextras/index-aframe.html",
"repo_id": "8thwall",
"token_count": 729
} | 6 |
import {
resourceComponent,
pbrMaterialComponent,
basicMaterialComponent,
videoMaterialComponent,
hiderMaterialComponent,
} from './components/asset-components'
import {
sessionReconfigureComponent,
} from './components/session-reconfigure-components'
import {
runtimeErrorComponent,
statsComponent,
logToScreenComponent,
} from './components/debug-components'
import {
tapRecenterComponent,
gestureDetectorComponent,
oneFingerRotateComponent,
twoFingerRotateComponent,
pinchScaleComponent,
holdDragComponent,
playVideoComponent,
} from './components/gestures-components'
import {
faceAttachmentComponent,
faceMeshComponent,
faceAnchorComponent,
} from './components/face-components'
import {
handAnchorComponent,
handAttachmentComponent,
handMeshComponent,
handOccluderComponent,
} from './components/hand-components'
import {
opaqueBackgroundComponent,
attachComponent,
pwaInstallerComponent,
pauseOnBlurComponent,
pauseOnHiddenComponent,
hideCameraFeedComponent,
almostThereComponent,
loadingComponent,
} from './components/lifecycle-components'
import {
captureButtonComponent,
capturePreviewComponent,
captureConfigComponent,
} from './components/recorder-components'
import {
targetMeshComponent,
curvedTargetContainerComponent,
targetVideoFadeComponent,
targetVideoSoundComponent,
generateImageTargetsComponent,
namedImageTargetComponent,
spinComponent,
} from './components/target-components'
const xrComponents = () => {
return {
'xrextras-almost-there': almostThereComponent,
'xrextras-loading': loadingComponent,
'xrextras-runtime-error': runtimeErrorComponent,
'xrextras-stats': statsComponent,
'xrextras-opaque-background': opaqueBackgroundComponent,
'xrextras-tap-recenter': tapRecenterComponent,
'xrextras-generate-image-targets': generateImageTargetsComponent,
'xrextras-named-image-target': namedImageTargetComponent,
'xrextras-gesture-detector': gestureDetectorComponent,
'xrextras-one-finger-rotate': oneFingerRotateComponent,
'xrextras-two-finger-rotate': twoFingerRotateComponent,
'xrextras-pinch-scale': pinchScaleComponent,
'xrextras-hold-drag': holdDragComponent,
'xrextras-attach': attachComponent,
'xrextras-play-video': playVideoComponent,
'xrextras-log-to-screen': logToScreenComponent,
'xrextras-pwa-installer': pwaInstallerComponent,
'xrextras-pause-on-blur': pauseOnBlurComponent,
'xrextras-pause-on-hidden': pauseOnHiddenComponent,
'xrextras-faceanchor': faceAnchorComponent,
'xrextras-resource': resourceComponent,
'xrextras-pbr-material': pbrMaterialComponent,
'xrextras-basic-material': basicMaterialComponent,
'xrextras-video-material': videoMaterialComponent,
'xrextras-face-mesh': faceMeshComponent,
'xrextras-face-attachment': faceAttachmentComponent,
'xrextras-hide-camera-feed': hideCameraFeedComponent,
'xrextras-hider-material': hiderMaterialComponent,
'xrextras-capture-button': captureButtonComponent,
'xrextras-capture-preview': capturePreviewComponent,
'xrextras-capture-config': captureConfigComponent,
'xrextras-curved-target-container': curvedTargetContainerComponent,
'xrextras-target-mesh': targetMeshComponent,
'xrextras-target-video-fade': targetVideoFadeComponent,
'xrextras-target-video-sound': targetVideoSoundComponent,
'xrextras-spin': spinComponent,
'xrextras-hand-anchor': handAnchorComponent,
'xrextras-hand-attachment': handAttachmentComponent,
'xrextras-hand-mesh': handMeshComponent,
'xrextras-hand-occluder': handOccluderComponent,
'xrextras-session-reconfigure': sessionReconfigureComponent,
}
}
export {
xrComponents,
}
| 8thwall/web/xrextras/src/aframe/xr-components.ts/0 | {
"file_path": "8thwall/web/xrextras/src/aframe/xr-components.ts",
"repo_id": "8thwall",
"token_count": 1281
} | 7 |
/* Preview Container */
#previewContainer {
display: flex;
flex-direction: column;
align-items: stretch;
justify-content: space-between;
z-index: 30;
opacity: 0.0;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
box-sizing: border-box;
pointer-events: none;
}
#previewContainer.fade-in {
transition: 0.5s opacity;
opacity: 1;
}
#videoPreview, #imagePreview {
display: none;
max-width: 90vw;
max-height: calc(88vh - 12vmin);
border-radius: 10px;
border: 1vmin solid white;
background-color: white;
}
.icon-button img, #videoPreview, #imagePreview, .finalize-container {
filter: drop-shadow(0 0 2px #333);
}
.video-preview #videoPreview {
display: block;
}
.image-preview #imagePreview {
display: block;
}
/* Top Bar */
.top-bar {
position: relative;
flex: 1 0 0;
}
.preview-box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.icon-button {
padding: 4vmin;
user-select: none;
-webkit-user-select: none;
cursor: pointer;
}
.icon-button img {
display: block;
height: 7.5vmin;
}
#toggleMuteButton, #closePreviewButton {
position: absolute;
z-index: 1;
}
#toggleMuteButton {
left: 0;
bottom: 0;
display: none;
}
.video-preview #toggleMuteButton {
display: block;
}
#closePreviewButton {
top: 0;
right: 0;
}
/* Bottom Bar */
.bottom-bar {
display: flex;
justify-content: center;
position: relative;
margin: 0 5vmin;
}
.style-reset {
background: none;
border: none;
outline: none;
box-shadow: none !important;
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
-webkit-tap-highlight-color: transparent;
}
.style-reset:focus { outline:0; }
#actionButton {
padding: 0.3em 0.5em 0.3em 0.5em;
user-select: none;
-webkit-user-select: none;
font-family: 'Nunito', sans-serif;
text-align: right;
color: white;
background-color: #AD50FF;
border-radius: 0.5em;
font-size: 5vmin;
min-width: 3.25em;
}
.show-with-download-button {
position: absolute;
top: 50%;
right: 0;
transform: translateY(-50%);
}
.show-alone {
margin-bottom: 2vmin;
}
#actionButton img {
height: 0.8em;
margin-left: 0.4em;
}
.disabled-download.video-preview #openSafariText {
display: block;
font-size: 5vmin;
}
.disabled-download.image-preview #tapAndHoldText {
display: block;
font-size: 7.5vmin;
}
#openSafariText, #tapAndHoldText {
display: none;
padding: 0.3em 0.5em 0.3em 0.5em;
user-select: none;
-webkit-user-select: none;
font-family: 'Nunito', sans-serif;
text-align: center;
color: white;
filter: drop-shadow(0px 1px 2px #333);
}
#previewContainer:not(.downloaded) .show-after-download {
display: none;
}
.finalize-container {
position: absolute;
top: 50%;
transform: translateY(-50%);
right: calc(50% + 13vmin);
width: 25vmin;
text-align: center;
opacity: 0;
transition: 0.3s opacity;
}
.finalize-waiting .finalize-container {
opacity: 1;
}
#finalizeText {
color: white;
font-family: 'Nunito', sans-serif;
color: white;
font-size: 3.5vmin;
margin-bottom: 0.5vmin;
font-style: italic;
}
#finalizeProgressBar {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #B5B8D0;
border-radius: 0.75vmin;
overflow: hidden;
width: 100%;
height: 1.5vmin;
display: block;
}
#finalizeProgressBar::-webkit-progress-bar {
background: #B5B8D0;
border-radius: 0.75vmin;
}
#finalizeProgressBar::-webkit-progress-value {
border-radius: 0.75vmin;
background: white;
transition: 2s width;
}
#finalizeProgressBar::-moz-progress-bar {
border-radius: 0.75vmin;
background: white;
}
| 8thwall/web/xrextras/src/mediarecorder/media-preview.css/0 | {
"file_path": "8thwall/web/xrextras/src/mediarecorder/media-preview.css",
"repo_id": "8thwall",
"token_count": 1462
} | 8 |
const DAYS_PER_WEEK = 7
// Hours
const HOURS_PER_DAY = 24
const HOURS_PER_WEEK = HOURS_PER_DAY * DAYS_PER_WEEK
// Minutes
const MINUTES_PER_HOUR = 60
const MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY
const MINUTES_PER_WEEK = MINUTES_PER_HOUR * HOURS_PER_WEEK
// Seconds
const SECONDS_PER_MINUTE = 60
const SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR
const SECONDS_PER_DAY = SECONDS_PER_MINUTE * MINUTES_PER_DAY
const SECONDS_PER_WEEK = SECONDS_PER_MINUTE * MINUTES_PER_WEEK
// Milliseconds
const MILLISECONDS_PER_SECOND = 1000
const MILLISECONDS_PER_MINUTE = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE
const MILLISECONDS_PER_HOUR = MILLISECONDS_PER_SECOND * SECONDS_PER_HOUR
const MILLISECONDS_PER_DAY = MILLISECONDS_PER_SECOND * SECONDS_PER_DAY
const MILLISECONDS_PER_WEEK = MILLISECONDS_PER_SECOND * SECONDS_PER_WEEK
export {
DAYS_PER_WEEK,
HOURS_PER_DAY,
HOURS_PER_WEEK,
MINUTES_PER_HOUR,
MINUTES_PER_DAY,
MINUTES_PER_WEEK,
SECONDS_PER_MINUTE,
SECONDS_PER_HOUR,
SECONDS_PER_DAY,
SECONDS_PER_WEEK,
MILLISECONDS_PER_SECOND,
MILLISECONDS_PER_MINUTE,
MILLISECONDS_PER_HOUR,
MILLISECONDS_PER_DAY,
MILLISECONDS_PER_WEEK,
}
| 8thwall/web/xrextras/src/pwainstallermodule/time.js/0 | {
"file_path": "8thwall/web/xrextras/src/pwainstallermodule/time.js",
"repo_id": "8thwall",
"token_count": 535
} | 9 |
## 一、链接伪类
CSS 伪类是添加到选择器的关键字,用于指定所选元素的特殊状态。
语法:
伪类由冒号(:)后跟着伪类名称组成(例如,:hover)
```css
a:link{属性:值;} /*链接默认状态 ( a{属性:值}效果是一样的。)*/
a:visited{属性:值;} /*链接访问之后的状态*/
a:hover{属性:值;} /*鼠标放到链接上显示的状态*/
a:active{属性:值;} /*链接激活的状态*/
a:focus{属性:值;} /*获取焦点*/
```
> **注意:**
> 1.`a:visited`之后要想回到之前的状态,需要清除缓存。
> 2.写的顺序要按照`link,visited,hover,active`的顺序来写,否则可能不显示。

- **文本修饰**
```css
text-decoration: none | underline | line-through | ...... /* 链接下划线/删除线/...... */
```
## 二、背景属性
- `background-color`: (背景颜色)
- `background-image`: (背景图片)
- `background-repeat`: repeat(默认) | no-repeat | repeat-x | repeat-y (背景平铺)
- `background-position`: left | right | center(默认) | top | bottom (背景定位)
- `background-attachment`
- scroll: 背景图的位置是基于盒子(假如是div)的范围进行显示
- fixed:背景图的位置是基于整个浏览器body的范围进行显示,如果背景图定义在div里面,而显示的位置在浏览器范围内但是不在div的范围内的话,背景图无法显示。
- `background-clip`:
- background-clip: border-box; 背景占据边框
- background-clip: padding-box; 背景不占据边框,但是占据 padding
- background-clip: content-box; 背景不占据边框,也不占据 padding,只占据内容区域
- background-clip: text; 背景不占据边框,也不占据 padding,也不占据内容区域,只占据文字区域(作为文字的背景色
- `background-origin` 规定了指定背景图片background-image 属性的原点位置的背景相对区域。
- background-origin: border-box 背景图片的摆放以 border 区域为参考
- background-origin: padding-box 背景图片的摆放以 padding 区域为参考
- background-origin: content-box 背景图片的摆放以 content 内容区域为参考
- `background-position`
- background-position: right; // 方位值只写一个的时候,另外一个值默认居中。
- background-position: right bottom // 写2个方位值的时候,顺序没有要求
- background-position: 20px 30px // 写2个具体值的时候,第一个值代表水平方向,第二个值代表垂直方向
- `background-size` 设置背景图片大小。图片可以保有其原有的尺寸,或者拉伸到新的尺寸,或者在保持其原有比例的同时缩放到元素的可用空间的尺寸。
- background-size: cover 缩放背景图片以完全覆盖背景区,可能背景图片部分看不见。
- background-size: contain 缩放背景图片以完全装入背景区,可能背景区部分空白。
- background-size: 50% 一个值,指定图片的宽度,图片的高度隐式的为 auto
- background-size: 50% 50% 第一个值指定图片的宽度,第二个值指定图片的高度
### 1、背景属性连写
```css
background: red url("1.png") no-repeat 30px 40px scroll;
```
> PS:连写的时候没有顺序要求,url为必写项
## 三、行高
行高:是基线与基线之间的距离 = 文字高度+上下边距

### 1、行高的单位
单位除了像素以外,行高都是与文字大小与前面数值的乘积。
| 行高单位 | 父元素文字大小(定义了行高) | 子元素文字大小(子元素未定义行高时) | 行高 |
| ---- | -------------- | ------------------ | ---- |
| 40px | 20px | 30px | 40px |
| 2em | 20px | 30px | 40px |
| 150% | 20px | 30px | 30px |
| 2 | 20px | 30px | 60px |
> 总结:不带单位时,行高是和子元素文字大小相乘,em和%的行高是和父元素文字大小相乘。行高以像素为单位,就是定义的行高值。
## 四、盒子模型
### 1、border(边框)
```css
border-style: solid /*实线*/
dotted /*点线*/
dashed /*虚线*/
none /*无边框*/
border-color /*边框颜色*/
border-width /*边框粗细*/
```
- 边框属性的连写
```css
border: 1px solid #fff;
```
> PS: 没有顺序要求,线型为必写项
- 边框合并(细线边框,一般在 table 上使用)
```css
border-collapse:collapse;
```

### 2、获取焦点

- 点击label也可以选择文本框:label for id 获取光标焦点
```css
<label for="username">用户名:</label>
<input type="text" class="username" id="username"></input>
```

### 3、padding(内边距)
语法:
```css
padding-left | right | top | bottom
```
- padding连写
```css
padding: 20px; /*上右下左内边距都是20px*/
padding: 20px 30px; /*上下20px 左右30px*/
padding: 20px 30px 40px; /* 上内边距为20px 左右内边距为30px 下内边距为40px*/
padding: 20px 30px 40px 50px; /*上20px 右30px 下40px 左 50px*/
```
- 内边距撑大盒子的问题
> 盒子的宽度 = 定义的宽度 + 边框宽度 + 左右内边距
如果不想盒子宽度背撑大,可以设置:
```css
box-sizing: border-box;
```
### 4、margin(外边距)
```
margin-left | right | top | bottom
```
- 外边距连写
```css
margin: 20px; /*上下左右外边距20PX*/
margin: 20px 30px; /*上下20px 左右30px*/
margin: 20px 30px 40px; /*上20px 左右30px 下40px*/
margin: 20px 30px 40px 50px; /*上20px 右30px 下40px 左50px*/
```
注意:
1、垂直方向外边距合并(取最大值)
> 两个盒子垂直布局,一个设置上外边距,一个设置下外边距,取的设置较大的值,而不是相加。
2、嵌套的盒子外边距塌陷
> 嵌套的盒子,直接给子盒子设置垂直方向外边距的时候,会发生外边距的塌陷(父盒子跟着移动)
> **解决方法:**
>
> 1.给父盒子设置边框
>
> 2.给父盒子`overflow:hidden; `
**add 20180904:**
注意:当父元素没有border-top或者padding-top再或者没有浮动的时候,子元素的margin-top会传递到父元素上面
```html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
.a {
width: 300px;
height: 100px;
background-color: red;
margin-bottom: 140px;
}
.b {
width: 100px;
height: 40px;
background-color: blue;
margin-top: 50px;
}
.c {
width: 300px;
height: 100px;
background-color: yellow;
margin-top: 50px;
}
</style>
</head>
<body>
<!--当父元素没有border-top或者padding-top再或者没有浮动的时候,子元素的margin-top会传递到父元素上面-->
<div class="a">
<div class="b"></div>
</div>
<div class="c"></div>
</body>
</html>
```

**解决办法:**
- 给父元素加`overflow:hidden;`
- 给父元素加透明边框:`border-top: 1px solid transparent; `
## 五、浮动
### 1、文档流(标准流)
元素自上而下,自左而右,块元素独占一行,行内元素在一行上显示,碰到父集元素的边框换行。
### 2、浮动布局
```css
float: left | right /*浮动方向*/
```
> **特点:**
> 1.元素浮动之后不占据原来的位置(脱标)
> 2.浮动的盒子在一行上显示
### 3、浮动的作用
- 文本绕图

- 制作导航(经常使用)
> 把无序列表 ul li 浮动起来做成的导航。
- 网页布局

### 4、清除浮动
清除浮动不是不用浮动,清除浮动产生的问题。
> 问题:当父盒子没有定义高度,嵌套的盒子浮动之后,下边的元素发生位置错误(占据父盒子的位置)。
#### 方法一
**额外标签法**:在最后一个浮动元素后添加标签。
```css
clear: left | right | both /*用的最多的是clear:both;*/
```

#### 方法二
给浮动元素的父集元素使用`overflow:hidden;`

> 注意:如果有内容出了盒子,不能使用这个方法。
#### 方法三(推荐使用)
伪元素清除浮动。

> : after 相当于在当前盒子后加了一个盒子。
#### 清除浮动总结
- 给父元素高度,缺点:高度无法自适应
- 父元素加 overflow:hidden; 缺点:超出会被隐藏
- 父元素加定位,absolute/fixed,缺点:脱离文档流。
- 父元素加浮动,缺点:可能父元素的父元素继续塌陷
- 父元素加inline-block,缺点:行内块的缺点。
- 浮动元素的最后加一个额外标签,标签使用clear:both; 缺点:结果冗余
- 万能清除法,伪元素清除浮动。
```css
content: ".";
display: block;
height: 0;
visibility: hidden;
clear:both;
overflow: hidden;
```
| Daotin/Web/02-CSS/01-CSS基础/03-链接伪类、背景、行高、盒子模型、浮动.md/0 | {
"file_path": "Daotin/Web/02-CSS/01-CSS基础/03-链接伪类、背景、行高、盒子模型、浮动.md",
"repo_id": "Daotin",
"token_count": 5965
} | 10 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>京东(JD.com)</title>
<link rel="stylesheet" href="css/base.css">
<link rel="stylesheet" href="css/index.css">
<link rel="icon" href="images/favicon.ico">
</head>
<body>
<!--兵马未动粮草先行: 先把注释写好-->
<!--site-nav部分start-->
<div class="site-nav">
<div class="w">
<div class="fl">
<div class="site-nav-send">
送至:北京
<i><s>◇</s></i>
</div>
</div>
<div class="fr">
<ul>
<li><a href="#">你好,请登录</a>
<a href="#" class="col-red">免费注册</a>
</li>
<li class="line"></li>
<li><a href="#">我的订单</a></li>
<li class="line"></li>
<li class="later">
<a href="#">我的京东</a>
<i><s>◇</s></i>
</li>
<li class="line"></li>
<li><a href="#">京东会员</a></li>
<li class="line"></li>
<li><a href="#">企业采购</a></li>
<li class="line"></li>
<li class="later tel">
<span></span>
<a href="#">手机京东</a>
<i><s>◇</s></i>
</li>
<li class="line"></li>
<li class="later">
关注京东
<i><s>◇</s></i>
</li>
<li class="line"></li>
<li class="later">
客户服务
<i><s>◇</s></i>
</li>
<li class="line"></li>
<li class="later">
网站导航
<i><s>◇</s></i>
</li>
</ul>
</div>
</div>
</div>
<!--site-nav部分end-->
<!--top-banner部分start-->
<div class="top-banner" id="topBanner">
<div class="w tb">
<a href="#"><img src="images/top-banner2.jpg" alt=""></a>
<a href="#" class="close-banner" id="closeBanner"></a>
</div>
</div>
<!--top-banner部分end-->
<!--title-nav部分start-->
<div class="clearfix w">
<div class="logo">
<img src="images/logo.png" alt="">
</div>
<div class="search">
<input type="text" value="等你下课">
<button>搜索</button>
</div>
<div class="shop-car">
<a href="#">我的购物车</a>
<i class="icon1"></i>
<i class="icon2">></i>
<i class="icon3">8</i>
</div>
<div class="index">
<a href="#" class="col-red">周杰伦</a>
<a href="#">七里香</a>
<a href="#">黑色毛衣</a>
<a href="#">一路向北</a>
<a href="#">枫</a>
<a href="#">霍元甲</a>
<a href="#">白色风车</a>
<a href="#">浪漫手机</a>
<a href="#">搁浅</a>
</div>
</div>
<!--title-nav部分end-->
<!--shortcut-nav部分start-->
<div class="shortcut-nav">
<div class="w">
<div class="shortcut-nav-menu">
<div class="shortcut-nav-menu-all">
<a href="#">全部商品分类</a>
</div>
<div class="shortcut-nav-menu-one">
<div>
<h3>
<a href="#">家用电器</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">手机、数码、京东通信</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">电脑、办公</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">家居、家具,家装、厨具</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">运动户外、钟表</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">家用电器</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">手机、数码、京东通信</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">电脑、办公</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">家居、家具,家装、厨具</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">运动户外、钟表</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">家用电器</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">手机、数码、京东通信</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">电脑、办公</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">家居、家具,家装、厨具</a>
</h3>
<i>></i>
</div>
<div>
<h3>
<a href="#">运动户外、钟表</a>
</h3>
<i>></i>
</div>
</div>
</div>
<div class="shortcut-nav-items">
<ul>
<li><a href="#">服装城</a></li>
<li><a href="#">美妆馆</a></li>
<li><a href="#">京东超市</a></li>
<li><a href="#">生鲜</a></li>
<li><a href="#">全球购</a></li>
<li><a href="#">闪购</a></li>
<li><a href="#">团购</a></li>
<li><a href="#">拍卖</a></li>
<li><a href="#">金融</a></li>
</ul>
</div>
<div class="shortcut-nav-pic">
<a href="#"><img src="images/img2.jpg" alt=""></a>
</div>
</div>
</div>
<!--shortcut-nav部分end-->
<!--sub-banner部分start-->
<div class="sub-banner">
<a href="#"></a>
</div>
<!--sub-banner部分end-->
<!--main部分start-->
<div class="w main clearfix">
<div class="main-slide">
<a href="#">
<img src="images/slide.jpg" alt="">
</a>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<div class="arrow">
<a class="arrow-left" href="#"><</a>
<a class="arrow-right" href="#">></a>
</div>
</div>
<div class="main-news">
<div class="main-news-top">
<div class="main-news-top-faster">
<div class="main-news-top-faster-more">
<h2>京东快报</h2>
<a href="#">
更多 >
</a>
</div>
<div class="main-news-top-faster-content">
<ul>
<li><a href="#"><span>[花海]</span>能不能给我一首歌的时间</a></li>
<li><a href="#"><span>[花海]</span>能不能给我一首歌的时间</a></li>
<li><a href="#"><span>[花海]</span>能不能给我一首歌的时间</a></li>
<li><a href="#"><span>[花海]</span>能不能给我一首歌的时间</a></li>
<li><a href="#"><span>[花海]</span>能不能给我一首歌的时间</a></li>
</ul>
</div>
</div>
<div class="main-news-top-money">
<ul>
<li><a href="#"><i class="main-news-top-money-pic1"></i>多热</a></li>
<li><a href="#"><i class="main-news-top-money-pic2"></i>烈的</a></li>
<li><a href="#"><i class="main-news-top-money-pic3"></i>白羊</a></li>
<li><a href="#"><i class="main-news-top-money-pic4"></i>多善</a></li>
<li><a href="#"><i class="main-news-top-money-pic5"></i>良多</a></li>
<li><a href="#"><i class="main-news-top-money-pic6"></i>抽象</a></li>
<li><a href="#"><i class="main-news-top-money-pic7"></i>多完</a></li>
<li><a href="#"><i class="main-news-top-money-pic8"></i>美的</a></li>
<li><a href="#"><i class="main-news-top-money-pic9"></i>她啊</a></li>
<li><a href="#"><i class="main-news-top-money-pic10"></i>却是</a></li>
<li><a href="#"><i class="main-news-top-money-pic11"></i>下落</a></li>
<li>
<a href="#"><i class="main-news-top-money-pic12"></i>不详</a>
<span></span>
</li>
</ul>
</div>
</div>
<a href="#">
<img src="images/pic.png" alt="">
</a>
</div>
</div>
<!--main部分end-->
<!--footer部分start-->
<div class="footer">
<div class="footer-top">
<div class="footer-top-slogan">
<span class="footer-top-slogan-icon footer-top-slogan-icon1"><img src="images/slogan1.png" alt=""></span>
<span class="footer-top-slogan-icon footer-top-slogan-icon2"><img src="images/slogan2.png" alt=""></span>
<span class="footer-top-slogan-icon footer-top-slogan-icon3"><img src="images/slogan3.png" alt=""></span>
<span class="footer-top-slogan-icon footer-top-slogan-icon4"><img src="images/slogan4.png" alt=""></span>
</div>
<div class="w footer-top-shop clearfix">
<dl>
<dt><a href="#">购物指南</a></dt>
<dd><a href="#">购物流程</a></dd>
<dd><a href="#">会员介绍</a></dd>
<dd><a href="#">生活旅行团购</a></dd>
<dd><a href="#">常见问题</a></dd>
<dd><a href="#">大家电</a></dd>
<dd><a href="#">联系客服</a></dd>
</dl>
<dl>
<dt><a href="#">购物指南</a></dt>
<dd><a href="#">购物流程</a></dd>
<dd><a href="#">会员介绍</a></dd>
<dd><a href="#">生活旅行团购</a></dd>
<dd><a href="#">常见问题</a></dd>
<dd><a href="#">大家电</a></dd>
<dd><a href="#">联系客服</a></dd>
</dl>
<dl>
<dt><a href="#">购物指南</a></dt>
<dd><a href="#">购物流程</a></dd>
<dd><a href="#">会员介绍</a></dd>
<dd><a href="#">生活旅行团购</a></dd>
<dd><a href="#">常见问题</a></dd>
<dd><a href="#">大家电</a></dd>
<dd><a href="#">联系客服</a></dd>
</dl>
<dl>
<dt><a href="#">购物指南</a></dt>
<dd><a href="#">购物流程</a></dd>
<dd><a href="#">会员介绍</a></dd>
<dd><a href="#">生活旅行团购</a></dd>
<dd><a href="#">常见问题</a></dd>
<dd><a href="#">大家电</a></dd>
<dd><a href="#">联系客服</a></dd>
</dl>
<dl class="last-dl">
<dt><a href="#">购物指南</a></dt>
<dd><a href="#">购物流程</a></dd>
<dd><a href="#">会员介绍</a></dd>
<dd><a href="#">生活旅行团购</a></dd>
<dd><a href="#">常见问题</a></dd>
<dd><a href="#">大家电</a></dd>
<dd><a href="#">联系客服</a></dd>
</dl>
<div class="map">
<h3>京东自营覆盖区县</h3>
<p>京东已向全国2630个区县提供自营配送服务,支持货到付款,POS机刷卡和售后上门服务。</p>
<a href="#">查看详情></a>
</div>
</div>
</div>
<div class="w footer-bottom">
<div class="footer-bottom-links">
<a href="#">告白气球</a>|
<a href="#">告白气球</a>|
<a href="#">告白气球</a>|
<a href="#">告白气球</a>|
<a href="#">告白气球</a>|
<a href="#">告白气球</a>|
<a href="#">告白气球</a>|
<a href="#">告白气球</a>|
<a href="#">告白气球</a>|
<a href="#">告白气球</a>|
<a href="#">告白气球</a>|
<a href="#">告白气球</a>
</div>
<div class="footer-bottom-copyright">
<img src="images/gh.png" alt=""> 窗外的麻雀 在电线杆上多嘴 你说这一句 很有夏天的感觉 手中的铅笔 在纸上来来回回 <br>
我用几行字形容你是我的谁 秋刀鱼的滋味 猫跟你都想了解 初恋的香味就这样被我们寻回 那温暖的阳光 <br>
像刚摘的鲜艳草莓 你说你舍不得吃掉这一种感觉
</div>
<div class="footer-bottom-pic">
<a href="#"><img src="images/img1.png" alt=""></a>
<a href="#"><img src="images/img1.png" alt=""></a>
<a href="#"><img src="images/img1.png" alt=""></a>
<a href="#"><img src="images/img1.png" alt=""></a>
<a href="#"><img src="images/img1.png" alt=""></a>
<a href="#"><img src="images/img1.png" alt=""></a>
</div>
</div>
</div>
<!--footer部分end-->
<script>
var closeBanner = document.getElementById("closeBanner");
var topBanner = document.getElementById("topBanner");
closeBanner.onclick = function (ev) {
topBanner.className = "hide";
}
</script>
</body>
</html> | Daotin/Web/02-CSS/03-案例/01-仿JD静态首页/index.html/0 | {
"file_path": "Daotin/Web/02-CSS/03-案例/01-仿JD静态首页/index.html",
"repo_id": "Daotin",
"token_count": 11342
} | 11 |
## 一、为元素绑定多个事件
**前导:**如果一个按钮绑定了多个点击事件,那么点击按钮的时候只会执行最后一个点击事件,前面的点击事件都被覆盖了。那么如何为一个按钮绑定多个相同的事件,并且每个事件都会执行呢?
### 1、为元素绑定多个事件
```html
<body>
<input type="button" value="按钮1" id="btn1">
<input type="button" value="按钮2" id="btn2">
<!-- <div id="dv"></div> -->
<script src="common.js"></script>
<script>
// 参数有3个
// 参数1:事件的类型(事件的名字),不要on
// 参数2:事件处理函数(命名函数或者匿名函数)
// 参数3:false
// 兼容性:chrome,firefox支持,IE8不支持
my$("btn1").addEventListener("click", function() {
alert("1");
},false)
my$("btn1").addEventListener("click", function() {
alert("2");
},false)
my$("btn1").addEventListener("click", function() {
alert("3");
},false)
// 参数有2个
// 参数1:事件的类型(事件的名字),要on
// 参数2:事件处理函数(命名函数或者匿名函数)
// 兼容性:chrome,firefox不支持,IE8支持
my$("btn2").attachEvent("onclick", function() {
alert("4");
});
my$("btn2").attachEvent("onclick", function() {
alert("5");
});
my$("btn2").attachEvent("onclick", function() {
alert("6");
});
</script>
</body>
```
> 绑定事件的方式:
>
> **addEventListener**: chrome,firefox支持,IE8不支持
>
> **attachEvent**: chrome,firefox不支持,IE8支持
### 2、绑定事件兼容代码
```html
<body>
<input type="button" value="按钮" id="btn">
<script src="common.js"></script>
<script>
// 为任意元素添加任意事件
function addAnyEventListener(element, type, func) {
if(element.addEventListener) {
element.addEventListener(type, func, false);
} else if(element.attachEvent) {
element.attachEvent("on"+type, func);
} else {
element["on"+type] = func;
}
}
addAnyEventListener(my$("btn"), "click", function() {
console.log("事件1");
});
addAnyEventListener(my$("btn"), "click", function() {
console.log("事件2");
});
addAnyEventListener(my$("btn"), "click", function() {
console.log("事件3");
});
</script>
</body>
```
>`my("dv").onclick == my$("dv")["onclick"]`
### 3、绑定事件的区别
- 方法名不同;
- 参数个数不同,addEventListener有三个参数,attachEvent有两个参数;
- addEventListener中事件的类型没有 on,attachEvent中事件的类型有on;
- chrome,firefox 支持 addEventListener ,IE8不支持;
chrome,firefox 不支持 attachEvent ,IE8支持;
- 事件中的 this 不同,addEventListener 中的 this 是当前绑定的对象;
attachEvent 中的 this 是 window。
## 二、为元素解绑事件
### 1、解绑方式
- 方式一
如果使用 `元素.onclick = function(){};` 的方式绑定对象的话,解绑的方式为 `元素.onclick = null;`
- 方式二
如果使用 `元素.addEventListener("click", f1, false);` 的方式绑定对象的话,解绑方式为 `元素.removeEventListener("click", f1, false);`
> 注意:这里面不能使用匿名函数,因为需要同一个事件处理函数,而两个匿名函数是两个不同的函数,所以需要使用命名函数。
- 方式三
如果使用 `元素.attachEvent("onclick", f1);` 的方式绑定对象的话,解绑方式为 `元素.detachEvent("onclick", f1);`
### 2、解绑事件兼容代码
```js
// 为任意元素绑定任意事件
function addAnyEventListener(element, type, func) {
if(element.addEventListener) {
element.addEventListener(type, func, false);
} else if(element.attachEvent) {
element.attachEvent("on"+type, func);
} else {
element["on"+type] = func;
}
}
// 为任意元素解绑任意事件
function removeAnyEventListener(element, type, funcName) {
if(element.removeEventListener) {
element.removeEventListener(type, funcName, false);
} else if(element.detachEvent) {
element.detachEvent("on"+type, funcName);
} else {
element["on"+type] = null;
}
}
```
示例:
```html
<body>
<input type="button" value="按钮" id="btn1">
<input type="button" value="按钮" id="btn2">
<script src="common.js"></script>
<script>
function f1() {
console.log("第一个");
}
function f2() {
console.log("第二个");
}
addAnyEventListener(my$("btn1"), "click", f1);
addAnyEventListener(my$("btn1"), "click", f2);
my$("btn2").onclick = function () {
removeAnyEventListener(my$("btn1"), "click", f1);
}
</script>
</body>
```
| Daotin/Web/03-JavaScript/02-DOM/06-元素绑定解绑事件.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/02-DOM/06-元素绑定解绑事件.md",
"repo_id": "Daotin",
"token_count": 2886
} | 12 |
## 一、同步请求与异步请求
**同步请求:**在用户进行请求发送之后,浏览器会一直等待服务器的数据返回,如果网络延迟比较高,浏览器就一直卡在当前界面,直到服务器返回数据才可进行其他操作。
**异步请求:**在用户进行请求发送之后,浏览器可以自由操作页面中其他的元素,当服务器放回数据的时候,才触发相应事件,对返回的数据进行操作。
如果将 Ajax 请求改为同步请求的话:
1、界面会卡顿,卡顿事件取决于网络速度;
2、xhr.onreadystatechange 的回调函数不会执行,因为在 xhr.send() 之后,xhr.readyState 就为 4 了,所以数据的处理,直接跟在xhr.send() 之后就可以了。
### 1、异步的底层原理
js 中的异步实现原理是单线程+事件队列。js 的代码执行是单线程的,单线程的意思是代码从上到下按照顺序执行,而事件队列存储了一些回调函数,当 js 从上往下执行的时候,遇到回调函数就将其放到事件队列,在所有 js 代码执行完成之后处于空闲状态时,才会去事件队列看有没有回调函数达到触发条件,有的话就执行,没有的话就继续闲着。
**Ajax 的四步操作中,同步和异步的区别:**
如果是异步请求,在 send 的时候,会调用浏览器进行网络数据的请求,send 就执行完了,接着将第四步的回调函数存储在事件队列里面,浏览器数据请求完了,readyState 状态发生变化,触发第四步回调函数的执行。
而在同步请求中, send 时是自己进行网络数据的请求,这个时候非得请求到数据,才会接着将第四步的回调函数存储在事件队列里面,所以如果网络延时页面就会卡死,在 send 过后接受到数据的时候 readyState 已经为4了,不会再变化,所以第四步的回调函数不会执行。
## 二、数据格式
什么是数据格式?
数据格式就是通过一定的规范组织起来,叫做数据格式。
### 1、XML 数据格式
XML 数据格式是将数据以标签的方式进行组装,必须以 `<? xml version="1.0" encoding="utf-8" ?>` 开头,标签必须成对出现,也就是有开始标签就一定要有结束标签。
```xml
<? xml version="1.0" encoding="utf-8" ?>
<students>
<student>
<name>张三</name>
<age>18</age>
<sex>男</sex>
</student>
</students>
```
缺点:体积太大,元数据(描述数据的数据)太多,解析不方便,目前使用很少。
### 2、json 数据格式
json 数据格式通过 key-value 的方式组装。
```json
{
"student" : [
{
"name": "张三",
"age": "18",
"sex": "男"
},
{
"name": "李四",
"age": "23",
"sex": "女"
}
]
}
```
优点:体积小,传输快,解析方便。
### 3、案例:获取图书信息
**接口文档:**
| 地址 | /server/getBooks/php |
| ------ | -------------------- |
| 作用描述 | 获取图书信息 |
| 请求类型 | get 请求 |
| 参数 | 无 |
| 返回数据格式 | xml 格式 |
| 返回数据说明 | 如下 |
```
<?xml version="1.0" encoding="utf-8" ?>
<booklist>
<book>
<name>三国演义</name>
<author>罗贯中</author>
<desc>一个杀伐纷争的年代</desc>
</book>
<book>
<name>水浒传</name>
<author>施耐庵</author>
<desc>108条好汉的故事</desc>
</book>
<book>
<name>西游记</name>
<author>吴承恩</author>
<desc>佛教与道教斗争</desc>
</book>
<book>
<name>红楼梦</name>
<author>曹雪芹</author>
<desc>一个封建王朝的缩影</desc>
</book>
</booklist>
```
**源代码:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>书籍列表</title>
<style>
div{
width: 800px;
margin: 20px auto;
}
table{
width: 800px;
margin: 20px auto;
border-collapse: collapse;
}
th{
background-color: #0094ff;
color:white;
font-size: 16px;
padding: 5px;
text-align: center;
border: 1px solid black;
}
td{
padding: 5px;
text-align: center;
border: 1px solid black;
}
</style>
<script>
window.onload = function () {
var xhr = new XMLHttpRequest();
xhr.open("get", "./server/getBooks.php", true);
xhr.send(null);
xhr.onreadystatechange = function () {
if(this.readyState == 4) {
if(this.status = 200) {
var booklists = this.responseXML.getElementsByTagName("booklist")[0].getElementsByTagName("book");
for(var i=0; i<booklists.length; i++) {
var name = booklists[i].getElementsByTagName("name")[0].textContent;
var author = booklists[i].getElementsByTagName("author")[0].textContent;
var desc = booklists[i].getElementsByTagName("desc")[0].textContent;
var trObj = document.createElement("tr");
trObj.innerHTML = "<td>"+name+"</td><td>"+author+"</td><td>"+desc+"</td>";
document.getElementsByTagName("table")[0].appendChild(trObj);
}
}
}
};
};
</script>
</head>
<body>
<div>
<table>
<tr>
<th>书名</th>
<th>作者</th>
<th>描述</th>
</tr>
<!-- <tr>
<td>三国演义</td>
<td>罗贯中</td>
<td>一个杀伐纷争的年代</td>
</tr> -->
</table>
</div>
</body>
</html>
```
> XML 数据的格式主要是通过:getElementsByTagName 来获取的。
### 4、案例:获取学生信息
**接口文档:**
| 地址 | /server/getStudents/php |
| ------ | ----------------------- |
| 作用描述 | 获取学生信息 |
| 请求类型 | get 请求 |
| 参数 | 无 |
| 返回数据格式 | json 格式 |
| 返回数据说明 | 如下 |
```json
[
{
"name":"张三",
"age":"18",
"sex":"男"
}
]
```
**源代码:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生列表</title>
<style>
div{
width: 800px;
margin: 20px auto;
}
table{
width: 800px;
margin: 20px auto;
border-collapse: collapse;
}
th{
background-color: #0094ff;
color:white;
font-size: 16px;
padding: 5px;
text-align: center;
border: 1px solid black;
}
td{
padding: 5px;
text-align: center;
border: 1px solid black;
}
</style>
<script>
window.onload = function () {
var xhr = new XMLHttpRequest();
xhr.open("get", "./server/getStudents.php", true);
xhr.send(null);
xhr.onreadystatechange = function () {
if(this.readyState == 4) {
if(this.status = 200) {
var jsonObj = JSON.parse(this.responseText);
for(var i=0; i<jsonObj.length; i++) {
var name = jsonObj[i].name;
var age = jsonObj[i].age;
var sex = jsonObj[i].sex;
var trObj = document.createElement("tr");
trObj.innerHTML = "<td>"+name+"</td><td>"+age+"</td><td>"+sex+"</td>";
document.getElementsByTagName("table")[0].appendChild(trObj);
}
}
}
};
};
</script>
</head>
<body>
<div>
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
<!-- <tr>
<td>张三</td>
<td>20</td>
<td>男</td>
</tr> -->
</table>
</div>
</body>
</html>
```
> 只需要将获取的 responseText 转化为 json 格式的对象,使用`JSON.parse(this.responseText);`
| Daotin/Web/06-Ajax/08-同步异步请求,数据格式.md/0 | {
"file_path": "Daotin/Web/06-Ajax/08-同步异步请求,数据格式.md",
"repo_id": "Daotin",
"token_count": 4691
} | 13 |
## 一、touch事件的缺陷
我们在上面《页面分类》的项目中,对 tap 事件的处理使用的是 touch 事件处理的,因为如果使用 click 事件的话,总会有延时。
但是呢,touch 事件并不是完美的,不管是我们自己封装的 tap 事件,还是 zepto 自带的 tap 事件,在移动端都有一个致命的缺陷,就是“**点透**”。
**什么是“点透”呢?**
假如有两个盒子,盒子A和盒子B,如果盒子A在盒子B的上面,当我们使用 tap 事件点击盒子A的时候,盒子B会触发 click 事件,这就是点透。

触发这两个事件的顺序是 tap 事件,然后是 click 事件。因为 tap 事件内部是 touch 事件处理的,而 touch 事件是先于 click 事件触发的。
这个时候,我们既想无延时,又不想触发点透效果,而且有的时候,我们希望我们的网页不仅可以在移动端访问,在 PC 模式下也可以访问,但是 tap 事件只能在移动端使用,所以只能用 click 事件,但是 click 又有延时,怎么办呢?
我们知道, touch 事件只能在移动端使用,这个我们无法改变,所以我们只能改变延时的问题,于是我们就引入了 **"fastclick.js"** 库文件,解决 click 的延时问题。
**使用方式:**
1、引入 fastclick.js 文件。
2、在 script 中加入以下函数:
原生 js 的话,加入:
```js
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
// document.body 表示整个body下的所有元素都是用fastclick效果,可以修改。
FastClick.attach(document.body);
}, false);
}
```
jQuery 或 Zepto 的话:
```js
$(function() {
FastClick.attach(document.body);
});
```
3、正常使用 `元素.addEventListener("click", function(){})` 或者 `元素.on("click", function(){})` ,来使用改装过后的 click 事件,这个 click 事件没有延时。
## 二、移动端的一些常用插件
见识到 fastclick 插件的好处之后,我们就挖掘出了更多好用的插件,可以大大提高我们开发的效率。
### 1、iScroll
以下为官方介绍:
iScroll是一个高性能,资源占用少,无依赖,多平台的 javascript **滚动** 插件。
它可以在桌面,移动设备和智能电视平台上工作。它一直在大力优化性能和文件大小以便在新旧设备上提供最顺畅的体验。
iScroll不仅仅是 滚动。它可以处理任何需要与用户进行移动交互的元素。在你的项目中包含仅仅4kb大小的iScroll,你的项目便拥有了滚动,缩放,平移,无限滚动,视差滚动,旋转功能。给它一个扫帚它甚至能帮你打扫办公室。
即使平台本身提供的滚动已经很不错,iScroll可以在此基础上提供更多不可思议的功能。具体来说:
细粒度控制滚动位置,甚至在滚动过程中。你总是可以获取和设置滚动器的x,y坐标。
动画可以使用用户自定义的擦出功能(反弹'bounce',弹性'elastic',回退'back',...)。
你可以很容易的挂靠大量的自定义事件(onBeforeScrollStart, *
开箱即用的多平台支持。从很老的安卓设备到最新的iPhone,从Chrome浏览器到IE浏览器。
API:http://caibaojian.com/iscroll-5/
**使用方式:**
1、希望你的结构如下,但是不限定标签(下面的 ul 可以改为 div,li 可以改为 p 等,不限定标签类型)。
```
<div id="wrapper">
<ul>
<li>...</li>
<li>...</li>
...
</ul>
</div>
```
2、在 script 标签中初始化 iScroll。
```js
var wrapper = document.getElementById('wrapper');
var myScroll = new IScroll(wrapper);
```
如果是 jQuery 的话更简单了,一句话:
```js
var myScroll = new IScroll(".wrapper");
```
3、如果想实现像滚轮,显示滚动条等效果,可以在初始化的时候,将这些需求作为对象,填入第二个参数中,比如,增加滚轮上下滚动操作和显示滚动条的效果:
```js
var myScroll = new IScroll(".wrapper", {
mouseWheel: true, // 使用滚轮
scrollbars: true // 显示滚动条
});
```
如此简单三步操作,就可以轻松实现你想要的功能。
### 2、swipe
swipe.js 是一个比较有名的触摸滑动插件,它能够处理内容滑动,支持自定义选项,你可以让它自动滚动,控制滚动间隔,返回回调函数等。经常作为**轮播图**使用。
**使用方法:**
1、引入 swipe.js 文件
2、希望你的 html 结构为(不限定标签名称):
```html
<div id='slider' class='swipe'>
<div class='swipe-wrap'>
<div></div>
<div></div>
<div></div>
</div>
</div>
```
3、对其格式进行设定(固定写法,最好不要修改,当然类名称需要修改)
```css
.swipe {
overflow: hidden;
visibility: hidden;
position: relative;
}
.swipe-wrap {
overflow: hidden;
position: relative;
}
.swipe-wrap > div {
float:left;
width:100%;
position: relative;
}
```
3、在 script 中进行初始化操作:
```js
window.mySwipe = Swipe(document.getElementById('slider'));
```
4、如果你想要自动轮播,滑动等操作,需要在初始化的第二个参数中,引入一个对象,比如:
```js
window.mySwipe = new Swipe(document.getElementById('slider'), {
startSlide: 2, // 默认显示第二张图片
speed: 400, // 过渡400ms
auto: 3000, // 轮播间隔 2s
continuous: true, // 循环轮播(默认开启)
disableScroll: false, // 禁止滑动(默认关闭)
stopPropagation: false,
callback: function(index, elem) {},
transitionEnd: function(index, elem) {}
});
```
5、当然你还可以在 PC 上使用左右两个按钮来上一张下一张翻页。swipe 会提供 `next()` , `prev()` 等函数来实现上一张下一张翻页。比如:
```js
document.getElementById('btn1').onclick = function(){
window.mySwipe.prev(); // 调用系统的prev()方法
};
document.getElementById('btn2').onclick = function(){
window.mySwipe.next(); // 调用系统的next()方法
};
```
### 3、swiper
swiper 与 swipe 类似,都可以提供轮播触摸滑动的效果,只不过 swiper 能够提供的特效更多,更加炫酷,相应的体积也更大。
使用说明: 参考链接:<http://www.swiper.com.cn/usage/index.html>
需要注意的是,swiper 不同于 swipe,它也是结构固定,不限标签的,唯一的区别是类样式的名称是不可改变的。因为它引入了库文件的 css 样式。所以最好不要改变类样式的名称。具体的内容可以参考官网,有很多详细的使用说明和特效演示。
临时Tips:`overflow:hidden` 可以让子元素浮动的父盒子由高度为0,到自动伸缩。
| Daotin/Web/07-移动Web开发/05-touch事件的缺陷,iScroll,swiper.md/0 | {
"file_path": "Daotin/Web/07-移动Web开发/05-touch事件的缺陷,iScroll,swiper.md",
"repo_id": "Daotin",
"token_count": 4178
} | 14 |
## 1、案例要求
利用响应式布局,实现微金所页面结构。
## 2、不同屏幕尺寸布局
### 整体样式

### 中大屏幕下样式

### 小屏幕下样式

### 超小屏幕(移动端)下样式

## 3、代码结构

## 4、页面结构
页面结构主要分8大块:
- 头部块
- 导航条
- 轮播图
- 信息块
- 预约块
- 产品块
- 新闻块
- 合作块
## 5、源码
相关源代码已放置github:https://github.com/Daotin/Web/blob/master/Code/src/11/wjs.zip
### index.html 文件
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>微金所</title>
<link href="./lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- 在线字体图标文件 -->
<link href="./lib/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="./css/common.css">
<link rel="stylesheet" href="./css/wjs-index.css">
</head>
<body>
<!-- 头部块开始 -->
<header class="wjs-header hidden-sm hidden-xs">
<div class="container">
<div class="row">
<!-- 在xs sm下是不显示的,所以没必要写 -->
<div class="col-md-2">
<a href="javascript:;" class="code">
<span class="fa fa-mobile fa-lg"></span>
<span>手机微金所</span>
<span class="fa fa-angle-down fa-lg"></span>
<img src="./images/code.jpg" alt="">
</a>
</div>
<div class="col-md-5">
<span class="fa fa-phone"></span>
<a href="javascript:;">4006-89-4006(服务时间:9:00~21:00) 联系在线客服</a>
</div>
<div class="col-md-2">
<a href="javascript:;">常见问题</a>
<a href="javascript:;">财富登录</a>
</div>
<div class="col-md-3">
<button type="button" class="btn btn-danger">免费注册</button>
<button type="button" class="btn btn-link">登录</button>
</div>
</div>
</div>
</header>
<!-- 头部块结束 -->
<!-- 导航条开始 -->
<nav class="navbar navbar-default wjs-nav">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<span class="wjs_icon wjs_icon_logo"></span>
<span class="wjs_icon wjs_icon_text"></span>
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav hidden-sm">
<li class="active">
<a href="#">我要投资
<span class="sr-only">(current)</span>
</a>
</li>
<li>
<a href="#">我要借贷</a>
</li>
<li>
<a href="#">平台介绍</a>
</li>
<li>
<a href="#">新手专区</a>
</li>
<li>
<a href="#">最新动态</a>
</li>
<li>
<a href="#">微平台</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#">个人中心</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- 导航条结束 -->
<!-- 轮播图开始 -->
<div class="wjs-banner">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- 小白点 -->
<ol class="carousel-indicators">
<!-- data-target="#carousel-example-generic":自定义属性,给哪个id的轮播图加小白点 -->
<!-- data-slide-to="0":第几个小白点 -->
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
<li data-target="#carousel-example-generic" data-slide-to="3"></li>
</ol>
<!-- 轮播图主体部分 -->
<div class="carousel-inner" role="listbox">
<!-- HTML5 增加了一项新功能是 自定义数据属性 ,也就是 data-* 自定义属性。
jQuery中可以使用data()方法获取自定义属性的值 -->
<div class="item active" data-large-image="./images/slide_01_2000x410.jpg" data-small-image="./images/slide_01_640x340.jpg">
<!-- 这里面的轮播图片使用jq动态添加,否则加大小图的话,加载的时候,不管是大屏幕还是小屏幕
大小图都会加载,浪费流量 -->
<!-- 每张轮播图的图片说明,这里不需要 -->
<!-- <div class="carousel-caption">
...
</div> -->
<a href="">
<img src="" alt="">
</a>
</div>
<div class="item" data-large-image="./images/slide_02_2000x410.jpg" data-small-image="./images/slide_02_640x340.jpg"></div>
<div class="item" data-large-image="./images/slide_03_2000x410.jpg" data-small-image="./images/slide_03_640x340.jpg"></div>
<div class="item" data-large-image="./images/slide_04_2000x410.jpg" data-small-image="./images/slide_04_640x340.jpg"></div>
</div>
<!-- 左右箭头,点击可切换上下一张 -->
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<!-- 轮播图结束 -->
<!-- 信息块开始 -->
<div class="wjs-info hidden-xs">
<!-- 信息块的制作可以使用bootstrap组件的媒体对象来做 -->
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4">
<a href="javascript:;">
<div class="media">
<span class="media-left wjs_icon wjs_icon_E900"></span>
<div class="media-body">
<h4 class="media-heading">支持交易保障</h4>
<p>银联支持全程保障安全</p>
</div>
</div>
</a>
</div>
<div class="col-sm-6 col-md-4">
<a href="javascript:;">
<div class="media">
<span class="media-left wjs_icon wjs_icon_E900"></span>
<div class="media-body">
<h4 class="media-heading">支持交易保障</h4>
<p>银联支持全程保障安全</p>
</div>
</div>
</a>
</div>
<div class="col-sm-6 col-md-4">
<a href="javascript:;">
<div class="media">
<span class="media-left wjs_icon wjs_icon_E900"></span>
<div class="media-body">
<h4 class="media-heading">支持交易保障</h4>
<p>银联支持全程保障安全</p>
</div>
</div>
</a>
</div>
<div class="col-sm-6 col-md-4">
<a href="javascript:;">
<div class="media">
<span class="media-left wjs_icon wjs_icon_E900"></span>
<div class="media-body">
<h4 class="media-heading">支持交易保障</h4>
<p>银联支持全程保障安全</p>
</div>
</div>
</a>
</div>
<div class="col-sm-6 col-md-4">
<a href="javascript:;">
<div class="media">
<span class="media-left wjs_icon wjs_icon_E900"></span>
<div class="media-body">
<h4 class="media-heading">支持交易保障</h4>
<p>银联支持全程保障安全</p>
</div>
</div>
</a>
</div>
<div class="col-sm-6 col-md-4">
<a href="javascript:;">
<div class="media">
<span class="media-left wjs_icon wjs_icon_E900"></span>
<div class="media-body">
<h4 class="media-heading">支持交易保障</h4>
<p>银联支持全程保障安全</p>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
<!-- 信息块结束 -->
<!-- 预约块开始 -->
<div class="wjs-reverse hidden-xs">
<div class="container">
<div class="row">
<div class="col-sm-9">
<span class="wjs_icon wjs_icon_E906"></span>
<span>现在的 272 人在排队,累计预约交易成功 7571 次</span>
<a href="javascript:;">什么叫预约投标</a>
<a href="javascript:;">立即预约</a>
</div>
<div class="col-sm-3">
<span class="wjs_icon wjs_icon_E905"></span>
<a href="javascript:;">微金所企业宣传片</a>
</div>
</div>
</div>
</div>
<!-- 预约块结束 -->
<!-- 产品块开始 -->
<div class="wjs-product">
<div class="container">
<!-- 手动滑动效果 -->
<div class="tabs-parent">
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">
<a href="#p1" aria-controls="p1" role="tab" data-toggle="tab">特别推荐</a>
</li>
<li role="presentation">
<a href="#p2" aria-controls="p2" role="tab" data-toggle="tab">微投资</a>
</li>
<li role="presentation">
<a href="#p3" aria-controls="p3" role="tab" data-toggle="tab">友金所</a>
</li>
<li role="presentation">
<a href="#p4" aria-controls="p4" role="tab" data-toggle="tab">团贷网</a>
</li>
<li role="presentation">
<a href="#p5" aria-controls="p5" role="tab" data-toggle="tab">懒投资</a>
</li>
<li role="presentation">
<a href="#p6" aria-controls="p6" role="tab" data-toggle="tab">掌游宝</a>
</li>
<li role="presentation">
<a href="#p7" aria-controls="p7" role="tab" data-toggle="tab">英雄联盟</a>
</li>
</ul>
</div>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="p1">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="wjs-pBox active">
<div class="wjs-pLeft">
<p>新手体验1002期</p>
<div class="row">
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
</div>
</div>
<div class="wjs-pRight">
<b>8</b>
<sub>%</sub>
<p>年利率</p>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="wjs-pBox">
<div class="wjs-pLeft">
<p>新手体验1002期</p>
<div class="row">
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
</div>
</div>
<div class="wjs-pRight">
<div class="wjs-pRight-tip">
<span data-toggle="tooltip" data-placement="top" title="微金宝">宝</span>
<span data-toggle="tooltip" data-placement="top" title="北京市">北</span>
</div>
<b>8</b>
<sub>%</sub>
<p>年利率</p>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="wjs-pBox">
<div class="wjs-pLeft">
<p>新手体验1002期</p>
<div class="row">
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
</div>
</div>
<div class="wjs-pRight">
<b>8</b>
<sub>%</sub>
<p>年利率</p>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="wjs-pBox">
<div class="wjs-pLeft">
<p>新手体验1002期</p>
<div class="row">
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
<div class="col-xs-6">
<p>起投金额(元)</p>
<p>0.01万</p>
</div>
</div>
</div>
<div class="wjs-pRight">
<b>8</b>
<sub>%</sub>
<p>年利率</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="p2">2</div>
<div role="tabpanel" class="tab-pane" id="p3">3</div>
<div role="tabpanel" class="tab-pane" id="p4">4</div>
<div role="tabpanel" class="tab-pane" id="p5">5</div>
<div role="tabpanel" class="tab-pane" id="p6">6</div>
<div role="tabpanel" class="tab-pane" id="p7">7</div>
</div>
</div>
</div>
<!-- 产品块结束 -->
<!-- 新闻块开始 -->
<div class="wjs-news">
<div class="container">
<div class="row">
<div class="col-md-2 col-md-offset-2">
<h3 class="wjs_nTitle">全部新闻</h3>
</div>
<div class="col-md-1">
<div class="wjs_newsLine hidden-xs hidden-sm"></div>
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">
<a href="#home" aria-controls="home" role="tab" data-toggle="tab">
<span class="wjs_icon wjs_icon_new01"></span>
</a>
</li>
<li role="presentation">
<a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">
<span class="wjs_icon wjs_icon_new02"></span>
</a>
</li>
<li role="presentation">
<a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">
<span class="wjs_icon wjs_icon_new03"></span>
</a>
</li>
<li role="presentation">
<a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">
<span class="wjs_icon wjs_icon_new04"></span>
</a>
</li>
</ul>
</div>
<div class="col-md-7">
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="home">
<ul class="wjs_newslist">
<li>
<a href="">
<span class="hidden-xs">2016-01-22</span>【微公告】关于海航通宝22期项目募集期延长通知
</a>
</li>
<li>
<a href="">
<span class="hidden-xs">2016-01-22</span>【微动态】世纪佳缘与百合网的投资人首善财富董事长吴正新一行莅临微金所调研指导
</a>
</li>
<li>
<a href="">
<span class="hidden-xs">2016-01-22</span>【微动态】封面人物第六期 ▏万雅泉—— 手写心情的双鱼座美女
</a>
</li>
<li>
<a href="">
<span class="hidden-xs">2016-01-22</span>【微公告】2016年7月11日微金所平台系统升级维护公告
</a>
</li>
<li>
<a href="">
<span class="hidden-xs">2016-01-22</span>【微动态】微金所与前海航交所携手,正式推出安全优质的理财产品—海航金宝!
</a>
</li>
<li>
<a href="">
<span class="hidden-xs">2016-01-22</span>【微动态】微金所七月电脑节,激情狂欢理财好礼送不停!
</a>
</li>
<li>
<a href="">
<span class="hidden-xs">2016-01-22</span>【微还款】一周还款公告2016年7月11日-7月17日
</a>
</li>
</ul>
</div>
<div role="tabpanel" class="tab-pane" id="profile">2</div>
<div role="tabpanel" class="tab-pane" id="messages">3</div>
<div role="tabpanel" class="tab-pane" id="settings">4</div>
</div>
</div>
</div>
</div>
</div>
<!-- 新闻块结束 -->
<!-- 合作块开始 -->
<footer class="wjs-partner">
<div class="container">
<h3>合作伙伴</h3>
<ul>
<li><a href="javascript:;" class="wjs_icon wjs_icon_partner01"></a></li>
<li><a href="javascript:;" class="wjs_icon wjs_icon_partner02"></a></li>
<li><a href="javascript:;" class="wjs_icon wjs_icon_partner03"></a></li>
<li><a href="javascript:;" class="wjs_icon wjs_icon_partner04"></a></li>
<li><a href="javascript:;" class="wjs_icon wjs_icon_partner05"></a></li>
<li><a href="javascript:;" class="wjs_icon wjs_icon_partner06"></a></li>
<li><a href="javascript:;" class="wjs_icon wjs_icon_partner07"></a></li>
<li><a href="javascript:;" class="wjs_icon wjs_icon_partner08"></a></li>
</ul>
</div>
</footer>
<!-- 合作块结束 -->
<script src="./lib/jquery/jquery.min.js"></script>
<script src="./lib/bootstrap/js/bootstrap.min.js"></script>
<script src="./js/iscroll.js"></script>
<script src="./js/wjs-index.js"></script>
</body>
</html>
```
### common.css 文件
```css
/*公共css样式*/
body {
font-family: "Microsoft YaHei", sans-serif;
font-size: 14px;
color: #333;
}
a {
text-decoration: none;
color: #333;
}
a:hover {
text-decoration: none;
color: #333;
}
/*左边距*/
.m_l10 {
margin-left: 10px;
}
/*右边距*/
.m_r10 {
margin-right: 10px;
}
/*自定义字体*/
@font-face {
font-family: 'wjs';
src: url('../fonts/MiFie-Web-Font.eot');
/* IE9*/
src: url('../lib/fonts/MiFie-Web-Font.eot') format('embedded-opentype'), /* IE6-IE8 */
url('../lib/fonts/MiFie-Web-Font.woff') format('woff'), /* chrome、firefox */
url('../lib/fonts/MiFie-Web-Font.ttf') format('truetype'), /* chrome、firefox、opera、Safari, Android, iOS 4.2+*/
url('../lib/fonts/MiFie-Web-Font.svg') format('svg');
/* iOS 4.1- */
}
/*自定义字体使用样式*/
.wjs_icon {
font-family: wjs;
}
/*手机图标对应的编码*/
.wjs_icon_phone::before {
content: "\e908";
}
/*电话图标对应的编码*/
.wjs_icon_tel::before {
content: "\e909";
font-size: 14px;
}
/*wjs logo*/
.wjs_icon_logo::before {
content: "\e920";
}
/*wjs 文本*/
.wjs_icon_text::before {
content: "\e93e";
}
.wjs_icon_new01::before {
content: "\e90e";
}
.wjs_icon_new02::before {
content: "\e90f";
}
.wjs_icon_new03::before {
content: "\e910";
}
.wjs_icon_new04::before {
content: "\e911";
}
.wjs_icon_partner01::before {
content: "\e946";
}
.wjs_icon_partner02::before {
content: "\e92f";
}
.wjs_icon_partner03::before {
content: "\e92e";
}
.wjs_icon_partner04::before {
content: "\e92a";
}
.wjs_icon_partner05::before {
content: "\e929";
}
.wjs_icon_partner06::before {
content: "\e931";
}
.wjs_icon_partner07::before {
content: "\e92c";
}
.wjs_icon_partner08::before {
content: "\e92b";
}
.wjs_icon_partner09::before {
content: "\e92d";
}
.wjs_iconn_E903::before {
content: "\e903";
}
.wjs_icon_E906::before {
content: "\e906";
}
.wjs_icon_E905::before {
content: "\e905";
}
.wjs_icon_E907::before {
content: "\e907";
}
.wjs_icon_E901::before {
content: "\e901";
}
.wjs_icon_E900::before {
content: "\e900";
}
.wjs_icon_E904::before {
content: "\e904";
}
.wjs_icon_E902::before {
content: "\e902";
}
.wjs_icon_E906::before {
content: "\e906";
}
```
### wjs-index.less 文件
```less
@baseColor: #e92322;
/* 头部块 */
.wjs-header {
height: 50px;
line-height: 50px;
border-bottom: 1px solid #ccc;
.row {
height: 100%;
text-align: center;
> div:nth-of-type(-n+3) {
border-right: 1px solid #ccc;
}
.code {
display: block;
position: relative;
> img {
display: none;
position: absolute;
border: 1px solid #ccc;
border-top: none;
left: 50%;
transform: translateX(-50%);
top: 49px;
}
&:hover {
> img {
display: block;
}
}
}
> div:nth-last-of-type(1) {
> .btn-danger {
background-color: @baseColor;
border-color: @baseColor;
}
> .btn {
padding: 3px 15px;
}
> .btn-link {
text-decoration: none;
color: #aaa;
}
}
}
}
/*导航条*/
.wjs-nav {
&.navbar {
margin-bottom: 0;
}
.navbar-brand {
height: 80px;
line-height: 50px;
font-size: 40px;
> span:nth-of-type(1) {
color: @baseColor;
}
> span:nth-of-type(2) {
color: #333;
}
}
.navbar-toggle {
margin-top: 23px;;
}
.navbar-nav {
> li {
height: 80px;
> a {
height: 80px;
line-height: 50px;
font-size: 16px;
&:hover, &:active {
color: #777;
border-bottom: 3px solid @baseColor;
}
}
}
.active {
a,a:hover,a:active {
background-color: transparent;
border-bottom: 3px solid @baseColor;
}
}
}
}
/*轮播图*/
/*
w<768px-移动端:图片会随着屏幕的缩小自动适应--缩小
img的宽度为100%,通过img标签来实现
w>=768px:
图片做为背景,当屏幕宽度变宽的时候,会显示更多的图片的两边区域
1.background-image添加图片
2.添加background-position:center center
3.background-size:cover
*/
.wjs-banner {
.bigImg {
width: 100%;
height: 410px;
/*去除图片基线*/
display: block;
background-position:center center;
background-size: cover;
}
.smallImg {
// width: 100%;
// display: block;
img {
width: 100%;
/*去除图片基线*/
display: block;
}
}
}
/*信息块*/
.wjs-info {
padding: 20px;
.wjs_icon {
font-size: 26px;
}
.row {
> div {
margin: 10px 0;
> a:hover {
color: @baseColor;
}
}
}
}
/*预约块*/
.wjs-reverse {
height: 60px;
line-height: 60px;
border-top: 1px solid #ccc;
border-bottom: 1px solid #ccc;
.wjs_icon {
font-size: 18px;
}
a:hover {
color: @baseColor;
}
.col-sm-9 {
> a:last-of-type {
color: @baseColor;
border-bottom: 1px dashed @baseColor;
}
}
}
/*产品块*/
.wjs-product{
clear: both;
background-color: #eee;
li {
height: 100px;
line-height: 100px;
padding: 0 10px;
> a {
margin: 0;
border: none;
line-height: 50px;
}
a:hover {
border: none;
border-bottom: 3px solid @baseColor;
}
&.active {
> a,a:hover,a:focus{
background-color: transparent;
border: none;
border-bottom: 3px solid @baseColor;
}
}
}
}
/*产品块*/
.wjs-product {
.tabs-parent {
width: 100%;
overflow: hidden;
}
.wjs-pBox {
height: 100%;
background-color: #fff;
margin-top: 20px;
position: relative;
box-shadow: 1px 1px 5px #ccc;
> .wjs-pLeft {
height: 100%;
margin-right: 100px;
padding: 10px 0;
font-size: 12px;
position: relative;
> p {
font-size: 16px;
text-align: center;
}
.row {
margin-left: 0;
margin-right: 0;
> div:nth-of-type(even) {
text-align: right;
}
}
}
> .wjs-pRight {
width: 100px;
height: 100%;
position: absolute;
right: 0;
top: 0;
border-left: 1px dashed #ccc;
text-align: center;
padding-top: 40px;
> .wjs-pRight-tip {
width: 100%;
span {
font-size: 12px;
border-radius: 3px;
cursor: pointer;
}
span:first-of-type {
border: 1px solid @baseColor;
color: @baseColor;
}
span:last-of-type {
border: 1px solid blue;
color: blue;
}
}
> b {
font-size: 40px;
color: @baseColor;
}
> sub {
bottom: 0;
color: @baseColor;
}
&::before, &::after {
content: "";
width: 10%;
height: 10px;
border-radius: 5px;
background-color: #eee;
position: absolute;
left: -5px;
}
&::before {
top: -5px;
}
&::after {
bottom: -5px;
}
}
&.active {
background-color: @baseColor;
.wjs-pLeft {
color: #fff;
&::before {
content: "\e915";
font-family: "wjs";
position: absolute;
left: 0;
top: -4px;
font-size: 26px;
}
}
.wjs-pRight {
b,sub,p {
color: #fff;
}
}
}
}
}
/*新闻块*/
.wjs-news {
padding: 20px;
.wjs_nTitle{
line-height:50px;
font-size: 25px;
border-bottom: 1px solid #ccc;
text-align: center;
position: relative;
&::before{
content: "";
width: 8px;
height: 8px;
border-radius: 4px;
border: 1px solid #ccc;
position: absolute;
bottom: -4px;
right: -8px;
}
}
/*设置li元素间的虚线*/
.wjs_newsLine {
width: 1px;
height: 100%;
position: absolute;
border-left: 1px dashed @baseColor;
left:45px;
top:0;
}
.nav-tabs {
border-bottom: none;
> li {
margin-bottom:60px;
> a {
background-color: #ccc;
width: 60px;
height: 60px;
border: none;
border-radius: 50%;
}
> a:hover {
border: none;
background-color: @baseColor;
}
&.active {
> a {
border: none;
background-color: @baseColor;
}
}
.wjs_icon{
font-size: 30px;
color: #fff;
}
}
> li:last-of-type {
margin-bottom: 0;
}
/*媒体查询设置li元素的样式*/
@media screen and (min-width: 768px) and (max-width: 992px) {
li {
margin: 20px 30px;
}
}
@media screen and (max-width: 768px) {
li {
margin: 20px 0;
width: 25%;
}
}
}
.tab-content {
.wjs_newslist {
list-style: none;
> li {
line-height:60px;
}
}
}
}
/*合作块*/
.wjs-partner {
background-color: #eee;
padding: 20px;
text-align: center;
h3 {
width: 100%;
}
ul {
list-style: none;
display: inline-block;
> li {
float: left;
margin: 0 15px;
}
.wjs_icon {
font-size: 80px;
}
}
}
```
### wjs-index.js 文件
```js
$(function () {
// 获取所有的item元素
var items = $(".carousel-inner .item");
// 当屏幕大小改变的时候,动态创建图片
// triggle函数表示页面在第一次加载的时候,自动触发一次。
$(window).on("resize", function () {
// 判断屏幕的大小,以决定加载大图还是小图
var screenWidth = $(window).width();
// 添加大屏幕的图片
if (screenWidth >= 768) {
// 为每个item添加大图片
items.each(function (index, value) {
// 获取每个item的图片,使用data()获取自定义属性
var imgSrc = $(this).data("largeImage");
// 使用插入小图片的方法不可以,因为路径符号会被解析成空格
$(this).html($('<a href="javascript:;" class="bigImg"></a>').css("backgroundImage", "url('" + imgSrc + "')"));
});
// 添加小屏幕的图片
} else {
// 为每个item添加小图片
items.each(function (index, value) {
// 获取每个item的图片,使用data()获取自定义属性
var imgSrc = $(this).data("smallImage");
$(this).html('<a href="javascript:;" class="smallImg"><img src="' + imgSrc + '"></a>');
});
}
}).trigger("resize");
// 实现滑动轮播效果
// 实现滑动轮播可以可以直接调用插件的点击按钮上下切换的功能
// 获取滑动区域的元素
var carouselInner = $(".carousel-inner");
var carousel = $(".carousel");
var startX, endX;
// 给元素添加touchstart和touchend事件
carouselInner[0].addEventListener("touchstart", function (e) {
startX = e.targetTouches[0].clientX;
});
carouselInner[0].addEventListener("touchend", function (e) {
endX = e.changedTouches[0].clientX;
// endX - startX > 10px 证明往右滑动
if (endX - startX > 10) {
carousel.carousel("prev");
} else if (startX - endX > 10) {
carousel.carousel("next");
}
});
// 产品块的宝,北标签的鼠标悬停效果
$('[data-toggle="tooltip"]').tooltip();
// 设置产品块的标签栏在移动端时可以滑动
var ulProduct = $(".tabs-parent .nav-tabs");
var liProducts = ulProduct.children("li");
var totleWidth = 0;
liProducts.each(function (index, element) {
/*获取宽度的方法的说明:
* width():它只能得到当前元素的内容的宽度
* innerWidth():它能获取当前元素的内容的宽度+padding
* outerWidth():获取当前元素的内容的宽度+padding+border
* outerWidth(true):获取元素的内容的宽度+padding+border+margin*/
totleWidth += $(element).innerWidth();
});
ulProduct.width(totleWidth);
// 使用iScroll插件实现滑动效果
/*使用插件实现导航条的滑动操作*/
var myScroll = new IScroll('.tabs-parent', {
/*设置水平滑动,不允许垂直滑动*/
scrollX: true,
scrollY: false
});
});
```
## 6、代码说明
使用到的技术点:
1. 大面积使用 bootstrap 的 `.container` + `.row` + `.col-xx-xx` 的布局,构成响应式布局结构;
2. 在某些屏幕尺寸下不显示,使用 `hidden-xx`;
3. 字体图标的使用;
4. 导航条样式直接使用 bootstrap 组件中的导航条样式修改而成。
5. 轮播图直接使用 bootstrap js插件下的 Carousel (轮播图)插件。
由于需要轮播图效果:
w<768px-移动端:图片会随着屏幕的缩小自动适应--缩小
实现方式:img的宽度为100%,通过img标签来实现。
w>=768px:
图片做为背景,当屏幕宽度变宽的时候,会显示更多的图片的两边区域
实现方式:
1.background-image添加图片
2.添加background-position:center center;
3.background-size:cover;
所以不能在 html 中直接添加代码的方式,只能通过 js 动态插入图片或背景图的方式。
6. 信息块的制作可以使用 bootstrap 组件的媒体对象来做,实现左边为图标,右边为文字说明的样式;
7. 产品块的制作可以使用 bootstrap js插件下的标签页修改得到,而且为了实现在小屏幕下的滑动效果,引入了
iScroll 插件。
产品块中“宝北”的添加:
- 添加两个文本
- 宝 北 两个字应该是一个整体,所以使用div包含
- 添加两个字之后,不应该破坏之前的元素的布局,所以可以让div进行定位
- 设置div的水平居中,垂直方向的偏移可以使用top实现
- 添加文本的颜色和边框
添加工具提示
- 添加工具提示,可以修改类型为span
> type="button":说明当前工具提示的类型,类型默认是按钮,如果不需要,可以修改为其它任意的元素类型
> data-toggle="tooltip":说明当前插件/组件是一工具提示
> data-placement="top":提示出现的位置
> title="提示文本"
- 工具提示会默认的生成一个新的div标签,只不过默认的文本显示会换行,原因是新添加的标签的宽度是参照父容器的
,应该将父容器div的宽度设置为100%。
- 记得对工具提示进行初始化 `$('[data-toggle="tooltip"]').tooltip();`
8. 新闻块同产品块一样,也是使用 bootstrap js插件下的标签页修改得到,值得注意的是,在不同屏幕大小下,的显示方式不同,所以在css样式中使用到了媒体查询的方式。
## 7、案例演示

| Daotin/Web/07-移动Web开发/案例01:微金所官网首页.md/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例01:微金所官网首页.md",
"repo_id": "Daotin",
"token_count": 29854
} | 15 |
$(function () {
// 1.在开始和最后位置添加图片
// 2.重新设置图片盒子的宽度和图片的宽度
// 3.添加定时器,自动轮播
// 4.添加过渡结束事件
// 5.设置小白点
// 6.添加手动轮播
// 获取元素
var ulObj = $(".slideshow-img");
var first = ulObj.find("li:first-of-type");
var last = ulObj.find("li:last-of-type");
var bannerWidth = $(".slideshow").width();
// 在开始和最后位置添加图片
ulObj.append(first.clone());
last.clone().insertBefore(first);
// 重新设置图片盒子的宽度和图片的宽度
var liObjs = ulObj.find("li");
ulObj.width(liObjs.length +"00%");
liObjs.each(function (index) {
// 数组是DOM操作,要转换成zepto元素
$(liObjs[index]).width(bannerWidth);
});
// 设置默认显示第一张图
ulObj.css("transform", "translateX("+ -bannerWidth +"px)");
var index = 1;
// 盒子改变大小的时候重现设置图片盒子的宽度和图片的宽度
$(window).on("resize", function () {
ulObj.width(liObjs.length +"00%");
liObjs.each(function (index) {
// 数组是DOM操作,要转换成zepto元素
$(liObjs[index]).width($(".slideshow").width());
});
ulObj.css("transform", "translateX("+ -$(".slideshow").width()*index +"px)");
});
// 轮播动画函数
var setAnimate = function () {
ulObj.animate(
{"transform": "translateX("+ -$(".slideshow").width()*index +"px)"},
500,
"linear",
function () { // 过渡结束事件回调函数
if(index == 0) {
index = liObjs.length -2;
ulObj.css("transform", "translateX("+ -$(".slideshow").width()*index +"px)");
} else if(index == liObjs.length -1) {
index = 1;
ulObj.css("transform", "translateX("+ -$(".slideshow").width()*index +"px)");
}
// 设置小白点
$(".slideshow-dot").children("li").removeClass("select").eq(index-1).addClass("select");
}
);
};
var timerId;
// 添加定时器,自动轮播
var timerStart = function () {
timerId = setInterval(function () {
index++;
setAnimate();
}, 1500);
};
timerStart();
// 手动轮播操作
ulObj.on("swipeLeft", function () {
clearInterval(timerId);
index++;
setAnimate();
//手动轮播操作完成后再开启定时器
timerStart();
});
ulObj.on("swipeRight", function () {
clearInterval(timerId);
index--;
setAnimate();
// 手动轮播操作完成后再开启定时器
timerStart();
});
//------------------------------------------------
// 搜索栏上下滚动时改变透明度
var bannerEffect = function () {
var bannerObj = $(".search");
var slideshowObj = $(".slideshow");
var bannerHeight = bannerObj.height();
var imgHeight = slideshowObj.height();
// console.log(bannerHeight + ' ' + imgHeight);
$(window).on("scroll", function (e) {
var scrollHeight = $(window).scrollTop();
if(scrollHeight < (imgHeight-bannerHeight)) {
var setopacity = scrollHeight / (imgHeight-bannerHeight);
bannerObj.css("backgroundColor", "rgba(233, 35, 34,"+setopacity+")");
}
});
};
bannerEffect();
//-----------------------------------------------------
// 设置倒计时
var timerCount = function () {
var timers = $(".content-title-left-time").children("span");
var titleCount = 2*60*60;
var timerId = setInterval(function () {
titleCount--;
var hour = Math.floor(titleCount / 3600);
var minute = Math.floor((titleCount % 3600) / 60);
var second = titleCount % 60;
if(titleCount >= 0) {
$(timers[0]).html(Math.floor(hour / 10));
$(timers[1]).html(hour % 10);
$(timers[3]).html(Math.floor(minute / 10));
$(timers[4]).html(minute % 10);
$(timers[6]).html(Math.floor(second / 10));
$(timers[7]).html(second % 10);
} else {
titleCount = 0;
clearInterval(timerId);
return;
}
}, 1000);
};
timerCount();
}); | Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/js/index-zepto.js/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/js/index-zepto.js",
"repo_id": "Daotin",
"token_count": 2535
} | 16 |
/*!
* Bootstrap v3.3.7 (http://getbootstrap.com)
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
.btn-default,
.btn-primary,
.btn-success,
.btn-info,
.btn-warning,
.btn-danger {
text-shadow: 0 -1px 0 rgba(0, 0, 0, .2);
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 1px rgba(0, 0, 0, .075);
}
.btn-default:active,
.btn-primary:active,
.btn-success:active,
.btn-info:active,
.btn-warning:active,
.btn-danger:active,
.btn-default.active,
.btn-primary.active,
.btn-success.active,
.btn-info.active,
.btn-warning.active,
.btn-danger.active {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn-default.disabled,
.btn-primary.disabled,
.btn-success.disabled,
.btn-info.disabled,
.btn-warning.disabled,
.btn-danger.disabled,
.btn-default[disabled],
.btn-primary[disabled],
.btn-success[disabled],
.btn-info[disabled],
.btn-warning[disabled],
.btn-danger[disabled],
fieldset[disabled] .btn-default,
fieldset[disabled] .btn-primary,
fieldset[disabled] .btn-success,
fieldset[disabled] .btn-info,
fieldset[disabled] .btn-warning,
fieldset[disabled] .btn-danger {
-webkit-box-shadow: none;
box-shadow: none;
}
.btn-default .badge,
.btn-primary .badge,
.btn-success .badge,
.btn-info .badge,
.btn-warning .badge,
.btn-danger .badge {
text-shadow: none;
}
.btn:active,
.btn.active {
background-image: none;
}
.btn-default {
text-shadow: 0 1px 0 #fff;
background-image: -webkit-linear-gradient(top, #fff 0%, #e0e0e0 100%);
background-image: -o-linear-gradient(top, #fff 0%, #e0e0e0 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#e0e0e0));
background-image: linear-gradient(to bottom, #fff 0%, #e0e0e0 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #dbdbdb;
border-color: #ccc;
}
.btn-default:hover,
.btn-default:focus {
background-color: #e0e0e0;
background-position: 0 -15px;
}
.btn-default:active,
.btn-default.active {
background-color: #e0e0e0;
border-color: #dbdbdb;
}
.btn-default.disabled,
.btn-default[disabled],
fieldset[disabled] .btn-default,
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled.focus,
.btn-default[disabled].focus,
fieldset[disabled] .btn-default.focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
background-color: #e0e0e0;
background-image: none;
}
.btn-primary {
background-image: -webkit-linear-gradient(top, #337ab7 0%, #265a88 100%);
background-image: -o-linear-gradient(top, #337ab7 0%, #265a88 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#265a88));
background-image: linear-gradient(to bottom, #337ab7 0%, #265a88 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff265a88', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #245580;
}
.btn-primary:hover,
.btn-primary:focus {
background-color: #265a88;
background-position: 0 -15px;
}
.btn-primary:active,
.btn-primary.active {
background-color: #265a88;
border-color: #245580;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled.focus,
.btn-primary[disabled].focus,
fieldset[disabled] .btn-primary.focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
background-color: #265a88;
background-image: none;
}
.btn-success {
background-image: -webkit-linear-gradient(top, #5cb85c 0%, #419641 100%);
background-image: -o-linear-gradient(top, #5cb85c 0%, #419641 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#5cb85c), to(#419641));
background-image: linear-gradient(to bottom, #5cb85c 0%, #419641 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #3e8f3e;
}
.btn-success:hover,
.btn-success:focus {
background-color: #419641;
background-position: 0 -15px;
}
.btn-success:active,
.btn-success.active {
background-color: #419641;
border-color: #3e8f3e;
}
.btn-success.disabled,
.btn-success[disabled],
fieldset[disabled] .btn-success,
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled.focus,
.btn-success[disabled].focus,
fieldset[disabled] .btn-success.focus,
.btn-success.disabled:active,
.btn-success[disabled]:active,
fieldset[disabled] .btn-success:active,
.btn-success.disabled.active,
.btn-success[disabled].active,
fieldset[disabled] .btn-success.active {
background-color: #419641;
background-image: none;
}
.btn-info {
background-image: -webkit-linear-gradient(top, #5bc0de 0%, #2aabd2 100%);
background-image: -o-linear-gradient(top, #5bc0de 0%, #2aabd2 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#5bc0de), to(#2aabd2));
background-image: linear-gradient(to bottom, #5bc0de 0%, #2aabd2 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #28a4c9;
}
.btn-info:hover,
.btn-info:focus {
background-color: #2aabd2;
background-position: 0 -15px;
}
.btn-info:active,
.btn-info.active {
background-color: #2aabd2;
border-color: #28a4c9;
}
.btn-info.disabled,
.btn-info[disabled],
fieldset[disabled] .btn-info,
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled.focus,
.btn-info[disabled].focus,
fieldset[disabled] .btn-info.focus,
.btn-info.disabled:active,
.btn-info[disabled]:active,
fieldset[disabled] .btn-info:active,
.btn-info.disabled.active,
.btn-info[disabled].active,
fieldset[disabled] .btn-info.active {
background-color: #2aabd2;
background-image: none;
}
.btn-warning {
background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #eb9316 100%);
background-image: -o-linear-gradient(top, #f0ad4e 0%, #eb9316 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#f0ad4e), to(#eb9316));
background-image: linear-gradient(to bottom, #f0ad4e 0%, #eb9316 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #e38d13;
}
.btn-warning:hover,
.btn-warning:focus {
background-color: #eb9316;
background-position: 0 -15px;
}
.btn-warning:active,
.btn-warning.active {
background-color: #eb9316;
border-color: #e38d13;
}
.btn-warning.disabled,
.btn-warning[disabled],
fieldset[disabled] .btn-warning,
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled.focus,
.btn-warning[disabled].focus,
fieldset[disabled] .btn-warning.focus,
.btn-warning.disabled:active,
.btn-warning[disabled]:active,
fieldset[disabled] .btn-warning:active,
.btn-warning.disabled.active,
.btn-warning[disabled].active,
fieldset[disabled] .btn-warning.active {
background-color: #eb9316;
background-image: none;
}
.btn-danger {
background-image: -webkit-linear-gradient(top, #d9534f 0%, #c12e2a 100%);
background-image: -o-linear-gradient(top, #d9534f 0%, #c12e2a 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#d9534f), to(#c12e2a));
background-image: linear-gradient(to bottom, #d9534f 0%, #c12e2a 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #b92c28;
}
.btn-danger:hover,
.btn-danger:focus {
background-color: #c12e2a;
background-position: 0 -15px;
}
.btn-danger:active,
.btn-danger.active {
background-color: #c12e2a;
border-color: #b92c28;
}
.btn-danger.disabled,
.btn-danger[disabled],
fieldset[disabled] .btn-danger,
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled.focus,
.btn-danger[disabled].focus,
fieldset[disabled] .btn-danger.focus,
.btn-danger.disabled:active,
.btn-danger[disabled]:active,
fieldset[disabled] .btn-danger:active,
.btn-danger.disabled.active,
.btn-danger[disabled].active,
fieldset[disabled] .btn-danger.active {
background-color: #c12e2a;
background-image: none;
}
.thumbnail,
.img-thumbnail {
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
background-color: #e8e8e8;
background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e8e8e8));
background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);
background-repeat: repeat-x;
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
background-color: #2e6da4;
background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4));
background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);
background-repeat: repeat-x;
}
.navbar-default {
background-image: -webkit-linear-gradient(top, #fff 0%, #f8f8f8 100%);
background-image: -o-linear-gradient(top, #fff 0%, #f8f8f8 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#f8f8f8));
background-image: linear-gradient(to bottom, #fff 0%, #f8f8f8 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 5px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 5px rgba(0, 0, 0, .075);
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .active > a {
background-image: -webkit-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%);
background-image: -o-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#dbdbdb), to(#e2e2e2));
background-image: linear-gradient(to bottom, #dbdbdb 0%, #e2e2e2 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdbdbdb', endColorstr='#ffe2e2e2', GradientType=0);
background-repeat: repeat-x;
-webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, .075);
box-shadow: inset 0 3px 9px rgba(0, 0, 0, .075);
}
.navbar-brand,
.navbar-nav > li > a {
text-shadow: 0 1px 0 rgba(255, 255, 255, .25);
}
.navbar-inverse {
background-image: -webkit-linear-gradient(top, #3c3c3c 0%, #222 100%);
background-image: -o-linear-gradient(top, #3c3c3c 0%, #222 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#3c3c3c), to(#222));
background-image: linear-gradient(to bottom, #3c3c3c 0%, #222 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-radius: 4px;
}
.navbar-inverse .navbar-nav > .open > a,
.navbar-inverse .navbar-nav > .active > a {
background-image: -webkit-linear-gradient(top, #080808 0%, #0f0f0f 100%);
background-image: -o-linear-gradient(top, #080808 0%, #0f0f0f 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#080808), to(#0f0f0f));
background-image: linear-gradient(to bottom, #080808 0%, #0f0f0f 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff080808', endColorstr='#ff0f0f0f', GradientType=0);
background-repeat: repeat-x;
-webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, .25);
box-shadow: inset 0 3px 9px rgba(0, 0, 0, .25);
}
.navbar-inverse .navbar-brand,
.navbar-inverse .navbar-nav > li > a {
text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
}
.navbar-static-top,
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
@media (max-width: 767px) {
.navbar .navbar-nav .open .dropdown-menu > .active > a,
.navbar .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #fff;
background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4));
background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);
background-repeat: repeat-x;
}
}
.alert {
text-shadow: 0 1px 0 rgba(255, 255, 255, .2);
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), 0 1px 2px rgba(0, 0, 0, .05);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), 0 1px 2px rgba(0, 0, 0, .05);
}
.alert-success {
background-image: -webkit-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%);
background-image: -o-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#dff0d8), to(#c8e5bc));
background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0);
background-repeat: repeat-x;
border-color: #b2dba1;
}
.alert-info {
background-image: -webkit-linear-gradient(top, #d9edf7 0%, #b9def0 100%);
background-image: -o-linear-gradient(top, #d9edf7 0%, #b9def0 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#d9edf7), to(#b9def0));
background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0);
background-repeat: repeat-x;
border-color: #9acfea;
}
.alert-warning {
background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%);
background-image: -o-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#fcf8e3), to(#f8efc0));
background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0);
background-repeat: repeat-x;
border-color: #f5e79e;
}
.alert-danger {
background-image: -webkit-linear-gradient(top, #f2dede 0%, #e7c3c3 100%);
background-image: -o-linear-gradient(top, #f2dede 0%, #e7c3c3 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#f2dede), to(#e7c3c3));
background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0);
background-repeat: repeat-x;
border-color: #dca7a7;
}
.progress {
background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%);
background-image: -o-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#f5f5f5));
background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar {
background-image: -webkit-linear-gradient(top, #337ab7 0%, #286090 100%);
background-image: -o-linear-gradient(top, #337ab7 0%, #286090 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#286090));
background-image: linear-gradient(to bottom, #337ab7 0%, #286090 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff286090', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar-success {
background-image: -webkit-linear-gradient(top, #5cb85c 0%, #449d44 100%);
background-image: -o-linear-gradient(top, #5cb85c 0%, #449d44 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#5cb85c), to(#449d44));
background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar-info {
background-image: -webkit-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);
background-image: -o-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#5bc0de), to(#31b0d5));
background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar-warning {
background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);
background-image: -o-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#f0ad4e), to(#ec971f));
background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar-danger {
background-image: -webkit-linear-gradient(top, #d9534f 0%, #c9302c 100%);
background-image: -o-linear-gradient(top, #d9534f 0%, #c9302c 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#d9534f), to(#c9302c));
background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar-striped {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.list-group {
border-radius: 4px;
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
text-shadow: 0 -1px 0 #286090;
background-image: -webkit-linear-gradient(top, #337ab7 0%, #2b669a 100%);
background-image: -o-linear-gradient(top, #337ab7 0%, #2b669a 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2b669a));
background-image: linear-gradient(to bottom, #337ab7 0%, #2b669a 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2b669a', GradientType=0);
background-repeat: repeat-x;
border-color: #2b669a;
}
.list-group-item.active .badge,
.list-group-item.active:hover .badge,
.list-group-item.active:focus .badge {
text-shadow: none;
}
.panel {
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
}
.panel-default > .panel-heading {
background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e8e8e8));
background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);
background-repeat: repeat-x;
}
.panel-primary > .panel-heading {
background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4));
background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);
background-repeat: repeat-x;
}
.panel-success > .panel-heading {
background-image: -webkit-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%);
background-image: -o-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#dff0d8), to(#d0e9c6));
background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0);
background-repeat: repeat-x;
}
.panel-info > .panel-heading {
background-image: -webkit-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%);
background-image: -o-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#d9edf7), to(#c4e3f3));
background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0);
background-repeat: repeat-x;
}
.panel-warning > .panel-heading {
background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%);
background-image: -o-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#fcf8e3), to(#faf2cc));
background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0);
background-repeat: repeat-x;
}
.panel-danger > .panel-heading {
background-image: -webkit-linear-gradient(top, #f2dede 0%, #ebcccc 100%);
background-image: -o-linear-gradient(top, #f2dede 0%, #ebcccc 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#f2dede), to(#ebcccc));
background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0);
background-repeat: repeat-x;
}
.well {
background-image: -webkit-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%);
background-image: -o-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%);
background-image: -webkit-gradient(linear, left top, left bottom, from(#e8e8e8), to(#f5f5f5));
background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0);
background-repeat: repeat-x;
border-color: #dcdcdc;
-webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, .05), 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 3px rgba(0, 0, 0, .05), 0 1px 0 rgba(255, 255, 255, .1);
}
/*# sourceMappingURL=bootstrap-theme.css.map */
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/bootstrap/css/bootstrap-theme.css/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/bootstrap/css/bootstrap-theme.css",
"repo_id": "Daotin",
"token_count": 10269
} | 17 |
// Rotated & Flipped Icons
// -------------------------
.#{$fa-css-prefix}-rotate-90 { @include fa-icon-rotate(90deg, 1); }
.#{$fa-css-prefix}-rotate-180 { @include fa-icon-rotate(180deg, 2); }
.#{$fa-css-prefix}-rotate-270 { @include fa-icon-rotate(270deg, 3); }
.#{$fa-css-prefix}-flip-horizontal { @include fa-icon-flip(-1, 1, 0); }
.#{$fa-css-prefix}-flip-vertical { @include fa-icon-flip(1, -1, 2); }
// Hook for IE8-9
// -------------------------
:root .#{$fa-css-prefix}-rotate-90,
:root .#{$fa-css-prefix}-rotate-180,
:root .#{$fa-css-prefix}-rotate-270,
:root .#{$fa-css-prefix}-flip-horizontal,
:root .#{$fa-css-prefix}-flip-vertical {
filter: none;
}
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_rotated-flipped.scss/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_rotated-flipped.scss",
"repo_id": "Daotin",
"token_count": 300
} | 18 |
/*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */
(function( w ){
"use strict";
// Bail out for browsers that have addListener support
if (w.matchMedia && w.matchMedia('all').addListener) {
return false;
}
var localMatchMedia = w.matchMedia,
hasMediaQueries = localMatchMedia('only all').matches,
isListening = false,
timeoutID = 0, // setTimeout for debouncing 'handleChange'
queries = [], // Contains each 'mql' and associated 'listeners' if 'addListener' is used
handleChange = function(evt) {
// Debounce
w.clearTimeout(timeoutID);
timeoutID = w.setTimeout(function() {
for (var i = 0, il = queries.length; i < il; i++) {
var mql = queries[i].mql,
listeners = queries[i].listeners || [],
matches = localMatchMedia(mql.media).matches;
// Update mql.matches value and call listeners
// Fire listeners only if transitioning to or from matched state
if (matches !== mql.matches) {
mql.matches = matches;
for (var j = 0, jl = listeners.length; j < jl; j++) {
listeners[j].call(w, mql);
}
}
}
}, 30);
};
w.matchMedia = function(media) {
var mql = localMatchMedia(media),
listeners = [],
index = 0;
mql.addListener = function(listener) {
// Changes would not occur to css media type so return now (Affects IE <= 8)
if (!hasMediaQueries) {
return;
}
// Set up 'resize' listener for browsers that support CSS3 media queries (Not for IE <= 8)
// There should only ever be 1 resize listener running for performance
if (!isListening) {
isListening = true;
w.addEventListener('resize', handleChange, true);
}
// Push object only if it has not been pushed already
if (index === 0) {
index = queries.push({
mql : mql,
listeners : listeners
});
}
listeners.push(listener);
};
mql.removeListener = function(listener) {
for (var i = 0, il = listeners.length; i < il; i++){
if (listeners[i] === listener){
listeners.splice(i, 1);
}
}
};
return mql;
};
}( this ));
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/respond/matchmedia.addListener.js/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/respond/matchmedia.addListener.js",
"repo_id": "Daotin",
"token_count": 898
} | 19 |
npm又称为包管理工具。
一般安装nodejs时会自带npm管理工具。
测试npm是否安装成功:
```js
npm -v
```
如果能成功打印版本号则安装成功。
如果需要使用npm下载安装软件,需要在项目下有一个`package.json` 文件。这个文件可以自己创建,也可以使用npm指令创建,用npm指令创建简单一些,不用在意修改其中的内容。
## 创建模块化开发项目
**1、创建package.json文件**
```js
npm init
```
创建的过程中会提示输入项目的名称等等一些问题,如果不在意的话,一路回车即可。
**2、向项目添加工具(这里以jQuery为例)**
```js
npm install jquery --save // npm i jquery --sava
```
> 参数 `--save`或者`-S` 该模块为项目依赖(运行依赖)
>
> 参数 `--save-dev`或`-D` 该模块为开发依赖(例如less就是开发依赖,开发的时候才使用,上线之后就不用了,用它生成的css文件)
>
> 参数 `-g` 全局安装某个模块
**3、卸载某个工具(已jQuery为例)**
```js
npm uninstall jquery -S // uninstall没有简单写法,后面的参数就是安装时的参数
```
> 有的时候安装失败的时候,仅仅卸载的话,可能还有缓存存在,可能导致下次安装不成功。所以每次在安装失败的时候,都应该卸载之后,再次运行清除缓存的操作。
>
> 清除缓存操作指令如下:
>
> ```js
> npm cache clear -f
> ```
还有一些其他的npm指令:
```js
npm info jquery //查看模块的相关信息
npm run start //执行package.json 中的script属性的脚本
```
## nrm
有的时候,npm访问的速度特别慢,是因为npm的主机是在国外的。幸运的是,国内有几个良心公司为了方便国内用户方便下载npm中的工具,于是在国内做了几个npm镜像主机,我们在国内访问这些镜像主机的时候,速度就很快了。
### nrm 的安装使用
nrm指令作用:提供了一些最常用的NPM包镜像地址,能够让我们快速的切换安装包时候的服务器地址。
什么是镜像:原来包刚一开始是只存在于国外的NPM服务器,但是由于网络原因,经常访问不到,这时候,我们可以在国内,创建一个和官网完全一样的NPM服务器,只不过,数据都是从人家那里拿过来的,除此之外,使用方式完全一样,这个地址就是镜像地址。
1. 运行`npm i nrm -g`全局安装`nrm`包;
2. 使用`nrm ls`查看当前所有可用的镜像源地址以及当前所使用的镜像源地址;
3. 使用`nrm use npm`或`nrm use taobao`切换不同的镜像源地址;
> 注意: nrm 只是单纯的提供了几个常用的下载包的 URL地址,并能够让我们在这几个地址之间切换,很方便的进行切换,但是我们每次装包的时候,使用的装包工具,都是 npm

> 注意:切换完源之后,软件的下载还是通过npm,nrm只是用来切换下载源的。
### npm、nrm、nvm是什么关系?
- npm(node.js package management):node.js 包管理,用于管理node.js包的下载等等
- nrm(node.js resource management): node.js 下载源管理,用于切换下载源,实现快速下载包
- nvm(node.js version management) :node.js版本管理,用于管理多个node.js版本共存、切换等
参考链接:https://juejin.cn/post/6844903718123470861
| Daotin/Web/10-Node.js/01-npm.md/0 | {
"file_path": "Daotin/Web/10-Node.js/01-npm.md",
"repo_id": "Daotin",
"token_count": 2288
} | 20 |
##一、Webpack介绍
Webpack 中文官网 https://www.webpackjs.com/

### 1、什么是webpack?
Webpack是一个**模块打包器(bundler)**。
但是,webpack的**核心功能**是:
> 把模块化规范的代码,比如commonJS等编译成浏览器能识别的代码输出出来(也叫作前端模块化)
**我们知道在之前,commonJS规范的代码只能在node后端中运行(node是原生支持commonJS模块化的),如果在前端使用的话,会报一个错误:‘require is not defined’ 找不到require,这就是模块化规范的代码不能在浏览器中解析运行,如果想运行,达到前端模块化的功能,就要使用自动化构建工具,webpack就是其中的一种。**
webpack的**辅助功能**才是对源代码的打包,压缩,混淆处理等。
所以一定要搞清楚主次关系。
在Webpack看来, 前端的所有资源文件(js/json/css/img/less/...)都会作为模块处理,每一个资源文件都是一个模块。它将根据模块的依赖关系进行静态编译,生成对应的静态资源。
webpack所有的配置都会写在项目根目录下的`webpack.config.js` 文件下。
webpack如何配置,你需要先理解四个**核心概念**:
- 入口(entry)
- 输出(output)
- loader
- 插件(plugins)
**入口**
指示 webpack 应该使用哪个模块作为主模块来构建静态资源,一般打包的时候只引入主模块,而在主模块中会引入其他的模块,这样我们就只需要打包一份主模块就够了。
**Loader**
Webpack 本身只能加载`JS/JSON`模块,如果要加载其他类型的文件(模块),就需要使用对应的loader 进行转换/加载
* Loader 本身也是运行在 node.js 环境中的 JavaScript 模块
* 它本身是一个函数,接受源文件作为参数,返回转换的结果
* loader 一般以 xxx-loader 的方式命名,xxx 代表了这个 loader 要做的转换功能,比如 json-loader。
* 配置文件(默认)
* webpack.config.js : 是一个node模块,返回一个 json 格式的配置信息对象
* 插件
插件件可以完成一些loader不能完成的功能。
插件的使用一般是在 webpack 的配置信息 plugins 选项中指定。
CleanWebpackPlugin: 自动清除指定文件夹资源
HtmlWebpackPlugin: 自动生成HTML文件并
UglifyJSPlugin: 压缩js文件
## 二、webpack初体验
### 1、安装webpack
由于现在webpack版本在2018年8月份的时候更新到 webpack 4+ 了,但是市面上用的最多的还是webpack3+,所以下面所有的示例均已webpack3+来演示。
如果想要使用 webpack3+ 的版本的话,在全局安装和局部安装的时候需要注意,需要在webpack后面加上`@3` ,表示安装webpack3+ 的版本。
```js
//全局安装
npm install webpack@3.11.0 -g
//局部安装
npm install webpack@3.11.0 -D
```
> 全局安装时为了能够使用webpack指令来进行项目的编译等,
>
> 项目安装是为了使用webpack模块的内容。
### 2、初始化项目
使用`npm init -y` 初始化项目。
> `-y`的目的是不提示项目名等等提示信息,直接全部使用默认的配置创建package.json文件。
创建src目录,目录下建一个主模块main.js,在主模块中调用sayHello.js文件
```js
// sayHello.js
module.exports = name => {
console.log(name);
}
// main.js
let say = require('./sayHello');
say('lvonve');
```
创建主页面
将来webpack打包生成的js文件是dist目录下的index.js文件
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>真的</div>
</body>
<script src="index.js"></script>
</html>
```
### 3、编译运行
```
webpack main.js index.js
```
然后就可以在浏览器中查看打印出‘lvonve’
## 三、webpack打包
有的时候我们希望将编译好的js文件放到指定的dist目录,但是我们又不想手工创建,有没有办法呢?
`webpack.config.js`配置文件可以解决。
1、新建一个`webpack.config.js`文件:
```js
module.exports = {
entry: __dirname + '/src/main.js',
output: {
path: __dirname + '/dist',
filename: 'index.js'
}
}
```
> `__dirname` 表示当前项目的根路径。
>
> `entry` 入口模块
>
> `output` 输出的目标文件的路径和文件名
2、使用指令进行编译:
```js
webpack
```
之后我们会在项目更目录下发现一个dist目录,目录下有个index.js文件,就是我们的目标文件。
## 四、热加载(自动编译)
每次在我们修改源文件后,都需要进行webpack指令进行打包才可以生成目标文件,才能在页面展示使用。
有没有在源代码修改保存后,自动~~编译成目标位文件~~刷新页面呢?
这就是`webpack-dev-server`模块。webpack-dev-server模块会自动开启个本地web服务器来运行我们的程序,一旦源文件被修改,会自动同步到浏览器中。
webpack-dev-server模块原理:
webpack-dev-server 其实就是个微服务器,在执行 webpack-dev-server 命令的时候,也会首先从 webpack.config.js 中找到任务,然后在其自己内部进行打包,打包好了之后,并不会输出到本地,而是在其内存中有一份 index.js ,我们通过 `http://localhost:3000/` 访问的其实就是其内存中的文件,这时候即使我们删除本地 index.js 也不会影响页面的显示。
并且 webpack-dev-server 会自动寻找文件的路径,所以我们不需要指定 index.js 和 大图的路径,这也是其智能的地方。
> **但是需要注意的是,webpack-dev-server模块不会生成目标文件,也就是不会生成dist文件夹和里面的目标文件,webpack-dev-server会将编译运行放在内存的目标文件,而不会生成到项目中。而webpack指令才可以生成目标文件。**
1、安装 webpack-dev-server模块
```js
npm i webpack-dev-server@2.9.7 -g
```
> 注意安装2.9.7版本的。
2、在webpack.config.js中进行配置:
```js
// 安装的webpack-dev-server模块配置信息
devServer: {
contentBase: __dirname + '/dist', // 指定本地web服务器根路径
port: 3000,
inline: true // 当源文件改变后,自动在浏览器页面刷新
}
```
3、运行指令
```
webpack-dev-server --inline --open
```
这时候,编译完成会自动访问`http://localhost:3000` 地址,就不用再打开浏览器了,如果项目源代码有修改,保存后,浏览器会自动进行刷新显示。
4、这个命令太长了,package.json就用到了。
```json
"scripts": {
"start": "webpack-dev-server --inline --open",
"build": "webpack"
}
```
以后直接使用指令:
```
npm run start
```
想生成dist文件的时候:
```
npm run build
```
## 五、html-webpack-plugin插件
我们之前编译的dist文件夹只有index.js目标文件,其实我们在项目上线的时候,除了有js文件还应该有index.html
主文件,所以我们应该把html文件放到dist目录下。但是由于一般dist下的文件不建议修改,我们希望的是修改了源文件中的html就自动复制一份到dist中,`html-webpack-plugin` 插件就给我们提供了帮助。
1、安装html-webpack-plugin插件
```
npm i html-webpack-plugin -D
```
2、修改webpack.config.js配置文件
```js
let Hwp = require('html-webpack-plugin');
//..
// 安装的html-webpack-plugin模块的配置
plugins: [
new Hwp({
template: __dirname + '/src/index.html', // 源文件index.html路径
filename: 'index.html', // 由于生成路径output已配置,这里只写生成的文件名
inject: true // 在index.html中自动引入需要的就js,css文件
})
]
```
> html-webpack-plugin插件还有个额外功能就是 `inject: true`,它可以自动识别需要引入的script和link文件,特别好使。
3、重启服务
## 六、打包css到js
项目还存在css文件怎么办?可以把css样式打包到js中。
1、安装模块 css-loader和style-loader
```
npm i css-loader style-loader -D
```
> css-loader:作用是读取css文件
>
> style-loader:作用是将css注入到js中
2、配置config
```js
module: {
rules: [{
test: /\.css$/, // 解析以.css结尾的文件
loader: 'style-loader!css-loader' //解析以.css结尾的文件需要用到的模块(注意:书写顺序是先使用的写后面)
}]
}
```
> 注意:loader: 'style-loader!css-loader' 中书写的顺序,先需要用到的写到后面。
3、在入口js引入css文件
```js
// main.js
require('./style/base.css');
```
4、重启服务
```js
npm run start
```
## 七、打包图片文件到js
1、安装插件
```js
// 图片相关插件(url-loader是对象file-loader的上层封装,使用时需配合file-loader使用。)
npm install file-loader url-loader -D
```
2、修改配置文件
```json
module: {
rules: [
{ test: /\.(png|jpg|gif)$/, use: [{ loader: 'url-loader', options: { limit: 8192 } }] } // 限制转换的图片大小为8Kb
]
},
```
3、在css中插入图片
```css
div {
width: 200px;
height: 200px;
background: url(../img/1.jpg);
}
```
4、重新编译
我们发现dist中没有图片,但是图片显示了,说明图片注入到了css中。我们可以查看生成的index.css看出来,图片是以base64的形式存在的:
```css
div {
width: 200px;
height: 200px;
background: url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASA...(太长省略)BBHDPds2gKCBThSN3rYhi5J6mjNJ2FJSsB7Sn+cV82af8A8hGy/wCvq3/9GpX0BXFXgnM3hJ2P/9k=);
}
```
> 注意:当我们设置的图片大小超过限时时,会在dist中产生一个图片,而不是base64形式的。
比如我把 limit: 1024 之后,重新webpack生成后会在dist下生成一个990384cd91d73b43929679287541587e.jpg图片,然后在css中引入的是这个图片,而不是base64。
```css
div {
width: 200px;
height: 200px;
background: url(990384cd91d73b43929679287541587e.jpg);
}
```
## 七、开启地图资源模式
之前把所有的js和css都编译到一个js里面之后,如果我们代码有运行错误,排错非常麻烦,因为生成的js文件非常长,可能报错的位置是在一万多行的位置,但是 实际上我们代码的位置只是在几十行的位置。这个该如何处理?
这就需要我们开启地图资源模式。
开启的方式很简单,只需要在配置文件中加上下面一句话即可。
```js
// 开启地图资源模式
devtool: 'source-map'
```
此时,当我们使用`webpack` 生成目标文件的时候,会自动多出一个map文件,比如index.js.map
这个就是一个源文件和编译后目标文件的一个映射文件,当程序有错误的时候,提示的就是源文件的行号而不是目标文件的行号,方便错误定位。
我们可以在目标文件的最后发现有个映射文件的声明的注释,这个注释不能删除,否则就无法实现映射功能。

## 八、多入口文件
之前的目标文件只有一个index.js,如何生成多个目标文件?
我们需要在配置文件的entry属性配置成一个对象,这个对象有多个属性,分别对应多个目标文件。
```json
entry: {
index: __dirname + '/src/main.js',
goods: __dirname + '/src/goods.js'
},
output: {
path: __dirname + '/dist',
filename: '[name].js'
},
```
> entry中每个属性即为目标文件名,输出文件的[name].js中的name即为entry的属性名。
但是,现在一般都是单页面应用,所以像这种对入口文件的形式很少见了。
## 九、打包Less,Scss等
下面以less为例。
1、安装loader
```js
npm i less-loader less -D
```
2、设置配置文件
```js
module: {
rules: [
{test: /\.css$/,loader: 'style-loader!css-loader'},
{test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }
]
},
```
> 也是要注意书写顺序。
3、重启服务。
## 十、提取样式文件
之前我们是把css样式打包到js文件中的,而js是使用script标签引入的页面的。
link标签与script的区别:
link标签的加载时异步的,而script的加载会阻塞程序的运行,影响用户体验,所有有必要将css文件提取出来。
1、安装插件
```
npm i extract-text-webpack-plugin -D
```
2、修改配置
```json
let Ext = require('extract-text-webpack-plugin');
module: {
rules: [
{ test: /\.css$/, loader: Ext.extract('css-loader') },
{ test: /\.less$/, loader: Ext.extract('css-loader!less-loader') }
]
},
plugins: [
new Ext('index.css')
],
```
由于不需要注入到js中了,所以style-loader就去掉了,但读取less和css还是需要的,顺序也是需要的。
在plugins中也要new Ext,参数为生成的css目标文件名。
## 十一、ES6转换成ES5
很多时候我们需要将ES6语法转换成ES5的,因为很多浏览器比如政府网站都比较老旧,不支持ES6语法。所以需要将ES6转换成ES5。
1、安装插件
```
npm i babel-loader@7.1.5 babel-core babel-preset-env -D
```
> 这三个插件:
>
> babel-loader@7.1.5 :是一个babel工具
>
> babel-core :是工具的依赖
>
> babel-preset-env:专门用来解析ES6到ES5的
2、修改配置文件
```json
module: {
rules: [
{ test: /\.css$/, loader: Ext.extract('css-loader') },
{ test: /\.less$/, loader: Ext.extract('css-loader!less-loader') },
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=env' }
]
},
```
> exclude:除去node-modules文件夹里面的js文件
我们在`loader:babel-loader`中加了参数`?presets[]=env`,这只是临时写法。
一般写法是在项目根目录新建一个文件`.babelrc`:
```json
{
"presets":["env"]
}
```
和上面是等价的。
如果使用到ES6的高级语法,比如展开符`...`时,上面的插件就满足不了了,需要另一个插件:
```
npm i babel-preset-stage-2 -D
```
然后修改`.babelrc` :
```json
{
"presets":["env", "stage-2"]
}
```
3、在main.js书写测试代码
```js
let obj = { name: 'daotin', age: 18 }
let { name: user, age } = obj;
console.log(user, age);
```
4、重启服务
## 十二、使用jquery
方式一:在线cdn
方式二:下载jq,然后在html引入
方式三:安装插件
1、安装jq插件
```js
npm i jquery -S
```
2、然后那个js文件需要,直接require引入
```js
let $ = require('jquery');
```
> 这种方式有个缺陷就是,只能本文件使用jq,其他文件要使用,还得require一次,很多文件使用jq就得很多文件require,可不可以只引入一次所有的js都可用呢?
3、设置jq全局作用域
```json
let webpack = require('webpack');
plugins: [
new webpack.ProvidePlugin({ $: 'jquery' })
],
```
4、重启服务即可。
##十二、其他插件
**webpack 插件:**
https://www.webpackjs.com/plugins/
https://webpack.docschina.org/plugins/

### 1、常用的插件
* 使用`html-webpack-plugin`根据模板html生成新的html文件,并自动引入js文件到页面
* 使用`clean-webpack-plugin`清除dist文件夹
* 使用`uglifyjs-webpack-plugin`压缩打包的js文件
### 2、使用步骤
**1、下载**
```
npm install --save-dev html-webpack-plugin clean-webpack-plugin uglifyjs-webpack-plugin
```
**2、配置**
```js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: './src/js/entry.js', // 入口文件
output: {
// 略
},
module: {
// 略
},
devServer: {
// 略
},
plugins: [
// template 表示模板的意思,表示以 './index.html' 为模板创建一个html文件
// 新创建的html文件默认会生成在dist/js目录下,并自动引入bundle.js文件到页面
new HtmlWebpackPlugin({template: './index.html'}),
// 在打包的时候,先清空dist目录下的所有文件再生成相关文件
new CleanWebpackPlugin(['dist']),
// 将生成的bundle.js压缩
new UglifyJsPlugin()
]
};
```
**3、打包运行项目**
```
webpack
```
结果在 dist/js下自动生成index.html文件,并且自动引入bundle.js文件。
| Daotin/Web/11-自动化构建/03-Webpack.md/0 | {
"file_path": "Daotin/Web/11-自动化构建/03-Webpack.md",
"repo_id": "Daotin",
"token_count": 10011
} | 21 |
使用示例还是 **vue的组件**
---
## 一、Vuex
Vuex 是一个专为 Vue.js 应用程序开发的**状态管理模式**。它采用集中式存储管理应用的所有组件的状态(意思就是数据),并以相应的规则保证状态以一种可预测的方式发生变化。
简单来说,vuex就是用来集中管理组件的数据的。
## 二、Vuex使用场合
如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。一个简单的 store 模式就足够您所需了。但是,如果您需要构建一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。引用 Redux 的作者 Dan Abramov 的话说就是:
> Flux 架构就像眼镜:您自会知道什么时候需要它。
### 1、store模式
安装vuex
```
npm i vuex -S
```
我们在原有项目下新建一个store.js管理Home,Goods,Users组件的数据。
其中state属性就是保存Home,Goods,Users组件所有的数据。
```js
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
title: '首页',
goodsList: [
{ goodsName: '苹果', price: 20 },
{ goodsName: '橘子', price: 22 },
{ goodsName: '香蕉', price: 50 },
{ goodsName: '菠萝', price: 43 },
],
userList: [
{ userName: 'lvonve', age: 18 },
{ userName: 'daotin', age: 19 },
{ userName: 'wenran', age: 17 },
]
}
});
export { store }
```
> 注意:将store.js文件导入到vue实例中:
>
> ```
> new Vue({
> el: "#app",
> components: { App },
> template: `<App />`,
> router,
> store
> })
> ```
然后各个组件在获取数据的时候,是在`computed`属性中获取的,例如User组件(我们在user组件也把所有的数据都显示出来吧):
获取的方式通过`this.$store.state` 的方式获取。
```js
export let Users = {
template: require('./index.html'),
// data() {
// return {
// users: [
// { name: 'lvonve' },
// { name: 'daotin' },
// { name: 'wenran' },
// ]
// }
// },
computed: {
// 这个userList就是获取到的state中的userList
title: function() {
return this.$store.state.title;
},
userList: function() {
return this.$store.state.userList;
},
goodsList: function() {
return this.$store.state.goodsList;
}
}
}
```
然后在user组件进行显示:
```html
<div>
<h1>{{title}}</h1>
<h4>用户列表</h4>
<ul>
<li v-for="user in userList">{{user.userName}}+{{user.age}}</li>
</ul>
<h4>商品列表</h4>
<ul>
<li v-for="goods in goodsList">{{goods.goodsName}}+{{goods.price}}</li>
</ul>
</div>
```

但是现在有个不好的地方就是,每个组件都需要使用`this.$store.state`来获取其中的数据,显得有些麻烦,有没有简单的办法呢?
### 2、mapState
vuex提供了一个工具叫做`mapState`,通过它可以简化我们获取数据的方式。
mapState的作用就是返回一个对象,这个对象可以直接丢给computed。所以上面获取state的数据的方式可以写成下面的方式:
```js
import { mapState } from 'vuex'
export let Users = {
template: require('./index.html'),
// computed: {
// userList: function() {
// return this.$store.state.userList;
// },
// goodsList: function() {
// return this.$store.state.goodsList;
// }
// }
computed: mapState({
title(state) {
return state.title;
},
userList(state) {
return state.userList;
},
goodsList(state) {
return state.goodsList;
}
}),
}
```
或者你想要更简单,可以使用ES6的解构赋值:
```json
computed: mapState({
title: ({ title }) => title,
userList: ({ userList }) => userList,
goodsList: ({ goodsList }) => goodsList,
}),
```
还有更简单的写法:如果state上有某个属性,可以直接赋值:
```json
computed: mapState({
title: 'title',
userList: 'userList',
goodsList: 'goodsList'
}),
```
终极写法,就是如果mapState属性的名字和state中属性的名字相同的话,就可以采用下面更简单的写法:
(我们上面的例子就是mapState属性的名字和state中属性的名字相同)
```js
computed: mapState(['title', 'goodsList', 'userList'])
```
**mapState使用展开符写法**
一个项目中,有些时候有些mapState属性的名字和state中属性的名字相同,有些又不相同,比如下面的例子:
```js
computed: mapState({
title: 'title',
users: 'userList',
goods: 'goodsList'
}),
```
受到users和goods的拖累,title也不能写成终极进化版,这时候可以使用展开符。
```js
...mapState(['title'])
// 就类似于
mapState({
title:'title'
})
```
所以上面的例子的最终写法为:
```json
computed: {
...mapState(['title']),
...mapState({
users: 'userList',
goods: 'goodsList'
})
},
```
由于我们的babel只能编译基础的ES6语法,展开符是高级ES6语法,所以还要安装一个模块:
```js
npm i babel-preset-stage-2 -D
```
然后在`.babelrc` 里面添加:
```json
{
"presets": [
"env", "stage-2"
]
}
```
使用展开符的写法还有一个好处就是可以写自己的computed计算属性,而终极写法是没办法加自己的计算属性的。所以展开符的写法是最灵活的写法。
### 3、mutations
#### 修改state
现在有个新需求,在user组件,点击按钮,添加一个新用户(先把没用的商品列表去掉),我门一般的想法是直接操作state数据,如下:
```json
methods: {
addUser() {
this.$store.state.userList.push({userName: 'aaa',age: 9})
}
}
```
但是这种写法是不符合store架构规范的,只能通过store提供的`mutations`来操作自己的state。所以我们在store中定义一个mutations属性,然后这个属性中定义一个addUser方法来添加用户,这个方法的参数指向的就是store的state属性:
```js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
title: '我是title',
goodsList: [
{ goodsName: '苹果', price: 20 },
{ goodsName: '橘子', price: 22 },
{ goodsName: '香蕉', price: 50 },
{ goodsName: '菠萝', price: 43 },
],
userList: [
{ userName: 'lvonve', age: 18 },
{ userName: 'daotin', age: 19 },
{ userName: 'wenran', age: 17 },
]
},
// 添加mutations属性用来操作state数据
mutations: {
addUser(state) {
state.userList.push({ userName: 'aaa', age: 10 });
}
}
});
export { store }
```
然后在User.js中怎么调用这个addList方法呢?
使用`this.$store.commit('mutations的属性名')`来调用:
```js
import { mapState } from 'vuex'
export let Users = {
template: require('./index.html'),
computed: {
...mapState(['title', 'userList', 'goodsList'])
},
methods: {
addUser() {
// 使用commit的方式调用
this.$store.commit('addUser');
}
},
}
```
这样就可以点击按钮添加用户了。
> 整个应用程序,只有mutations才可以操作state状态。
>
> 但是注意:
>
> **mutations中的属性,必须为纯函数,必须为同步代码。**
>
> 纯函数就是传入相同的参数,得到相同的结果。
>
> 同步代码就不能是异步的,比如ajax,比如setTimeout等。
#### 修改state时传参
我们现在希望添加的用户信息自定义怎么向addUser传递参数呢?
**我们在commit的第二个参数传递数据。这里有个专业的术语叫做【载荷】**
```js
import { mapState } from 'vuex'
export let Users = {
template: require('./index.html'),
data() {
return {
name: '',
age: 0
}
},
computed: {
...mapState(['title', 'userList', 'goodsList'])
},
methods: {
addUser() {
// commit的第二个参数填写传递的载荷
this.$store.commit('addUser', {
name: this.name,
age: this.age
});
}
},
}
```
在store里面addUser的第二个参数接收数据:
```js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
title: '我是title',
goodsList: [
{ goodsName: '苹果', price: 20 },
{ goodsName: '橘子', price: 22 },
{ goodsName: '香蕉', price: 50 },
{ goodsName: '菠萝', price: 43 },
],
userList: [
{ userName: 'lvonve', age: 18 },
{ userName: 'daotin', age: 19 },
{ userName: 'wenran', age: 17 },
]
},
mutations: {
// data接收commit的载荷
addUser(state, data) {
state.userList.push({
userName: data.name,
age: data.age
});
}
}
});
export { store }
```
### 3、actions
除了state和mutations,store还有一个属性叫做`actions`。
actions里面放的就是mutations不能放的非纯函数,异步函数等。
actions里面的方法,**第一个参数不是指向state,而知指向store**,第二个参数还是载荷。
> 需要注意的是,能操作state的只有mutations,actions也不行。只能调用mutations去操作state。
举个例子,这里我们还是添加user,不过是间隔3s才写入state。
```json
actions: {
// 第一个参数指向store
// 第二个参数还是载荷
addUserTimeout(cStore, data) {
setTimeout(() => {
cStore.commit('addUser', data);
}, 3000);
}
}
```
然后在调用的时候就不能使用commit了,而是使用`dispatch` :
```json
methods: {
addUser() {
this.$store.commit('addUser', {
name: this.name,
age: this.age
});
},
addUserTimeout() {
// 使用dispatch调用actions的属性
this.$store.dispatch('addUserTimeout', {
name: this.name,
age: this.age
});
}
},
```
> **总结mutations与actiosn的区别:**
>
> 1、commit方法用于调用mutation;dispatch 方法用于调用action;
>
> 2、mutation 函数必须是纯函数,而且不能有异步代码;action 可以不是纯函数,也可以有异步代码;
>
> 3、按照上述规则,可以用mutation完成的事情,可以直接调用mutation,mutation不能实现的事情丢给action来完成。
>
> 4、在action中,当完成异步操作,最终需要修改数据模型时,还是需要通过mutation来完成对数据模型的操作。action不允许直接操作数据模型。
### 4、getters
store还有一个属性`getters`,相当于store的一个计算属性,就是对state的数据进行计算,当组件需要取到state的属性然后进行计算得到想要的结果的时候,计算的过程可以在`getters` 中进行,组件从getters中就可以直接拿到计算好的值。
这样还有一个好处就是,不仅当前组件可以拿个计算好的值,所有组件都可以拿到,如果所有组件都需要这个计算的话,那就方便多了。
举个例子:我们获取所有用户age之和:
```json
getters: {
countAge(state) {
let num = 0;
state.userList.map(user => {
num += user.age;
})
return num;
}
}
```
然后在user组件里面:
```json
computed: {
...mapState(['title', 'userList', 'goodsList']),
// 直接调用getters的countAge属性即可
allAge() {
return this.$store.getters.countAge
}
},
```
然后页面:`<div>age之和:{ {allAge} }</div>` 就会显示所有用户age之和。
和获取state值一样类似,每次获取getters的值都要使用`this.$store.getters` 的方式很麻烦,所以类似mapState还有mapGetters,写法和mapState一样:
```json
computed: {
...mapState(['title', 'userList', 'goodsList']),
...mapGetters({ allAge: 'countAge' }),
// allAge() {
// return this.$store.getters.countAge
// }
},
```
> 实际上,除了有mapState,mapActions,mapMutations,mapGetters都有,且用法相同。 **需要注意的是,mapState,mapGetters 是写在`computed`里面,而mapActions,mapMutations 写在 `methods` 里面。**
我们将user组件进行进行改造:
```json
methods: {
// addUser() {
// this.$store.commit('addUser', {
// name: this.name,
// age: this.age
// });
// },
// addUserTimeout() {
// console.log('user', this.name, this.age);
// this.$store.dispatch('addUserTimeout', {
// name: this.name,
// age: this.age
// });
// },
// 改造一
...mapMutations({ addUser: 'addUser' }),
...mapActions({ addUserTimeout: 'addUserTimeout' }),
// 改造二
...mapMutations(['addUser']),
...mapActions(['addUserTimeout']),
},
```
上面的写法有个问题就是没法传递载荷?
那么载荷在哪里传递呢?在视图中绑定点击事件时传递:
**给事件加上参数,这个参数就是载荷。**
```html
<div>
<h1>{{title}}</h1>
<h4>用户列表</h4>
<div>用户名:<input type="text" v-model="name"></div>
<div>年龄:<input type="text" v-model.number="age"></div>
<!-- 原始的只有函数名 -->
<!-- <button @click='addUser'>添加用户</button> -->
<!-- <button @click='addUserTimeout'>间隔3s添加用户</button> -->
<!-- 改造一 -->
<!-- <button @click='addUser({name:name,age:age})'>添加用户</button>
<button @click='addUserTimeout({name:name,age:age})'>间隔3s添加用户</button> -->
<!-- 改造二 -->
<button @click='addUser({name,age})'>添加用户</button>
<button @click='addUserTimeout({name,age})'>间隔3s添加用户</button>
<ul>
<li v-for="user in userList">{{user.userName}}+{{user.age}}</li>
</ul>
<div>age之和:{{allAge}}</div>
</div>
```
## 三、store拆分
如果组件特别多,每个组件的数据也就特别多,我们希望对这些数据根据不同的组件进行拆分方便管理。
现在有Home和User组件,Home组件的数据放在Home的store里面,User的数据放在User的store里面。
分别为homeStore.js和userStore.js,然后还有一个合并一起的主store叫index.js。
我们在home组件就显示一个title,user组件还是显示之前的内容。
```js
// homeStore.js
export default {
state: {
title: '我是首页',
}
}
// userStore.js
export default {
state: {
title: '我是用户页',
userList: [
{ userName: 'lvonve', age: 18 },
{ userName: 'daotin', age: 19 },
{ userName: 'wenran', age: 17 },
]
},
mutations: {
addUser(state, data) {
state.userList.push({
userName: data.name,
age: data.age
});
}
},
actions: {
// 第一个参数指向store
// 第二个参数还是载荷
addUserTimeout(cStore, data) {
setTimeout(() => {
cStore.commit('addUser', data);
}, 3000);
}
},
getters: {
countAge(state) {
let num = 0;
state.userList.map(user => {
num += user.age;
})
return num;
}
}
}
```
然后主store,index.js:
通过`modules`属性来注入各个子store
```js
import Vue from 'vue'
import Vuex from 'vuex'
import homeStore from './homeStore'
import userStore from './userStore'
Vue.use(Vuex);
const store = new Vuex.Store({
// 可以有自己的根状态,所有的组件都可以使用。比如用户的登录信息等
state:{
userInfo:{
name: 'daotin'
}
},
modules: {
home: homeStore,
user: userStore
}
});
export { store }
```
然后在main.js里面vue实例中注入的就不是原先的store.js而是index.js。
由于store下的主store名字是index.js,所以不需要修改,但是要重启服务。
```js
import Vue from 'vue'
import { router } from './router'
import { store } from './store'
import { App } from './App'
new Vue({
el: '#app',
template: '<App/>',
components: { App },
router,
store
});
```
然后在Home.js和User.js显示这些数据:
```js
// Home.js
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export let Home = {
template: require('./index.html'),
computed: {
...mapState(['title'])
}
}
//User.js
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export let Users = {
template: require('./index.html'),
data() {
return {
name: '',
age: 0
}
},
computed: {
...mapState(['title', 'userList', 'goodsList']),
...mapGetters({ allAge: 'countAge' }),
},
methods: {
...mapMutations(['addUser']),
...mapActions(['addUserTimeout']),
},
}
```
但是我们发现一个问题就是Home.js中的:
```json
computed: {
...mapState(['title'])
}
```
拿不到title的值,为什么呢?上面的写法相当于:
```js
computed: {
...mapState({
//title:'title'
title: (state)=>state.title;
})
}
```
但是我们现在state里面还title吗,没有了state.home下才有title。
所以,令人沮丧的是,如果使用了store拆分,就不能使用展开符的写法了。
正确的写法是:
```json
computed: {
...mapState({
title: (state) => state.home.title;
})
}
```
User.js也是一样的。
> 注意:
>
> 但是对于mutations,actions,getters不会区分home和user,都会集合到一起,类似于全局的属性,所欲的组件都可以访问到,所以也就不需要加home和user前缀。
### 1、namespaced命名空间
但是可能会存在这样一个问题,就是home和user下的mutations或者actions或者getters都有一个叫做add的方法,那么在调用的时候,调用的是谁的add呢?命名会冲突吗?
我们可以在子store里面加一句话:
`namespaced:true` 开启命名空间。
```js
// homeStore.js
export default {
// 开启命名空间
namespaced: true,
state: {
title: '我是首页',
}
}
```
然后获取的这些方法的时候就要加前缀home或者user:
```js
// User.js
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export let Users = {
template: require('./index.html'),
data() {
return {
name: '',
age: 0
}
},
computed: {
...mapState({
title: (state) => state.user.title,
userList: (state) => state.user.userList
}),
// 加user前缀
...mapGetters({ allAge: 'user/countAge' }),
},
methods: {
// 加user前缀
...mapMutations({ addUser: 'user/addUser' }),
...mapActions({ addUserTimeout: 'user/addUserTimeout' }),
},
}
```
然后还有一种写法如下,效果一样:
就是把前缀路径‘user/’提到第一个参数的位置,后面的写法和以前相同。
```json
computed: {
...mapState({
title: (state) => state.user.title,
userList: (state) => state.user.userList
}),
// 'user/'提前
...mapGetters('user/', { allAge: 'countAge' }),
},
methods: {
// 'user/'提前
...mapMutations('user/', ['addUser']),
...mapActions('user/', ['addUserTimeout']),
},
```
| Daotin/Web/12-Vue/09-vuex.md/0 | {
"file_path": "Daotin/Web/12-Vue/09-vuex.md",
"repo_id": "Daotin",
"token_count": 11712
} | 22 |
基础事件参考 :v-on 指令
---
## 自定义事件

## 自定义组件使用v-model
**(2.2.0+新增)**
> 一个组件上的 `v-model` 默认会利用名为 `value` 的 prop 和名为 `input` 的事件。
我们知道 v-model 其实是个语法糖。
```vue
<input v-model="searchText">
```
等价于
```vue
<input
:value="searchText"
@input="searchText = $event.target.value"
>
```
当用在自定义组件上的时候,我们需要将v-mode绑定的值:
- 传递给子组件一个叫`value` 的属性,这个`value`属性会自动绑定到子组件的`value` prop上。
- 在子组件中当这个值被改变的时候,通过手动抛出 `input` 事件的方式,将该值抛出,这个值会自动更新
`v-model`绑定的值。
从而实现自定义组件的双向绑定。
举个例子🌰:
例如`hand-over`自定义组件:我 v-model 绑定的是一个对象。

然后在`hand-over.vue`中的`props`需要一个`value`为对象类型:

上面是将 `handOverObj` 作为初始值传入自定义组件,来初始化显示(初始化的操作需要手动进行,这里省略)。
下面如果需要在值改变的时候传回到`handOverObj`上需要通过自定义`input`事件抛出。
```js
this.$emit('input', this.selectObj); // this.selectObj 为修改后的值
```
后面那个值就是我需要更新的handOverObj值。
如此这般,这般如此就实现了双向绑定。
| Daotin/Web/12-Vue/自定义事件.md/0 | {
"file_path": "Daotin/Web/12-Vue/自定义事件.md",
"repo_id": "Daotin",
"token_count": 1031
} | 23 |
/*
Navicat Premium Data Transfer
Source Server : 阿里云MySQL
Source Server Type : MySQL
Source Server Version : 50718
Source Host : rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306
Source Schema : web
Target Server Type : MySQL
Target Server Version : 50718
File Encoding : 65001
Date: 07/03/2018 09:59:47
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for release_feature
-- ----------------------------
DROP TABLE IF EXISTS `release_feature`;
CREATE TABLE `release_feature` (
`release_id` int(32) NOT NULL AUTO_INCREMENT,
`release_author` char(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`release_date` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0),
`release_number` char(20) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
`release_content` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`release_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
| Humsen/web/docs/数据库部署/第1步 - 创建数据库/release_feature.sql/0 | {
"file_path": "Humsen/web/docs/数据库部署/第1步 - 创建数据库/release_feature.sql",
"repo_id": "Humsen",
"token_count": 431
} | 24 |
package pers.husen.web.bean.vo;
import java.io.Serializable;
import java.util.Date;
/**
*
*
* @author 何明胜
*
* 2017年10月17日
*/
public class ReleaseFeatureVo implements Serializable{
private static final long serialVersionUID = 1L;
private int releaseId;
private String releaseAuthor;
private Date releaseDate;
private String releaseNumber;
private String releaseContent;
@Override
public String toString() {
return "ReleaseFeatureVo [releaseId=" + releaseId + ", releaseAuthor=" + releaseAuthor + ", releaseDate="
+ releaseDate + ", releaseNumber=" + releaseNumber + ", releaseContent=" + releaseContent + "]";
}
/**
* @return the releaseId
*/
public int getReleaseId() {
return releaseId;
}
/**
* @param releaseId the releaseId to set
*/
public void setReleaseId(int releaseId) {
this.releaseId = releaseId;
}
/**
* @return the releaseAuthor
*/
public String getReleaseAuthor() {
return releaseAuthor;
}
/**
* @param releaseAuthor the releaseAuthor to set
*/
public void setReleaseAuthor(String releaseAuthor) {
this.releaseAuthor = releaseAuthor;
}
/**
* @return the releaseDate
*/
public Date getReleaseDate() {
return releaseDate;
}
/**
* @param releaseDate the releaseDate to set
*/
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
/**
* @return the releaseNumber
*/
public String getReleaseNumber() {
return releaseNumber;
}
/**
* @param releaseNumber the releaseNumber to set
*/
public void setReleaseNumber(String releaseNumber) {
this.releaseNumber = releaseNumber;
}
/**
* @return the releaseContent
*/
public String getReleaseContent() {
return releaseContent;
}
/**
* @param releaseContent the releaseContent to set
*/
public void setReleaseContent(String releaseContent) {
this.releaseContent = releaseContent;
}
} | Humsen/web/web-core/src/pers/husen/web/bean/vo/ReleaseFeatureVo.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/bean/vo/ReleaseFeatureVo.java",
"repo_id": "Humsen",
"token_count": 588
} | 25 |
package pers.husen.web.common.helper;
/**
* 获取指定长度的验证码
*
* @author 何明胜
*
* 2017年10月27日
*/
public class RandomCodeHelper {
public static int producedRandomCode(double length) {
int randomCode = (int)(Math.random() * Math.pow(10, length));
//进制系统,这里是10进制
int decimalSystem = 10;
while(randomCode < Math.pow(decimalSystem, length-1) || randomCode >= Math.pow(decimalSystem, length)) {
randomCode = (int)(Math.random() * Math.pow(10, length));
}
return randomCode;
}
} | Humsen/web/web-core/src/pers/husen/web/common/helper/RandomCodeHelper.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/common/helper/RandomCodeHelper.java",
"repo_id": "Humsen",
"token_count": 240
} | 26 |
package pers.husen.web.dao;
import java.util.ArrayList;
import pers.husen.web.bean.vo.FileDownloadVo;
/**
* @author 何明胜
*
* 2017年9月29日
*/
public interface FileDownloadDao {
/**
* 查询下载区数量
*
* @return
*/
public int queryFileTotalCount();
/**
* 查询某一页的下载区
*
* @param pageSize
* @param pageNo
* @return
*/
public ArrayList<FileDownloadVo> queryFileDownlaodPerPage(int pageSize, int pageNo);
/**
* 根据Id查询查询某个下载
* @param fileId
* @return
*/
public FileDownloadVo queryPerFileById(int fileId);
/**
* 插入新纪录到下载区
*
* @param fVo
* @return
*/
public int insertFileDownload(FileDownloadVo fVo);
/**
* 根据file_url更新文件下载次数
* @param fileUrl
* @return
*/
public int updateFileDownCountByUrl(String fileUrl);
} | Humsen/web/web-core/src/pers/husen/web/dao/FileDownloadDao.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dao/FileDownloadDao.java",
"repo_id": "Humsen",
"token_count": 394
} | 27 |
package pers.husen.web.dbutil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pers.husen.web.common.helper.StackTrace2Str;
import pers.husen.web.dbutil.assist.DbConnectUtils;
import pers.husen.web.dbutil.assist.SetPsParamUtils;
import pers.husen.web.dbutil.assist.TypeTransformUtils;
/**
* 数据库查询工具类 DQL
*
* @author 何明胜
*
* 2017年9月21日
*/
public class DbQueryUtils {
private static final Logger logger = LogManager.getLogger(DbQueryUtils.class);
/**
* 根据条件查询 beanVoList
*
* @param sql
* @param paramList
* @param classType
* Vo类 类型
* @return
*/
public static <T> ArrayList<T> queryBeanListByParam(String sql, ArrayList<Object> paramList, Class<T> classType) {
Connection conn = DbConnectUtils.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<T> tVos = null;
try {
ps = conn.prepareStatement(sql);
if (paramList != null && paramList.size() != 0) {
for (int i = 0; i < paramList.size(); i++) {
SetPsParamUtils.setParamInit(i + 1, paramList.get(i), ps);
}
}
logger.info(ps);
rs = ps.executeQuery();
tVos = TypeTransformUtils.resultSet2BeanList(rs, classType);
} catch (Exception e) {
logger.error(StackTrace2Str.exceptionStackTrace2Str(e));
} finally {
DbConnectUtils.closeResouce(rs, ps, conn);
}
return tVos;
}
/**
* 根据条件查询bean
*/
public static <T> T queryBeanByParam(String sql, ArrayList<Object> paramList, Class<T> classType) {
Connection conn = DbConnectUtils.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
T tVo = null;
try {
ps = conn.prepareStatement(sql);
if (paramList != null && paramList.size() != 0) {
for (int i = 0; i < paramList.size(); i++) {
SetPsParamUtils.setParamInit(i + 1, paramList.get(i), ps);
}
}
logger.info(ps);
rs = ps.executeQuery();
tVo = TypeTransformUtils.resultSet2Bean(rs, classType);
} catch (Exception e) {
logger.error(StackTrace2Str.exceptionStackTrace2Str(e));
} finally {
DbConnectUtils.closeResouce(rs, ps, conn);
}
return tVo;
}
public static int queryIntByParam(String sql, ArrayList<Object> paramList) {
return ((Number) queryResultByParam(sql, paramList)).intValue();
}
public static String queryStringByParam(String sql, ArrayList<Object> paramList) {
return (String) queryResultByParam(sql, paramList);
}
public static Date queryDateByParam(String sql, ArrayList<Object> paramList) {
java.sql.Date sqlDate = (java.sql.Date) queryResultByParam(sql, paramList);
Date date = new Date(sqlDate.getTime());
return date;
}
public static boolean queryBooleanByParam(String sql, ArrayList<Object> paramList) {
return (boolean) queryResultByParam(sql, paramList);
}
/**
* 根据条件查询某个字段或者数量 String int Date etc.
*
* @param sql
* @param paramList
* @param classType
* @return
*/
private static Object queryResultByParam(String sql, ArrayList<Object> paramList) {
Connection conn = DbConnectUtils.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
Object result = null;
try {
ps = conn.prepareStatement(sql);
if (paramList != null && paramList.size() != 0) {
for (int i = 0; i < paramList.size(); i++) {
SetPsParamUtils.setParamInit(i + 1, paramList.get(i), ps);
}
}
logger.info(ps);
rs = ps.executeQuery();
if (rs.next()) {
result = rs.getObject(1);
}
} catch (Exception e) {
logger.error(StackTrace2Str.exceptionStackTrace2Str(e));
} finally {
DbConnectUtils.closeResouce(rs, ps, conn);
}
return result;
}
} | Humsen/web/web-core/src/pers/husen/web/dbutil/DbQueryUtils.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dbutil/DbQueryUtils.java",
"repo_id": "Humsen",
"token_count": 1553
} | 28 |
package pers.husen.web.service;
import java.util.ArrayList;
import pers.husen.web.bean.vo.ArticleCategoryVo;
import pers.husen.web.dao.ArticleCategoryDao;
import pers.husen.web.dao.impl.ArticleCategoryDaoImpl;
/**
* @desc 文章分类服务类
*
* @author 何明胜
*
* @created 2017年12月12日 上午10:38:46
*/
public class ArticleCategorySvc implements ArticleCategoryDao {
private static final ArticleCategoryDaoImpl articleCategoryDaoImpl = new ArticleCategoryDaoImpl();
@Override
public int insertCategory(ArticleCategoryVo aVo) {
return articleCategoryDaoImpl.insertCategory(aVo);
}
@Override
public int queryMaxId() {
return articleCategoryDaoImpl.queryMaxId();
}
@Override
public ArrayList<ArticleCategoryVo> queryCategory3Num(String classification) {
return articleCategoryDaoImpl.queryCategory3Num(classification);
}
@Override
public ArrayList<ArticleCategoryVo> queryAllCategory() {
return articleCategoryDaoImpl.queryAllCategory();
}
} | Humsen/web/web-core/src/pers/husen/web/service/ArticleCategorySvc.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/service/ArticleCategorySvc.java",
"repo_id": "Humsen",
"token_count": 325
} | 29 |
package pers.husen.web.servlet.category;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import pers.husen.web.bean.vo.ArticleCategoryVo;
import pers.husen.web.common.constants.RequestConstants;
import pers.husen.web.service.ArticleCategorySvc;
/**
* @desc 文章目录servlet,查询、插入
*
* @author 何明胜
*
* @created 2017年12月12日 上午10:45:48
*/
@WebServlet(urlPatterns = "/category.hms")
public class CategorySvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public CategorySvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
ArticleCategorySvc aSvc = new ArticleCategorySvc();
String requestType = request.getParameter(RequestConstants.PARAM_TYPE);
/** 如果是创建新的分类 **/
if (RequestConstants.REQUEST_TYPE_CREATE.equals(requestType)) {
ArticleCategoryVo aVo = new ArticleCategoryVo();
aVo.setCategoryName(request.getParameter("cateName"));
aVo.setCreateDate(new Date());
int resultInsert = aSvc.insertCategory(aVo);
if (resultInsert == 1) {
int curCateId = aSvc.queryMaxId();
out.println(curCateId);
return;
}
}
/** 如果是查询文章分类(数量不为0的) **/
String queryCategory = RequestConstants.REQUEST_TYPE_QUERY + RequestConstants.MODE_CATEGORY;
if (queryCategory.equals(requestType)) {
String classification = request.getParameter("class");
ArrayList<ArticleCategoryVo> aVos = aSvc.queryCategory3Num(classification);
String json = JSONArray.fromObject(aVos).toString();
out.println(json);
return;
}
/** 如果是查询所有分类 **/
String queryAll = RequestConstants.REQUEST_TYPE_QUERY + RequestConstants.MODE_ALL;
if(queryAll.equals(requestType)) {
ArrayList<ArticleCategoryVo> aVos = aSvc.queryAllCategory();
String json = JSONArray.fromObject(aVos).toString();
out.println(json);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/category/CategorySvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/category/CategorySvt.java",
"repo_id": "Humsen",
"token_count": 981
} | 30 |
package pers.husen.web.servlet.releasefea;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import pers.husen.web.bean.vo.ReleaseFeatureVo;
import pers.husen.web.service.ReleaseFeatureSvc;
/**
* 查询最新的版本特性
*
* @author 何明胜
*
* 2017年10月20日
*/
@WebServlet(urlPatterns="/latestRlseFetr.hms")
public class LatestRlseFetrSvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public LatestRlseFetrSvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
ReleaseFeatureSvc rSvc = new ReleaseFeatureSvc();
ReleaseFeatureVo rVo;
String releaseId = request.getParameter("releaseId");
/** 如果是请求最新版本 id为 null或者0 */
if(releaseId == null || Integer.parseInt(releaseId) == 0) {
rVo = rSvc.queryLatestReleaseFeature();
String json = JSONObject.fromObject(rVo).toString();
out.println(json);
return;
}
/** 如果是请求其他版本 */
if(Integer.parseInt(releaseId) != 0) {
rVo = rSvc.queryReleaseById(Integer.parseInt(releaseId));
String json = JSONObject.fromObject(rVo).toString();
out.println(json);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/releasefea/LatestRlseFetrSvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/releasefea/LatestRlseFetrSvt.java",
"repo_id": "Humsen",
"token_count": 684
} | 31 |
@charset "UTF-8";
.form-group-div-label {
margin-left: 0 !important;
margin-right: 0 !important;
}
.form-div-label {
text-align: left !important;
padding-left: 0;
width: 20%
}
.form-div-input {
padding-right: 0 !important;
}
.form-group-div-input{
padding-left: 0
} | Humsen/web/web-mobile/WebContent/css/login/retrive-pwd.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/css/login/retrive-pwd.css",
"repo_id": "Humsen",
"token_count": 118
} | 32 |
/**
* 加载博客目录
*
* @author 何明胜
*
* 2017年9月18日
*/
/** 加载插件 * */
$.ajax({
url : '/plugins/plugins.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$($('head')[0]).find('script:first').after(data);
}
});
$(function() {
/** 顶部导航栏 **/
$.ajax({
url : '/module/navigation/topbar.html',
async : false,
type : 'GET',
success : function(data) {
$('#menuBarNo').before(data);
}
});
/** 登录控制 **/
$.ajax({
url : '/module/login/login.html',
async : false,
type : 'GET',
success : function(data) {
$('#menuBarNo').before(data);
}
});
/** 右侧导航栏 **/
$.ajax({
url : '/module/navigation/rightbar.html',
async : false,
type : 'GET',
success : function(data) {
$('#fh5co-main').after(data);
}
});
});
//博客总数
var blog_total_num = 0;
var blog_page_size = 5;
$(function(){
queryBlogNum();
queryBlogCatalog(1);
//页面选择
choosePageSize();
});
/**
* 查询博客数量
* @returns
*/
function queryBlogNum(){
$.ajax({
type : 'POST',
async: false,
url : '/blog/query.hms',
data : {
type : 'query_total_num'
},
success : function(response){
blog_total_num = response;
},
error : function(XMLHttpRequest, textStatus){
$.confirm({
title: '博客加载出错',
content: textStatus + ' : ' + XMLHttpRequest.status,
autoClose: 'ok|1000',
type: 'green',
buttons: {
ok: {
text: '确认',
btnClass: 'btn-primary',
},
}
});
}
});
}
/**
* 查询博客目录
*
* @param pageSize
* @param pageNo
* @returns
*/
function queryBlogCatalog(pageNo){
$.ajax({
type : 'POST',
async: false,
url : '/blog/query.hms',
dataType : 'json',
data : {
type : 'query_one_page',
pageSize : blog_page_size,
pageNo : pageNo,
},
success : function(response){
for(x in response){
loadSimpleBlog(response[x]);
}
showPagination(pageNo, 6);//显示分页
},
error : function(XMLHttpRequest, textStatus){
$.confirm({
title: '博客目录加载出错',
content: textStatus + ' : ' + XMLHttpRequest.status,
autoClose: 'ok|1000',
type: 'red',
buttons: {
ok: {
text: '确认',
btnClass: 'btn-primary',
},
}
});
}
});
}
/**
* 加载目录形式的博客
*
* @param blog_data
* @returns
*/
function loadSimpleBlog(blog_data){
$('#list_blog').append('<div class="fh5co-entry padding">'
+ '<span class="fh5co-post-date">' + new Date(blog_data.blogDate.time).format('yyyy-MM-dd hh:mm:ss') + '</span>'
+ '<span class="fh5co-post-date">作者:' + blog_data.userNickName + '</span>'
+ '<span class="fh5co-post-date">浏览' + blog_data.blogRead + '次</span>'
+ '<h2 class="article-title"><input type="hidden" value=' + blog_data.blogId + ' />'
+ '<a href=/blog.hms?blogId=' + blog_data.blogId + '>' + blog_data.blogTitle + '</a></h2>'
+ '<p><b>摘要:</b>' + blog_data.blogSummary + '</p>'
+ '</div>'
+ '</div><hr>');
}
/**
* 显示底部分页
*
* @returns void
*/
function showPagination(currPageNum, paginationMaxLength){
$('#list_blog').append('<hr />'
+ '<div id="pagination" class="text-align-center" pagination="pagination_new" '
+ ' currpagenum=' + currPageNum + ' paginationmaxlength=' + paginationMaxLength + ' totalpages=' + Math.ceil(blog_total_num/blog_page_size)
+ ' onlyonepageshow="true"> '
+ '</div>'
+ '<hr />');
PaginationHelper($('#pagination'), blog_page_size);//显示分页
}
/**
* 选择每页显示博客数量
*
* @returns
*/
function choosePageSize(){
$('#choose_page_size').find('.dropdown-menu').children('li').click(function() {
blog_page_size = $(this).attr('value');
$('#list_blog').html('');
queryBlogNum();
queryBlogCatalog(currentPageNum);
choosePageSize();
});
}
/**
* 实现的点击事件,参数为分页容器的id
* pagination.js调用这里
*
* @param currentPageNum
* @returns
*/
function paginationClick(currentPageNum) {
$('#list_blog').html('');
queryBlogNum();
queryBlogCatalog(currentPageNum);
} | Humsen/web/web-mobile/WebContent/js/article/blog.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/js/article/blog.js",
"repo_id": "Humsen",
"token_count": 2074
} | 33 |
<!-- 上部导航栏 -->
<link rel="stylesheet" href="/css/navigation/topbar.css">
<!-- 登录、注册表单验证 -->
<script src="/js/login/formvalidator.js"></script>
<!-- md5加密 -->
<script src="/js/customize-jquery.md5.js"></script>
<!-- 自定义js -->
<script src="/js/navigation/topbar.js"></script>
<nav id="topBar" class="navbar navbar-default topbar-nav">
<div class="container-fluid">
<div class="navbar-header header-nav">
<a class="navbar-brand navbar-brand-a" href="/"> <span
id="trademark" class="glyphicon glyphicon-header" aria-hidden="true"></span>
</a>
</div>
<div class="access-statistics">
<!-- 今日访问量 -->
<label id="accessToday" class="access-today"></label>
<!-- 总访问量 -->
<label id="accessTotal"></label>
<!-- 当前在线 -->
<label id="onlineCurrent" class="online-current"></label>
<!-- 登录状态显示 -->
<a id="loginBtn" class="btn btn-warning btn-sm topbar-btn-login"
href="#" role="button" data-toggle="modal" data-target="#login"
href=""> <span class="glyphicon glyphicon-user"></span>登录
</a> <a id="registerBtn" class="btn btn-info btn-sm topbar-btn-right"
href="#" role="button" data-toggle="modal" data-target="#register"
href=""> <span class="glyphicon glyphicon-log-in"></span>注册
</a> <a id="persCenterBtn" class="btn btn-success btn-sm topbar-btn-pers"
href="#" role="button" data-toggle="modal" data-target="#" href="">
<span class="glyphicon glyphicon-header"></span>个人中心
</a> <a id="quitLoginBtn" class="btn btn-primary btn-sm topbar-btn-right"
href="#" role="button" data-toggle="modal" data-target="#" href="">
<span class="glyphicon glyphicon-log-out"></span>退出
</a>
</div>
</div>
</nav>
<!-- 选择网站主题 -->
<div class="choose-theme">
<button type="button" class="btn btn-success btn-xs">
下一个主题 <span class="glyphicon glyphicon-forward"></span>
</button>
<a class="btn btn-default btn-xs web-pc-blank"
href="https://demo.hemingsheng.cn/" role="button"><span
class="glyphicon glyphicon-blackboard"></span> 电脑版</a>
</div> | Humsen/web/web-mobile/WebContent/module/navigation/topbar.html/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/module/navigation/topbar.html",
"repo_id": "Humsen",
"token_count": 913
} | 34 |
.CodeMirror-fullscreen {
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
height: auto;
z-index: 9;
}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/display/fullscreen.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/display/fullscreen.css",
"repo_id": "Humsen",
"token_count": 49
} | 35 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.registerHelper("fold", "indent", function(cm, start) {
var tabSize = cm.getOption("tabSize"), firstLine = cm.getLine(start.line);
if (!/\S/.test(firstLine)) return;
var getIndent = function(line) {
return CodeMirror.countColumn(line, null, tabSize);
};
var myIndent = getIndent(firstLine);
var lastLineInFold = null;
// Go through lines until we find a line that definitely doesn't belong in
// the block we're folding, or to the end.
for (var i = start.line + 1, end = cm.lastLine(); i <= end; ++i) {
var curLine = cm.getLine(i);
var curIndent = getIndent(curLine);
if (curIndent > myIndent) {
// Lines with a greater indent are considered part of the block.
lastLineInFold = i;
} else if (!/\S/.test(curLine)) {
// Empty lines might be breaks within the block we're trying to fold.
} else {
// A non-empty line at an indent equal to or less than ours marks the
// start of another block.
break;
}
}
if (lastLineInFold) return {
from: CodeMirror.Pos(start.line, firstLine.length),
to: CodeMirror.Pos(lastLineInFold, cm.getLine(lastLineInFold).length)
};
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/fold/indent-fold.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/fold/indent-fold.js",
"repo_id": "Humsen",
"token_count": 586
} | 36 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var GUTTER_ID = "CodeMirror-lint-markers";
function showTooltip(e, content) {
var tt = document.createElement("div");
tt.className = "CodeMirror-lint-tooltip";
tt.appendChild(content.cloneNode(true));
document.body.appendChild(tt);
function position(e) {
if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px";
tt.style.left = (e.clientX + 5) + "px";
}
CodeMirror.on(document, "mousemove", position);
position(e);
if (tt.style.opacity != null) tt.style.opacity = 1;
return tt;
}
function rm(elt) {
if (elt.parentNode) elt.parentNode.removeChild(elt);
}
function hideTooltip(tt) {
if (!tt.parentNode) return;
if (tt.style.opacity == null) rm(tt);
tt.style.opacity = 0;
setTimeout(function() { rm(tt); }, 600);
}
function showTooltipFor(e, content, node) {
var tooltip = showTooltip(e, content);
function hide() {
CodeMirror.off(node, "mouseout", hide);
if (tooltip) { hideTooltip(tooltip); tooltip = null; }
}
var poll = setInterval(function() {
if (tooltip) for (var n = node;; n = n.parentNode) {
if (n && n.nodeType == 11) n = n.host;
if (n == document.body) return;
if (!n) { hide(); break; }
}
if (!tooltip) return clearInterval(poll);
}, 400);
CodeMirror.on(node, "mouseout", hide);
}
function LintState(cm, options, hasGutter) {
this.marked = [];
this.options = options;
this.timeout = null;
this.hasGutter = hasGutter;
this.onMouseOver = function(e) { onMouseOver(cm, e); };
}
function parseOptions(cm, options) {
if (options instanceof Function) return {getAnnotations: options};
if (!options || options === true) options = {};
if (!options.getAnnotations) options.getAnnotations = cm.getHelper(CodeMirror.Pos(0, 0), "lint");
if (!options.getAnnotations) throw new Error("Required option 'getAnnotations' missing (lint addon)");
return options;
}
function clearMarks(cm) {
var state = cm.state.lint;
if (state.hasGutter) cm.clearGutter(GUTTER_ID);
for (var i = 0; i < state.marked.length; ++i)
state.marked[i].clear();
state.marked.length = 0;
}
function makeMarker(labels, severity, multiple, tooltips) {
var marker = document.createElement("div"), inner = marker;
marker.className = "CodeMirror-lint-marker-" + severity;
if (multiple) {
inner = marker.appendChild(document.createElement("div"));
inner.className = "CodeMirror-lint-marker-multiple";
}
if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) {
showTooltipFor(e, labels, inner);
});
return marker;
}
function getMaxSeverity(a, b) {
if (a == "error") return a;
else return b;
}
function groupByLine(annotations) {
var lines = [];
for (var i = 0; i < annotations.length; ++i) {
var ann = annotations[i], line = ann.from.line;
(lines[line] || (lines[line] = [])).push(ann);
}
return lines;
}
function annotationTooltip(ann) {
var severity = ann.severity;
if (!severity) severity = "error";
var tip = document.createElement("div");
tip.className = "CodeMirror-lint-message-" + severity;
tip.appendChild(document.createTextNode(ann.message));
return tip;
}
function startLinting(cm) {
var state = cm.state.lint, options = state.options;
var passOptions = options.options || options; // Support deprecated passing of `options` property in options
if (options.async || options.getAnnotations.async)
options.getAnnotations(cm.getValue(), updateLinting, passOptions, cm);
else
updateLinting(cm, options.getAnnotations(cm.getValue(), passOptions, cm));
}
function updateLinting(cm, annotationsNotSorted) {
clearMarks(cm);
var state = cm.state.lint, options = state.options;
var annotations = groupByLine(annotationsNotSorted);
for (var line = 0; line < annotations.length; ++line) {
var anns = annotations[line];
if (!anns) continue;
var maxSeverity = null;
var tipLabel = state.hasGutter && document.createDocumentFragment();
for (var i = 0; i < anns.length; ++i) {
var ann = anns[i];
var severity = ann.severity;
if (!severity) severity = "error";
maxSeverity = getMaxSeverity(maxSeverity, severity);
if (options.formatAnnotation) ann = options.formatAnnotation(ann);
if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
className: "CodeMirror-lint-mark-" + severity,
__annotation: ann
}));
}
if (state.hasGutter)
cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,
state.options.tooltips));
}
if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
}
function onChange(cm) {
var state = cm.state.lint;
clearTimeout(state.timeout);
state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);
}
function popupSpanTooltip(ann, e) {
var target = e.target || e.srcElement;
showTooltipFor(e, annotationTooltip(ann), target);
}
function onMouseOver(cm, e) {
var target = e.target || e.srcElement;
if (!/\bCodeMirror-lint-mark-/.test(target.className)) return;
var box = target.getBoundingClientRect(), x = (box.left + box.right) / 2, y = (box.top + box.bottom) / 2;
var spans = cm.findMarksAt(cm.coordsChar({left: x, top: y}, "client"));
for (var i = 0; i < spans.length; ++i) {
var ann = spans[i].__annotation;
if (ann) return popupSpanTooltip(ann, e);
}
}
CodeMirror.defineOption("lint", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
clearMarks(cm);
cm.off("change", onChange);
CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
delete cm.state.lint;
}
if (val) {
var gutters = cm.getOption("gutters"), hasLintGutter = false;
for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
cm.on("change", onChange);
if (state.options.tooltips != false)
CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
startLinting(cm);
}
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/lint/lint.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/lint/lint.js",
"repo_id": "Humsen",
"token_count": 2831
} | 37 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.