text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
import { computed, unref } from 'vue'
import { useGettext } from 'vue3-gettext'
import { FileAction, FileActionOptions } from '../../actions'
import { CreateLinkModal } from '../../../components'
import { useAbility } from '../../ability'
import { LinkShare, isProjectSpaceResource } from '@ownclouders/web-client/src/helpers'
import { useLinkTypes } from '../../links'
import { useLoadingService } from '../../loadingService'
import {
useMessages,
useModals,
useUserStore,
useCapabilityStore,
useSharesStore
} from '../../piniaStores'
import { useClipboard } from '../../clipboard'
import { useClientService } from '../../clientService'
import { SharingLinkType } from '@ownclouders/web-client/src/generated'
export const useFileActionsCreateLink = ({
enforceModal = false,
showMessages = true,
onLinkCreatedCallback = undefined
}: {
enforceModal?: boolean
showMessages?: boolean
onLinkCreatedCallback?: (result: PromiseSettledResult<LinkShare>[]) => Promise<void> | void
} = {}) => {
const clientService = useClientService()
const userStore = useUserStore()
const { showMessage, showErrorMessage } = useMessages()
const { $gettext, $ngettext } = useGettext()
const capabilityStore = useCapabilityStore()
const ability = useAbility()
const loadingService = useLoadingService()
const { defaultLinkType } = useLinkTypes()
const { addLink } = useSharesStore()
const { dispatchModal } = useModals()
const { copyToClipboard } = useClipboard()
const proceedResult = async (result: PromiseSettledResult<LinkShare>[]) => {
const succeeded = result.filter(
(val): val is PromiseFulfilledResult<LinkShare> => val.status === 'fulfilled'
)
if (succeeded.length) {
let successMessage = $gettext('Link has been created successfully')
if (result.length === 1) {
// Only copy to clipboard if the user tries to create one single link
try {
await copyToClipboard(succeeded[0].value.webUrl)
successMessage = $gettext('The link has been copied to your clipboard.')
} catch (e) {
console.warn('Unable to copy link to clipboard', e)
}
}
if (showMessages) {
showMessage({
title: $ngettext(
successMessage,
'Links have been created successfully.',
succeeded.length
)
})
}
}
const failed = result.filter(({ status }) => status === 'rejected')
if (failed.length) {
showErrorMessage({
errors: (failed as PromiseRejectedResult[]).map(({ reason }) => reason),
title: $ngettext('Failed to create link', 'Failed to create links', failed.length)
})
}
if (onLinkCreatedCallback) {
onLinkCreatedCallback(result)
}
}
const handler = async (
{ space, resources }: FileActionOptions,
{ isQuickLink = false }: { isQuickLink?: boolean } = {}
) => {
const passwordEnforced = capabilityStore.sharingPublicPasswordEnforcedFor.read_only === true
if (enforceModal || (passwordEnforced && unref(defaultLinkType) !== SharingLinkType.Internal)) {
dispatchModal({
title: $ngettext(
'Create link for "%{resourceName}"',
'Create links for the selected items',
resources.length,
{ resourceName: resources[0].name }
),
customComponent: CreateLinkModal,
customComponentAttrs: () => ({
space,
resources,
isQuickLink,
callbackFn: proceedResult
}),
hideActions: true
})
return
}
const promises = resources.map((resource) =>
addLink({
clientService,
space,
resource,
options: {
'@libre.graph.quickLink': isQuickLink,
displayName: $gettext('Link'),
type: unref(defaultLinkType)
}
})
)
const result = await loadingService.addTask(() => Promise.allSettled<LinkShare>(promises))
proceedResult(result)
}
const isVisible = ({ resources }: FileActionOptions) => {
if (!resources.length) {
return false
}
for (const resource of resources) {
if (!resource.canShare({ user: userStore.user, ability })) {
return false
}
if (isProjectSpaceResource(resource) && resource.disabled) {
return false
}
}
return true
}
const actions = computed((): FileAction[] => {
return [
{
name: 'create-links',
icon: 'link',
handler: (...args) => handler(...args, { isQuickLink: false }),
label: () => {
return $gettext('Create links')
},
isVisible,
componentType: 'button',
class: 'oc-files-actions-create-links'
},
{
name: 'create-quick-links',
icon: 'link',
handler: (...args) => handler(...args, { isQuickLink: true }),
label: () => {
return $gettext('Create links')
},
isVisible,
componentType: 'button',
class: 'oc-files-actions-create-quick-links'
}
]
})
return {
actions
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsCreateLink.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsCreateLink.ts",
"repo_id": "owncloud",
"token_count": 2004
} | 824 |
import { isSameResource } from '../../../helpers/resource'
import { isLocationTrashActive, isLocationSharesActive } from '../../../router'
import { Resource } from '@ownclouders/web-client'
import { dirname, join } from 'path'
import { WebDAV } from '@ownclouders/web-client/src/webdav'
import {
SpaceResource,
isShareSpaceResource,
extractNameWithoutExtension
} from '@ownclouders/web-client/src/helpers'
import { createFileRouteOptions } from '../../../helpers/router'
import { renameResource as _renameResource } from '../../../helpers/resource'
import { computed } from 'vue'
import { useClientService } from '../../clientService'
import { useRouter } from '../../router'
import { useGettext } from 'vue3-gettext'
import { FileAction, FileActionOptions } from '../types'
import {
useMessages,
useModals,
useCapabilityStore,
useConfigStore,
useResourcesStore
} from '../../piniaStores'
export const useFileActionsRename = () => {
const { showErrorMessage } = useMessages()
const capabilityStore = useCapabilityStore()
const router = useRouter()
const { $gettext } = useGettext()
const clientService = useClientService()
const configStore = useConfigStore()
const { dispatchModal } = useModals()
const resourcesStore = useResourcesStore()
const { setCurrentFolder, upsertResource } = resourcesStore
const getNameErrorMsg = (resource: Resource, newName: string, parentResources = undefined) => {
const newPath =
resource.path.substring(0, resource.path.length - resource.name.length) + newName
if (!newName) {
return $gettext('The name cannot be empty')
}
if (/[/]/.test(newName)) {
return $gettext('The name cannot contain "/"')
}
if (newName === '.') {
return $gettext('The name cannot be equal to "."')
}
if (newName === '..') {
return $gettext('The name cannot be equal to ".."')
}
if (/\s+$/.test(newName)) {
return $gettext('The name cannot end with whitespace')
}
const exists = resourcesStore.resources.find(
(file) => file.path === newPath && resource.name !== newName
)
if (exists) {
const translated = $gettext('The name "%{name}" is already taken')
return $gettext(translated, { name: newName }, true)
}
if (parentResources) {
const exists = parentResources.find(
(file) => file.path === newPath && resource.name !== newName
)
if (exists) {
const translated = $gettext('The name "%{name}" is already taken')
return $gettext(translated, { name: newName }, true)
}
}
return null
}
const renameResource = async (space: SpaceResource, resource: Resource, newName: string) => {
let currentFolder = resourcesStore.currentFolder
try {
const newPath = join(dirname(resource.path), newName)
await (clientService.webdav as WebDAV).moveFiles(space, resource, space, {
path: newPath
})
const isCurrentFolder = isSameResource(resource, currentFolder)
if (isShareSpaceResource(space) && resource.isReceivedShare()) {
space.rename(newName)
if (isCurrentFolder) {
currentFolder = { ...currentFolder } as Resource
currentFolder.name = newName
setCurrentFolder(currentFolder)
return router.push(
createFileRouteOptions(space, {
path: '',
fileId: resource.fileId
})
)
}
const sharedResource = { ...resource }
sharedResource.name = newName
upsertResource(sharedResource)
return
}
if (isCurrentFolder) {
currentFolder = { ...currentFolder } as Resource
_renameResource(space, currentFolder, newPath)
setCurrentFolder(currentFolder)
return router.push(
createFileRouteOptions(space, {
path: newPath,
fileId: resource.fileId
})
)
}
const fileResource = { ...resource } as Resource
_renameResource(space, fileResource, newPath)
upsertResource(fileResource)
} catch (error) {
console.error(error)
let title = $gettext(
'Failed to rename "%{file}" to "%{newName}"',
{ file: resource.name, newName },
true
)
if (error.statusCode === 423) {
title = $gettext(
'Failed to rename "%{file}" to "%{newName}" - the file is locked',
{ file: resource.name, newName },
true
)
}
showErrorMessage({ title, errors: [error] })
}
}
const handler = async ({ space, resources }: FileActionOptions) => {
const currentFolder = resourcesStore.currentFolder
let parentResources
if (isSameResource(resources[0], currentFolder)) {
const parentPath = dirname(currentFolder.path)
parentResources = (await clientService.webdav.listFiles(space, { path: parentPath })).children
}
const areFileExtensionsShown = resourcesStore.areFileExtensionsShown
const onConfirm = async (newName: string) => {
if (!areFileExtensionsShown) {
newName = `${newName}.${resources[0].extension}`
}
await renameResource(space, resources[0], newName)
}
const checkName = (newName: string, setError: (error: string) => void) => {
if (!areFileExtensionsShown) {
newName = `${newName}.${resources[0].extension}`
}
const error = getNameErrorMsg(resources[0], newName, parentResources)
setError(error)
}
const nameWithoutExtension = extractNameWithoutExtension(resources[0])
const modalTitle =
!resources[0].isFolder && !areFileExtensionsShown ? nameWithoutExtension : resources[0].name
const title = resources[0].isFolder
? $gettext('Rename folder %{name}', { name: modalTitle })
: $gettext('Rename file %{name}', { name: modalTitle })
const inputValue =
!resources[0].isFolder && !areFileExtensionsShown ? nameWithoutExtension : resources[0].name
const inputSelectionRange =
resources[0].isFolder || !areFileExtensionsShown
? null
: ([0, nameWithoutExtension.length] as [number, number])
dispatchModal({
variation: 'passive',
title,
confirmText: $gettext('Rename'),
hasInput: true,
inputValue,
inputSelectionRange,
inputLabel: resources[0].isFolder ? $gettext('Folder name') : $gettext('File name'),
onConfirm,
onInput: checkName
})
}
const actions = computed((): FileAction[] => [
{
name: 'rename',
icon: 'pencil',
label: () => {
return $gettext('Rename')
},
handler,
isVisible: ({ resources }) => {
if (isLocationTrashActive(router, 'files-trash-generic')) {
return false
}
if (
isLocationSharesActive(router, 'files-shares-with-me') &&
!capabilityStore.sharingCanRename
) {
return false
}
if (resources.length !== 1) {
return false
}
// FIXME: Remove this check as soon as renaming shares works as expected
// see https://github.com/owncloud/ocis/issues/4866
const rootShareIncluded = configStore.options.routing.fullShareOwnerPaths
? resources.some((r) => r.shareRoot && r.path)
: resources.some((r) => r.shareId && r.path === '/')
if (rootShareIncluded) {
return false
}
if (resources.length === 1 && resources[0].locked) {
return false
}
const renameDisabled = resources.some((resource) => {
return !resource.canRename()
})
return !renameDisabled
},
componentType: 'button',
class: 'oc-files-actions-rename-trigger'
}
])
return {
actions,
// HACK: exported for unit tests:
getNameErrorMsg,
renameResource
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsRename.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsRename.ts",
"repo_id": "owncloud",
"token_count": 3088
} | 825 |
import { SpaceResource } from '@ownclouders/web-client'
import { computed } from 'vue'
import { SpaceAction, SpaceActionOptions } from '../types'
import { useGettext } from 'vue3-gettext'
import { useAbility } from '../../ability'
import { useClientService } from '../../clientService'
import { useLoadingService } from '../../loadingService'
import { buildSpace, isProjectSpaceResource } from '@ownclouders/web-client/src/helpers'
import { Drive } from '@ownclouders/web-client/src/generated'
import { resolveFileNameDuplicate } from '../../../helpers/resource/conflictHandling'
import PQueue from 'p-queue'
import { useRouter } from '../../router'
import { isLocationSpacesActive } from '../../../router'
import { useConfigStore, useMessages, useResourcesStore, useSpacesStore } from '../../piniaStores'
export const useSpaceActionsDuplicate = () => {
const configStore = useConfigStore()
const spacesStore = useSpacesStore()
const { showMessage, showErrorMessage } = useMessages()
const router = useRouter()
const { $gettext } = useGettext()
const ability = useAbility()
const clientService = useClientService()
const loadingService = useLoadingService()
const { upsertResource } = useResourcesStore()
const isProjectsLocation = isLocationSpacesActive(router, 'files-spaces-projects')
const duplicateSpace = async (existingSpace: SpaceResource) => {
const projectSpaces = spacesStore.spaces.filter(isProjectSpaceResource)
const duplicatedSpaceName = resolveFileNameDuplicate(existingSpace.name, '', projectSpaces)
try {
const { data: createdSpace } = await clientService.graphAuthenticated.drives.createDrive(
{
name: duplicatedSpaceName,
description: existingSpace.description,
quota: { total: existingSpace.spaceQuota.total }
},
{}
)
let duplicatedSpace = buildSpace(createdSpace)
const existingSpaceFiles = await clientService.webdav.listFiles(existingSpace)
if (existingSpaceFiles.children.length) {
const queue = new PQueue({
concurrency: configStore.options.concurrentRequests.resourceBatchActions
})
const copyOps = []
for (const file of existingSpaceFiles.children) {
copyOps.push(
queue.add(() =>
clientService.webdav.copyFiles(existingSpace, file, duplicatedSpace, {
path: file.name
})
)
)
}
await Promise.all(copyOps)
}
if (existingSpace.spaceReadmeData || existingSpace.spaceImageData) {
const specialRequestData = {
special: []
}
if (existingSpace.spaceReadmeData) {
const newSpaceReadmeFile = await clientService.webdav.getFileInfo(duplicatedSpace, {
path: `.space/${existingSpace.spaceReadmeData.name}`
})
specialRequestData.special.push({
specialFolder: {
name: 'readme'
},
id: newSpaceReadmeFile.id
})
}
if (existingSpace.spaceImageData) {
const newSpaceImageFile = await clientService.webdav.getFileInfo(duplicatedSpace, {
path: `.space/${existingSpace.spaceImageData.name}`
})
specialRequestData.special.push({
specialFolder: {
name: 'image'
},
id: newSpaceImageFile.id
})
}
const { data: updatedDriveData } =
await clientService.graphAuthenticated.drives.updateDrive(
duplicatedSpace.id.toString(),
specialRequestData as Drive,
{}
)
duplicatedSpace = buildSpace(updatedDriveData)
}
spacesStore.upsertSpace(duplicatedSpace)
if (isProjectsLocation) {
upsertResource(duplicatedSpace)
}
showMessage({
title: $gettext('Space "%{space}" was duplicated successfully', {
space: existingSpace.name
})
})
} catch (error) {
console.error(error)
showErrorMessage({
title: $gettext('Failed to duplicate space "%{space}"', { space: existingSpace.name }),
errors: [error]
})
}
}
const handler = async ({ resources }: SpaceActionOptions) => {
for (const resource of resources) {
if (resource.disabled || !isProjectSpaceResource(resource)) {
continue
}
await duplicateSpace(resource)
}
}
const actions = computed((): SpaceAction[] => [
{
name: 'duplicate',
icon: 'folders',
label: () => $gettext('Duplicate'),
handler: (args) => loadingService.addTask(() => handler(args)),
isVisible: ({ resources }) => {
if (!resources?.length) {
return false
}
if (resources.every((resource) => resource.disabled)) {
return false
}
if (resources.every((resource) => !isProjectSpaceResource(resource))) {
return false
}
return ability.can('create-all', 'Drive')
},
componentType: 'button',
class: 'oc-files-actions-duplicate-trigger'
}
])
return {
actions,
duplicateSpace
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsDuplicate.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsDuplicate.ts",
"repo_id": "owncloud",
"token_count": 2082
} | 826 |
import { computed, unref, Ref } from 'vue'
import { useRouter, useRoute, useRouteParam } from '../router'
import { ClientService } from '../../services'
import { basename } from 'path'
import { FileContext } from './types'
import {
useAppNavigation,
AppNavigationResult,
contextQueryToFileContextProps,
contextRouteNameKey,
queryItemAsString
} from './useAppNavigation'
import { useAppConfig, AppConfigResult } from './useAppConfig'
import { useAppFileHandling, AppFileHandlingResult } from './useAppFileHandling'
import { useAppFolderHandling, AppFolderHandlingResult } from './useAppFolderHandling'
import { useAppDocumentTitle } from './useAppDocumentTitle'
import { RequestResult, useRequest } from '../authContext'
import { useClientService } from '../clientService'
import { MaybeRef } from '../../utils'
import { useDriveResolver } from '../driveResolver'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import { useAppsStore, useAuthStore } from '../piniaStores'
import { storeToRefs } from 'pinia'
// TODO: this file/folder contains file/folder loading logic extracted from preview and drawio extensions
// Discussion how to progress from here can be found in this issue:
// https://github.com/owncloud/web/issues/3301
interface AppDefaultsOptions {
applicationId: string
applicationName?: MaybeRef<string>
clientService?: ClientService
}
export type AppDefaultsResult = AppConfigResult &
AppNavigationResult &
AppFileHandlingResult &
RequestResult &
AppFolderHandlingResult & {
isPublicLinkContext: Ref<boolean>
currentFileContext: Ref<FileContext>
}
export function useAppDefaults(options: AppDefaultsOptions): AppDefaultsResult {
const router = useRouter()
const appsStore = useAppsStore()
const currentRoute = useRoute()
const clientService = options.clientService ?? useClientService()
const applicationId = options.applicationId
const authStore = useAuthStore()
const { publicLinkContextReady } = storeToRefs(authStore)
const driveAliasAndItem = useRouteParam('driveAliasAndItem')
const { space, item, itemId, loading } = useDriveResolver({ driveAliasAndItem })
const currentFileContext = computed((): FileContext => {
if (unref(loading)) {
return null
}
let path: string
if (unref(space)) {
path = urlJoin(unref(space).webDavPath, unref(item))
} else {
// deprecated.
path = urlJoin(unref(currentRoute).params.filePath)
}
return {
path,
driveAliasAndItem: unref(driveAliasAndItem),
space: unref(space),
item: unref(item),
itemId: unref(itemId),
fileName: basename(path),
routeName: queryItemAsString(unref(currentRoute).query[contextRouteNameKey]),
...contextQueryToFileContextProps(unref(currentRoute).query)
}
})
useAppDocumentTitle({
appsStore,
applicationId,
applicationName: options.applicationName,
currentFileContext,
currentRoute
})
return {
isPublicLinkContext: publicLinkContextReady,
currentFileContext,
...useAppConfig({ appsStore, ...options }),
...useAppNavigation({ router, currentFileContext }),
...useAppFileHandling({
clientService
}),
...useAppFolderHandling({
clientService,
currentRoute
}),
...useRequest({ clientService, currentRoute: unref(currentRoute) })
}
}
| owncloud/web/packages/web-pkg/src/composables/appDefaults/useAppDefaults.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/appDefaults/useAppDefaults.ts",
"repo_id": "owncloud",
"token_count": 1080
} | 827 |
export * from './useClipboard'
| owncloud/web/packages/web-pkg/src/composables/clipboard/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/clipboard/index.ts",
"repo_id": "owncloud",
"token_count": 11
} | 828 |
import { Resource } from '@ownclouders/web-client'
import {
extractParentFolderName,
isProjectSpaceResource,
isShareRoot,
isShareSpaceResource
} from '@ownclouders/web-client/src/helpers'
import { useGettext } from 'vue3-gettext'
import { unref } from 'vue'
import { useGetMatchingSpace } from '../spaces'
import path, { dirname } from 'path'
import { ResourceRouteResolverOptions, useResourceRouteResolver } from '../filesList'
import { createLocationShares, createLocationSpaces } from '../../router'
import { useCapabilityStore } from '../piniaStores'
export const useFolderLink = (options: ResourceRouteResolverOptions = {}) => {
const capabilityStore = useCapabilityStore()
const { $gettext } = useGettext()
const { getInternalSpace, getMatchingSpace, isResourceAccessible } = useGetMatchingSpace()
const { createFolderLink } = useResourceRouteResolver(options)
const getPathPrefix = (resource: Resource) => {
const space = unref(options.space) || getMatchingSpace(resource)
if (isProjectSpaceResource(space)) {
return path.join($gettext('Spaces'), space.name)
}
if (isShareSpaceResource(space)) {
return path.join($gettext('Shares'), space.name)
}
return space.name
}
const getFolderLink = (resource: Resource) => {
return createFolderLink({
path: resource.path,
fileId: resource.fileId,
resource
})
}
const getParentFolderLink = (resource: Resource) => {
const space = unref(options.space) || getMatchingSpace(resource)
const parentFolderAccessible = isResourceAccessible({
space,
path: dirname(resource.path)
})
if ((resource.shareId && resource.path === '/') || !parentFolderAccessible) {
return createLocationShares('files-shares-with-me')
}
if (isProjectSpaceResource(resource)) {
return createLocationSpaces('files-spaces-projects')
}
return createFolderLink({
path: dirname(resource.path),
...(resource.parentFolderId && { fileId: resource.parentFolderId }),
resource
})
}
const getParentFolderName = (resource: Resource) => {
const space = unref(options.space) || getMatchingSpace(resource)
const parentFolderAccessible = isResourceAccessible({
space,
path: dirname(resource.path)
})
if (isShareRoot(resource) || !parentFolderAccessible) {
return $gettext('Shared with me')
}
const parentFolder = extractParentFolderName(resource)
if (parentFolder) {
return parentFolder
}
if (isShareSpaceResource(space)) {
return space.name
}
if (capabilityStore.spacesProjects) {
if (isProjectSpaceResource(resource)) {
return $gettext('Spaces')
}
if (space?.driveType === 'project') {
return space.name
}
}
return $gettext('Personal')
}
const getParentFolderLinkIconAdditionalAttributes = (resource: Resource) => {
// Identify if resource is project space or is part of a project space and the resource is located in its root
if (
isProjectSpaceResource(resource) ||
(isProjectSpaceResource(getInternalSpace(resource.storageId) || ({} as Resource)) &&
resource.path.split('/').length === 2)
) {
return {
name: 'layout-grid',
'fill-type': 'fill'
}
}
return {}
}
return {
getPathPrefix,
getFolderLink,
getParentFolderLink,
getParentFolderName,
getParentFolderLinkIconAdditionalAttributes
}
}
| owncloud/web/packages/web-pkg/src/composables/folderLink/useFolderLink.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/folderLink/useFolderLink.ts",
"repo_id": "owncloud",
"token_count": 1217
} | 829 |
import { defineStore } from 'pinia'
import { computed, ref, unref } from 'vue'
import { AppConfigObject, ApplicationInformation, ApplicationFileExtension } from '../../apps'
export const useAppsStore = defineStore('apps', () => {
const apps = ref<Record<string, ApplicationInformation>>({})
const externalAppConfig = ref<Record<string, AppConfigObject>>({})
const fileExtensions = ref<ApplicationFileExtension[]>([])
const appIds = computed(() => Object.keys(unref(apps)))
const registerApp = (appInfo: ApplicationInformation) => {
if (!appInfo.id) {
return
}
if (appInfo.extensions) {
appInfo.extensions.forEach((extension) => {
registerFileExtension({ appId: appInfo.id, data: extension })
})
}
unref(apps)[appInfo.id] = {
applicationMenu: appInfo.applicationMenu || { enabled: () => false },
defaultExtension: appInfo.defaultExtension || '',
icon: 'check_box_outline_blank',
name: appInfo.name || appInfo.id,
...appInfo
}
}
const registerFileExtension = ({
appId,
data
}: {
appId: string
data: ApplicationFileExtension
}) => {
unref(fileExtensions).push({
app: appId,
extension: data.extension,
createFileHandler: data.createFileHandler,
label: data.label,
mimeType: data.mimeType,
routeName: data.routeName,
newFileMenu: data.newFileMenu,
icon: data.icon,
name: data.name,
hasPriority:
data.hasPriority ||
unref(externalAppConfig)?.[appId]?.priorityExtensions?.includes(data.extension) ||
false
})
}
const loadExternalAppConfig = ({ appId, config }: { appId: string; config: AppConfigObject }) => {
externalAppConfig.value = { ...unref(externalAppConfig), [appId]: config }
}
return {
apps,
externalAppConfig,
appIds,
fileExtensions,
registerApp,
registerFileExtension,
loadExternalAppConfig
}
})
export type AppsStore = ReturnType<typeof useAppsStore>
| owncloud/web/packages/web-pkg/src/composables/piniaStores/apps.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/apps.ts",
"repo_id": "owncloud",
"token_count": 749
} | 830 |
import merge from 'deepmerge'
import { defineStore } from 'pinia'
import { computed, ref, unref } from 'vue'
import { useLocalStorage, usePreferredDark } from '@vueuse/core'
import { z } from 'zod'
import { applyCustomProp } from 'design-system/src/'
const AppBanner = z.object({
title: z.string().optional(),
publisher: z.string().optional(),
additionalInformation: z.string().optional(),
ctaText: z.string().optional(),
icon: z.string().optional(),
appScheme: z.string().optional()
})
const CommonSection = z.object({
name: z.string(),
slogan: z.string(),
logo: z.string(),
urls: z.object({
accessDeniedHelp: z.string(),
imprint: z.string(),
privacy: z.string()
})
})
const DesignTokens = z.object({
breakpoints: z.record(z.string()).optional(),
colorPalette: z.record(z.string()).optional(),
fontFamily: z.string().optional(),
fontSizes: z.record(z.string()).optional(),
sizes: z.record(z.string()).optional(),
spacing: z.record(z.string()).optional()
})
const LoginPage = z.object({
autoRedirect: z.boolean(),
backgroundImg: z.string()
})
const Logo = z.object({
topbar: z.string(),
favicon: z.string(),
login: z.string(),
notFound: z.string().optional()
})
const ThemeDefaults = z.object({
appBanner: AppBanner.optional(),
common: CommonSection.optional(),
designTokens: DesignTokens,
loginPage: LoginPage,
logo: Logo
})
const WebTheme = z.object({
appBanner: AppBanner.optional(),
common: CommonSection.optional(),
designTokens: DesignTokens.optional(),
isDark: z.boolean(),
name: z.string(),
loginPage: LoginPage.optional(),
logo: Logo.optional()
})
export const WebThemeConfig = z.object({
defaults: ThemeDefaults,
themes: z.array(WebTheme)
})
export const ThemingConfig = z.object({
common: CommonSection.optional(),
clients: z.object({
web: WebThemeConfig
})
})
export type WebThemeType = z.infer<typeof WebTheme>
export type WebThemeConfigType = z.infer<typeof WebThemeConfig>
const themeStorageKey = 'oc_currentThemeName'
export const useThemeStore = defineStore('theme', () => {
const currentLocalStorageThemeName = useLocalStorage(themeStorageKey, null)
const isDark = usePreferredDark()
const currentTheme = ref<WebThemeType | undefined>()
const availableThemes = ref<WebThemeType[]>([])
const initializeThemes = (themeConfig: WebThemeConfigType) => {
availableThemes.value = themeConfig.themes.map((theme) => merge(themeConfig.defaults, theme))
setThemeFromStorageOrSystem()
}
const setThemeFromStorageOrSystem = () => {
const firstLightTheme = unref(availableThemes).find((theme) => !theme.isDark)
const firstDarkTheme = unref(availableThemes).find((theme) => theme.isDark)
setAndApplyTheme(
unref(availableThemes).find((t) => t.name === unref(currentLocalStorageThemeName)) ||
(unref(isDark) ? firstDarkTheme : firstLightTheme) ||
unref(availableThemes)[0],
false
)
}
const setAutoSystemTheme = () => {
currentLocalStorageThemeName.value = null
setThemeFromStorageOrSystem()
}
const isCurrentThemeAutoSystem = computed(() => {
return currentLocalStorageThemeName.value === null
})
const setAndApplyTheme = (theme: WebThemeType, updateStorage = true) => {
currentTheme.value = theme
if (updateStorage) {
currentLocalStorageThemeName.value = unref(currentTheme).name
}
const customizableDesignTokens = [
{ name: 'breakpoints', prefix: 'breakpoint' },
{ name: 'colorPalette', prefix: 'color' },
{ name: 'fontSizes', prefix: 'font-size' },
{ name: 'sizes', prefix: 'size' },
{ name: 'spacing', prefix: 'spacing' }
]
applyCustomProp('font-family', unref(currentTheme).designTokens.fontFamily)
customizableDesignTokens.forEach((token) => {
for (const param in unref(currentTheme).designTokens[token.name]) {
applyCustomProp(
`${token.prefix}-${param}`,
unref(currentTheme).designTokens[token.name][param]
)
}
})
}
return {
availableThemes,
currentTheme,
initializeThemes,
setAndApplyTheme,
setAutoSystemTheme,
isCurrentThemeAutoSystem
}
})
| owncloud/web/packages/web-pkg/src/composables/piniaStores/theme.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/theme.ts",
"repo_id": "owncloud",
"token_count": 1448
} | 831 |
import { computed, Ref, unref } from 'vue'
import { useRoute } from './useRoute'
export const useRouteMeta = (key: string, defaultValue?: string): Ref<string> => {
const route = useRoute()
return computed(() => (unref(route).meta[key] as string) || defaultValue)
}
| owncloud/web/packages/web-pkg/src/composables/router/useRouteMeta.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/router/useRouteMeta.ts",
"repo_id": "owncloud",
"token_count": 85
} | 832 |
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { useAbility } from '../ability'
import { useCapabilityStore, useUserStore } from '../piniaStores'
import { isProjectSpaceResource, isShareSpaceResource } from '@ownclouders/web-client/src/helpers'
export const useCanShare = () => {
const capabilityStore = useCapabilityStore()
const ability = useAbility()
const userStore = useUserStore()
const canShare = ({ space, resource }: { space: SpaceResource; resource: Resource }) => {
if (!capabilityStore.sharingApiEnabled) {
return false
}
if (isShareSpaceResource(space)) {
return false
}
if (isProjectSpaceResource(space) && !space.isManager(userStore.user)) {
return false
}
return resource.canShare({ ability, user: userStore.user })
}
return { canShare }
}
| owncloud/web/packages/web-pkg/src/composables/shares/useCanShare.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/shares/useCanShare.ts",
"repo_id": "owncloud",
"token_count": 269
} | 833 |
import { computed, ComputedRef, ref, Ref, unref } from 'vue'
import { queryItemAsString } from '../appDefaults'
import { useRouteQueryPersisted } from '../router'
import { FolderViewModeConstants } from './constants'
export function useViewMode(options: ComputedRef<string>): ComputedRef<string> {
if (options) {
return computed(() => unref(options))
}
const viewModeQuery = useRouteQueryPersisted({
name: FolderViewModeConstants.queryName,
defaultValue: FolderViewModeConstants.defaultModeName
})
return computed(() => queryItemAsString(unref(viewModeQuery)))
}
export function useViewSize(options: ComputedRef<string>): ComputedRef<number> {
if (options) {
return computed(() => parseInt(unref(options)))
}
const viewModeSize = useRouteQueryPersisted({
name: FolderViewModeConstants.tilesSizeQueryName,
defaultValue: FolderViewModeConstants.tilesSizeDefault.toString()
})
return computed(() => parseInt(queryItemAsString(unref(viewModeSize))))
}
// doesn't need to be persisted anywhere. Gets re-calculated when the ResourceTiles component gets mounted.
const viewSizeMax = ref<number>(FolderViewModeConstants.tilesSizeMax)
export function useViewSizeMax(): Ref<number> {
return viewSizeMax
}
| owncloud/web/packages/web-pkg/src/composables/viewMode/useViewMode.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/viewMode/useViewMode.ts",
"repo_id": "owncloud",
"token_count": 379
} | 834 |
export * from './cache'
export * from './folderLink'
export * from './resource'
export * from './router'
export * from './share'
export * from './ui'
export * from './breadcrumbs'
export * from './clipboardActions'
export * from './contextMenuDropdown'
export * from './datetime'
export * from './download'
export * from './filesize'
export * from './fuse'
export * from './locale'
export * from './path'
export * from './statusIndicators'
export * from './store'
export * from './binary'
| owncloud/web/packages/web-pkg/src/helpers/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/index.ts",
"repo_id": "owncloud",
"token_count": 161
} | 835 |
export * from './routeOptions'
export * from './buildUrl'
| owncloud/web/packages/web-pkg/src/helpers/router/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/router/index.ts",
"repo_id": "owncloud",
"token_count": 18
} | 836 |
import {
RouteRecordRaw,
RouteLocationNamedRaw,
RouteMeta,
Router,
RouteLocationPathRaw,
RouteLocationRaw
} from 'vue-router'
import { createLocationSpaces } from './spaces'
import { createLocationShares } from './shares'
import { createLocationCommon } from './common'
import { createLocationPublic } from './public'
import { isLocationActive as isLocationActiveNoCompat } from './utils'
import { createLocationTrash } from './trash'
import { urlJoin } from '@ownclouders/web-client/src/utils'
/**
* all route configs created by buildRoutes are deprecated,
* this helper wraps a route config and warns the user that it will go away and redirect to the new location.
*
* @param routeConfig
*/
const deprecatedRedirect = (routeConfig: {
path: string
meta?: RouteMeta
redirect: (to: RouteLocationRaw) => Partial<RouteLocationPathRaw & RouteLocationNamedRaw>
}): RouteRecordRaw => {
return {
meta: { ...routeConfig.meta, authContext: 'anonymous' }, // authContext belongs to the redirect target, not to the redirect itself.
path: routeConfig.path,
redirect: (to) => {
const location = routeConfig.redirect(to)
console.warn(
`route "${routeConfig.path}" is deprecated, use "${
String(location.path) || String(location.name)
}" instead.`
)
return location
}
}
}
/**
* listed routes only exist to keep backwards compatibility intact,
* all routes written in a flat syntax to keep them readable.
*/
export const buildRoutes = (): RouteRecordRaw[] =>
[
{
path: '/list',
redirect: (to) =>
createLocationSpaces('files-spaces-generic', {
...to,
params: { ...to.params, driveAliasAndItem: 'personal/home' }
})
},
{
path: '/list/all/:item(.*)',
redirect: (to) =>
createLocationSpaces('files-spaces-generic', {
...to,
params: {
...to.params,
driveAliasAndItem: urlJoin('personal/home', to.params.item, { leadingSlash: false })
}
})
},
{
path: '/list/favorites',
redirect: (to) => createLocationCommon('files-common-favorites', to)
},
{
path: '/list/shared-with-me',
redirect: (to) => createLocationShares('files-shares-with-me', to)
},
{
path: '/list/shared-with-others',
redirect: (to) => createLocationShares('files-shares-with-others', to)
},
{
path: '/list/shared-via-link',
redirect: (to) => createLocationShares('files-shares-via-link', to)
},
{
path: '/trash-bin',
redirect: (to) => createLocationTrash('files-trash-generic', to)
},
{
path: '/public/list/:item(.*)',
redirect: (to) => createLocationPublic('files-public-link', to)
},
{
path: '/private-link/:fileId',
redirect: (to) => ({ name: 'resolvePrivateLink', params: { fileId: to.params.fileId } })
},
{
path: '/public-link/:token',
redirect: (to) => ({ name: 'resolvePublicLink', params: { token: to.params.token } })
}
].map(deprecatedRedirect)
/**
* same as utils.isLocationActive with the difference that it remaps old route names to new ones and warns
* @param router
* @param comparatives
*/
export const isLocationActive = (
router: Router,
...comparatives: [RouteLocationNamedRaw, ...RouteLocationNamedRaw[]]
): boolean => {
const [first, ...rest] = comparatives.map((c) => {
const newName = {
'files-personal': createLocationSpaces('files-spaces-generic').name,
'files-favorites': createLocationCommon('files-common-favorites').name,
'files-shared-with-others': createLocationShares('files-shares-with-others').name,
'files-shared-with-me': createLocationShares('files-shares-with-me').name,
'files-trashbin ': createLocationTrash('files-trash-generic').name,
'files-public-list': createLocationPublic('files-public-link').name
}[c.name]
if (newName) {
console.warn(`route name "${name}" is deprecated, use "${newName}" instead.`)
}
return {
...c,
...(!!newName && { name: newName })
}
})
return isLocationActiveNoCompat(router, first, ...rest)
}
| owncloud/web/packages/web-pkg/src/router/deprecated.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/router/deprecated.ts",
"repo_id": "owncloud",
"token_count": 1589
} | 837 |
export * from './passwordPolicy'
| owncloud/web/packages/web-pkg/src/services/passwordPolicy/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/services/passwordPolicy/index.ts",
"repo_id": "owncloud",
"token_count": 9
} | 838 |
import { Ref, MaybeRef } from 'vue'
export type StringUnionOrAnyString<T extends string> = T | Omit<string, T>
export type ReadOnlyRef<T> = Readonly<Ref<T>>
export type MaybeReadonlyRef<T> = MaybeRef<T> | ReadOnlyRef<T>
// FIXME: get rid of imports using this re-export
export type { MaybeRef } from 'vue'
| owncloud/web/packages/web-pkg/src/utils/types.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/utils/types.ts",
"repo_id": "owncloud",
"token_count": 105
} | 839 |
import CreateLinkModal from '../../../src/components/CreateLinkModal.vue'
import { defaultComponentMocks, defaultPlugins, mount } from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { PasswordPolicyService } from '../../../src/services'
import { usePasswordPolicyService } from '../../../src/composables/passwordPolicyService'
import { AbilityRule, LinkShare, Resource, ShareRole } from '@ownclouders/web-client/src/helpers'
import { PasswordPolicy } from 'design-system/src/helpers'
import { useEmbedMode } from '../../../src/composables/embedMode'
import { useLinkTypes } from '../../../src/composables/links'
import { ref } from 'vue'
import { CapabilityStore, useSharesStore } from '../../../src/composables/piniaStores'
import { SharingLinkType } from '@ownclouders/web-client/src/generated'
vi.mock('../../../src/composables/embedMode')
vi.mock('../../../src/composables/passwordPolicyService')
vi.mock('../../../src/composables/links', async (importOriginal) => ({
...(await importOriginal<any>()),
useLinkTypes: vi.fn()
}))
const selectors = {
passwordInput: '.link-modal-password-input',
roleElements: '.role-dropdown-list li',
contextMenuToggle: '#link-modal-context-menu-toggle',
confirmBtn: '.link-modal-confirm',
cancelBtn: '.link-modal-cancel'
}
describe('CreateLinkModal', () => {
describe('password input', () => {
it('should be rendered', () => {
const { wrapper } = getWrapper()
expect(wrapper.find(selectors.passwordInput).exists()).toBeTruthy()
})
it('should be disabled for internal links', () => {
const { wrapper } = getWrapper({ defaultLinkType: SharingLinkType.Internal })
expect(wrapper.find(selectors.passwordInput).attributes('disabled')).toBeTruthy()
})
it('should not be rendered if user cannot create public links', () => {
const { wrapper } = getWrapper({
userCanCreatePublicLinks: false,
availableLinkTypes: [SharingLinkType.Internal],
defaultLinkType: SharingLinkType.Internal
})
expect(wrapper.find(selectors.passwordInput).exists()).toBeFalsy()
})
})
describe('link role select', () => {
it('lists all types as roles', () => {
const availableLinkTypes = [
SharingLinkType.View,
SharingLinkType.Internal,
SharingLinkType.Edit
]
const { wrapper } = getWrapper({ availableLinkTypes })
expect(wrapper.findAll(selectors.roleElements).length).toBe(availableLinkTypes.length)
})
})
describe('context menu', () => {
it('should display the button to toggle the context menu', () => {
const { wrapper } = getWrapper()
expect(wrapper.find(selectors.contextMenuToggle).exists()).toBeTruthy()
})
it('should not display the button to toggle the context menu if user cannot create public links', () => {
const { wrapper } = getWrapper({
userCanCreatePublicLinks: false,
availableLinkTypes: [SharingLinkType.Internal],
defaultLinkType: SharingLinkType.Internal
})
expect(wrapper.find(selectors.contextMenuToggle).exists()).toBeFalsy()
})
})
describe('method "confirm"', () => {
it('shows an error if a password is enforced but empty', async () => {
vi.spyOn(console, 'error').mockImplementation(undefined)
const { wrapper } = getWrapper({ passwordEnforced: true })
try {
await wrapper.vm.onConfirm()
} catch (error) {}
expect(wrapper.vm.password.error).toBeDefined()
})
it('does not create links when the password policy is not fulfilled', async () => {
vi.spyOn(console, 'error').mockImplementation(undefined)
const callbackFn = vi.fn()
const { wrapper } = getWrapper({ passwordPolicyFulfilled: false, callbackFn })
try {
await wrapper.vm.onConfirm()
} catch (error) {}
expect(callbackFn).not.toHaveBeenCalled()
})
it('creates links for all resources', async () => {
const callbackFn = vi.fn()
const resources = [mock<Resource>({ isFolder: false }), mock<Resource>({ isFolder: false })]
const { wrapper } = getWrapper({ resources, callbackFn })
await wrapper.vm.onConfirm()
const { addLink } = useSharesStore()
expect(addLink).toHaveBeenCalledTimes(resources.length)
expect(callbackFn).toHaveBeenCalledTimes(1)
})
it('emits event in embed mode including the created links', async () => {
const resources = [mock<Resource>({ isFolder: false })]
const { wrapper, mocks } = getWrapper({ resources, embedModeEnabled: true })
const link = mock<LinkShare>({ webUrl: 'someurl' })
const { addLink } = useSharesStore()
;(addLink as any).mockResolvedValue(link)
await wrapper.vm.onConfirm()
expect(mocks.postMessageMock).toHaveBeenCalledWith('owncloud-embed:share', [link.webUrl])
})
it('shows error messages for links that failed to be created', async () => {
const consoleMock = vi.fn(() => undefined)
vi.spyOn(console, 'error').mockImplementation(consoleMock)
const resources = [mock<Resource>({ isFolder: false })]
const { wrapper } = getWrapper({ resources })
const { addLink } = useSharesStore()
;(addLink as any).mockRejectedValue({ response: {} })
await wrapper.vm.onConfirm()
expect(consoleMock).toHaveBeenCalledTimes(1)
})
it('calls the callback at the end if given', async () => {
const resources = [mock<Resource>({ isFolder: false })]
const callbackFn = vi.fn()
const { wrapper } = getWrapper({ resources, callbackFn })
await wrapper.vm.onConfirm()
expect(callbackFn).toHaveBeenCalledTimes(1)
})
it.each([true, false])(
'correctly passes the quicklink property to createLink',
async (isQuickLink) => {
const resources = [mock<Resource>({ isFolder: false })]
const { wrapper } = getWrapper({ resources, isQuickLink })
await wrapper.vm.onConfirm()
const { addLink } = useSharesStore()
expect(addLink).toHaveBeenCalledWith(
expect.objectContaining({
options: expect.objectContaining({ '@libre.graph.quickLink': isQuickLink })
})
)
}
)
})
})
function getWrapper({
resources = [],
defaultLinkType = SharingLinkType.View,
userCanCreatePublicLinks = true,
passwordEnforced = false,
passwordPolicyFulfilled = true,
embedModeEnabled = false,
callbackFn = undefined,
isQuickLink = false,
availableLinkTypes = [SharingLinkType.Internal, SharingLinkType.View]
}: {
resources?: Resource[]
defaultLinkType?: SharingLinkType
userCanCreatePublicLinks?: boolean
passwordEnforced?: boolean
passwordPolicyFulfilled?: boolean
embedModeEnabled?: boolean
callbackFn?: any
isQuickLink?: boolean
availableLinkTypes?: SharingLinkType[]
} = {}) {
vi.mocked(usePasswordPolicyService).mockReturnValue(
mock<PasswordPolicyService>({
getPolicy: () => mock<PasswordPolicy>({ check: () => passwordPolicyFulfilled })
})
)
vi.mocked(useLinkTypes).mockReturnValue(
mock<ReturnType<typeof useLinkTypes>>({
defaultLinkType: ref(defaultLinkType),
getAvailableLinkTypes: () => availableLinkTypes,
getLinkRoleByType: () => mock<ShareRole>(),
isPasswordEnforcedForLinkType: () => passwordEnforced
})
)
const postMessageMock = vi.fn()
vi.mocked(useEmbedMode).mockReturnValue(
mock<ReturnType<typeof useEmbedMode>>({
isEnabled: ref(embedModeEnabled),
postMessage: postMessageMock
})
)
const mocks = { ...defaultComponentMocks(), postMessageMock }
const abilities = [] as AbilityRule[]
if (userCanCreatePublicLinks) {
abilities.push({ action: 'create-all', subject: 'PublicLink' })
}
const capabilities = {
files_sharing: {
public: {
expire_date: {},
can_edit: true,
can_contribute: true,
alias: true,
password: { enforced_for: { read_only: passwordEnforced } }
}
}
} satisfies Partial<CapabilityStore['capabilities']>
return {
mocks,
wrapper: mount(CreateLinkModal, {
props: {
resources,
isQuickLink,
callbackFn,
modal: undefined
},
global: {
plugins: [
...defaultPlugins({ abilities, piniaOptions: { capabilityState: { capabilities } } })
],
mocks,
provide: mocks,
stubs: { OcTextInput: true, OcDatepicker: true, OcButton: true }
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/CreateLinkModal.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/CreateLinkModal.spec.ts",
"repo_id": "owncloud",
"token_count": 3114
} | 840 |
import ItemFilter from '../../../src/components/ItemFilter.vue'
import { defaultComponentMocks, defaultPlugins, mount } from 'web-test-helpers'
import { queryItemAsString } from '../../../src/composables/appDefaults'
import { OcCheckbox } from 'design-system/src/components'
import { unref } from 'vue'
vi.mock('../../../src/composables/appDefaults')
const filterItems = [
{ id: '1', name: 'Albert Einstein' },
{ id: '2', name: 'Marie Curie' }
]
const selectors = {
filterInput: '.item-filter-input input',
checkboxStub: 'oc-checkbox-stub',
filterListItem: '.item-filter-list-item',
activeFilterListItem: '.item-filter-list-item-active',
clearBtn: '.oc-filter-chip-clear'
}
describe('ItemFilter', () => {
it('renders all items', () => {
const { wrapper } = getWrapper()
expect(wrapper.html()).toMatchSnapshot()
})
it('can use a custom attribute as display name', () => {
const filterItems = [
{ id: '1', displayName: 'Albert Einstein' },
{ id: '2', displayName: 'Marie Curie' }
]
const { wrapper } = getWrapper({
props: { displayNameAttribute: 'displayName', items: filterItems }
})
expect(wrapper.html()).toMatchSnapshot()
})
describe('filter', () => {
it('renders the input field when enabled', () => {
const { wrapper } = getWrapper({
props: { showOptionFilter: true, filterableAttributes: ['name'] }
})
expect(wrapper.find(selectors.filterInput).exists()).toBeTruthy()
})
it.each([
{ filterTerm: '', expectedResult: 2 },
{ filterTerm: 'Albert', expectedResult: 1 },
{ filterTerm: 'invalid', expectedResult: 0 }
])('filters on input', async (data) => {
const { wrapper } = getWrapper({
props: { showOptionFilter: true, filterableAttributes: ['name'] }
})
await wrapper.find(selectors.filterInput).setValue(data.filterTerm)
expect(wrapper.findAll(selectors.filterListItem).length).toBe(data.expectedResult)
})
})
describe('selection', () => {
it('allows selection of multiple items on click', async () => {
const { wrapper } = getWrapper({ props: { allowMultiple: true } })
expect(wrapper.emitted('selectionChange')).toBeFalsy()
let selectionChangeEmits = 0
for (const item of wrapper.findAll(selectors.filterListItem)) {
expect(
item.findComponent<typeof OcCheckbox>(selectors.checkboxStub).props('modelValue')
).toBeFalsy()
await item.trigger('click')
selectionChangeEmits += 1
expect(wrapper.emitted('selectionChange').length).toBe(selectionChangeEmits)
expect(
item.findComponent<typeof OcCheckbox>(selectors.checkboxStub).props('modelValue')
).toBeTruthy()
}
expect(wrapper.vm.selectedItems.length).toBe(wrapper.findAll(selectors.filterListItem).length)
})
it('does not allow selection of multiple items when disabled', async () => {
const { wrapper } = getWrapper({ props: { allowMultiple: false } })
const first = wrapper.findAll(selectors.filterListItem).at(0)
await first.trigger('click')
expect(wrapper.emitted('selectionChange').length).toBe(1)
expect(wrapper.find(selectors.activeFilterListItem).exists()).toBeTruthy()
const second = wrapper.findAll(selectors.filterListItem).at(1)
await second.trigger('click')
expect(wrapper.emitted('selectionChange').length).toBe(2)
expect(wrapper.vm.selectedItems.length).toBe(1)
})
it('does de-select the current selected item on click', async () => {
const { wrapper } = getWrapper({ props: { allowMultiple: true } })
const item = wrapper.findAll(selectors.filterListItem).at(0)
await item.trigger('click')
await item.trigger('click')
expect(wrapper.emitted('selectionChange').length).toBe(2)
expect(
item.findComponent<typeof OcCheckbox>(selectors.checkboxStub).props('modelValue')
).toBeFalsy()
expect(wrapper.vm.selectedItems.length).toBe(0)
})
it('clears the selection when the clear-button is being clicked', async () => {
const { wrapper } = getWrapper({ props: { allowMultiple: true } })
const item = wrapper.findAll(selectors.filterListItem).at(0)
await item.trigger('click')
await wrapper.find(selectors.clearBtn).trigger('click')
expect(wrapper.emitted('selectionChange').length).toBe(2)
expect(
item.findComponent<typeof OcCheckbox>(selectors.checkboxStub).props('modelValue')
).toBeFalsy()
expect(wrapper.vm.selectedItems.length).toBe(0)
})
})
describe('route query', () => {
it('sets the selected item as route query param', async () => {
const { wrapper, mocks } = getWrapper()
const item = wrapper.findAll(selectors.filterListItem).at(0)
const currentRouteQuery = unref(mocks.$router.currentRoute).query
expect(mocks.$router.push).not.toHaveBeenCalled()
await item.trigger('click')
expect(currentRouteQuery[wrapper.vm.queryParam]).toBeDefined()
expect(mocks.$router.push).toHaveBeenCalled()
})
it('sets the selected items initially when given via query param', () => {
const { wrapper } = getWrapper({ initialQuery: '1' })
expect(wrapper.vm.selectedItems).toEqual([filterItems[0]])
})
})
describe('label prop', () => {
it('sets the correct label using getLabel computed property', () => {
const label = 'Filter groups'
const { wrapper } = getWrapper({
props: {
showOptionFilter: true,
filterableAttributes: ['name'],
optionFilterLabel: label
}
})
expect(wrapper.find('.item-filter-input label').text()).toBe(label)
})
it('sets the default label using getLabel computed property when no prop is set', () => {
const label = undefined
const { wrapper } = getWrapper({
props: {
showOptionFilter: true,
filterableAttributes: ['name'],
optionFilterLabel: label
}
})
expect(wrapper.find('.item-filter-input label').text()).toBe('Filter list')
})
})
})
function getWrapper({ props = {}, initialQuery = '' }: any = {}) {
vi.mocked(queryItemAsString).mockImplementation(() => initialQuery)
const mocks = defaultComponentMocks()
return {
mocks,
wrapper: mount(ItemFilter, {
props: {
filterLabel: 'Users',
filterName: 'users',
items: filterItems,
...props
},
slots: {
item(data: any) {
return props.displayNameAttribute ? data.item[props.displayNameAttribute] : data.item.name
}
},
global: {
plugins: [...defaultPlugins()],
mocks,
provide: mocks,
stubs: { OcCheckbox: true }
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/ItemFilter.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/ItemFilter.spec.ts",
"repo_id": "owncloud",
"token_count": 2592
} | 841 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`SpaceQuota component > renders the space storage quota label 1`] = `
"<div class="space-quota">
<p class="oc-mb-s oc-mt-rm">1 B of 10 B used (10% used)</p>
<oc-progress-stub max="100" size="small" variation="primary" indeterminate="false" value="10"></oc-progress-stub>
</div>"
`;
| owncloud/web/packages/web-pkg/tests/unit/components/__snapshots__/SpaceQuota.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/__snapshots__/SpaceQuota.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 132
} | 842 |
import { mock } from 'vitest-mock-extended'
import { unref } from 'vue'
import { defaultComponentMocks, RouteLocation, getComposableWrapper } from 'web-test-helpers'
import { useFileActionsCreateNewShortcut, useModals } from '../../../../../src/composables'
import { Resource, SpaceResource } from '@ownclouders/web-client'
describe('createNewShortcut', () => {
describe('computed property "actions"', () => {
describe('method "isVisible"', () => {
it.each([
{
currentFolderCanCreate: true,
expectedStatus: true
},
{
currentFolderCanCreate: false,
expectedStatus: false
}
])('should be set correctly', ({ currentFolderCanCreate, expectedStatus }) => {
getWrapper({
currentFolder: mock<Resource>({ canCreate: () => currentFolderCanCreate }),
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible()).toBe(expectedStatus)
}
})
})
})
describe('method "handler"', () => {
it('creates a modal', () => {
getWrapper({
setup: async ({ actions }) => {
const { dispatchModal } = useModals()
await unref(actions)[0].handler()
expect(dispatchModal).toHaveBeenCalled()
}
})
})
})
})
})
function getWrapper({
setup,
currentFolder = mock<Resource>()
}: {
setup: (instance: ReturnType<typeof useFileActionsCreateNewShortcut>) => void
currentFolder?: Resource
}) {
const mocks = {
...defaultComponentMocks({
currentRoute: mock<RouteLocation>({ name: 'files-spaces-generic' })
})
}
return {
wrapper: getComposableWrapper(
() => {
const instance = useFileActionsCreateNewShortcut({ space: mock<SpaceResource>() })
setup(instance)
},
{
mocks,
provide: mocks,
pluginOptions: { piniaOptions: { resourcesStore: { currentFolder } } }
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCreateNewShortcut.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCreateNewShortcut.spec.ts",
"repo_id": "owncloud",
"token_count": 825
} | 843 |
import { useSpaceActionsEditQuota } from '../../../../../src/composables/actions'
import { useModals } from '../../../../../src/composables/piniaStores'
import { buildSpace } from '@ownclouders/web-client/src/helpers'
import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers'
import { unref } from 'vue'
import { mock } from 'vitest-mock-extended'
import { Drive } from '@ownclouders/web-client/src/generated'
describe('editQuota', () => {
describe('isVisible property', () => {
it('should be false when not resource given', () => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [] })).toBe(false)
}
})
})
it('should be true when the current user has the "set-space-quota"-permission', () => {
const spaceMock = mock<Drive>({
id: '1',
quota: {},
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
driveType: 'project',
special: null
})
getWrapper({
canEditSpaceQuota: true,
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [buildSpace(spaceMock)] })).toBe(true)
}
})
})
it('should be false when the current user does not have the "set-space-quota"-permission', () => {
const spaceMock = mock<Drive>({
id: '1',
quota: {},
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
driveType: 'project',
special: null
})
getWrapper({
canEditSpaceQuota: false,
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [buildSpace(spaceMock)] })).toBe(false)
}
})
})
})
describe('handler', () => {
it('should create a modal', () => {
getWrapper({
setup: async ({ actions }) => {
const { dispatchModal } = useModals()
await unref(actions)[0].handler({ resources: [] })
expect(dispatchModal).toHaveBeenCalled()
}
})
})
})
})
function getWrapper({
canEditSpaceQuota = false,
setup
}: {
canEditSpaceQuota?: boolean
setup: (instance: ReturnType<typeof useSpaceActionsEditQuota>) => void
}) {
const mocks = defaultComponentMocks()
return {
wrapper: getComposableWrapper(
() => {
const instance = useSpaceActionsEditQuota()
setup(instance)
},
{
mocks,
pluginOptions: {
abilities: canEditSpaceQuota ? [{ action: 'set-quota-all', subject: 'Drive' }] : []
}
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsEditQuota.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsEditQuota.spec.ts",
"repo_id": "owncloud",
"token_count": 1170
} | 844 |
import { ref, unref } from 'vue'
import { usePagination } from '../../../../src/composables'
import { getComposableWrapper } from 'web-test-helpers'
describe('usePagination', () => {
describe('computed items', () => {
const items = [1, 2, 3, 4, 5, 6]
it.each([
{ currentPage: 1, itemsPerPage: 100, expected: [1, 2, 3, 4, 5, 6] },
{ currentPage: 1, itemsPerPage: 2, expected: [1, 2] },
{ currentPage: 2, itemsPerPage: 2, expected: [3, 4] }
])('returns proper paginated items', ({ currentPage, itemsPerPage, expected }) => {
getWrapper({
setup: ({ items }) => {
expect(unref(items)).toEqual(expected)
},
items,
currentPage,
itemsPerPage
})
})
})
describe('computed total', () => {
it.each([
{ itemCount: 1, itemsPerPage: 100, expected: 1 },
{ itemCount: 101, itemsPerPage: 100, expected: 2 },
{ itemCount: 201, itemsPerPage: 100, expected: 3 }
])('returns proper total pages', ({ itemCount, itemsPerPage, expected }) => {
const items = Array(itemCount).fill(1)
getWrapper({
setup: ({ total }) => {
expect(unref(total)).toEqual(expected)
},
items,
currentPage: 1,
itemsPerPage
})
})
})
})
function getWrapper({
setup,
items,
currentPage,
itemsPerPage
}: {
setup: (instance: ReturnType<typeof usePagination>) => void
items: any[]
currentPage: number
itemsPerPage: number
}) {
return {
wrapper: getComposableWrapper(() => {
const instance = usePagination({
items: ref(items),
page: currentPage,
perPage: itemsPerPage,
perPageStoragePrefix: 'unit-tests'
})
setup(instance)
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/pagination/usePagination.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/pagination/usePagination.spec.ts",
"repo_id": "owncloud",
"token_count": 747
} | 845 |
import Cache from '../../../../src/helpers/cache/cache'
const newCache = <T>(vs: T[], ttl?: number, capacity?: number): Cache<number, T> => {
const cache = new Cache<number, T>({ ttl, capacity })
vs.forEach((v, i) => cache.set(i, v))
return cache
}
describe('Cache', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('can set and get entries', () => {
const cacheValues: number[] = [1, 2, 3, 4]
const cache = newCache(cacheValues)
cacheValues.forEach((v, i) => {
expect(cache.get(i)).toBe(v)
})
cache.set(4, 5)
expect(cache.get(4)).toBe(5)
expect(cache.set(5, 6)).toBe(6)
})
it('return all keys', () => {
const cache = newCache([1, 2, 3, 4])
expect(cache.keys()).toMatchObject([0, 1, 2, 3])
})
it('return all values', () => {
const cacheValues: number[] = [1, 2, 3, 4]
const cache = newCache(cacheValues)
expect(cache.values()).toMatchObject(cacheValues)
})
it('return all entries', () => {
const cache = newCache([1, 2, 3, 4])
expect(cache.entries()).toMatchObject([
[0, 1],
[1, 2],
[2, 3],
[3, 4]
])
})
it('can handle ttl', () => {
const cacheValues: number[] = []
const cache = newCache(cacheValues, 50)
cache.set(1, 1)
vi.setSystemTime(new Date().getTime() + 10)
cache.set(2, 2)
expect(cache.get(1)).toBe(1)
expect(cache.get(2)).toBe(2)
expect(cache.values().length).toBe(2)
expect(cache.keys().length).toBe(2)
expect(cache.entries().length).toBe(2)
vi.setSystemTime(new Date().getTime() + 41)
expect(cache.get(1)).toBeFalsy()
expect(cache.get(2)).toBe(2)
expect(cache.values().length).toBe(1)
expect(cache.keys().length).toBe(1)
expect(cache.entries().length).toBe(1)
vi.setSystemTime(new Date().getTime() + 10)
expect(cache.get(2)).toBeFalsy()
expect(cache.values().length).toBe(0)
expect(cache.keys().length).toBe(0)
expect(cache.entries().length).toBe(0)
cache.set(3, 3, 10)
cache.set(4, 4, 20)
cache.set(5, 5, 0)
cache.set(6, 6, 0)
expect(cache.get(3)).toBe(3)
expect(cache.get(4)).toBe(4)
expect(cache.get(5)).toBe(5)
expect(cache.get(6)).toBe(6)
expect(cache.values().length).toBe(4)
expect(cache.keys().length).toBe(4)
expect(cache.entries().length).toBe(4)
vi.setSystemTime(new Date().getTime() + 11)
expect(cache.get(3)).toBeFalsy()
expect(cache.get(4)).toBe(4)
expect(cache.get(5)).toBe(5)
expect(cache.get(6)).toBe(6)
expect(cache.values().length).toBe(3)
expect(cache.keys().length).toBe(3)
expect(cache.entries().length).toBe(3)
vi.setSystemTime(new Date().getTime() + 10)
expect(cache.get(4)).toBeFalsy()
expect(cache.get(5)).toBe(5)
expect(cache.get(6)).toBe(6)
expect(cache.values().length).toBe(2)
expect(cache.keys().length).toBe(2)
expect(cache.entries().length).toBe(2)
})
it('can handle capacity', () => {
const initialValues: number[] = [1, 2, 3, 4, 5]
const newValues: number[] = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
const capacity = 5
const cache = newCache(initialValues, 0, capacity)
newValues.forEach((v) => {
cache.set(v, v)
expect(cache.get(v)).toBe(v)
expect(cache.entries().length).toBe(capacity)
})
})
it('can clear the cache', () => {
const cache = newCache([1, 2, 3, 4, 5])
expect(cache.entries().length).toBe(5)
cache.clear()
expect(cache.entries().length).toBe(0)
})
it('can check if a cache contains a entry for given key', () => {
const values = [1, 2, 3, 4, 5]
const cache = newCache(values)
values.forEach((value) => expect(cache.has(value - 1)).toBeTruthy())
expect(cache.has(5)).toBeFalsy()
})
})
describe('cache', () => {
describe('CacheElement', () => {
let cache
let key, value, key2, value2
let evictSpy
beforeEach(() => {
const options = { ttl: 0, opacity: 0 }
evictSpy = vi.spyOn(Cache.prototype, 'evict')
cache = new Cache<string, string>(options)
key = 'key'
value = 'value'
key2 = 'key2'
value2 = 'value2'
})
it('should set value and be receivable with get', () => {
expect(cache.set(key, value)).toBe(value)
expect(cache.get(key)).toBe(value)
})
it('should evict before any access', () => {
cache.set(key, value)
cache.get(key)
cache.entries()
cache.keys()
cache.values()
cache.has(key)
expect(evictSpy).toHaveBeenCalledTimes(6)
})
it('should delete key', () => {
cache.set(key, value)
cache.set(key2, value2)
expect(cache.delete(key)).toBeTruthy()
expect(cache.get(key)).toBe(undefined)
expect(cache.get(key2)).toBe(value2)
})
it('should clear cache', () => {
cache.set(key, value)
cache.set(key2, value2)
cache.clear()
expect(cache.keys().length).toBe(0)
})
it('should return cache entries', () => {
cache.set(key, value)
cache.set(key2, value2)
expect(cache.entries()).toStrictEqual([
[key, value],
[key2, value2]
])
})
it('should return keys', () => {
cache.set(key, value)
cache.set(key2, value2)
expect(cache.keys()).toStrictEqual([key, key2])
})
it('should return values', () => {
cache.set(key, value)
cache.set(key2, value2)
expect(cache.values()).toStrictEqual([value, value2])
})
it('should return if has key', () => {
cache.set(key, value)
expect(cache.has(key)).toBe(true)
expect(cache.has(key2)).toBe(false)
})
it('should evict expired item', () => {
const oldGetTime = Date.prototype.getTime
Date.prototype.getTime = vi.fn(() => 1487076708000)
cache.set(key, value, 1)
Date.prototype.getTime = oldGetTime
expect(cache.values().length).toBe(0)
})
it('should not evict item that has not expired', () => {
cache.set(key, value, 1000)
expect(cache.values().length).toBe(1)
})
it('should not evict item without ttl', () => {
const oldGetTime = Date.prototype.getTime
Date.prototype.getTime = vi.fn(() => 1487076708000)
cache.set(key, value, 0)
Date.prototype.getTime = oldGetTime
expect(cache.values().length).toBe(1)
})
})
})
| owncloud/web/packages/web-pkg/tests/unit/helpers/cache/cache.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/cache/cache.spec.ts",
"repo_id": "owncloud",
"token_count": 2792
} | 846 |
import { VisibilityObserver } from '../../../src/observer'
let callback
let mockIntersectionObserver
const reset = () => {
mockIntersectionObserver = {
observe: vi.fn(),
disconnect: vi.fn(),
unobserve: vi.fn()
}
window.IntersectionObserver = vi.fn().mockImplementation((cb) => {
callback = cb
return mockIntersectionObserver
})
}
beforeEach(reset)
window.document.body.innerHTML = `<div id="target">foo</div>`
describe('VisibilityObserver', () => {
it.each([
{ onEnter: vi.fn() },
{ onExit: vi.fn() },
{
onEnter: vi.fn(),
onExit: vi.fn()
},
{}
])('observes %p', (cb) => {
const observer = new VisibilityObserver()
observer.observe(document.getElementById('target'), cb)
expect(mockIntersectionObserver.observe).toHaveBeenCalledTimes(Object.keys(cb).length ? 1 : 0)
})
it('handles entered and exited callbacks', () => {
const onEnter = vi.fn()
const onExit = vi.fn()
const observer = new VisibilityObserver()
const target = document.getElementById('target')
observer.observe(target, { onEnter, onExit })
callback([{ isIntersecting: false, intersectionRatio: -1, target }])
expect(onEnter).toHaveBeenCalledTimes(0)
expect(onExit).toHaveBeenCalledTimes(0)
callback([{ isIntersecting: true, intersectionRatio: 1, target }])
expect(onEnter).toHaveBeenCalledTimes(1)
expect(onExit).toHaveBeenCalledTimes(0)
callback([{ isIntersecting: false, intersectionRatio: -1, target }])
expect(onEnter).toHaveBeenCalledTimes(1)
expect(onExit).toHaveBeenCalledTimes(1)
callback([{ isIntersecting: true, intersectionRatio: 1, target }])
expect(onEnter).toHaveBeenCalledTimes(2)
expect(onExit).toHaveBeenCalledTimes(1)
callback([{ isIntersecting: false, intersectionRatio: -1, target }])
expect(onEnter).toHaveBeenCalledTimes(2)
expect(onExit).toHaveBeenCalledTimes(2)
})
it.each(['disconnect', 'unobserve'])('handles %p', (m) => {
const onEnter = vi.fn()
const onExit = vi.fn()
const observer = new VisibilityObserver()
const target = document.getElementById('target')
observer.observe(target, { onEnter, onExit })
observer[m](target)
callback([{ isIntersecting: false, intersectionRatio: -1, target }])
expect(onEnter).toHaveBeenCalledTimes(0)
expect(onExit).toHaveBeenCalledTimes(0)
callback([{ isIntersecting: true, intersectionRatio: 1, target }])
expect(onEnter).toHaveBeenCalledTimes(0)
expect(onExit).toHaveBeenCalledTimes(0)
callback([{ isIntersecting: false, intersectionRatio: -1, target }])
expect(onEnter).toHaveBeenCalledTimes(0)
expect(onExit).toHaveBeenCalledTimes(0)
})
it('unobserves in callback', () => {
const onEnter = vi.fn()
const onExit = vi.fn()
const observer = new VisibilityObserver()
const target = document.getElementById('target')
observer.observe(target, {
onEnter: ({ unobserve }) => {
unobserve()
onEnter()
},
onExit: ({ unobserve }) => {
unobserve()
onExit()
}
})
callback([{ isIntersecting: false, intersectionRatio: -1, target }])
expect(onEnter).toHaveBeenCalledTimes(0)
expect(onExit).toHaveBeenCalledTimes(0)
expect(mockIntersectionObserver.unobserve).toHaveBeenCalledTimes(0)
callback([{ isIntersecting: true, intersectionRatio: 1, target }])
expect(onEnter).toHaveBeenCalledTimes(1)
expect(onExit).toHaveBeenCalledTimes(0)
expect(mockIntersectionObserver.unobserve).toHaveBeenCalledTimes(0)
callback([{ isIntersecting: false, intersectionRatio: -1, target }])
expect(onEnter).toHaveBeenCalledTimes(1)
expect(onExit).toHaveBeenCalledTimes(1)
expect(mockIntersectionObserver.unobserve).toHaveBeenCalledTimes(1)
callback([{ isIntersecting: true, intersectionRatio: 1, target }])
expect(onEnter).toHaveBeenCalledTimes(1)
expect(onExit).toHaveBeenCalledTimes(1)
callback([{ isIntersecting: false, intersectionRatio: -1, target }])
expect(onEnter).toHaveBeenCalledTimes(1)
expect(onExit).toHaveBeenCalledTimes(1)
})
})
| owncloud/web/packages/web-pkg/tests/unit/observer/visibility.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/observer/visibility.spec.ts",
"repo_id": "owncloud",
"token_count": 1598
} | 847 |
<template>
<div id="oc-notifications">
<notification-bell :notification-count="notifications.length" />
<oc-drop
id="oc-notifications-drop"
drop-id="notifications-dropdown"
toggle="#oc-notifications-bell"
mode="click"
:options="{ pos: 'bottom-right', delayHide: 0 }"
class="oc-overflow-auto"
@hide-drop="hideDrop"
@show-drop="showDrop"
>
<div class="oc-flex oc-flex-between oc-flex-middle oc-mb-s">
<span class="oc-text-bold oc-text-large oc-m-rm" v-text="$gettext('Notifications')" />
<oc-button
v-if="notifications.length"
class="oc-notifications-mark-all"
appearance="raw"
@click="deleteNotifications(notifications.map((n) => n.notification_id))"
><span v-text="$gettext('Mark all as read')"
/></oc-button>
</div>
<hr />
<div class="oc-position-relative">
<div v-if="loading" class="oc-notifications-loading">
<div class="oc-notifications-loading-background oc-width-1-1 oc-height-1-1" />
<oc-spinner class="oc-notifications-loading-spinner" size="large" />
</div>
<span
v-if="!notifications.length"
class="oc-notifications-no-new"
v-text="$gettext('Nothing new')"
/>
<oc-list v-else>
<li v-for="(el, index) in notifications" :key="index" class="oc-notifications-item">
<component
:is="el.computedLink ? 'router-link' : 'div'"
class="oc-flex oc-flex-middle oc-my-xs"
:to="el.computedLink"
>
<avatar-image
class="oc-mr-m"
:width="32"
:userid="el.messageRichParameters?.user?.name || el.user"
:user-name="el.messageRichParameters?.user?.displayname || el.user"
/>
<div>
<div v-if="!el.message && !el.messageRich" class="oc-notifications-subject">
<span v-text="el.subject" />
</div>
<div v-if="el.computedMessage" class="oc-notifications-message">
<span v-bind="{ innerHTML: el.computedMessage }" />
</div>
<div
v-if="el.link && el.object_type !== 'local_share'"
class="oc-notifications-link"
>
<a :href="el.link" target="_blank" v-text="el.link" />
</div>
<div v-if="el.datetime" class="oc-text-small oc-text-muted oc-mt-xs">
<span
v-oc-tooltip="formatDate(el.datetime)"
tabindex="0"
v-text="formatDateRelative(el.datetime)"
/>
</div>
</div>
</component>
<hr v-if="index + 1 !== notifications.length" class="oc-my-m" />
</li>
</oc-list>
</div>
</oc-drop>
</div>
</template>
<script lang="ts">
import { onMounted, onUnmounted, ref, unref } from 'vue'
import isEmpty from 'lodash-es/isEmpty'
import { useCapabilityStore, useSpacesStore } from '@ownclouders/web-pkg'
import NotificationBell from './NotificationBell.vue'
import { Notification } from '../../helpers/notifications'
import {
formatDateFromISO,
formatRelativeDateFromISO,
useClientService,
useRoute
} from '@ownclouders/web-pkg'
import { useGettext } from 'vue3-gettext'
import { useTask } from 'vue-concurrency'
import { createFileRouteOptions } from '@ownclouders/web-pkg'
import { MESSAGE_TYPE } from '@ownclouders/web-client/src/sse'
const POLLING_INTERVAL = 30000
export default {
components: {
NotificationBell
},
setup() {
const spacesStore = useSpacesStore()
const capabilityStore = useCapabilityStore()
const clientService = useClientService()
const { current: currentLanguage } = useGettext()
const route = useRoute()
const notifications = ref<Notification[]>([])
const loading = ref(false)
const notificationsInterval = ref()
const dropdownOpened = ref(false)
const formatDate = (date) => {
return formatDateFromISO(date, currentLanguage)
}
const formatDateRelative = (date) => {
return formatRelativeDateFromISO(date, currentLanguage)
}
const messageParameters = [
{ name: 'user', labelAttribute: 'displayname' },
{ name: 'resource', labelAttribute: 'name' },
{ name: 'space', labelAttribute: 'name' },
{ name: 'virus', labelAttribute: 'name' }
]
const getMessage = ({ message, messageRich, messageRichParameters }: Notification) => {
if (messageRich && !isEmpty(messageRichParameters)) {
let interpolatedMessage = messageRich
for (const param of messageParameters) {
if (interpolatedMessage.includes(`{${param.name}}`)) {
const richParam = messageRichParameters[param.name] ?? undefined
if (!richParam) {
return message
}
const label = richParam[param.labelAttribute] ?? undefined
if (!label) {
return message
}
interpolatedMessage = interpolatedMessage.replace(
`{${param.name}}`,
`<strong>${label}</strong>`
)
}
}
return interpolatedMessage
}
return message
}
const getLink = ({ messageRichParameters, object_type }: Notification) => {
if (!messageRichParameters) {
return null
}
if (object_type === 'share') {
return {
name: 'files-shares-with-me',
...(!!messageRichParameters?.share?.id && {
query: { scrollTo: messageRichParameters.share.id }
})
}
}
if (object_type === 'storagespace' && messageRichParameters?.space?.id) {
const space = spacesStore.spaces.find(
(s) => s.fileId === messageRichParameters?.space?.id.split('!')[0] && !s.disabled
)
if (space) {
return {
name: 'files-spaces-generic',
...createFileRouteOptions(space, { path: '', fileId: space.fileId })
}
}
}
return null
}
const setAdditionalData = () => {
loading.value = true
for (const notification of unref(notifications)) {
notification.computedMessage = getMessage(notification)
notification.computedLink = getLink(notification)
}
loading.value = false
}
const fetchNotificationsTask = useTask(function* (signal) {
loading.value = true
try {
const response = yield clientService.httpAuthenticated.get(
'ocs/v2.php/apps/notifications/api/v1/notifications'
)
if (response.headers.get('Content-Length') === '0') {
return
}
const {
ocs: { data = [] }
} = yield response.data
notifications.value =
data?.sort((a, b) => (new Date(b.datetime) as any) - (new Date(a.datetime) as any)) || []
} catch (e) {
console.error(e)
} finally {
if (unref(dropdownOpened)) {
setAdditionalData()
}
loading.value = false
}
}).restartable()
const deleteNotifications = async (ids: string[]) => {
loading.value = true
try {
await clientService.httpAuthenticated.delete(
'ocs/v2.php/apps/notifications/api/v1/notifications',
{ data: { ids } }
)
} catch (e) {
console.error(e)
} finally {
notifications.value = unref(notifications).filter((n) => !ids.includes(n.notification_id))
loading.value = false
}
}
const onSSENotificationEvent = (event) => {
try {
const notification = JSON.parse(event.data) as Notification
if (!notification || !notification.notification_id) {
return
}
notifications.value = [notification, ...unref(notifications)]
} catch (_) {
console.error('Unable to parse sse notification data')
}
}
const hideDrop = () => {
dropdownOpened.value = false
}
const showDrop = () => {
dropdownOpened.value = true
setAdditionalData()
}
onMounted(() => {
fetchNotificationsTask.perform()
if (unref(capabilityStore.supportSSE)) {
clientService.sseAuthenticated.addEventListener(
MESSAGE_TYPE.NOTIFICATION,
onSSENotificationEvent
)
} else {
notificationsInterval.value = setInterval(() => {
fetchNotificationsTask.perform()
}, POLLING_INTERVAL)
}
})
onUnmounted(() => {
if (unref(capabilityStore.supportSSE)) {
clientService.sseAuthenticated.removeEventListener(
MESSAGE_TYPE.NOTIFICATION,
onSSENotificationEvent
)
} else {
clearInterval(unref(notificationsInterval))
}
})
return {
notifications,
fetchNotificationsTask,
loading,
dropdownOpened,
deleteNotifications,
formatDate,
formatDateRelative,
getMessage,
getLink,
hideDrop,
showDrop
}
}
}
</script>
<style lang="scss" scoped>
#oc-notifications-drop {
width: 400px;
max-width: 100%;
max-height: 400px;
}
.oc-notifications {
&-item {
> a {
color: var(--oc-color-text-default);
}
}
&-loading {
* {
position: absolute;
}
&-background {
background-color: var(--oc-color-background-secondary);
opacity: 0.6;
}
&-spinner {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
opacity: 1;
}
}
&-actions {
button:not(:last-child) {
margin-right: var(--oc-space-small);
}
}
&-link {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
width: 300px;
}
}
</style>
| owncloud/web/packages/web-runtime/src/components/Topbar/Notifications.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/components/Topbar/Notifications.vue",
"repo_id": "owncloud",
"token_count": 4593
} | 848 |
import {
ClientService,
createFileRouteOptions,
getIndicators,
ImageDimension,
MessageStore,
PreviewService,
ResourcesStore,
SpacesStore
} from '@ownclouders/web-pkg'
import PQueue from 'p-queue'
import { extractNodeId, extractStorageId } from '@ownclouders/web-client/src/helpers'
import { z } from 'zod'
import { Router } from 'vue-router'
import { Language } from 'vue3-gettext'
const eventSchema = z.object({
itemid: z.string(),
parentitemid: z.string(),
spaceid: z.string().optional()
})
const itemInCurrentFolder = ({
resourcesStore,
parentFolderId
}: {
resourcesStore: ResourcesStore
parentFolderId: string
}) => {
const currentFolder = resourcesStore.currentFolder
if (!currentFolder) {
return false
}
if (!extractNodeId(currentFolder.id)) {
// if we don't have a nodeId here, we have a space (root) as current folder and can only check against the storageId
if (currentFolder.id !== extractStorageId(parentFolderId)) {
return false
}
} else {
if (currentFolder.id !== parentFolderId) {
return false
}
}
return true
}
export const onSSEItemRenamedEvent = async ({
topic,
resourcesStore,
spacesStore,
msg,
clientService,
router
}: {
topic: string
resourcesStore: ResourcesStore
spacesStore: SpacesStore
msg: MessageEvent
clientService: ClientService
router: Router
}) => {
try {
const sseData = eventSchema.parse(JSON.parse(msg.data))
const currentFolder = resourcesStore.currentFolder
const resourceIsCurrentFolder = currentFolder.id === sseData.itemid
const resource = resourceIsCurrentFolder
? currentFolder
: resourcesStore.resources.find((f) => f.id === sseData.itemid)
const space = spacesStore.spaces.find((s) => s.id === resource.storageId)
if (!resource || !space) {
return
}
const updatedResource = await clientService.webdav.getFileInfo(space, {
fileId: sseData.itemid
})
if (resourceIsCurrentFolder) {
resourcesStore.setCurrentFolder(updatedResource)
return router.push(
createFileRouteOptions(space, {
path: updatedResource.path,
fileId: updatedResource.fileId
})
)
}
resourcesStore.upsertResource(updatedResource)
} catch (e) {
console.error(`Unable to parse sse event ${topic} data`, e)
}
}
export const onSSEFileLockingEvent = async ({
topic,
resourcesStore,
spacesStore,
msg,
clientService
}: {
topic: string
resourcesStore: ResourcesStore
spacesStore: SpacesStore
msg: MessageEvent
clientService: ClientService
}) => {
try {
const sseData = eventSchema.parse(JSON.parse(msg.data))
const resource = resourcesStore.resources.find((f) => f.id === sseData.itemid)
const space = spacesStore.spaces.find((s) => s.id === resource.storageId)
if (!resource || !space) {
return
}
const updatedResource = await clientService.webdav.getFileInfo(space, {
fileId: sseData.itemid
})
resourcesStore.upsertResource(updatedResource)
resourcesStore.updateResourceField({
id: updatedResource.id,
field: 'indicators',
value: getIndicators({
resource: updatedResource,
ancestorMetaData: resourcesStore.ancestorMetaData
})
})
} catch (e) {
console.error(`Unable to parse sse event ${topic} data`, e)
}
}
export const onSSEProcessingFinishedEvent = async ({
topic,
resourcesStore,
spacesStore,
msg,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
clientService,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
resourceQueue,
previewService
}: {
topic: string
resourcesStore: ResourcesStore
spacesStore: SpacesStore
msg: MessageEvent
clientService: ClientService
resourceQueue: PQueue
previewService: PreviewService
}) => {
try {
const sseData = eventSchema.parse(JSON.parse(msg.data))
if (!itemInCurrentFolder({ resourcesStore, parentFolderId: sseData.parentitemid })) {
return false
}
const resource = resourcesStore.resources.find((f) => f.id === sseData.itemid)
const space = spacesStore.spaces.find((s) => s.id === resource.storageId)
const isFileLoaded = !!resource
if (isFileLoaded) {
resourcesStore.updateResourceField({
id: sseData.itemid,
field: 'processing',
value: false
})
if (space) {
const preview = await previewService.loadPreview({
resource,
space,
dimensions: ImageDimension.Thumbnail
})
if (preview) {
resourcesStore.updateResourceField({
id: sseData.itemid,
field: 'thumbnail',
value: preview
})
}
}
} else {
// FIXME: we currently cannot do this, we need to block this for ongoing uploads and copy operations
// when fixing revert the changelog removal
// resourceQueue.add(async () => {
// const { resource } = await clientService.webdav.listFilesById({
// fileId: sseData.itemid
// })
// resource.path = urlJoin(currentFolder.path, resource.name)
// resourcesStore.upsertResource(resource)
// })
}
} catch (e) {
console.error(`Unable to parse sse event ${topic} data`, e)
}
}
export const onSSEItemTrashedEvent = async ({
topic,
language,
messageStore,
resourcesStore,
msg
}: {
topic: string
language: Language
resourcesStore: ResourcesStore
messageStore: MessageStore
msg: MessageEvent
}) => {
try {
/**
* TODO: Implement a mechanism to identify the client that initiated the trash event.
* Currently, a timeout is utilized to ensure the frontend business logic execution,
* preventing the user from being prompted to navigate to 'another location'
* if the active current folder has been deleted.
* If the initiating client matches the current client, no action is required.
*/
await new Promise((resolve) => setTimeout(resolve, 500))
const sseData = eventSchema.parse(JSON.parse(msg.data))
const currentFolder = resourcesStore.currentFolder
const resourceIsCurrentFolder = currentFolder.id === sseData.itemid
if (resourceIsCurrentFolder) {
return messageStore.showMessage({
title: language.$gettext(
'The folder you were accessing has been removed. Please navigate to another location.'
)
})
}
const resource = resourcesStore.resources.find((f) => f.id === sseData.itemid)
if (!resource) {
return
}
resourcesStore.removeResources([resource])
} catch (e) {
console.error(`Unable to parse sse event ${topic} data`, e)
}
}
export const onSSEItemRestoredEvent = async ({
topic,
resourcesStore,
spacesStore,
msg,
clientService
}: {
topic: string
resourcesStore: ResourcesStore
spacesStore: SpacesStore
msg: MessageEvent
clientService: ClientService
}) => {
try {
const sseData = eventSchema.parse(JSON.parse(msg.data))
const space = spacesStore.spaces.find((space) => space.id === sseData.spaceid)
if (!space) {
return
}
const resource = await clientService.webdav.getFileInfo(space, {
fileId: sseData.itemid
})
if (!resource) {
return
}
if (!itemInCurrentFolder({ resourcesStore, parentFolderId: resource.parentFolderId })) {
return false
}
resourcesStore.upsertResource(resource)
resourcesStore.updateResourceField({
id: resource.id,
field: 'indicators',
value: getIndicators({
resource,
ancestorMetaData: resourcesStore.ancestorMetaData
})
})
} catch (e) {
console.error(`Unable to parse sse event ${topic} data`, e)
}
}
| owncloud/web/packages/web-runtime/src/container/sse.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/container/sse.ts",
"repo_id": "owncloud",
"token_count": 2792
} | 849 |
<template>
<div id="web-content">
<loading-indicator />
<div id="web-content-header">
<div v-if="isIE11" class="oc-background-muted oc-text-center oc-py-m">
<p class="oc-m-rm" v-text="ieDeprecationWarning" />
</div>
<top-bar :applications-list="applicationsList" />
</div>
<div id="web-content-main" class="oc-px-s oc-pb-s">
<div class="app-container oc-flex">
<app-loading-spinner v-if="isLoading" />
<template v-else>
<sidebar-nav
v-if="isSidebarVisible"
class="app-navigation"
:nav-items="navItems"
:closed="navBarClosed"
@update:nav-bar-closed="setNavBarClosed"
/>
<portal to="app.runtime.mobile.nav">
<mobile-nav v-if="isMobileWidth" :nav-items="navItems" />
</portal>
<router-view
v-for="name in ['default', 'app', 'fullscreen']"
:key="`router-view-${name}`"
class="app-content oc-width-1-1"
:name="name"
/>
</template>
</div>
<portal-target name="app.runtime.footer" />
</div>
<div class="snackbars">
<message-bar />
<upload-info />
</div>
</div>
</template>
<script lang="ts">
import orderBy from 'lodash-es/orderBy'
import {
AppLoadingSpinner,
useAppsStore,
useAuthStore,
useExtensionRegistry,
useLocalStorage
} from '@ownclouders/web-pkg'
import TopBar from '../components/Topbar/TopBar.vue'
import MessageBar from '../components/MessageBar.vue'
import SidebarNav from '../components/SidebarNav/SidebarNav.vue'
import UploadInfo from '../components/UploadInfo.vue'
import MobileNav from '../components/MobileNav.vue'
import { NavItem, getExtensionNavItems } from '../helpers/navItems'
import { LoadingIndicator } from '@ownclouders/web-pkg'
import { useActiveApp, useRoute, useRouteMeta, useSpacesLoading } from '@ownclouders/web-pkg'
import { computed, defineComponent, provide, ref, unref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useGettext } from 'vue3-gettext'
import '@uppy/core/dist/style.min.css'
import { storeToRefs } from 'pinia'
const MOBILE_BREAKPOINT = 640
export default defineComponent({
name: 'ApplicationLayout',
components: {
AppLoadingSpinner,
MessageBar,
MobileNav,
TopBar,
SidebarNav,
UploadInfo,
LoadingIndicator
},
setup() {
const router = useRouter()
const route = useRoute()
const { $gettext } = useGettext()
const authStore = useAuthStore()
const activeApp = useActiveApp()
const extensionRegistry = useExtensionRegistry()
const appsStore = useAppsStore()
const { apps } = storeToRefs(appsStore)
const extensionNavItems = computed(() =>
getExtensionNavItems({ extensionRegistry, appId: unref(activeApp) })
)
// FIXME: we can convert to a single router-view without name (thus without the loop) and without this watcher when we release v6.0.0
watch(
useRoute(),
(route) => {
if (unref(route).matched.length) {
unref(route).matched.forEach((match) => {
const keys = Object.keys(match.components).filter((key) => key !== 'default')
if (keys.length) {
console.warn(
`named components are deprecated, use "default" instead of "${keys.join(
', '
)}" on route ${String(route.name)}`
)
}
})
}
},
{ immediate: true }
)
const requiredAuthContext = useRouteMeta('authContext')
const { areSpacesLoading } = useSpacesLoading()
const isLoading = computed(() => {
if (['anonymous', 'idp'].includes(unref(requiredAuthContext))) {
return false
}
return unref(areSpacesLoading)
})
const isMobileWidth = ref<boolean>(window.innerWidth < MOBILE_BREAKPOINT)
provide('isMobileWidth', isMobileWidth)
const onResize = () => {
isMobileWidth.value = window.innerWidth < MOBILE_BREAKPOINT
}
const navItems = computed<NavItem[]>(() => {
if (!authStore.userContextReady) {
return []
}
const { href: currentHref } = router.resolve(unref(route))
return orderBy(
unref(extensionNavItems).map((item) => {
let active = typeof item.isActive !== 'function' || item.isActive()
if (active) {
active = [item.route, ...(item.activeFor || [])].filter(Boolean).some((currentItem) => {
try {
const comparativeHref = router.resolve(currentItem).href
return currentHref.startsWith(comparativeHref)
} catch (e) {
console.error(e)
return false
}
})
}
const name = typeof item.name === 'function' ? item.name() : item.name
return {
...item,
name: $gettext(name),
active
}
}),
['priority', 'name']
)
})
const isSidebarVisible = computed(() => {
return unref(navItems).length && !unref(isMobileWidth)
})
const navBarClosed = useLocalStorage(`oc_navBarClosed`, false)
const setNavBarClosed = (value: boolean) => {
navBarClosed.value = value
}
return {
apps,
isSidebarVisible,
isLoading,
navItems,
onResize,
isMobileWidth,
navBarClosed,
setNavBarClosed
}
},
computed: {
isIE11() {
return !!(window as any).MSInputMethodContext && !!(document as any).documentMode
},
ieDeprecationWarning() {
return this.$gettext(
'Internet Explorer (your current browser) is not officially supported. For security reasons, please switch to another browser.'
)
},
applicationsList() {
const list = []
Object.values(this.apps).forEach((app) => {
list.push({
...app,
type: 'extension'
})
})
return list.sort(
(a, b) =>
(a.applicationMenu?.priority || Number.MAX_SAFE_INTEGER) -
(b.applicationMenu?.priority || Number.MAX_SAFE_INTEGER)
)
}
},
mounted() {
this.$nextTick(() => {
window.addEventListener('resize', this.onResize)
this.onResize()
})
},
beforeUnmount() {
window.removeEventListener('resize', this.onResize)
}
})
</script>
<style lang="scss">
#web-content {
display: flex;
flex-flow: column;
flex-wrap: nowrap;
height: 100vh;
#web-content-header,
#web-content-main {
flex-shrink: 1;
flex-basis: auto;
}
#web-content-header {
flex-grow: 0;
}
#web-content-main {
align-items: flex-start;
display: flex;
flex-direction: column;
flex-grow: 1;
justify-content: flex-start;
overflow-y: hidden;
.app-container {
height: 100%;
background-color: var(--oc-color-background-default);
border-radius: 15px;
overflow: hidden;
width: 100%;
.app-content {
transition: all 0.35s cubic-bezier(0.34, 0.11, 0, 1.12);
}
}
}
.snackbars {
position: absolute;
right: 20px;
bottom: 20px;
z-index: calc(var(--oc-z-index-modal) + 1);
@media (max-width: 640px) {
left: 0;
right: 0;
margin: 0 auto;
width: 100%;
max-width: 500px;
}
}
}
</style>
| owncloud/web/packages/web-runtime/src/layouts/Application.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/layouts/Application.vue",
"repo_id": "owncloud",
"token_count": 3298
} | 850 |
import { SubjectRawRule } from '@casl/ability'
import { AbilityActions, AbilitySubjects } from '@ownclouders/web-client/src/helpers/resource/types'
export const getAbilities = (
permissions: string[]
): SubjectRawRule<AbilityActions, AbilitySubjects, any>[] => {
const abilities: Record<string, SubjectRawRule<AbilityActions, AbilitySubjects, any>[]> = {
'Accounts.ReadWrite.all': [
{ action: 'create-all', subject: 'Account' },
{ action: 'delete-all', subject: 'Account' },
{ action: 'read-all', subject: 'Account' },
{ action: 'update-all', subject: 'Account' }
],
'Favorites.List.own': [{ action: 'read', subject: 'Favorite' }],
'Favorites.Write.own': [
{ action: 'create', subject: 'Favorite' },
{ action: 'update', subject: 'Favorite' }
],
'Groups.ReadWrite.all': [
{ action: 'create-all', subject: 'Group' },
{ action: 'delete-all', subject: 'Group' },
{ action: 'read-all', subject: 'Group' },
{ action: 'update-all', subject: 'Group' }
],
'Language.ReadWrite.all': [
{ action: 'read-all', subject: 'Language' },
{ action: 'update-all', subject: 'Language' }
],
'Logo.Write.all': [{ action: 'update-all', subject: 'Logo' }],
'PublicLink.Write.all': [{ action: 'create-all', subject: 'PublicLink' }],
'ReadOnlyPublicLinkPassword.Delete.all': [
{ action: 'delete-all', subject: 'ReadOnlyPublicLinkPassword' }
],
'Roles.ReadWrite.all': [
{ action: 'create-all', subject: 'Role' },
{ action: 'delete-all', subject: 'Role' },
{ action: 'read-all', subject: 'Role' },
{ action: 'update-all', subject: 'Role' }
],
'Shares.Write.all': [
{ action: 'create-all', subject: 'Share' },
{ action: 'update-all', subject: 'Share' }
],
'Settings.ReadWrite.all': [
{ action: 'read-all', subject: 'Setting' },
{ action: 'update-all', subject: 'Setting' }
],
'Drives.Create.all': [{ action: 'create-all', subject: 'Drive' }],
'Drives.ReadWriteEnabled.all': [
{ action: 'delete-all', subject: 'Drive' },
{ action: 'update-all', subject: 'Drive' }
],
'Drives.List.all': [{ action: 'read-all', subject: 'Drive' }],
'Drives.ReadWriteProjectQuota.all': [{ action: 'set-quota-all', subject: 'Drive' }]
}
return Object.keys(abilities).reduce((acc, permission) => {
if (permissions.includes(permission)) {
acc.push(...abilities[permission])
}
return acc
}, [])
}
| owncloud/web/packages/web-runtime/src/services/auth/abilities.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/services/auth/abilities.ts",
"repo_id": "owncloud",
"token_count": 983
} | 851 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`OcSidebarNav > renders navItem with toolTip if collapsed 1`] = `
"<li class="oc-sidebar-nav-item oc-pb-xs oc-px-s" id="123">
<router-link-stub to="/files/list/all" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw oc-sidebar-nav-item-link oc-oc-width-1-1" data-nav-id="5" data-nav-name="route.name"></router-link-stub>
</li>"
`;
exports[`OcSidebarNav > renders navItem without toolTip if expanded 1`] = `
"<li class="oc-sidebar-nav-item oc-pb-xs oc-px-s" id="123">
<router-link-stub to="/files/list/all" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw oc-sidebar-nav-item-link oc-oc-width-1-1" data-nav-id="5" data-nav-name="route.name"></router-link-stub>
</li>"
`;
| owncloud/web/packages/web-runtime/tests/unit/components/SidebarNav/__snapshots__/SidebarNavItem.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/SidebarNav/__snapshots__/SidebarNavItem.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 381
} | 852 |
import { mock } from 'vitest-mock-extended'
import { createApp, defineComponent, App } from 'vue'
import { useAppsStore, useConfigStore } from '@ownclouders/web-pkg'
import {
initializeApplications,
announceApplicationsReady,
announceCustomScripts,
announceCustomStyles,
announceConfiguration
} from '../../../src/container/bootstrap'
import { buildApplication } from '../../../src/container/application'
import { createTestingPinia } from 'web-test-helpers/src'
vi.mock('../../../src/container/application')
// @vitest-environment jsdom
describe('initialize applications', () => {
beforeEach(() => {
createTestingPinia()
})
it('continues even if one or more applications are falsy', async () => {
const fishyError = new Error('fishy')
const initialize = vi.fn()
const ready = vi.fn()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const buildApplicationMock = vi
.fn()
.mockImplementation(({ applicationPath }: { applicationPath: string }) => {
if (applicationPath.includes('Valid')) {
return Promise.resolve({ initialize, ready })
}
return Promise.reject(fishyError)
})
vi.mocked(buildApplication).mockImplementation(buildApplicationMock)
const configStore = useConfigStore()
configStore.apps = ['internalFishy', 'internalValid']
configStore.externalApps = [{ path: 'externalFishy' }, { path: 'externalValid' }]
const applications = await initializeApplications({
app: createApp(defineComponent({})),
configStore,
router: undefined,
gettext: undefined,
supportedLanguages: {}
})
expect(buildApplicationMock).toHaveBeenCalledTimes(4)
expect(initialize).toHaveBeenCalledTimes(2)
expect(errorSpy).toHaveBeenCalledTimes(2)
expect(errorSpy.mock.calls[0][0]).toMatchObject(fishyError)
expect(errorSpy.mock.calls[1][0]).toMatchObject(fishyError)
createTestingPinia()
await announceApplicationsReady({
app: mock<App>(),
appsStore: useAppsStore(),
applications
})
expect(ready).toHaveBeenCalledTimes(2)
})
})
describe('announceCustomScripts', () => {
beforeEach(() => {
createTestingPinia()
})
afterEach(() => {
document.getElementsByTagName('html')[0].innerHTML = ''
})
it('injects basic scripts', () => {
const configStore = useConfigStore()
configStore.scripts = [{ src: 'foo.js' }, { src: 'bar.js' }]
announceCustomScripts({ configStore })
const elements = document.getElementsByTagName('script')
expect(elements.length).toBe(2)
})
it('skips the injection if no src option is provided', () => {
const configStore = useConfigStore()
configStore.scripts = [{}, {}, {}, {}, {}]
announceCustomScripts({ configStore })
const elements = document.getElementsByTagName('script')
expect(elements.length).toBeFalsy()
})
it('loads scripts synchronous by default', () => {
const configStore = useConfigStore()
configStore.scripts = [{ src: 'foo.js' }]
announceCustomScripts({ configStore })
const element = document.querySelector<HTMLScriptElement>('[src="foo.js"]')
expect(element.async).toBeFalsy()
})
it('injects scripts async if the corresponding configurations option is set', () => {
const configStore = useConfigStore()
configStore.scripts = [{ src: 'foo.js', async: true }]
announceCustomScripts({ configStore })
const element = document.querySelector<HTMLScriptElement>('[src="foo.js"]')
expect(element.async).toBeTruthy()
})
})
describe('announceCustomStyles', () => {
beforeEach(() => {
createTestingPinia()
})
afterEach(() => {
document.getElementsByTagName('html')[0].innerHTML = ''
})
it('injects basic styles', () => {
const styles = [{ href: 'foo.css' }, { href: 'bar.css' }]
const configStore = useConfigStore()
configStore.styles = styles
announceCustomStyles({ configStore })
styles.forEach(({ href }) => {
const element = document.querySelector<HTMLLinkElement>(`[href="${href}"]`)
expect(element).toBeTruthy()
expect(element.type).toBe('text/css')
expect(element.rel).toBe('stylesheet')
})
})
it('skips the injection if no href option is provided', () => {
const configStore = useConfigStore()
configStore.styles = [{}, {}]
announceCustomStyles({ configStore })
const elements = document.getElementsByTagName('link')
expect(elements.length).toBeFalsy()
})
})
describe('announceConfiguration', () => {
beforeEach(() => {
createTestingPinia({ stubActions: false })
})
it('should not enable embed mode when it is not set', async () => {
vi.spyOn(global, 'fetch').mockResolvedValue(
mock<Response>({
status: 200,
json: () => Promise.resolve({ theme: '', server: '', options: {} })
})
)
const configStore = useConfigStore()
await announceConfiguration({ path: '/config.json', configStore })
expect(configStore.options.embed.enabled).toStrictEqual(false)
})
it('should embed mode when it is set in config.json', async () => {
vi.spyOn(global, 'fetch').mockResolvedValue(
mock<Response>({
status: 200,
json: () =>
Promise.resolve({ theme: '', server: '', options: { embed: { enabled: true } } })
})
)
const configStore = useConfigStore()
await announceConfiguration({ path: '/config.json', configStore })
expect(configStore.options.embed.enabled).toStrictEqual(true)
})
it('should enable embed mode when it is set in URL query but config.json does not set it', async () => {
Object.defineProperty(window, 'location', {
value: {
search: '?embed=true'
},
writable: true
})
vi.spyOn(global, 'fetch').mockResolvedValue(
mock<Response>({
status: 200,
json: () => Promise.resolve({ theme: '', server: '', options: {} })
})
)
const configStore = useConfigStore()
await announceConfiguration({ path: '/config.json', configStore })
expect(configStore.options.embed.enabled).toStrictEqual(true)
})
it('should not enable the embed mode when it is set in URL query but config.json disables it', async () => {
Object.defineProperty(window, 'location', {
value: {
search: '?embed=true'
},
writable: true
})
vi.spyOn(global, 'fetch').mockResolvedValue(
mock<Response>({
status: 200,
json: () =>
Promise.resolve({ theme: '', server: '', options: { embed: { enabled: false } } })
})
)
const configStore = useConfigStore()
await announceConfiguration({ path: '/config.json', configStore })
expect(configStore.options.embed.enabled).toStrictEqual(false)
})
})
| owncloud/web/packages/web-runtime/tests/unit/container/bootstrap.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/container/bootstrap.spec.ts",
"repo_id": "owncloud",
"token_count": 2442
} | 853 |
import { mock } from 'vitest-mock-extended'
import { SpaceResource } from '../../../web-client/src'
import { useGetMatchingSpace } from '../../../web-pkg'
export const useGetMatchingSpaceMock = (
options: Partial<ReturnType<typeof useGetMatchingSpace>> = {}
): ReturnType<typeof useGetMatchingSpace> => {
return {
getInternalSpace() {
return mock<SpaceResource>()
},
getMatchingSpace() {
return mock<SpaceResource>()
},
isResourceAccessible() {
return false
},
isPersonalSpaceRoot() {
return false
},
...options
}
}
| owncloud/web/packages/web-test-helpers/src/mocks/useGetMatchingSpaceMock.ts/0 | {
"file_path": "owncloud/web/packages/web-test-helpers/src/mocks/useGetMatchingSpaceMock.ts",
"repo_id": "owncloud",
"token_count": 215
} | 854 |
/**
*
* @param {string} enableOrDisable
* @param {string} selector
* @param {string} strategy which selection strategy to use 'css selector' or 'xpath'
*/
exports.command = function (enableOrDisable, selector, strategy = 'css selector') {
this.element(strategy, selector, (response) => {
this.elementIdSelected(response.value.ELEMENT, (result) => {
const checked = result.value === true
if (
(enableOrDisable === 'disable' && checked) ||
(enableOrDisable === 'enable' && !checked)
) {
// if the checkbox needs to be unchecked but it is checked
// Or the checkbox needs to be checked but it is unchecked
if (strategy === 'xpath') {
this.useXpath().click(selector).useCss()
} else {
this.click(selector)
}
} else if (enableOrDisable !== 'enable' && enableOrDisable !== 'disable') {
throw new Error(`Expected 'enable' or 'disable', ${enableOrDisable} given`)
}
})
})
return this
}
| owncloud/web/tests/acceptance/customCommands/toggleCheckbox.js/0 | {
"file_path": "owncloud/web/tests/acceptance/customCommands/toggleCheckbox.js",
"repo_id": "owncloud",
"token_count": 378
} | 855 |
Feature: move files
As a user
I want to move files
So that I can organise my data structure
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
And user "Alice" has uploaded file "lorem.txt" to "lorem.txt" in the server
Scenario: An attempt to move a file into a sub-folder using rename is not allowed
Given user "Alice" has logged in using the webUI
And the user has browsed to the personal page
When the user tries to rename file "lorem.txt" to "simple-folder/lorem.txt" using the webUI
Then the error message 'The name cannot contain "/"' should be displayed on the webUI dialog prompt
And file "lorem.txt" should be listed on the webUI
Scenario Outline: move a file into a folder (problematic characters)
Given user "Alice" has logged in using the webUI
And the user has browsed to the personal page
When the user renames file "lorem.txt" to <file_name> using the webUI
And the user renames folder "simple-folder" to <folder_name> using the webUI
And the user moves file <file_name> into folder <folder_name> using the webUI
Then breadcrumb for folder <folder_name> should be displayed on the webUI
And file <file_name> should be listed on the webUI
Examples:
| file_name | folder_name |
| "'single'" | "folder-with-'single'" |
# | "\"double\" quotes" | "folder-with\"double\" quotes" | FIXME: Needs a way to access breadcrumbs with double quotes issue-3734
| "question?" | "folder-with-question?" |
| "&and#hash" | "folder-with-&and#hash" |
Scenario: move files on a 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 shared folder "simple-folder" with link with "read, update, create, delete" permissions in the server
And the public uses the webUI to access the last public link created by user "Alice" in a new session
And the user moves file "data.zip" into folder "simple-empty-folder" using the webUI
Then breadcrumb for folder "simple-empty-folder" should be displayed on the webUI
And file "data.zip" should be listed on the webUI
And as "Alice" file "simple-folder/simple-empty-folder/data.zip" should exist in the server
But as "Alice" file "simple-folder/data.zip" should not exist in the server
| owncloud/web/tests/acceptance/features/webUIMoveFilesFolders/moveFiles.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUIMoveFilesFolders/moveFiles.feature",
"repo_id": "owncloud",
"token_count": 788
} | 856 |
@public_link_share-feature-required @disablePreviews
Feature: Public link share indicator
As a user
I want to check share indicator
So that I can know with resources are shared
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
@issue-2060
Scenario: sharing indicator inside a shared folder
Given user "Alice" has created folder "/simple-folder/sub-folder" in the server
And user "Alice" has uploaded file with content "test" to "/simple-folder/textfile.txt" in the server
And user "Alice" has shared folder "simple-folder" with link with "read" permissions in the server
When user "Alice" has logged in using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| simple-folder | link-direct |
When the user opens folder "simple-folder" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| sub-folder | link-indirect |
| textfile.txt | link-indirect |
@issue-2060
Scenario: sharing indicator for file uploaded inside a shared folder
Given user "Alice" has shared folder "simple-folder" with link with "read" permissions in the server
And user "Alice" has logged in using the webUI
When the user opens folder "simple-folder" using the webUI
And the user uploads file "new-lorem.txt" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| new-lorem.txt | link-indirect |
@issue-2060
Scenario: sharing indicator for folder created inside a shared folder
Given user "Alice" has shared folder "simple-folder" with link with "read" permissions in the server
And user "Alice" has logged in using the webUI
When the user opens folder "simple-folder" using the webUI
And the user creates a folder with the name "sub-folder" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| sub-folder | link-indirect |
@issue-2060
Scenario: sharing indicators public link and collaborators inside a shared folder
Given user "Brian" has been created with default attributes and without skeleton files in the server
And user "Alice" has created folder "/simple-folder/sub-folder" in the server
And user "Alice" has uploaded file with content "test" to "/simple-folder/textfile.txt" in the server
And user "Alice" has shared folder "simple-folder" with link with "read" permissions in the server
And user "Alice" has shared folder "simple-folder" with user "Brian" in the server
When user "Alice" has logged in using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| simple-folder | link-direct,user-direct |
When the user opens folder "simple-folder" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| sub-folder | link-indirect,user-indirect |
| textfile.txt | link-indirect,user-indirect |
@issue-2939
Scenario: sharing indicator for link shares stays up to date
Given user "Brian" has been created with default attributes and without skeleton files in the server
And user "Alice" has uploaded file "testavatar.png" to "simple-folder/testimage.png" in the server
When user "Alice" has logged in using the webUI
Then the following resources should not have share indicators on the webUI
| simple-folder |
When the user shares folder "simple-folder" with user "Brian Murphy" as "Viewer" using the webUI
And the user creates a new public link for resource "simple-folder" using the webUI
And the user renames the most recently created public link of resource "simple-folder" to "first"
And the user creates a new public link for resource "simple-folder" using the webUI
And the user renames the most recently created public link of resource "simple-folder" to "second"
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| simple-folder | user-direct,link-direct |
When the user opens folder "simple-folder" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| testimage.png | user-indirect,link-indirect |
When the user creates a new public link for resource "testimage.png" using the webUI
And the user renames the most recently created public link of resource "testimage.png" to "third"
# the indicator changes from link-indirect to link-direct to show the direct share
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| testimage.png | user-indirect,link-direct |
# removing the last link reverts the indicator to user-indirect
When the user removes the public link named "third" of resource "testimage.png" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| testimage.png | user-indirect,link-indirect |
When the user opens folder "" directly on the webUI
And the user removes the public link named "second" of resource "simple-folder" using the webUI
# because there is still another link share left, the indicator stays
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| simple-folder | user-direct,link-direct |
# deleting the last collaborator removes the indicator
When the user removes the public link named "first" of resource "simple-folder" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| simple-folder | user-direct |
| owncloud/web/tests/acceptance/features/webUISharingPublicManagement/publicLinkIndicator.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUISharingPublicManagement/publicLinkIndicator.feature",
"repo_id": "owncloud",
"token_count": 1863
} | 857 |
const httpHelper = require('../helpers/httpHelper')
/**
* Run occ command using the testing API
*
* @param {Array} args
*/
exports.runOcc = async function (args) {
const params = new URLSearchParams()
params.append('command', args.join(' '))
const apiURL = 'apps/testing/api/v1/occ'
const res = await httpHelper.postOCS(apiURL, 'admin', params).then((res) => {
return httpHelper.checkStatus(res, 'Failed while executing occ command')
})
const json = await res.json()
await httpHelper.checkOCSStatus(json, 'Failed while executing occ command')
await clearOpCache()
return json
}
const clearOpCache = async function () {
const apiURL = 'apps/testing/api/v1/opcache'
try {
const res = await httpHelper.deleteOCS(apiURL, 'admin').then((res) => {
return httpHelper.checkStatus(res, 'Failed while resetting the opcache')
})
const json = await res.json()
return httpHelper.checkOCSStatus(json, 'Failed while resetting the opcache')
} catch {
console.log(
'\x1b[33m%s\x1b[0m',
"could not reset opcache, if tests fail try to set 'opcache.revalidate_freq=0' in the php.ini file\n"
)
}
}
| owncloud/web/tests/acceptance/helpers/occHelper.js/0 | {
"file_path": "owncloud/web/tests/acceptance/helpers/occHelper.js",
"repo_id": "owncloud",
"token_count": 406
} | 858 |
const util = require('util')
const assert = require('assert')
const xpathHelper = require('../../helpers/xpath')
const { client } = require('nightwatch-api')
const appSideBar = client.page.FilesPageElement.appSideBar()
const contextMenu = client.page.FilesPageElement.contextMenu()
const filesRow = client.page.FilesPageElement.filesRow()
const fileActionsMenu = client.page.FilesPageElement.fileActionsMenu()
module.exports = {
commands: {
/**
* @param resource
* @returns {Promise<void>}
*/
openDetailsDialog: async function (resource) {
await this.openSideBar(resource)
await appSideBar.activatePanel('details')
},
/**
* @param {string} resource
* @return {Promise<*>}
*/
openSharingDialog: async function (resource) {
await this.openSideBar(resource)
await appSideBar.activatePanel('people')
},
/**
* @param {string} resource
* @return {Promise<*>}
*/
openPublicLinkDialog: async function (resource) {
await this.openSideBar(resource)
return await appSideBar.activatePanel('people')
},
/**
* @param {string} resource
* @param {boolean} expected Asserts if we expect the preview image to be shown
*/
checkPreviewImage: function (resource, expected) {
const resourceRowSelector = this.getFileRowSelectorByFileName(resource)
const previewSelector = resourceRowSelector + this.elements.previewImage.selector
if (expected) {
return this.useXpath().waitForElementVisible(previewSelector)
}
return this.useXpath().waitForElementNotPresent(previewSelector)
},
/**
* @param {string} resource
* @param {string} elementType
* @return {Promise<module.exports.commands>}
*/
deleteFile: async function (resource, elementType = 'any') {
await this.openFileActionsMenu(resource, elementType)
await fileActionsMenu.delete()
return this
},
deleteSingleShare: async function () {
await fileActionsMenu.delete()
return this
},
deleteSingleShare: async function (resource) {
await fileActionsMenu.delete()
return this
},
/**
* @param {string} resource
* @param {string} elementType
* @returns {Promise<exports.commands>}
*/
acceptShare: async function (resource, elementType = 'any') {
await this.openFileActionsMenu(resource, elementType)
await fileActionsMenu.acceptShare()
return this
},
/**
* @param {string} resource
* @param {string} elementType
* @returns {Promise<exports.commands>}
*/
declineShare: async function (resource, elementType = 'any') {
await this.openFileActionsMenu(resource, elementType)
await fileActionsMenu.declineShare()
return this
},
/**
* @param {string} fromName
* @param {string} toName
* @param {boolean} expectToSucceed
* @param {string} elementType
* @return {Promise<module.exports.commands>}
*/
renameFile: async function (fromName, toName, expectToSucceed = true, elementType = 'any') {
await this.openFileActionsMenu(fromName, elementType)
await fileActionsMenu.rename(toName, expectToSucceed)
return this
},
renameSingleShare: async function (
fromName,
toName,
expectToSucceed = true,
elementType = 'any'
) {
await fileActionsMenu.rename(toName, expectToSucceed)
return this
},
renameFileFromContextMenu: async function (
fromName,
toName,
expectToSucceed = true,
elementType = 'any'
) {
await this.openContextMenu(fromName, elementType)
await contextMenu.selectRenameFile()
return await fileActionsMenu.rename(toName, expectToSucceed, true)
},
/**
* @param {string} resource
* @param {string} elementType
* @return {Promise<module.exports.commands>}
*/
markFavorite: async function (resource, elementType = 'any') {
await this.openFileActionsMenu(resource, elementType)
await fileActionsMenu.favorite()
return this
},
/**
* @param {string} resource
* @param {string} elementType
* @return {Promise<module.exports.commands>}
*/
unmarkFavorite: async function (resource, elementType = 'any') {
await this.openFileActionsMenu(resource, elementType)
await fileActionsMenu.unmarkFavorite()
return this
},
/**
* @param {string} resource
* @param {string} elementType
* @return {Promise<module.exports.commands>}
*/
restoreFile: async function (resource, elementType = 'any') {
// if there is popup message then wait for it to disappear
await this.isVisible(
{
selector: this.page.webPage().elements.message.__selector,
locateStrategy: this.page.webPage().elements.message.locateStrategy,
timeout: this.api.globals.waitForNegativeConditionTimeout,
suppressNotFoundErrors: true
},
(result) => {
if (result.value === true) {
this.waitForElementNotPresent({
selector: this.page.webPage().elements.message.__selector,
locateStrategy: this.page.webPage().elements.message.locateStrategy
})
}
}
)
await this.openFileActionsMenu(resource, elementType)
await fileActionsMenu.restore()
return this
},
/**
* @param {string} resource
* @param {string} elementType
* @return {Promise<module.exports.commands>}
*/
deleteImmediately: async function (resource, elementType = 'any') {
await this.openFileActionsMenu(resource, elementType)
await fileActionsMenu.deleteResourceImmediately()
return this
},
/**
* @param {string} action
* @param {string} resource
* @param {string} elementType
* @return {Promise<boolean>}
*/
isActionAttributeDisabled: async function (action, resource, elementType = 'any') {
await this.openFileActionsMenu(resource, elementType)
return await fileActionsMenu.getActionDisabledAttr('delete')
},
/**
* @param {string} resource
* @param {string} elementType
* @return {Promise<module.exports.commands>}
*/
downloadFile: async function (resource, elementType = 'any') {
await this.openFileActionsMenu(resource, elementType)
await fileActionsMenu.download()
return this
},
/**
* @param {string} resource
* @param {string} elementType
* @return {Promise<module.exports.commands>}
*/
isSharingButtonPresent: async function (resource, elementType = 'any') {
const sharingBtnSelector = util.format(filesRow.elements.quickAction.selector, 'show-shares')
const resourceRowSelector = this.getFileRowSelectorByFileName(resource, elementType)
let isPresent = true
await this.api.elements(
this.elements.shareButtonInFileRow.locateStrategy,
resourceRowSelector + sharingBtnSelector,
(result) => {
isPresent = result.value.length > 0
}
)
return isPresent
},
/**
* @return {Promise<*>}
*/
confirmDeletion: function () {
return this.click('@dialogConfirmBtnEnabled').waitForElementNotPresent('@dialog')
},
/**
*
* @param {string} folder
*/
navigateToFolder: async function (folder) {
const paths = folder.split('/')
for (const folderName of paths) {
if (folderName === '') {
continue
}
await this.waitForFileVisible(folderName)
await this.useXpath()
.click(this.getFileLinkSelectorByFileName(folderName, 'folder'))
.useCss()
// wait until loading is finished
await this.waitForLoadingFinished()
}
return this
},
/**
* opens context menu for given resource
*
* @param {string} resource The name or path of a resource
* @param {string} elementType The resource type (file|folder|any)
* @returns {*}
*/
openContextMenu: async function (resource, elementType = 'any') {
await this.waitForFileVisible(resource, elementType)
const selectorContextMenu =
this.getFileRowSelectorByFileName(resource, elementType) +
this.elements.contextBtnInFileRow.selector
await this.click('xpath', selectorContextMenu)
await this.waitForElementVisible('@contextMenuPanel')
return contextMenu
},
/**
* opens file-actions menu for given resource
*
* @param {string} resource The resource name
* @param {string} elementType The resource type (file|folder|any)
*
* @returns {*}
*/
openFileActionsMenu: async function (resource, elementType = 'any') {
await this.openSideBar(resource, elementType)
await appSideBar.activatePanel('actions')
return fileActionsMenu
},
/**
* opens sidebar for given resource
*
* @param {string} resource
* @param {string} elementType The resource type (file|folder|any)
* @returns {*}
*/
openSideBar: async function (resource, elementType = 'any') {
// nothing to do if already open for correct resource
if (await appSideBar.isSideBarOpenForResource(resource, elementType, false)) {
return appSideBar
}
// closing it since otherwise tests fail on mobile
// on desktop sidebar content gets replaced with new resource
await appSideBar.closeSidebarIfOpen()
// open the sidebar for the resource
await this.clickRow(resource, elementType)
await this.click('@btnToggleSideBar')
await this.waitForAnimationToFinish() // wait for the sidebar animation to finish
return appSideBar
},
/**
* @param {string} resource the file/folder to click
* @param {string} elementType The resource type (file|folder|any)
*/
clickRow: async function (resource, elementType = 'any') {
await this.waitForFileVisible(resource, elementType)
await this.initAjaxCounters()
.useXpath()
// click in empty space in the tr using coordinates to avoid
// clicking on other elements that might be in the front
.clickElementAt(this.getFileRowSelectorByFileName(resource, elementType), 1, 1)
.waitForOutstandingAjaxCalls()
.useCss()
return this
},
/**
*
*/
checkAllFiles: function () {
return this.waitForElementVisible('@filesTable')
.waitForElementVisible('@checkBoxAllFiles')
.click('@checkBoxAllFiles')
},
/**
* Toggle enable or disable file/folder select checkbox
*
* @param {string} enableOrDisable
* @param {string} path
*/
toggleFileOrFolderCheckbox: async function (enableOrDisable, path) {
await this.waitForFileVisible(path)
const fileCheckbox =
this.getFileRowSelectorByFileName(path) + this.elements.checkboxInFileRow.selector
await this.toggleCheckbox(enableOrDisable, fileCheckbox, 'xpath')
return this
},
/**
*
* @param {string} path
* @return {Promise<boolean>}
*/
isResourceSelected: async function (path) {
await this.waitForFileVisible(path)
const fileCheckbox =
this.getFileRowSelectorByFileName(path) + this.elements.checkboxInFileRow.selector
let selectionStatus = ''
await this.api.element('xpath', fileCheckbox, (result) => {
if (!result.value.ELEMENT) {
throw new Error('Web element identifier not found for ' + fileCheckbox)
}
this.api.elementIdSelected(
result.value.ELEMENT,
(result) => (selectionStatus = result.value)
)
})
return selectionStatus
},
waitForLoadingFinished: async function (awaitVisible = true, abortOnFailure = true) {
if (awaitVisible) {
await this.waitForElementVisible({ selector: '@anyAfterLoading', abortOnFailure })
return this
}
await this.waitForElementPresent({ selector: '@anyAfterLoading', abortOnFailure })
return this
},
waitForFileVisibleAsSingleShare: async function (resource) {
await this.waitForElementPresent({ selector: '@sharedDetailResource' })
return this
},
/**
* Wait for a filerow with given filename to be visible
*
* @param {string} fileName
* @param {string} elementType (file|folder)
*/
waitForFileVisible: async function (fileName, elementType = 'any') {
await this.checkFileName(fileName, elementType)
const rowSelector = this.getFileRowSelectorByFileName(fileName, elementType)
await appSideBar.closeSidebarIfOpen()
await this.waitForElementVisible({ selector: rowSelector, locateStrategy: 'xpath' })
},
checkFileName: async function (fileName, elementType = 'any') {
const fileSelector = this.getFileSelectorByFileName(fileName, elementType)
// res.value return file/folder name and file extension in different row
// res.status return -1 if res return error otherwise return
let resourceName = null
let status = null
let error = null
await this.getText('xpath', fileSelector, (res) => {
status = res.status
const result = res.value
if (status === 0) {
resourceName = result.split('\n').join('')
} else if (status === -1) {
error = res.value.error
}
})
if (error !== null) {
assert.fail(error)
}
assert.ok(
fileName.endsWith(resourceName),
`Expected file name to be "${fileName}" but found "${resourceName}"`
)
},
/**
*
* @param {string} fileName
* @param {string} elementType Resource type (file/folder). Use `any` if not relevant.
*
* @returns {string}
*/
getFileRowSelectorByFileName: function (fileName, elementType = 'any') {
const name = xpathHelper.buildXpathLiteral(fileName)
const path = xpathHelper.buildXpathLiteral('/' + fileName)
if (elementType === 'any') {
return util.format(this.elements.fileRowByResourcePathAnyType.selector, name, path)
}
const type = xpathHelper.buildXpathLiteral(elementType)
return util.format(this.elements.fileRowByResourcePath.selector, name, path, type)
},
/**
*
* @param {string} fileName
* @param {string} elementType
* @returns {string}
*/
getFileLinkSelectorByFileName: function (fileName, elementType = 'any') {
const name = xpathHelper.buildXpathLiteral(fileName)
const path = xpathHelper.buildXpathLiteral('/' + fileName)
if (elementType === 'any') {
return util.format(this.elements.fileLinkInFileRowAnyType.selector, name, path)
}
const type = xpathHelper.buildXpathLiteral(elementType)
return util.format(this.elements.fileLinkInFileRow.selector, name, path, type)
},
/**
*
* @param {string} Name of the file/folder/resource
* @param {string} elementType
* @returns {string}
*/
getFileSelectorByFileName: function (fileName, elementType = 'any') {
const name = xpathHelper.buildXpathLiteral(fileName)
const path = xpathHelper.buildXpathLiteral('/' + fileName)
if (elementType === 'any') {
return util.format(this.elements.fileNameResourcePathAnyType.selector, name, path)
}
const type = xpathHelper.buildXpathLiteral(elementType)
return util.format(this.elements.fileNameResourcePath.selector, name, path, type)
},
/**
* checks whether the element is listed or not on the filesList
*
* @param {string} name Name of the file/folder/resource
* @param {string} elementType
* @returns {boolean}
*/
isElementListed: async function (name, elementType = 'any', expectToBeListed = true) {
const selector = this.getFileRowSelectorByFileName(name, elementType)
let isVisible = false
const timeout = expectToBeListed
? this.api.globals.waitForConditionTimeout
: this.api.globals.waitForNegativeConditionTimeout
await this.isVisible(
{
selector,
locateStrategy: 'xpath',
timeout,
suppressNotFoundErrors: expectToBeListed !== true
},
(result) => {
isVisible = result.value === true
}
)
return isVisible
},
/**
* @returns {Array} array of files/folders element
*/
allFileRows: async function () {
let returnResult = null
await this.waitForElementPresent('@anyAfterLoading')
await this.api.elements('css selector', this.elements.fileRow, function (result) {
returnResult = result
})
return returnResult
},
waitForNoContentMessageVisible: async function () {
let visible = false
let elementId = null
await this.waitForElementVisible('@filesListNoContentMessage')
await this.api.element('@filesListNoContentMessage', (result) => {
if (result.status !== -1) {
elementId = result.value.ELEMENT
}
})
if (elementId !== null) {
await this.api.elementIdText(elementId, (result) => {
// verify that at least some text is displayed, not an empty container
if (result.status !== -1 && result.value.trim() !== '') {
visible = true
}
})
}
assert.ok(visible, 'Message about empty file list must be visible')
},
waitForNotFoundMessageVisible: async function () {
await this.waitForElementVisible('@filesListNotFoundMessage')
},
countFilesAndFolders: async function () {
let itemCount = 0
await this.waitForElementVisible('@filesListFooterInfo').getAttribute(
'@filesListFooterInfo',
'data-test-items',
(result) => {
itemCount = parseInt(result.value)
}
)
return itemCount
},
/**
*
* @param {string} fileName
* @param {boolean} sharingIndicatorExpectedToBeVisible
* @returns {Array} array of sharing indicator
*/
getShareIndicatorsForResource: async function (fileName, sharingIndicatorExpectedToBeVisible) {
const resourceRowXpath = this.getFileRowSelectorByFileName(fileName)
const shareIndicatorsXpath =
resourceRowXpath + this.elements.shareIndicatorsInFileRow.selector
const indicators = []
await this.waitForFileVisible(fileName)
await this.waitForAnimationToFinish()
const {
waitForNegativeConditionTimeout,
waitForConditionTimeout,
waitForConditionPollInterval
} = client.globals
await this.waitForElementVisible({
selector: shareIndicatorsXpath,
locateStrategy: this.elements.shareIndicatorsInFileRow.locateStrategy,
abortOnFailure: false,
timeout: sharingIndicatorExpectedToBeVisible
? waitForConditionTimeout
: waitForNegativeConditionTimeout,
pollInterval: waitForConditionPollInterval
})
await this.api.elements(
this.elements.shareIndicatorsInFileRow.locateStrategy,
shareIndicatorsXpath,
(result) => {
result.value.forEach((element) => {
this.api.elementIdAttribute(element.ELEMENT, 'class', (attr) => {
if (parseInt(attr.status) < 0) {
return
}
this.api.elementIdAttribute(element.ELEMENT, 'data-test-indicator-type', (attr) => {
indicators.push(attr.value)
})
})
})
}
)
return indicators
},
/**
*
* @param {string} fileName
* @param {boolean} sharingIndicatorExpectedToBeVisible
* @returns {Array} array of sharing indicator
*/
getShareIndicatorsForResourceWithRetry: async function (
fileName,
sharingIndicatorExpectedToBeVisible
) {
let indicators = await this.getShareIndicatorsForResource(
fileName,
sharingIndicatorExpectedToBeVisible
)
if (!indicators.length) {
console.log('Share indicators not found on first try, Retrying again')
indicators = await this.getShareIndicatorsForResource(
fileName,
sharingIndicatorExpectedToBeVisible
)
}
return indicators
},
setSort: async function (column, isDesc = false) {
const columnSelector = util.format(
this.elements.filesTableHeaderColumn.selector,
xpathHelper.buildXpathLiteral(column)
)
await this.useXpath()
.waitForElementVisible(columnSelector)
.click(columnSelector)
.waitForElementVisible(columnSelector)
.useCss()
let currentClass = null
await this.useXpath().getAttribute(columnSelector, 'class', (result) => {
currentClass = result.value
})
if (currentClass.includes('-asc') && isDesc) {
// click again to match expected sort order
await this.useXpath().waitForElementVisible(columnSelector).click(columnSelector).useCss()
}
return this.useCss()
},
useQuickAction: async function (resource, action) {
const className = action === 'collaborators' ? 'show-shares' : 'copy-quicklink'
const actionSelector = util.format(filesRow.elements.quickAction.selector, className)
const resourceRowSelector = this.getFileRowSelectorByFileName(resource)
await this.waitForFileVisible(resource)
await this.click('xpath', resourceRowSelector + actionSelector)
await this.waitForAnimationToFinish() // wait for the sidebar animation to finish
return this
},
moveResource: async function (resource, target) {
// Trigger move
await this.openFileActionsMenu(resource)
await fileActionsMenu.move()
// Execute move
await this.selectFolderAndPasteFiles(target)
return this
},
moveMultipleResources: async function (target) {
// Trigger move
await this.click('@moveSelectedBtn')
// Execute move
return await this.selectFolderAndPasteFiles(target)
},
copyResource: async function (resource, target) {
// Trigger copy
await this.openFileActionsMenu(resource)
await fileActionsMenu.copy()
// Execute copy
await this.selectFolderAndPasteFiles(target)
return this
},
copyMultipleResources: async function (target) {
// Trigger copy
await this.click('@copySelectedBtn')
// Execute copy
return await this.selectFolderAndPasteFiles(target)
},
selectFolderAndPasteFiles: async function (target) {
if (target.startsWith('/')) {
// if the target is absolute, we need to go to the root element first
await this.waitForElementVisible('@firstBreadcrumbLink').click('@firstBreadcrumbLink')
}
const targetSplitted = target.replace(/^(\/|\\)+/, '').split('/')
for (let i = 0; i < targetSplitted.length; i++) {
await client.page.FilesPageElement.filesList().navigateToFolder(targetSplitted[i])
}
await this.initAjaxCounters()
.waitForElementVisible('@pasteSelectedBtn')
.click('@pasteSelectedBtn')
.waitForAjaxCallsToStartAndFinish()
try {
await this.waitForElementNotPresent({
selector: '@pasteSelectedBtn',
timeout: 200
})
} catch (e) {
console.error(e)
throw new Error('ElementPresentError')
}
return this
},
clickOnFileName: function (fileName) {
const file = this.getFileLinkSelectorByFileName(fileName, 'file')
return this.useXpath().waitForElementVisible(file).click(file).useCss()
},
closeRenameDialog: function () {
return this.waitForElementVisible('@dialogCancelBtn').click('@dialogCancelBtn')
}
},
elements: {
filesContainer: {
selector: '.files-view-wrapper'
},
filesAppBar: {
selector: '#files-app-bar'
},
filesTable: {
selector: '.files-table'
},
loadingIndicator: {
selector: '//*[contains(@class, "oc-loader")]',
locateStrategy: 'xpath'
},
filesListNoContentMessage: {
selector: '.files-empty'
},
filesListNotFoundMessage: {
selector: '.files-not-found'
},
filesListProgressBar: {
selector: '#files-list-progress'
},
sharedDetailResource: {
selector: '.resource-details .oc-resource-name'
},
anyAfterLoading: {
selector:
'//*[self::table[contains(@class, "files-table")] or self::div[contains(@class, "files-empty")] or self::div[contains(@class, "files-not-found")] or self::div[contains(@class, "resource-details")]]',
locateStrategy: 'xpath'
},
shareButtonInFileRow: {
selector: '//button[@aria-label="People"]',
locateStrategy: 'xpath'
},
fileRow: {
selector: '.files-table .oc-tbody-tr'
},
fileNameResourcePathAnyType: {
selector: `//span[contains(@class, "oc-resource-name") and (@data-test-resource-name=%s or @data-test-resource-path=%s)]`,
locateStrategy: 'xpath'
},
fileNameResourcePath: {
selector:
'//span[contains(@class, "oc-resource-name") and (@data-test-resource-name=%s or @data-test-resource-path=%s) and @data-test-resource-type=%s]',
locateStrategy: 'xpath'
},
fileRowByResourcePathAnyType: {
selector: `//span[contains(@class, "oc-resource-name") and (@data-test-resource-name=%s or @data-test-resource-path=%s)]/ancestor::tr[contains(@class, "oc-tbody-tr")]`,
locateStrategy: 'xpath'
},
fileRowByResourcePath: {
selector: `//span[contains(@class, "oc-resource-name") and (@data-test-resource-name=%s or @data-test-resource-path=%s) and @data-test-resource-type=%s]/ancestor::tr[contains(@class, "oc-tbody-tr")]`,
locateStrategy: 'xpath'
},
fileRowDisabled: {
selector:
'//span[contains(@class, "oc-resource-name") and (@data-test-resource-name=%s or @data-test-resource-path=%s) and @data-test-resource-type=%s]/ancestor::tr[contains(@class, "oc-table-disabled")]',
locateStrategy: 'xpath'
},
fileLinkInFileRowAnyType: {
selector:
'//span[contains(@class, "oc-resource-name") and (@data-test-resource-name=%s or @data-test-resource-path=%s)]/parent::*',
locateStrategy: 'xpath'
},
fileLinkInFileRow: {
selector:
'//span[contains(@class, "oc-resource-name") and (@data-test-resource-name=%s or @data-test-resource-path=%s) and @data-test-resource-type=%s]/parent::*',
locateStrategy: 'xpath'
},
contextBtnInFileRow: {
selector: '//button[contains(@class, "resource-table-btn-action-dropdown")]',
locateStrategy: 'xpath'
},
contextMenuPanel: {
selector: '#oc-files-context-menu'
},
/**
* This element is concatenated as child of @see fileRowByResourcePath
*/
filePreviewInFileRow: {
selector: '//img[contains(@class, "oc-resource-thumbnail")]',
locateStrategy: 'xpath'
},
/**
* This element is concatenated as child of @see fileRowByResourcePath
*/
shareIndicatorsInFileRow: {
selector: '//*[contains(@class, "oc-status-indicators-indicator")]',
locateStrategy: 'xpath'
},
checkBoxAllFiles: {
selector: '#resource-table-select-all'
},
checkboxInFileRow: {
selector: '//input[@type="checkbox"]',
locateStrategy: 'xpath'
},
collaboratorsList: {
selector: '.files-collaborators-lists'
},
filesListFooterInfo: {
selector: '//p[@data-testid="files-list-footer-info"]',
locateStrategy: 'xpath'
},
filesTableHeader: {
selector: '.files-table .oc-thead'
},
filesTableHeaderColumn: {
selector: '//*[contains(@class, "oc-table-header-cell")]//*[text()=%s]',
locateStrategy: 'xpath'
},
// TODO: Merge with selectors in personalPage
dialog: {
selector: '.oc-modal'
},
dialogConfirmBtnEnabled: {
selector: '.oc-modal-body-actions-confirm:enabled'
},
dialogCancelBtn: {
selector: '.oc-modal-body-actions-cancel'
},
previewImage: {
selector: '//img[contains(@class, "oc-resource-thumbnail")]',
locateStrategy: 'xpath'
},
btnToggleSideBar: {
selector: '#files-toggle-sidebar'
},
sharedWithToggleButton: {
selector: '//*[contains(@class, "sharee-avatars")]/ancestor::button',
locateStrategy: 'xpath'
},
firstBreadcrumbLink: {
selector: '//nav[contains(@class, "oc-breadcrumb")]/ol/li[1]/a',
locateStrategy: 'xpath'
},
moveSelectedBtn: {
selector: '.oc-files-actions-move-trigger'
},
copySelectedBtn: {
selector: '.oc-files-actions-copy-trigger'
},
pasteSelectedBtn: {
selector: '#clipboard-btns button:first-child'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/FilesPageElement/filesList.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/FilesPageElement/filesList.js",
"repo_id": "owncloud",
"token_count": 11636
} | 859 |
const { join } = require('../helpers/path')
const util = require('util')
module.exports = {
url: function (token = '') {
return join(this.api.launchUrl, '/s', token)
},
commands: {
/**
* like build-in navigate() but also waits till for the progressbar to appear and disappear
* @returns {*}
*/
navigateAndWaitTillLoaded: function (token) {
return this.navigate(this.url(token)).waitForElementPresent(
this.page.FilesPageElement.filesList().elements.anyAfterLoading
)
},
navigateAndWaitForPasswordPage: function (token) {
this.navigate(this.url(token))
return this.page.publicLinkPasswordPage().waitForElementPresent('@passwordInput')
},
/**
* It is not reliably possible to determine if it's a public link.
* This checks for combination of files-list, and absence of hamburger menu
* to determine this is a public links page
*
* @return {Promise<boolean>}
*/
waitForPage: function () {
const menuButton = this.page.webPage().elements.menuButton
return this.api
.waitForElementPresent(this.elements.filesListContainer.selector)
.useStrategy(menuButton)
.assert.elementNotPresent(menuButton)
.useCss()
},
/**
* navigates to the root directory of the link share
* @param {string} linkName
*
* @returns {*}
*/
navigateToRootFolder: function (linkName) {
if (!linkName) {
linkName = 'Public link'
}
const linkNameSelector = {
selector: util.format(this.elements.linkName.selector, linkName),
locateStrategy: 'xpath'
}
return this.waitForElementVisible(linkNameSelector).click(linkNameSelector)
}
},
elements: {
filesListContainer: {
selector: '#files-list-container',
locateStrategy: 'css selector'
},
linkName: {
selector: '//li[contains(@class, "oc-breadcrumb-list-item")]//span[text()="%s"]'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/publicLinkFilesPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/publicLinkFilesPage.js",
"repo_id": "owncloud",
"token_count": 775
} | 860 |
const { client } = require('nightwatch-api')
const { When } = require('@cucumber/cucumber')
When('the user closes the message', function () {
return client.page.webPage().closeMessage()
})
| owncloud/web/tests/acceptance/stepDefinitions/messagesContext.js/0 | {
"file_path": "owncloud/web/tests/acceptance/stepDefinitions/messagesContext.js",
"repo_id": "owncloud",
"token_count": 58
} | 861 |
{
"server": "https://ocis:9200",
"theme": "https://ocis:9200/themes/owncloud/theme.json",
"openIdConnect": {
"client_id": "web",
"response_type": "code",
"scope": "openid profile email"
},
"options": {
"topCenterNotifications": true,
"disablePreviews": true,
"displayResourcesLazy": false,
"sidebar": {
"shares": {
"showAllOnLoad": true
}
},
"routing": {
"idBased": false
}
},
"apps": [
"files",
"draw-io",
"text-editor",
"media-viewer",
"pdf-viewer",
"search",
"admin-settings"
]
}
| owncloud/web/tests/drone/web-keycloak.json/0 | {
"file_path": "owncloud/web/tests/drone/web-keycloak.json",
"repo_id": "owncloud",
"token_count": 276
} | 862 |
Feature: Search
As a user
I want to do full text search
So that I can find the files with the content I am looking for
Scenario: search for content of file
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
And "Admin" assigns following roles to the users using API
| id | role |
| Brian | Space Admin |
And "Alice" logs in
And "Alice" uploads the following local file into personal space using API
| localFile | to |
| filesForUpload/textfile.txt | fileToShare.txt |
And "Alice" opens the "files" app
And "Alice" adds the following tags for the following resources using API
| resource | tags |
| fileToShare.txt | alice tag |
And "Alice" shares the following resource using API
| resource | recipient | type | role |
| fileToShare.txt | Brian | user | Can edit |
And "Alice" logs out
And "Brian" logs in
And "Brian" creates the following folder in personal space using API
| name |
| testFolder |
And "Brian" uploads the following local file into personal space using API
| localFile | to |
| filesForUpload/textfile.txt | textfile.txt |
| filesForUpload/textfile.txt | fileWithTag.txt |
| filesForUpload/textfile.txt | withTag.txt |
| filesForUpload/textfile.txt | testFolder/innerTextfile.txt |
And "Brian" creates the following project spaces using API
| name | id |
| FullTextSearch | fulltextsearch.1 |
And "Brian" creates the following folder in space "FullTextSearch" using API
| name |
| spaceFolder |
And "Brian" creates the following file in space "FullTextSearch" using API
| name | content |
| spaceFolder/spaceTextfile.txt | This is test file. Cheers |
And "Brian" opens the "files" app
And "Brian" adds the following tags for the following resources using API
| resource | tags |
| fileWithTag.txt | tag 1 |
| withTag.txt | tag 1 |
When "Brian" searches "" using the global search and the "all files" filter and presses enter
Then "Brian" should see the message "Search for files" on the webUI
When "Brian" selects tag "alice tag" from the search result filter chip
Then following resources should be displayed in the files list for user "Brian"
| resource |
| fileToShare.txt |
When "Brian" clears tags filter
And "Brian" selects tag "tag 1" from the search result filter chip
Then following resources should be displayed in the files list for user "Brian"
| resource |
| fileWithTag.txt |
| withTag.txt |
When "Brian" searches "file" using the global search and the "all files" filter and presses enter
Then following resources should be displayed in the files list for user "Brian"
| resource |
| fileWithTag.txt |
When "Brian" clears tags filter
Then following resources should be displayed in the files list for user "Brian"
| resource |
| textfile.txt |
| fileWithTag.txt |
| testFolder/innerTextfile.txt |
| fileToShare.txt |
| spaceFolder/spaceTextfile.txt |
When "Brian" searches "Cheers" using the global search and the "all files" filter and presses enter
Then following resources should be displayed in the files list for user "Brian"
| resource |
| textfile.txt |
| testFolder/innerTextfile.txt |
| fileToShare.txt |
| fileWithTag.txt |
| withTag.txt |
| spaceFolder/spaceTextfile.txt |
When "Brian" opens the following file in texteditor
| resource |
| textfile.txt |
And "Brian" closes the file viewer
Then following resources should be displayed in the files list for user "Brian"
| resource |
| textfile.txt |
| testFolder/innerTextfile.txt |
| fileToShare.txt |
| fileWithTag.txt |
| withTag.txt |
| spaceFolder/spaceTextfile.txt |
And "Brian" logs out
| owncloud/web/tests/e2e/cucumber/features/search/fullTextSearch.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/search/fullTextSearch.feature",
"repo_id": "owncloud",
"token_count": 1875
} | 863 |
Feature: check files pagination in personal space
As a user
I want to navigate a large number of files using pagination
So that I do not have to scroll deep down
Scenario: pagination
Given "Admin" creates following user using API
| id |
| Alice |
And "Alice" logs in
And "Alice" creates 55 folders in personal space using API
And "Alice" creates 55 files in personal space using API
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| .hidden-testFile.txt | This is a hidden file. |
And "Alice" opens the "files" app
When "Alice" navigates to page "2" of the personal space files view
Then "Alice" should see the text "111 items with 1 kB in total (56 files, 55 folders)" at the footer of the page
And "Alice" should see 10 resources in the personal space files view
When "Alice" enables the option to display the hidden file
Then "Alice" should see 11 resources in the personal space files view
When "Alice" changes the items per page to "500"
Then "Alice" should not see the pagination in the personal space files view
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/smoke/personalSpacePagination.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/personalSpacePagination.feature",
"repo_id": "owncloud",
"token_count": 370
} | 864 |
const { program } = require('commander')
const getRepoInfo = require('git-repo-info')
const pkg = require('../../../../package.json')
const reporter = require('cucumber-html-reporter')
const os = require('os')
program
.option('--backend-version <semver>', 'version of used backend')
.option('--environment <type>', 'test environment e.g. docker, local, remote ...')
.option('--report-open', 'open report in browser', false)
.option(
'--report-location <path>',
'location where the report gets generated to',
'reports/e2e/cucumber/releaseReport/cucumber_report.html'
)
.option(
'--report-input <path>',
'location of generated cucumber json',
'tests/e2e/cucumber/report/cucumber_report.json'
)
program.parse()
const { backendName, backendVersion, environment, reportOpen, reportLocation, reportInput } =
program.opts()
const repoInfo = getRepoInfo()
reporter.generate({
theme: 'bootstrap',
jsonFile: reportInput,
output: reportLocation,
reportSuiteAsScenarios: true,
scenarioTimestamp: true,
launchReport: reportOpen,
metadata: {
'web-version': pkg.version,
platform: os.platform(),
repository: `${repoInfo.branch}`,
...(backendVersion && { [`${backendName}-version`]: backendVersion }),
...(environment && { environment: environment })
}
})
| owncloud/web/tests/e2e/cucumber/report/index.js/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/report/index.js",
"repo_id": "owncloud",
"token_count": 443
} | 865 |
export * from './user'
export * from './utils'
| owncloud/web/tests/e2e/support/api/keycloak/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/keycloak/index.ts",
"repo_id": "owncloud",
"token_count": 16
} | 866 |
import { Space } from '../types'
import { createdSpaceStore } from '../store'
export class SpacesEnvironment {
getSpace({ key }: { key: string }): Space {
if (!createdSpaceStore.has(key)) {
throw new Error(`space with key '${key}' not found`)
}
return createdSpaceStore.get(key)
}
createSpace({ key, space }: { key: string; space: Space }): Space {
if (createdSpaceStore.has(key)) {
throw new Error(`link with key '${key}' already exists`)
}
createdSpaceStore.set(key, space)
return space
}
}
| owncloud/web/tests/e2e/support/environment/space.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/environment/space.ts",
"repo_id": "owncloud",
"token_count": 194
} | 867 |
import { Page } from '@playwright/test'
import util from 'util'
import { locatorUtils } from '../../../utils'
const spaceTrSelector = '.spaces-table tbody > tr'
const actionConfirmButton = '.oc-modal-body-actions-confirm'
const contextMenuSelector = `[data-item-id="%s"] .spaces-table-btn-action-dropdown`
const spaceCheckboxSelector = `[data-item-id="%s"] input[type=checkbox]`
const contextMenuActionButton = `.oc-files-actions-%s-trigger`
const inputFieldSelector =
'//div[@class="oc-modal-body-input"]//input[contains(@class,"oc-text-input")]'
const modalConfirmBtn = `.oc-modal-body-actions-confirm`
const quotaValueDropDown = `.vs__dropdown-option :text-is("%s")`
const selectedQuotaValueField = '.vs__dropdown-toggle'
const spacesQuotaSearchField = '.oc-modal .vs__search'
const appSidebarDiv = '#app-sidebar'
const toggleSidebarButton = '#files-toggle-sidebar'
const sideBarActive = '.sidebar-panel.is-active-default-panel'
const sideBarCloseButton = '.sidebar-panel .header__close:visible'
const sideBarBackButton = '.sidebar-panel .header__back:visible'
const sideBarActionButtons = `#sidebar-panel-%s-select`
const siderBarActionPanel = `#sidebar-panel-%s`
const spaceMembersDiv = '[data-testid="space-members"]'
const spaceMemberList =
'[data-testid="space-members-role-%s"] ul [data-testid="space-members-list"]'
export const getDisplayedSpaces = async (page): Promise<string[]> => {
const spaces = []
const result = await page.locator(spaceTrSelector)
const count = await result.count()
for (let i = 0; i < count; i++) {
spaces.push(await result.nth(i).getAttribute('data-item-id'))
}
return spaces
}
const performAction = async (args: {
page: Page
action: string
context: string
id?: string
}): Promise<void> => {
const { page, action, context, id } = args
if (id && context === 'context-menu') {
await page.locator(util.format(contextMenuSelector, id)).click()
}
let contextMenuActionButtonSelector = `.${context} `
switch (action) {
case 'rename':
contextMenuActionButtonSelector += util.format(contextMenuActionButton, action)
break
case 'edit-description':
contextMenuActionButtonSelector += util.format(contextMenuActionButton, action)
break
case 'edit-quota':
contextMenuActionButtonSelector += util.format(contextMenuActionButton, action)
break
case 'delete':
contextMenuActionButtonSelector += util.format(contextMenuActionButton, action)
break
case 'disable':
contextMenuActionButtonSelector += util.format(contextMenuActionButton, action)
break
case 'restore':
contextMenuActionButtonSelector += util.format(contextMenuActionButton, action)
break
default:
throw new Error(`${action} not implemented`)
}
await page.locator(contextMenuActionButtonSelector).click()
}
export const changeSpaceQuota = async (args: {
page: Page
spaceIds: string[]
value: string
context: string
}): Promise<void> => {
const { page, value, spaceIds, context } = args
await performAction({ page, action: 'edit-quota', context, id: spaceIds[0] })
const searchLocator = page.locator(spacesQuotaSearchField)
await searchLocator.pressSequentially(value)
await page.locator(selectedQuotaValueField).waitFor()
await page.locator(util.format(quotaValueDropDown, `${value} GB`)).click()
await confirmAction({
page,
method: 'PATCH',
statusCode: 200,
spaceIds,
actionConfirm: true
})
}
export const disableSpace = async (args: {
page: Page
spaceIds: string[]
context: string
}): Promise<void> => {
const { page, spaceIds, context } = args
await performAction({ page, action: 'disable', context, id: spaceIds[0] })
await confirmAction({
page,
method: 'DELETE',
statusCode: 204,
spaceIds,
actionConfirm: false
})
}
export const enableSpace = async (args: {
page: Page
spaceIds: string[]
context: string
}): Promise<void> => {
const { page, spaceIds, context } = args
await performAction({ page, action: 'restore', context, id: spaceIds[0] })
await confirmAction({
page,
method: 'PATCH',
statusCode: 200,
spaceIds,
actionConfirm: false
})
}
export const deleteSpace = async (args: {
page: Page
spaceIds: string[]
context: string
}): Promise<void> => {
const { page, spaceIds, context } = args
await performAction({ page, action: 'delete', context, id: spaceIds[0] })
await confirmAction({
page,
method: 'DELETE',
statusCode: 204,
spaceIds,
actionConfirm: false
})
}
export const selectSpace = async (args: { page: Page; id: string }): Promise<void> => {
const { page, id } = args
const checkbox = page.locator(util.format(spaceCheckboxSelector, id))
const checkBoxAlreadySelected = await checkbox.isChecked()
if (checkBoxAlreadySelected) {
return
}
await checkbox.click()
}
export const renameSpace = async (args: {
page: Page
id: string
value: string
}): Promise<void> => {
const { page, id, value } = args
await performAction({ page, action: 'rename', context: 'context-menu', id })
await page.locator(inputFieldSelector).fill(value)
await confirmAction({
page,
method: 'PATCH',
statusCode: 200,
spaceIds: [id],
actionConfirm: true
})
}
export const changeSpaceSubtitle = async (args: {
page: Page
id: string
value: string
}): Promise<void> => {
const { page, id, value } = args
await performAction({ page, action: 'edit-description', context: 'context-menu', id })
await page.locator(inputFieldSelector).fill(value)
await confirmAction({
page,
method: 'PATCH',
statusCode: 200,
spaceIds: [id],
actionConfirm: true
})
}
const confirmAction = async (args: {
page: Page
method: string
statusCode: number
spaceIds: string[]
actionConfirm: boolean
}): Promise<void> => {
const { page, method, statusCode, spaceIds, actionConfirm } = args
let confirmButton = modalConfirmBtn
if (actionConfirm) {
confirmButton = actionConfirmButton
}
const checkResponses = []
for (const id of spaceIds) {
checkResponses.push(
page.waitForResponse(
(resp) =>
resp.url().endsWith(encodeURIComponent(id)) &&
resp.status() === statusCode &&
resp.request().method() === method
)
)
}
await page.locator(confirmButton).waitFor()
await Promise.all([...checkResponses, page.locator(confirmButton).click()])
}
export const openSpaceAdminSidebarPanel = async (args: {
page: Page
id: string
}): Promise<void> => {
const { page, id } = args
if (await page.locator(appSidebarDiv).count()) {
await page.locator(sideBarCloseButton).click()
}
await selectSpace({ page, id })
await page.click(toggleSidebarButton)
}
export const openSpaceAdminActionSidebarPanel = async (args: {
page: Page
action: string
}): Promise<void> => {
const { page, action } = args
const currentPanel = page.locator(sideBarActive)
const backButton = currentPanel.locator(sideBarBackButton)
if (await backButton.count()) {
await backButton.click()
await locatorUtils.waitForEvent(currentPanel, 'transitionend')
}
const panelSelector = page.locator(util.format(sideBarActionButtons, action))
const nextPanel = page.locator(util.format(siderBarActionPanel, action))
await panelSelector.click()
await locatorUtils.waitForEvent(nextPanel, 'transitionend')
}
export const listSpaceMembers = async (args: {
page: Page
filter: string
}): Promise<Array<string>> => {
const { page, filter } = args
await page.locator(spaceMembersDiv).waitFor()
let users = []
const names = []
switch (filter) {
case 'managers':
users = await page.locator(util.format(spaceMemberList, filter)).allTextContents()
break
case 'viewers':
users = await page.locator(util.format(spaceMemberList, filter)).allTextContents()
break
case 'editors':
users = await page.locator(util.format(spaceMemberList, filter)).allTextContents()
break
}
for (const user of users) {
// the value comes in "['initials firstName secondName lastName',..]" format so only get the first name
const [, name] = user.split(' ')
names.push(name)
}
return names
}
| owncloud/web/tests/e2e/support/objects/app-admin-settings/spaces/actions.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/spaces/actions.ts",
"repo_id": "owncloud",
"token_count": 2851
} | 868 |
import { errors, Page } from '@playwright/test'
import util from 'util'
const resourceNameSelector = '#files-space-table [data-test-resource-name="%s"]'
/**
* one of the few places where timeout should be used, as we also use this to detect the absence of an element
* it is not possible to differentiate between `element not there yet` and `element not loaded yet`.
*
* @param page
* @param name
* @param timeout
*/
export const resourceExists = async ({
page,
name,
timeout = 500
}: {
page: Page
name: string
timeout?: number
}): Promise<boolean> => {
let exist = true
await page
.locator(util.format(resourceNameSelector, name))
.waitFor({ timeout })
.catch((e) => {
if (!(e instanceof errors.TimeoutError)) {
throw e
}
exist = false
})
return exist
}
export const waitForResources = async ({
page,
names
}: {
page: Page
names: string[]
}): Promise<void> => {
await Promise.all(
names.map((name) => page.locator(util.format(resourceNameSelector, name)).waitFor())
)
}
| owncloud/web/tests/e2e/support/objects/app-files/resource/utils.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/resource/utils.ts",
"repo_id": "owncloud",
"token_count": 355
} | 869 |
import { Page } from '@playwright/test'
import util from 'util'
const appSwitcherButton = '#_appSwitcherButton'
const appSelector = `//ul[contains(@class, "applications-list")]//*[@data-test-id="%s"]`
const notificationsBell = `#oc-notifications-bell`
const notificationsDrop = `#oc-notifications-drop`
const notificationsLoading = `#oc-notifications-drop .oc-notifications-loading`
const markNotificationsAsReadButton = `#oc-notifications-drop .oc-notifications-mark-all`
const notificationItemsMessages = `#oc-notifications-drop .oc-notifications-item .oc-notifications-message`
export class Application {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
async reloadPage(): Promise<void> {
await this.#page.reload()
}
async open({ name }: { name: string }): Promise<void> {
await this.#page.waitForTimeout(1000)
await this.#page.locator(appSwitcherButton).click()
await this.#page.locator(util.format(appSelector, name)).click()
}
async getNotificationMessages(): Promise<string[]> {
// reload will fetch notifications immediately
// wait for the notifications to load
await Promise.all([
this.#page.waitForResponse(
(resp) =>
resp.url().endsWith('notifications') &&
resp.status() === 200 &&
resp.request().method() === 'GET'
),
this.#page.reload()
])
const dropIsOpen = await this.#page.locator(notificationsDrop).isVisible()
if (!dropIsOpen) {
await this.#page.locator(notificationsBell).click()
}
await this.#page.locator(notificationsLoading).waitFor({ state: 'detached' })
const result = this.#page.locator(notificationItemsMessages)
const messages = []
const count = await result.count()
for (let i = 0; i < count; i++) {
messages.push(await result.nth(i).innerText())
}
return messages
}
async markNotificationsAsRead(): Promise<void> {
const dropIsOpen = await this.#page.locator(notificationsDrop).isVisible()
if (!dropIsOpen) {
await this.#page.locator(notificationsBell).click()
}
await this.#page.locator(notificationsLoading).waitFor({ state: 'detached' })
await this.#page.locator(markNotificationsAsReadButton).click()
await this.#page.locator(notificationsLoading).waitFor({ state: 'detached' })
}
}
| owncloud/web/tests/e2e/support/objects/runtime/application.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/runtime/application.ts",
"repo_id": "owncloud",
"token_count": 811
} | 870 |
import { readFileSync } from 'fs'
import { Page } from '@playwright/test'
interface File {
name: string
path: string
}
interface FileBuffer {
name: string
bufferString: string
}
export const dragDropFiles = async (page: Page, resources: File[], targetSelector: string) => {
const files = resources.map((file) => ({
name: file.name,
bufferString: JSON.stringify(Array.from(readFileSync(file.path)))
}))
await page.evaluate(
([files, targetSelector]: [FileBuffer[], string]) => {
const dropArea = document.querySelector(targetSelector)
const dt = new DataTransfer()
for (const file of files) {
const buffer = Buffer.from(JSON.parse(file.bufferString))
const blob = new Blob([buffer])
dt.items.add(new File([blob], file.name))
}
dropArea.dispatchEvent(new DragEvent('drop', { dataTransfer: dt }))
return Promise.resolve()
},
[files, targetSelector]
)
}
| owncloud/web/tests/e2e/support/utils/dragDrop.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/utils/dragDrop.ts",
"repo_id": "owncloud",
"token_count": 346
} | 871 |
<?php
//验证码
function vcode($width=120,$height=40,$fontSize=30,$countElement=5,$countPixel=100,$countLine=4){
header('Content-type:image/jpeg');
$element=array('a','b','c','d','e','f','g','h','i','j','k','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9');
$string='';
for ($i=0;$i<$countElement;$i++){
$string.=$element[rand(0,count($element)-1)];
}
$img=imagecreatetruecolor($width, $height);
$colorBg=imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));
$colorBorder=imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));
$colorString=imagecolorallocate($img,rand(10,100),rand(10,100),rand(10,100));
imagefill($img,0,0,$colorBg);
for($i=0;$i<$countPixel;$i++){
imagesetpixel($img,rand(0,$width-1),rand(0,$height-1),imagecolorallocate($img,rand(100,200),rand(100,200),rand(100,200)));
}
for($i=0;$i<$countLine;$i++){
imageline($img,rand(0,$width/2),rand(0,$height),rand($width/2,$width),rand(0,$height),imagecolorallocate($img,rand(100,200),rand(100,200),rand(100,200)));
}
//imagestring($img,5,0,0,'abcd',$colorString);
imagettftext($img,$fontSize,rand(-5,5),rand(5,15),rand(30,35),$colorString,'../assets/fonts/ManyGifts.ttf',$string);
imagejpeg($img);
imagedestroy($img);
return $string;
}
//之前的验证码有点问题,重新从网上搜了一个简单的验证码函数,是的,从网上搜的。
function vcodex(){
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
$str = "";
for($i=0;$i<6;$i++){
$pos = rand(0,35);
$str .= $string[$pos];
}
//session_start();
//$_SESSION['img_number'] = $str;
$img_handle = Imagecreate(80, 20); //图片大小80X20
$back_color = ImageColorAllocate($img_handle, 255, 255, 255); //背景颜色(白色)
$txt_color = ImageColorAllocate($img_handle, 0,0, 0); //文本颜色(黑色)
//加入干扰线
for($i=0;$i<3;$i++)
{
$line = ImageColorAllocate($img_handle,rand(0,255),rand(0,255),rand(0,255));
Imageline($img_handle, rand(0,15), rand(0,15), rand(100,150),rand(10,50), $line);
}
//加入干扰象素
for($i=0;$i<200;$i++)
{
$randcolor = ImageColorallocate($img_handle,rand(0,255),rand(0,255),rand(0,255));
Imagesetpixel($img_handle, rand()%100 , rand()%50 , $randcolor);
}
Imagefill($img_handle, 0, 0, $back_color); //填充图片背景色
ImageString($img_handle, 28, 10, 0, $str, $txt_color);//水平填充一行字符串
ob_clean(); // ob_clean()清空输出缓存区
header("Content-type: image/png"); //生成验证码图片
Imagepng($img_handle);//显示图片
return $str;
}
//生成一个token,以当前微妙时间+一个5位的前缀
function set_token(){
if(isset($_SESSION['token'])){
unset($_SESSION['token']);
}
$_SESSION['token']=str_replace('.','',uniqid(mt_rand(10000,99999),true));
}
//跳转页面
function skip($notice,$url){
$html=<<<A
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="2;URL={$url}" />
<title>notice</title>
<link rel="stylesheet" type="text/css" href="../../../style/header.css"/>
</head>
<body>
<p id='op_notice'>{$notice} | <a href='{$url}'>点击快速返回</a></p>
</body>
</html>
A;
echo $html;
exit();
}
//在访问一个页面时,先验证是否登录,csrf里面,使用的是session验证
function check_csrf_login($link){
if(isset($_SESSION['csrf']['username']) && isset($_SESSION['csrf']['password'])){
$query="select * from member where username='{$_SESSION['csrf']['username']}' and sha1(pw)='{$_SESSION['csrf']['password']}'";
$result=execute($link,$query);
if(mysqli_num_rows($result)==1){
return true;
}else{
return false;
}
}else{
return false;
}
}
//在访问一个页面时,先验证是否登录,sqli的insert,update问题里面,使用的是session验证
function check_sqli_session($link){
if(isset($_SESSION['sqli']['username']) && isset($_SESSION['sqli']['password'])){
$query="select * from member where username='{$_SESSION['sqli']['username']}' and sha1(pw)='{$_SESSION['sqli']['password']}'";
$result=execute($link,$query);
if(mysqli_num_rows($result)==1){
return true;
}else{
return false;
}
}else{
return false;
}
}
//在访问一个页面时,先验证是否登录,sqli里面,使用的是cookie验证
function check_sqli_login($link){
if(isset($_COOKIE['ant']['uname']) && isset($_COOKIE['ant']['pw'])){
//这里如果不对获取的cookie进行转义,则会存在SQL注入漏洞,也会导致验证被绕过
//$username=escape($link, $_COOKIE['ant']['username']);
//$password=escape($link, $_COOKIE['ant']['password']);
$username=$_COOKIE['ant']['uname'];
$password=$_COOKIE['ant']['pw'];
$query="select * from users where username='$username' and sha1(password)='$password'";
$result=execute($link,$query);
if(mysqli_num_rows($result)==1){
$data=mysqli_fetch_assoc($result);
return $data['id'];
}else{
return false;
}
}else{
return false;
}
}
/*xss里面的logincheck*/
function check_xss_login($link){
if(isset($_COOKIE['ant']['uname']) && isset($_COOKIE['ant']['pw'])){
//这里如果不对获取的cookie进行转义,则会存在SQL注入漏洞,也会导致验证被绕过
$username=escape($link, $_COOKIE['ant']['uname']);
$password=escape($link, $_COOKIE['ant']['pw']);
// $username=$_COOKIE['ant']['uname'];
// $password=$_COOKIE['ant']['pw'];
$query="select * from users where username='$username' and sha1(password)='$password'";
$result=execute($link,$query);
if(mysqli_num_rows($result)==1){
$data=mysqli_fetch_assoc($result);
return $data['id'];
}else{
return false;
}
}else{
return false;
}
}
/*op1的check login*/
function check_op_login($link){
if(isset($_SESSION['op']['username']) && isset($_SESSION['op']['password'])){
$query="select * from member where username='{$_SESSION['op']['username']}' and sha1(pw)='{$_SESSION['op']['password']}'";
$result=execute($link,$query);
if(mysqli_num_rows($result)==1){
return true;
}else{
return false;
}
}else{
return false;
}
}
/*op2的check login*/
function check_op2_login($link){
if(isset($_SESSION['op2']['username']) && isset($_SESSION['op2']['password'])){
$query="select * from users where username='{$_SESSION['op2']['username']}' and sha1(password)='{$_SESSION['op2']['password']}'";
$result=execute($link,$query);
if(mysqli_num_rows($result)==1){
return true;
}else{
return false;
}
}else{
return false;
}
}
?>
| zhuifengshaonianhanlu/pikachu/inc/function.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/inc/function.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 3733
} | 872 |
<?php
// error_reporting(0);
include_once '../inc/config.inc.php';
include_once '../inc/mysql.inc.php';
$link=connect();
// 判断是否登录,没有登录不能访问
if(!check_login($link)){
header("location:../pkxss_login.php");
}
if(isset($_GET['id']) && is_numeric($_GET['id'])){
$id=escape($link, $_GET['id']);
$query="delete from cookies where id=$id";
execute($link, $query);
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cookie搜集结果</title>
<link rel="stylesheet" type="text/css" href="../antxss.css" />
</head>
<body>
<div id="title">
<h1>pikachu Xss 获取cookies结果</h1>
<a href="../xssmanager.php">返回首页</a>
</div>
<div id="xss_main">
<table border="1px" cellpadding="10" cellspacing="1" bgcolor="#5f9ea0">
<tr>
<td>id</td>
<td>time</td>
<td>ipaddress</td>
<td>cookie</td>
<td>referer</td>
<td>useragent</td>
<td>删除</td>
</tr>
<?php
$query="select * from cookies";
$result=mysqli_query($link, $query);
while($data=mysqli_fetch_assoc($result)){
$html=<<<A
<tr>
<td>{$data['id']}</td>
<td>{$data['time']}</td>
<td>{$data['ipaddress']}</td>
<td>{$data['cookie']}</td>
<td>{$data['referer']}</td>
<td>{$data['useragent']}</td>
<td><a href="pkxss_cookie_result.php?id={$data['id']}">删除</a></td>
</tr>
A;
echo $html;
}
?>
</table>
</div>
</body>
</html> | zhuifengshaonianhanlu/pikachu/pkxss/xcookie/pkxss_cookie_result.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/pkxss/xcookie/pkxss_cookie_result.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 834
} | 873 |
<?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 = "csrf_get.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();
// 判断是否登录,没有登录不能访问
if(!check_csrf_login($link)){
// echo "<script>alert('登录后才能进入会员中心哦')</script>";
header("location:csrf_get_login.php");
}
if(isset($_GET['logout']) && $_GET['logout'] == 1){
session_unset();
session_destroy();
setcookie(session_name(),'',time()-3600,'/');
header("location:csrf_get_login.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="../csrf.php">CSRF</a>
</li>
<li class="active">CSRF(get)</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<?php
//通过当前session-name到数据库查询,并显示其对应信息
$username=$_SESSION['csrf']['username'];
$query="select * from member where username='$username'";
$result=execute($link, $query);
$data=mysqli_fetch_array($result);
$name=$data['username'];
$sex=$data['sex'];
$phonenum=$data['phonenum'];
$add=$data['address'];
$email=$data['email'];
$html=<<<A
<div id="per_info">
<h1 class="per_title">hello,{$name},欢迎来到个人会员中心 | <a style="color:bule;" href="csrf_get.php?logout=1">退出登录</a></h1>
<p class="per_name">姓名:{$name}</p>
<p class="per_sex">性别:{$sex}</p>
<p class="per_phone">手机:{$phonenum}</p>
<p class="per_add">住址:{$add}</p>
<p class="per_email">邮箱:{$email}</p>
<a class="edit" href="csrf_get_edit.php">修改个人信息</a>
</div>
A;
echo $html;
?>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/csrf/csrfget/csrf_get.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/csrf/csrfget/csrf_get.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1466
} | 874 |
<?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 = "op1_login.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../../";
include_once $PIKA_ROOT_DIR . 'header.php';
include_once $PIKA_ROOT_DIR.'inc/mysql.inc.php';
include_once $PIKA_ROOT_DIR.'inc/function.php';
include_once $PIKA_ROOT_DIR.'inc/config.inc.php';
$link=connect();
// 判断是否登录,没有登录不能访问
if(!check_op_login($link)){
header("location:op1_login.php");
}
$html='';
if(isset($_GET['submit']) && $_GET['username']!=null){
//没有使用session来校验,而是使用的传进来的值,权限校验出现问题,这里应该跟登录态关系进行绑定
$username=escape($link, $_GET['username']);
$query="select * from member where username='$username'";
$result=execute($link, $query);
if(mysqli_num_rows($result)==1){
$data=mysqli_fetch_assoc($result);
$uname=$data['username'];
$sex=$data['sex'];
$phonenum=$data['phonenum'];
$add=$data['address'];
$email=$data['email'];
$html.=<<<A
<div id="per_info">
<h1 class="per_title">hello,{$uname},你的具体信息如下:</h1>
<p class="per_name">姓名:{$uname}</p>
<p class="per_sex">性别:{$sex}</p>
<p class="per_phone">手机:{$phonenum}</p>
<p class="per_add">住址:{$add}</p>
<p class="per_email">邮箱:{$email}</p>
</div>
A;
}
}
if(isset($_GET['logout']) && $_GET['logout'] == 1){
session_unset();
session_destroy();
setcookie(session_name(),'',time()-3600,'/');
header("location:op1_login.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">op1 member</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="mem_main">
<p class="mem_title">欢迎来到个人信息中心 | <a style="color:bule;" href="op1_mem.php?logout=1">退出登录</a></p>
<form class="msg1" method="get">
<input type="hidden" name="username" value="<?php echo $_SESSION['op']['username']; ?>" />
<input 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/overpermission/op1/op1_mem.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/overpermission/op1/op1_mem.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1785
} | 875 |
<?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_insert.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();
//判断是是否登录,如果已经登录,点击时,直接进入会员中心
if(check_sqli_session($link)){
header("location:sqli_mem.php");
}
$html='';
if(isset($_GET['submit'])){
if($_GET['username']!=null && $_GET['password']!=null){
//转义,防注入
$username=escape($link, $_GET['username']);
$password=escape($link, $_GET['password']);
$query="select * from member where username='$username' and pw=md5('$password')";
$result=execute($link, $query);
if(mysqli_num_rows($result)==1){
$data=mysqli_fetch_assoc($result);
$_SESSION['sqli']['username']=$username;
$_SESSION['sqli']['password']=sha1(md5($password));
header("location:sqli_mem.php");
}else{
$html.="<p>登录失败,请重新登录</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">login</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 class="sqli_form">
<div class="sqli_form_main">
<h4 class="header blue lighter bigger">
<i class="ace-icon fa fa-coffee green"></i>
Please Enter Your Information
</h4>
<form method="get" action="sqli_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>
</div>
</form>
<?php echo $html;?>
<p>如果你还没有账号,请点击<a href="sqli_reg.php">注册</a></p>
</div><!-- /.widget-main -->
</div><!-- /.widget-body -->
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_iu/sqli_login.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_iu/sqli_login.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2183
} | 876 |
<?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 = "unserilization.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="unserilization.php">PHP反序列化</a>
</li>
<li class="active">概述</li>
</ul>
</div>
<div class="page-content">
<p>在理解这个漏洞前,你需要先搞清楚php中serialize(),unserialize()这两个函数。</p>
<b>序列化serialize()</b><br />
序列化说通俗点就是把一个对象变成可以传输的字符串,比如下面是一个对象:
<pre>
class S{
public $test="pikachu";
}
$s=new S(); //创建一个对象
serialize($s); //把这个对象进行序列化
序列化后得到的结果是这个样子的:O:1:"S":1:{s:4:"test";s:7:"pikachu";}
O:代表object
1:代表对象名字长度为一个字符
S:对象的名称
1:代表对象里面有一个变量
s:数据类型
4:变量名称的长度
test:变量名称
s:数据类型
7:变量值的长度
pikachu:变量值
</pre>
<b>反序列化unserialize()</b><br />
<p>就是把被序列化的字符串还原为对象,然后在接下来的代码中继续使用。</p>
<pre>
$u=unserialize("O:1:"S":1:{s:4:"test";s:7:"pikachu";}");
echo $u->test; //得到的结果为pikachu
</pre>
<p>序列化和反序列化本身没有问题,但是如果反序列化的内容是用户可以控制的,且后台不正当的使用了PHP中的魔法函数,就会导致安全问题</p>
<pre>
常见的几个魔法函数:
__construct()当一个对象创建时被调用
__destruct()当一个对象销毁时被调用
__toString()当一个对象被当作一个字符串使用
__sleep() 在对象在被序列化之前运行
__wakeup将在序列化之后立即被调用
漏洞举例:
class S{
var $test = "pikachu";
function __destruct(){
echo $this->test;
}
}
$s = $_GET['test'];
@$unser = unserialize($a);
payload:O:1:"S":1:{s:4:"test";s:29:"<?php echo htmlspecialchars("<script>alert('xss')</script>");?>";}
</pre>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/unserilization/unserilization.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/unserilization/unserilization.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1987
} | 877 |
<?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 = "post_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:xss_reflected_post.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">反射性xss(post)</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="为了能够让你练习xss获取cookie,我们还是登陆一下,账号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="post_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/xsspost/post_login.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/xss/xsspost/post_login.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2581
} | 878 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>8th Wall Web: Animations</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>
<script src="//cdn.8thwall.com/web/aframe/aframe-extras-6.1.1.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 async src="//apps.8thwall.com/xrweb?appKey=XXXXX"></script>
<script>
AFRAME.registerComponent('next-button', {
init() {
const animationList = ['idle', 'pockets', 'hiphop', 'chicken']
const model = document.getElementById('model')
const nextButton = document.getElementById('nextbutton')
nextButton.style.display = 'block'
let idx = 1 // Start with the 2nd animation because the model starts with idle animation
const nextAnimation = () => {
model.setAttribute('animation-mixer', {
clip: animationList[idx],
loop: 'repeat',
crossFadeDuration: 0.4,
})
idx = (idx + 1) % animationList.length
}
nextButton.onclick = nextAnimation // Switch to the next animation when the button is pressed.
},
})
</script>
</head>
<body>
<div id="nextbutton" style="display: none; z-index: 10">
<h2>Next Animation</h2>
</div>
<a-scene
next-button
xrextras-gesture-detector
landing-page
xrextras-loading
xrextras-runtime-error
renderer="colorManagement:true"
xrweb="allowedDevices: any">
<!-- We can define assets here to be loaded when A-Frame initializes -->
<a-assets>
<a-asset-item id="animatedModel" src="mixamo-animated-lowpoly.glb"></a-asset-item>
</a-assets>
<!-- The raycaster will emit mouse events on scene objects specified with the cantap class -->
<a-camera
id="camera"
position="0 8 8"
raycaster="objects: .cantap"
cursor="
fuse: false;
rayOrigin: mouse;">
</a-camera>
<a-entity
light="type: directional;
intensity: 0.8;
castShadow: true;
shadowMapHeight:2048;
shadowMapWidth:2048;
shadowCameraTop: 10;
target: #model;"
position="1 4.3 2.5"
xrextras-attach="target: model; offset: 1 15 3;"
shadow>
</a-entity>
<a-light type="ambient" intensity="0.5"></a-light>
<a-entity
id="model"
gltf-model="#animatedModel"
class="cantap"
scale="3 3 3"
animation-mixer="clip: idle; loop: repeat"
xrextras-hold-drag
xrextras-two-finger-rotate
xrextras-pinch-scale
shadow>
</a-entity>
<a-plane id="ground" position="0 0 0" rotation="-90 0 0" width="50" height="50" material="shader: shadow" shadow></a-plane>
</a-scene>
</body>
</html>
| 8thwall/web/examples/aframe/animation-mixer/index.html/0 | {
"file_path": "8thwall/web/examples/aframe/animation-mixer/index.html",
"repo_id": "8thwall",
"token_count": 1569
} | 0 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>8th Wall Web: Capture a photo</title>
<!-- 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>
<script src="photo-mode.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 async src="//apps.8thwall.com/xrweb?appKey=XXXXX"></script>
<link rel="stylesheet" href="index.css">
</head>
<body>
<a-scene
landing-page
xrextras-loading
xrextras-runtime-error
xrextras-tap-recenter
renderer="colorManagement:true"
xrweb="allowedDevices: any">
<!-- We can define assets here to be loaded when A-Frame initializes -->
<a-assets>
<!-- Credit to Poly by Google for the model: https://poly.google.com/view/fojR5i3h_nh -->
<a-asset-item id="ufoModel" src="ufo.glb"></a-asset-item>
</a-assets>
<!-- add capture button -->
<xrextras-capture-button capture-mode="photo"></xrextras-capture-button>
<!-- configure capture settings -->
<xrextras-capture-config
watermark-image-url="8logo.png"
watermark-max-width="100"
watermark-max-height="10"
file-name-prefix="ufo-image-"
request-mic="manual"
></xrextras-capture-config>
<!-- add capture preview -->
<xrextras-capture-preview></xrextras-capture-preview>
<a-camera position="0 4 10"></a-camera>
<a-entity light="type: directional; intensity: 0.8;" position="1 4.3 2.5"></a-entity>
<a-light type="ambient" intensity="1"></a-light>
<a-entity gltf-model="#ufoModel" scale="3 3 3" position="0 7 0"></a-entity>
<a-cylinder
geometry="segments-radial: 8"
material="transparent:true; opacity: 0.5; color: #33ff33"
open-ended="true"
height="7"
radius="1.5"
position="0 3.5 0">
</a-cylinder>
</a-scene>
</body>
</html>
| 8thwall/web/examples/aframe/capturephoto/index.html/0 | {
"file_path": "8thwall/web/examples/aframe/capturephoto/index.html",
"repo_id": "8thwall",
"token_count": 1030
} | 1 |
{
"name": "reactapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"html-loader": "^4.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "HTTPS=true react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"react-app-rewired": "^2.2.1"
}
}
| 8thwall/web/examples/aframe/reactapp/package.json/0 | {
"file_path": "8thwall/web/examples/aframe/reactapp/package.json",
"repo_id": "8thwall",
"token_count": 426
} | 2 |
import React from 'react'
import {AFrameScene} from '../lib/aframe-components'
import html from './cube.html'
const Scene = () => (
<AFrameScene sceneHtml={html} />
)
export {Scene}
| 8thwall/web/examples/aframe/reactapp/src/views/scene.jsx/0 | {
"file_path": "8thwall/web/examples/aframe/reactapp/src/views/scene.jsx",
"repo_id": "8thwall",
"token_count": 65
} | 3 |
# 8th Wall Web Examples - Camera Pipeline - Camera Feed
This example shows how to create an 8th Wall Web that draws the camera feed over the entire
screen.
Camera Feed
:----------:

[Try Demo (mobile)](https://apps.8thwall.com/8thWall/camerapipeline_camerafeed)
or scan on phone:<br> 
| 8thwall/web/examples/camerapipeline/camerafeed/README.md/0 | {
"file_path": "8thwall/web/examples/camerapipeline/camerafeed/README.md",
"repo_id": "8thwall",
"token_count": 140
} | 4 |
/*
Ported to JavaScript by Lazar Laszlo 2011
lazarsoft@gmail.com, www.lazarsoft.info
*/
/*
*
* Copyright 2007 ZXing authors
*
* 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.
*/
function PerspectiveTransform( a11, a21, a31, a12, a22, a32, a13, a23, a33)
{
this.a11 = a11;
this.a12 = a12;
this.a13 = a13;
this.a21 = a21;
this.a22 = a22;
this.a23 = a23;
this.a31 = a31;
this.a32 = a32;
this.a33 = a33;
this.transformPoints1=function( points)
{
var max = points.length;
var a11 = this.a11;
var a12 = this.a12;
var a13 = this.a13;
var a21 = this.a21;
var a22 = this.a22;
var a23 = this.a23;
var a31 = this.a31;
var a32 = this.a32;
var a33 = this.a33;
for (var i = 0; i < max; i += 2)
{
var x = points[i];
var y = points[i + 1];
var denominator = a13 * x + a23 * y + a33;
points[i] = (a11 * x + a21 * y + a31) / denominator;
points[i + 1] = (a12 * x + a22 * y + a32) / denominator;
}
}
this. transformPoints2=function(xValues, yValues)
{
var n = xValues.length;
for (var i = 0; i < n; i++)
{
var x = xValues[i];
var y = yValues[i];
var denominator = this.a13 * x + this.a23 * y + this.a33;
xValues[i] = (this.a11 * x + this.a21 * y + this.a31) / denominator;
yValues[i] = (this.a12 * x + this.a22 * y + this.a32) / denominator;
}
}
this.buildAdjoint=function()
{
// Adjoint is the transpose of the cofactor matrix:
return new PerspectiveTransform(this.a22 * this.a33 - this.a23 * this.a32, this.a23 * this.a31 - this.a21 * this.a33, this.a21 * this.a32 - this.a22 * this.a31, this.a13 * this.a32 - this.a12 * this.a33, this.a11 * this.a33 - this.a13 * this.a31, this.a12 * this.a31 - this.a11 * this.a32, this.a12 * this.a23 - this.a13 * this.a22, this.a13 * this.a21 - this.a11 * this.a23, this.a11 * this.a22 - this.a12 * this.a21);
}
this.times=function( other)
{
return new PerspectiveTransform(this.a11 * other.a11 + this.a21 * other.a12 + this.a31 * other.a13, this.a11 * other.a21 + this.a21 * other.a22 + this.a31 * other.a23, this.a11 * other.a31 + this.a21 * other.a32 + this.a31 * other.a33, this.a12 * other.a11 + this.a22 * other.a12 + this.a32 * other.a13, this.a12 * other.a21 + this.a22 * other.a22 + this.a32 * other.a23, this.a12 * other.a31 + this.a22 * other.a32 + this.a32 * other.a33, this.a13 * other.a11 + this.a23 * other.a12 +this.a33 * other.a13, this.a13 * other.a21 + this.a23 * other.a22 + this.a33 * other.a23, this.a13 * other.a31 + this.a23 * other.a32 + this.a33 * other.a33);
}
}
PerspectiveTransform.quadrilateralToQuadrilateral=function( x0, y0, x1, y1, x2, y2, x3, y3, x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p)
{
var qToS = this.quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3);
var sToQ = this.squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p);
return sToQ.times(qToS);
}
PerspectiveTransform.squareToQuadrilateral=function( x0, y0, x1, y1, x2, y2, x3, y3)
{
var dy2 = y3 - y2;
var dy3 = y0 - y1 + y2 - y3;
if (dy2 == 0.0 && dy3 == 0.0)
{
return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0, 0.0, 1.0);
}
else
{
var dx1 = x1 - x2;
var dx2 = x3 - x2;
var dx3 = x0 - x1 + x2 - x3;
var dy1 = y1 - y2;
var denominator = dx1 * dy2 - dx2 * dy1;
var a13 = (dx3 * dy2 - dx2 * dy3) / denominator;
var a23 = (dx1 * dy3 - dx3 * dy1) / denominator;
return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0);
}
}
PerspectiveTransform.quadrilateralToSquare=function( x0, y0, x1, y1, x2, y2, x3, y3)
{
// Here, the adjoint serves as the inverse:
return this.squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint();
}
function DetectorResult(bits, points)
{
this.bits = bits;
this.points = points;
}
function Detector(image)
{
this.image=image;
this.resultPointCallback = null;
this.sizeOfBlackWhiteBlackRun=function( fromX, fromY, toX, toY)
{
// Mild variant of Bresenham's algorithm;
// see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
var steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
if (steep)
{
var temp = fromX;
fromX = fromY;
fromY = temp;
temp = toX;
toX = toY;
toY = temp;
}
var dx = Math.abs(toX - fromX);
var dy = Math.abs(toY - fromY);
var error = - dx >> 1;
var ystep = fromY < toY?1:- 1;
var xstep = fromX < toX?1:- 1;
var state = 0; // In black pixels, looking for white, first or second time
for (var x = fromX, y = fromY; x != toX; x += xstep)
{
var realX = steep?y:x;
var realY = steep?x:y;
if (state == 1)
{
// In white pixels, looking for black
if (this.image[realX + realY*qrcode.width])
{
state++;
}
}
else
{
if (!this.image[realX + realY*qrcode.width])
{
state++;
}
}
if (state == 3)
{
// Found black, white, black, and stumbled back onto white; done
var diffX = x - fromX;
var diffY = y - fromY;
return Math.sqrt( (diffX * diffX + diffY * diffY));
}
error += dy;
if (error > 0)
{
if (y == toY)
{
break;
}
y += ystep;
error -= dx;
}
}
var diffX2 = toX - fromX;
var diffY2 = toY - fromY;
return Math.sqrt( (diffX2 * diffX2 + diffY2 * diffY2));
}
this.sizeOfBlackWhiteBlackRunBothWays=function( fromX, fromY, toX, toY)
{
var result = this.sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
// Now count other way -- don't run off image though of course
var scale = 1.0;
var otherToX = fromX - (toX - fromX);
if (otherToX < 0)
{
scale = fromX / (fromX - otherToX);
otherToX = 0;
}
else if (otherToX >= qrcode.width)
{
scale = (qrcode.width - 1 - fromX) / (otherToX - fromX);
otherToX = qrcode.width - 1;
}
var otherToY = Math.floor (fromY - (toY - fromY) * scale);
scale = 1.0;
if (otherToY < 0)
{
scale = fromY / (fromY - otherToY);
otherToY = 0;
}
else if (otherToY >= qrcode.height)
{
scale = (qrcode.height - 1 - fromY) / (otherToY - fromY);
otherToY = qrcode.height - 1;
}
otherToX = Math.floor (fromX + (otherToX - fromX) * scale);
result += this.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
return result - 1.0; // -1 because we counted the middle pixel twice
}
this.calculateModuleSizeOneWay=function( pattern, otherPattern)
{
var moduleSizeEst1 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor( pattern.X), Math.floor( pattern.Y), Math.floor( otherPattern.X), Math.floor(otherPattern.Y));
var moduleSizeEst2 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(otherPattern.X), Math.floor(otherPattern.Y), Math.floor( pattern.X), Math.floor(pattern.Y));
if (isNaN(moduleSizeEst1))
{
return moduleSizeEst2 / 7.0;
}
if (isNaN(moduleSizeEst2))
{
return moduleSizeEst1 / 7.0;
}
// Average them, and divide by 7 since we've counted the width of 3 black modules,
// and 1 white and 1 black module on either side. Ergo, divide sum by 14.
return (moduleSizeEst1 + moduleSizeEst2) / 14.0;
}
this.calculateModuleSize=function( topLeft, topRight, bottomLeft)
{
// Take the average
return (this.calculateModuleSizeOneWay(topLeft, topRight) + this.calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0;
}
this.distance=function( pattern1, pattern2)
{
var xDiff = pattern1.X - pattern2.X;
var yDiff = pattern1.Y - pattern2.Y;
return Math.sqrt( (xDiff * xDiff + yDiff * yDiff));
}
this.computeDimension=function( topLeft, topRight, bottomLeft, moduleSize)
{
var tltrCentersDimension = Math.round(this.distance(topLeft, topRight) / moduleSize);
var tlblCentersDimension = Math.round(this.distance(topLeft, bottomLeft) / moduleSize);
var dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
switch (dimension & 0x03)
{
// mod 4
case 0:
dimension++;
break;
// 1? do nothing
case 2:
dimension--;
break;
case 3:
throw "Error";
}
return dimension;
}
this.findAlignmentInRegion=function( overallEstModuleSize, estAlignmentX, estAlignmentY, allowanceFactor)
{
// Look for an alignment pattern (3 modules in size) around where it
// should be
var allowance = Math.floor (allowanceFactor * overallEstModuleSize);
var alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
var alignmentAreaRightX = Math.min(qrcode.width - 1, estAlignmentX + allowance);
if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3)
{
throw "Error";
}
var alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
var alignmentAreaBottomY = Math.min(qrcode.height - 1, estAlignmentY + allowance);
var alignmentFinder = new AlignmentPatternFinder(this.image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, this.resultPointCallback);
return alignmentFinder.find();
}
this.createTransform=function( topLeft, topRight, bottomLeft, alignmentPattern, dimension)
{
var dimMinusThree = dimension - 3.5;
var bottomRightX;
var bottomRightY;
var sourceBottomRightX;
var sourceBottomRightY;
if (alignmentPattern != null)
{
bottomRightX = alignmentPattern.X;
bottomRightY = alignmentPattern.Y;
sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0;
}
else
{
// Don't have an alignment pattern, just make up the bottom-right point
bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X;
bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y;
sourceBottomRightX = sourceBottomRightY = dimMinusThree;
}
var transform = PerspectiveTransform.quadrilateralToQuadrilateral(3.5, 3.5, dimMinusThree, 3.5, sourceBottomRightX, sourceBottomRightY, 3.5, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y);
return transform;
}
this.sampleGrid=function( image, transform, dimension)
{
var sampler = GridSampler;
return sampler.sampleGrid3(image, dimension, transform);
}
this.processFinderPatternInfo = function( info)
{
var topLeft = info.TopLeft;
var topRight = info.TopRight;
var bottomLeft = info.BottomLeft;
var moduleSize = this.calculateModuleSize(topLeft, topRight, bottomLeft);
if (moduleSize < 1.0)
{
throw "Error";
}
var dimension = this.computeDimension(topLeft, topRight, bottomLeft, moduleSize);
var provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
var modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7;
var alignmentPattern = null;
// Anything above version 1 has an alignment pattern
if (provisionalVersion.AlignmentPatternCenters.length > 0)
{
// Guess where a "bottom right" finder pattern would have been
var bottomRightX = topRight.X - topLeft.X + bottomLeft.X;
var bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y;
// Estimate that alignment pattern is closer by 3 modules
// from "bottom right" to known top left location
var correctionToTopLeft = 1.0 - 3.0 / modulesBetweenFPCenters;
var estAlignmentX = Math.floor (topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X));
var estAlignmentY = Math.floor (topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y));
// Kind of arbitrary -- expand search radius before giving up
for (var i = 4; i <= 16; i <<= 1)
{
//try
//{
alignmentPattern = this.findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, i);
break;
//}
//catch (re)
//{
// try next round
//}
}
// If we didn't find alignment pattern... well try anyway without it
}
var transform = this.createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);
var bits = this.sampleGrid(this.image, transform, dimension);
var points;
if (alignmentPattern == null)
{
points = new Array(bottomLeft, topLeft, topRight);
}
else
{
points = new Array(bottomLeft, topLeft, topRight, alignmentPattern);
}
return new DetectorResult(bits, points);
}
this.detect=function()
{
var info = new FinderPatternFinder().findFinderPattern(this.image);
return this.processFinderPatternInfo(info);
}
} | 8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/detector.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/detector.js",
"repo_id": "8thwall",
"token_count": 5650
} | 5 |
html, body {
-webkit-tap-highlight-color: rgba(0,0,0,0);
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
| 8thwall/web/examples/threejs/8i-hologram/index.css/0 | {
"file_path": "8thwall/web/examples/threejs/8i-hologram/index.css",
"repo_id": "8thwall",
"token_count": 60
} | 6 |
body {
overflow: hidden;
width: 100%;
height: 100%;
margin: -1px 0px 0px 0px !important;
padding: 0;
}
| 8thwall/web/examples/threejs/placeground/index.css/0 | {
"file_path": "8thwall/web/examples/threejs/placeground/index.css",
"repo_id": "8thwall",
"token_count": 45
} | 7 |
/*jshint esversion: 6, asi: true, laxbreak: true*/
var FaceController = pc.createScript('face-controller');
FaceController.attributes.add('material', {
type: 'asset',
assetType: 'material'
});
FaceController.prototype.initialize = function() {
const pcCamera = XRExtras.PlayCanvas.findOneCamera(this.entity)
let mesh = null
// Fires when loading begins for additional face AR resources.
this.app.on('xr:faceloading', ({maxDetections, pointsPerDetection, indices, uvs}) => {
const node = new pc.GraphNode();
const material = this.material.resource;
mesh = pc.createMesh(
this.app.graphicsDevice,
new Array(pointsPerDetection * 3).fill(0.0), // setting filler vertex positions
{
uvs: uvs.map((uv) => [uv.u, uv.v]).flat(),
indices: indices.map((i) => [i.a, i.b, i.c]).flat()
}
);
const meshInstance = new pc.MeshInstance(node, mesh, material);
const model = new pc.Model();
model.graph = node;
model.meshInstances.push(meshInstance);
this.entity.model.model = model;
}, {})
// Fires when all face AR resources have been loaded and scanning has begun.
this.app.on('xr:facescanning', ({maxDetections, pointsPerDetection, indices, uvs}) => {
}, {})
// Fires when a face first found
this.app.on('xr:facefound', ({id, transform, attachmentPoints, vertices, normals}) => {
}, {})
// Fires when a face is lost
this.app.on('xr:facelost', ({id}) => {
}, {})
// Fires when a face is subsequently found.
this.app.on('xr:faceupdated', ({id, transform, attachmentPoints, vertices, normals}) => {
const {position, rotation, scale, scaledDepth, scaledHeight, scaledWidth} = transform
this.entity.setPosition(position.x, position.y, position.z);
this.entity.setLocalScale(scale, scale, scale)
this.entity.setRotation(rotation.x, rotation.y, rotation.z, rotation.w)
// Set mesh vertices in local space
mesh.setPositions(vertices.map((vertexPos) => [vertexPos.x, vertexPos.y, vertexPos.z]).flat())
// Set vertex normals
mesh.setNormals(normals.map((normal) => [normal.x, normal.y, normal.z]).flat())
mesh.update()
}, {})
// After XR has fully loaded, open the camera feed and start displaying AR.
const runOnLoad = ({pcCamera, pcApp}, extramodules) => () => {
const config = {allowedDevices: XR8.XrConfig.device().ANY,
cameraConfig: {direction: XR8.XrConfig.camera().FRONT}}
XR8.PlayCanvas.run({pcCamera, pcApp}, extramodules, config)
XR8.FaceController.configure({
meshGeometry: ['face'],
coordinates: {
axes: 'RIGHT_HANDED',
mirroredDisplay: true,
}
})
}
XRExtras.Loading.showLoading({onxrloaded: runOnLoad({pcCamera, pcApp: this.app}, [
XR8.FaceController.pipelineModule(), // Enables Face tracking.
XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup.
])})
};
| 8thwall/web/gettingstarted/playcanvas/scripts/facecontroller.js/0 | {
"file_path": "8thwall/web/gettingstarted/playcanvas/scripts/facecontroller.js",
"repo_id": "8thwall",
"token_count": 1075
} | 8 |
import type {ComponentDefinition} from 'aframe'
declare const THREE: any
// Recenter the scene when the screen is tapped.
const tapRecenterComponent: ComponentDefinition = {
init() {
const scene = this.el.sceneEl
scene.addEventListener('click', () => { scene.emit('recenter', {}) })
},
}
type FingerMoveEvent = {
positionChange: {
x: number
y: number
},
touchCount: number
startTime: number
startSpread: number
spreadChange: number
startPosition: {
x: number
y: number
}
positionRaw: {
x: number
y: number
}
}
interface GestureDetectorComponentDefinition extends ComponentDefinition {
emitGestureEvent: (event: TouchEvent) => void
getTouchState: (event: TouchEvent) => FingerMoveEvent
getEventPrefix: (event: number) => string
}
// Component that detects and emits events for touch gestures
const gestureDetectorComponent: GestureDetectorComponentDefinition = {
schema: {
element: {default: ''},
},
init() {
this.targetElement = this.data.element && document.querySelector(this.data.element)
if (!this.targetElement) {
this.targetElement = this.el
}
this.internalState = {
previousState: null,
}
this.emitGestureEvent = this.emitGestureEvent.bind(this)
this.targetElement.addEventListener('touchstart', this.emitGestureEvent)
this.targetElement.addEventListener('touchend', this.emitGestureEvent)
this.targetElement.addEventListener('touchmove', this.emitGestureEvent)
},
remove() {
this.targetElement.removeEventListener('touchstart', this.emitGestureEvent)
this.targetElement.removeEventListener('touchend', this.emitGestureEvent)
this.targetElement.removeEventListener('touchmove', this.emitGestureEvent)
},
emitGestureEvent(event) {
const currentState = this.getTouchState(event)
const {previousState} = this.internalState
const gestureContinues = previousState &&
currentState &&
currentState.touchCount == previousState.touchCount
const gestureEnded = previousState && !gestureContinues
const gestureStarted = currentState && !gestureContinues
if (gestureEnded) {
const eventName = `${this.getEventPrefix(previousState.touchCount)}fingerend`
this.el.emit(eventName, previousState)
this.internalState.previousState = null
}
if (gestureStarted) {
currentState.startTime = performance.now()
currentState.startPosition = currentState.position
currentState.startSpread = currentState.spread
const eventName = `${this.getEventPrefix(currentState.touchCount)}fingerstart`
this.el.emit(eventName, currentState)
this.internalState.previousState = currentState
}
if (gestureContinues) {
const eventDetail: any = {
positionChange: {
x: currentState.position.x - previousState.position.x,
y: currentState.position.y - previousState.position.y,
},
}
if (currentState.spread) {
eventDetail.spreadChange = currentState.spread - previousState.spread
}
// Update state with new data
Object.assign(previousState, currentState)
// Add state data to event detail
Object.assign(eventDetail, previousState)
const eventName = `${this.getEventPrefix(currentState.touchCount)}fingermove`
this.el.emit(eventName, eventDetail)
}
},
getTouchState(event) {
if (event.touches.length == 0) {
return null
}
// Convert event.touches to an array so we can use reduce
const touchList = []
for (let i = 0; i < event.touches.length; i++) {
touchList.push(event.touches[i])
}
const touchState: any = {
touchCount: touchList.length,
}
// Calculate center of all current touches
const centerPositionRawX = touchList.reduce((sum, touch) => sum + touch.clientX, 0) / touchList.length
const centerPositionRawY = touchList.reduce((sum, touch) => sum + touch.clientY, 0) / touchList.length
touchState.positionRaw = {x: centerPositionRawX, y: centerPositionRawY}
// Scale touch position and spread by average of window dimensions
const screenScale = 2 / (window.innerWidth + window.innerHeight)
touchState.position = {x: centerPositionRawX * screenScale, y: centerPositionRawY * screenScale}
// Calculate average spread of touches from the center point
if (touchList.length >= 2) {
const spread = touchList.reduce((sum, touch) => sum +
Math.sqrt(
Math.pow(centerPositionRawX - touch.clientX, 2) +
Math.pow(centerPositionRawY - touch.clientY, 2)
), 0) / touchList.length
touchState.spread = spread * screenScale
}
return touchState
},
getEventPrefix(touchCount) {
const numberNames = ['one', 'two', 'three', 'many']
return numberNames[Math.min(touchCount, 4) - 1]
},
}
type DragCallback = ({detail}: {detail: FingerMoveEvent}) => void
interface FingerMoveComponentDefinition extends ComponentDefinition {
handleEvent: DragCallback
}
const oneFingerRotateComponent: FingerMoveComponentDefinition = {
schema: {
factor: {default: 6},
},
init() {
this.handleEvent = this.handleEvent.bind(this)
this.el.sceneEl.addEventListener('onefingermove', this.handleEvent)
this.el.classList.add('cantap') // Needs "objects: .cantap" attribute on raycaster.
},
remove() {
this.el.sceneEl.removeEventListener('onefingermove', this.handleEvent)
},
handleEvent(event) {
this.el.object3D.rotation.y += event.detail.positionChange.x * this.data.factor
},
}
const twoFingerRotateComponent: FingerMoveComponentDefinition = {
schema: {
factor: {default: 5},
},
init() {
this.handleEvent = this.handleEvent.bind(this)
this.el.sceneEl.addEventListener('twofingermove', this.handleEvent)
this.el.classList.add('cantap') // Needs "objects: .cantap" attribute on raycaster.
},
remove() {
this.el.sceneEl.removeEventListener('twofingermove', this.handleEvent)
},
handleEvent(event) {
this.el.object3D.rotation.y += event.detail.positionChange.x * this.data.factor
},
}
const pinchScaleComponent: FingerMoveComponentDefinition = {
schema: {
min: {default: 0.33},
max: {default: 3},
scale: {default: 0}, // If scale is set to zero here, the object's initial scale is used.
},
init() {
const s = this.data.scale
this.initialScale = (s && {x: s, y: s, z: s}) || this.el.object3D.scale.clone()
this.scaleFactor = 1
this.handleEvent = this.handleEvent.bind(this)
this.el.sceneEl.addEventListener('twofingermove', this.handleEvent)
this.el.classList.add('cantap') // Needs "objects: .cantap" attribute on raycaster.
},
remove() {
this.el.sceneEl.removeEventListener('twofingermove', this.handleEvent)
},
handleEvent(event) {
this.scaleFactor *= 1 + event.detail.spreadChange / event.detail.startSpread
this.scaleFactor = Math.min(Math.max(this.scaleFactor, this.data.min), this.data.max)
this.el.object3D.scale.x = this.scaleFactor * this.initialScale.x
this.el.object3D.scale.y = this.scaleFactor * this.initialScale.y
this.el.object3D.scale.z = this.scaleFactor * this.initialScale.z
},
}
interface HoldDragComponentDefinition extends ComponentDefinition {
fingerDown: DragCallback
startDrag: DragCallback
fingerMove: DragCallback
fingerUp: DragCallback
}
const holdDragComponent: HoldDragComponentDefinition = {
schema: {
cameraId: {default: 'camera'},
groundId: {default: 'ground'},
dragDelay: {default: 300},
riseHeight: {default: 1},
},
init() {
this.camera = document.getElementById(this.data.cameraId)
if (!this.camera) {
throw new Error(`[xrextras-hold-drag] Couldn't find camera with id '${this.data.cameraId}'`)
}
this.threeCamera = this.camera.getObject3D('camera')
this.ground = document.getElementById(this.data.groundId)
if (!this.ground) {
throw new Error(`[xrextras-hold-drag] Couldn't find ground with id '${this.data.groundId}'`)
}
this.internalState = {
fingerDown: false,
dragging: false,
distance: 0,
startDragTimeout: null,
raycaster: new THREE.Raycaster(),
}
this.fingerDown = this.fingerDown.bind(this)
this.startDrag = this.startDrag.bind(this)
this.fingerMove = this.fingerMove.bind(this)
this.fingerUp = this.fingerUp.bind(this)
this.el.addEventListener('mousedown', this.fingerDown)
this.el.sceneEl.addEventListener('onefingermove', this.fingerMove)
this.el.sceneEl.addEventListener('onefingerend', this.fingerUp)
this.el.classList.add('cantap') // Needs "objects: .cantap" attribute on raycaster.
},
tick() {
if (this.internalState.dragging) {
let desiredPosition = null
if (this.internalState.positionRaw) {
const screenPositionX = this.internalState.positionRaw.x / document.body.clientWidth * 2 - 1
const screenPositionY = this.internalState.positionRaw.y / document.body.clientHeight * 2 - 1
const screenPosition = new THREE.Vector2(screenPositionX, -screenPositionY)
this.threeCamera = this.threeCamera || this.camera.getObject3D('camera')
this.internalState.raycaster.setFromCamera(screenPosition, this.threeCamera)
const intersects = this.internalState.raycaster.intersectObject(this.ground.object3D, true)
if (intersects.length > 0) {
const intersect = intersects[0]
this.internalState.distance = intersect.distance
desiredPosition = intersect.point
}
}
if (!desiredPosition) {
desiredPosition = this.camera.object3D.localToWorld(new THREE.Vector3(0, 0, -this.internalState.distance))
}
desiredPosition.y = this.data.riseHeight
this.el.object3D.position.lerp(desiredPosition, 0.2)
}
},
remove() {
this.el.removeEventListener('mousedown', this.fingerDown)
this.el.sceneEl.removeEventListener('onefingermove', this.fingerMove)
this.el.sceneEl.removeEventListener('onefingerend', this.fingerUp)
if (this.internalState.fingerDown) {
this.fingerUp()
}
},
fingerDown(event) {
this.internalState.fingerDown = true
this.internalState.startDragTimeout = setTimeout(this.startDrag, this.data.dragDelay)
this.internalState.positionRaw = event.detail.positionRaw
},
startDrag(event) {
if (!this.internalState.fingerDown) {
return
}
this.internalState.dragging = true
this.internalState.distance = this.el.object3D.position.distanceTo(this.camera.object3D.position)
},
fingerMove(event) {
this.internalState.positionRaw = event.detail.positionRaw
},
fingerUp(event) {
this.internalState.fingerDown = false
clearTimeout(this.internalState.startDragTimeout)
this.internalState.positionRaw = null
if (this.internalState.dragging) {
const endPosition = this.el.object3D.position.clone()
this.el.setAttribute('animation__drop', {
property: 'position',
to: `${endPosition.x} 0 ${endPosition.z}`,
dur: 300,
easing: 'easeOutQuad',
})
}
this.internalState.dragging = false
},
}
// Triggers video playback on tap.
const playVideoComponent: ComponentDefinition = {
schema: {
video: {type: 'string'},
thumb: {type: 'string'},
canstop: {type: 'bool'},
},
init() {
const v = document.querySelector(this.data.video)
const p = this.data.thumb && document.querySelector(this.data.thumb)
const {el} = this
el.setAttribute('material', 'src', p || v)
el.setAttribute('class', 'cantap')
let playing = false
el.addEventListener('click', () => {
if (!playing) {
el.setAttribute('material', 'src', v)
v.play()
playing = true
} else if (this.data.canstop) {
el.setAttribute('material', 'src', p || v)
v.pause()
playing = false
}
})
},
}
export {
tapRecenterComponent,
gestureDetectorComponent,
oneFingerRotateComponent,
twoFingerRotateComponent,
pinchScaleComponent,
holdDragComponent,
playVideoComponent,
FingerMoveComponentDefinition,
GestureDetectorComponentDefinition,
HoldDragComponentDefinition,
}
| 8thwall/web/xrextras/src/aframe/components/gestures-components.ts/0 | {
"file_path": "8thwall/web/xrextras/src/aframe/components/gestures-components.ts",
"repo_id": "8thwall",
"token_count": 4426
} | 9 |
declare const XR8: any
function create() {
let canvas_ = null
const vsize_ = {
w: 0,
h: 0,
}
let orientation_ = 0
const originalBodyStyleSubset_ = {
backgroundColor: 'initial',
overflowY: 'initial',
}
const originalHtmlStyleSubset_ = {
overflow: 'initial',
}
const canvasStyle_ = {
width: '100%',
height: '100%',
margin: '0px',
padding: '0px',
border: '0px',
display: 'block',
}
const bodyStyle_ = {
width: '100%',
height: '100%',
margin: '0px',
padding: '0px',
border: '0px',
overflowY: 'initial',
backgroundColor: 'initial',
}
const isCompatibleMobile = () =>
// eslint-disable-next-line implicit-arrow-linebreak
XR8.XrDevice.isDeviceBrowserCompatible({allowedDevices: XR8.XrConfig.device().MOBILE}) &&
!XR8.XrDevice.deviceEstimate().model.toLowerCase().includes('ipad')
// Update the size of the camera feed canvas to fill the screen.
const fillScreenWithCanvas = () => {
if (!canvas_) { return }
// Get the pixels of the browser window.
const uww = window.innerWidth
const uwh = window.innerHeight
const ww = uww * devicePixelRatio
const wh = uwh * devicePixelRatio
// Wait for orientation change to take effect before handling resize on mobile phones only.
const displayOrientationMismatch = ((orientation_ === 0 || orientation_ === 180) && ww > wh) ||
((orientation_ === 90 || orientation_ === -90) && wh > ww)
if (displayOrientationMismatch && isCompatibleMobile()) {
window.requestAnimationFrame(fillScreenWithCanvas)
return
}
// Compute the portrait-orientation aspect ratio of the browser window.
const ph = Math.max(ww, wh)
const pw = Math.min(ww, wh)
const pa = ph / pw
// Compute the portrait-orientation dimensions of the video.
const pvh = Math.max(vsize_.w, vsize_.h)
const pvw = Math.min(vsize_.w, vsize_.h)
// Compute the cropped dimensions of a video that fills the screen, assuming that width is
// cropped.
let ch = pvh
let cw = Math.round(pvh / pa)
// Figure out if we should have cropped from the top, and if so, compute a new cropped video
// dimension.
if (cw > pvw) {
cw = pvw
ch = Math.round(pvw * pa)
}
// If the video has more pixels than the screen, set the canvas size to the screen pixel
// resolution.
if (cw > pw || ch > ph) {
cw = pw
ch = ph
}
// Switch back to a landscape aspect ratio if required.
if (ww > wh) {
const tmp = cw
cw = ch
ch = tmp
}
// Set the canvas geometry to the new window size.
Object.assign(canvas_.style, canvasStyle_)
canvas_.width = cw
canvas_.height = ch
// on iOS, rotating from portrait to landscape back to portrait can lead to a situation where
// address bar is hidden and the content doesn't fill the screen. Scroll back up to the top in
// this case. In chrome this has no effect. We need to scroll to something that's not our
// scroll position, so scroll to 0 or 1 depending on the current position.
setTimeout(() => window.scrollTo(0, (window.scrollY + 1) % 2), 300)
}
const updateVideoSize = ({videoWidth, videoHeight}) => {
vsize_.w = videoWidth
vsize_.h = videoHeight
}
const onWindowResize = () => {
if (isCompatibleMobile()) {
return
}
fillScreenWithCanvas()
}
const onVideoSizeChange = ({videoWidth, videoHeight}) => {
updateVideoSize({videoWidth, videoHeight})
fillScreenWithCanvas()
}
const onCameraStatusChange = ({status, video}) => {
if (status !== 'hasVideo') {
return
}
updateVideoSize(video)
}
const onCanvasSizeChange = () => {
fillScreenWithCanvas()
}
const onUpdate = () => {
if (canvas_.style.width === canvasStyle_.width &&
canvas_.style.height === canvasStyle_.height) {
return
}
fillScreenWithCanvas()
}
const onAttach = ({canvas, orientation, videoWidth, videoHeight}) => {
canvas_ = canvas
orientation_ = orientation
if (XR8.XrDevice.deviceEstimate().os === 'iOS') {
// Save styles that we modify in unusual ways so we can reset them to their original state.
const computedBodyStyle = getComputedStyle(document.body)
originalBodyStyleSubset_.backgroundColor =
computedBodyStyle.getPropertyValue('background-color')
originalBodyStyleSubset_.overflowY = computedBodyStyle.getPropertyValue('overflow-y')
originalHtmlStyleSubset_.overflow =
getComputedStyle(document.documentElement).getPropertyValue('overflow')
// Set black / white background color on iOS devices depending on dark / light mode.
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
bodyStyle_.backgroundColor = 'black'
} else {
bodyStyle_.backgroundColor = 'white'
}
// Prevent address bar hiding on scroll on iOS (https://stackoverflow.com/a/33953987/4979029).
bodyStyle_.overflowY = 'scroll'
Object.assign(document.documentElement.style, {overflow: 'hidden'})
}
Object.assign(document.body.style, bodyStyle_)
document.body.appendChild(canvas_)
window.addEventListener('resize', onWindowResize)
updateVideoSize({videoWidth, videoHeight})
fillScreenWithCanvas()
}
const onDetach = () => {
// Reset styles that we cached in `onAttach()`.
Object.assign(document.body.style, originalBodyStyleSubset_)
Object.assign(document.documentElement.style, originalHtmlStyleSubset_)
canvas_ = null
orientation_ = 0
delete vsize_.w
delete vsize_.h
window.removeEventListener('resize', onWindowResize)
}
const onDeviceOrientationChange = ({orientation}) => {
orientation_ = orientation
fillScreenWithCanvas()
}
const pipelineModule = () => ({
name: 'fullwindowcanvas',
onAttach,
onDetach,
onCameraStatusChange,
onDeviceOrientationChange,
onVideoSizeChange,
onCanvasSizeChange,
onUpdate,
})
return {
// Creates a camera pipeline module that, when installed, keeps the canvas specified on
// XR8.run() to cover the whole window.
pipelineModule,
}
}
let fullWindowCanvas = null
const FullWindowCanvasFactory = () => {
if (fullWindowCanvas == null) {
fullWindowCanvas = create()
}
return fullWindowCanvas
}
export {
FullWindowCanvasFactory,
}
| 8thwall/web/xrextras/src/fullwindowcanvasmodule/full-window-canvas-module.ts/0 | {
"file_path": "8thwall/web/xrextras/src/fullwindowcanvasmodule/full-window-canvas-module.ts",
"repo_id": "8thwall",
"token_count": 2297
} | 10 |
/* globals XR8 */
// This pauses XR8 when the tab is hidden and calls resumes XR8 once the tab is visible again.
// Useful for when you want your camera feed and MediaRecorder audio to continue even if your
// desktop browser tab isn't focused. It has nearly identical functionality to PauseOnBlur for
// mobile.
// https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event
let pauseOnHidden = null
function create() {
const onVisChange = () => {
if (document.visibilityState === 'visible') {
XR8.resume()
} else {
XR8.pause()
}
}
const pipelineModule = () => ({
name: 'pauseonhidden',
onAttach: () => {
document.addEventListener('visibilitychange', onVisChange)
},
onDetach: () => {
document.removeEventListener('visibilitychange', onVisChange)
},
})
return {
// Creates a camera pipeline module that, when installed, pauses the camera feed and processing
// when the tab is hidden and restarts again when it's visible
pipelineModule,
}
}
const PauseOnHiddenFactory = () => {
if (pauseOnHidden == null) {
pauseOnHidden = create()
}
return pauseOnHidden
}
export {
PauseOnHiddenFactory,
}
| 8thwall/web/xrextras/src/pauseonhiddenmodule/pauseonhidden.js/0 | {
"file_path": "8thwall/web/xrextras/src/pauseonhiddenmodule/pauseonhidden.js",
"repo_id": "8thwall",
"token_count": 396
} | 11 |
import {AFrameFactory} from './aframe/aframe'
import {AlmostThereFactory} from './almosttheremodule/almost-there-module'
import {DebugWebViewsFactory} from './debugwebviews/debug-web-views'
import {FullWindowCanvasFactory} from './fullwindowcanvasmodule/full-window-canvas-module'
import {LoadingFactory} from './loadingmodule/loading-module'
import {LifecycleFactory} from './lifecyclemodule/lifecycle'
import {PauseOnBlurFactory} from './pauseonblurmodule/pauseonblur'
import {PauseOnHiddenFactory} from './pauseonhiddenmodule/pauseonhidden'
import {PlayCanvasFactory} from './playcanvas/playcanvas'
import {PwaInstallerFactory} from './pwainstallermodule/pwa-installer-module'
import {RuntimeErrorFactory} from './runtimeerrormodule/runtime-error-module'
import {StatsFactory} from './statsmodule/stats'
import {ThreeExtrasFactory} from './three/three-extras'
import {MediaRecorder} from './mediarecorder/mediarecorder'
import {SessionReconfigureFactory} from './sessionreconfiguremodule/session-reconfigure-module'
import './common.css'
const XRExtras = {
AFrame: AFrameFactory(),
AlmostThere: AlmostThereFactory(),
DebugWebViews: DebugWebViewsFactory(),
FullWindowCanvas: FullWindowCanvasFactory(),
Lifecycle: LifecycleFactory(),
Loading: LoadingFactory(),
PauseOnBlur: PauseOnBlurFactory(),
PauseOnHidden: PauseOnHiddenFactory(),
PlayCanvas: PlayCanvasFactory(),
PwaInstaller: PwaInstallerFactory(),
RuntimeError: RuntimeErrorFactory(),
Stats: StatsFactory(),
ThreeExtras: ThreeExtrasFactory(),
MediaRecorder,
SessionReconfigure: SessionReconfigureFactory(),
}
const setDeprecatedProperty = (object, property, value, message) => {
let warned = false
Object.defineProperty(object, property, {
get: () => {
if (!warned) {
warned = true
/* eslint-disable no-console */
console.warn('[XR] Deprecation Warning:', message)
console.warn(Error().stack.replace(/^Error.*\n\s*/, '').replace(/\n\s+/g, '\n'))
/* eslint-enable no-console */
}
return value
},
})
}
const setRenameDeprecation = (oldName, newName, value, version) => {
const message = `XRExtras.${oldName} was deprecated in ${version}. Use ${newName} instead.`
setDeprecatedProperty(XRExtras, oldName, value, message)
}
setRenameDeprecation('PauseOnBlur', 'PauseOnHidden', XRExtras.PauseOnBlur, 'R17.0')
export {
XRExtras,
}
| 8thwall/web/xrextras/src/xrextras.js/0 | {
"file_path": "8thwall/web/xrextras/src/xrextras.js",
"repo_id": "8thwall",
"token_count": 809
} | 12 |
## HTML 表单
HTML 表单主要用于收集用户的输入信息。
它包含各种表单元素。
表单元素是允许用户在表单中输入内容的一些标签元素,比如:输入框(input)、文本域(textarea)、下拉列表(select)、单选框(radio-buttons)、复选框(checkbox) 等等。
比如我们经常用到的注册/登录的界面就是一个表单。
一个常见的表单,通常由左侧`提示文本`和右侧`表单元素`组成。

## 1、表单域
表单域,顾名思义,就是包含表单元素的一个区域。我们用 `form` 标签来表示表单域。
语法如下:
```html
<form action="http://xxx.com/1.php" method="get" name="" autocomplete="off"></form>
```
> `action`:处理表单提交的地址URL,表示表单要提交到什么地方进行处理
>
> `method`:表示浏览器使用哪种方式来提交表单
>
> - `get`: 通过地址栏提交表单数据,表单数据会附加在 `action` 属性的 URL 中,并以 `?` 作为分隔符(简单来说,就是可以在地址栏里看到你提交的内容),安全性较差,因为如果输入了账号和密码,那么就可以直接在地址栏看到了。
> - `post`:表单数据会包含在表单体内然后发送给服务器,安全性高。
>
> `name`: 表单的名称。
>
> `autocomplete`:表示是否能够自动补全上次的输入内容。
## 2、表单元素-输入框
输入框使用`input`标签。
`<input>`标签,根据`type`属性的不同,会有不同的表现样式。默认`type="text"`,也就是文本输入框。
### 2.1、文本输入框
单行的文本区域,(输入中的换行会被自动去除)。
```html
<input type="text"
name="username"
maxlength="6"
readonly="readonly"
disabled="disabled"
value="用户名" />
```
> `type`:type="text" 表示文本输入框
>
> `name`:输入框的名字
>
> `maxlength`:文本框能输入的最大字符数。
>
> `minlength`:文本框能输入的最小字符数。
>
> `readonly`:文本框只读
>
> `disabled`:文本框禁用
>
> `value`:输入框中的默认内容
>
> `placeholder`:输入框中的提示语
### 2.2、密码输入框
用于输入密码的元素。
```html
<input type="password" />
```
注意:密码字段字符不会明文显示,而是以星号 `*` 或圆点 `·` 替代。
> PS:文本输入框的所有属性对密码输入框都有效
### 2.3、数字输入框
用于输入数字的元素。
```html
<input type="number" name="num" step="2" />
```
> `step`:默认情况下,向上和向下按钮可以将值增加或减小。通过使用step 属性来更改此步长值。
>
> `min`:最小值
>
> `max`:最大值
> 注意:min和max只是点击上下按钮不会让你低于 min 或高于 max 的值,但是可以通过手动输入数字。
### 2.3、单选框
单选框的type=radio,单选框元素默认渲染为小型圆圈图表,填充即为激活,也就是我们所说的选中效果。
```html
<input type="radio" name="gender" checked="checked" />男
<input type="radio" name="gender" />女
```
> `checked="checked"` 或者直接写 `checked`,可以设置默认选中的项。
> **单选效果**:当有多个单选框是如何设置只能有一个被选中?
> 默认的情况下,单选框是独立存在的,如果要实现单选切换效果,需要`将 name 的值设置相同`,才能实现单选效果。
**设置单选框的样式(add 20181009)**
由于单选框的样式是只能设置大小,不能设置颜色,更不能设置样式。所以,一般我们自定义单选框的样式。
**实现原理:**
在单选框的后面加上label标签(需要设置为inline-block或者block),在点击单选框的时候,使用 + 选择器选中label标签,设置label标签的宽高和颜色代替单选框,将单选框display:none;
代码:
```html
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
input {
display: none;
}
label {
display: inline-block;
width: 30px;
height: 30px;
background-color: #ccc;
border-radius: 50%;
vertical-align: middle;
}
input:checked + label {
background-color: red;
}
</style>
</head>
<body>
<input type="radio" name="sex" id="a"><label for="a" />男
<input type="radio" name="sex" id="b"><label for="b" />女
<input type="radio" name="sex" id="c"><label for="c" />保密
</body>
</html>
```

另外,我们还可以实现**选项卡效果**,代码如下:
```html
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
ul {
position: relative;
}
li {
list-style: none;
float: left;
}
input {
outline: none;
}
input[type="radio"] {
display: none;
}
label {
display: block;
text-align: center;
line-height: 42px;
width: 124px;
height: 42px;
color: rgb(227,64,5);
border-bottom: 1px solid rgb(227,64,5);
cursor: pointer;
}
input:checked + label {
background-color: rgb(227,64,5);
color: #fff;
}
li .dv1,
li .dv2 {
width: 248px;
height: 50px;
/* background-color: #ddd; */
position: absolute;
display: none;
}
.dv1 {
position: relative;
left: 0;
top: 42px;
}
.dv2 {
left: 0;
top: 42px;
}
input:checked + label + div {
display: block;
}
.txt1 {
position: absolute;
width: 200px;
height: 30px;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -15px;
}
.txt1 input[type="text"] {
width: 150px;
height: 30px;
vertical-align: top;
float: left;
box-sizing: border-box;
border: 1px solid rgb(227,64,5);
border-radius: 10px 0 0 10px;
padding-left: 5px;
}
.txt1 input[type="submit"] {
width: 50px;
height: 30px;
float: left;
border: 1px solid rgb(227,64,5);
border-radius: 0 10px 10px 0;
margin-left: -1px;
background-color: rgb(227,64,5);
color: white;
}
.txt2 {
position: absolute;
width: 200px;
height: 30px;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -15px;
}
.txt2 input[type="text"] {
width: 150px;
height: 30px;
vertical-align: top;
float: left;
box-sizing: border-box;
border: 1px solid rgb(227,64,5);
border-radius: 10px 0 0 10px;
padding-left: 5px;
}
.txt2 input[type="submit"] {
width: 50px;
height: 30px;
float: left;
border: 1px solid rgb(227,64,5);
border-radius: 0 10px 10px 0;
margin-left: -1px;
background-color: rgb(227,64,5);
color: white;
}
</style>
</head>
<body>
<div class="box">
<form action="">
<ul class="uu">
<li>
<input type="radio" name="yz" id="a" checked>
<label for="a">客服验证</label>
<div class="dv1">
<div class="txt1">
<input type="text" placeholder="请输入需要验证的QQ号">
<input type="submit" value="验证">
</div>
</div>
</li>
<li>
<input type="radio" name="yz" id="b">
<label for="b">网址验证</label>
<div class="dv2">
<div class="txt2">
<input type="text" placeholder="请输入需要验证的网址">
<input type="submit" value="验证">
</div>
</div>
</li>
</ul>
</form>
</div>
</body>
</html>
```
效果:

### 2.4、多选框
复选框可以选取一个或多个选项:
```html
第一个多选框:<input type="checkbox" checked="checked" value="one" />
第二个多选框:<input type="checkbox" checked />
```
> `value`:复选框选中时的值。如果省略,则默认为"on"。
注意:所有的 `<input>` 元素都有 value 属性;但是,它对 checkbox 类型的输入有特殊作用:当表单被提交时,只有当前被选中的复选框会被提交给服务器,值就是 value 属性的值。如果没有指定 value,默认为字符串 on。
### 2.5、文本上传控件
文本上传控件允许用户可以从他们的设备中选择一个或多个文件。选择后,这些文件可以使用提交表单的方式上传到服务器上。
```html
<input type="file" />
```
> `accept`:表示允许的文件类型(accept="image/*,.pdf" 表示任何图片文件或者pdf文件。
>
> `multiple`:如果出现,则表示用户可以选择多个文件
**20181009 修改文本上传控件的样式:**
实现原理:
**由于上传控件的大小和颜色等是无法直接修改的,若想要修改的话,可以另外添加一个div,将div的大小设置和file控件的大小一致,将div定位,之后file文件也进行定位,覆盖到div之上(可以设置z-index),然后设置file控件的opacity为0即可。**
示例:
```html
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
input {
width: 180px;
height: 60px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
z-index: 1;
opacity: 0;
}
div {
width: 180px;
height: 60px;
background-color: #37f;
color: white;
text-align: center;
line-height: 60px;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<input type="file" />
<div>点击上传</div>
</body>
</html>
```

### 2.6、文件提交按钮
文件提交按钮,可以实现信息提交功能。
当用户单击确认按钮时,表单的内容会被传送到服务器。表单form的属性 action 定义了服务端的文件名。
```html
<form name="input" action="html_form_action.php" method="get">
用户名: <input type="text" name="user">
<input type="submit" value="Submit">
</form>
```
比如在上面的文本框内键入几个字母,然后点击确认按钮,那么输入数据会传送到 `html_form_action.php` 文件。
### 2.7、按钮
用来创建一个没有默认值的可点击按钮。已经在 HTML5 被 `<button>`元素取代。
```html
<input type="button" value="input按钮">
<!--HTML5方式-->
<button>button按钮</button>
```
> 区别:`<button>`在form里面,默认可以进行提交操作,除非设置type=button;而input按钮需要配合JS进行提交。
### 2.8、重置按钮
此按钮点击后,会将表单的所有内容重置为输入前的初始值(一般为空值)。不推荐使用。
```html
<input type="reset">
```
## 3、下拉列表
下拉列表在我们的表单中也非常常用。
使用 `<select>`标签,来创建下拉列表。
使用 `<select>` 元素中的 `<option>` 标签,来表示下拉列表中的每一个选项。
示例:
```html
<select name="下拉框">
<option value="1">选项1</option>
<option value="2" selected>选项2</option>
<option value="3">选项3</option>
</select>
<select multiple>
<optgroup label="爱好">
<option value="1">听音乐</option>
<option value="2" disabled>看电影</option>
</optgroup>
<optgroup label="游戏">
<option value="3">王者荣耀</option>
<option value="4">LOL</option>
</optgroup>
</select>
```
常见属性:
> `name`:下拉列表名称
>
> `multiple`: 表示下拉列表可以多选
>
> `selected`:设置默认选中的选项
>
> `disabled`:1、用在select上禁用整个下拉列表;2、如果用在选项上,表示禁用该选项。
>
> `value`: 选中的下拉框的值
>
> `<optgroup></optgroup>` 对下拉列表进行分组。
>
> `label`:分组名称。
## 4、文本域
使用 `<textarea>` 标签定义一个多行的文本输入元素。
文本域一般使用在,当你希望用户输入一段相当长的文本的时候,比如评论,备注等。
示例:
```html
<textarea cols="130" rows="10" placeholder="请输入"></textarea>
```
文本域大部分属性和input相同(比如placeholder,maxlength,minlength等)。
但是有一些独有的属性:
> `cols`:设置文本域宽度(字符的列数)
>
> `rows`:设置文本域的高度(字符的行数)
注意:
- cols和rows一般不用,直接使用css中的`width`和`height`来设置宽高。
- 在css中设置 `resize:none; `不可改变大小。
```css
textarea {
width: 100px;
height: 100px;
resize: none;
}
```
## 5、表单信息分组
一个表单里面,可能会有很多表单元素,我们可以通过 `fieldset` 标签,对其中过的表单元素进行分组。`legend` 标签会显示分组区域的名称。
```html
<form action="http://xxx.com/1.php" method="post">
<fieldset>
<legend>分组1</legend>
<input />
</fieldset>
<fieldset disabled>
<legend>分组2</legend>
<input />
</fieldset>
</form>
```
> `disabled`:fieldset中所有元素都会禁用
## 6、html5补充表单控件
html5可以理解为html的第5个版本,在 2014 年发布,目前html5是现在最新最稳定的版本。
```html
<!--类似 text 输入,但在提交时会有验证-->
<input type="url">网址控件
<!--输入日期的控件(年、月、日,不包括时间)。在支持的浏览器激活时打开日期选择器或年月日的数字滚轮。-->
<input type="date">日期控件
<!--用于输入时间的控件,不包括时区。-->
<input type="time">时间控件
<!--编辑邮箱地址的区域。类似 text 输入,但在支持的浏览器和带有动态键盘的设备上会有确认参数和相应的键盘。-->
<input type="email">邮件控件
<!--用于指定颜色的控件;在支持的浏览器中,激活时会打开取色器。-->
<input type="color">颜色控件
<!--此控件用于输入不需要精确的数字。控件是一个范围组件,默认值为正中间的值。同时使用 min 和 max 来规定值的范围。-->
<input type="range" step="1">滑块控件
```
> 可以通过该链接,查看所有不同type的input标签:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/Input
## 补充完整示例
```html
<!-- 表单域 -->
<form action="1.php" method="post">
<!-- 对表单信息分组 -->
<fieldset>
<!-- 表单信息分组名称 -->
<legend>分组信息</legend>
<!-- 文本输入框 -->
账户: <input type="text" name="User" value="账号/邮箱/手机号">
<br>
<!-- 密码输出框 -->
密码: <input type="password" name="Pwd">
<br>
<!-- 文件提交按钮 -->
<input type="submit">
<br>
<!-- 单选框 -->
<input type="radio" name="gender">男
<input type="radio" name="gender" checked="checked">女
<br>
<br>
<!-- 下拉列表 -->
省(市) <select>
<!-- 下拉列表选项 -->
<option value="">北京</option>
<option value="">山东</option>
<option value="">广东</option>
<option value="">福建</option>
<option value="">河南</option>
<option value="" selected="selected">湖北</option>
</select>
<select>
<!-- 对下拉列表分组 -->
<optgroup label="湖北省">
<option value="">武汉</option>
<option value="" selected="selected">襄阳</option>
<option value="">天门</option>
<option value="">荆州</option>
<option value="">仙桃</option>
</optgroup>
</select>
<br><br>
<!-- 多选框 -->
<input type="checkbox"> A
<input type="checkbox" checked="checked"> B
<input type="checkbox"> C
<br><br>
<!-- 多行文本框 -->
<textarea cols="30" rows="10"></textarea><br><br>
<!-- 文本上传控件 -->
<input type="file"><br><br>
<input type="submit">
<!-- 普通按钮 -->
<input type="button" value="Button">
<!-- 重置按钮 -->
<input type="reset"><br><br>
<!-- 图片按钮 -->
<input type="image" src="1.png" width="100"><br><br>
<!-- 网址控件 -->
<input type="url" value="http://www.baidu.com"><br><br>
<!-- 日期控件 -->
<input type="date">
<!-- 颜色控件 -->
<input type="color">
</fieldset>
</form>
```

| Daotin/Web/01-HTML/01-HTML基础/04-表单.md/0 | {
"file_path": "Daotin/Web/01-HTML/01-HTML基础/04-表单.md",
"repo_id": "Daotin",
"token_count": 10841
} | 13 |
## 一、动画
### 1、创建动画
好的前端工程师,会更注重用户的体验和交互。那么动画就是将我们的静态页面,变成具有灵动性,为我们的界面添加个性的一种方式。
一个动画至少需要两个属性:
`animation-name` :动画的名字(创建动画时起的名字,如下为 moveTest)
`animation-duration` :动画的耗时
```css
animation-name: moveTest;
animation-duration: 2s;
```
如需在 CSS3 中创建动画,需要学习 `@keyframes` 规则。`@keyframes` 规则用于创建动画。在 `@keyframes` 中规定某项 CSS 样式,就能创建由当前样式逐渐改为新样式的动画效果。
使用 `@keyframes `关键字来创建动画。
```css
@keyframes moveTest {
/*百分比是指整个动画耗时的百分比*/
0% {
transform: translate(0px, 0px);
}
50% {
transform: translateY(200px);
}
100% {
transform: translate(200px,200px);
}
}
```
> 其中,百分比是指整个动画耗时的百分比。
**示例:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div {
width: 100px;
height: 100px;
background-color: blue;
animation-name: moveTest;
animation-duration: 2s;
}
@keyframes moveTest {
0% {
transform: translate(0px, 0px);
}
50% {
transform: translateY(200px);
}
100% {
transform: translate(200px,200px);
}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
```
> `0%`:动画起始位置,也可以写成 from
>
> `100%`:动画终点位置,也可以写成 to。

### 2、动画的其他属性
`animation-iteration-count`:设置动画的播放次数,默认为1次
`animation-direction`:设置交替动画
`animation-delay`:设置动画的延迟
`animation-fill-mode`:设置动画结束时的状态:默认情况下,动画执行完毕之后,会回到原始状态
`animation-timing-function`:动画的时间函数(动画的效果,平滑?先快后慢等)
`animation-play-state`:设置动画的播放状态 paused:暂停 running:播放
```css
/*3.设置动画的播放次数,默认为1次 可以指定具体的数值,也可以指定infinite(无限次)*/
animation-iteration-count: 1;
/*4.设置交替动画 alternate:来回交替*/
animation-direction: alternate;
/*5.设置动画的延迟*/
animation-delay: 2s;
/*5.设置动画结束时的状态:默认情况下,动画执行完毕之后,会回到原始状态
forwards:会保留动画结束时的状态,在有延迟的情况下,并不会立刻进行到动画的初始状态
backwards:不会保留动画结束时的状态,在添加了动画延迟的前提下,如果动画有初始状态,那么会立刻进行到初始状态
both:会保留动画的结束时状态,在有延迟的情况下也会立刻进入到动画的初始状态*/
animation-fill-mode: both;
/*6.动画的时间函数:linear,ease...*/
animation-timing-function: linear;
/*设置动画的播放状态 paused:暂停 running:播放*/
animation-play-state: running;
```
### 3、案例:无缝滚动
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 600px;
height: 100px;
margin: 100px auto;
background-color: #ccc;
overflow: hidden;
}
ul {
width: 200%;
animation: moveLeft 6s linear 0s infinite;
}
ul > li {
float: left;
list-style: none;
}
li > img {
width: 200px;
height: 100px;
}
div:hover > ul {
cursor: pointer;
animation-play-state: paused;
}
@keyframes moveLeft {
from {
transform: translateX(0);
}
to {
transform: translateX(-600px);
}
}
</style>
</head>
<body>
<div>
<ul>
<li><img src="images/img1.jpg" alt=""></li>
<li><img src="images/img2.jpg" alt=""></li>
<li><img src="images/img3.jpg" alt=""></li>
<!-- 复制的一份图片 -->
<li><img src="images/img1.jpg" alt=""></li>
<li><img src="images/img2.jpg" alt=""></li>
<li><img src="images/img3.jpg" alt=""></li>
</ul>
</div>
</body>
</html>
```
> 1、将要显示的图片复制一份,以完成无缝滚动的需求。
>
> 2、然后让 ul 移动整个ul的宽度即可,并且无限循环,就实现无线轮播的效果。
>
> 3、然后在鼠标放上去的时候,使得动画暂停。

### 4、案例:时钟
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.clock {
width: 300px;
height: 300px;
margin: 100px auto;
border: 10px solid #ccc;
border-radius: 50%;
position: relative;
}
.line {
width: 8px;
height: 300px;
background-color: #ccc;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.line2 {
transform: translate(-50%, -50%) rotate(30deg);
}
.line3 {
transform: translate(-50%, -50%) rotate(60deg);
}
.line4 {
width: 10px;
transform: translate(-50%, -50%) rotate(90deg);
}
.line5 {
transform: translate(-50%, -50%) rotate(120deg);
}
.line6 {
transform: translate(-50%, -50%) rotate(150deg);
}
.cover {
width: 250px;
height: 250px;
background-color: #fff;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.center {
width: 20px;
height: 20px;
background-color: #ccc;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.hour {
width: 12px;
height: 80px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -100%);
transform-origin: center bottom;
animation: clockMove 43200s linear infinite;
}
.minute {
width: 8px;
height: 100px;
background-color: blue;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -100%);
transform-origin: center bottom;
animation: clockMove 3600s linear infinite;
}
.second {
width: 4px;
height: 120px;
background-color: green;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -100%);
transform-origin: center bottom;
animation: clockMove 60s infinite steps(60);
}
@keyframes clockMove {
from {
transform: translate(-50%, -100%) rotate(0deg);
}
to {
transform: translate(-50%, -100%) rotate(360deg);
}
}
</style>
</head>
<body>
<div class="clock">
<div class="line line1"></div>
<div class="line line2"></div>
<div class="line line3"></div>
<div class="line line4"></div>
<div class="line line5"></div>
<div class="line line6"></div>
<div class="cover"></div>
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>
<div class="center"></div>
</div>
</body>
</html>
```
> 我们让秒针step(60)一步一步走,效果更好。

---
## 二、Web字体与图标
### 1、web字体
我们有些时候需要在网页上显示一些特殊的字体,如果这些特殊的字体在电脑上没有安装的话,就会显示系统默认的字体,而不是这些特殊的字体。
这时就有了 Web 字体。开发人员可以为自已的网页指定特殊的字体,无需考虑用户电脑上是否安装了此特殊字体,从此把特殊字体处理成图片的时代便成为了过去。它的支持程度比较好,甚至 IE 低版本浏览器也能支持。
### 2、字体格式
不同浏览器所支持的字体格式是不一样的,我们有必要了解一下有关字体格式的知识。
- `TureTpe(.ttf) `格式
.ttf字体是Windows和Mac的最常见的字体,是一种RAW格式,支持这种字体的浏览器有IE9+、Firefox3.5+、Chrome4+、Safari3+、Opera10+、iOS Mobile、Safari4.2+;
- `OpenType(.otf)`格式
.otf字体被认为是一种原始的字体格式,其内置在TureType的基础上,支持这种字体的浏览器有Firefox3.5+、Chrome4.0+、Safari3.1+、Opera10.0+、iOS Mobile、Safari4.2+;
- `Web Open Font Format(.woff)`格式
woff字体是Web字体中最佳格式,他是一个开放的TrueType/OpenType的压缩版本,同时也支持元数据包的分离,支持这种字体的浏览器有IE9+、Firefox3.5+、Chrome6+、Safari3.6+、Opera11.1+;
- `Embedded Open Type(.eot)`格式
.eot字体是IE专用字体,可以从TrueType创建此格式字体,支持这种字体的浏览器有IE4+;
- `SVG(.svg)`格式
.svg字体是基于SVG字体渲染的一种格式,支持这种字体的浏览器有Chrome4+、Safari3.1+、Opera10.0+、iOS Mobile Safari3.2+
### 3、使用步骤
需要注意的是,我们在使用 Web 字体的时候,应该首先把需要用到特殊字体的这些字写好,然后在网络上生成这些字体对应的 Web 字体库,并将其下载下来。下图为一个网站生成和下载web字体的网站,点击立即使用就可以了:

下载下来之后,把下在下来的所有文件导入自己的项目,注意路径的匹配问题。
之后在我们css样式里面使用` @font-face`关键字来自定义 Web 字体。
```css
@font-face {
font-family: 'shuangyuan';
src: url('../fonts/webfont.eot'); /* IE9*/
src: url('../fonts/webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/webfont.woff') format('woff'), /* chrome、firefox */
url('../fonts/webfont.ttf') format('truetype'), /* chrome、firefox、opera、Safari, Android, iOS 4.2+*/
url('../fonts/webfont.svg#webfont') format('svg'); /* iOS 4.1- */
}
```
最后在使用的时候:`font-family: "shuangyuan";` 就可以使用 shuangyuan 这种字体了。
### 4、字体图标
字体图标就是我们常见的字体,不过这个字体的表现形式为一个图标。这样我们就可以使用这些特殊的字体来代替精灵图了。
常见的是把网页常用的一些小的图标,借助工具帮我们生成一个字体包,然后就可以像使用文字一样使用图标了。
**优点:**
- 将所有图标打包成字体库,减少请求;
- 具有矢量性,可保证清晰度;
- 使用灵活,便于维护
#### 4.1、方法一
使用方法和Web字体一样。也是先下载需要的图标字体库文件,然后使用关键字 `@font-face` 生成自己的web图标字体。
示例:
```css
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
@font-face {
font-family: 'iconfont';
src: url('../fonts/iconfont.eot'); /* IE9*/
src: url('../fonts/iconfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/iconfont.woff') format('woff'), /* chrome、firefox */
url('../fonts/iconfont.ttf') format('truetype'), /* chrome、firefox、opera、Safari, Android, iOS 4.2+*/
url('../fonts/iconfont.svg#iconfont') format('svg'); /* iOS 4.1- */
}
.myFont{
font-family: iconfont;
}
/*笑脸*/
.smile::before{
content: "\e641";
color: red;
font-size: 50px;
}
/*输出*/
.output::before{
content: "\e640";
color: blue;
font-size: 50px;
}
</style>
</head>
<body>
<!--使用字体图标的时候,得自己指定你想使用的图片-->
<span class="myFont smile"></span>
<span class="myFont output"></span>
<span class="myFont"></span>
</body>
</html>
```
#### 4.2、方法二
直接在线调用网上web图标 css库
```css
<link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css">
```
使用的时候:和方法一一样,直接使用类属性 `class='fa fa-play` 的方式,fa-play是一个播放的图标,不同的图标的名字含义不同,只需要到 font-awesome 官网(http://www.fontawesome.com.cn/)找到对应的图标的名称即可。
示例:
```html
<a href="javascript:void(0);" class="fa fa-play"></a> <!--播放图标-->
<a href="javascript:void(0);" class="fa fa-arrows-alt"></a> <!--全屏图标-->
```
> 注意:class 样式的 第一个 fa 是必写的,表示的是用的 font-awesome 的字体图标。
| Daotin/Web/02-CSS/02-CSS3/06-animation动画,Web字体.md/0 | {
"file_path": "Daotin/Web/02-CSS/02-CSS3/06-animation动画,Web字体.md",
"repo_id": "Daotin",
"token_count": 8290
} | 14 |
## 1、对象创建方式
### 1.1、调用系统函数创建对象
**(创建对象的最简单方式就是创建一个 Object 的实例,然后再为它添加属性和方法。)**
```javascript
var obj = new Object();
obj.name = "Daotin";
obj.age = 18;
obj.eat = function () {
console.log("我很能吃");
);
```
缺点:使用同一个接口创建很多对象,会产生大量的重复代码。
### 1.2、自定义构造函数创建对象
**工厂模式创建对象**:考虑到在 ECMAScript 中无法创建类,开发人员就发明了一种函数,用函数来封装以特定接口创建对象的细节(把创建一个函数的过程封装在一个函数里面),**缺点:创建的对象属性都是一样的。**
```javascript
function creatObject() {
var obj = new Object();
obj.name = "Daotin";
obj.age = 18;
obj.eat = function () {
console.log("我很能吃");
};
return obj;
}
var person = creatObject();
person.eat();
```
**工厂模式创建对象进阶版:**可以修改属性
```javascript
function creatObject(name, age) {
var obj = new Object();
obj.name = name;
obj.age = age;
obj.eat = function () {
console.log("我很能吃");
};
return obj;
}java
var person = creatObject("Daotin", 18);
person.eat();
```
**自定义构造函数:**(函数和构造函数的区别:没有区别,但是通常构造函数**首字母大写**)
**特点:**
- 没有显式地创建对象;
- 直接将属性和方法赋给了 this 对象;
- 没有 return 语句。
```javascript
function CreatObject() { // 首字母大写
this.name = "Daotin";
this.age = 18;
this.eat = function () {
console.log("我很能吃");
};
}
var person = new CreatObject();
person.eat();
```
**进阶(传参数):**
```javascript
function CreatObject(name, age) {
this.name = name;
this.age = age;
this.eat = function () {
console.log("我很能吃");
};
}
var person = new CreatObject();
person.eat();
```
**构造函数的问题**
构造函数模式虽然好用,但也并非没有缺点。使用构造函数的主要问题,就是每个方法都要在每个实例上重新创建一遍。在前面的例子中, person1 和 person2 都有一个名为 sayName()的方法,但那两个方法不是同一个 Function 的实例。不要忘了——ECMAScript 中的函数是对象,因此每定义一个函数,也就是实例化了一个对象。从逻辑角度讲,此时的构造函数也可以这样义。
```javascript
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = new Function("alert(this.name)"); // 与声明函数在逻辑上是等价的
}
```
从这个角度上来看构造函数,更容易明白每个 Person 实例都包含一个不同的 Function 实例(以显示 name 属性)的本质。说明白些,以这种方式创建函数,会导致不同的作用域链和标识符解析,但创建 Function 新实例的机制仍然是相同的。因此,不同实例上的同名函数是不相等的,以下代码可以证明这一点:` alert(person1.sayName == person2.sayName); //false `
然而,创建两个完成同样任务的 Function 实例的确没有必要;况且有 this 对象在,根本不用在执行代码前就把函数绑定到特定对象上面。因此,大可像下面这样,通过**把函数定义转移到构造函数外部来解决这个问题。**
```javascript
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = sayName;
}
function sayName(){
alert(this.name);
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
```
在这个例子中,我们把 sayName() 函数的定义转移到了构造函数外部。而在构造函数内部,我们将 sayName 属性设置成等于全局的 sayName 函数。这样一来,由于 sayName 包含的是一个指向函数的指针,因此 person1 和 person2 对象就共享了在全局作用域中定义的同一个 sayName() 函数。
### 1.3、使用对象字面量表示法
对象字面量是对象定义的一种简写形式,目的在于简化创建包含大量属性的对象的过程。
如果留空其花括号,则可以定义只包含默认属性和方法的对象 `var person = {}; //与 new Object()相同 `
**缺点:一次性对象,无法修改属性的值。**
```javascript
var obj = {
name:"Daotin", // 注意是属性赋值是冒号
age: 18,
eat: function () {
console.log("我很能吃");
} // 最后一个后面没有逗号
};
obj.eat();
```
### 1.4、使用create方式创建对象
```js
var obj = Object.create({a:1}); //根据对象{a:1}来创建对象obj
```
> 使用create创建就是通过其他的对象做为该对象的原型加入在对象中。
>
> 我们在获取 obj 的属性的时候,如果 obj 对象没有对象属性,但是有对象的原型属性(创建的时候遗传下来的属性),那么获取的就是原型属性;如果 obj 对象有自己的对象属性,那么就获取自己的对象属性。
>
> 但是在设置 obj 属性值时,只能设置自己的对象属性,不能修改遗传下来的原型属性。
示例:
```js
var obj1 = {
a: 1
};
var obj2 = Object.create(obj1);
console.log(obj2.a); // 1
obj2.a = 10;
console.log(obj2.a); // 10
console.log(obj2); //{a: 10}a: 10 __proto__: a: 1 __proto__: Object
```
可以看出 obj2.a = 10; 修改的是自己的属性,而遗传的 obj1.a 还是1.
## 2、访问对象属性
**点表示法 和 方括号表示法**
```javascript
alert(person["name"]); //"Nicholas"
alert(person.name); //"Nicholas"
```
从功能上看,这两种访问对象属性的方法没有任何区别。但方括号语法的主要优点是可以通过变量来访问属性(属性绑定),例如:
```javascript
var propertyName = "name";
alert(person[propertyName]); //"Nicholas"
```
**如果属性名中包含会导致语法错误的字符,或者属性名使用的是关键字或保留字,也可以使用方括号表示法。**
例如:` person["first name"] = "Nicholas"; `
由于"first name"中包含一个空格,所以不能使用点表示法来访问它。然而,属性名中是可以包含非字母非数字的,这时候就可以使用方括号表示法来访问它们。通常,除非必须使用变量来访问属性,否则我们建议使用点表示法。
**PS: 如果访问一个没有的属性的值,那么这个值为 undefined,而不是报错?**
因为 js 是一门动态类型的语言,不管使用点表示法还是方括号表示法,如果没有这个属性,就相当于在创建这个属性,然而这个时候没有赋值,所以就是 undefined。
## 3、访问对象方法
```javascript
对象名.函数名();
```
## 4、对象的静态方法
对象的动态属性和方法,必须是实例化的对象才可以执行。
对象的静态方法,可以直接使用 `Object.方法名` 的形式来执行。
### 4.1、delete
删除对象的属性(包括值属性和方法属性)
```js
var obj1 = {
a: 1,
b: function () {
alert("b");
}
};
delete obj1.b;
console.log(obj1); // {a:1}
```
> 注意:delete 不能删除window下的属性和方法。
>
> var s=10;
> delete window.s;
> console.log(s);
不建议使用delete删除数组的元素,因为这样数组就变成松散结构(个数不变,中间有空缺)。
```js
var array = [1, 2, 3, 4];
delete array[1];
console.log(array); // [1, empty, 3, 4]
```
### 4.2、assign
语法:`Object.assign(目标对象,源对象);`返回值也是目标对象。
描述:assign方法用于将所有可枚举的属性的值(包括方法)从一个或多个源对象复制到目标对象。它将返回目标对象。如果目标对象中的属性具有相同的键,则属性将被源中的属性覆盖。后来的源的属性将类似地覆盖早先的属性。
```js
var obj1 = {
a: 1,
b: 2
}
var obj2 = {};
Object.assign(obj2, obj1);
console.log(obj2); // {a: 1, b: 2}
```
> 如果复制多个对象的属性时,后面的对象属性如果和前面相同就会覆盖前面的.
>
> 原型属性不能复制,不可遍历属性,不可写属性,冻结属性都不能复制
```js
var obj1 = {
a: 1,
b: 2
}
var obj2 = {
c: 3,
b: 4
}
var obj = {};
Object.assign(obj, obj1, obj2);
console.log(obj); // {a: 1, b: 4, c: 3}
```
> 注意:assign 是浅拷贝,拷贝的仍然是引用关系。
```js
var obj1 = {
a: 1,
b: 2
}
var obj2 = {
c: 3,
b: {
d: 10
}
}
var obj = {};
Object.assign(obj, obj1, obj2);
console.log(obj); // {a: 1, b: {d : 20}, c: 3}
obj2.b.d = 20;
console.log(obj); // {a: 1, b: {d : 20}, c: 3}
```
#### -那么如何做到深拷贝呢?
方式一:使用JSON.parse和JSON.stringify来转换
```js
var obj2 = {
c: 3,
b: {
d: 10
}
}
var obj = {};
obj = JSON.parse(JSON.stringify(obj2));
console.log(obj);
obj2.b.d = 20;
console.log(obj); //{c: 3, b: {d:10}}
console.log(obj2); //{c: 3, b: {d:20}}
```
这种方法只适用于纯数据json对象的深度克隆,因为有些时候,这种方法也有缺陷,因为其会自动忽略值为 function 和 undefined 的属性。
方式二:使用 `for in` 递归拷贝
```js
function deepCopy(obj) {
var result = Array.isArray(obj) ? [] : {}; // obj 是数组还是对象
for (var key in obj) {
// obj.hasOwnProperty(prop) 方法会返回一个布尔值,指示对象obj自身属性中是否具有prop属性。
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object') {
result[key] = deepCopy(obj[key]); //递归复制
} else {
result[key] = obj[key];
}
}
}
return result;
}
var obj2 = {
c: 3,
b: {
d: 10,
e: {
f: 20,
g: {
h: 30
}
}
}
}
var obj = deepCopy(obj2);
console.log(obj); // h:30
obj2.b.e.g.h = 100;
console.log(obj);// h:30
```
#### -assign在DOM中的使用
我们之前在设置新创建的元素的时候,总是每个属性单独写一行,这样如果有几百条属性的话,就很麻烦,而且由于比较零散,不便于管理。
而现在我们就可以使用对象的assign来设置操作DOM元素的属性。
```js
var div1 = document.createElement("div");
var div2 = document.createElement("div");
var style = {
width: "100px",
height: "100px",
backgroundColor: "pink"
}
style.border = "1px solid blue";
Object.assign(div1.style, style);
style.border = "2px solid red";
Object.assign(div2.style, style);
document.body.appendChild(div1);
document.body.appendChild(div2);
```
上面的这种方式就可以很方便的把众多的属性,一次性的全部加到新创建的元素中,特别好使。
### 4.3、defineProperty
描述: `Object.defineProperty()` 方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性, 并返回这个对象。
语法:`Object.defineProperty(obj, prop, descriptor)`
参数:
obj: 要在其上定义属性的对象。
prop: 要定义或修改的属性的名称。
descriptor: 属性描述符,是一个对象,这个对象里面有四个属性和两个方法来修饰 obj 新定义的属性。
```json
{
value: 1, // 属性对应的值
enumerable: true, // 是否可遍历,默认 false
configurable: true, // 是否可删除,默认 false
writable: true, // 是否可修改
set: function(value) {
this._data = value;
},
get: function() {
return this._data;
}
}
```
示例1:
```js
var obj = {
a: 1,
b: 2
};
Object.defineProperty(obj, "c", {
value: 3,
enumerable: true, // 是否可遍历,默认 false
configurable: true, // 是否可删除,默认 false
writable: true // 是否可修改
});
for (var i in obj) {
console.log(i); // a,b,c
}
```
> 如果 enumerable: false 的话,不会显示 c。
>
> 如果 configurable: false 的话,delete 无法删除 obj 的 c 属性。
>
> 如果 writable: false 的话,obj 的 c 属性无法修改其值。
示例2:
```js
var obj = {
_data: 3,
a: 1,
b: 2
};
Object.defineProperty(obj, "c", {
// value: 3,
enumerable: true, // 是否可遍历,默认 false
configurable: true, // 是否可删除,默认 false
// writable: true, // 是否可修改
set: function (value) {
this._data = value;
},
get: function () {
return this._data;
}
});
obj.c = 10;
console.log(obj.c);
```
> 当我们执行 obj.c = 10; 的时候相当于使用set函数将 10 给了临时变量(一般临时变量用_开头),然后我们在获取的时候,是通过get函数来获取的。
但是这个时候我们不能写value和writable属性。会报错:*`Invalid property descriptor. Cannot both specify accessors and a value or writable attribute.`*
**SOLUTION:**
the error means `It doesn't make sense to say if a property is writable when you explicitly state what happens when you try to write it.`
So ,we should remove `writable: true`, we also should remove `value:3` , because `the value is calculated dynamically when you read it.`
So ,your `value ` should be replaced by `_data`.
### 4.4、defineProperties
语法:`Object.defineProperties(obj, props)`
描述:defineProperties 方法直接在一个对象上定义新的属性或修改现有属性,并返回该对象。
props 是一个对象,这个对象包含了你需要定义或修改的属性名和属性值。
属性名:必须为字符串。
属性描述符:又是一个对象,就是上面的descriptor对象:
示例:
```js
var obj = {};
Object.defineProperties(obj, {
'name': {
value: "daotin",
writable: true,
enumerable: true,
configurable: false
},
'age': {
value: 18,
writable: false,
enumerable: true,
configurable: false
}
});
console.log(obj); // {"name":"daotin", "age":18}
obj.age = 20;
console.log(obj); // {"name":"daotin", "age":18} writable为false,无法修改。
```
### 4.5、getOwnPropertyNames
描述:getOwnPropertyNames方法返回一个由指定对象的所有自身属性的属性名(包括不可枚举属性但不包括Symbol值作为名称的属性)组成的数组集合。
语法:`Object.getOwnPropertyNames(obj)`
示例:
```js
var obj = {
a: 1,
b: 2,
c: function () {
},
d: 3
}
var list = Object.getOwnPropertyNames(obj);
list.map(function (item) {
console.log(item); // a,b,c,d
});
```
### 4.6、getOwnPropertyDescriptor
描述:Object.getOwnPropertyDescriptor() 方法返回指定对象上一个自有属性对应的属性描述符。(自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性)
语法:`Object.getOwnPropertyDescriptor(obj, prop)`
示例:
```js
var obj = {
a: 1,
b: 2,
c: function () {},
d: 3
}
Object.defineProperty(obj, "e", {
value: "daotin",
writable: true,
enumerable: true,
configurable: false
});
var desc = Object.getOwnPropertyDescriptor(obj, "e");
console.log(desc); //{value: "daotin", writable: true, enumerable: true, configurable: false}
```
### 4.7、getOwnPropertyDescriptors
描述:getOwnPropertyDescriptors 获取一个对象的所有自身属性的描述符,返回值为所有属性对象的对象集合。
语法:`Object.getOwnPropertyDescriptors(obj)`
示例:
```js
var obj = {
a: 1,
b: 2,
c: function () {
},
d: 3
}
Object.defineProperties(obj, {
"e": {
value: "daotin",
writable: true,
enumerable: true,
configurable: false
},
"f": {
value: "lvonve",
writable: false,
enumerable: true,
configurable: true
}
});
var desc = Object.getOwnPropertyDescriptors(obj);
console.log(desc.e); // {value: "daotin", writable: true, enumerable: true, configurable: false}
console.log(desc.f); // {value: "lvonve", writable: false, enumerable: true, configurable: true}
```
## 5、setter和getter
setter和getter的作用:使你可以快速获取或设置一个对象的数据。
我们之前定义一个对象的set和get是下面这样的:
```js
var obj = {
_data: 0
};
Object.defineProperty(obj, "a", {
set: function (value) {
this._data = value;
},
get: function () {
return this._data;
}
});
```
现在我们可以使用字面量对象的方式添加set和get:
```js
var obj = {
_data: 0,
a: 1,
b: 2,
set data(value) {
this._data = value;
console.log("set");
},
get data() {
console.log("get");
return this._data;
}
};
obj.data = 10; // set
console.log(obj.data); // get 10
obj.num = 20;
console.log(obj.num); // 20
```
可以看到set和get后面的名称(如data)和我们在设置和获取的时候的名称(如data)一致的时候才会调用。
也就是,你要`设置获取的属性名` == `set和get后面的属性名`。
> 并且如果你不写set,那么你就设置这个对象的属性为不可修改;
>
> 并且如果你不写get,那么你就设置这个对象的属性为不可读取;
删除getter或setter的唯一方法是:`delete object[name]`。delete可以删除一些常见的属性,getters和setters。
```js
delete obj["data"]; // 这样就把set和get属性全部删除了
```
## 4、JSON
**什么是JSON?**
JSON 的全称为:**JavaScript Object Notation**(JavaScript对象表示形式:就是对象字面量)
JSON格式的数据:一般都是成对的,键值对。
**JSON和对象字面量的区别?**
json 和对象(对象字面量)的区别仅仅在于,json 格式的数据中的键必须用双引号括起来;
```javascript
var json = {
"name" : "zs",
"age" : 18,
"sex" : true,
"sayHi" : function() {
console.log(this.name);
}
};
```
##5、字面量的遍历
**对象本身没有 length,所以不能用 for 循环遍历。要使用 for...in...**
```javascript
var json = {“aaa”: 1, “bbb”: 2, “ccc”: 3, “ddd”: 4}
for(var key in json){
//key代表aaa,bbb.....等
//json[key]代表1,2,3....等(k 不要加引号)
}
```
##6、值传递和引用类型传递
**分析值传递和址传递最好的方法就是画图分析,最简单。**
##7、内置对象
`Math, Date, String, Array `
学习的时候可以查阅在线文档:
[MDN 在线文档](https://developer.mozilla.org/zh-CN/)
[菜鸟教程](http://www.runoob.com/)
##8、基本包装类型
本身是基本类型,但是在执行的过程中,如果这种类型的变量调用了属性或者方法,那么这种类型就不是基本类型了,而是基本包装类型。这个变量也不是普通变量了,而是基本包装类型的变量。
```javascript
var str = "hello";
str = str.replace("he", "wo");
console.log(str); // wollo
```
**需要注意的地方:**
如果一个`对象&&true`,那么结果是true
如果一个`true&&对象`,那么结果是对象。
```javascript
var flag = new Boolean(false);
var result = flag && true;
var result1 = true && flag;
console.log(result); // true
console.log(result1); // Boolean
```
```javascript
var num = 10; // 基本类型
var num2 = Number("10"); // 不是基本包装类型,而是转换,这里换成 Boolean 也成立
var num3 = new Number("10"); // 这才是基本包装类型
```
| Daotin/Web/03-JavaScript/01-JavaScript基础知识/08-对象.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/01-JavaScript基础知识/08-对象.md",
"repo_id": "Daotin",
"token_count": 11594
} | 15 |
## 一、client 系列
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#dv {
width: 300px;
height: 200px;
border: 20px solid purple;
margin-top: 50px;
margin-left: 100px;
}
#dv2 {
width: 100px;
height: 50px;
border: 15px solid #e88e1d;
margin-top: 20px;
margin-left: 30px;
}
</style>
</head>
<body>
<div id="dv">
<div id="dv2"></div>
</div>
<script src="common.js"></script>
<script>
console.log(my$("dv").clientWidth); // 300
console.log(my$("dv").clientHeight); // 200
console.log(my$("dv").clientLeft); // 20
console.log(my$("dv").clientTop); // 20
console.log(my$("dv2").clientWidth); // 100
console.log(my$("dv2").clientHeight); // 50
console.log(my$("dv2").clientLeft); // 15
console.log(my$("dv2").clientTop); // 15
</script>
</body>
</html>
```
> **clientWidth**:可视区域的宽度**(不含边框)**
>
> **clientHeight**:可视区域的高度**(不含边框)**
>
> **clientLeft**:左边框的宽度
>
> **clientTop**: 上边框的宽度
>
> **clientX**:可视区域的横坐标
>
> **clientY**:可视区域的纵坐标
**页面可视区域的大小:**
```js
document.documentElement.clientWidth || document.body.clientWidth
document.documentElement.clientHeight || document.body.clientHeight
```
**页面实际宽高:**
```js
document.documentElement.scrollWidth || document.body.scrollWidth
document.documentElement.scrollHeight || document.body.scrollHeight
```
### 1、案例:图片跟着鼠标移动
之前图片跟着鼠标移动的案例有些bug,就是IE8不支持。
在IE8 下 没有事件参数,但是有 window.event 可以代替。
window.event: 谷歌, IE8 支持,但是火狐不支持。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
img {
position: absolute;
}
</style>
</head>
<body>
<img src="images/Daotin.png" id="im">
<script src="common.js"></script>
<script>
document.onmousemove = function (e) {
// 获取鼠标的横纵坐标
e = window.event || e;
my$("im").style.left = e.clientX + "px";
my$("im").style.top = e.clientY + "px";
console.log(window.event);
}
</script>
</body>
</html>
```
这个时候,如果 body 的高度/宽度变化了,可以滚动滑轮了会怎样呢?
```javascript
body {
height: 5000px;
}
```
这时候,如果鼠标不动,只滚动滑轮的话,会发现图片会距离鼠标原点越来越远。为什么呢?
因为当我们滚动滑轮的时候,鼠标距离页面顶部的距离改变了,但是 clientY 是可视区域的大小,滚动滑轮的时候, clientY 的大小是没有变的,但是鼠标距离页面顶部的距离改变了,而图片在 Y 轴的距离计算还是按照 clientY 计算的,所以图片就会距离鼠标越来越远。
那么,怎么办呢?
事件参数 e 有连个属性:pageX,pageY 是距离页面顶部边界的距离,可以直接使用,但是不幸的是,IE8 又不支持。看来,只能是鼠标移动的距离 + 滑轮卷曲出去的距离来实现了。
**思路:**
之前我们封装的兼容代码都在一个函数里面,这里我们封装到一个对象 evt 里面。
这个 evt 对象封装了所有浏览器都支持的关于 clientX,clientY 等页面坐标的函数。
**图片跟着鼠标移动的最终版:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
height: 5000px;
}
img {
position: absolute;
}
</style>
</head>
<body>
<img src="images/Daotin.png" id="im">
<script src="common.js"></script>
<script>
var evt = {
// 获取通用事件对象
getEvent: function (e) {
return window.event||e;
},
// 获取通用ClientX
getClientX: function (e) {
return this.getEvent(e).clientX;
},
// 获取通用ClientY
getClientY: function (e) {
return this.getEvent(e).clientY;
},
// 获取通用 scrollLeft
getScrollLeft: function () {
return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
},
// 获取通用 scrollTop
getScrollTop: function () {
return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
},
// 获取通用 pageX
getPageX: function (e) {
return this.getEvent(e).pageX?this.getEvent(e).pageX:this.getClientX(e)+this.getScrollLeft();
},
// 获取通用 pageY
getPageY: function (e) {
return this.getEvent(e).pageY?this.getEvent(e).pageY:this.getClientY(e)+this.getScrollTop();
}
};
document.onmousemove = function (e) {
my$("im").style.left = evt.getPageX(e) + "px";
my$("im").style.top = evt.getPageY(e) + "px";
}
</script>
</body>
</html>
```
### 2、案例:淘宝宝贝放大镜
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
/*#box {*/
/*width: 100%;*/
/*height: 100%;*/
/*background-color: lightpink;*/
/*}*/
.small {
float: left;
width: 384px;
height: 240px;
margin-top: 50px;
margin-left: 50px;
}
.mask {
width: 128px;
height: 80px;
background-color: yellow;
opacity: 0.4;
position: absolute;
margin-top: 50px;
margin-left: 50px;
left: 0;
top: 0;
cursor: move;
display: none;
}
.big {
width: 640px;
height: 400px;
float: left;
margin-left: 50px;
overflow: hidden;
display: none;
}
</style>
</head>
<body>
<div id="box">
<div class="small">
<img src="images/dos.jpg" alt="">
<div class="mask"></div>
</div>
<div class="big">
<img src="images/window.jpg" alt="">
</div>
</div>
<script src="common.js"></script>
<script>
// 获取所有需要的元素
var boxObj = my$("box");
// 获取 small
var smallObj = boxObj.children[0];
// 获取 mask
var maskObj = smallObj.children[1];
// 获取 big
var bigObj = boxObj.children[1];
// 获取 bigImg
var bigImgObj = bigObj.children[0];
// 鼠标进入,显示遮挡层和大图
smallObj.onmouseover = function () {
maskObj.style.display = "block";
bigObj.style.display = "block";
};
// 鼠标退出,隐藏遮挡层和大图
smallObj.onmouseout = function () {
maskObj.style.display = "none";
bigObj.style.display = "none";
};
// 遮挡层跟着鼠标移动,使鼠标位于遮挡层中央
smallObj.onmousemove = function (e) {
var x = evt.getClientX(e) - parseInt(maskObj.offsetWidth / 2)-50; // 这50是遮挡层初始偏移left的距离
var y = evt.getClientY(e) - parseInt(maskObj.offsetHeight / 2)-50;// 这50是遮挡层初始偏移top的距离
// 遮挡层的最小移动范围
x = x < 0 ? 0 : x;
y = y < 0 ? 0 : y;
// 遮挡层的最大移动范围
x = x > smallObj.offsetWidth - maskObj.offsetWidth
? smallObj.offsetWidth - maskObj.offsetWidth
: x;
y = y > smallObj.offsetHeight - maskObj.offsetHeight
? smallObj.offsetHeight - maskObj.offsetHeight
: y;
maskObj.style.left = x + "px";
maskObj.style.top = y + "px";
// 小图移动的距离/小图能移动的最大距离 == 大图移动的距离/大图能移动的最大距离
// 大图移动的距离 = 小图移动的距离 * 大图能移动的最大距离 / 小图能移动的最大距离;
var bigImgX = x * (bigImgObj.offsetWidth - bigObj.offsetWidth) / (smallObj.offsetWidth - maskObj.offsetWidth);
var bigImgY = y * (bigImgObj.offsetHeight - bigObj.offsetHeight) / (smallObj.offsetHeight - maskObj.offsetHeight);
bigImgObj.style.marginLeft = -bigImgX + "px";
bigImgObj.style.marginTop = -bigImgY + "px";
};
</script>
</body>
</html>
```
> 第一步:获取所有需要的元素对象。
>
> 第二步:鼠标进入,离开小图,显示和隐藏遮挡层和大图。
>
> 第三步:遮挡层随着鼠标的移动而移动。
>
> 第四步:遮挡层移动的最大范围在小图内。
>
> 第五步:小图移动的距离/小图能移动的最大距离 == 大图移动的距离/大图能移动的最大距离,由此算出大图移动的距离 = 小图移动的距离 * 大图能移动的最大距离 / 小图能移动的最大距离。
>
> 第六步:将得到的大图移动的距离的负值赋值给大图即可。
### 3、案例:DIY 滑动栏
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 200px;
height: 300px;
border: 1px solid red;
margin-top: 100px;
margin-left: 300px;
overflow: hidden;
}
.content {
float: left;
width: 180px;
/*height: 900px;*/
}
.right {
float: left;
width: 20px;
height: 300px;
background-color: #e7e7e7;
position: relative;
}
.bar {
position: absolute;
left: 0;
top: 0;
width: 12px;
height: 50px;
margin: 0 4px;
background-color: #7b7b7b;
/*cursor: pointer;*/
}
</style>
</head>
<body>
<div id="box">
<div class="content">
kkkkkk温馨提示:由于厂商可能在未提前通知的情况下更改产品包装、产地、赠品或随机附件等。
飞虎回复仅在回复当时对提问者有效,其他网友仅供参考!若由此给您带来不便敬请谅解,谢谢!
温馨提示:由于厂商可能在未提前通知的情况下更改产品包装、产地、赠品或随机附件等。
飞虎回复仅在回复当时对提问者有效,其他网友仅供参考!若由此给您带来不便敬请谅解,谢谢!
温馨提示:由于厂商可能在未提前通知的情况下更改产品包装、产地、赠品或随机附件等。
飞虎回复仅在回复当时对提问者有效,其他网友仅供参考!若由此给您带来不便敬请谅解,谢谢!
温馨提示:由于厂商可能在未提前通知的情况下更改产品包装、产地、赠品或随机附件等。
飞虎回复仅在回复当时对提问者有效,其他网友仅供参考!若由此给您带来不便敬请谅解,谢谢!
温馨提示:由于厂商可能在未提前通知的情况下更改产品包装、产地、赠品或随机附件等。
飞虎回复仅在回复当时对提问者有效,其他网友仅供参考!若由此给您带来不便敬请谅解,谢谢!
温馨提示:由于厂商可能在未提前通知的情况下更改产品包装、产地、赠品或随机附件等。
飞虎回复仅在回复当时对提问者有效,其他网友仅供参考!若由此给您带来不便敬请谅解,谢谢!
温馨提示:由于厂商可能在未提前通知的情况下更改产品包装、产地、赠品或随机附件等。
飞虎回复仅在回复当时对提问者有效,其他网友仅供参考!若由此给您带来不便敬请谅解,谢谢!
温馨提示:由于厂商可能在未提前通知的情况下更改产品包装、产地、赠品或随机附件等。
飞虎回复仅在回复当时对提问者有效,其他网友仅供参考!若由此给您带来不便敬请谅解,谢谢!Daotin
</div>
<div class="right">
<div class="bar"></div>
</div>
</div>
<script src="common.js"></script>
<script>
// 获取所有的元素
// 获取 box
var boxObj = my$("box");
// 获取 content
var conObj = boxObj.children[0];
// 获取 right box
var rightObj = boxObj.children[1];
// 获取 bar
var barObj = rightObj.children[0];
// 鼠标点击bar,拖动
barObj.onmousedown = function (e) {
var spaceY = evt.getClientY(e) - barObj.offsetTop; // 鼠标距离bar顶部的距离
document.onmousemove = function () {
var y = evt.getClientY(e) - spaceY;
y = y < 0 ? 0 : y;
y = y < rightObj.offsetHeight - barObj.offsetHeight ? y : rightObj.offsetHeight - barObj.offsetHeight;
barObj.style.top = y + "px";
// 防止滑动的时候选中了文字
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
// 鼠标移动的时候,content也应该移动
// bar移动的距离/ bar可以移动的最大距离 = content移动的距离/ content可以移动的最大距离
var contentY = y * (conObj.offsetHeight - boxObj.offsetHeight) / (rightObj.offsetHeight - barObj.offsetHeight);
conObj.style.marginTop = -contentY + "px";
};
};
document.onmouseup = function () {
document.onmousemove = null;
}
// 鼠标离开
</script>
</body>
</html>
```
> 1、获取所有需要的元素。
>
> 2、鼠标点击,滑动,抬起,三个事件。
>
> 3、鼠标点击的时候获取鼠标的位置。
>
> 4、鼠标滑动的时候计算坐标 y。由于要保证鼠标移动的时候,鼠标相对滑动条顶部的距离一定,所以需要 spaceY。还需要注意滑动条滑动的范围。
>
> 5、鼠标抬起的时候,清除鼠标移动的事件。
>
> 6、防止滑动的时候选中了文字 `window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();`
>
> 7、通过比例,计算 content 内容反方向移动的距离。
## 二、复习
### 1、元素隐藏的不同方式
```javascript
my$("dv").style.display = "none"; // 不占位
my$("dv").style.visibility = "hidden"; // 占位
my$("dv").style.opacity = 0; // 占位
my$("dv").style.height = 0; // 占位
```
| Daotin/Web/03-JavaScript/03-BOM/04-client.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/03-BOM/04-client.md",
"repo_id": "Daotin",
"token_count": 8883
} | 16 |
这个案例按照面向对象的思想,我们把它分成四个模块。
第一,地图模块;
第二,食物模块,也就是上面小方块的模块;
第三,小蛇模块;
第四,整个游戏也可以封装成一个模块,这个模块是将上面三个模块再次封装起来。
### 1、地图模块
地图模块最简单了,就是一块 div,设置宽高,背景就可以了。
注意:由于食物和小蛇都要在背景之上移动,所以食物和小蛇是脱标的,所以地图需要设置 position: relative;
```html
<style>
.map {
width: 800px;
height: 600px;
background-color: #ccc;
position: relative;
}
</style>
<div class="map"></div>
```
### 2、食物模块
首先,食物的主体是由一个 div 组成,另外还有宽高,背景颜色属性,在食物脱标之后还有left,top属性,所以为了创建一个食物对象,就需要一个食物的构造函数,这个构造函数要设置食物的属性就是上面提到的属性。
```js
function Food(width, height, color) {
this.width = width || 20;
this.height = height || 20;
this.color = color || "green";
this.x = 0; // left属性
this.y = 0; // top属性
this.element = document.createElement("div"); // 食物实例对象
}
```
别忘了将 Food 暴露给 window
```js
window.Food = Food;
```
之后需要初始化食物的显示效果和位置。
> 1、由于经常使用 init 函数,所以将其写入原型对象。
>
> 2、每次在创建食物之前先删除之前的小方块,保证map中只有一个食物
>
> 3、我们需要在自调用函数中定义一个数组,用来保存食物,方便每次创建食物之前的删除和后来小蛇吃掉食物后的删除。
```js
Food.prototype.init = function (map) {
// 每次在创建小方块之前先删除之前的小方块,保证map中只有一个小方块
remove();
var div = this.element;
map.appendChild(div);
div.style.width = this.width + "px";
div.style.height = this.height + "px";
div.style.backgroundColor = this.color;
div.style.borderRadius = "50%";
div.style.position = "absolute";
this.x = new Random().getRandom(0, map.offsetWidth / this.width) * this.width;
this.y = new Random().getRandom(0, map.offsetHeight / this.height) * this.height;
div.style.left = this.x + "px";
div.style.top = this.y + "px";
// 把div加到数组中
elements.push(div);
};
```
食物的删除函数。设置为私有函数,其实就是自调用函数中的一个函数,保证不被自调用函数外面使用。
```js
function remove() {
for (var i = 0; i < elements.length; i++) {
elements[i].parentElement.removeChild(elements[i]);
elements.splice(i, 1); // 清空数组,从i的位置删除1个元素
}
}
```
### 3、小蛇模块
小蛇模块也得现有构造函数。
> 1、direction是小蛇移动的方向;
>
> 2、beforeDirection 是小蛇在键盘点击上下左右移动之前移动的方法,作用是不让小蛇回头,比如小蛇正往右走,不能点击左按键让其往左走,这时只能上下和右走。
>
> 3、小蛇最初的身体是三个 div,所以每个 div 都是一个对象,有自己的宽高和背景颜色和坐标。,所以这里用一个数组保存小蛇的身体。
```js
function Snack(width, height, direction) {
// 小蛇每一块的宽高
this.width = width || 20;
this.height = height || 20;
this.direction = direction || "right";
this.beforeDirection = this.direction;
// 小蛇组成身体的每个小方块
this.body = [
{x: 3, y: 2, color: "red"},
{x: 2, y: 2, color: "orange"},
{x: 1, y: 2, color: "orange"}
];
}
```
还是需要暴露给 window
```js
window.Snack = Snack;
```
小蛇的初始化函数就就是设置构造函数中的属性。由于有多个 div 组成,所以要循环设置。初始化之前也要先删除小蛇。
```js
Snack.prototype.init = function (map) {
// 显示小蛇之前删除小蛇
remove();
// 循环创建小蛇身体div
for (var i = 0; i < this.body.length; i++) {
var div = document.createElement("div");
map.appendChild(div);
div.style.width = this.width + "px";
div.style.height = this.height + "px";
div.style.borderRadius = "50%";
div.style.position = "absolute";
// 移动方向,移动的时候设置
// 坐标位置
var tempObj = this.body[i];
div.style.left = tempObj.x * this.width + "px";
div.style.top = tempObj.y * this.width + "px";
div.style.backgroundColor = tempObj.color;
// 将小蛇添加到数组
elements.push(div);
}
};
```
接下来是小蛇移动的方法。
> 1、小蛇移动的方法分两步,第一步是身体的移动;第二步是头部的移动。
>
> 2、当小蛇头坐标和食物的坐标相同时,表示吃到食物,这个时候小蛇要增长,怎么增长呢?将小蛇的尾巴赋值一份添加到小蛇的尾部。
>
> 3、之后删除食物,并重新生成食物。
```js
Snack.prototype.move = function (food, map) {
var index = this.body.length - 1; // 小蛇身体的索引
// 不考虑小蛇头部
for (var i = index; i > 0; i--) { // i>0 而不是 i>=0
this.body[i].x = this.body[i - 1].x;
this.body[i].y = this.body[i - 1].y;
}
// 小蛇头部移动
switch (this.direction) {
case "right" :
// if(this.beforeDirection !== "left") {
this.body[0].x += 1;
// }
break;
case "left" :
this.body[0].x -= 1;
break;
case "up" :
this.body[0].y -= 1;
break;
case "down" :
this.body[0].y += 1;
break;
default:
break;
}
// 小蛇移动的时候,当小蛇偷坐标和食物的坐标相同表示吃到食物
var headX = this.body[0].x * this.width;
var headY = this.body[0].y * this.height;
// 吃到食物,将尾巴复制一份加到小蛇body最后
if ((headX === food.x) && (headY === food.y)) {
var last = this.body[this.body.length - 1];
this.body.push({
x: last.x,
y: last.y,
color: last.color
});
// 删除食物
food.init(map);
}
};
```
### 4、游戏模块
首先创建游戏对象需要游戏构造函数,这个构造函数应该包含三个部分:食物,小蛇和地图。
> 这个 that 是为了以后进入定时器后的 this 是 window,而不是 Game 做的准备。
```js
function Game(map) {
this.food = new Food(20, 20, "purple");
this.snack = new Snack(20, 20);
this.map = map;
that = this;
}
```
然后是游戏初始化函数,初始化游戏的目的就是让游戏开始,用户可以开始玩游戏了。
这里面调用了两个函数:autoRun 和 changeDirection。
```js
Game.prototype.init = function () {
this.food.init(this.map);
this.snack.init(this.map);
this.autoRun();
this.changeDirection();
};
```
autoRun 是小蛇自动跑起来函数。这个函数主要是让小蛇动起来,并且在碰到边界时结束游戏。
> **注意:**这里有一个在函数后面使用 bind 函数:使用bind,那么 setInterval 方法中所有的 this 都将被bind 的参数 that 替换,而这个 that 就是 Game。
```js
Game.prototype.autoRun = function () {
var timeId = setInterval(function () {
this.snack.move(this.food, this.map);
this.snack.init(this.map);
// 判断最大X,Y边界
var maxX = this.map.offsetWidth / this.snack.width;
var maxY = this.map.offsetHeight / this.snack.height;
// X方向边界
if ((this.snack.body[0].x < 0) || (this.snack.body[0].x >= maxX)) {
// 撞墙了
clearInterval(timeId);
alert("Oops, Game Over!");
}
// Y方向边界
if ((this.snack.body[0].y < 0) || (this.snack.body[0].y >= maxY)) {
// 撞墙了
clearInterval(timeId);
alert("Oops, Game Over!");
}
}.bind(that), 150); // 使用bind,那么init方法中所有的this都将被bind的参数that替换
};
```
changeDirection 是监听按键,改变小蛇的走向。
> 这里面按键按下的事件是 onkeydown 事件。每个按键按下都会有一个对应的 keyCode 值,通过这个值就可以判断用户按下的是哪个键。
```js
Game.prototype.changeDirection = function () {
addAnyEventListener(document, "keydown", function (e) {
// 每次按键之前保存按键方向
this.snack.beforeDirection = this.snack.direction;
switch (e.keyCode) {
case 37: // 左
this.snack.beforeDirection !== "right" ? this.snack.direction = "left" : this.snack.direction = "right";
break;
case 38: // 上
this.snack.beforeDirection !== "down" ? this.snack.direction = "up" : this.snack.direction = "down";
break;
case 39: // 右
this.snack.beforeDirection !== "left" ? this.snack.direction = "right" : this.snack.direction = "left";
break;
case 40: // 下
this.snack.beforeDirection !== "up" ? this.snack.direction = "down" : this.snack.direction = "up";
break;
default:
break;
}
}.bind(that));
};
```
### 5、开始游戏
最后,我们只需要两行代码就可以开启游戏。
```js
var game = new Game(document.getElementsByClassName("map")[0]);
game.init();
``` | Daotin/Web/03-JavaScript/04-JavaScript高级知识/02-原型案例:贪吃蛇.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/04-JavaScript高级知识/02-原型案例:贪吃蛇.md",
"repo_id": "Daotin",
"token_count": 6106
} | 17 |
## 一、jQuery中的一些方法
### 1、使用css操作元素样式
#### 1.1、常规写法
```js
$("#dv").css("width", "200px");
$("#dv").css("backgroundColor", "red");
$("#dv").css("width", function(index,item){
return index+1;
});
```
> $("#dv").css("width", 200); px加不加都可以
>
> $("#dv").css("background-color", "red"); 两种写法都可以
#### 1.2、链式写法
```js
$("#dv").css("width", "200px").css("height", "100px").css("background", "red");
```
#### 1.3、键值对写法
```js
var json = {"width":"200px", "height":"100px"; "backgroundColor":"red"};
$("#dv").css(json);
```
示例:
```html
<div></div>
<div></div>
<div></div>
<script>
$("div").css({
width:50,
height:50,
backgroundColor:function () {
return randomColor();
},
position:"absolute",
left:function (index) {
return index*100;
},
top:function (index) {
return index*100;
}
}).on("click",function (e) {
$(this).css("backgroundColor",randomColor());
});
function randomColor() {
var col="#";
for(var i=0;i<6;i++){
col+=Math.floor(Math.random()*16).toString(16);
}
return col;
}
</script>
```
### 2、操作元素内容val,text,html
#### 2.1、value
```js
val(); // 获取或设置表单标签中的 value 值。
元素集合.val(); // 获取的是元素集合中第一个元素的value值
元素集合.val(function(index,item){return index;}); // 设置元素集合中每个元素的value为不同的值
```
#### 2.2、text
```js
text(); // 获取或设置标签的文本内容----相当于DOM中的innerText
元素集合.text(); // 当获取的时候,获取的是所有元素中所有html内容的拼接。
元素集合.text(function(index,item){ //text可以使用函数作为参数:设置元素集合中每个text的值。
return index+"aaa"; // 使用return来设置text的值
});
```
#### 2.3、html
```js
html(); // 获取或设置标签的html内容----相当于DOM中的innerHTML
元素集合.html(); // 当获取的时候,获取的是所有元素中第一个元素里面的html内容
元素集合.html(function(index,item){return index;});
```
> 除了text的元素集合的获取内容是所有元素的内容拼接之外,其他的获取内容都是第一个元素的内容。
## 二、链式编程
### 1、什么是链式编程?
对象在调用方法后可以继续调用方法,直到海枯石烂,地老天荒,直到山无棱,天地合,冬雷震震夏雨雪,乃敢不链式O.o。
### 2、语法
```js
对象.方法().方法().方法().......
```
### 3、条件
链式编程的前提:对象调用方法后的返回值还是**当前对象**,那么就可以继续调用方法,否则不可以继续调用方法。
### 4、经验
在 jQuery 中,一般情况下,对象调用方法,如果这个方法是设置某个属性的话(方法有参数是设置属性的值),那么返回值几乎都是当前对象,就可以继续链式编程。
示例:
```js
$("#dv").css("width","10px").val("haha").css("height":"20px");
```
## 三、使用class操作元素样式
### 1、添加类样式
语法:
```js
$("#dv").addClass("类选择器");
```
如果需要应用多个类样式,可以使用链式编程或者在一个addClass中写两个类选择器,中间用空格隔开。
```js
// 链式编程
$("#dv").addClass("类选择器1").addClass("类选择器2");
// 或者
$("#dv").addClass("类选择器1 类选择器2")
```
### 2、移除类样式
语法:
```js
// 链式编程
$("#dv").removeClass("类选择器1").removeClass("类选择器2");
// 或者
$("#dv").removeClass("类选择器1 类选择器2")
```
### 3、判断是否采用类样式
语法:
```js
// 链式编程
$("#dv").hasClass("类选择器1").hasClass("类选择器2");
// 或者
$("#dv").hasClass("类选择器1 类选择器2")
```
### 4、切换类样式
语法
```js
$("#dv").toggleClass("类选择器");
```
判断是否应用类选择器,如果没应用就添加,应用了就移除。
> 注意:
>
> 1、`addClass`, `removeClass`, `toggleClass` 方法不管有没有参数,返回值都是调用其的对象,都可以链式编程。
>
> 2、使用 CSS 方式是不能添加和移除类样式的。
## 四、动画相关方法
### 1、第一组
```js
// 参数1:时间(有两种写法:1. 1000ms,2. "normal","slow","fast")
// normal: 相当于400ms,slow:600ms,fast:200ms
// 参数2:函数(在动画执行完成之后调用)
// 这两个动画都是从左上角同时改变宽高来实现显示和隐藏的。
show(参数1,参数2);
hide(参数1,参数2);
```
示例:
```js
$("#btn1").click(function () {
$("#dv").hide("slow", function () {
alert("hide");
});
});
$("#btn2").click(function () {
$("#dv").show("slow", function () {
alert("show");
});
});
```
### 2、第二组
```js
// 参数和 show hide 一样
// 效果是上划入和划出
slideDown() // 显示
sildeUp() // 隐藏
slideToggle(); // 隐藏和显示切换
```
示例:
```js
$("#btn1").click(function () {
$("#dv").slideUp("slow", function () {
alert("hide");
});
});
$("#btn2").click(function () {
$("#dv").slideDown("slow", function () {
alert("show");
});
});
```
案例:省市联动
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul id="ulTop">
<li>中国大陆
<ul>
<li>湖北
<ul>
<li>武汉</li>
<li>荆州</li>
<li>襄阳</li>
<li>宜昌</li>
</ul>
</li>
<li>湖南</li>
<li>河南</li>
<li>河北</li>
<li>陕西
<ul>
<li>西安</li>
<li>咸阳</li>
<li>宝鸡</li>
<li>延安</li>
<li>安康</li>
</ul>
</li>
</ul>
</li>
<li>香港澳门</li>
<li>台湾</li>
</ul>
</body>
<script src="../js/jquery-1.12.4.js"></script>
<script>
$("li").click(function (e) {
e.stopPropagation(); // 阻止事件冒泡
if (!this.firstElementChild) return;
if (!this.bool) {
$(this.firstElementChild).slideUp(1000);
this.bool = true;
} else {
$(this.firstElementChild).slideDown(1000);
this.bool = false;
}
})
</script>
</html>
```

### 3、第三组
```js
// 参数和hide show一样,只不过fade是透明度的改变
fadeIn(); // 显示
fadeOut(); // 隐藏
fadeToggle(); // 隐藏和显示切换
// 参数1:时间
// 参数2:需要到达的透明度值(比如:0.2)
fadeTo(参数1,参数2)
```
示例:
```js
$("#btn1").click(function () {
$("#dv").fadeOut("slow", function () {
alert("fadeOut");
});
});
$("#btn2").click(function () {
$("#dv").fadeIn("slow", function () {
alert("fadeIn");
});
});
```
> 不管是show,slideDown,fadeIn都有第二个参数,第二个参数是函数,动画完成后执行的函数。
## 4、综合动画方法
```js
// 一般三个参数
// 参数1:css键值对,属性集合
// 参数2:时间,单位ms
// 参数3:回调函数
animate({...}, 1000, function (){...})
```
示例:
```html
<script>
$("#btn1").click(function () {
$("#dv").animate({"width":"100px","height":"50px"}, 3000, function () {
console.log("第一步");
}).animate({"width":"1000px","height":"200px"}, 3000, function () {
console.log("第二步");
}).animate({"width":"300px","height":"150px"}, 3000, function () {
console.log("第三步");
});
});
</script>
```
> PS:貌似颜色,背景色不能动画。
| Daotin/Web/04-jQuery/03-元素操作,链式编程,动画方法.md/0 | {
"file_path": "Daotin/Web/04-jQuery/03-元素操作,链式编程,动画方法.md",
"repo_id": "Daotin",
"token_count": 5053
} | 18 |
.jd {
width: 100%;
/* height: 1000px; */
/* 最大宽度 */
max-width: 640px;
/* 最小宽度 */
min-width: 320px;
margin: 0 auto;
background-color: #eee;
}
/* 搜索栏开始 */
.search {
width: 100%;
max-width: 640px;
height: 40px;
background-color: rgba(233, 35, 34, 0);
position: fixed;
z-index: 10;
}
.search-logo {
width: 56px;
height: 20px;
background-image: url("../images/jd-sprites.png");
background-size: 200px 200px;
background-position: left -109px;
position: absolute;
left: 10px;
top: 10px;
}
.search-login {
color: #fff;
font-size: 14px;
line-height: 40px;
position: absolute;
right: 10px;
top: 0;
}
.search-login:visited {
color: #fff;
}
.search-text {
width: 100%;
height: 100%;
padding-left: 76px;
padding-right: 50px;
}
.search-text>input {
width: 100%;
height: 30px;
margin-top: 5px;
border-radius: 15px;
color: #666;
padding-left: 30px;
font-size: 14px;
}
.search-text::before {
content: "";
width: 19px;
height: 20px;
background-image: url("../images/jd-sprites.png");
background-size: 200px 200px;
background-position: -60px -109px;
position: absolute;
left: 83px;
top: 10px;
}
/* 搜索栏结束 */
/* 轮播图开始 */
.slideshow {
width: 100%;
overflow: hidden;
position: relative;
}
.slideshow-img {
width: 800%;
}
.slideshow-img>li {
width: 12.5%;
float: left;
}
.slideshow-img>li img {
width: 100%;
}
.slideshow-dot {
width: 80px;
height: 10px;
position: absolute;
left: 50%;
bottom: 0;
transform: translateX(-50%);
}
.slideshow-dot>li {
width: 6px;
height: 6px;
float: left;
border-radius: 50%;
border: 1px solid #fff;
margin: 0 2px;
}
.slideshow-dot>li.select {
background-color: #fff;
}
/* 轮播图结束 */
/* 导航栏开始 */
.nav {
width: 100%;
box-shadow: 0 2px 2px #ccc;
}
.nav-ul {
width: 100%;
background-color: #fff;
}
.nav-ul>li {
width: 25%;
float: left;
text-align: center;
margin-top: 10px;
}
.nav-ul>li img {
width: 60px;
height: 60px;
}
.nav-ul>li p {
margin: 5px 0;
}
/* 导航栏结束 */
/* 主体内容开始 */
.content {
width: 100%;
}
.content-box {
width: 100%;
margin-top: 10px;
background-color: #fff;
box-shadow: 0 2px 2px #ccc;
}
.content-title {
border-bottom: 1px solid #ccc;
position: relative;
}
.content-box>.content-title {
height: 30px;
line-height: 30px;
}
.content-title>h3 {
margin-left: 20px;
position: relative;
font-weight: 700;
}
.content-title>h3::before {
content: "";
width: 3px;
height: 10px;
background-color: #e92322;
position: absolute;
left: -8px;
top: 10px;
}
.content-ul {
width: 100%;
}
.content-ul>li {
width: 50%;
}
.content-ul>li img {
width: 100%;
display: block;
}
.content-title-left-clock {
display: block;
width: 16px;
height: 20px;
background-image: url("../images/jd-sprites.png");
background-size: 200px 200px;
background-position: -85px -111px;
position: absolute;
left: 3px;
top: 4px;
}
.content-title-left-text {
padding: 0 10px 0 25px;
color: #e92322;
}
.content-title-left-time>span {
display: inline-block;
width: 12px;
height: 18px;
line-height: 18px;
background-color: #363634;
color: #e5d790;
text-align: center;
font-weight: bold;
}
.content-title-left-time>span:nth-of-type(3n) {
background-color: transparent;
width: 3px;
}
.content-title-right {
margin-right: 10px;
}
.content-box-sk {
padding: 10px;
}
.content-box-sk>.content-title {
border-bottom: 0;
margin-bottom: 10px;
}
.content-box-sk .content-ul {
padding: 10px 0;
display: flex;
justify-content: space-around;
}
.content-box-sk .content-ul>li {
/* width: 33.33%; */
text-align: center;
}
.content-box-sk .content-ul>li img {
width: 100%;
display: inline-block;
padding: 0 30px;
margin-bottom: 5px;
}
.content-ul-delete {
text-decoration: line-through;
color: #aaa;
}
/* 主体内容结束 */ | Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/css/index.css/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/css/index.css",
"repo_id": "Daotin",
"token_count": 2015
} | 19 |
// Base Class Definition
// -------------------------
.#{$fa-css-prefix} {
display: inline-block;
font: normal normal normal #{$fa-font-size-base}/#{$fa-line-height-base} FontAwesome; // shortening font declaration
font-size: inherit; // can't have font-size inherit on line above, so need to override
text-rendering: auto; // optimizelegibility throws things off #1094
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_core.scss/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_core.scss",
"repo_id": "Daotin",
"token_count": 148
} | 20 |
/**
* @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
;(function(window, document) {
/*jshint evil:true */
/** version */
var version = '3.7.3';
/** Preset options */
var options = window.html5 || {};
/** Used to skip problem elements */
var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
/** Not all elements can be cloned in IE **/
var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
/** Detect whether the browser supports default html5 styles */
var supportsHtml5Styles;
/** Name of the expando, to work with multiple documents or to re-shiv one document */
var expando = '_html5shiv';
/** The id for the the documents expando */
var expanID = 0;
/** Cached data for each document */
var expandoData = {};
/** Detect whether the browser supports unknown elements */
var supportsUnknownElements;
(function() {
try {
var a = document.createElement('a');
a.innerHTML = '<xyz></xyz>';
//if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
supportsHtml5Styles = ('hidden' in a);
supportsUnknownElements = a.childNodes.length == 1 || (function() {
// assign a false positive if unable to shiv
(document.createElement)('a');
var frag = document.createDocumentFragment();
return (
typeof frag.cloneNode == 'undefined' ||
typeof frag.createDocumentFragment == 'undefined' ||
typeof frag.createElement == 'undefined'
);
}());
} catch(e) {
// assign a false positive if detection fails => unable to shiv
supportsHtml5Styles = true;
supportsUnknownElements = true;
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a style sheet with the given CSS text and adds it to the document.
* @private
* @param {Document} ownerDocument The document.
* @param {String} cssText The CSS text.
* @returns {StyleSheet} The style element.
*/
function addStyleSheet(ownerDocument, cssText) {
var p = ownerDocument.createElement('p'),
parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
p.innerHTML = 'x<style>' + cssText + '</style>';
return parent.insertBefore(p.lastChild, parent.firstChild);
}
/**
* Returns the value of `html5.elements` as an array.
* @private
* @returns {Array} An array of shived element node names.
*/
function getElements() {
var elements = html5.elements;
return typeof elements == 'string' ? elements.split(' ') : elements;
}
/**
* Extends the built-in list of html5 elements
* @memberOf html5
* @param {String|Array} newElements whitespace separated list or array of new element names to shiv
* @param {Document} ownerDocument The context document.
*/
function addElements(newElements, ownerDocument) {
var elements = html5.elements;
if(typeof elements != 'string'){
elements = elements.join(' ');
}
if(typeof newElements != 'string'){
newElements = newElements.join(' ');
}
html5.elements = elements +' '+ newElements;
shivDocument(ownerDocument);
}
/**
* Returns the data associated to the given document
* @private
* @param {Document} ownerDocument The document.
* @returns {Object} An object of data.
*/
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
/**
* returns a shived element for the given nodeName and document
* @memberOf html5
* @param {String} nodeName name of the element
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived element.
*/
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
// Avoid adding some elements to fragments in IE < 9 because
// * Attributes like `name` or `type` cannot be set/changed once an element
// is inserted into a document/fragment
// * Link elements with `src` attributes that are inaccessible, as with
// a 403 response, will cause the tab/window to crash
// * Script elements appended to fragments will execute when their `src`
// or `text` property is set
return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
}
/**
* returns a shived DocumentFragment for the given document
* @memberOf html5
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived DocumentFragment.
*/
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
/**
* Shivs the `createElement` and `createDocumentFragment` methods of the document.
* @private
* @param {Document|DocumentFragment} ownerDocument The document.
* @param {Object} data of the document.
*/
function shivMethods(ownerDocument, data) {
if (!data.cache) {
data.cache = {};
data.createElem = ownerDocument.createElement;
data.createFrag = ownerDocument.createDocumentFragment;
data.frag = data.createFrag();
}
ownerDocument.createElement = function(nodeName) {
//abort shiv
if (!html5.shivMethods) {
return data.createElem(nodeName);
}
return createElement(nodeName, ownerDocument, data);
};
ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
'var n=f.cloneNode(),c=n.createElement;' +
'h.shivMethods&&(' +
// unroll the `createElement` calls
getElements().join().replace(/[\w\-:]+/g, function(nodeName) {
data.createElem(nodeName);
data.frag.createElement(nodeName);
return 'c("' + nodeName + '")';
}) +
');return n}'
)(html5, data.frag);
}
/*--------------------------------------------------------------------------*/
/**
* Shivs the given document.
* @memberOf html5
* @param {Document} ownerDocument The document to shiv.
* @returns {Document} The shived document.
*/
function shivDocument(ownerDocument) {
if (!ownerDocument) {
ownerDocument = document;
}
var data = getExpandoData(ownerDocument);
if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
data.hasCSS = !!addStyleSheet(ownerDocument,
// corrects block display not defined in IE6/7/8/9
'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' +
// adds styling not present in IE6/7/8/9
'mark{background:#FF0;color:#000}' +
// hides non-rendered elements
'template{display:none}'
);
}
if (!supportsUnknownElements) {
shivMethods(ownerDocument, data);
}
return ownerDocument;
}
/*--------------------------------------------------------------------------*/
/**
* The `html5` object is exposed so that more elements can be shived and
* existing shiving can be detected on iframes.
* @type Object
* @example
*
* // options can be changed before the script is included
* html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
*/
var html5 = {
/**
* An array or space separated string of node names of the elements to shiv.
* @memberOf html5
* @type Array|String
*/
'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video',
/**
* current version of html5shiv
*/
'version': version,
/**
* A flag to indicate that the HTML5 style sheet should be inserted.
* @memberOf html5
* @type Boolean
*/
'shivCSS': (options.shivCSS !== false),
/**
* Is equal to true if a browser supports creating unknown/HTML5 elements
* @memberOf html5
* @type boolean
*/
'supportsUnknownElements': supportsUnknownElements,
/**
* A flag to indicate that the document's `createElement` and `createDocumentFragment`
* methods should be overwritten.
* @memberOf html5
* @type Boolean
*/
'shivMethods': (options.shivMethods !== false),
/**
* A string to describe the type of `html5` object ("default" or "default print").
* @memberOf html5
* @type String
*/
'type': 'default',
// shivs the document according to the specified `html5` object options
'shivDocument': shivDocument,
//creates a shived element
createElement: createElement,
//creates a shived documentFragment
createDocumentFragment: createDocumentFragment,
//extends list of elements
addElements: addElements
};
/*--------------------------------------------------------------------------*/
// expose html5
window.html5 = html5;
// shiv the document
shivDocument(document);
/*------------------------------- Print Shiv -------------------------------*/
/** Used to filter media types */
var reMedia = /^$|\b(?:all|print)\b/;
/** Used to namespace printable elements */
var shivNamespace = 'html5shiv';
/** Detect whether the browser supports shivable style sheets */
var supportsShivableSheets = !supportsUnknownElements && (function() {
// assign a false negative if unable to shiv
var docEl = document.documentElement;
return !(
typeof document.namespaces == 'undefined' ||
typeof document.parentWindow == 'undefined' ||
typeof docEl.applyElement == 'undefined' ||
typeof docEl.removeNode == 'undefined' ||
typeof window.attachEvent == 'undefined'
);
}());
/*--------------------------------------------------------------------------*/
/**
* Wraps all HTML5 elements in the given document with printable elements.
* (eg. the "header" element is wrapped with the "html5shiv:header" element)
* @private
* @param {Document} ownerDocument The document.
* @returns {Array} An array wrappers added.
*/
function addWrappers(ownerDocument) {
var node,
nodes = ownerDocument.getElementsByTagName('*'),
index = nodes.length,
reElements = RegExp('^(?:' + getElements().join('|') + ')$', 'i'),
result = [];
while (index--) {
node = nodes[index];
if (reElements.test(node.nodeName)) {
result.push(node.applyElement(createWrapper(node)));
}
}
return result;
}
/**
* Creates a printable wrapper for the given element.
* @private
* @param {Element} element The element.
* @returns {Element} The wrapper.
*/
function createWrapper(element) {
var node,
nodes = element.attributes,
index = nodes.length,
wrapper = element.ownerDocument.createElement(shivNamespace + ':' + element.nodeName);
// copy element attributes to the wrapper
while (index--) {
node = nodes[index];
node.specified && wrapper.setAttribute(node.nodeName, node.nodeValue);
}
// copy element styles to the wrapper
wrapper.style.cssText = element.style.cssText;
return wrapper;
}
/**
* Shivs the given CSS text.
* (eg. header{} becomes html5shiv\:header{})
* @private
* @param {String} cssText The CSS text to shiv.
* @returns {String} The shived CSS text.
*/
function shivCssText(cssText) {
var pair,
parts = cssText.split('{'),
index = parts.length,
reElements = RegExp('(^|[\\s,>+~])(' + getElements().join('|') + ')(?=[[\\s,>+~#.:]|$)', 'gi'),
replacement = '$1' + shivNamespace + '\\:$2';
while (index--) {
pair = parts[index] = parts[index].split('}');
pair[pair.length - 1] = pair[pair.length - 1].replace(reElements, replacement);
parts[index] = pair.join('}');
}
return parts.join('{');
}
/**
* Removes the given wrappers, leaving the original elements.
* @private
* @params {Array} wrappers An array of printable wrappers.
*/
function removeWrappers(wrappers) {
var index = wrappers.length;
while (index--) {
wrappers[index].removeNode();
}
}
/*--------------------------------------------------------------------------*/
/**
* Shivs the given document for print.
* @memberOf html5
* @param {Document} ownerDocument The document to shiv.
* @returns {Document} The shived document.
*/
function shivPrint(ownerDocument) {
var shivedSheet,
wrappers,
data = getExpandoData(ownerDocument),
namespaces = ownerDocument.namespaces,
ownerWindow = ownerDocument.parentWindow;
if (!supportsShivableSheets || ownerDocument.printShived) {
return ownerDocument;
}
if (typeof namespaces[shivNamespace] == 'undefined') {
namespaces.add(shivNamespace);
}
function removeSheet() {
clearTimeout(data._removeSheetTimer);
if (shivedSheet) {
shivedSheet.removeNode(true);
}
shivedSheet= null;
}
ownerWindow.attachEvent('onbeforeprint', function() {
removeSheet();
var imports,
length,
sheet,
collection = ownerDocument.styleSheets,
cssText = [],
index = collection.length,
sheets = Array(index);
// convert styleSheets collection to an array
while (index--) {
sheets[index] = collection[index];
}
// concat all style sheet CSS text
while ((sheet = sheets.pop())) {
// IE does not enforce a same origin policy for external style sheets...
// but has trouble with some dynamically created stylesheets
if (!sheet.disabled && reMedia.test(sheet.media)) {
try {
imports = sheet.imports;
length = imports.length;
} catch(er){
length = 0;
}
for (index = 0; index < length; index++) {
sheets.push(imports[index]);
}
try {
cssText.push(sheet.cssText);
} catch(er){}
}
}
// wrap all HTML5 elements with printable elements and add the shived style sheet
cssText = shivCssText(cssText.reverse().join(''));
wrappers = addWrappers(ownerDocument);
shivedSheet = addStyleSheet(ownerDocument, cssText);
});
ownerWindow.attachEvent('onafterprint', function() {
// remove wrappers, leaving the original elements, and remove the shived style sheet
removeWrappers(wrappers);
clearTimeout(data._removeSheetTimer);
data._removeSheetTimer = setTimeout(removeSheet, 500);
});
ownerDocument.printShived = true;
return ownerDocument;
}
/*--------------------------------------------------------------------------*/
// expose API
html5.type += ' print';
html5.shivPrint = shivPrint;
// shiv for print
shivPrint(document);
if(typeof module == 'object' && module.exports){
module.exports = html5;
}
}(typeof window !== "undefined" ? window : this, document));
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/html5shiv/html5shiv-printshiv.js/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/html5shiv/html5shiv-printshiv.js",
"repo_id": "Daotin",
"token_count": 5916
} | 21 |
## Browserify模块化使用教程
区别Node与Browserify
Node.js运行时动态加载模块(同步)
Browserify是在转译(编译)时就会加载打包(合并)require的模块
### 操作步骤
1、创建项目结构
```
|-js
|-dist //打包生成文件的目录
|-src //源码所在的目录
|-module1.js
|-module2.js
|-module3.js
|-app.js //应用主源文件
|-index.html
|-package.json
{
"name": "browserify-test",
"version": "1.0.0"
}
```
2、下载插件browserify
```
npm install browserify -g
npm install browserify --save-dev
```
3、定义模块代码
* module1.js
```js
module.exports = {
foo() {
console.log('moudle1 foo()')
}
}
```
* module2.js
```js
module.exports = function () {
console.log('module2()')
}
```
* module3.js
```js
exports.foo = function () {
console.log('module3 foo()')
}
exports.bar = function () {
console.log('module3 bar()')
}
```
* app.js (应用的主js)
```js
//引用模块
let module1 = require('./module1')
let module2 = require('./module2')
let module3 = require('./module3')
let uniq = require('uniq')
//使用模块
module1.foo()
module2()
module3.foo()
module3.bar()
console.log(uniq([1, 3, 1, 4, 3]))
```
* 打包处理js:
```
browserify js/src/app.js -o js/dist/bundle.js
```
**(为什么不直接在html中引入app.js 呢?**
**答案:因为浏览器无法识别 require。)**

- 页面使用引入:
```html
<script src="js/dist/bundle.js"></script>
```
| Daotin/Web/09-模块化规范/03-前端CommonJS-Browserify模块化.md/0 | {
"file_path": "Daotin/Web/09-模块化规范/03-前端CommonJS-Browserify模块化.md",
"repo_id": "Daotin",
"token_count": 829
} | 22 |
## 一、品牌管理案例
如下图,
1、实现输入id和name后,点击add按钮,添加到table中;
2、点击数据的del,可以删除这条数据。

代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="./lib/vue-2.4.0.js"></script>
<style>
* {
padding: 0;
margin: 0;
position: relative;
}
/* 实现任意无宽高盒子居中显示 */
#app {
position: absolute;
left: 50%;
top: 100px;
transform: translateX(-50%);
}
.box {
width: 500px;
height: 40px;
background-color: #ccc;
display: inline-block;
text-align: center;
line-height: 40px;
border: 1px solid #aaa;
box-sizing: border-box;
border-bottom: none;
}
.tb {
width: 500px;
text-align: center;
border-collapse: collapse;
border-color: #ccc;
}
</style>
</head>
<body>
<div id="app">
<div class="box">
<label for="id">
ID:
<input type="text" id="id" v-model="id">
</label>
<label for="name">
name:
<input type="text" id="name" v-model="name">
</label>
<input type="button" value="add" @click="addClick">
</div>
<table border="1" cellspacing="0" class="tb">
<tr v-for="item in list">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.ctime}}</td>
<td>
<!-- 绑定的事件是可以传参数的,这里传入需要删除的对象id -->
<a href="javascript:;" @click.prevent="delClick(item.id)">del</a>
</td>
</tr>
</table>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
id: "",
name: "",
list: [{
id: 1,
name: 'tony',
ctime: new Date()
},
{
id: 2,
name: 'stark',
ctime: new Date()
}
]
},
methods: {
addClick() {
// 1.获取表单数据
// 2.组织出一个对象
// 3.将对象添加到data中(不需要重新渲染页面)
let item = {
id: this.id,
name: this.name,
ctime: new Date()
};
if ((this.id != "") && (this.name != "")) {
this.list.push(item);
}
// 4.最后将表单清空
this.id = this.name = "";
},
delClick(id) {
// 1.根据id找到索引(循环查找)
// 2.调用数组的 splice方法删除
this.list.filter((item, index) => {
if (item.id == id) {
this.list.splice(index, 1);
return true;
}
});
}
}
});
</script>
</body>
</html>
```
> 注意:
>
> 1、事件名后面可以加括号(`@click="addClick"` 等价于 `@click="addClick()` ,这样写的话,就可以传参。)
### 1、增加搜索需求

在Query中输入字符串,如果name项中包括Query中的字符串,则显示。
分析:
如果要满足条件才显示相关行,那么 `<tr v-for="item in list">` 中的list就是一个可变的。这里我们使用一个函数,函数里面进行判断是否包含Query中的字符串,然后将包含的拷贝到新数组中,填充到list的位置:
`<tr v-for="item in search(keywords)">`
```json
methods: {
addClick() {
//...
},
delClick(id) {
//...
},
// 添加的用于判断的函数
search(keywords) {
// 定义新数组保存符合条件的项
let newList = [];
this.list.forEach((item, index) => {
// 包含则返回true
if (item.name.includes(keywords)) {
newList.push(item);
}
});
return newList;
}
}
```
## 二、过滤器
vue 允许自定义过滤器,可被用作一些常见的文本格式化。
过滤器只能用在两个地方:**插值表达式**和 **`v-bind`表达式** 。
### 1、全局过滤器
基本用法:**(必须在new Vue之前定义)**
```html
<body>
<div id="box">
<p>{{msg | msgFormat}}</p>
</div>
<script>
// 使用Vue.filter来定义一个过滤器:
// 第一个参数:过滤器函数名称
// 第二个参数:过滤器函数体
// 过滤器的参数就是管道符的前面待处理的字符串。
Vue.filter('msgFormat', (data) => {
return data.replace("vue", "Daotin");
});
var vm = new Vue({
el: " #box ",
data: {
msg: "hello vue"
}
});
</script>
</body>
```
> 1、使用 `Vue.filter` 来定义一个过滤器。
>
> **2、必须在new Vue之前定义。**
>
> 2、第一个参数:过滤器函数名称;第二个参数:过滤器函数体
>
> 3、过滤器的第一个参数就是**管道符的前面待处理的字符串**。
**插值表达式里的过滤器函数可以带参数:**
相应的,在 `Vue.filter('msgFormat', (data, arg1,arg2,...)` 中 msgFormat 的参数从第二位开始放置。
可以带多个参数。
```html
<body>
<div id="box">
<!--hello Daotin is a boy and good-->
<p>{{msg | msgFormat('is a boy', 'and good')}}</p>
</div>
<script>
// 使用Vue.filter来定义一个过滤器:
// 第一个参数:过滤器函数名称
// 第二个参数:过滤器函数体
// 过滤器的参数就是管道符的前面待处理的字符串。
Vue.filter('msgFormat', (data, arg1, arg2='and bad') => {
return data.replace("vue", "Daotin " + arg1 + arg2);
});
var vm = new Vue({
el: " #box ",
data: {
msg: "hello vue"
},
methods: {}
});
</script>
</body>
```
**使用全局过滤器格式化品牌管理案例的 ctime:**
```js
<td>{{item.ctime | ctimeFormat}}</td>
...
// ctime 过滤器
Vue.filter('ctimeFormat', (data) => {
let time = new Date(data);
let year = time.getFullYear();
let month = time.getMonth() + 1;
let day = time.getDate();
let hour = time.getHours();
let minute = time.getMinutes();
return `${year}-${month}-${day} ${hour}:${minute}`;
});
```
### 2、局部过滤器
局部过滤器只能在当前组件使用。

> 注意:过滤器的调用原则是**就近原则**,即先调用局部过滤器再调用全局过滤器。
**padStart和padEnd**
```js
// ctime 过滤器
Vue.filter('ctimeFormat', (data) => {
let time = new Date(data);
let year = time.getFullYear();
let month = (time.getMonth() + 1).toString().padStart(2, '0');
let day = (time.getDate()).toString().padStart(2, '0');
let hour = (time.getHours()).toString().padStart(2, '0');
let minute = (time.getMinutes()).toString().padStart(2, '0');
let second = (time.getSeconds()).toString().padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
});
```
> 使用ES6中的字符串新方法 `String.prototype.padStart(maxLength, fillString='')` 或 `String.prototype.padEnd(maxLength, fillString='')`来填充字符串;
>
> padStart:从开头填充
>
> padEnd:从结尾填充
>
> maxLength:填充后最大的长度
>
> fillString:需要填充的字符串(fillString='',不填则以空字符填充)
## 三、按键修饰符
我们现在有个需求就是输入ID和name后不点击add按钮,而是按下回车键也需要添加到列表中。
我们可以在name输入框中加入按键抬起事件,并且指定是enter键抬起时才触发。
```html
<label for="name">
name:
<input type="text" id="name" v-model="name" @keyup.enter="addClick">
```
> `.enter` : 就是按键修饰符。
**系统提供的按键修饰符有:**
- `.enter`
- `.tab`
- `.delete` (捕获“删除”和“退格”键)
- `.esc`
- `.space`
- `.up`
- `.down`
- `.left`
- `.right`
如果我们想自定义其他的按键怎么办呢?
通过`Vue.config.keyCodes.f2 = 113;` ;可以将f2作为按键修饰符添加到系统按键修饰符中。
具体每个按键的值是多少?下面是常见的按键的码。
```
keyCode 8 = BackSpace BackSpace
keyCode 9 = Tab Tab
keyCode 12 = Clear
keyCode 13 = Enter
keyCode 16 = Shift_L
keyCode 17 = Control_L
keyCode 18 = Alt_L
keyCode 19 = Pause
keyCode 20 = Caps_Lock
keyCode 27 = Escape Escape
keyCode 32 = space
keyCode 33 = Prior
keyCode 34 = Next
keyCode 35 = End
keyCode 36 = Home
keyCode 37 = Left
keyCode 38 = Up
keyCode 39 = Right
keyCode 40 = Down
keyCode 41 = Select
keyCode 42 = Print
keyCode 43 = Execute
keyCode 45 = Insert
keyCode 46 = Delete
keyCode 47 = Help
keyCode 48 = 0 equal braceright
keyCode 49 = 1 exclam onesuperior
keyCode 50 = 2 quotedbl twosuperior
keyCode 51 = 3 section threesuperior
keyCode 52 = 4 dollar
keyCode 53 = 5 percent
keyCode 54 = 6 ampersand
keyCode 55 = 7 slash braceleft
keyCode 56 = 8 parenleft bracketleft
keyCode 57 = 9 parenright bracketright
keyCode 65 = a A
keyCode 66 = b B
keyCode 67 = c C
keyCode 68 = d D
keyCode 69 = e E EuroSign
keyCode 70 = f F
keyCode 71 = g G
keyCode 72 = h H
keyCode 73 = i I
keyCode 74 = j J
keyCode 75 = k K
keyCode 76 = l L
keyCode 77 = m M mu
keyCode 78 = n N
keyCode 79 = o O
keyCode 80 = p P
keyCode 81 = q Q at
keyCode 82 = r R
keyCode 83 = s S
keyCode 84 = t T
keyCode 85 = u U
keyCode 86 = v V
keyCode 87 = w W
keyCode 88 = x X
keyCode 89 = y Y
keyCode 90 = z Z
keyCode 96 = KP_0 KP_0
keyCode 97 = KP_1 KP_1
keyCode 98 = KP_2 KP_2
keyCode 99 = KP_3 KP_3
keyCode 100 = KP_4 KP_4
keyCode 101 = KP_5 KP_5
keyCode 102 = KP_6 KP_6
keyCode 103 = KP_7 KP_7
keyCode 104 = KP_8 KP_8
keyCode 105 = KP_9 KP_9
keyCode 106 = KP_Multiply KP_Multiply
keyCode 107 = KP_Add KP_Add
keyCode 108 = KP_Separator KP_Separator
keyCode 109 = KP_Subtract KP_Subtract
keyCode 110 = KP_Decimal KP_Decimal
keyCode 111 = KP_Divide KP_Divide
keyCode 112 = F1
keyCode 113 = F2
keyCode 114 = F3
keyCode 115 = F4
keyCode 116 = F5
keyCode 117 = F6
keyCode 118 = F7
keyCode 119 = F8
keyCode 120 = F9
keyCode 121 = F10
keyCode 122 = F11
keyCode 123 = F12
keyCode 124 = F13
keyCode 125 = F14
keyCode 126 = F15
keyCode 127 = F16
keyCode 128 = F17
keyCode 129 = F18
keyCode 130 = F19
keyCode 131 = F20
keyCode 132 = F21
keyCode 133 = F22
keyCode 134 = F23
keyCode 135 = F24
```
示例:
```html
<input type="text" id="name" v-model="name" @keyup.f2="addClick">
//...
<script>
Vue.config.keyCodes.f2 = 113;
</script>
```
## 四、自定义指令
除了核心功能默认内置的指令 (`v-model` 等),Vue 也允许注册自定义指令。自定义指令是以 `v-`开头的指令。
比如我们想让品牌管理案例中,在刚进入页面的时候,就获取 Query输入框的焦点,但是vue并没有提供这样的指令。
之前我们可以通过获取DOM元素,然后使用 `DOM元素.focus();` 方法来获取焦点。但是在vue里面不推荐获取DOM元素的方式。这时我们可以使用自定义指令的方式来达到获取焦点。
比如:我们想定义一个`v-focus` 的指令来获取焦点。
```html
<label for="sel">
Query:
<input type="text" id="sel" v-model="keywords" v-focus>
</label>
<script>
// 自定义全局指令 v-focus,为绑定的元素自动获取焦点:
Vue.directive('focus', {
inserted: function (el) { // inserted 表示被绑定元素插入父节点时调用
el.focus();
}
});
</script>
```
> 1、定义自定义指令的时候,不需要加`v-` ,使用的时候需要加。
>
> 2、注意: 在每个 函数中,第一个参数,永远是 `el` ,表示 被绑定了指令的那个元素,这个 el 参数,是一个原生的JS对象。
>
> 3、和JS行为有关的操作,最好在 `inserted` 中去执行
如果想注册局部指令,组件中也接受一个 `directives` 的选项:
```js
directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus()
}
}
}
```
### 1、钩子函数
inserted 是钩子函数,类似的钩子函数还有几个,但是应用场景不同:
- `inserted` :被绑定元素插入DOM元素时调用一次(**从内存渲染到页面时如果绑定了 inserted 就执行**)。
- `bind`:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置(**在代码加载到内存中的时候,如果绑定了bind就执行**,比如样式style的设定,使用bind绑定)。
- `update`:所在组件的 VNode 更新时调用,**但是可能发生在其子 VNode 更新之前**。指令的值可能发生了改变,也可能没有。
- `componentUpdated`:指令所在组件的 VNode **及其子 VNode** 全部更新后调用。
- `unbind`:只调用一次,指令与元素解绑时调用。
---
### *(added in 20210105)*
**bind和inserted区别:**
共同点: dom插入都会调用
不同点:bind在inserted之前调用,bind 时元素的父节点为 null,inserted 时元素的父节点存在。
```js
bind: function (el) {
console.log(el.parentNode) // null
},
inserted: function (el) {
console.log(el.parentNode) // <div id="app">...</div>
}
```
**update和componentUpdated区别:**
共同点: 组件更新都会调用
不同点:update在组件更新前调用,componentUpdated在组件更新后调用。
```js
update: function (el) {
console.log(el.innerHTML) // Hello, before updated
},
componentUpdated: function (el) {
console.log(el.innerHTML) // Hi, after updated
}
```
### 2、钩子函数参数
指令钩子函数会被传入以下参数:
- `el`:指令所绑定的元素,可以用来直接操作 DOM 。
- `binding`:一个对象,包含以下属性:
- `name`:指令名,不包括 `v-` 前缀。
- `value`:指令的绑定值,例如:`v-my-directive="10"` 中,绑定值为 `10`。
- `expression`:字符串形式的指令表达式。例如 `v-my-directive="1 + 1"` 中,表达式为 `"1 + 1"`。
- `arg`:传给指令的参数,可选。例如 `v-my-directive:foo` 中,参数为 `"foo"`。
- `modifiers`:一个包含修饰符的对象。例如:`v-my-directive.foo.bar` 中,修饰符对象为 `{ foo: true, bar: true }`。
- `vnode`:Vue 编译生成的虚拟节点。
- `oldVnode`:上一个虚拟节点,仅在 `update` 和 `componentUpdated` 钩子中可用。
> **注意:除了 `el` 之外,其它参数都应该是只读的,切勿进行修改。**
我们可以为自定义指令赋值,比如我们想给Query文本框的字体颜色赋值:
```html
<label for="sel">
Query:
<input type="text" id="sel" v-model="keywords" v-focus v-color="'red'">
</label>
```
> 之所以使用`v-color="'red'"`,而不是`v-color="red"`,是因为如果是red字符串的话,就当做变量在vue的data中查找,而这里要表达的是字符串red。
自定义v-color指令:
```js
Vue.directive("color", {
bind(el, binding) {
el.style.color = binding.value;
}
});
```
---
### *(added in 20210105)*
案例补充:
**点击元素之外的地方执行相应的方法**。
一般我们在开发项目的时候都会遇到这样的场景,当点击一个按钮的时候,弹出下拉菜单,再次点击的时候,下拉菜单收起。但是我们有时候不想再次点击这个按钮,而是点击屏幕其他地方,也需要这个下拉菜单收起。
常用的做法就是给整个页面绑定一个click事件,当点击页面的时候收起下拉菜单。但是如果有很多页面都需要这样做的话,就比较麻烦,今天我们做一个vue指令,绑定到该下拉菜单上,实现点击屏幕其他地方,收起下拉菜单。
```javascript
<div v-if="showproducts" v-clickoutside="closeProducts"></div>
// 执行方法
closeProducts() {
this.showproducts = false;
}
```
假设有这样一个div,点击屏幕其他位置的时候,`showproducts=false`,关闭弹框。Vue指令如何编写呢?
在点击的时候,给document绑定一个click事件,事件的处理函数可以获取鼠标点击的元素e.target,
判断鼠标点击的位置是否在绑定的元素中,是的话`retuen false`;否则的话执行传入的函数。
这里的:
- binding.expression:表示`v-clickoutside ` 后面是否传入了表达式,我们传入了`closeProducts`字符串。
- binding.value:表示`v-clickoutside `绑定的具体的值。` binding.value();` 就相当于执行`closeProducts()` ;
由于给document绑定了click事件,在`showproducts==false`,也就是指令解绑的时候,解绑click事件,`el._vueClickOutside_` 用来传递同一个click事件对应的函数。
```js
// 点击绑定了元素之外的地方,执行相应的方法
Vue.directive('clickoutside', {
bind: function (el, binding) {
function domHandler(e) {
if(el.contains(e.target)) {
return false;
}
if (binding.expression) {
binding.value(); // 执行函数
}
}
el._vueClickOutside_ = domHandler;
document.addEventListener('click', domHandler);
},
unbind: function (el) {
document.removeEventListener('click', el._vueClickOutside_);
delete el._vueClickOutside_;
}
});
```
### 3、动态指令参数
指令的参数可以是动态的。例如,在 `v-mydirective:[argument]="value"` 中,`argument` 参数可以根据组件实例数据进行更新!这使得自定义指令可以在应用中被灵活使用。
例如你想要创建一个自定义指令,用来通过固定布局将元素固定在页面上。我们可以像这样创建一个通过指令值来更新竖直位置像素值的自定义指令:
```html
<div id="baseexample">
<p>Scroll down the page</p>
<p v-pin="200">Stick me 200px from the top of the page</p>
</div>
<script>
Vue.directive('pin', {
bind: function (el, binding, vnode) {
el.style.position = 'fixed'
el.style.top = binding.value + 'px'
}
})
new Vue({
el: '#baseexample'
});
</script>
```
这会把该元素固定在距离页面顶部 200 像素的位置。但如果场景是我们需要把元素固定在左侧而不是顶部又该怎么办呢?这时使用动态参数就可以非常方便地根据每个组件实例来进行更新。
```html
<div id="dynamicexample">
<h3>Scroll down inside this section ↓</h3>
<p v-pin:[direction]="200">I am pinned onto the page at 200px to the left.</p>
</div>
<script>
Vue.directive('pin', {
bind: function (el, binding, vnode) {
el.style.position = 'fixed'
var s = (binding.arg == 'left' ? 'left' : 'top')
el.style[s] = binding.value + 'px'
}
})
new Vue({
el: '#dynamicexample',
data: function () {
return {
direction: 'left'
}
}
})</script>
```
### 4、函数简写
我们之前都是在自定义指令名称的后面跟上一个对象,里面写上 bind,inserted,update的钩子函数列表。
现在简写的话,就不需要跟上一个对象了:
```js
directives: {
"color": (el, binding) => {
el.style.color = binding.value;
}
}
```
自定义名称后可以直接跟上一个匿名函数,这个匿名函数就`相当于bind和update的钩子函数集合`。所以,如果你只需要在bind或者update中进行元素的设置的话,就可以用这种简写的方式。
当然如果是inserted的话,还是要写回对象的方式。
### 5、对象字面量
如果指令需要多个值,可以传入一个 JavaScript 对象字面量。记住,指令函数能够接受所有合法的 JavaScript 表达式。
```html
<div v-demo="{ color: 'white', text: 'hello!' }"></div>
<script>
Vue.directive('demo', function (el, binding) {
console.log(binding.value.color) // => "white"
console.log(binding.value.text) // => "hello!"
})
</script>
```
| Daotin/Web/12-Vue/02-过滤器,按键修饰符,自定义指令.md/0 | {
"file_path": "Daotin/Web/12-Vue/02-过滤器,按键修饰符,自定义指令.md",
"repo_id": "Daotin",
"token_count": 12443
} | 23 |
## 一、模板式表单
模板式表单常用于form表单,用于注册登录等表单提交。
模板式表单需要引入模板式表单模块,这个模块在项目创建时会自动引入。
```js
imports: [
FormsModule,
],
```
创建一个login组件进行示例:
```html
<form>
<div>用户名:<input type="text"></div>
<div>密码:<input type="text"></div>
<input type="submit" value="登录">
</form>
```
> 1、只要创建了form表单,就会自动被FormsModule模块接管。
>
> 2、如果创建的不是form表单(比如div),如果想让这个div被模板式表单接管,需要指令 `ngForm` 将标签标识为模板式表单。
```html
<div ngForm>
<div>用户名:<input type="text"></div>
<div>密码:<input type="text"></div>
<input type="submit" value="登录">
</div>
```
form表单自带的submit也会被angular的`ngSubmit`事件接管。
```html
<form (ngSubmit)="getData()">
<div>用户名:<input type="text"></div>
<div>密码:<input type="text"></div>
<input type="submit" value="登录">
</form>
```
**如何获取表单的值?**
- 通过ngModel将各个input挂载到myForm(input必须有name属性)
- form表单定义变量mgForm为ngForm,用来操作表单
- ngSubmit触发函数getData的参数mgForm.value即是所有表单的值的集合,是一个对象。
```html
<form (ngSubmit)="getData(mgForm.value)" #mgForm="ngForm">
<div>用户名:<input type="text" name="user" ngModel></div>
<div>密码:<input type="text" name="pwd" ngModel></div>
<input type="submit" value="登录">
</form>
```
由于定义的变量myForm只能在模板中被访问到,控制器想访问只能通过参数传递,所以叫模板式表单。
**可以直接在页面显示form表单值的对象:**
```html
<form (ngSubmit)="getData(mgForm.value)" #mgForm="ngForm">
<div>用户名:<input type="text" name="user" ngModel></div>
<div>密码:<input type="text" name="pwd" ngModel></div>
<input type="submit" value="登录">
<!-- 直接显示 (json为内置管道)-->
{{myForm.value | json}}
</form>
```
**也可以将表单中各个input的值进行分组:**
使用`ngModelGroup`分组:
```html
<form (ngSubmit)="getData(mgForm.value)" #mgForm="ngForm">
<div>用户名:<input type="text" name="user" ngModel></div>
<div ngModelGroup="pwdGroup">
<div>密码:<input type="text" name="pwd" ngModel></div>
<div>确认密码:<input type="text" name="pwd2" ngModel></div>
</div>
<input type="submit" value="登录">
</form>
```
未分组的时候:`{user: "", pwd: "", pwd2: ""}`
分组后:`{user: "", pwdGroup: {pwd: "", pwd2: ""}}`
## 二、继续响应式表单
之前只是简单的一个input标签,现在是一个表单集合,如何使用响应式表单进行数据的获取和提交。
**响应式表单和模板式表单对比:**
模板式表单很难做到在控制器中实时监听表单数据的变化,只能在提交的时候将数据传回给控制器,但是响应式表单可以做到实时监听表单数据的变化。
### 1、一个完整的响应式表单
#### 1.1、在主模块引入`ReactiveFormsModule`响应式表单模块
#### 1.2、在控制器定义表单数据模型:
```typescript
loginForm: FormGroup = new FormGroup({
user: new FormControl('Daotin'),
pwdGroup: new FormGroup({
pwd: new FormControl(),
pwd2: new FormControl()
})
});
```
#### 1.3、映射到视图
- 表单数据模型loginForm映射到formGroup
- 分组pwdGroup映射到formGroupName
- 单个表单映射到formControlName
```html
<form [formGroup]="loginForm">
<div>用户名:<input type="text" formControlName="user"></div>
<div formGroupName="pwdGroup">
<div>密码:<input type="text" formControlName="pwd"></div>
<div>确认密码:<input type="text" formControlName="pwd2"></div>
</div>
<input type="submit" value="登录">
</form>
```
#### 1.4、点击提交获取表单数据
给表单添加submit事件:
```html
<form [formGroup]="loginForm" (submit)="getData()">
<div>用户名:<input type="text" formControlName="user"></div>
<div formGroupName="pwdGroup">
<div>密码:<input type="text" formControlName="pwd"></div>
<div>确认密码:<input type="text" formControlName="pwd2"></div>
</div>
<input type="submit" value="登录">
</form>
```
```js
getData() {
// 通过表单数据模型的value获取表单的数据
console.log(this.loginForm.value);
}
```
### 2、其他获取表单的值
> **获取表单中单个的值**:`this.loginForm.get('user').value`
>
> **监听表单中单个的值的变化**:`this.loginForm.get('user').valueChanges.subscribe(value => {})`
>
> **监听整个表单任意值的变化**:`this.loginForm.valueChanges.subscribe(obj => { })`
### 3、表单的个数不确定
现在有两个按钮,一个添加,一个删除,用来动态添加或删除邮箱表单。
由于邮箱的表单的个数不确定,所以会用到`FromArray`。
#### 3.1、定义emails数据模型
```js
loginForm: FormGroup = new FormGroup({
user: new FormControl('Daotin'),
pwdGroup: new FormGroup({
pwd: new FormControl(),
pwd2: new FormControl()
}),
// emails数据模型
emails: new FormArray([
new FormControl(),
])
});
```
#### 3.2、绑定数据模型到视图
```html
<div formArrayName="emails">
<div *ngFor="let item of loginForm.get('emails').controls; let i = index">
邮箱{{i+1}}:<input type="text" [formControlName]="i">
</div>
</div>
<button (click)="addEmail()">添加邮箱</button>
<button (click)="delEmail()">删除邮箱</button>
```
> emails的数组通过`loginForm.get('emails').controls` 获取。
>
> email表单formContril绑定的是索引index。
#### 3.3、点击按钮添加删除邮箱
```js
addEmail() {
// 由于只有FormArray有push方法(这个push不是数组中的push,而是由FormArray对象提供的方法),
// 所以 as FormArray 表示:声明返回值为FormArray类型
let emailsArray = this.loginForm.get('emails') as FormArray;
// 添加一个邮箱
emailsArray.push(new FormControl());
}
delEmail() {
let emailsArray = this.loginForm.get('emails') as FormArray;
// 移除最后一个邮箱
emailsArray.removeAt(emailsArray.length - 1);
}
```
| Daotin/Web/14-Angular/08-模板式表单,响应式表单2.md/0 | {
"file_path": "Daotin/Web/14-Angular/08-模板式表单,响应式表单2.md",
"repo_id": "Daotin",
"token_count": 3570
} | 24 |
/**
* po是持久层
*
* @author 何明胜
*
* 2017年10月18日
*/
package pers.husen.web.bean.po; | Humsen/web/web-core/src/pers/husen/web/bean/po/package-info.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/bean/po/package-info.java",
"repo_id": "Humsen",
"token_count": 54
} | 25 |
package pers.husen.web.common.handler;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pers.husen.web.common.helper.StackTrace2Str;
import pers.husen.web.config.ProjectDeployConfig;
/**
* @author 何明胜
*
* 2017年9月29日
*/
public class FileUploadHandler {
private final Logger logger = LogManager.getLogger(FileUploadHandler.class.getName());
public String fileUploadHandler(HttpServletRequest request) {
//得到上传文件的保存目录,将上传的文件存放于工程文件的兄弟级文件download目录下
String saveFile = ProjectDeployConfig.DOWNLOAD_PATH;
File file = new File(saveFile);
//判断上传文件的保存目录是否存在
if (!file.exists() && !file.isDirectory()) {
logger.info(saveFile+"目录不存在,已经创建");
//创建目录
file.mkdir();
}
try{
//使用Apache文件上传组件处理文件上传步骤:
//1、创建一个DiskFileItemFactory工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//2、创建一个文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factory);
//解决上传文件名的中文乱码
upload.setHeaderEncoding("UTF-8");
//3、判断提交上来的数据是否是上传表单的数据
if(!ServletFileUpload.isMultipartContent(request)){
//按照传统方式获取数据
return null;
}
//4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){
//如果fileitem中封装的是普通输入项的数据
if(item.isFormField()){
String name = item.getFieldName();
//解决普通输入项的数据的中文乱码问题
String value = item.getString("UTF-8");
logger.info("普通表单(暂不处理):" + name + "=" + value);
}else{//如果fileitem中封装的是上传文件
//得到上传的文件名称,
String filename = item.getName();
if(filename==null || filename.trim().equals("")){
continue;
}
//注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如: c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt
//处理获取到的上传文件的文件名的路径部分,只保留文件名部分
filename = filename.substring(filename.lastIndexOf("\\")+1);
//判断文件是否已经存在
while(true) {
File tempFile = new File(saveFile + "/" + filename);
if(tempFile.exists()) {
//获取扩展名
int index = filename.lastIndexOf(".");
String fileHeadName = filename.substring(0, index);
String fileBackName = filename.substring(index+1);
//重命名文件名
filename = fileHeadName + "1." + fileBackName;
}else {
break;
}
}
//获取item中的上传文件的输入流
InputStream in = item.getInputStream();
//创建一个文件输出流
FileOutputStream out = new FileOutputStream(saveFile + "/" + filename);
//创建一个缓冲区
byte[] buffer = new byte[1024];
//判断输入流中的数据是否已经读完的标识
int len = 0;
//循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
while((len=in.read(buffer))>0){
//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
out.write(buffer, 0, len);
}
//关闭输入流
in.close();
//关闭输出流
out.close();
//删除处理文件上传时生成的临时文件
item.delete();
logger.info("上传文件名称:"+filename);
return filename;
}
}
}catch (Exception e) {
logger.error(StackTrace2Str.exceptionStackTrace2Str(e));
}
return null;
}
} | Humsen/web/web-core/src/pers/husen/web/common/handler/FileUploadHandler.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/common/handler/FileUploadHandler.java",
"repo_id": "Humsen",
"token_count": 3195
} | 26 |
package pers.husen.web.config.filter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* 错误捕获
*
* @author 何明胜
* <p>
* 2017年11月7日
*/
public class ExceptionFilter implements Filter {
private final Logger logger = LogManager.getLogger(ExceptionFilter.class);
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
try {
chain.doFilter(request, response);
} catch (Exception e) {
logger.error(e);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {}
} | Humsen/web/web-core/src/pers/husen/web/config/filter/ExceptionFilter.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/config/filter/ExceptionFilter.java",
"repo_id": "Humsen",
"token_count": 346
} | 27 |
package pers.husen.web.dao.impl;
import java.util.ArrayList;
import java.util.Date;
import pers.husen.web.bean.vo.FileDownloadVo;
import pers.husen.web.dao.FileDownloadDao;
import pers.husen.web.dbutil.DbQueryUtils;
import pers.husen.web.dbutil.DbManipulationUtils;
/**
* @author 何明胜
*
* 2017年9月29日
*/
public class FileDownloadDaoImpl implements FileDownloadDao {
@Override
public int queryFileTotalCount() {
String sql = "SELECT count(*) as count FROM file_download";
ArrayList<Object> paramList = new ArrayList<Object>();
return DbQueryUtils.queryIntByParam(sql, paramList);
}
@Override
public ArrayList<FileDownloadVo> queryFileDownlaodPerPage(int pageSize, int pageNo) {
String sql = "SELECT file_id, file_name, file_url, file_upload_date, file_download_count FROM file_download" + " ORDER BY file_download_count DESC LIMIT " + pageSize + " OFFSET "
+ (pageNo - 1) * pageSize;
ArrayList<Object> paramList = new ArrayList<Object>();
return DbQueryUtils.queryBeanListByParam(sql, paramList, FileDownloadVo.class);
}
@Override
public FileDownloadVo queryPerFileById(int fileId) {
String sql = "SELECT file_id, file_name, file_url, file_upload_date, file_download_count FROM file_download" + " WHERE file_id = ? ";
ArrayList<Object> paramList = new ArrayList<Object>();
paramList.add(fileId);
return DbQueryUtils.queryBeanListByParam(sql, paramList, FileDownloadVo.class).get(0);
}
@Override
public int insertFileDownload(FileDownloadVo fVo) {
String sql = "INSERT INTO file_download (file_name, file_url, file_upload_date, file_download_count) VALUES (?, ?, ?, ?)";
ArrayList<Object> paramList = new ArrayList<Object>();
Object obj = null;
paramList.add((obj = fVo.getFileName()) != null ? obj : new Date());
paramList.add((obj = fVo.getFileUrl()) != null ? obj : "");
paramList.add((obj = fVo.getFileUploadDate()) != null ? obj : "");
paramList.add(fVo.getFileDownloadCount());
return DbManipulationUtils.insertNewRecord(sql, paramList);
}
@Override
public int updateFileDownCountByUrl(String fileUrl) {
ArrayList<Object> paramList = new ArrayList<Object>();
String selectSql = "SELECT file_download_count FROM file_download WHERE file_url = ?";
paramList.add(fileUrl);
FileDownloadVo fileDownloadVo = DbQueryUtils.queryBeanListByParam(selectSql, paramList, FileDownloadVo.class).get(0);
int fileDownloadCount = fileDownloadVo.getFileDownloadCount() + 1;
String sql = "UPDATE file_download SET file_download_count = ? WHERE file_url = ?";
paramList.clear();
paramList.add(fileDownloadCount);
paramList.add(fileUrl);
return DbManipulationUtils.updateRecordByParam(sql, paramList);
}
} | Humsen/web/web-core/src/pers/husen/web/dao/impl/FileDownloadDaoImpl.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dao/impl/FileDownloadDaoImpl.java",
"repo_id": "Humsen",
"token_count": 936
} | 28 |
package pers.husen.web.dbutil.mappingdb;
/**
* 图片上传数据库
*
* @author 何明胜
*
* 2017年10月20日
*/
public class ImageUploadMapping {
/**
* 数据库名称
*/
public static String DB_NAME = "image_upload";
} | Humsen/web/web-core/src/pers/husen/web/dbutil/mappingdb/ImageUploadMapping.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dbutil/mappingdb/ImageUploadMapping.java",
"repo_id": "Humsen",
"token_count": 110
} | 29 |
package pers.husen.web.servlet;
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 pers.husen.web.common.constants.RequestConstants;
import pers.husen.web.service.BlogArticleSvc;
import pers.husen.web.service.CodeLibrarySvc;
/**
* 删除文章
*
* @author 何明胜
*
* 2017年11月8日
*/
@WebServlet(urlPatterns = "/article/delete.hms")
public class ArticleDeleteSvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public ArticleDeleteSvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String requestType = request.getParameter("type");
/** 如果是删除博客 */
String logicDeleteBlog = RequestConstants.REQUEST_TYPE_LOGIC_DELETE + RequestConstants.MODE_BLOG;
if(logicDeleteBlog.equals(requestType)) {
int blogId = Integer.parseInt(request.getParameter("blogId"));
BlogArticleSvc bSvc = new BlogArticleSvc();
int result = bSvc.logicDeleteBlogById(blogId);
out.println(result);
return;
}
/** 如果是删除代码 */
String logicDeleteCode = RequestConstants.REQUEST_TYPE_LOGIC_DELETE + RequestConstants.MODE_CODE;
if(logicDeleteCode.equals(requestType)) {
int codeId = Integer.parseInt(request.getParameter("codeId"));
CodeLibrarySvc cSvc = new CodeLibrarySvc();
int result = cSvc.logicDeleteCodeById(codeId);
out.println(result);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/ArticleDeleteSvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/ArticleDeleteSvt.java",
"repo_id": "Humsen",
"token_count": 711
} | 30 |
package pers.husen.web.servlet.module;
import java.io.IOException;
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 pers.husen.web.common.constants.ResponseConstants;
import pers.husen.web.common.helper.ReadH5Helper;
/**
* @desc 代码模块
*
* @author 何明胜
*
* @created 2017年12月20日 下午9:32:59
*/
@WebServlet(urlPatterns = "/module/code.hms")
public class CodeModuleSvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public CodeModuleSvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
ReadH5Helper.writeHtmlByName(ResponseConstants.CODE_MODULE_TEMPLATE_PATH, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/module/CodeModuleSvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/module/CodeModuleSvt.java",
"repo_id": "Humsen",
"token_count": 425
} | 31 |
@charset "UTF-8";
.download-div {
padding: 0em 1em !important;
}
.text-align-center {
text-align: center !important;
}
.h3-letter-space {
letter-spacing: 0.05em !important;
padding: 15px 0 5px 0 !important;
height: 45px;
}
#list_file div.col-md-6 {
padding-right: 5px;
padding-left: 5px;
} | Humsen/web/web-mobile/WebContent/css/download/download.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/css/download/download.css",
"repo_id": "Humsen",
"token_count": 130
} | 32 |
@charset "UTF-8";
.modify-userinfo-form {
margin-top: 50px;
}
.up-img-hidden {
padding-top: 30px;
display: none !important;
}
.btn-chang-head-img {
margin-top: 30px;
}
.head-img-size {
width: 80px;
height: 80px;
} | Humsen/web/web-mobile/WebContent/css/personal_center/modify-userinfo.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/css/personal_center/modify-userinfo.css",
"repo_id": "Humsen",
"token_count": 107
} | 33 |
/**
* @desc 首页
*
* @author 何明胜
*
* @created 2018年1月12日 下午3:24:11
*/
/** 加载插件 */
$.ajax({
url : '/plugins/plugins.html',
async : false,
type : 'GET',
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);
}
});
});
$(document).ready(function() {
// 每隔3秒自动轮播
$('#indexCarousel').carousel({
interval : 3000
});
}); | Humsen/web/web-mobile/WebContent/js/index/index.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/js/index/index.js",
"repo_id": "Humsen",
"token_count": 457
} | 34 |
/**
* 个人中心的js
*
* @author 何明胜
*
* 2017年10月17日
*/
$(function() {
/** 顶部导航栏 **/
$.ajax({
url : '/module/navigation/topbar.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$(document.body).prepend(data);
}
});
/** 登录控制 **/
$.ajax({
url : '/module/login/login.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$(document.body).prepend(data);
}
});
});
/** 初始化 */
$(function() {
// 调整顶部导航的宽度
$('#topBar').css('width', '100%');
/** 手机隐藏右边导航 */
var mobile_flag = $.isMobile(); // false为PC端,true为手机端
if (mobile_flag) {
// 右边导航栏隐藏
$('#rightBar').hide();
// 顶部调节排版
$('.access-today').css('margin-left', 0);
$('.online-current').css('margin-left', '32px');
}
// 添加返回首页按钮
$('.choose-theme')
.append(
'<a class="btn btn-warning btn-xs return-index-blank" href="/" role="button">返回首页</a>');
// 加载网站管理
loadAdminManageMenu();
});
/**
* 注册点击事件
*
* @returns
*/
$(function() {
$('#editorVerFeature').click(editVerFeature);
$('#showuserinfo').click(showUserInfo);
$('#edituserinfo').click(editUserInfo);
$('#modifypassword').click(modifyPassword);
$('#btn_modifyEmail').click(modifyEmail);
$('#btn_uploadFile').click(uploadFile);
});
/**
* 根据用户级别加载管理员的网站管理
*
* @returns
*/
function loadAdminManageMenu() {
if ($.cookie('username') == 'husen') {
$('#menunav')
.append(
'<!-- 站长才有 -->'
+ '<li><a href="#webManagement" class="nav-header collapsed"'
+ 'data-toggle="collapse"> <i class="glyphicon glyphicon-cog"></i> 网站管理<span'
+ ' class="pull-right glyphicon glyphicon-chevron-down"></span>'
+ '</a>'
+ '<ul id="webManagement" class="nav nav-list collapse secondmenu">'
+ '<li><a href="/editor/article.hms" target="_blank"><i class="glyphicon glyphicon-user"></i> 写新博客</a></li>'
+ '<li><a href="/editor/article.hms" target="_blank"><i class="glyphicon glyphicon-th-list"></i> 写新代码库</a></li>'
+ '<li><a href="#" id="btn_uploadFile"><i class="glyphicon glyphicon-asterisk"></i> 上传新文件</a></li>'
+ '<li><a href="#" id="editorVerFeature"><i class="glyphicon glyphicon-edit"></i> 编辑新版特性</a></li>'
+ '<li><a href="#"><i class="glyphicon glyphicon-eye-open"></i> 查看所有用户</a></li>'
+ '</ul>' + '</li>');
} else {
$('#menunav')
.append(
'<!-- 站长才有 -->'
+ '<li><a href="#webManagement" class="nav-header collapsed"'
+ 'data-toggle="collapse"> <i class="glyphicon glyphicon-cog"></i> 新文章 & 新文件<span'
+ ' class="pull-right glyphicon glyphicon-chevron-down"></span>'
+ '</a>'
+ '<ul id="webManagement" class="nav nav-list collapse secondmenu">'
+ '<li><a href="/upload/editor_article.jsp" target="_blank"><i class="glyphicon glyphicon-user"></i> 写新博客</a></li>'
+ '<li><a href="/upload/editor_article.jsp" target="_blank"><i class="glyphicon glyphicon-th-list"></i> 写新代码库</a></li>'
+ '<li><a href="#" id="btn_uploadFile"><i class="glyphicon glyphicon-asterisk"></i> 上传新文件</a></li>'
+ '<li><a href="#"><i class="glyphicon glyphicon-eye-open"></i> 查看所有用户</a></li>'
+ '</ul>' + '</li>');
}
}
/**
* 修改密码点击
*
* @returns
*/
function modifyPassword() {
if (isNotLogin()) {
return;
}
$('#mainWindow').html('');
$.ajax({
url : '/personal_center/modify_pwd.html',
async : false,
type : 'GET',
success : function(data) {
$('#mainWindow').html(data);
}
});
}
/**
* 判断是否登录
*
* @returns
*/
function isNotLogin() {
if (!$.cookie('username')) {
$.confirm({
title : false,
content : '请先登录!',
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
return true;
}
return false;
}
/**
* 显示用户信息
*
* @returns
*/
function showUserInfo() {
if (isNotLogin()) {
return;
}
$
.ajax({
type : 'POST',
async : false,
url : '/userInfo.hms',
dataType : 'json',
data : {
type : 'query_user_info',
userName : $.cookie('username')
},
success : function(response) {
$('#mainWindow').html('');
$('#mainWindow')
.append(
'<form class="form-horizontal form-show-userinfo">'
+ '<div class="form-group">'
+ ' <label class="col-sm-4 control-label">头像</label>'
+ ' <div class="col-sm-8">'
+ '<img src="'
+ response.userHeadUrl
+ '" alt=""'
+ 'class="img-circle img-user-head">'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<label class="col-sm-4 control-label">用户名(用作登录)</label>'
+ '<div class="col-sm-8">'
+ '<p class="form-control-static form-show-p">'
+ response.userName
+ '</p>'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<label class="col-sm-4 control-label">用户昵称(用作显示)</label>'
+ '<div class="col-sm-8">'
+ '<p class="form-control-static form-show-p">'
+ response.userNickName
+ '</p>'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<label class="col-sm-4 control-label">邮箱</label>'
+ '<div class="col-sm-8">'
+ '<p class="form-control-static form-show-p">'
+ response.userEmail
+ '</p>'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<label class="col-sm-4 control-label">手机</label>'
+ '<div class="col-sm-8">'
+ '<p class="form-control-static form-show-p">'
+ response.userPhone
+ '</p>'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<label class="col-sm-4 control-label">年龄</label>'
+ '<div class="col-sm-8">'
+ '<p class="form-control-static form-show-p">'
+ response.userAge
+ '</p>'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<label class="col-sm-4 control-label">地址</label>'
+ '<div class="col-sm-8">'
+ '<p class="form-control-static form-show-p">'
+ response.userAddress
+ '</p>'
+ '</div>' + '</div>' + '</form>');
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '用户信息加载出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|1000',
type : 'green',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
/**
* 编辑用户信息
*
* @returns
*/
function editUserInfo() {
if (isNotLogin()) {
return;
}
$('#mainWindow').html('');
$.ajax({
url : '/personal_center/modify_userinfo.html',
async : false,
type : 'GET',
success : function(data) {
$('#mainWindow').html(data);
}
});
}
/**
* 编辑新版特性点击事件
*
* @returns
*/
function editVerFeature() {
$('#mainWindow').html('');
$.ajax({
url : '/personal_center/editor_version.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$('#mainWindow').html(data);
}
});
}
/**
* 修改邮箱点击事件
*
* @returns
*/
function modifyEmail() {
if (isNotLogin()) {
return;
}
$('#mainWindow').html('');
$.ajax({
url : '/personal_center/modify_email.html', // 这里是静态页的地址
async : false,
type : 'GET', // 静态页用get方法,否则服务器会抛出405错误
success : function(data) {
$('#mainWindow').html(data);
}
});
}
/**
* 上传新文件点击事件
*
* @returns
*/
function uploadFile() {
$('#mainWindow').html('');
$.ajax({
url : '/personal_center/upload_file.html',
async : false,
type : 'GET',
success : function(data) {
$('#mainWindow').html(data);
}
});
} | Humsen/web/web-mobile/WebContent/js/personal_center/personal-center.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/js/personal_center/personal-center.js",
"repo_id": "Humsen",
"token_count": 4576
} | 35 |
/*!
* Bootstrap v3.3.7 (http://getbootstrap.com)
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
html {
font-family: sans-serif;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
body {
margin: 0;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
audio,
canvas,
progress,
video {
display: inline-block;
vertical-align: baseline;
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden],
template {
display: none;
}
a {
background-color: transparent;
}
a:active,
a:hover {
outline: 0;
}
abbr[title] {
border-bottom: 1px dotted;
}
b,
strong {
font-weight: bold;
}
dfn {
font-style: italic;
}
h1 {
margin: .67em 0;
font-size: 2em;
}
mark {
color: #000;
background: #ff0;
}
small {
font-size: 80%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sup {
top: -.5em;
}
sub {
bottom: -.25em;
}
img {
border: 0;
}
svg:not(:root) {
overflow: hidden;
}
figure {
margin: 1em 40px;
}
hr {
height: 0;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
pre {
overflow: auto;
}
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
button,
input,
optgroup,
select,
textarea {
margin: 0;
font: inherit;
color: inherit;
}
button {
overflow: visible;
}
button,
select {
text-transform: none;
}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
cursor: pointer;
}
button[disabled],
html input[disabled] {
cursor: default;
}
button::-moz-focus-inner,
input::-moz-focus-inner {
padding: 0;
border: 0;
}
input {
line-height: normal;
}
input[type="checkbox"],
input[type="radio"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
input[type="search"] {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
-webkit-appearance: textfield;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
fieldset {
padding: .35em .625em .75em;
margin: 0 2px;
border: 1px solid #c0c0c0;
}
legend {
padding: 0;
border: 0;
}
textarea {
overflow: auto;
}
optgroup {
font-weight: bold;
}
table {
border-spacing: 0;
border-collapse: collapse;
}
td,
th {
padding: 0;
}
/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
@media print {
*,
*:before,
*:after {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
.navbar {
display: none;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table td,
.table th {
background-color: #fff !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}
.glyphicon {
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.glyphicon-asterisk:before {
content: "\002a";
}
.glyphicon-plus:before {
content: "\002b";
}
.glyphicon-euro:before,
.glyphicon-eur:before {
content: "\20ac";
}
.glyphicon-minus:before {
content: "\2212";
}
.glyphicon-cloud:before {
content: "\2601";
}
.glyphicon-envelope:before {
content: "\2709";
}
.glyphicon-pencil:before {
content: "\270f";
}
.glyphicon-glass:before {
content: "\e001";
}
.glyphicon-music:before {
content: "\e002";
}
.glyphicon-search:before {
content: "\e003";
}
.glyphicon-heart:before {
content: "\e005";
}
.glyphicon-star:before {
content: "\e006";
}
.glyphicon-star-empty:before {
content: "\e007";
}
.glyphicon-user:before {
content: "\e008";
}
.glyphicon-film:before {
content: "\e009";
}
.glyphicon-th-large:before {
content: "\e010";
}
.glyphicon-th:before {
content: "\e011";
}
.glyphicon-th-list:before {
content: "\e012";
}
.glyphicon-ok:before {
content: "\e013";
}
.glyphicon-remove:before {
content: "\e014";
}
.glyphicon-zoom-in:before {
content: "\e015";
}
.glyphicon-zoom-out:before {
content: "\e016";
}
.glyphicon-off:before {
content: "\e017";
}
.glyphicon-signal:before {
content: "\e018";
}
.glyphicon-cog:before {
content: "\e019";
}
.glyphicon-trash:before {
content: "\e020";
}
.glyphicon-home:before {
content: "\e021";
}
.glyphicon-file:before {
content: "\e022";
}
.glyphicon-time:before {
content: "\e023";
}
.glyphicon-road:before {
content: "\e024";
}
.glyphicon-download-alt:before {
content: "\e025";
}
.glyphicon-download:before {
content: "\e026";
}
.glyphicon-upload:before {
content: "\e027";
}
.glyphicon-inbox:before {
content: "\e028";
}
.glyphicon-play-circle:before {
content: "\e029";
}
.glyphicon-repeat:before {
content: "\e030";
}
.glyphicon-refresh:before {
content: "\e031";
}
.glyphicon-list-alt:before {
content: "\e032";
}
.glyphicon-lock:before {
content: "\e033";
}
.glyphicon-flag:before {
content: "\e034";
}
.glyphicon-headphones:before {
content: "\e035";
}
.glyphicon-volume-off:before {
content: "\e036";
}
.glyphicon-volume-down:before {
content: "\e037";
}
.glyphicon-volume-up:before {
content: "\e038";
}
.glyphicon-qrcode:before {
content: "\e039";
}
.glyphicon-barcode:before {
content: "\e040";
}
.glyphicon-tag:before {
content: "\e041";
}
.glyphicon-tags:before {
content: "\e042";
}
.glyphicon-book:before {
content: "\e043";
}
.glyphicon-bookmark:before {
content: "\e044";
}
.glyphicon-print:before {
content: "\e045";
}
.glyphicon-camera:before {
content: "\e046";
}
.glyphicon-font:before {
content: "\e047";
}
.glyphicon-bold:before {
content: "\e048";
}
.glyphicon-italic:before {
content: "\e049";
}
.glyphicon-text-height:before {
content: "\e050";
}
.glyphicon-text-width:before {
content: "\e051";
}
.glyphicon-align-left:before {
content: "\e052";
}
.glyphicon-align-center:before {
content: "\e053";
}
.glyphicon-align-right:before {
content: "\e054";
}
.glyphicon-align-justify:before {
content: "\e055";
}
.glyphicon-list:before {
content: "\e056";
}
.glyphicon-indent-left:before {
content: "\e057";
}
.glyphicon-indent-right:before {
content: "\e058";
}
.glyphicon-facetime-video:before {
content: "\e059";
}
.glyphicon-picture:before {
content: "\e060";
}
.glyphicon-map-marker:before {
content: "\e062";
}
.glyphicon-adjust:before {
content: "\e063";
}
.glyphicon-tint:before {
content: "\e064";
}
.glyphicon-edit:before {
content: "\e065";
}
.glyphicon-share:before {
content: "\e066";
}
.glyphicon-check:before {
content: "\e067";
}
.glyphicon-move:before {
content: "\e068";
}
.glyphicon-step-backward:before {
content: "\e069";
}
.glyphicon-fast-backward:before {
content: "\e070";
}
.glyphicon-backward:before {
content: "\e071";
}
.glyphicon-play:before {
content: "\e072";
}
.glyphicon-pause:before {
content: "\e073";
}
.glyphicon-stop:before {
content: "\e074";
}
.glyphicon-forward:before {
content: "\e075";
}
.glyphicon-fast-forward:before {
content: "\e076";
}
.glyphicon-step-forward:before {
content: "\e077";
}
.glyphicon-eject:before {
content: "\e078";
}
.glyphicon-chevron-left:before {
content: "\e079";
}
.glyphicon-chevron-right:before {
content: "\e080";
}
.glyphicon-plus-sign:before {
content: "\e081";
}
.glyphicon-minus-sign:before {
content: "\e082";
}
.glyphicon-remove-sign:before {
content: "\e083";
}
.glyphicon-ok-sign:before {
content: "\e084";
}
.glyphicon-question-sign:before {
content: "\e085";
}
.glyphicon-info-sign:before {
content: "\e086";
}
.glyphicon-screenshot:before {
content: "\e087";
}
.glyphicon-remove-circle:before {
content: "\e088";
}
.glyphicon-ok-circle:before {
content: "\e089";
}
.glyphicon-ban-circle:before {
content: "\e090";
}
.glyphicon-arrow-left:before {
content: "\e091";
}
.glyphicon-arrow-right:before {
content: "\e092";
}
.glyphicon-arrow-up:before {
content: "\e093";
}
.glyphicon-arrow-down:before {
content: "\e094";
}
.glyphicon-share-alt:before {
content: "\e095";
}
.glyphicon-resize-full:before {
content: "\e096";
}
.glyphicon-resize-small:before {
content: "\e097";
}
.glyphicon-exclamation-sign:before {
content: "\e101";
}
.glyphicon-gift:before {
content: "\e102";
}
.glyphicon-leaf:before {
content: "\e103";
}
.glyphicon-fire:before {
content: "\e104";
}
.glyphicon-eye-open:before {
content: "\e105";
}
.glyphicon-eye-close:before {
content: "\e106";
}
.glyphicon-warning-sign:before {
content: "\e107";
}
.glyphicon-plane:before {
content: "\e108";
}
.glyphicon-calendar:before {
content: "\e109";
}
.glyphicon-random:before {
content: "\e110";
}
.glyphicon-comment:before {
content: "\e111";
}
.glyphicon-magnet:before {
content: "\e112";
}
.glyphicon-chevron-up:before {
content: "\e113";
}
.glyphicon-chevron-down:before {
content: "\e114";
}
.glyphicon-retweet:before {
content: "\e115";
}
.glyphicon-shopping-cart:before {
content: "\e116";
}
.glyphicon-folder-close:before {
content: "\e117";
}
.glyphicon-folder-open:before {
content: "\e118";
}
.glyphicon-resize-vertical:before {
content: "\e119";
}
.glyphicon-resize-horizontal:before {
content: "\e120";
}
.glyphicon-hdd:before {
content: "\e121";
}
.glyphicon-bullhorn:before {
content: "\e122";
}
.glyphicon-bell:before {
content: "\e123";
}
.glyphicon-certificate:before {
content: "\e124";
}
.glyphicon-thumbs-up:before {
content: "\e125";
}
.glyphicon-thumbs-down:before {
content: "\e126";
}
.glyphicon-hand-right:before {
content: "\e127";
}
.glyphicon-hand-left:before {
content: "\e128";
}
.glyphicon-hand-up:before {
content: "\e129";
}
.glyphicon-hand-down:before {
content: "\e130";
}
.glyphicon-circle-arrow-right:before {
content: "\e131";
}
.glyphicon-circle-arrow-left:before {
content: "\e132";
}
.glyphicon-circle-arrow-up:before {
content: "\e133";
}
.glyphicon-circle-arrow-down:before {
content: "\e134";
}
.glyphicon-globe:before {
content: "\e135";
}
.glyphicon-wrench:before {
content: "\e136";
}
.glyphicon-tasks:before {
content: "\e137";
}
.glyphicon-filter:before {
content: "\e138";
}
.glyphicon-briefcase:before {
content: "\e139";
}
.glyphicon-fullscreen:before {
content: "\e140";
}
.glyphicon-dashboard:before {
content: "\e141";
}
.glyphicon-paperclip:before {
content: "\e142";
}
.glyphicon-heart-empty:before {
content: "\e143";
}
.glyphicon-link:before {
content: "\e144";
}
.glyphicon-phone:before {
content: "\e145";
}
.glyphicon-pushpin:before {
content: "\e146";
}
.glyphicon-usd:before {
content: "\e148";
}
.glyphicon-gbp:before {
content: "\e149";
}
.glyphicon-sort:before {
content: "\e150";
}
.glyphicon-sort-by-alphabet:before {
content: "\e151";
}
.glyphicon-sort-by-alphabet-alt:before {
content: "\e152";
}
.glyphicon-sort-by-order:before {
content: "\e153";
}
.glyphicon-sort-by-order-alt:before {
content: "\e154";
}
.glyphicon-sort-by-attributes:before {
content: "\e155";
}
.glyphicon-sort-by-attributes-alt:before {
content: "\e156";
}
.glyphicon-unchecked:before {
content: "\e157";
}
.glyphicon-expand:before {
content: "\e158";
}
.glyphicon-collapse-down:before {
content: "\e159";
}
.glyphicon-collapse-up:before {
content: "\e160";
}
.glyphicon-log-in:before {
content: "\e161";
}
.glyphicon-flash:before {
content: "\e162";
}
.glyphicon-log-out:before {
content: "\e163";
}
.glyphicon-new-window:before {
content: "\e164";
}
.glyphicon-record:before {
content: "\e165";
}
.glyphicon-save:before {
content: "\e166";
}
.glyphicon-open:before {
content: "\e167";
}
.glyphicon-saved:before {
content: "\e168";
}
.glyphicon-import:before {
content: "\e169";
}
.glyphicon-export:before {
content: "\e170";
}
.glyphicon-send:before {
content: "\e171";
}
.glyphicon-floppy-disk:before {
content: "\e172";
}
.glyphicon-floppy-saved:before {
content: "\e173";
}
.glyphicon-floppy-remove:before {
content: "\e174";
}
.glyphicon-floppy-save:before {
content: "\e175";
}
.glyphicon-floppy-open:before {
content: "\e176";
}
.glyphicon-credit-card:before {
content: "\e177";
}
.glyphicon-transfer:before {
content: "\e178";
}
.glyphicon-cutlery:before {
content: "\e179";
}
.glyphicon-header:before {
content: "\e180";
}
.glyphicon-compressed:before {
content: "\e181";
}
.glyphicon-earphone:before {
content: "\e182";
}
.glyphicon-phone-alt:before {
content: "\e183";
}
.glyphicon-tower:before {
content: "\e184";
}
.glyphicon-stats:before {
content: "\e185";
}
.glyphicon-sd-video:before {
content: "\e186";
}
.glyphicon-hd-video:before {
content: "\e187";
}
.glyphicon-subtitles:before {
content: "\e188";
}
.glyphicon-sound-stereo:before {
content: "\e189";
}
.glyphicon-sound-dolby:before {
content: "\e190";
}
.glyphicon-sound-5-1:before {
content: "\e191";
}
.glyphicon-sound-6-1:before {
content: "\e192";
}
.glyphicon-sound-7-1:before {
content: "\e193";
}
.glyphicon-copyright-mark:before {
content: "\e194";
}
.glyphicon-registration-mark:before {
content: "\e195";
}
.glyphicon-cloud-download:before {
content: "\e197";
}
.glyphicon-cloud-upload:before {
content: "\e198";
}
.glyphicon-tree-conifer:before {
content: "\e199";
}
.glyphicon-tree-deciduous:before {
content: "\e200";
}
.glyphicon-cd:before {
content: "\e201";
}
.glyphicon-save-file:before {
content: "\e202";
}
.glyphicon-open-file:before {
content: "\e203";
}
.glyphicon-level-up:before {
content: "\e204";
}
.glyphicon-copy:before {
content: "\e205";
}
.glyphicon-paste:before {
content: "\e206";
}
.glyphicon-alert:before {
content: "\e209";
}
.glyphicon-equalizer:before {
content: "\e210";
}
.glyphicon-king:before {
content: "\e211";
}
.glyphicon-queen:before {
content: "\e212";
}
.glyphicon-pawn:before {
content: "\e213";
}
.glyphicon-bishop:before {
content: "\e214";
}
.glyphicon-knight:before {
content: "\e215";
}
.glyphicon-baby-formula:before {
content: "\e216";
}
.glyphicon-tent:before {
content: "\26fa";
}
.glyphicon-blackboard:before {
content: "\e218";
}
.glyphicon-bed:before {
content: "\e219";
}
.glyphicon-apple:before {
content: "\f8ff";
}
.glyphicon-erase:before {
content: "\e221";
}
.glyphicon-hourglass:before {
content: "\231b";
}
.glyphicon-lamp:before {
content: "\e223";
}
.glyphicon-duplicate:before {
content: "\e224";
}
.glyphicon-piggy-bank:before {
content: "\e225";
}
.glyphicon-scissors:before {
content: "\e226";
}
.glyphicon-bitcoin:before {
content: "\e227";
}
.glyphicon-btc:before {
content: "\e227";
}
.glyphicon-xbt:before {
content: "\e227";
}
.glyphicon-yen:before {
content: "\00a5";
}
.glyphicon-jpy:before {
content: "\00a5";
}
.glyphicon-ruble:before {
content: "\20bd";
}
.glyphicon-rub:before {
content: "\20bd";
}
.glyphicon-scale:before {
content: "\e230";
}
.glyphicon-ice-lolly:before {
content: "\e231";
}
.glyphicon-ice-lolly-tasted:before {
content: "\e232";
}
.glyphicon-education:before {
content: "\e233";
}
.glyphicon-option-horizontal:before {
content: "\e234";
}
.glyphicon-option-vertical:before {
content: "\e235";
}
.glyphicon-menu-hamburger:before {
content: "\e236";
}
.glyphicon-modal-window:before {
content: "\e237";
}
.glyphicon-oil:before {
content: "\e238";
}
.glyphicon-grain:before {
content: "\e239";
}
.glyphicon-sunglasses:before {
content: "\e240";
}
.glyphicon-text-size:before {
content: "\e241";
}
.glyphicon-text-color:before {
content: "\e242";
}
.glyphicon-text-background:before {
content: "\e243";
}
.glyphicon-object-align-top:before {
content: "\e244";
}
.glyphicon-object-align-bottom:before {
content: "\e245";
}
.glyphicon-object-align-horizontal:before {
content: "\e246";
}
.glyphicon-object-align-left:before {
content: "\e247";
}
.glyphicon-object-align-vertical:before {
content: "\e248";
}
.glyphicon-object-align-right:before {
content: "\e249";
}
.glyphicon-triangle-right:before {
content: "\e250";
}
.glyphicon-triangle-left:before {
content: "\e251";
}
.glyphicon-triangle-bottom:before {
content: "\e252";
}
.glyphicon-triangle-top:before {
content: "\e253";
}
.glyphicon-console:before {
content: "\e254";
}
.glyphicon-superscript:before {
content: "\e255";
}
.glyphicon-subscript:before {
content: "\e256";
}
.glyphicon-menu-left:before {
content: "\e257";
}
.glyphicon-menu-right:before {
content: "\e258";
}
.glyphicon-menu-down:before {
content: "\e259";
}
.glyphicon-menu-up:before {
content: "\e260";
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-size: 10px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333;
background-color: #fff;
}
input,
button,
select,
textarea {
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
a {
color: #337ab7;
text-decoration: none;
}
a:hover,
a:focus {
color: #23527c;
text-decoration: underline;
}
a:focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
figure {
margin: 0;
}
img {
vertical-align: middle;
}
.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
display: block;
max-width: 100%;
height: auto;
}
.img-rounded {
border-radius: 6px;
}
.img-thumbnail {
display: inline-block;
max-width: 100%;
height: auto;
padding: 4px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: all .2s ease-in-out;
-o-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
.img-circle {
border-radius: 50%;
}
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eee;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
.sr-only-focusable:active,
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto;
}
[role="button"] {
cursor: pointer;
}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small,
.h1 small,
.h2 small,
.h3 small,
.h4 small,
.h5 small,
.h6 small,
h1 .small,
h2 .small,
h3 .small,
h4 .small,
h5 .small,
h6 .small,
.h1 .small,
.h2 .small,
.h3 .small,
.h4 .small,
.h5 .small,
.h6 .small {
font-weight: normal;
line-height: 1;
color: #777;
}
h1,
.h1,
h2,
.h2,
h3,
.h3 {
margin-top: 20px;
margin-bottom: 10px;
}
h1 small,
.h1 small,
h2 small,
.h2 small,
h3 small,
.h3 small,
h1 .small,
.h1 .small,
h2 .small,
.h2 .small,
h3 .small,
.h3 .small {
font-size: 65%;
}
h4,
.h4,
h5,
.h5,
h6,
.h6 {
margin-top: 10px;
margin-bottom: 10px;
}
h4 small,
.h4 small,
h5 small,
.h5 small,
h6 small,
.h6 small,
h4 .small,
.h4 .small,
h5 .small,
.h5 .small,
h6 .small,
.h6 .small {
font-size: 75%;
}
h1,
.h1 {
font-size: 36px;
}
h2,
.h2 {
font-size: 30px;
}
h3,
.h3 {
font-size: 24px;
}
h4,
.h4 {
font-size: 18px;
}
h5,
.h5 {
font-size: 14px;
}
h6,
.h6 {
font-size: 12px;
}
p {
margin: 0 0 10px;
}
.lead {
margin-bottom: 20px;
font-size: 16px;
font-weight: 300;
line-height: 1.4;
}
@media (min-width: 768px) {
.lead {
font-size: 21px;
}
}
small,
.small {
font-size: 85%;
}
mark,
.mark {
padding: .2em;
background-color: #fcf8e3;
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-justify {
text-align: justify;
}
.text-nowrap {
white-space: nowrap;
}
.text-lowercase {
text-transform: lowercase;
}
.text-uppercase {
text-transform: uppercase;
}
.text-capitalize {
text-transform: capitalize;
}
.text-muted {
color: #777;
}
.text-primary {
color: #337ab7;
}
a.text-primary:hover,
a.text-primary:focus {
color: #286090;
}
.text-success {
color: #3c763d;
}
a.text-success:hover,
a.text-success:focus {
color: #2b542c;
}
.text-info {
color: #31708f;
}
a.text-info:hover,
a.text-info:focus {
color: #245269;
}
.text-warning {
color: #8a6d3b;
}
a.text-warning:hover,
a.text-warning:focus {
color: #66512c;
}
.text-danger {
color: #a94442;
}
a.text-danger:hover,
a.text-danger:focus {
color: #843534;
}
.bg-primary {
color: #fff;
background-color: #337ab7;
}
a.bg-primary:hover,
a.bg-primary:focus {
background-color: #286090;
}
.bg-success {
background-color: #dff0d8;
}
a.bg-success:hover,
a.bg-success:focus {
background-color: #c1e2b3;
}
.bg-info {
background-color: #d9edf7;
}
a.bg-info:hover,
a.bg-info:focus {
background-color: #afd9ee;
}
.bg-warning {
background-color: #fcf8e3;
}
a.bg-warning:hover,
a.bg-warning:focus {
background-color: #f7ecb5;
}
.bg-danger {
background-color: #f2dede;
}
a.bg-danger:hover,
a.bg-danger:focus {
background-color: #e4b9b9;
}
.page-header {
padding-bottom: 9px;
margin: 40px 0 20px;
border-bottom: 1px solid #eee;
}
ul,
ol {
margin-top: 0;
margin-bottom: 10px;
}
ul ul,
ol ul,
ul ol,
ol ol {
margin-bottom: 0;
}
.list-unstyled {
padding-left: 0;
list-style: none;
}
.list-inline {
padding-left: 0;
margin-left: -5px;
list-style: none;
}
.list-inline > li {
display: inline-block;
padding-right: 5px;
padding-left: 5px;
}
dl {
margin-top: 0;
margin-bottom: 20px;
}
dt,
dd {
line-height: 1.42857143;
}
dt {
font-weight: bold;
}
dd {
margin-left: 0;
}
@media (min-width: 768px) {
.dl-horizontal dt {
float: left;
width: 160px;
overflow: hidden;
clear: left;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.dl-horizontal dd {
margin-left: 180px;
}
}
abbr[title],
abbr[data-original-title] {
cursor: help;
border-bottom: 1px dotted #777;
}
.initialism {
font-size: 90%;
text-transform: uppercase;
}
blockquote {
padding: 10px 20px;
margin: 0 0 20px;
font-size: 17.5px;
border-left: 5px solid #eee;
}
blockquote p:last-child,
blockquote ul:last-child,
blockquote ol:last-child {
margin-bottom: 0;
}
blockquote footer,
blockquote small,
blockquote .small {
display: block;
font-size: 80%;
line-height: 1.42857143;
color: #777;
}
blockquote footer:before,
blockquote small:before,
blockquote .small:before {
content: '\2014 \00A0';
}
.blockquote-reverse,
blockquote.pull-right {
padding-right: 15px;
padding-left: 0;
text-align: right;
border-right: 5px solid #eee;
border-left: 0;
}
.blockquote-reverse footer:before,
blockquote.pull-right footer:before,
.blockquote-reverse small:before,
blockquote.pull-right small:before,
.blockquote-reverse .small:before,
blockquote.pull-right .small:before {
content: '';
}
.blockquote-reverse footer:after,
blockquote.pull-right footer:after,
.blockquote-reverse small:after,
blockquote.pull-right small:after,
.blockquote-reverse .small:after,
blockquote.pull-right .small:after {
content: '\00A0 \2014';
}
address {
margin-bottom: 20px;
font-style: normal;
line-height: 1.42857143;
}
code,
kbd,
pre,
samp {
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}
code {
padding: 2px 4px;
font-size: 90%;
color: #c7254e;
background-color: #f9f2f4;
border-radius: 4px;
}
kbd {
padding: 2px 4px;
font-size: 90%;
color: #fff;
background-color: #333;
border-radius: 3px;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
}
kbd kbd {
padding: 0;
font-size: 100%;
font-weight: bold;
-webkit-box-shadow: none;
box-shadow: none;
}
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
line-height: 1.42857143;
color: #333;
word-break: break-all;
word-wrap: break-word;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px;
}
pre code {
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre-wrap;
background-color: transparent;
border-radius: 0;
}
.pre-scrollable {
max-height: 340px;
overflow-y: scroll;
}
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
.container-fluid {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
.row {
margin-right: -15px;
margin-left: -15px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
position: relative;
min-height: 1px;
padding-right: 15px;
padding-left: 15px;
}
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
float: left;
}
.col-xs-12 {
width: 100%;
}
.col-xs-11 {
width: 91.66666667%;
}
.col-xs-10 {
width: 83.33333333%;
}
.col-xs-9 {
width: 75%;
}
.col-xs-8 {
width: 66.66666667%;
}
.col-xs-7 {
width: 58.33333333%;
}
.col-xs-6 {
width: 50%;
}
.col-xs-5 {
width: 41.66666667%;
}
.col-xs-4 {
width: 33.33333333%;
}
.col-xs-3 {
width: 25%;
}
.col-xs-2 {
width: 16.66666667%;
}
.col-xs-1 {
width: 8.33333333%;
}
.col-xs-pull-12 {
right: 100%;
}
.col-xs-pull-11 {
right: 91.66666667%;
}
.col-xs-pull-10 {
right: 83.33333333%;
}
.col-xs-pull-9 {
right: 75%;
}
.col-xs-pull-8 {
right: 66.66666667%;
}
.col-xs-pull-7 {
right: 58.33333333%;
}
.col-xs-pull-6 {
right: 50%;
}
.col-xs-pull-5 {
right: 41.66666667%;
}
.col-xs-pull-4 {
right: 33.33333333%;
}
.col-xs-pull-3 {
right: 25%;
}
.col-xs-pull-2 {
right: 16.66666667%;
}
.col-xs-pull-1 {
right: 8.33333333%;
}
.col-xs-pull-0 {
right: auto;
}
.col-xs-push-12 {
left: 100%;
}
.col-xs-push-11 {
left: 91.66666667%;
}
.col-xs-push-10 {
left: 83.33333333%;
}
.col-xs-push-9 {
left: 75%;
}
.col-xs-push-8 {
left: 66.66666667%;
}
.col-xs-push-7 {
left: 58.33333333%;
}
.col-xs-push-6 {
left: 50%;
}
.col-xs-push-5 {
left: 41.66666667%;
}
.col-xs-push-4 {
left: 33.33333333%;
}
.col-xs-push-3 {
left: 25%;
}
.col-xs-push-2 {
left: 16.66666667%;
}
.col-xs-push-1 {
left: 8.33333333%;
}
.col-xs-push-0 {
left: auto;
}
.col-xs-offset-12 {
margin-left: 100%;
}
.col-xs-offset-11 {
margin-left: 91.66666667%;
}
.col-xs-offset-10 {
margin-left: 83.33333333%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-8 {
margin-left: 66.66666667%;
}
.col-xs-offset-7 {
margin-left: 58.33333333%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-5 {
margin-left: 41.66666667%;
}
.col-xs-offset-4 {
margin-left: 33.33333333%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-2 {
margin-left: 16.66666667%;
}
.col-xs-offset-1 {
margin-left: 8.33333333%;
}
.col-xs-offset-0 {
margin-left: 0;
}
@media (min-width: 768px) {
.col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
float: left;
}
.col-sm-12 {
width: 100%;
}
.col-sm-11 {
width: 91.66666667%;
}
.col-sm-10 {
width: 83.33333333%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-8 {
width: 66.66666667%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666667%;
}
.col-sm-4 {
width: 33.33333333%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-2 {
width: 16.66666667%;
}
.col-sm-1 {
width: 8.33333333%;
}
.col-sm-pull-12 {
right: 100%;
}
.col-sm-pull-11 {
right: 91.66666667%;
}
.col-sm-pull-10 {
right: 83.33333333%;
}
.col-sm-pull-9 {
right: 75%;
}
.col-sm-pull-8 {
right: 66.66666667%;
}
.col-sm-pull-7 {
right: 58.33333333%;
}
.col-sm-pull-6 {
right: 50%;
}
.col-sm-pull-5 {
right: 41.66666667%;
}
.col-sm-pull-4 {
right: 33.33333333%;
}
.col-sm-pull-3 {
right: 25%;
}
.col-sm-pull-2 {
right: 16.66666667%;
}
.col-sm-pull-1 {
right: 8.33333333%;
}
.col-sm-pull-0 {
right: auto;
}
.col-sm-push-12 {
left: 100%;
}
.col-sm-push-11 {
left: 91.66666667%;
}
.col-sm-push-10 {
left: 83.33333333%;
}
.col-sm-push-9 {
left: 75%;
}
.col-sm-push-8 {
left: 66.66666667%;
}
.col-sm-push-7 {
left: 58.33333333%;
}
.col-sm-push-6 {
left: 50%;
}
.col-sm-push-5 {
left: 41.66666667%;
}
.col-sm-push-4 {
left: 33.33333333%;
}
.col-sm-push-3 {
left: 25%;
}
.col-sm-push-2 {
left: 16.66666667%;
}
.col-sm-push-1 {
left: 8.33333333%;
}
.col-sm-push-0 {
left: auto;
}
.col-sm-offset-12 {
margin-left: 100%;
}
.col-sm-offset-11 {
margin-left: 91.66666667%;
}
.col-sm-offset-10 {
margin-left: 83.33333333%;
}
.col-sm-offset-9 {
margin-left: 75%;
}
.col-sm-offset-8 {
margin-left: 66.66666667%;
}
.col-sm-offset-7 {
margin-left: 58.33333333%;
}
.col-sm-offset-6 {
margin-left: 50%;
}
.col-sm-offset-5 {
margin-left: 41.66666667%;
}
.col-sm-offset-4 {
margin-left: 33.33333333%;
}
.col-sm-offset-3 {
margin-left: 25%;
}
.col-sm-offset-2 {
margin-left: 16.66666667%;
}
.col-sm-offset-1 {
margin-left: 8.33333333%;
}
.col-sm-offset-0 {
margin-left: 0;
}
}
@media (min-width: 992px) {
.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
float: left;
}
.col-md-12 {
width: 100%;
}
.col-md-11 {
width: 91.66666667%;
}
.col-md-10 {
width: 83.33333333%;
}
.col-md-9 {
width: 75%;
}
.col-md-8 {
width: 66.66666667%;
}
.col-md-7 {
width: 58.33333333%;
}
.col-md-6 {
width: 50%;
}
.col-md-5 {
width: 41.66666667%;
}
.col-md-4 {
width: 33.33333333%;
}
.col-md-3 {
width: 25%;
}
.col-md-2 {
width: 16.66666667%;
}
.col-md-1 {
width: 8.33333333%;
}
.col-md-pull-12 {
right: 100%;
}
.col-md-pull-11 {
right: 91.66666667%;
}
.col-md-pull-10 {
right: 83.33333333%;
}
.col-md-pull-9 {
right: 75%;
}
.col-md-pull-8 {
right: 66.66666667%;
}
.col-md-pull-7 {
right: 58.33333333%;
}
.col-md-pull-6 {
right: 50%;
}
.col-md-pull-5 {
right: 41.66666667%;
}
.col-md-pull-4 {
right: 33.33333333%;
}
.col-md-pull-3 {
right: 25%;
}
.col-md-pull-2 {
right: 16.66666667%;
}
.col-md-pull-1 {
right: 8.33333333%;
}
.col-md-pull-0 {
right: auto;
}
.col-md-push-12 {
left: 100%;
}
.col-md-push-11 {
left: 91.66666667%;
}
.col-md-push-10 {
left: 83.33333333%;
}
.col-md-push-9 {
left: 75%;
}
.col-md-push-8 {
left: 66.66666667%;
}
.col-md-push-7 {
left: 58.33333333%;
}
.col-md-push-6 {
left: 50%;
}
.col-md-push-5 {
left: 41.66666667%;
}
.col-md-push-4 {
left: 33.33333333%;
}
.col-md-push-3 {
left: 25%;
}
.col-md-push-2 {
left: 16.66666667%;
}
.col-md-push-1 {
left: 8.33333333%;
}
.col-md-push-0 {
left: auto;
}
.col-md-offset-12 {
margin-left: 100%;
}
.col-md-offset-11 {
margin-left: 91.66666667%;
}
.col-md-offset-10 {
margin-left: 83.33333333%;
}
.col-md-offset-9 {
margin-left: 75%;
}
.col-md-offset-8 {
margin-left: 66.66666667%;
}
.col-md-offset-7 {
margin-left: 58.33333333%;
}
.col-md-offset-6 {
margin-left: 50%;
}
.col-md-offset-5 {
margin-left: 41.66666667%;
}
.col-md-offset-4 {
margin-left: 33.33333333%;
}
.col-md-offset-3 {
margin-left: 25%;
}
.col-md-offset-2 {
margin-left: 16.66666667%;
}
.col-md-offset-1 {
margin-left: 8.33333333%;
}
.col-md-offset-0 {
margin-left: 0;
}
}
@media (min-width: 1200px) {
.col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
float: left;
}
.col-lg-12 {
width: 100%;
}
.col-lg-11 {
width: 91.66666667%;
}
.col-lg-10 {
width: 83.33333333%;
}
.col-lg-9 {
width: 75%;
}
.col-lg-8 {
width: 66.66666667%;
}
.col-lg-7 {
width: 58.33333333%;
}
.col-lg-6 {
width: 50%;
}
.col-lg-5 {
width: 41.66666667%;
}
.col-lg-4 {
width: 33.33333333%;
}
.col-lg-3 {
width: 25%;
}
.col-lg-2 {
width: 16.66666667%;
}
.col-lg-1 {
width: 8.33333333%;
}
.col-lg-pull-12 {
right: 100%;
}
.col-lg-pull-11 {
right: 91.66666667%;
}
.col-lg-pull-10 {
right: 83.33333333%;
}
.col-lg-pull-9 {
right: 75%;
}
.col-lg-pull-8 {
right: 66.66666667%;
}
.col-lg-pull-7 {
right: 58.33333333%;
}
.col-lg-pull-6 {
right: 50%;
}
.col-lg-pull-5 {
right: 41.66666667%;
}
.col-lg-pull-4 {
right: 33.33333333%;
}
.col-lg-pull-3 {
right: 25%;
}
.col-lg-pull-2 {
right: 16.66666667%;
}
.col-lg-pull-1 {
right: 8.33333333%;
}
.col-lg-pull-0 {
right: auto;
}
.col-lg-push-12 {
left: 100%;
}
.col-lg-push-11 {
left: 91.66666667%;
}
.col-lg-push-10 {
left: 83.33333333%;
}
.col-lg-push-9 {
left: 75%;
}
.col-lg-push-8 {
left: 66.66666667%;
}
.col-lg-push-7 {
left: 58.33333333%;
}
.col-lg-push-6 {
left: 50%;
}
.col-lg-push-5 {
left: 41.66666667%;
}
.col-lg-push-4 {
left: 33.33333333%;
}
.col-lg-push-3 {
left: 25%;
}
.col-lg-push-2 {
left: 16.66666667%;
}
.col-lg-push-1 {
left: 8.33333333%;
}
.col-lg-push-0 {
left: auto;
}
.col-lg-offset-12 {
margin-left: 100%;
}
.col-lg-offset-11 {
margin-left: 91.66666667%;
}
.col-lg-offset-10 {
margin-left: 83.33333333%;
}
.col-lg-offset-9 {
margin-left: 75%;
}
.col-lg-offset-8 {
margin-left: 66.66666667%;
}
.col-lg-offset-7 {
margin-left: 58.33333333%;
}
.col-lg-offset-6 {
margin-left: 50%;
}
.col-lg-offset-5 {
margin-left: 41.66666667%;
}
.col-lg-offset-4 {
margin-left: 33.33333333%;
}
.col-lg-offset-3 {
margin-left: 25%;
}
.col-lg-offset-2 {
margin-left: 16.66666667%;
}
.col-lg-offset-1 {
margin-left: 8.33333333%;
}
.col-lg-offset-0 {
margin-left: 0;
}
}
table {
background-color: transparent;
}
caption {
padding-top: 8px;
padding-bottom: 8px;
color: #777;
text-align: left;
}
th {
text-align: left;
}
.table {
width: 100%;
max-width: 100%;
margin-bottom: 20px;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #ddd;
}
.table > thead > tr > th {
vertical-align: bottom;
border-bottom: 2px solid #ddd;
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
border-top: 0;
}
.table > tbody + tbody {
border-top: 2px solid #ddd;
}
.table .table {
background-color: #fff;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
padding: 5px;
}
.table-bordered {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-of-type(odd) {
background-color: #f9f9f9;
}
.table-hover > tbody > tr:hover {
background-color: #f5f5f5;
}
table col[class*="col-"] {
position: static;
display: table-column;
float: none;
}
table td[class*="col-"],
table th[class*="col-"] {
position: static;
display: table-cell;
float: none;
}
.table > thead > tr > td.active,
.table > tbody > tr > td.active,
.table > tfoot > tr > td.active,
.table > thead > tr > th.active,
.table > tbody > tr > th.active,
.table > tfoot > tr > th.active,
.table > thead > tr.active > td,
.table > tbody > tr.active > td,
.table > tfoot > tr.active > td,
.table > thead > tr.active > th,
.table > tbody > tr.active > th,
.table > tfoot > tr.active > th {
background-color: #f5f5f5;
}
.table-hover > tbody > tr > td.active:hover,
.table-hover > tbody > tr > th.active:hover,
.table-hover > tbody > tr.active:hover > td,
.table-hover > tbody > tr:hover > .active,
.table-hover > tbody > tr.active:hover > th {
background-color: #e8e8e8;
}
.table > thead > tr > td.success,
.table > tbody > tr > td.success,
.table > tfoot > tr > td.success,
.table > thead > tr > th.success,
.table > tbody > tr > th.success,
.table > tfoot > tr > th.success,
.table > thead > tr.success > td,
.table > tbody > tr.success > td,
.table > tfoot > tr.success > td,
.table > thead > tr.success > th,
.table > tbody > tr.success > th,
.table > tfoot > tr.success > th {
background-color: #dff0d8;
}
.table-hover > tbody > tr > td.success:hover,
.table-hover > tbody > tr > th.success:hover,
.table-hover > tbody > tr.success:hover > td,
.table-hover > tbody > tr:hover > .success,
.table-hover > tbody > tr.success:hover > th {
background-color: #d0e9c6;
}
.table > thead > tr > td.info,
.table > tbody > tr > td.info,
.table > tfoot > tr > td.info,
.table > thead > tr > th.info,
.table > tbody > tr > th.info,
.table > tfoot > tr > th.info,
.table > thead > tr.info > td,
.table > tbody > tr.info > td,
.table > tfoot > tr.info > td,
.table > thead > tr.info > th,
.table > tbody > tr.info > th,
.table > tfoot > tr.info > th {
background-color: #d9edf7;
}
.table-hover > tbody > tr > td.info:hover,
.table-hover > tbody > tr > th.info:hover,
.table-hover > tbody > tr.info:hover > td,
.table-hover > tbody > tr:hover > .info,
.table-hover > tbody > tr.info:hover > th {
background-color: #c4e3f3;
}
.table > thead > tr > td.warning,
.table > tbody > tr > td.warning,
.table > tfoot > tr > td.warning,
.table > thead > tr > th.warning,
.table > tbody > tr > th.warning,
.table > tfoot > tr > th.warning,
.table > thead > tr.warning > td,
.table > tbody > tr.warning > td,
.table > tfoot > tr.warning > td,
.table > thead > tr.warning > th,
.table > tbody > tr.warning > th,
.table > tfoot > tr.warning > th {
background-color: #fcf8e3;
}
.table-hover > tbody > tr > td.warning:hover,
.table-hover > tbody > tr > th.warning:hover,
.table-hover > tbody > tr.warning:hover > td,
.table-hover > tbody > tr:hover > .warning,
.table-hover > tbody > tr.warning:hover > th {
background-color: #faf2cc;
}
.table > thead > tr > td.danger,
.table > tbody > tr > td.danger,
.table > tfoot > tr > td.danger,
.table > thead > tr > th.danger,
.table > tbody > tr > th.danger,
.table > tfoot > tr > th.danger,
.table > thead > tr.danger > td,
.table > tbody > tr.danger > td,
.table > tfoot > tr.danger > td,
.table > thead > tr.danger > th,
.table > tbody > tr.danger > th,
.table > tfoot > tr.danger > th {
background-color: #f2dede;
}
.table-hover > tbody > tr > td.danger:hover,
.table-hover > tbody > tr > th.danger:hover,
.table-hover > tbody > tr.danger:hover > td,
.table-hover > tbody > tr:hover > .danger,
.table-hover > tbody > tr.danger:hover > th {
background-color: #ebcccc;
}
.table-responsive {
min-height: .01%;
overflow-x: auto;
}
@media screen and (max-width: 767px) {
.table-responsive {
width: 100%;
margin-bottom: 15px;
overflow-y: hidden;
-ms-overflow-style: -ms-autohiding-scrollbar;
border: 1px solid #ddd;
}
.table-responsive > .table {
margin-bottom: 0;
}
.table-responsive > .table > thead > tr > th,
.table-responsive > .table > tbody > tr > th,
.table-responsive > .table > tfoot > tr > th,
.table-responsive > .table > thead > tr > td,
.table-responsive > .table > tbody > tr > td,
.table-responsive > .table > tfoot > tr > td {
white-space: nowrap;
}
.table-responsive > .table-bordered {
border: 0;
}
.table-responsive > .table-bordered > thead > tr > th:first-child,
.table-responsive > .table-bordered > tbody > tr > th:first-child,
.table-responsive > .table-bordered > tfoot > tr > th:first-child,
.table-responsive > .table-bordered > thead > tr > td:first-child,
.table-responsive > .table-bordered > tbody > tr > td:first-child,
.table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.table-responsive > .table-bordered > thead > tr > th:last-child,
.table-responsive > .table-bordered > tbody > tr > th:last-child,
.table-responsive > .table-bordered > tfoot > tr > th:last-child,
.table-responsive > .table-bordered > thead > tr > td:last-child,
.table-responsive > .table-bordered > tbody > tr > td:last-child,
.table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.table-responsive > .table-bordered > tbody > tr:last-child > th,
.table-responsive > .table-bordered > tfoot > tr:last-child > th,
.table-responsive > .table-bordered > tbody > tr:last-child > td,
.table-responsive > .table-bordered > tfoot > tr:last-child > td {
border-bottom: 0;
}
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 20px;
font-size: 21px;
line-height: inherit;
color: #333;
border: 0;
border-bottom: 1px solid #e5e5e5;
}
label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
font-weight: bold;
}
input[type="search"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
margin: 4px 0 0;
margin-top: 1px \9;
line-height: normal;
}
input[type="file"] {
display: block;
}
input[type="range"] {
display: block;
width: 100%;
}
select[multiple],
select[size] {
height: auto;
}
input[type="file"]:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
output {
display: block;
padding-top: 7px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
}
.form-control {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
}
.form-control::-moz-placeholder {
color: #999;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #999;
}
.form-control::-webkit-input-placeholder {
color: #999;
}
.form-control::-ms-expand {
background-color: transparent;
border: 0;
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
background-color: #eee;
opacity: 1;
}
.form-control[disabled],
fieldset[disabled] .form-control {
cursor: not-allowed;
}
textarea.form-control {
height: auto;
}
input[type="search"] {
-webkit-appearance: none;
}
@media screen and (-webkit-min-device-pixel-ratio: 0) {
input[type="date"].form-control,
input[type="time"].form-control,
input[type="datetime-local"].form-control,
input[type="month"].form-control {
line-height: 34px;
}
input[type="date"].input-sm,
input[type="time"].input-sm,
input[type="datetime-local"].input-sm,
input[type="month"].input-sm,
.input-group-sm input[type="date"],
.input-group-sm input[type="time"],
.input-group-sm input[type="datetime-local"],
.input-group-sm input[type="month"] {
line-height: 30px;
}
input[type="date"].input-lg,
input[type="time"].input-lg,
input[type="datetime-local"].input-lg,
input[type="month"].input-lg,
.input-group-lg input[type="date"],
.input-group-lg input[type="time"],
.input-group-lg input[type="datetime-local"],
.input-group-lg input[type="month"] {
line-height: 46px;
}
}
.form-group {
margin-bottom: 15px;
}
.radio,
.checkbox {
position: relative;
display: block;
margin-top: 10px;
margin-bottom: 10px;
}
.radio label,
.checkbox label {
min-height: 20px;
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
cursor: pointer;
}
.radio input[type="radio"],
.radio-inline input[type="radio"],
.checkbox input[type="checkbox"],
.checkbox-inline input[type="checkbox"] {
position: absolute;
margin-top: 4px \9;
margin-left: -20px;
}
.radio + .radio,
.checkbox + .checkbox {
margin-top: -5px;
}
.radio-inline,
.checkbox-inline {
position: relative;
display: inline-block;
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
vertical-align: middle;
cursor: pointer;
}
.radio-inline + .radio-inline,
.checkbox-inline + .checkbox-inline {
margin-top: 0;
margin-left: 10px;
}
input[type="radio"][disabled],
input[type="checkbox"][disabled],
input[type="radio"].disabled,
input[type="checkbox"].disabled,
fieldset[disabled] input[type="radio"],
fieldset[disabled] input[type="checkbox"] {
cursor: not-allowed;
}
.radio-inline.disabled,
.checkbox-inline.disabled,
fieldset[disabled] .radio-inline,
fieldset[disabled] .checkbox-inline {
cursor: not-allowed;
}
.radio.disabled label,
.checkbox.disabled label,
fieldset[disabled] .radio label,
fieldset[disabled] .checkbox label {
cursor: not-allowed;
}
.form-control-static {
min-height: 34px;
padding-top: 7px;
padding-bottom: 7px;
margin-bottom: 0;
}
.form-control-static.input-lg,
.form-control-static.input-sm {
padding-right: 0;
padding-left: 0;
}
.input-sm {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-sm {
height: 30px;
line-height: 30px;
}
textarea.input-sm,
select[multiple].input-sm {
height: auto;
}
.form-group-sm .form-control {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.form-group-sm select.form-control {
height: 30px;
line-height: 30px;
}
.form-group-sm textarea.form-control,
.form-group-sm select[multiple].form-control {
height: auto;
}
.form-group-sm .form-control-static {
height: 30px;
min-height: 32px;
padding: 6px 10px;
font-size: 12px;
line-height: 1.5;
}
.input-lg {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
select.input-lg {
height: 46px;
line-height: 46px;
}
textarea.input-lg,
select[multiple].input-lg {
height: auto;
}
.form-group-lg .form-control {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
.form-group-lg select.form-control {
height: 46px;
line-height: 46px;
}
.form-group-lg textarea.form-control,
.form-group-lg select[multiple].form-control {
height: auto;
}
.form-group-lg .form-control-static {
height: 46px;
min-height: 38px;
padding: 11px 16px;
font-size: 18px;
line-height: 1.3333333;
}
.has-feedback {
position: relative;
}
.has-feedback .form-control {
padding-right: 42.5px;
}
.form-control-feedback {
position: absolute;
top: 0;
right: 0;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
pointer-events: none;
}
.input-lg + .form-control-feedback,
.input-group-lg + .form-control-feedback,
.form-group-lg .form-control + .form-control-feedback {
width: 46px;
height: 46px;
line-height: 46px;
}
.input-sm + .form-control-feedback,
.input-group-sm + .form-control-feedback,
.form-group-sm .form-control + .form-control-feedback {
width: 30px;
height: 30px;
line-height: 30px;
}
.has-success .help-block,
.has-success .control-label,
.has-success .radio,
.has-success .checkbox,
.has-success .radio-inline,
.has-success .checkbox-inline,
.has-success.radio label,
.has-success.checkbox label,
.has-success.radio-inline label,
.has-success.checkbox-inline label {
color: #3c763d;
}
.has-success .form-control {
border-color: #3c763d;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-success .form-control:focus {
border-color: #2b542c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
}
.has-success .input-group-addon {
color: #3c763d;
background-color: #dff0d8;
border-color: #3c763d;
}
.has-success .form-control-feedback {
color: #3c763d;
}
.has-warning .help-block,
.has-warning .control-label,
.has-warning .radio,
.has-warning .checkbox,
.has-warning .radio-inline,
.has-warning .checkbox-inline,
.has-warning.radio label,
.has-warning.checkbox label,
.has-warning.radio-inline label,
.has-warning.checkbox-inline label {
color: #8a6d3b;
}
.has-warning .form-control {
border-color: #8a6d3b;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-warning .form-control:focus {
border-color: #66512c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
}
.has-warning .input-group-addon {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #8a6d3b;
}
.has-warning .form-control-feedback {
color: #8a6d3b;
}
.has-error .help-block,
.has-error .control-label,
.has-error .radio,
.has-error .checkbox,
.has-error .radio-inline,
.has-error .checkbox-inline,
.has-error.radio label,
.has-error.checkbox label,
.has-error.radio-inline label,
.has-error.checkbox-inline label {
color: #a94442;
}
.has-error .form-control {
border-color: #a94442;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-error .form-control:focus {
border-color: #843534;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
}
.has-error .input-group-addon {
color: #a94442;
background-color: #f2dede;
border-color: #a94442;
}
.has-error .form-control-feedback {
color: #a94442;
}
.has-feedback label ~ .form-control-feedback {
top: 25px;
}
.has-feedback label.sr-only ~ .form-control-feedback {
top: 0;
}
.help-block {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #737373;
}
@media (min-width: 768px) {
.form-inline .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.form-inline .form-control-static {
display: inline-block;
}
.form-inline .input-group {
display: inline-table;
vertical-align: middle;
}
.form-inline .input-group .input-group-addon,
.form-inline .input-group .input-group-btn,
.form-inline .input-group .form-control {
width: auto;
}
.form-inline .input-group > .form-control {
width: 100%;
}
.form-inline .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio,
.form-inline .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio label,
.form-inline .checkbox label {
padding-left: 0;
}
.form-inline .radio input[type="radio"],
.form-inline .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.form-inline .has-feedback .form-control-feedback {
top: 0;
}
}
.form-horizontal .radio,
.form-horizontal .checkbox,
.form-horizontal .radio-inline,
.form-horizontal .checkbox-inline {
padding-top: 7px;
margin-top: 0;
margin-bottom: 0;
}
.form-horizontal .radio,
.form-horizontal .checkbox {
min-height: 27px;
}
.form-horizontal .form-group {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.form-horizontal .control-label {
padding-top: 7px;
margin-bottom: 0;
text-align: right;
}
}
.form-horizontal .has-feedback .form-control-feedback {
right: 15px;
}
@media (min-width: 768px) {
.form-horizontal .form-group-lg .control-label {
padding-top: 11px;
font-size: 18px;
}
}
@media (min-width: 768px) {
.form-horizontal .form-group-sm .control-label {
padding-top: 6px;
font-size: 12px;
}
}
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: normal;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.btn:focus,
.btn:active:focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn.active.focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.btn:hover,
.btn:focus,
.btn.focus {
color: #333;
text-decoration: none;
}
.btn:active,
.btn.active {
background-image: none;
outline: 0;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
cursor: not-allowed;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
opacity: .65;
}
a.btn.disabled,
fieldset[disabled] a.btn {
pointer-events: none;
}
.btn-default {
color: #333;
background-color: #fff;
border-color: #ccc;
}
.btn-default:focus,
.btn-default.focus {
color: #333;
background-color: #e6e6e6;
border-color: #8c8c8c;
}
.btn-default:hover {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.btn-default:active:hover,
.btn-default.active:hover,
.open > .dropdown-toggle.btn-default:hover,
.btn-default:active:focus,
.btn-default.active:focus,
.open > .dropdown-toggle.btn-default:focus,
.btn-default:active.focus,
.btn-default.active.focus,
.open > .dropdown-toggle.btn-default.focus {
color: #333;
background-color: #d4d4d4;
border-color: #8c8c8c;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
background-image: none;
}
.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 {
background-color: #fff;
border-color: #ccc;
}
.btn-default .badge {
color: #fff;
background-color: #333;
}
.btn-primary {
color: #fff;
background-color: #337ab7;
border-color: #2e6da4;
}
.btn-primary:focus,
.btn-primary.focus {
color: #fff;
background-color: #286090;
border-color: #122b40;
}
.btn-primary:hover {
color: #fff;
background-color: #286090;
border-color: #204d74;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
color: #fff;
background-color: #286090;
border-color: #204d74;
}
.btn-primary:active:hover,
.btn-primary.active:hover,
.open > .dropdown-toggle.btn-primary:hover,
.btn-primary:active:focus,
.btn-primary.active:focus,
.open > .dropdown-toggle.btn-primary:focus,
.btn-primary:active.focus,
.btn-primary.active.focus,
.open > .dropdown-toggle.btn-primary.focus {
color: #fff;
background-color: #204d74;
border-color: #122b40;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
background-image: none;
}
.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 {
background-color: #337ab7;
border-color: #2e6da4;
}
.btn-primary .badge {
color: #337ab7;
background-color: #fff;
}
.btn-success {
color: #fff;
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success:focus,
.btn-success.focus {
color: #fff;
background-color: #449d44;
border-color: #255625;
}
.btn-success:hover {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.btn-success:active:hover,
.btn-success.active:hover,
.open > .dropdown-toggle.btn-success:hover,
.btn-success:active:focus,
.btn-success.active:focus,
.open > .dropdown-toggle.btn-success:focus,
.btn-success:active.focus,
.btn-success.active.focus,
.open > .dropdown-toggle.btn-success.focus {
color: #fff;
background-color: #398439;
border-color: #255625;
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
background-image: none;
}
.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 {
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success .badge {
color: #5cb85c;
background-color: #fff;
}
.btn-info {
color: #fff;
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info:focus,
.btn-info.focus {
color: #fff;
background-color: #31b0d5;
border-color: #1b6d85;
}
.btn-info:hover {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active:hover,
.btn-info.active:hover,
.open > .dropdown-toggle.btn-info:hover,
.btn-info:active:focus,
.btn-info.active:focus,
.open > .dropdown-toggle.btn-info:focus,
.btn-info:active.focus,
.btn-info.active.focus,
.open > .dropdown-toggle.btn-info.focus {
color: #fff;
background-color: #269abc;
border-color: #1b6d85;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
background-image: none;
}
.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 {
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info .badge {
color: #5bc0de;
background-color: #fff;
}
.btn-warning {
color: #fff;
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning:focus,
.btn-warning.focus {
color: #fff;
background-color: #ec971f;
border-color: #985f0d;
}
.btn-warning:hover {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active:hover,
.btn-warning.active:hover,
.open > .dropdown-toggle.btn-warning:hover,
.btn-warning:active:focus,
.btn-warning.active:focus,
.open > .dropdown-toggle.btn-warning:focus,
.btn-warning:active.focus,
.btn-warning.active.focus,
.open > .dropdown-toggle.btn-warning.focus {
color: #fff;
background-color: #d58512;
border-color: #985f0d;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
background-image: none;
}
.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 {
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning .badge {
color: #f0ad4e;
background-color: #fff;
}
.btn-danger {
color: #fff;
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger:focus,
.btn-danger.focus {
color: #fff;
background-color: #c9302c;
border-color: #761c19;
}
.btn-danger:hover {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active:hover,
.btn-danger.active:hover,
.open > .dropdown-toggle.btn-danger:hover,
.btn-danger:active:focus,
.btn-danger.active:focus,
.open > .dropdown-toggle.btn-danger:focus,
.btn-danger:active.focus,
.btn-danger.active.focus,
.open > .dropdown-toggle.btn-danger.focus {
color: #fff;
background-color: #ac2925;
border-color: #761c19;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
background-image: none;
}
.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 {
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger .badge {
color: #d9534f;
background-color: #fff;
}
.btn-link {
font-weight: normal;
color: #337ab7;
border-radius: 0;
}
.btn-link,
.btn-link:active,
.btn-link.active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
.btn-link,
.btn-link:hover,
.btn-link:focus,
.btn-link:active {
border-color: transparent;
}
.btn-link:hover,
.btn-link:focus {
color: #23527c;
text-decoration: underline;
background-color: transparent;
}
.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:hover,
.btn-link[disabled]:focus,
fieldset[disabled] .btn-link:focus {
color: #777;
text-decoration: none;
}
.btn-lg,
.btn-group-lg > .btn {
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
.btn-sm,
.btn-group-sm > .btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-xs,
.btn-group-xs > .btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-block {
display: block;
width: 100%;
}
.btn-block + .btn-block {
margin-top: 5px;
}
input[type="submit"].btn-block,
input[type="reset"].btn-block,
input[type="button"].btn-block {
width: 100%;
}
.fade {
opacity: 0;
-webkit-transition: opacity .15s linear;
-o-transition: opacity .15s linear;
transition: opacity .15s linear;
}
.fade.in {
opacity: 1;
}
.collapse {
display: none;
}
.collapse.in {
display: block;
}
tr.collapse.in {
display: table-row;
}
tbody.collapse.in {
display: table-row-group;
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
-webkit-transition-timing-function: ease;
-o-transition-timing-function: ease;
transition-timing-function: ease;
-webkit-transition-duration: .35s;
-o-transition-duration: .35s;
transition-duration: .35s;
-webkit-transition-property: height, visibility;
-o-transition-property: height, visibility;
transition-property: height, visibility;
}
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: 4px dashed;
border-top: 4px solid \9;
border-right: 4px solid transparent;
border-left: 4px solid transparent;
}
.dropup,
.dropdown {
position: relative;
}
.dropdown-toggle:focus {
outline: 0;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
font-size: 14px;
text-align: left;
list-style: none;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
}
.dropdown-menu.pull-right {
right: 0;
left: auto;
}
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.dropdown-menu > li > a {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333;
white-space: nowrap;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #f5f5f5;
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
color: #fff;
text-decoration: none;
background-color: #337ab7;
outline: 0;
}
.dropdown-menu > .disabled > a,
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
color: #777;
}
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
background-image: none;
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
}
.open > .dropdown-menu {
display: block;
}
.open > a {
outline: 0;
}
.dropdown-menu-right {
right: 0;
left: auto;
}
.dropdown-menu-left {
right: auto;
left: 0;
}
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: 12px;
line-height: 1.42857143;
color: #777;
white-space: nowrap;
}
.dropdown-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 990;
}
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
.dropup .caret,
.navbar-fixed-bottom .dropdown .caret {
content: "";
border-top: 0;
border-bottom: 4px dashed;
border-bottom: 4px solid \9;
}
.dropup .dropdown-menu,
.navbar-fixed-bottom .dropdown .dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 2px;
}
@media (min-width: 768px) {
.navbar-right .dropdown-menu {
right: 0;
left: auto;
}
.navbar-right .dropdown-menu-left {
right: auto;
left: 0;
}
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
.btn-group > .btn,
.btn-group-vertical > .btn {
position: relative;
float: left;
}
.btn-group > .btn:hover,
.btn-group-vertical > .btn:hover,
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus,
.btn-group > .btn:active,
.btn-group-vertical > .btn:active,
.btn-group > .btn.active,
.btn-group-vertical > .btn.active {
z-index: 2;
}
.btn-group .btn + .btn,
.btn-group .btn + .btn-group,
.btn-group .btn-group + .btn,
.btn-group .btn-group + .btn-group {
margin-left: -1px;
}
.btn-toolbar {
margin-left: -5px;
}
.btn-toolbar .btn,
.btn-toolbar .btn-group,
.btn-toolbar .input-group {
float: left;
}
.btn-toolbar > .btn,
.btn-toolbar > .btn-group,
.btn-toolbar > .input-group {
margin-left: 5px;
}
.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
border-radius: 0;
}
.btn-group > .btn:first-child {
margin-left: 0;
}
.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group > .btn:last-child:not(:first-child),
.btn-group > .dropdown-toggle:not(:first-child) {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group > .btn-group {
float: left;
}
.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group .dropdown-toggle:active,
.btn-group.open .dropdown-toggle {
outline: 0;
}
.btn-group > .btn + .dropdown-toggle {
padding-right: 8px;
padding-left: 8px;
}
.btn-group > .btn-lg + .dropdown-toggle {
padding-right: 12px;
padding-left: 12px;
}
.btn-group.open .dropdown-toggle {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn-group.open .dropdown-toggle.btn-link {
-webkit-box-shadow: none;
box-shadow: none;
}
.btn .caret {
margin-left: 0;
}
.btn-lg .caret {
border-width: 5px 5px 0;
border-bottom-width: 0;
}
.dropup .btn-lg .caret {
border-width: 0 5px 5px;
}
.btn-group-vertical > .btn,
.btn-group-vertical > .btn-group,
.btn-group-vertical > .btn-group > .btn {
display: block;
float: none;
width: 100%;
max-width: 100%;
}
.btn-group-vertical > .btn-group > .btn {
float: none;
}
.btn-group-vertical > .btn + .btn,
.btn-group-vertical > .btn + .btn-group,
.btn-group-vertical > .btn-group + .btn,
.btn-group-vertical > .btn-group + .btn-group {
margin-top: -1px;
margin-left: 0;
}
.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
border-radius: 0;
}
.btn-group-vertical > .btn:first-child:not(:last-child) {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn:last-child:not(:first-child) {
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px;
}
.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.btn-group-justified {
display: table;
width: 100%;
table-layout: fixed;
border-collapse: separate;
}
.btn-group-justified > .btn,
.btn-group-justified > .btn-group {
display: table-cell;
float: none;
width: 1%;
}
.btn-group-justified > .btn-group .btn {
width: 100%;
}
.btn-group-justified > .btn-group .dropdown-menu {
left: auto;
}
[data-toggle="buttons"] > .btn input[type="radio"],
[data-toggle="buttons"] > .btn-group > .btn input[type="radio"],
[data-toggle="buttons"] > .btn input[type="checkbox"],
[data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] {
position: absolute;
clip: rect(0, 0, 0, 0);
pointer-events: none;
}
.input-group {
position: relative;
display: table;
border-collapse: separate;
}
.input-group[class*="col-"] {
float: none;
padding-right: 0;
padding-left: 0;
}
.input-group .form-control {
position: relative;
z-index: 2;
float: left;
width: 100%;
margin-bottom: 0;
}
.input-group .form-control:focus {
z-index: 3;
}
.input-group-lg > .form-control,
.input-group-lg > .input-group-addon,
.input-group-lg > .input-group-btn > .btn {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
select.input-group-lg > .form-control,
select.input-group-lg > .input-group-addon,
select.input-group-lg > .input-group-btn > .btn {
height: 46px;
line-height: 46px;
}
textarea.input-group-lg > .form-control,
textarea.input-group-lg > .input-group-addon,
textarea.input-group-lg > .input-group-btn > .btn,
select[multiple].input-group-lg > .form-control,
select[multiple].input-group-lg > .input-group-addon,
select[multiple].input-group-lg > .input-group-btn > .btn {
height: auto;
}
.input-group-sm > .form-control,
.input-group-sm > .input-group-addon,
.input-group-sm > .input-group-btn > .btn {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-group-sm > .form-control,
select.input-group-sm > .input-group-addon,
select.input-group-sm > .input-group-btn > .btn {
height: 30px;
line-height: 30px;
}
textarea.input-group-sm > .form-control,
textarea.input-group-sm > .input-group-addon,
textarea.input-group-sm > .input-group-btn > .btn,
select[multiple].input-group-sm > .form-control,
select[multiple].input-group-sm > .input-group-addon,
select[multiple].input-group-sm > .input-group-btn > .btn {
height: auto;
}
.input-group-addon,
.input-group-btn,
.input-group .form-control {
display: table-cell;
}
.input-group-addon:not(:first-child):not(:last-child),
.input-group-btn:not(:first-child):not(:last-child),
.input-group .form-control:not(:first-child):not(:last-child) {
border-radius: 0;
}
.input-group-addon,
.input-group-btn {
width: 1%;
white-space: nowrap;
vertical-align: middle;
}
.input-group-addon {
padding: 6px 12px;
font-size: 14px;
font-weight: normal;
line-height: 1;
color: #555;
text-align: center;
background-color: #eee;
border: 1px solid #ccc;
border-radius: 4px;
}
.input-group-addon.input-sm {
padding: 5px 10px;
font-size: 12px;
border-radius: 3px;
}
.input-group-addon.input-lg {
padding: 10px 16px;
font-size: 18px;
border-radius: 6px;
}
.input-group-addon input[type="radio"],
.input-group-addon input[type="checkbox"] {
margin-top: 0;
}
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.input-group-addon:first-child {
border-right: 0;
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child),
.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.input-group-addon:last-child {
border-left: 0;
}
.input-group-btn {
position: relative;
font-size: 0;
white-space: nowrap;
}
.input-group-btn > .btn {
position: relative;
}
.input-group-btn > .btn + .btn {
margin-left: -1px;
}
.input-group-btn > .btn:hover,
.input-group-btn > .btn:focus,
.input-group-btn > .btn:active {
z-index: 2;
}
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group {
margin-right: -1px;
}
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group {
z-index: 2;
margin-left: -1px;
}
.nav {
padding-left: 0;
margin-bottom: 0;
list-style: none;
}
.nav > li {
position: relative;
display: block;
}
.nav > li > a {
position: relative;
display: block;
padding: 10px 15px;
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: #eee;
}
.nav > li.disabled > a {
color: #777;
}
.nav > li.disabled > a:hover,
.nav > li.disabled > a:focus {
color: #777;
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
background-color: #eee;
border-color: #337ab7;
}
.nav .nav-divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.nav > li > a > img {
max-width: none;
}
.nav-tabs {
border-bottom: 1px solid #ddd;
}
.nav-tabs > li {
float: left;
margin-bottom: -1px;
}
.nav-tabs > li > a {
margin-right: 2px;
line-height: 1.42857143;
border: 1px solid transparent;
border-radius: 4px 4px 0 0;
}
.nav-tabs > li > a:hover {
border-color: #eee #eee #ddd;
}
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
color: #555;
cursor: default;
background-color: #fff;
border: 1px solid #ddd;
border-bottom-color: transparent;
}
.nav-tabs.nav-justified {
width: 100%;
border-bottom: 0;
}
.nav-tabs.nav-justified > li {
float: none;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 5px;
text-align: center;
}
.nav-tabs.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs.nav-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.nav-pills > li {
float: left;
}
.nav-pills > li > a {
border-radius: 4px;
}
.nav-pills > li + li {
margin-left: 2px;
}
.nav-pills > li.active > a,
.nav-pills > li.active > a:hover,
.nav-pills > li.active > a:focus {
color: #fff;
background-color: #337ab7;
}
.nav-stacked > li {
float: none;
}
.nav-stacked > li + li {
margin-top: 2px;
margin-left: 0;
}
.nav-justified {
width: 100%;
}
.nav-justified > li {
float: none;
}
.nav-justified > li > a {
margin-bottom: 5px;
text-align: center;
}
.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs-justified {
border-bottom: 0;
}
.nav-tabs-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.tab-content > .tab-pane {
display: none;
}
.tab-content > .active {
display: block;
}
.nav-tabs .dropdown-menu {
margin-top: -1px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.navbar {
position: relative;
min-height: 50px;
margin-bottom: 20px;
border: 1px solid transparent;
}
@media (min-width: 768px) {
.navbar {
border-radius: 4px;
}
}
@media (min-width: 768px) {
.navbar-header {
float: left;
}
}
.navbar-collapse {
padding-right: 15px;
padding-left: 15px;
overflow-x: visible;
-webkit-overflow-scrolling: touch;
border-top: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
}
.navbar-collapse.in {
overflow-y: auto;
}
@media (min-width: 768px) {
.navbar-collapse {
width: auto;
border-top: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-collapse.collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
}
.navbar-collapse.in {
overflow-y: visible;
}
.navbar-fixed-top .navbar-collapse,
.navbar-static-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
padding-right: 0;
padding-left: 0;
}
}
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 340px;
}
@media (max-device-width: 480px) and (orientation: landscape) {
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 200px;
}
}
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
}
.navbar-static-top {
z-index: 1000;
border-width: 0 0 1px;
}
@media (min-width: 768px) {
.navbar-static-top {
border-radius: 0;
}
}
.navbar-fixed-top,
.navbar-fixed-bottom {
position: fixed;
right: 0;
left: 0;
z-index: 1030;
}
@media (min-width: 768px) {
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
}
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px;
}
.navbar-fixed-bottom {
bottom: 0;
margin-bottom: 0;
border-width: 1px 0 0;
}
.navbar-brand {
float: left;
height: 50px;
padding: 15px 15px;
font-size: 18px;
line-height: 20px;
}
.navbar-brand:hover,
.navbar-brand:focus {
text-decoration: none;
}
.navbar-brand > img {
display: block;
}
@media (min-width: 768px) {
.navbar > .container .navbar-brand,
.navbar > .container-fluid .navbar-brand {
margin-left: -15px;
}
}
.navbar-toggle {
position: relative;
float: right;
padding: 9px 10px;
margin-top: 8px;
margin-right: 15px;
margin-bottom: 8px;
background-color: transparent;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.navbar-toggle:focus {
outline: 0;
}
.navbar-toggle .icon-bar {
display: block;
width: 22px;
height: 2px;
border-radius: 1px;
}
.navbar-toggle .icon-bar + .icon-bar {
margin-top: 4px;
}
@media (min-width: 768px) {
.navbar-toggle {
display: none;
}
}
.navbar-nav {
margin: 7.5px -15px;
}
.navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 20px;
}
@media (max-width: 767px) {
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-nav .open .dropdown-menu > li > a,
.navbar-nav .open .dropdown-menu .dropdown-header {
padding: 5px 15px 5px 25px;
}
.navbar-nav .open .dropdown-menu > li > a {
line-height: 20px;
}
.navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-nav .open .dropdown-menu > li > a:focus {
background-image: none;
}
}
@media (min-width: 768px) {
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding-top: 15px;
padding-bottom: 15px;
}
}
.navbar-form {
padding: 10px 15px;
margin-top: 8px;
margin-right: -15px;
margin-bottom: 8px;
margin-left: -15px;
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
}
@media (min-width: 768px) {
.navbar-form .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.navbar-form .form-control-static {
display: inline-block;
}
.navbar-form .input-group {
display: inline-table;
vertical-align: middle;
}
.navbar-form .input-group .input-group-addon,
.navbar-form .input-group .input-group-btn,
.navbar-form .input-group .form-control {
width: auto;
}
.navbar-form .input-group > .form-control {
width: 100%;
}
.navbar-form .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio,
.navbar-form .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio label,
.navbar-form .checkbox label {
padding-left: 0;
}
.navbar-form .radio input[type="radio"],
.navbar-form .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.navbar-form .has-feedback .form-control-feedback {
top: 0;
}
}
@media (max-width: 767px) {
.navbar-form .form-group {
margin-bottom: 5px;
}
.navbar-form .form-group:last-child {
margin-bottom: 0;
}
}
@media (min-width: 768px) {
.navbar-form {
width: auto;
padding-top: 0;
padding-bottom: 0;
margin-right: 0;
margin-left: 0;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
}
.navbar-nav > li > .dropdown-menu {
margin-top: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
margin-bottom: 0;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.navbar-btn {
margin-top: 8px;
margin-bottom: 8px;
}
.navbar-btn.btn-sm {
margin-top: 10px;
margin-bottom: 10px;
}
.navbar-btn.btn-xs {
margin-top: 14px;
margin-bottom: 14px;
}
.navbar-text {
margin-top: 15px;
margin-bottom: 15px;
}
@media (min-width: 768px) {
.navbar-text {
float: left;
margin-right: 15px;
margin-left: 15px;
}
}
@media (min-width: 768px) {
.navbar-left {
float: left !important;
}
.navbar-right {
float: right !important;
margin-right: -15px;
}
.navbar-right ~ .navbar-right {
margin-right: 0;
}
}
.navbar-default {
background-color: #f8f8f8;
border-color: #e7e7e7;
}
.navbar-default .navbar-brand {
color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #5e5e5e;
background-color: transparent;
}
.navbar-default .navbar-text {
color: #777;
}
.navbar-default .navbar-nav > li > a {
color: #777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav > .disabled > a,
.navbar-default .navbar-nav > .disabled > a:hover,
.navbar-default .navbar-nav > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
.navbar-default .navbar-toggle {
border-color: #ddd;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #ddd;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #888;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: #e7e7e7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
color: #555;
background-color: #e7e7e7;
}
@media (max-width: 767px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #777;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
}
.navbar-default .navbar-link {
color: #777;
}
.navbar-default .navbar-link:hover {
color: #333;
}
.navbar-default .btn-link {
color: #777;
}
.navbar-default .btn-link:hover,
.navbar-default .btn-link:focus {
color: #333;
}
.navbar-default .btn-link[disabled]:hover,
fieldset[disabled] .navbar-default .btn-link:hover,
.navbar-default .btn-link[disabled]:focus,
fieldset[disabled] .navbar-default .btn-link:focus {
color: #ccc;
}
.navbar-inverse {
background-color: #222;
border-color: #080808;
}
.navbar-inverse .navbar-brand {
color: #9d9d9d;
}
.navbar-inverse .navbar-brand:hover,
.navbar-inverse .navbar-brand:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-text {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav > li > a {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav > .disabled > a,
.navbar-inverse .navbar-nav > .disabled > a:hover,
.navbar-inverse .navbar-nav > .disabled > a:focus {
color: #444;
background-color: transparent;
}
.navbar-inverse .navbar-toggle {
border-color: #333;
}
.navbar-inverse .navbar-toggle:hover,
.navbar-inverse .navbar-toggle:focus {
background-color: #333;
}
.navbar-inverse .navbar-toggle .icon-bar {
background-color: #fff;
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
border-color: #101010;
}
.navbar-inverse .navbar-nav > .open > a,
.navbar-inverse .navbar-nav > .open > a:hover,
.navbar-inverse .navbar-nav > .open > a:focus {
color: #fff;
background-color: #080808;
}
@media (max-width: 767px) {
.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
border-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
color: #9d9d9d;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #444;
background-color: transparent;
}
}
.navbar-inverse .navbar-link {
color: #9d9d9d;
}
.navbar-inverse .navbar-link:hover {
color: #fff;
}
.navbar-inverse .btn-link {
color: #9d9d9d;
}
.navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link:focus {
color: #fff;
}
.navbar-inverse .btn-link[disabled]:hover,
fieldset[disabled] .navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link[disabled]:focus,
fieldset[disabled] .navbar-inverse .btn-link:focus {
color: #444;
}
.breadcrumb {
padding: 8px 15px;
margin-bottom: 20px;
list-style: none;
background-color: #f5f5f5;
border-radius: 4px;
}
.breadcrumb > li {
display: inline-block;
}
.breadcrumb > li + li:before {
padding: 0 5px;
color: #ccc;
content: "/\00a0";
}
.breadcrumb > .active {
color: #777;
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 20px 0;
border-radius: 4px;
}
.pagination > li {
display: inline;
}
.pagination > li > a,
.pagination > li > span {
position: relative;
float: left;
padding: 6px 12px;
margin-left: -1px;
line-height: 1.42857143;
color: #337ab7;
text-decoration: none;
background-color: #fff;
border: 1px solid #ddd;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
margin-left: 0;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
z-index: 2;
color: #23527c;
background-color: #eee;
border-color: #ddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
z-index: 3;
color: #fff;
cursor: default;
background-color: #337ab7;
border-color: #337ab7;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
color: #777;
cursor: not-allowed;
background-color: #fff;
border-color: #ddd;
}
.pagination-lg > li > a,
.pagination-lg > li > span {
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
}
.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
}
.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
}
.pagination-sm > li > a,
.pagination-sm > li > span {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
}
.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
}
.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
.pager {
padding-left: 0;
margin: 20px 0;
text-align: center;
list-style: none;
}
.pager li {
display: inline;
}
.pager li > a,
.pager li > span {
display: inline-block;
padding: 5px 14px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 15px;
}
.pager li > a:hover,
.pager li > a:focus {
text-decoration: none;
background-color: #eee;
}
.pager .next > a,
.pager .next > span {
float: right;
}
.pager .previous > a,
.pager .previous > span {
float: left;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.label {
display: inline;
padding: .2em .6em .3em;
font-size: 75%;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em;
}
a.label:hover,
a.label:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
.label:empty {
display: none;
}
.btn .label {
position: relative;
top: -1px;
}
.label-default {
background-color: #777;
}
.label-default[href]:hover,
.label-default[href]:focus {
background-color: #5e5e5e;
}
.label-primary {
background-color: #337ab7;
}
.label-primary[href]:hover,
.label-primary[href]:focus {
background-color: #286090;
}
.label-success {
background-color: #5cb85c;
}
.label-success[href]:hover,
.label-success[href]:focus {
background-color: #449d44;
}
.label-info {
background-color: #5bc0de;
}
.label-info[href]:hover,
.label-info[href]:focus {
background-color: #31b0d5;
}
.label-warning {
background-color: #f0ad4e;
}
.label-warning[href]:hover,
.label-warning[href]:focus {
background-color: #ec971f;
}
.label-danger {
background-color: #d9534f;
}
.label-danger[href]:hover,
.label-danger[href]:focus {
background-color: #c9302c;
}
.badge {
display: inline-block;
min-width: 10px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: middle;
background-color: #777;
border-radius: 10px;
}
.badge:empty {
display: none;
}
.btn .badge {
position: relative;
top: -1px;
}
.btn-xs .badge,
.btn-group-xs > .btn .badge {
top: 0;
padding: 1px 5px;
}
a.badge:hover,
a.badge:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
.list-group-item.active > .badge,
.nav-pills > .active > a > .badge {
color: #337ab7;
background-color: #fff;
}
.list-group-item > .badge {
float: right;
}
.list-group-item > .badge + .badge {
margin-right: 5px;
}
.nav-pills > li > a > .badge {
margin-left: 3px;
}
.jumbotron {
padding-top: 30px;
padding-bottom: 30px;
margin-bottom: 30px;
color: inherit;
background-color: #eee;
}
.jumbotron h1,
.jumbotron .h1 {
color: inherit;
}
.jumbotron p {
margin-bottom: 15px;
font-size: 21px;
font-weight: 200;
}
.jumbotron > hr {
border-top-color: #d5d5d5;
}
.container .jumbotron,
.container-fluid .jumbotron {
padding-right: 15px;
padding-left: 15px;
border-radius: 6px;
}
.jumbotron .container {
max-width: 100%;
}
@media screen and (min-width: 768px) {
.jumbotron {
padding-top: 48px;
padding-bottom: 48px;
}
.container .jumbotron,
.container-fluid .jumbotron {
padding-right: 60px;
padding-left: 60px;
}
.jumbotron h1,
.jumbotron .h1 {
font-size: 63px;
}
}
.thumbnail {
display: block;
padding: 4px;
margin-bottom: 20px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: border .2s ease-in-out;
-o-transition: border .2s ease-in-out;
transition: border .2s ease-in-out;
}
.thumbnail > img,
.thumbnail a > img {
margin-right: auto;
margin-left: auto;
}
a.thumbnail:hover,
a.thumbnail:focus,
a.thumbnail.active {
border-color: #337ab7;
}
.thumbnail .caption {
padding: 9px;
color: #333;
}
.alert {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
}
.alert h4 {
margin-top: 0;
color: inherit;
}
.alert .alert-link {
font-weight: bold;
}
.alert > p,
.alert > ul {
margin-bottom: 0;
}
.alert > p + p {
margin-top: 5px;
}
.alert-dismissable,
.alert-dismissible {
padding-right: 35px;
}
.alert-dismissable .close,
.alert-dismissible .close {
position: relative;
top: -2px;
right: -21px;
color: inherit;
}
.alert-success {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.alert-success hr {
border-top-color: #c9e2b3;
}
.alert-success .alert-link {
color: #2b542c;
}
.alert-info {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.alert-info hr {
border-top-color: #a6e1ec;
}
.alert-info .alert-link {
color: #245269;
}
.alert-warning {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.alert-warning hr {
border-top-color: #f7e1b5;
}
.alert-warning .alert-link {
color: #66512c;
}
.alert-danger {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.alert-danger hr {
border-top-color: #e4b9c0;
}
.alert-danger .alert-link {
color: #843534;
}
@-webkit-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@-o-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
.progress {
height: 20px;
margin-bottom: 20px;
overflow: hidden;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
}
.progress-bar {
float: left;
width: 0;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #337ab7;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
-webkit-transition: width .6s ease;
-o-transition: width .6s ease;
transition: width .6s ease;
}
.progress-striped .progress-bar,
.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);
-webkit-background-size: 40px 40px;
background-size: 40px 40px;
}
.progress.active .progress-bar,
.progress-bar.active {
-webkit-animation: progress-bar-stripes 2s linear infinite;
-o-animation: progress-bar-stripes 2s linear infinite;
animation: progress-bar-stripes 2s linear infinite;
}
.progress-bar-success {
background-color: #5cb85c;
}
.progress-striped .progress-bar-success {
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);
}
.progress-bar-info {
background-color: #5bc0de;
}
.progress-striped .progress-bar-info {
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);
}
.progress-bar-warning {
background-color: #f0ad4e;
}
.progress-striped .progress-bar-warning {
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);
}
.progress-bar-danger {
background-color: #d9534f;
}
.progress-striped .progress-bar-danger {
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);
}
.media {
margin-top: 15px;
}
.media:first-child {
margin-top: 0;
}
.media,
.media-body {
overflow: hidden;
zoom: 1;
}
.media-body {
width: 10000px;
}
.media-object {
display: block;
}
.media-object.img-thumbnail {
max-width: none;
}
.media-right,
.media > .pull-right {
padding-left: 10px;
}
.media-left,
.media > .pull-left {
padding-right: 10px;
}
.media-left,
.media-right,
.media-body {
display: table-cell;
vertical-align: top;
}
.media-middle {
vertical-align: middle;
}
.media-bottom {
vertical-align: bottom;
}
.media-heading {
margin-top: 0;
margin-bottom: 5px;
}
.media-list {
padding-left: 0;
list-style: none;
}
.list-group {
padding-left: 0;
margin-bottom: 20px;
}
.list-group-item {
position: relative;
display: block;
padding: 10px 15px;
margin-bottom: -1px;
background-color: #fff;
border: 1px solid #ddd;
}
.list-group-item:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.list-group-item:last-child {
margin-bottom: 0;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px;
}
a.list-group-item,
button.list-group-item {
color: #555;
}
a.list-group-item .list-group-item-heading,
button.list-group-item .list-group-item-heading {
color: #333;
}
a.list-group-item:hover,
button.list-group-item:hover,
a.list-group-item:focus,
button.list-group-item:focus {
color: #555;
text-decoration: none;
background-color: #f5f5f5;
}
button.list-group-item {
width: 100%;
text-align: left;
}
.list-group-item.disabled,
.list-group-item.disabled:hover,
.list-group-item.disabled:focus {
color: #777;
cursor: not-allowed;
background-color: #eee;
}
.list-group-item.disabled .list-group-item-heading,
.list-group-item.disabled:hover .list-group-item-heading,
.list-group-item.disabled:focus .list-group-item-heading {
color: inherit;
}
.list-group-item.disabled .list-group-item-text,
.list-group-item.disabled:hover .list-group-item-text,
.list-group-item.disabled:focus .list-group-item-text {
color: #777;
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
z-index: 2;
color: #fff;
background-color: #337ab7;
border-color: #337ab7;
}
.list-group-item.active .list-group-item-heading,
.list-group-item.active:hover .list-group-item-heading,
.list-group-item.active:focus .list-group-item-heading,
.list-group-item.active .list-group-item-heading > small,
.list-group-item.active:hover .list-group-item-heading > small,
.list-group-item.active:focus .list-group-item-heading > small,
.list-group-item.active .list-group-item-heading > .small,
.list-group-item.active:hover .list-group-item-heading > .small,
.list-group-item.active:focus .list-group-item-heading > .small {
color: inherit;
}
.list-group-item.active .list-group-item-text,
.list-group-item.active:hover .list-group-item-text,
.list-group-item.active:focus .list-group-item-text {
color: #c7ddef;
}
.list-group-item-success {
color: #3c763d;
background-color: #dff0d8;
}
a.list-group-item-success,
button.list-group-item-success {
color: #3c763d;
}
a.list-group-item-success .list-group-item-heading,
button.list-group-item-success .list-group-item-heading {
color: inherit;
}
a.list-group-item-success:hover,
button.list-group-item-success:hover,
a.list-group-item-success:focus,
button.list-group-item-success:focus {
color: #3c763d;
background-color: #d0e9c6;
}
a.list-group-item-success.active,
button.list-group-item-success.active,
a.list-group-item-success.active:hover,
button.list-group-item-success.active:hover,
a.list-group-item-success.active:focus,
button.list-group-item-success.active:focus {
color: #fff;
background-color: #3c763d;
border-color: #3c763d;
}
.list-group-item-info {
color: #31708f;
background-color: #d9edf7;
}
a.list-group-item-info,
button.list-group-item-info {
color: #31708f;
}
a.list-group-item-info .list-group-item-heading,
button.list-group-item-info .list-group-item-heading {
color: inherit;
}
a.list-group-item-info:hover,
button.list-group-item-info:hover,
a.list-group-item-info:focus,
button.list-group-item-info:focus {
color: #31708f;
background-color: #c4e3f3;
}
a.list-group-item-info.active,
button.list-group-item-info.active,
a.list-group-item-info.active:hover,
button.list-group-item-info.active:hover,
a.list-group-item-info.active:focus,
button.list-group-item-info.active:focus {
color: #fff;
background-color: #31708f;
border-color: #31708f;
}
.list-group-item-warning {
color: #8a6d3b;
background-color: #fcf8e3;
}
a.list-group-item-warning,
button.list-group-item-warning {
color: #8a6d3b;
}
a.list-group-item-warning .list-group-item-heading,
button.list-group-item-warning .list-group-item-heading {
color: inherit;
}
a.list-group-item-warning:hover,
button.list-group-item-warning:hover,
a.list-group-item-warning:focus,
button.list-group-item-warning:focus {
color: #8a6d3b;
background-color: #faf2cc;
}
a.list-group-item-warning.active,
button.list-group-item-warning.active,
a.list-group-item-warning.active:hover,
button.list-group-item-warning.active:hover,
a.list-group-item-warning.active:focus,
button.list-group-item-warning.active:focus {
color: #fff;
background-color: #8a6d3b;
border-color: #8a6d3b;
}
.list-group-item-danger {
color: #a94442;
background-color: #f2dede;
}
a.list-group-item-danger,
button.list-group-item-danger {
color: #a94442;
}
a.list-group-item-danger .list-group-item-heading,
button.list-group-item-danger .list-group-item-heading {
color: inherit;
}
a.list-group-item-danger:hover,
button.list-group-item-danger:hover,
a.list-group-item-danger:focus,
button.list-group-item-danger:focus {
color: #a94442;
background-color: #ebcccc;
}
a.list-group-item-danger.active,
button.list-group-item-danger.active,
a.list-group-item-danger.active:hover,
button.list-group-item-danger.active:hover,
a.list-group-item-danger.active:focus,
button.list-group-item-danger.active:focus {
color: #fff;
background-color: #a94442;
border-color: #a94442;
}
.list-group-item-heading {
margin-top: 0;
margin-bottom: 5px;
}
.list-group-item-text {
margin-bottom: 0;
line-height: 1.3;
}
.panel {
margin-bottom: 20px;
background-color: #fff;
border: 1px solid transparent;
border-radius: 4px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
}
.panel-body {
padding: 15px;
}
.panel-heading {
padding: 10px 15px;
border-bottom: 1px solid transparent;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel-heading > .dropdown .dropdown-toggle {
color: inherit;
}
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: 16px;
color: inherit;
}
.panel-title > a,
.panel-title > small,
.panel-title > .small,
.panel-title > small > a,
.panel-title > .small > a {
color: inherit;
}
.panel-footer {
padding: 10px 15px;
background-color: #f5f5f5;
border-top: 1px solid #ddd;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .list-group,
.panel > .panel-collapse > .list-group {
margin-bottom: 0;
}
.panel > .list-group .list-group-item,
.panel > .panel-collapse > .list-group .list-group-item {
border-width: 1px 0;
border-radius: 0;
}
.panel > .list-group:first-child .list-group-item:first-child,
.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child {
border-top: 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .list-group:last-child .list-group-item:last-child,
.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child {
border-bottom: 0;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .panel-heading + .panel-collapse > .list-group .list-group-item:first-child {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.panel-heading + .list-group .list-group-item:first-child {
border-top-width: 0;
}
.list-group + .panel-footer {
border-top-width: 0;
}
.panel > .table,
.panel > .table-responsive > .table,
.panel > .panel-collapse > .table {
margin-bottom: 0;
}
.panel > .table caption,
.panel > .table-responsive > .table caption,
.panel > .panel-collapse > .table caption {
padding-right: 15px;
padding-left: 15px;
}
.panel > .table:first-child,
.panel > .table-responsive:first-child > .table:first-child {
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child {
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
border-top-left-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
border-top-right-radius: 3px;
}
.panel > .table:last-child,
.panel > .table-responsive:last-child > .table:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
border-bottom-right-radius: 3px;
}
.panel > .panel-body + .table,
.panel > .panel-body + .table-responsive,
.panel > .table + .panel-body,
.panel > .table-responsive + .panel-body {
border-top: 1px solid #ddd;
}
.panel > .table > tbody:first-child > tr:first-child th,
.panel > .table > tbody:first-child > tr:first-child td {
border-top: 0;
}
.panel > .table-bordered,
.panel > .table-responsive > .table-bordered {
border: 0;
}
.panel > .table-bordered > thead > tr > th:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
.panel > .table-bordered > tbody > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
.panel > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-bordered > thead > tr > td:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
.panel > .table-bordered > tbody > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
.panel > .table-bordered > tfoot > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.panel > .table-bordered > thead > tr > th:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
.panel > .table-bordered > tbody > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
.panel > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-bordered > thead > tr > td:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
.panel > .table-bordered > tbody > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
.panel > .table-bordered > tfoot > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.panel > .table-bordered > thead > tr:first-child > td,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
.panel > .table-bordered > tbody > tr:first-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
.panel > .table-bordered > thead > tr:first-child > th,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
.panel > .table-bordered > tbody > tr:first-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
border-bottom: 0;
}
.panel > .table-bordered > tbody > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
.panel > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-bordered > tbody > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
.panel > .table-bordered > tfoot > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
border-bottom: 0;
}
.panel > .table-responsive {
margin-bottom: 0;
border: 0;
}
.panel-group {
margin-bottom: 20px;
}
.panel-group .panel {
margin-bottom: 0;
border-radius: 4px;
}
.panel-group .panel + .panel {
margin-top: 5px;
}
.panel-group .panel-heading {
border-bottom: 0;
}
.panel-group .panel-heading + .panel-collapse > .panel-body,
.panel-group .panel-heading + .panel-collapse > .list-group {
border-top: 1px solid #ddd;
}
.panel-group .panel-footer {
border-top: 0;
}
.panel-group .panel-footer + .panel-collapse .panel-body {
border-bottom: 1px solid #ddd;
}
.panel-default {
border-color: #ddd;
}
.panel-default > .panel-heading {
color: #333;
background-color: #f5f5f5;
border-color: #ddd;
}
.panel-default > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ddd;
}
.panel-default > .panel-heading .badge {
color: #f5f5f5;
background-color: #333;
}
.panel-default > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ddd;
}
.panel-primary {
border-color: #337ab7;
}
.panel-primary > .panel-heading {
color: #fff;
background-color: #337ab7;
border-color: #337ab7;
}
.panel-primary > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #337ab7;
}
.panel-primary > .panel-heading .badge {
color: #337ab7;
background-color: #fff;
}
.panel-primary > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #337ab7;
}
.panel-success {
border-color: #d6e9c6;
}
.panel-success > .panel-heading {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.panel-success > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #d6e9c6;
}
.panel-success > .panel-heading .badge {
color: #dff0d8;
background-color: #3c763d;
}
.panel-success > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #d6e9c6;
}
.panel-info {
border-color: #bce8f1;
}
.panel-info > .panel-heading {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.panel-info > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #bce8f1;
}
.panel-info > .panel-heading .badge {
color: #d9edf7;
background-color: #31708f;
}
.panel-info > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #bce8f1;
}
.panel-warning {
border-color: #faebcc;
}
.panel-warning > .panel-heading {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.panel-warning > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #faebcc;
}
.panel-warning > .panel-heading .badge {
color: #fcf8e3;
background-color: #8a6d3b;
}
.panel-warning > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #faebcc;
}
.panel-danger {
border-color: #ebccd1;
}
.panel-danger > .panel-heading {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.panel-danger > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ebccd1;
}
.panel-danger > .panel-heading .badge {
color: #f2dede;
background-color: #a94442;
}
.panel-danger > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ebccd1;
}
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object,
.embed-responsive video {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
.embed-responsive-16by9 {
padding-bottom: 56.25%;
}
.embed-responsive-4by3 {
padding-bottom: 75%;
}
.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
}
.well blockquote {
border-color: #ddd;
border-color: rgba(0, 0, 0, .15);
}
.well-lg {
padding: 24px;
border-radius: 6px;
}
.well-sm {
padding: 9px;
border-radius: 3px;
}
.close {
float: right;
font-size: 21px;
font-weight: bold;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
filter: alpha(opacity=20);
opacity: .2;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
filter: alpha(opacity=50);
opacity: .5;
}
button.close {
-webkit-appearance: none;
padding: 0;
cursor: pointer;
background: transparent;
border: 0;
}
.modal-open {
overflow: hidden;
}
.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1050;
display: none;
overflow: hidden;
-webkit-overflow-scrolling: touch;
outline: 0;
}
.modal.fade .modal-dialog {
-webkit-transition: -webkit-transform .3s ease-out;
-o-transition: -o-transform .3s ease-out;
transition: transform .3s ease-out;
-webkit-transform: translate(0, -25%);
-ms-transform: translate(0, -25%);
-o-transform: translate(0, -25%);
transform: translate(0, -25%);
}
.modal.in .modal-dialog {
-webkit-transform: translate(0, 0);
-ms-transform: translate(0, 0);
-o-transform: translate(0, 0);
transform: translate(0, 0);
}
.modal-open .modal {
overflow-x: hidden;
overflow-y: auto;
}
.modal-dialog {
position: relative;
width: auto;
margin: 10px;
}
.modal-content {
position: relative;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #999;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
outline: 0;
-webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
}
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1040;
background-color: #000;
}
.modal-backdrop.fade {
filter: alpha(opacity=0);
opacity: 0;
}
.modal-backdrop.in {
filter: alpha(opacity=50);
opacity: .5;
}
.modal-header {
padding: 15px;
border-bottom: 1px solid #e5e5e5;
}
.modal-header .close {
margin-top: -2px;
}
.modal-title {
margin: 0;
line-height: 1.42857143;
}
.modal-body {
position: relative;
padding: 15px;
}
.modal-footer {
padding: 15px;
text-align: right;
border-top: 1px solid #e5e5e5;
}
.modal-footer .btn + .btn {
margin-bottom: 0;
margin-left: 5px;
}
.modal-footer .btn-group .btn + .btn {
margin-left: -1px;
}
.modal-footer .btn-block + .btn-block {
margin-left: 0;
}
.modal-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll;
}
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
.modal-content {
-webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
}
.modal-sm {
width: 300px;
}
}
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
.tooltip {
position: absolute;
z-index: 1070;
display: block;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-weight: normal;
line-height: 1.42857143;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
letter-spacing: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
white-space: normal;
filter: alpha(opacity=0);
opacity: 0;
line-break: auto;
}
.tooltip.in {
filter: alpha(opacity=90);
opacity: .9;
}
.tooltip.top {
padding: 5px 0;
margin-top: -3px;
}
.tooltip.right {
padding: 0 5px;
margin-left: 3px;
}
.tooltip.bottom {
padding: 5px 0;
margin-top: 3px;
}
.tooltip.left {
padding: 0 5px;
margin-left: -3px;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #fff;
text-align: center;
background-color: #000;
border-radius: 4px;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-left .tooltip-arrow {
right: 5px;
bottom: 0;
margin-bottom: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-right .tooltip-arrow {
bottom: 0;
left: 5px;
margin-bottom: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-width: 5px 5px 5px 0;
border-right-color: #000;
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-width: 5px 0 5px 5px;
border-left-color: #000;
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-left .tooltip-arrow {
top: 0;
right: 5px;
margin-top: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-right .tooltip-arrow {
top: 0;
left: 5px;
margin-top: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1060;
display: none;
max-width: 276px;
padding: 1px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
font-style: normal;
font-weight: normal;
line-height: 1.42857143;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
letter-spacing: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
white-space: normal;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
line-break: auto;
}
.popover.top {
margin-top: -10px;
}
.popover.right {
margin-left: 10px;
}
.popover.bottom {
margin-top: 10px;
}
.popover.left {
margin-left: -10px;
}
.popover-title {
padding: 8px 14px;
margin: 0;
font-size: 14px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
border-radius: 5px 5px 0 0;
}
.popover-content {
padding: 9px 14px;
}
.popover > .arrow,
.popover > .arrow:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.popover > .arrow {
border-width: 11px;
}
.popover > .arrow:after {
content: "";
border-width: 10px;
}
.popover.top > .arrow {
bottom: -11px;
left: 50%;
margin-left: -11px;
border-top-color: #999;
border-top-color: rgba(0, 0, 0, .25);
border-bottom-width: 0;
}
.popover.top > .arrow:after {
bottom: 1px;
margin-left: -10px;
content: " ";
border-top-color: #fff;
border-bottom-width: 0;
}
.popover.right > .arrow {
top: 50%;
left: -11px;
margin-top: -11px;
border-right-color: #999;
border-right-color: rgba(0, 0, 0, .25);
border-left-width: 0;
}
.popover.right > .arrow:after {
bottom: -10px;
left: 1px;
content: " ";
border-right-color: #fff;
border-left-width: 0;
}
.popover.bottom > .arrow {
top: -11px;
left: 50%;
margin-left: -11px;
border-top-width: 0;
border-bottom-color: #999;
border-bottom-color: rgba(0, 0, 0, .25);
}
.popover.bottom > .arrow:after {
top: 1px;
margin-left: -10px;
content: " ";
border-top-width: 0;
border-bottom-color: #fff;
}
.popover.left > .arrow {
top: 50%;
right: -11px;
margin-top: -11px;
border-right-width: 0;
border-left-color: #999;
border-left-color: rgba(0, 0, 0, .25);
}
.popover.left > .arrow:after {
right: 1px;
bottom: -10px;
content: " ";
border-right-width: 0;
border-left-color: #fff;
}
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-inner > .item {
position: relative;
display: none;
-webkit-transition: .6s ease-in-out left;
-o-transition: .6s ease-in-out left;
transition: .6s ease-in-out left;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
}
@media all and (transform-3d), (-webkit-transform-3d) {
.carousel-inner > .item {
-webkit-transition: -webkit-transform .6s ease-in-out;
-o-transition: -o-transform .6s ease-in-out;
transition: transform .6s ease-in-out;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-perspective: 1000px;
perspective: 1000px;
}
.carousel-inner > .item.next,
.carousel-inner > .item.active.right {
left: 0;
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
}
.carousel-inner > .item.prev,
.carousel-inner > .item.active.left {
left: 0;
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
}
.carousel-inner > .item.next.left,
.carousel-inner > .item.prev.right,
.carousel-inner > .item.active {
left: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
.carousel-inner > .active,
.carousel-inner > .next,
.carousel-inner > .prev {
display: block;
}
.carousel-inner > .active {
left: 0;
}
.carousel-inner > .next,
.carousel-inner > .prev {
position: absolute;
top: 0;
width: 100%;
}
.carousel-inner > .next {
left: 100%;
}
.carousel-inner > .prev {
left: -100%;
}
.carousel-inner > .next.left,
.carousel-inner > .prev.right {
left: 0;
}
.carousel-inner > .active.left {
left: -100%;
}
.carousel-inner > .active.right {
left: 100%;
}
.carousel-control {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 15%;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
background-color: rgba(0, 0, 0, 0);
filter: alpha(opacity=50);
opacity: .5;
}
.carousel-control.left {
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
background-repeat: repeat-x;
}
.carousel-control.right {
right: 0;
left: auto;
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
background-repeat: repeat-x;
}
.carousel-control:hover,
.carousel-control:focus {
color: #fff;
text-decoration: none;
filter: alpha(opacity=90);
outline: 0;
opacity: .9;
}
.carousel-control .icon-prev,
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
margin-top: -10px;
}
.carousel-control .icon-prev,
.carousel-control .glyphicon-chevron-left {
left: 50%;
margin-left: -10px;
}
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-right {
right: 50%;
margin-right: -10px;
}
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 20px;
height: 20px;
font-family: serif;
line-height: 1;
}
.carousel-control .icon-prev:before {
content: '\2039';
}
.carousel-control .icon-next:before {
content: '\203a';
}
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 15;
width: 60%;
padding-left: 0;
margin-left: -30%;
text-align: center;
list-style: none;
}
.carousel-indicators li {
display: inline-block;
width: 10px;
height: 10px;
margin: 1px;
text-indent: -999px;
cursor: pointer;
background-color: #000 \9;
background-color: rgba(0, 0, 0, 0);
border: 1px solid #fff;
border-radius: 10px;
}
.carousel-indicators .active {
width: 12px;
height: 12px;
margin: 0;
background-color: #fff;
}
.carousel-caption {
position: absolute;
right: 15%;
bottom: 20px;
left: 15%;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
}
.carousel-caption .btn {
text-shadow: none;
}
@media screen and (min-width: 768px) {
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 30px;
height: 30px;
margin-top: -10px;
font-size: 30px;
}
.carousel-control .glyphicon-chevron-left,
.carousel-control .icon-prev {
margin-left: -10px;
}
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next {
margin-right: -10px;
}
.carousel-caption {
right: 20%;
left: 20%;
padding-bottom: 30px;
}
.carousel-indicators {
bottom: 20px;
}
}
.clearfix:before,
.clearfix:after,
.dl-horizontal dd:before,
.dl-horizontal dd:after,
.container:before,
.container:after,
.container-fluid:before,
.container-fluid:after,
.row:before,
.row:after,
.form-horizontal .form-group:before,
.form-horizontal .form-group:after,
.btn-toolbar:before,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:before,
.btn-group-vertical > .btn-group:after,
.nav:before,
.nav:after,
.navbar:before,
.navbar:after,
.navbar-header:before,
.navbar-header:after,
.navbar-collapse:before,
.navbar-collapse:after,
.pager:before,
.pager:after,
.panel-body:before,
.panel-body:after,
.modal-header:before,
.modal-header:after,
.modal-footer:before,
.modal-footer:after {
display: table;
content: " ";
}
.clearfix:after,
.dl-horizontal dd:after,
.container:after,
.container-fluid:after,
.row:after,
.form-horizontal .form-group:after,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:after,
.nav:after,
.navbar:after,
.navbar-header:after,
.navbar-collapse:after,
.pager:after,
.panel-body:after,
.modal-header:after,
.modal-footer:after {
clear: both;
}
.center-block {
display: block;
margin-right: auto;
margin-left: auto;
}
.pull-right {
float: right !important;
}
.pull-left {
float: left !important;
}
.hide {
display: none !important;
}
.show {
display: block !important;
}
.invisible {
visibility: hidden;
}
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.hidden {
display: none !important;
}
.affix {
position: fixed;
}
@-ms-viewport {
width: device-width;
}
.visible-xs,
.visible-sm,
.visible-md,
.visible-lg {
display: none !important;
}
.visible-xs-block,
.visible-xs-inline,
.visible-xs-inline-block,
.visible-sm-block,
.visible-sm-inline,
.visible-sm-inline-block,
.visible-md-block,
.visible-md-inline,
.visible-md-inline-block,
.visible-lg-block,
.visible-lg-inline,
.visible-lg-inline-block {
display: none !important;
}
@media (max-width: 767px) {
.visible-xs {
display: block !important;
}
table.visible-xs {
display: table !important;
}
tr.visible-xs {
display: table-row !important;
}
th.visible-xs,
td.visible-xs {
display: table-cell !important;
}
}
@media (max-width: 767px) {
.visible-xs-block {
display: block !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline {
display: inline !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline-block {
display: inline-block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm {
display: block !important;
}
table.visible-sm {
display: table !important;
}
tr.visible-sm {
display: table-row !important;
}
th.visible-sm,
td.visible-sm {
display: table-cell !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-block {
display: block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline {
display: inline !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline-block {
display: inline-block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md {
display: block !important;
}
table.visible-md {
display: table !important;
}
tr.visible-md {
display: table-row !important;
}
th.visible-md,
td.visible-md {
display: table-cell !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-block {
display: block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline {
display: inline !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline-block {
display: inline-block !important;
}
}
@media (min-width: 1200px) {
.visible-lg {
display: block !important;
}
table.visible-lg {
display: table !important;
}
tr.visible-lg {
display: table-row !important;
}
th.visible-lg,
td.visible-lg {
display: table-cell !important;
}
}
@media (min-width: 1200px) {
.visible-lg-block {
display: block !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline {
display: inline !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline-block {
display: inline-block !important;
}
}
@media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.hidden-sm {
display: none !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.hidden-md {
display: none !important;
}
}
@media (min-width: 1200px) {
.hidden-lg {
display: none !important;
}
}
.visible-print {
display: none !important;
}
@media print {
.visible-print {
display: block !important;
}
table.visible-print {
display: table !important;
}
tr.visible-print {
display: table-row !important;
}
th.visible-print,
td.visible-print {
display: table-cell !important;
}
}
.visible-print-block {
display: none !important;
}
@media print {
.visible-print-block {
display: block !important;
}
}
.visible-print-inline {
display: none !important;
}
@media print {
.visible-print-inline {
display: inline !important;
}
}
.visible-print-inline-block {
display: none !important;
}
@media print {
.visible-print-inline-block {
display: inline-block !important;
}
}
@media print {
.hidden-print {
display: none !important;
}
}
/*# sourceMappingURL=bootstrap.css.map */
| Humsen/web/web-mobile/WebContent/plugins/bootstrap/css/bootstrap.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/bootstrap/css/bootstrap.css",
"repo_id": "Humsen",
"token_count": 61644
} | 36 |
List of CodeMirror contributors. Updated before every release.
4r2r
Aaron Brooks
Abdelouahab
Abe Fettig
Adam Ahmed
Adam King
adanlobato
Adán Lobato
Adrian Aichner
aeroson
Ahmad Amireh
Ahmad M. Zawawi
ahoward
Akeksandr Motsjonov
Alberto González Palomo
Alberto Pose
Albert Xing
Alexander Pavlov
Alexander Schepanovski
Alexander Shvets
Alexander Solovyov
Alexandre Bique
alexey-k
Alex Piggott
Aliaksei Chapyzhenka
Amsul
amuntean
Amy
Ananya Sen
anaran
AndersMad
Anders Nawroth
Anderson Mesquita
Andrea G
Andreas Reischuck
Andre von Houck
Andrey Fedorov
Andrey Klyuchnikov
Andrey Lushnikov
Andy Joslin
Andy Kimball
Andy Li
angelozerr
angelo.zerr@gmail.com
Ankit
Ankit Ahuja
Ansel Santosa
Anthony Grimes
Anton Kovalyov
areos
as3boyan
AtomicPages LLC
Atul Bhouraskar
Aurelian Oancea
Bastian Müller
Bem Jones-Bey
benbro
Beni Cherniavsky-Paskin
Benjamin DeCoste
Ben Keen
Bernhard Sirlinger
Bert Chang
Billy Moon
binny
B Krishna Chaitanya
Blaine G
blukat29
boomyjee
borawjm
Brandon Frohs
Brandon Wamboldt
Brett Zamir
Brian Grinstead
Brian Sletten
Bruce Mitchener
Chandra Sekhar Pydi
Charles Skelton
Cheah Chu Yeow
Chris Coyier
Chris Granger
Chris Houseknecht
Chris Morgan
Christian Oyarzun
Christian Petrov
Christopher Brown
ciaranj
CodeAnimal
ComFreek
Curtis Gagliardi
dagsta
daines
Dale Jung
Dan Bentley
Dan Heberden
Daniel, Dao Quang Minh
Daniele Di Sarli
Daniel Faust
Daniel Huigens
Daniel KJ
Daniel Neel
Daniel Parnell
Danny Yoo
darealshinji
Darius Roberts
Dave Myers
David Mignot
David Pathakjee
David Vázquez
deebugger
Deep Thought
Devon Carew
dignifiedquire
Dimage Sapelkin
Dmitry Kiselyov
domagoj412
Dominator008
Domizio Demichelis
Doug Wikle
Drew Bratcher
Drew Hintz
Drew Khoury
Dror BG
duralog
eborden
edsharp
ekhaled
Enam Mijbah Noor
Eric Allam
eustas
Fabien O'Carroll
Fabio Zendhi Nagao
Faiza Alsaied
Fauntleroy
fbuchinger
feizhang365
Felipe Lalanne
Felix Raab
Filip Noetzel
flack
ForbesLindesay
Forbes Lindesay
Ford_Lawnmower
Forrest Oliphant
Frank Wiegand
Gabriel Gheorghian
Gabriel Horner
Gabriel Nahmias
galambalazs
Gautam Mehta
gekkoe
Gerard Braad
Gergely Hegykozi
Giovanni Calò
Glenn Jorde
Glenn Ruehle
Golevka
Gordon Smith
Grant Skinner
greengiant
Gregory Koberger
Guillaume Massé
Guillaume Massé
Gustavo Rodrigues
Hakan Tunc
Hans Engel
Hardest
Hasan Karahan
Herculano Campos
Hiroyuki Makino
hitsthings
Hocdoc
Ian Beck
Ian Dickinson
Ian Wehrman
Ian Wetherbee
Ice White
ICHIKAWA, Yuji
ilvalle
Ingo Richter
Irakli Gozalishvili
Ivan Kurnosov
Jacob Lee
Jakob Miland
Jakub Vrana
Jakub Vrána
James Campos
James Thorne
Jamie Hill
Jan Jongboom
jankeromnes
Jan Keromnes
Jan Odvarko
Jan T. Sott
Jared Forsyth
Jason
Jason Barnabe
Jason Grout
Jason Johnston
Jason San Jose
Jason Siefken
Jaydeep Solanki
Jean Boussier
jeffkenton
Jeff Pickhardt
jem (graphite)
Jeremy Parmenter
Jochen Berger
Johan Ask
John Connor
John Lees-Miller
John Snelson
John Van Der Loo
Jonathan Malmaud
jongalloway
Jon Malmaud
Jon Sangster
Joost-Wim Boekesteijn
Joseph Pecoraro
Joshua Newman
Josh Watzman
jots
jsoojeon
Juan Benavides Romero
Jucovschi Constantin
Juho Vuori
Justin Hileman
jwallers@gmail.com
kaniga
Ken Newman
Ken Rockot
Kevin Sawicki
Kevin Ushey
Klaus Silveira
Koh Zi Han, Cliff
komakino
Konstantin Lopuhin
koops
ks-ifware
kubelsmieci
KwanEsq
Lanfei
Lanny
Laszlo Vidacs
leaf corcoran
Leonid Khachaturov
Leon Sorokin
Leonya Khachaturov
Liam Newman
LM
lochel
Lorenzo Stoakes
Luciano Longo
Luke Stagner
lynschinzer
Maksim Lin
Maksym Taran
Malay Majithia
Manuel Rego Casasnovas
Marat Dreizin
Marcel Gerber
Marco Aurélio
Marco Munizaga
Marcus Bointon
Marek Rudnicki
Marijn Haverbeke
Mário Gonçalves
Mario Pietsch
Mark Lentczner
Marko Bonaci
Martin Balek
Martín Gaitán
Martin Hasoň
Mason Malone
Mateusz Paprocki
Mathias Bynens
mats cronqvist
Matthew Beale
Matthias Bussonnier
Matthias BUSSONNIER
Matt McDonald
Matt Pass
Matt Sacks
mauricio
Maximilian Hils
Maxim Kraev
Max Kirsch
Max Xiantu
mbarkhau
Metatheos
Micah Dubinko
Michael Lehenbauer
Michael Zhou
Mighty Guava
Miguel Castillo
mihailik
Mike
Mike Brevoort
Mike Diaz
Mike Ivanov
Mike Kadin
MinRK
Miraculix87
misfo
mloginov
Moritz Schwörer
mps
mtaran-google
Narciso Jaramillo
Nathan Williams
ndr
nerbert
nextrevision
ngn
nguillaumin
Ng Zhi An
Nicholas Bollweg
Nicholas Bollweg (Nick)
Nick Small
Niels van Groningen
nightwing
Nikita Beloglazov
Nikita Vasilyev
Nikolay Kostov
nilp0inter
Nisarg Jhaveri
nlwillia
Norman Rzepka
pablo
Page
Panupong Pasupat
paris
Patil Arpith
Patrick Stoica
Patrick Strawderman
Paul Garvin
Paul Ivanov
Pavel Feldman
Pavel Strashkin
Paweł Bartkiewicz
peteguhl
Peter Flynn
peterkroon
Peter Kroon
prasanthj
Prasanth J
Radek Piórkowski
Rahul
Randall Mason
Randy Burden
Randy Edmunds
Rasmus Erik Voel Jensen
Ray Ratchup
Richard van der Meer
Richard Z.H. Wang
Robert Crossfield
Roberto Abdelkader Martínez Pérez
robertop23
Robert Plummer
Ruslan Osmanov
Ryan Prior
sabaca
Samuel Ainsworth
sandeepshetty
Sander AKA Redsandro
santec
Sascha Peilicke
satchmorun
sathyamoorthi
SCLINIC\jdecker
Scott Aikin
Scott Goodhew
Sebastian Zaha
shaund
shaun gilchrist
Shawn A
sheopory
Shiv Deepak
Shmuel Englard
Shubham Jain
silverwind
snasa
soliton4
sonson
spastorelli
srajanpaliwal
Stanislav Oaserele
Stas Kobzar
Stefan Borsje
Steffen Beyer
Steve O'Hara
stoskov
Taha Jahangir
Takuji Shimokawa
Tarmil
tel
tfjgeorge
Thaddee Tyl
TheHowl
think
Thomas Dvornik
Thomas Schmid
Tim Alby
Tim Baumann
Timothy Farrell
Timothy Hatcher
TobiasBg
Tomas-A
Tomas Varaneckas
Tom Erik Støwer
Tom MacWright
Tony Jian
Travis Heppe
Triangle717
twifkak
Vestimir Markov
vf
Vincent Woo
Volker Mische
wenli
Wesley Wiser
Will Binns-Smith
William Jamieson
William Stein
Willy
Wojtek Ptak
Xavier Mendez
Yassin N. Hassan
YNH Webdev
Yunchi Luo
Yuvi Panda
Zachary Dremann
Zhang Hao
zziuni
魏鹏刚
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/AUTHORS/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/AUTHORS",
"repo_id": "Humsen",
"token_count": 2231
} | 37 |
// 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"), require("../fold/xml-fold"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../fold/xml-fold"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineOption("matchTags", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.off("cursorActivity", doMatchTags);
cm.off("viewportChange", maybeUpdateMatch);
clear(cm);
}
if (val) {
cm.state.matchBothTags = typeof val == "object" && val.bothTags;
cm.on("cursorActivity", doMatchTags);
cm.on("viewportChange", maybeUpdateMatch);
doMatchTags(cm);
}
});
function clear(cm) {
if (cm.state.tagHit) cm.state.tagHit.clear();
if (cm.state.tagOther) cm.state.tagOther.clear();
cm.state.tagHit = cm.state.tagOther = null;
}
function doMatchTags(cm) {
cm.state.failedTagMatch = false;
cm.operation(function() {
clear(cm);
if (cm.somethingSelected()) return;
var cur = cm.getCursor(), range = cm.getViewport();
range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to);
var match = CodeMirror.findMatchingTag(cm, cur, range);
if (!match) return;
if (cm.state.matchBothTags) {
var hit = match.at == "open" ? match.open : match.close;
if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: "CodeMirror-matchingtag"});
}
var other = match.at == "close" ? match.open : match.close;
if (other)
cm.state.tagOther = cm.markText(other.from, other.to, {className: "CodeMirror-matchingtag"});
else
cm.state.failedTagMatch = true;
});
}
function maybeUpdateMatch(cm) {
if (cm.state.failedTagMatch) doMatchTags(cm);
}
CodeMirror.commands.toMatchingTag = function(cm) {
var found = CodeMirror.findMatchingTag(cm, cm.getCursor());
if (found) {
var other = found.at == "close" ? found.open : found.close;
if (other) cm.extendSelection(other.to, other.from);
}
};
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/edit/matchtags.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/edit/matchtags.js",
"repo_id": "Humsen",
"token_count": 945
} | 38 |
// 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"), require("../../mode/sql/sql"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../../mode/sql/sql"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var tables;
var defaultTable;
var keywords;
var CONS = {
QUERY_DIV: ";",
ALIAS_KEYWORD: "AS"
};
var Pos = CodeMirror.Pos;
function getKeywords(editor) {
var mode = editor.doc.modeOption;
if (mode === "sql") mode = "text/x-sql";
return CodeMirror.resolveMode(mode).keywords;
}
function getText(item) {
return typeof item == "string" ? item : item.text;
}
function getItem(list, item) {
if (!list.slice) return list[item];
for (var i = list.length - 1; i >= 0; i--) if (getText(list[i]) == item)
return list[i];
}
function shallowClone(object) {
var result = {};
for (var key in object) if (object.hasOwnProperty(key))
result[key] = object[key];
return result;
}
function match(string, word) {
var len = string.length;
var sub = getText(word).substr(0, len);
return string.toUpperCase() === sub.toUpperCase();
}
function addMatches(result, search, wordlist, formatter) {
for (var word in wordlist) {
if (!wordlist.hasOwnProperty(word)) continue;
if (Array.isArray(wordlist)) {
word = wordlist[word];
}
if (match(search, word)) {
result.push(formatter(word));
}
}
}
function cleanName(name) {
// Get rid name from backticks(`) and preceding dot(.)
if (name.charAt(0) == ".") {
name = name.substr(1);
}
return name.replace(/`/g, "");
}
function insertBackticks(name) {
var nameParts = getText(name).split(".");
for (var i = 0; i < nameParts.length; i++)
nameParts[i] = "`" + nameParts[i] + "`";
var escaped = nameParts.join(".");
if (typeof name == "string") return escaped;
name = shallowClone(name);
name.text = escaped;
return name;
}
function nameCompletion(cur, token, result, editor) {
// Try to complete table, colunm names and return start position of completion
var useBacktick = false;
var nameParts = [];
var start = token.start;
var cont = true;
while (cont) {
cont = (token.string.charAt(0) == ".");
useBacktick = useBacktick || (token.string.charAt(0) == "`");
start = token.start;
nameParts.unshift(cleanName(token.string));
token = editor.getTokenAt(Pos(cur.line, token.start));
if (token.string == ".") {
cont = true;
token = editor.getTokenAt(Pos(cur.line, token.start));
}
}
// Try to complete table names
var string = nameParts.join(".");
addMatches(result, string, tables, function(w) {
return useBacktick ? insertBackticks(w) : w;
});
// Try to complete columns from defaultTable
addMatches(result, string, defaultTable, function(w) {
return useBacktick ? insertBackticks(w) : w;
});
// Try to complete columns
string = nameParts.pop();
var table = nameParts.join(".");
// Check if table is available. If not, find table by Alias
if (!getItem(tables, table))
table = findTableByAlias(table, editor);
var columns = getItem(tables, table);
if (columns && Array.isArray(tables) && columns.columns)
columns = columns.columns;
if (columns) {
addMatches(result, string, columns, function(w) {
if (typeof w == "string") {
w = table + "." + w;
} else {
w = shallowClone(w);
w.text = table + "." + w.text;
}
return useBacktick ? insertBackticks(w) : w;
});
}
return start;
}
function eachWord(lineText, f) {
if (!lineText) return;
var excepted = /[,;]/g;
var words = lineText.split(" ");
for (var i = 0; i < words.length; i++) {
f(words[i]?words[i].replace(excepted, '') : '');
}
}
function convertCurToNumber(cur) {
// max characters of a line is 999,999.
return cur.line + cur.ch / Math.pow(10, 6);
}
function convertNumberToCur(num) {
return Pos(Math.floor(num), +num.toString().split('.').pop());
}
function findTableByAlias(alias, editor) {
var doc = editor.doc;
var fullQuery = doc.getValue();
var aliasUpperCase = alias.toUpperCase();
var previousWord = "";
var table = "";
var separator = [];
var validRange = {
start: Pos(0, 0),
end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length)
};
//add separator
var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV);
while(indexOfSeparator != -1) {
separator.push(doc.posFromIndex(indexOfSeparator));
indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1);
}
separator.unshift(Pos(0, 0));
separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));
//find valid range
var prevItem = 0;
var current = convertCurToNumber(editor.getCursor());
for (var i=0; i< separator.length; i++) {
var _v = convertCurToNumber(separator[i]);
if (current > prevItem && current <= _v) {
validRange = { start: convertNumberToCur(prevItem), end: convertNumberToCur(_v) };
break;
}
prevItem = _v;
}
var query = doc.getRange(validRange.start, validRange.end, false);
for (var i = 0; i < query.length; i++) {
var lineText = query[i];
eachWord(lineText, function(word) {
var wordUpperCase = word.toUpperCase();
if (wordUpperCase === aliasUpperCase && getItem(tables, previousWord))
table = previousWord;
if (wordUpperCase !== CONS.ALIAS_KEYWORD)
previousWord = word;
});
if (table) break;
}
return table;
}
CodeMirror.registerHelper("hint", "sql", function(editor, options) {
tables = (options && options.tables) || {};
var defaultTableName = options && options.defaultTable;
defaultTable = (defaultTableName && getItem(tables, defaultTableName)) || [];
keywords = keywords || getKeywords(editor);
var cur = editor.getCursor();
var result = [];
var token = editor.getTokenAt(cur), start, end, search;
if (token.end > cur.ch) {
token.end = cur.ch;
token.string = token.string.slice(0, cur.ch - token.start);
}
if (token.string.match(/^[.`\w@]\w*$/)) {
search = token.string;
start = token.start;
end = token.end;
} else {
start = end = cur.ch;
search = "";
}
if (search.charAt(0) == "." || search.charAt(0) == "`") {
start = nameCompletion(cur, token, result, editor);
} else {
addMatches(result, search, tables, function(w) {return w;});
addMatches(result, search, defaultTable, function(w) {return w;});
addMatches(result, search, keywords, function(w) {return w.toUpperCase();});
}
return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)};
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/hint/sql-hint.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/hint/sql-hint.js",
"repo_id": "Humsen",
"token_count": 2929
} | 39 |
// 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"), require("./runmode"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "./runmode"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var isBlock = /^(p|li|div|h\\d|pre|blockquote|td)$/;
function textContent(node, out) {
if (node.nodeType == 3) return out.push(node.nodeValue);
for (var ch = node.firstChild; ch; ch = ch.nextSibling) {
textContent(ch, out);
if (isBlock.test(node.nodeType)) out.push("\n");
}
}
CodeMirror.colorize = function(collection, defaultMode) {
if (!collection) collection = document.body.getElementsByTagName("pre");
for (var i = 0; i < collection.length; ++i) {
var node = collection[i];
var mode = node.getAttribute("data-lang") || defaultMode;
if (!mode) continue;
var text = [];
textContent(node, text);
node.innerHTML = "";
CodeMirror.runMode(text.join(""), mode, node);
node.className += " cm-s-default";
}
};
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/runmode/colorize.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/runmode/colorize.js",
"repo_id": "Humsen",
"token_count": 498
} | 40 |
.CodeMirror-Tern-completion {
padding-left: 22px;
position: relative;
}
.CodeMirror-Tern-completion:before {
position: absolute;
left: 2px;
bottom: 2px;
border-radius: 50%;
font-size: 12px;
font-weight: bold;
height: 15px;
width: 15px;
line-height: 16px;
text-align: center;
color: white;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.CodeMirror-Tern-completion-unknown:before {
content: "?";
background: #4bb;
}
.CodeMirror-Tern-completion-object:before {
content: "O";
background: #77c;
}
.CodeMirror-Tern-completion-fn:before {
content: "F";
background: #7c7;
}
.CodeMirror-Tern-completion-array:before {
content: "A";
background: #c66;
}
.CodeMirror-Tern-completion-number:before {
content: "1";
background: #999;
}
.CodeMirror-Tern-completion-string:before {
content: "S";
background: #999;
}
.CodeMirror-Tern-completion-bool:before {
content: "B";
background: #999;
}
.CodeMirror-Tern-completion-guess {
color: #999;
}
.CodeMirror-Tern-tooltip {
border: 1px solid silver;
border-radius: 3px;
color: #444;
padding: 2px 5px;
font-size: 90%;
font-family: monospace;
background-color: white;
white-space: pre-wrap;
max-width: 40em;
position: absolute;
z-index: 10;
-webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
-moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
box-shadow: 2px 3px 5px rgba(0,0,0,.2);
transition: opacity 1s;
-moz-transition: opacity 1s;
-webkit-transition: opacity 1s;
-o-transition: opacity 1s;
-ms-transition: opacity 1s;
}
.CodeMirror-Tern-hint-doc {
max-width: 25em;
margin-top: -3px;
}
.CodeMirror-Tern-fname { color: black; }
.CodeMirror-Tern-farg { color: #70a; }
.CodeMirror-Tern-farg-current { text-decoration: underline; }
.CodeMirror-Tern-type { color: #07c; }
.CodeMirror-Tern-fhint-guess { opacity: .7; }
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/tern/tern.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/tern/tern.css",
"repo_id": "Humsen",
"token_count": 783
} | 41 |
// 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.defineMode("commonlisp", function (config) {
var specialForm = /^(block|let*|return-from|catch|load-time-value|setq|eval-when|locally|symbol-macrolet|flet|macrolet|tagbody|function|multiple-value-call|the|go|multiple-value-prog1|throw|if|progn|unwind-protect|labels|progv|let|quote)$/;
var assumeBody = /^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/;
var numLiteral = /^(?:[+\-]?(?:\d+|\d*\.\d+)(?:[efd][+\-]?\d+)?|[+\-]?\d+(?:\/[+\-]?\d+)?|#b[+\-]?[01]+|#o[+\-]?[0-7]+|#x[+\-]?[\da-f]+)/;
var symbol = /[^\s'`,@()\[\]";]/;
var type;
function readSym(stream) {
var ch;
while (ch = stream.next()) {
if (ch == "\\") stream.next();
else if (!symbol.test(ch)) { stream.backUp(1); break; }
}
return stream.current();
}
function base(stream, state) {
if (stream.eatSpace()) {type = "ws"; return null;}
if (stream.match(numLiteral)) return "number";
var ch = stream.next();
if (ch == "\\") ch = stream.next();
if (ch == '"') return (state.tokenize = inString)(stream, state);
else if (ch == "(") { type = "open"; return "bracket"; }
else if (ch == ")" || ch == "]") { type = "close"; return "bracket"; }
else if (ch == ";") { stream.skipToEnd(); type = "ws"; return "comment"; }
else if (/['`,@]/.test(ch)) return null;
else if (ch == "|") {
if (stream.skipTo("|")) { stream.next(); return "symbol"; }
else { stream.skipToEnd(); return "error"; }
} else if (ch == "#") {
var ch = stream.next();
if (ch == "[") { type = "open"; return "bracket"; }
else if (/[+\-=\.']/.test(ch)) return null;
else if (/\d/.test(ch) && stream.match(/^\d*#/)) return null;
else if (ch == "|") return (state.tokenize = inComment)(stream, state);
else if (ch == ":") { readSym(stream); return "meta"; }
else return "error";
} else {
var name = readSym(stream);
if (name == ".") return null;
type = "symbol";
if (name == "nil" || name == "t" || name.charAt(0) == ":") return "atom";
if (state.lastType == "open" && (specialForm.test(name) || assumeBody.test(name))) return "keyword";
if (name.charAt(0) == "&") return "variable-2";
return "variable";
}
}
function inString(stream, state) {
var escaped = false, next;
while (next = stream.next()) {
if (next == '"' && !escaped) { state.tokenize = base; break; }
escaped = !escaped && next == "\\";
}
return "string";
}
function inComment(stream, state) {
var next, last;
while (next = stream.next()) {
if (next == "#" && last == "|") { state.tokenize = base; break; }
last = next;
}
type = "ws";
return "comment";
}
return {
startState: function () {
return {ctx: {prev: null, start: 0, indentTo: 0}, lastType: null, tokenize: base};
},
token: function (stream, state) {
if (stream.sol() && typeof state.ctx.indentTo != "number")
state.ctx.indentTo = state.ctx.start + 1;
type = null;
var style = state.tokenize(stream, state);
if (type != "ws") {
if (state.ctx.indentTo == null) {
if (type == "symbol" && assumeBody.test(stream.current()))
state.ctx.indentTo = state.ctx.start + config.indentUnit;
else
state.ctx.indentTo = "next";
} else if (state.ctx.indentTo == "next") {
state.ctx.indentTo = stream.column();
}
state.lastType = type;
}
if (type == "open") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};
else if (type == "close") state.ctx = state.ctx.prev || state.ctx;
return style;
},
indent: function (state, _textAfter) {
var i = state.ctx.indentTo;
return typeof i == "number" ? i : state.ctx.start + 1;
},
lineComment: ";;",
blockCommentStart: "#|",
blockCommentEnd: "|#"
};
});
CodeMirror.defineMIME("text/x-common-lisp", "commonlisp");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/commonlisp/commonlisp.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/commonlisp/commonlisp.js",
"repo_id": "Humsen",
"token_count": 1873
} | 42 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
/*jshint unused:true, eqnull:true, curly:true, bitwise:true */
/*jshint undef:true, latedef:true, trailing:true */
/*global CodeMirror:true */
// erlang mode.
// tokenizer -> token types -> CodeMirror styles
// tokenizer maintains a parse stack
// indenter uses the parse stack
// TODO indenter:
// bit syntax
// old guard/bif/conversion clashes (e.g. "float/1")
// type/spec/opaque
(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.defineMIME("text/x-erlang", "erlang");
CodeMirror.defineMode("erlang", function(cmCfg) {
"use strict";
/////////////////////////////////////////////////////////////////////////////
// constants
var typeWords = [
"-type", "-spec", "-export_type", "-opaque"];
var keywordWords = [
"after","begin","catch","case","cond","end","fun","if",
"let","of","query","receive","try","when"];
var separatorRE = /[\->,;]/;
var separatorWords = [
"->",";",","];
var operatorAtomWords = [
"and","andalso","band","bnot","bor","bsl","bsr","bxor",
"div","not","or","orelse","rem","xor"];
var operatorSymbolRE = /[\+\-\*\/<>=\|:!]/;
var operatorSymbolWords = [
"=","+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-","!"];
var openParenRE = /[<\(\[\{]/;
var openParenWords = [
"<<","(","[","{"];
var closeParenRE = /[>\)\]\}]/;
var closeParenWords = [
"}","]",")",">>"];
var guardWords = [
"is_atom","is_binary","is_bitstring","is_boolean","is_float",
"is_function","is_integer","is_list","is_number","is_pid",
"is_port","is_record","is_reference","is_tuple",
"atom","binary","bitstring","boolean","function","integer","list",
"number","pid","port","record","reference","tuple"];
var bifWords = [
"abs","adler32","adler32_combine","alive","apply","atom_to_binary",
"atom_to_list","binary_to_atom","binary_to_existing_atom",
"binary_to_list","binary_to_term","bit_size","bitstring_to_list",
"byte_size","check_process_code","contact_binary","crc32",
"crc32_combine","date","decode_packet","delete_module",
"disconnect_node","element","erase","exit","float","float_to_list",
"garbage_collect","get","get_keys","group_leader","halt","hd",
"integer_to_list","internal_bif","iolist_size","iolist_to_binary",
"is_alive","is_atom","is_binary","is_bitstring","is_boolean",
"is_float","is_function","is_integer","is_list","is_number","is_pid",
"is_port","is_process_alive","is_record","is_reference","is_tuple",
"length","link","list_to_atom","list_to_binary","list_to_bitstring",
"list_to_existing_atom","list_to_float","list_to_integer",
"list_to_pid","list_to_tuple","load_module","make_ref","module_loaded",
"monitor_node","node","node_link","node_unlink","nodes","notalive",
"now","open_port","pid_to_list","port_close","port_command",
"port_connect","port_control","pre_loaded","process_flag",
"process_info","processes","purge_module","put","register",
"registered","round","self","setelement","size","spawn","spawn_link",
"spawn_monitor","spawn_opt","split_binary","statistics",
"term_to_binary","time","throw","tl","trunc","tuple_size",
"tuple_to_list","unlink","unregister","whereis"];
// upper case: [A-Z] [Ø-Þ] [À-Ö]
// lower case: [a-z] [ß-ö] [ø-ÿ]
var anumRE = /[\w@Ø-ÞÀ-Öß-öø-ÿ]/;
var escapesRE =
/[0-7]{1,3}|[bdefnrstv\\"']|\^[a-zA-Z]|x[0-9a-zA-Z]{2}|x{[0-9a-zA-Z]+}/;
/////////////////////////////////////////////////////////////////////////////
// tokenizer
function tokenizer(stream,state) {
// in multi-line string
if (state.in_string) {
state.in_string = (!doubleQuote(stream));
return rval(state,stream,"string");
}
// in multi-line atom
if (state.in_atom) {
state.in_atom = (!singleQuote(stream));
return rval(state,stream,"atom");
}
// whitespace
if (stream.eatSpace()) {
return rval(state,stream,"whitespace");
}
// attributes and type specs
if (!peekToken(state) &&
stream.match(/-\s*[a-zß-öø-ÿ][\wØ-ÞÀ-Öß-öø-ÿ]*/)) {
if (is_member(stream.current(),typeWords)) {
return rval(state,stream,"type");
}else{
return rval(state,stream,"attribute");
}
}
var ch = stream.next();
// comment
if (ch == '%') {
stream.skipToEnd();
return rval(state,stream,"comment");
}
// colon
if (ch == ":") {
return rval(state,stream,"colon");
}
// macro
if (ch == '?') {
stream.eatSpace();
stream.eatWhile(anumRE);
return rval(state,stream,"macro");
}
// record
if (ch == "#") {
stream.eatSpace();
stream.eatWhile(anumRE);
return rval(state,stream,"record");
}
// dollar escape
if (ch == "$") {
if (stream.next() == "\\" && !stream.match(escapesRE)) {
return rval(state,stream,"error");
}
return rval(state,stream,"number");
}
// dot
if (ch == ".") {
return rval(state,stream,"dot");
}
// quoted atom
if (ch == '\'') {
if (!(state.in_atom = (!singleQuote(stream)))) {
if (stream.match(/\s*\/\s*[0-9]/,false)) {
stream.match(/\s*\/\s*[0-9]/,true);
return rval(state,stream,"fun"); // 'f'/0 style fun
}
if (stream.match(/\s*\(/,false) || stream.match(/\s*:/,false)) {
return rval(state,stream,"function");
}
}
return rval(state,stream,"atom");
}
// string
if (ch == '"') {
state.in_string = (!doubleQuote(stream));
return rval(state,stream,"string");
}
// variable
if (/[A-Z_Ø-ÞÀ-Ö]/.test(ch)) {
stream.eatWhile(anumRE);
return rval(state,stream,"variable");
}
// atom/keyword/BIF/function
if (/[a-z_ß-öø-ÿ]/.test(ch)) {
stream.eatWhile(anumRE);
if (stream.match(/\s*\/\s*[0-9]/,false)) {
stream.match(/\s*\/\s*[0-9]/,true);
return rval(state,stream,"fun"); // f/0 style fun
}
var w = stream.current();
if (is_member(w,keywordWords)) {
return rval(state,stream,"keyword");
}else if (is_member(w,operatorAtomWords)) {
return rval(state,stream,"operator");
}else if (stream.match(/\s*\(/,false)) {
// 'put' and 'erlang:put' are bifs, 'foo:put' is not
if (is_member(w,bifWords) &&
((peekToken(state).token != ":") ||
(peekToken(state,2).token == "erlang"))) {
return rval(state,stream,"builtin");
}else if (is_member(w,guardWords)) {
return rval(state,stream,"guard");
}else{
return rval(state,stream,"function");
}
}else if (is_member(w,operatorAtomWords)) {
return rval(state,stream,"operator");
}else if (lookahead(stream) == ":") {
if (w == "erlang") {
return rval(state,stream,"builtin");
} else {
return rval(state,stream,"function");
}
}else if (is_member(w,["true","false"])) {
return rval(state,stream,"boolean");
}else if (is_member(w,["true","false"])) {
return rval(state,stream,"boolean");
}else{
return rval(state,stream,"atom");
}
}
// number
var digitRE = /[0-9]/;
var radixRE = /[0-9a-zA-Z]/; // 36#zZ style int
if (digitRE.test(ch)) {
stream.eatWhile(digitRE);
if (stream.eat('#')) { // 36#aZ style integer
if (!stream.eatWhile(radixRE)) {
stream.backUp(1); //"36#" - syntax error
}
} else if (stream.eat('.')) { // float
if (!stream.eatWhile(digitRE)) {
stream.backUp(1); // "3." - probably end of function
} else {
if (stream.eat(/[eE]/)) { // float with exponent
if (stream.eat(/[-+]/)) {
if (!stream.eatWhile(digitRE)) {
stream.backUp(2); // "2e-" - syntax error
}
} else {
if (!stream.eatWhile(digitRE)) {
stream.backUp(1); // "2e" - syntax error
}
}
}
}
}
return rval(state,stream,"number"); // normal integer
}
// open parens
if (nongreedy(stream,openParenRE,openParenWords)) {
return rval(state,stream,"open_paren");
}
// close parens
if (nongreedy(stream,closeParenRE,closeParenWords)) {
return rval(state,stream,"close_paren");
}
// separators
if (greedy(stream,separatorRE,separatorWords)) {
return rval(state,stream,"separator");
}
// operators
if (greedy(stream,operatorSymbolRE,operatorSymbolWords)) {
return rval(state,stream,"operator");
}
return rval(state,stream,null);
}
/////////////////////////////////////////////////////////////////////////////
// utilities
function nongreedy(stream,re,words) {
if (stream.current().length == 1 && re.test(stream.current())) {
stream.backUp(1);
while (re.test(stream.peek())) {
stream.next();
if (is_member(stream.current(),words)) {
return true;
}
}
stream.backUp(stream.current().length-1);
}
return false;
}
function greedy(stream,re,words) {
if (stream.current().length == 1 && re.test(stream.current())) {
while (re.test(stream.peek())) {
stream.next();
}
while (0 < stream.current().length) {
if (is_member(stream.current(),words)) {
return true;
}else{
stream.backUp(1);
}
}
stream.next();
}
return false;
}
function doubleQuote(stream) {
return quote(stream, '"', '\\');
}
function singleQuote(stream) {
return quote(stream,'\'','\\');
}
function quote(stream,quoteChar,escapeChar) {
while (!stream.eol()) {
var ch = stream.next();
if (ch == quoteChar) {
return true;
}else if (ch == escapeChar) {
stream.next();
}
}
return false;
}
function lookahead(stream) {
var m = stream.match(/([\n\s]+|%[^\n]*\n)*(.)/,false);
return m ? m.pop() : "";
}
function is_member(element,list) {
return (-1 < list.indexOf(element));
}
function rval(state,stream,type) {
// parse stack
pushToken(state,realToken(type,stream));
// map erlang token type to CodeMirror style class
// erlang -> CodeMirror tag
switch (type) {
case "atom": return "atom";
case "attribute": return "attribute";
case "boolean": return "atom";
case "builtin": return "builtin";
case "close_paren": return null;
case "colon": return null;
case "comment": return "comment";
case "dot": return null;
case "error": return "error";
case "fun": return "meta";
case "function": return "tag";
case "guard": return "property";
case "keyword": return "keyword";
case "macro": return "variable-2";
case "number": return "number";
case "open_paren": return null;
case "operator": return "operator";
case "record": return "bracket";
case "separator": return null;
case "string": return "string";
case "type": return "def";
case "variable": return "variable";
default: return null;
}
}
function aToken(tok,col,ind,typ) {
return {token: tok,
column: col,
indent: ind,
type: typ};
}
function realToken(type,stream) {
return aToken(stream.current(),
stream.column(),
stream.indentation(),
type);
}
function fakeToken(type) {
return aToken(type,0,0,type);
}
function peekToken(state,depth) {
var len = state.tokenStack.length;
var dep = (depth ? depth : 1);
if (len < dep) {
return false;
}else{
return state.tokenStack[len-dep];
}
}
function pushToken(state,token) {
if (!(token.type == "comment" || token.type == "whitespace")) {
state.tokenStack = maybe_drop_pre(state.tokenStack,token);
state.tokenStack = maybe_drop_post(state.tokenStack);
}
}
function maybe_drop_pre(s,token) {
var last = s.length-1;
if (0 < last && s[last].type === "record" && token.type === "dot") {
s.pop();
}else if (0 < last && s[last].type === "group") {
s.pop();
s.push(token);
}else{
s.push(token);
}
return s;
}
function maybe_drop_post(s) {
var last = s.length-1;
if (s[last].type === "dot") {
return [];
}
if (s[last].type === "fun" && s[last-1].token === "fun") {
return s.slice(0,last-1);
}
switch (s[s.length-1].token) {
case "}": return d(s,{g:["{"]});
case "]": return d(s,{i:["["]});
case ")": return d(s,{i:["("]});
case ">>": return d(s,{i:["<<"]});
case "end": return d(s,{i:["begin","case","fun","if","receive","try"]});
case ",": return d(s,{e:["begin","try","when","->",
",","(","[","{","<<"]});
case "->": return d(s,{r:["when"],
m:["try","if","case","receive"]});
case ";": return d(s,{E:["case","fun","if","receive","try","when"]});
case "catch":return d(s,{e:["try"]});
case "of": return d(s,{e:["case"]});
case "after":return d(s,{e:["receive","try"]});
default: return s;
}
}
function d(stack,tt) {
// stack is a stack of Token objects.
// tt is an object; {type:tokens}
// type is a char, tokens is a list of token strings.
// The function returns (possibly truncated) stack.
// It will descend the stack, looking for a Token such that Token.token
// is a member of tokens. If it does not find that, it will normally (but
// see "E" below) return stack. If it does find a match, it will remove
// all the Tokens between the top and the matched Token.
// If type is "m", that is all it does.
// If type is "i", it will also remove the matched Token and the top Token.
// If type is "g", like "i", but add a fake "group" token at the top.
// If type is "r", it will remove the matched Token, but not the top Token.
// If type is "e", it will keep the matched Token but not the top Token.
// If type is "E", it behaves as for type "e", except if there is no match,
// in which case it will return an empty stack.
for (var type in tt) {
var len = stack.length-1;
var tokens = tt[type];
for (var i = len-1; -1 < i ; i--) {
if (is_member(stack[i].token,tokens)) {
var ss = stack.slice(0,i);
switch (type) {
case "m": return ss.concat(stack[i]).concat(stack[len]);
case "r": return ss.concat(stack[len]);
case "i": return ss;
case "g": return ss.concat(fakeToken("group"));
case "E": return ss.concat(stack[i]);
case "e": return ss.concat(stack[i]);
}
}
}
}
return (type == "E" ? [] : stack);
}
/////////////////////////////////////////////////////////////////////////////
// indenter
function indenter(state,textAfter) {
var t;
var unit = cmCfg.indentUnit;
var wordAfter = wordafter(textAfter);
var currT = peekToken(state,1);
var prevT = peekToken(state,2);
if (state.in_string || state.in_atom) {
return CodeMirror.Pass;
}else if (!prevT) {
return 0;
}else if (currT.token == "when") {
return currT.column+unit;
}else if (wordAfter === "when" && prevT.type === "function") {
return prevT.indent+unit;
}else if (wordAfter === "(" && currT.token === "fun") {
return currT.column+3;
}else if (wordAfter === "catch" && (t = getToken(state,["try"]))) {
return t.column;
}else if (is_member(wordAfter,["end","after","of"])) {
t = getToken(state,["begin","case","fun","if","receive","try"]);
return t ? t.column : CodeMirror.Pass;
}else if (is_member(wordAfter,closeParenWords)) {
t = getToken(state,openParenWords);
return t ? t.column : CodeMirror.Pass;
}else if (is_member(currT.token,[",","|","||"]) ||
is_member(wordAfter,[",","|","||"])) {
t = postcommaToken(state);
return t ? t.column+t.token.length : unit;
}else if (currT.token == "->") {
if (is_member(prevT.token, ["receive","case","if","try"])) {
return prevT.column+unit+unit;
}else{
return prevT.column+unit;
}
}else if (is_member(currT.token,openParenWords)) {
return currT.column+currT.token.length;
}else{
t = defaultToken(state);
return truthy(t) ? t.column+unit : 0;
}
}
function wordafter(str) {
var m = str.match(/,|[a-z]+|\}|\]|\)|>>|\|+|\(/);
return truthy(m) && (m.index === 0) ? m[0] : "";
}
function postcommaToken(state) {
var objs = state.tokenStack.slice(0,-1);
var i = getTokenIndex(objs,"type",["open_paren"]);
return truthy(objs[i]) ? objs[i] : false;
}
function defaultToken(state) {
var objs = state.tokenStack;
var stop = getTokenIndex(objs,"type",["open_paren","separator","keyword"]);
var oper = getTokenIndex(objs,"type",["operator"]);
if (truthy(stop) && truthy(oper) && stop < oper) {
return objs[stop+1];
} else if (truthy(stop)) {
return objs[stop];
} else {
return false;
}
}
function getToken(state,tokens) {
var objs = state.tokenStack;
var i = getTokenIndex(objs,"token",tokens);
return truthy(objs[i]) ? objs[i] : false;
}
function getTokenIndex(objs,propname,propvals) {
for (var i = objs.length-1; -1 < i ; i--) {
if (is_member(objs[i][propname],propvals)) {
return i;
}
}
return false;
}
function truthy(x) {
return (x !== false) && (x != null);
}
/////////////////////////////////////////////////////////////////////////////
// this object defines the mode
return {
startState:
function() {
return {tokenStack: [],
in_string: false,
in_atom: false};
},
token:
function(stream, state) {
return tokenizer(stream, state);
},
indent:
function(state, textAfter) {
return indenter(state,textAfter);
},
lineComment: "%"
};
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/erlang/erlang.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/erlang/erlang.js",
"repo_id": "Humsen",
"token_count": 8456
} | 43 |
// 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";
function wordRegexp(words) {
return new RegExp('^((' + words.join(')|(') + '))\\b', 'i');
};
var builtinArray = [
'a_correlate', 'abs', 'acos', 'adapt_hist_equal', 'alog',
'alog2', 'alog10', 'amoeba', 'annotate', 'app_user_dir',
'app_user_dir_query', 'arg_present', 'array_equal', 'array_indices',
'arrow', 'ascii_template', 'asin', 'assoc', 'atan',
'axis', 'axis', 'bandpass_filter', 'bandreject_filter', 'barplot',
'bar_plot', 'beseli', 'beselj', 'beselk', 'besely',
'beta', 'biginteger', 'bilinear', 'bin_date', 'binary_template',
'bindgen', 'binomial', 'bit_ffs', 'bit_population', 'blas_axpy',
'blk_con', 'boolarr', 'boolean', 'boxplot', 'box_cursor',
'breakpoint', 'broyden', 'bubbleplot', 'butterworth', 'bytarr',
'byte', 'byteorder', 'bytscl', 'c_correlate', 'calendar',
'caldat', 'call_external', 'call_function', 'call_method',
'call_procedure', 'canny', 'catch', 'cd', 'cdf', 'ceil',
'chebyshev', 'check_math', 'chisqr_cvf', 'chisqr_pdf', 'choldc',
'cholsol', 'cindgen', 'cir_3pnt', 'clipboard', 'close',
'clust_wts', 'cluster', 'cluster_tree', 'cmyk_convert', 'code_coverage',
'color_convert', 'color_exchange', 'color_quan', 'color_range_map',
'colorbar', 'colorize_sample', 'colormap_applicable',
'colormap_gradient', 'colormap_rotation', 'colortable',
'comfit', 'command_line_args', 'common', 'compile_opt', 'complex',
'complexarr', 'complexround', 'compute_mesh_normals', 'cond', 'congrid',
'conj', 'constrained_min', 'contour', 'contour', 'convert_coord',
'convol', 'convol_fft', 'coord2to3', 'copy_lun', 'correlate',
'cos', 'cosh', 'cpu', 'cramer', 'createboxplotdata',
'create_cursor', 'create_struct', 'create_view', 'crossp', 'crvlength',
'ct_luminance', 'cti_test', 'cursor', 'curvefit', 'cv_coord',
'cvttobm', 'cw_animate', 'cw_animate_getp', 'cw_animate_load',
'cw_animate_run', 'cw_arcball', 'cw_bgroup', 'cw_clr_index',
'cw_colorsel', 'cw_defroi', 'cw_field', 'cw_filesel', 'cw_form',
'cw_fslider', 'cw_light_editor', 'cw_light_editor_get',
'cw_light_editor_set', 'cw_orient', 'cw_palette_editor',
'cw_palette_editor_get', 'cw_palette_editor_set', 'cw_pdmenu',
'cw_rgbslider', 'cw_tmpl', 'cw_zoom', 'db_exists',
'dblarr', 'dcindgen', 'dcomplex', 'dcomplexarr', 'define_key',
'define_msgblk', 'define_msgblk_from_file', 'defroi', 'defsysv',
'delvar', 'dendro_plot', 'dendrogram', 'deriv', 'derivsig',
'determ', 'device', 'dfpmin', 'diag_matrix', 'dialog_dbconnect',
'dialog_message', 'dialog_pickfile', 'dialog_printersetup',
'dialog_printjob', 'dialog_read_image',
'dialog_write_image', 'dictionary', 'digital_filter', 'dilate', 'dindgen',
'dissolve', 'dist', 'distance_measure', 'dlm_load', 'dlm_register',
'doc_library', 'double', 'draw_roi', 'edge_dog', 'efont',
'eigenql', 'eigenvec', 'ellipse', 'elmhes', 'emboss',
'empty', 'enable_sysrtn', 'eof', 'eos', 'erase',
'erf', 'erfc', 'erfcx', 'erode', 'errorplot',
'errplot', 'estimator_filter', 'execute', 'exit', 'exp',
'expand', 'expand_path', 'expint', 'extrac', 'extract_slice',
'f_cvf', 'f_pdf', 'factorial', 'fft', 'file_basename',
'file_chmod', 'file_copy', 'file_delete', 'file_dirname',
'file_expand_path', 'file_gunzip', 'file_gzip', 'file_info',
'file_lines', 'file_link', 'file_mkdir', 'file_move',
'file_poll_input', 'file_readlink', 'file_same',
'file_search', 'file_tar', 'file_test', 'file_untar', 'file_unzip',
'file_which', 'file_zip', 'filepath', 'findgen', 'finite',
'fix', 'flick', 'float', 'floor', 'flow3',
'fltarr', 'flush', 'format_axis_values', 'forward_function', 'free_lun',
'fstat', 'fulstr', 'funct', 'function', 'fv_test',
'fx_root', 'fz_roots', 'gamma', 'gamma_ct', 'gauss_cvf',
'gauss_pdf', 'gauss_smooth', 'gauss2dfit', 'gaussfit',
'gaussian_function', 'gaussint', 'get_drive_list', 'get_dxf_objects',
'get_kbrd', 'get_login_info',
'get_lun', 'get_screen_size', 'getenv', 'getwindows', 'greg2jul',
'grib', 'grid_input', 'grid_tps', 'grid3', 'griddata',
'gs_iter', 'h_eq_ct', 'h_eq_int', 'hanning', 'hash',
'hdf', 'hdf5', 'heap_free', 'heap_gc', 'heap_nosave',
'heap_refcount', 'heap_save', 'help', 'hilbert', 'hist_2d',
'hist_equal', 'histogram', 'hls', 'hough', 'hqr',
'hsv', 'i18n_multibytetoutf8',
'i18n_multibytetowidechar', 'i18n_utf8tomultibyte',
'i18n_widechartomultibyte',
'ibeta', 'icontour', 'iconvertcoord', 'idelete', 'identity',
'idl_base64', 'idl_container', 'idl_validname',
'idlexbr_assistant', 'idlitsys_createtool',
'idlunit', 'iellipse', 'igamma', 'igetcurrent', 'igetdata',
'igetid', 'igetproperty', 'iimage', 'image', 'image_cont',
'image_statistics', 'image_threshold', 'imaginary', 'imap', 'indgen',
'int_2d', 'int_3d', 'int_tabulated', 'intarr', 'interpol',
'interpolate', 'interval_volume', 'invert', 'ioctl', 'iopen',
'ir_filter', 'iplot', 'ipolygon', 'ipolyline', 'iputdata',
'iregister', 'ireset', 'iresolve', 'irotate', 'isa',
'isave', 'iscale', 'isetcurrent', 'isetproperty', 'ishft',
'isocontour', 'isosurface', 'isurface', 'itext', 'itranslate',
'ivector', 'ivolume', 'izoom', 'journal', 'json_parse',
'json_serialize', 'jul2greg', 'julday', 'keyword_set', 'krig2d',
'kurtosis', 'kw_test', 'l64indgen', 'la_choldc', 'la_cholmprove',
'la_cholsol', 'la_determ', 'la_eigenproblem', 'la_eigenql', 'la_eigenvec',
'la_elmhes', 'la_gm_linear_model', 'la_hqr', 'la_invert',
'la_least_square_equality', 'la_least_squares', 'la_linear_equation',
'la_ludc', 'la_lumprove', 'la_lusol',
'la_svd', 'la_tridc', 'la_trimprove', 'la_triql', 'la_trired',
'la_trisol', 'label_date', 'label_region', 'ladfit', 'laguerre',
'lambda', 'lambdap', 'lambertw', 'laplacian', 'least_squares_filter',
'leefilt', 'legend', 'legendre', 'linbcg', 'lindgen',
'linfit', 'linkimage', 'list', 'll_arc_distance', 'lmfit',
'lmgr', 'lngamma', 'lnp_test', 'loadct', 'locale_get',
'logical_and', 'logical_or', 'logical_true', 'lon64arr', 'lonarr',
'long', 'long64', 'lsode', 'lu_complex', 'ludc',
'lumprove', 'lusol', 'm_correlate', 'machar', 'make_array',
'make_dll', 'make_rt', 'map', 'mapcontinents', 'mapgrid',
'map_2points', 'map_continents', 'map_grid', 'map_image', 'map_patch',
'map_proj_forward', 'map_proj_image', 'map_proj_info',
'map_proj_init', 'map_proj_inverse',
'map_set', 'matrix_multiply', 'matrix_power', 'max', 'md_test',
'mean', 'meanabsdev', 'mean_filter', 'median', 'memory',
'mesh_clip', 'mesh_decimate', 'mesh_issolid',
'mesh_merge', 'mesh_numtriangles',
'mesh_obj', 'mesh_smooth', 'mesh_surfacearea',
'mesh_validate', 'mesh_volume',
'message', 'min', 'min_curve_surf', 'mk_html_help', 'modifyct',
'moment', 'morph_close', 'morph_distance',
'morph_gradient', 'morph_hitormiss',
'morph_open', 'morph_thin', 'morph_tophat', 'multi', 'n_elements',
'n_params', 'n_tags', 'ncdf', 'newton', 'noise_hurl',
'noise_pick', 'noise_scatter', 'noise_slur', 'norm', 'obj_class',
'obj_destroy', 'obj_hasmethod', 'obj_isa', 'obj_new', 'obj_valid',
'objarr', 'on_error', 'on_ioerror', 'online_help', 'openr',
'openu', 'openw', 'oplot', 'oploterr', 'orderedhash',
'p_correlate', 'parse_url', 'particle_trace', 'path_cache', 'path_sep',
'pcomp', 'plot', 'plot3d', 'plot', 'plot_3dbox',
'plot_field', 'ploterr', 'plots', 'polar_contour', 'polar_surface',
'polyfill', 'polyshade', 'pnt_line', 'point_lun', 'polarplot',
'poly', 'poly_2d', 'poly_area', 'poly_fit', 'polyfillv',
'polygon', 'polyline', 'polywarp', 'popd', 'powell',
'pref_commit', 'pref_get', 'pref_set', 'prewitt', 'primes',
'print', 'printf', 'printd', 'pro', 'product',
'profile', 'profiler', 'profiles', 'project_vol', 'ps_show_fonts',
'psafm', 'pseudo', 'ptr_free', 'ptr_new', 'ptr_valid',
'ptrarr', 'pushd', 'qgrid3', 'qhull', 'qromb',
'qromo', 'qsimp', 'query_*', 'query_ascii', 'query_bmp',
'query_csv', 'query_dicom', 'query_gif', 'query_image', 'query_jpeg',
'query_jpeg2000', 'query_mrsid', 'query_pict', 'query_png', 'query_ppm',
'query_srf', 'query_tiff', 'query_video', 'query_wav', 'r_correlate',
'r_test', 'radon', 'randomn', 'randomu', 'ranks',
'rdpix', 'read', 'readf', 'read_ascii', 'read_binary',
'read_bmp', 'read_csv', 'read_dicom', 'read_gif', 'read_image',
'read_interfile', 'read_jpeg', 'read_jpeg2000', 'read_mrsid', 'read_pict',
'read_png', 'read_ppm', 'read_spr', 'read_srf', 'read_sylk',
'read_tiff', 'read_video', 'read_wav', 'read_wave', 'read_x11_bitmap',
'read_xwd', 'reads', 'readu', 'real_part', 'rebin',
'recall_commands', 'recon3', 'reduce_colors', 'reform', 'region_grow',
'register_cursor', 'regress', 'replicate',
'replicate_inplace', 'resolve_all',
'resolve_routine', 'restore', 'retall', 'return', 'reverse',
'rk4', 'roberts', 'rot', 'rotate', 'round',
'routine_filepath', 'routine_info', 'rs_test', 's_test', 'save',
'savgol', 'scale3', 'scale3d', 'scatterplot', 'scatterplot3d',
'scope_level', 'scope_traceback', 'scope_varfetch',
'scope_varname', 'search2d',
'search3d', 'sem_create', 'sem_delete', 'sem_lock', 'sem_release',
'set_plot', 'set_shading', 'setenv', 'sfit', 'shade_surf',
'shade_surf_irr', 'shade_volume', 'shift', 'shift_diff', 'shmdebug',
'shmmap', 'shmunmap', 'shmvar', 'show3', 'showfont',
'signum', 'simplex', 'sin', 'sindgen', 'sinh',
'size', 'skewness', 'skip_lun', 'slicer3', 'slide_image',
'smooth', 'sobel', 'socket', 'sort', 'spawn',
'sph_4pnt', 'sph_scat', 'spher_harm', 'spl_init', 'spl_interp',
'spline', 'spline_p', 'sprsab', 'sprsax', 'sprsin',
'sprstp', 'sqrt', 'standardize', 'stddev', 'stop',
'strarr', 'strcmp', 'strcompress', 'streamline', 'streamline',
'stregex', 'stretch', 'string', 'strjoin', 'strlen',
'strlowcase', 'strmatch', 'strmessage', 'strmid', 'strpos',
'strput', 'strsplit', 'strtrim', 'struct_assign', 'struct_hide',
'strupcase', 'surface', 'surface', 'surfr', 'svdc',
'svdfit', 'svsol', 'swap_endian', 'swap_endian_inplace', 'symbol',
'systime', 't_cvf', 't_pdf', 't3d', 'tag_names',
'tan', 'tanh', 'tek_color', 'temporary', 'terminal_size',
'tetra_clip', 'tetra_surface', 'tetra_volume', 'text', 'thin',
'thread', 'threed', 'tic', 'time_test2', 'timegen',
'timer', 'timestamp', 'timestamptovalues', 'tm_test', 'toc',
'total', 'trace', 'transpose', 'tri_surf', 'triangulate',
'trigrid', 'triql', 'trired', 'trisol', 'truncate_lun',
'ts_coef', 'ts_diff', 'ts_fcast', 'ts_smooth', 'tv',
'tvcrs', 'tvlct', 'tvrd', 'tvscl', 'typename',
'uindgen', 'uint', 'uintarr', 'ul64indgen', 'ulindgen',
'ulon64arr', 'ulonarr', 'ulong', 'ulong64', 'uniq',
'unsharp_mask', 'usersym', 'value_locate', 'variance', 'vector',
'vector_field', 'vel', 'velovect', 'vert_t3d', 'voigt',
'volume', 'voronoi', 'voxel_proj', 'wait', 'warp_tri',
'watershed', 'wdelete', 'wf_draw', 'where', 'widget_base',
'widget_button', 'widget_combobox', 'widget_control',
'widget_displaycontextmenu', 'widget_draw',
'widget_droplist', 'widget_event', 'widget_info',
'widget_label', 'widget_list',
'widget_propertysheet', 'widget_slider', 'widget_tab',
'widget_table', 'widget_text',
'widget_tree', 'widget_tree_move', 'widget_window',
'wiener_filter', 'window',
'window', 'write_bmp', 'write_csv', 'write_gif', 'write_image',
'write_jpeg', 'write_jpeg2000', 'write_nrif', 'write_pict', 'write_png',
'write_ppm', 'write_spr', 'write_srf', 'write_sylk', 'write_tiff',
'write_video', 'write_wav', 'write_wave', 'writeu', 'wset',
'wshow', 'wtn', 'wv_applet', 'wv_cwt', 'wv_cw_wavelet',
'wv_denoise', 'wv_dwt', 'wv_fn_coiflet',
'wv_fn_daubechies', 'wv_fn_gaussian',
'wv_fn_haar', 'wv_fn_morlet', 'wv_fn_paul',
'wv_fn_symlet', 'wv_import_data',
'wv_import_wavelet', 'wv_plot3d_wps', 'wv_plot_multires',
'wv_pwt', 'wv_tool_denoise',
'xbm_edit', 'xdisplayfile', 'xdxf', 'xfont', 'xinteranimate',
'xloadct', 'xmanager', 'xmng_tmpl', 'xmtool', 'xobjview',
'xobjview_rotate', 'xobjview_write_image',
'xpalette', 'xpcolor', 'xplot3d',
'xregistered', 'xroi', 'xsq_test', 'xsurface', 'xvaredit',
'xvolume', 'xvolume_rotate', 'xvolume_write_image',
'xyouts', 'zlib_compress', 'zlib_uncompress', 'zoom', 'zoom_24'
];
var builtins = wordRegexp(builtinArray);
var keywordArray = [
'begin', 'end', 'endcase', 'endfor',
'endwhile', 'endif', 'endrep', 'endforeach',
'break', 'case', 'continue', 'for',
'foreach', 'goto', 'if', 'then', 'else',
'repeat', 'until', 'switch', 'while',
'do', 'pro', 'function'
];
var keywords = wordRegexp(keywordArray);
CodeMirror.registerHelper("hintWords", "idl", builtinArray.concat(keywordArray));
var identifiers = new RegExp('^[_a-z\xa1-\uffff][_a-z0-9\xa1-\uffff]*', 'i');
var singleOperators = /[+\-*&=<>\/@#~$]/;
var boolOperators = new RegExp('(and|or|eq|lt|le|gt|ge|ne|not)', 'i');
function tokenBase(stream) {
// whitespaces
if (stream.eatSpace()) return null;
// Handle one line Comments
if (stream.match(';')) {
stream.skipToEnd();
return 'comment';
}
// Handle Number Literals
if (stream.match(/^[0-9\.+-]/, false)) {
if (stream.match(/^[+-]?0x[0-9a-fA-F]+/))
return 'number';
if (stream.match(/^[+-]?\d*\.\d+([EeDd][+-]?\d+)?/))
return 'number';
if (stream.match(/^[+-]?\d+([EeDd][+-]?\d+)?/))
return 'number';
}
// Handle Strings
if (stream.match(/^"([^"]|(""))*"/)) { return 'string'; }
if (stream.match(/^'([^']|(''))*'/)) { return 'string'; }
// Handle words
if (stream.match(keywords)) { return 'keyword'; }
if (stream.match(builtins)) { return 'builtin'; }
if (stream.match(identifiers)) { return 'variable'; }
if (stream.match(singleOperators) || stream.match(boolOperators)) {
return 'operator'; }
// Handle non-detected items
stream.next();
return null;
};
CodeMirror.defineMode('idl', function() {
return {
token: function(stream) {
return tokenBase(stream);
}
};
});
CodeMirror.defineMIME('text/x-idl', 'idl');
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/idl/idl.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/idl/idl.js",
"repo_id": "Humsen",
"token_count": 6661
} | 44 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.