text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
import { computed, unref } from 'vue'
import {
useFileActionsCopyQuickLink,
useFileActionsCreateLink
} from '../../../../../src/composables/actions/files'
import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { FileAction } from '../../../../../src/composables/actions'
import { useCanShare } from '../../../../../src/composables/shares'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { LinkShare } from '@ownclouders/web-client/src/helpers/share'
import { buildLinkShare } from '@ownclouders/web-client/src/helpers/share/functionsNG'
import { useClipboard } from '../../../../../src/composables/clipboard'
import { useMessages } from '../../../../../src/composables/piniaStores'
import { Permission } from '@ownclouders/web-client/src/generated'
vi.mock('../../../../../src/composables/shares', () => ({
useCanShare: vi.fn()
}))
vi.mock('../../../../../src/composables/actions/files/useFileActionsCreateLink', () => ({
useFileActionsCreateLink: vi.fn()
}))
vi.mock('../../../../../src/composables/clipboard', () => ({
useClipboard: vi.fn()
}))
vi.mock('@ownclouders/web-client/src/helpers/share/functionsNG', () => ({
buildLinkShare: vi.fn()
}))
describe('useFileActionsCopyQuickLink', () => {
describe('isVisible property', () => {
it('should return false if no resource selected', () => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ space: null, resources: [] })).toBeFalsy()
}
})
})
it('should return false if canShare is false', () => {
getWrapper({
canShare: false,
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [mock<Resource>()] })).toBeFalsy()
}
})
})
it('should return true if resource can be shared', () => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [mock<Resource>()] })).toBeTruthy()
}
})
})
})
describe('handler', () => {
it('should create a new link if quick link does not yet exist', () => {
getWrapper({
setup: async ({ actions }, { mocks }) => {
await unref(actions)[0].handler({
resources: [mock<Resource>()],
space: mock<SpaceResource>()
})
expect(mocks.createLinkMock).toHaveBeenCalledTimes(1)
}
})
})
it('should not create a new link if quick link does already exist', () => {
getWrapper({
quickLinkExists: true,
setup: async ({ actions }, { mocks }) => {
await unref(actions)[0].handler({
resources: [mock<Resource>()],
space: mock<SpaceResource>()
})
expect(mocks.createLinkMock).not.toHaveBeenCalled()
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalledTimes(1)
}
})
})
})
})
function getWrapper({ setup, canShare = true, quickLinkExists = false }) {
const createLinkMock = vi.fn()
vi.mocked(useFileActionsCreateLink).mockReturnValue({
actions: computed(() => [
mock<FileAction>({ name: 'create-quick-links', handler: createLinkMock })
])
})
vi.mocked(useCanShare).mockReturnValue({ canShare: vi.fn(() => canShare) })
vi.mocked(buildLinkShare).mockReturnValue(mock<LinkShare>({ isQuickLink: quickLinkExists }))
vi.mocked(useClipboard).mockReturnValue({ copyToClipboard: vi.fn() })
const mocks = { ...defaultComponentMocks(), createLinkMock }
mocks.$clientService.graphAuthenticated.permissions.listPermissions.mockResolvedValue({
data: {
value: [mock<Permission>({ link: { '@libre.graph.quickLink': quickLinkExists } })]
}
} as any)
return {
wrapper: getComposableWrapper(
() => {
const instance = useFileActionsCopyQuickLink()
setup(instance, { mocks })
},
{
mocks,
provide: mocks
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCopyQuicklink.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCopyQuicklink.spec.ts",
"repo_id": "owncloud",
"token_count": 1627
} | 845 |
import { useSpaceActionsDelete } from '../../../../../src/composables/actions'
import { useMessages, useModals } from '../../../../../src/composables/piniaStores'
import { buildSpace, SpaceResource } from '@ownclouders/web-client/src/helpers'
import {
defaultComponentMocks,
mockAxiosResolve,
RouteLocation,
getComposableWrapper
} from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { unref } from 'vue'
import { Drive } from '@ownclouders/web-client/src/generated'
describe('delete', () => {
describe('isVisible property', () => {
it('should be false when no resource given', () => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [] })).toBe(false)
}
})
})
it('should be false when the space is not disabled', () => {
const spaceMock = mock<Drive>({
id: '1',
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
driveType: 'project',
special: null
})
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [buildSpace(spaceMock)] })).toBe(false)
}
})
})
it('should be true when the space is disabled', () => {
const spaceMock = mock<Drive>({
id: '1',
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }],
deleted: { state: 'trashed' }
},
driveType: 'project',
special: null
})
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [buildSpace(spaceMock)] })).toBe(true)
}
})
})
it('should be false when the current user is a viewer', () => {
const spaceMock = mock<Drive>({
id: '1',
root: {
permissions: [{ roles: ['viewer'], grantedToIdentities: [{ user: { id: '1' } }] }],
deleted: { state: 'trashed' }
},
driveType: 'project',
special: null
})
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [buildSpace(spaceMock)] })).toBe(false)
}
})
})
})
describe('handler', () => {
it('should trigger the delete modal window', () => {
getWrapper({
setup: async ({ actions }) => {
const { dispatchModal } = useModals()
await unref(actions)[0].handler({
resources: [
mock<SpaceResource>({ id: '1', canBeDeleted: () => true, driveType: 'project' })
]
})
expect(dispatchModal).toHaveBeenCalledTimes(1)
}
})
})
it('should not trigger the delete modal window without any resource to delete', () => {
getWrapper({
setup: async ({ actions }) => {
const { dispatchModal } = useModals()
await unref(actions)[0].handler({
resources: [
mock<SpaceResource>({ id: '1', canBeDeleted: () => false, driveType: 'project' })
]
})
expect(dispatchModal).toHaveBeenCalledTimes(0)
}
})
})
})
describe('method "deleteSpace"', () => {
it('should show message on success', () => {
getWrapper({
setup: async ({ deleteSpaces }, { clientService }) => {
clientService.graphAuthenticated.drives.deleteDrive.mockResolvedValue(mockAxiosResolve())
await deleteSpaces([
mock<SpaceResource>({ id: '1', canBeDeleted: () => true, driveType: 'project' })
])
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalledTimes(1)
}
})
})
it('should show message on error', () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
getWrapper({
setup: async ({ deleteSpaces }, { clientService }) => {
clientService.graphAuthenticated.drives.deleteDrive.mockRejectedValue(new Error())
await deleteSpaces([
mock<SpaceResource>({ id: '1', canBeDeleted: () => true, driveType: 'project' })
])
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalledTimes(1)
}
})
})
})
})
function getWrapper({
setup
}: {
setup: (
instance: ReturnType<typeof useSpaceActionsDelete>,
{
clientService
}: {
clientService: ReturnType<typeof defaultComponentMocks>['$clientService']
}
) => void
}) {
const mocks = defaultComponentMocks({
currentRoute: mock<RouteLocation>({ name: 'files-spaces-projects' })
})
return {
mocks,
wrapper: getComposableWrapper(
() => {
const instance = useSpaceActionsDelete()
setup(instance, { clientService: mocks.$clientService })
},
{
mocks,
provide: mocks,
pluginOptions: {
piniaOptions: { userState: { user: { id: '1', onPremisesSamAccountName: 'alice' } } }
}
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsDelete.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsDelete.spec.ts",
"repo_id": "owncloud",
"token_count": 2239
} | 846 |
import { nextTick } from 'vue'
import { createWrapper, createAppBar } from './spec'
import { useFileListHeaderPosition } from '../../../../src/composables/fileListHeaderPosition'
describe('useFileListHeaderPosition', () => {
it('should be valid', () => {
const wrapper = createWrapper()
expect(useFileListHeaderPosition).toBeDefined()
expect(wrapper.vm.y).toBe(0)
expect(wrapper.vm.refresh).toBeInstanceOf(Function)
wrapper.unmount()
})
it('should calculate y on window resize', async () => {
const wrapper = createWrapper()
const appBar = createAppBar()
appBar.createElement()
for (const height of [50, 100, 150, 200, 201]) {
appBar.resize(height)
window.onresize(new UIEvent('resize'))
await nextTick()
expect(wrapper.vm.y).toBe(height)
}
wrapper.unmount()
})
it('should calculate y on manual refresh', async () => {
const wrapper = createWrapper()
const appBar = createAppBar()
appBar.createElement()
for (const height of [50, 100, 150, 200, 201]) {
appBar.resize(height)
wrapper.vm.refresh()
await nextTick()
expect(wrapper.vm.y).toBe(height)
}
wrapper.unmount()
})
})
| owncloud/web/packages/web-pkg/tests/unit/composables/fileListHeaderPosition/useFileListHeaderPosition.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/fileListHeaderPosition/useFileListHeaderPosition.spec.ts",
"repo_id": "owncloud",
"token_count": 451
} | 847 |
import { useGetMatchingSpace } from '../../../../src/composables/spaces'
import { defaultComponentMocks, getComposableWrapper, RouteLocation } from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { Resource, SpaceResource } from '@ownclouders/web-client'
describe('useSpaceHelpers', () => {
it('should be valid', () => {
expect(useGetMatchingSpace).toBeDefined()
})
describe('method "getMatchingSpace"', () => {
it('should return the matching project space', () => {
getWrapper({
setup: ({ getMatchingSpace }) => {
const resource = mock<Resource>({ storageId: '1' })
expect(getMatchingSpace(resource).id).toEqual('1')
}
})
})
it('should return the matching public space', () => {
getWrapper({
driveAliasAndItem: 'public/xyz',
setup: ({ getMatchingSpace }) => {
const resource = mock<Resource>()
expect(getMatchingSpace(resource).id).toEqual('xyz')
}
})
})
it('should return the matching share space', () => {
getWrapper({
setup: ({ getMatchingSpace }) => {
const resource = mock<Resource>({ shareRoot: '/' })
expect(getMatchingSpace(resource).driveType).toEqual('share')
}
})
})
})
})
function getWrapper({
driveAliasAndItem = '',
setup
}: {
driveAliasAndItem?: string
setup: (instance: ReturnType<typeof useGetMatchingSpace>) => void
}) {
const mocks = {
...defaultComponentMocks({
currentRoute: mock<RouteLocation>({
name: 'files-spaces-generic',
params: { driveAliasAndItem }
})
})
}
const spaces = [
mock<SpaceResource>({ id: '1', driveType: 'project' }),
mock<SpaceResource>({ id: 'xyz', driveType: 'public' })
]
return {
wrapper: getComposableWrapper(
() => {
const instance = useGetMatchingSpace()
setup(instance)
},
{
mocks,
provide: mocks,
pluginOptions: { piniaOptions: { spacesState: { spaces } } }
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/spaces/useGetMatchingSpace.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/spaces/useGetMatchingSpace.spec.ts",
"repo_id": "owncloud",
"token_count": 839
} | 848 |
import { getExpirationRules } from '../../../../src/helpers/share'
import { mock } from 'vitest-mock-extended'
import { PublicExpirationCapability } from '@ownclouders/web-client/src/ocs/capabilities'
import { createTestingPinia } from 'web-test-helpers'
import { useCapabilityStore } from '../../../../src/composables/piniaStores'
describe('getExpirationRules', () => {
it('correctly computes rules based on the "expire_date"-capability', () => {
vi.useFakeTimers().setSystemTime(new Date('2000-01-01'))
createTestingPinia()
const capabilityStore = useCapabilityStore()
const capabilities = mock<PublicExpirationCapability>({ enforced: true, days: '10' })
capabilityStore.capabilities.files_sharing.public.expire_date = capabilities
const rules = getExpirationRules({
currentLanguage: 'de',
capabilityStore
})
expect(rules.enforced).toEqual(capabilities.enforced)
expect(rules.default).toEqual(new Date('2000-01-11'))
expect(rules.min).toEqual(new Date('2000-01-01'))
expect(rules.max).toEqual(new Date('2000-01-11'))
})
})
| owncloud/web/packages/web-pkg/tests/unit/helpers/share/link.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/share/link.spec.ts",
"repo_id": "owncloud",
"token_count": 375
} | 849 |
import { Ability } from '@ownclouders/web-client/src/helpers/resource/types'
import {
ArchiverService,
ClientService,
LoadingService,
PreviewService,
PasswordPolicyService
} from './src/services'
export * from './src'
declare module 'vue' {
interface ComponentCustomProperties {
$ability: Ability
$archiverService: ArchiverService
$clientService: ClientService
$loadingService: LoadingService
$previewService: PreviewService
$passwordPolicyService: PasswordPolicyService
}
}
| owncloud/web/packages/web-pkg/types.d.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/types.d.ts",
"repo_id": "owncloud",
"token_count": 158
} | 850 |
<template>
<div>
<oc-select
:model-value="currentThemeOrAuto"
:clearable="false"
:options="availableThemesAndAuto"
option-label="name"
@update:model-value="updateTheme"
/>
</div>
</template>
<script lang="ts">
import { computed, defineComponent, ref, unref } from 'vue'
import { useMessages, useThemeStore, WebThemeType } from '@ownclouders/web-pkg'
import { storeToRefs } from 'pinia'
import { useGettext } from 'vue3-gettext'
export default defineComponent({
setup() {
const themeStore = useThemeStore()
const { showMessage } = useMessages()
const { $gettext } = useGettext()
const autoTheme = computed(() => ({ name: $gettext('Auto (same as system)') }))
const { availableThemes, currentTheme } = storeToRefs(themeStore)
const currentThemeSelection = ref(null)
const { setAndApplyTheme, setAutoSystemTheme, isCurrentThemeAutoSystem } = themeStore
const updateTheme = (newTheme: WebThemeType) => {
currentThemeSelection.value = newTheme
showMessage({ title: $gettext('Preference saved.') })
if (newTheme == unref(autoTheme)) {
return setAutoSystemTheme()
}
setAndApplyTheme(newTheme)
}
const currentThemeOrAuto = computed(() => {
if (unref(currentThemeSelection)) {
return unref(currentThemeSelection)
}
if (unref(isCurrentThemeAutoSystem)) {
return unref(autoTheme)
}
return unref(currentTheme)
})
const availableThemesAndAuto = computed(() => [unref(autoTheme), ...unref(availableThemes)])
return {
availableThemesAndAuto,
currentThemeOrAuto,
updateTheme
}
}
})
</script>
| owncloud/web/packages/web-runtime/src/components/ThemeSwitcher.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/components/ThemeSwitcher.vue",
"repo_id": "owncloud",
"token_count": 632
} | 851 |
import { RuntimeApi } from '../types'
import { buildRuntimeApi } from '../api'
import { App } from 'vue'
import { isFunction, isObject } from 'lodash-es'
import { NextApplication } from './next'
import { Router } from 'vue-router'
import { RuntimeError, useAppsStore } from '@ownclouders/web-pkg'
import { AppConfigObject, AppReadyHookArgs, ClassicApplicationScript } from '@ownclouders/web-pkg'
import { useExtensionRegistry } from '@ownclouders/web-pkg'
import type { Language } from 'vue3-gettext'
/**
* this wraps a classic application structure into a next application format.
* it is fully backward compatible and will stay around as a fallback.
*/
class ClassicApplication extends NextApplication {
private readonly applicationScript: ClassicApplicationScript
private readonly app: App
constructor(runtimeApi: RuntimeApi, applicationScript: ClassicApplicationScript, app: App) {
super(runtimeApi)
this.applicationScript = applicationScript
this.app = app
}
initialize(): Promise<void> {
const { routes, navItems, translations } = this.applicationScript
const { globalProperties } = this.app.config
const _routes = typeof routes === 'function' ? routes(globalProperties) : routes
const _navItems = typeof navItems === 'function' ? navItems(globalProperties) : navItems
routes && this.runtimeApi.announceRoutes(_routes)
navItems && this.runtimeApi.announceNavigationItems(_navItems)
translations && this.runtimeApi.announceTranslations(translations)
return Promise.resolve(undefined)
}
ready(): Promise<void> {
const { ready: readyHook } = this.applicationScript
this.attachPublicApi(readyHook)
return Promise.resolve(undefined)
}
mounted(instance: App): Promise<void> {
const { mounted: mountedHook } = this.applicationScript
this.attachPublicApi(mountedHook, instance)
return Promise.resolve(undefined)
}
private attachPublicApi(hook: (arg: AppReadyHookArgs) => void, instance?: App) {
isFunction(hook) &&
hook({
...(instance && {
portal: {
open: (...args) => this.runtimeApi.openPortal.apply(instance, [instance, ...args])
}
}),
instance,
router: this.runtimeApi.requestRouter(),
globalProperties: this.app.config.globalProperties
})
}
}
/**
*
* @param app
* @param applicationPath
* @param router
* @param translations
* @param supportedLanguages
*/
export const convertClassicApplication = ({
app,
applicationScript,
applicationConfig,
router,
gettext,
supportedLanguages
}: {
app: App
applicationScript: ClassicApplicationScript
applicationConfig: AppConfigObject
router: Router
gettext: Language
supportedLanguages: { [key: string]: string }
}): NextApplication => {
if (applicationScript.setup) {
applicationScript = app.runWithContext(() => {
return applicationScript.setup({
...(applicationConfig && { applicationConfig })
})
})
}
const { appInfo } = applicationScript
if (!isObject(appInfo)) {
throw new RuntimeError("appInfo can't be blank")
}
const { id: applicationId, name: applicationName } = appInfo
if (!applicationId) {
throw new RuntimeError("appInfo.id can't be blank")
}
if (!applicationName) {
throw new RuntimeError("appInfo.name can't be blank")
}
const extensionRegistry = useExtensionRegistry()
const runtimeApi = buildRuntimeApi({
applicationName,
applicationId,
router,
gettext,
supportedLanguages,
extensionRegistry
})
const appsStore = useAppsStore()
appsStore.registerApp(applicationScript.appInfo)
if (applicationScript.extensions) {
extensionRegistry.registerExtensions(applicationScript.extensions)
}
return new ClassicApplication(runtimeApi, applicationScript, app)
}
| owncloud/web/packages/web-runtime/src/container/application/classic.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/container/application/classic.ts",
"repo_id": "owncloud",
"token_count": 1226
} | 852 |
export interface SettingsValue {
identifier: {
bundle: string
extension: string
setting: string
}
value: {
accountUuid: string
bundleId: string
id: string
resource: {
type: string
}
settingId: string
boolValue?: boolean
listValue?: {
values: {
stringValue: string
}[]
}
}
}
export interface SettingsBundle {
displayName: string
extension: string
id: string
name: string
resource: {
type: string
}
settings: {
description: string
displayName: string
id: string
name: string
resource: {
type: string
}
singleChoiceValue?: {
options: Record<string, any>[]
}
boolValue?: Record<string, any>
}[]
type: string
}
export interface LanguageOption {
label: string
value: string
}
| owncloud/web/packages/web-runtime/src/helpers/settings.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/helpers/settings.ts",
"repo_id": "owncloud",
"token_count": 319
} | 853 |
import { RouteLocation, RouteParams, Router, RouteRecordNormalized } from 'vue-router'
import {
AuthContext,
authContextValues,
contextQueryToFileContextProps,
queryItemAsString,
WebRouteMeta
} from '@ownclouders/web-pkg'
/**
* Checks if the `to` route or the route it was reached from (i.e. the `contextRoute`) needs authentication from the IdP and a successfully fetched ownCloud user.
*
* @param router {Router}
* @param to {Route}
* @returns {boolean}
*/
export const isUserContextRequired = (router: Router, to: RouteLocation): boolean => {
const meta = getRouteMeta(to)
if (meta.authContext === 'user') {
return true
}
if (meta.authContext !== 'hybrid') {
return false
}
const contextRoute = getContextRoute(router, to)
return (
!contextRoute ||
getRouteMeta({ meta: contextRoute.meta } as RouteLocation).authContext === 'user'
)
}
/**
* Checks if the `to` route or the route it was reached from (i.e. the `contextRoute`) needs authentication from the IdP but should not try to fetch an ownCloud user.
*
* @param router {Router}
* @param to {Route}
* @returns {boolean}
*/
export const isIdpContextRequired = (router: Router, to: RouteLocation): boolean => {
const meta = getRouteMeta(to)
if (meta.authContext === 'idp') {
return true
}
const contextRoute = getContextRoute(router, to)
return (
contextRoute && getRouteMeta({ meta: contextRoute.meta } as RouteLocation).authContext === 'idp'
)
}
/**
* Checks if the `to` route or the route it was reached from (i.e. the `contextRoute`) needs a resolved public link context (with or without password).
*
* @param router {Router}
* @param to {Route}
* @returns {boolean}
*/
export const isPublicLinkContextRequired = (router: Router, to: RouteLocation): boolean => {
if (
(to.params.driveAliasAndItem as string)?.startsWith('public/') ||
(to.params.driveAliasAndItem as string)?.startsWith('ocm/')
) {
return true
}
const meta = getRouteMeta(to)
if (meta.authContext === 'publicLink') {
return true
}
if (meta.authContext !== 'hybrid') {
return false
}
const contextRoute = getContextRoute(router, to)
return (
contextRoute &&
getRouteMeta({ meta: contextRoute.meta } as RouteLocation).authContext === 'publicLink'
)
}
/**
* Extracts the public link token from the various possible route params.
*
* @param to {Route}
* @returns {string}
*/
export const extractPublicLinkToken = (to: RouteLocation): string => {
const contextRouteParams = contextQueryToFileContextProps(to.query)?.routeParams
if (contextRouteParams) {
return extractPublicLinkTokenFromRouteParams(contextRouteParams)
}
return extractPublicLinkTokenFromRouteParams(to.params)
}
/**
* Extracts the public link token from known possible occurrences in params of a route.
*
* @param params {LocationParams}
*/
const extractPublicLinkTokenFromRouteParams = (params: RouteParams): string => {
if (Object.prototype.hasOwnProperty.call(params, 'driveAliasAndItem')) {
const driveAliasAndItem = queryItemAsString(params.driveAliasAndItem)
if (!driveAliasAndItem.startsWith('public/') && !driveAliasAndItem.startsWith('ocm/')) {
return ''
}
return (params.driveAliasAndItem as string).split('/')[1]
}
return ((params.item || params.filePath || params.token || '') as string).split('/')[0]
}
/**
* Asserts that no form of authentication is required.
*
* @param router {Router}
* @param to {Route}
* @returns {boolean}
*/
export const isAnonymousContext = (router: Router, to: RouteLocation): boolean => {
return getRouteMeta(to).authContext === 'anonymous'
}
/**
* The contextRoute in URLs is used to give applications additional context where the application route was triggered from
* (e.g. from a project space, a public link file listing, a personal space, etc).
* Application routes need to fulfill both their own auth requirements and the auth requirements from the context route.
*
* Example: the `preview` app and its routes don't explicitly require authentication (`meta.auth` is set to `false`), because
* the app can be used from both an authenticated context or from a public link context. The information which endpoint
* the preview app is supposed to load files from is transported via the contextRouteName, contextRouteParams and contextRouteQuery
* in the URL (provided by the context that opens the preview app in the first place).
*/
const getContextRoute = (router: Router, to: RouteLocation): RouteRecordNormalized | null => {
const contextRouteNameKey = 'contextRouteName'
if (!to.query || !to.query[contextRouteNameKey]) {
return null
}
return router.getRoutes().find((r) => r.name === to.query[contextRouteNameKey])
}
const getRouteMeta = (to: RouteLocation): WebRouteMeta => {
if (!to.meta) {
return {
authContext: 'user'
}
}
// rewrite deprecated `auth` property to the respective `authContext` value
if (!to.meta.authContext && Object.prototype.hasOwnProperty.call(to.meta, 'auth')) {
to.meta.authContext = to.meta.auth ? 'user' : 'hybrid'
console.warn(
`route key meta.auth is deprecated. Please switch to meta.authContext="${
to.meta.authContext
}" in route "${String(to.name)}".`
)
}
if (to?.meta?.authContext) {
if (authContextValues.includes(to.meta.authContext as AuthContext)) {
return to.meta
}
console.warn(
`invalid authContext "${to.meta.authContext}" in route "${String(
to.name
)}". must be one of [${authContextValues.join(', ')}].`
)
}
if (to?.meta) {
return {
...to.meta,
authContext: 'user'
}
}
return {
authContext: 'user'
}
}
| owncloud/web/packages/web-runtime/src/router/helpers.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/router/helpers.ts",
"repo_id": "owncloud",
"token_count": 1836
} | 854 |
import { Modal, useModals } from '@ownclouders/web-pkg'
import { mock } from 'vitest-mock-extended'
import { PropType, defineComponent } from 'vue'
import ModalWrapper from 'web-runtime/src/components/ModalWrapper.vue'
import { defaultPlugins, shallowMount, defaultComponentMocks } from 'web-test-helpers'
const CustomModalComponent = defineComponent({
name: 'CustomModalComponent',
props: {
modal: { type: Object as PropType<Modal>, required: true }
},
setup() {
return { onConfirm: vi.fn() }
},
template: '<div id="foo"></div>'
})
describe('ModalWrapper', () => {
it('renders OcModal when a modal is active', async () => {
const modal = mock<Modal>()
const { wrapper } = getShallowWrapper({ modals: [modal] })
const modalStore = useModals()
;(modalStore.activeModal as any) = modal
await wrapper.vm.$nextTick()
expect(wrapper.find('.oc-modal').exists()).toBeTruthy()
})
it('renders a custom component if given', async () => {
const modal = {
id: 'some-id',
title: 'some-title',
customComponent: CustomModalComponent
} as Modal
const { wrapper } = getShallowWrapper({ modals: [modal] })
const modalStore = useModals()
;(modalStore.activeModal as any) = modal
await wrapper.vm.$nextTick()
expect(wrapper.find('custom-modal-component-stub').exists()).toBeTruthy()
})
describe('method "onModalConfirm"', () => {
it('calls the modal "onConfirm" if given, disables the confirm button and removes the modal', async () => {
const modal = mock<Modal>({ onConfirm: vi.fn().mockResolvedValue(undefined) })
const { wrapper } = getShallowWrapper({ modals: [modal] })
const modalStore = useModals()
;(modalStore.activeModal as any) = modal
const value = 'value'
await wrapper.vm.onModalConfirm(value)
expect(modal.onConfirm).toHaveBeenCalledWith(value)
expect(modalStore.updateModal).toHaveBeenCalled()
expect(modalStore.removeModal).toHaveBeenCalled()
})
it('does not remove the modal if the promise has not been resolved', async () => {
const modal = mock<Modal>({ onConfirm: vi.fn().mockRejectedValue(new Error('')) })
const { wrapper } = getShallowWrapper({ modals: [modal] })
const modalStore = useModals()
;(modalStore.activeModal as any) = modal
await wrapper.vm.onModalConfirm()
expect(modalStore.removeModal).not.toHaveBeenCalled()
})
it('calls the custom component "onConfirm" if given', async () => {
const modal = mock<Modal>({ onConfirm: null })
const { wrapper } = getShallowWrapper({ modals: [modal] })
const modalStore = useModals()
;(modalStore.activeModal as any) = modal
await wrapper.vm.$nextTick()
wrapper.vm.customComponentRef = { onConfirm: vi.fn() }
await wrapper.vm.onModalConfirm()
expect(wrapper.vm.customComponentRef.onConfirm).toHaveBeenCalled()
})
})
describe('method "onModalCancel"', () => {
it('calls the modal "onCancel" if given and removes the modal', async () => {
const modal = mock<Modal>({ onCancel: vi.fn() })
const { wrapper } = getShallowWrapper({ modals: [modal] })
const modalStore = useModals()
;(modalStore.activeModal as any) = modal
await wrapper.vm.onModalCancel()
expect(modal.onCancel).toHaveBeenCalled()
expect(modalStore.removeModal).toHaveBeenCalled()
})
it('calls the custom component "onCancel" if given', async () => {
const modal = mock<Modal>({ onCancel: null })
const { wrapper } = getShallowWrapper({ modals: [modal] })
const modalStore = useModals()
;(modalStore.activeModal as any) = modal
await wrapper.vm.$nextTick()
wrapper.vm.customComponentRef = { onCancel: vi.fn() }
await wrapper.vm.onModalCancel()
expect(wrapper.vm.customComponentRef.onCancel).toHaveBeenCalled()
})
})
describe('method "onModalInput"', () => {
it('calls the modal "onInput" if given', async () => {
const modal = mock<Modal>({ onInput: vi.fn() })
const { wrapper } = getShallowWrapper({ modals: [modal] })
const modalStore = useModals()
;(modalStore.activeModal as any) = modal
const value = 'value'
await wrapper.vm.onModalInput(value)
expect(modal.onInput).toHaveBeenCalledWith(value, expect.anything())
})
})
describe('method "onModalConfirmDisabled"', () => {
it('updates the modal confirm button state', async () => {
const modal = mock<Modal>()
const { wrapper } = getShallowWrapper({ modals: [modal] })
const modalStore = useModals()
;(modalStore.activeModal as any) = modal
const value = true
await wrapper.vm.onModalConfirmDisabled(value)
expect(modalStore.updateModal).toHaveBeenCalled()
})
})
})
function getShallowWrapper({ modals = [] } = {}) {
const mocks = defaultComponentMocks()
return {
wrapper: shallowMount(ModalWrapper, {
global: {
plugins: [...defaultPlugins({ piniaOptions: { modalsState: { modals } } })],
renderStubDefaultSlot: true,
mocks,
provide: mocks,
stubs: { OcModal: false }
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/components/ModalWrapper.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/ModalWrapper.spec.ts",
"repo_id": "owncloud",
"token_count": 2049
} | 855 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`SidebarToggle component > should show the "Toggle sidebar"-button with sidebar opened and closed 1`] = `
"<button type="button" aria-label="Open sidebar to view details" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-brand oc-button-brand-raw-inverse oc-my-s" id="files-toggle-sidebar" issidebaropen="true">
<!--v-if-->
<!-- @slot Content of the button --> <span class="oc-icon oc-icon-m oc-icon-passive"><!----></span>
</button>"
`;
exports[`SidebarToggle component > should show the "Toggle sidebar"-button with sidebar opened and closed 2`] = `
"<button type="button" aria-label="Open sidebar to view details" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-brand oc-button-brand-raw-inverse oc-my-s" id="files-toggle-sidebar" issidebaropen="false">
<!--v-if-->
<!-- @slot Content of the button --> <span class="oc-icon oc-icon-m oc-icon-passive"><!----></span>
</button>"
`;
| owncloud/web/packages/web-runtime/tests/unit/components/Topbar/__snapshots__/SidebarToggle.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Topbar/__snapshots__/SidebarToggle.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 371
} | 856 |
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
// @vitest-environment jsdom
describe('buildUrl', () => {
it.each`
location | base | path | expected
${'https://localhost:8080/index.php/apps/web/index.html#/files/list/all'} | ${''} | ${'/login'} | ${'https://localhost:8080/index.php/apps/web#/login'}
${'https://localhost:8080/index.php/apps/web/index.html#/files/list/all'} | ${''} | ${'/login/foo'} | ${'https://localhost:8080/index.php/apps/web#/login/foo'}
${'https://localhost:8080/////index.php/apps/web/////index.html#/files/list/all'} | ${''} | ${'/login/foo'} | ${'https://localhost:8080/index.php/apps/web#/login/foo'}
${'https://localhost:8080/index.php/apps/web/#/login'} | ${''} | ${'/bar.html'} | ${'https://localhost:8080/index.php/apps/web/bar.html'}
${'https://localhost:8080/index.php/apps/web/#/login'} | ${'/index.php/apps/web/foo'} | ${'/bar'} | ${'https://localhost:8080/index.php/apps/web/foo/bar'}
${'https://localhost:8080/index.php/apps/web/#/login'} | ${'/index.php/apps/web/foo'} | ${'/bar.html'} | ${'https://localhost:8080/index.php/apps/web/foo/bar.html'}
${'https://localhost:9200/#/files/list/all'} | ${''} | ${'/login/foo'} | ${'https://localhost:9200/#/login/foo'}
${'https://localhost:9200/#/files/list/all'} | ${''} | ${'/bar.html'} | ${'https://localhost:9200/bar.html'}
${'https://localhost:9200/files/list/all'} | ${'/'} | ${'/login/foo'} | ${'https://localhost:9200/login/foo'}
${'https://localhost:9200/files/list/all'} | ${'/foo'} | ${'/login/foo'} | ${'https://localhost:9200/foo/login/foo'}
${'https://localhost:9200/files/list/all'} | ${'/'} | ${'/bar.html'} | ${'https://localhost:9200/bar.html'}
${'https://localhost:9200/files/list/all'} | ${'/foo'} | ${'/bar.html'} | ${'https://localhost:9200/foo/bar.html'}
`('$path -> $expected', async ({ location, base, path, expected }) => {
delete window.location
window.location = new URL(location) as any
document.querySelectorAll('base').forEach((e) => e.remove())
if (base) {
const baseElement = document.createElement('base')
baseElement.href = base
document.getElementsByTagName('head')[0].appendChild(baseElement)
}
const { buildUrl } = await import('@ownclouders/web-pkg/src/helpers/router/buildUrl')
vi.resetModules()
// hide warnings for non-existent routes
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const router = createRouter({
routes: [
{
path: '/login',
component: {}
}
],
history: (base && createWebHistory(base)) || createWebHashHistory()
})
expect(buildUrl(router, path)).toBe(expected)
})
})
| owncloud/web/packages/web-runtime/tests/unit/router/index.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/router/index.spec.ts",
"repo_id": "owncloud",
"token_count": 1773
} | 857 |
export * from './axios'
export * from './useGetMatchingSpaceMock'
export * from './pinia'
| owncloud/web/packages/web-test-helpers/src/mocks/index.ts/0 | {
"file_path": "owncloud/web/packages/web-test-helpers/src/mocks/index.ts",
"repo_id": "owncloud",
"token_count": 32
} | 858 |
exports.command = function (callback) {
const helperElementId = 'helperClipboardInput'
this.execute(
function (elementId) {
const myInput = document.createElement('INPUT')
const inputId = document.createAttribute('id')
inputId.value = elementId
myInput.setAttributeNode(inputId)
myInput.setAttribute('style', 'position: absolute; left:0; top:0;') // make sure its visible
document.body.appendChild(myInput)
},
[helperElementId]
)
.useCss()
.setValue(`#${helperElementId}`, '') // just to focus the element
.keys([this.Keys.CONTROL, 'v']) // copy the content of the clipboard into that field
.getValue(`#${helperElementId}`, function (clipboard) {
callback(clipboard.value)
})
.execute(
function (elementId) {
const el = document.getElementById(elementId)
el.parentNode.removeChild(el)
},
[helperElementId]
)
return this
}
| owncloud/web/tests/acceptance/customCommands/getClipBoardContent.js/0 | {
"file_path": "owncloud/web/tests/acceptance/customCommands/getClipBoardContent.js",
"repo_id": "owncloud",
"token_count": 364
} | 859 |
Feature: deleting files and folders
As a user
I want to delete files and folders
So that I can keep my filing system clean and tidy
Background:
Given user "Alice" has been created with default attributes and without skeleton files in the server
Scenario Outline: Delete a file with problematic characters
Given user "Alice" has created file <file_name> in the server
And user "Alice" has logged in using the webUI
When the user deletes file <file_name> using the webUI
Then file <file_name> should not be listed on the webUI
When the user reloads the current page of the webUI
Then file <file_name> should not be listed on the webUI
Examples:
| file_name |
| "'single'" |
| "\"double\" quotes" |
| "question?" |
| "&and#hash" |
Scenario: delete a file on a public share with problematic characters
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has created folder "simple-folder" in the server
And user "Alice" has renamed the following file in the server
| from-name-parts | to-name-parts |
| lorem.txt | simple-folder/ |
| | 'single' |
| | "double" quotes |
| | question? |
| | &and#hash |
And user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions in the server
When the public uses the webUI to access the last public link created by user "Alice" in a new session
And the user deletes the following file using the webUI
| name-parts |
| 'single' |
| "double" quotes |
| question? |
| &and#hash |
Then the following file should not be listed on the webUI
| name-parts |
| 'single' |
| "double" quotes |
| question? |
| &and#hash |
And no message should be displayed on the webUI
When the user reloads the current page of the webUI
Then the following file should not be listed on the webUI
| name-parts |
| 'single' |
| "double" quotes |
| question? |
| &and#hash |
Scenario: Delete folder with dot in the name
Given user "Alice" has created the following folders in the server
| folders |
| fo. |
| fo.1 |
| fo...1.. |
| fo.xyz |
And user "Alice" has logged in using the webUI
When the user batch deletes these files using the webUI
| folders |
| fo. |
| fo.1 |
| fo...1.. |
| fo.xyz |
Then as "Alice" these folders should not be listed on the webUI
| folders |
| fo. |
| fo.1 |
| fo...1.. |
| fo.xyz |
| owncloud/web/tests/acceptance/features/webUIDeleteFilesFolders/deleteFilesFolders.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUIDeleteFilesFolders/deleteFilesFolders.feature",
"repo_id": "owncloud",
"token_count": 1193
} | 860 |
@public_link_share-feature-required
Feature: Create public link shares
As a user
I want to share files through a publicly accessible link
So that users who do not have an account on my ownCloud server can access them
Background:
Given user "Alice" has been created with default attributes and without skeleton files in the server
@smokeTest @ocisSmokeTest @issue-ocis-reva-383
Scenario: simple folder sharing by public link
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has logged in using the webUI
When the user creates a new public link for resource "simple-folder" using the webUI
Then user "Alice" should have a share with these details in the server:
| field | value |
| share_type | public_link |
| uid_owner | Alice |
| permissions | read |
| path | /simple-folder |
| name | Link |
And a link named "Link" should be listed with role "Anyone with the link can view" in the public link list of resource "simple-folder" on the webUI
When the public uses the webUI to access the last public link created by user "Alice" in a new session
Then file "lorem.txt" should be listed on the webUI
@skipOnOC10 @smokeTest @ocisSmokeTest @issue-ocis-reva-383
Scenario: simple file sharing by public link
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has logged in using the webUI
When the user creates a new public link for resource "lorem.txt" using the webUI
Then user "Alice" should have a share with these details in the server:
| field | value |
| share_type | public_link |
| uid_owner | Alice |
| permissions | read |
| path | /lorem.txt |
| name | Link |
And a link named "Link" should be listed with role "Anyone with the link can view" in the public link list of resource "lorem.txt" on the webUI
When the public uses the webUI to access the last public link created by user "Alice" in a new session
And the user closes the text editor using the webUI
Then file "lorem.txt" should be listed on the webUI as single share
@skipOnOC10 @issue-ocis-reva-383
# When this issue is fixed delete this scenario and use the one above
Scenario: simple folder sharing by public link (ocis bug demonstration)
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has logged in using the webUI
When the user creates a new public link for resource "simple-folder" using the webUI
Then user "Alice" should have a share with these details in the server:
| field | value |
| share_type | public_link |
| uid_owner | Alice |
| permissions | read |
| path | /simple-folder |
When the public uses the webUI to access the last public link created by user "Alice" in a new session
Then file "lorem.txt" should be listed on the webUI
@skipOnOC10 @issue-ocis-reva-383
# When this issue is fixed delete this scenario and use the one above
Scenario: simple file sharing by public link (ocis bug demonstration)
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has logged in using the webUI
When the user creates a new public link for resource "lorem.txt" using the webUI
Then user "Alice" should have a share with these details in the server:
| field | value |
| share_type | public_link |
| uid_owner | Alice |
| permissions | read |
| path | /lorem.txt |
When the public uses the webUI to access the last public link created by user "Alice" in a new session
And the user closes the text editor using the webUI
Then file "lorem.txt" should be listed on the webUI as single share
@issue-ocis-reva-389
Scenario: user shares a public link with folder longer than 64 chars and shorter link name
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has renamed folder "simple-folder" to "aquickbrownfoxjumpsoveraverylazydogaquickbrownfoxjumpsoveralazydog" in the server
And user "Alice" has logged in using the webUI
When the user creates a new public link for folder "aquickbrownfoxjumpsoveraverylazydogaquickbrownfoxjumpsoveralazydog" using the webUI
And the public uses the webUI to access the last public link created by user "Alice" in a new session
Then file "lorem.txt" should be listed on the webUI
Scenario: share two files with same name but different paths by public link
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has created file "lorem.txt" in the server
And user "Alice" has logged in using the webUI
When the user creates a new public link for file "lorem.txt" using the webUI
And the user opens folder "simple-folder" using the webUI
And the user creates a new public link for file "lorem.txt" using the webUI
# using the webui to navigate creates a problem because "successfully created link" notifications block the nav
And the user has browsed to the shared-via-link page
Then file with path "lorem.txt" should be listed on the webUI
And file with path "simple-folder/lorem.txt" should be listed on the webUI
Scenario: user creates a multiple public link of a file and delete the first link
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | first-name |
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | second-name |
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | third-name |
And user "Alice" has logged in using the webUI
When the user removes the public link named "first-name" of file "lorem.txt" using the webUI
Then public link named "first-name" should not be listed on the public links list on the webUI
And a link named "second-name" should be listed with role "Anyone with the link can view" in the public link list of file "lorem.txt" on the webUI
And a link named "third-name" should be listed with role "Anyone with the link can view" in the public link list of folder "lorem.txt" on the webUI
Scenario: user creates a multiple public link of a file and delete the second link
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | first-name |
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | second-name |
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | third-name |
And user "Alice" has logged in using the webUI
When the user removes the public link named "second-name" of file "lorem.txt" using the webUI
Then public link named "second-name" should not be listed on the public links list on the webUI
And a link named "first-name" should be listed with role "Anyone with the link can view" in the public link list of file "lorem.txt" on the webUI
And a link named "third-name" should be listed with role "Anyone with the link can view" in the public link list of folder "lorem.txt" on the webUI
Scenario: user creates a multiple public link of a file and delete the third link
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | first-name |
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | second-name |
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | third-name |
And user "Alice" has logged in using the webUI
When the user removes the public link named "third-name" of file "lorem.txt" using the webUI
Then public link named "third-name" should not be listed on the public links list on the webUI
And a link named "first-name" should be listed with role "Anyone with the link can view" in the public link list of file "lorem.txt" on the webUI
And a link named "second-name" should be listed with role "Anyone with the link can view" in the public link list of folder "lorem.txt" on the webUI
Scenario Outline: user creates multiple public links with same name for the same file/folder
Given user "Alice" has created <element> "<name>" in the server
And user "Alice" has logged in using the webUI
When the user creates a new public link for <element> "<name>" using the webUI
And the user creates a new public link for <element> "<name>" using the webUI
Then the tokens should be unique for each public links on the webUI
Examples:
| element | name |
| folder | simple-folder |
| file | lorem.txt |
Scenario: User can create a public link via quick action
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has logged in using the webUI
When the user creates a public link via quick action for resource "simple-folder" using the webUI
Then user "Alice" should have a share with these details in the server:
| field | value |
| share_type | public_link |
| uid_owner | Alice |
| permissions | read |
| path | /simple-folder |
| name | Link |
And the following success message should be displayed on the webUI
"""
The link has been copied to your clipboard.
"""
| owncloud/web/tests/acceptance/features/webUISharingPublicBasic/publicLinkCreate.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUISharingPublicBasic/publicLinkCreate.feature",
"repo_id": "owncloud",
"token_count": 3376
} | 861 |
const occHelper = require('./occHelper')
const { difference } = require('./objects')
const _ = require('lodash')
const config = {}
async function rollbackSystemConfigs(oldSysConfig, newSysConfig) {
const configToChange = difference(newSysConfig, oldSysConfig)
for (const key in configToChange) {
if (typeof configToChange[key] === 'object') {
continue
}
const value = _.get(oldSysConfig, [key])
if (value === undefined) {
await occHelper.runOcc(['config:system:delete', key])
} else if (typeof value === 'boolean') {
await occHelper.runOcc(['config:system:set', key, `--type=boolean --value=${value}`])
} else {
await occHelper.runOcc(['config:system:set', key, `--value=${value}`])
}
}
}
async function rollbackAppConfigs(oldAppConfig, newAppConfig) {
const configToChange = difference(newAppConfig, oldAppConfig)
for (const app in configToChange) {
for (const key in configToChange[app]) {
const value = _.get(oldAppConfig, [app, key])
if (value === undefined) {
await occHelper.runOcc(['config:app:delete', app, key])
} else {
await occHelper.runOcc(['config:app:set', app, key, `--value=${value}`])
}
}
}
}
const getConfigs = async function () {
const resp = await occHelper.runOcc(['config:list'])
let stdOut = _.get(resp, 'ocs.data.stdOut')
if (stdOut === undefined) {
throw new Error('stdOut notFound, Found:', resp)
}
stdOut = JSON.parse(stdOut)
return stdOut
}
exports.getConfigs = getConfigs
exports.cacheConfigs = async function (server) {
config[server] = await getConfigs()
return config
}
exports.rollbackConfigs = async function (server) {
const newConfig = await getConfigs()
const appConfig = _.get(newConfig, 'apps')
const systemConfig = _.get(newConfig, 'system')
const initialAppConfig = _.get(config[server], 'apps')
const initialSysConfig = _.get(config[server], 'system')
await rollbackSystemConfigs(initialSysConfig, systemConfig)
await rollbackAppConfigs(initialAppConfig, appConfig)
}
| owncloud/web/tests/acceptance/helpers/config.js/0 | {
"file_path": "owncloud/web/tests/acceptance/helpers/config.js",
"repo_id": "owncloud",
"token_count": 733
} | 862 |
module.exports = {
commands: {
/**
* @enum {string}
* @readonly
*/
ContextMenuItem: Object.freeze({
showDetails: 'detailsButton',
showActions: 'actionsButton',
selectRenameFile: 'renameButton'
}),
/**
* @param {string} elementName the name of the element (mapped in `ContextMenuItem`)
*/
clickMenuItem: async function (elementName) {
const element = this.elements[elementName]
await this.click(element.locateStrategy, element.selector)
return this
},
/**
* Clicks the menu item for showing details
*
* @returns {*}
*/
showDetails: async function () {
await this.clickMenuItem(this.ContextMenuItem.showDetails)
await this.waitForAnimationToFinish() // wait for sidebar animation to finish
return this
},
/**
* Clicks the menu item for showing all actions
*
* @returns {*}
*/
showActions: async function () {
await this.clickMenuItem(this.ContextMenuItem.showActions)
await this.waitForAnimationToFinish() // wait for sidebar animation to finish
return this
},
selectRenameFile: function () {
return this.clickMenuItem(this.ContextMenuItem.selectRenameFile)
}
},
elements: {
detailsButton: {
selector: '//button[contains(@class, "oc-files-actions-show-details-trigger")]',
locateStrategy: 'xpath'
},
actionsButton: {
selector: '//button[contains(@class, "oc-files-actions-show-actions-trigger")]',
locateStrategy: 'xpath'
},
renameButton: {
selector: '//button[contains(@class, "oc-files-actions-rename-trigger")]',
locateStrategy: 'xpath'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/FilesPageElement/contextMenu.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/FilesPageElement/contextMenu.js",
"repo_id": "owncloud",
"token_count": 668
} | 863 |
module.exports = {
url: function () {
return this.api.launchUrl
},
elements: {
body: 'body',
usernameInput: {
selector: 'input[autocomplete="kopano-account username"]'
},
passwordInput: {
selector: 'input[autocomplete="kopano-account current-password"]'
},
loginSubmitButton: {
selector: 'button[type="submit"]'
},
invalidCredentialsMessage: {
selector: '#oc-login-error-message'
}
},
commands: [
{
/**
*
* @param {string} username
* @param {string} password
* @param expectToSucceed
*/
login: async function (username, password, expectToSucceed = true) {
await this.waitForElementVisible('@usernameInput')
.clearValue('@usernameInput')
.setValue('@usernameInput', username)
.clearValue('@passwordInput')
.setValue('@passwordInput', password)
.click('@loginSubmitButton')
if (expectToSucceed) {
await this.waitForElementNotPresent('@usernameInput')
} else {
await this.waitForElementPresent('@usernameInput')
}
return this
},
getLoginErrorMessage: async function () {
let errorMessage
await this.api.assert.visible(this.elements.usernameInput.selector)
await this.api.assert.visible(this.elements.passwordInput.selector)
await this.api.assert.visible(this.elements.loginSubmitButton.selector)
await this.useXpath()
.waitForElementVisible('@invalidCredentialsMessage')
.getText('@invalidCredentialsMessage', (result) => {
errorMessage = result.value
})
.useCss()
return errorMessage
},
waitForPage: function () {
return this.waitForElementVisible('@loginSubmitButton')
}
}
]
}
| owncloud/web/tests/acceptance/pageObjects/ocisLoginPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/ocisLoginPage.js",
"repo_id": "owncloud",
"token_count": 790
} | 864 |
const { When } = require('@cucumber/cucumber')
When('pause for {int}', async function (duration) {
await new Promise((resolve) => setTimeout(resolve, duration))
})
| owncloud/web/tests/acceptance/stepDefinitions/debugContext.js/0 | {
"file_path": "owncloud/web/tests/acceptance/stepDefinitions/debugContext.js",
"repo_id": "owncloud",
"token_count": 53
} | 865 |
{
"server": "https://ocis:9200",
"theme": "https://ocis:9200/themes/owncloud/theme.json",
"openIdConnect": {
"metadata_url": "https://ocis:9200/.well-known/openid-configuration",
"authority": "https://ocis:9200",
"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/config-ocis.json/0 | {
"file_path": "owncloud/web/tests/drone/config-ocis.json",
"repo_id": "owncloud",
"token_count": 321
} | 866 |
Feature: lock
As a user
I can see that a file is locked if it is opened by a user with edit permissions,
and I am restricted in some actions such as moving deleting renaming a locked file
Scenario: file lock indication
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
And "Alice" logs in
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| test.odt | some content |
And "Alice" creates the following folder in personal space using API
| name |
| folder |
And "Alice" shares the following resource using API
| resource | recipient | type | role |
| test.odt | Brian | user | Can edit |
And "Brian" logs in
And "Brian" opens the "files" app
And "Brian" navigates to the shared with me page
When "Brian" opens the following file in Collabora
| resource |
| test.odt |
Then "Brian" should see the content "some content" in editor "Collabora"
When "Alice" opens the "files" app
Then for "Alice" file "test.odt" should be locked
# checking that sharing/unsharing and creating link of the locked file is possible
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | password |
| test.odt | %public% |
And "Alice" shares the following resource using the sidebar panel
| resource | recipient | type | role | resourceType |
| test.odt | Carol | user | Can view | file |
# unsharing should remove lock https://github.com/owncloud/ocis/issues/8273
# And "Alice" removes following sharee
# | resource | recipient |
# | test.odt | Brian |
And "Brian" logs out
When "Alice" reloads the page
Then for "Alice" file "test.odt" should not be locked
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/app-provider/lock.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/app-provider/lock.feature",
"repo_id": "owncloud",
"token_count": 659
} | 867 |
Feature: GDPR export
As a user
I want to export a report of all my personal data
So I know what data is currently being stored on the system
Background:
Given "Admin" creates following users using API
| id |
| Alice |
Scenario: User should be able to create and download a GDPR export
And "Alice" logs in
And "Alice" opens the user menu
And "Alice" requests a new GDPR export
And "Alice" downloads the GDPR export
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/smoke/gdprExport.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/gdprExport.feature",
"repo_id": "owncloud",
"token_count": 154
} | 868 |
Feature: check files pagination in project 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 "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Alice" logs in
And "Alice" creates the following project space using API
| name | id |
| Developers | dev.1 |
And "Alice" creates 55 folders in space "Developers" using API
And "Alice" creates 55 files in space "Developers" using API
And "Alice" creates the following file in space "Developers" using API
| name | content |
| .hidden-testFile.txt | This is a hidden file. |
And "Alice" opens the "files" app
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "dev.1"
When "Alice" navigates to page "2" of the project space files view
Then "Alice" should see the text "112 items with 1 kB in total (56 files, 56 folders)" at the footer of the page
And "Alice" should see 10 resources in the project space files view
When "Alice" enables the option to display the hidden file
Then "Alice" should see 12 resources in the project space files view
When "Alice" changes the items per page to "500"
Then "Alice" should not see the pagination in the project space files view
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/spaces/pagination.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/spaces/pagination.feature",
"repo_id": "owncloud",
"token_count": 514
} | 869 |
import { Given, When, Then } from '@cucumber/cucumber'
import { World } from '../../environment'
import { config } from '../../../config'
import { objects } from '../../../support'
async function createNewSession(world: World, stepUser: string) {
const { page } = await world.actorsEnvironment.createActor({
key: stepUser,
namespace: world.actorsEnvironment.generateNamespace(world.feature.name, stepUser)
})
return new objects.runtime.Session({ page })
}
async function LogInUser(this: World, stepUser: string): Promise<void> {
const sessionObject = await createNewSession(this, stepUser)
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const user =
stepUser === 'Admin'
? this.usersEnvironment.getUser({ key: stepUser })
: this.usersEnvironment.getCreatedUser({ key: stepUser })
await page.goto(config.frontendUrl)
await sessionObject.login({ user })
await page.locator('#web-content').waitFor()
}
Given('{string} has logged in', LogInUser)
When('{string} logs in', LogInUser)
async function LogOutUser(this: World, stepUser: string): Promise<void> {
const actor = this.actorsEnvironment.getActor({ key: stepUser })
const canLogout = !!(await actor.page.locator('#_userMenuButton').count())
const sessionObject = new objects.runtime.Session({ page: actor.page })
canLogout && (await sessionObject.logout())
await actor.close()
}
Given('{string} has logged out', LogOutUser)
When('{string} logs out', LogOutUser)
Then('{string} fails to log in', async function (this: World, stepUser: string): Promise<void> {
await createNewSession(this, stepUser)
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const user = this.usersEnvironment.getUser({ key: stepUser })
await page.goto(config.frontendUrl)
await page.locator('#oc-login-username').fill(user.id)
await page.locator('#oc-login-password').fill(user.password)
await page.locator('button[type="submit"]').click()
await page.locator('#oc-login-error-message').waitFor()
})
When(
'{string} logs in from the internal link',
async function (this: World, stepUser: string): Promise<void> {
const sessionObject = await createNewSession(this, stepUser)
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const user = this.usersEnvironment.getUser({ key: stepUser })
await sessionObject.login({ user })
await page.locator('#web').waitFor()
}
)
| owncloud/web/tests/e2e/cucumber/steps/ui/session.ts/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/steps/ui/session.ts",
"repo_id": "owncloud",
"token_count": 775
} | 870 |
import { checkResponseStatus, request } from '../http'
import { Group, Me, User } from '../../types'
import join from 'join-path'
import { config } from '../../../config'
import { getApplicationEntity } from './utils'
import { userRoleStore } from '../../store'
import { UsersEnvironment } from '../../environment'
export const me = async ({ user }: { user: User }): Promise<Me> => {
const response = await request({
method: 'GET',
path: join('graph', 'v1.0', 'me'),
user
})
return (await response.json()) as Me
}
export const createUser = async ({ user, admin }: { user: User; admin: User }): Promise<User> => {
const body = JSON.stringify({
displayName: user.displayName,
mail: user.email,
onPremisesSamAccountName: user.id,
passwordProfile: { password: user.password }
})
const response = await request({
method: 'POST',
path: join('graph', 'v1.0', 'users'),
body,
user: admin
})
checkResponseStatus(response, 'Failed while creating user')
const usersEnvironment = new UsersEnvironment()
const resBody = (await response.json()) as User
usersEnvironment.storeCreatedUser({ user: { ...user, uuid: resBody.id } })
return user
}
export const deleteUser = async ({ user, admin }: { user: User; admin: User }): Promise<User> => {
await request({
method: 'DELETE',
path: join('graph', 'v1.0', 'users', user.id),
user: admin
})
try {
const usersEnvironment = new UsersEnvironment()
usersEnvironment.removeCreatedUser({ key: user.id })
} catch (e) {}
return user
}
export const getUserId = async ({ user, admin }: { user: User; admin: User }): Promise<string> => {
let userId = ''
const response = await request({
method: 'GET',
path: join('graph', 'v1.0', 'users', user.id),
user: admin
})
if (response.ok) {
const resBody = (await response.json()) as User
userId = resBody.id
}
return userId
}
export const createGroup = async ({
group,
admin
}: {
group: Group
admin: User
}): Promise<Group> => {
const body = JSON.stringify({
displayName: group.displayName
})
const response = await request({
method: 'POST',
path: join('graph', 'v1.0', 'groups'),
body,
user: admin
})
checkResponseStatus(response, 'Failed while creating group')
const usersEnvironment = new UsersEnvironment()
const resBody = (await response.json()) as Group
usersEnvironment.storeCreatedGroup({ group: { ...group, uuid: resBody.id } })
return group
}
const getGroupId = async ({ group, admin }: { group: Group; admin: User }): Promise<string> => {
let groupId = ''
const response = await request({
method: 'GET',
path: join('graph', 'v1.0', 'groups', group.displayName),
user: admin
})
if (response.ok) {
const resBody = (await response.json()) as Group
groupId = resBody.id
}
return groupId
}
export const deleteGroup = async ({
group,
admin
}: {
group: Group
admin: User
}): Promise<Group> => {
const usersEnvironment = new UsersEnvironment()
const groupId = usersEnvironment.getCreatedGroup({ key: group.id }).uuid
await request({
method: 'DELETE',
path: join('graph', 'v1.0', 'groups', groupId),
user: admin
})
return group
}
export const addUserToGroup = async ({
user,
group,
admin
}: {
user: User
group: Group
admin: User
}): Promise<void> => {
const groupId = await getGroupId({ group, admin })
const userId = await getUserId({ user, admin })
const body = JSON.stringify({
'@odata.id': join(config.backendUrl, 'graph', 'v1.0', 'users', userId)
})
const response = await request({
method: 'POST',
path: join('graph', 'v1.0', 'groups', groupId, 'members', '$ref'),
body: body,
user: admin
})
checkResponseStatus(response, 'Failed while adding an user to the group')
}
export const assignRole = async (admin: User, id: string, role: string): Promise<void> => {
const applicationEntity = await getApplicationEntity(admin)
if (!userRoleStore.has(role)) {
applicationEntity.appRoles.forEach((role) => {
userRoleStore.set(role.displayName, role.id)
})
}
if (userRoleStore.get(role) === undefined) {
throw new Error(`unknown role "${role}"`)
}
const response = await request({
method: 'POST',
path: join('graph', 'v1.0', 'users', id, 'appRoleAssignments'),
user: admin,
body: JSON.stringify({
principalId: id,
appRoleId: userRoleStore.get(role),
resourceId: applicationEntity.id
})
})
checkResponseStatus(response, 'Failed while assigning role to the user')
}
| owncloud/web/tests/e2e/support/api/graph/userManagement.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/graph/userManagement.ts",
"repo_id": "owncloud",
"token_count": 1569
} | 871 |
import { Browser, BrowserContextOptions } from '@playwright/test'
import path from 'path'
export interface ActorsOptions {
browser: Browser
context: {
acceptDownloads: boolean
reportDir: string
reportVideo: boolean
reportHar: boolean
reportTracing: boolean
}
}
export interface ActorOptions extends ActorsOptions {
id: string
namespace: string
}
export const buildBrowserContextOptions = (options: ActorOptions): BrowserContextOptions => {
const contextOptions: BrowserContextOptions = {
acceptDownloads: options.context.acceptDownloads,
permissions: ['clipboard-read', 'clipboard-write'],
ignoreHTTPSErrors: true,
locale: 'en-US'
}
if (options.context.reportVideo) {
contextOptions.recordVideo = {
dir: path.join(options.context.reportDir, 'playwright', 'video')
}
}
if (options.context.reportHar) {
contextOptions.recordHar = {
path: path.join(options.context.reportDir, 'playwright', 'har', `${options.namespace}.har`)
}
}
return contextOptions
}
| owncloud/web/tests/e2e/support/environment/actor/shared.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/environment/actor/shared.ts",
"repo_id": "owncloud",
"token_count": 335
} | 872 |
import { Page } from '@playwright/test'
const groupsNavSelector = '//a[@data-nav-name="admin-settings-groups"]'
const appLoadingSpinnerSelector = '#app-loading-spinner'
export class Groups {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
async navigate(): Promise<void> {
await this.#page.locator(groupsNavSelector).click()
await this.#page.locator(appLoadingSpinnerSelector).waitFor({ state: 'detached' })
}
}
| owncloud/web/tests/e2e/support/objects/app-admin-settings/page/groups.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/page/groups.ts",
"repo_id": "owncloud",
"token_count": 156
} | 873 |
import { Page } from '@playwright/test'
export class Projects {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
async navigate(): Promise<void> {
await this.#page.locator('//a[@data-nav-name="files-spaces-projects"]').click()
await this.#page.locator('#app-loading-spinner').waitFor({ state: 'detached' })
}
}
| owncloud/web/tests/e2e/support/objects/app-files/page/spaces/projects.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/page/spaces/projects.ts",
"repo_id": "owncloud",
"token_count": 127
} | 874 |
import { Locator, Page } from '@playwright/test'
const closeTextEditorOrViewerButton = '#app-top-bar-close'
const saveTextEditorOrViewerButton = '#app-save-action'
const texEditor = '#text-editor'
const pdfViewer = '#pdf-viewer'
const imageViewer = '.stage'
export const close = (page: Page): Promise<unknown> => {
return Promise.all([
page.waitForNavigation(),
page.locator(closeTextEditorOrViewerButton).click()
])
}
export const save = async (page: Page): Promise<unknown> => {
return await Promise.all([
page.waitForResponse((res) => res.request().method() === 'PUT' && res.status() === 204),
page.locator(saveTextEditorOrViewerButton).click()
])
}
export const fileViewerLocator = ({
page,
fileViewerType
}: {
page: Page
fileViewerType: string
}): Locator => {
switch (fileViewerType) {
case 'text-editor':
return page.locator(texEditor)
case 'pdf-viewer':
return page.locator(pdfViewer)
case 'image-viewer':
return page.locator(imageViewer)
default:
throw new Error(`${fileViewerType} not implemented`)
}
}
| owncloud/web/tests/e2e/support/objects/app-files/utils/editor.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/utils/editor.ts",
"repo_id": "owncloud",
"token_count": 393
} | 875 |
import { Token } from '../types'
export const createdTokenStore = new Map<string, Token>()
export const keycloakTokenStore = new Map<string, Token>()
| owncloud/web/tests/e2e/support/store/token.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/store/token.ts",
"repo_id": "owncloud",
"token_count": 44
} | 876 |
import { CompilerOptions } from '@vue/compiler-sfc'
export const compilerOptions: CompilerOptions = {
whitespace: 'preserve'
}
| owncloud/web/vite.config.common.ts/0 | {
"file_path": "owncloud/web/vite.config.common.ts",
"repo_id": "owncloud",
"token_count": 42
} | 877 |
FROM mattrayner/lamp:latest-2004-php7
LABEL maintainer="8023 - i@8023.moe"
LABEL description="pikachu on php7 with expect @230613"
COPY . /app/
RUN apt-get update -y &&\
apt-get install -y php7.4-dev php-pear expect tcl-dev tcl-expect-dev &&\
ln -s /usr/include/tcl8.6/tcl.h /usr/include/tcl.h &&\
ln -s /usr/include/tcl8.6/tclDecls.h /usr/include/tclDecls.h &&\
ln -s /usr/include/tcl8.6/expect_tcl.h /usr/include/expect_tcl.h &&\
ln -s /usr/include/tcl8.6/tclPlatDecls.h /usr/include/tclPlatDecls.h &&\
pecl channel-update pecl.php.net && pecl install expect &&\
sed -i '/AllowNoPassword/s/false/true/g' /var/www/phpMyAdmin-5.1.1-all-languages/config.inc.php ;\
sed -i '/display_startup_errors/s/Off/On/g' /etc/php/7.4/apache2/php.ini ;\
sed -i '/allow_url_include/s/Off/On/g' /etc/php/7.4/apache2/php.ini ;\
sed -i '/allow_url_fopen/s/Off/On/g' /etc/php/7.4/apache2/php.ini ;\
sed -i '/display_errors/s/Off/On/g' /etc/php/7.4/apache2/php.ini ;\
sed -i '$a extension=expect.so' /etc/php/7.4/apache2/php.ini ;\
sed -i '/DBPW/s/root//g' /app/pkxss/inc/config.inc.php ;\
sed -i '/DBPW/s/root//g' /app/inc/config.inc.php ;\
phpenmod expect && \
apt-get remove -y php7.4-dev tcl-dev tcl-expect-dev &&\
apt-get autoremove -y && apt-get clean -y && rm -rf /var/lib/apt/lists/*
EXPOSE 80
CMD ["/run.sh"] | zhuifengshaonianhanlu/pikachu/Dockerfile/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/Dockerfile",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 664
} | 878 |
<?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 keypress where id=$id";
execute($link, $query);
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>键盘记录结果</title>
<link rel="stylesheet" type="text/css" href="../antxss.css" />
</head>
<body>
<div id="title">
<h1>pikachu Xss 获取键盘记录结果</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>记录</td>
<td>操作</td>
</tr>
<?php
$query="select * from keypress";
$result=mysqli_query($link, $query);
while($data=mysqli_fetch_assoc($result)){
$html=<<<A
<tr>
<td>{$data['id']}</td>
<td>{$data['data']}</td>
<td><a href="pkxss_keypress_result.php?id={$data['id']}">删除</a></td>
</tr>
A;
echo $html;
}
?>
</table>
</div>
</body>
</html> | zhuifengshaonianhanlu/pikachu/pkxss/rkeypress/pkxss_keypress_result.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/pkxss/rkeypress/pkxss_keypress_result.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 702
} | 879 |
<?php
$html=<<<A
<pre>
Good morning,
and in case I don't see ya,
good afternoon, good evening, and good night!
</pre>
A;
?>
| zhuifengshaonianhanlu/pikachu/vul/dir/soup/truman.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/dir/soup/truman.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 51
} | 880 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "findabc.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR.'header.php';
include_once $PIKA_ROOT_DIR.'inc/function.php';
include_once $PIKA_ROOT_DIR.'inc/mysql.inc.php';
include_once $PIKA_ROOT_DIR.'inc/config.inc.php';
$link=connect();
$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);
setcookie('abc[uname]',$_GET['username'],time()+36000);
setcookie('abc[pw]',md5($_GET['password']),time()+36000);
//登录时,生成cookie,10个小时有效期,供其他页面判断
header("location:abc.php");
}else{
$query_username = "select * from member where username='$username'";
$res_user = execute($link,$query_username);
if(mysqli_num_rows($res_user) == 1){
$html.="<p class='notice'>您输入的密码错误</p>";
}else{
$html.="<p class='notice'>您输入的账号错误</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="infoleak.php">敏感信息泄露</a>
</li>
<li class="active">find abc</li>
</ul>
<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="form">
<div class="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">
<!-- <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;?>
</div><!-- 测试账号:lili/123456-->
</div><!-- /.widget-body -->
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/infoleak/findabc.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/infoleak/findabc.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2238
} | 881 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "sqli_header.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();
$is_login_id=check_sqli_login($link);
if(!$is_login_id){
header("location:sqli_header_login.php");
}
// $remoteipadd=escape($link, $_SERVER['REMOTE_ADDR']);
// $useragent=escape($link, $_SERVER['HTTP_USER_AGENT']);
// $httpaccept=escape($link, $_SERVER['HTTP_ACCEPT']);
// $httpreferer=escape($link, $_SERVER['HTTP_REFERER']);
//直接获取前端过来的头信息,没人任何处理,留下安全隐患
$remoteipadd=$_SERVER['REMOTE_ADDR'];
$useragent=$_SERVER['HTTP_USER_AGENT'];
$httpaccept=$_SERVER['HTTP_ACCEPT'];
$remoteport=$_SERVER['REMOTE_PORT'];
//这里把http的头信息存到数据库里面去了,但是存进去之前没有进行转义,导致SQL注入漏洞
$query="insert httpinfo(userid,ipaddress,useragent,httpaccept,remoteport) values('$is_login_id','$remoteipadd','$useragent','$httpaccept','$remoteport')";
$result=execute($link, $query);
if(isset($_GET['logout']) && $_GET['logout'] == 1){
setcookie('ant[uname]','',time()-3600);
setcookie('ant[pw]','',time()-3600);
header("location:sqli_header_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="../sqli.php">sqli</a>
</li>
<li class="active">http头注入</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="这里的问题挺多的,跟http头里面有关的字段都可以测试一下">
点一下提示~
</a>
</div>
<div class="page-content">
<?php
$html=<<<A
<div id="http_main">
<h1>朋友,你好,你的信息已经被记录了:<a href="sqli_header.php?logout=1">点击退出</a></h1>
<p>你的ip地址:$remoteipadd</p>
<p>你的user agent:$useragent</p>
<p>你的http accept:$httpaccept</p>
<p>你的端口(本次连接):tcp$remoteport</p>
</div>
A;
echo $html;
?>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_header/sqli_header.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_header/sqli_header.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1628
} | 882 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "unsafedownload.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="unsafedownload.php">unsafe filedownload</a>
</li>
<li class="active">不安全的文件下载</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="我就说一句,1996年的状元是艾弗森,但是下面这个列表里面kobe排在第一位,你说奇怪不奇怪吧。">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="usd_main" style="width: 600px;">
<h2 class="title" >NBA 1996年 黄金一代</h2>
<p class="mes" style="color: #1d6fa6;">Notice:点击球员名字即可下载头像图片!</p>
<div class="png" style="float: left">
<img src="download/kb.png" /><br />
<a href="execdownload.php?filename=kb.png" >科比.布莱恩特</a>
</div>
<div class="png" style="float: left">
<img src="download/ai.png" /><br />
<a href="execdownload.php?filename=ai.png" >阿伦.艾弗森</a>
</div>
<div class="png" style="float: left">
<img src="download/ns.png" /><br />
<a href="execdownload.php?filename=ns.png" >史蒂夫.纳什</a>
</div>
<div class="png" style="float: left">
<img src="download/rayal.png" /><br />
<a href="execdownload.php?filename=rayal.png" >雷.阿伦</a>
</div>
<div class="png" style="float: left">
<img src="download/mbl.png" /><br />
<a href="execdownload.php?filename=mbl.png" >斯蒂芬.马布里</a>
</div>
<div class="png" style="float: left">
<img src="download/camby.png" /><br />
<a href="execdownload.php?filename=camby.png" >马库斯.坎比</a>
</div>
<div class="png" style="float: left">
<img src="download/pj.png" /><br />
<a href="execdownload.php?filename=pj.png" >斯托贾科维奇</a>
</div>
<div class="png" style="float: left">
<img src="download/bigben.png" /><br />
<a href="execdownload.php?filename=bigben.png" >本.华莱士</a>
</div>
<div class="png" style="float: left">
<img src="download/sks.png" /><br />
<a href="execdownload.php?filename=sks.png" >伊尔戈斯卡斯</a>
</div>
<div class="png" style="float: left">
<img src="download/oldfish.png" /><br />
<a href="execdownload.php?filename=oldfish.png" >德里克.费舍尔</a>
</div>
<div class="png" style="float: left">
<img src="download/smallane.png" /><br />
<a href="execdownload.php?filename=smallane.png" >杰梅因.奥尼尔</a>
</div>
<div class="png" style="float: left">
<img src="download/lmx.png" /><br />
<a href="execdownload.php?filename=lmx.png" >阿卜杜.拉希姆</a>
</div>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/unsafedownload/down_nba.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/unsafedownload/down_nba.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2632
} | 883 |
<?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 = "clientcheck.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.php';
include_once $PIKA_ROOT_DIR.'inc/uploadfunction.php';
$html='';
if(isset($_POST['submit'])){
$type=array('jpg','jpeg','png');//指定类型
$mime=array('image/jpg','image/jpeg','image/png');
$save_path='uploads'.date('/Y/m/d/');//根据当天日期生成一个文件夹
$upload=upload('uploadfile','512000',$type,$mime,$save_path);//调用函数
if($upload['return']){
$html.="<p class='notice'>文件上传成功</p><p class='notice'>文件保存的路径为:{$upload['save_path']}</p>";
}else{
$html.="<p class=notice>{$upload['error']}</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="upload.php">unsafe upfileupload</a>
</li>
<li class="active">getimagesize()</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="getimagesize了解一下">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="usu_main">
<p class="title">这里只允许上传图片,不要乱搞!</p>
<form class="upload" method="post" enctype="multipart/form-data" action="">
<input class="uploadfile" type="file" name="uploadfile" /><br />
<input class="sub" 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/unsafeupload/getimagesize.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/unsafeupload/getimagesize.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1386
} | 884 |
<?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 = "xss_stored.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/mysql.inc.php";
$link=connect();
$html='';
if(array_key_exists("message",$_POST) && $_POST['message']!=null){
$message=escape($link, $_POST['message']);
$query="insert into message(content,time) values('$message',now())";
$result=execute($link, $query);
if(mysqli_affected_rows($link)!=1){
$html.="<p>数据库出现异常,提交失败!</p>";
}
}
if(array_key_exists('id', $_GET) && is_numeric($_GET['id'])){
//彩蛋:虽然这是个存储型xss的页面,但这里有个delete的sql注入
$query="delete from message where id={$_GET['id']}";
$result=execute($link, $query);
if(mysqli_affected_rows($link)==1){
echo "<script type='text/javascript'>document.location.href='xss_stored.php'</script>";
}else{
$html.="<p id='op_notice'>删除失败,请重试并检查数据库是否还好!</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="xss.php">xss</a>
</li>
<li class="active">存储型xss</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="xsss_main">
<p class="xsss_title">我是一个留言板:</p>
<form method="post">
<textarea class="xsss_in" name="message"></textarea><br />
<input class="xsss_submit" type="submit" name="submit" value="submit" />
</form>
<div id="show_message">
<br />
<br />
<p class="line">留言列表:</p>
<?php echo $html;
$query="select * from message";
$result=execute($link, $query);
while($data=mysqli_fetch_assoc($result)){
echo "<p class='con'>{$data['content']}</p><a href='xss_stored.php?id={$data['id']}'>删除</a>";
}
echo $html;
?>
</div>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR.'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/xss/xss_stored.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/xss/xss_stored.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1852
} | 885 |
<!doctype html>
<html>
<head>
<title>8th Wall Web: Art Gallery</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<!-- We've included a slightly modified version of A-Frame, which fixes some polish concerns -->
<script src="//cdn.8thwall.com/web/aframe/8frame-1.3.0.min.js"></script>
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<!-- Landing Pages - see https://www.8thwall.com/docs/web/#landing-pages -->
<script src='//cdn.8thwall.com/web/landing-page/landing-page.js'></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXX"></script>
<!-- client code -->
<script src="index.js"></script>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div id="container" class="collapsed">
<div class="outer">
<div id="closeButton" onclick="document.getElementById('container').classList.add('collapsed')">close</div>
</div>
<div id="contents"></div>
<div class="outer">Article provided by Wikipedia</div>
</div>
<a-scene
xrextras-generate-image-targets="primitive: artgallery-frame"
landing-page
xrextras-loading
xrextras-runtime-error
renderer="antialias: true; colorManagement: true;"
xrweb="disableWorldTracking: true">
<a-assets>
<a-asset-item id="frame-model" src="frame.glb"></a-asset-item>
</a-assets>
<a-camera
id="camera"
position="0 4 10"
raycaster="objects: .cantap"
cursor="fuse:false; rayOrigin:mouse;">
</a-camera>
<a-light type="ambient" intensity="1.3"></a-light>
<a-light type="directional" intensity="3" position="1.5 2.5 0.6"></a-light>
</a-scene>
</body>
</html>
| 8thwall/web/examples/aframe/artgallery/index.html/0 | {
"file_path": "8thwall/web/examples/aframe/artgallery/index.html",
"repo_id": "8thwall",
"token_count": 776
} | 0 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>8th Wall Web: Toss an Object</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.1.0.min.js"></script>
<script src="//cdn.8thwall.com/web/aframe/aframe-physics-system-4.0.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 src="toss-object.js"></script>
</head>
<body>
<!-- We must add the shoot-tomato component to the scene so it has an effect, as well as the physics component -->
<a-scene
shoot-tomato
physics="iterations: 1"
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="tomatoModel" src="tomato.glb"></a-asset-item>
<a-asset-item preload="auto" class="a-sound" id="splatSrc" src="splat.m4a" response-type="arraybuffer"></a-asset-item>
</a-assets>
<a-camera
id="camera"
position="0 4 4">
<a-sound id="splat" src="#splatSrc"></a-sound>
</a-camera>
<a-entity
light="
type: directional;
intensity: 0.8;
castShadow: true;
shadowMapHeight:2048;
shadowMapWidth:2048;
shadowCameraTop: 20;
shadowCameraBottom: -20;
shadowCameraRight: 20;
shadowCameraLeft: -20;
target: #camera"
xrextras-attach="target: camera; offset: 0 15 0"
position="1 4.3 2.5"
shadow>
</a-entity>
<a-light type="ambient" intensity="0.5"></a-light>
<!-- Adding the static-body component allows the ground to be collided with -->
<a-box
id="ground"
static-body
scale="1000 2 1000"
position="0 -1 0"
material="shader: shadow; transparent: true; opacity: 0.4"
shadow>
</a-box>
</a-scene>
</body>
</html>
| 8thwall/web/examples/aframe/tossobject/index.html/0 | {
"file_path": "8thwall/web/examples/aframe/tossobject/index.html",
"repo_id": "8thwall",
"token_count": 1129
} | 1 |
// Copyright (c) 2018 8th Wall, Inc.
// Define a custom pipeline module. This module scans the camera feed for qr codes, and makes the
// result available to other modules in onUpdate. It requires that the CameraPixelArray module is
// installed and configured to provide a luminance (black and white) image.
const qrprocessPipelineModule = () => {
return {
name: 'qrprocess',
onProcessCpu: ({processGpuResult}) => {
// Check whether there is any data ready to process.
if (!processGpuResult.camerapixelarray || !processGpuResult.camerapixelarray.pixels) {
return {found: false}
}
try {
// Set input variables on the global qrcode object before calling qrcode.process().
const {rows, cols} = processGpuResult.camerapixelarray
window.qrcode.width = cols
window.qrcode.height = rows
window.qrcode.grayscale = () => { return processGpuResult.camerapixelarray.pixels }
const res = window.qrcode.process() // Scan the image for a QR code.
res.points = res.points.map(
({x: x_, y: y_}) => { return {x: x_ / (cols - 1), y: y_ / (rows - 1)}})
return res
} catch (e) {
return {found: false} // jsqrcode throws errors when qr codes are not found in an image.
}
},
}
}
// Define a custom pipeline module. This module updates UI elements with the result of the QR code
// scanning, and navigates to the found url on any tap to the screen.
const qrdisplayPipelineModule = () => {
const url = document.getElementById('url')
const canvas2d_ = document.getElementById('overlay2d')
const ctx_ = canvas2d_.getContext('2d')
let lastSeen = 0
let canvas_
// if the window is touched anywhere, navigate to the URL that was detected.
window.addEventListener('touchstart', () => {
if (!url.href || !url.href.startsWith('http')) { return }
XR8.pause()
url.innerHTML = `Navigating to ${url.href}`
window.location.href = url.href
})
// Keep the 2d drawing canvas in sync with the camera feed.
const onCanvasSizeChange = () => {
canvas2d_.width = canvas_.clientWidth
canvas2d_.height = canvas_.clientHeight
ctx_.scale(canvas_.width / canvas_.clientWidth, canvas_.height / canvas_.clientHeight)
}
const drawCircle = (pt) => {
ctx_.beginPath();
ctx_.arc(pt.x, pt.y, 9 /* radius */, 0, 2 * Math.PI, false);
ctx_.fillStyle = '#AD50FF'
ctx_.fill();
ctx_.strokeStyle = '#7611B7'
ctx_.lineWidth = 2
ctx_.stroke();
}
const mapToTextureViewport = (pt, vp) => {
return { x: pt.x * vp.width + vp.offsetX, y: pt.y * vp.height + vp.offsetY}
}
return {
name: 'qrdisplay',
onStart: ({canvas}) => {
url.style.visibility = 'visible' // Show the card that displays the url.
canvas_ = canvas
},
onUpdate: ({processGpuResult, processCpuResult}) => {
if (!processCpuResult.qrprocess) { return }
canvas2d_.width = canvas2d_.width; // Clears canvas
const {found, foundText, points} = processCpuResult.qrprocess
const {viewport} = processGpuResult.gltexturerenderer
// Toggle display text based on whether a qrcode result was found.
if (found) {
url.innerHTML = `<u>${foundText}</u>`
url.href = foundText
lastSeen = Date.now()
points.forEach((pt) => { drawCircle(mapToTextureViewport(pt, viewport)) })
} else if (Date.now() - lastSeen > 5000) {
url.innerHTML = 'Scanning for QR Code...'
url.href = ''
}
},
onCanvasSizeChange,
}
}
const onxrloaded = () => {
XR8.addCameraPipelineModules([ // Add camera pipeline modules.
// Existing pipeline modules.
XR8.CameraPixelArray.pipelineModule({ luminance: true, maxDimension: 640 }), // Provides pixels.
XR8.GlTextureRenderer.pipelineModule(), // Draws the camera feed.
XRExtras.AlmostThere.pipelineModule(), // Detects unsupported browsers and gives hints.
XRExtras.FullWindowCanvas.pipelineModule(), // Modifies the canvas to fill the window.
XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup.
XRExtras.RuntimeError.pipelineModule(), // Shows an error image on runtime error.
// Custom pipeline modules.
qrprocessPipelineModule(), // Scans the image for QR Codes
qrdisplayPipelineModule(), // Displays the result of QR Code scanning.
])
// Request camera permissions and run the camera.
XR8.run({canvas: document.getElementById('camerafeed')})
}
// Show loading screen before the full XR library has been loaded.
const load = () => { XRExtras.Loading.showLoading({onxrloaded}) }
window.onload = () => { window.XRExtras ? load() : window.addEventListener('xrextrasloaded', load) }
| 8thwall/web/examples/camerapipeline/qrcode/index.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/index.js",
"repo_id": "8thwall",
"token_count": 1776
} | 2 |
/*
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.
*/
var GridSampler = {};
GridSampler.checkAndNudgePoints=function( image, points)
{
var width = qrcode.width;
var height = qrcode.height;
// Check and nudge points from start until we see some that are OK:
var nudged = true;
for (var offset = 0; offset < points.length && nudged; offset += 2)
{
var x = Math.floor (points[offset]);
var y = Math.floor( points[offset + 1]);
if (x < - 1 || x > width || y < - 1 || y > height)
{
throw "Error.checkAndNudgePoints ";
}
nudged = false;
if (x == - 1)
{
points[offset] = 0.0;
nudged = true;
}
else if (x == width)
{
points[offset] = width - 1;
nudged = true;
}
if (y == - 1)
{
points[offset + 1] = 0.0;
nudged = true;
}
else if (y == height)
{
points[offset + 1] = height - 1;
nudged = true;
}
}
// Check and nudge points from end:
nudged = true;
for (var offset = points.length - 2; offset >= 0 && nudged; offset -= 2)
{
var x = Math.floor( points[offset]);
var y = Math.floor( points[offset + 1]);
if (x < - 1 || x > width || y < - 1 || y > height)
{
throw "Error.checkAndNudgePoints ";
}
nudged = false;
if (x == - 1)
{
points[offset] = 0.0;
nudged = true;
}
else if (x == width)
{
points[offset] = width - 1;
nudged = true;
}
if (y == - 1)
{
points[offset + 1] = 0.0;
nudged = true;
}
else if (y == height)
{
points[offset + 1] = height - 1;
nudged = true;
}
}
}
GridSampler.sampleGrid3=function( image, dimension, transform)
{
var bits = new BitMatrix(dimension);
var points = new Array(dimension << 1);
for (var y = 0; y < dimension; y++)
{
var max = points.length;
var iValue = y + 0.5;
for (var x = 0; x < max; x += 2)
{
points[x] = (x >> 1) + 0.5;
points[x + 1] = iValue;
}
transform.transformPoints1(points);
// Quick check to see if points transformed to something inside the image;
// sufficient to check the endpoints
GridSampler.checkAndNudgePoints(image, points);
try
{
for (var x = 0; x < max; x += 2)
{
//var xpoint = (Math.floor( points[x]) * 4) + (Math.floor( points[x + 1]) * qrcode.width * 4);
var bit = image[Math.floor( points[x])+ qrcode.width* Math.floor( points[x + 1])];
//qrcode.imagedata.data[xpoint] = bit?255:0;
//qrcode.imagedata.data[xpoint+1] = bit?255:0;
//qrcode.imagedata.data[xpoint+2] = 0;
//qrcode.imagedata.data[xpoint+3] = 255;
//bits[x >> 1][ y]=bit;
if(bit)
bits.set_Renamed(x >> 1, y);
}
}
catch ( aioobe)
{
// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
// transform gets "twisted" such that it maps a straight line of points to a set of points
// whose endpoints are in bounds, but others are not. There is probably some mathematical
// way to detect this about the transformation that I don't know yet.
// This results in an ugly runtime exception despite our clever checks above -- can't have
// that. We could check each point's coordinates but that feels duplicative. We settle for
// catching and wrapping ArrayIndexOutOfBoundsException.
throw "Error.checkAndNudgePoints";
}
}
return bits;
}
GridSampler.sampleGridx=function( image, dimension, p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY)
{
var transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY);
return GridSampler.sampleGrid3(image, dimension, transform);
} | 8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/grid.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/grid.js",
"repo_id": "8thwall",
"token_count": 1998
} | 3 |
# 8th Wall Web Examples - three.js - Flyer
This example uses image targets to display information about jellyfish on a flyer.


[Try the live demo here](https://templates.8thwall.app/flyer-threejs)
## Uploading to Console
To link the image targets to your app key, you will need to upload (and enable autoload) each image to your project in the 8th Wall Console at www.8thwall.com.
| 8thwall/web/examples/threejs/flyer/README.md/0 | {
"file_path": "8thwall/web/examples/threejs/flyer/README.md",
"repo_id": "8thwall",
"token_count": 144
} | 4 |
.hidden {
display: none;
}
| 8thwall/web/gettingstarted/aframe-imagetarget/index.css/0 | {
"file_path": "8thwall/web/gettingstarted/aframe-imagetarget/index.css",
"repo_id": "8thwall",
"token_count": 12
} | 5 |
.hidden {
display: none;
}
| 8thwall/web/gettingstarted/threejs-imagetarget/index.css/0 | {
"file_path": "8thwall/web/gettingstarted/threejs-imagetarget/index.css",
"repo_id": "8thwall",
"token_count": 12
} | 6 |
# XR Extras
This library provides modules that extend the
[Camera Pipeline Module framework](https://docs.8thwall.com/web/#camerapipelinemodule) in
[8th Wall XR](https://8thwall.com/products-web.html) to handle common application needs.
The library is served at
[//cdn.8thwall.com/web/xrextras/xrextras.js](https://cdn.8thwall.com/web/xrextras/xrextras.js), or
can be built from this repository by running
```bash
$ npm install
$ npm run build
```
## Hello World
### Native JS
index.html:
```html
<html>
<head>
<title>XR Extras: Camera Pipeline</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<!-- XR Extras - provides utilities like load screen, error handling, and gesture control helpers.
See https://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>
<!-- 8th Wall Engine - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXXXXX"></script>
<script src="index.js"></script>
</head>
<body>
<canvas id="camerafeed"></canvas>
</body>
</html>
```
index.js:
```javascript
const onxrloaded = () => {
XR8.addCameraPipelineModules([ // Add camera pipeline modules.
// Existing pipeline modules.
XR8.GlTextureRenderer.pipelineModule(), // Draws the camera feed.
window.LandingPage.pipelineModule(), // Detects unsupported browsers and gives hints.
XRExtras.FullWindowCanvas.pipelineModule(), // Modifies the canvas to fill the window.
XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup.
XRExtras.RuntimeError.pipelineModule(), // Shows an error image on runtime error.
])
XR8.run({canvas: document.getElementById('camerafeed')}) // Request permissions and run camera.
}
window.XR8 ? onxrloaded() : window.addEventListener('xrloaded', onxrloaded)
```
### AFrame
index.html:
```html
<html>
<head>
<title>XRExtras: A-FRAME</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>
<!-- XR Extras - provides utilities like load screen, error handling, and gesture control helpers.
See https://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>
<!-- 8th Wall Engine - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXXXXX"></script>
</head>
<body>
<!-- Add the 'xrweb' attribute to your scene to make it an 8th Wall Web A-FRAME scene. -->
<a-scene
xrweb
landing-pages
xrextras-loading
xrextras-runtime-error
xrextras-tap-recenter>
<a-camera position="0 8 8"></a-camera>
<a-entity
light="type: directional; castShadow: true; intensity: 0.8; shadowCameraTop: 7;
shadowMapHeight: 1024; shadowMapWidth: 1024;"
position="1 4.3 2.5">
</a-entity>
<a-entity
light="type: directional; castShadow: false; intensity: 0.5;" position="-0.8 3 1.85">
</a-entity>
<a-light type="ambient" intensity="1"></a-light>
<a-box
position="-1.7 0.5 -2" rotation="0 45 0" shadow
material="roughness: 0.8; metalness: 0.2; color: #00EDAF;">
</a-box>
<a-sphere
position="-1.175 1.25 -5.2" radius="1.25" shadow
material="roughness: 0.8; metalness: 0.2; color: #DD0065;">
</a-sphere>
<a-cylinder
position="2 0.75 -1.85" radius="0.5" height="1.5" shadow
material="roughness: 0.8; metalness: 0.2; color: #FCEE21;">
</a-cylinder>
<a-circle position="0 0 -4" rotation="-90 0 0" radius="4" shadow
material="roughness: 0.8; metalness: 0.5; color: #AD50FF">
</a-circle>
</a-scene>
</body>
</html>
```
## API
### Pipeline Modules
Quick Reference:
```javascript
XR8.addCameraPipelineModules([ // Add camera pipeline modules.
// Existing pipeline modules.
XR8.GlTextureRenderer.pipelineModule(), // Draws the camera feed.
window.LandingPage.pipelineModule(), // Detects unsupported browsers and gives hints.
XRExtras.FullWindowCanvas.pipelineModule(), // Modifies the canvas to fill the window.
XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup.
XRExtras.RuntimeError.pipelineModule(), // Shows an error image on runtime error.
XRExtras.PwaInstaller.pipelineModule(), // Displays a prompt to add to home screen.
])
```
Pipeline Modules:
* LandingPage.pipelineModule(): Detects if the user is not on a supported device or browser, and
provides helpful information for how to view the XR experience.
* FullWindowCanvas.pipelineModule(): Makes sure that the camera display canvas fills the full
browser window across device orientation changes, etc.
* Loading.pipelineModule(): Displays a loading overlay and camera permissions prompt while
libraries are loading, and while the camera is starting up.
* RuntimeError.pipelineModule(): Shows an error image when an error occurs at runtime.
* PwaInstaller.pipelineModule(): Displays a prompt to add to home screen.
### AFrame Components
Quick Reference:
```html
<a-scene
xrweb
landing-pages
xrextras-loading
xrextras-runtime-error
xrextras-tap-recenter>
```
Javascript Functions:
* XRExtras.AFrame.registerXrExtrasComponents(): Registers the XR Extras AFrame components if they
aren't already registered. If AFrame is loaded befor XR Extras, then there is no need to call this
method. In the case that AFrame is loaded late and you need to explicitly register the components,
you can call this method.
AFrame Components:
* landing-pages: Detects if the user is not on a supported device or browser, and provides
helpful information for how to view the XR experience.
* xrextras-loading: Displays a loading overlay and camera permissions prompt while the scene and
libraries are loading, and while the camera is starting up.
* xrextras-runtime-error: Hides the scene and shows an error image when an error occurs at runtime.
* xrextras-tap-recenter: Calls 'XR.recenter()' when the AFrame scene is tapped.
### Other
Fonts: Provides common .css for fonts used by various modules.
DebugWebViews: Provides utilities for debugging javascript while it runs in browsers embedded in
applications.
Quick Reference:
```html
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<script>
const screenlog = () => {
window.XRExtras.DebugWebViews.enableLogToScreen()
console.log('screenlog enabled')
}
window.XRExtras ? screenlog() : window.addEventListener('xrextrasloaded', screenlog)
</script>
```
| 8thwall/web/xrextras/README.md/0 | {
"file_path": "8thwall/web/xrextras/README.md",
"repo_id": "8thwall",
"token_count": 2647
} | 7 |
// Get a promise that resolves when an event with the given name has been dispacted to the window.
const waitEventPromise = eventname => new Promise(resolve => window.addEventListener(eventname, resolve, {once: true}))
// If XR and XRExtras aren't loaded, wait for them.
const ensureXrAndExtras = () => {
const eventnames = []
window.XR8 || eventnames.push('xrloaded')
window.XRExtras || eventnames.push('xrextrasloaded')
return Promise.all(eventnames.map(waitEventPromise))
}
export {
ensureXrAndExtras,
}
| 8thwall/web/xrextras/src/aframe/ensure.js/0 | {
"file_path": "8thwall/web/xrextras/src/aframe/ensure.js",
"repo_id": "8thwall",
"token_count": 164
} | 8 |
/* globals XR8 */
const currentConfig = {
enableEndCard: true,
footerImageUrl: 'https://cdn.8thwall.com/web/img/almostthere/v2/poweredby-horiz-white-4.svg',
}
const internalConfig = {}
let waitingOnXr = false
let loadedWatermarkUrl
const updateWatermarkImage = () => {
const newImageUrl = internalConfig.watermarkImageUrl
if (newImageUrl === loadedWatermarkUrl) {
return
}
loadedWatermarkUrl = newImageUrl
if (!loadedWatermarkUrl) {
internalConfig.watermarkImage = null
return
}
const img = document.createElement('img')
img.onload = () => {
internalConfig.watermarkImage = img
}
img.onerror = () => {
console.error(`Failed to load image from ${img.src}`)
internalConfig.watermarkImage = null
}
img.setAttribute('crossorigin', 'anonymous')
img.setAttribute('src', loadedWatermarkUrl)
}
const updateConfig = () => {
XR8.MediaRecorder.configure(currentConfig)
}
const internalKeys = new Set([
'watermarkImageUrl', 'watermarkMaxWidth', 'watermarkMaxHeight', 'watermarkLocation',
'fileNamePrefix', 'onProcessFrame',
])
const configure = (config = {}) => {
Object.keys(config).forEach((key) => {
const value = config[key]
if (value === undefined) {
return
}
if (internalKeys.has(key)) {
internalConfig[key] = value
} else {
currentConfig[key] = value
}
})
updateWatermarkImage()
if (window.XR8) {
updateConfig()
} else if (!waitingOnXr) {
waitingOnXr = true
window.addEventListener('xrloaded', updateConfig, {once: true})
}
}
const getConfig = () => internalConfig
export {
configure,
getConfig,
}
| 8thwall/web/xrextras/src/mediarecorder/capture-config.js/0 | {
"file_path": "8thwall/web/xrextras/src/mediarecorder/capture-config.js",
"repo_id": "8thwall",
"token_count": 582
} | 9 |
/* globals XR8 */
import '../fonts/fonts.css'
import './pwa-installer-module.css'
import {MILLISECONDS_PER_SECOND, MILLISECONDS_PER_DAY} from './time'
import html from './pwa-installer-module.html'
import iosActionSvg from './ios-action-icon-svg.html'
const NUM_VISITS_BEFORE_INSTALL_PROMPT = 2
const PROMPT_DISMISSAL_DELAY_MS = MILLISECONDS_PER_DAY * 90
const LAST_INSTALL_DISMISS_TIME_KEY = 'LAST_INSTALL_DISMISS_TIME_KEY'
const NUM_VISITS_KEY = 'NUM_VISITS_KEY'
const DEFAULT_INSTALL_TITLE = 'Add to your home screen'
const DEFAULT_INSTALL_SUBTITLE = 'for easy access.'
const DEFAULT_INSTALL_BUTTON_TEXT = 'Install'
const DEFAULT_IOS_INSTALL_TEXT = 'Tap $ACTION_ICON and then "Add to Homescreen"'
let pwaInstallerModule_ = null
let installEvent_ = null
const lastDismissalKey = () => `${LAST_INSTALL_DISMISS_TIME_KEY}/${getAppKey()}`
const numVisitsKey = () => `${NUM_VISITS_KEY}/${getAppKey()}`
const getXrWebScript = () => [].find.call(document.scripts, s => /xrweb(\?.*)?$/.test(s.src))
const getAppKey = () => {
try {
return new URL(getXrWebScript().src).searchParams.get('appKey')
} catch (e) {
return ''
}
}
const localStorageGetItem = (key, defaultValue = null) => {
try {
return localStorage.getItem(key) || defaultValue
} catch (e) {
return defaultValue
}
}
const localStorageSetItem = (key, value) => {
try {
localStorage.setItem(key, value)
} catch (e) {
// No-op.
}
}
const recordVisit = () => {
const key = numVisitsKey()
const numVisits = parseInt(localStorageGetItem(key, '0'), 10)
localStorageSetItem(key, (numVisits + 1).toString())
}
const recordInstallPromptDismissed = () => {
localStorageSetItem(lastDismissalKey(), new Date().getTime().toString())
}
const getDefaultIconSrc = () => (
(document.querySelector('meta[name="8thwall:pwa_icon"]') || {content: ''}).content
)
const getDefaultPwaName = () => (
(document.querySelector('meta[name="8thwall:pwa_name"]') || {content: ''}).content
)
const create = () => {
const preferredName = () => getDefaultPwaName()
const preferredIconSrc = () => getDefaultIconSrc()
const preferredInstallTitle = () => DEFAULT_INSTALL_TITLE
const preferredInstallSubtitle = () => DEFAULT_INSTALL_SUBTITLE
const preferredInstallButtonText = () => DEFAULT_INSTALL_BUTTON_TEXT
const preferredIosInstallText = () => DEFAULT_IOS_INSTALL_TEXT
const promptConfig_ = {
delayAfterDismissalMillis: PROMPT_DISMISSAL_DELAY_MS,
minNumVisits: NUM_VISITS_BEFORE_INSTALL_PROMPT,
}
const displayConfig_ = {
preferredName,
preferredIconSrc,
preferredInstallTitle,
preferredInstallSubtitle,
preferredInstallButtonText,
preferredIosInstallText,
}
let numUpdates_ = 0
let waitingOnReality_ = true
let rootNode_ = null
let pendingDisplayPromptId_ = null
let displayAllowed_ = false
let runConfig_ = null
// Overridable functions
let shouldDisplayInstallPrompt_ = shouldDisplayInstallPrompt
let displayInstallPrompt_ = displayInstallPrompt
let hideInstallPrompt_ = hideInstallPrompt
function pipelineModule() {
return {
name: 'pwa-installer',
onBeforeRun: (args) => {
runConfig_ = args && args.config
setDisplayAllowed(false)
},
onAttach: () => {
numUpdates_ = 0
waitingOnReality_ = true
},
onUpdate: () => {
if (!waitingOnReality_) {
return
}
if (numUpdates_ < 5) {
++numUpdates_
} else {
waitingOnReality_ = false
setDisplayAllowed(true)
}
},
onDetach: () => {
setDisplayAllowed(false)
},
}
}
function displayInstallPrompt(displayConfig, onInstalled, onDismissed) {
const e = document.createElement('template')
e.innerHTML = html.trim()
rootNode_ = e.content.firstChild
// Display appropriate install action.
const installActionNode = XR8.XrDevice.deviceEstimate().os !== 'iOS'
? rootNode_.querySelector('#android-install-action')
: rootNode_.querySelector('#ios-install-action')
installActionNode.classList.remove('hidden')
// Add the PWA icon preview source.
const iconNode = rootNode_.querySelector('#pwa-icon-preview')
if (iconNode) {
iconNode.src = displayConfig.iconSrc
}
// Add the PWA name.
const pwaNameNode = rootNode_.querySelector('#pwa-name')
if (pwaNameNode) {
pwaNameNode.innerHTML = displayConfig.name
}
const installTitleNode = rootNode_.querySelector('#install-title')
if (installTitleNode) {
installTitleNode.innerHTML = displayConfig.installTitle
}
const installSubtitle = rootNode_.querySelector('#install-subtitle')
if (installSubtitle) {
installSubtitle.innerHTML = displayConfig.installSubtitle
}
// Add close button click listener.
const closeButtonNode = rootNode_.querySelector('#close-button')
if (closeButtonNode) {
closeButtonNode.onclick = onDismissed
}
// Add install button text and click listener.
const installButtonNode = rootNode_.querySelector('#android-install-action')
if (installButtonNode) {
installButtonNode.innerHTML = displayConfig.installButtonText
installButtonNode.onclick = () => {
if (!installEvent_) {
console.error('Attempting install app without `beforeinstallprompt` event')
hideInstallPrompt_()
return Promise.resolve()
}
installEvent_.prompt()
return installEvent_.userChoice.then((choice) => {
if (choice.outcome === 'accepted') {
onInstalled()
} else {
onDismissed()
}
installEvent_ = null
})
}
}
// Add iOS install action text.
const iosInstallTextNode = rootNode_.querySelector('#ios-install-action')
if (iosInstallTextNode) {
const iosInstallText =
displayConfig.iosInstallText && displayConfig.iosInstallText.replace('$ACTION_ICON', iosActionSvg)
iosInstallTextNode.innerHTML = iosInstallText
}
document.getElementsByTagName('body')[0].appendChild(rootNode_)
installPromptShown = true
}
function hideInstallPrompt() {
if (!rootNode_) {
return
}
document.getElementsByTagName('body')[0].removeChild(rootNode_)
rootNode_ = null
}
function shouldDisplayInstallPrompt(promptConfig, lastDismissalMillis, numVisits) {
// Incompatible devices shouldn't have the option to install.
if (!XR8.XrDevice.isDeviceBrowserCompatible(runConfig_)) {
return false
}
const requiresPromptEvent = XR8.XrDevice.deviceEstimate().os !== 'iOS'
if (requiresPromptEvent && !installEvent_) {
return false
}
// Wait the appropriate amount of time before displaying the prompt again.
const currentTimeMillis = new Date().getTime()
const delayTimeMillis = promptConfig.delayAfterDismissalMillis
if (lastDismissalMillis && (currentTimeMillis < (lastDismissalMillis + delayTimeMillis))) {
return false
}
// Ensure the user has visited the page enough times before displaying the prompt.
if (numVisits < promptConfig.minNumVisits) {
return false
}
// Don't display the install prompt if the app is already running through a PWA.
const url = new URL(location.href)
const mode = url.searchParams.get('mode')
if (mode === 'pwa' || window.matchMedia('(display-mode: standalone)').matches) {
return false
}
return true
}
function onInstalled() {
hideInstallPrompt_()
}
function onDismissed() {
recordInstallPromptDismissed()
hideInstallPrompt_()
}
function displayOrSchedulePrompt() {
if (pendingDisplayPromptId_) {
clearTimeout(pendingDisplayPromptId_)
pendingDisplayPromptId_ = null
}
const numVisits = parseInt(localStorageGetItem(numVisitsKey(), '0'), 10)
const lastDismissalMillis = parseInt(localStorageGetItem(lastDismissalKey(), '0'), 10)
if (displayAllowed_ && shouldDisplayInstallPrompt_(promptConfig_, lastDismissalMillis, numVisits)) {
const config = {
name: displayConfig_.preferredName(),
iconSrc: displayConfig_.preferredIconSrc(),
installTitle: displayConfig_.preferredInstallTitle(),
installSubtitle: displayConfig_.preferredInstallSubtitle(),
installButtonText: displayConfig_.preferredInstallButtonText(),
iosInstallText: displayConfig_.preferredIosInstallText(),
}
displayInstallPrompt_(config, onInstalled, onDismissed)
} else if (displayInstallPrompt_) {
pendingDisplayPromptId_ = setTimeout(displayOrSchedulePrompt, MILLISECONDS_PER_SECOND * 5)
} else {
hideInstallPrompt_()
}
}
function setDisplayAllowed(displayAllowed) {
displayAllowed_ = displayAllowed
displayOrSchedulePrompt()
}
const configure = (args) => {
const {
promptConfig,
displayConfig,
shouldDisplayInstallPrompt,
displayInstallPrompt,
hideInstallPrompt,
} = args
if (displayConfig) {
if (displayConfig.name) {
displayConfig_.preferredName = () => displayConfig.name
}
if (displayConfig.iconSrc) {
displayConfig_.preferredIconSrc = () => displayConfig.iconSrc
}
if (displayConfig.installButtonText) {
displayConfig_.preferredInstallButtonText = () => displayConfig.installButtonText
}
if (displayConfig.iosInstallText) {
displayConfig_.preferredIosInstallText = () => displayConfig.iosInstallText
}
if (displayConfig.installTitle) {
displayConfig_.preferredInstallTitle = () => displayConfig.installTitle
}
if (displayConfig.installSubtitle) {
displayConfig_.preferredInstallSubtitle = () => displayConfig.installSubtitle
}
}
if (promptConfig) {
Object.assign(promptConfig_, promptConfig)
}
if (shouldDisplayInstallPrompt) {
shouldDisplayInstallPrompt_ = shouldDisplayInstallPrompt
}
if (displayInstallPrompt) {
displayInstallPrompt_ = displayInstallPrompt
}
if (hideInstallPrompt) {
hideInstallPrompt_ = hideInstallPrompt
}
}
function hideInstallPrompt() {
if (!rootNode_) {
return
}
document.getElementsByTagName('body')[0].removeChild(rootNode_)
rootNode_ = null
}
return {
configure,
pipelineModule,
setDisplayAllowed,
}
}
const PwaInstallerFactory = () => {
if (!pwaInstallerModule_) {
pwaInstallerModule_ = create()
}
return pwaInstallerModule_
}
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault()
installEvent_ = e
})
window.addEventListener('load', (event) => {
recordVisit()
})
export {
PwaInstallerFactory,
}
| 8thwall/web/xrextras/src/pwainstallermodule/pwa-installer-module.js/0 | {
"file_path": "8thwall/web/xrextras/src/pwainstallermodule/pwa-installer-module.js",
"repo_id": "8thwall",
"token_count": 4060
} | 10 |
## 1、文本元素
CSS 的文本属性设置:
### 1.1、属性
```css
font-size: 50px; /*文字大小*/
font-weight: bold; /*文字粗细 */
font-family: "微软雅黑"; /*文本的字体*/
font-style: normal | italic; /*normal:默认值 italic:斜体*/
line-height: 50px /*行高*/
```
### 1.2、连写方式
```css
/* 格式:font: font-style font-weight font-size/line-height font-family; */
font: italic bold 50px/40px "微软雅黑";
```
> 注意:font:后边写属性的值。一定按照书写顺序。
> **PS:文本属性连写中,文字大小和字体为必写项。**
### 1.3、字体属性
- 直接写中文名称
```css
font-family: "微软雅黑";
```
- 写字体的英文名称
```css
font-family: "Microsoft Yahei";
```
## 2、标签分类
### 2.1、块元素
```css
/*典型代表:*/
div, h1-h6, p, ul, li, table
```
> **特点:**
> 1.独占一行;
> 2.可以设置宽高;
> 3.在嵌套时,子块元素**宽度**(没有定义情况下)和父块元素**宽度**默认一致。
### 2.2、行内元素
```css
/*典型代表*/
a,span
```
> **特点:**
> 1.在一行上显示;
> 2.不能直接设置宽高(需要转行内块);
> 3.元素的宽和高就是内容撑开的宽高。
### 2.3、行内块元素
```css
/*典型代表*/
input, img, textarea, select, button
```
> **特点:**
> 1.不独占一行(在一行上显示)
> 2.可以设置宽高。
### 2.4、三者相互转换
- 块元素转行内元素
```css
display:inline;
```
- 行内元素转块元素
```css
display:block;
```
- 块和行内元素转行内块元素
```css
display:inline-block;
```
## 3、CSS三大特性
### 3.1、层叠性
当多个样式作用于同一个(同一类)标签时,样式发生了冲突,总是执行后边的代码(后边代码层叠前边的代码)。**和标签中书写的选择器顺序无关。**

### 3.2、继承性
**继承性发生的前提是包含(嵌套关系)**
- 文字颜色可以继承
- 文字大小可以继承
- 字体可以继续
- 字体粗细可以继承
- 文字风格可以继承
- 行高可以继承
**总结:文字的所有属性都可以继承。**
**特殊情况:**
1. h系列不会继承文字大小。
> 实际上:h1显示的是你设置的 font-size * 2;
> h2显示的是:你设置的 font-size * 1.5
> .......
2. a链接标签不能继承文字颜色(继承了但是不显示,链接标签默认是蓝色)
### 3.3、优先级
```html
默认样式 < 标签选择器 < 类选择器 < id选择器 < 行内样式< !important
权重: 0 1 10 100 1000 1000以上
```
> **PS:这里的数字不是准确的,实际上100个标签选择器叠加的权重也比不过一个类选择器的权重。这里用数字只是更加直观的展示**

> 特点:
>
> 1.继承的权重为0(当没有自己的样式时,听继承的;有自己的样式时,继承的权重为0)
> 2.权重会叠加。

(上图:类选择器10+标签选择器1=11,所以最后14期威武显示的是黄色)


## 补充
**add 20180905:**
`display:table;` 的几个用法:
原文链接:https://www.cnblogs.com/stephen666/p/6995388.html
display:table 解决了一部分需要使用表格特性但又不需要表格语义的情况。
**一、父元素宽度固定,想让若干个子元素平分宽度**
通常的做法是手动设置子元素的宽度,如果设置百分数不一定能整除,设置具体的数值又限制了父元素的宽度固定,很烦。
可以使用display:table来解决:
```css
.parent{display: table; width: 1000px;}
.son{display: table-cell;}
```
如此一来,就算是三个或者六个元素也可以很方便均分父元素的宽度了。
**二、块级子元素垂直居中**
想让一个div或p在父元素中垂直居中一直是很多人头疼的问题(注意直接对块级元素使用vertical-align是不能解决这个问题的,vertical-align定义行内元素的基线相对于该元素所在行的基线的垂直对齐),同样可以使用display:table方便解决:
```css
.parent {display: table;}
.son {display: table-cell; vertical-align: middle;}
```
将块级子元素的display设置为table-cell之后再使用vertical-align就可以了。
注意:虽然display:table解决了避免使用表格的问题,但有几个需要注意的:
(1)display: table时padding会失效
(2)display: table-row时margin、padding同时失效
(3)display: table-cell时margin会失效。 | Daotin/Web/02-CSS/01-CSS基础/02-文本元素、标签分类、CSS三大特性.md/0 | {
"file_path": "Daotin/Web/02-CSS/01-CSS基础/02-文本元素、标签分类、CSS三大特性.md",
"repo_id": "Daotin",
"token_count": 3039
} | 11 |
## 1、元素创建的三种方式
### 1.1、方式一
`document.write("标签代码及内容");`
示例:
```html
<body>
<input type="button" value="按钮" id="btn">
<script src="common.js"></script>
<script>
my$("btn").onclick = function() {
document.write("<p>这是一个p标签</p>");
};
// document.write("<p>这是一个p标签</p>");
</script>
</body>
```
> 缺陷:如果是在页面加载完毕后,通过这种方式创建元素的话,页面上的除此创建元素之外的所有内容都会被清除。但是在页面加载的时候不会。
### 1.2、方式二
`标签.innerHTML = "标签代码及内容";`
示例:
```html
<body>
<script>
<input type="button" value="按钮" id="btn">
<div id="dv"></div>
<script src="common.js"></script>
<script>
my$("btn").onclick = function() {
my$("dv").innerHTML = "lvonve";
};
</script>
</body>
```
> 使用 innerHTML,在页面加载完毕后,不会清除页面的内容。
#### 案例:动态创建列表
```html
// 方式一
<body>
<input type="button" value="创建列表" id="btn">
<div id="dv"></div>
<script src="common.js"></script>
<script>
my$("btn").onclick = function() {
my$("dv").innerHTML = "<ul><li>列表一</li><li>列表二</li><li>列表三</li></ul>";
};
</script>
</body>
```
> 方式一的方式太过死板,li 标签的个数和内容都是固定的,如果增加 li 的个数需要修改源码。
```html
// 方式二
<body>
<input type="button" value="创建列表" id="btn">
<div id="dv"></div>
<script src="common.js"></script>
<script>
var value = ["列表一", "列表二", "列表三", "列表四", "列表五"];
my$("btn").onclick = function() {
var str = "<ul style='list-style: none;cursor: pointer;'>"
for(var i=0; i<value.length; i++) {
str += "<li>"+value[i]+"</li>";
}
str += "</ul>";
my$("dv").innerHTML = str;
};
</script>
</body>
```
### 1.3、方式三
**第一步:创建元素,返回值为一个对象元素**
`document.creatElement("标签的名字");`
**第二步:将元素追加到父元素中**
`父元素.appendChild(创建的对象);`
示例:
```html
<body>
<input type="button" value="创建列表" id="btn">
<div id="dv"></div>
<script src="common.js"></script>
<script>
my$("btn").onclick = function() {
var pObj = document.createElement("p");
setInnerText(pObj, "这是个p标签"); // 自己封装在 common.js 的方法
my$("dv").appendChild(pObj);
};
</script>
</body>
```
#### 案例:动态创建列表
```html
<body>
<input type="button" value="创建列表" id="btn">
<div id="dv"></div>
<script src="common.js"></script>
<script>
var values = ["列表1","列表2","列表3","列表4","列表5","列表6"];
my$("btn").onclick = function() {
var ulObj = document.createElement("ul");
my$("dv").appendChild(ulObj);
for(var i=0; i<values.length; i++) {
var liObj = document.createElement("li");
liObj.innerHTML = values[i];
ulObj.appendChild(liObj);
// 鼠标进入事件
liObj.onmouseover = onmouseoverHandle;
// 鼠标离开事件
liObj.onmouseout = onmouseoutHandle;
}
function onmouseoverHandle() {
this.style.backgroundColor = "yellow";
}
function onmouseoutHandle() {
this.style.backgroundColor = "";
}
};
</script>
</body>
```
> 当在循环中添加事件的时候,建议不使用匿名函数,因为每个匿名函数都会占用一片内存空间,而使用函数调用的方式,不管循环多少次,都使用一份代码。
#### 案例:动态创建表格
```html
<body>
<input type="button" value="创建列表" id="btn">
<div id="dv"></div>
<script src="common.js"></script>
<script>
var arr = [
{name:"百度", href:"www.baidu.com"},
{name:"谷歌", href:"www.baidu.com"},
{name:"优酷", href:"www.baidu.com"},
{name:"土豆", href:"www.baidu.com"},
{name:"腾讯", href:"www.baidu.com"}
];
my$("btn").onclick = function() {
// 创建table标签,并添加到div中
var tableObj = document.createElement("table");
tableObj.border = "1";
tableObj.cellSpacing = "0";
tableObj.cellPadding = "0";
my$("dv").appendChild(tableObj);
// 创建tr标签,添加到table中
for(var i=0; i<arr.length; i++) {
var trObj = document.createElement("tr");
tableObj.appendChild(trObj);
// 添加第一列
var tdObj1 = document.createElement("td");
tdObj1.innerHTML = arr[i].name;
trObj.appendChild(tdObj1);
// 添加第二列
var tdObj2 = document.createElement("td");
tdObj2.innerHTML = "<a href="+arr[i].href+">"+arr[i].name+"</a>";
trObj.appendChild(tdObj2);
}
};
</script>
</body>
```
> `tableObj.border = "1";` 不能使用 `tableObj.style.border = "1px solid red";` 这样的话,只有table有边框,而 tr 没边框。所以 js 中,table 标签有自带的 border 属性可以设置边框,注意不需要 px。
### 2、DOM元素增删改查
`appendChild(ele)`:追加元素ele
`insertBefore(newEle, oldEle)`: 在oldEle元素前添加newEle
`removeChild(ele)`:删除元素ele(或者子元素自杀 `ele.remove();`)
`replaceChild(newEle, oldEle)`:将oldEle修改为newEle元素
```html
<body>
<input type="button" value="添加一个按钮1" id="btn1">
<input type="button" value="添加一个按钮2" id="btn2">
<input type="button" value="删除第一个按钮" id="btn3">
<input type="button" value="删除所有按钮" id="btn4">
<input type="button" value="修改按钮" id="btn5">
<div id="dv"></div>
<script src="common.js"></script>
<script>
var count = 0;
// 往后追加按钮
my$("btn1").onclick = function() {
count++;
var btn = document.createElement("input");
btn.type = "button";
btn.value = "按钮" + count;
my$("dv").appendChild(btn);
};
// 往前追加按钮
my$("btn2").onclick = function() {
count++;
var btn = document.createElement("input");
btn.type = "button";
btn.value = "按钮" + count;
my$("dv").insertBefore(btn, my$("dv").firstElementChild);
};
// 从第一个按钮开始删除一个按钮
my$("btn3").onclick = function() {
my$("dv").removeChild(my$("dv").firstElementChild);
};
// 删除所有按钮
my$("btn4").onclick = function() {
while(my$("dv").firstElementChild) {
my$("dv").removeChild(my$("dv").firstElementChild);
}
};
// 修改元素:将第一个按钮替换成btn元素
m$("btn5").onclick = function() {
my$("dv").replaceChild(btn, my$("dv").firstElementChild);
};
</script>
</body>
```
**removeChild 和 remove 的区别:**
`remove` is a new function. It's a shortcut, making it simpler to remove an element without having to look for the parent node. It's unfortunately not available on old versions of Internet Explorer so, unless you don't want to support this browser, you'll have to use `removeChild` or use a [polyfill](https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove#Polyfill).
| Daotin/Web/03-JavaScript/02-DOM/05-元素的创建,元素增删改查.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/02-DOM/05-元素的创建,元素增删改查.md",
"repo_id": "Daotin",
"token_count": 4506
} | 12 |
需求:使用接口文档验证用户名、邮箱、手机的唯一性
## 1、接口文档
当前端界面需要从服务器获取数据的时候,其实就是眼访问一个 URL 地址,指定特定的参数即可。这个 URL 对应的是 php 或者 jsp 等都是服务器开发人员已经开发好了。服务器开发人员开发好相关的接口之后,会提供一份接口文档给前端开发人员,在接口中会详细说明你要获取什么数据,访问什么地址,传入什么参数等等内容,下面就是一个简单接口文档的内容:
**验证用户名唯一性的接口**
| 地址 | /server/checkUsername.php |
| ------- | --------------------------------- |
| 作用描述 | 验证用户名是否可用 |
| 请求类型 | get 请求 |
| 参数 | uname |
| 返回的数据格式 | 普通字符串 |
| 返回数据说明 | 返回 ok:代表用户名可用; 返回 error:代表用户名不可用。 |
**验证邮箱唯一性的接口**
| 地址 | /server/checkEmail.php |
| ------- | -------------------------- |
| 作用描述 | 验证邮箱是否可用 |
| 请求类型 | post 请求 |
| 参数 | e |
| 返回的数据格式 | 数字 |
| 返回数据说明 | 返回 0:代表邮箱可用; 返回 1:代表邮箱不可用。 |
**验证手机号唯一性的接口**
| 地址 | /server/checkPhone.php |
| ------- | ---------------------- |
| 作用描述 | 验证手机号是否可用 |
| 请求类型 | post 请求 |
| 参数 | phonenumber |
| 返回的数据格式 | json格式 |
| 返回数据说明 | 如下: |
```
手机号可用情况下返回如下:
{
"status":0,
"message":{
"tips":"手机号可用",
"phonefrom":"中国电信"
}
}
手机号不可用情况下返回如下:
{
"status":1,
"message":"手机号已被注册"
}
```
## 2、示例代码
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="dv">
<h1>用户注册</h1>
用户名:<input type="text" name="username"><span id="user-span"></span><br>
邮箱:<input type="text" name="email"><span id="email-span"></span><br>
手机:<input type="text" name="phone"><span id="phone-span"></span><br>
</div>
<script>
// 获取所有元素
var userObj = document.getElementsByName("username")[0];
var emailObj = document.getElementsByName("email")[0];
var phoneObj = document.getElementsByName("phone")[0];
var userSpanObj = document.getElementById("user-span");
var emailSpanObj = document.getElementById("email-span");
var phoneSpanObj = document.getElementById("phone-span");
//用户名文本框失去焦点事件
userObj.onblur = function () {
// 获取文本内容
var userText = this.value;
var xhr = new XMLHttpRequest();
xhr.open("get", "./server/checkUsername.php?uname="+userText, true);
xhr.send(null);
xhr.onreadystatechange = function () {
if(this.readyState == 4) {
if(this.status == 200) {
if(this.responseText == "ok") {
userSpanObj.innerHTML = "用户名可用";
} else if(this.responseText == "error") {
userSpanObj.innerHTML = "用户名不可用";
}
}
}
};
};
//邮箱文本框失去焦点事件
emailObj.onblur = function () {
// 获取文本内容
var emailText = this.value;
var xhr = new XMLHttpRequest();
xhr.open("post", "./server/checkEmail.php", true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("e="+emailText);
xhr.onreadystatechange = function () {
if(this.readyState == 4) {
if(this.status == 200) {
console.log(this.responseText);
if(this.responseText == 0) {
emailSpanObj.innerHTML = "邮箱可用";
} else if(this.responseText == 1) {
emailSpanObj.innerHTML = "邮箱不可用";
}
}
}
};
};
//手机号文本框失去焦点事件
phoneObj.onblur = function () {
// 获取文本内容
var phoneText = this.value;
var xhr = new XMLHttpRequest();
xhr.open("post", "./server/checkPhone.php", true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("phonenumber="+phoneText);
xhr.onreadystatechange = function () {
if(this.readyState == 4) {
if(this.status == 200) {
var val = JSON.parse(this.responseText);
// console.log(val.status);
if(val.status == 0) {
phoneSpanObj.innerHTML = val.message.tips + " " + val.message.phonefrom;
} else if(val.status == 1) {
phoneSpanObj.innerHTML = val.message;
}
}
}
};
};
</script>
</body>
</html>
```
> 书写以上代码的过程中,完全不需要查看对应的 php 文件,只需要查看接口文档就可以搞定。
**注意:**
上面手机号文本框失去焦点事件中,responseText 返回的内容永远是字符串,如果要取得字符串里面的json,需要使用关键字JSON.parse来转换。
JSON.parse 表示把字符串类型的json转换成json数据格式,但是转换的时候可能会出现下面的错误:

出现错误提示:“Uncaught SyntaxError: Unexpected token u in JSON at position 2”,
如果出现了这个错误,就表示这个字符串无法转成json格式的数据。
json 数据的格式必须要求属性名一定要用双引号(不能是单引号)包裹起来,必须!
而上面的第一个 username 没有用双引号括起来,所以报错。
## 3、代码封装
上面验证用户名,邮箱和手机号的时候,都是使用的 Ajax 的四部操作,有很多代码冗余,所以将 Ajax 的四步操作封装在一个函数中很有必要的。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="dv">
<h1>用户注册</h1>
用户名:<input type="text" name="username"><span id="user-span"></span><br>
邮箱:<input type="text" name="email"><span id="email-span"></span><br>
手机:<input type="text" name="phone"><span id="phone-span"></span><br>
</div>
<script>
// Ajax 四步操作的封装函数
function myAjax(type, url, param, async, dataType, callback) {
var xhr = null;
// 兼容性处理
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if((type == "get") || (type == "GET")) {
if(param && param != "") {
url += "?" + param;
}
xhr.open(type, url, async);
xhr.send(null);
} else if((type == "post") || (type == "POST")) {
xhr.open(type, url, async);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(param);
}
if(async) {
xhr.onreadystatechange = function () {
if(this.readyState == 4) {
if(this.status == 200) {
if(dataType == "xml") {
callback(this.responseXML);
} else if(dataType == "json") {
callback(JSON.parse(this.responseText));
} else {
callback(this.responseText);
}
}
}
};
} else {
if(this.readyState == 4) {
if(this.status == 200) {
if(dataType == "xml") {
callback(this.responseXML);
} else if(dataType == "json") {
callback(JSON.parse(this.responseText));
} else {
callback(this.responseText);
}
}
}
}
}
// 获取所有元素
var userObj = document.getElementsByName("username")[0];
var emailObj = document.getElementsByName("email")[0];
var phoneObj = document.getElementsByName("phone")[0];
var userSpanObj = document.getElementById("user-span");
var emailSpanObj = document.getElementById("email-span");
var phoneSpanObj = document.getElementById("phone-span");
//用户名文本框失去焦点事件
userObj.onblur = function () {
// 获取文本内容
var userText = this.value;
myAjax("get", "./server/checkUsername.php", "uname="+userText, "true", "text", function (result) {
if(result == "ok") {
userSpanObj.innerHTML = "用户名可用";
} else if(result == "error") {
userSpanObj.innerHTML = "用户名不可用";
}
});
};
//邮箱文本框失去焦点事件
emailObj.onblur = function () {
// 获取文本内容
var emailText = this.value;
myAjax("post", "./server/checkEmail.php", "e="+emailText, "true", "text", function (result) {
if(result == 0) {
emailSpanObj.innerHTML = "邮箱可用";
} else if(result == 1) {
emailSpanObj.innerHTML = "邮箱不可用";
}
});
};
//手机号文本框失去焦点事件
phoneObj.onblur = function () {
// 获取文本内容
var phoneText = this.value;
myAjax("post", "./server/checkPhone.php", "phonenumber="+phoneText, "true", "json", function (result) {
if(result.status == 0) {
phoneSpanObj.innerHTML = result.message.tips + " " + result.message.phonefrom;
} else if(result.status == 1) {
phoneSpanObj.innerHTML = result.message;
}
});
};
</script>
</body>
</html>
```
**仍然存在的问题**:
1、参数的顺序不可改变;
2、参数没有默认值,所有的参数必须传递。
## 4、代码进一步封装
将需要传入的参数做成一个对象,这个对象所有的有默认参数,如果没有传入一些参数的话,使用默认参数代替;如果传入了相关参数,则覆盖掉默认参数。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="dv">
<h1>用户注册</h1>
用户名:<input type="text" name="username"><span id="user-span"></span><br>
邮箱:<input type="text" name="email"><span id="email-span"></span><br>
手机:<input type="text" name="phone"><span id="phone-span"></span><br>
</div>
<script>
function myAjax2(obj) {
var defaults = {
type: "get",
url: "#",
dataType: "",
data: {}, // 参数有可能多个,用对象保存
async: true,
success: function (result) {
console.log(result);
}
};
for(var key in obj) {
defaults[key] = obj[key];
}
var xhr = null;
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var param = "";
for(var attr in defaults.data) {
param += attr + "=" + defaults.data[attr] + "&" // 比如:uname=zhangsan&pwd=123
}
// 最后一个参数后面去掉 &
if(param) {
param = param.substring(0, param.length-1);
}
if((defaults.type == "get") || (defaults.type == "GET")) {
defaults.url += "?" + param;
}
xhr.open(defaults.type, defaults.url, defaults.async);
if((defaults.type == "get") || (defaults.type == "GET")) {
xhr.send(null);
} else if((defaults.type == "post") || (defaults.type == "POST")) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(param);
}
if(defaults.async) {
xhr.onreadystatechange = function () {
if(this.readyState == 4) {
if(this.status == 200) {
if(defaults.dataType == "xml") {
defaults.success(this.responseXML);
} else if(defaults.dataType == "json") {
defaults.success(JSON.parse(this.responseText));
} else {
defaults.success(this.responseText);
}
}
}
};
} else {
if(this.readyState == 4) {
if(this.status == 200) {
if(defaults.dataType == "xml") {
defaults.success(this.responseXML);
} else if(defaults.dataType == "json") {
defaults.success(JSON.parse(this.responseText));
} else {
defaults.success(this.responseText);
}
}
}
}
}
// 获取所有元素
var userObj = document.getElementsByName("username")[0];
var emailObj = document.getElementsByName("email")[0];
var phoneObj = document.getElementsByName("phone")[0];
var userSpanObj = document.getElementById("user-span");
var emailSpanObj = document.getElementById("email-span");
var phoneSpanObj = document.getElementById("phone-span");
//用户名文本框失去焦点事件
userObj.onblur = function () {
myAjax2({
url: "./server/checkUsername.php",
type: "get",
data: {uname: this.value},
success: function (result) {
if(result == "ok") {
userSpanObj.innerHTML = "用户名可用";
} else if(result == "error") {
userSpanObj.innerHTML = "用户名不可用";
}
}
});
};
//邮箱文本框失去焦点事件
emailObj.onblur = function () {
myAjax2({
url: "./server/checkEmail.php",
type: "post",
data: {e: this.value},
success: function (result) {
if(result == 0) {
emailSpanObj.innerHTML = "邮箱可用";
} else if(result == 1) {
emailSpanObj.innerHTML = "邮箱不可用";
}
}
});
};
//手机号文本框失去焦点事件
phoneObj.onblur = function () {
myAjax2({
url: "./server/checkPhone.php",
type: "post",
dataType: "json",
data: {phonenumber: this.value},
success: function (result) {
if(result.status == 0) {
phoneSpanObj.innerHTML = result.message.tips + " " + result.message.phonefrom;
} else if(result.status == 1) {
phoneSpanObj.innerHTML = result.message;
}
}
});
};
</script>
</body>
</html>
```
> 进一步封装后的函数为: myAjax2({}); 里面是一个对象。使用默认对象的方式,不仅可以解决传入参数顺序不一致的问题;还可以解决不传参数时默认值的问题。
| Daotin/Web/06-Ajax/07-接口文档,验证用户名唯一性案例.md/0 | {
"file_path": "Daotin/Web/06-Ajax/07-接口文档,验证用户名唯一性案例.md",
"repo_id": "Daotin",
"token_count": 10908
} | 13 |
我们先看看要实现的效果图:

### 1、项目需求:
- 全屏页面
- 右侧的页面随着页面宽度的变化而变化,左侧栏宽度固定不变。
- 左侧栏可以上下滑动,如果滑动超出上下范围自动反弹回去
- 点击左侧栏每个项目,自动滚动左侧栏使得项目置顶
- 当点击项目可能使得超出滑动范围的时候,以滑动范围为准,当前点击的项目不必置顶。
### 2、项目分析
**如何实现一个全屏页面,没有滚动条?**
如下面的结构:大盒子1和大盒子2分为上下结构,小盒子3和小盒子4在大盒子2的内部,分为左右结构。

那么如何排布,使得上下左右都没有滚动条呢?
**思路:**
1、要使得大盒子1和大盒子2上下没有滚动条,可以使得大盒子1 的宽度为 100%,高度加入100px,大盒子2的高度 100%;这时会超出100px的高度,如果这时我们让大盒子1定位(position:absolute;),,确实可以实现上下没有滚动条,但是大盒子的头部100px 的位置会被覆盖,所以再让大盒子2 padding-top: 100px; 就可以了。
2、要使得小盒子3和小盒子4左右没有滚动条,可不可以参考大盒子1和大盒子2的策略呢?让小盒子3 宽度100px,高度100%,小盒子4宽度100%,高度100%,然后小盒子3定位(position:absolute;),这是不可以的,因为小盒子3的高度是100%,参照父盒子(大盒子2)的,所以高度是整个视口的高度,而大盒子1占了位置,所以小盒子3只能往下挪,在底部冲出100px的大小,无法弥补。
那么怎么办呢?
**第一,可以将小盒子3定位(position:absolute;)改为浮动(float:left);**
**第二,可以取消大盒子2的宽度100%,改为 margin-left:100px;小盒子3依然浮动(float:left),也是可以的。**
**第三,BFC区域不与浮动区域重叠,而将一个区域变成BFC区域可以使用`overflow:hidden;`**
**BFC主要三个特点:**
- BFC区域不会与float区域重叠(对应两栏布局)
- BFC容器中的子元素,不会影响到外边。(对应子元素margin-top会传递到父元素,清除方法可以使用overflow:hidden,position:absolute/flex; display:inline-block/flex/table-cell;)
- 计算BFC的高度时,浮动元素也参与计算(对应清除浮动的三个方法,都是让父元素成为BFC区域)
### 3、示例代码:
相关源码以放置 Github:https://github.com/Daotin/Web/tree/master/Code/src/11/jd.zip
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./css/base.css">
<link rel="stylesheet" href="./css/category.css">
<script src="./js/category.js"></script>
<script src="./js/tap.js"></script>
<title>Document</title>
</head>
<body>
<div class="layout">
<!-- 头部header -->
<div class="header">
<div class="header-back"></div>
<form action="" class="header-text">
<input type="text" placeholder="请输入商品名称">
</form>
<div class="header-menu"></div>
</div>
<!-- 主体main -->
<div class="main">
<div class="main-left">
<span>拉这么多想干嘛?</span>
<ul>
<li class=""><a href="javascript:;">热门推荐</a></li>
<li class="active"><a href="javascript:;">潮流女装</a></li>
<li class=""><a href="javascript:;">品牌男装</a></li>
<li class=""><a href="javascript:;">内衣配饰</a></li>
<li class=""><a href="javascript:;">家用电器</a></li>
<li class=""><a href="javascript:;">电脑办公</a></li>
<li class=""><a href="javascript:;">手机数码</a></li>
<li class=""><a href="javascript:;">母婴频道</a></li>
<li class=""><a href="javascript:;">图书</a></li>
<li class=""><a href="javascript:;">家居家纺</a></li>
<li class=""><a href="javascript:;">居家生活</a></li>
<li class=""><a href="javascript:;">家具建材</a></li>
<li class=""><a href="javascript:;">热门推荐</a></li>
<li class=""><a href="javascript:;">潮流女装</a></li>
<li class=""><a href="javascript:;">品牌男装</a></li>
<li class=""><a href="javascript:;">内衣配饰</a></li>
<li class=""><a href="javascript:;">家用电器</a></li>
<li class=""><a href="javascript:;">电脑办公</a></li>
<li class=""><a href="javascript:;">手机数码</a></li>
<li class=""><a href="javascript:;">母婴频道</a></li>
<li class=""><a href="javascript:;">图书</a></li>
<li class=""><a href="javascript:;">家居家纺</a></li>
<li class=""><a href="javascript:;">居家生活</a></li>
<li class=""><a href="javascript:;">家具建材</a></li>
</ul>
</div>
<div class="main-right">
<a href="javascript:;" class="main-right-img">
<img src="./uploads/banner_1.jpg" alt="">
</a>
<h3>商品分类</h3>
<div class="main-right-cate">
<ul>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
```
CSS 代码:
```css
html, body {
width: 100%;
height: 100%;
}
.layout {
width: 100%;
height: 100%;
}
/* 头部header */
.header {
width: 100%;
height: 50px;
background-color: #eee;
border-bottom: 1px solid #ccc;
position: absolute;
}
.header-back,
.header-menu {
width: 50px;
height: 50px;
background: url("../images/jd-sprites.png");
background-size: 200px 200px;
position: absolute;
top: 0;
padding: 15px;
background-origin: content-box;
background-clip: content-box;
}
.header-back {
background-position: -20px 0;
left: 0;
}
.header-menu {
background-position: -60px 0;
right: 0;
}
.header-text {
padding: 0 60px;
}
.header-text > input {
width: 100%;
height: 30px;
margin-top: 10px;
border-radius: 10px;
padding-left: 10px;
font-size: 16px;
color: #aaa;
}
/* 主体main */
.main {
width: 100%;
height: 100%;
padding-top: 50px;
}
.main-left {
width: 100px;
height: 100%;
float: left;
overflow: hidden;
position: relative;
background: #eee;
}
.main-left > span {
display: inline-block;
width: 100%;
font-size: 10px;
color: #ccc;
text-align: center;
margin-top: 80px;
}
.main-left ul {
width: 100px;
position: absolute;
left: 0;
top: 0;
}
.main-left ul li {
width: 100%;
height: 50px;
line-height: 50px;
text-align: center;
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
background-color: #eee;
}
.main-left li.active {
background-color: #fff;
border-bottom: 1px solid #ccc;
border-right: 1px solid #ccc;
}
.main-left li.active a {
color: #e92322;
}
.main-left a {
display: block;
width: 100%;
height: 50px;
color: #666;
}
.main-right {
/* width: 100%; */
height: 100%;
margin-left: 100px;
/* 设置为伸缩盒子 */
display: flex;
flex-direction: column;
}
.main-right-img {
width: 100%;
}
.main-right-img > img {
width: 100%;
/* 消除基线 */
display: block;
}
.main-right > h3 {
font-size: 14px;
font-weight: bold;
color: #333;
margin: 10px 0 10px 5px;
}
.main-right-cate {
width: 100%;
/* 下面两个一起使得没有上下滚动条 */
flex: 1;
overflow: hidden;
}
.main-right-cate> ul {
width: 100%;
}
.main-right-cate > ul > li {
width: 33.33%;
text-align: center;
float: left;
}
```

原生 js 代码:
```js
window.onload = function () {
leftSlideEffect();
};
// 左侧滑动栏效果和点击效果
function leftSlideEffect() {
// 添加左侧栏的滑动效果
var mainObj = document.querySelector(".main");
var leftUlObj = document.querySelector(".main-left").children[1];
var mainLeftHeight = document.querySelector(".main-left").offsetHeight;
var leftUlObjHeight = leftUlObj.offsetHeight;
var liObjs = leftUlObj.querySelectorAll("li");
var startY=0; // 起始位置
var diffY=0; // 滑动后与起始位置的偏移
var currentY=0; // 保存每次滑动后的偏移
var maxTop = 0; // 最大top偏移值
var minTop = mainLeftHeight-leftUlObjHeight; // 最大top偏移值
var maxBounceTop = maxTop + 100; //弹性最大高度
var minBounceTop = minTop - 100; //弹性最小高度
leftUlObj.addEventListener("touchstart", function(e) {
// 计算起始坐标
startY = e.targetTouches[0].clientY;
});
leftUlObj.addEventListener("touchmove", function(e) {
/*计算距离的差异*/
diffY = e.targetTouches[0].clientY - startY;
/*判断滑动的时候是否超出当前指定的滑动区间*/
if((diffY+currentY > maxBounceTop) || (diffY+currentY < minBounceTop)) {
return;
}
/*先将之前可能添加的过渡效果清除*/
leftUlObj.style.transition = "none";
/*实现偏移操作:应该在之前的滑动距离的基础之上再进行滑动*/
leftUlObj.style.top = diffY+currentY + "px";
});
leftUlObj.addEventListener("touchend", function() {
if(diffY+currentY > maxTop) {
// 回到maxTop位置,设置currentY当前值
leftUlObj.style.transition = "top 0.5s"
leftUlObj.style.top = maxTop + "px";
currentY = maxTop;
} else if(diffY+currentY < minTop) {
// 回到minTop位置,设置currentY当前值
leftUlObj.style.transition = "top 0.5s"
leftUlObj.style.top = minTop + "px";
currentY = minTop;
} else {
// 记录当前滑动的距离
currentY += diffY;
}
});
// -----------------------------------------------------
// 左侧滑动栏点击效果
/*为每一个li元素设置添加一个索引值*/
for(var i=0; i<liObjs.length; i++) {
// liObjs是对象,给对象增加属性值
liObjs[i].index = i;
}
// 点击事件
fingerTap.tap(leftUlObj, function (e) {
// 清除所有li标签
for(var i=0; i<liObjs.length; i++) {
liObjs[i].classList.remove("active");
}
//设置点击的li标签的样式
var indexLi = e.target.parentElement;
indexLi.classList.add("active");
// 每个li标签的高度
var indexLiHeight = indexLi.offsetHeight;
/*2.移动当前的li元素到父容器的最顶部,但是不能超出之前设定了静止状态下的最小top值*/
leftUlObj.style.transition = "top 0.5s";
if(-indexLiHeight*indexLi.index < minTop) {
leftUlObj.style.top = minTop + "px";
// 记得重置currentY的值
currentY=minTop;
} else {
leftUlObj.style.top = -indexLiHeight*indexLi.index + "px";
// 记得重置currentY的值
currentY=-indexLiHeight*indexLi.index;
}
});
}
```
把点击事件封装成一个单独 js 库,tap.js。
```js
// 封装移动端的tap事件
var fingerTap = {
tap: function (dom, callback) {
// 判断dom是否存在
if((!dom) || (typeof dom != "object")) {
return;
}
var startX, startY, endX, endY, startTime, endTime;
dom.addEventListener("touchstart", function (e) {
// 不止一个手指
if(e.targetTouches.length > 1) {
return;
}
startX = e.targetTouches[0].clientX;
startY = e.targetTouches[0].clientY;
// 点击时记录毫秒数
startTime = Date.now();
});
dom.addEventListener("touchend", function (e) {
// 不止一个手指
if(e.changedTouches.length > 1) {
return;
}
// 之所以使用changedTouches,是因为手指离开后就没有targetTouches了
endX = e.changedTouches[0].clientX;
endY = e.changedTouches[0].clientY;
// 记录离开手指的毫秒数
endTime = Date.now();
//如果是长按操作就返回
if(endTime - startTime > 300) {
return;
}
// 判断从按下到抬起手指在一定的范围滑动也算tap事件
if((Math.abs(endX-startX) <= 6) && (Math.abs(endY-startY) <= 6)) {
// tap点击事件的处理函数
callback && callback(e);
}
});
}
};
```
### 4、使用 Zepto 实现点击操作
上面 tap.js 是我们自己封装的点击事件,其实在 Zepto 中,已经封装好了 tap 单击事件,我们可以直接使用。
只需要将
```js
fingerTap.tap(leftUlObj, function (e) {});
```
改为:
```js
$(leftUlObj).on("tap", function() {});
```
就可以实现相同的效果。
| Daotin/Web/07-移动Web开发/04-实现JD分类页面.md/0 | {
"file_path": "Daotin/Web/07-移动Web开发/04-实现JD分类页面.md",
"repo_id": "Daotin",
"token_count": 12394
} | 14 |
;(function () {
'use strict';
/**
* @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
*
* @codingstandard ftlabs-jsv2
* @copyright The Financial Times Limited [All Rights Reserved]
* @license MIT License (see LICENSE.txt)
*/
/*jslint browser:true, node:true*/
/*global define, Event, Node*/
/**
* Instantiate fast-clicking listeners on the specified layer.
*
* @constructor
* @param {Element} layer The layer to listen on
* @param {Object} [options={}] The options to override the defaults
*/
function FastClick(layer, options) {
var oldOnClick;
options = options || {};
/**
* Whether a click is currently being tracked.
*
* @type boolean
*/
this.trackingClick = false;
/**
* Timestamp for when click tracking started.
*
* @type number
*/
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
*
* @type EventTarget
*/
this.targetElement = null;
/**
* X-coordinate of touch start event.
*
* @type number
*/
this.touchStartX = 0;
/**
* Y-coordinate of touch start event.
*
* @type number
*/
this.touchStartY = 0;
/**
* ID of the last touch, retrieved from Touch.identifier.
*
* @type number
*/
this.lastTouchIdentifier = 0;
/**
* Touchmove boundary, beyond which a click will be cancelled.
*
* @type number
*/
this.touchBoundary = options.touchBoundary || 10;
/**
* The FastClick layer.
*
* @type Element
*/
this.layer = layer;
/**
* The minimum time between tap(touchstart and touchend) events
*
* @type number
*/
this.tapDelay = options.tapDelay || 200;
/**
* The maximum time for a tap
*
* @type number
*/
this.tapTimeout = options.tapTimeout || 700;
if (FastClick.notNeeded(layer)) {
return;
}
// Some old versions of Android don't have Function.prototype.bind
function bind(method, context) {
return function() { return method.apply(context, arguments); };
}
var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
var context = this;
for (var i = 0, l = methods.length; i < l; i++) {
context[methods[i]] = bind(context[methods[i]], context);
}
// Set up event handlers as required
if (deviceIsAndroid) {
layer.addEventListener('mouseover', this.onMouse, true);
layer.addEventListener('mousedown', this.onMouse, true);
layer.addEventListener('mouseup', this.onMouse, true);
}
layer.addEventListener('click', this.onClick, true);
layer.addEventListener('touchstart', this.onTouchStart, false);
layer.addEventListener('touchmove', this.onTouchMove, false);
layer.addEventListener('touchend', this.onTouchEnd, false);
layer.addEventListener('touchcancel', this.onTouchCancel, false);
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
// layer when they are cancelled.
if (!Event.prototype.stopImmediatePropagation) {
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener;
if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture);
} else {
rmv.call(layer, type, callback, capture);
}
};
layer.addEventListener = function(type, callback, capture) {
var adv = Node.prototype.addEventListener;
if (type === 'click') {
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
if (!event.propagationStopped) {
callback(event);
}
}), capture);
} else {
adv.call(layer, type, callback, capture);
}
};
}
// If a handler is already declared in the element's onclick attribute, it will be fired before
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
// adding it as listener.
if (typeof layer.onclick === 'function') {
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick;
layer.addEventListener('click', function(event) {
oldOnClick(event);
}, false);
layer.onclick = null;
}
}
/**
* Windows Phone 8.1 fakes user agent string to look like Android and iPhone.
*
* @type boolean
*/
var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;
/**
* Android requires exceptions.
*
* @type boolean
*/
var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;
/**
* iOS requires exceptions.
*
* @type boolean
*/
var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;
/**
* iOS 4 requires an exception for select elements.
*
* @type boolean
*/
var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
/**
* iOS 6.0-7.* requires the target element to be manually derived
*
* @type boolean
*/
var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent);
/**
* BlackBerry requires exceptions.
*
* @type boolean
*/
var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;
/**
* Determine whether a given element requires a native click.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element needs a native click
*/
FastClick.prototype.needsClick = function(target) {
switch (target.nodeName.toLowerCase()) {
// Don't send a synthetic click to disabled inputs (issue #62)
case 'button':
case 'select':
case 'textarea':
if (target.disabled) {
return true;
}
break;
case 'input':
// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
if ((deviceIsIOS && target.type === 'file') || target.disabled) {
return true;
}
break;
case 'label':
case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
case 'video':
return true;
}
return (/\bneedsclick\b/).test(target.className);
};
/**
* Determine whether a given element requires a call to focus to simulate click into element.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
*/
FastClick.prototype.needsFocus = function(target) {
switch (target.nodeName.toLowerCase()) {
case 'textarea':
return true;
case 'select':
return !deviceIsAndroid;
case 'input':
switch (target.type) {
case 'button':
case 'checkbox':
case 'file':
case 'image':
case 'radio':
case 'submit':
return false;
}
// No point in attempting to focus disabled inputs
return !target.disabled && !target.readOnly;
default:
return (/\bneedsfocus\b/).test(target.className);
}
};
/**
* Send a click event to the specified element.
*
* @param {EventTarget|Element} targetElement
* @param {Event} event
*/
FastClick.prototype.sendClick = function(targetElement, event) {
var clickEvent, touch;
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
if (document.activeElement && document.activeElement !== targetElement) {
document.activeElement.blur();
}
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
};
FastClick.prototype.determineEventType = function(targetElement) {
//Issue #159: Android Chrome Select Box does not open with a synthetic click event
if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
return 'mousedown';
}
return 'click';
};
/**
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.focus = function(targetElement) {
var length;
// Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
length = targetElement.value.length;
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
/**
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
*
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.updateScrollParent = function(targetElement) {
var scrollParent, parentElement;
scrollParent = targetElement.fastClickScrollParent;
// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
// target element was moved to another parent.
if (!scrollParent || !scrollParent.contains(targetElement)) {
parentElement = targetElement;
do {
if (parentElement.scrollHeight > parentElement.offsetHeight) {
scrollParent = parentElement;
targetElement.fastClickScrollParent = parentElement;
break;
}
parentElement = parentElement.parentElement;
} while (parentElement);
}
// Always update the scroll top tracker if possible.
if (scrollParent) {
scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
}
};
/**
* @param {EventTarget} targetElement
* @returns {Element|EventTarget}
*/
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
if (eventTarget.nodeType === Node.TEXT_NODE) {
return eventTarget.parentNode;
}
return eventTarget;
};
/**
* On touch start, record the position and scroll offset.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchStart = function(event) {
var targetElement, touch, selection;
// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
if (event.targetTouches.length > 1) {
return true;
}
targetElement = this.getTargetElementFromEventTarget(event.target);
touch = event.targetTouches[0];
if (deviceIsIOS) {
// Only trusted events will deselect text on iOS (issue #49)
selection = window.getSelection();
if (selection.rangeCount && !selection.isCollapsed) {
return true;
}
if (!deviceIsIOS4) {
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
// with the same identifier as the touch event that previously triggered the click that triggered the alert.
// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
// Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
// which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
// random integers, it's safe to to continue if the identifier is 0 here.
if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
event.preventDefault();
return false;
}
this.lastTouchIdentifier = touch.identifier;
// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
// 1) the user does a fling scroll on the scrollable layer
// 2) the user stops the fling scroll with another tap
// then the event.target of the last 'touchend' event will be the element that was under the user's finger
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
this.updateScrollParent(targetElement);
}
}
this.trackingClick = true;
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement;
this.touchStartX = touch.pageX;
this.touchStartY = touch.pageY;
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
event.preventDefault();
}
return true;
};
/**
* Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.touchHasMoved = function(event) {
var touch = event.changedTouches[0], boundary = this.touchBoundary;
if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
return true;
}
return false;
};
/**
* Update the last position.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchMove = function(event) {
if (!this.trackingClick) {
return true;
}
// If the touch has moved, cancel the click tracking
if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
this.trackingClick = false;
this.targetElement = null;
}
return true;
};
/**
* Attempt to find the labelled control for the given label element.
*
* @param {EventTarget|HTMLLabelElement} labelElement
* @returns {Element|null}
*/
FastClick.prototype.findControl = function(labelElement) {
// Fast path for newer browsers supporting the HTML5 control attribute
if (labelElement.control !== undefined) {
return labelElement.control;
}
// All browsers under test that support touch events also support the HTML5 htmlFor attribute
if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor);
}
// If no for attribute exists, attempt to retrieve the first labellable descendant element
// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
};
/**
* On touch end, determine whether to send a click event at once.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchEnd = function(event) {
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
if (!this.trackingClick) {
return true;
}
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
this.cancelNextClick = true;
return true;
}
if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
return true;
}
// Reset to prevent wrong click cancel on input (issue #156).
this.cancelNextClick = false;
this.lastClickTime = event.timeStamp;
trackingClickStart = this.trackingClickStart;
this.trackingClick = false;
this.trackingClickStart = 0;
// On some iOS devices, the targetElement supplied with the event is invalid if the layer
// is performing a transition or scroll, and has to be re-detected manually. Note that
// for this to function correctly, it must be called *after* the event target is checked!
// See issue #57; also filed as rdar://13048589 .
if (deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0];
// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
}
targetTagName = targetElement.tagName.toLowerCase();
if (targetTagName === 'label') {
forElement = this.findControl(targetElement);
if (forElement) {
this.focus(targetElement);
if (deviceIsAndroid) {
return false;
}
targetElement = forElement;
}
} else if (this.needsFocus(targetElement)) {
// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
this.targetElement = null;
return false;
}
this.focus(targetElement);
this.sendClick(targetElement, event);
// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
if (!deviceIsIOS || targetTagName !== 'select') {
this.targetElement = null;
event.preventDefault();
}
return false;
}
if (deviceIsIOS && !deviceIsIOS4) {
// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
scrollParent = targetElement.fastClickScrollParent;
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
return true;
}
}
// Prevent the actual click from going though - unless the target node is marked as requiring
// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
if (!this.needsClick(targetElement)) {
event.preventDefault();
this.sendClick(targetElement, event);
}
return false;
};
/**
* On touch cancel, stop tracking the click.
*
* @returns {void}
*/
FastClick.prototype.onTouchCancel = function() {
this.trackingClick = false;
this.targetElement = null;
};
/**
* Determine mouse events which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onMouse = function(event) {
// If a target element was never set (because a touch event was never fired) allow the event
if (!this.targetElement) {
return true;
}
if (event.forwardedTouchEvent) {
return true;
}
// Programmatically generated events targeting a specific element should be permitted
if (!event.cancelable) {
return true;
}
// Derive and check the target element to see whether the mouse event needs to be permitted;
// unless explicitly enabled, prevent non-touch click events from triggering actions,
// to prevent ghost/doubleclicks.
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
event.propagationStopped = true;
}
// Cancel the event
event.stopPropagation();
event.preventDefault();
return false;
}
// If the mouse event is permitted, return true for the action to go through.
return true;
};
/**
* On actual clicks, determine whether this is a touch-generated click, a click action occurring
* naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
* an actual click which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onClick = function(event) {
var permitted;
// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
if (this.trackingClick) {
this.targetElement = null;
this.trackingClick = false;
return true;
}
// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
if (event.target.type === 'submit' && event.detail === 0) {
return true;
}
permitted = this.onMouse(event);
// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
if (!permitted) {
this.targetElement = null;
}
// If clicks are permitted, return true for the action to go through.
return permitted;
};
/**
* Remove all FastClick's event listeners.
*
* @returns {void}
*/
FastClick.prototype.destroy = function() {
var layer = this.layer;
if (deviceIsAndroid) {
layer.removeEventListener('mouseover', this.onMouse, true);
layer.removeEventListener('mousedown', this.onMouse, true);
layer.removeEventListener('mouseup', this.onMouse, true);
}
layer.removeEventListener('click', this.onClick, true);
layer.removeEventListener('touchstart', this.onTouchStart, false);
layer.removeEventListener('touchmove', this.onTouchMove, false);
layer.removeEventListener('touchend', this.onTouchEnd, false);
layer.removeEventListener('touchcancel', this.onTouchCancel, false);
};
/**
* Check whether FastClick is needed.
*
* @param {Element} layer The layer to listen on
*/
FastClick.notNeeded = function(layer) {
var metaViewport;
var chromeVersion;
var blackberryVersion;
var firefoxVersion;
// Devices that don't support touch don't need FastClick
if (typeof window.ontouchstart === 'undefined') {
return true;
}
// Chrome version - zero for other browsers
chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
if (chromeVersion) {
if (deviceIsAndroid) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport) {
// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// Chrome 32 and above with width=device-width or less don't need FastClick
if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
return true;
}
}
// Chrome desktop doesn't need FastClick (issue #15)
} else {
return true;
}
}
if (deviceIsBlackBerry10) {
blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);
// BlackBerry 10.3+ does not require Fastclick library.
// https://github.com/ftlabs/fastclick/issues/251
if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport) {
// user-scalable=no eliminates click delay.
if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// width=device-width (or less than device-width) eliminates click delay.
if (document.documentElement.scrollWidth <= window.outerWidth) {
return true;
}
}
}
}
// IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {
return true;
}
// Firefox version - zero for other browsers
firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
if (firefoxVersion >= 27) {
// Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
return true;
}
}
// IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version
// http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {
return true;
}
return false;
};
/**
* Factory method for creating a FastClick object
*
* @param {Element} layer The layer to listen on
* @param {Object} [options={}] The options to override the defaults
*/
FastClick.attach = function(layer, options) {
return new FastClick(layer, options);
};
if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
// AMD. Register as an anonymous module.
define(function() {
return FastClick;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = FastClick.attach;
module.exports.FastClick = FastClick;
} else {
window.FastClick = FastClick;
}
}());
| Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/js/fastclick.js/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/js/fastclick.js",
"repo_id": "Daotin",
"token_count": 8481
} | 15 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./css/base.css">
<link rel="stylesheet" href="./css/category.css">
<script src="./js/category.js"></script>
<script src="./js/tap.js"></script>
<title>Document</title>
</head>
<body>
<div class="layout">
<!-- 头部header -->
<div class="header">
<div class="header-back"></div>
<form action="" class="header-text">
<input type="text" placeholder="请输入商品名称">
</form>
<div class="header-menu"></div>
</div>
<!-- 主体main -->
<div class="main">
<div class="main-left">
<span>拉这么多想干嘛?</span>
<ul>
<li class=""><a href="javascript:;">热门推荐</a></li>
<li class="active"><a href="javascript:;">潮流女装</a></li>
<li class=""><a href="javascript:;">品牌男装</a></li>
<li class=""><a href="javascript:;">内衣配饰</a></li>
<li class=""><a href="javascript:;">家用电器</a></li>
<li class=""><a href="javascript:;">电脑办公</a></li>
<li class=""><a href="javascript:;">手机数码</a></li>
<li class=""><a href="javascript:;">母婴频道</a></li>
<li class=""><a href="javascript:;">图书</a></li>
<li class=""><a href="javascript:;">家居家纺</a></li>
<li class=""><a href="javascript:;">居家生活</a></li>
<li class=""><a href="javascript:;">家具建材</a></li>
<li class=""><a href="javascript:;">热门推荐</a></li>
<li class=""><a href="javascript:;">潮流女装</a></li>
<li class=""><a href="javascript:;">品牌男装</a></li>
<li class=""><a href="javascript:;">内衣配饰</a></li>
<li class=""><a href="javascript:;">家用电器</a></li>
<li class=""><a href="javascript:;">电脑办公</a></li>
<li class=""><a href="javascript:;">手机数码</a></li>
<li class=""><a href="javascript:;">母婴频道</a></li>
<li class=""><a href="javascript:;">图书</a></li>
<li class=""><a href="javascript:;">家居家纺</a></li>
<li class=""><a href="javascript:;">居家生活</a></li>
<li class=""><a href="javascript:;">家具建材</a></li>
</ul>
</div>
<div class="main-right">
<a href="javascript:;" class="main-right-img">
<img src="./uploads/banner_1.jpg" alt="">
</a>
<h3>商品分类</h3>
<div class="main-right-cate">
<ul>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
<li>
<a href="javascript:;">
<img src="./uploads/nv-fy.jpg" alt="">
<p>毛衣</p>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html> | Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/新建文件夹/category.html/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/新建文件夹/category.html",
"repo_id": "Daotin",
"token_count": 6364
} | 16 |
$(function () {
// 获取所有的item元素
var items = $(".carousel-inner .item");
// 当屏幕大小改变的时候,动态创建图片
// triggle函数表示页面在第一次加载的时候,自动触发一次。
$(window).on("resize", function () {
// 判断屏幕的大小,以决定加载大图还是小图
var screenWidth = $(window).width();
// 添加大屏幕的图片
if (screenWidth >= 768) {
// 为每个item添加大图片
items.each(function (index, value) {
// 获取每个item的图片,使用data()获取自定义属性
var imgSrc = $(this).data("largeImage");
// 使用插入小图片的方法不可以,因为路径符号会被解析成空格
$(this).html($('<a href="javascript:;" class="bigImg"></a>').css("backgroundImage", "url('" + imgSrc + "')"));
});
// 添加小屏幕的图片
} else {
// 为每个item添加小图片
items.each(function (index, value) {
// 获取每个item的图片,使用data()获取自定义属性
var imgSrc = $(this).data("smallImage");
$(this).html('<a href="javascript:;" class="smallImg"><img src="' + imgSrc + '"></a>');
});
}
}).trigger("resize");
// 实现滑动轮播效果
// 实现滑动轮播可以可以直接调用插件的点击按钮上下切换的功能
// 获取滑动区域的元素
var carouselInner = $(".carousel-inner");
var carousel = $(".carousel");
var startX, endX;
// 给元素添加touchstart和touchend事件
carouselInner[0].addEventListener("touchstart", function (e) {
startX = e.targetTouches[0].clientX;
});
carouselInner[0].addEventListener("touchend", function (e) {
endX = e.changedTouches[0].clientX;
// endX - startX > 10px 证明往右滑动
if (endX - startX > 10) {
carousel.carousel("prev");
} else if (startX - endX > 10) {
carousel.carousel("next");
}
});
// 产品块的宝,北标签的鼠标悬停效果
$('[data-toggle="tooltip"]').tooltip();
// 设置产品块的标签栏在移动端时可以滑动
var ulProduct = $(".tabs-parent .nav-tabs");
var liProducts = ulProduct.children("li");
var totleWidth = 0;
liProducts.each(function (index, element) {
/*获取宽度的方法的说明:
* width():它只能得到当前元素的内容的宽度
* innerWidth():它能获取当前元素的内容的宽度+padding
* outerWidth():获取当前元素的内容的宽度+padding+border
* outerWidth(true):获取元素的内容的宽度+padding+border+margin*/
totleWidth += $(element).innerWidth();
});
ulProduct.width(totleWidth);
// 使用iScroll插件实现滑动效果
/*使用插件实现导航条的滑动操作*/
var myScroll = new IScroll('.tabs-parent', {
/*设置水平滑动,不允许垂直滑动*/
scrollX: true,
scrollY: false
});
}); | Daotin/Web/07-移动Web开发/案例源码/03-微金所/js/wjs-index.js/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/js/wjs-index.js",
"repo_id": "Daotin",
"token_count": 1802
} | 17 |
// This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment.
require('../../js/transition.js')
require('../../js/alert.js')
require('../../js/button.js')
require('../../js/carousel.js')
require('../../js/collapse.js')
require('../../js/dropdown.js')
require('../../js/modal.js')
require('../../js/tooltip.js')
require('../../js/popover.js')
require('../../js/scrollspy.js')
require('../../js/tab.js')
require('../../js/affix.js') | Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/bootstrap/js/npm.js/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/bootstrap/js/npm.js",
"repo_id": "Daotin",
"token_count": 172
} | 18 |
/* FONT PATH
* -------------------------- */
@font-face {
font-family: 'FontAwesome';
src: url('#{$fa-font-path}/fontawesome-webfont.eot?v=#{$fa-version}');
src: url('#{$fa-font-path}/fontawesome-webfont.eot?#iefix&v=#{$fa-version}') format('embedded-opentype'),
url('#{$fa-font-path}/fontawesome-webfont.woff2?v=#{$fa-version}') format('woff2'),
url('#{$fa-font-path}/fontawesome-webfont.woff?v=#{$fa-version}') format('woff'),
url('#{$fa-font-path}/fontawesome-webfont.ttf?v=#{$fa-version}') format('truetype'),
url('#{$fa-font-path}/fontawesome-webfont.svg?v=#{$fa-version}#fontawesomeregular') format('svg');
// src: url('#{$fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts
font-weight: normal;
font-style: normal;
}
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_path.scss/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_path.scss",
"repo_id": "Daotin",
"token_count": 332
} | 19 |
## 几个要点:
- Nodejs 是基于 Chrome 的 V8 引擎开发的一个 C++ 程序,目的是提供一个 **JS 的运行环境**。
- Node.js 和浏览器是不同的环境,是有着很多细小的差异的。首先,二者各自包含的全局变量不同。document 对象是用来操作页面的,所以只有浏览器环境下才可以直接使用。但是如果是要放到 Node.js 环境下运行代码,就不要使用 document 。同样的道理,Node.js 中可以直接拿来使用的 http 对象,在浏览器环境下就没有。其次,Node.js 和浏览器对 ES6 新特性的支持程度也是不同的,这一点也要注意。(参考:[Node.js与浏览器的区别](http://nodejs.cn/learn/differences-between-nodejs-and-the-browser))
## node和npm的关系
- npm由于内置在node.js中,所以就一并安装了。
- 如果只想单独安装npm,不想安装node.js,这个好像是不行的。
**引用大神的总结:**
其实npm是nodejs的包管理器(package manager)。
我们在Node.js上开发时,会用到很多别人已经写好的javascript代码,如果每当我们需要别人的代码时,都根据名字搜索一下,下载源码,解压,再使用,会非常麻烦。
于是就出现了包管理器npm。
大家把自己写好的源码上传到npm官网上,如果要用某个或某些个,直接通过npm安装就可以了,不用管那个源码在哪里。
并且如果我们要使用模块A,而模块A又依赖模块B,模块B又依赖模块C和D,此时npm会根据依赖关系,把所有依赖的包都下载下来并且管理起来。试想如果这些工作全靠我们自己去完成会多么麻烦!
**发展历程**
npm作者已经将npm开发完成,于是发邮件通知 jQuery、Bootstrap、Underscore 作者,希望他们把 jquery、bootstrap 、 underscore 放到npm远程仓库,但是没有收到回应,于是npm的发展遇到了瓶颈。
Node.js作者也将Node.js开发完成,但是 Node.js 缺少一个包管理器,于是他和 npm 的作者一拍即合、抱团取暖,最终 Node.js 内置了 npm。
后来的事情大家都知道,Node.js 火了。随着 Node.js 的火爆,大家开始用 npm 来共享 JS 代码了,于是 jQuery 作者也将 jQuery 发布到 npm 了。
所以现在,你可以使用 npm install jquery 来下载 jQuery 代码。现在用 npm 来分享代码已经成了前端的标配。
## 参考文档:
- http://nodejs.cn/learn
- https://zhuanlan.zhihu.com/p/47822968
| Daotin/Web/10-Node.js/00-什么是Node.js.md/0 | {
"file_path": "Daotin/Web/10-Node.js/00-什么是Node.js.md",
"repo_id": "Daotin",
"token_count": 1616
} | 20 |
## 一、Gulp介绍
Gulp 中文主页: http://www.gulpjs.com.cn/

gulp是与grunt功能类似的**前端项目构建**工具, 也是基于Nodejs的**自动任务运行器** 。能自动化地完成 javascript/coffee/sass/less/html/image/css 等文件的合并、压缩、检查、监听文件变化、浏览器自动刷新、测试等任务。
gulp比Grunt更加高效,Gulp是基于**异步多任务**的处理方式,而 Grunt 则是同步的任务处理方式。使得Gulp 更易于使用。
**注意:Gulp 也不支持 ES6 语法。**
## 二、Gulp使用步骤
由于 Gulp 也是基于 node.js 的,所以首先要确保安装了 node.js.
**1、安装 nodejs,**
查看版本: `node -v`
**2、创建一个简单的应用 gulp_test**
下面为gulp_test项目的目录结构:
```
|- dist ---- 存放项目上线的文件
|- src
|- js
|- css
|- less
|- index.html
|- gulpfile.js-----gulp配置文件
|- package.json
{
"name": "gulp_test",
"version": "1.0.0"
}
```
**3、安装gulp**
* 全局安装gulp
```
npm install gulp -g
```
* 局部安装gulp
```
npm install gulp --save-dev
```
**4、配置编码:gulpfile.js**
> 注意:gulpfile.js 不需要首字母大写,而 Gruntfile.js 需要首字母大写。
```js
//引入gulp模块
var gulp = require('gulp');
//定义默认任务
gulp.task('任务名', function() {
// 将你的任务的任务代码放在这
});
gulp.task('default', ['任务'])//异步执行
```
**5、构建命令**
```
gulp 任务名
```
## 三、Gulp插件
Gulp 同 Grunt 一样,Culp 本身是不会执行任务的,执行任务的都是小弟,也就是gulp下的插件。
注意:查找gulp的插件,需要**切换到gulp国外官网**,然后点击 `plugins` 选项,才可以查看查找相关插件。
**相关插件:**
* `gulp-concat` : 合并文件(js/css)
* `gulp-uglify` : 压缩js文件
* `gulp-rename `: 文件重命名
* `gulp-less` : 编译less
* `gulp-clean-css` : 压缩css
* `gulp-livereload` : 实时自动编译刷新
**重要API**
* `gulp.src(filePath/pathArr)` : 指向指定路径的所有文件, 返回文件流对象。用于读取文件。
* `gulp.dest(dirPath/pathArr)` :指向指定的所有文件夹。用于向文件夹中输出文件。
* `gulp.task(name, [deps], fn) ` :定义一个任务
* `gulp.watch() ` :监视文件的变化
## 四、插件使用
### 1、合并压缩js
**1、创建js文件**
* src/js/test1.js
```js
(function () {
function add(num1, num2) {
return num1 + num2;
}
console.log(add(10, 30));
})();
```
* src/js/test2.js
```js
(function () {
var arr = [2,3,4].map(function (item, index) {
return item+1;
});
console.log(arr);
})();
```
**2、下载相应插件:**
```
npm install gulp-concat gulp-uglify gulp-rename --save-dev
```
**3、配置 gulpfile.js**
```js
// 引入gulp模块
var gulp = require("gulp");
//引入gulp插件
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
gulp.task('js', function () {
return gulp.src('src/js/*.js') // 引入js源文件
.pipe(concat('build.js')) // 合并为临时js文件build.js
.pipe(gulp.dest('dist/js/')) // 输出到dist/js目录下
.pipe(uglify()) // 将临时js文件压缩
.pipe(rename({ // 将压缩后的js文件添加.min后缀(重命名为build.min.js)
suffix: '.min'
}))
.pipe(gulp.dest('dist/js/')); // 再将最终的build.min.js输出到dist/js目录下
});
gulp.task('default', ['js']);
```
> 1、插件的引入不同于gulp模块的引入,gulp 的引入之后,gulp是个对象,可以点出task等任务,但是插件引入之后是个方法,既然是方法,就可以直接加括号来调用,此为区别,需要注意。
>
> 2、gulp.src 引入源文件的时候,如果 js目录 下面还有目录,这个目录里面也有js文件,如果想递归引入src里面所有的js可以这样写:`src/js/**/*.js` ,给 js 目录下面套上一个 `**` 目录就递归查找 js目录下所有的js文件。
>
> 3、`.pipe` 是管道操作,用来链接任务的执行流。
>
> 4、rename 方法里面可以直接填写 `build.min.js` 来指定文件名,也可以使用一个对象,其键为 `suffix` 表示后缀名的意思,值为 `.min` 表示后缀名为 .min,但是这里面的后缀名是除开 `.js` 后缀的,最后在文件名的最后还会加上`.js`的。
>
> **5、return 的作用:使得grup的任务执行为异步的,就这一点,非常重要。**
**4、页面引入 js 浏览测试**
```html
<script type="text/javascript" src="dist/js/built.min.js"></script>
```
### 2、合并压缩css/less
**1、创建less/css文件**
* src/css/test1.css
```css
#div1 {
width: 100px;
height: 100px;
background: green;
}
```
* src/css/test2.css
```css
#div2 {
width: 200px;
height: 200px;
background: blue;
}
```
* src/less/test3.less
```less
@base: yellow;
.index1 { color: @base; }
.index2 { color: green; }
```
**2、下载插件**
```
npm install gulp-less gulp-clean-css --save-dev
```
**3、配置gulpfile.js**
```js
var less = require('gulp-less');
var cleanCSS = require('gulp-clean-css');
//less处理任务
gulp.task('lessTask', function () {
return gulp.src('src/less/*.less')
.pipe(less())
.pipe(gulp.dest('src/css/'));
})
//css处理任务, 指定依赖的任务
gulp.task('cssTask',['lessTask'], function () {
return gulp.src('src/css/*.css')
.pipe(concat('built.css'))
.pipe(gulp.dest('dist/css/'))
.pipe(rename({suffix: '.min'}))
.pipe(cleanCSS({compatibility: 'ie8'})) // 为了兼容IE8浏览器
.pipe(gulp.dest('dist/css/'));
});
gulp.task('default', ['minifyjs', 'cssTask']);
```
> 有个问题:
>
> 1、我们知道,grup是异步执行的,那么上面的 less任务和 css任务会异步执行,但是有这个情况就是 less任务量非常大,事件消耗长,而css任务很小,那么有可能 css执行完了 less还没有执行完,也就没有生成 css 任务需要的 css文件,这个时候 css的任务执行就没有包括 less生成的 css文件,相当于 less的任务白做了。
>
> 2、所以,为了保证任务的执行先后,grup也可以同步执行,在gulp.task中传入一个数组,里面是处理当前任务所要依赖的任务,只有依赖的任务完成之后,才会执行当前任务。
>
> 3、所以,grup其实可以同步可以异步,但是它的异步才是它最大的卖点。

**4、页面引入css测试**
```
<link rel="stylesheet" href="dist/css/built.min.css">
<div id="div1" class="index1">div1111111</div>
<div id="div2" class="index2">div2222222</div>
```
### 3、压缩html
**1、下载插件**
```
npm install gulp-htmlmin --save-dev
```
**2、配置gulpfile.js**
```js
var htmlmin = require('gulp-htmlmin');
//压缩html任务
gulp.task('htmlMinify', function() {
return gulp.src('index.html')
.pipe(htmlmin({collapseWhitespace: true})) // 去除多余的空格
.pipe(gulp.dest('dist/'));
});
gulp.task('default', ['minifyjs', 'cssTask', 'htmlMinify']);
```
**3、修改页面引入路径**
```html
<link rel="stylesheet" href="css/built.min.css">
<script type="text/javascript" src="js/built.min.js"></script>
```
### 4、半自动编译
我们在 grunt 中有个watch插件,可以实时监视源文件的变化,那么在 gulp中也有类似的插件,叫做`gulp-livereload` 。
**1、下载插件**
```
npm install gulp-livereload --save-dev
```
**2、配置gulpfile.js**
```js
var livereload = require('gulp-livereload');
//每个任务的最后都应该加上下面这一句
.pipe(livereload());
gulp.task('watch', ['default'], function () {
//开启监视
livereload.listen();
//监视指定的文件, 并指定对应的处理任务
gulp.watch('src/js/*.js', ['minifyjs'])
gulp.watch(['src/css/*.css','src/less/*.less'], ['cssTask','lessTask']);
});
```
> 注意:
>
> 1、watch 任务执行代码,一定要先执行 default 任务,也就是要把 default 作为 watch 任务的依赖。
>
> 2、在default里的每个任务的最后要接一个管道`.pipe(livereload());`来保证源文件修改后执行watch任务后,重新刷新到页面。

### 5、全自动编译
上面半自动编译的过程,我们可以看到在我们对源码编译保存后,还需要手动刷新浏览器,能不能在我修改源文件保存后自动刷新到浏览器显示呢?
**1、下载插件gulp-connect**
```
npm install gulp-connect --save-dev
```
**2、配置 gulpfile.js**
```js
var connect = require("gulp-connect");
//每个任务的最后都应该加上下面这一句
.pipe(connect.reload());
// 全自动任务
gulp.task('server', ['default'], function () {
connect.server({
// 最后要生成的源文件的路径
root: 'dist/',
// 开启实时刷新
livereload: true,
// 开启服务器的端口号
port: 1000
});
// 监视的源文件
gulp.watch('src/js/*.js', ['js']);
gulp.watch(['src/css/*.css', 'src/less/*.less'], ['css']);
});
```

问题:每次我还是要复制链接`http://localhost:1000/` 到浏览器打开网页查看,还是很麻烦哦,能不能自动打开网页?^_^
0.o 额你也太懒了....不过我还是有办法解决的。
**1、下载插件:open**
```
npm install open --save-dev
```
**2、配置(只需要加上一句open(你的链接);)**
```js
var open = require("open");
gulp.task('server', ['default'], function () {
connect.server({
// 最后要生成的源文件的路径
root: 'dist/',
// 开启实时刷新
livereload: true,
// 开启服务器的端口号
port: 1000
});
// 自动打开链接
open("http://localhost:1000/");
// 监视的源文件
gulp.watch('src/js/*.js', ['js']);
gulp.watch(['src/css/*.css', 'src/less/*.less'], ['css']);
});
```

## 五、插件打包加载
插件打包加载的好处是,我们不需要每次在 gulpfile.js 的开始定义插件的方法,而是用一个对象,这个对象的属性中包含所有用到的插件的方法。
**1、将所有需要的插件都下载好。**
```
npm install gulp-concat gulp-uglify gulp-rename gulp-clean-css gulp-connect gulp-htmlmin gulp-less gulp-livereload open --save-dev
```
**2、下载打包插件: gulp-load-plugins**
```
npm install gulp-load-plugins --save-dev
```
**3、在gulpfile.js引入**
```js
var $ = require('gulp-load-plugins')();
```
注意:引入的插件是个方法,调用之后的返回值就是我们需要的对象,这个对象中包含之前引入的所有插件的方法,以后用到哪个插件的方法,直接使用 `$.方法` 的方式即可。
```js
var gulp = require("gulp");
var $ = require("gulp-load-plugins")();
// var concat = require("gulp-concat");
// var uglify = require("gulp-uglify");
// var rename = require("gulp-rename");
// var less = require("gulp-less");
// var cleanCss = require("gulp-clean-css");
// var htmlmin = require("gulp-htmlmin");
// var livereload = require("gulp-livereload");
// var connect = require("gulp-connect");
var open = require("open");
// 合并压缩js
gulp.task('js', function () {
return gulp.src('src/js/*.js')
.pipe($.concat('build.js'))
.pipe(gulp.dest('dist/js/'))
.pipe($.uglify())
.pipe($.rename({
suffix: '.min'
}))
.pipe(gulp.dest('dist/js/'))
.pipe($.livereload())
.pipe($.connect.reload());
});
// less编译为css
gulp.task('less', function () {
return gulp.src("src/less/*.less")
.pipe($.less())
.pipe(gulp.dest("src/css/"))
.pipe($.livereload())
.pipe($.connect.reload());
});
// css合并压缩
gulp.task('css', ['less'], function () {
return gulp.src('src/css/*.css')
.pipe($.concat("build.css"))
.pipe(gulp.dest('dist/css/'))
.pipe($.cleanCss({
compatibility: 'ie8'
}))
.pipe($.rename({
suffix: '.min'
}))
.pipe(gulp.dest('dist/css/'))
.pipe($.livereload())
.pipe($.connect.reload());
});
// html压缩
gulp.task('html', function () {
return gulp.src('index.html')
.pipe($.htmlmin({
collapseWhitespace: true
}))
.pipe(gulp.dest('dist/'))
.pipe($.livereload())
.pipe($.connect.reload());
});
// 半自动编译
gulp.task('watch', ['default'], function () {
$.livereload.listen();
gulp.watch('src/js/*.js', ['js']);
gulp.watch(['src/css/*.css', 'src/less/*.less'], ['css']);
});
// 全自动编译
gulp.task('server', ['default'], function () {
$.connect.server({
// 最后要生成的源文件的路径
root: 'dist/',
// 开启实时刷新
livereload: true,
// 开启服务器的端口号
port: 1000
});
// 自动打开链接
open("http://localhost:1000/");
// 监视的源文件
gulp.watch('src/js/*.js', ['js']);
gulp.watch(['src/css/*.css', 'src/less/*.less'], ['css']);
});
gulp.task('default', ['js', 'less', 'css', 'html']);
```
> 注意:
>
> 1、gulp-load-plugins 中没有 open 方法,open插件需要单独引入。
>
> 2、`$` 包含的方法有个规律,就是它的方法的命名一般都是插件的除去grup的剩下单词的组合,比如 gulp-rename 插件对应的方法,在`$`对象中就是 `$.less` ,gulp-clean-css 插件比较特殊,因为后面两个单词,所以在 `$` 中的方法遵循驼峰命名法,就是 `$.cleanCss` 。
 | Daotin/Web/11-自动化构建/02-Gulp.md/0 | {
"file_path": "Daotin/Web/11-自动化构建/02-Gulp.md",
"repo_id": "Daotin",
"token_count": 7720
} | 21 |
举例示例内容链接到上一篇 **Vue的组件**
---
<!-- TOC -->
- [一、slot内容插槽](#一slot内容插槽)
- [1、slot的基本使用](#1slot的基本使用)
- [2、具名slot](#2具名slot)
- [3、slot-scope](#3slot-scope)
- [补充](#3补充)
<!-- /TOC -->
## 一、slot内容插槽
### 1、slot的基本使用
现在我们在component文件夹新建一个组件Box.js
```js
// Box.js
export let Box = {
template: require('./Box.html')
}
```
```html
<div>
<h4>我是Box组件</h4>
</div>
```
这时候我们在Home中调用Box组件。
```js
import { Header } from '../components/Header'
import { A } from '../components/A'
import { B } from '../components/B'
import { Box } from '../components/Box'
export let Home = {
template: `
<div>
<Header :title="title"></Header>
<h1>首页</h1>
<A @countChange="change"></A>
<B :cCount="count"></B>
<Box></Box>
</div>
`,
data() {
return {
title: '首页的title',
count: 0
}
},
methods: {
change(count) {
console.log(count);
this.count = count;
}
},
components: { Header, A, B, Box }
}
```
这时候如何我们往`<Box></Box>`中插入一个按钮代码会怎么?会显示按钮吗?
```html
<Box>
<button>我是按钮</button>
</Box>
```
答案是不会显示的。但是我们就想在子组件中插入其他标签怎么办呢?
这时候就用到了vue的内容插槽slot。
我们在Box.html代码里面写上:
```html
<div>
<h4>我是Box组件</h4>
<slot />
</div>
```
`<slot />` 代码位置就会被按钮标签代替。
> **slot的作用是:父组件在调用子组件的时候,往子组件中插入内容会出现在子组件slot标签的位置来替换slot标签,就相当于在子组件中形成了一个内容插槽,里面的内容可以由父组件进行选择性填充。**
### 2、具名slot
> 注意:本章节 `具名slot` 方法在 2.6.0 后已废弃,新的使用具名插槽方法参看《补充》章节。
现在有一个问题就是父组件想将不同的标签插入到不同的slot中怎么办?
原来的slot会把父组件在子组件插入的所有内容全部替换slot,没有区分。所以为了区分,我们给slot加个名字。
我们想在header,main和footer分别插入不同的内容。
```html
<!--Box.html-->
<div>
<h4>我是Box组件</h4>
<header>
<slot name="h" />
</header>
<main>
<slot />
</main>
<footer>
<slot name="f" />
</footer>
</div>
```
> 当子组件中存在多个slot时,我们可以给不同的slot加上name属性。
>
> 在父级内,给不同的内容添加上slot属性,设置对应的名字,即可将内容显示在子组件的对应位置。
父组件的template这样写,使用`slot='名称'`的方式插入到子组件name为‘名称’的地方。
没有名称的就插入到没有名称的地方。
```js
// Home.js
// ...
export let Home = {
template: `
<div>
<Header :title="title"></Header>
<h1>首页</h1>
<A @countChange="change"></A>
<B :cCount="count"></B>
<Box>
<h3 slot='h'>头部</h3>
<p>中部</p>
<button slot='f'>底部</button>
</Box>
</div>
`,
//...
components: { Header, A, B, Box }
}
```
*(added in 20190715)*
### 编译作用域
当你想在一个插槽中使用数据时,例如:
```html
<Box url="/app">
<h3>头部{{ user.name }}</h3>
</Box>
```
该插槽跟 Box 一样可以访问相同的实例属性 (父组件的数据),而**不能**访问 `<Box>` 的里面的数据。例如 `url` 是访问不到的:
也就是说,**子组件的插槽和子组件本身都可以访问父组件的数据,但是子组件的插槽访问不到子组件本身的数据。**
如何让子组件中的插槽访问到子组件本身的数据?
往下看:
### 3、作用域插槽slot-scope
> 注意:自 2.6.0 起有所更新。 `slot-scope` 已废弃,更新内容见《补充》章节。
**使用场景:子组件中的插槽需要用到子组件的数据,这时候会使用slot-scope。也就是子组件向子组件里面插槽的内容传递数据。**
这时候,父组件可以获取到Box组件中的数据,`<Box>{ {Box的data中的属性} }</Box>` ,但是如果这个数据写在里面的内容上就获取不到了。比如获取count属性,如下面这样:
```js
// Home.js
// ...
export let Home = {
template: `
<div>
<Header :title="title"></Header>
<h1>首页</h1>
<A @countChange="change"></A>
<B :cCount="count"></B>
<Box>
<h3 slot='h'>头部{{count}}</h3>
<p>中部</p>
<button slot='f'>底部</button>
</Box>
</div>
`,
//...
components: { Header, A, B, Box }
}
```
看起来h3在Box内部,其实不然。那么怎么在Box中间的内容中获取到子组件的数据呢?
> 在子组件的slot标签上使用自定义属性的方式传递数据
```html
<div>
<h4>我是Box组件</h4>
<header>
<slot name="h" :dcount="count" />
</header>
<main>
<slot />
</main>
<footer>
<slot name="f" />
</footer>
</div>
```
然后在父组件的template中:
```js
//...
export let Home = {
template: `
<div>
<Header :title="title"></Header>
<h1>首页</h1>
<A @countChange="change"></A>
<B :cCount="count"></B>
<Box>
<h3 slot='h' slot-scope='BoxData'>头部{ {BoxData.dcount}}</h3>
<p>中部</p>
<button slot='f'>底部</button>
</Box>
</div>
`,
//...
components: { Header, A, B, Box }
}
```
上面的`<h3 slot='h' slot-scope='BoxData'>头部{ {BoxData.dcount}}</h3>` 就从子组件的内容上获得子组件的数据。
*(added in 20190715)*
### 补充
> 在 2.6.0 中,我们为具名插槽和作用域插槽引入了一个新的统一的语法 (即 `v-slot` 指令)。它取代了 `slot` 和 `slot-scope` 这两个目前已被废弃但未被移除且仍在[文档中](https://cn.vuejs.org/v2/guide/components-slots.html#废弃了的语法)的特性。
#### 具名插槽
有时我们需要多个插槽。例如对于一个带有如下模板的 `<base-layout>` 组件:
```html
<div class="container">
<header>
<!-- 我们希望把页头放这里 -->
</header>
<main>
<!-- 我们希望把主要内容放这里 -->
</main>
<footer>
<!-- 我们希望把页脚放这里 -->
</footer>
</div>
```
对于这样的情况,`<slot>` 元素有一个特殊的特性:`name`。这个特性可以用来定义额外的插槽:
```html
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
```
> 一个不带 `name` 的 `<slot>` 出口会带有隐含的名字`default`。
在向具名插槽提供内容的时候,我们可以在元素上使用 `v-slot` 指令,并以 `v-slot` 的参数的形式提供其名称:
```html
<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>
```
> Tips:已废弃的方案采用的是 `slot="header"` 的方式。
现在元素中的所有内容都将会被传入相应的插槽。
任何没有被包裹在带有 `v-slot` 元素的中的内容都会被视为`默认插槽`的内容。
然而,如果你希望更明确一些,仍然可以在元素中包裹`默认插槽`的内容:
```html
<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<template v-slot:default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>
```
#### 作用域插槽
> 以下内容来自官网文档:
当你想在一个插槽中使用数据时,例如:
```html
<navigation-link url="/profile">
Logged in as {{ user.name }}
</navigation-link>
```
该插槽跟当前模板的其它地方一样可以访问data的数据,而不能访问子组件 `<navigation-link>` 的作用域。例如 `url` 是访问不到的:
```html
<navigation-link url="/profile">
Clicking here will send you to: {{ url }}
<!--
这里的 `url` 会是 undefined,因为其 (指该插槽的) 内容是
_传递给_ <navigation-link> 的而不是
在 <navigation-link> 组件*内部*定义的。
-->
</navigation-link>
```
作为一条规则,请记住:
> **父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。**
| Daotin/Web/12-Vue/08-内容插槽slot.md/0 | {
"file_path": "Daotin/Web/12-Vue/08-内容插槽slot.md",
"repo_id": "Daotin",
"token_count": 5578
} | 22 |
## 什么是混入
混入(mixin)相当于从一个组件中抽出公共的部分形成的一个对象。
这个对象可以包含任意组件选项(如,data,created等,组件有的属性,它都可以有)。
例如:
```js
// 定义一个混入对象
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// 定义一个使用混入对象的组件
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // => "hello from mixin!"
```
相当于混入是一个组件的一些属性的集合。但是混入也有一些特性:
## 混入特性
### 选项合并
**1、对于data中的数据**
当组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”。
比如,数据对象在内部会进行递归合并,并在发生冲突时**以组件数据优先**。
```js
var mixin = {
data: function () {
return {
message: 'hello',
foo: 'abc'
}
}
}
new Vue({
mixins: [mixin],
data: function () {
return {
message: 'goodbye',
bar: 'def'
}
},
created: function () {
console.log(this.$data)
// => { message: "goodbye", foo: "abc", bar: "def" }
}
})
```
**2、对于钩子函数**
同名钩子函数将**合并为一个数组**,因此都将被调用。
> 混入对象的钩子将在组件自身钩子之前调用。
```js
var mixin = {
created: function () {
console.log('混入对象的钩子被调用')
}
}
new Vue({
mixins: [mixin],
created: function () {
console.log('组件钩子被调用')
}
})
// => "混入对象的钩子被调用"
// => "组件钩子被调用"
```
**3、值为对象的属性**
值为对象的选项,例如 `methods`、`components` 和 `directives`,将被合并为同一个对象。
两个对象键名冲突时,取**组件对象**的键值对。
```js
var mixin = {
methods: {
foo: function () {
console.log('foo')
},
conflicting: function () {
console.log('from mixin')
}
}
}
var vm = new Vue({
mixins: [mixin],
methods: {
bar: function () {
console.log('bar')
},
conflicting: function () {
console.log('from self')
}
}
})
vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"
```
### 全局混入
混入也可以进行全局注册。使用时格外小心!一旦使用全局混入,它将影响每一个之后创建的 Vue 实例。使用恰当时,这可以用来为自定义选项注入处理逻辑。
```js
// 为自定义的选项 'myOption' 注入一个处理器。
Vue.mixin({
created: function () {
var myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
new Vue({
myOption: 'hello!'
})
// => "hello!"
```
### 自定义选项合并策略
自定义选项将使用默认策略,即简单地覆盖已有值。如果想让自定义选项以自定义逻辑合并,可以向 `Vue.config.optionMergeStrategies` 添加一个函数:
```js
Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) {
// 返回合并后的值
}
```
| Daotin/Web/12-Vue/混入.md/0 | {
"file_path": "Daotin/Web/12-Vue/混入.md",
"repo_id": "Daotin",
"token_count": 1852
} | 23 |
## 项目介绍
📚 本项目为从零开始学 Web 前端系列图文教程。从零基础开始,手把手教你进入前端开发的世界。从入门到进阶,我们一同前行。



对于非计算机专业的我来说,初学前端领域的时候,常常因为找不到适合零基础自学的教程感到无助,即使找到了一些学习资料,也因为零零散散不成体系而让人困惑,所以才有了本教程。
- 希望能够帮助到想要踏入前端的你,免去找资料的痛苦。
- 也可以帮自己梳理前端知识体系,遇到问题的时候可以更加方便地定位检索相关的知识点。
## 阅读指引
- 项目地址:https://github.com/Daotin/Web
- 如果网络较慢,或者图片显示不出,可以进入 Gitee 项目同步地址:https://gitee.com/Daotin/Web
- 建议 Chrome 用户下载 `Octotree` 或者 `GayHub` 插件,查看目录文件更方便
## 个人博客
基于 Jekyll 的个人博客 https://daotin.github.io ,分享工作和生活,欢迎 star!(*/ω\*)
| Daotin/Web/README.md/0 | {
"file_path": "Daotin/Web/README.md",
"repo_id": "Daotin",
"token_count": 790
} | 24 |
/*
Navicat Premium Data Transfer
Source Server : 阿里云MySQL
Source Server Type : MySQL
Source Server Version : 50718
Source Host : rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306
Source Schema : web
Target Server Type : MySQL
Target Server Version : 50718
File Encoding : 65001
Date: 07/03/2018 09:59:42
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for message_area
-- ----------------------------
DROP TABLE IF EXISTS `message_area`;
CREATE TABLE `message_area` (
`message_id` int(32) NOT NULL AUTO_INCREMENT,
`message_parent` int(32) NOT NULL,
`message_belong` int(32) NOT NULL,
`message_content` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`message_date` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0),
`message_email` char(40) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
`message_username` char(40) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
PRIMARY KEY (`message_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
| Humsen/web/docs/数据库部署/第1步 - 创建数据库/message_area.sql/0 | {
"file_path": "Humsen/web/docs/数据库部署/第1步 - 创建数据库/message_area.sql",
"repo_id": "Humsen",
"token_count": 462
} | 25 |
package pers.husen.web.bean.vo;
import java.util.Date;
/**
* @author 何明胜
*
* 2017年9月25日
*/
public class MessageAreaVo {
private int messageId;
private int messageParent;
private int messageBelong;
private String messageContent;
private Date messageDate;
private String messageEmail;
private String messageUsername;
/**
* @return the messageId
*/
public int getMessageId() {
return messageId;
}
/**
* @return the messageEmail
*/
public String getMessageEmail() {
return messageEmail;
}
/**
* @param messageEmail the messageEmail to set
*/
public void setMessageEmail(String messageEmail) {
this.messageEmail = messageEmail;
}
/**
* @param messageId the messageId to set
*/
public void setMessageId(int messageId) {
this.messageId = messageId;
}
/**
* @return the messageParent
*/
public int getMessageParent() {
return messageParent;
}
/**
* @param messageParent the messageParent to set
*/
public void setMessageParent(int messageParent) {
this.messageParent = messageParent;
}
/**
* @return the messageBelong
*/
public int getMessageBelong() {
return messageBelong;
}
/**
* @param messageBelong the messageBelong to set
*/
public void setMessageBelong(int messageBelong) {
this.messageBelong = messageBelong;
}
/**
* @return the messageContent
*/
public String getMessageContent() {
return messageContent;
}
/**
* @param messageContent the messageContent to set
*/
public void setMessageContent(String messageContent) {
this.messageContent = messageContent;
}
/**
* @return the messageDate
*/
public Date getMessageDate() {
return messageDate;
}
/**
* @param messageDate the messageDate to set
*/
public void setMessageDate(Date messageDate) {
this.messageDate = messageDate;
}
@Override
public String toString() {
return "MessageAreaVo [messageId=" + messageId + ", messageParent=" + messageParent + ", messageBelong="
+ messageBelong + ", messageContent=" + messageContent + ", messageDate=" + messageDate
+ ", mseeageEmail=" + messageEmail + ", messageUsername=" + messageUsername + "]";
}
/**
* @return the messageUsername
*/
public String getMessageUsername() {
return messageUsername;
}
/**
* @param messageUsername the messageUsername to set
*/
public void setMessageUsername(String messageUsername) {
this.messageUsername = messageUsername;
}
}
| Humsen/web/web-core/src/pers/husen/web/bean/vo/MessageAreaVo.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/bean/vo/MessageAreaVo.java",
"repo_id": "Humsen",
"token_count": 775
} | 26 |
package pers.husen.web.common.helper;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @desc MD5加密工具
*
* @author 何明胜
*
* @created 2017年12月29日 上午10:56:47
*/
public class Md5EncryptHelper {
private static final String KEY_MD5 = "MD5";
/** 全局数组 */
private static final String[] STRING_DIGITS = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
/**
* 返回形式为数字跟字符串
* @param bByte
* @return
*/
private static String byteToArrayString(byte bByte) {
int iRet = bByte;
if (iRet < 0) {
iRet += 256;
}
int iD1 = iRet / 16;
int iD2 = iRet % 16;
return STRING_DIGITS[iD1] + STRING_DIGITS[iD2];
}
/**
* 转换字节数组为16进制字串
* @param bByte
* @return
*/
private static String byteToString(byte[] bByte) {
StringBuilder sBuffer = new StringBuilder();
for (byte b : bByte) {
sBuffer.append(byteToArrayString(b));
}
return sBuffer.toString();
}
/**
* MD5加密
* @param strObj
* @return
* @throws Exception
*/
public static String getMD5Code(String strObj){
MessageDigest md = null;
try {
md = MessageDigest.getInstance(KEY_MD5);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// md.digest() 该函数返回值为存放哈希值结果的byte数组
return byteToString(md.digest(strObj.getBytes()));
}
public static void main(String[] args) {
try {
System.out.println(getMD5Code("123123"));
System.out.println(getMD5Code("123123").length());
} catch (Exception e) {
e.printStackTrace();
}
}
} | Humsen/web/web-core/src/pers/husen/web/common/helper/Md5EncryptHelper.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/common/helper/Md5EncryptHelper.java",
"repo_id": "Humsen",
"token_count": 905
} | 27 |
package pers.husen.web.dao;
import java.util.ArrayList;
import pers.husen.web.bean.vo.CodeLibraryVo;
/**
* @author 何明胜
*
* 2017年9月28日
*/
public interface CodeLibraryDao {
/**
* 根据条件查询代码库数量
* @param cVo
* @return
*/
public int queryCodeTotalCount(CodeLibraryVo cVo);
/**
* 根据条件查询某一页的代码库
* @param cVo
* @param pageSize
* @param pageNo
* @return
*/
public ArrayList<CodeLibraryVo> queryCodeLibraryPerPage(CodeLibraryVo cVo, int pageSize, int pageNo);
/**
* 根据Id查询单独一处代码
* @param codeId
* @return
*/
public CodeLibraryVo queryPerCodeById(int codeId);
/**
* 插入新纪录到代码库,返回id
*
* @param cVo
* @return
*/
public int insertCodeLibrary(CodeLibraryVo cVo);
/**
* 根据id更新代码库代码阅读次数
* @param codeId
* @return
*/
public int updateCodeReadById(int codeId);
/**
* 根据id修改代码内容
* @param cVo
* @return
*/
public int updateCodeById(CodeLibraryVo cVo);
/**
* 根据id逻辑删除代码
* @param blogId
* @return
*/
public int logicDeleteCodeById(int blogId);
/**
* 根据id查找上一篇有效代码
* @param codeId
* @return
*/
public CodeLibraryVo queryPreviousCode(int codeId);
/**
* 根据id查找下一篇有效代码
* @param codeId
* @return
*/
public CodeLibraryVo queryNextCode(int codeId);
} | Humsen/web/web-core/src/pers/husen/web/dao/CodeLibraryDao.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dao/CodeLibraryDao.java",
"repo_id": "Humsen",
"token_count": 669
} | 28 |
package pers.husen.web.dbutil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pers.husen.web.dbutil.assist.DbConnectUtils;
import pers.husen.web.dbutil.assist.SetPsParamUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
* 数据库操纵工具类 DML
*
* @author 何明胜
*
* 2017年9月29日
*/
public class DbManipulationUtils {
private static final Logger logger = LogManager.getLogger(DbManipulationUtils.class.getName());
/**
* 插入新纪录
*/
public static int insertNewRecord(String sql, ArrayList<Object> paramList) {
return dbManipulation(sql, paramList);
}
/**
* 执行更新
*/
public static int updateRecordByParam(String sql, ArrayList<Object> paramList) {
return dbManipulation(sql, paramList);
}
/**
* 逻辑删除
*/
public static int deleteRecordByParamLogic (String sql, ArrayList<Object> paramList) {
return dbManipulation(sql, paramList);
}
/**
* 物理删除
*/
public static int deleteRecordByParamPhysical(String sql, ArrayList<Object> paramList) {
return dbManipulation(sql, paramList);
}
/**
* 数据库更新通用
*/
public static int dbManipulation(String sql, ArrayList<Object> paramList) {
Connection conn = DbConnectUtils.getConnection();
PreparedStatement ps = null;
int result = -1;
try {
ps=conn.prepareStatement(sql);
if (paramList != null && paramList.size() != 0) {
for(int i=0; i<paramList.size(); i++) {
SetPsParamUtils.setParamInit(i+1, paramList.get(i), ps);
}
logger.info(ps);
result = ps.executeUpdate();
}
}catch (Exception e) {
logger.error(e);
}finally {
ResultSet rs = null;
DbConnectUtils.closeResouce(rs, ps, conn);
}
return result;
}
} | Humsen/web/web-core/src/pers/husen/web/dbutil/DbManipulationUtils.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dbutil/DbManipulationUtils.java",
"repo_id": "Humsen",
"token_count": 760
} | 29 |
/**
* 个人网站 web
*
* @author 何明胜
*
* 2017年10月21日
*/
package pers.husen.web; | Humsen/web/web-core/src/pers/husen/web/package-info.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/package-info.java",
"repo_id": "Humsen",
"token_count": 50
} | 30 |
package pers.husen.web.servlet.article;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import pers.husen.web.bean.vo.CodeLibraryVo;
import pers.husen.web.common.constants.CommonConstants;
import pers.husen.web.common.constants.RequestConstants;
import pers.husen.web.common.helper.TypeConvertHelper;
import pers.husen.web.service.CodeLibrarySvc;
/**
* 上传代码, 可能是新的,也可能是编辑
*
* @author 何明胜
*
* 2017年11月7日
*/
@WebServlet(urlPatterns = "/code/upload.hms")
public class CodeUploadSvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public CodeUploadSvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取文章细节
String newArticle = request.getParameter("newArticle");
// 转化为json
JSONObject jsonObject = JSONObject.fromObject(newArticle);
// 转化为bean
CodeLibraryVo cVo = TypeConvertHelper.jsonObj2CodeBean(jsonObject);
// 如果不是以逗号分隔的,关键字之间的多个空格都处理为一个
String codeLabel = cVo.getCodeLabel();
if (codeLabel.indexOf(CommonConstants.ENGLISH_COMMA) == -1
&& codeLabel.indexOf(CommonConstants.CHINESE_COMMA) == -1) {
cVo.setCodeLabel(codeLabel.replaceAll("\\s+", " "));
}
if (codeLabel.indexOf(CommonConstants.CHINESE_COMMA) != -1) {
cVo.setCodeLabel(codeLabel.replace(",", ","));
}
CodeLibrarySvc cSvc = new CodeLibrarySvc();
PrintWriter out = response.getWriter();
String uploadType = request.getParameter("type");
/** 如果是修改代码 */
if (RequestConstants.REQUEST_TYPE_MODIFY.equals(uploadType)) {
// 获取id
int codeId = Integer.parseInt(request.getParameter("articleId"));
// 设置id
cVo.setCodeId(codeId);
int resultInsert = cSvc.updateCodeById(cVo);
out.println(resultInsert);
return;
}
/** 如果是上传新代码 */
if (RequestConstants.REQUEST_TYPE_CREATE.equals(uploadType)) {
int insertResult = cSvc.insertCodeLibrary(cVo);
out.println(insertResult);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/article/CodeUploadSvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/article/CodeUploadSvt.java",
"repo_id": "Humsen",
"token_count": 1007
} | 31 |
package pers.husen.web.servlet.releasefea;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import pers.husen.web.bean.vo.ReleaseFeatureVo;
import pers.husen.web.common.constants.RequestConstants;
import pers.husen.web.common.helper.TypeConvertHelper;
import pers.husen.web.service.ReleaseFeatureSvc;
/**
* 上传新的版本特性
*
* @author 何明胜
*
* 2017年10月20日
*/
@WebServlet(urlPatterns="/editRlseFetr.hms")
public class EditRlseFetrSvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public EditRlseFetrSvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String newArticle = request.getParameter("newArticle");
JSONObject jsonObject = JSONObject.fromObject(newArticle);
ReleaseFeatureVo rVo = TypeConvertHelper.jsonObj2ReleaseBean(jsonObject);
ReleaseFeatureSvc rSvc = new ReleaseFeatureSvc();
PrintWriter out = response.getWriter();
int result = 0;
String requestType = request.getParameter("type");
/** 如果是请求创建新版本 */
if(RequestConstants.REQUEST_TYPE_CREATE.equals(requestType)) {
result = rSvc.insertReleaseFeature(rVo);
out.println(result);
return;
}
/** 如果是请求编辑版本 */
if(RequestConstants.REQUEST_TYPE_MODIFY.equals(requestType)) {
String releaseId = request.getParameter("releaseId");
if(releaseId != null) {
rVo.setReleaseId(Integer.parseInt(releaseId));
result = rSvc.updateReleaseContentById(rVo);
}
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/releasefea/EditRlseFetrSvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/releasefea/EditRlseFetrSvt.java",
"repo_id": "Humsen",
"token_count": 764
} | 32 |
@charset "UTF-8";
.forget-pwd {
margin-left: 12%;
}
.navbar-bottom {
text-align: center;
background-color: whitesmoke;
}
.login-title {
margin: 0;
}
.qq-fixed-bottom {
bottom: 20px;
margin-bottom: 0;
border-width: 1px 0 0;
} | Humsen/web/web-mobile/WebContent/css/login/login.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/css/login/login.css",
"repo_id": "Humsen",
"token_count": 108
} | 33 |
<!-- 放在login.jsp里面 -->
<!-- 右侧固定栏 -->
<link rel="stylesheet" href="/css/navigation/rightbar.css" />
<div id="rightBar">
<div>
<div class="sidebar-module">
<h4>关于本站</h4>
<p> 欢迎来到何明胜的个人网站.</p>
<p>体验账户:husen,密码:admin123,登录可以看到后台菜单,并体检管理员权限,盼文明操作。此代码为初级Java web项目,已停止维护,仅供参考。</p>
<p>本站源码已托管github。欢迎访问:<br/>
<a href="https://github.com/HelloHusen/web" target="_blank">https://github.com/CrazyHusen/web</a>
</p>
</div>
<div class="sidebar-module">
<h4>我的其他主页</h4>
<ol class="list-unstyled">
<li><a href="http://blog.csdn.net/qq_24879495" target="_blank">CSDN博客 一格的程序人生</a></li>
<li><a href="https://github.com/CrazyHusen/" target="_blank">GitHub 何明胜</a></li>
</ol>
</div>
</div>
</div> | Humsen/web/web-mobile/WebContent/module/navigation/rightbar.html/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/module/navigation/rightbar.html",
"repo_id": "Humsen",
"token_count": 559
} | 34 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// Open simple dialogs on top of an editor. Relies on dialog.css.
(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) {
function dialogDiv(cm, template, bottom) {
var wrap = cm.getWrapperElement();
var dialog;
dialog = wrap.appendChild(document.createElement("div"));
if (bottom)
dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
else
dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
if (typeof template == "string") {
dialog.innerHTML = template;
} else { // Assuming it's a detached DOM element.
dialog.appendChild(template);
}
return dialog;
}
function closeNotification(cm, newVal) {
if (cm.state.currentNotificationClose)
cm.state.currentNotificationClose();
cm.state.currentNotificationClose = newVal;
}
CodeMirror.defineExtension("openDialog", function(template, callback, options) {
if (!options) options = {};
closeNotification(this, null);
var dialog = dialogDiv(this, template, options.bottom);
var closed = false, me = this;
function close(newVal) {
if (typeof newVal == 'string') {
inp.value = newVal;
} else {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
me.focus();
if (options.onClose) options.onClose(dialog);
}
}
var inp = dialog.getElementsByTagName("input")[0], button;
if (inp) {
if (options.value) {
inp.value = options.value;
inp.select();
}
if (options.onInput)
CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
if (options.onKeyUp)
CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
CodeMirror.on(inp, "keydown", function(e) {
if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
inp.blur();
CodeMirror.e_stop(e);
close();
}
if (e.keyCode == 13) callback(inp.value, e);
});
if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close);
inp.focus();
} else if (button = dialog.getElementsByTagName("button")[0]) {
CodeMirror.on(button, "click", function() {
close();
me.focus();
});
if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close);
button.focus();
}
return close;
});
CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
closeNotification(this, null);
var dialog = dialogDiv(this, template, options && options.bottom);
var buttons = dialog.getElementsByTagName("button");
var closed = false, me = this, blurring = 1;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
me.focus();
}
buttons[0].focus();
for (var i = 0; i < buttons.length; ++i) {
var b = buttons[i];
(function(callback) {
CodeMirror.on(b, "click", function(e) {
CodeMirror.e_preventDefault(e);
close();
if (callback) callback(me);
});
})(callbacks[i]);
CodeMirror.on(b, "blur", function() {
--blurring;
setTimeout(function() { if (blurring <= 0) close(); }, 200);
});
CodeMirror.on(b, "focus", function() { ++blurring; });
}
});
/*
* openNotification
* Opens a notification, that can be closed with an optional timer
* (default 5000ms timer) and always closes on click.
*
* If a notification is opened while another is opened, it will close the
* currently opened one and open the new one immediately.
*/
CodeMirror.defineExtension("openNotification", function(template, options) {
closeNotification(this, close);
var dialog = dialogDiv(this, template, options && options.bottom);
var closed = false, doneTimer;
var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;
function close() {
if (closed) return;
closed = true;
clearTimeout(doneTimer);
dialog.parentNode.removeChild(dialog);
}
CodeMirror.on(dialog, 'click', function(e) {
CodeMirror.e_preventDefault(e);
close();
});
if (duration)
doneTimer = setTimeout(close, duration);
return close;
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/dialog/dialog.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/dialog/dialog.js",
"repo_id": "Humsen",
"token_count": 1935
} | 35 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("./foldcode"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "./foldcode"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.clearGutter(cm.state.foldGutter.options.gutter);
cm.state.foldGutter = null;
cm.off("gutterClick", onGutterClick);
cm.off("change", onChange);
cm.off("viewportChange", onViewportChange);
cm.off("fold", onFold);
cm.off("unfold", onFold);
cm.off("swapDoc", updateInViewport);
}
if (val) {
cm.state.foldGutter = new State(parseOptions(val));
updateInViewport(cm);
cm.on("gutterClick", onGutterClick);
cm.on("change", onChange);
cm.on("viewportChange", onViewportChange);
cm.on("fold", onFold);
cm.on("unfold", onFold);
cm.on("swapDoc", updateInViewport);
}
});
var Pos = CodeMirror.Pos;
function State(options) {
this.options = options;
this.from = this.to = 0;
}
function parseOptions(opts) {
if (opts === true) opts = {};
if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
return opts;
}
function isFolded(cm, line) {
var marks = cm.findMarksAt(Pos(line));
for (var i = 0; i < marks.length; ++i)
if (marks[i].__isFold && marks[i].find().from.line == line) return true;
}
function marker(spec) {
if (typeof spec == "string") {
var elt = document.createElement("div");
elt.className = spec + " CodeMirror-guttermarker-subtle";
return elt;
} else {
return spec.cloneNode(true);
}
}
function updateFoldInfo(cm, from, to) {
var opts = cm.state.foldGutter.options, cur = from;
var minSize = cm.foldOption(opts, "minFoldSize");
var func = cm.foldOption(opts, "rangeFinder");
cm.eachLine(from, to, function(line) {
var mark = null;
if (isFolded(cm, cur)) {
mark = marker(opts.indicatorFolded);
} else {
var pos = Pos(cur, 0);
var range = func && func(cm, pos);
if (range && range.to.line - range.from.line >= minSize)
mark = marker(opts.indicatorOpen);
}
cm.setGutterMarker(line, opts.gutter, mark);
++cur;
});
}
function updateInViewport(cm) {
var vp = cm.getViewport(), state = cm.state.foldGutter;
if (!state) return;
cm.operation(function() {
updateFoldInfo(cm, vp.from, vp.to);
});
state.from = vp.from; state.to = vp.to;
}
function onGutterClick(cm, line, gutter) {
var state = cm.state.foldGutter;
if (!state) return;
var opts = state.options;
if (gutter != opts.gutter) return;
cm.foldCode(Pos(line, 0), opts.rangeFinder);
}
function onChange(cm) {
var state = cm.state.foldGutter;
if (!state) return;
var opts = state.options;
state.from = state.to = 0;
clearTimeout(state.changeUpdate);
state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, opts.foldOnChangeTimeSpan || 600);
}
function onViewportChange(cm) {
var state = cm.state.foldGutter;
if (!state) return;
var opts = state.options;
clearTimeout(state.changeUpdate);
state.changeUpdate = setTimeout(function() {
var vp = cm.getViewport();
if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
updateInViewport(cm);
} else {
cm.operation(function() {
if (vp.from < state.from) {
updateFoldInfo(cm, vp.from, state.from);
state.from = vp.from;
}
if (vp.to > state.to) {
updateFoldInfo(cm, state.to, vp.to);
state.to = vp.to;
}
});
}
}, opts.updateViewportTimeSpan || 400);
}
function onFold(cm, from) {
var state = cm.state.foldGutter;
if (!state) return;
var line = from.line;
if (line >= state.from && line < state.to)
updateFoldInfo(cm, line, line + 1);
}
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/fold/foldgutter.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/fold/foldgutter.js",
"repo_id": "Humsen",
"token_count": 1947
} | 36 |
/* The lint marker gutter */
.CodeMirror-lint-markers {
width: 16px;
}
.CodeMirror-lint-tooltip {
background-color: infobackground;
border: 1px solid black;
border-radius: 4px 4px 4px 4px;
color: infotext;
font-family: monospace;
font-size: 10pt;
overflow: hidden;
padding: 2px 5px;
position: fixed;
white-space: pre;
white-space: pre-wrap;
z-index: 100;
max-width: 600px;
opacity: 0;
transition: opacity .4s;
-moz-transition: opacity .4s;
-webkit-transition: opacity .4s;
-o-transition: opacity .4s;
-ms-transition: opacity .4s;
}
.CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning {
background-position: left bottom;
background-repeat: repeat-x;
}
.CodeMirror-lint-mark-error {
background-image:
url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==")
;
}
.CodeMirror-lint-mark-warning {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII=");
}
.CodeMirror-lint-marker-error, .CodeMirror-lint-marker-warning {
background-position: center center;
background-repeat: no-repeat;
cursor: pointer;
display: inline-block;
height: 16px;
width: 16px;
vertical-align: middle;
position: relative;
}
.CodeMirror-lint-message-error, .CodeMirror-lint-message-warning {
padding-left: 18px;
background-position: top left;
background-repeat: no-repeat;
}
.CodeMirror-lint-marker-error, .CodeMirror-lint-message-error {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII=");
}
.CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII=");
}
.CodeMirror-lint-marker-multiple {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC");
background-repeat: no-repeat;
background-position: right bottom;
width: 100%; height: 100%;
}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/lint/lint.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/lint/lint.css",
"repo_id": "Humsen",
"token_count": 1537
} | 37 |
.CodeMirror-simplescroll-horizontal div, .CodeMirror-simplescroll-vertical div {
position: absolute;
background: #ccc;
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid #bbb;
border-radius: 2px;
}
.CodeMirror-simplescroll-horizontal, .CodeMirror-simplescroll-vertical {
position: absolute;
z-index: 6;
background: #eee;
}
.CodeMirror-simplescroll-horizontal {
bottom: 0; left: 0;
height: 8px;
}
.CodeMirror-simplescroll-horizontal div {
bottom: 0;
height: 100%;
}
.CodeMirror-simplescroll-vertical {
right: 0; top: 0;
width: 8px;
}
.CodeMirror-simplescroll-vertical div {
right: 0;
width: 100%;
}
.CodeMirror-overlayscroll .CodeMirror-scrollbar-filler, .CodeMirror-overlayscroll .CodeMirror-gutter-filler {
display: none;
}
.CodeMirror-overlayscroll-horizontal div, .CodeMirror-overlayscroll-vertical div {
position: absolute;
background: #bcd;
border-radius: 3px;
}
.CodeMirror-overlayscroll-horizontal, .CodeMirror-overlayscroll-vertical {
position: absolute;
z-index: 6;
}
.CodeMirror-overlayscroll-horizontal {
bottom: 0; left: 0;
height: 6px;
}
.CodeMirror-overlayscroll-horizontal div {
bottom: 0;
height: 100%;
}
.CodeMirror-overlayscroll-vertical {
right: 0; top: 0;
width: 6px;
}
.CodeMirror-overlayscroll-vertical div {
right: 0;
width: 100%;
}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/scroll/simplescrollbars.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/scroll/simplescrollbars.css",
"repo_id": "Humsen",
"token_count": 554
} | 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"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("d", function(config, parserConfig) {
var indentUnit = config.indentUnit,
statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
keywords = parserConfig.keywords || {},
builtin = parserConfig.builtin || {},
blockKeywords = parserConfig.blockKeywords || {},
atoms = parserConfig.atoms || {},
hooks = parserConfig.hooks || {},
multiLineStrings = parserConfig.multiLineStrings;
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (hooks[ch]) {
var result = hooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == '"' || ch == "'" || ch == "`") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null;
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
if (ch == "/") {
if (stream.eat("+")) {
state.tokenize = tokenComment;
return tokenNestedComment(stream, state);
}
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
}
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
}
if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
stream.eatWhile(/[\w\$_\xa1-\uffff]/);
var cur = stream.current();
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "keyword";
}
if (builtin.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "builtin";
}
if (atoms.propertyIsEnumerable(cur)) return "atom";
return "variable";
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next, end = false;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {end = true; break;}
escaped = !escaped && next == "\\";
}
if (end || !(escaped || multiLineStrings))
state.tokenize = null;
return "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function tokenNestedComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = null;
break;
}
maybeEnd = (ch == "+");
}
return "comment";
}
function Context(indented, column, type, align, prev) {
this.indented = indented;
this.column = column;
this.type = type;
this.align = align;
this.prev = prev;
}
function pushContext(state, col, type) {
var indent = state.indented;
if (state.context && state.context.type == "statement")
indent = state.context.indented;
return state.context = new Context(indent, col, type, null, state.context);
}
function popContext(state) {
var t = state.context.type;
if (t == ")" || t == "]" || t == "}")
state.indented = state.context.indented;
return state.context = state.context.prev;
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: null,
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
indented: 0,
startOfLine: true
};
},
token: function(stream, state) {
var ctx = state.context;
if (stream.sol()) {
if (ctx.align == null) ctx.align = false;
state.indented = stream.indentation();
state.startOfLine = true;
}
if (stream.eatSpace()) return null;
curPunc = null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment" || style == "meta") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
else if (curPunc == "{") pushContext(state, stream.column(), "}");
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == "}") {
while (ctx.type == "statement") ctx = popContext(state);
if (ctx.type == "}") ctx = popContext(state);
while (ctx.type == "statement") ctx = popContext(state);
}
else if (curPunc == ctx.type) popContext(state);
else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
pushContext(state, stream.column(), "statement");
state.startOfLine = false;
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
var closing = firstChar == ctx.type;
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indented + (closing ? 0 : indentUnit);
},
electricChars: "{}"
};
});
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var blockKeywords = "body catch class do else enum for foreach foreach_reverse if in interface mixin " +
"out scope struct switch try union unittest version while with";
CodeMirror.defineMIME("text/x-d", {
name: "d",
keywords: words("abstract alias align asm assert auto break case cast cdouble cent cfloat const continue " +
"debug default delegate delete deprecated export extern final finally function goto immutable " +
"import inout invariant is lazy macro module new nothrow override package pragma private " +
"protected public pure ref return shared short static super synchronized template this " +
"throw typedef typeid typeof volatile __FILE__ __LINE__ __gshared __traits __vector __parameters " +
blockKeywords),
blockKeywords: words(blockKeywords),
builtin: words("bool byte char creal dchar double float idouble ifloat int ireal long real short ubyte " +
"ucent uint ulong ushort wchar wstring void size_t sizediff_t"),
atoms: words("exit failure success true false null"),
hooks: {
"@": function(stream, _state) {
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/d/d.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/d/d.js",
"repo_id": "Humsen",
"token_count": 3037
} | 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"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("kotlin", function (config, parserConfig) {
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var multiLineStrings = parserConfig.multiLineStrings;
var keywords = words(
"package continue return object while break class data trait throw super" +
" when type this else This try val var fun for is in if do as true false null get set");
var softKeywords = words("import" +
" where by get set abstract enum open annotation override private public internal" +
" protected catch out vararg inline finally final ref");
var blockKeywords = words("catch class do else finally for if where try while enum");
var atoms = words("null true false this");
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'") {
return startString(ch, stream, state);
}
// Wildcard import w/o trailing semicolon (import smth.*)
if (ch == "." && stream.eat("*")) {
return "word";
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null;
}
if (/\d/.test(ch)) {
if (stream.eat(/eE/)) {
stream.eat(/\+\-/);
stream.eatWhile(/\d/);
}
return "number";
}
if (ch == "/") {
if (stream.eat("*")) {
state.tokenize.push(tokenComment);
return tokenComment(stream, state);
}
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
if (expectExpression(state.lastToken)) {
return startString(ch, stream, state);
}
}
// Commented
if (ch == "-" && stream.eat(">")) {
curPunc = "->";
return null;
}
if (/[\-+*&%=<>!?|\/~]/.test(ch)) {
stream.eatWhile(/[\-+*&%=<>|~]/);
return "operator";
}
stream.eatWhile(/[\w\$_]/);
var cur = stream.current();
if (atoms.propertyIsEnumerable(cur)) {
return "atom";
}
if (softKeywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "softKeyword";
}
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "keyword";
}
return "word";
}
tokenBase.isBase = true;
function startString(quote, stream, state) {
var tripleQuoted = false;
if (quote != "/" && stream.eat(quote)) {
if (stream.eat(quote)) tripleQuoted = true;
else return "string";
}
function t(stream, state) {
var escaped = false, next, end = !tripleQuoted;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {
if (!tripleQuoted) {
break;
}
if (stream.match(quote + quote)) {
end = true;
break;
}
}
if (quote == '"' && next == "$" && !escaped && stream.eat("{")) {
state.tokenize.push(tokenBaseUntilBrace());
return "string";
}
if (next == "$" && !escaped && !stream.eat(" ")) {
state.tokenize.push(tokenBaseUntilSpace());
return "string";
}
escaped = !escaped && next == "\\";
}
if (multiLineStrings)
state.tokenize.push(t);
if (end) state.tokenize.pop();
return "string";
}
state.tokenize.push(t);
return t(stream, state);
}
function tokenBaseUntilBrace() {
var depth = 1;
function t(stream, state) {
if (stream.peek() == "}") {
depth--;
if (depth == 0) {
state.tokenize.pop();
return state.tokenize[state.tokenize.length - 1](stream, state);
}
} else if (stream.peek() == "{") {
depth++;
}
return tokenBase(stream, state);
}
t.isBase = true;
return t;
}
function tokenBaseUntilSpace() {
function t(stream, state) {
if (stream.eat(/[\w]/)) {
var isWord = stream.eatWhile(/[\w]/);
if (isWord) {
state.tokenize.pop();
return "word";
}
}
state.tokenize.pop();
return "string";
}
t.isBase = true;
return t;
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize.pop();
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function expectExpression(last) {
return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) ||
last == "newstatement" || last == "keyword" || last == "proplabel";
}
function Context(indented, column, type, align, prev) {
this.indented = indented;
this.column = column;
this.type = type;
this.align = align;
this.prev = prev;
}
function pushContext(state, col, type) {
return state.context = new Context(state.indented, col, type, null, state.context);
}
function popContext(state) {
var t = state.context.type;
if (t == ")" || t == "]" || t == "}")
state.indented = state.context.indented;
return state.context = state.context.prev;
}
// Interface
return {
startState: function (basecolumn) {
return {
tokenize: [tokenBase],
context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false),
indented: 0,
startOfLine: true,
lastToken: null
};
},
token: function (stream, state) {
var ctx = state.context;
if (stream.sol()) {
if (ctx.align == null) ctx.align = false;
state.indented = stream.indentation();
state.startOfLine = true;
// Automatic semicolon insertion
if (ctx.type == "statement" && !expectExpression(state.lastToken)) {
popContext(state);
ctx = state.context;
}
}
if (stream.eatSpace()) return null;
curPunc = null;
var style = state.tokenize[state.tokenize.length - 1](stream, state);
if (style == "comment") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
// Handle indentation for {x -> \n ... }
else if (curPunc == "->" && ctx.type == "statement" && ctx.prev.type == "}") {
popContext(state);
state.context.align = false;
}
else if (curPunc == "{") pushContext(state, stream.column(), "}");
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == "}") {
while (ctx.type == "statement") ctx = popContext(state);
if (ctx.type == "}") ctx = popContext(state);
while (ctx.type == "statement") ctx = popContext(state);
}
else if (curPunc == ctx.type) popContext(state);
else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
pushContext(state, stream.column(), "statement");
state.startOfLine = false;
state.lastToken = curPunc || style;
return style;
},
indent: function (state, textAfter) {
if (!state.tokenize[state.tokenize.length - 1].isBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), ctx = state.context;
if (ctx.type == "statement" && !expectExpression(state.lastToken)) ctx = ctx.prev;
var closing = firstChar == ctx.type;
if (ctx.type == "statement") {
return ctx.indented + (firstChar == "{" ? 0 : config.indentUnit);
}
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indented + (closing ? 0 : config.indentUnit);
},
electricChars: "{}"
};
});
CodeMirror.defineMIME("text/x-kotlin", "kotlin");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/kotlin/kotlin.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/kotlin/kotlin.js",
"repo_id": "Humsen",
"token_count": 3571
} | 40 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
var mode = CodeMirror.getMode({indentUnit: 2}, "php");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
MT('simple_test',
'[meta <?php] ' +
'[keyword echo] [string "aaa"]; ' +
'[meta ?>]');
MT('variable_interpolation_non_alphanumeric',
'[meta <?php]',
'[keyword echo] [string "aaa$~$!$@$#$$$%$^$&$*$($)$.$<$>$/$\\$}$\\\"$:$;$?$|$[[$]]$+$=aaa"]',
'[meta ?>]');
MT('variable_interpolation_digits',
'[meta <?php]',
'[keyword echo] [string "aaa$1$2$3$4$5$6$7$8$9$0aaa"]',
'[meta ?>]');
MT('variable_interpolation_simple_syntax_1',
'[meta <?php]',
'[keyword echo] [string "aaa][variable-2 $aaa][string .aaa"];',
'[meta ?>]');
MT('variable_interpolation_simple_syntax_2',
'[meta <?php]',
'[keyword echo] [string "][variable-2 $aaaa][[','[number 2]', ']][string aa"];',
'[keyword echo] [string "][variable-2 $aaaa][[','[number 2345]', ']][string aa"];',
'[keyword echo] [string "][variable-2 $aaaa][[','[number 2.3]', ']][string aa"];',
'[keyword echo] [string "][variable-2 $aaaa][[','[variable aaaaa]', ']][string aa"];',
'[keyword echo] [string "][variable-2 $aaaa][[','[variable-2 $aaaaa]',']][string aa"];',
'[keyword echo] [string "1aaa][variable-2 $aaaa][[','[number 2]', ']][string aa"];',
'[keyword echo] [string "aaa][variable-2 $aaaa][[','[number 2345]', ']][string aa"];',
'[keyword echo] [string "aaa][variable-2 $aaaa][[','[number 2.3]', ']][string aa"];',
'[keyword echo] [string "aaa][variable-2 $aaaa][[','[variable aaaaa]', ']][string aa"];',
'[keyword echo] [string "aaa][variable-2 $aaaa][[','[variable-2 $aaaaa]',']][string aa"];',
'[meta ?>]');
MT('variable_interpolation_simple_syntax_3',
'[meta <?php]',
'[keyword echo] [string "aaa][variable-2 $aaaa]->[variable aaaaa][string .aaaaaa"];',
'[keyword echo] [string "aaa][variable-2 $aaaa][string ->][variable-2 $aaaaa][string .aaaaaa"];',
'[keyword echo] [string "aaa][variable-2 $aaaa]->[variable aaaaa][string [[2]].aaaaaa"];',
'[keyword echo] [string "aaa][variable-2 $aaaa]->[variable aaaaa][string ->aaaa2.aaaaaa"];',
'[meta ?>]');
MT('variable_interpolation_escaping',
'[meta <?php] [comment /* Escaping */]',
'[keyword echo] [string "aaa\\$aaaa->aaa.aaa"];',
'[keyword echo] [string "aaa\\$aaaa[[2]]aaa.aaa"];',
'[keyword echo] [string "aaa\\$aaaa[[asd]]aaa.aaa"];',
'[keyword echo] [string "aaa{\\$aaaa->aaa.aaa"];',
'[keyword echo] [string "aaa{\\$aaaa[[2]]aaa.aaa"];',
'[keyword echo] [string "aaa{\\aaaaa[[asd]]aaa.aaa"];',
'[keyword echo] [string "aaa\\${aaaa->aaa.aaa"];',
'[keyword echo] [string "aaa\\${aaaa[[2]]aaa.aaa"];',
'[keyword echo] [string "aaa\\${aaaa[[asd]]aaa.aaa"];',
'[meta ?>]');
MT('variable_interpolation_complex_syntax_1',
'[meta <?php]',
'[keyword echo] [string "aaa][variable-2 $]{[variable aaaa]}[string ->aaa.aaa"];',
'[keyword echo] [string "aaa][variable-2 $]{[variable-2 $aaaa]}[string ->aaa.aaa"];',
'[keyword echo] [string "aaa][variable-2 $]{[variable-2 $aaaa][[',' [number 42]',']]}[string ->aaa.aaa"];',
'[keyword echo] [string "aaa][variable-2 $]{[variable aaaa][meta ?>]aaaaaa');
MT('variable_interpolation_complex_syntax_2',
'[meta <?php] [comment /* Monsters */]',
'[keyword echo] [string "][variable-2 $]{[variable aaa][comment /*}?>} $aaa<?php } */]}[string ->aaa.aaa"];',
'[keyword echo] [string "][variable-2 $]{[variable aaa][comment /*}?>*/][[',' [string "aaa][variable-2 $aaa][string {}][variable-2 $]{[variable aaa]}[string "]',']]}[string ->aaa.aaa"];',
'[keyword echo] [string "][variable-2 $]{[variable aaa][comment /*} } $aaa } */]}[string ->aaa.aaa"];');
function build_recursive_monsters(nt, t, n){
var monsters = [t];
for (var i = 1; i <= n; ++i)
monsters[i] = nt.join(monsters[i - 1]);
return monsters;
}
var m1 = build_recursive_monsters(
['[string "][variable-2 $]{[variable aaa] [operator +] ', '}[string "]'],
'[comment /* }?>} */] [string "aaa][variable-2 $aaa][string .aaa"]',
10
);
MT('variable_interpolation_complex_syntax_3_1',
'[meta <?php] [comment /* Recursive monsters */]',
'[keyword echo] ' + m1[4] + ';',
'[keyword echo] ' + m1[7] + ';',
'[keyword echo] ' + m1[8] + ';',
'[keyword echo] ' + m1[5] + ';',
'[keyword echo] ' + m1[1] + ';',
'[keyword echo] ' + m1[6] + ';',
'[keyword echo] ' + m1[9] + ';',
'[keyword echo] ' + m1[0] + ';',
'[keyword echo] ' + m1[10] + ';',
'[keyword echo] ' + m1[2] + ';',
'[keyword echo] ' + m1[3] + ';',
'[keyword echo] [string "end"];',
'[meta ?>]');
var m2 = build_recursive_monsters(
['[string "a][variable-2 $]{[variable aaa] [operator +] ', ' [operator +] ', '}[string .a"]'],
'[comment /* }?>{{ */] [string "a?>}{{aa][variable-2 $aaa][string .a}a?>a"]',
5
);
MT('variable_interpolation_complex_syntax_3_2',
'[meta <?php] [comment /* Recursive monsters 2 */]',
'[keyword echo] ' + m2[0] + ';',
'[keyword echo] ' + m2[1] + ';',
'[keyword echo] ' + m2[5] + ';',
'[keyword echo] ' + m2[4] + ';',
'[keyword echo] ' + m2[2] + ';',
'[keyword echo] ' + m2[3] + ';',
'[keyword echo] [string "end"];',
'[meta ?>]');
function build_recursive_monsters_2(mf1, mf2, nt, t, n){
var monsters = [t];
for (var i = 1; i <= n; ++i)
monsters[i] = nt[0] + mf1[i - 1] + nt[1] + mf2[i - 1] + nt[2] + monsters[i - 1] + nt[3];
return monsters;
}
var m3 = build_recursive_monsters_2(
m1,
m2,
['[string "a][variable-2 $]{[variable aaa] [operator +] ', ' [operator +] ', ' [operator +] ', '}[string .a"]'],
'[comment /* }?>{{ */] [string "a?>}{{aa][variable-2 $aaa][string .a}a?>a"]',
4
);
MT('variable_interpolation_complex_syntax_3_3',
'[meta <?php] [comment /* Recursive monsters 2 */]',
'[keyword echo] ' + m3[4] + ';',
'[keyword echo] ' + m3[0] + ';',
'[keyword echo] ' + m3[3] + ';',
'[keyword echo] ' + m3[1] + ';',
'[keyword echo] ' + m3[2] + ';',
'[keyword echo] [string "end"];',
'[meta ?>]');
MT("variable_interpolation_heredoc",
"[meta <?php]",
"[string <<<here]",
"[string doc ][variable-2 $]{[variable yay]}[string more]",
"[string here]; [comment // normal]");
})();
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/php/test.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/php/test.js",
"repo_id": "Humsen",
"token_count": 2947
} | 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("sieve", function(config) {
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var keywords = words("if elsif else stop require");
var atoms = words("true false not");
var indentUnit = config.indentUnit;
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == "/" && stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
if (ch === '#') {
stream.skipToEnd();
return "comment";
}
if (ch == "\"") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (ch == "(") {
state._indent.push("(");
// add virtual angel wings so that editor behaves...
// ...more sane incase of broken brackets
state._indent.push("{");
return null;
}
if (ch === "{") {
state._indent.push("{");
return null;
}
if (ch == ")") {
state._indent.pop();
state._indent.pop();
}
if (ch === "}") {
state._indent.pop();
return null;
}
if (ch == ",")
return null;
if (ch == ";")
return null;
if (/[{}\(\),;]/.test(ch))
return null;
// 1*DIGIT "K" / "M" / "G"
if (/\d/.test(ch)) {
stream.eatWhile(/[\d]/);
stream.eat(/[KkMmGg]/);
return "number";
}
// ":" (ALPHA / "_") *(ALPHA / DIGIT / "_")
if (ch == ":") {
stream.eatWhile(/[a-zA-Z_]/);
stream.eatWhile(/[a-zA-Z0-9_]/);
return "operator";
}
stream.eatWhile(/\w/);
var cur = stream.current();
// "text:" *(SP / HTAB) (hash-comment / CRLF)
// *(multiline-literal / multiline-dotstart)
// "." CRLF
if ((cur == "text") && stream.eat(":"))
{
state.tokenize = tokenMultiLineString;
return "string";
}
if (keywords.propertyIsEnumerable(cur))
return "keyword";
if (atoms.propertyIsEnumerable(cur))
return "atom";
return null;
}
function tokenMultiLineString(stream, state)
{
state._multiLineString = true;
// the first line is special it may contain a comment
if (!stream.sol()) {
stream.eatSpace();
if (stream.peek() == "#") {
stream.skipToEnd();
return "comment";
}
stream.skipToEnd();
return "string";
}
if ((stream.next() == ".") && (stream.eol()))
{
state._multiLineString = false;
state.tokenize = tokenBase;
}
return "string";
}
function tokenCComment(stream, state) {
var maybeEnd = false, ch;
while ((ch = stream.next()) != null) {
if (maybeEnd && ch == "/") {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped)
break;
escaped = !escaped && ch == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return "string";
};
}
return {
startState: function(base) {
return {tokenize: tokenBase,
baseIndent: base || 0,
_indent: []};
},
token: function(stream, state) {
if (stream.eatSpace())
return null;
return (state.tokenize || tokenBase)(stream, state);;
},
indent: function(state, _textAfter) {
var length = state._indent.length;
if (_textAfter && (_textAfter[0] == "}"))
length--;
if (length <0)
length = 0;
return length * indentUnit;
},
electricChars: "}"
};
});
CodeMirror.defineMIME("application/sieve", "sieve");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/sieve/sieve.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/sieve/sieve.js",
"repo_id": "Humsen",
"token_count": 1867
} | 42 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") { // CommonJS
mod(require("../../lib/codemirror"));
} else if (typeof define == "function" && define.amd) { // AMD
define(["../../lib/codemirror"], mod);
} else { // Plain browser env
mod(CodeMirror);
}
})(function(CodeMirror) {
"use strict";
var TOKEN_STYLES = {
addition: "positive",
attributes: "attribute",
bold: "strong",
cite: "keyword",
code: "atom",
definitionList: "number",
deletion: "negative",
div: "punctuation",
em: "em",
footnote: "variable",
footCite: "qualifier",
header: "header",
html: "comment",
image: "string",
italic: "em",
link: "link",
linkDefinition: "link",
list1: "variable-2",
list2: "variable-3",
list3: "keyword",
notextile: "string-2",
pre: "operator",
p: "property",
quote: "bracket",
span: "quote",
specialChar: "tag",
strong: "strong",
sub: "builtin",
sup: "builtin",
table: "variable-3",
tableHeading: "operator"
};
function startNewLine(stream, state) {
state.mode = Modes.newLayout;
state.tableHeading = false;
if (state.layoutType === "definitionList" && state.spanningLayout &&
stream.match(RE("definitionListEnd"), false))
state.spanningLayout = false;
}
function handlePhraseModifier(stream, state, ch) {
if (ch === "_") {
if (stream.eat("_"))
return togglePhraseModifier(stream, state, "italic", /__/, 2);
else
return togglePhraseModifier(stream, state, "em", /_/, 1);
}
if (ch === "*") {
if (stream.eat("*")) {
return togglePhraseModifier(stream, state, "bold", /\*\*/, 2);
}
return togglePhraseModifier(stream, state, "strong", /\*/, 1);
}
if (ch === "[") {
if (stream.match(/\d+\]/)) state.footCite = true;
return tokenStyles(state);
}
if (ch === "(") {
var spec = stream.match(/^(r|tm|c)\)/);
if (spec)
return tokenStylesWith(state, TOKEN_STYLES.specialChar);
}
if (ch === "<" && stream.match(/(\w+)[^>]+>[^<]+<\/\1>/))
return tokenStylesWith(state, TOKEN_STYLES.html);
if (ch === "?" && stream.eat("?"))
return togglePhraseModifier(stream, state, "cite", /\?\?/, 2);
if (ch === "=" && stream.eat("="))
return togglePhraseModifier(stream, state, "notextile", /==/, 2);
if (ch === "-" && !stream.eat("-"))
return togglePhraseModifier(stream, state, "deletion", /-/, 1);
if (ch === "+")
return togglePhraseModifier(stream, state, "addition", /\+/, 1);
if (ch === "~")
return togglePhraseModifier(stream, state, "sub", /~/, 1);
if (ch === "^")
return togglePhraseModifier(stream, state, "sup", /\^/, 1);
if (ch === "%")
return togglePhraseModifier(stream, state, "span", /%/, 1);
if (ch === "@")
return togglePhraseModifier(stream, state, "code", /@/, 1);
if (ch === "!") {
var type = togglePhraseModifier(stream, state, "image", /(?:\([^\)]+\))?!/, 1);
stream.match(/^:\S+/); // optional Url portion
return type;
}
return tokenStyles(state);
}
function togglePhraseModifier(stream, state, phraseModifier, closeRE, openSize) {
var charBefore = stream.pos > openSize ? stream.string.charAt(stream.pos - openSize - 1) : null;
var charAfter = stream.peek();
if (state[phraseModifier]) {
if ((!charAfter || /\W/.test(charAfter)) && charBefore && /\S/.test(charBefore)) {
var type = tokenStyles(state);
state[phraseModifier] = false;
return type;
}
} else if ((!charBefore || /\W/.test(charBefore)) && charAfter && /\S/.test(charAfter) &&
stream.match(new RegExp("^.*\\S" + closeRE.source + "(?:\\W|$)"), false)) {
state[phraseModifier] = true;
state.mode = Modes.attributes;
}
return tokenStyles(state);
};
function tokenStyles(state) {
var disabled = textileDisabled(state);
if (disabled) return disabled;
var styles = [];
if (state.layoutType) styles.push(TOKEN_STYLES[state.layoutType]);
styles = styles.concat(activeStyles(
state, "addition", "bold", "cite", "code", "deletion", "em", "footCite",
"image", "italic", "link", "span", "strong", "sub", "sup", "table", "tableHeading"));
if (state.layoutType === "header")
styles.push(TOKEN_STYLES.header + "-" + state.header);
return styles.length ? styles.join(" ") : null;
}
function textileDisabled(state) {
var type = state.layoutType;
switch(type) {
case "notextile":
case "code":
case "pre":
return TOKEN_STYLES[type];
default:
if (state.notextile)
return TOKEN_STYLES.notextile + (type ? (" " + TOKEN_STYLES[type]) : "");
return null;
}
}
function tokenStylesWith(state, extraStyles) {
var disabled = textileDisabled(state);
if (disabled) return disabled;
var type = tokenStyles(state);
if (extraStyles)
return type ? (type + " " + extraStyles) : extraStyles;
else
return type;
}
function activeStyles(state) {
var styles = [];
for (var i = 1; i < arguments.length; ++i) {
if (state[arguments[i]])
styles.push(TOKEN_STYLES[arguments[i]]);
}
return styles;
}
function blankLine(state) {
var spanningLayout = state.spanningLayout, type = state.layoutType;
for (var key in state) if (state.hasOwnProperty(key))
delete state[key];
state.mode = Modes.newLayout;
if (spanningLayout) {
state.layoutType = type;
state.spanningLayout = true;
}
}
var REs = {
cache: {},
single: {
bc: "bc",
bq: "bq",
definitionList: /- [^(?::=)]+:=+/,
definitionListEnd: /.*=:\s*$/,
div: "div",
drawTable: /\|.*\|/,
foot: /fn\d+/,
header: /h[1-6]/,
html: /\s*<(?:\/)?(\w+)(?:[^>]+)?>(?:[^<]+<\/\1>)?/,
link: /[^"]+":\S/,
linkDefinition: /\[[^\s\]]+\]\S+/,
list: /(?:#+|\*+)/,
notextile: "notextile",
para: "p",
pre: "pre",
table: "table",
tableCellAttributes: /[\/\\]\d+/,
tableHeading: /\|_\./,
tableText: /[^"_\*\[\(\?\+~\^%@|-]+/,
text: /[^!"_=\*\[\(<\?\+~\^%@-]+/
},
attributes: {
align: /(?:<>|<|>|=)/,
selector: /\([^\(][^\)]+\)/,
lang: /\[[^\[\]]+\]/,
pad: /(?:\(+|\)+){1,2}/,
css: /\{[^\}]+\}/
},
createRe: function(name) {
switch (name) {
case "drawTable":
return REs.makeRe("^", REs.single.drawTable, "$");
case "html":
return REs.makeRe("^", REs.single.html, "(?:", REs.single.html, ")*", "$");
case "linkDefinition":
return REs.makeRe("^", REs.single.linkDefinition, "$");
case "listLayout":
return REs.makeRe("^", REs.single.list, RE("allAttributes"), "*\\s+");
case "tableCellAttributes":
return REs.makeRe("^", REs.choiceRe(REs.single.tableCellAttributes,
RE("allAttributes")), "+\\.");
case "type":
return REs.makeRe("^", RE("allTypes"));
case "typeLayout":
return REs.makeRe("^", RE("allTypes"), RE("allAttributes"),
"*\\.\\.?", "(\\s+|$)");
case "attributes":
return REs.makeRe("^", RE("allAttributes"), "+");
case "allTypes":
return REs.choiceRe(REs.single.div, REs.single.foot,
REs.single.header, REs.single.bc, REs.single.bq,
REs.single.notextile, REs.single.pre, REs.single.table,
REs.single.para);
case "allAttributes":
return REs.choiceRe(REs.attributes.selector, REs.attributes.css,
REs.attributes.lang, REs.attributes.align, REs.attributes.pad);
default:
return REs.makeRe("^", REs.single[name]);
}
},
makeRe: function() {
var pattern = "";
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments[i];
pattern += (typeof arg === "string") ? arg : arg.source;
}
return new RegExp(pattern);
},
choiceRe: function() {
var parts = [arguments[0]];
for (var i = 1; i < arguments.length; ++i) {
parts[i * 2 - 1] = "|";
parts[i * 2] = arguments[i];
}
parts.unshift("(?:");
parts.push(")");
return REs.makeRe.apply(null, parts);
}
};
function RE(name) {
return (REs.cache[name] || (REs.cache[name] = REs.createRe(name)));
}
var Modes = {
newLayout: function(stream, state) {
if (stream.match(RE("typeLayout"), false)) {
state.spanningLayout = false;
return (state.mode = Modes.blockType)(stream, state);
}
var newMode;
if (!textileDisabled(state)) {
if (stream.match(RE("listLayout"), false))
newMode = Modes.list;
else if (stream.match(RE("drawTable"), false))
newMode = Modes.table;
else if (stream.match(RE("linkDefinition"), false))
newMode = Modes.linkDefinition;
else if (stream.match(RE("definitionList")))
newMode = Modes.definitionList;
else if (stream.match(RE("html"), false))
newMode = Modes.html;
}
return (state.mode = (newMode || Modes.text))(stream, state);
},
blockType: function(stream, state) {
var match, type;
state.layoutType = null;
if (match = stream.match(RE("type")))
type = match[0];
else
return (state.mode = Modes.text)(stream, state);
if (match = type.match(RE("header"))) {
state.layoutType = "header";
state.header = parseInt(match[0][1]);
} else if (type.match(RE("bq"))) {
state.layoutType = "quote";
} else if (type.match(RE("bc"))) {
state.layoutType = "code";
} else if (type.match(RE("foot"))) {
state.layoutType = "footnote";
} else if (type.match(RE("notextile"))) {
state.layoutType = "notextile";
} else if (type.match(RE("pre"))) {
state.layoutType = "pre";
} else if (type.match(RE("div"))) {
state.layoutType = "div";
} else if (type.match(RE("table"))) {
state.layoutType = "table";
}
state.mode = Modes.attributes;
return tokenStyles(state);
},
text: function(stream, state) {
if (stream.match(RE("text"))) return tokenStyles(state);
var ch = stream.next();
if (ch === '"')
return (state.mode = Modes.link)(stream, state);
return handlePhraseModifier(stream, state, ch);
},
attributes: function(stream, state) {
state.mode = Modes.layoutLength;
if (stream.match(RE("attributes")))
return tokenStylesWith(state, TOKEN_STYLES.attributes);
else
return tokenStyles(state);
},
layoutLength: function(stream, state) {
if (stream.eat(".") && stream.eat("."))
state.spanningLayout = true;
state.mode = Modes.text;
return tokenStyles(state);
},
list: function(stream, state) {
var match = stream.match(RE("list"));
state.listDepth = match[0].length;
var listMod = (state.listDepth - 1) % 3;
if (!listMod)
state.layoutType = "list1";
else if (listMod === 1)
state.layoutType = "list2";
else
state.layoutType = "list3";
state.mode = Modes.attributes;
return tokenStyles(state);
},
link: function(stream, state) {
state.mode = Modes.text;
if (stream.match(RE("link"))) {
stream.match(/\S+/);
return tokenStylesWith(state, TOKEN_STYLES.link);
}
return tokenStyles(state);
},
linkDefinition: function(stream, state) {
stream.skipToEnd();
return tokenStylesWith(state, TOKEN_STYLES.linkDefinition);
},
definitionList: function(stream, state) {
stream.match(RE("definitionList"));
state.layoutType = "definitionList";
if (stream.match(/\s*$/))
state.spanningLayout = true;
else
state.mode = Modes.attributes;
return tokenStyles(state);
},
html: function(stream, state) {
stream.skipToEnd();
return tokenStylesWith(state, TOKEN_STYLES.html);
},
table: function(stream, state) {
state.layoutType = "table";
return (state.mode = Modes.tableCell)(stream, state);
},
tableCell: function(stream, state) {
if (stream.match(RE("tableHeading")))
state.tableHeading = true;
else
stream.eat("|");
state.mode = Modes.tableCellAttributes;
return tokenStyles(state);
},
tableCellAttributes: function(stream, state) {
state.mode = Modes.tableText;
if (stream.match(RE("tableCellAttributes")))
return tokenStylesWith(state, TOKEN_STYLES.attributes);
else
return tokenStyles(state);
},
tableText: function(stream, state) {
if (stream.match(RE("tableText")))
return tokenStyles(state);
if (stream.peek() === "|") { // end of cell
state.mode = Modes.tableCell;
return tokenStyles(state);
}
return handlePhraseModifier(stream, state, stream.next());
}
};
CodeMirror.defineMode("textile", function() {
return {
startState: function() {
return { mode: Modes.newLayout };
},
token: function(stream, state) {
if (stream.sol()) startNewLine(stream, state);
return state.mode(stream, state);
},
blankLine: blankLine
};
});
CodeMirror.defineMIME("text/x-textile", "textile");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/textile/textile.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/textile/textile.js",
"repo_id": "Humsen",
"token_count": 6119
} | 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";
CodeMirror.defineMode("xquery", function() {
// The keywords object is set to the result of this self executing
// function. Each keyword is a property of the keywords object whose
// value is {type: atype, style: astyle}
var keywords = function(){
// conveinence functions used to build keywords object
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a")
, B = kw("keyword b")
, C = kw("keyword c")
, operator = kw("operator")
, atom = {type: "atom", style: "atom"}
, punctuation = {type: "punctuation", style: null}
, qualifier = {type: "axis_specifier", style: "qualifier"};
// kwObj is what is return from this function at the end
var kwObj = {
'if': A, 'switch': A, 'while': A, 'for': A,
'else': B, 'then': B, 'try': B, 'finally': B, 'catch': B,
'element': C, 'attribute': C, 'let': C, 'implements': C, 'import': C, 'module': C, 'namespace': C,
'return': C, 'super': C, 'this': C, 'throws': C, 'where': C, 'private': C,
',': punctuation,
'null': atom, 'fn:false()': atom, 'fn:true()': atom
};
// a list of 'basic' keywords. For each add a property to kwObj with the value of
// {type: basic[i], style: "keyword"} e.g. 'after' --> {type: "after", style: "keyword"}
var basic = ['after','ancestor','ancestor-or-self','and','as','ascending','assert','attribute','before',
'by','case','cast','child','comment','declare','default','define','descendant','descendant-or-self',
'descending','document','document-node','element','else','eq','every','except','external','following',
'following-sibling','follows','for','function','if','import','in','instance','intersect','item',
'let','module','namespace','node','node','of','only','or','order','parent','precedes','preceding',
'preceding-sibling','processing-instruction','ref','return','returns','satisfies','schema','schema-element',
'self','some','sortby','stable','text','then','to','treat','typeswitch','union','variable','version','where',
'xquery', 'empty-sequence'];
for(var i=0, l=basic.length; i < l; i++) { kwObj[basic[i]] = kw(basic[i]);};
// a list of types. For each add a property to kwObj with the value of
// {type: "atom", style: "atom"}
var types = ['xs:string', 'xs:float', 'xs:decimal', 'xs:double', 'xs:integer', 'xs:boolean', 'xs:date', 'xs:dateTime',
'xs:time', 'xs:duration', 'xs:dayTimeDuration', 'xs:time', 'xs:yearMonthDuration', 'numeric', 'xs:hexBinary',
'xs:base64Binary', 'xs:anyURI', 'xs:QName', 'xs:byte','xs:boolean','xs:anyURI','xf:yearMonthDuration'];
for(var i=0, l=types.length; i < l; i++) { kwObj[types[i]] = atom;};
// each operator will add a property to kwObj with value of {type: "operator", style: "keyword"}
var operators = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', ':=', '=', '>', '>=', '<', '<=', '.', '|', '?', 'and', 'or', 'div', 'idiv', 'mod', '*', '/', '+', '-'];
for(var i=0, l=operators.length; i < l; i++) { kwObj[operators[i]] = operator;};
// each axis_specifiers will add a property to kwObj with value of {type: "axis_specifier", style: "qualifier"}
var axis_specifiers = ["self::", "attribute::", "child::", "descendant::", "descendant-or-self::", "parent::",
"ancestor::", "ancestor-or-self::", "following::", "preceding::", "following-sibling::", "preceding-sibling::"];
for(var i=0, l=axis_specifiers.length; i < l; i++) { kwObj[axis_specifiers[i]] = qualifier; };
return kwObj;
}();
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
// the primary mode tokenizer
function tokenBase(stream, state) {
var ch = stream.next(),
mightBeFunction = false,
isEQName = isEQNameAhead(stream);
// an XML tag (if not in some sub, chained tokenizer)
if (ch == "<") {
if(stream.match("!--", true))
return chain(stream, state, tokenXMLComment);
if(stream.match("![CDATA", false)) {
state.tokenize = tokenCDATA;
return ret("tag", "tag");
}
if(stream.match("?", false)) {
return chain(stream, state, tokenPreProcessing);
}
var isclose = stream.eat("/");
stream.eatSpace();
var tagName = "", c;
while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
return chain(stream, state, tokenTag(tagName, isclose));
}
// start code block
else if(ch == "{") {
pushStateStack(state,{ type: "codeblock"});
return ret("", null);
}
// end code block
else if(ch == "}") {
popStateStack(state);
return ret("", null);
}
// if we're in an XML block
else if(isInXmlBlock(state)) {
if(ch == ">")
return ret("tag", "tag");
else if(ch == "/" && stream.eat(">")) {
popStateStack(state);
return ret("tag", "tag");
}
else
return ret("word", "variable");
}
// if a number
else if (/\d/.test(ch)) {
stream.match(/^\d*(?:\.\d*)?(?:E[+\-]?\d+)?/);
return ret("number", "atom");
}
// comment start
else if (ch === "(" && stream.eat(":")) {
pushStateStack(state, { type: "comment"});
return chain(stream, state, tokenComment);
}
// quoted string
else if ( !isEQName && (ch === '"' || ch === "'"))
return chain(stream, state, tokenString(ch));
// variable
else if(ch === "$") {
return chain(stream, state, tokenVariable);
}
// assignment
else if(ch ===":" && stream.eat("=")) {
return ret("operator", "keyword");
}
// open paren
else if(ch === "(") {
pushStateStack(state, { type: "paren"});
return ret("", null);
}
// close paren
else if(ch === ")") {
popStateStack(state);
return ret("", null);
}
// open paren
else if(ch === "[") {
pushStateStack(state, { type: "bracket"});
return ret("", null);
}
// close paren
else if(ch === "]") {
popStateStack(state);
return ret("", null);
}
else {
var known = keywords.propertyIsEnumerable(ch) && keywords[ch];
// if there's a EQName ahead, consume the rest of the string portion, it's likely a function
if(isEQName && ch === '\"') while(stream.next() !== '"'){}
if(isEQName && ch === '\'') while(stream.next() !== '\''){}
// gobble up a word if the character is not known
if(!known) stream.eatWhile(/[\w\$_-]/);
// gobble a colon in the case that is a lib func type call fn:doc
var foundColon = stream.eat(":");
// if there's not a second colon, gobble another word. Otherwise, it's probably an axis specifier
// which should get matched as a keyword
if(!stream.eat(":") && foundColon) {
stream.eatWhile(/[\w\$_-]/);
}
// if the next non whitespace character is an open paren, this is probably a function (if not a keyword of other sort)
if(stream.match(/^[ \t]*\(/, false)) {
mightBeFunction = true;
}
// is the word a keyword?
var word = stream.current();
known = keywords.propertyIsEnumerable(word) && keywords[word];
// if we think it's a function call but not yet known,
// set style to variable for now for lack of something better
if(mightBeFunction && !known) known = {type: "function_call", style: "variable def"};
// if the previous word was element, attribute, axis specifier, this word should be the name of that
if(isInXmlConstructor(state)) {
popStateStack(state);
return ret("word", "variable", word);
}
// as previously checked, if the word is element,attribute, axis specifier, call it an "xmlconstructor" and
// push the stack so we know to look for it on the next word
if(word == "element" || word == "attribute" || known.type == "axis_specifier") pushStateStack(state, {type: "xmlconstructor"});
// if the word is known, return the details of that else just call this a generic 'word'
return known ? ret(known.type, known.style, word) :
ret("word", "variable", word);
}
}
// handle comments, including nested
function tokenComment(stream, state) {
var maybeEnd = false, maybeNested = false, nestedCount = 0, ch;
while (ch = stream.next()) {
if (ch == ")" && maybeEnd) {
if(nestedCount > 0)
nestedCount--;
else {
popStateStack(state);
break;
}
}
else if(ch == ":" && maybeNested) {
nestedCount++;
}
maybeEnd = (ch == ":");
maybeNested = (ch == "(");
}
return ret("comment", "comment");
}
// tokenizer for string literals
// optionally pass a tokenizer function to set state.tokenize back to when finished
function tokenString(quote, f) {
return function(stream, state) {
var ch;
if(isInString(state) && stream.current() == quote) {
popStateStack(state);
if(f) state.tokenize = f;
return ret("string", "string");
}
pushStateStack(state, { type: "string", name: quote, tokenize: tokenString(quote, f) });
// if we're in a string and in an XML block, allow an embedded code block
if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
state.tokenize = tokenBase;
return ret("string", "string");
}
while (ch = stream.next()) {
if (ch == quote) {
popStateStack(state);
if(f) state.tokenize = f;
break;
}
else {
// if we're in a string and in an XML block, allow an embedded code block in an attribute
if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
state.tokenize = tokenBase;
return ret("string", "string");
}
}
}
return ret("string", "string");
};
}
// tokenizer for variables
function tokenVariable(stream, state) {
var isVariableChar = /[\w\$_-]/;
// a variable may start with a quoted EQName so if the next character is quote, consume to the next quote
if(stream.eat("\"")) {
while(stream.next() !== '\"'){};
stream.eat(":");
} else {
stream.eatWhile(isVariableChar);
if(!stream.match(":=", false)) stream.eat(":");
}
stream.eatWhile(isVariableChar);
state.tokenize = tokenBase;
return ret("variable", "variable");
}
// tokenizer for XML tags
function tokenTag(name, isclose) {
return function(stream, state) {
stream.eatSpace();
if(isclose && stream.eat(">")) {
popStateStack(state);
state.tokenize = tokenBase;
return ret("tag", "tag");
}
// self closing tag without attributes?
if(!stream.eat("/"))
pushStateStack(state, { type: "tag", name: name, tokenize: tokenBase});
if(!stream.eat(">")) {
state.tokenize = tokenAttribute;
return ret("tag", "tag");
}
else {
state.tokenize = tokenBase;
}
return ret("tag", "tag");
};
}
// tokenizer for XML attributes
function tokenAttribute(stream, state) {
var ch = stream.next();
if(ch == "/" && stream.eat(">")) {
if(isInXmlAttributeBlock(state)) popStateStack(state);
if(isInXmlBlock(state)) popStateStack(state);
return ret("tag", "tag");
}
if(ch == ">") {
if(isInXmlAttributeBlock(state)) popStateStack(state);
return ret("tag", "tag");
}
if(ch == "=")
return ret("", null);
// quoted string
if (ch == '"' || ch == "'")
return chain(stream, state, tokenString(ch, tokenAttribute));
if(!isInXmlAttributeBlock(state))
pushStateStack(state, { type: "attribute", tokenize: tokenAttribute});
stream.eat(/[a-zA-Z_:]/);
stream.eatWhile(/[-a-zA-Z0-9_:.]/);
stream.eatSpace();
// the case where the attribute has not value and the tag was closed
if(stream.match(">", false) || stream.match("/", false)) {
popStateStack(state);
state.tokenize = tokenBase;
}
return ret("attribute", "attribute");
}
// handle comments, including nested
function tokenXMLComment(stream, state) {
var ch;
while (ch = stream.next()) {
if (ch == "-" && stream.match("->", true)) {
state.tokenize = tokenBase;
return ret("comment", "comment");
}
}
}
// handle CDATA
function tokenCDATA(stream, state) {
var ch;
while (ch = stream.next()) {
if (ch == "]" && stream.match("]", true)) {
state.tokenize = tokenBase;
return ret("comment", "comment");
}
}
}
// handle preprocessing instructions
function tokenPreProcessing(stream, state) {
var ch;
while (ch = stream.next()) {
if (ch == "?" && stream.match(">", true)) {
state.tokenize = tokenBase;
return ret("comment", "comment meta");
}
}
}
// functions to test the current context of the state
function isInXmlBlock(state) { return isIn(state, "tag"); }
function isInXmlAttributeBlock(state) { return isIn(state, "attribute"); }
function isInXmlConstructor(state) { return isIn(state, "xmlconstructor"); }
function isInString(state) { return isIn(state, "string"); }
function isEQNameAhead(stream) {
// assume we've already eaten a quote (")
if(stream.current() === '"')
return stream.match(/^[^\"]+\"\:/, false);
else if(stream.current() === '\'')
return stream.match(/^[^\"]+\'\:/, false);
else
return false;
}
function isIn(state, type) {
return (state.stack.length && state.stack[state.stack.length - 1].type == type);
}
function pushStateStack(state, newState) {
state.stack.push(newState);
}
function popStateStack(state) {
state.stack.pop();
var reinstateTokenize = state.stack.length && state.stack[state.stack.length-1].tokenize;
state.tokenize = reinstateTokenize || tokenBase;
}
// the interface for the mode API
return {
startState: function() {
return {
tokenize: tokenBase,
cc: [],
stack: []
};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
return style;
},
blockCommentStart: "(:",
blockCommentEnd: ":)"
};
});
CodeMirror.defineMIME("application/xquery", "xquery");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/xquery/xquery.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/xquery/xquery.js",
"repo_id": "Humsen",
"token_count": 5979
} | 44 |
.cm-s-erlang-dark.CodeMirror { background: #002240; color: white; }
.cm-s-erlang-dark div.CodeMirror-selected { background: #b36539 !important; }
.cm-s-erlang-dark.CodeMirror ::selection { background: rgba(179, 101, 57, .99); }
.cm-s-erlang-dark.CodeMirror ::-moz-selection { background: rgba(179, 101, 57, .99); }
.cm-s-erlang-dark .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }
.cm-s-erlang-dark .CodeMirror-guttermarker { color: white; }
.cm-s-erlang-dark .CodeMirror-guttermarker-subtle { color: #d0d0d0; }
.cm-s-erlang-dark .CodeMirror-linenumber { color: #d0d0d0; }
.cm-s-erlang-dark .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-erlang-dark span.cm-atom { color: #f133f1; }
.cm-s-erlang-dark span.cm-attribute { color: #ff80e1; }
.cm-s-erlang-dark span.cm-bracket { color: #ff9d00; }
.cm-s-erlang-dark span.cm-builtin { color: #eaa; }
.cm-s-erlang-dark span.cm-comment { color: #77f; }
.cm-s-erlang-dark span.cm-def { color: #e7a; }
.cm-s-erlang-dark span.cm-keyword { color: #ffee80; }
.cm-s-erlang-dark span.cm-meta { color: #50fefe; }
.cm-s-erlang-dark span.cm-number { color: #ffd0d0; }
.cm-s-erlang-dark span.cm-operator { color: #d55; }
.cm-s-erlang-dark span.cm-property { color: #ccc; }
.cm-s-erlang-dark span.cm-qualifier { color: #ccc; }
.cm-s-erlang-dark span.cm-quote { color: #ccc; }
.cm-s-erlang-dark span.cm-special { color: #ffbbbb; }
.cm-s-erlang-dark span.cm-string { color: #3ad900; }
.cm-s-erlang-dark span.cm-string-2 { color: #ccc; }
.cm-s-erlang-dark span.cm-tag { color: #9effff; }
.cm-s-erlang-dark span.cm-variable { color: #50fe50; }
.cm-s-erlang-dark span.cm-variable-2 { color: #e0e; }
.cm-s-erlang-dark span.cm-variable-3 { color: #ccc; }
.cm-s-erlang-dark span.cm-error { color: #9d1e15; }
.cm-s-erlang-dark .CodeMirror-activeline-background {background: #013461 !important;}
.cm-s-erlang-dark .CodeMirror-matchingbracket {outline:1px solid grey; color:white !important;}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/erlang-dark.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/erlang-dark.css",
"repo_id": "Humsen",
"token_count": 922
} | 45 |
/*
Name: Tomorrow Night - Eighties
Author: Chris Kempson
CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)
Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)
*/
.cm-s-tomorrow-night-eighties.CodeMirror {background: #000000; color: #CCCCCC;}
.cm-s-tomorrow-night-eighties div.CodeMirror-selected {background: #2D2D2D !important;}
.cm-s-tomorrow-night-eighties.CodeMirror ::selection { background: rgba(45, 45, 45, 0.99); }
.cm-s-tomorrow-night-eighties.CodeMirror ::-moz-selection { background: rgba(45, 45, 45, 0.99); }
.cm-s-tomorrow-night-eighties .CodeMirror-gutters {background: #000000; border-right: 0px;}
.cm-s-tomorrow-night-eighties .CodeMirror-guttermarker { color: #f2777a; }
.cm-s-tomorrow-night-eighties .CodeMirror-guttermarker-subtle { color: #777; }
.cm-s-tomorrow-night-eighties .CodeMirror-linenumber {color: #515151;}
.cm-s-tomorrow-night-eighties .CodeMirror-cursor {border-left: 1px solid #6A6A6A !important;}
.cm-s-tomorrow-night-eighties span.cm-comment {color: #d27b53;}
.cm-s-tomorrow-night-eighties span.cm-atom {color: #a16a94;}
.cm-s-tomorrow-night-eighties span.cm-number {color: #a16a94;}
.cm-s-tomorrow-night-eighties span.cm-property, .cm-s-tomorrow-night-eighties span.cm-attribute {color: #99cc99;}
.cm-s-tomorrow-night-eighties span.cm-keyword {color: #f2777a;}
.cm-s-tomorrow-night-eighties span.cm-string {color: #ffcc66;}
.cm-s-tomorrow-night-eighties span.cm-variable {color: #99cc99;}
.cm-s-tomorrow-night-eighties span.cm-variable-2 {color: #6699cc;}
.cm-s-tomorrow-night-eighties span.cm-def {color: #f99157;}
.cm-s-tomorrow-night-eighties span.cm-bracket {color: #CCCCCC;}
.cm-s-tomorrow-night-eighties span.cm-tag {color: #f2777a;}
.cm-s-tomorrow-night-eighties span.cm-link {color: #a16a94;}
.cm-s-tomorrow-night-eighties span.cm-error {background: #f2777a; color: #6A6A6A;}
.cm-s-tomorrow-night-eighties .CodeMirror-activeline-background {background: #343600 !important;}
.cm-s-tomorrow-night-eighties .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/tomorrow-night-eighties.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/tomorrow-night-eighties.css",
"repo_id": "Humsen",
"token_count": 850
} | 46 |
/*!
* Test plugin for Editor.md
*
* @file test-plugin.js
* @author pandao
* @version 1.2.0
* @updateTime 2015-03-07
* {@link https://github.com/pandao/editor.md}
* @license MIT
*/
(function() {
var factory = function (exports) {
var $ = jQuery; // if using module loader(Require.js/Sea.js).
exports.testPlugin = function(){
alert("testPlugin");
};
exports.fn.testPluginMethodA = function() {
/*
var _this = this; // this == the current instance object of Editor.md
var lang = _this.lang;
var settings = _this.settings;
var editor = this.editor;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var classPrefix = this.classPrefix;
cm.focus();
*/
//....
alert("testPluginMethodA");
};
};
// CommonJS/Node.js
if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
{
module.exports = factory;
}
else if (typeof define === "function") // AMD/CMD/Sea.js
{
if (define.amd) { // for Require.js
define(["editormd"], function(editormd) {
factory(editormd);
});
} else { // for Sea.js
define(function(require) {
var editormd = require("./../../editormd");
factory(editormd);
});
}
}
else
{
factory(window.editormd);
}
})();
| Humsen/web/web-mobile/WebContent/plugins/editormd/plugins/test-plugin/test-plugin.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/plugins/test-plugin/test-plugin.js",
"repo_id": "Humsen",
"token_count": 660
} | 47 |
@charset "UTF-8";
.upload-file-form {
margin-top: 50px;
} | Humsen/web/web-pc/WebContent/css/personal_center/upload-file.css/0 | {
"file_path": "Humsen/web/web-pc/WebContent/css/personal_center/upload-file.css",
"repo_id": "Humsen",
"token_count": 29
} | 48 |
<!-- DataTables CSS -->
<link rel="stylesheet"
href="/plugins/DataTables/css/jquery.dataTables.css">
<!-- bootstrap -->
<link rel="stylesheet"
href="/plugins/DataTables/css/dataTables.bootstrap4.css">
<!-- 自定义css -->
<link rel="stylesheet" href="/css/personal_center/show-users.css">
<!-- jQuery -->
<!-- <script src="/plugins/DataTables/js/jquery.js"></script> -->
<!-- DataTables -->
<script src="/plugins/DataTables/js/jquery.dataTables.js"></script>
<!-- bootstrap -->
<script src="/plugins/DataTables/js/dataTables.bootstrap4.js"></script>
<!-- 自定义脚本 -->
<script src="/js/personal_center/show-users.js"></script>
<div class="show-users-table">
<table id="tbl_showUsers">
<!-- <thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
</tbody> -->
</table>
</div>
| Humsen/web/web-pc/WebContent/personal_center/show_users.html/0 | {
"file_path": "Humsen/web/web-pc/WebContent/personal_center/show_users.html",
"repo_id": "Humsen",
"token_count": 340
} | 49 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_advanced_search_x2x
#
# Translators:
# Rodrigo de Almeida Sottomaior Macedo <rmsolucoeseminformatic4@gmail.com>, 2017
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 10.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-01-03 03:49+0000\n"
"PO-Revision-Date: 2019-08-30 15:23+0000\n"
"Last-Translator: Rodrigo Macedo <rmsolucoeseminformatic4@gmail.com>\n"
"Language-Team: Portuguese (Brazil) (https://www.transifex.com/oca/"
"teams/23907/pt_BR/)\n"
"Language: pt_BR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n > 1;\n"
"X-Generator: Weblate 3.8\n"
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/js/utils.esm.js:0
#, python-format
msgid " and "
msgstr ""
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/js/utils.esm.js:0
#, python-format
msgid " is not "
msgstr ""
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/js/utils.esm.js:0
#, python-format
msgid " or "
msgstr ""
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/search/filter_menu/advanced_filter_item.xml:0
#, python-format
msgid "Add Advanced Filter"
msgstr "Adicionar filtro avançado"
#~ msgid "is in selection"
#~ msgstr "Está em seleção"
| OCA/web/web_advanced_search/i18n/pt_BR.po/0 | {
"file_path": "OCA/web/web_advanced_search/i18n/pt_BR.po",
"repo_id": "OCA",
"token_count": 610
} | 50 |
/** @odoo-module **/
import AdvancedFilterItem from "./advanced_filter_item.esm";
import FilterMenu from "web.FilterMenu";
import {patch} from "@web/core/utils/patch";
/**
* Patches the FilterMenu for legacy widgets.
*
* Tree views still use this old legacy widget, so we need to patch it.
* This is likely to disappear in 17.0
*/
patch(FilterMenu, "web_advanced_search.legacy.FilterMenu", {
components: {
...FilterMenu.components,
AdvancedFilterItem,
},
});
export default FilterMenu;
| OCA/web/web_advanced_search/static/src/legacy/js/control_panel/filter_menu.esm.js/0 | {
"file_path": "OCA/web/web_advanced_search/static/src/legacy/js/control_panel/filter_menu.esm.js",
"repo_id": "OCA",
"token_count": 169
} | 51 |
# © 2023 David BEAL @ Akretion
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from odoo import api, exceptions, models
logger = logging.getLogger(__name__)
class Base(models.AbstractModel):
_inherit = "base"
@api.model
def _get_view(self, view_id=None, view_type="form", **options):
arch, view = super()._get_view(view_id, view_type, **options)
if view_type == "form":
self._update_css_class(arch)
return arch, view
def _update_css_class(self, arch):
css = self._get_field_styles()
if css:
self._check_css_dict(css)
for style in css.get(self._name):
for field_name in css[self._name][style]:
for field in arch.xpath(f"//field[@name='{field_name}']"):
field.attrib[
"class"
] = f"{style} {field.attrib.get('class') or ''}".strip()
def _get_field_styles(self):
"""Inherit me with:
res = super()._get_field_styles()
res.append({'my_model': {"css_class": ['field1', 'field2'], "bg-info": [...] }})
return res
"""
return {}
def _check_css_dict(self, css):
rtfm = "\n\nPlease have a look to the readme.\n\nThe rtfm team."
if not isinstance(css, dict):
raise exceptions.ValidationError(
f"_get_field_styles() should return a dict{rtfm}"
)
model = self._name
if model in css:
if not isinstance(css[model], dict):
raise exceptions.ValidationError(f"{css[model]} should be a dict{rtfm}")
for vals in css[model].values():
if not isinstance(vals, list):
raise exceptions.ValidationError(
f"{vals} should be a list of fields !{rtfm}"
)
| OCA/web/web_apply_field_style/models/base.py/0 | {
"file_path": "OCA/web/web_apply_field_style/models/base.py",
"repo_id": "OCA",
"token_count": 955
} | 52 |
This documentation is for developers.
If you want to configure your calendar view's snap duration, make sure that you
action includes a context similar to this (example is the default value)::
{"calendar_slot_duration": "00:30:00"}
It can be added in actions defined on python or as ``ir.actions.act_window``
records.
| OCA/web/web_calendar_slot_duration/readme/CONFIGURE.rst/0 | {
"file_path": "OCA/web/web_calendar_slot_duration/readme/CONFIGURE.rst",
"repo_id": "OCA",
"token_count": 86
} | 53 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_chatter_position
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2023-04-03 13:22+0000\n"
"Last-Translator: Bole <bole@dajmi5.com>\n"
"Language-Team: none\n"
"Language: hr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
"X-Generator: Weblate 4.14.1\n"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__bottom
msgid "Bottom"
msgstr "Na dnu"
#. module: web_chatter_position
#: model:ir.model.fields,field_description:web_chatter_position.field_res_users__chatter_position
msgid "Chatter Position"
msgstr "Pozicija razgovora"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__auto
msgid "Responsive"
msgstr "Responzivno"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__sided
msgid "Sided"
msgstr "Sa strane"
#. module: web_chatter_position
#: model:ir.model,name:web_chatter_position.model_res_users
msgid "User"
msgstr "Korisnik"
| OCA/web/web_chatter_position/i18n/hr.po/0 | {
"file_path": "OCA/web/web_chatter_position/i18n/hr.po",
"repo_id": "OCA",
"token_count": 567
} | 54 |
=================
Web Company Color
=================
..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:0d77639a7fc2cad4e3f3eefdb495036be87e1f9487c6601a255ff3b5ec96a071
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fweb-lightgray.png?logo=github
:target: https://github.com/OCA/web/tree/16.0/web_company_color
:alt: OCA/web
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/web-16-0/web-16-0-web_company_color
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
:target: https://runboat.odoo-community.org/builds?repo=OCA/web&target_branch=16.0
:alt: Try me on Runboat
|badge1| |badge2| |badge3| |badge4| |badge5|
This module change navbar colors based in the company logo colors.
**Table of contents**
.. contents::
:local:
Usage
=====
Go to company record and set a logo. Can see/modify applied colors on the "Navbar" section.
For optimal results use images with alpha channel.
Known issues / Roadmap
======================
White color is omitted in the addition operation to support images without alpha channel.
Bug Tracker
===========
Bugs are tracked on `GitHub Issues <https://github.com/OCA/web/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us to smash it by providing a detailed and welcomed
`feedback <https://github.com/OCA/web/issues/new?body=module:%20web_company_color%0Aversion:%2016.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
Do not contact contributors directly about support or help with technical issues.
Credits
=======
Authors
~~~~~~~
* Alexandre Díaz
Contributors
~~~~~~~~~~~~
* Jordi Ballester Alomar <jordi.ballester@forgeflow.com> (ForgeFlow)
* Lois Rilo <lois.rilo@forgeflow.com> (ForgeFlow)
* Simone Orsi <simone.orsi@camptocamp.com>
* Iván Antón <ozono@ozonomultimedia.com>
* Bernat Puig <bernat.puig@forgeflow.com> (ForgeFlow)
* Dhara Solanki <dhara.solanki@initos.com>
* `Tecnativa <https://www.tecnativa.com>`_:
* Jairo Llopis
* Alexandre Díaz
* Carlos Roca
Maintainers
~~~~~~~~~~~
This module is maintained by the OCA.
.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
This module is part of the `OCA/web <https://github.com/OCA/web/tree/16.0/web_company_color>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
| OCA/web/web_company_color/README.rst/0 | {
"file_path": "OCA/web/web_company_color/README.rst",
"repo_id": "OCA",
"token_count": 1207
} | 55 |
# Copyright 2020 Alexandre Díaz <dev@redneboa.es>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
from .assetsbundle import AssetsBundleCompanyColor
class QWeb(models.AbstractModel):
_inherit = "ir.qweb"
def _generate_asset_nodes_cache(
self,
bundle,
css=True,
js=True,
debug=False,
async_load=False,
defer_load=False,
lazy_load=False,
media=None,
):
res = super()._generate_asset_nodes(
bundle, css, js, debug, async_load, defer_load, lazy_load, media
)
if bundle == "web_company_color.company_color_assets":
asset = AssetsBundleCompanyColor(
bundle, [], env=self.env, css=True, js=True
)
res += [asset.get_company_color_asset_node()]
return res
def _get_asset_content(self, bundle, defer_load=False, lazy_load=False, media=None):
"""Handle 'special' web_company_color bundle"""
if bundle == "web_company_color.company_color_assets":
return [], []
return super()._get_asset_content(
bundle, defer_load=defer_load, lazy_load=lazy_load, media=media
)
| OCA/web/web_company_color/models/ir_qweb.py/0 | {
"file_path": "OCA/web/web_company_color/models/ir_qweb.py",
"repo_id": "OCA",
"token_count": 574
} | 56 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_copy_confirm
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 14.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2021-10-13 20:46+0000\n"
"Last-Translator: Corneliuus <cornelius@clk-it.de>\n"
"Language-Team: none\n"
"Language: de\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 4.3.2\n"
#. module: web_copy_confirm
#. odoo-javascript
#: code:addons/web_copy_confirm/static/src/js/web_copy_confirm.esm.js:0
#, python-format
msgid "Are you sure that you would like to copy this record?"
msgstr "Sind Sie sicher, dass Sie diesen Datensatz kopieren möchten?"
#. module: web_copy_confirm
#. odoo-javascript
#: code:addons/web_copy_confirm/static/src/js/web_copy_confirm.esm.js:0
#, python-format
msgid "Duplicate"
msgstr "Duplizieren"
| OCA/web/web_copy_confirm/i18n/de.po/0 | {
"file_path": "OCA/web/web_copy_confirm/i18n/de.po",
"repo_id": "OCA",
"token_count": 400
} | 57 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_dark_mode
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2023-02-16 14:23+0000\n"
"Last-Translator: Bole <bole@dajmi5.com>\n"
"Language-Team: none\n"
"Language: hr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
"X-Generator: Weblate 4.14.1\n"
#. module: web_dark_mode
#. odoo-javascript
#: code:addons/web_dark_mode/static/src/js/switch_item.esm.js:0
#: model:ir.model.fields,field_description:web_dark_mode.field_res_users__dark_mode
#, python-format
msgid "Dark Mode"
msgstr "Tamni način"
#. module: web_dark_mode
#: model:ir.model.fields,field_description:web_dark_mode.field_res_users__dark_mode_device_dependent
msgid "Device Dependent Dark Mode"
msgstr "Tamni način zavisi od uređaja"
#. module: web_dark_mode
#: model:ir.model,name:web_dark_mode.model_ir_http
msgid "HTTP Routing"
msgstr "HTTP Routing"
#. module: web_dark_mode
#: model:ir.model,name:web_dark_mode.model_res_users
msgid "User"
msgstr "Korisnik"
| OCA/web/web_dark_mode/i18n/hr.po/0 | {
"file_path": "OCA/web/web_dark_mode/i18n/hr.po",
"repo_id": "OCA",
"token_count": 537
} | 58 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.