text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
import LoadingIndicator from '../../../src/components/LoadingIndicator.vue' import { defaultPlugins, shallowMount } from 'web-test-helpers' import { mock } from 'vitest-mock-extended' import { LoadingService } from '../../../src/services' import { OcProgress } from 'design-system/src/components' const selectors = { loadingIndicator: '#oc-loading-indicator', progressStub: 'oc-progress-stub' } describe('LoadingIndicator', () => { it('should not render when not loading', () => { const { wrapper } = getWrapper() expect(wrapper.find(selectors.loadingIndicator).exists()).toBeFalsy() }) it('should render when loading', () => { const { wrapper } = getWrapper({ isLoading: true }) expect(wrapper.find(selectors.loadingIndicator).exists()).toBeTruthy() }) describe('indeterminate', () => { it('progress bar should be in indeterminate when no progress given', () => { const { wrapper } = getWrapper({ isLoading: true }) expect( wrapper.findComponent<typeof OcProgress>(selectors.progressStub).props('indeterminate') ).toBeTruthy() }) it('progress bar should not be in indeterminate when progress given', () => { const { wrapper } = getWrapper({ isLoading: true, currentProgress: 50 }) expect( wrapper.findComponent<typeof OcProgress>(selectors.progressStub).props('indeterminate') ).toBeFalsy() }) }) }) function getWrapper({ isLoading = false, currentProgress = null } = {}) { const mocks = { $loadingService: mock<LoadingService>({ isLoading, currentProgress }) } return { wrapper: shallowMount(LoadingIndicator, { global: { plugins: [...defaultPlugins()], mocks, provide: mocks } }) } }
owncloud/web/packages/web-pkg/tests/unit/components/LoadingIndicator.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/LoadingIndicator.spec.ts", "repo_id": "owncloud", "token_count": 608 }
838
import FileInfo from '../../../../../src/components/SideBar/Files/FileInfo.vue' import { defaultComponentMocks, defaultPlugins, shallowMount, RouteLocation } from 'web-test-helpers' import { mock } from 'vitest-mock-extended' import { Resource } from '@ownclouders/web-client' const selectors = { name: '[data-testid="files-info-name"]' } describe('FileInfo', () => { it('shows file info', () => { const { wrapper } = createWrapper() expect(wrapper.find(selectors.name).exists()).toBeTruthy() }) }) function createWrapper() { const file = mock<Resource>({ name: 'someFolder', webDavPath: '', type: 'folder', extension: '' }) return { wrapper: shallowMount(FileInfo, { global: { plugins: [...defaultPlugins()], provide: { resource: file }, mocks: { ...defaultComponentMocks({ currentRoute: mock<RouteLocation>({ path: '/files' }) }) } } }) } }
owncloud/web/packages/web-pkg/tests/unit/components/sidebar/Files/FileInfo.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/sidebar/Files/FileInfo.spec.ts", "repo_id": "owncloud", "token_count": 390 }
839
import { useFileActionsEmptyTrashBin } from '../../../../../src/composables/actions' import { useMessages, useModals } from '../../../../../src/composables/piniaStores' import { createLocationTrash, createLocationSpaces } from '../../../../../src/router' import { mock } from 'vitest-mock-extended' import { getComposableWrapper, defaultComponentMocks, RouteLocation } from 'web-test-helpers' import { unref } from 'vue' import { ProjectSpaceResource, Resource } from '@ownclouders/web-client/src/helpers' import { FileActionOptions } from '../../../../../src/composables/actions' describe('emptyTrashBin', () => { describe('isVisible property', () => { it('should be false when location is invalid', () => { getWrapper({ invalidLocation: true, setup: ({ actions }, { space }) => { expect(unref(actions)[0].isVisible({ space, resources: [] })).toBe(false) } }) }) it('should be false in a space trash bin with insufficient permissions', () => { getWrapper({ driveType: 'project', setup: ({ actions }, { space }) => { expect( unref(actions)[0].isVisible({ space, resources: [{ canBeRestored: () => true }] as Resource[] }) ).toBe(false) } }) }) }) describe('empty trashbin action', () => { it('should trigger the empty trash bin modal window', () => { getWrapper({ setup: async ({ actions }) => { const { dispatchModal } = useModals() await unref(actions)[0].handler(mock<FileActionOptions>()) expect(dispatchModal).toHaveBeenCalledTimes(1) } }) }) }) describe('method "emptyTrashBin"', () => { it('should show message on success', () => { getWrapper({ setup: async ({ emptyTrashBin }, { space }) => { await emptyTrashBin({ space }) const { showMessage } = useMessages() expect(showMessage).toHaveBeenCalledTimes(1) } }) }) it('should show message on error', () => { vi.spyOn(console, 'error').mockImplementation(() => undefined) getWrapper({ resolveClearTrashBin: false, setup: async ({ emptyTrashBin }, { space }) => { await emptyTrashBin({ space }) const { showErrorMessage } = useMessages() expect(showErrorMessage).toHaveBeenCalledTimes(1) } }) }) }) }) function getWrapper({ invalidLocation = false, resolveClearTrashBin = true, driveType = 'personal', setup }: { invalidLocation?: boolean resolveClearTrashBin?: boolean driveType?: string setup: ( instance: ReturnType<typeof useFileActionsEmptyTrashBin>, { space }: { space: ProjectSpaceResource } ) => void }) { const mocks = { ...defaultComponentMocks({ currentRoute: mock<RouteLocation>( invalidLocation ? (createLocationSpaces('files-spaces-generic') as any) : (createLocationTrash('files-trash-generic') as any) ) }), space: mock<ProjectSpaceResource>({ driveType, isEditor: () => false, isManager: () => false }) } if (resolveClearTrashBin) { mocks.$clientService.webdav.clearTrashBin.mockResolvedValue(undefined) } else { mocks.$clientService.webdav.clearTrashBin.mockRejectedValue(new Error('')) } return { wrapper: getComposableWrapper( () => { const instance = useFileActionsEmptyTrashBin() setup(instance, { space: mocks.space }) }, { mocks, provide: mocks } ) } }
owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsEmptyTrashBin.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsEmptyTrashBin.spec.ts", "repo_id": "owncloud", "token_count": 1484 }
840
import { useSpaceActionsRename } from '../../../../../src/composables/actions/spaces' import { useMessages, useModals } from '../../../../../src/composables/piniaStores' import { mock } from 'vitest-mock-extended' import { defaultComponentMocks, mockAxiosResolve, RouteLocation, getComposableWrapper } from 'web-test-helpers' import { unref } from 'vue' import { SpaceResource } from '@ownclouders/web-client/src' describe('rename', () => { describe('handler', () => { it('should trigger the rename modal window', () => { getWrapper({ setup: async ({ actions }) => { const { dispatchModal } = useModals() await unref(actions)[0].handler({ resources: [{ id: '1', name: 'renamed space' } as SpaceResource] }) expect(dispatchModal).toHaveBeenCalledTimes(1) } }) }) it('should not trigger the rename modal window without any resource', () => { getWrapper({ setup: async ({ actions }) => { const { dispatchModal } = useModals() await unref(actions)[0].handler({ resources: [] }) expect(dispatchModal).toHaveBeenCalledTimes(0) } }) }) }) describe('method "renameSpace"', () => { it('should show message on success', () => { getWrapper({ setup: async ({ renameSpace }, { clientService }) => { clientService.graphAuthenticated.drives.updateDrive.mockResolvedValue(mockAxiosResolve()) await renameSpace(mock<SpaceResource>({ id: '1' }), 'renamed space') const { showMessage } = useMessages() expect(showMessage).toHaveBeenCalledTimes(1) } }) }) it('should show message on error', () => { vi.spyOn(console, 'error').mockImplementation(() => undefined) getWrapper({ setup: async ({ renameSpace }, { clientService }) => { clientService.graphAuthenticated.drives.updateDrive.mockRejectedValue(new Error()) await renameSpace(mock<SpaceResource>({ id: '1' }), 'renamed space') const { showErrorMessage } = useMessages() expect(showErrorMessage).toHaveBeenCalledTimes(1) } }) }) }) }) function getWrapper({ setup }: { setup: ( instance: ReturnType<typeof useSpaceActionsRename>, { clientService }: { clientService: ReturnType<typeof defaultComponentMocks>['$clientService'] } ) => void }) { const mocks = defaultComponentMocks({ currentRoute: mock<RouteLocation>({ name: 'files-spaces-projects' }) }) return { mocks, wrapper: getComposableWrapper( () => { const instance = useSpaceActionsRename() setup(instance, { clientService: mocks.$clientService }) }, { mocks, provide: mocks } ) } }
owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsRename.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsRename.spec.ts", "repo_id": "owncloud", "token_count": 1148 }
841
import { getComposableWrapper } from 'web-test-helpers' import { useModals } from '../../../../src/composables/piniaStores' import { createPinia, setActivePinia } from 'pinia' describe('useModals', () => { beforeEach(() => { setActivePinia(createPinia()) }) describe('method "dispatchModal"', () => { it('adds a modal to the stack of modals and sets it active', () => { getWrapper({ setup: (instance) => { const data = { title: 'test' } const modal = instance.dispatchModal(data) expect(modal.id).toBeDefined() expect(modal.title).toEqual(data.title) expect(instance.activeModal).toEqual(modal) const modal2 = instance.dispatchModal(data) expect(instance.activeModal).toEqual(modal2) } }) }) }) describe('method "updateModal"', () => { it('updates a modal with new data', () => { getWrapper({ setup: (instance) => { const modal = instance.dispatchModal({ title: 'test' }) const newTitle = 'new title' instance.updateModal(modal.id, 'title', newTitle) expect(instance.activeModal.title).toEqual(newTitle) } }) }) }) describe('method "removeModal"', () => { it('removes an existing modal and sets another existing modal active', () => { getWrapper({ setup: (instance) => { const modal = instance.dispatchModal({ title: 'test' }) const modal2 = instance.dispatchModal({ title: 'test2' }) expect(instance.modals.length).toBe(2) expect(instance.activeModal).toEqual(modal2) instance.removeModal(modal2.id) expect(instance.modals.length).toBe(1) expect(instance.activeModal).toEqual(modal) } }) }) }) describe('method "setModalActive"', () => { it('moves a modal to the first position of the modal stack, making it active', () => { getWrapper({ setup: (instance) => { const modal = instance.dispatchModal({ title: 'test' }) const modal2 = instance.dispatchModal({ title: 'test2' }) expect(instance.activeModal.id).toEqual(modal2.id) instance.setModalActive(modal.id) expect(instance.activeModal.id).toEqual(modal.id) } }) }) }) }) function getWrapper({ setup }: { setup: (instance: ReturnType<typeof useModals>) => void }) { return { wrapper: getComposableWrapper( () => { const instance = useModals() setup(instance) }, { pluginOptions: { pinia: false } } ) } }
owncloud/web/packages/web-pkg/tests/unit/composables/piniaStores/modals.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/piniaStores/modals.spec.ts", "repo_id": "owncloud", "token_count": 1140 }
842
import { formatFileSize } from '../../../src/helpers' describe('formatFileSize', () => { describe('converts numeric input to a human readable format', () => { it.each([ [0, '0 B'], [1, '1 B'], [1023, '1 kB'], [1024, '1 kB'], [1287654323, '1.3 GB'] ])('input "%s"', (input: number, expected: string) => { expect(formatFileSize(input, '')).toEqual(expected) }) }) describe('converts string input to a human readable format', () => { it.each([ ['0', '0 B'], ['1287654323', '1.3 GB'] ])('input "%s"', (input: string, expected: string) => { expect(formatFileSize(input, '')).toEqual(expected) }) }) describe('rounds values', () => { it('to integers if file size below 1 MB', () => { expect(formatFileSize(4321, '')).toBe('4 kB') }) it('to 1 decimal if file size above 1 MB', () => { expect(formatFileSize(4321000, '')).toBe('4.3 MB') }) }) describe('handles invalid input', () => { it.each([ [-1, ''], ['nonNumericInput', '?'], [NaN, '?'] ])('input "%s"', (input: any, expected: string) => { expect(formatFileSize(input, '')).toEqual(expected) }) }) describe('respects different locales', () => { it.each([ ['en', 1287654323, '1.3 GB'], ['de', 1287654323, '1,3 GB'] ])('language "%s"', (language: string, input: number, expected: string) => { expect(formatFileSize(input, language)).toEqual(expected) }) }) })
owncloud/web/packages/web-pkg/tests/unit/helpers/filesize.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/filesize.spec.ts", "repo_id": "owncloud", "token_count": 642 }
843
import { cacheService } from '../../../src/services' import { Cache } from '../../../src/helpers/cache' describe('cache', () => { describe('cacheService', () => { test('filePreview', () => { const filePreviewCache = cacheService.filePreview expect(filePreviewCache).toBeInstanceOf(Cache) }) test('avatarUrl', () => { const avatarUrlCache = cacheService.avatarUrl expect(avatarUrlCache).toBeInstanceOf(Cache) }) }) })
owncloud/web/packages/web-pkg/tests/unit/services/cache.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/services/cache.spec.ts", "repo_id": "owncloud", "token_count": 164 }
844
<template> <div class="oc-mb-l"> <p v-text="$gettext('Request a personal data export according to §20 GDPR.')" /> <span v-if="loading"> <oc-spinner /> </span> <span v-else-if="exportInProgress" class="oc-flex oc-flex-middle" data-testid="export-in-process" > <oc-icon name="time" fill-type="line" size="small" class="oc-mr-s" /> <span v-text="$gettext('Export is being processed. This can take up to 24 hours.')" /> </span> <div v-else class="oc-flex"> <oc-button appearance="outline" variation="primary" data-testid="request-export-btn" class="oc-mr-s" @click="requestExport" > <span v-text="$gettext('Request new export')" /> </oc-button> <oc-button v-if="exportFile" appearance="outline" variation="primary" data-testid="download-export-btn" @click="downloadExport" > <oc-icon name="download" fill-type="line" size="small" /> <span v-text="$gettext('Download latest export')" /> <span v-text="`(${exportDate})`" /> </oc-button> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, onMounted, onUnmounted, ref, unref } from 'vue' import { useTask } from 'vue-concurrency' import { useGettext } from 'vue3-gettext' import { Resource } from '@ownclouders/web-client' import { useClientService, useMessages, useSpacesStore, useUserStore } from '@ownclouders/web-pkg' import { useDownloadFile } from '@ownclouders/web-pkg' import { formatDateFromJSDate } from '@ownclouders/web-pkg' const GDPR_EXPORT_FILE_NAME = '.personal_data_export.json' const POLLING_INTERVAL = 30000 export default defineComponent({ name: 'GdprExport', setup() { const { showMessage, showErrorMessage } = useMessages() const userStore = useUserStore() const spacesStore = useSpacesStore() const { $gettext, current: currentLanguage } = useGettext() const clientService = useClientService() const { downloadFile } = useDownloadFile() const loading = ref(true) const checkInterval = ref<ReturnType<typeof setInterval>>() const exportFile = ref<Resource>() const exportInProgress = ref(false) const loadExportTask = useTask(function* () { try { const resource = yield clientService.webdav.getFileInfo(spacesStore.personalSpace, { path: `/${GDPR_EXPORT_FILE_NAME}` }) if (resource.processing) { exportInProgress.value = true if (!unref(checkInterval)) { checkInterval.value = setInterval(() => { loadExportTask.perform() }, POLLING_INTERVAL) } return } exportFile.value = resource exportInProgress.value = false if (unref(checkInterval)) { clearInterval(unref(checkInterval)) checkInterval.value = undefined } } catch (e) { if (e.statusCode !== 404) { // resource seems to exist, but something else went wrong console.error(e) } } finally { loading.value = false } }).restartable() const requestExport = async () => { try { await clientService.graphAuthenticated.users.exportPersonalData(userStore.user.id, { storageLocation: `/${GDPR_EXPORT_FILE_NAME}` }) await loadExportTask.perform() showMessage({ title: $gettext('GDPR export has been requested') }) } catch (e) { showErrorMessage({ title: $gettext('GDPR export could not be requested. Please contact an administrator.'), errors: [e] }) } } const downloadExport = () => { return downloadFile(spacesStore.personalSpace, unref(exportFile)) } const exportDate = computed(() => { return formatDateFromJSDate(new Date(unref(exportFile).mdate), currentLanguage) }) onMounted(() => { loadExportTask.perform() }) onUnmounted(() => { if (unref(checkInterval)) { clearInterval(unref(checkInterval)) } }) return { loading, loadExportTask, exportFile, exportInProgress, requestExport, downloadExport, exportDate } } }) </script>
owncloud/web/packages/web-runtime/src/components/Account/GdprExport.vue/0
{ "file_path": "owncloud/web/packages/web-runtime/src/components/Account/GdprExport.vue", "repo_id": "owncloud", "token_count": 1814 }
845
<template> <nav :aria-label="$gettext('Account menu')"> <oc-button id="_userMenuButton" ref="menuButton" v-oc-tooltip="$gettext('My Account')" class="oc-topbar-personal" appearance="raw" :aria-label="$gettext('My Account')" > <avatar-image v-if="onPremisesSamAccountName" class="oc-topbar-avatar oc-topbar-personal-avatar oc-flex-inline oc-flex-center oc-flex-middle" :width="32" :userid="onPremisesSamAccountName" :user-name="user.displayName" /> <oc-avatar-item v-else class="oc-topbar-avatar oc-topbar-unauthenticated-avatar oc-flex-inline oc-flex-center oc-flex-middle" :name="$gettext('User Menu login')" :width="32" icon="user" icon-fill-type="line" icon-color="var(--oc-color-swatch-brand-default)" background="var(--oc-color-swatch-brand-contrast)" /> </oc-button> <oc-drop ref="menu" drop-id="account-info-container" toggle="#_userMenuButton" mode="click" close-on-click padding-size="small" class="oc-overflow-hidden" > <oc-list class="user-menu-list"> <template v-if="!onPremisesSamAccountName"> <li> <oc-button id="oc-topbar-account-manage" type="router-link" :to="accountPageRoute" appearance="raw" > <oc-icon name="settings-4" fill-type="line" class="oc-p-xs" /> <span v-text="$gettext('Preferences')" /> </oc-button> </li> <li> <oc-button id="oc-topbar-account-login" appearance="raw" type="router-link" :to="loginLink" > <oc-icon name="login-box" fill-type="line" class="oc-p-xs" /> <span v-text="$gettext('Log in')" /> </oc-button> </li> </template> <template v-else> <li class="profile-info-wrapper oc-pl-s"> <avatar-image :width="32" :userid="onPremisesSamAccountName" :user-name="user.displayName" /> <span class="profile-info-wrapper" :class="{ 'oc-py-xs': !user.mail }"> <span class="oc-display-block" v-text="user.displayName" /> <span v-if="user.mail" class="oc-text-small" v-text="user.mail" /> </span> </li> <li> <oc-button id="oc-topbar-account-manage" type="router-link" :to="accountPageRoute" appearance="raw" > <oc-icon name="settings-4" fill-type="line" class="oc-p-xs" /> <span v-text="$gettext('Preferences')" /> </oc-button> </li> <li v-for="(app, index) in applicationsList" :key="`user-menu-${index}`"> <oc-button v-if="app.url" type="a" appearance="raw" :target="app.target" :href="app.url" > <oc-icon :name="app.icon" class="oc-p-xs" /> <span v-text="$gettext(app.title)" /> </oc-button> <oc-button v-else type="router-link" appearance="raw" :to="{ path: app.path }"> <oc-icon :name="app.icon" class="oc-p-xs" /> <span v-text="$gettext(app.title)" /> </oc-button> </li> <li v-if="quotaEnabled" class="storage-wrapper oc-pl-s"> <oc-icon name="cloud" fill-type="line" class="oc-p-xs" /> <div class="oc-width-1-1"> <p class="oc-my-rm"> <span class="oc-display-block" v-text="personalStorageLabel" /> <span class="storage-wrapper-quota oc-text-small" v-text="personalStorageDetailsLabel" /> </p> <oc-progress v-if="limitedPersonalStorage" :value="quotaUsagePercent" :max="100" size="small" :variation="quotaProgressVariant" /> </div> </li> <li> <oc-button id="oc-topbar-account-logout" appearance="raw" @click="logout"> <oc-icon name="logout-box-r" fill-type="line" class="oc-p-xs" /> <span v-text="$gettext('Log out')" /> </oc-button> </li> </template> </oc-list> <div v-if="imprintUrl || privacyUrl" class="imprint-footer oc-py-s oc-mt-m oc-text-center"> <oc-button v-if="imprintUrl" type="a" appearance="raw" :href="imprintUrl" target="_blank" ><span v-text="$gettext('Imprint')" /></oc-button> <span v-if="privacyUrl">·</span> <oc-button v-if="privacyUrl" type="a" appearance="raw" :href="privacyUrl" target="_blank" ><span v-text="$gettext('Privacy')" /></oc-button> </div> </oc-drop> </nav> </template> <script lang="ts"> import { storeToRefs } from 'pinia' import { defineComponent, PropType, ComponentPublicInstance, computed, unref } from 'vue' import { filesize } from 'filesize' import { authService } from '../../services/auth' import { useRoute, useSpacesStore, useThemeStore, useUserStore, routeToContextQuery } from '@ownclouders/web-pkg' import { OcDrop } from 'design-system/src/components' export default defineComponent({ props: { applicationsList: { type: Array as PropType<any>, required: false, default: () => [] } }, setup() { const route = useRoute() const userStore = useUserStore() const themeStore = useThemeStore() const spacesStore = useSpacesStore() const { user } = storeToRefs(userStore) const accountPageRoute = computed(() => ({ name: 'account', query: routeToContextQuery(unref(route)) })) const loginLink = computed(() => { return { name: 'login', query: { redirectUrl: unref(route).fullPath } } }) const imprintUrl = computed(() => themeStore.currentTheme.common.urls.imprint) const privacyUrl = computed(() => themeStore.currentTheme.common.urls.privacy) const quota = computed(() => { return spacesStore.personalSpace?.spaceQuota }) return { user, accountPageRoute, loginLink, imprintUrl, privacyUrl, quota } }, computed: { onPremisesSamAccountName() { return this.user?.onPremisesSamAccountName }, personalStorageLabel() { if (!this.limitedPersonalStorage) { return this.$gettext('Personal storage') } return this.$gettext('Personal storage (%{percentage}% used)', { percentage: (this.quotaUsagePercent || 0).toString() }) }, personalStorageDetailsLabel() { const total = this.quota.definition === 'none' ? 0 : this.quota.total || 0 const used = this.quota.used || 0 return total ? this.$gettext('%{used} of %{total} used', { used: filesize(used), total: filesize(total) }) : this.$gettext('%{used} used', { used: filesize(used), total: filesize(total) }) }, limitedPersonalStorage() { return this.quota.total !== 0 }, quotaEnabled() { return !!this.quota }, quotaUsagePercent() { return parseFloat(((this.quota.used / this.quota.total) * 100).toFixed(2)) }, quotaProgressVariant() { if ((this.quotaUsagePercent || 0) < 80) { return 'primary' } if ((this.quotaUsagePercent || 0) < 90) { return 'warning' } return 'danger' } }, mounted() { ;(this.$refs.menu as InstanceType<typeof OcDrop>)?.tippy?.setProps({ onHidden: () => (this.$refs.menuButton as ComponentPublicInstance).$el.focus(), onShown: () => (this.$refs.menu as ComponentPublicInstance).$el.querySelector('a:first-of-type').focus() }) }, methods: { logout() { authService.logoutUser() } } }) </script> <style lang="scss" scoped> .user-menu-list li { align-items: center; display: flex; margin: var(--oc-space-xsmall) 0; &:first-child { margin-top: 0; } &:last-child { margin-bottom: 0; } a, button { gap: var(--oc-space-medium); justify-content: flex-start; min-height: 3rem; padding-left: var(--oc-space-small); width: 100%; &:focus, &:hover { background-color: var(--oc-color-background-hover); color: var(--oc-color-swatch-passive-default); text-decoration: none; } } &.profile-info-wrapper, &.storage-wrapper { gap: var(--oc-space-medium); min-height: 3rem; } } .imprint-footer { background-color: var(--oc-color-background-hover); margin-left: calc(var(--oc-space-small) * -1); width: calc(100% + var(--oc-space-small) * 2); margin-bottom: calc(var(--oc-space-small) * -1) !important; a { font-size: var(--oc-font-size-medium) !important; color: var(--oc-color-text-default); } } </style>
owncloud/web/packages/web-runtime/src/components/Topbar/UserMenu.vue/0
{ "file_path": "owncloud/web/packages/web-runtime/src/components/Topbar/UserMenu.vue", "repo_id": "owncloud", "token_count": 4514 }
846
import { CapabilityStore } from '@ownclouders/web-pkg' export const getWebVersion = (): string => { return `ownCloud Web UI ${process.env.PACKAGE_VERSION}` } export const getBackendVersion = ({ capabilityStore }: { capabilityStore: CapabilityStore }): string => { const backendStatus = capabilityStore.status if (!backendStatus || !backendStatus.versionstring) { return undefined } const product = backendStatus.product || 'ownCloud' const version = backendStatus.productversion || backendStatus.versionstring const edition = backendStatus.edition return `${product} ${version} ${edition}` }
owncloud/web/packages/web-runtime/src/container/versions.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/container/versions.ts", "repo_id": "owncloud", "token_count": 175 }
847
const tape = [] const isDomNode = (node) => node instanceof Element const DIRECTION_FORWARD = 'forward' const DIRECTION_BACKWARD = 'backward' export default { methods: { focus({ from, to, revert }) { const direction = revert ? DIRECTION_BACKWARD : DIRECTION_FORWARD if (from && direction === DIRECTION_FORWARD) { tape.splice(0, tape.length) } else { from = document.activeElement } if (direction === DIRECTION_FORWARD) { tape.push(from) } if (direction === DIRECTION_BACKWARD) { to = tape.pop() } if (isDomNode(to)) { to.focus() } } } }
owncloud/web/packages/web-runtime/src/mixins/focusMixin.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/mixins/focusMixin.ts", "repo_id": "owncloud", "token_count": 275 }
848
import { AuthStore, CapabilityStore, ClientService } from '@ownclouders/web-pkg' import { PublicLinkType } from '@ownclouders/web-client/src/helpers' export interface PublicLinkManagerOptions { clientService: ClientService authStore: AuthStore capabilityStore: CapabilityStore } export class PublicLinkManager { private clientService: ClientService private authStore: AuthStore private capabilityStore: CapabilityStore constructor(options: PublicLinkManagerOptions) { this.clientService = options.clientService this.authStore = options.authStore this.capabilityStore = options.capabilityStore } private static buildStorageKey(token: string, suffix: string): string { return `oc.publicLink.${token}.${suffix}` } clear(token: string) { ;['resolved', 'passwordRequired', 'password'].forEach((key) => { sessionStorage.removeItem(PublicLinkManager.buildStorageKey(token, key)) }) this.authStore.clearPublicLinkContext() } isResolved(token: string): boolean { const resolved = sessionStorage.getItem(PublicLinkManager.buildStorageKey(token, 'resolved')) return resolved === 'true' } setResolved(token: string, resolved: boolean): void { sessionStorage.setItem(PublicLinkManager.buildStorageKey(token, 'resolved'), resolved + '') } setType(token: string, type: PublicLinkType): void { sessionStorage.setItem(PublicLinkManager.buildStorageKey(token, 'type'), type) } getType(token: string): PublicLinkType { return sessionStorage.getItem( PublicLinkManager.buildStorageKey(token, 'type') ) as PublicLinkType } isPasswordRequired(token: string): boolean { const passwordRequired = sessionStorage.getItem( PublicLinkManager.buildStorageKey(token, 'passwordRequired') ) return passwordRequired === 'true' } setPasswordRequired(token: string, required: boolean): void { sessionStorage.setItem( PublicLinkManager.buildStorageKey(token, 'passwordRequired'), required + '' ) } getPassword(token: string): string { const password = sessionStorage.getItem(PublicLinkManager.buildStorageKey(token, 'password')) if (password) { try { return Buffer.from(password, 'base64').toString() } catch (e) { this.clear(token) } } return '' } setPassword(token: string, password: string): void { if (password.length) { const encodedPassword = Buffer.from(password).toString('base64') sessionStorage.setItem(PublicLinkManager.buildStorageKey(token, 'password'), encodedPassword) } else { sessionStorage.removeItem(PublicLinkManager.buildStorageKey(token, 'password')) } } async updateContext(token: string) { if (!this.isResolved(token)) { return } if (this.authStore.publicLinkContextReady && this.authStore.publicLinkToken === token) { return } let password if (this.isPasswordRequired(token)) { password = this.getPassword(token) } try { await this.fetchCapabilities({ password }) } catch (e) { console.error(e) } this.authStore.setPublicLinkContext({ publicLinkToken: token, publicLinkPassword: password, publicLinkContextReady: true, publicLinkType: this.getType(token) }) } clearContext() { this.authStore.clearPublicLinkContext() } private async fetchCapabilities({ password = '' }): Promise<void> { if (this.capabilityStore.isInitialized) { return } const client = this.clientService.ocsPublicLinkContext(password) const response = await client.getCapabilities() this.capabilityStore.setCapabilities(response) } }
owncloud/web/packages/web-runtime/src/services/auth/publicLinkManager.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/services/auth/publicLinkManager.ts", "repo_id": "owncloud", "token_count": 1239 }
849
import FeedbackLink from '../../../../src/components/Topbar/FeedbackLink.vue' import { defaultPlugins, mount } from 'web-test-helpers' describe('FeedbackLink component', () => { describe('properties', () => { it('allows to overwrite the link href', async () => { const { wrapper } = getWrapper() const url = 'https://some-link.tld/' await wrapper.setProps({ href: url }) expect(wrapper.find('a').attributes().href).toEqual(url) }) it('allows to overwrite the link ariaLabel', async () => { const { wrapper } = getWrapper() const ariaLabel = 'some aria label' await wrapper.setProps({ ariaLabel }) expect(wrapper.find('a').attributes()['aria-label']).toEqual(ariaLabel) }) it('allows to overwrite the link description', async () => { const { wrapper } = getWrapper() const description = 'some lengthy description' await wrapper.setProps({ description }) expect(wrapper.find('#oc-feedback-link-description').text()).toEqual(description) }) }) }) const getWrapper = () => { return { wrapper: mount(FeedbackLink, { global: { plugins: [...defaultPlugins()] } }) } }
owncloud/web/packages/web-runtime/tests/unit/components/Topbar/FeedbackLink.spec.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Topbar/FeedbackLink.spec.ts", "repo_id": "owncloud", "token_count": 439 }
850
import focusMixin from '../../../src/mixins/focusMixin' import { defineComponent } from 'vue' import { mount } from 'web-test-helpers' const Component = defineComponent({ name: 'DummyComponent', mixins: [focusMixin], template: ` <ul> <li v-for="index in 10" :key="index"> <a v-bind:id="'item-' + index" tabindex="0">{{index}}</a> </li> </ul> ` }) function getWrapper() { return { wrapper: mount(Component, { attachTo: document.body }) } } const { wrapper } = getWrapper() const wrapperComponent = wrapper.findComponent({ name: 'DummyComponent' }) const item1 = wrapper.get('#item-1') const item2 = wrapper.get('#item-2') const item3 = wrapper.get('#item-3') const item4 = wrapper.get('#item-4') const item5 = wrapper.get('#item-5') const item6 = wrapper.get('#item-6') const item7 = wrapper.get('#item-7') const item8 = wrapper.get('#item-8') const item9 = wrapper.get('#item-9') const item10 = wrapper.get('#item-10') const focus = wrapperComponent.vm?.focus describe('focusMixin', () => { // trap ----------------------- // #item-1 || --- x || 3 <-- // #item-2 || --> 4 || x --- // #item-3 || --> 1 || 5 <-- // #item-4 || --> 6 || 2 <-- // #item-5 || --> 3 || 7 <-- // #item-6 || --> 8 || 4 <-- // #item-7 || --> 5 || 9 <-- // #item-8 || --> 10 || 6 <-- // #item-9 || --> 7 || 10 <-- // #item-10 || --> 9 || 8 <-- it('records and replays focus events', () => { focus({ from: item2.element, to: item4.element }) expect(document.activeElement.id).toBe(item4.element.id) focus({ to: item6.element }) expect(document.activeElement.id).toBe(item6.element.id) focus({ to: item8.element }) expect(document.activeElement.id).toBe(item8.element.id) focus({ to: item10.element }) expect(document.activeElement.id).toBe(item10.element.id) focus({ to: item9.element }) expect(document.activeElement.id).toBe(item9.element.id) focus({ to: item7.element }) expect(document.activeElement.id).toBe(item7.element.id) focus({ to: item5.element }) expect(document.activeElement.id).toBe(item5.element.id) focus({ to: item3.element }) expect(document.activeElement.id).toBe(item3.element.id) focus({ to: item1.element }) expect(document.activeElement.id).toBe(item1.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item3.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item5.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item7.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item9.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item10.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item8.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item6.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item4.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item2.element.id) }) // trap ---------------------- // #item-2 || --> 4 || x --- // #item-4 || --> 6 || x --- // #item-6 || --- x || 4 <-- // restart trap -------------- // #item-1 || --> 8 || x --- // #item-8 || --> 10 || 1 <-- // #item-10 || --- x || 8 <-- it('can be restarted', () => { focus({ from: item2.element, to: item4.element }) expect(document.activeElement.id).toBe(item4.element.id) focus({ to: item6.element }) expect(document.activeElement.id).toBe(item6.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item4.element.id) focus({ from: item1.element, to: item8.element }) expect(document.activeElement.id).toBe(item8.element.id) focus({ to: item10.element }) expect(document.activeElement.id).toBe(item10.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item8.element.id) focus({ revert: true }) expect(document.activeElement.id).toBe(item1.element.id) }) })
owncloud/web/packages/web-runtime/tests/unit/mixins/focusMixin.spec.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/tests/unit/mixins/focusMixin.spec.ts", "repo_id": "owncloud", "token_count": 1617 }
851
diff --git a/lib/components/date-picker.umd.js b/lib/components/date-picker.umd.js index 571ada2a0d82ed79833600b75eca9a5ec670660f..124df53b7b8fe976c5afcc4588783b3c626cd8e2 100644 --- a/lib/components/date-picker.umd.js +++ b/lib/components/date-picker.umd.js @@ -17351,7 +17351,7 @@ const _yearGroupCount = 12; for (let year = startYear; year < endYear; year += 1) { let enabled = false; - for (let month = 1; month < 12; month++) { + for (let month = 1; month <= 12; month++) { enabled = this.validator({ month, year
owncloud/web/patches/v-calendar@2.3.4.patch/0
{ "file_path": "owncloud/web/patches/v-calendar@2.3.4.patch", "repo_id": "owncloud", "token_count": 279 }
852
let numAjaxRequestsStart = 0 let start = 0 let end = 0 const sleepWhenNoNewAjaxCallsStarted = function (result) { const currentTime = Date.now() if (result.value <= numAjaxRequestsStart && currentTime < end) { this.pause(this.globals.waitForConditionPollInterval) checkSumStartedAjaxRequests(this) } if (currentTime >= end) { console.error('Timeout waiting for Ajax calls to start') } } const checkSumStartedAjaxRequests = function (api) { api.execute('return window.sumStartedAjaxRequests', [], sleepWhenNoNewAjaxCallsStarted) } exports.command = function () { // init the ajax counters if they haven't been initialized yet this.execute( 'return (typeof window.sumStartedAjaxRequests === "undefined")', [], function (result) { if (result.value === true) { this.initAjaxCounters() } } ) this.execute('return window.sumStartedAjaxRequests', [], function (result) { numAjaxRequestsStart = result.value }) start = Date.now() end = start + this.globals.waitForNegativeConditionTimeout checkSumStartedAjaxRequests(this) this.waitForOutstandingAjaxCalls() }
owncloud/web/tests/acceptance/customCommands/waitForAjaxCallsToStartAndFinish.js/0
{ "file_path": "owncloud/web/tests/acceptance/customCommands/waitForAjaxCallsToStartAndFinish.js", "repo_id": "owncloud", "token_count": 412 }
853
Feature: rename files As a user I want to rename files So that I can organise my data structure Background: Given user "Alice" has been created with default attributes and without skeleton files in the server And user "Alice" has uploaded file "lorem.txt" to "lorem.txt" in the server And user "Alice" has uploaded file "data.zip" to "data.zip" in the server And user "Alice" has uploaded file "lorem-big.txt" to "lorem-big.txt" in the server @smokeTest @ocisSmokeTest @disablePreviews Scenario Outline: Rename a file Given user "Alice" has logged in using the webUI When the user renames file "lorem.txt" to <to_file_name> using the webUI Then file <to_file_name> should be listed on the webUI When the user reloads the current page of the webUI Then file <to_file_name> should be listed on the webUI Examples: | to_file_name | | "simple-name.txt" | | '"quotes1"' | | "\"quote\"d-folders'" | | "'quotes2'" | | "लोरेम।तयक्स्त? $%#&@" | Scenario Outline: Rename a file that has special characters in its name Given user "Alice" has created file <from_name> in the server And user "Alice" has logged in using the webUI When the user renames file <from_name> to <to_name> using the webUI Then file <to_name> should be listed on the webUI When the user reloads the current page of the webUI Then file <to_name> should be listed on the webUI Examples: | from_name | to_name | | "'single'quotes.txt" | "single-quotes.txt" | | "strängé filename (duplicate #2 &).txt" | "strängé filename (duplicate #3).txt" | | "sämple,1.txt" | "file,with,commä,.txt" | @smokeTest Scenario: Rename a file using special characters and check its existence after page reload Given user "Alice" has created file "zzzz-must-be-last-file-in-folder.txt" in the server And user "Alice" has logged in using the webUI When the user renames file "lorem.txt" to "लोरेम।तयक्स्त $%&" using the webUI And the user reloads the current page of the webUI Then file "लोरेम।तयक्स्त $%&" should be listed on the webUI When the user renames file "लोरेम।तयक्स्त $%&" to '"double"quotes.txt' using the webUI And the user reloads the current page of the webUI Then file '"double"quotes.txt' should be listed on the webUI When the user renames file '"double"quotes.txt' to "no-double-quotes.txt" using the webUI And the user reloads the current page of the webUI Then file "no-double-quotes.txt" should be listed on the webUI When the user renames file 'no-double-quotes.txt' to "hash#And&QuestionMark?At@Filename.txt" using the webUI And the user reloads the current page of the webUI Then file "hash#And&QuestionMark?At@Filename.txt" should be listed on the webUI When the user renames file 'zzzz-must-be-last-file-in-folder.txt' to "aaaaaa.txt" using the webUI And the user reloads the current page of the webUI Then file "aaaaaa.txt" should be listed on the webUI @issue-964 Scenario: Rename a file using spaces at front and/or back of file name and type Given user "Alice" has logged in using the webUI When the user renames file "lorem.txt" to " space at start" using the webUI And the user reloads the current page of the webUI Then file " space at start" should be listed on the webUI When the user renames file " space at start" to "space at end .txt" using the webUI And the user reloads the current page of the webUI Then file "space at end .txt" should be listed on the webUI When the user renames file "space at end .txt" to "space at end. lis" using the webUI And the user reloads the current page of the webUI Then file "space at end. lis" should be listed on the webUI When the user renames file "space at end. lis" to " multiple space all over . dat" using the webUI And the user reloads the current page of the webUI Then file " multiple space all over . dat" should be listed on the webUI Scenario: Rename a file using spaces at end is prohibited Given user "Alice" has logged in using the webUI When the user tries to rename file "lorem.txt" to "space at end " using the webUI Then the error message 'The name cannot end with whitespace' should be displayed on the webUI dialog prompt When the user reloads the current page of the webUI Then file "lorem.txt" should be listed on the webUI And file "space at end " should not be listed on the webUI When the user tries to rename file "lorem.txt" to " multiple space all over . dat " using the webUI Then the error message 'The name cannot end with whitespace' should be displayed on the webUI dialog prompt And the user reloads the current page of the webUI And file "lorem.txt" should be listed on the webUI And file " multiple space all over . dat " should not be listed on the webUI @issue-4859 @disablePreviews Scenario: Rename a file using both double and single quotes Given user "Alice" has logged in using the webUI When the user renames the following file using the webUI | fromName | toName | | lorem.txt | '"First 'single" quotes" '.txt | | lorem-big.txt | Test" 'me o'ut".txt | And the user reloads the current page of the webUI Then these files should be listed on the webUI | files | | '"First 'single" quotes" '.txt | | Test" 'me o'ut".txt | When the user renames the following file using the webUI | fromName | toName | | '"First 'single" quotes" '.txt | loremz.dat | | Test" 'me o'ut".txt | loremy.tad | And the user reloads the current page of the webUI Then file "loremz.dat" should be listed on the webUI And file "loremy.tad" should be listed on the webUI Scenario Outline: Rename a file/folder using forward slash in its name Given user "Alice" has logged in using the webUI When the user tries to rename file "<from_file_name>" to "<to_file_name>" using the webUI Then the error message 'The name cannot contain "/"' should be displayed on the webUI dialog prompt And file "<from_file_name>" should be listed on the webUI Examples: | from_file_name | to_file_name | | lorem.txt | simple-folder/lorem.txt | | lorem.txt | lorem/txt | Scenario: Rename the last file in a folder Given user "Alice" has created file "zzzz-must-be-last-file-in-folder.txt" in the server And user "Alice" has logged in using the webUI When the user renames file "zzzz-must-be-last-file-in-folder.txt" to "a-file.txt" using the webUI And the user reloads the current page of the webUI Then file "a-file.txt" should be listed on the webUI Scenario: Rename a file to become the last file in a folder Given user "Alice" has logged in using the webUI When the user renames file "lorem.txt" to "zzzz-z-this-is-now-the-last-file.txt" using the webUI And the user reloads the current page of the webUI Then file "zzzz-z-this-is-now-the-last-file.txt" should be listed on the webUI Scenario: Rename a file putting a name of a file which already exists Given user "Alice" has logged in using the webUI When the user tries to rename file "data.zip" to "lorem.txt" using the webUI Then the error message 'The name "lorem.txt" is already taken' should be displayed on the webUI dialog prompt And file 'data.zip' should be listed on the webUI Scenario: Rename a file to .. Given user "Alice" has logged in using the webUI When the user tries to rename file "data.zip" to ".." using the webUI Then the error message 'The name cannot be equal to ".."' should be displayed on the webUI dialog prompt And file 'data.zip' should be listed on the webUI Scenario: Rename a file to . Given user "Alice" has logged in using the webUI When the user tries to rename file "data.zip" to "." using the webUI Then the error message 'The name cannot be equal to "."' should be displayed on the webUI dialog prompt And file 'data.zip' should be listed on the webUI Scenario: Rename a file to .part Given user "Alice" has logged in using the webUI When the user renames file "data.zip" to "data.part" using the webUI Then file 'data.part' should be listed on the webUI Scenario: Rename file extension through context-menu without reload Given user "Alice" has logged in using the webUI When the user renames file "lorem.txt" to "lorem.md" through context-menu using the webUI Then file "lorem.md" should be listed on the webUI And file "lorem.md" should be listed on the sidebar
owncloud/web/tests/acceptance/features/webUIRenameFiles/renameFiles.feature/0
{ "file_path": "owncloud/web/tests/acceptance/features/webUIRenameFiles/renameFiles.feature", "repo_id": "owncloud", "token_count": 3312 }
854
Feature: create markdown files As a user I want to create markdown files So that I can organize my text data in formatted form Background: Given user "Alice" has been created with default attributes and without skeleton files in the server And user "Alice" has uploaded file with content "simple markdown file" to "simple.md" in the server And user "Alice" has logged in using the webUI And the user has browsed to the personal page @disablePreviews Scenario: create a new markdown file in the root directory When the user creates a markdown file with the name "simple_new.md" using the webUI Then the file "simple_new.md" should be displayed in the text editor webUI When the user closes the text editor using the webUI Then as "Alice" file "simple_new.md" should exist in the server And file "simple_new.md" should be listed on the webUI @disablePreviews Scenario: update a markdown file with new content Given the user has opened file "simple.md" in the text editor webUI When the user inputs the content "updated content" in the text editor webUI And the user saves the file in the text editor webUI And the user closes the text editor using the webUI Then as "Alice" the file "simple.md" should have the content "updated content" in the server @disablePreviews Scenario: append new content in a markdown file Given the user has opened file "simple.md" in the text editor webUI When the user appends the content " new content added" in the text editor webUI And the user saves the file in the text editor webUI And the user closes the text editor using the webUI Then as "Alice" the file "simple.md" should have the content "simple markdown file new content added" in the server @disablePreviews Scenario: close the text editor without saving the updated content Given the user has opened file "simple.md" in the text editor webUI When the user inputs the content "updated content" in the text editor webUI And the user closes the text editor using the webUI And as "Alice" the file "simple.md" should have the content "simple markdown file" in the server @disablePreviews Scenario: preview content of the file When the user opens file "simple.md" in the text editor webUI Then the file "simple.md" should be displayed in the text editor webUI And the preview panel should have the content "simple markdown file" on the webUI @disablePreviews Scenario: preview content of the file while editing Given the user has opened file "simple.md" in the text editor webUI When the user inputs the content "updating the file with new content" in the text editor webUI Then the preview panel should have the content "updating the file with new content" on the webUI @disablePreviews Scenario: open text file in text editor Given user "Alice" has uploaded file with content "test" to "lorem.txt" in the server And the user has reloaded the current page of the webUI When the user opens file "lorem.txt" in the text editor webUI Then the file "lorem.txt" should be displayed in the text editor webUI @disablePreviews Scenario Outline: preview of files with text editor by clicking the action menu option Given user "Alice" has uploaded file with content "test" to "lorem.txt" in the server And the user has reloaded the current page of the webUI When the user opens file "<file>" in the text editor using the action menu option on the webUI Then the file "<file>" should be displayed in the text editor webUI Examples: | file | | simple.md | | lorem.txt | @disablePreviews Scenario Outline: Previewing text writen in markdown format Given the user has opened file "simple.md" in the text editor webUI When the user inputs the content "<content>" in the text editor webUI Then the preview panel should have "<tagname>" element with text "<innertext>" Examples: | content | innertext | tagname | | `code` | code | p > code | | # heading | heading | h1 | | ###### heading | heading | h6 | | - list1 | list1 | ul > li | | [link]() | link | p > a |
owncloud/web/tests/acceptance/features/webUITextEditor/textFile.feature/0
{ "file_path": "owncloud/web/tests/acceptance/features/webUITextEditor/textFile.feature", "repo_id": "owncloud", "token_count": 1278 }
855
module.exports = { camelize: function (str) { return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) { if (+match === 0) { return '' // or if (/\s+/.test(match)) for white spaces } return index === 0 ? match.toLowerCase() : match.toUpperCase() }) } }
owncloud/web/tests/acceptance/helpers/stringHelper.js/0
{ "file_path": "owncloud/web/tests/acceptance/helpers/stringHelper.js", "repo_id": "owncloud", "token_count": 136 }
856
const util = require('util') const _ = require('lodash') const sharingHelper = require('../../helpers/sharingHelper') const timeoutHelper = require('../../helpers/timeoutHelper') module.exports = { commands: { /** * opens expiration date field on the webUI * @return {*} */ openExpirationDatePicker: function () { this.useCss() .waitForElementVisible( '@expirationDateField', this.api.globals.waitForNegativeConditionTimeout ) .click('@expirationDateField') }, /** * clicks the edit button of public link * * @param linkName Name of the public link * @returns {Promise<void>} */ clickLinkEditBtn: function (linkName) { const linkRowEditButtonSelector = this.elements.publicLinkContainer.selector + util.format(this.elements.publicLinkEditButton.selector, linkName) const linkRowEditButton = { locateStrategy: this.elements.publicLinkEditButton.locateStrategy, selector: linkRowEditButtonSelector } return this.waitForElementVisible(linkRowEditButton) .initAjaxCounters() .click(linkRowEditButton) .waitForOutstandingAjaxCalls() }, clickLinkAddPasswordBtn: function (linkName) { const linkRowAddPasswordSelector = this.elements.publicLinkContainer.selector + util.format(this.elements.publicLinkAddPasswordButton.selector, linkName) const publicLinkAddPasswordButton = { locateStrategy: this.elements.publicLinkAddPasswordButton.locateStrategy, selector: linkRowAddPasswordSelector } return this.waitForElementVisible(publicLinkAddPasswordButton) .initAjaxCounters() .click(publicLinkAddPasswordButton) .waitForOutstandingAjaxCalls() }, clickLinkEditPasswordBtn: function (linkName) { const linkRowEditPasswordSelector = this.elements.publicLinkContainer.selector + util.format(this.elements.publicLinkRenamePasswordButton.selector, linkName) const publicLinkRenamePasswordButton = { locateStrategy: this.elements.publicLinkRenamePasswordButton.locateStrategy, selector: linkRowEditPasswordSelector } return this.waitForElementVisible(publicLinkRenamePasswordButton) .initAjaxCounters() .click(publicLinkRenamePasswordButton) .waitForOutstandingAjaxCalls() }, clickLinkEditNameBtn: function (linkName) { const linkRowEditNameSelector = this.elements.publicLinkContainer.selector + util.format(this.elements.publicLinkRenameButton.selector, linkName) const publicLinkRenameButton = { locateStrategy: this.elements.publicLinkRenameButton.locateStrategy, selector: linkRowEditNameSelector } return this.waitForElementVisible(publicLinkRenameButton) .initAjaxCounters() .click(publicLinkRenameButton) .waitForOutstandingAjaxCalls() }, clickLinkEditExpirationBtn: function (linkName) { const linkRowEditExpirationDateSelector = this.elements.publicLinkContainer.selector + util.format(this.elements.publicLinkExpirationDateEditButton.selector, linkName) const publicLinkExpirationDateEditButton = { locateStrategy: this.elements.publicLinkExpirationDateEditButton.locateStrategy, selector: linkRowEditExpirationDateSelector } return this.waitForElementVisible(publicLinkExpirationDateEditButton) .initAjaxCounters() .click(publicLinkExpirationDateEditButton) .waitForOutstandingAjaxCalls() }, isRemovePasswordBtnVisible: async function (linkName, expectedVisible = true) { let isVisible = false const publicLinkRemovePasswordSelector = this.elements.publicLinkContainer.selector + util.format(this.elements.publicLinkRemovePasswordButton.selector, linkName) const publicLinkRemovePasswordButton = { locateStrategy: this.elements.publicLinkRemovePasswordButton.locateStrategy, selector: publicLinkRemovePasswordSelector } const timeout = expectedVisible ? this.api.globals.waitForConditionTimeout : this.api.globals.waitForNegativeConditionTimeout await this.isVisible( { ...publicLinkRemovePasswordButton, timeout: timeoutHelper.parseTimeout(timeout), suppressNotFoundErrors: !expectedVisible }, (result) => { isVisible = result.value === true } ) return isVisible }, /** * sets role or permissions for public link on webUI * * @param {string} role - e.g. Viewer, Contributor, Editor, Uploader * @returns {Promise<void>} */ setPublicLinkInitialRole: function (role) { role = _(role).chain().toLower().startCase().replace(/\s/g, '').value() const selectedRoleDropdown = util.format( this.elements.publicLinkRoleSelectionDropdown.selector, role ) return this.click('@selectRoleButton') .click(`@role${role}`) .useXpath() .waitForElementVisible(selectedRoleDropdown) .useCss() }, /** * sets name of the public link share on webUI * * @param {string} linkName Name of the public link share * */ setPublicLinkName: function (linkName) { return this.waitForElementVisible('@publicLinkNameInputField') .clearValue('@publicLinkNameInputField') .setValue('@publicLinkNameInputField', linkName) }, /** * sets password of the public link share * * @param {string} linkPassword * @returns {Promise<void>} */ setPublicLinkPassword: function (linkPassword) { this.waitForElementVisible('@publicLinkPasswordField') if (linkPassword === '') { return this.click('@publicLinkDeletePasswordButton') } return this.clearValue('@publicLinkPasswordField').setValue( '@publicLinkPasswordField', linkPassword ) }, /** * function sets different fields for public link * * @param key fields like name, password, expireDate, role * @param value values for the different fields to be set * @returns {*|Promise<void>|exports} */ setPublicLinkForm: async function (key, value) { if (key === 'role') { return this.setPublicLinkInitialRole(value) } else if (key === 'name') { return this.setPublicLinkName(value) } else if (key === 'password') { return this.setPublicLinkPassword(value) } else if (key === 'expireDate') { value = sharingHelper.calculateDate(value) await this.openExpirationDatePicker() return this.api.page.FilesPageElement.expirationDatePicker().setExpirationDate( value, 'link' ) } return this }, changeExpirationDate: async function (linkName, expiry) { const value = sharingHelper.calculateDate(expiry) await this.clickLinkEditBtn(linkName) await this.clickLinkEditExpirationBtn(linkName) return this.api.page.FilesPageElement.expirationDatePicker().setExpirationDate(value, 'link') }, openRolesDrop: function (linkName) { const linkRowEditRoleButtonSelector = this.elements.publicLinkContainer.selector + util.format(this.elements.publicLinkEditRoleButton.selector, linkName) const linkRowEditRoleButton = { locateStrategy: this.elements.publicLinkEditRoleButton.locateStrategy, selector: linkRowEditRoleButtonSelector } return this.waitForElementVisible(linkRowEditRoleButton) .initAjaxCounters() .click(linkRowEditRoleButton) .waitForOutstandingAjaxCalls() }, setPublicLinkRole: function (role) { role = _(role).chain().toLower().startCase().replace(/\s/g, '').value() return this.waitForElementVisible(`@role${role}`) .initAjaxCounters() .click(`@role${role}`) .waitForOutstandingAjaxCalls() }, changeRole: async function (linkName, role) { await this.openRolesDrop(linkName) await this.setPublicLinkRole(role) return this }, /** * clicks save button of public link form * * @returns {exports} */ savePublicLink: async function () { await this.waitForElementVisible('@publicLinkSaveButton') .initAjaxCounters() .click('@publicLinkSaveButton') try { await this.waitForElementNotPresent({ selector: '@publicLinkSaveButton' }).waitForOutstandingAjaxCalls() } catch (e) { throw new Error('ElementPresentError') } return this }, /** * deletes existing public link share * * @param {string} linkName Name of the public link share of a resource to be deleted * @returns {exports} */ removePublicLink: async function (linkName) { const linkRowDeleteButtonSelector = this.elements.publicLinkContainer.selector + util.format(this.elements.publicLinkDeleteButton.selector, linkName) const linkRowDeleteButton = { locateStrategy: this.elements.publicLinkDeleteButton.locateStrategy, selector: linkRowDeleteButtonSelector } await this.clickLinkEditBtn(linkName) return this.waitForElementVisible(linkRowDeleteButton) .initAjaxCounters() .click(linkRowDeleteButton) .waitForElementVisible('@dialog') .waitForAnimationToFinish() // wait for transition on the modal to finish .click('@dialogConfirmBtnEnabled') .waitForOutstandingAjaxCalls() }, /** * cancels remove public link share action * * @param {string} linkName Name of the public link share of a resource to be deleted * @returns {exports} */ cancelRemovePublicLink: async function (linkName) { const linkRowDeleteButtonSelector = this.elements.publicLinkContainer.selector + util.format(this.elements.publicLinkDeleteButton.selector, linkName) const linkRowDeleteButton = { locateStrategy: this.elements.publicLinkDeleteButton.locateStrategy, selector: linkRowDeleteButtonSelector } await this.clickLinkEditBtn(linkName) return this.waitForElementVisible(linkRowDeleteButton) .initAjaxCounters() .click(linkRowDeleteButton) .waitForElementVisible('@dialog') .waitForAnimationToFinish() // wait for transition on the modal to finish .click('@dialogCancelBtn') .waitForOutstandingAjaxCalls() }, /** * checks if public link share with given name is present * * @param {string} linkName - Name of the public link share to be asserted * @returns {boolean} */ isPublicLinkPresent: async function (linkName) { const fileNameSelectorXpath = this.elements.publicLinkContainer.selector + this.elements.publicLinkName.selector let isPresent await this.api.elements( this.elements.publicLinkName.locateStrategy, util.format(fileNameSelectorXpath, linkName), (result) => { isPresent = result.value.length > 0 } ) return isPresent }, /** * creates a new public link * * @returns {*} */ addNewLink: function () { return this.waitForElementVisible('@publicLinkCreateButton') .initAjaxCounters() .click('@publicLinkCreateButton') .waitForElementNotPresent('@popupNotificationMessage') .waitForOutstandingAjaxCalls() }, /** * Gets the data of all public links of the currently open public link panel * * @param {Object.<String,Object>} subSelectors Map of arbitrary attribute name to selector to query * inside the collaborator element, defaults to all when null * @returns {Array.<Object>} array of link data */ getPublicLinkList: async function (subSelectors = null) { if (subSelectors === null) { subSelectors = { name: this.elements.publicLinkSubName, role: this.elements.publicLinkSubRole, viaLabel: this.elements.publicLinkSubVia } } const informationSelector = this.elements.publicLinkContainer.selector + this.elements.publicLinkInformation.selector let results = [] let linkElementIds = null await this.waitForElementPresent({ locateStrategy: 'xpath', selector: informationSelector, abortOnFailure: false }).api.elements('xpath', informationSelector, (result) => { linkElementIds = result.value.map((item) => item[Object.keys(item)[0]]) }) results = linkElementIds.map(async (linkElementId) => { const linkResult = {} for (const attrName in subSelectors) { let attrElementId = null await this.api.elementIdElement( linkElementId, 'css selector', subSelectors[attrName], (result) => { if (result.status !== -1) { attrElementId = result.value.ELEMENT } } ) // hack to check for presence of via-button // since the redesign removed the visual via-text if (attrElementId && attrName === 'viaLabel') { linkResult.viaLabel = true } else if (attrElementId) { await this.api.elementIdText(attrElementId, (text) => { linkResult[attrName] = text.value }) } else { linkResult[attrName] = null } } return linkResult }) results = await Promise.all(results) return results }, /** * gets the urls of all public links of the currently open public link panel * * @returns {Promise<string>} */ getPublicLinkUrls: async function () { const promiseList = [] const publicLinkUrlXpath = this.elements.publicLinkContainer.selector + this.elements.publicLinkInformation.selector + this.elements.publicLinkUrl.selector await this.waitForElementPresent({ locateStrategy: 'xpath', selector: publicLinkUrlXpath, abortOnFailure: false }).api.elements('xpath', publicLinkUrlXpath, (result) => { result.value.forEach((item) => { promiseList.push( new Promise((resolve) => { this.api.elementIdAttribute(item.ELEMENT, 'innerText', (text) => { resolve(text) }) }) ) }) }) return Promise.all(promiseList) }, /** * * @returns {Promise<string>} */ getErrorMessage: async function () { let message await this.getText( 'xpath', this.elements.errorMessageInsidePublicLinkContainer.selector, function (result) { message = result.value } ) console.log('\n\n', message, '\n\n') return message }, getErrorMessageFromModal: async function () { let message await this.getText('.oc-modal-body-input .oc-text-input-message', function (result) { message = result.value }) return message }, changeName: async function (linkName, newName) { await this.clickLinkEditBtn(linkName) await this.clickLinkEditNameBtn(linkName) await this.useXpath() .waitForElementVisible('@dialog') .waitForAnimationToFinish() .clearValue('@dialogInput') .setValue('@dialogInput', newName) .useCss() await this.click('@dialogConfirmBtnEnabled') }, changeLatestLinkName: async function (newName) { let latestLinkName await this.waitForElementVisible('@latestLinkName').getText( '@latestLinkName', (result) => (latestLinkName = result.value) ) await this.changeName(latestLinkName, newName) }, changeLatestLinkRole: async function (newRole) { let latestLinkName await this.waitForElementVisible('@latestLinkName').getText( '@latestLinkName', (result) => (latestLinkName = result.value) ) await this.changeRole(latestLinkName, newRole) }, addPassword: async function (linkName, password) { await this.clickLinkEditBtn(linkName) await this.clickLinkAddPasswordBtn(linkName) await this.useXpath() .waitForElementVisible('@dialog') .waitForAnimationToFinish() .clearValue('@dialogInput') .setValue('@dialogInput', password) .useCss() await this.click('@dialogConfirmBtnEnabled') }, setRequiredPassword: async function (password) { await this.useXpath() .waitForElementVisible('@dialog') .waitForAnimationToFinish() .clearValue('@dialogInput') .setValue('@dialogInput', password) .useCss() await this.waitForElementVisible('@dialogConfirmBtnEnabled') .initAjaxCounters() .click('@dialogConfirmBtnEnabled') .waitForOutstandingAjaxCalls() }, changePassword: async function (linkName, password) { await this.clickLinkEditBtn(linkName) await this.clickLinkEditPasswordBtn(linkName) await this.useXpath() .waitForElementVisible('@dialog') .waitForAnimationToFinish() .clearValue('@dialogInput') .setValue('@dialogInput', password) .useCss() await this.click('@dialogConfirmBtnEnabled') }, /** * clicks the 'copy-public-link-uri' button of a public link * * @param {string} linkName Name of the public link whose URL is to be copied */ copyPublicLinkURI: function (linkName) { const copyBtnXpath = this.elements.publicLinkContainer.selector + util.format(this.elements.publicLinkURLCopyButton.selector, linkName) const copyBtnSelector = { selector: copyBtnXpath, locateStrategy: this.elements.publicLinkURLCopyButton.locateStrategy } return this.waitForElementVisible(copyBtnSelector).click(copyBtnSelector) }, /** * extracts set value in expiration date trigger button * @return {Promise<*>} */ getExpirationDate: async function () { let expirationDate await this.waitForElementVisible('@expirationDateFieldWrapper') await this.waitForElementVisible('@editor').getAttribute( '@expirationDateFieldWrapper', 'value', (result) => { const date = new Date(result.value) const dateString = date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0') + ' 00:00:00' expirationDate = dateString } ) return expirationDate } }, elements: { popupNotificationMessage: { selector: '//*[contains(@class, "oc-notification-message")]//div[contains(@class, "oc-notification-message-title")]', locateStrategy: 'xpath' }, latestLinkName: { selector: '//div[@id="oc-files-file-link"]//ul/li[1]//h4', locateStrategy: 'xpath' }, expirationDateFieldWrapper: { selector: '#oc-files-file-link-expire-date' }, expirationDateField: { selector: '#files-links-expiration-btn' }, publicLinkContainer: { selector: '//*[@id="oc-files-file-link"]', locateStrategy: 'xpath' }, publicLinkInformation: { selector: '//li', locateStrategy: 'xpath' }, publicLinkUrl: { selector: '//p[contains(@class, "oc-files-file-link-url")]', locateStrategy: 'xpath' }, publicLinkName: { selector: '//li//span[.="%s"]', locateStrategy: 'xpath' }, publicLinkSubName: { selector: '.oc-files-file-link-name' }, publicLinkSubRole: { selector: '.link-details .link-current-role' }, publicLinkSubVia: { selector: '.oc-files-file-link-via' }, selectRoleButton: { selector: '#files-file-link-role-button' }, roleViewer: { selector: '#files-role-viewer' }, roleContributor: { selector: '#files-role-contributor' }, roleEditor: { selector: '#files-role-editor' }, roleUploader: { selector: '#files-role-uploader' }, publicLinkEditRoleButton: { selector: '//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]//ancestor::li//div[contains(@class, "link-details")]/div/button[contains(@class, "link-role-dropdown-toggle")]', locateStrategy: 'xpath' }, publicLinkEditButton: { selector: '//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]//ancestor::li//div[contains(@class, "details-buttons")]//button[contains(@class, "edit-drop-trigger")]', locateStrategy: 'xpath' }, publicLinkRenameButton: { selector: '//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]//ancestor::li//div[contains(@class, "details-buttons")]//button/span[text()="Rename"]', locateStrategy: 'xpath' }, publicLinkAddPasswordButton: { selector: '//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]//ancestor::li//div[contains(@class, "details-buttons")]//button/span[text()="Add password"]', locateStrategy: 'xpath' }, publicLinkRemovePasswordButton: { selector: '//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]//ancestor::li//div[contains(@class, "details-buttons")]//button/span[text()="Remove password"]', locateStrategy: 'xpath' }, publicLinkRenamePasswordButton: { selector: '//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]//ancestor::li//div[contains(@class, "details-buttons")]//button/span[text()="Edit password"]', locateStrategy: 'xpath' }, publicLinkExpirationDateEditButton: { selector: '//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]//ancestor::li//div[contains(@class, "details-buttons")]//button/span[text()="Edit expiration date"]', locateStrategy: 'xpath' }, publicLinkDeleteButton: { selector: '//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]//ancestor::li//div[contains(@class, "details-buttons")]//button/span[text()="Delete link"]', locateStrategy: 'xpath' }, publicLinkURLCopyButton: { selector: '//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]/../../..//button[contains(@class, "oc-files-public-link-copy-url")]', locateStrategy: 'xpath' }, publicLinkPasswordField: { selector: '//input[@type="password"]', locateStrategy: 'xpath' }, publicLinkDeletePasswordButton: { selector: '#oc-files-file-link-password-delete' }, publicLinkCreateButton: { selector: '#files-file-link-add' }, publicLinkRoleSelectionDropdown: { selector: '//div[contains(@class, "files-file-link-role-button-wrapper")]//span[.="%s"]', locateStrategy: 'xpath' }, dialog: { selector: '.oc-modal' }, dialogInput: { selector: '.oc-modal-body-input .oc-text-input' }, dialogConfirmBtnEnabled: { selector: '.oc-modal-body-actions-confirm' }, dialogCancelBtn: { selector: '.oc-modal-body-actions-cancel' } } }
owncloud/web/tests/acceptance/pageObjects/FilesPageElement/publicLinksDialog.js/0
{ "file_path": "owncloud/web/tests/acceptance/pageObjects/FilesPageElement/publicLinksDialog.js", "repo_id": "owncloud", "token_count": 9792 }
857
const util = require('util') const { join } = require('../helpers/path') const { SHARE_STATE } = require('../helpers/sharingHelper') module.exports = { url: function (viewMode) { return join(this.api.launchUrl, '/files/shares/with-me/?view-mode=' + viewMode) }, commands: { /** * like build-in navigate() but also waits till for the progressbar to appear and disappear * @returns {*} */ navigateAndWaitTillLoaded: function (viewMode = SHARE_STATE.accepted) { return this.navigate(this.url(viewMode)).waitForElementPresent( this.page.FilesPageElement.filesList().elements.anyAfterLoading ) }, /** * Navigate to the shared with me page in `accepted` view mode and wait until loading finished. * @returns {*} */ navigateToAcceptedAndWaitUntilLoaded: function () { return this.navigateAndWaitTillLoaded(SHARE_STATE.accepted) }, /** * Navigate to the shared with me page in `declined` view mode and wait until loading finished. * @returns {*} */ navigateToDeclinedAndWaitUntilLoaded: function () { return this.navigateAndWaitTillLoaded(SHARE_STATE.declined) }, /** * Checks if the share matching the given status, filename and owner is present on the given page. * Note: make sure that the view mode matching the given share status is loaded by navigating to * it first. See navigateToAcceptedAndWaitUntilLoaded and navigateToDeclinedAndWaitUntilLoaded. * * @param {string} status * @param {string} filename * @param {string} owner * @returns {Promise<boolean>} */ hasShareStatusByFilenameAndUser: async function (status, filename, owner) { let selector = this.api.page.FilesPageElement.filesList().getFileRowSelectorByFileName(filename) if (owner) { selector += util.format(this.elements.shareOwnerName.selector, owner) } selector += this.elements.syncEnabled.selector let isPresent = false await this.api.element('xpath', selector, function (result) { isPresent = !!(result.value && result.value.ELEMENT) }) if (status === SHARE_STATE.accepted) { return isPresent } return !isPresent }, /** * Checks if the share matching the given status and filename is present on the given page. * Note: make sure that the view mode matching the given share status is loaded by navigating to * it first. See navigateToAcceptedAndWaitUntilLoaded and navigateToDeclinedAndWaitUntilLoaded. * Note: this function ignores the user who shared the file. The same file/foldername could * be shared by different users. In that case you need to use the more precise * `hasShareStatusByFilenameAndUser` instead. * * @param {string} status * @param {string} filename * @returns {Promise<boolean>} */ hasShareStatusByFilename: async function (status, filename) { return await this.hasShareStatusByFilenameAndUser(status, filename, null) }, batchDeclineShares: function () { return this.waitForElementVisible('@batchDeclineSharesButton') .initAjaxCounters() .click('@batchDeclineSharesButton') .waitForAjaxCallsToStartAndFinish() }, /** * gets the username of user that the element(file/folder/resource) on the shared-with-me page is shared by * * @param {string} element * * @return {Promise<string>} */ getSharedByUser: async function (element) { let username const requiredXpath = this.api.page.FilesPageElement.filesList().getFileRowSelectorByFileName(element) + this.elements.sharedFrom.selector await this.waitForElementVisible({ locateStrategy: this.elements.sharedFrom.locateStrategy, selector: requiredXpath }) await this.api.getAttribute( this.elements.sharedFrom.locateStrategy, requiredXpath, 'data-test-user-name', (result) => { username = result.value } ) return username }, isSharePresent: async function (element, sharer) { const requiredXpath = this.api.page.FilesPageElement.filesList().getFileRowSelectorByFileName(element) + util.format(this.elements.shareOwnerName.selector, sharer) let shareFound = false await this.api.elements('xpath', requiredXpath, function (result) { shareFound = result.value.length > 0 }) return shareFound }, unshareAllCheckedFiles: function () { return this.waitForElementVisible('@batchDeclineSharesButton') .click('@batchDeclineSharesButton') .waitForAjaxCallsToStartAndFinish() } }, elements: { shareOwnerName: { selector: '//td[contains(@class,"oc-table-data-cell-sharedBy")]//span[@data-test-user-name="%s"]', locateStrategy: 'xpath' }, syncEnabled: { selector: '/ancestor::tr//span[contains(@class,"sync-enabled")]', locateStrategy: 'xpath' }, sharedFrom: { // ugly hack: oc-avatar has a parent div.oc-avatars, which is also matched by `contains(@class, 'oc-avatar')`. // to solve this we try matching on the class surrounded by blanks, which is not matching the oc-avatars anymore. selector: "//td[contains(@class,'oc-table-data-cell-sharedBy')]//span[contains(concat(' ', normalize-space(@class), ' '), ' oc-avatar ')]", locateStrategy: 'xpath' }, shareStatusActionOnFileRow: { selector: '/ancestor::tr[contains(@class, "oc-tbody-tr")]//button[contains(@class,"file-row-share")][normalize-space(.)="%s"]', locateStrategy: 'xpath' }, batchDeclineSharesButton: { selector: '.oc-files-actions-disable-sync-trigger' } } }
owncloud/web/tests/acceptance/pageObjects/sharedWithMePage.js/0
{ "file_path": "owncloud/web/tests/acceptance/pageObjects/sharedWithMePage.js", "repo_id": "owncloud", "token_count": 2206 }
858
const { client } = require('nightwatch-api') const { Given, When, Then } = require('@cucumber/cucumber') const previewPage = client.page.FilesPageElement.previewPage() const filesList = client.page.FilesPageElement.filesList() const assert = require('assert') Given( 'the user has viewed the file {string} in the preview app using the webUI', async function (fileName) { await previewPage.openPreview(fileName) return previewPage.waitForPreviewLoaded(fileName) } ) When( 'the user/public views the file {string} in the preview app using the webUI', async function (fileName) { await previewPage.openPreview(fileName) return previewPage.waitForPreviewLoaded(fileName) } ) When( 'the user/public views the single share file {string} in the preview app using the webUI', async function (fileName) { await previewPage.openPreviewFromDetailsView(fileName) return previewPage.waitForPreviewLoaded(fileName) } ) When('the user navigates to the next media resource using the webUI', function () { return previewPage.nextMediaResource() }) When('the user navigates to the previous media resource using the webUI', function () { return previewPage.previousMediaResource() }) When('the user closes the media resource using the webUI', function () { return previewPage.closeMediaResource() }) When('the user downloads the media resource using the webUI', function () { return previewPage.downloadMediaResource() }) Then('the file {string} should be displayed in the preview app webUI', function (fileName) { return previewPage.waitForPreviewLoaded(fileName) }) Then( 'the file {string} should not be displayed in the preview app webUI', async function (fileName) { const isPresent = await previewPage.isPreviewPresent(fileName) return assert.ok(!isPresent) } ) When( 'the user views the file {string} in the preview app by clicking on the file name using the webUI', function (fileName) { return filesList.clickOnFileName(fileName) } )
owncloud/web/tests/acceptance/stepDefinitions/previewContext.js/0
{ "file_path": "owncloud/web/tests/acceptance/stepDefinitions/previewContext.js", "repo_id": "owncloud", "token_count": 589 }
859
const withHttp = (url) => (/^https?:\/\//i.test(url) ? url : `https://${url}`) exports.config = { // environment assets: './tests/e2e/filesForUpload', tempAssetsPath: './tests/e2e/filesForUpload/temp', baseUrlOcis: process.env.BASE_URL_OCIS ?? 'host.docker.internal:9200', basicAuth: process.env.BASIC_AUTH === 'true', // keycloak config keycloak: process.env.KEYCLOAK === 'true', keycloakHost: process.env.KEYCLOAK_HOST ?? 'keycloak.owncloud.test', keycloakRealm: process.env.KEYCLOAK_REALM ?? 'oCIS', keycloakAdminUser: process.env.KEYCLOAK_ADMIN_USER ?? 'admin', keycloakAdminPassword: process.env.KEYCLOAK_ADMIN_PASSWORD ?? 'admin', get backendUrl() { return withHttp(process.env.BACKEND_HOST || this.baseUrlOcis) }, get frontendUrl() { return withHttp(process.env.SERVER_HOST || this.baseUrlOcis) }, get keycloakUrl() { return withHttp(this.keycloakHost) }, get keycloakLoginUrl() { return withHttp(this.keycloakHost + '/admin/master/console') }, debug: process.env.DEBUG === 'true', logLevel: process.env.LOG_LEVEL || 'silent', // cucumber retry: process.env.RETRY || 0, // playwright slowMo: parseInt(process.env.SLOW_MO) || 0, timeout: parseInt(process.env.TIMEOUT) || 60, minTimeout: parseInt(process.env.MIN_TIMEOUT) || 5, headless: process.env.HEADLESS === 'true', acceptDownloads: process.env.DOWNLOADS !== 'false', browser: process.env.BROWSER ?? 'chrome', reportDir: process.env.REPORT_DIR || 'reports/e2e', reportVideo: process.env.REPORT_VIDEO === 'true', reportHar: process.env.REPORT_HAR === 'true', reportTracing: process.env.REPORT_TRACING === 'true' }
owncloud/web/tests/e2e/config.js/0
{ "file_path": "owncloud/web/tests/e2e/config.js", "repo_id": "owncloud", "token_count": 637 }
860
Feature: deny share access # FIXME: enable as soon as sharing NG supports it # Scenario: deny and grant access # Given "Admin" creates following users using API # | id | # | Alice | # | Brian | # When "Alice" logs in # And "Alice" creates the following folder in personal space using API # | name | # | folder_to_shared | # | folder_to_shared/folder | # | folder_to_shared/folder_to_deny | # And "Alice" opens the "files" app # And "Alice" shares the following resource using the quick action # | resource | recipient | type | role | resourceType | # | folder_to_shared | Brian | user | Can view | folder | # And "Alice" opens folder "folder_to_shared" # When "Alice" denies access to the following resources for user "Brian" using the sidebar panel # | resource | # | folder_to_deny | # And "Brian" logs in # And "Brian" opens the "files" app # And "Brian" navigates to the shared with me page # And "Brian" opens folder "folder_to_shared" # Then following resources should not be displayed in the files list for user "Brian" # | resource | # | folder_to_deny | # And "Alice" opens the "files" app # And "Alice" opens folder "folder_to_shared" # When "Alice" grants access to the following resources for user "Brian" using the sidebar panel # | resource | # | folder_to_deny | # And "Brian" opens the "files" app # And "Brian" navigates to the shared with me page # And "Brian" opens folder "folder_to_shared" # Then following resources should be displayed in the files list for user "Brian" # | resource | # | folder_to_deny | # And "Brian" logs out # And "Alice" logs out
owncloud/web/tests/e2e/cucumber/features/shares/denyShareAccess.feature/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/features/shares/denyShareAccess.feature", "repo_id": "owncloud", "token_count": 710 }
861
Feature: Users can use web to organize tags Background: Given "Admin" creates following users using API | id | | Alice | | Brian | Scenario: Tag management When "Alice" logs in And "Alice" opens the "files" app And "Alice" uploads the following resource | resource | | lorem.txt | And "Alice" adds the following tags for the following resources using the sidebar panel | resource | tags | | lorem.txt | tag 1, tag 2 | Then the following resources should contain the following tags in the files list for user "Alice" | resource | tags | | lorem.txt | tag 1, tag 2 | Then the following resources should contain the following tags in the details panel for user "Alice" | resource | tags | | lorem.txt | tag 1, tag 2 | When "Alice" removes the following tags for the following resources using the sidebar panel | resource | tags | | lorem.txt | tag 1 | Then the following resources should contain the following tags in the files list for user "Alice" | resource | tags | | lorem.txt | tag 2 | Then the following resources should contain the following tags in the details panel for user "Alice" | resource | tags | | lorem.txt | tag 2 | And "Alice" logs out Scenario: Tag search When "Alice" logs in And "Alice" opens the "files" app And "Alice" uploads the following resource | resource | | lorem.txt | | textfile.txt | And "Alice" adds the following tags for the following resources using the sidebar panel | resource | tags | | lorem.txt | tag1, tag2 | And "Alice" clicks the tag "tag1" on the resource "lorem.txt" Then the following resources should contain the following tags in the files list for user "Alice" | resource | tags | | lorem.txt | tag1 | Then following resources should not be displayed in the files list for user "Alice" | resource | | textfile.txt | And "Alice" logs out Scenario: Tag sharing When "Alice" logs in And "Alice" opens the "files" app And "Alice" creates the following resources | resource | type | | folder_to_shared | folder | And "Alice" uploads the following resource | resource | to | | lorem.txt | folder_to_shared | And "Alice" adds the following tags for the following resources using the sidebar panel | resource | tags | | folder_to_shared/lorem.txt | tag 1, tag 2 | When "Alice" shares the following resource using the sidebar panel | resource | recipient | type | role | resourceType | | folder_to_shared | Brian | user | Can edit | folder | And "Alice" logs out And "Brian" logs in And "Brian" navigates to the shared with me page Then the following resources should contain the following tags in the files list for user "Brian" | resource | tags | | folder_to_shared/lorem.txt | tag 1, tag 2 | And "Brian" logs out
owncloud/web/tests/e2e/cucumber/features/smoke/tags.feature/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/tags.feature", "repo_id": "owncloud", "token_count": 1153 }
862
import { When, Then, DataTable } from '@cucumber/cucumber' import { World } from '../../environment' import { objects } from '../../../support' import { expect } from '@playwright/test' Then( '{string} should have quota {string}', async function (this: World, stepUser: string, quota: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const accountObject = new objects.account.Account({ page }) expect(await accountObject.getQuotaValue()).toBe(quota) } ) Then( '{string} should have self info:', async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const accountObject = new objects.account.Account({ page }) for (const info of stepTable.hashes()) { expect(await accountObject.getUserInfo(info.key)).toBe(info.value) } } ) When('{string} opens the user menu', async function (this: World, stepUser: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const accountObject = new objects.account.Account({ page }) await accountObject.openAccountPage() }) When( '{string} requests a new GDPR export', async function (this: World, stepUser: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const accountObject = new objects.account.Account({ page }) await accountObject.requestGdprExport() } ) When( '{string} downloads the GDPR export', async function (this: World, stepUser: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const accountObject = new objects.account.Account({ page }) const downloadedResource = await accountObject.downloadGdprExport() expect(downloadedResource).toContain('personal_data_export.json') } ) When( '{string} changes the language to {string}', async function (this: World, stepUser: string, language: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const accountObject = new objects.account.Account({ page }) const isAnonymousUser = stepUser === 'Anonymous' const expectedLanguage = await accountObject.changeLanguage(language, isAnonymousUser) expect(expectedLanguage).toBe(language) } ) Then( '{string} should see the following account page title {string}', async function (this: World, stepUser: string, title: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const accountObject = new objects.account.Account({ page }) const pageTitle = await accountObject.getTitle() expect(pageTitle).toEqual(title) } )
owncloud/web/tests/e2e/cucumber/steps/ui/accountMenu.ts/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/steps/ui/accountMenu.ts", "repo_id": "owncloud", "token_count": 847 }
863
export * from './user'
owncloud/web/tests/e2e/support/api/provision/index.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/api/provision/index.ts", "repo_id": "owncloud", "token_count": 8 }
864
export * as api from './api' export * as utils from './utils' export * as objects from './objects' export * as environment from './environment'
owncloud/web/tests/e2e/support/index.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/index.ts", "repo_id": "owncloud", "token_count": 41 }
865
import { Page } from '@playwright/test' import { UsersEnvironment } from '../../../environment' import * as po from './actions' import { config } from '../../../../config' import { getUserId } from '../../../api/graph' export class Users { #page: Page #usersEnvironment: UsersEnvironment constructor({ page }: { page: Page }) { this.#usersEnvironment = new UsersEnvironment() this.#page = page } async getUUID({ key }: { key: string }): Promise<string> { if (config.keycloak) { const user = this.#usersEnvironment.getUser({ key }) const admin = this.#usersEnvironment.getUser({ key: 'admin' }) return await getUserId({ user, admin }) } else { return this.#usersEnvironment.getCreatedUser({ key }).uuid } } async allowLogin({ key, action }: { key: string; action: string }): Promise<void> { const uuid = await this.getUUID({ key }) await po.openEditPanel({ page: this.#page, uuid, action }) await po.changeAccountEnabled({ uuid, value: true, page: this.#page }) } async forbidLogin({ key, action }: { key: string; action: string }): Promise<void> { const uuid = await this.getUUID({ key }) await po.openEditPanel({ page: this.#page, uuid, action }) await po.changeAccountEnabled({ uuid, value: false, page: this.#page }) } async changeQuota({ key, value, action }: { key: string value: string action: string }): Promise<void> { const uuid = await this.getUUID({ key }) await po.openEditPanel({ page: this.#page, uuid, action }) await po.changeQuota({ uuid, value, page: this.#page }) } async selectUser({ key }: { key: string }): Promise<void> { const uuid = await this.getUUID({ key }) await po.selectUser({ page: this.#page, uuid }) } async changeQuotaUsingBatchAction({ value, users }: { value: string users: string[] }): Promise<void> { const userIds = [] for (const user of users) { userIds.push(await this.getUUID({ key: user })) } await po.changeQuotaUsingBatchAction({ page: this.#page, value, userIds }) } getDisplayedUsers(): Promise<string[]> { return po.getDisplayedUsers({ page: this.#page }) } async select({ key }: { key: string }): Promise<void> { await po.selectUser({ page: this.#page, uuid: await this.getUUID({ key }) }) } async addToGroupsBatchAtion({ userIds, groups }: { userIds: string[] groups: string[] }): Promise<void> { await po.addSelectedUsersToGroups({ page: this.#page, userIds, groups }) } async removeFromGroupsBatchAtion({ userIds, groups }: { userIds: string[] groups: string[] }): Promise<void> { await po.removeSelectedUsersFromGroups({ page: this.#page, userIds, groups }) } async filter({ filter, values }: { filter: string; values: string[] }): Promise<void> { await po.filterUsers({ page: this.#page, filter, values }) } async changeUser({ key, attribute, value, action }: { key: string attribute: string value: string action: string }): Promise<void> { const uuid = await this.getUUID({ key }) await po.openEditPanel({ page: this.#page, uuid, action }) await po.changeUser({ uuid, attribute: attribute, value: value, page: this.#page }) const currentUser = this.#usersEnvironment.getCreatedUser({ key }) if (attribute !== 'role') { this.#usersEnvironment.updateCreatedUser({ key: key, user: { ...currentUser, [attribute === 'userName' ? 'id' : attribute]: value } }) } } async addToGroups({ key, groups, action }: { key: string groups: string[] action: string }): Promise<void> { const uuid = await this.getUUID({ key }) await po.openEditPanel({ page: this.#page, uuid, action }) await po.addUserToGroups({ page: this.#page, userId: uuid, groups }) } async removeFromGroups({ key, groups, action }: { key: string groups: string[] action: string }): Promise<void> { const uuid = await this.getUUID({ key }) await po.openEditPanel({ page: this.#page, uuid, action }) await po.removeUserFromGroups({ page: this.#page, userId: uuid, groups }) } async deleteUserUsingContextMenu({ key }: { key: string }): Promise<void> { await po.deleteUserUsingContextMenu({ page: this.#page, uuid: await this.getUUID({ key }) }) } async deleteUserUsingBatchAction({ userIds }: { userIds: string[] }): Promise<void> { await po.deleteUserUsingBatchAction({ page: this.#page, userIds }) } async createUser({ name, displayname, email, password }: { name: string displayname: string email: string password: string }): Promise<void> { const response = await po.createUser({ page: this.#page, name, displayname, email, password }) this.#usersEnvironment.storeCreatedUser({ user: { id: response.onPremisesSamAccountName, displayName: response.displayName, password: password, email: response.mail, uuid: response.id } }) } async openEditPanel({ key, action }: { key: string; action: string }): Promise<void> { await po.openEditPanel({ page: this.#page, uuid: await this.getUUID({ key }), action }) } async waitForEditPanelToBeVisible(): Promise<void> { await po.waitForEditPanelToBeVisible({ page: this.#page }) } }
owncloud/web/tests/e2e/support/objects/app-admin-settings/users/index.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/users/index.ts", "repo_id": "owncloud", "token_count": 1993 }
866
import { Page, expect } from '@playwright/test' import util from 'util' import Collaborator, { ICollaborator, IAccessDetails } from './collaborator' import { sidebar } from '../utils' import { clickResource } from '../resource/actions' import { clearCurrentPopup, createLinkArgs } from '../link/actions' import { config } from '../../../../config.js' import { createdLinkStore } from '../../../store' const quickShareButton = '//*[@data-test-resource-name="%s"]/ancestor::tr//button[contains(@class, "files-quick-action-show-shares")]' const noPermissionToShareLabel = '//*[@data-testid="files-collaborators-no-reshare-permissions-message"]' const actionMenuDropdownButton = '//*[@data-test-resource-name="%s"]/ancestor::tr//button[contains(@class, "resource-table-btn-action-dropdown")]' const actionsTriggerButton = '//*[@data-test-resource-name="%s"]/ancestor::tr//button[contains(@class, "oc-files-actions-%s-trigger")]' const publicLinkInputField = '//h4[contains(@class, "oc-files-file-link-name") and text()="%s"]' + '/following-sibling::div//p[contains(@class,"oc-files-file-link-url")]' const selecAllCheckbox = '#resource-table-select-all' const acceptButton = '.oc-files-actions-enable-sync-trigger' const pendingShareItem = '//div[@id="files-shared-with-me-pending-section"]//tr[contains(@class,"oc-tbody-tr")]' const passwordInput = '.oc-modal-body input.oc-text-input' const createLinkButton = '.oc-modal-body-actions-confirm' const showMoreOptionsButton = '#show-more-share-options-btn' const calendarDatePickerId = 'recipient-datepicker-btn' export interface ShareArgs { page: Page resource: string recipients: ICollaborator[] expirationDate?: string } export const openSharingPanel = async function ( page: Page, resource: string, via = 'SIDEBAR_PANEL' ): Promise<void> { const folderPaths = resource.split('/') const item = folderPaths.pop() if (folderPaths.length) { await clickResource({ page, path: folderPaths.join('/') }) } switch (via) { case 'QUICK_ACTION': await page.locator(util.format(quickShareButton, item)).click() break case 'SIDEBAR_PANEL': await sidebar.open({ page, resource: item }) await sidebar.openPanel({ page, name: 'sharing' }) break } } /**/ export interface createShareArgs extends ShareArgs { via?: 'SIDEBAR_PANEL' | 'QUICK_ACTION' | 'URL_NAVIGATION' } export const createShare = async (args: createShareArgs): Promise<void> => { const { page, resource, recipients, via } = args if (via !== 'URL_NAVIGATION') { await openSharingPanel(page, resource, via) } const expirationDate = recipients[0].expirationDate if (expirationDate) { await page.locator(showMoreOptionsButton).click() await page.getByTestId(calendarDatePickerId).click() await Collaborator.setExpirationDate(page, expirationDate) } await Collaborator.inviteCollaborators({ page, collaborators: recipients }) await sidebar.close({ page }) } /**/ export interface ShareStatusArgs extends Omit<ShareArgs, 'recipients'> { via?: 'STATUS' | 'CONTEXT_MENU' } export const enableSync = async (args: ShareStatusArgs): Promise<void> => { const { resource, page } = args await clickActionInContextMenu({ page, resource }, 'enable-sync') } export const syncAllShares = async ({ page }: { page: Page }): Promise<void> => { await page.locator(selecAllCheckbox).click() const numberOfPendingShares = await page.locator(pendingShareItem).count() const checkResponses = [] for (let i = 0; i < numberOfPendingShares; i++) { checkResponses.push( page.waitForResponse( (resp) => resp.url().includes('root/children') && resp.status() === 201 && resp.request().method() === 'POST' ) ) } await Promise.all([...checkResponses, page.locator(acceptButton).click()]) } export const disableSync = async (args: ShareStatusArgs): Promise<void> => { const { page, resource } = args await clickActionInContextMenu({ page, resource }, 'disable-sync') } export const clickActionInContextMenu = async ( args: ShareStatusArgs, action: string ): Promise<void> => { const { page, resource } = args await page.locator(util.format(actionMenuDropdownButton, resource)).click() switch (action) { case 'enable-sync': await Promise.all([ page.waitForResponse( (resp) => resp.url().includes('root/children') && resp.status() === 201 && resp.request().method() === 'POST' ), page.locator(util.format(actionsTriggerButton, resource, action)).click() ]) break case 'copy-quicklink': await page.locator(util.format(actionsTriggerButton, resource, action)).click() break case 'disable-sync': await Promise.all([ page.waitForResponse( (resp) => resp.url().includes('drives') && resp.status() === 200 && resp.request().method() === 'DELETE' ), page.locator(util.format(actionsTriggerButton, resource, action)).click() ]) break } } export const changeShareeRole = async (args: ShareArgs): Promise<void> => { const { page, resource, recipients } = args await openSharingPanel(page, resource) for (const collaborator of recipients) { await Promise.all([ page.waitForResponse( (resp) => resp.url().includes('permissions') && resp.status() === 200 && resp.request().method() === 'PATCH' ), Collaborator.changeCollaboratorRole({ page, collaborator }) ]) } } /**/ export interface removeShareeArgs extends ShareArgs { removeOwnSpaceAccess?: boolean } export const removeSharee = async (args: removeShareeArgs): Promise<void> => { const { page, resource, recipients, removeOwnSpaceAccess } = args await openSharingPanel(page, resource) for (const collaborator of recipients) { await Collaborator.removeCollaborator({ page, collaborator, removeOwnSpaceAccess }) } } /**/ export const checkSharee = async (args: ShareArgs): Promise<void> => { const { resource, page, recipients } = args await openSharingPanel(page, resource) for (const collaborator of recipients) { await Collaborator.checkCollaborator({ page, collaborator }) } } export const hasPermissionToShare = async ( args: Omit<ShareArgs, 'recipients'> ): Promise<boolean> => { const { page, resource } = args // reload page to make sure the changes are reflected await page.reload() await openSharingPanel(page, resource) await Collaborator.waitForInvitePanel(page) return !(await page.isVisible(noPermissionToShareLabel)) } export const createQuickLink = async (args: createLinkArgs): Promise<string> => { const { page, resource, password } = args let url = '' const linkName = 'Link' await clickActionInContextMenu({ page, resource }, 'copy-quicklink') await page.locator(passwordInput).fill(password) await Promise.all([ page.waitForResponse( (res) => res.url().includes('createLink') && res.request().method() === 'POST' && res.status() === 200 ), page.locator(createLinkButton).click() ]) if (config.backendUrl.startsWith('https')) { // here is flaky https://github.com/owncloud/web/issues/9941 // sometimes test doesn't have time to pick up the correct buffer await page.waitForTimeout(500) url = await page.evaluate(() => navigator.clipboard.readText()) expect(url).toContain(config.baseUrlOcis) } else { const quickLinkUrlLocator = util.format(publicLinkInputField, linkName) if (!(await page.locator(quickLinkUrlLocator).isVisible())) { await openSharingPanel(page, resource) } url = await page.locator(quickLinkUrlLocator).textContent() } await clearCurrentPopup(page) if (url && !createdLinkStore.has(linkName)) { createdLinkStore.set(linkName, { name: linkName, url }) } return url } export interface setDenyShareArgs { page: Page resource: string deny: boolean collaborator: ICollaborator } export const setDenyShare = async (args: setDenyShareArgs): Promise<void> => { const { page, resource, deny, collaborator } = args await openSharingPanel(page, resource) await Collaborator.setDenyShareForCollaborator({ page, deny, collaborator }) } export const addExpirationDate = async (args: { page: Page resource: string collaborator: Omit<ICollaborator, 'role'> expirationDate: string }): Promise<void> => { const { page, resource, collaborator, expirationDate } = args await openSharingPanel(page, resource) await Promise.all([ page.waitForResponse( (resp) => resp.url().includes('drives') && resp.status() === 200 && resp.request().method() === 'PATCH' ), Collaborator.setExpirationDateForCollaborator({ page, collaborator, expirationDate }) ]) } export const getAccessDetails = async (args: { page: Page resource: string collaborator: Omit<ICollaborator, 'role'> }): Promise<IAccessDetails> => { const { page, resource, collaborator } = args await openSharingPanel(page, resource) return Collaborator.getAccessDetails(page, collaborator) }
owncloud/web/tests/e2e/support/objects/app-files/share/actions.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/objects/app-files/share/actions.ts", "repo_id": "owncloud", "token_count": 3176 }
867
import { Page } from '@playwright/test' import { config } from '../../../config' import { getIdOfFileInsideSpace } from '../../api/davSpaces' import { User } from '../../types' import { getSpaceIdBySpaceName } from '../../api/graph' import { getOpenWithWebUrl } from '../../api/external' export interface navigateToDetailsPanelOfResourceArgs { page: Page resource: string detailsPanel: string user: User space: string } export interface openResourceViaUrlArgs { page: Page resource?: string user: User space?: string editorName?: string client?: string } export const navigateToDetailsPanelOfResource = async ( args: navigateToDetailsPanelOfResourceArgs ): Promise<void> => { const { page, resource, detailsPanel, user, space } = args const fileId = await getTheFileIdOfSpaceFile(user, space, resource) const fullUrl = `${config.backendUrl}/f/${fileId}?details=${detailsPanel}` await page.goto(fullUrl) } export const openResourceViaUrl = async (args: openResourceViaUrlArgs) => { const { page, resource, user, space, editorName, client = '' } = args const fileId = await getTheFileIdOfSpaceFile(user, space, resource) let fullUrl switch (client) { case 'desktop': fullUrl = `${config.backendUrl}/external/open-with-web/?appName=${editorName}&fileId=${fileId}` break case 'mobile': fullUrl = await getOpenWithWebUrl({ user, fileId, editorName }) break default: fullUrl = `${config.backendUrl}/f/${fileId}` } await page.goto(fullUrl) } export const openSpaceViaUrl = async (args: openResourceViaUrlArgs) => { const { page, user, space } = args let spaceName = null let spaceType = null if (space.toLowerCase() === 'personal') { spaceName = user.displayName spaceType = space.toLowerCase() } else { spaceName = space spaceType = 'project' } const fileId = await getSpaceIdBySpaceName({ user, spaceType, spaceName }) const fullUrl = `${config.backendUrl}/f/${fileId}` await page.goto(fullUrl) } const getTheFileIdOfSpaceFile = async ( user: User, space: string, pathToFileName: string ): Promise<string> => { let spaceName = null let spaceType = null if (space.toLowerCase() === 'personal') { spaceName = user.displayName spaceType = space.toLowerCase() } else { spaceName = space spaceType = 'project' } return await getIdOfFileInsideSpace({ user, pathToFileName, spaceType, spaceName }) }
owncloud/web/tests/e2e/support/objects/url-navigation/actions.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/objects/url-navigation/actions.ts", "repo_id": "owncloud", "token_count": 838 }
868
import fs from 'fs' import path from 'path' import { config } from '../../config' // max file creation size is 10GB export const MAX_FILE_SIZE = Math.pow(1024, 3) * 10 export const getBytes = (fileSize: string): number => { fileSize = fileSize.replace(/\s/g, '').toLowerCase() const size = parseFloat(fileSize.match(/([\d.]+)/)[0]) const type = fileSize.match(/[kKmMgGbB]{1,2}/)[0] let sizeInbytes = size if (!type) { return sizeInbytes } switch (type) { case 'b': sizeInbytes = size case 'kb': sizeInbytes = size * 1024 break case 'mb': sizeInbytes = size * Math.pow(1024, 2) break case 'gb': sizeInbytes = size * Math.pow(1024, 3) break default: throw new Error('Invalid file size. Must be one of these: b, kb, mb, gb') } if (sizeInbytes > MAX_FILE_SIZE) { throw Error(`File size must be less than '${MAX_FILE_SIZE}' bytes, i.e. 10GB`) } return sizeInbytes } export const getTempUploadPath = (): string => { if (!fs.existsSync(config.tempAssetsPath)) { fs.mkdirSync(config.tempAssetsPath) } return config.tempAssetsPath } export const createFileWithSize = ( fileName: string, sizeInBytes: number, dir: string = getTempUploadPath() ): Promise<void> => { return new Promise((resolve, reject) => { const fileStream = fs.createWriteStream(path.join(dir, fileName)) // 500MB buffer size for writing const bufferSize = 500 * Math.pow(1024, 2) const iterations = Math.ceil(sizeInBytes / bufferSize) fileStream.on('open', (fd) => { let bytesWritten = 0 for (let i = 0; i < iterations; i++) { const remainingBytes = sizeInBytes - bytesWritten const buffer = Buffer.alloc(remainingBytes < bufferSize ? remainingBytes : bufferSize) fs.writeSync(fd, buffer, 0, buffer.length, null) bytesWritten += buffer.length } fileStream.end() }) fileStream.on('finish', () => resolve()) fileStream.on('error', (err) => { reject(`An error occurred while writing file '${fileName}': ${err}`) }) }) } export const createFile = ( fileName: string, content: string, dir: string = getTempUploadPath() ) => { fs.writeFileSync(path.join(dir, fileName), content) } export const removeTempUploadDirectory = () => { if (fs.existsSync(config.tempAssetsPath)) { fs.rmSync(config.tempAssetsPath, { recursive: true }) } }
owncloud/web/tests/e2e/support/utils/runtimeFs.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/utils/runtimeFs.ts", "repo_id": "owncloud", "token_count": 923 }
869
<?php //客户端前端验证的后台函数 function upload_client($key,$save_path){ $arr_errors=array( 1=>'上传的文件超过了 php.ini中 upload_max_filesize 选项限制的值', 2=>'上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值', 3=>'文件只有部分被上传', 4=>'没有文件被上传', 6=>'找不到临时文件夹', 7=>'文件写入失败' ); if(!isset($_FILES[$key]['error'])){ $return_data['error']='请选择上传文件!'; $return_data['return']=false; return $return_data; } if ($_FILES[$key]['error']!=0) { $return_data['error']=$arr_errors[$_FILES[$key]['error']]; $return_data['return']=false; return $return_data; } //新建一个保存文件的目录 if(!file_exists($save_path)){ if(!mkdir($save_path,0777,true)){ $return_data['error']='上传文件保存目录创建失败,请检查权限!'; $return_data['return']=false; return $return_data; } } $save_path=rtrim($save_path,'/').'/';//给路径加个斜杠 if(!move_uploaded_file($_FILES[$key]['tmp_name'],$save_path.$_FILES[$key]['name'])){ $return_data['error']='临时文件移动失败,请检查权限!'; $return_data['return']=false; return $return_data; } //如果以上都通过了,则返回这些值,存储的路径,新的文件名(不要暴露出去) $return_data['new_path']=$save_path.$_FILES[$key]['name']; $return_data['return']=true; return $return_data; } //只通过MIME类型验证了一下图片类型,其他的无验证,upsafe_upload_check.php function upload_sick($key,$mime,$save_path){ $arr_errors=array( 1=>'上传的文件超过了 php.ini中 upload_max_filesize 选项限制的值', 2=>'上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值', 3=>'文件只有部分被上传', 4=>'没有文件被上传', 6=>'找不到临时文件夹', 7=>'文件写入失败' ); if(!isset($_FILES[$key]['error'])){ $return_data['error']='请选择上传文件!'; $return_data['return']=false; return $return_data; } if ($_FILES[$key]['error']!=0) { $return_data['error']=$arr_errors[$_FILES[$key]['error']]; $return_data['return']=false; return $return_data; } //验证一下MIME类型 if(!in_array($_FILES[$key]['type'], $mime)){ $return_data['error']='上传的图片只能是jpg,jpeg,png格式的!'; $return_data['return']=false; return $return_data; } //新建一个保存文件的目录 if(!file_exists($save_path)){ if(!mkdir($save_path,0777,true)){ $return_data['error']='上传文件保存目录创建失败,请检查权限!'; $return_data['return']=false; return $return_data; } } $save_path=rtrim($save_path,'/').'/';//给路径加个斜杠 if(!move_uploaded_file($_FILES[$key]['tmp_name'],$save_path.$_FILES[$key]['name'])){ $return_data['error']='临时文件移动失败,请检查权限!'; $return_data['return']=false; return $return_data; } //如果以上都通过了,则返回这些值,存储的路径,新的文件名(不要暴露出去) $return_data['new_path']=$save_path.$_FILES[$key]['name']; $return_data['return']=true; return $return_data; } //进行了严格的验证 function upload($key,$size,$type=array(),$mime=array(),$save_path){ $arr_errors=array( 1=>'上传的文件超过了 php.ini中 upload_max_filesize 选项限制的值', 2=>'上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值', 3=>'文件只有部分被上传', 4=>'没有文件被上传', 6=>'找不到临时文件夹', 7=>'文件写入失败' ); // var_dump($_FILES); if(!isset($_FILES[$key]['error'])){ $return_data['error']='请选择上传文件!'; $return_data['return']=false; return $return_data; } if ($_FILES[$key]['error']!=0) { $return_data['error']=$arr_errors[$_FILES[$key]['error']]; $return_data['return']=false; return $return_data; } //验证上传方式 if(!is_uploaded_file($_FILES[$key]['tmp_name'])){ $return_data['error']='您上传的文件不是通过 HTTP POST方式上传的!'; $return_data['return']=false; return $return_data; } //获取后缀名,如果不存在后缀名,则将变量设置为空 $arr_filename=pathinfo($_FILES[$key]['name']); if(!isset($arr_filename['extension'])){ $arr_filename['extension']=''; } //先验证后缀名 if(!in_array(strtolower($arr_filename['extension']),$type)){//转换成小写,在比较 $return_data['error']='上传文件的后缀名不能为空,且必须是'.implode(',',$type).'中的一个'; $return_data['return']=false; return $return_data; } //验证MIME类型,MIME类型可以被绕过 if(!in_array($_FILES[$key]['type'], $mime)){ $return_data['error']='你上传的是个假图片,不要欺骗我xxx!'; $return_data['return']=false; return $return_data; } //通过getimagesize来读取图片的属性,从而判断是不是真实的图片,还是可以被绕过的 if(!getimagesize($_FILES[$key]['tmp_name'])){ $return_data['error']='你上传的是个假图片,不要欺骗我!'; $return_data['return']=false; return $return_data; } //验证大小 if($_FILES[$key]['size']>$size){ $return_data['error']='上传文件的大小不能超过'.$size.'byte(500kb)'; $return_data['return']=false; return $return_data; } //把上传的文件给他搞一个新的路径存起来 if(!file_exists($save_path)){ if(!mkdir($save_path,0777,true)){ $return_data['error']='上传文件保存目录创建失败,请检查权限!'; $return_data['return']=false; return $return_data; } } //生成一个新的文件名,并将新的文件名和之前获取的扩展名合起来,形成文件名称 $new_filename=str_replace('.','',uniqid(mt_rand(100000,999999),true)); if($arr_filename['extension']!=''){ $arr_filename['extension']=strtolower($arr_filename['extension']);//小写保存 $new_filename.=".{$arr_filename['extension']}"; } //将tmp目录里面的文件拷贝到指定目录下并使用新的名称 $save_path=rtrim($save_path,'/').'/'; if(!move_uploaded_file($_FILES[$key]['tmp_name'],$save_path.$new_filename)){ $return_data['error']='临时文件移动失败,请检查权限!'; $return_data['return']=false; return $return_data; } //如果以上都通过了,则返回这些值,存储的路径,新的文件名(不要暴露出去) $return_data['save_path']=$save_path.$new_filename; $return_data['filename']=$new_filename; $return_data['return']=true; return $return_data; } ?>
zhuifengshaonianhanlu/pikachu/inc/uploadfunction.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/inc/uploadfunction.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 4172 }
870
<?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 fish 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="result"> <table class="tb" border="1px" cellpadding="10" cellspacing="1" bgcolor="#5f9ea0"> <tr> <td class="1">id</td> <td class="1">time</td> <td class="1">username</td> <td class="1">password</td> <td class="2">referer</td> <td class="2">操作</td> </tr> <?php $query="select * from fish"; $result=mysqli_query($link, $query); while($data=mysqli_fetch_assoc($result)){ $html=<<<A <tr> <td class="1">{$data['id']}</td> <td class="1">{$data['time']}</td> <td class="1">{$data['username']}</td> <td class="1">{$data['password']}</td> <td class="2">{$data['referer']}</td> <td><a href="pkxss_fish_result.php?id={$data['id']}">删除</a></td> </tr> A; echo $html; } ?> </table> </div> </body> </html>
zhuifengshaonianhanlu/pikachu/pkxss/xfish/pkxss_fish_result.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/pkxss/xfish/pkxss_fish_result.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 838 }
871
<?php /** * Created by runner.han * There is nothing new under the sun */ $SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1); if ($SELF_PAGE = "csrf_post.php"){ $ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','active open','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''); } $PIKA_ROOT_DIR = "../../../"; include_once $PIKA_ROOT_DIR . 'header.php'; include_once $PIKA_ROOT_DIR."inc/config.inc.php"; include_once $PIKA_ROOT_DIR."inc/function.php"; include_once $PIKA_ROOT_DIR."inc/mysql.inc.php"; $link=connect(); // 判断是否登录,没有登录不能访问 if(!check_csrf_login($link)){ // echo "<script>alert('登录后才能进入会员中心哦')</script>"; header("location:csrf_get_login.php"); } if(isset($_GET['logout']) && $_GET['logout'] == 1){ session_unset(); session_destroy(); setcookie(session_name(),'',time()-3600,'/'); header("location:csrf_post_login.php"); } ?> <div class="main-content"> <div class="main-content-inner"> <div class="breadcrumbs ace-save-state" id="breadcrumbs"> <ul class="breadcrumb"> <li> <i class="ace-icon fa fa-home home-icon"></i> <a href="../csrf.php">CSRF</a> </li> <li class="active">CSRF(post)</li> </ul><!-- /.breadcrumb --> </div> <div class="page-content"> <?php //通过当前session-name到数据库查询,并显示其对应信息 $username=$_SESSION['csrf']['username']; $query="select * from member where username='$username'"; $result=execute($link, $query); $data=mysqli_fetch_array($result); $name=$data['username']; $sex=$data['sex']; $phonenum=$data['phonenum']; $add=$data['address']; $email=$data['email']; $html=<<<A <div id="per_info"> <h1 class="per_title">hello,{$name},欢迎来到个人会员中心 | <a style="color:bule;" href="csrf_post.php?logout=1">退出登录</a></h1> <p class="per_name">姓名:{$name}</p> <p class="per_sex">性别:{$sex}</p> <p class="per_phone">手机:{$phonenum}</p> <p class="per_add">住址:{$add}</p> <p class="per_email">邮箱:{$email}</p> <a class="edit" href="csrf_post_edit.php">修改个人信息</a> </div> A; echo $html; ?> </div><!-- /.page-content --> </div> </div><!-- /.main-content --> <?php include_once $PIKA_ROOT_DIR . 'footer.php'; ?>
zhuifengshaonianhanlu/pikachu/vul/csrf/csrfpost/csrf_post.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/vul/csrf/csrfpost/csrf_post.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 1467 }
872
<?php $html.=<<<A <img class=player src="include/kd.png" /> <p class=nabname> Durant in 2007 first round draft sequence of the second was drafted by the Seattle supersonics, 2008 with the team moved to Oklahoma.In 2010, durant, 21, became the youngest NBA scoring champion, after two seasons in the NBA regular season scoring in a row.In 2014, durant and scoring with the NBA regular season MVP award (MVP). </p> A; ?>
zhuifengshaonianhanlu/pikachu/vul/fileinclude/include/file3.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/vul/fileinclude/include/file3.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 121 }
873
<?php /** * Created by runner.han * There is nothing new under the sun */ $SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1); if ($SELF_PAGE = "op1_login.php"){ $ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''); } $PIKA_ROOT_DIR = "../../../"; include_once $PIKA_ROOT_DIR . 'header.php'; include_once $PIKA_ROOT_DIR.'inc/mysql.inc.php'; include_once $PIKA_ROOT_DIR.'inc/function.php'; include_once $PIKA_ROOT_DIR.'inc/config.inc.php'; $link=connect(); $html=""; if(isset($_POST['submit'])){ if($_POST['username']!=null && $_POST['password']!=null){ $username=escape($link, $_POST['username']); $password=escape($link, $_POST['password']);//转义,防注入 $query="select * from users where username='$username' and password=md5('$password')"; $result=execute($link, $query); if(mysqli_num_rows($result)==1){ $data=mysqli_fetch_assoc($result); if($data['level']==1){//如果级别是1,进入admin.php $_SESSION['op2']['username']=$username; $_SESSION['op2']['password']=sha1(md5($password)); $_SESSION['op2']['level']=1; header("location:op2_admin.php"); } if($data['level']==2){//如果级别是2,进入user.php $_SESSION['op2']['username']=$username; $_SESSION['op2']['password']=sha1(md5($password)); $_SESSION['op2']['level']=2; header("location:op2_user.php"); } }else{ //查询不到,登录失败 $html.="<p>登录失败,请重新登录</p>"; } } } //只要退到这个界面就先清除登录状态,需要重新登录 //session_unset(); //session_destroy(); //setcookie(session_name(),'',time()-3600,'/'); ?> <div class="main-content"> <div class="main-content-inner"> <div class="breadcrumbs ace-save-state" id="breadcrumbs"> <ul class="breadcrumb"> <li> <i class="ace-icon fa fa-home home-icon"></i> <a href="../op.php">Over Permission</a> </li> <li class="active">op2 login</li> </ul><!-- /.breadcrumb --> <a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)" data-content="这里有两个用户admin/123456,pikachu/000000,admin是超级boss"> 点一下提示~ </a> </div> <div class="page-content"> <div class="op_form"> <div class="op_form_main"> <h4 class="header blue lighter bigger"> <i class="ace-icon fa fa-coffee green"></i> Please Enter Your Information </h4> <form method="post"> <!-- <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><!-- /.widget-main --> </div><!-- /.widget-body --> </div><!-- /.page-content --> </div> </div><!-- /.main-content --> <?php include_once $PIKA_ROOT_DIR . 'footer.php'; ?>
zhuifengshaonianhanlu/pikachu/vul/overpermission/op2/op2_login.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/vul/overpermission/op2/op2_login.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 2413 }
874
<?php /** * Created by runner.han * There is nothing new under the sun */ $SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1); if ($SELF_PAGE = "sqli_search.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(); $html1=''; $html2=''; if(isset($_GET['submit']) && $_GET['name']!=null){ //这里没有做任何处理,直接拼到select里面去了 $name=$_GET['name']; //这里的变量是模糊匹配,需要考虑闭合 $query="select username,id,email from member where username like '%$name%'"; $result=execute($link, $query); if(mysqli_num_rows($result)>=1){ //彩蛋:这里还有个xss $html2.="<p class='notice'>用户名中含有{$_GET['name']}的结果如下:<br />"; while($data=mysqli_fetch_assoc($result)){ $uname=$data['username']; $id=$data['id']; $email=$data['email']; $html1.="<p class='notice'>username:{$uname}<br />uid:{$id} <br />email is: {$email}</p>"; } }else{ $html1.="<p class='notice'>0o。..没有搜索到你输入的信息!</p>"; } } ?> <div class="main-content"> <div class="main-content-inner"> <div class="breadcrumbs ace-save-state" id="breadcrumbs"> <ul class="breadcrumb"> <li> <i class="ace-icon fa fa-home home-icon"></i> <a href="sqli.php">sqli</a> </li> <li class="active">搜索型注入</li> </ul><!-- /.breadcrumb --> <a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)" data-content="%%"> 点一下提示~ </a> </div> <div class="page-content"> <div id="sqli_main"> <p class="sqli_title">请输入用户名进行查找<br />如果记不住用户名,输入用户名的一部分搜索的试试看?</p> <form method="get"> <input class="sqli_in" type="text" name="name" /> <input class="sqli_submit" type="submit" name="submit" value="搜索" /> </form> <?php echo $html2;echo $html1;?> </div> </div><!-- /.page-content --> </div> </div><!-- /.main-content --> <?php include_once $PIKA_ROOT_DIR . 'footer.php'; ?>
zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_search.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_search.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 1620 }
875
<?php /** * Created by PhpStorm. * User: hanlu220 * Date: 2019/5/29 * Time: 13:26 */ /** 1.元素内容:能解释标签和字符实体 2.标签属性值,能解释字符实体 3.属性值支持javascript:协议的,像src,href等,能解释字符实体。 4.事件中的绑定函数,像onmouseover=""这种事件绑定也是标签属性值,能解释字符实体 5.script中的内容:不能解释标签和字符实体。 * * 根据 HTML 的规格,script 元素中的数据不能出现 </。 * 而字符实体因不能被解释也不能 使用。所以,必须通过变更生成的 JavaScript 代码来避免这些问题。 */ $div = ''; $msg = ''; $in = ''; $url = ''; $name = ''; $print = ''; //001--------html普通标签位置输出 if (isset($_GET['div'])){ //这里因为输出是在普通的div标签里面,所以这里直接htmlspecial实体编码即可 // $div .= $_GET['div']; $div .= htmlspecialchars($_GET['div'],ENT_QUOTES); } //002-------输出在普通标签的普通属性 if (isset($_GET['msg'])){ $msg .= $_GET['msg']; // 防范措施:html实体编码 // $msg .= htmlspecialchars($_GET['msg'],ENT_QUOTES); } //003------输出在事件属性中 if (isset($_GET['in'])){ //这里实体编码能解决问题吗。并不能:onmouseover="init('&#039;);alert(document.cookie)//')"> //问题的关键在于:onmouseover是html标签中的属性,能解释字符实体,因此虽然实体编码了,但是解析是任然会被解析成' //比较好的方法是:先做js转义,在进行html实体编码,在解析时:实体被解析出来后,任然是被转义的js $in .= htmlspecialchars($_GET['in'],ENT_QUOTES); // $in .= $_GET['in']; } //004-------输出点在特殊的属性中,如a标签的href //检测输入的是否是http,https,或者/开通的url .正则:\A指定字符必须出现在开头。 function check_url($url){ if (preg_match('/\Ahttp:/',$url) || preg_match('/\Ahttps:/',$url) || preg_match('#\A/#',$url)){ return true; }else{ return false; } } if (isset($_GET['url'])){ // 输出在a标签的href属性中,默认存在xss,payload:aa"><script>alert(1)</script> // 此时用htmlspecialchars进行实体转义,有用吗? 上面的payload确实无法执行了。 $url .= htmlspecialchars($_GET['url'],ENT_QUOTES); // 但是因为href属性中支持使用javascript:执行js,因此问题任然存在,payload:javascript:alert(1) // $url .= $_GET['url']; //正确的做法:先检查是否是url,在进行html实体编码 // if (check_url($_GET['url'])){ // $url .= htmlspecialchars($_GET['url']); // } } //005-------输出点在js中 //转义函数:所有的字符串,除字母,数字,.号,-号外的其他全部进行转义。 //全部转义为unicode(utf-8是unicode的一种实现),unicode可以在js中可以被正常解析使用, //所有的转义操作在后台进行后输出到前台 //转换字符的编码 function unicode_escape($str){ $u16 = mb_convert_encoding($str[0],'UTF-16'); return preg_replace('/[0-9a-f]{4}/','\u$0',bin2hex($u16)); } //将字母和数字还有.-排除后的剩下的字符全部\uXXXX的unicode的形式进行转义 //搜索一个正则,并使用指定的回调函数进行callback function escape_js_string($input){ return preg_replace_callback('/[^-\.0-9a-zA-Z]+/u','unicode_escape',$input); } if (isset($_GET['name'])){ // $name .= $_GET['name']; //处理1:这里直接html实体编码可以吗?其实也可以,就是输出的内容在js里面全是实体字符, //但是由于js本身并不解析html实体字符,因此虽然编码破坏了payload的含义,但也破坏了代码,比如"字符串比较"就无法完成。 // $name .=htmlspecialchars($_GET['name'],ENT_QUOTES); //处理2:将字母和数字还有.-排除后的剩下的字符全部\uXXXX的unicode的形式进行转义 $name .= escape_js_string($_GET['name']); } ?> <html> <body> <div>xss fix demo</div> <div> <!-- 001-输出点在普通的标签中,没什么好说的,实体编码即可--> <!-- payload:<script>alert('xss')</script>--> <?php echo $div;?> <!-- 修复方案,输出的时候做html实体编码,注意单引号--> </div> <form> <!-- 002-输出内容在标签属性中,普通属性--> <!-- payload:a"><script>alert('xss')</script> --> <input name="msg" value="<?php echo $msg;?>"> <!-- 003-输出在支持事件绑定函数的属性中--> <!-- payload:');alert(document.cookie)// --> <input type="button" value="submit" onmouseover="init('<?php echo $in;?>')"> </form> <!-- 004-输出点在标签属性中,支持“javascript:协议” --> <!-- //输出点在标签内容中,payload:javascript:alert(1) --> <a href="<?php echo $url;?>">www.google.com</a> <!-- 005-输出在js中--> <script type="text/javascript"> function init() {} // 005-输出点在js中,构造闭合,即可,payload:xx';alert(1);// var echoxy = '<?php echo $name;?>'; // alert(echoxy); if (echoxy === '>中国'){ alert("比较成功,你的编码杠杠的~"); } </script> </body> </html>
zhuifengshaonianhanlu/pikachu/vul/xss/fixxss.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/vul/xss/fixxss.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 3092 }
876
<?php /** * Created by runner.han * There is nothing new under the sun */ $SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1); if ($SELF_PAGE = "xxe_1.php"){ $ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''); } $PIKA_ROOT_DIR = "../../"; include_once $PIKA_ROOT_DIR.'header.php'; //payload,url编码一下: $xxepayload1 = <<<EOF <?xml version = "1.0"?> <!DOCTYPE ANY [ <!ENTITY f SYSTEM "file:///etc/passwd"> ]> <x>&f;</x> EOF; $xxetest = <<<EOF <?xml version = "1.0"?> <!DOCTYPE note [ <!ENTITY hacker "ESHLkangi"> ]> <name>&hacker;</name> EOF; //$xxedata = simplexml_load_string($xxetest,'SimpleXMLElement'); //print_r($xxedata); //查看当前LIBXML的版本 //print_r(LIBXML_VERSION); $html=''; //考虑到目前很多版本里面libxml的版本都>=2.9.0了,所以这里添加了LIBXML_NOENT参数开启了外部实体解析 if(isset($_POST['submit']) and $_POST['xml'] != null){ $xml =$_POST['xml']; // $xml = $test; $data = @simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOENT); if($data){ $html.="<pre>{$data}</pre>"; }else{ $html.="<p>XML声明、DTD文档类型定义、文档元素这些都搞懂了吗?</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="xee.php"></a> </li> <li class="active">xxe漏洞</li> </ul> <a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)" data-content="先把XML声明、DTD文档类型定义、文档元素这些基础知识自己看一下"> 点一下提示~ </a> </div> <div class="page-content"> <form method="post"> <p>这是一个接收xml数据的api:</p> <input type="text" name="xml" /> <input type="submit" name="submit" value="提交"> </form> <?php echo $html;?> </div><!-- /.page-content --> </div> </div><!-- /.main-content --> <?php include_once $PIKA_ROOT_DIR . 'footer.php'; ?>
zhuifengshaonianhanlu/pikachu/vul/xxe/xxe_1.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/vul/xxe/xxe_1.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 1479 }
877
# 8th Wall Web Examples - AFrame - Tap to place [Try the live demo here](https://8thwall.8thwall.app/placeground-aframe) This example allows the user to grow trees on the ground by tapping. Showcases raycasting, creating new objects, and importing a 3D model. ![](https://media.giphy.com/media/1vcbBZMlaZ4KElLnNH/giphy.gif) ### Project Components ```tap-place``` The primary component used is called ‘tap-place’. This component attaches to the a-scene. On ‘click’ (when the user taps the screen), it creates a new a-entity. This is the empty game object that will hold the tree. Then, using the raycaster attached to the scene’s a-camera, it determines where the intersection with the ground occurs (the new tree’s position). Next, it applies a random rotation for aesthetic, sets its scale to a very small value (in preparation for the scale-up animation), sets the ‘gltf-model’ attribute to the tree model and append the new element as a child of the scene. Finally, once the ‘model-loaded’ event fires, it applies the scale-up animation.
8thwall/web/examples/aframe/placeground/README.md/0
{ "file_path": "8thwall/web/examples/aframe/placeground/README.md", "repo_id": "8thwall", "token_count": 299 }
0
// jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom'
8thwall/web/examples/aframe/reactapp/src/setupTests.js/0
{ "file_path": "8thwall/web/examples/aframe/reactapp/src/setupTests.js", "repo_id": "8thwall", "token_count": 75 }
1
/* globals BABYLON TWEEN XR8 XRExtras */ const modelRootURL = './' // Directory where 3D model lives const modelFile = 'tree.glb' // 3D model to spawn at tap const startScale = new BABYLON.Vector3(0.1, 0.1, -0.1) // Initial scale value for our model const endScale = new BABYLON.Vector3(2.0, 2.0, -2.0) // Ending scale value for our model const animationMillis = 750 // Animate over 0.75 seconds let surface, engine, scene, camera // Populates some object into an XR scene and sets the initial camera position. const initXrScene = () => { const directionalLight = new BABYLON.DirectionalLight( 'DirectionalLight', new BABYLON.Vector3(0, -1, 1), scene ) directionalLight.intensity = 1.0 const ground = BABYLON.Mesh.CreatePlane('ground', 100, scene) ground.rotation.x = Math.PI / 2 ground.material = new BABYLON.StandardMaterial('groundMaterial', scene) ground.material.diffuseColor = BABYLON.Color3.Purple() ground.material.alpha = 0 surface = ground // Set the initial camera position relative to the scene we just laid out. This must be at a // height greater than y=0. camera.position = new BABYLON.Vector3(0, 3, -5) } const placeObjectTouchHandler = (e) => { // console.log('placeObjectTouchHandler') // Call XrController.recenter() when the canvas is tapped with two fingers. This resets the // AR camera to the position specified by XrController.updateCameraProjectionMatrix() above. if (e.touches.length === 2) { XR8.XrController.recenter() } if (e.touches.length > 2) { return } // If the canvas is tapped with one finger and hits the "surface", spawn an object. const pickResult = scene.pick(e.touches[0].clientX, e.touches[0].clientY) if (pickResult.hit && pickResult.pickedMesh === surface) { BABYLON.SceneLoader.ImportMesh( '', modelRootURL, modelFile, scene, (newMeshes) => { // onSuccess const mesh = newMeshes[0] mesh.scaling = new BABYLON.Vector3(startScale.x, startScale.y, startScale.z) const yRot = Math.random() * Math.PI mesh.position = new BABYLON.Vector3(pickResult.pickedPoint.x, 0, pickResult.pickedPoint.z) mesh.rotation = new BABYLON.Vector3(0, yRot, 0) const scale = Object.assign({}, startScale) new TWEEN.Tween(scale) .to(endScale, animationMillis) .easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth. .onUpdate(() => { mesh.scaling.x = scale.x mesh.scaling.y = scale.y mesh.scaling.z = scale.z }) .start() // Start the tween immediately. }, (xhr) => { // onProgress console.log(`${(xhr.loaded / xhr.total * 100)}% loaded`) }, () => { // onError console.log('Error loading model') } ) } } const startScene = () => { const canvas = document.getElementById('renderCanvas') engine = new BABYLON.Engine(canvas, true, {stencil: true, preserveDrawingBuffer: true}) engine.enableOfflineSupport = false scene = new BABYLON.Scene(engine) camera = new BABYLON.FreeCamera('camera', new BABYLON.Vector3(0, 0, 0), scene) initXrScene() // Add objects to the scene and set starting camera position. // Connect the camera to the XR engine and show camera feed camera.addBehavior(XR8.Babylonjs.xrCameraBehavior(), true) canvas.addEventListener('touchstart', placeObjectTouchHandler, true) // Add touch listener. engine.runRenderLoop(() => { // Enable TWEEN animations. TWEEN.update(performance.now()) scene.render() }) window.addEventListener('resize', () => { engine.resize() }) } const onxrloaded = () => { XR8.addCameraPipelineModules([ // Add camera pipeline modules. XRExtras.AlmostThere.pipelineModule(), // Detects unsupported browsers and gives hints. XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup. XRExtras.RuntimeError.pipelineModule(), // Shows an error image on runtime error. ]) startScene() } // Show loading screen before the full XR library has been loaded. const load = () => { XRExtras.Loading.showLoading({onxrloaded}) } window.onload = () => { if (window.XRExtras) { load() } else { window.addEventListener('xrextrasloaded', load) } }
8thwall/web/examples/babylonjs/placeground/index.js/0
{ "file_path": "8thwall/web/examples/babylonjs/placeground/index.js", "repo_id": "8thwall", "token_count": 1706 }
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. */ function QRCodeDataBlockReader(blocks, version, numErrorCorrectionCode) { this.blockPointer = 0; this.bitPointer = 7; this.dataLength = 0; this.blocks = blocks; this.numErrorCorrectionCode = numErrorCorrectionCode; if (version <= 9) this.dataLengthMode = 0; else if (version >= 10 && version <= 26) this.dataLengthMode = 1; else if (version >= 27 && version <= 40) this.dataLengthMode = 2; this.getNextBits = function( numBits) { var bits = 0; if (numBits < this.bitPointer + 1) { // next word fits into current data block var mask = 0; for (var i = 0; i < numBits; i++) { mask += (1 << i); } mask <<= (this.bitPointer - numBits + 1); bits = (this.blocks[this.blockPointer] & mask) >> (this.bitPointer - numBits + 1); this.bitPointer -= numBits; return bits; } else if (numBits < this.bitPointer + 1 + 8) { // next word crosses 2 data blocks var mask1 = 0; for (var i = 0; i < this.bitPointer + 1; i++) { mask1 += (1 << i); } bits = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); this.blockPointer++; bits += ((this.blocks[this.blockPointer]) >> (8 - (numBits - (this.bitPointer + 1)))); this.bitPointer = this.bitPointer - numBits % 8; if (this.bitPointer < 0) { this.bitPointer = 8 + this.bitPointer; } return bits; } else if (numBits < this.bitPointer + 1 + 16) { // next word crosses 3 data blocks var mask1 = 0; // mask of first block var mask3 = 0; // mask of 3rd block //bitPointer + 1 : number of bits of the 1st block //8 : number of the 2nd block (note that use already 8bits because next word uses 3 data blocks) //numBits - (bitPointer + 1 + 8) : number of bits of the 3rd block for (var i = 0; i < this.bitPointer + 1; i++) { mask1 += (1 << i); } var bitsFirstBlock = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); this.blockPointer++; var bitsSecondBlock = this.blocks[this.blockPointer] << (numBits - (this.bitPointer + 1 + 8)); this.blockPointer++; for (var i = 0; i < numBits - (this.bitPointer + 1 + 8); i++) { mask3 += (1 << i); } mask3 <<= 8 - (numBits - (this.bitPointer + 1 + 8)); var bitsThirdBlock = (this.blocks[this.blockPointer] & mask3) >> (8 - (numBits - (this.bitPointer + 1 + 8))); bits = bitsFirstBlock + bitsSecondBlock + bitsThirdBlock; this.bitPointer = this.bitPointer - (numBits - 8) % 8; if (this.bitPointer < 0) { this.bitPointer = 8 + this.bitPointer; } return bits; } else { return 0; } } this.NextMode=function() { if ((this.blockPointer > this.blocks.length - this.numErrorCorrectionCode - 2)) return 0; else return this.getNextBits(4); } this.getDataLength=function( modeIndicator) { var index = 0; while (true) { if ((modeIndicator >> index) == 1) break; index++; } return this.getNextBits(qrcode.sizeOfDataLengthInfo[this.dataLengthMode][index]); } this.getRomanAndFigureString=function( dataLength) { var length = dataLength; var intData = 0; var strData = ""; var tableRomanAndFigure = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'); do { if (length > 1) { intData = this.getNextBits(11); var firstLetter = Math.floor(intData / 45); var secondLetter = intData % 45; strData += tableRomanAndFigure[firstLetter]; strData += tableRomanAndFigure[secondLetter]; length -= 2; } else if (length == 1) { intData = this.getNextBits(6); strData += tableRomanAndFigure[intData]; length -= 1; } } while (length > 0); return strData; } this.getFigureString=function( dataLength) { var length = dataLength; var intData = 0; var strData = ""; do { if (length >= 3) { intData = this.getNextBits(10); if (intData < 100) strData += "0"; if (intData < 10) strData += "0"; length -= 3; } else if (length == 2) { intData = this.getNextBits(7); if (intData < 10) strData += "0"; length -= 2; } else if (length == 1) { intData = this.getNextBits(4); length -= 1; } strData += intData; } while (length > 0); return strData; } this.get8bitByteArray=function( dataLength) { var length = dataLength; var intData = 0; var output = new Array(); do { intData = this.getNextBits(8); output.push( intData); length--; } while (length > 0); return output; } this.getKanjiString=function( dataLength) { var length = dataLength; var intData = 0; var unicodeString = ""; do { intData = this.getNextBits(13); var lowerByte = intData % 0xC0; var higherByte = intData / 0xC0; var tempWord = (higherByte << 8) + lowerByte; var shiftjisWord = 0; if (tempWord + 0x8140 <= 0x9FFC) { // between 8140 - 9FFC on Shift_JIS character set shiftjisWord = tempWord + 0x8140; } else { // between E040 - EBBF on Shift_JIS character set shiftjisWord = tempWord + 0xC140; } //var tempByte = new Array(0,0); //tempByte[0] = (sbyte) (shiftjisWord >> 8); //tempByte[1] = (sbyte) (shiftjisWord & 0xFF); //unicodeString += new String(SystemUtils.ToCharArray(SystemUtils.ToByteArray(tempByte))); unicodeString += String.fromCharCode(shiftjisWord); length--; } while (length > 0); return unicodeString; } this.parseECIValue = function () { var intData = 0; var firstByte = this.getNextBits(8); if ((firstByte & 0x80) == 0) { intData = firstByte & 0x7F; } if ((firstByte & 0xC0) == 0x80) { // two bytes var secondByte = this.getNextBits(8); intData = ((firstByte & 0x3F) << 8) | secondByte; } if ((firstByte & 0xE0) == 0xC0) { // three bytes var secondThirdBytes = this.getNextBits(8);; intData = ((firstByte & 0x1F) << 16) | secondThirdBytes; } return intData; } this.__defineGetter__("DataByte", function() { var output = new Array(); var MODE_NUMBER = 1; var MODE_ROMAN_AND_NUMBER = 2; var MODE_8BIT_BYTE = 4; var MODE_ECI = 7; var MODE_KANJI = 8; do { var mode = this.NextMode(); //canvas.println("mode: " + mode); if (mode == 0) { if (output.length > 0) break; else throw "Empty data block"; } if (mode != MODE_NUMBER && mode != MODE_ROMAN_AND_NUMBER && mode != MODE_8BIT_BYTE && mode != MODE_KANJI && mode != MODE_ECI) { throw "Invalid mode: " + mode + " in (block:" + this.blockPointer + " bit:" + this.bitPointer + ")"; } if(mode == MODE_ECI) { var temp_sbyteArray3 = this.parseECIValue(); //output.push(temp_sbyteArray3); } else { var dataLength = this.getDataLength(mode); if (dataLength < 1) throw "Invalid data length: " + dataLength; switch (mode) { case MODE_NUMBER: var temp_str = this.getFigureString(dataLength); var ta = new Array(temp_str.length); for(var j=0;j<temp_str.length;j++) ta[j]=temp_str.charCodeAt(j); output.push(ta); break; case MODE_ROMAN_AND_NUMBER: var temp_str = this.getRomanAndFigureString(dataLength); var ta = new Array(temp_str.length); for(var j=0;j<temp_str.length;j++) ta[j]=temp_str.charCodeAt(j); output.push(ta ); break; case MODE_8BIT_BYTE: var temp_sbyteArray3 = this.get8bitByteArray(dataLength); output.push(temp_sbyteArray3); break; case MODE_KANJI: var temp_str = this.getKanjiString(dataLength); output.push(temp_str); break; } } } while (true); return output; }); }
8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/databr.js/0
{ "file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/databr.js", "repo_id": "8thwall", "token_count": 4214 }
3
// Copyright (c) 2018 8th Wall, Inc. const fragmentShaders = [ // Define some simple shaders to apply to the camera feed. ` precision mediump float; // Just the camera feed. varying vec2 texUv; uniform sampler2D sampler; void main() { gl_FragColor = texture2D(sampler, texUv); }`, ` precision mediump float; // Color boost. varying vec2 texUv; uniform sampler2D sampler; void main() { vec4 c = texture2D(sampler, texUv); float y = dot(c.rgb, vec3(0.299, 0.587, 0.114)); float u = dot(c.rgb, vec3(-.159, -.331, .5)) * 6.0; float v = dot(c.rgb, vec3(.5, -.419, -.081)) * 3.0; gl_FragColor = vec4(y + 1.4 * v, y - .343 * u - .711 * v, y + 1.765 * u, c.a); }`, ` precision mediump float; // Vignette. varying vec2 texUv; uniform sampler2D sampler; void main() { float x = texUv.x - .5; float y = texUv.y - .5; float v = 1.5 - sqrt(x * x + y * y) * 2.5; vec4 c = texture2D(sampler, texUv); gl_FragColor = vec4(c.rgb * (v > 1.0 ? 1.0 : v), c.a); }`, ` precision mediump float; // Black and white. varying vec2 texUv; uniform sampler2D sampler; void main() { vec4 c = texture2D(sampler, texUv); gl_FragColor = vec4(vec3(dot(c.rgb, vec3(0.299, 0.587, 0.114))), c.a); }`, ` precision mediump float; // Sepia. varying vec2 texUv; uniform sampler2D sampler; void main() { vec4 c = texture2D(sampler, texUv); gl_FragColor.r = dot(c.rgb, vec3(.393, .769, .189)); gl_FragColor.g = dot(c.rgb, vec3(.349, .686, .168)); gl_FragColor.b = dot(c.rgb, vec3(.272, .534, .131)); gl_FragColor.a = c.a; }`, ` precision mediump float; // Purple. varying vec2 texUv; uniform sampler2D sampler; void main() { vec4 c = texture2D(sampler, texUv); float y = dot(c.rgb, vec3(0.299, 0.587, 0.114)); vec3 p = vec3(.463, .067, .712); vec3 rgb = y < .25 ? (y * 4.0) * p : ((y - .25) * 1.333) * (vec3(1.0, 1.0, 1.0) - p) + p; gl_FragColor = vec4(rgb, c.a); }`, ] // Define a custom pipeline module. This module cycles through a set of pre-defined shaders each // time the next button is pressed. It also updates the button style on orientation changes. const nextbuttonPipelineModule = () => { const nextButton = document.getElementById('nextbutton') let idx = 0 // Index of the shader to use next. const nextShader = () => { // Reconfigure the texture renderer pipline module to use the next shader. XR8.GlTextureRenderer.configure({fragmentSource: fragmentShaders[idx]}) idx = (idx + 1) % fragmentShaders.length } nextShader() // Call 'nextShader' once to set the first shader. nextButton.onclick = nextShader // Switch to the next shader when the next button is pressed. const adjustButtonTextCenter = ({orientation}) => { // Update the line height on the button. const ww = window.innerWidth const wh = window.innerHeight // Wait for orientation change to take effect before handling resize. if (((orientation == 0 || orientation == 180) && ww > wh) || ((orientation == 90 || orientation == -90) && wh > ww)) { window.requestAnimationFrame(() => adjustButtonTextCenter({orientation})) return } nextButton.style.lineHeight = `${nextButton.getBoundingClientRect().height}px` } // Return a pipeline module that updates the state of the UI on relevant lifecycle events. return { name: 'nextbutton', onStart: ({orientation}) => { nextButton.style.visibility = 'visible' adjustButtonTextCenter({orientation}) }, onDeviceOrientationChange: ({orientation}) => { adjustButtonTextCenter({orientation}) }, } } const onxrloaded = () => { XR8.addCameraPipelineModules([ // Add camera pipeline modules. // Existing pipeline modules. 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. nextbuttonPipelineModule(), // Cycles through shaders and keeps UI up to date. ]) // 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/simpleshaders/index.js/0
{ "file_path": "8thwall/web/examples/camerapipeline/simpleshaders/index.js", "repo_id": "8thwall", "token_count": 1880 }
4
/* globals BABYLON XR8 XRExtras */ let box, engine, scene, camera // Populates some object into an XR scene and sets the initial camera position. const initXrScene = () => { const directionalLight = new BABYLON.DirectionalLight( 'DirectionalLight', new BABYLON.Vector3(0, -1, 1), scene ) directionalLight.intensity = 1.0 const sphere = BABYLON.MeshBuilder.CreateSphere('sphere', {diameter: 1}, scene) sphere.material = new BABYLON.StandardMaterial('sphereMaterial', scene) sphere.material.diffuseColor = BABYLON.Color3.Red() sphere.position = new BABYLON.Vector3(1, 0.5, 0) const cone = BABYLON.MeshBuilder.CreateCylinder( 'cone', {height: 1, diameterBottom: 1, diameterTop: 0}, scene ) cone.material = new BABYLON.StandardMaterial('coneMaterial', scene) cone.material.diffuseColor = BABYLON.Color3.Green() cone.position = new BABYLON.Vector3(-1, 0.5, 0.5) const ground = BABYLON.MeshBuilder.CreatePlane('ground', {size: 4}, scene) ground.rotation.x = Math.PI / 2 ground.material = new BABYLON.StandardMaterial('groundMaterial', scene) ground.material.diffuseColor = BABYLON.Color3.Purple() ground.material.alpha = 0.5 ground.position = new BABYLON.Vector3(0, 0, 0) box = BABYLON.MeshBuilder.CreateBox('box', {size: 0.5}, scene) box.material = new BABYLON.StandardMaterial('boxMaterial', scene) box.material.diffuseColor = BABYLON.Color3.Teal() box.position = new BABYLON.Vector3(0, 0.25, -1) box.rotation.y = 45 // Set the initial camera position relative to the scene we just laid out. // This must be at a height greater than y=0. camera.position = new BABYLON.Vector3(0, 3, -5) } const recenterTouchHandler = (e) => { // Call XrController.recenter() when the canvas is tapped with two fingers. // This resets the AR camera to the position specified by // XrController.updateCameraProjectionMatrix() above. if (e.touches.length === 2) { XR8.XrController.recenter() } } const startScene = () => { const canvas = document.getElementById('renderCanvas') engine = new BABYLON.Engine(canvas, true, {stencil: true, preserveDrawingBuffer: true}) engine.enableOfflineSupport = false scene = new BABYLON.Scene(engine) camera = new BABYLON.FreeCamera('camera', new BABYLON.Vector3(0, 0, 0), scene) initXrScene() // Add objects to the scene and set starting camera position. // Connect the camera to the XR engine and show camera feed camera.addBehavior(XR8.Babylonjs.xrCameraBehavior(), true) canvas.addEventListener('touchstart', recenterTouchHandler, true) // Add touch listener. engine.runRenderLoop(() => { // Animate box rotation box.rotation.y += 0.02 // Render scene scene.render() }) window.addEventListener('resize', () => { engine.resize() }) } const onxrloaded = () => { XR8.addCameraPipelineModules([ // Add camera pipeline modules. window.LandingPage.pipelineModule(), // Detects unsupported browsers and gives hints. XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup. XRExtras.RuntimeError.pipelineModule(), // Shows an error image on runtime error. ]) startScene() } // Show loading screen before the full XR library has been loaded. window.onload = () => { XRExtras.Loading.showLoading({onxrloaded}) }
8thwall/web/gettingstarted/babylonjs/index.js/0
{ "file_path": "8thwall/web/gettingstarted/babylonjs/index.js", "repo_id": "8thwall", "token_count": 1148 }
5
import type {ComponentDefinition} from 'aframe' declare const XRExtras: any const resourceComponent: ComponentDefinition = { schema: { src: {type: 'string'}, }, } const srcFromAttr = (scene, v) => { if (!v) { return v } const el = scene.querySelector(v) if (!el) { return v } return el.getAttribute('src') || v } const pbrMaterialComponent: ComponentDefinition = { schema: { tex: {type: 'string'}, metalness: {type: 'string'}, normals: {type: 'string'}, roughness: {type: 'string'}, alpha: {type: 'string'}, opacity: {default: 1.0}, }, init() { this.el.object3D.visible = false this.el.material = XRExtras.ThreeExtras.pbrMaterial({ tex: srcFromAttr(this.el.sceneEl, this.data.tex), metalness: srcFromAttr(this.el.sceneEl, this.data.metalness), normals: srcFromAttr(this.el.sceneEl, this.data.normals), roughness: srcFromAttr(this.el.sceneEl, this.data.roughness), alpha: srcFromAttr(this.el.sceneEl, this.data.alpha), opacity: this.data.opacity, }) }, } const basicMaterialComponent: ComponentDefinition = { schema: { tex: {type: 'string'}, alpha: {type: 'string'}, opacity: {default: 1.0}, }, init() { this.el.object3D.visible = false this.el.material = XRExtras.ThreeExtras.basicMaterial({ tex: srcFromAttr(this.el.sceneEl, this.data.tex), alpha: srcFromAttr(this.el.sceneEl, this.data.alpha), opacity: this.data.opacity, }) }, } const videoMaterialComponent: ComponentDefinition = { schema: { video: {type: 'string'}, alpha: {type: 'string'}, autoplay: {type: 'bool', default: true}, opacity: {default: 1.0}, }, init() { const video = document.querySelector(this.data.video) this.el.object3D.visible = false this.el.material = XRExtras.ThreeExtras.videoMaterial({ video, alpha: srcFromAttr(this.el.sceneEl, this.data.alpha), opacity: this.data.opacity, }) if (this.data.autoplay) { video.play() } }, } const hiderMaterialComponent: ComponentDefinition = { init() { const hiderMaterial = new window.THREE.MeshStandardMaterial() hiderMaterial.colorWrite = false const applyHiderMaterial = (mesh) => { if (!mesh) { return } if (mesh.material) { mesh.material = hiderMaterial } mesh.traverse((node) => { if (node.isMesh) { node.material = hiderMaterial } }) } applyHiderMaterial(this.el.getObject3D('mesh')) this.el.addEventListener( 'model-loaded', () => applyHiderMaterial(this.el.getObject3D('mesh')) ) }, } export { resourceComponent, pbrMaterialComponent, basicMaterialComponent, videoMaterialComponent, hiderMaterialComponent, }
8thwall/web/xrextras/src/aframe/components/asset-components.ts/0
{ "file_path": "8thwall/web/xrextras/src/aframe/components/asset-components.ts", "repo_id": "8thwall", "token_count": 1132 }
6
// The create method will only be called once const memo = <T extends ((...args: any[]) => NonNullable<any>)>(create: T) => { let value: ReturnType<T> | null = null let didCall = false return (...args: Parameters<typeof create>): ReturnType<T> => { if (!didCall) { value = create(...args) didCall = true } return value! } } export { memo, }
8thwall/web/xrextras/src/common/factory.ts/0
{ "file_path": "8thwall/web/xrextras/src/common/factory.ts", "repo_id": "8thwall", "token_count": 140 }
7
import htmlContent from './record-button.html' import './record-button.css' import {configure, getConfig} from './capture-config' import {drawWatermark} from './watermark' const ACTIVE_TIMEOUT = 300 let captureMode = 'standard' let status = 'waiting' let activeTimeout = null let isDown = false // This is used to keep track of if the preview video has been generated, but the final video has // not yet completed let isWaitingOnFinal = false let container let flashElement let progressBar const clearDisplayState = () => { container.classList.remove('fade-container') container.classList.remove('active') container.classList.remove('recording') container.classList.remove('loading') container.classList.remove('fixed-mode') flashElement.classList.remove('flashing') clearTimeout(activeTimeout) isDown = false status = 'waiting' } const clearState = () => { clearDisplayState() isWaitingOnFinal = false } const previewOpened = () => { // Wait for preview to be shown before clearing the loading state clearDisplayState() container.classList.add('fade-container') } const previewClosed = () => { // If we're waiting on finalization of the media recording when the preview closes, we can't start // a new recording yet, so the record button must remain in a loading state. if (isWaitingOnFinal) { container.classList.add('loading') container.classList.remove('fade-container') status = 'finalize-blocked' } else { clearState() } } const takeScreenshot = () => { const currentConfig = getConfig() status = 'flash' flashElement.classList.add('flashing') window.XR8.CanvasScreenshot.takeScreenshot({ onProcessFrame: ({ctx}) => { if (currentConfig.onProcessFrame) { currentConfig.onProcessFrame({ctx}) } drawWatermark(ctx) }, }).then( (data) => { const bytes = atob(data) const buffer = new ArrayBuffer(bytes.length) const array = new Uint8Array(buffer) for (let i = 0; i < bytes.length; i++) { array[i] = bytes.charCodeAt(i) } const blob = new Blob([buffer], {type: 'image/jpeg'}) clearState() window.dispatchEvent(new CustomEvent('mediarecorder-photocomplete', {detail: {blob}})) } ).catch(() => { clearState() }) } const showLoading = () => { if (status !== 'recording') { return } container.classList.remove('fixed-mode') container.classList.remove('recording') container.classList.add('loading') status = 'loading' } const endRecording = () => { if (status !== 'recording') { return } XR8.MediaRecorder.stopRecording() showLoading() } const startRecording = () => { if (status !== 'active') { return } const currentConfig = getConfig() status = 'recording' container.classList.add('recording') XR8.MediaRecorder.recordVideo({ onVideoReady: (result) => { isWaitingOnFinal = false if (status === 'finalize-blocked') { clearState() } window.dispatchEvent(new CustomEvent('mediarecorder-recordcomplete', {detail: result})) }, onStart: (result) => { window.dispatchEvent(new CustomEvent('mediarecorder-recordstart', {detail: result})) }, onStop: (result) => { window.dispatchEvent(new CustomEvent('mediarecorder-recordstop', {detail: result})) showLoading() }, onError: (result) => { window.dispatchEvent(new CustomEvent('mediarecorder-recorderror', {detail: result})) clearState() }, onProcessFrame: (frameInfo) => { const {elapsedTimeMs, maxRecordingMs, ctx} = frameInfo const timeLeft = (1 - elapsedTimeMs / maxRecordingMs) progressBar.style.strokeDashoffset = `${100 * timeLeft}` if (currentConfig.onProcessFrame) { currentConfig.onProcessFrame(frameInfo) } drawWatermark(ctx) }, onPreviewReady: (result) => { isWaitingOnFinal = true window.dispatchEvent(new CustomEvent('mediarecorder-previewready', {detail: result})) }, onFinalizeProgress: result => window.dispatchEvent( new CustomEvent('mediarecorder-finalizeprogress', {detail: result}) ), }) } const goActive = () => { if (status !== 'waiting') { return } status = 'active' container.classList.add('active') activeTimeout = setTimeout(startRecording, ACTIVE_TIMEOUT) } const cancelActive = () => { if (status !== 'active') { return } clearTimeout(activeTimeout) takeScreenshot() } const down = (e) => { e.preventDefault() if (isDown) { return } isDown = true if (captureMode === 'fixed') { if (status === 'waiting') { status = 'active' container.classList.add('fixed-mode') container.classList.add('active') startRecording() } else if (status === 'recording') { endRecording() } } else if (captureMode === 'photo') { container.classList.add('active') takeScreenshot() } else if (status === 'waiting') { // Standard mode down starts active state goActive() } } const up = () => { if (!isDown) { return } isDown = false if (captureMode !== 'standard') { return } if (status === 'active') { cancelActive() } if (status === 'recording') { endRecording() } } const initRecordButton = () => { window.XR8.addCameraPipelineModule(XR8.MediaRecorder.pipelineModule()) document.body.insertAdjacentHTML('beforeend', htmlContent) container = document.querySelector('#recorder') flashElement = document.querySelector('#flashElement') progressBar = document.querySelector('#progressBar') const button = document.querySelector('#recorder-button') button.addEventListener('touchstart', down) button.addEventListener('mousedown', down) window.addEventListener('mouseup', up) window.addEventListener('touchend', up) window.addEventListener('mediarecorder-previewclosed', previewClosed) window.addEventListener('mediarecorder-previewopened', previewOpened) // Initialize with default configuration configure() } const removeRecordButton = () => { window.XR8.removeCameraPipelineModule(window.XR8.MediaRecorder.pipelineModule().name) container.parentNode.removeChild(container) flashElement.parentNode.removeChild(flashElement) window.removeEventListener('mouseup', up) window.removeEventListener('touchend', up) window.removeEventListener('mediarecorder-previewclosed', previewClosed) window.removeEventListener('mediarecorder-previewopened', previewOpened) clearState() container = null flashElement = null progressBar = null } const setCaptureMode = (mode) => { switch (mode) { case 'photo': case 'fixed': captureMode = mode break default: captureMode = 'standard' } } export { initRecordButton, removeRecordButton, setCaptureMode, }
8thwall/web/xrextras/src/mediarecorder/record-button.js/0
{ "file_path": "8thwall/web/xrextras/src/mediarecorder/record-button.js", "repo_id": "8thwall", "token_count": 2392 }
8
/* globals THREE */ let threeExtras = null const ThreeExtrasFactory = () => { if (threeExtras == null) { threeExtras = create() } return threeExtras } const pbrMaterial = ({opacity, tex, metalness, normals, roughness, alpha}) => { let texLoader = null const props = {} if (opacity < 1.0) { props.transparent = true props.opacity = Math.max(0.0, opacity) } if (tex) { texLoader = texLoader || new THREE.TextureLoader() props.map = texLoader.load(tex) } if (metalness) { texLoader = texLoader || new THREE.TextureLoader() props.metalnessMap = texLoader.load(metalness) } if (normals) { texLoader = texLoader || new THREE.TextureLoader() props.normalMap = texLoader.load(normals) } if (roughness) { texLoader = texLoader || new THREE.TextureLoader() props.roughnessMap = texLoader.load(roughness) } if (alpha) { texLoader = texLoader || new THREE.TextureLoader() props.alphaMap = texLoader.load(alpha) } return new THREE.MeshStandardMaterial(props) } const basicMaterial = ({opacity, tex, alpha}) => { let texLoader = null const props = {} if (opacity < 1.0) { props.transparent = true props.opacity = Math.max(0.0, opacity) } if (tex) { texLoader = texLoader || new THREE.TextureLoader() props.map = texLoader.load(tex) } if (alpha) { texLoader = texLoader || new THREE.TextureLoader() props.alphaMap = texLoader.load(alpha) } return new THREE.MeshBasicMaterial(props) } const videoMaterial = ({opacity, video, alpha}) => { let texLoader = null const props = {} if (opacity < 1.0) { props.transparent = true props.opacity = Math.max(0.0, opacity) } if (video) { props.map = new THREE.VideoTexture(video) } if (alpha) { texLoader = texLoader || new THREE.TextureLoader() props.alphaMap = texLoader.load(alpha) } return new THREE.MeshBasicMaterial(props) } const faceMesh = (modelGeometry, material) => { const geometry = new THREE.BufferGeometry() // Fill geometry with default vertices. const vertices = new Float32Array(modelGeometry.pointsPerDetection * 3) geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3)) // Fill geometry with default normals. const normals = new Float32Array(modelGeometry.pointsPerDetection * 3) geometry.setAttribute('normal', new THREE.BufferAttribute(normals, 3)) // Add the UVs to the geometry. const uvs = new Float32Array(modelGeometry.uvs.length * 2) for (let i = 0; i < modelGeometry.uvs.length; ++i) { uvs[i * 2] = modelGeometry.uvs[i].u uvs[i * 2 + 1] = modelGeometry.uvs[i].v } geometry.setAttribute('uv', new THREE.BufferAttribute(uvs, 2)) // Add the indices. const indices = new Array(modelGeometry.indices.length * 3) for (let i = 0; i < modelGeometry.indices.length; ++i) { indices[i * 3] = modelGeometry.indices[i].a indices[i * 3 + 1] = modelGeometry.indices[i].b indices[i * 3 + 2] = modelGeometry.indices[i].c } geometry.setIndex(indices) const mesh = new THREE.Mesh(geometry, material) const show = ({detail}) => { // Update vertex positions. for (let i = 0; i < detail.vertices.length; ++i) { vertices[i * 3] = detail.vertices[i].x vertices[i * 3 + 1] = detail.vertices[i].y vertices[i * 3 + 2] = detail.vertices[i].z } mesh.geometry.attributes.position.needsUpdate = true // Update vertex normals. for (let i = 0; i < detail.normals.length; ++i) { normals[i * 3] = detail.normals[i].x normals[i * 3 + 1] = detail.normals[i].y normals[i * 3 + 2] = detail.normals[i].z } mesh.geometry.attributes.normal.needsUpdate = true mesh.visible = true } const hide = () => { mesh.visible = false } return { mesh, show, hide, } } const createCurvedGeometry = (geometry, isFull, userHeight, userWidth) => { const length = geometry.arcLengthRadians * (userWidth || 1) return new THREE.CylinderGeometry( geometry.radiusTop, geometry.radiusBottom, userHeight ? geometry.height * userHeight : geometry.height, 50, 1, true, (isFull ? 0.0 : (2 * Math.PI - length) / 2) + Math.PI, isFull ? 2 * Math.PI : length ) } const createFlatGeometry = (geometry, userHeight, userWidth) => new THREE.PlaneGeometry( geometry.scaledWidth * (userWidth || 1), geometry.scaledHeight * (userHeight || 1) ) const createTargetGeometry = (geometry, isFull, userHeight, userWidth) => { switch (geometry.type) { case 'FLAT': return createFlatGeometry(geometry, userHeight, userWidth) case 'CONICAL': case 'CYLINDRICAL': return createCurvedGeometry(geometry, !!isFull, userHeight, userWidth) default: return null } } const create = () => ({ basicMaterial, createTargetGeometry, faceMesh, pbrMaterial, videoMaterial, }) export { ThreeExtrasFactory, }
8thwall/web/xrextras/src/three/three-extras.js/0
{ "file_path": "8thwall/web/xrextras/src/three/three-extras.js", "repo_id": "8thwall", "token_count": 1816 }
9
## 1、什么是前端 前端对于网站来说,通常是指网页,网站的前端部分包括网站的表现层和结构层。因此前端技术一般分为前端设计和前端开发。 前端设计一般可以理解为网站的视觉设计,比如 UI 设计; 前端开发则是网站的前台代码实现,包括基本的HTML和CSS以及JavaScript等。 前端开发的核心部分主要是:`HTML`,`CSS`,`JavaScript` 三个部分。 **HTML** 是这三者中最基础的部分,相当于是网页的骨架,也就是网页的结构; **CSS** 部分是网页的表现形式,也可以说是网页的美化,比如一个图片的大小、位置,文字的大小颜色等; **JavaScript** 是一种动态的脚本语言,负责与用户进行交互,增加用户体验的作用。 ## 2、网页组成 一个网页的组成部分主要包括下面几个部分:**文字、图片、输入框、视频、音频、超链接** 等。 ## 3、Web 标准 说道 Web 标准,不能不说 W3C 组织(World Wide Web Consortium),全程为「万维网联盟」。万维网联盟创建于1994年,是Web技术领域最具权威和影响力的国际中立性技术标准机构。 W3C 最重要的工作是发展 Web 规范,这些规范描述了 Web 的通信协议。简单的说就是就是确定 Web 页面的语法格式和规范的。 与之类似的一个组织是「European Computer Manufacturers Association」(ECMA组织),这个组织制定了标准的脚本语言规范 ECMAScript ,而 JavaScript 就参照的这个规范。 那么 Web 标准规范了下面三个部分: - HTML 标准(结构标准 ),相当人的骨架结构。 - CSS 样式(表现)标准 , 相当于给人化妆变的更漂亮。 - JavaScript 行为标准 , 相当与人在唱歌,页面更灵动。 ## 4、浏览器内核 浏览器内核是一个浏览器的核心部分,也就是「**渲染引擎**」。它的主要作用是决定一个浏览器如何显示网页的内容及页面的格式信息。不同的浏览器内核对网页编写语法的解释也有不同,因此同一网页在不同的内核的浏览器里的渲染(显示)效果也可能不同。 这里涉及到一个「**兼容性问题**」,浏览器兼容性问题又被称为网页兼容性或网站兼容性问题,指网页在各种浏览器上的显示效果可能不一致而产生浏览器和网页间的兼容问题。所以我们在编写代码的时候,做好浏览器兼容,才能够让网站在不同的浏览器下都正常显示。而对于浏览器软件的开发和设计,浏览器对标准的更好兼容能够给用户更好的使用体验。 **常见浏览器以及对应的内核:** | 内核 | 代表浏览器 | 描述 | | ---------- | ------------------ | ------------------------------------------------------------ | | `Trident` | IE | IE内核,是微软开发的一种排版引擎 | | `Gecko` | Firefox | Gecko是当年最流行的排版引擎之一,仅次于Trident | | `Webkit` | Safari | 苹果浏览器内核,它的特点在于源码结构清晰、渲染速度极快。缺点是对网页代码的兼容性不高 | | `Chromium` | Chrome(前期) | fork自苹果的Webkit内核,谷歌前期使用,后期谷歌联手Opera自研和发布了Blink引擎 | | `Blink` | Chrome/Opera | Blink内核诞生于2013年4月。Blink其实是基于WebKit的 | | `Presto` | Opera前内核,已废弃 | 2013年被Blink取代 | 参考链接:https://www.zguangju.com/Other/browserKernel.html ## 5、认识 HTML 通常我们看到的网页,都是以 `.htm` 或 `.html` 后缀结尾的文件,因此将其俗称为 HTML 文件。 HTML 指的是`超文本标记语言`,它是用来描述网页的一种语言。 所谓超文本,有 2 层含义: 1. 它可以加入图片、声音、动画、多媒体等内容(超越了文本限制 )。 2. 它还可以从一个文件跳转到另一个文件,与世界各地主机的文件连接(超级链接文本 )。 ## 6、HTML 结构标准 HTML 基本结构如下: ```html <!doctype html> 声明文档类型 <html> 根标签 <head> 头标签 <title></title> 标题标签 </head> <body> 主体标签 </body> </html> ``` - `<!DOCTYPE html>` 是告诉浏览器,以下文件用 HTML 哪个版本解析,这里是 HTML5 版本。 - `<html></html>` 标签是一个网页的根标签,所有的标签都要写在这一对根标签里面。 - `<head></head>` 是头标签,主要是定义文档(网页)的头部,包括完档的属性和信息,文档的标题,还可以引入 JavaScript 脚本,CSS 格式等。 - `<body></body>` 是一个文档的主题,里面包含文档的所有内容,比如文本,超链接,图片,表格等内容。 ## 7、html 标签分类 HTML标签从数量上分为`单标签`和`双标签`。 单标签: ` <! Doctype html>` 双标签: `<html> </html> ,<head></head>, <title></title>` ## 8、html 标签关系分类 包含(嵌套关系):` <head><title></title></head>` 父子关系 并列关系: `<head></head> <body></body>` 兄弟姐妹 ## 9、开发工具 前期学习一种语言的时候,开发工具很重要。Web开发工具有很多。最简单的一个开发工具就是 Windows 系统自带的记事本了,但是又难用又难看,没有语法高亮、代码补全等功能。 那么我推荐大家使用的是「[Visual Studio Code](https://code.visualstudio.com/)」 ,VScode 是一款轻量级的编辑器,安装包小,启动速度快,而且功能非常强大,以及成为前端不可缺少的编码利器。 提到 Web 开发工具不得不提到 JebBrain 全家桶的「 [Webstorm](http://www.jetbrains.com/webstorm/) 」软件。目前已经被广大 Web 开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。它令人称到的是它智能打代码补全、代码一键格式化、HTML 提示、联想查询、代码重构等强大功能。 建议初学者初期使用VSCode等文本编辑器,太过于智能的编辑器确实会带给我们极大地便利,但是在带给我们便利的同时,也会削弱我们对基础知识的掌握,只有自己一个单词一个单词敲出来的代码,才会让我们记得更加牢固。
Daotin/Web/01-HTML/01-HTML基础/01-认识前端.md/0
{ "file_path": "Daotin/Web/01-HTML/01-HTML基础/01-认识前端.md", "repo_id": "Daotin", "token_count": 4401 }
10
## 一、渐变 渐变是CSS3当中比较丰富多彩的一个特性,通过渐变我们可以实现许多炫丽的效果,有效的减少图片的使用数量,并且具有很强的适应性和可扩展性。可分为**线性渐变**、**径向渐变**。 ### 1、线性渐变 线性渐变:**指沿着某条直线朝一个方向产生渐变效果。** **语法:** ```css background: linear-gradient(direction, color1, color2 [stop], color3...); ``` **参数说明**: - `direction`:表示线性渐变的方向, - `to left`:设置渐变为从右到左。相当于: 270deg; - `to right`:设置渐变从左到右。相当于: 90deg; - `to top`:设置渐变从下到上。相当于: 0deg; - `to bottom`:设置渐变从上到下。相当于: 180deg。这是默认值。 - `45deg` : 45度方向渐变。 - `color1`:起点颜色。 - `color2`:过渡颜色,指定过渡颜色的位置 stop. - `color3`:结束颜色。你还可以在后面添加更多的过渡颜色和位置,表示多种颜色的渐变。 **示例:** ```css background: linear-gradient(to right, blue, green 20%, yellow 50%, purple 80%, red); ``` ![](./images/2.1.png) ### 2、径向渐变 径向渐变:**指从一个中心点开始沿着四周产生渐变效果。** **语法:** ```css background: radial-gradient(shape size at position, start-color, ..., color [stop] ..., last-color); ``` **参数说明:** - `shape`:渐变的形状。 - `ellipse`表示椭圆形, - `circle`表示圆形。默认为**ellipse**, **如果元素宽高相同为正方形,则ellipse和circle显示一样;** 如果元素宽高不相同,默认效果为 ellipse。** - size:渐变的大小,即渐变到哪里停止,它有四个值。 - `closest-side`:最近边; - `farthest-side`:最远边; - `closest-corner`:最近角; - `farthest-corner`:最远角。默认是**最远角**。 - `at position`:渐变的中心位置。比如: - `at top left`: 中心为元素左上角位置 - `at center center`:中心为元素中心位置 - `at 5px 10px`: 中心为偏移元素左上角位置右边5px, 下边10px位置。 - `start-color` :起始颜色 - `color` :渐变颜色,可选起始位置 stop。 - `last-color`: 结束颜色。 > 注意:各个参数之间用**空格隔开**,而不是逗号隔开。 **示例:** ```css background: radial-gradient(circle farthest-side at right top, red, yellow 50%, blue); ``` ![](./images/2.2.png) ### 3、重复渐变 **语法:** ```css repeating-linear-gradient /*线性重复渐变*/ repeating-radial-gradient /*径向重复渐变*/ ``` 重复的话,就需要**有一个重合的百分百**作为分界线。然后自动按照比例重复渐变。 **示例:** ```html <style> div:first-of-type { width: 200px; height: 200px; margin: 100px auto; /* border: 1px solid blue; */ background: repeating-radial-gradient(circle closest-side at center center, blue 0%, yellow 10%, blue 20%, red 20%, yellow 30%, red 40%); } div:last-of-type { width: 800px; height: 10px; margin: 100px auto; /* border: 1px solid blue; */ background: repeating-linear-gradient(45deg, yellow 0%, blue 5%, red 10%, red 10%, blue 15%, yellow 20%); } </style> </head> <body> <div></div> <div></div> </body> ``` ![2](./images/2.png) ## 二、background 属性 ### 1、复习background属性 ```css /*添加背景颜色*/ background-color: #fff; /*添加背景图片*/ background-image: url("./images/img.jpg"); /*设置背景平铺*/ background-repeat:repeat(默认) | no-repeat | repeat-x | repeat-y | round | space /*新增两个值: round:会将图片进行缩放之后再平铺。保证图片完整紧凑排列。 space:图片不会缩放平铺,只是会在图片之间产生相同的间距值。 */ /*背景定位*/ background-position:left | right | center(默认) | top | bottom /*背景是否滚动*/ background-attachment:scroll(默认) | fixed /* 说明: scroll: 背景图的位置是基于盒子(假如是div)的范围进行显示; fixed:背景图的位置是基于整个浏览器body的范围进行显示,如果背景图定义在div里面,而显示的位置在浏览器范围内但是不在div的范围内的话,背景图无法显示。 */ ``` > **local与scroll的区别**:当滚动的是当前盒子(div)里面的内容的时候, > > `local`:背景图片会跟随内容一起滚动; > > `scroll`:背景图片不会跟随内容一起滚动。 ### 2、新增的background属性 #### 2.1、background-size CSS里的 `background-size` 属性能够让程序员决定如何在指定的元素里展示,它通过各种不同是属性值改变背景尺寸呈现的大小。往往建议不要将图放大,如果有需要,尽量让图缩小,以保证图片的精度。 ```css /*设置背景图片的大小:宽度/高度 宽度/auto(保持比例自动缩放)*/ background-size: 100px 50px; background-size: 100px; /*设置百分比,是参照父容器可放置内容区域的百分比*/ background-size: 50% 50%; /*设置contain:按比例调整图片大小,使用图片宽高自适应整个元素的背景区域,使图片全部包含在容器内 1.图片大于容器:有可能造成容器的空白区域,将图片缩小 2.图片小于容器:有可能造成容器的空白区域,将图片放大*/ *background-size: contain; /*cover:与contain刚好相反,背景图片会按比例缩放自适应填充整个背景区域,如果背景区域不足以包含所有背景图片,图片内容会溢出 1.图片大于容器:等比例缩小,会填满整个背景区域,有可能造成图片的某些区域不可见 2.图片小于容器:等比例放大,填满整个背景区域,图片有可能造成某个方向上内容的溢出*/ background-size: cover; ``` #### 2.2、background-origin 作用:**提升用户的响应区域。** 我们在 background-position 定位的时候,都是默认定位原点在元素的左上角来定位的。可不可以调节定位的位置呢? `background-origin`:可以调节定位原点的位置。 **语法:** ```css background-origin: padding-box|border-box|content-box; ``` - `border-box`:从border的左上角位置开始填充背景,会与border重叠; - `padding-box`:从padding的左上角位置开始填充背景,会与padding重叠; - `content-box`:从内容左上角的位置开始填充背景。 ![3](./images/3.png) 当设置 `background-origin:content-box;` 时,可以将要显示的图片放在盒子中间,如果这时图片是个精灵图的话,旁边会有其他的图干扰,怎么办呢,能不能只显示我需要的精灵图?看下面的 background-clip. #### 2.3、background-clip `background-clip`:属性**规定背景的绘制区域.** 虽然是设置裁切,但是控制的是显示。说白了,就是设置最终显示那些区域。 **语法:** ```css background-clip: border-box|padding-box|content-box; ``` - `border-box`:只显示border及以内的内容 - `padding-box`:只显示padding及以内的内容 - `content-box`:只显示content及以内的内容 所以,回到 2.2 节最后的问题,这时我们再设置 `background-clip:content-box;` 就可以屏蔽其他不要的精灵图了。 **那么为什么要这么做呢?干嘛把 a 标签做的这么大,跟需要的精灵图一样大不好吗?** 还记得手机通讯录右侧的A-Z的列表吗?容易点吗?是不是很容易点错? 我这样做的目的就是**提升用户点击的范围**,但是显示的内容还是以前的,这样可以提高用户的使用体验啊。 #### 2.4、案例:精灵图的使用 需求:为一个块元素设置精灵图背景,精灵图很小,但是需要更大的展示区域,能够以更大的范围响应用户的需要,但是只需要显示指定的背景图片。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> /*提升移动端响应区域的大小*/ a { display: block; width: 50px; height: 50px; background: url("./images/sprites.png") -22px 0; background-repeat: no-repeat; padding: 15px; box-sizing: border-box; background-origin: content-box; background-clip: content-box; } </style> </head> <body> <a href="#"></a> </body> </html> ``` ![4](./images/4.png) 由图可见,返回箭头下 a 的范围变大了,那么用户点击的响应区域也就大了。 ## 三、透明度 css3新增透明度属性:`opacity` ```css opacity:0; /*全透明*/ opacity:1; /*不透明*/ ``` 为了兼容IE8及以下的浏览器,可以使用 filter 属性(谷歌浏览器不识别,仅IE浏览器识别): ```css filter: alpha(opacity=0); 等价于 opacity: 0; filter: alpha(opacity=100); 等价于 opacity: 1; ```
Daotin/Web/02-CSS/02-CSS3/03-渐变,background属性.md/0
{ "file_path": "Daotin/Web/02-CSS/02-CSS3/03-渐变,background属性.md", "repo_id": "Daotin", "token_count": 5779 }
11
@charset "UTF-8"; /*css 初始化 */ html, body, ul, li, ol, dl, dd, dt, p, h1, h2, h3, h4, h5, h6, form, fieldset, legend, img { margin: 0; padding: 0; } fieldset, img, input, button { /*fieldset组合表单中的相关元素*/ border: none; padding: 0; margin: 0; outline-style: none; /*去除蓝色边框*/ } ul, ol { list-style: none; /*清除列表风格*/ } input { padding-top: 0; padding-bottom: 0; font-family: "SimSun", "宋体"; } select, input { vertical-align: middle; /*图片文字垂直居中*/ } select, input, textarea { font-size: 12px; margin: 0; } textarea { resize: none; /*不能改变多行文本框的大小*/ } img { border: 0; vertical-align: middle; /* 去掉图片低测默认的3像素空白缝隙*/ } table { border-collapse: collapse; /*合并外边线*/ } body { font: 12px/150% Arial, Verdana, "\5b8b\4f53"; /*宋体,Unicode,统一码*/ color: #666; background: #fff } .clearfix:before, .clearfix:after { content: ""; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; /*IE/7/6*/ } a { color: #666; text-decoration: none; } a:hover { color: #C81623; } h1, h2, h3, h4, h5, h6 { text-decoration: none; font-weight: normal; font-size: 100%; } s, i, em { font-style: normal; text-decoration: none; } .col-red { color: #C81623 !important; } /*公共类*/ .w { /*版心 提取 */ width: 1210px; margin: 0 auto; } .fl { float: left } .fr { float: right } .al { text-align: left } .ac { text-align: center } .ar { text-align: right } .hide { display: none } /*site-nav部分start*/ .site-nav { background: #f1f1f1; height: 30px; } .site-nav-send, .site-nav .later { position: relative; line-height: 30px; padding-left: 10px; padding-right: 25px; } .site-nav .fl:hover { background: #fff; } .site-nav-send i, .later i { position: absolute; top: 15px; right: 5px; width: 15px; height: 6px; font: 13px/15px "Consolas"; overflow: hidden; /*background: #b6121e;*/ } .site-nav-send s, .later s { position: absolute; top: -7px; } .site-nav .line { width: 1px; background: #DDD; height: 12px; margin-top: 9px; padding: 0; } .site-nav li { float: left; line-height: 30px; padding: 0 7px; } .site-nav .tel { padding-left: 25px; } .tel span{ position: absolute; width: 15px; height: 20px; background: url("../images/tel.png") no-repeat; top: 5px; left: 6px; } .site-nav .tel:hover span { background: url("../images/tel.png") 0 -25px no-repeat; } /*site-nav部分end*/ /*-------------------------------------------------------------------------*/ /*top-banner部分start*/ .top-banner { background: #00376D; } .tb { position: relative; } .close-banner { position: absolute; width: 19px; height: 19px; background: url("../images/close-banner.png") no-repeat; top: 5px; right: 5px; } .close-banner:hover { background-position: bottom; } /*top-banner部分end*/ /*----------------------------------------------------------------------------------------*/ /*title-nav部分start*/ .logo { float: left; width: 362px; height: 60px; padding: 20px 0; } .search { padding-top: 25px; } .search input { float: left; width: 456px; height: 32px; border: 2px solid #B61D1D; font: 16px/36px "Microsoft YaHei"; color: #666; } .search button { float: left; width: 82px; height: 36px; background-color: #B61D1D; color: #fff; font: 16px/36px "Microsoft YaHei"; cursor: pointer; } .index { float: left; width: 530px; height: 28px; line-height: 28px; } .index a { margin-right: 8px; } .shop-car { float: right; border: 1px solid #DFDFDF; width: 141px; height: 34px; line-height: 36px; position: relative; margin-right: 65px; } .icon1 { position: absolute; left:18px; top: 9px; width: 18px; height: 16px; background: url("../images/tel.png") no-repeat 0 -57px; } .icon2 { position: absolute; right: 12px; top: 0; font: 13px/36px "SimSun"; } .icon3 { position: absolute; right: 22px; top: -6px; width: 16px; height: 14px; line-height: 14px; text-align: center; background-color: #C81623; color: #fff; border-radius: 7px 7px 7px 0; } .shop-car a { padding-left: 43px; } /*title-nav部分end*/ /*----------------------------------------------------*/ /*shortcut-nav部分start*/ .shortcut-nav { height: 44px; width: 100%; border-bottom: 2px solid #B1191A; } .shortcut-nav-menu { float: left; width: 210px; height: 44px; background-color: #B1191A; position: relative; z-index: 1; } .shortcut-nav-menu-all a { display: inline-block; width: 210px; height: 44px; font: 400 15px/44px "Microsoft YaHei"; padding-left: 10px; color: #fff; } .shortcut-nav-menu-one { width: 208px; height: 466px; border-left: 2px solid #B61D1D; /*border-bottom: 2px solid #B61D1D;*/ background-color: #C81623; margin-top: 2px; } .shortcut-nav-menu-one div { height: 31px; font: 400 12px/31px "Microsoft YaHei"; padding: 0 10px; } .shortcut-nav-menu-one div:hover { background-color: #fff; } .shortcut-nav-menu-one div:hover a { color: #C81623; } .shortcut-nav-menu-one h3 { float: left; } .shortcut-nav-menu-one a { color: #fff; } .shortcut-nav-menu-one i { float: right; font: 400 9px/31px Consolas; color: #fff; } .shortcut-nav-items { float: left; width: 730px; height: 44px; } .shortcut-nav-items a { display: inline-block; float: left; height: 44px; line-height: 44px; padding: 0 20px; font: 400 16px/44px "Microsoft YaHei"; color: #333; } .shortcut-nav-items a:hover { color: #C81623; } .shortcut-nav-pic { width: 200px; height: 44px; float: right; margin-top: -10px; margin-right: 50px; } /*shortcut-nav部分end*/ /*------------------------------------------------------------------------*/ /*footer部分start*/ .footer { position: relative; } .footer-top-slogan { height: 54px; background-color: #F5F5F5; padding: 20px 0; position: relative; } .footer-top-slogan-icon { position: absolute; left: 50%; } .footer-top-slogan-icon1 { margin-left: -600px; } .footer-top-slogan-icon2 { margin-left: -300px; } .footer-top-slogan-icon4 { margin-left: 300px; } .footer-top-shop { padding-top: 15px; } .footer-top-shop dl { float: left; width: 199px; } .footer-top-shop .last-dl { width: 100px; } .footer-top-shop dt, .map h3{ /*padding: 10px 0;*/ height: 34px; font: 16px/34px "Microsoft YaHei"; } .footer-top-shop dd { line-height: 20px; } .map { float: right; margin-right: 66px; width: 203px; height: 171px; background: url("../images/china.png") no-repeat left bottom; padding-left: 18px; } .map p { margin: 12px 0 6px 0; } .map a { float: right; } .footer-bottom { border-top: 1px solid #E5E5E5; margin-top: 20px; text-align: center; padding: 20px 0 30px; } .footer-bottom-links a { margin: 0 10px; } .footer-bottom-copyright { padding: 10px 0; } .footer-bottom-pic a { margin: 0 5px; } /*footer部分end*/
Daotin/Web/02-CSS/03-案例/01-仿JD静态首页/css/base.css/0
{ "file_path": "Daotin/Web/02-CSS/03-案例/01-仿JD静态首页/css/base.css", "repo_id": "Daotin", "token_count": 4640 }
12
## 1、数组定义 **通过字面量定义数组**: ```js var arr = [10,20,30]; ``` **通过构造函数定义数组**: ```js var arr = new Array(参数); // 参数位置为一个数值时为数组长度,多个数值时为数组中的元素。 // 如果没有参数的时候 Array后面的括号可以省略。 ``` ## 2、数组操作 1. 数组长度: `数组名.length; ` > **问:数组中存储的数据类型一定是一样的吗?** > > 类型可以不一样。 > > **问:数组的长度是不是可以改变呢?** > > 可以改变。 > ## 3、数组高级API ### 3.1、判断数组和转换数组 ```javascript instanceof // 是一个关键字,判断A是否是B类型:A instanceof B。 isArray() //HTML5中新增 ,判断是不是数组 toString() //把数组转换成字符串,每一项用,分割 valueOf() //返回数组对象本身 join(变量) //根据每个字符把数组元素连起来变成字符串,变量可以有可以没有。不写变量默认用逗号分隔,无缝连接用空字符串。 ``` #### instanceof ```javascript var str1 = new String("abc"); var str2 = "abc"; console.log(str1 instanceof String); // true console.log(str2 instanceof String); // false str2不是String对象 ``` #### join ```javascript //join是把数组元素用特殊方式链接成字符串(参数决定用什么链接,无参默认用逗号链接) var arr = ["关羽","张飞","刘备"]; var str1 = arr.join(); var str2 = arr.join(" ");//如果用空格的话,那么元素之间会有一个空格 var str3 = arr.join("");//用空字符串,链接元素,无缝连接 var str4 = arr.join("&"); console.log(str1); // 关羽,张飞,刘备 console.log(str2); // 关羽 张飞 刘备 console.log(str3); // 关羽张飞刘备 console.log(str4); // 关羽 & 张飞 & 刘备 ``` #### arguements 只在函数中使用,代表传入实参的数组。 **arguements 是伪数组:不能修改长短的数组。(可以修改元素,但是不能变长变短)** ```javascript fn(1,2); fn(1,2,3); fn(1,2,3,4,5); function fn(a,b){ //只在函数中使用,实参的数组。 arguments[0] = 0; // 可以修改内容 console.log(arguments); //伪数组:不能修改长短的数组。(可以修改元素,但是不能变长变短) arguments.push(1); // 报错:arguments是伪数组没有push方法,可以用来辨别真伪数组。 console.log(arguments instanceof Array); // false //形参个数 console.log(fn.length); //实参个数 console.log(arguments.length); // 形参和实参个数可以不同,因为实参传入的时候可以形参的个数不一样。 // arguments.callee相当于函数名,这里打印整个函数。 console.log(arguments.callee); } ``` ### 3.2、数组增删和换位置(原数组将被修改) #### push 向数组的**末尾添加一个或更多**元素,并返回**数组的长度**。 **注意:** 新元素将添加在数组的末尾。 **注意:** 此方法改变数组的长度。 > 在数组起始位置添加元素请使用 [unshift()](http://www.runoob.com/jsref/jsref-unshift.html) 方法。 #### pop 删除数组的**最后一个元素**并返回**删除的元素**。 **注意:**此方法改变数组的长度! > 移除数组第一个元素,请使用 [shift()](http://www.runoob.com/jsref/jsref-shift.html) 方法。 ```javascript push() //在数组最后面插入项,返回数组的长度 //数组1改后的长度 = 数组.push(元素1); pop() //取出数组中的最后一项,返回最后一项 //被删除的元素 = 数组.pop(); unshift() //在数组最前面插入项,返回数组的长度 //数组1改后的长度 = 数组.unshift(元素1); shift() //取出数组中的第一个元素,返回第一项 //被删除的元素 = 数组.shift(); ``` #### reverse 翻转数组(原数组讲被反转,返回值也是被反转后的数组) 使用方法:反转后的数组 = 数组.reverse(); #### sort 给数组排序(只能通过第一位字母或数字的 unicode 编码进行排列),返回排序后的数组。 ```javascript var arr2 = [7,6,15,4,13,2,1]; console.log(arr2); // 7,6,15,4,13,2,1 console.log(arr2.sort()); // 1,13,15,2,4,6,7 ``` **解决:sort方法不稳定,设计的时候就是这么设计的,可以通过回调函数进行规则设置。** ```javascript console.log(arr2); console.log(arr2.sort(function (a,b) { return a-b; //a-b,从小到大排序,如果是b-a则从大到小排序 })); ``` ## 4、迭代方法 作用:代替 for 循环。 ### forEach(遍历用) 特点:无返回值,纯遍历数组中的元素。 > 注意:不能使用element直接修改数组的元素,可以使用arr[index]来修改。 ```javascript var arr = ["关长","张飞","赵子龙","马超","黄忠"]; var str = ""; // function (element,index,array) // element:数组元素的值 // index:索引 // array:调用这个方法的整个数组对象(一般不用) arr.forEach(function (ele,index,array) { str+=ele; }); console.log(str); // 关长张飞赵子龙马超黄忠 ``` > 注意: > > 只写一个参数就是 element; > > 写两个参数就是 element 和 index > > 写三个参数就是: element 和 index 和 array本身。 ### map(遍历用) map有返回值,返回什么都添加到新数组中。 > 注意:map可以直接使用ele修改数组里面的值。这是与forEach的区别, > > 还有一个区别是map有返回值,而forEach没有。 特点:遍历数组使用。 ```javascript var arr = ["关长","张飞","赵子龙","马超","黄忠"]; var arr2 = arr.map(function (ele,index,array) { return ele+"你好"; }) console.log(arr2); // (5) ["关长你好", "张飞你好", "赵子龙你好", "马超你好", "黄忠你好"] ``` ### every 返回值是一个 boolean 类型值。而参数是一个回调函数。 参数有三个。名字随便起,但是表示的意思还是这样顺序的。 特点:只要有一个不满足条件,就返回false。 ```javascript var arr = ["青花瓷", "一路向北", "轨迹"]; var flag = arr.every(function (ele, index) { // 只要有一个没满足条件,就返回false return ele.length > 2; }); console.log(flag); // false ``` ### some 特点:如果函数结果有一个是true,那么some方法结果也是true。 ```javascript var arr = ["关长","张飞","赵子龙","马超","黄忠"]; var flag = arr.some(function (ele,index,array) { if(ele.length>2){ return true; } return false; }) console.log(flag); // true ``` ### filter filter 返回值是一个新数组。 特点:返回一个返回值为 true 的新数组。 ```javascript var arr = ["关长","张飞","赵子龙","马超","黄忠"]; var arr1 = arr.filter(function (ele,index,array) { return ele.length > 2; }); console.log(arr1); // ["赵子龙"] ``` ### reduce reduce()方法对累计器和数组中的每个元素(从左到右)应用一个函数,将其简化为单个值。 特点:按照某种规律遍历数组。 ```js var arr = [1,2,3,4,5]; var arr2 = arr.reduce(function(a,b){ return a-b; // 1-2-3-4-5 = -13 }); ``` ### reduceRight 特点:从右开始执行某种规律。 ```js var arr = [1,2,3,4,5]; var arr2 = arr.reduce(function(a,b){ return a-b; // 5-4-3-2-1 = -5 }); ``` ## 5、了解方法 ### concat() 把参数数组拼接到当前数组。 举个🌰:`新数组 = 数组1.concat(数组2);` ### slice() 从当前数组中截取一个新的数组,**不影响原来的数组**,参数start从0开始,end从1开始。 举个🌰:`新数组 = 数组1.slice(startIndex,endIndex);` ### indexOf()、lastIndexOf() 查找数组中有没有某个元素,找到了返回这个元素在数组中的索引,如果没找到返回-1。 举个🌰:`索引值 = 数组.indexOf/lastIndexOf(数组中的元素);` ### delete 删除数组中的某个值。 特点:只删除值,不删除位置,删除后原位置的值为 undefined。 ### splice() --- 增删改 增加,删除或替换当前数组的某些元素。**影响原来的元素**。 举个🌰:`新数组 = 数组1.splice(起始索引,删除个数 [,替换内容,替换内容,...]);` ```js var arr = [1, 2, 3, 4, 5]; // 增 arr.splice(1, 0, 'a', 'b', 'c'); // 1,a,b,c,2,3,4,5 // 删 arr.splice(1, 2); // 1,4,5 //改 arr.splice(1, 3, 'a', 'b', 'c'); // 1,a,b,c,5 ``` ## 6、清空数组 ```javascript var array = [1,2,3,4,5,6]; // 方法一:删除数组中所有项目(替换的内容为空) array.splice(0,array.length); // 方法二:length属性可以赋值,其它语言中length是只读 array.length = 0; // 方法三: array = []; //推荐 ``` ## 7、区分伪数组和真数组 ```js // 真数组 var arr = [10,20,30]; // 伪数组 var obj = { 0:10, 1:20, 2:30, length: 3 }; // 真数组的访问 for(var i=0; i<arr.length; i++) { console.log("真数组的访问:"+arr[i]); } // 伪数组的访问 for(var j=0; j<obj.length; j++) { // 错误:对象中没有length方法 console.log("伪数组的访问:"+obj[j]); } ``` > 方法1、使用 length 来区分 > > 这样看起来,真数组和伪数组就没法区别了。 > > 但是真数组的长度 length 可以改变,伪数组不可以,貌似可以区分了。 > > 但是,你还记得有个 `arguement` 这个伪数组(对象)的 length 是可以改变的,方法一区分失败。 > > 其实 `childNodes` 也是伪数组。 > > > > 方法2、使用`数组的方法`来鉴别 > > 因为每个数组都是 Array 的实例对象,而 forEach 等在 Array 的原型对象中,所以其他的伪数组是不能使用的。方法二成功。 > > > > 方法3、`Array.isArray(数组);` // 真数组返回 true,伪数组返回 false。 > > 方法4、 > > `伪数组 instanceof Array === false;` > > `真数组 instanceof Array === true;` > > 方法5、 > > `Object.prototype.toString.call(伪数组) === "[object Object]";` > > `Object.prototype.toString.call(真数组) === "[object Array]"`
Daotin/Web/03-JavaScript/01-JavaScript基础知识/05-数组.md/0
{ "file_path": "Daotin/Web/03-JavaScript/01-JavaScript基础知识/05-数组.md", "repo_id": "Daotin", "token_count": 6243 }
13
## 1、BOM的概念 BOM(Browser Object Model):浏览器对象模型。 在浏览器中的一些操作都可以使用 BOM 的方法进行编程处理。 比如:刷新浏览器、前进、后退、在地址栏输入 URL 等。 ## 2、BOM 顶级对象 BOM 的顶级对象是:`window` window 是浏览器的顶级对象,当调用 window 下的属性和方法时,可以省略 window。 > 注意: > > 1、window 下的一个特殊属性:window.name,所以不要轻易定义 name 变量,会导致 window.name 被修改。 > > 2、top 等同于 window。 ## 3、系统对话框 ```javascript window.alert(); window.prompt(); window.confirm(); // 两个按钮,分别返回 true 和 false。 ``` > 以上对话框都不建议使用。 > > 1、弹框时页面无法加载; > > 2、各个浏览器的样式不相同,且样式不可自定义。 ## 4、window对象方法 ### 4.1、open **描述:**打开一个新的浏览器窗口或查找一个已命名的窗口。 **语法:**`var openId = window.open(新窗口地址,"窗口名",窗口属性);` **示例:**`var openId = window.open("sub.html","窗口名","Width=300px, height=250px, left=100px, top=100px");` > width: 新窗口的宽 > > height:新窗口的高 > > left:新窗口距离屏幕左边的距离 > > top:新窗口距离屏幕顶部的距离 **注意:**如果两次弹出窗口名一样,将不会打开新弹窗,而再之前的弹窗中加载新页面。 **关闭窗口:** ```js openId.close(); //关闭id为openId的窗口 close(); // 关闭当前窗口 ``` ## 5、页面加载对象 **提出问题:** 我们知道,如果将 script 标签放在 head 里面的话,页面加载的时候是先加载的 script 标签,之后才加载 body 里面的标签。如果 script 特别大的话,就很影响用户体验。 **解决办法:** 1、将 script 标签放在 body 最后。 2、使用 `window.onload` 事件。 ```html <head> <meta charset="UTF-8"> <title>Title</title> <script> window.onload = function () { document.getElementById("btn").onclick = function () { alert("haha"); } } </script> </head> <body> <input type="button" value="BUTTON" id="btn"> </body> ``` > 1、如果不写 window.onload 的话,执行到 document.getElementById("btn") 会报错,因为程序是从上至下执行。 > > 2、window.onload 事件会在页面加载完毕(**页面中所有内容、标签、属性以及外部引入的 js文件**)时触发。 > > 3、window.onload 可以省略 window。 ```javascript window.onunload = function () { alert("yes"); } ``` > `onunload`: 页面关闭后才触发的事件 ```javascript window.onbeforeunload = function () { alert("yes"); } ``` > `onbeforeunload`:在页面关闭之前触发的事件 > > `onscroll` :当滚轮滚动时触发。 > > `onresize` :当窗口大小改变时触发。 ## 6、location 对象(地址栏) 学习一个对象主要是学习它里面的属性和方法。 ### 6.1、属性 ```javascript console.log(window.location.href); // 地址域名 console.log(window.location.search);//?_ijt=28855sggj8kcffva8q9bhc1eh0 --- 搜索的内容 console.log(window.location.hash); // 地址栏上#及后面的内容 console.log(window.location.host); // localhost:63342 ---- 主机名及端口号 console.log(window.location.hostname); // localhost ---- 主机名 console.log(window.location.port); //63342 ---- 端口号 console.log(window.location.pathname);// /JS/images/location.html --- 相对路径 console.log(window.location.protocol);// http: --- 协议 ``` ### 6.2、方法 ```javascript document.getElementById("btn").onclick = function () { location.href = "http://fengdaoting.com"; location.assign("http://fengdaoting.com"); location.reload(); location.replace("http://fengdaoting.com"); }; ``` > `location.href` 和 ` location.assign()`: 设置跳转的页面地址,这两个属性和方法作用相同,并且都保存跳转前的地址(在浏览器中可以点击返回按钮)。 > > `location.reload() `: 刷新页面。刷新页面也可以使用:把href =自己本身的地址 > > `location.replace() `: 设置跳转的页面地址,但是不保存跳转前的地址。 ## 7、history 对象 ```js window.history.length // 返回浏览器历史列表中的 URL 数量 window.history.forward(); // 前进,加载 history 列表中的下一个 URL window.history.back() // 后退,加载 history 列表中的前一个 URL window.history.go(number); //加载 history 列表中的某个具体页面,或者要求浏览器移动到指定的页面数量(负数为后退number页,正数为前进number页) ``` `<a href="javascript:window.history.reload()"></a>` a 标签可以使用 javascript的方式来编写js代码。 ## 8、navigator 对象 ```js window.navigator.platform; // 判断浏览器所在的系统平台 // win32 window.navigator.appName // 浏览器名称 // Netscape window.navigator.appVersion // 浏览器版本 //5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36 window.navigator.userAgent; // 判断浏览器的类型,是谷歌火狐还是IE // chrome 下结果:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36 ``` ## 9、screen 对象 screen 对象包含有关客户端显示屏幕的信息。 很少使用,用的话只在移动端使用,在PC端固定不变,获取的是设备的宽高,而不是页面的宽高。 ```js screen.availHeight // 返回可用显示屏幕的高度 (除 Windows 任务栏之外)。 screen.availWidth//返回可用显示屏幕的宽度 (除 Windows 任务栏之外)。 screen.height //返回显示器屏幕的高度。 screen.width //返回显示器屏幕的宽度。 ``` ## 10、document 属性: ```js document.all //提供对文档中所有 HTML 元素的访问。是数组类型 document.forms // 返回对文档中所有 Form 对象引用。是数组类型 document.URL //返回当前文档的 URL。 document.bgColor //可以改变文档的颜色;( document.bgColor="gray";) document.documentElement // html元素 document.body // body元素 ``` 方法: ```js document.getElementById() //返回对拥有指定 id 的第一个对象的引用。 document.getElementsByName()// 返回带有指定名称的对象集合。 document.getElementsByTagName() //返回带有指定标签名的对象集合。 document.write() //向文档写 HTML 表达式 或 JavaScript 代码。 ``` ## 11、iframe 引入外部链接,一般用于展示,可以一个页面放多个外部链接页面。如果操作页面的话,还是会跳转到外部链接网站。 ```html <iframe src="http://www.360.com" width="400px" height="400px"></iframe> ```
Daotin/Web/03-JavaScript/03-BOM/01-BOM的概念,一些BOM对象.md/0
{ "file_path": "Daotin/Web/03-JavaScript/03-BOM/01-BOM的概念,一些BOM对象.md", "repo_id": "Daotin", "token_count": 3927 }
14
// 获取任一元素(只能是单个元素) // 示例:$("#dv .uu span") function $(str, parent) { parent = parent || document; if (str.indexOf(" ") != -1) { // str中有空格 var strList = str.split(" "); // [ul,#dv] for (var i = 0; i < strList.length; i++) { if (i == strList.length - 1) { return $(strList[i], parent); } if (strList[i].indexOf("#") == 0) { parent = $(strList[i], parent); } else { parent = $(strList[i], parent)[0]; } } return tmpObj; } else { switch (str.charAt(0)) { case "#": return parent.getElementById(str.substring(1)); break; case ".": return parent.getElementsByClassName(str.substring(1))[0]; break; default: return parent.getElementsByTagName(str)[0]; break; } } } // 从array中取length个不重复随机数,返回组成的字符串 function getSecurityCode(array, length) { var index = []; var tmp = 0; while (1) { tmp = Math.floor(Math.random() * array.length); if (!checkNumIfRepeat(index, array[tmp])) { // 下标存在 index[index.length] = array[tmp]; } if (index.length == length) { break; } } return index.join(""); } function checkNumIfRepeat(list, num) { for (var i = 0; i < list.length; i++) { if (list[i] == num) { return true; } } return false; } // 获取当前月的天数 function getCurrentDays(date) { var tmp = new Date(date); tmp.setDate(1); tmp.setMonth(date.getMonth() + 1); // date.getMonth() 是比当前月上一天的,但是设置的时候会自动多加一天,抵消了 tmp.setDate(0); return tmp.getDate(); } // 获取上个月的天数 function getPrevMonthDays(date) { var tmp = new Date(date); // tmp.setMonth(date.getMonth()); tmp.setDate(0); return tmp.getDate(); } // 根据日期获取当月的第一天是星期几 function getWeekByFirstDay(date) { var tmp = new Date(date); // tmp.setMonth(date.getMonth()); tmp.setDate(1); return tmp.getDay(); } // 格式化date函数 // 示例:dateFormat(new Date(), "yyyy-mm-dd hh:mm:ss") function dateFormat(date, formatStr) { var year = date.getFullYear(); var month = date.getMonth()+1; month = month < 10 ? "0" + month : month; var day = date.getDate(); day = day < 10 ? "0" + day : day; var hour = date.getHours(); hour = hour < 10 ? "0" + hour : hour; var min = date.getMinutes(); min = min < 10 ? "0" + min : min; var sec = date.getSeconds(); sec = sec < 10 ? "0" + sec : sec; return formatStr.replace("yyyy", year).replace("mm", month).replace("dd", day).replace("hh", hour).replace("mm", min).replace("ss", sec); } // 设置任意标签的文本内容为任意内容 function setInnerText(element, text) { (typeof element.TextContent === "undefined") ? (element.innerText = text) : (element.textContent = text); } // 获取任意标签的文本内容 function getInnerText(element) { return typeof element.TextContent === "undefined" ? element.innerText : element.textContent; } // 为任意元素绑定任意事件 function addEvent(obj, type, fn) { if (obj.addEventListener) { obj.addEventListener(type, fn, false); } else if (obj.attachEvent) { obj.attachEvent("on" + type, fn); } else { obj["on" + type] = fn; } } // 为任意元素解绑任意事件 function removeEvent(obj, type, fnName) { if (obj.removeEventListener) { obj.removeEventListener(type, fnName, false); } else if (obj.detachEvent) { obj.detachEvent("on" + type, fnName); } else { obj["on" + type] = null; } } // 获取页面可视区域宽高 function getAvail() { return { width: document.documentElement.clientWidth || document.body.clientWidth || 0, height: document.documentElement.clientHeight || document.body.clientHeight || 0 }; } // 获取页面实际宽高 function getReal() { return { width: document.documentElement.scrollWidth || document.body.scrollWidth || 0, height: document.documentElement.scrollHeight || document.body.scrollHeight || 0 }; } // 获取浏览器滑动栏向上向左卷曲的距离 function getScroll() { return { left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0, top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0 }; } // 获取任意元素的任意一个属性值 function getStyle(element, attr) { return window.getComputedStyle ? window.getComputedStyle(element, null)[attr] : element.currentStyle[attr]; } // 函数描述:匀速动画函数 // element:要实现动画的元素 // onestep:每次移动的大小 // json:设置的目标属性集合(比如{"left":100,"top":400,"width":400,"height":200}) // fn:动画完成之后的回调函数 function animate_ys(obj, json, step, fn) { clearInterval(obj.timer); step = step || 10; var len = 0; for (let i in json) { len++; } obj.timer = setInterval(function () { var count = 0; for (let attr in json) { var start = parseInt(getStyle(obj, attr)); var target = json[attr]; step = target > start ? Math.abs(step) : -Math.abs(step); obj.style[attr] = parseInt(getStyle(obj, attr)) + step + "px"; if (step > 0) { if (parseInt(getStyle(obj, attr)) >= target) { obj.style[attr] = target + "px"; count++; } } else { if (parseInt(getStyle(obj, attr)) <= target) { obj.style[attr] = target + "px"; count++; } } } if (len == count) { clearInterval(obj.timer); if (fn) fn(); } }, 100); }; // 函数描述:变速动画函数 // element:要实现动画的元素 // json:设置的目标属性集合(比如{"left":100,"top":400,"width":400,"height":200}) // fn:动画完成之后的回调函数 function animation(element, json, fn) { clearInterval(element.timeId); // 每次调用函数就清理之前的timeId // 判断当前的位置 element.timeId = setInterval(function () { var flag = true; for (var attr in json) { // 判断attr是不是层级zIndex if (attr == "zIndex") { element.style[attr] = json[attr]; } else if (attr == "opacity") { // 判断attr是不是透明度opacity // 获取当前透明度*100,方便计算 var current = getStyle(element, attr) * 100; // 目标透明度也*100 var target = json[attr] * 100; var onestep = (target - current) / 10; onestep = onestep > 0 ? Math.ceil(onestep) : Math.floor(onestep); current += onestep; element.style[attr] = current / 100; } else { // 其他属性 var current = parseInt(getStyle(element, attr)); // 获取任意元素的任意一个属性值 var target = json[attr]; var onestep = (target - current) / 10; // 变速 // var onestep = -3; // 匀速 onestep = onestep > 0 ? Math.ceil(onestep) : Math.floor(onestep); current += onestep; element.style[attr] = current + "px"; } // 有一个没到的flag都为false if (target != current) { flag = false; } } if (flag) { clearInterval(element.timeId); if (fn) { fn(); } } // 测试代码 console.log("target=" + target + ", current=" + current + ", step=" + onestep); }, 50); } function animate_bs(obj, json, step, fn) { clearInterval(obj.timer); step = step || 10; var len = 0; for (let attr in json) { len++; } obj.timer = setInterval(function () { var count = 0; for (var attr in json) { var start = parseInt(getStyle(obj, attr)); var target = json[attr]; var step = (target - start) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); obj.style[attr] = parseInt(getStyle(obj, attr)) + step + "px"; if (step == 0) { count++; } } if (len == count) { clearInterval(obj.timer); if (fn) fn(); } }, 100); } // 封装通用事件位置相关对象 // 使用示例: // document.onmousemove=function (e) { // obj.style.left = evt.getPageX(e)+"px"; // obj.style.top = evt.getPageY(e)+"px"; // }; var evt = { // 获取通用事件对象 getEvent: function (e) { return window.event || e; }, // 获取通用 ClientX // 兼容IE浏览器不支持.evt的事件 getClientX: function (e) { return this.getEvent(e).clientX; }, // 获取通用 ClientY getClientY: function (e) { return this.getEvent(e).clientY; }, // 获取通用 scrollLeft getScrollLeft: function () { return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0; }, // 获取通用 scrollTop getScrollTop: function () { return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; }, // 获取通用 pageX getPageX: function (e) { return this.getEvent(e).pageX ? this.getEvent(e).pageX : this.getClientX(e) + this.getScrollLeft(); }, // 获取通用 pageY getPageY: function (e) { return this.getEvent(e).pageY ? this.getEvent(e).pageY : this.getClientY(e) + this.getScrollTop(); } }; // 获取cookie中对应key的value值 // for循环实现的 // function getCookie(key) { // var cookie = document.cookie; // if (cookie) { // var cookieStr = cookie.split("; "); // for (var i = 0; i < cookieStr.length; i++) { // var item = cookieStr[i]; // if (item.split("=")[0] == key) { //key // return item.split("=")[1]; // value // } // } // return ""; // } else { // return ""; // } // }; function getCookie(key, decode) { var cookie = document.cookie; if (decode) { if (cookie) { var cookieStr = cookie.split("; "); var item = cookieStr.filter(function (ele) { return ele.split("=")[0] == encodeURIComponent(key); })[0]; if (item) { return decodeURIComponent(item.split('=')[1]); } else { return ""; } } else { return ""; } } else { if (cookie) { var cookieStr = cookie.split("; "); var item = cookieStr.filter(function (ele) { return ele.split("=")[0] == key; })[0]; if (item) { return item.split('=')[1]; } else { return ""; } } else { return ""; } } }; // cookie的增加,删除,修改 // key 键 // value 值 // days 过期时间 //path 可访问路径 // encode 是否对key和value进行编码 function setCookie(key, value, days, path, encode) { path = path || "/"; // 网站根路径 if (encode) { if (days) { var date = new Date(); date.setDate(date.getDate() + days); document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value) + ";expires=" + date + ";path=" + path; } else { document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value) + ";path=" + path; } } else { if (days) { var date = new Date(); date.setDate(date.getDate() + days); document.cookie = key + "=" + value + ";expires=" + date + ";path=" + path; } else { document.cookie = key + "=" + value + ";path=" + path; } } }; // 封装 getElementByClassName 函数兼容 IE8 // Tips:IE8 不兼容getElementByClassName和 indexOf函数 function daotin_indexOf(str, list) { var index = -1; for (var i = 0; i < list.length; i++) { if (str == list[i]) { return i; } } return index; }; function daotin_getElementByClassName(className) { var allEle = document.getElementsByTagName("*"); var list = []; for (var i = 0; i < allEle.length; i++) { if (allEle[i].className) { var classList = allEle[i].className.split(" "); //["ll", "haha"] // if (classList.indexOf(className) != -1) { if (daotin_indexOf(className, classList) != -1) { list.push(allEle[i]); } } } return list; } // 调用此函数:阻止事件传递(不止是冒泡) function daotin_stopPropagation(e) { var e = window.event || e; e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true; }; // 阻止默认事件 function stopDefault(e) { var e = window.event || e; if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } };
Daotin/Web/03-JavaScript/daotin.js/0
{ "file_path": "Daotin/Web/03-JavaScript/daotin.js", "repo_id": "Daotin", "token_count": 7046 }
15
// Variables // -------------------------- @fa-font-path: "../fonts"; @fa-font-size-base: 14px; @fa-line-height-base: 1; //@fa-font-path: "//netdna.bootstrapcdn.com/font-awesome/4.7.0/fonts"; // for referencing Bootstrap CDN font files directly @fa-css-prefix: fa; @fa-version: "4.7.0"; @fa-border-color: #eee; @fa-inverse: #fff; @fa-li-width: (30em / 14); @fa-var-500px: "\f26e"; @fa-var-address-book: "\f2b9"; @fa-var-address-book-o: "\f2ba"; @fa-var-address-card: "\f2bb"; @fa-var-address-card-o: "\f2bc"; @fa-var-adjust: "\f042"; @fa-var-adn: "\f170"; @fa-var-align-center: "\f037"; @fa-var-align-justify: "\f039"; @fa-var-align-left: "\f036"; @fa-var-align-right: "\f038"; @fa-var-amazon: "\f270"; @fa-var-ambulance: "\f0f9"; @fa-var-american-sign-language-interpreting: "\f2a3"; @fa-var-anchor: "\f13d"; @fa-var-android: "\f17b"; @fa-var-angellist: "\f209"; @fa-var-angle-double-down: "\f103"; @fa-var-angle-double-left: "\f100"; @fa-var-angle-double-right: "\f101"; @fa-var-angle-double-up: "\f102"; @fa-var-angle-down: "\f107"; @fa-var-angle-left: "\f104"; @fa-var-angle-right: "\f105"; @fa-var-angle-up: "\f106"; @fa-var-apple: "\f179"; @fa-var-archive: "\f187"; @fa-var-area-chart: "\f1fe"; @fa-var-arrow-circle-down: "\f0ab"; @fa-var-arrow-circle-left: "\f0a8"; @fa-var-arrow-circle-o-down: "\f01a"; @fa-var-arrow-circle-o-left: "\f190"; @fa-var-arrow-circle-o-right: "\f18e"; @fa-var-arrow-circle-o-up: "\f01b"; @fa-var-arrow-circle-right: "\f0a9"; @fa-var-arrow-circle-up: "\f0aa"; @fa-var-arrow-down: "\f063"; @fa-var-arrow-left: "\f060"; @fa-var-arrow-right: "\f061"; @fa-var-arrow-up: "\f062"; @fa-var-arrows: "\f047"; @fa-var-arrows-alt: "\f0b2"; @fa-var-arrows-h: "\f07e"; @fa-var-arrows-v: "\f07d"; @fa-var-asl-interpreting: "\f2a3"; @fa-var-assistive-listening-systems: "\f2a2"; @fa-var-asterisk: "\f069"; @fa-var-at: "\f1fa"; @fa-var-audio-description: "\f29e"; @fa-var-automobile: "\f1b9"; @fa-var-backward: "\f04a"; @fa-var-balance-scale: "\f24e"; @fa-var-ban: "\f05e"; @fa-var-bandcamp: "\f2d5"; @fa-var-bank: "\f19c"; @fa-var-bar-chart: "\f080"; @fa-var-bar-chart-o: "\f080"; @fa-var-barcode: "\f02a"; @fa-var-bars: "\f0c9"; @fa-var-bath: "\f2cd"; @fa-var-bathtub: "\f2cd"; @fa-var-battery: "\f240"; @fa-var-battery-0: "\f244"; @fa-var-battery-1: "\f243"; @fa-var-battery-2: "\f242"; @fa-var-battery-3: "\f241"; @fa-var-battery-4: "\f240"; @fa-var-battery-empty: "\f244"; @fa-var-battery-full: "\f240"; @fa-var-battery-half: "\f242"; @fa-var-battery-quarter: "\f243"; @fa-var-battery-three-quarters: "\f241"; @fa-var-bed: "\f236"; @fa-var-beer: "\f0fc"; @fa-var-behance: "\f1b4"; @fa-var-behance-square: "\f1b5"; @fa-var-bell: "\f0f3"; @fa-var-bell-o: "\f0a2"; @fa-var-bell-slash: "\f1f6"; @fa-var-bell-slash-o: "\f1f7"; @fa-var-bicycle: "\f206"; @fa-var-binoculars: "\f1e5"; @fa-var-birthday-cake: "\f1fd"; @fa-var-bitbucket: "\f171"; @fa-var-bitbucket-square: "\f172"; @fa-var-bitcoin: "\f15a"; @fa-var-black-tie: "\f27e"; @fa-var-blind: "\f29d"; @fa-var-bluetooth: "\f293"; @fa-var-bluetooth-b: "\f294"; @fa-var-bold: "\f032"; @fa-var-bolt: "\f0e7"; @fa-var-bomb: "\f1e2"; @fa-var-book: "\f02d"; @fa-var-bookmark: "\f02e"; @fa-var-bookmark-o: "\f097"; @fa-var-braille: "\f2a1"; @fa-var-briefcase: "\f0b1"; @fa-var-btc: "\f15a"; @fa-var-bug: "\f188"; @fa-var-building: "\f1ad"; @fa-var-building-o: "\f0f7"; @fa-var-bullhorn: "\f0a1"; @fa-var-bullseye: "\f140"; @fa-var-bus: "\f207"; @fa-var-buysellads: "\f20d"; @fa-var-cab: "\f1ba"; @fa-var-calculator: "\f1ec"; @fa-var-calendar: "\f073"; @fa-var-calendar-check-o: "\f274"; @fa-var-calendar-minus-o: "\f272"; @fa-var-calendar-o: "\f133"; @fa-var-calendar-plus-o: "\f271"; @fa-var-calendar-times-o: "\f273"; @fa-var-camera: "\f030"; @fa-var-camera-retro: "\f083"; @fa-var-car: "\f1b9"; @fa-var-caret-down: "\f0d7"; @fa-var-caret-left: "\f0d9"; @fa-var-caret-right: "\f0da"; @fa-var-caret-square-o-down: "\f150"; @fa-var-caret-square-o-left: "\f191"; @fa-var-caret-square-o-right: "\f152"; @fa-var-caret-square-o-up: "\f151"; @fa-var-caret-up: "\f0d8"; @fa-var-cart-arrow-down: "\f218"; @fa-var-cart-plus: "\f217"; @fa-var-cc: "\f20a"; @fa-var-cc-amex: "\f1f3"; @fa-var-cc-diners-club: "\f24c"; @fa-var-cc-discover: "\f1f2"; @fa-var-cc-jcb: "\f24b"; @fa-var-cc-mastercard: "\f1f1"; @fa-var-cc-paypal: "\f1f4"; @fa-var-cc-stripe: "\f1f5"; @fa-var-cc-visa: "\f1f0"; @fa-var-certificate: "\f0a3"; @fa-var-chain: "\f0c1"; @fa-var-chain-broken: "\f127"; @fa-var-check: "\f00c"; @fa-var-check-circle: "\f058"; @fa-var-check-circle-o: "\f05d"; @fa-var-check-square: "\f14a"; @fa-var-check-square-o: "\f046"; @fa-var-chevron-circle-down: "\f13a"; @fa-var-chevron-circle-left: "\f137"; @fa-var-chevron-circle-right: "\f138"; @fa-var-chevron-circle-up: "\f139"; @fa-var-chevron-down: "\f078"; @fa-var-chevron-left: "\f053"; @fa-var-chevron-right: "\f054"; @fa-var-chevron-up: "\f077"; @fa-var-child: "\f1ae"; @fa-var-chrome: "\f268"; @fa-var-circle: "\f111"; @fa-var-circle-o: "\f10c"; @fa-var-circle-o-notch: "\f1ce"; @fa-var-circle-thin: "\f1db"; @fa-var-clipboard: "\f0ea"; @fa-var-clock-o: "\f017"; @fa-var-clone: "\f24d"; @fa-var-close: "\f00d"; @fa-var-cloud: "\f0c2"; @fa-var-cloud-download: "\f0ed"; @fa-var-cloud-upload: "\f0ee"; @fa-var-cny: "\f157"; @fa-var-code: "\f121"; @fa-var-code-fork: "\f126"; @fa-var-codepen: "\f1cb"; @fa-var-codiepie: "\f284"; @fa-var-coffee: "\f0f4"; @fa-var-cog: "\f013"; @fa-var-cogs: "\f085"; @fa-var-columns: "\f0db"; @fa-var-comment: "\f075"; @fa-var-comment-o: "\f0e5"; @fa-var-commenting: "\f27a"; @fa-var-commenting-o: "\f27b"; @fa-var-comments: "\f086"; @fa-var-comments-o: "\f0e6"; @fa-var-compass: "\f14e"; @fa-var-compress: "\f066"; @fa-var-connectdevelop: "\f20e"; @fa-var-contao: "\f26d"; @fa-var-copy: "\f0c5"; @fa-var-copyright: "\f1f9"; @fa-var-creative-commons: "\f25e"; @fa-var-credit-card: "\f09d"; @fa-var-credit-card-alt: "\f283"; @fa-var-crop: "\f125"; @fa-var-crosshairs: "\f05b"; @fa-var-css3: "\f13c"; @fa-var-cube: "\f1b2"; @fa-var-cubes: "\f1b3"; @fa-var-cut: "\f0c4"; @fa-var-cutlery: "\f0f5"; @fa-var-dashboard: "\f0e4"; @fa-var-dashcube: "\f210"; @fa-var-database: "\f1c0"; @fa-var-deaf: "\f2a4"; @fa-var-deafness: "\f2a4"; @fa-var-dedent: "\f03b"; @fa-var-delicious: "\f1a5"; @fa-var-desktop: "\f108"; @fa-var-deviantart: "\f1bd"; @fa-var-diamond: "\f219"; @fa-var-digg: "\f1a6"; @fa-var-dollar: "\f155"; @fa-var-dot-circle-o: "\f192"; @fa-var-download: "\f019"; @fa-var-dribbble: "\f17d"; @fa-var-drivers-license: "\f2c2"; @fa-var-drivers-license-o: "\f2c3"; @fa-var-dropbox: "\f16b"; @fa-var-drupal: "\f1a9"; @fa-var-edge: "\f282"; @fa-var-edit: "\f044"; @fa-var-eercast: "\f2da"; @fa-var-eject: "\f052"; @fa-var-ellipsis-h: "\f141"; @fa-var-ellipsis-v: "\f142"; @fa-var-empire: "\f1d1"; @fa-var-envelope: "\f0e0"; @fa-var-envelope-o: "\f003"; @fa-var-envelope-open: "\f2b6"; @fa-var-envelope-open-o: "\f2b7"; @fa-var-envelope-square: "\f199"; @fa-var-envira: "\f299"; @fa-var-eraser: "\f12d"; @fa-var-etsy: "\f2d7"; @fa-var-eur: "\f153"; @fa-var-euro: "\f153"; @fa-var-exchange: "\f0ec"; @fa-var-exclamation: "\f12a"; @fa-var-exclamation-circle: "\f06a"; @fa-var-exclamation-triangle: "\f071"; @fa-var-expand: "\f065"; @fa-var-expeditedssl: "\f23e"; @fa-var-external-link: "\f08e"; @fa-var-external-link-square: "\f14c"; @fa-var-eye: "\f06e"; @fa-var-eye-slash: "\f070"; @fa-var-eyedropper: "\f1fb"; @fa-var-fa: "\f2b4"; @fa-var-facebook: "\f09a"; @fa-var-facebook-f: "\f09a"; @fa-var-facebook-official: "\f230"; @fa-var-facebook-square: "\f082"; @fa-var-fast-backward: "\f049"; @fa-var-fast-forward: "\f050"; @fa-var-fax: "\f1ac"; @fa-var-feed: "\f09e"; @fa-var-female: "\f182"; @fa-var-fighter-jet: "\f0fb"; @fa-var-file: "\f15b"; @fa-var-file-archive-o: "\f1c6"; @fa-var-file-audio-o: "\f1c7"; @fa-var-file-code-o: "\f1c9"; @fa-var-file-excel-o: "\f1c3"; @fa-var-file-image-o: "\f1c5"; @fa-var-file-movie-o: "\f1c8"; @fa-var-file-o: "\f016"; @fa-var-file-pdf-o: "\f1c1"; @fa-var-file-photo-o: "\f1c5"; @fa-var-file-picture-o: "\f1c5"; @fa-var-file-powerpoint-o: "\f1c4"; @fa-var-file-sound-o: "\f1c7"; @fa-var-file-text: "\f15c"; @fa-var-file-text-o: "\f0f6"; @fa-var-file-video-o: "\f1c8"; @fa-var-file-word-o: "\f1c2"; @fa-var-file-zip-o: "\f1c6"; @fa-var-files-o: "\f0c5"; @fa-var-film: "\f008"; @fa-var-filter: "\f0b0"; @fa-var-fire: "\f06d"; @fa-var-fire-extinguisher: "\f134"; @fa-var-firefox: "\f269"; @fa-var-first-order: "\f2b0"; @fa-var-flag: "\f024"; @fa-var-flag-checkered: "\f11e"; @fa-var-flag-o: "\f11d"; @fa-var-flash: "\f0e7"; @fa-var-flask: "\f0c3"; @fa-var-flickr: "\f16e"; @fa-var-floppy-o: "\f0c7"; @fa-var-folder: "\f07b"; @fa-var-folder-o: "\f114"; @fa-var-folder-open: "\f07c"; @fa-var-folder-open-o: "\f115"; @fa-var-font: "\f031"; @fa-var-font-awesome: "\f2b4"; @fa-var-fonticons: "\f280"; @fa-var-fort-awesome: "\f286"; @fa-var-forumbee: "\f211"; @fa-var-forward: "\f04e"; @fa-var-foursquare: "\f180"; @fa-var-free-code-camp: "\f2c5"; @fa-var-frown-o: "\f119"; @fa-var-futbol-o: "\f1e3"; @fa-var-gamepad: "\f11b"; @fa-var-gavel: "\f0e3"; @fa-var-gbp: "\f154"; @fa-var-ge: "\f1d1"; @fa-var-gear: "\f013"; @fa-var-gears: "\f085"; @fa-var-genderless: "\f22d"; @fa-var-get-pocket: "\f265"; @fa-var-gg: "\f260"; @fa-var-gg-circle: "\f261"; @fa-var-gift: "\f06b"; @fa-var-git: "\f1d3"; @fa-var-git-square: "\f1d2"; @fa-var-github: "\f09b"; @fa-var-github-alt: "\f113"; @fa-var-github-square: "\f092"; @fa-var-gitlab: "\f296"; @fa-var-gittip: "\f184"; @fa-var-glass: "\f000"; @fa-var-glide: "\f2a5"; @fa-var-glide-g: "\f2a6"; @fa-var-globe: "\f0ac"; @fa-var-google: "\f1a0"; @fa-var-google-plus: "\f0d5"; @fa-var-google-plus-circle: "\f2b3"; @fa-var-google-plus-official: "\f2b3"; @fa-var-google-plus-square: "\f0d4"; @fa-var-google-wallet: "\f1ee"; @fa-var-graduation-cap: "\f19d"; @fa-var-gratipay: "\f184"; @fa-var-grav: "\f2d6"; @fa-var-group: "\f0c0"; @fa-var-h-square: "\f0fd"; @fa-var-hacker-news: "\f1d4"; @fa-var-hand-grab-o: "\f255"; @fa-var-hand-lizard-o: "\f258"; @fa-var-hand-o-down: "\f0a7"; @fa-var-hand-o-left: "\f0a5"; @fa-var-hand-o-right: "\f0a4"; @fa-var-hand-o-up: "\f0a6"; @fa-var-hand-paper-o: "\f256"; @fa-var-hand-peace-o: "\f25b"; @fa-var-hand-pointer-o: "\f25a"; @fa-var-hand-rock-o: "\f255"; @fa-var-hand-scissors-o: "\f257"; @fa-var-hand-spock-o: "\f259"; @fa-var-hand-stop-o: "\f256"; @fa-var-handshake-o: "\f2b5"; @fa-var-hard-of-hearing: "\f2a4"; @fa-var-hashtag: "\f292"; @fa-var-hdd-o: "\f0a0"; @fa-var-header: "\f1dc"; @fa-var-headphones: "\f025"; @fa-var-heart: "\f004"; @fa-var-heart-o: "\f08a"; @fa-var-heartbeat: "\f21e"; @fa-var-history: "\f1da"; @fa-var-home: "\f015"; @fa-var-hospital-o: "\f0f8"; @fa-var-hotel: "\f236"; @fa-var-hourglass: "\f254"; @fa-var-hourglass-1: "\f251"; @fa-var-hourglass-2: "\f252"; @fa-var-hourglass-3: "\f253"; @fa-var-hourglass-end: "\f253"; @fa-var-hourglass-half: "\f252"; @fa-var-hourglass-o: "\f250"; @fa-var-hourglass-start: "\f251"; @fa-var-houzz: "\f27c"; @fa-var-html5: "\f13b"; @fa-var-i-cursor: "\f246"; @fa-var-id-badge: "\f2c1"; @fa-var-id-card: "\f2c2"; @fa-var-id-card-o: "\f2c3"; @fa-var-ils: "\f20b"; @fa-var-image: "\f03e"; @fa-var-imdb: "\f2d8"; @fa-var-inbox: "\f01c"; @fa-var-indent: "\f03c"; @fa-var-industry: "\f275"; @fa-var-info: "\f129"; @fa-var-info-circle: "\f05a"; @fa-var-inr: "\f156"; @fa-var-instagram: "\f16d"; @fa-var-institution: "\f19c"; @fa-var-internet-explorer: "\f26b"; @fa-var-intersex: "\f224"; @fa-var-ioxhost: "\f208"; @fa-var-italic: "\f033"; @fa-var-joomla: "\f1aa"; @fa-var-jpy: "\f157"; @fa-var-jsfiddle: "\f1cc"; @fa-var-key: "\f084"; @fa-var-keyboard-o: "\f11c"; @fa-var-krw: "\f159"; @fa-var-language: "\f1ab"; @fa-var-laptop: "\f109"; @fa-var-lastfm: "\f202"; @fa-var-lastfm-square: "\f203"; @fa-var-leaf: "\f06c"; @fa-var-leanpub: "\f212"; @fa-var-legal: "\f0e3"; @fa-var-lemon-o: "\f094"; @fa-var-level-down: "\f149"; @fa-var-level-up: "\f148"; @fa-var-life-bouy: "\f1cd"; @fa-var-life-buoy: "\f1cd"; @fa-var-life-ring: "\f1cd"; @fa-var-life-saver: "\f1cd"; @fa-var-lightbulb-o: "\f0eb"; @fa-var-line-chart: "\f201"; @fa-var-link: "\f0c1"; @fa-var-linkedin: "\f0e1"; @fa-var-linkedin-square: "\f08c"; @fa-var-linode: "\f2b8"; @fa-var-linux: "\f17c"; @fa-var-list: "\f03a"; @fa-var-list-alt: "\f022"; @fa-var-list-ol: "\f0cb"; @fa-var-list-ul: "\f0ca"; @fa-var-location-arrow: "\f124"; @fa-var-lock: "\f023"; @fa-var-long-arrow-down: "\f175"; @fa-var-long-arrow-left: "\f177"; @fa-var-long-arrow-right: "\f178"; @fa-var-long-arrow-up: "\f176"; @fa-var-low-vision: "\f2a8"; @fa-var-magic: "\f0d0"; @fa-var-magnet: "\f076"; @fa-var-mail-forward: "\f064"; @fa-var-mail-reply: "\f112"; @fa-var-mail-reply-all: "\f122"; @fa-var-male: "\f183"; @fa-var-map: "\f279"; @fa-var-map-marker: "\f041"; @fa-var-map-o: "\f278"; @fa-var-map-pin: "\f276"; @fa-var-map-signs: "\f277"; @fa-var-mars: "\f222"; @fa-var-mars-double: "\f227"; @fa-var-mars-stroke: "\f229"; @fa-var-mars-stroke-h: "\f22b"; @fa-var-mars-stroke-v: "\f22a"; @fa-var-maxcdn: "\f136"; @fa-var-meanpath: "\f20c"; @fa-var-medium: "\f23a"; @fa-var-medkit: "\f0fa"; @fa-var-meetup: "\f2e0"; @fa-var-meh-o: "\f11a"; @fa-var-mercury: "\f223"; @fa-var-microchip: "\f2db"; @fa-var-microphone: "\f130"; @fa-var-microphone-slash: "\f131"; @fa-var-minus: "\f068"; @fa-var-minus-circle: "\f056"; @fa-var-minus-square: "\f146"; @fa-var-minus-square-o: "\f147"; @fa-var-mixcloud: "\f289"; @fa-var-mobile: "\f10b"; @fa-var-mobile-phone: "\f10b"; @fa-var-modx: "\f285"; @fa-var-money: "\f0d6"; @fa-var-moon-o: "\f186"; @fa-var-mortar-board: "\f19d"; @fa-var-motorcycle: "\f21c"; @fa-var-mouse-pointer: "\f245"; @fa-var-music: "\f001"; @fa-var-navicon: "\f0c9"; @fa-var-neuter: "\f22c"; @fa-var-newspaper-o: "\f1ea"; @fa-var-object-group: "\f247"; @fa-var-object-ungroup: "\f248"; @fa-var-odnoklassniki: "\f263"; @fa-var-odnoklassniki-square: "\f264"; @fa-var-opencart: "\f23d"; @fa-var-openid: "\f19b"; @fa-var-opera: "\f26a"; @fa-var-optin-monster: "\f23c"; @fa-var-outdent: "\f03b"; @fa-var-pagelines: "\f18c"; @fa-var-paint-brush: "\f1fc"; @fa-var-paper-plane: "\f1d8"; @fa-var-paper-plane-o: "\f1d9"; @fa-var-paperclip: "\f0c6"; @fa-var-paragraph: "\f1dd"; @fa-var-paste: "\f0ea"; @fa-var-pause: "\f04c"; @fa-var-pause-circle: "\f28b"; @fa-var-pause-circle-o: "\f28c"; @fa-var-paw: "\f1b0"; @fa-var-paypal: "\f1ed"; @fa-var-pencil: "\f040"; @fa-var-pencil-square: "\f14b"; @fa-var-pencil-square-o: "\f044"; @fa-var-percent: "\f295"; @fa-var-phone: "\f095"; @fa-var-phone-square: "\f098"; @fa-var-photo: "\f03e"; @fa-var-picture-o: "\f03e"; @fa-var-pie-chart: "\f200"; @fa-var-pied-piper: "\f2ae"; @fa-var-pied-piper-alt: "\f1a8"; @fa-var-pied-piper-pp: "\f1a7"; @fa-var-pinterest: "\f0d2"; @fa-var-pinterest-p: "\f231"; @fa-var-pinterest-square: "\f0d3"; @fa-var-plane: "\f072"; @fa-var-play: "\f04b"; @fa-var-play-circle: "\f144"; @fa-var-play-circle-o: "\f01d"; @fa-var-plug: "\f1e6"; @fa-var-plus: "\f067"; @fa-var-plus-circle: "\f055"; @fa-var-plus-square: "\f0fe"; @fa-var-plus-square-o: "\f196"; @fa-var-podcast: "\f2ce"; @fa-var-power-off: "\f011"; @fa-var-print: "\f02f"; @fa-var-product-hunt: "\f288"; @fa-var-puzzle-piece: "\f12e"; @fa-var-qq: "\f1d6"; @fa-var-qrcode: "\f029"; @fa-var-question: "\f128"; @fa-var-question-circle: "\f059"; @fa-var-question-circle-o: "\f29c"; @fa-var-quora: "\f2c4"; @fa-var-quote-left: "\f10d"; @fa-var-quote-right: "\f10e"; @fa-var-ra: "\f1d0"; @fa-var-random: "\f074"; @fa-var-ravelry: "\f2d9"; @fa-var-rebel: "\f1d0"; @fa-var-recycle: "\f1b8"; @fa-var-reddit: "\f1a1"; @fa-var-reddit-alien: "\f281"; @fa-var-reddit-square: "\f1a2"; @fa-var-refresh: "\f021"; @fa-var-registered: "\f25d"; @fa-var-remove: "\f00d"; @fa-var-renren: "\f18b"; @fa-var-reorder: "\f0c9"; @fa-var-repeat: "\f01e"; @fa-var-reply: "\f112"; @fa-var-reply-all: "\f122"; @fa-var-resistance: "\f1d0"; @fa-var-retweet: "\f079"; @fa-var-rmb: "\f157"; @fa-var-road: "\f018"; @fa-var-rocket: "\f135"; @fa-var-rotate-left: "\f0e2"; @fa-var-rotate-right: "\f01e"; @fa-var-rouble: "\f158"; @fa-var-rss: "\f09e"; @fa-var-rss-square: "\f143"; @fa-var-rub: "\f158"; @fa-var-ruble: "\f158"; @fa-var-rupee: "\f156"; @fa-var-s15: "\f2cd"; @fa-var-safari: "\f267"; @fa-var-save: "\f0c7"; @fa-var-scissors: "\f0c4"; @fa-var-scribd: "\f28a"; @fa-var-search: "\f002"; @fa-var-search-minus: "\f010"; @fa-var-search-plus: "\f00e"; @fa-var-sellsy: "\f213"; @fa-var-send: "\f1d8"; @fa-var-send-o: "\f1d9"; @fa-var-server: "\f233"; @fa-var-share: "\f064"; @fa-var-share-alt: "\f1e0"; @fa-var-share-alt-square: "\f1e1"; @fa-var-share-square: "\f14d"; @fa-var-share-square-o: "\f045"; @fa-var-shekel: "\f20b"; @fa-var-sheqel: "\f20b"; @fa-var-shield: "\f132"; @fa-var-ship: "\f21a"; @fa-var-shirtsinbulk: "\f214"; @fa-var-shopping-bag: "\f290"; @fa-var-shopping-basket: "\f291"; @fa-var-shopping-cart: "\f07a"; @fa-var-shower: "\f2cc"; @fa-var-sign-in: "\f090"; @fa-var-sign-language: "\f2a7"; @fa-var-sign-out: "\f08b"; @fa-var-signal: "\f012"; @fa-var-signing: "\f2a7"; @fa-var-simplybuilt: "\f215"; @fa-var-sitemap: "\f0e8"; @fa-var-skyatlas: "\f216"; @fa-var-skype: "\f17e"; @fa-var-slack: "\f198"; @fa-var-sliders: "\f1de"; @fa-var-slideshare: "\f1e7"; @fa-var-smile-o: "\f118"; @fa-var-snapchat: "\f2ab"; @fa-var-snapchat-ghost: "\f2ac"; @fa-var-snapchat-square: "\f2ad"; @fa-var-snowflake-o: "\f2dc"; @fa-var-soccer-ball-o: "\f1e3"; @fa-var-sort: "\f0dc"; @fa-var-sort-alpha-asc: "\f15d"; @fa-var-sort-alpha-desc: "\f15e"; @fa-var-sort-amount-asc: "\f160"; @fa-var-sort-amount-desc: "\f161"; @fa-var-sort-asc: "\f0de"; @fa-var-sort-desc: "\f0dd"; @fa-var-sort-down: "\f0dd"; @fa-var-sort-numeric-asc: "\f162"; @fa-var-sort-numeric-desc: "\f163"; @fa-var-sort-up: "\f0de"; @fa-var-soundcloud: "\f1be"; @fa-var-space-shuttle: "\f197"; @fa-var-spinner: "\f110"; @fa-var-spoon: "\f1b1"; @fa-var-spotify: "\f1bc"; @fa-var-square: "\f0c8"; @fa-var-square-o: "\f096"; @fa-var-stack-exchange: "\f18d"; @fa-var-stack-overflow: "\f16c"; @fa-var-star: "\f005"; @fa-var-star-half: "\f089"; @fa-var-star-half-empty: "\f123"; @fa-var-star-half-full: "\f123"; @fa-var-star-half-o: "\f123"; @fa-var-star-o: "\f006"; @fa-var-steam: "\f1b6"; @fa-var-steam-square: "\f1b7"; @fa-var-step-backward: "\f048"; @fa-var-step-forward: "\f051"; @fa-var-stethoscope: "\f0f1"; @fa-var-sticky-note: "\f249"; @fa-var-sticky-note-o: "\f24a"; @fa-var-stop: "\f04d"; @fa-var-stop-circle: "\f28d"; @fa-var-stop-circle-o: "\f28e"; @fa-var-street-view: "\f21d"; @fa-var-strikethrough: "\f0cc"; @fa-var-stumbleupon: "\f1a4"; @fa-var-stumbleupon-circle: "\f1a3"; @fa-var-subscript: "\f12c"; @fa-var-subway: "\f239"; @fa-var-suitcase: "\f0f2"; @fa-var-sun-o: "\f185"; @fa-var-superpowers: "\f2dd"; @fa-var-superscript: "\f12b"; @fa-var-support: "\f1cd"; @fa-var-table: "\f0ce"; @fa-var-tablet: "\f10a"; @fa-var-tachometer: "\f0e4"; @fa-var-tag: "\f02b"; @fa-var-tags: "\f02c"; @fa-var-tasks: "\f0ae"; @fa-var-taxi: "\f1ba"; @fa-var-telegram: "\f2c6"; @fa-var-television: "\f26c"; @fa-var-tencent-weibo: "\f1d5"; @fa-var-terminal: "\f120"; @fa-var-text-height: "\f034"; @fa-var-text-width: "\f035"; @fa-var-th: "\f00a"; @fa-var-th-large: "\f009"; @fa-var-th-list: "\f00b"; @fa-var-themeisle: "\f2b2"; @fa-var-thermometer: "\f2c7"; @fa-var-thermometer-0: "\f2cb"; @fa-var-thermometer-1: "\f2ca"; @fa-var-thermometer-2: "\f2c9"; @fa-var-thermometer-3: "\f2c8"; @fa-var-thermometer-4: "\f2c7"; @fa-var-thermometer-empty: "\f2cb"; @fa-var-thermometer-full: "\f2c7"; @fa-var-thermometer-half: "\f2c9"; @fa-var-thermometer-quarter: "\f2ca"; @fa-var-thermometer-three-quarters: "\f2c8"; @fa-var-thumb-tack: "\f08d"; @fa-var-thumbs-down: "\f165"; @fa-var-thumbs-o-down: "\f088"; @fa-var-thumbs-o-up: "\f087"; @fa-var-thumbs-up: "\f164"; @fa-var-ticket: "\f145"; @fa-var-times: "\f00d"; @fa-var-times-circle: "\f057"; @fa-var-times-circle-o: "\f05c"; @fa-var-times-rectangle: "\f2d3"; @fa-var-times-rectangle-o: "\f2d4"; @fa-var-tint: "\f043"; @fa-var-toggle-down: "\f150"; @fa-var-toggle-left: "\f191"; @fa-var-toggle-off: "\f204"; @fa-var-toggle-on: "\f205"; @fa-var-toggle-right: "\f152"; @fa-var-toggle-up: "\f151"; @fa-var-trademark: "\f25c"; @fa-var-train: "\f238"; @fa-var-transgender: "\f224"; @fa-var-transgender-alt: "\f225"; @fa-var-trash: "\f1f8"; @fa-var-trash-o: "\f014"; @fa-var-tree: "\f1bb"; @fa-var-trello: "\f181"; @fa-var-tripadvisor: "\f262"; @fa-var-trophy: "\f091"; @fa-var-truck: "\f0d1"; @fa-var-try: "\f195"; @fa-var-tty: "\f1e4"; @fa-var-tumblr: "\f173"; @fa-var-tumblr-square: "\f174"; @fa-var-turkish-lira: "\f195"; @fa-var-tv: "\f26c"; @fa-var-twitch: "\f1e8"; @fa-var-twitter: "\f099"; @fa-var-twitter-square: "\f081"; @fa-var-umbrella: "\f0e9"; @fa-var-underline: "\f0cd"; @fa-var-undo: "\f0e2"; @fa-var-universal-access: "\f29a"; @fa-var-university: "\f19c"; @fa-var-unlink: "\f127"; @fa-var-unlock: "\f09c"; @fa-var-unlock-alt: "\f13e"; @fa-var-unsorted: "\f0dc"; @fa-var-upload: "\f093"; @fa-var-usb: "\f287"; @fa-var-usd: "\f155"; @fa-var-user: "\f007"; @fa-var-user-circle: "\f2bd"; @fa-var-user-circle-o: "\f2be"; @fa-var-user-md: "\f0f0"; @fa-var-user-o: "\f2c0"; @fa-var-user-plus: "\f234"; @fa-var-user-secret: "\f21b"; @fa-var-user-times: "\f235"; @fa-var-users: "\f0c0"; @fa-var-vcard: "\f2bb"; @fa-var-vcard-o: "\f2bc"; @fa-var-venus: "\f221"; @fa-var-venus-double: "\f226"; @fa-var-venus-mars: "\f228"; @fa-var-viacoin: "\f237"; @fa-var-viadeo: "\f2a9"; @fa-var-viadeo-square: "\f2aa"; @fa-var-video-camera: "\f03d"; @fa-var-vimeo: "\f27d"; @fa-var-vimeo-square: "\f194"; @fa-var-vine: "\f1ca"; @fa-var-vk: "\f189"; @fa-var-volume-control-phone: "\f2a0"; @fa-var-volume-down: "\f027"; @fa-var-volume-off: "\f026"; @fa-var-volume-up: "\f028"; @fa-var-warning: "\f071"; @fa-var-wechat: "\f1d7"; @fa-var-weibo: "\f18a"; @fa-var-weixin: "\f1d7"; @fa-var-whatsapp: "\f232"; @fa-var-wheelchair: "\f193"; @fa-var-wheelchair-alt: "\f29b"; @fa-var-wifi: "\f1eb"; @fa-var-wikipedia-w: "\f266"; @fa-var-window-close: "\f2d3"; @fa-var-window-close-o: "\f2d4"; @fa-var-window-maximize: "\f2d0"; @fa-var-window-minimize: "\f2d1"; @fa-var-window-restore: "\f2d2"; @fa-var-windows: "\f17a"; @fa-var-won: "\f159"; @fa-var-wordpress: "\f19a"; @fa-var-wpbeginner: "\f297"; @fa-var-wpexplorer: "\f2de"; @fa-var-wpforms: "\f298"; @fa-var-wrench: "\f0ad"; @fa-var-xing: "\f168"; @fa-var-xing-square: "\f169"; @fa-var-y-combinator: "\f23b"; @fa-var-y-combinator-square: "\f1d4"; @fa-var-yahoo: "\f19e"; @fa-var-yc: "\f23b"; @fa-var-yc-square: "\f1d4"; @fa-var-yelp: "\f1e9"; @fa-var-yen: "\f157"; @fa-var-yoast: "\f2b1"; @fa-var-youtube: "\f167"; @fa-var-youtube-play: "\f16a"; @fa-var-youtube-square: "\f166";
Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/less/variables.less/0
{ "file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/less/variables.less", "repo_id": "Daotin", "token_count": 11894 }
16
## 一、Promise Promise是一个对象,代表了未来某个将要发生的事件(,这个事件通常是一个异步操作) 有了Promise对象, 可以将异步操作以同步的流程表达出来, 避免了层层嵌套的回调函数(俗称'回调地狱')。 ES6的Promise是一个构造函数, 用来生成promise实例。 ### 1、promise对象3个状态 - `pending`: 初始化状态 - `fullfilled`: 成功状态 - `rejected`: 失败状态 只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。这也是Promise这个名字的由来,它的英语意思就是“承诺”,表示其他手段无法改变。 一旦状态改变,就不会再变,任何时候都可以得到这个结果。 Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected。只要这两种情况发生,状态就凝固了,不会再变了,会一直保持这个结果,这时就称为 resolved(已定型)。 ### 2、使用方法 **1、创建一个promise实例对象,参数是一个匿名函数,这个匿名函数有两个参数,resolve和reject,** **2、每一个参数都是一个回调函数。然后,函数体中一般执行的是异步操作,比如发起Ajax请求,或者开启定时器等。** **3、异步操作成功时,调用resolve回调函数,异步操作失败时,调用reject回调函数。** **4、在初始化Promise实例对象的时候,Promise的状态为pending;在调用resolve回调函数的时候,Promise的状态为fullfilled,表示成功状态;在调用reject回调函数的时候,Promise的状态为rejected,表示失败状态;** **5、 Promise的实例对象有一个方法then,参数为两个匿名函数,第一个匿名函数处理Promise的状态为fullfilled的情况;第二个匿名函数处理Promise的状态为rejected的情况;** **6、上面说到,在异步操作成功或者失败的时候,会调用resolve和reject函数,在这两个回调函数中可以传入参数,这个参数可以直接带入到then中两个匿名函数的参数中使用。比如获取到ajax的数据,可以将获取的数作为参数传入resolve的参数中,然后会自动将这个参数传入then的第一个匿名函数中,reject也一样。** 用代码表示: ```js function timeout(ms) { return new Promise((resolve, reject) => { setTimeout(resolve, ms, 'done'); }); } timeout(100).then((value) => { console.log(value); }); ``` 用图示的方法表示: ![](./images/13.png) 示例: ```js let promise = new Promise((resolve, reject) => { console.log(111); // 执行异步操作 setTimeout(() => { console.log(222); // 执行异步操作成功,此时修改promise的状态fullfilled resolve("success!"); // 执行异步操作成功,此时修改promise的状态rejected reject("failed!"); }, 2000); }); promise.then((data) => { // promise的状态fullfilled的操作 console.log("成功", data); }, () => { // promise的状态rejected的操作 console.log("失败", data); }); ``` > 注意:当执行到resolve("success!");修改promise的状态fullfilled的时候,后面的reject("failed!");不会执行。也就不会打印console.log("失败");的语句。 ![](./images/12.png) ### 3、promise执行顺序 Promise 新建后就会立即执行。 ```js let promise = new Promise(function(resolve, reject) { console.log('Promise'); resolve(); }); promise.then(function() { console.log('resolved.'); }); console.log('Hi!'); // Promise // Hi! // resolved ``` 上面代码中,Promise 新建后立即执行,所以首先输出的是Promise。然后,then方法指定的回调函数,将在当前脚本所有同步任务执行完才会执行,所以resolved最后输出。 ```js new Promise((resolve, reject) => { resolve(1); console.log(2); }).then(r => { console.log(r); }); // 2 // 1 ``` 上面代码中,调用resolve(1)以后,后面的console.log(2)还是会执行,并且会首先打印出来。这是因为立即 resolved 的 Promise 是在本轮事件循环的末尾执行,**总是晚于本轮循环的同步任务**。 然而—— 一般来说,调用resolve或reject以后,Promise 的使命就完成了,后继操作应该放到then方法里面,而不应该直接写在resolve或reject的后面。所以,最好在它们前面加上return语句,这样就不会有意外。 ```js new Promise((resolve, reject) => { return resolve(1); // 后面的语句不会执行 console.log(2); }) ``` ### 4、小栗子 使用 promise 获取新闻内容和评论内容: ```js // 定义一个请求news的方法 function getNews(url) { //创建一个promise对象 let promise = new Promise((resolve, reject) => { //初始化promise状态为pending //启动异步任务,发起Ajax请求 //1.创建一个 XMLHttpRequest 类型的对象 let request = new XMLHttpRequest(); // 4. 指定 xhr 状态变化事件处理函数 request.onreadystatechange = function () { if (request.readyState === 4) { if (request.status === 200) { let news = request.response; resolve(news); } else { reject('请求失败了...'); } } }; request.responseType = 'json'; //设置返回的数据类型 // 2. 打开与一个网址之间的连接 request.open("GET", url); //规定请求的方法,创建链接 // 3. 通过链接发送一次请求 request.send(); //发送 }) // 只有将promise返回,才可以调用then方法 return promise; }; // 调用getNews,获取新闻内容,其中一个字节为评论内容的地址 getNews('http://localhost:3000/news?id=2') .then((news) => { // 获取到新闻内容 console.log(news); // document.write(JSON.stringify(news)); // 获取新闻内容中的评论地址 console.log('http://localhost:3000' + news.commentsUrl); // 递归获取新闻评论内容,并且返回promise对象,以便链式then方法。 return getNews('http://localhost:3000' + news.commentsUrl); }, (error) => { alert(error); }) .then((comments) => { // then方法可以链式编程 console.log(comments); // 把新闻的评论部分已json的格式打印出来显示 document.write('<br><br><br><br><br>' + JSON.stringify(comments)); }, (error) => { alert(error); }); ``` ### 5、catch `Promise.prototype.catch`方法是`.then(null, rejection)`或`.then(undefined, rejection)`的别名,用于指定发生错误时的回调函数。 当状态就会变为`rejected`,就会调用`catch`方法指定的回调函数,处理这个错误。另外,`then`方法指定的回调函数,如果运行中抛出错误,也会被`catch`方法捕获。 ```js new Promise((resolve, reject) => { reject(1); console.log(2); }).catch(r => { console.log(r); }); // 2 // 1 ``` > 一般来说,不要在`then`方法里面定义 Reject 状态的回调函数(即`then`的第二个参数),总是使用`catch`方法。 ```js // 不好的写法 promise .then(function(data) { // success }, function(err) { // error }); // 好的写法 promise .then(function(data) { //cb // success }) .catch(function(err) { // error }); ``` 上面代码中,第二种写法要好于第一种写法,理由是第二种写法可以捕获前面`then`方法执行中的错误,也更接近同步的写法(`try/catch`)。因此,建议总是使用`catch`方法,而不使用`then`方法的第二个参数。 ### 6、finally `finally`方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。该方法是 ES2018 引入标准的。 ```js promise .then(result => {···}) .catch(error => {···}) .finally(() => {···}); ``` 上面代码中,不管`promise`最后的状态,在执行完`then`或`catch`指定的回调函数以后,都会执行`finally`方法指定的回调函数。 ### 7、Promise静态方法 #### 7.1、all和race 有时候需要同时处理多个ajax请求,如何在都获取到数据的时候才进行下一步操作呢? `Promise.all` 就派上用场了。 ```js Promise.all([ajax1(), ajax2(), ajax3()]) .then(function(res) { // res 处理 }) .catch(function(err) { // err 错误处理 }) ``` 其中`ajax1`,`ajax2`,`ajax3` 返回值都是 Promise 实例。 > 当 ajax1(), ajax2(), ajax3() 状态全为 `fulfilled` 的时候,才会调用`then`方法。 > > 当 ajax1(), ajax2(), ajax3() 状态有一个为 `rejected` 的时候,就会调用`catch`方法。 而 rece 与all 用法相同,但是结果相反: ```js Promise.rece([ajax1(), ajax2(), ajax3()]) .then(function(res) { // res 处理 }) .catch(function(err) { // err 错误处理 }) ``` > 当 ajax1(), ajax2(), ajax3() 状态有一个为 `fulfilled` 的时候,就会调用`then`方法。 > > 当 ajax1(), ajax2(), ajax3() 状态全为 `rejected` 的时候,才会调用`catch`方法。 #### 7.2、resolve和reject `Promise.resolve(value) `方法返回一个已给定值解析后的新的Promise对象,从而能继续使用then的链式方法调用。 ```js var promise1 = Promise.resolve(123); promise.then(function(value) { console.log(value); // expected output: 123 }); ``` 而 `Promise.reject()` 和 resolve 一样。 ## 二、Symbol ES5 的对象属性名都是字符串,这容易造成属性名的冲突。比如,你使用了一个他人提供的对象,但又想为这个对象添加新的方法(mixin 模式),新方法的名字就有可能与现有方法产生冲突。如果有一种机制,**保证每个属性的名字都是独一无二**的就好了,这样就从根本上防止属性名的冲突。这就是 ES6 引入Symbol的原因。 **1、Symbol属性对应的值是唯一的,解决命名冲突问题** Symbol 是一种**新的数据类型**,跟 String,Number,Object,Boolean,null,undefined 并列。 Symbol 值通过`Symbol`函数生成。这就是说,对象的属性名现在可以有两种类型,一种是原来就有的字符串,另一种就是新增的 Symbol 类型。**凡是属性名属于 Symbol 类型,就都是独一无二的,可以保证不会与其他属性名产生冲突。** ```js let s = Symbol(); typeof s; // symbol ``` 上面代码中,变量`s`就是一个独一无二的值。`typeof`运算符的结果,表明变量`s`是 Symbol 数据类型,而不是字符串之类的其他类型。 > 注意,`Symbol`函数前不能使用`new`命令,否则会报错。这是因为生成的 Symbol 是一个原始类型的值,不是对象。也就是说,由于 Symbol 值不是对象,所以不能添加属性。基本上,它是一种类似于字符串的数据类型。 `Symbol`函数可以接受一个字符串作为参数,表示对 Symbol 实例的描述,主要是为了在控制台显示,或者转为字符串时,比较容易区分。 ```js let s1 = Symbol('foo'); let s2 = Symbol('bar'); s1 // Symbol(foo) s2 // Symbol(bar) s1.toString() // "Symbol(foo)" s2.toString() // "Symbol(bar)" ``` 上面代码中,`s1`和`s2`是两个 Symbol 值。如果不加参数,它们在控制台的输出都是`Symbol()`,不利于区分。有了参数以后,就等于为它们加上了描述,输出的时候就能够分清,到底是哪一个值。 **2、Symbol值不能与其他数据进行计算,包括同字符串拼串** ```js let sym = Symbol('My symbol'); "your symbol is " + sym // TypeError: can't convert symbol to string `your symbol is ${sym}` // TypeError: can't convert symbol to string ``` **3、作为属性名的 Symbol** 由于每一个 Symbol 值都是不相等的,这意味着 Symbol 值可以作为标识符,用于对象的属性名,就能保证不会出现同名的属性。这对于一个对象由多个模块构成的情况非常有用,能防止某一个键被不小心改写或覆盖。 ```js let mySymbol = Symbol(); // 第一种写法 let a = {}; a[mySymbol] = 'Hello!'; // 第二种写法 let a = { [mySymbol]: 'Hello!' }; // 第三种写法 let a = {}; Object.defineProperty(a, mySymbol, { value: 'Hello!' }); // 以上写法都得到同样结果 a[mySymbol] // "Hello!" ``` > 注意,Symbol 值作为对象属性名时,不能用点运算符。`a.mySymbol = 'Hello!';` **4、for in, for of遍历时不会遍历symbol属性** ```js let obj = { username: 'Daotin', age: 18 }; obj[symbol] = 'hello'; obj[symbol] = 'symbol'; console.log(obj); for (let i in obj) { console.log(i); } ``` **5、内置的 Symbol 值** 除了定义自己使用的 Symbol 值以外,ES6 还提供了 11 个内置的 Symbol 值,指向语言内部使用的方法。 **6、Symbol.hasInstance** 对象的`Symbol.hasInstance`属性,指向一个内部方法。当其他对象使用`instanceof`运算符,判断是否为该对象的实例时,会调用这个方法。比如,`foo instanceof Foo`在语言内部,实际调用的是`Foo[Symbol.hasInstance](foo)`。 **7、Symbol.iterator** 对象的`Symbol.iterator`属性,指向该对象的默认遍历器方法。 ## 三、Iterator > 以下来自 [ECMAScript 6 入门 - 阮一峰](http://es6.ruanyifeng.com/) Iterator 是迭代器(遍历器)的意思。 JavaScript 原有的表示“集合”的数据结构,主要是数组(`Array`)和对象(`Object`),ES6 又添加了`Map`和`Set`。这样就有了四种数据集合,用户还可以组合使用它们,定义自己的数据结构,比如数组的成员是`Map`,`Map`的成员是对象。这样就需要一种统一的接口机制,来处理所有不同的数据结构。 **遍历器(Iterator)就是这样一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署 Iterator 接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。** **Iterator 的作用:** - 为各种数据结构,提供一个统一的、简便的访问接口 - 使得数据结构的成员能够按某种次序排列 - ES6 创造了一种新的遍历命令`for...of`循环,Iterator 接口主要供`for...of`消费。 **Iterator 的遍历过程:** (1)创建一个指针对象,指向当前数据结构的起始位置。也就是说,遍历器对象本质上,就是一个指针对象。 (2)第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员。 (3)第二次调用指针对象的next方法,指针就指向数据结构的第二个成员。 (4)不断调用指针对象的next方法,直到它指向数据结构的结束位置。 每一次调用next方法,都会返回数据结构的当前成员的信息。具体来说,就是返回一个包含value和done两个属性的对象。其中,value属性是当前成员的值,done属性是一个布尔值,表示遍历是否结束。 下面是一个模拟`next`方法返回值的例子。 ```js var it = makeIterator(['a', 'b']); it.next() // { value: "a", done: false } it.next() // { value: "b", done: false } it.next() // { value: undefined, done: true } function makeIterator(array) { var nextIndex = 0; return { next: function() { return nextIndex < array.length ? {value: array[nextIndex++], done: false} : {value: undefined, done: true}; } }; } ``` 对于遍历器对象来说,`done: false`和`value: undefined`属性都是可以省略的,因此上面的`makeIterator`函数可以简写成下面的形式。 ```js function makeIterator(array) { var nextIndex = 0; return { next: function() { return nextIndex < array.length ? {value: array[nextIndex++]} : {done: true}; } }; } ``` ### 1、默认 Iterator 接口 ES6 规定,默认的 Iterator 接口部署在数据结构的`Symbol.iterator`属性,或者说,一个数据结构只要具有`Symbol.iterator`属性,就可以认为是“可遍历的”(iterable)。 `Symbol.iterator`属性本身是一个函数,就是当前数据结构默认的遍历器生成函数。执行这个函数,就会返回一个遍历器。至于属性名`Symbol.iterator`,它是一个表达式,返回`Symbol`对象的`iterator`属性,这是一个预定义好的、类型为 Symbol 的特殊值,所以要放在方括号内. ```js const obj = { [Symbol.iterator] : function () { return { next: function () { return { value: 1, done: true }; } }; } }; ``` 上面代码中,对象`obj`是可遍历的(iterable),因为具有`Symbol.iterator`属性。执行这个属性,会返回一个遍历器对象。该对象的根本特征就是具有`next`方法。每次调用`next`方法,都会返回一个代表当前成员的信息对象,具有`value`和`done`两个属性。 ES6 的有些数据结构原生具备 Iterator 接口(比如数组),即不用任何处理,就可以被`for...of`循环遍历。原因在于,这些数据结构原生部署了`Symbol.iterator`属性(详见下文),另外一些数据结构没有(比如对象)。凡是部署了`Symbol.iterator`属性的数据结构,就称为部署了遍历器接口。调用这个接口,就会返回一个遍历器对象。 原生具备 Iterator 接口的数据结构如下。 - Array - Map - Set - String - TypedArray - 函数的 arguments 对象 - NodeList 对象 下面的例子是数组的`Symbol.iterator`属性。 ```js let arr = ['a', 'b', 'c']; let iter = arr[Symbol.iterator](); iter.next() // { value: 'a', done: false } iter.next() // { value: 'b', done: false } iter.next() // { value: 'c', done: false } iter.next() // { value: undefined, done: true } ``` 上面代码中,变量`arr`是一个数组,原生就具有遍历器接口,部署在`arr`的`Symbol.iterator`属性上面。所以,调用这个属性,就得到遍历器对象。 对于原生部署 Iterator 接口的数据结构,不用自己写遍历器生成函数,`for...of`循环会自动遍历它们。除此之外,其他数据结构(主要是对象)的 Iterator 接口,都需要自己在`Symbol.iterator`属性上面部署,这样才会被`for...of`循环遍历。 一个对象如果要具备可被`for...of`循环调用的 Iterator 接口,就必须在`Symbol.iterator`的属性上部署遍历器生成方法(原型链上的对象具有该方法也可)。 ### 2、调用 Iterator 接口的场合 - 使用解构赋值以及...三点运算符时会调用iterator接口 ```js let arr1 = [1, 2, 3, 4, 5]; let [value1, ...arr2] = arr1; ``` **for..of..遍历** ```js // 原生测试 数组 let arr3 = [1, 2, 'kobe', true]; for (let i of arr3) { console.log(i); } // 字符串 string let str = 'abcdefg'; for (let item of str) { console.log(item); } ```
Daotin/Web/08-ES6语法/04-Promise,Symbol,Iterator.md/0
{ "file_path": "Daotin/Web/08-ES6语法/04-Promise,Symbol,Iterator.md", "repo_id": "Daotin", "token_count": 11423 }
17
## Express 简介 Express 是一个简洁而灵活的 node.js Web应用框架。Express提供了一个轻量级模块,把Node.js的http模块功能封装在一个简单易用的接口中。Express也扩展了http模块的功能,使你轻松处理服务器的路由、响应、cookie和HTTP请求的状态。使用Express可以充当Web服务器。 使用 Express 可以快速地搭建一个完整功能的网站。 简单来说就是,之前我们每次引入静态文件的时候,都需要自己写路由来解析界面,有了 express 框架,就可以像php一样,放入的静态文件可以自动解析。 还有可以自动生成package.json等创建一个web网站基本的文件架构。总之很方便了。 ## Express的安装 ### 安装 express 到项目 ```js npm i express -S ``` ### 安装 express 快速构建工具 ``` npm i express-generator -g ``` (其实安装 express 快速构建工具就可以了,不需要安装express,我们在初始化项目的时候,会自动安装express的。) ### 快速构建项目 ```js express -e expressDemo //项目名 ``` 项目构建好了会自动创建如下文件: ![](./img/4.png) 其中就有了package.json项目依赖文件列表。我们可以看到有我们必须的express依赖。 ![](./img/5.png) 可以看到有很多依赖项目没有的,怎么一次性下载所由需要的依赖呢? ### 初始化项目 在当前项目目录下使用指令: ``` npm install ``` 就可以下载所有package.json下的所有指定版本的依赖(这也就是我之前说的不需要先下载express模块了),最后生成node_modules文件夹。 ### 运行项目 在bin文件夹下有个www文件,这个就是类似我们的main.js文件,启动文件了。 我们可以直接使用node命令运行: ``` node ./bin/www ``` 或者我们看到在package.json中有个`scripts`属性,其值有个start属性,对应的正是node运行项目的指令,故可以在项目目录下使用: ``` npm run start ``` 也可以将项目跑起来。 有时候我们修改了node后端的代码就需要重启服务,每次都要重启太麻烦了,有没有什么工具可以在修改完服务代码保存的时候自动重启服务呢? 答案是有的,只需要全局安装`supervisor`工具就可以了。 ``` npm i supervisor -g ``` 然后像node一样启动服务就可以实时监听服务代码的改动自动重启: ``` supervisor ./bin/www ``` ## 案例:商品录入 要求:使用express实现商品信息录入MongoDB数据库,并且提取出来展示在列表,具有翻页排序功能。 项目代码过于复杂,略了。只把重点写一下: `views` 文件夹下的ejs文件时渲染到页面的文件。 这个在app.js已经进行默认说明: ```js app.set('views', path.join(__dirname, 'views')); // 默认路径为 views app.set('view engine', 'ejs'); // 默认后缀为ejs ``` 所以在我们路由路径`routes` 下的js文件中渲染到前端页面就可以直接写: ```js res.render('input'); // 不需要写成 res.render('/views/input.ejs'); ``` 在路由界面,通过下面设置自己的路由文件: ```js var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var ajaxRouter = require('./routes/ajax'); app.use('/', indexRouter); app.use('/users', usersRouter); // 新建自己的关于ajax的路由,便于分类。你非要写到index.js或者users.js谁敢说不行。 app.use('/ajax', ajaxRouter); ``` 然后在路由文件里面:(以自己的ajax.js路由为例) ```js var express = require('express'); var router = express.Router(); let dbc = require("../db"); /* GET users listing. */ // 这里的 '/' 相当于 '/ajax' router.get('/', function (req, res, next) { res.send('respond with a resource'); }); router.post('/inputGoods', function (req, res, next) { // req.query get请求时 通过该参数获取前端发送的数据 // req.body post请求时 通过该参数获取前端发送的数据 let data = req.body; // { name: '1', price: '2', num: '3' } let good = dbc("goods"); good.insert(data, (err, info) => { res.json({ code: !err ? 200 : 500, msg: !err ? '录入数据成功' : '录入数据失败' }); }); }); router.get('/getGoods', function (req, res, next) { let good = dbc("goods"); good.find().toArray((err, list) => { if (!err) { res.json({ code: !err ? 200 : 500, data: !err ? list : null }); } }); }); module.exports = router; ``` 这里:`router.get('/', function (req, res, next) ` 这里的 `/` 其实就是对应的 `/ajax` 只不过这个前缀在app.js里面提前写了`app.use('/ajax', ajaxRouter);`。 上面代码中,可以看到有发起`/inputGoods` 路由的,那么我们前端是ajax发起时的地址是什么?是`/inputGoods`吗? 其实不是而是 `/ajax/inputGoods`,因为/ajax在别处写了。 ```js $.ajax({ type: "post", url: "/ajax/inputGoods", data: inputObj, dataType: "json", success: function (res) { console.log(res); } }); ``` 还有一些知识点: > **res对象api** > > `res.render("pagename",data)` 将data数据注入到ejs模板代码中,并且输出到浏览器端(渲染html页面) > > `res.redirect(path)` 重定向到指定的路径 > > `res.json(obj)` 向前端返回对象类型数据 > > `res.jsonp(obj)` 向前端通过jsonp的方式进行返回数据 > > `res.send(text)` 向前端发送数据 > > > > **req 属性** > > `req.query` get请求时 通过该参数获取前端发送的数据 > > `req.body` post请求时 通过该参数获取前端发送的数据 > > > > **使得get和post均可访问:** > > `render.all()` ejs文件的一些语法: ```ejs <!DOCTYPE html> <html lang="zh-cn"> <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>商品列表</title> </head> <body> <h1>商品列表</h1> <ul> <% list.map(goods=>{ %> <li> <h3>商品名: <span><%= goods.goodsname %></span></h3> <p class="price">价格: <span><%= goods.price %></span></p> <p class="discount">折扣: <span><%= goods.discount %></span>折</p> <p class="stock">库存: <span><%= goods.stock %></span>件</p> </li> <% }) %> </ul> </body> </html> ``` > <% 之间插入js代码 %> > > <%= 之间插入变量 %> 在ejs文件中引入自己的js代码是写在 `public/javascrips` 文件夹下的。 所以在ejs中引入自己的js代码是这样写的: ```ejs <!-- 这里的完整地址:http://localhost:3000/javascripts/input.js --> <!-- public就相当于http://localhost:3000 ,这个在app.js写的 --> <script src="/javascripts/input.js"></script> ``` public就相当于http://localhost:3000 ,这个在app.js里面写好的。 ```js // public 相当于 http://localhost:3000 app.use(express.static(path.join(__dirname, 'public'))); ``` ## 案例:用户注册登录 注册界面:register.ejs ```ejs <!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> 用户:<input type="text" id="user"> 密码:<input type="text" id="pwd"> <button>注册</button> </body> <script src="http://code.jquery.com/jquery.min.js"></script> <script> $("button").on("click", function () { $.ajax({ type: "post", url: "/ajax/register", data: { name: $("#user").val(), pwd: $("#pwd").val() }, dataType: "json", success: function (res) { console.log(res); } }); }); </script> </html> ``` 登录界面:login.ejs ```ejs <!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> 用户:<input type="text" id="user"> 密码:<input type="text" id="pwd"> <button>登录</button> </body> <script src="http://code.jquery.com/jquery.min.js"></script> <script> $("button").on("click", function() { $.ajax({ type: "post", url: "/ajax/login", data: { name: $("#user").val(), pwd: $("#pwd").val() }, dataType: "json", success: function({ msg }) { alert(msg); } }); }); </script> </html> ``` 页面渲染:index.js ```js router.get('/register', (req, res) => res.render('register')) router.get('/login', (req, res) => res.render('login')) ``` 登录和注册的ajax请求:ajax.js ```js router.post('/register', function(req, res, next) { let data = req.body; // { name: '1', price: '2', num: '3' } let user = dbc("users"); user.insert(data, (err, info) => { res.json({ code: !err ? 200 : 500, msg: !err ? '录入数据成功' : '录入数据失败' }); }); }); router.post('/login', function(req, res, next) { let { name, pwd } = req.body; // { name: '1', price: '2', num: '3' } let user = dbc("users"); user.find({ name }).toArray((err, list) => { if (!err) { if (list.length == 0) { res.json({ msg: '用户名不存在' }) } else { if (list[0].pwd == pwd) { res.json({ msg: '登录成功' }) } else { res.json({ msg: '密码错误' }) } } } else { console.log("数据查询失败"); } }); }); ```
Daotin/Web/10-Node.js/07-express框架介绍.md/0
{ "file_path": "Daotin/Web/10-Node.js/07-express框架介绍.md", "repo_id": "Daotin", "token_count": 6040 }
18
## 一、Redux框架 Redux是 Flux架构的体现,将 Flux 与函数式编程结合一起,很短时间内就成为了最热门的前端架构。 ![](./img/8.png) Redux是在解决中大型项目用到的框架,像Flux一样,小型项目可以不必使用。 > "如果你不知道是否需要 Redux,那就是不需要它。" ——someone > > "只有遇到 React 实在解决不了的问题,你才需要 Redux 。" —— Redux 的创造者 Dan Abramov ## 二、Redux设计思想 Redux 的设计思想很简单,就两句话。 (1)Web 应用是一个状态机,视图与状态是一一对应的。 (2)所有的状态,保存在一个对象里面。 ![](./img/9.png) 如上图流程如下: - `React Component`即我们通常说的视图,视图可能触发修改store的事件 - 修改store事件由`Action Creators`创建并通过store的dispatch方法,发送给store。 - store接收到action后,会发送给`Reducers`,发送给Reducers的有两个参数,一个是store本身,一个是action,然后Reducers拿到action对原来的store进行更新,然后返回新的store给store。 - 事先会在在视图加载后中绑定更新视图的函数,一旦store发生更新就会同步到视图。 ## 三、示例 以商品列表页进行演示。 使用redux首先要安装redux模块。 ``` npm i redux -S ``` ### 1、创建store ```jsx import { createStore } from 'redux'; import { reducer } from './reducer' export let store = createStore(reducer); ``` ### 2、在视图点击按钮发送action ```jsx import {store} from './store' add() { let action = { type: 'ADD_ITEM', goods: {name:'新商品'} } store.dispatch(action); } ``` ### 3、创建reducer,接收action ```jsx import { deepCopy } from "./deepCopy"; // 自定义深拷贝函数 // 参数以:store中的state // 参数二:store传过来的action export let reducer = (state = { list: [ { name: '商品1' }, { name: '商品2' }, { name: '商品3' }, ] }, action) => { let newStore = {}; switch (action.type) { case 'ADD_ITEM': newStore = deepCopy(state); newStore.list.push(action.goods); return newStore; break; case 'DEL_ITEM': newStore = deepCopy(state); newStore.list.pop(); return newStore; break; default: return state; break; } } ``` state需要有初始值,即没有action修改的时候的初始值。也就是视图中不点击按钮时后显示的默认值。 既然要返回默认值,所以在default中,return state。 ### 4、会事先在视图初始化时绑定视图更新函数 ```jsx import { List } from "./List"; import { store } from "./store"; import { addAction } from "./ActionCreators"; export class ListController extends React.Component{ constructor(props){ super(props) this.add = this.add.bind(this) this.updateView = this.updateView.bind(this) this.state = store.getState() } componentDidMount(){ this.unsub = store.subscribe(this.updateView) } componentWillUnmount(){ // 解绑视图更新函数 this.unsub() } // 视图更新函数 updateView(){ this.setState(store.getState()) } add(){ store.dispatch(addAction({name:"新的商品"})) } render(){ return <List list={this.state.list} add={this.add} /> } } ``` ## 四、优化 ### 1、封装action创建函数 发送的action一般会封装到一个函数中。 而action的type也会封装到一个单独的文件,避免重复。 ```jsx // actionCreators import { ADD_ITEM, DEL_ITEM } from "./actionTypes"; export let addAction = (goods) => { return { type: ADD_ITEM, goods } } export let delAction = () => { return { type: DEL_ITEM } } ``` ```jsx // actionTypes.js export const ADD_ITEM = 'ADD_ITEM'; export const DEL_ITEM = 'DEL_ITEM'; ``` 于是我们的add函数就变成这样: ```jsx import { addAction } from "./ActionCreators"; add(){ store.dispatch(addAction({name:"新的商品"})) } ``` ### 2、自动创建容器组件 我门之前容器组件和UI组件都是自己创建的,现在react提供了专门的插件,方便我们创建容器组件。 > 而且由于创建的容器组件代码量小,所以可以将UI组件和容器组件合并成一个文件。 安装插件: ``` npm i react-redux -S ``` 组件代码: ```jsx // Goods.js import { connect } from "react-redux"; import { addAction, delAction } from "../actionCreators"; // 1、容器部分 // 此函数放容器的state let mapStateToProps = (state) => { return { list: state.list } } // 此函数放容器的一些方法 let mapDispatchToProps = dispatch => { return { add() { let name = this.refs.goodsInput.value; let action = addAction({ name }); dispatch(action); }, del() { let action = delAction(); dispatch(action); } } } // 最后导入UI中的Goods,Goods来自UI export let GoodsController = connect(mapStateToProps, mapDispatchToProps)(Goods); /*——————————————————————————————————容器,UI分界线————————————————————————————————————————*/ // 2、UI部分 export class Goods extends React.Component { constructor() { super(); } render() { let { list } = this.props; let domList = list.map((item, i) => { return ( <li key={i}>{item.name}</li> ); }); return ( <div> 商品名:<input type="text" ref="goodsInput" /> <button onClick={this.props.add.bind(this)}>添加</button> <button onClick={this.props.del}>删除</button> <ul> {domList} </ul> </div> ); } } ``` 上面代码,前一部分是容器,后一部分是UI(**UI组件是不用暴露出去的**),分界还是很明显的。 最后需要注意的是,**整个应用**需要最外面包裹一层`Provider`才可以,还要传一个store参数过去: ```jsx import { render } from 'react-dom'; import { GoodsController } from './Goods'; import { Provider } from "react-redux"; import { store } from "./store"; render(<Provider store={store}><GoodsController /></Provider>, document.getElementById('app')); ``` > 注意:自动创建的容器组件不需要绑定视图更新函数。 ### 3、reducer拆分 我们之前的reducer长下面这样,只有一个Goods组件: ```jsx import { deepCopy } from "./deepCopy"; export let reducer = (state = { list: [ { name: '商品1' }, { name: '商品2' }, { name: '商品3' }, ] }, action) => { let newStore = {}; switch (action.type) { case 'ADD_ITEM': newStore = deepCopy(state); newStore.list.push(action.goods); return newStore; break; case 'DEL_ITEM': newStore = deepCopy(state); newStore.list.pop(); return newStore; break; default: return state; break; } } ``` 如果组件一多,所有的store的初始state就会积压在一起不方便管理,所以要进行拆分。 比如增加一个Home组件,Home组件有title和banner列表,那么我就要写在一起: ```jsx import { deepCopy } from "../deepCopy"; export let reducer = (state = { list: [ { name: '商品1' }, { name: '商品2' }, { name: '商品3' }, ], title: '首页', banner: [ { name: '首页1' }, { name: '首页2' }, { name: '首页3' }, ] }, action) => { let newStore = deepCopy(state);; switch (action.type) { case 'ADD_ITEM': newStore.list.push(action.goods); return newStore; case 'DEL_ITEM': newStore.list.pop(); return newStore; default: return state; } } ``` 如果有更多组件的话就更乱了。 拆分成`homeReducer.js`和`goodsReducer.js`,最后合并到`index.js` ```jsx // homeReducer.js export let homeReducer = (state = { title: '首页', banner: [ { name: '首页1' }, { name: '首页2' }, { name: '首页3' }, ] }, action) => { return state; } ``` ```jsx // goodsReducer.js import { deepCopy } from "../deepCopy"; export let goodsReducer = (state = { list: [ { name: '商品1' }, { name: '商品2' }, { name: '商品3' }, ], }, action) => { let newStore = deepCopy(state);; switch (action.type) { case 'ADD_ITEM': newStore.list.push(action.goods); return newStore; case 'DEL_ITEM': newStore.list.pop(); return newStore; default: return state; } } ``` 合并的时候需要用到一个来自redux的插件`combineReducers`: ```jsx import { combineReducers } from "redux"; import { homeReducer } from "./homeReducer"; import { goodsReducer } from "./goodsReducer"; export let reducer = combineReducers({ home: homeReducer, goods: goodsReducer }); ``` ### 4、异步action > 注意: > > 我们创建action的函数actionCreators中的代码必须是纯函数,也必须是同步函数,有点类似与mutations。 那么如果有异步的代码怎么办?比如ajax获取数据? 这时候需要用到`redux-thunk`安装插件。 1、安装插件 ``` npm i redux-thunk -S ``` 2、修改store applyMiddleware 是中间件的意思。 ```jsx import { createStore, applyMiddleware } from 'redux'; import { reducer } from './reducers' import thunk from "redux-thunk"; export let store = createStore(reducer, applyMiddleware(thunk)); ``` 这个时候,我们store的dispatch的action就可以不是对象了,可以是个函数类型,如果是函数类型的话,dispatch这个函数,会使得这个函数立即执行。 然后一般这个函数就是用来异步请求数据的,在这个函数请求到数据的时候才会在这个函数内部再次dispatch得到的数据,这个数据就是一个对象。有点像绕弯的样子。 我们就在Home页请求商品列表: Home.js 容器加UI组件: ```jsx import { connect } from "react-redux"; import { getListAction } from "./actionCreators"; // UI组件 class UI extends React.Component { constructor() { super(); } componentDidMount() { // UI加载完成就获取ajax信息 this.props.getList(); } render() { let { title, banner } = this.props; let domList = banner.map((item, i) => { return ( <li key={i}>{item._id}</li> ); }); return ( <div> <h1>{title}</h1> <ul>{domList}</ul> </div> ); } } let mapStateToProps = (state) => { // 注意:由于拆分了reducer,所以state相应的也改变了。 // 就不是之前的state.title和state.banner了 return { title: state.home.title, banner: state.home.banner } } let mapDispatchToProps = dispatch => { return { getList() { // getListAction是一个异步函数,用来获取ajax数据 dispatch(getListAction); } } } export let Home = connect(mapStateToProps, mapDispatchToProps)(UI); ``` 创建actionCreators.js函数:异步请求ajax数据,并发给homeReducer ```jsx import { BANNER_ITEM } from "./actionTypes"; import axios from 'axios'; export let setListAction = (banner) => { return { type: BANNER_ITEM, banner } } // getListAction有一个参数就是mapDispatchToProps的参数dispatch,用来发送action export let getListAction = dispatch => { axios.get("/zhuiszhu/goods/getHot") .then(({ data }) => { // 获取到数据后,将action对象发送给homeReducer dispatch(setListAction(data.list)); }) } ``` homeReducer接收数据,更新homeState: ```jsx import { BANNER_ITEM } from "../actionTypes"; import { deepCopy } from "../deepCopy"; export let homeReducer = (state = { title: '首页', banner: [] }, action) => { let newState = deepCopy(state); switch (action.type) { case BANNER_ITEM: newState.banner = action.banner; return newState; default: return state; } } ``` 自动创建的容器组件会自动更新视图。 我们知道store的dispatch的action在异步的时候是个函数类型,如果我们要获取商品详情的话,必然会在类似下面代码的getListAction函数中传入参数,一旦传入参数,就不是函数类型了,类型是函数的返回值。所以我们应该在getListAction中返回一个函数类型。 ```jsx let mapDispatchToProps = dispatch => { return { getList() { // getListAction是一个异步函数,用来获取ajax数据 dispatch(getListAction(id)); } } } ``` 类似下面的伪代码: ```jsx export let getListAction = dispatch => { // 返回的是个函数 return dispatch => { axios.get("/zhuiszhu/goods/getHot",{parems:{xxx}}) .then(({ data }) => { dispatch(xxx); }) } } ``` ## 五、简易redux项目 包括首页,商品列表,详情页和页面。 文章链接:https://github.com/Daotin/daotin.github.io/issues/133
Daotin/Web/13-React/06-Redux框架.md/0
{ "file_path": "Daotin/Web/13-React/06-Redux框架.md", "repo_id": "Daotin", "token_count": 7626 }
19
## 一、输入属性(父组件向子组件传值) 比如主组件向Home组件传递数据: 父组件传递数据: ```js // app.component.html 主组件 <app-home messageText="这是主组件传递的数据"></app-home> ``` 子组件接收数据: ```typescript // home.component.ts // 修饰器,将messageText修饰为外部传入的属性 @Input() // 定义一个属性,未给值 messageText: string // home.component.html <p>{{messageText}}</p> ``` > 注意:装饰器`@Input`需要先引入才能使用。 **将主组件传入的字符串变为动态属性:** 主组件在调用home组件的时候有两种方式: ```html <!--方式一--> <app-home messageText="{{text}}"></app-home> <!--方式二--> <app-home [messageText]="text"></app-home> ``` **给输入属性改名** 给Input装饰器加个参数就是新的名字。 ```typescript @Input('mt'); messageText:string; // 调用的时候 <app-message [mt]="text"></app-massage> ``` ## 二、输出属性(子组件向父组件传值) 示例:Home组件调用child组件。 ### 1、子组件发送数据 child组件 ```typescript import { Component, OnInit, Output, EventEmitter } from '@angular/core'; export class ChildComponent implements OnInit { constructor() { } ngOnInit() { } // 装饰为输出属性 @Output() // childData为属性名,发给父组件的数据为string类型 childData: EventEmitter<string> = new EventEmitter(); // 点击按钮发送数据(不需要事件名,事件名就是输出属性名。) send() { this.childData.emit('子组件发给父组件的数据'); } } ``` > 不需要事件名,事件名就是输出属性名。 ### 2、父组件接收数据 Home组件引入child组件 ```html <app-child (childData)="getData($event)"></app-child> ``` 触发接收子组件的数据的事件名就是输出属性名。 > $event (是固定写法),用来存放子组件发来的数据。 ```typescript export class HomeComponent implements OnInit { constructor() { } ngOnInit() { } // 接收子组件的数据 getData(data) { console.log(data); } } ``` ## 三、子组件互相传值 1、中间人模式 > 子组件A --> 父组件 --> 子组件B
Daotin/Web/14-Angular/05-组件间传值.md/0
{ "file_path": "Daotin/Web/14-Angular/05-组件间传值.md", "repo_id": "Daotin", "token_count": 1294 }
20
## 一、canvas 通过JS完成画图而不是css canvas 默认 inline-block,可以认为是一种特殊的图片。 ### 1、canvas 划线 ```html <canvas id="can" width="800" height="800"></canvas> ``` > (宽高不能放在style里面,否则比例不对) > > canvas里面的width和height相当于图片的原始尺寸,加了外部style的宽高,就相当于对图片进行压缩和拉伸。 ```js // 1、获取原生dom对象 let dom = document.getElementById('can'); // 2、获取绘图对象 let can = dom.getContext('2d'); // 3d是webgl // 定义线条起点 can.moveTo(0,0); // 定义线条中点(非终点) can.lineTo(400,400); can.lineTo(800,0); // 对标记范围进行描边 can.stroke() // 对标记范围进行填充 can.fill(); ``` ![](./img/1.png) ### 2、设置线条属性 线条默认宽度是1. > (一定要在绘图之前设置。) ```js can.lineWidth = 2; //设置线条宽度 can.strokeStyle = '#f00'; // 设置线条颜色 can.fillStyle = '#f00'; // 设置填充区域颜色 ``` ### 3、折线样式 - `miter`:尖角(当尖角长度值过长时会自动变成折角,如果强制显示尖角:`can.miterLimit = 100`设置尖角长度阈值) - `round`:圆角 - `bevel`:折角 ```js can.lineJoin = 'miter'; can.moveTo(100, 100); can.lineTo(300, 100); can.lineTo(100, 200); can.stroke() can.lineJoin = 'round'; can.moveTo(400, 100); can.lineTo(600, 100); can.lineTo(400, 200); can.stroke() can.lineJoin = 'bevel'; can.moveTo(700, 100); can.lineTo(900, 100); can.lineTo(700, 200); can.stroke() ``` ![](./img/2.png) ### 4、设置线帽 - `round`:加圆角线帽 - `square`:加直角线帽 - `butt`:不加线帽 ```js can.lineCap = 'round'; can.moveTo(100, 100); can.lineTo(300, 100); can.stroke() // 新建绘图,使得上一次的绘画样式不会影响下面的绘画样式(代码加在上一次绘画和下一次绘画中间。) can.beginPath() can.lineCap = 'square'; can.moveTo(100, 200); can.lineTo(300, 200); can.stroke() can.beginPath() can.lineCap = 'butt'; can.moveTo(100, 300); can.lineTo(300, 300); ``` ![](./img/3.png) ### 5、画矩形 ```js // 参数:x,y,宽,高 can.rect(100,100,100,100); can.stroke(); ``` ![](./img/4.png) ```js // 画完即填充 can.fillRect(100,100,100,100); ``` ![](./img/5.png) ### 6、画圆弧 ```js // 参数:圆心x,圆心y,半径,圆弧起点与圆心的夹角度数,圆弧终点与圆心的夹角度数,true(逆时针绘画) can.arc(500,300,200,0,2*Math.PI/360*90,false); can.stroke() ``` ![](./img/6.png) 示例: ```js can.moveTo(500,300); can.lineTo(500 + Math.sqrt(100), 300 + Math.sqrt(100)) can.arc(500, 300, 100, 2 * Math.PI / 360 *startDeg, 2 * Math.PI / 360 *endDeg, false); can.closePath()//将图形起点和终点用线连接起来使之成为封闭的图形 can.fill() ``` ![](./img/7.png) > 1、`can.beginPath()` // 新建绘图,使得上一次的绘画样式不会影响下面的绘画样式(代码加在上一次绘画和下一次绘画中间。) > > 2、`can.closePath()` //将图形起点和终点用线连接起来使之成为封闭的图形。 ### 7、旋转画布 ```js can.rotate(2*Math.PI/360*45); // 一定要写在开始绘图之前 can.fillRect(0,0,200, 10); ``` > 旋转整个画布的坐标系(参考坐标为画布的(0,0)位置) ![](./img/8.png) ### 8、缩放画布 ```js can.scale(0.5,2); can.fillRect(0,0,200, 10); ``` **整个画布**:x方向缩放为原来的0.5,y方向拉伸为原来的2倍。 ![](./img/9.png) ### 9、画布位移 ```js can.translate(100,100) can.fillRect(0,0,200, 10); ``` ![](./img/10.png) ### 10、保存与恢复画布状态 ```js can.save() // 存档:保存当前画布坐标系状态 can.restore() // 读档:恢复之前保存的画布坐标系状态 ``` ![](./img/11.png) ![](./img/12.png) ### 11、示例1:指针时钟 ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>clock</title> <style type="text/css"> #can { width: 1000px; height: 600px; background: linear-gradient(45deg, green, skyblue); } </style> </head> <body> <canvas id="can" width="2000" height="1200"></canvas> </body> <script type="text/javascript"> let dom = document.getElementById('can'); let can = dom.getContext('2d'); // 把画布的圆心移动到画布的中心 can.translate(dom.width / 2, dom.height / 2); // 保存当前的画布坐标系 can.save() run(); function run() { setInterval(function() { clearCanvas(); draw(); }, 10); } // 绘图 function draw() { let time = new Date(); let hour = time.getHours(); let min = time.getMinutes(); let sec = time.getSeconds(); let minSec = time.getMilliseconds(); drawPannl(); drawHour(hour, min, sec); drawMin(min, sec); drawSec(sec, minSec); drawPoint(); } // 最简单的方法:由于canvas每当高度或宽度被重设时,画布内容就会被清空 function clearCanvas() { dom.height = dom.height; can.translate(dom.width / 2, dom.height / 2); can.save() } // 画表盘 function drawPannl() { can.beginPath(); can.restore() can.save() can.lineWidth = 10; can.strokeStyle = 'skyblue'; can.arc(0, 0, 400, 0, 2 * Math.PI); can.stroke(); for (let i = 0; i < 12; i++) { can.beginPath(); can.lineWidth = 16; can.strokeStyle = 'greenyellow'; can.rotate(2 * Math.PI / 12) can.moveTo(0, -395); can.lineTo(0, -340); can.stroke(); } for (let i = 0; i < 60; i++) { can.beginPath(); can.lineWidth = 10; can.strokeStyle = '#fff'; can.rotate(2 * Math.PI / 60) can.moveTo(0, -395); can.lineTo(0, -370); can.stroke(); } } // 画时针 function drawHour(h, m, s) { can.beginPath(); can.restore() can.save() can.lineWidth = 24; can.strokeStyle = 'palevioletred'; can.lineCap = 'round' can.rotate(2 * Math.PI / (12 * 60 * 60) * (h * 60 * 60 + m * 60 + s)) can.moveTo(0, 0); can.lineTo(0, -200); can.stroke(); } // 画分针 function drawMin(m, s) { can.beginPath(); can.restore() can.save() can.lineWidth = 14; can.strokeStyle = '#09f'; can.lineCap = 'round' can.rotate(2 * Math.PI / (60 * 60) * (m * 60 + s)) can.moveTo(0, 0); can.lineTo(0, -260); can.stroke(); } // 画秒针 function drawSec(s, ms) { can.beginPath(); can.restore() can.save() can.lineWidth = 8; can.strokeStyle = '#f00'; can.lineCap = 'round' can.rotate(2 * Math.PI / (60 * 1000) * (s * 1000 + ms)); can.moveTo(0, 50); can.lineTo(0, -320); can.stroke(); } // 画中心点 function drawPoint() { can.beginPath(); can.restore() can.save() can.lineWidth = 10; can.fillStyle = 'red'; can.arc(0, 0, 12, 0, 2 * Math.PI); can.fill(); } </script> </html> ``` ![](./img/13.png) ### 12、示例2:圆弧时钟 ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>clock</title> <style type="text/css"> #can { width: 1000px; height: 600px; background: linear-gradient(45deg, rgb(94, 53, 6), black); } </style> </head> <body> <canvas id="can" width="2000" height="1200"></canvas> </body> <script type="text/javascript"> let dom = document.getElementById('can'); let can = dom.getContext('2d'); // 把画布的圆心移动到画布的中心 can.translate(dom.width / 2, dom.height / 2); // 保存当前的画布坐标系 can.save(); // 圆形指针起始角度 let startDeg = 2 * Math.PI / 360 * 270; run(); // draw(); function run() { setInterval(function() { clearCanvas(); draw(); }, 20); } // 绘图 function draw() { let time = new Date(); // let hour = time.getHours(); let hour = time.getHours() > 10 ? time.getHours() - 12 : time.getHours(); let min = time.getMinutes(); let sec = time.getSeconds(); let minSec = time.getMilliseconds(); drawPannl(); drawTime(hour, min, sec, minSec); drawHour(hour, min, sec); drawMin(min, sec); drawSec(sec, minSec); drawPoint(); } // 最简单的方法:由于canvas每当高度或宽度被重设时,画布内容就会被清空 function clearCanvas() { dom.height = dom.height; can.translate(dom.width / 2, dom.height / 2); can.save() } // 画表盘 function drawPannl() { can.restore() can.save() // 设置时表盘 can.beginPath(); can.lineWidth = 50; can.strokeStyle = 'rgba(255,23,87,0.2)'; can.arc(0, 0, 400, 0, 2 * Math.PI); can.stroke(); // 设置分表盘 can.beginPath(); can.strokeStyle = 'rgba(169,242,15,0.2)'; can.arc(0, 0, 345, 0, 2 * Math.PI); can.stroke(); // 设置秒表盘 can.beginPath(); can.strokeStyle = 'rgba(21,202,230,0.2)'; can.arc(0, 0, 290, 0, 2 * Math.PI); can.stroke(); // 小时刻度 // for (let i = 0; i < 12; i++) { // can.beginPath(); // can.lineWidth = 16; // can.strokeStyle = 'rgba(0,0,0,0.2)'; // can.rotate(2 * Math.PI / 12) // can.moveTo(0, -375); // can.lineTo(0, -425); // can.stroke(); // } // 分针刻度 // for (let i = 0; i < 60; i++) { // can.beginPath(); // can.lineWidth = 10; // can.strokeStyle = '#fff'; // can.rotate(2 * Math.PI / 60) // can.moveTo(0, -395); // can.lineTo(0, -370); // can.stroke(); // } } // 画时针 function drawHour(h, m, s) { let rotateDeg = 2 * Math.PI / (12 * 60 * 60) * (h * 60 * 60 + m * 60 + s); can.beginPath(); can.restore() can.save() // 时针圆弧 can.lineWidth = 50; can.strokeStyle = 'rgb(255,23,87)'; can.lineCap = 'round'; can.shadowColor = "rgb(255,23,87)"; // 设置阴影颜色 can.shadowBlur = 20; // 设置阴影范围 can.arc(0, 0, 400, startDeg, startDeg + rotateDeg); can.stroke(); // 时针指针 can.beginPath(); can.lineWidth = 24; can.strokeStyle = 'rgb(255,23,87)'; can.lineCap = 'round' can.rotate(rotateDeg) can.moveTo(0, 0); can.lineTo(0, -100); can.stroke(); } // 画分针 function drawMin(m, s) { let rotateDeg = 2 * Math.PI / (60 * 60) * (m * 60 + s); can.beginPath(); can.restore() can.save() // 分针圆弧 can.lineWidth = 50; can.strokeStyle = 'rgb(169,242,15)'; can.lineCap = 'round' can.shadowColor = "rgb(169,242,15)"; can.shadowBlur = 20; can.arc(0, 0, 345, startDeg, startDeg + rotateDeg); can.stroke(); // 分针指针 can.beginPath(); can.lineWidth = 14; can.strokeStyle = 'rgb(169,242,15)'; can.lineCap = 'round' can.rotate(rotateDeg) can.moveTo(0, 0); can.lineTo(0, -160); can.stroke(); } // 画秒针 function drawSec(s, ms) { let rotateDeg = 2 * Math.PI / (60 * 1000) * (s * 1000 + ms); can.beginPath(); can.restore() can.save() can.lineWidth = 50; can.strokeStyle = 'rgb(21,202,230)'; can.lineCap = 'round' can.arc(0, 0, 290, startDeg, startDeg + rotateDeg); can.stroke(); can.beginPath(); can.lineWidth = 8; can.strokeStyle = 'rgb(21,202,230)'; can.lineCap = 'round' can.shadowColor = "rgb(21,202,230)"; can.shadowBlur = 20; can.rotate(rotateDeg); can.moveTo(0, 50); can.lineTo(0, -220); can.stroke(); } // 画中心点 function drawPoint() { can.beginPath(); can.restore() can.save() can.lineWidth = 10; can.fillStyle = 'red'; can.arc(0, 0, 12, 0, 2 * Math.PI); can.fill(); } // 显示数字时钟 function drawTime(h, m, s, ms) { can.font = '60px Calibri'; can.fillStyle = '#0f0' can.shadowColor = "#fff"; can.shadowBlur = 20; can.fillText(`${h}:${m}:${s}.${ms}`, -140, -100); } </script> </html> ``` ![](./img/1.gif)
Daotin/Web/16-前端综合/01-canvas.md/0
{ "file_path": "Daotin/Web/16-前端综合/01-canvas.md", "repo_id": "Daotin", "token_count": 7539 }
21
/** * java bean : PO VO * * @author 何明胜 * * 2017年10月21日 */ package pers.husen.web.bean;
Humsen/web/web-core/src/pers/husen/web/bean/package-info.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/bean/package-info.java", "repo_id": "Humsen", "token_count": 47 }
22
package pers.husen.web.common.constants; /** * 前端到后端请求常量 * * @author 何明胜 * * 2017年11月6日 */ public class RequestConstants { /****************************************************************************** * 前端请求参数名称 ******************************************************************************/ public static final String PARAM_TYPE = "type"; public static final String PARAM_KEYWORDS = "keywords"; public static final String PARAM_CATEGORY = "category"; /****************************************************************************** * 前端请求类型常量, 先用类型, 如果类型不足以表达含义, 再加个模式 ******************************************************************************/ /* 没有组合,只用类型就能解决的放上面. 一旦组合就放下面 */ /** 请求类型:json格式数据 -> 博客、代码等 */ public static final String REQUEST_TYPE_JSON = "json_return"; /* 前端请求为 类型(动词)+模式(名词),两个单词拼接,前端请求直接拼接两个单词. 如 auth_login为登录验证. 以下的已经统一化 */ /** 请求类型:验证 */ public static final String REQUEST_TYPE_AUTH = "auth"; /** 请求类型:修改 -> 密码/邮箱/文章等 */ public static final String REQUEST_TYPE_MODIFY = "modify"; /** 请求类型:查询 -> 个人资料等 */ public static final String REQUEST_TYPE_QUERY = "query"; /** 请求类型:创建(注册) -> 新用户、留言、文章等 */ public static final String REQUEST_TYPE_CREATE = "create"; /** 请求类型:发送验证码 -> 认证邮箱、注册等 */ public static final String REQUEST_TYPE_SEND_CODE = "send_code"; /** 请求类型:发送验证码 -> 认证邮箱等 */ public static final String REQUEST_TYPE_AUTH_CODE = "auth_code"; /** 请求类型:逻辑删除 -> 博客、代码等 */ public static final String REQUEST_TYPE_LOGIC_DELETE = "logic_delete"; /** 请求类型:物理删除 -> 博客、代码等 */ public static final String REQUEST_TYPE_PHYSICALLY_DELETE = "physically_delete"; /* ********************* 我是分割线 ******************************/ /** 请求模式:登录 */ public static final String MODE_LOGIN = "_login"; /** 请求模式:注册 */ public static final String MODE_REGISTER = "_register"; /** 请求模式:密码 */ public static final String MODE_PASSWORD = "_pwd"; /** 请求模式:用户信息 */ public static final String MODE_USER_INFO = "_user_info"; /** 请求模式:旧邮箱 -> 修改密码需要验证 */ public static final String MODE_OLD_EMAIL = "_old_email"; /** 请求模式:绑定(新)邮箱 -> 注册、修改密码绑定 */ public static final String MODE_BIND_EMAIL = "_bind_email"; /** 请求模式:找回密码 -> 找回密码需要验证码 */ public static final String MODE_RETRIVE_PWD = "_retrive_pwd"; /** 请求模式:所有 -> 所有留言、博客等 */ public static final String MODE_ALL = "_all"; /** 请求模式:一个(含内容) -> 上传留言、查询某篇博客等 */ public static final String MODE_ONE = "_one"; /** 请求模式:一页 -> 博客、代码、下载等分页查询 */ public static final String MODE_ONE_PAGE = "_one_page"; /** 请求模式:总数量 */ public static final String MODE_TOTAL_NUM = "_total_num"; /** 请求模式:目录 */ public static final String MODE_CATEGORY = "_category"; /** 请求模式:博客 */ public static final String MODE_BLOG = "_blog"; /** 请求模式:代码 */ public static final String MODE_CODE = "_code"; /** 请求模式:留言 */ public static final String MODE_MESSAGE = "_message"; /** 请求模式:文件 */ public static final String MODE_FILE = "_file"; /** 请求模式:上一篇 -> 有效文章等 **/ public static final String MODE_PREVIOUS = "_previous"; /** 请求模式:下一篇 -> 有效文章等 **/ public static final String MODE_NEXT = "_next"; }
Humsen/web/web-core/src/pers/husen/web/common/constants/RequestConstants.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/common/constants/RequestConstants.java", "repo_id": "Humsen", "token_count": 1961 }
23
/** * 通用助手 * * @author 何明胜 * * 2017年10月20日 */ package pers.husen.web.common;
Humsen/web/web-core/src/pers/husen/web/common/package-info.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/common/package-info.java", "repo_id": "Humsen", "token_count": 51 }
24
package pers.husen.web.dao.impl; import java.util.ArrayList; import java.util.Date; import pers.husen.web.bean.vo.ArticleCategoryVo; import pers.husen.web.bean.vo.BlogArticleVo; import pers.husen.web.bean.vo.CodeLibraryVo; import pers.husen.web.common.constants.DbConstans; import pers.husen.web.dao.ArticleCategoryDao; import pers.husen.web.dbutil.DbManipulationUtils; import pers.husen.web.dbutil.DbQueryUtils; import pers.husen.web.dbutil.mappingdb.ArticleCategoryMapping; import pers.husen.web.dbutil.mappingdb.BlogDetailsMapping; import pers.husen.web.dbutil.mappingdb.CodeLibraryMapping; import pers.husen.web.service.BlogArticleSvc; import pers.husen.web.service.CodeLibrarySvc; /** * @desc 文章目录 * * @author 何明胜 * * @created 2017年12月12日 上午10:13:12 */ public class ArticleCategoryDaoImpl implements ArticleCategoryDao { @Override public int insertCategory(ArticleCategoryVo aVo) { String sql = "INSERT INTO " + ArticleCategoryMapping.DB_NAME + " (" + ArticleCategoryMapping.CATEGORY_NAME + ", " + ArticleCategoryMapping.CREATE_DATE + ", " + ArticleCategoryMapping.CATEGORY_DELETE + ") VALUES (?, ?, ?)"; ArrayList<Object> paramList = new ArrayList<Object>(); Object obj = null; paramList.add((obj = aVo.getCategoryName()) != null ? obj : ""); paramList.add((obj = aVo.getCreateDate()) != null ? obj : new Date()); paramList.add(DbConstans.FIELD_VALID_FLAG); return DbManipulationUtils.insertNewRecord(sql, paramList); } @Override public int queryMaxId() { String sql = "SELECT max(" + ArticleCategoryMapping.CATEGORY_ID + ") FROM " + ArticleCategoryMapping.DB_NAME; return DbQueryUtils.queryIntByParam(sql, new ArrayList<Object>()); } @Override public ArrayList<ArticleCategoryVo> queryCategory3Num(String classification) { String dbName = null; String cateClass = null; String isValid = null; int totalNum = 0; String classBlog = "blog"; if (classBlog.equals(classification)) { dbName = BlogDetailsMapping.DB_NAME; cateClass = BlogDetailsMapping.BLOG_CATEGOTY; isValid = BlogDetailsMapping.BLOG_DELETE; // 查询总数量 BlogArticleVo bVo = new BlogArticleVo(); bVo.setBlogCategory(-1); ; totalNum = new BlogArticleSvc().queryBlogTotalCount(bVo); } else { dbName = CodeLibraryMapping.DB_NAME; cateClass = CodeLibraryMapping.CODE_CATEGORY; isValid = CodeLibraryMapping.CODE_DELETE; // 查询总数量 CodeLibraryVo cVo = new CodeLibraryVo(); cVo.setCodeCategory(-1); totalNum = new CodeLibrarySvc().queryCodeTotalCount(cVo); } String sql = "SELECT " + ArticleCategoryMapping.CATEGORY_ID + ", " + ArticleCategoryMapping.CATEGORY_NAME + ", COUNT(*) AS category_num FROM " + ArticleCategoryMapping.DB_NAME + " LEFT JOIN " + dbName + " ON " + isValid + " = " + DbConstans.FIELD_VALID_FLAG + " AND " + ArticleCategoryMapping.CATEGORY_ID + " = " + cateClass + " WHERE " + cateClass + " IS NOT NULL GROUP BY " + ArticleCategoryMapping.CATEGORY_ID + ", " + ArticleCategoryMapping.CATEGORY_NAME + " ORDER BY " + ArticleCategoryMapping.CATEGORY_ID; ArrayList<ArticleCategoryVo> aVos = DbQueryUtils.queryBeanListByParam(sql, new ArrayList<Object>(), ArticleCategoryVo.class); // 判断是否还存在未分类的 // 如果存在,设置该数量为总共梳理 // 如果不存在,在最前面新增一个 if (aVos.get(0).getCategoryId() == 0) { aVos.get(0).setCategoryNum(totalNum); } else { ArticleCategoryVo aVo = new ArticleCategoryVo(); aVo.setCategoryId(0); aVo.setCategoryName("所有文章"); aVo.setCategoryNum(totalNum); aVos.add(0, aVo); } return aVos; } @Override public ArrayList<ArticleCategoryVo> queryAllCategory() { String sql = "SELECT " + ArticleCategoryMapping.CATEGORY_ID + ", " + ArticleCategoryMapping.CATEGORY_NAME + " FROM " + ArticleCategoryMapping.DB_NAME + " ORDER BY " + ArticleCategoryMapping.CATEGORY_ID; return DbQueryUtils.queryBeanListByParam(sql, new ArrayList<Object>(), ArticleCategoryVo.class); } }
Humsen/web/web-core/src/pers/husen/web/dao/impl/ArticleCategoryDaoImpl.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/dao/impl/ArticleCategoryDaoImpl.java", "repo_id": "Humsen", "token_count": 1574 }
25
package pers.husen.web.dbutil.mappingdb; /** * 博客数据库映射 * * @author 何明胜 * * 2017年10月20日 */ public class BlogDetailsMapping { /** * 数据库名称 */ public static final String DB_NAME = "blog_details"; public static final String BLOG_ID = "blog_id"; public static final String BLOG_TITLE = "blog_title"; public static final String BLOG_AUTHOR = "blog_author"; public static final String BLOG_SUMMARY = "blog_summary"; public static final String BLOG_HTML_CONTENT = "blog_html_content"; public static final String BLOG_MD_CONTENT = "blog_md_content"; public static final String BLOG_LABEL = "blog_label"; public static final String BLOG_DELETE = "blog_delete"; public static final String BLOG_CATEGOTY = "blog_category"; }
Humsen/web/web-core/src/pers/husen/web/dbutil/mappingdb/BlogDetailsMapping.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/dbutil/mappingdb/BlogDetailsMapping.java", "repo_id": "Humsen", "token_count": 281 }
26
package pers.husen.web.service; import pers.husen.web.bean.vo.ReleaseFeatureVo; import pers.husen.web.dao.ReleaseFeatureDao; import pers.husen.web.dao.impl.ReleaseFeatureDaoImpl; /** * @author 何明胜 * * 2017年10月17日 */ public class ReleaseFeatureSvc implements ReleaseFeatureDao{ private static final ReleaseFeatureDaoImpl releaseFeatureDaoImpl = new ReleaseFeatureDaoImpl(); @Override public int insertReleaseFeature(ReleaseFeatureVo rVo) { return releaseFeatureDaoImpl.insertReleaseFeature(rVo); } @Override public ReleaseFeatureVo queryLatestReleaseFeature() { return releaseFeatureDaoImpl.queryLatestReleaseFeature(); } @Override public ReleaseFeatureVo queryReleaseById(int releaseId) { return releaseFeatureDaoImpl.queryReleaseById(releaseId); } @Override public int updateReleaseContentById(ReleaseFeatureVo rVo) { return releaseFeatureDaoImpl.updateReleaseContentById(rVo); } }
Humsen/web/web-core/src/pers/husen/web/service/ReleaseFeatureSvc.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/service/ReleaseFeatureSvc.java", "repo_id": "Humsen", "token_count": 289 }
27
package pers.husen.web.servlet.image; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import pers.husen.web.bean.po.ImageUploadPo; import pers.husen.web.bean.vo.ImageUploadVo; import pers.husen.web.common.handler.ImageUploadHandler; import pers.husen.web.common.helper.DateFormatHelper; import pers.husen.web.service.ImageUploadSvc; /** * 图片上传 * * @author 何明胜 * * 2017年10月20日 */ @WebServlet(urlPatterns="/imageUpload.hms") public class ImageUploadSvt extends HttpServlet { private static final long serialVersionUID = 1L; public ImageUploadSvt() { super(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); ImageUploadHandler imageUploadHandler = new ImageUploadHandler(); String imageDatePath = DateFormatHelper.dateNumberFormat(); String fileName = imageUploadHandler.imageUploadHandler(request, imageDatePath); //上传结果 ImageUploadPo iPo = new ImageUploadPo(); // 不为null则上传成功 if (fileName != null) { //上传成功为1 iPo.setSuccess(1); //图片带网址完整链接 StringBuffer resquestUrl = request.getRequestURL(); int serverPathStart = resquestUrl.lastIndexOf("/"); String imageFullLink = resquestUrl.substring(0, serverPathStart) + "/imageDownload.hms?imageUrl=" + imageDatePath + "/" + fileName; ImageUploadVo iVo = new ImageUploadVo(); iVo.setImageName(imageDatePath + fileName); iVo.setImageUrl(imageFullLink); iVo.setImageUploadDate(new Date()); iVo.setImageType(1); iVo.setImageDownloadCount(0); ImageUploadSvc iSvc = new ImageUploadSvc(); iSvc.insertImageUpload(iVo); iPo.setUrl(imageFullLink); iPo.setMessage("上传成功"); }else { iPo.setSuccess(0); iPo.setMessage("上传失败"); } JSONObject jsonObject = JSONObject.fromObject(iPo); PrintWriter out = response.getWriter(); out.println(jsonObject); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Humsen/web/web-core/src/pers/husen/web/servlet/image/ImageUploadSvt.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/image/ImageUploadSvt.java", "repo_id": "Humsen", "token_count": 936 }
28
Manifest-Version: 1.0 Class-Path:
Humsen/web/web-mobile/WebContent/META-INF/MANIFEST.MF/0
{ "file_path": "Humsen/web/web-mobile/WebContent/META-INF/MANIFEST.MF", "repo_id": "Humsen", "token_count": 15 }
29
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>web</display-name> <description>默认欢迎列表</description> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <description>设置session的有效时间(分钟)</description> <session-config> <session-timeout>10</session-timeout> </session-config> <description>初始化路径的配置和log4j配置</description> <listener> <listener-class>pers.husen.web.config.listener.WebInitConfigListener</listener-class> </listener> <description>监听session,实现在线人数统计</description> <listener> <listener-class>pers.husen.web.config.listener.OnlineCountListener</listener-class> </listener> <description>异常处理过滤器</description> <filter> <filter-name>ExceptionFilter</filter-name> <filter-class>pers.husen.web.config.filter.ExceptionFilter</filter-class> </filter> <filter-mapping> <filter-name>ExceptionFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
Humsen/web/web-mobile/WebContent/WEB-INF/web.xml/0
{ "file_path": "Humsen/web/web-mobile/WebContent/WEB-INF/web.xml", "repo_id": "Humsen", "token_count": 545 }
30
@charset "UTF-8"; .form-editor-version { margin-top: 50px; }
Humsen/web/web-mobile/WebContent/css/personal_center/editor_version.css/0
{ "file_path": "Humsen/web/web-mobile/WebContent/css/personal_center/editor_version.css", "repo_id": "Humsen", "token_count": 29 }
31
/** * 自定义开发工具包 * * @author 何明胜 * * 2017年10月23日 */ /** * 重写日期格式 * * 对Date的扩展,将 Date 转化为指定格式的String 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 例子: (new * Date()).Format('yyyy-MM-dd hh:mm:ss.S') ==> 2006-07-02 08:09:04.423 (new * Date()).Format('yyyy-M-d h:m:s.S') ==> 2006-7-2 8:9:4.18 */ Date.prototype.format = function(fmt) { var o = { 'M+' : this.getMonth() + 1, // 月份 'd+' : this.getDate(), // 日 'h+' : this.getHours(), // 小时 'm+' : this.getMinutes(), // 分 's+' : this.getSeconds(), // 秒 'q+' : Math.floor((this.getMonth() + 3) / 3), // 季度 'S' : this.getMilliseconds() // 毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '') .substr(4 - RegExp.$1.length)); for ( var k in o) if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))); return fmt; } /** * 获取url 地址参数 */ $.extend({ 'getUrlParam' : function(variable){ var query = window.location.search.substring(1); var vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (pair[0] == variable) { return pair[1]; } } return false; } }); /** * 获取当前 HH:mm:ss 格式的时间 */ $.extend({ 'nowDateHMS' : function() { var date = new Date(); var seperator1 = '-'; var seperator2 = ':'; var month = date.getMonth() + 1; var strDate = date.getDate(); if (month >= 1 && month <= 9) { month = '0' + month; } if (strDate >= 0 && strDate <= 9) { strDate = '0' + strDate; } var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + ' ' + date.getHours() + seperator2 + date.getMinutes() + seperator2 + date.getSeconds(); return currentdate; } }); /** * 判断是否是手机 * * @returns */ $.extend({ 'isMobile' : function() { var userAgentInfo = navigator.userAgent; var mobileAgents = [ 'Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad','iPod']; var mobile_flag = false; // 根据userAgent判断是否是手机 for (var v = 0; v < mobileAgents.length; v++) { if (userAgentInfo.indexOf(mobileAgents[v]) > 0) { mobile_flag = true; break; } } var screen_width = window.screen.width; var screen_height = window.screen.height; // 根据屏幕分辨率判断是否是手机 if(screen_width < 500 && screen_height < 800){ mobile_flag = true; } return mobile_flag; } }); /** * 验证码60s后可重发 */ $.extend({ 'codeCountDown' : function ($btnSendCode) { $btnSendCode.html('重发(<label id="txt_secondsCount">60</label>s)'); $btnSendCode.attr({'disabled':'disabled'}); /** * 验证码60s重发辅助内部函数 * @returns */ function codeCountDownHelper(){ //验证码的id统一命名 var nowCount = $('#txt_secondsCount').text(); if (nowCount == 1) { setTimeout(function() { $btnSendCode.html('发送验证码'); $btnSendCode.removeAttr('disabled'); }, 1000); return; } else { $('#txt_secondsCount').text(nowCount - 1); } setTimeout(function(){ codeCountDownHelper(); }, 1000); } //开始倒计时 codeCountDownHelper(); } }); /** * 表单转json */ $.fn.form2Json = function(){ var json_obj = {}; var array = this.serializeArray(); $.each(array, function() { if (json_obj[this.name] !== undefined) { if (!json_obj[this.name].push) { json_obj[this.name] = [json_obj[this.name]]; } json_obj[this.name].push(this.value || ''); } else { json_obj[this.name] = this.value || ''; } }); return json_obj; };
Humsen/web/web-mobile/WebContent/js/customize-sdk.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/js/customize-sdk.js", "repo_id": "Humsen", "token_count": 2086 }
32
/** * @author 何明胜 * * 2017年11月1日 */ /** 初始化 */ $(document).ready(function() { // 有效性校验 modifyEmailValidator(); //认证 if($('#btn_modifyEmailAuth').length > 0){ // 绑定发送验证码事件 $('#btn_sendValidateCode').click(sendAuthValidateCodeClick); //初始化下一步按钮 initNextStepBtn(); } //绑定 if($('#btn_modifyEmailBind').length > 0){ // 绑定发送验证码事件 $('#btn_sendValidateCode').click(sendBindValidateCodeClick); //初始化提交按钮 initSubmitBtn(); } }); /********************************************* 认证区 **********************************************/ /** * 初始化下一步按钮 * @returns */ function initNextStepBtn(){ var btnModifyEmailAuth = $('#btn_modifyEmailAuth'); btnModifyEmailAuth.attr('disabled', 'true'); //绑定邮箱和输入验证码监听 $('#txt_modifyEmail,#txt_validateCode2').on('input propertychange', function() { //点击下一步,先看表单是否合法 var $formModifyEmail = $('#form_modifyEmail').data('bootstrapValidator'); $formModifyEmail.validate(); if ($formModifyEmail.isValid()) { btnModifyEmailAuth.removeAttr('disabled'); btnModifyEmailAuth.addClass('btn-success'); } }); //下一步按钮点击事件 $('#btn_modifyEmailAuth').click(nextStepClick); } /** * 修改邮箱, 旧邮箱认证, 下一步点击事件 * @returns */ function nextStepClick(){ $.ajax({ url : '/userInfo/code.hms', async : true, type : 'POST', data : { type : 'auth_code_old_email', randomCode : $('#txt_validateCode2').val(), }, success : function(response) { if (response != 0) { $('#mainWindow').html(''); $.ajax( { url: 'modify_email1.html', //这里是静态页的地址 async : false, type: 'GET', //静态页用get方法,否则服务器会抛出405错误 success: function(data){ $('#mainWindow').html(data); } }); } else { $.confirm({ title : '验证失败', content : '请稍后再尝试', autoClose : 'ok|3000', type : 'red', buttons : { ok : { text : '确定', btnClass : 'btn-primary', } } }); } }, error : function(XMLHttpRequest, textStatus) { $.confirm({ title : '验证码校验发送失败', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); } }); } /** * 修改邮箱, 点击发送验证码事件 * @returns */ function sendAuthValidateCodeClick() { // 判断邮箱格式是否正确 var $emailValidate = $('#form_modifyEmail').data('bootstrapValidator'); $emailValidate.validateField('email'); var isEmailValid = $emailValidate.isValidField('email'); if (!isEmailValid) { return; } // 修改邮箱, 发送验证码到旧邮箱 $.ajax({ url : '/userInfo/code.hms', async : true,// 异步,启动倒计时 type : 'POST', data : { type : 'send_code_old_email', email : $('#txt_modifyEmail').val(), }, success : function(response) { if (response != 1) { $.confirm({ title : '验证码发送失败', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', } } }); } }, error : function(XMLHttpRequest, textStatus) { $.confirm({ title : '验证码发送失败', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); } }); // 60s倒计时 $.codeCountDown($('#btn_sendValidateCode')); } /********************************************* 绑定区 **********************************************/ /** * 初始化提交按钮 * @returns */ function initSubmitBtn(){ var btnModifyEmailBind= $('#btn_modifyEmailBind'); btnModifyEmailBind.attr('disabled', 'true'); //绑定邮箱和输入验证码监听 $('#txt_modifyEmail,#txt_validateCode2').on('input propertychange', function() { //点击下一步,先看表单是否合法 var $formModifyEmail = $('#form_modifyEmail').data('bootstrapValidator'); $formModifyEmail.validate(); if ($formModifyEmail.isValid()) { btnModifyEmailBind.removeAttr('disabled'); btnModifyEmailBind.addClass('btn-success'); } }); //提交按钮点击事件 $('#btn_modifyEmailBind').click(submitModifyEmailClick); } /** * 修改邮箱, 绑定新邮箱提交事件 * @returns */ function submitModifyEmailClick(){ $.ajax({ url : '/userInfo/code.hms', async : false,// 同步,会阻塞操作 type : 'POST',// PUT DELETE POST data : { type : 'auth_code_bind_email', randomCode : $('#txt_validateCode2').val(), userName : $.cookie('username'), email : $('#txt_modifyEmail').val(), }, success : function(response) { if (response != 0) { $.confirm({ title : '邮箱修改成功', content : '你的邮箱已成功修改为:' + $('#txt_modifyEmail').val(), autoClose : 'ok|4000', type : 'green', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); //清空修改区 $('#mainWindow').html(''); } else { $.confirm({ title : '验证失败', content : '请稍后再尝试', autoClose : 'ok|3000', type : 'red', buttons : { ok : { text : '确定', btnClass : 'btn-primary', } } }); } }, error : function(XMLHttpRequest, textStatus) { $.confirm({ title : '验证码校验发送失败', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); } }); } /** * 绑定新邮箱, 发送验证码 * @returns */ function sendBindValidateCodeClick(){ // 判断邮箱格式是否正确 var $emailValidate = $('#form_modifyEmail').data('bootstrapValidator'); $emailValidate.validateField('email'); var isEmailValid = $emailValidate.isValidField('email'); if (!isEmailValid) { return; } // 发送ajax请求 $.ajax({ url : '/userInfo/code.hms', async : true,// 异步,启动倒计时 type : 'POST', data : { type : 'send_code_bind_email', email : $('#txt_modifyEmail').val(), }, success : function(response) { if (response != 1) { $.confirm({ title : '验证码发送失败', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', } } }); } }, error : function(XMLHttpRequest, textStatus) { $.confirm({ title : '验证码发送失败', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); } }); // 60s倒计时 $.codeCountDown($('#btn_sendValidateCode')); } /********************************************* 公共区 **********************************************/ /** * 添加修改邮箱校验 * * @returns */ function modifyEmailValidator() { $('#form_modifyEmail') .bootstrapValidator( { message : '输入无效!', feedbackIcons : { valid : 'glyphicon glyphicon-ok', invalid : 'glyphicon glyphicon-remove', validating : 'glyphicon glyphicon-refresh' }, fields : { email : { message : '用户名无效!', validators : { notEmpty : { message : '邮箱不能为空!' }, regexp : { regexp : /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message : '邮箱格式不正确' } } }, validateCode : { message : '验证码无效!', validators : { notEmpty : { message : '验证码不能为空!' }, regexp : { regexp : /^\d{6}$/, message : '验证码为6位数字' } } } } }); }
Humsen/web/web-mobile/WebContent/js/personal_center/modify-email.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/js/personal_center/modify-email.js", "repo_id": "Humsen", "token_count": 4397 }
33
<link rel="stylesheet" href="/css/personal_center/modify-userinfo.css"> <!-- 修改用户信息脚本 --> <script src="/js/personal_center/modify-userinfo.js"></script> <form id="modifyForm" class="form-horizontal modify-userinfo-form"> <div class="form-group"> <label class="col-sm-4 control-label">头像</label> <div id="imgdiv" class="col-sm-2"> <img id="imgshow" src="" alt="" class="img-circle head-img-size" > </div> <input id="upimg" class="col-sm-4 up-img-hidden" type="file" accept="image/*" /> <button class="btn btn-default col-sm-4 btn-chang-head-img" id="changepic">更换头像</button> </div> <div class="form-group"> <label for="username" class="col-sm-4 control-label">用户名(用作登录)</label> <div class="col-sm-8"> <input type="text" class="form-control" id="username" name="userName" placeholder="用户名"> </div> </div> <div class="form-group"> <label for="txt_userNickName" class="col-sm-4 control-label">用户昵称(用作显示)</label> <div class="col-sm-8"> <input type="text" class="form-control" id="txt_userNickName" name="userNickName" placeholder="用户名"> </div> </div> <div class="form-group"> <label for="email" class="col-sm-4 control-label">邮箱</label> <div class="col-sm-6"> <input type="text" class="form-control" id="txt_userEmail" name="userEmail" placeholder="邮箱" disabled> </div> <div class="col-sm-2"> <button id="btn_goModifyEmail" class="btn btn-default">修改邮箱</button> </div> </div> <div class="form-group"> <label for="phone" class="col-sm-4 control-label">手机</label> <div class="col-sm-8"> <input type="text" class="form-control" id="phone" name="userPhone" placeholder="手机"> </div> </div> <div class="form-group"> <label for="age" class="col-sm-4 control-label">年龄</label> <div class="col-sm-8"> <input type="text" class="form-control" id="age" name="userAge" placeholder="年龄"> </div> </div> <div class="form-group"> <label for="address" class="col-sm-4 control-label">地址</label> <div class="col-sm-8"> <input type="text" class="form-control" id="address" name="userAddress" placeholder="地址"> </div> </div> <div class="form-group"> <div class="col-sm-offset-10 col-sm-2"> <a id="submitModify" class="btn btn-default" href="#" role="button">提交</a> </div> </div> <input type="hidden" name="userId" id="userid"> <input type="hidden" name="userHeadUrl" id="headurl"/> </form>
Humsen/web/web-mobile/WebContent/personal_center/modify_userinfo.html/0
{ "file_path": "Humsen/web/web-mobile/WebContent/personal_center/modify_userinfo.html", "repo_id": "Humsen", "token_count": 1093 }
34
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE /** * Tag-closer extension for CodeMirror. * * This extension adds an "autoCloseTags" option that can be set to * either true to get the default behavior, or an object to further * configure its behavior. * * These are supported options: * * `whenClosing` (default true) * Whether to autoclose when the '/' of a closing tag is typed. * `whenOpening` (default true) * Whether to autoclose the tag when the final '>' of an opening * tag is typed. * `dontCloseTags` (default is empty tags for HTML, none for XML) * An array of tag names that should not be autoclosed. * `indentTags` (default is block tags for HTML, none for XML) * An array of tag names that should, when opened, cause a * blank line to be added inside the tag, and the blank line and * closing line to be indented. * * See demos/closetag.html for a usage example. */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../fold/xml-fold")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../fold/xml-fold"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) { if (old != CodeMirror.Init && old) cm.removeKeyMap("autoCloseTags"); if (!val) return; var map = {name: "autoCloseTags"}; if (typeof val != "object" || val.whenClosing) map["'/'"] = function(cm) { return autoCloseSlash(cm); }; if (typeof val != "object" || val.whenOpening) map["'>'"] = function(cm) { return autoCloseGT(cm); }; cm.addKeyMap(map); }); var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]; var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"]; function autoCloseGT(cm) { if (cm.getOption("disableInput")) return CodeMirror.Pass; var ranges = cm.listSelections(), replacements = []; for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) return CodeMirror.Pass; var pos = ranges[i].head, tok = cm.getTokenAt(pos); var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; if (inner.mode.name != "xml" || !state.tagName) return CodeMirror.Pass; var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html"; var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose); var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent); var tagName = state.tagName; if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch); var lowerTagName = tagName.toLowerCase(); // Don't process the '>' at the end of an end-tag or self-closing tag if (!tagName || tok.type == "string" && (tok.end != pos.ch || !/[\"\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) || tok.type == "tag" && state.type == "closeTag" || tok.string.indexOf("/") == (tok.string.length - 1) || // match something like <someTagName /> dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 || closingTagExists(cm, tagName, pos, state, true)) return CodeMirror.Pass; var indent = indentTags && indexOf(indentTags, lowerTagName) > -1; replacements[i] = {indent: indent, text: ">" + (indent ? "\n\n" : "") + "</" + tagName + ">", newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)}; } for (var i = ranges.length - 1; i >= 0; i--) { var info = replacements[i]; cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, "+insert"); var sel = cm.listSelections().slice(0); sel[i] = {head: info.newPos, anchor: info.newPos}; cm.setSelections(sel); if (info.indent) { cm.indentLine(info.newPos.line, null, true); cm.indentLine(info.newPos.line + 1, null, true); } } } function autoCloseCurrent(cm, typingSlash) { var ranges = cm.listSelections(), replacements = []; var head = typingSlash ? "/" : "</"; for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) return CodeMirror.Pass; var pos = ranges[i].head, tok = cm.getTokenAt(pos); var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; if (typingSlash && (tok.type == "string" || tok.string.charAt(0) != "<" || tok.start != pos.ch - 1)) return CodeMirror.Pass; // Kludge to get around the fact that we are not in XML mode // when completing in JS/CSS snippet in htmlmixed mode. Does not // work for other XML embedded languages (there is no general // way to go from a mixed mode to its current XML state). if (inner.mode.name != "xml") { if (cm.getMode().name == "htmlmixed" && inner.mode.name == "javascript") replacements[i] = head + "script>"; else if (cm.getMode().name == "htmlmixed" && inner.mode.name == "css") replacements[i] = head + "style>"; else return CodeMirror.Pass; } else { if (!state.context || !state.context.tagName || closingTagExists(cm, state.context.tagName, pos, state)) return CodeMirror.Pass; replacements[i] = head + state.context.tagName + ">"; } } cm.replaceSelections(replacements); ranges = cm.listSelections(); for (var i = 0; i < ranges.length; i++) if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line) cm.indentLine(ranges[i].head.line); } function autoCloseSlash(cm) { if (cm.getOption("disableInput")) return CodeMirror.Pass; return autoCloseCurrent(cm, true); } CodeMirror.commands.closeTag = function(cm) { return autoCloseCurrent(cm); }; function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } // If xml-fold is loaded, we use its functionality to try and verify // whether a given tag is actually unclosed. function closingTagExists(cm, tagName, pos, state, newTag) { if (!CodeMirror.scanForClosingTag) return false; var end = Math.min(cm.lastLine() + 1, pos.line + 500); var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end); if (!nextClose || nextClose.tag != tagName) return false; var cx = state.context; // If the immediate wrapping context contains onCx instances of // the same tag, a closing tag only exists if there are at least // that many closing tags of that type following. for (var onCx = newTag ? 1 : 0; cx && cx.tagName == tagName; cx = cx.prev) ++onCx; pos = nextClose.to; for (var i = 1; i < onCx; i++) { var next = CodeMirror.scanForClosingTag(cm, pos, null, end); if (!next || next.tag != tagName) return false; pos = next.to; } return true; } });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/edit/closetag.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/edit/closetag.js", "repo_id": "Humsen", "token_count": 2973 }
35
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { var Pos = CodeMirror.Pos; function forEach(arr, f) { for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); } function arrayContains(arr, item) { if (!Array.prototype.indexOf) { var i = arr.length; while (i--) { if (arr[i] === item) { return true; } } return false; } return arr.indexOf(item) != -1; } function scriptHint(editor, keywords, getToken, options) { // Find the token at the cursor var cur = editor.getCursor(), token = getToken(editor, cur); if (/\b(?:string|comment)\b/.test(token.type)) return; token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; // If it's not a 'word-style' token, ignore the token. if (!/^[\w$_]*$/.test(token.string)) { token = {start: cur.ch, end: cur.ch, string: "", state: token.state, type: token.string == "." ? "property" : null}; } else if (token.end > cur.ch) { token.end = cur.ch; token.string = token.string.slice(0, cur.ch - token.start); } var tprop = token; // If it is a property, find out what it is a property of. while (tprop.type == "property") { tprop = getToken(editor, Pos(cur.line, tprop.start)); if (tprop.string != ".") return; tprop = getToken(editor, Pos(cur.line, tprop.start)); if (!context) var context = []; context.push(tprop); } return {list: getCompletions(token, context, keywords, options), from: Pos(cur.line, token.start), to: Pos(cur.line, token.end)}; } function javascriptHint(editor, options) { return scriptHint(editor, javascriptKeywords, function (e, cur) {return e.getTokenAt(cur);}, options); }; CodeMirror.registerHelper("hint", "javascript", javascriptHint); function getCoffeeScriptToken(editor, cur) { // This getToken, it is for coffeescript, imitates the behavior of // getTokenAt method in javascript.js, that is, returning "property" // type and treat "." as indepenent token. var token = editor.getTokenAt(cur); if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') { token.end = token.start; token.string = '.'; token.type = "property"; } else if (/^\.[\w$_]*$/.test(token.string)) { token.type = "property"; token.start++; token.string = token.string.replace(/\./, ''); } return token; } function coffeescriptHint(editor, options) { return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options); } CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint); var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " + "toUpperCase toLowerCase split concat match replace search").split(" "); var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " + "lastIndexOf every some filter forEach map reduce reduceRight ").split(" "); var funcProps = "prototype apply call bind".split(" "); var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " + "if in instanceof new null return switch throw true try typeof var void while with").split(" "); var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " + "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" "); function getCompletions(token, context, keywords, options) { var found = [], start = token.string, global = options && options.globalScope || window; function maybeAdd(str) { if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str); } function gatherCompletions(obj) { if (typeof obj == "string") forEach(stringProps, maybeAdd); else if (obj instanceof Array) forEach(arrayProps, maybeAdd); else if (obj instanceof Function) forEach(funcProps, maybeAdd); for (var name in obj) maybeAdd(name); } if (context && context.length) { // If this is a property, see if it belongs to some object we can // find in the current environment. var obj = context.pop(), base; if (obj.type && obj.type.indexOf("variable") === 0) { if (options && options.additionalContext) base = options.additionalContext[obj.string]; if (!options || options.useGlobalScope !== false) base = base || global[obj.string]; } else if (obj.type == "string") { base = ""; } else if (obj.type == "atom") { base = 1; } else if (obj.type == "function") { if (global.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') && (typeof global.jQuery == 'function')) base = global.jQuery(); else if (global._ != null && (obj.string == '_') && (typeof global._ == 'function')) base = global._(); } while (base != null && context.length) base = base[context.pop().string]; if (base != null) gatherCompletions(base); } else { // If not, just look in the global object and any local scope // (reading into JS mode internals to get at the local and global variables) for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name); for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name); if (!options || options.useGlobalScope !== false) gatherCompletions(global); forEach(keywords, maybeAdd); } return found; } });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/hint/javascript-hint.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/hint/javascript-hint.js", "repo_id": "Humsen", "token_count": 2355 }
36
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { CodeMirror.defineMode("markdown_with_stex", function(){ var inner = CodeMirror.getMode({}, "stex"); var outer = CodeMirror.getMode({}, "markdown"); var innerOptions = { open: '$', close: '$', mode: inner, delimStyle: 'delim', innerStyle: 'inner' }; return CodeMirror.multiplexingMode(outer, innerOptions); }); var mode = CodeMirror.getMode({}, "markdown_with_stex"); function MT(name) { test.mode( name, mode, Array.prototype.slice.call(arguments, 1), 'multiplexing'); } MT( "stexInsideMarkdown", "[strong **Equation:**] [delim $][inner&tag \\pi][delim $]"); })();
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/mode/multiplex_test.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/mode/multiplex_test.js", "repo_id": "Humsen", "token_count": 330 }
37
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // Because sometimes you need to style the cursor's line. // // Adds an option 'styleActiveLine' which, when enabled, gives the // active line's wrapping <div> the CSS class "CodeMirror-activeline", // and gives its background <div> the class "CodeMirror-activeline-background". (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 WRAP_CLASS = "CodeMirror-activeline"; var BACK_CLASS = "CodeMirror-activeline-background"; CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) { var prev = old && old != CodeMirror.Init; if (val && !prev) { cm.state.activeLines = []; updateActiveLines(cm, cm.listSelections()); cm.on("beforeSelectionChange", selectionChange); } else if (!val && prev) { cm.off("beforeSelectionChange", selectionChange); clearActiveLines(cm); delete cm.state.activeLines; } }); function clearActiveLines(cm) { for (var i = 0; i < cm.state.activeLines.length; i++) { cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS); cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS); } } function sameArray(a, b) { if (a.length != b.length) return false; for (var i = 0; i < a.length; i++) if (a[i] != b[i]) return false; return true; } function updateActiveLines(cm, ranges) { var active = []; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; if (!range.empty()) continue; var line = cm.getLineHandleVisualStart(range.head.line); if (active[active.length - 1] != line) active.push(line); } if (sameArray(cm.state.activeLines, active)) return; cm.operation(function() { clearActiveLines(cm); for (var i = 0; i < active.length; i++) { cm.addLineClass(active[i], "wrap", WRAP_CLASS); cm.addLineClass(active[i], "background", BACK_CLASS); } cm.state.activeLines = active; }); } function selectionChange(cm, sel) { updateActiveLines(cm, sel.ranges); } });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/selection/active-line.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/selection/active-line.js", "repo_id": "Humsen", "token_count": 922 }
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("ebnf", function (config) { var commentType = {slash: 0, parenthesis: 1}; var stateType = {comment: 0, _string: 1, characterClass: 2}; var bracesMode = null; if (config.bracesMode) bracesMode = CodeMirror.getMode(config, config.bracesMode); return { startState: function () { return { stringType: null, commentType: null, braced: 0, lhs: true, localState: null, stack: [], inDefinition: false }; }, token: function (stream, state) { if (!stream) return; //check for state changes if (state.stack.length === 0) { //strings if ((stream.peek() == '"') || (stream.peek() == "'")) { state.stringType = stream.peek(); stream.next(); // Skip quote state.stack.unshift(stateType._string); } else if (stream.match(/^\/\*/)) { //comments starting with /* state.stack.unshift(stateType.comment); state.commentType = commentType.slash; } else if (stream.match(/^\(\*/)) { //comments starting with (* state.stack.unshift(stateType.comment); state.commentType = commentType.parenthesis; } } //return state //stack has switch (state.stack[0]) { case stateType._string: while (state.stack[0] === stateType._string && !stream.eol()) { if (stream.peek() === state.stringType) { stream.next(); // Skip quote state.stack.shift(); // Clear flag } else if (stream.peek() === "\\") { stream.next(); stream.next(); } else { stream.match(/^.[^\\\"\']*/); } } return state.lhs ? "property string" : "string"; // Token style case stateType.comment: while (state.stack[0] === stateType.comment && !stream.eol()) { if (state.commentType === commentType.slash && stream.match(/\*\//)) { state.stack.shift(); // Clear flag state.commentType = null; } else if (state.commentType === commentType.parenthesis && stream.match(/\*\)/)) { state.stack.shift(); // Clear flag state.commentType = null; } else { stream.match(/^.[^\*]*/); } } return "comment"; case stateType.characterClass: while (state.stack[0] === stateType.characterClass && !stream.eol()) { if (!(stream.match(/^[^\]\\]+/) || stream.match(/^\\./))) { state.stack.shift(); } } return "operator"; } var peek = stream.peek(); if (bracesMode !== null && (state.braced || peek === "{")) { if (state.localState === null) state.localState = bracesMode.startState(); var token = bracesMode.token(stream, state.localState), text = stream.current(); if (!token) { for (var i = 0; i < text.length; i++) { if (text[i] === "{") { if (state.braced === 0) { token = "matchingbracket"; } state.braced++; } else if (text[i] === "}") { state.braced--; if (state.braced === 0) { token = "matchingbracket"; } } } } return token; } //no stack switch (peek) { case "[": stream.next(); state.stack.unshift(stateType.characterClass); return "bracket"; case ":": case "|": case ";": stream.next(); return "operator"; case "%": if (stream.match("%%")) { return "header"; } else if (stream.match(/[%][A-Za-z]+/)) { return "keyword"; } else if (stream.match(/[%][}]/)) { return "matchingbracket"; } break; case "/": if (stream.match(/[\/][A-Za-z]+/)) { return "keyword"; } case "\\": if (stream.match(/[\][a-z]+/)) { return "string-2"; } case ".": if (stream.match(".")) { return "atom"; } case "*": case "-": case "+": case "^": if (stream.match(peek)) { return "atom"; } case "$": if (stream.match("$$")) { return "builtin"; } else if (stream.match(/[$][0-9]+/)) { return "variable-3"; } case "<": if (stream.match(/<<[a-zA-Z_]+>>/)) { return "builtin"; } } if (stream.match(/^\/\//)) { stream.skipToEnd(); return "comment"; } else if (stream.match(/return/)) { return "operator"; } else if (stream.match(/^[a-zA-Z_][a-zA-Z0-9_]*/)) { if (stream.match(/(?=[\(.])/)) { return "variable"; } else if (stream.match(/(?=[\s\n]*[:=])/)) { return "def"; } return "variable-2"; } else if (["[", "]", "(", ")"].indexOf(stream.peek()) != -1) { stream.next(); return "bracket"; } else if (!stream.eatSpace()) { stream.next(); } return null; } }; }); CodeMirror.defineMIME("text/x-ebnf", "ebnf"); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/ebnf/ebnf.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/ebnf/ebnf.js", "repo_id": "Humsen", "token_count": 3156 }
39
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("htmlembedded", function(config, parserConfig) { //config settings var scriptStartRegex = parserConfig.scriptStartRegex || /^<%/i, scriptEndRegex = parserConfig.scriptEndRegex || /^%>/i; //inner modes var scriptingMode, htmlMixedMode; //tokenizer when in html mode function htmlDispatch(stream, state) { if (stream.match(scriptStartRegex, false)) { state.token=scriptingDispatch; return scriptingMode.token(stream, state.scriptState); } else return htmlMixedMode.token(stream, state.htmlState); } //tokenizer when in scripting mode function scriptingDispatch(stream, state) { if (stream.match(scriptEndRegex, false)) { state.token=htmlDispatch; return htmlMixedMode.token(stream, state.htmlState); } else return scriptingMode.token(stream, state.scriptState); } return { startState: function() { scriptingMode = scriptingMode || CodeMirror.getMode(config, parserConfig.scriptingModeSpec); htmlMixedMode = htmlMixedMode || CodeMirror.getMode(config, "htmlmixed"); return { token : parserConfig.startOpen ? scriptingDispatch : htmlDispatch, htmlState : CodeMirror.startState(htmlMixedMode), scriptState : CodeMirror.startState(scriptingMode) }; }, token: function(stream, state) { return state.token(stream, state); }, indent: function(state, textAfter) { if (state.token == htmlDispatch) return htmlMixedMode.indent(state.htmlState, textAfter); else if (scriptingMode.indent) return scriptingMode.indent(state.scriptState, textAfter); }, copyState: function(state) { return { token : state.token, htmlState : CodeMirror.copyState(htmlMixedMode, state.htmlState), scriptState : CodeMirror.copyState(scriptingMode, state.scriptState) }; }, innerMode: function(state) { if (state.token == scriptingDispatch) return {state: state.scriptState, mode: scriptingMode}; else return {state: state.htmlState, mode: htmlMixedMode}; } }; }, "htmlmixed"); CodeMirror.defineMIME("application/x-ejs", { name: "htmlembedded", scriptingModeSpec:"javascript"}); CodeMirror.defineMIME("application/x-aspx", { name: "htmlembedded", scriptingModeSpec:"text/x-csharp"}); CodeMirror.defineMIME("application/x-jsp", { name: "htmlembedded", scriptingModeSpec:"text/x-java"}); CodeMirror.defineMIME("application/x-erb", { name: "htmlembedded", scriptingModeSpec:"ruby"}); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/htmlembedded/htmlembedded.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/htmlembedded/htmlembedded.js", "repo_id": "Humsen", "token_count": 1147 }
40
// 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('mllike', function(_config, parserConfig) { var words = { 'let': 'keyword', 'rec': 'keyword', 'in': 'keyword', 'of': 'keyword', 'and': 'keyword', 'if': 'keyword', 'then': 'keyword', 'else': 'keyword', 'for': 'keyword', 'to': 'keyword', 'while': 'keyword', 'do': 'keyword', 'done': 'keyword', 'fun': 'keyword', 'function': 'keyword', 'val': 'keyword', 'type': 'keyword', 'mutable': 'keyword', 'match': 'keyword', 'with': 'keyword', 'try': 'keyword', 'open': 'builtin', 'ignore': 'builtin', 'begin': 'keyword', 'end': 'keyword' }; var extraWords = parserConfig.extraWords || {}; for (var prop in extraWords) { if (extraWords.hasOwnProperty(prop)) { words[prop] = parserConfig.extraWords[prop]; } } function tokenBase(stream, state) { var ch = stream.next(); if (ch === '"') { state.tokenize = tokenString; return state.tokenize(stream, state); } if (ch === '(') { if (stream.eat('*')) { state.commentLevel++; state.tokenize = tokenComment; return state.tokenize(stream, state); } } if (ch === '~') { stream.eatWhile(/\w/); return 'variable-2'; } if (ch === '`') { stream.eatWhile(/\w/); return 'quote'; } if (ch === '/' && parserConfig.slashComments && stream.eat('/')) { stream.skipToEnd(); return 'comment'; } if (/\d/.test(ch)) { stream.eatWhile(/[\d]/); if (stream.eat('.')) { stream.eatWhile(/[\d]/); } return 'number'; } if ( /[+\-*&%=<>!?|]/.test(ch)) { return 'operator'; } stream.eatWhile(/\w/); var cur = stream.current(); return words[cur] || 'variable'; } function tokenString(stream, state) { var next, end = false, escaped = false; while ((next = stream.next()) != null) { if (next === '"' && !escaped) { end = true; break; } escaped = !escaped && next === '\\'; } if (end && !escaped) { state.tokenize = tokenBase; } return 'string'; }; function tokenComment(stream, state) { var prev, next; while(state.commentLevel > 0 && (next = stream.next()) != null) { if (prev === '(' && next === '*') state.commentLevel++; if (prev === '*' && next === ')') state.commentLevel--; prev = next; } if (state.commentLevel <= 0) { state.tokenize = tokenBase; } return 'comment'; } return { startState: function() {return {tokenize: tokenBase, commentLevel: 0};}, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); }, blockCommentStart: "(*", blockCommentEnd: "*)", lineComment: parserConfig.slashComments ? "//" : null }; }); CodeMirror.defineMIME('text/x-ocaml', { name: 'mllike', extraWords: { 'succ': 'keyword', 'trace': 'builtin', 'exit': 'builtin', 'print_string': 'builtin', 'print_endline': 'builtin', 'true': 'atom', 'false': 'atom', 'raise': 'keyword' } }); CodeMirror.defineMIME('text/x-fsharp', { name: 'mllike', extraWords: { 'abstract': 'keyword', 'as': 'keyword', 'assert': 'keyword', 'base': 'keyword', 'class': 'keyword', 'default': 'keyword', 'delegate': 'keyword', 'downcast': 'keyword', 'downto': 'keyword', 'elif': 'keyword', 'exception': 'keyword', 'extern': 'keyword', 'finally': 'keyword', 'global': 'keyword', 'inherit': 'keyword', 'inline': 'keyword', 'interface': 'keyword', 'internal': 'keyword', 'lazy': 'keyword', 'let!': 'keyword', 'member' : 'keyword', 'module': 'keyword', 'namespace': 'keyword', 'new': 'keyword', 'null': 'keyword', 'override': 'keyword', 'private': 'keyword', 'public': 'keyword', 'return': 'keyword', 'return!': 'keyword', 'select': 'keyword', 'static': 'keyword', 'struct': 'keyword', 'upcast': 'keyword', 'use': 'keyword', 'use!': 'keyword', 'val': 'keyword', 'when': 'keyword', 'yield': 'keyword', 'yield!': 'keyword', 'List': 'builtin', 'Seq': 'builtin', 'Map': 'builtin', 'Set': 'builtin', 'int': 'builtin', 'string': 'builtin', 'raise': 'builtin', 'failwith': 'builtin', 'not': 'builtin', 'true': 'builtin', 'false': 'builtin' }, slashComments: true }); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/mllike/mllike.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/mllike/mllike.js", "repo_id": "Humsen", "token_count": 2189 }
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("rpm-changes", function() { var headerSeperator = /^-+$/; var headerLine = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ?\d{1,2} \d{2}:\d{2}(:\d{2})? [A-Z]{3,4} \d{4} - /; var simpleEmail = /^[\w+.-]+@[\w.-]+/; return { token: function(stream) { if (stream.sol()) { if (stream.match(headerSeperator)) { return 'tag'; } if (stream.match(headerLine)) { return 'tag'; } } if (stream.match(simpleEmail)) { return 'string'; } stream.next(); return null; } }; }); CodeMirror.defineMIME("text/x-rpm-changes", "rpm-changes"); // Quick and dirty spec file highlighting CodeMirror.defineMode("rpm-spec", function() { var arch = /^(i386|i586|i686|x86_64|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/; var preamble = /^(Name|Version|Release|License|Summary|Url|Group|Source|BuildArch|BuildRequires|BuildRoot|AutoReqProv|Provides|Requires(\(\w+\))?|Obsoletes|Conflicts|Recommends|Source\d*|Patch\d*|ExclusiveArch|NoSource|Supplements):/; var section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preinstall|preun|postinstall|postun|pre|post|triggerin|triggerun|pretrans|posttrans|verifyscript|check|triggerpostun|triggerprein|trigger)/; var control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros var control_flow_simple = /^%(else|endif)/; // rpm control flow macros var operators = /^(\!|\?|\<\=|\<|\>\=|\>|\=\=|\&\&|\|\|)/; // operators in control flow macros return { startState: function () { return { controlFlow: false, macroParameters: false, section: false }; }, token: function (stream, state) { var ch = stream.peek(); if (ch == "#") { stream.skipToEnd(); return "comment"; } if (stream.sol()) { if (stream.match(preamble)) { return "preamble"; } if (stream.match(section)) { return "section"; } } if (stream.match(/^\$\w+/)) { return "def"; } // Variables like '$RPM_BUILD_ROOT' if (stream.match(/^\$\{\w+\}/)) { return "def"; } // Variables like '${RPM_BUILD_ROOT}' if (stream.match(control_flow_simple)) { return "keyword"; } if (stream.match(control_flow_complex)) { state.controlFlow = true; return "keyword"; } if (state.controlFlow) { if (stream.match(operators)) { return "operator"; } if (stream.match(/^(\d+)/)) { return "number"; } if (stream.eol()) { state.controlFlow = false; } } if (stream.match(arch)) { return "number"; } // Macros like '%make_install' or '%attr(0775,root,root)' if (stream.match(/^%[\w]+/)) { if (stream.match(/^\(/)) { state.macroParameters = true; } return "macro"; } if (state.macroParameters) { if (stream.match(/^\d+/)) { return "number";} if (stream.match(/^\)/)) { state.macroParameters = false; return "macro"; } } if (stream.match(/^%\{\??[\w \-]+\}/)) { return "macro"; } // Macros like '%{defined fedora}' //TODO: Include bash script sub-parser (CodeMirror supports that) stream.next(); return null; } }; }); CodeMirror.defineMIME("text/x-rpm-spec", "rpm-spec"); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/rpm/rpm.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/rpm/rpm.js", "repo_id": "Humsen", "token_count": 1632 }
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"), require("../htmlmixed/htmlmixed")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var indentingTags = ["template", "literal", "msg", "fallbackmsg", "let", "if", "elseif", "else", "switch", "case", "default", "foreach", "ifempty", "for", "call", "param", "deltemplate", "delcall", "log"]; CodeMirror.defineMode("soy", function(config) { var textMode = CodeMirror.getMode(config, "text/plain"); var modes = { html: CodeMirror.getMode(config, {name: "text/html", multilineTagIndentFactor: 2, multilineTagIndentPastTag: false}), attributes: textMode, text: textMode, uri: textMode, css: CodeMirror.getMode(config, "text/css"), js: CodeMirror.getMode(config, {name: "text/javascript", statementIndent: 2 * config.indentUnit}) }; function last(array) { return array[array.length - 1]; } function tokenUntil(stream, state, untilRegExp) { var oldString = stream.string; var match = untilRegExp.exec(oldString.substr(stream.pos)); if (match) { // We don't use backUp because it backs up just the position, not the state. // This uses an undocumented API. stream.string = oldString.substr(0, stream.pos + match.index); } var result = stream.hideFirstChars(state.indent, function() { return state.localMode.token(stream, state.localState); }); stream.string = oldString; return result; } return { startState: function() { return { kind: [], kindTag: [], soyState: [], indent: 0, localMode: modes.html, localState: CodeMirror.startState(modes.html) }; }, copyState: function(state) { return { tag: state.tag, // Last seen Soy tag. kind: state.kind.concat([]), // Values of kind="" attributes. kindTag: state.kindTag.concat([]), // Opened tags with kind="" attributes. soyState: state.soyState.concat([]), indent: state.indent, // Indentation of the following line. localMode: state.localMode, localState: CodeMirror.copyState(state.localMode, state.localState) }; }, token: function(stream, state) { var match; switch (last(state.soyState)) { case "comment": if (stream.match(/^.*?\*\//)) { state.soyState.pop(); } else { stream.skipToEnd(); } return "comment"; case "variable": if (stream.match(/^}/)) { state.indent -= 2 * config.indentUnit; state.soyState.pop(); return "variable-2"; } stream.next(); return null; case "tag": if (stream.match(/^\/?}/)) { if (state.tag == "/template" || state.tag == "/deltemplate") state.indent = 0; else state.indent -= (stream.current() == "/}" || indentingTags.indexOf(state.tag) == -1 ? 2 : 1) * config.indentUnit; state.soyState.pop(); return "keyword"; } else if (stream.match(/^(\w+)(?==)/)) { if (stream.current() == "kind" && (match = stream.match(/^="([^"]+)/, false))) { var kind = match[1]; state.kind.push(kind); state.kindTag.push(state.tag); state.localMode = modes[kind] || modes.html; state.localState = CodeMirror.startState(state.localMode); } return "attribute"; } else if (stream.match(/^"/)) { state.soyState.push("string"); return "string"; } stream.next(); return null; case "literal": if (stream.match(/^(?=\{\/literal})/)) { state.indent -= config.indentUnit; state.soyState.pop(); return this.token(stream, state); } return tokenUntil(stream, state, /\{\/literal}/); case "string": if (stream.match(/^.*?"/)) { state.soyState.pop(); } else { stream.skipToEnd(); } return "string"; } if (stream.match(/^\/\*/)) { state.soyState.push("comment"); return "comment"; } else if (stream.match(stream.sol() ? /^\s*\/\/.*/ : /^\s+\/\/.*/)) { return "comment"; } else if (stream.match(/^\{\$\w*/)) { state.indent += 2 * config.indentUnit; state.soyState.push("variable"); return "variable-2"; } else if (stream.match(/^\{literal}/)) { state.indent += config.indentUnit; state.soyState.push("literal"); return "keyword"; } else if (match = stream.match(/^\{([\/@\\]?\w*)/)) { if (match[1] != "/switch") state.indent += (/^(\/|(else|elseif|case|default)$)/.test(match[1]) && state.tag != "switch" ? 1 : 2) * config.indentUnit; state.tag = match[1]; if (state.tag == "/" + last(state.kindTag)) { // We found the tag that opened the current kind="". state.kind.pop(); state.kindTag.pop(); state.localMode = modes[last(state.kind)] || modes.html; state.localState = CodeMirror.startState(state.localMode); } state.soyState.push("tag"); return "keyword"; } return tokenUntil(stream, state, /\{|\s+\/\/|\/\*/); }, indent: function(state, textAfter) { var indent = state.indent, top = last(state.soyState); if (top == "comment") return CodeMirror.Pass; if (top == "literal") { if (/^\{\/literal}/.test(textAfter)) indent -= config.indentUnit; } else { if (/^\s*\{\/(template|deltemplate)\b/.test(textAfter)) return 0; if (/^\{(\/|(fallbackmsg|elseif|else|ifempty)\b)/.test(textAfter)) indent -= config.indentUnit; if (state.tag != "switch" && /^\{(case|default)\b/.test(textAfter)) indent -= config.indentUnit; if (/^\{\/switch\b/.test(textAfter)) indent -= config.indentUnit; } if (indent && state.localMode.indent) indent += state.localMode.indent(state.localState, textAfter); return indent; }, innerMode: function(state) { if (state.soyState.length && last(state.soyState) != "literal") return null; else return {state: state.localState, mode: state.localMode}; }, electricInput: /^\s*\{(\/|\/template|\/deltemplate|\/switch|fallbackmsg|elseif|else|case|default|ifempty|\/literal\})$/, lineComment: "//", blockCommentStart: "/*", blockCommentEnd: "*/", blockCommentContinue: " * ", fold: "indent" }; }, "htmlmixed"); CodeMirror.registerHelper("hintWords", "soy", indentingTags.concat( ["delpackage", "namespace", "alias", "print", "css", "debugger"])); CodeMirror.defineMIME("text/x-soy", "soy"); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/soy/soy.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/soy/soy.js", "repo_id": "Humsen", "token_count": 3558 }
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("turtle", function(config) { var indentUnit = config.indentUnit; var curPunc; function wordRegexp(words) { return new RegExp("^(?:" + words.join("|") + ")$", "i"); } var ops = wordRegexp([]); var keywords = wordRegexp(["@prefix", "@base", "a"]); var operatorChars = /[*+\-<>=&|]/; function tokenBase(stream, state) { var ch = stream.next(); curPunc = null; if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) { stream.match(/^[^\s\u00a0>]*>?/); return "atom"; } else if (ch == "\"" || ch == "'") { state.tokenize = tokenLiteral(ch); return state.tokenize(stream, state); } else if (/[{}\(\),\.;\[\]]/.test(ch)) { curPunc = ch; return null; } else if (ch == "#") { stream.skipToEnd(); return "comment"; } else if (operatorChars.test(ch)) { stream.eatWhile(operatorChars); return null; } else if (ch == ":") { return "operator"; } else { stream.eatWhile(/[_\w\d]/); if(stream.peek() == ":") { return "variable-3"; } else { var word = stream.current(); if(keywords.test(word)) { return "meta"; } if(ch >= "A" && ch <= "Z") { return "comment"; } else { return "keyword"; } } var word = stream.current(); if (ops.test(word)) return null; else if (keywords.test(word)) return "meta"; else return "variable"; } } function tokenLiteral(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { state.tokenize = tokenBase; break; } escaped = !escaped && ch == "\\"; } return "string"; }; } function pushContext(state, type, col) { state.context = {prev: state.context, indent: state.indent, col: col, type: type}; } function popContext(state) { state.indent = state.context.indent; state.context = state.context.prev; } return { startState: function() { return {tokenize: tokenBase, context: null, indent: 0, col: 0}; }, token: function(stream, state) { if (stream.sol()) { if (state.context && state.context.align == null) state.context.align = false; state.indent = stream.indentation(); } if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") { state.context.align = true; } if (curPunc == "(") pushContext(state, ")", stream.column()); else if (curPunc == "[") pushContext(state, "]", stream.column()); else if (curPunc == "{") pushContext(state, "}", stream.column()); else if (/[\]\}\)]/.test(curPunc)) { while (state.context && state.context.type == "pattern") popContext(state); if (state.context && curPunc == state.context.type) popContext(state); } else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state); else if (/atom|string|variable/.test(style) && state.context) { if (/[\}\]]/.test(state.context.type)) pushContext(state, "pattern", stream.column()); else if (state.context.type == "pattern" && !state.context.align) { state.context.align = true; state.context.col = stream.column(); } } return style; }, indent: function(state, textAfter) { var firstChar = textAfter && textAfter.charAt(0); var context = state.context; if (/[\]\}]/.test(firstChar)) while (context && context.type == "pattern") context = context.prev; var closing = context && firstChar == context.type; if (!context) return 0; else if (context.type == "pattern") return context.col; else if (context.align) return context.col + (closing ? 0 : 1); else return context.indent + (closing ? 0 : indentUnit); }, lineComment: "#" }; }); CodeMirror.defineMIME("text/turtle", "turtle"); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/turtle/turtle.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/turtle/turtle.js", "repo_id": "Humsen", "token_count": 2126 }
44
.cm-s-ambiance.CodeMirror { -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; }
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/ambiance-mobile.css/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/ambiance-mobile.css", "repo_id": "Humsen", "token_count": 46 }
45
/* neo theme for codemirror */ /* Color scheme */ .cm-s-neo.CodeMirror { background-color:#ffffff; color:#2e383c; line-height:1.4375; } .cm-s-neo .cm-comment {color:#75787b} .cm-s-neo .cm-keyword, .cm-s-neo .cm-property {color:#1d75b3} .cm-s-neo .cm-atom,.cm-s-neo .cm-number {color:#75438a} .cm-s-neo .cm-node,.cm-s-neo .cm-tag {color:#9c3328} .cm-s-neo .cm-string {color:#b35e14} .cm-s-neo .cm-variable,.cm-s-neo .cm-qualifier {color:#047d65} /* Editor styling */ .cm-s-neo pre { padding:0; } .cm-s-neo .CodeMirror-gutters { border:none; border-right:10px solid transparent; background-color:transparent; } .cm-s-neo .CodeMirror-linenumber { padding:0; color:#e0e2e5; } .cm-s-neo .CodeMirror-guttermarker { color: #1d75b3; } .cm-s-neo .CodeMirror-guttermarker-subtle { color: #e0e2e5; } .cm-s-neo div.CodeMirror-cursor { width: auto; border: 0; background: rgba(155,157,162,0.37); z-index: 1; }
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/neo.css/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/neo.css", "repo_id": "Humsen", "token_count": 451 }
46
##### Markdown语法教程 (Markdown syntax tutorial) - [Markdown Syntax](http://daringfireball.net/projects/markdown/syntax/ "Markdown Syntax") - [Mastering Markdown](https://guides.github.com/features/mastering-markdown/ "Mastering Markdown") - [Markdown Basics](https://help.github.com/articles/markdown-basics/ "Markdown Basics") - [GitHub Flavored Markdown](https://help.github.com/articles/github-flavored-markdown/ "GitHub Flavored Markdown") - [Markdown 语法说明(简体中文)](http://www.markdown.cn/ "Markdown 语法说明(简体中文)") - [Markdown 語法說明(繁體中文)](http://markdown.tw/ "Markdown 語法說明(繁體中文)") ##### 键盘快捷键 (Keyboard shortcuts) > If Editor.md code editor is on focus, you can use keyboard shortcuts. | Keyboard shortcuts (键盘快捷键) | 说明 | Description | | :---------------------------------------------- |:--------------------------------- | :------------------------------------------------- | | F9 | 切换实时预览 | Switch watch/unwatch | | F10 | 全屏HTML预览(按 Shift + ESC 退出) | Full preview HTML (Press Shift + ESC exit) | | F11 | 切换全屏状态 | Switch fullscreen (Press ESC exit) | | Ctrl + 1~6 / Command + 1~6 | 插入标题1~6 | Insert heading 1~6 | | Ctrl + A / Command + A | 全选 | Select all | | Ctrl + B / Command + B | 插入粗体 | Insert bold | | Ctrl + D / Command + D | 插入日期时间 | Insert datetime | | Ctrl + E / Command + E | 插入Emoji符号 | Insert &#58;emoji&#58; | | Ctrl + F / Command + F | 查找/搜索 | Start searching | | Ctrl + G / Command + G | 切换到下一个搜索结果项 | Find next search results | | Ctrl + H / Command + H | 插入水平线 | Insert horizontal rule | | Ctrl + I / Command + I | 插入斜体 | Insert italic | | Ctrl + K / Command + K | 插入行内代码 | Insert inline code | | Ctrl + L / Command + L | 插入链接 | Insert link | | Ctrl + U / Command + U | 插入无序列表 | Insert unordered list | | Ctrl + Q | 代码折叠切换 | Switch code fold | | Ctrl + Z / Command + Z | 撤销 | Undo | | Ctrl + Y / Command + Y | 重做 | Redo | | Ctrl + Shift + A | 插入@链接 | Insert &#64;link | | Ctrl + Shift + C | 插入行内代码 | Insert inline code | | Ctrl + Shift + E | 打开插入Emoji表情对话框 | Open emoji dialog | | Ctrl + Shift + F / Command + Option + F | 替换 | Replace | | Ctrl + Shift + G / Shift + Command + G | 切换到上一个搜索结果项 | Find previous search results | | Ctrl + Shift + H | 打开HTML实体字符对话框 | Open HTML Entities dialog | | Ctrl + Shift + I | 插入图片 | Insert image &#33;[]&#40;&#41; | | Ctrl + Shift + K | 插入TeX(KaTeX)公式符号 | Insert TeX(KaTeX) symbol &#36;&#36;TeX&#36;&#36; | | Ctrl + Shift + L | 打开插入链接对话框 | Open link dialog | | Ctrl + Shift + O | 插入有序列表 | Insert ordered list | | Ctrl + Shift + P | 打开插入PRE对话框 | Open Preformatted text dialog | | Ctrl + Shift + Q | 插入引用 | Insert blockquotes | | Ctrl + Shift + R / Shift + Command + Option + F | 全部替换 | Replace all | | Ctrl + Shift + S | 插入删除线 | Insert strikethrough | | Ctrl + Shift + T | 打开插入表格对话框 | Open table dialog | | Ctrl + Shift + U | 将所选文字转成大写 | Selection text convert to uppercase | | Shift + Alt + C | 插入```代码 | Insert code blocks (```) | | Shift + Alt + H | 打开使用帮助对话框 | Open help dialog | | Shift + Alt + L | 将所选文本转成小写 | Selection text convert to lowercase | | Shift + Alt + P | 插入分页符 | Insert page break | | Alt + L | 将所选文本转成小写 | Selection text convert to lowercase | | Shift + Alt + U | 将所选的每个单词的首字母转成大写 | Selection words first letter convert to Uppercase | | Ctrl + Shift + Alt + C | 打开插入代码块对话框层 | Open code blocks dialog | | Ctrl + Shift + Alt + I | 打开插入图片对话框层 | Open image dialog | | Ctrl + Shift + Alt + U | 将所选文本的第一个首字母转成大写 | Selection text first letter convert to uppercase | | Ctrl + Alt + G | 跳转到指定的行 | Goto line | ##### Emoji表情参考 (Emoji reference) - [Github emoji](http://www.emoji-cheat-sheet.com/ "Github emoji") - [Twitter Emoji \(Twemoji\)](http://twitter.github.io/twemoji/preview.html "Twitter Emoji \(Twemoji\)") - [FontAwesome icons emoji](http://fortawesome.github.io/Font-Awesome/icons/ "FontAwesome icons emoji") ##### 流程图参考 (Flowchart reference) [http://adrai.github.io/flowchart.js/](http://adrai.github.io/flowchart.js/) ##### 时序图参考 (SequenceDiagram reference) [http://bramp.github.io/js-sequence-diagrams/](http://bramp.github.io/js-sequence-diagrams/) ##### TeX/LaTeX reference [http://meta.wikimedia.org/wiki/Help:Formula](http://meta.wikimedia.org/wiki/Help:Formula)
Humsen/web/web-mobile/WebContent/plugins/editormd/plugins/help-dialog/help.md/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/plugins/help-dialog/help.md", "repo_id": "Humsen", "token_count": 5464 }
47
(function ($) { /** * Arabic language package * Translated by @Arkni */ $.fn.bootstrapValidator.i18n = $.extend(true, $.fn.bootstrapValidator.i18n, { base64: { 'default': 'الرجاء إدخال قيمة مشفرة طبقا للقاعدة 64.' }, between: { 'default': 'الرجاء إدخال قيمة بين %s و %s .', notInclusive: 'الرجاء إدخال قيمة بين %s و %s بدقة.' }, callback: { 'default': 'الرجاء إدخال قيمة صالحة.' }, choice: { 'default': 'الرجاء إدخال قيمة صالحة.', less: 'الرجاء اختيار %s خيارات كحد أدنى.', more: 'الرجاء اختيار %s خيارات كحد أقصى.', between: 'الرجاء إختيار %s-%s خيارات.' }, color: { 'default': 'الرجاء إدخال رمز لون صالح.' }, creditCard: { 'default': 'الرجاء إدخال رقم بطاقة إئتمان صحيح.' }, cusip: { 'default': 'الرجاء إدخال رقم CUSIP صالح.' }, cvv: { 'default': 'الرجاء إدخال رقم CVV صالح.' }, date: { 'default': 'الرجاء إدخال تاريخ صالح.', min: 'الرجاء إدخال تاريخ بعد %s.', max: 'الرجاء إدخال تاريخ قبل %s.', range: 'الرجاء إدخال تاريخ في المجال %s - %s.' }, different: { 'default': 'الرجاء إدخال قيمة مختلفة.' }, digits: { 'default': 'الرجاء إدخال الأرقام فقط.' }, ean: { 'default': 'الرجاء إدخال رقم EAN صالح.' }, emailAddress: { 'default': 'الرجاء إدخال بريد إلكتروني صحيح.' }, file: { 'default': 'الرجاء إختيار ملف صالح.' }, greaterThan: { 'default': 'الرجاء إدخال قيمة أكبر من أو تساوي %s.', notInclusive: 'الرجاء إدخال قيمة أكبر من %s.' }, grid: { 'default': 'الرجاء إدخال رقم GRid صالح.' }, hex: { 'default': 'الرجاء إدخال رقم ست عشري صالح.' }, hexColor: { 'default': 'الرجاء إدخال رمز لون صالح.' }, iban: { 'default': 'الرجاء إدخال رقم IBAN صالح.', countryNotSupported: 'البلد ذو الرمز %s غير معتمد.', country: 'الرجاء إدخال رقم IBAN صالح في %s.', countries: { AD: 'أندورا', AE: 'الإمارات العربية المتحدة', AL: 'ألبانيا', AO: 'أنغولا', AT: 'النمسا', AZ: 'أذربيجان', BA: 'البوسنة والهرسك', BE: 'بلجيكا', BF: 'بوركينا فاسو', BG: 'بلغاريا', BH: 'البحرين', BI: 'بوروندي', BJ: 'بنين', BR: 'البرازيل', CH: 'سويسرا', CI: 'ساحل العاج', CM: 'الكاميرون', CR: 'كوستاريكا', CV: 'الرأس الأخضر', CY: 'قبرص', CZ: 'التشيك', DE: 'ألمانيا', DK: 'الدنمارك', DO: 'جمهورية الدومينيكان', DZ: 'الجزائر', EE: 'إستونيا', ES: 'إسبانيا', FI: 'فنلندا', FO: 'جزر فارو', FR: 'فرنسا', GB: 'المملكة المتحدة', GE: 'جورجيا', GI: 'جبل طارق', GL: 'جرينلاند', GR: 'اليونان', GT: 'غواتيمالا', HR: 'كرواتيا', HU: 'المجر', IE: 'أيرلندا', IL: 'إسرائيل', IR: 'إيران', IS: 'آيسلندا', IT: 'إيطاليا', JO: 'الأردن', KW: 'الكويت', KZ: 'كازاخستان', LB: 'لبنان', LI: 'ليختنشتاين', LT: 'ليتوانيا', LU: 'لوكسمبورغ', LV: 'لاتفيا', MC: 'موناكو', MD: 'مولدوفا', ME: 'الجبل الأسود', MG: 'مدغشقر', MK: 'جمهورية مقدونيا', ML: 'مالي', MR: 'موريتانيا', MT: 'مالطا', MU: 'موريشيوس', MZ: 'موزمبيق', NL: 'هولندا', NO: 'النرويج', PK: 'باكستان', PL: 'بولندا', PS: 'فلسطين', PT: 'البرتغال', QA: 'قطر', RO: 'رومانيا', RS: 'صربيا', SA: 'المملكة العربية السعودية', SE: 'السويد', SI: 'سلوفينيا', SK: 'سلوفاكيا', SM: 'سان مارينو', SN: 'السنغال', TN: 'تونس', TR: 'تركيا', VG: 'جزر العذراء البريطانية' } }, id: { 'default': 'الرجاء إدخال رقم هوية صالحة.', countryNotSupported: 'البلد ذو الرمز %s غير معتمد.', country: 'الرجاء إدخال رقم تعريف صالح في %s.', countries: { BA: 'البوسنة والهرسك', BG: 'بلغاريا', BR: 'البرازيل', CH: 'سويسرا', CL: 'تشيلي', CN: 'الصين', CZ: 'التشيك', DK: 'الدنمارك', EE: 'إستونيا', ES: 'إسبانيا', FI: 'فنلندا', HR: 'كرواتيا', IE: 'أيرلندا', IS: 'آيسلندا', LT: 'ليتوانيا', LV: 'لاتفيا', ME: 'الجبل الأسود', MK: 'جمهورية مقدونيا', NL: 'هولندا', RO: 'رومانيا', RS: 'صربيا', SE: 'السويد', SI: 'سلوفينيا', SK: 'سلوفاكيا', SM: 'سان مارينو', TH: 'تايلاند', ZA: 'جنوب أفريقيا' } }, identical: { 'default': 'الرجاء إدخال نفس القيمة.' }, imei: { 'default': 'الرجاء إدخال رقم IMEI صالح.' }, imo: { 'default': 'الرجاء إدخال رقم IMO صالح.' }, integer: { 'default': 'الرجاء إدخال رقم صحيح.' }, ip: { 'default': 'الرجاء إدخال عنوان IP صالح.', ipv4: 'الرجاء إدخال عنوان IPv4 صالح.', ipv6: 'الرجاء إدخال عنوان IPv6 صالح.' }, isbn: { 'default': 'الرجاء إدخال رقم ISBN صالح.' }, isin: { 'default': 'الرجاء إدخال رقم ISIN صالح.' }, ismn: { 'default': 'الرجاء إدخال رقم ISMN صالح.' }, issn: { 'default': 'الرجاء إدخال رقم ISSN صالح.' }, lessThan: { 'default': 'الرجاء إدخال قيمة أصغر من أو تساوي %s.', notInclusive: 'الرجاء إدخال قيمة أصغر من %s.' }, mac: { 'default': 'يرجى إدخال عنوان MAC صالح.' }, meid: { 'default': 'الرجاء إدخال رقم MEID صالح.' }, notEmpty: { 'default': 'الرجاء إدخال قيمة.' }, numeric: { 'default': 'الرجاء إدخال عدد عشري صالح.' }, phone: { 'default': 'الرجاء إدخال رقم هاتف صحيح.', countryNotSupported: 'البلد ذو الرمز %s غير معتمد.', country: 'الرجاء إدخال رقم هاتف صالح في %s.', countries: { BR: 'البرازيل', CN: 'الصين', CZ: 'التشيك', DE: 'ألمانيا', DK: 'الدنمارك', ES: 'إسبانيا', FR: 'فرنسا', GB: 'المملكة المتحدة', MA: 'المغرب', PK: 'باكستان', RO: 'رومانيا', RU: 'روسيا', SK: 'سلوفاكيا', TH: 'تايلاند', US: 'الولايات المتحدة', VE: 'فنزويلا' } }, regexp: { 'default': 'الرجاء إدخال قيمة مطابقة للنمط.' }, remote: { 'default': 'الرجاء إدخال قيمة صالحة.' }, rtn: { 'default': 'الرجاء إدخال رقم RTN صالح.' }, sedol: { 'default': 'الرجاء إدخال رقم SEDOL صالح.' }, siren: { 'default': 'الرجاء إدخال رقم SIREN صالح.' }, siret: { 'default': 'الرجاء إدخال رقم SIRET صالح.' }, step: { 'default': 'الرجاء إدخال قيمة من مضاعفات %s .' }, stringCase: { 'default': 'الرجاء إدخال أحرف صغيرة فقط.', upper: 'الرجاء إدخال أحرف كبيرة فقط.' }, stringLength: { 'default': 'الرجاء إدخال قيمة ذات طول صحيح.', less: 'الرجاء إدخال أقل من %s حرفا.', more: 'الرجاء إدخال أكتر من %s حرفا.', between: 'الرجاء إدخال قيمة ذات عدد حروف بين %s و %s حرفا.' }, uri: { 'default': 'الرجاء إدخال URI صالح.' }, uuid: { 'default': 'الرجاء إدخال رقم UUID صالح.', version: 'الرجاء إدخال رقم UUID صالح إصدار %s.' }, vat: { 'default': 'الرجاء إدخال رقم VAT صالح.', countryNotSupported: 'البلد ذو الرمز %s غير معتمد.', country: 'الرجاء إدخال رقم VAT صالح في %s.', countries: { AT: 'النمسا', BE: 'بلجيكا', BG: 'بلغاريا', BR: 'البرازيل', CH: 'سويسرا', CY: 'قبرص', CZ: 'التشيك', DE: 'جورجيا', DK: 'الدنمارك', EE: 'إستونيا', ES: 'إسبانيا', FI: 'فنلندا', FR: 'فرنسا', GB: 'المملكة المتحدة', GR: 'اليونان', EL: 'اليونان', HR: 'كرواتيا', HU: 'المجر', IE: 'أيرلندا', IS: 'آيسلندا', IT: 'إيطاليا', LT: 'ليتوانيا', LU: 'لوكسمبورغ', LV: 'لاتفيا', MT: 'مالطا', NL: 'هولندا', NO: 'النرويج', PL: 'بولندا', PT: 'البرتغال', RO: 'رومانيا', RU: 'روسيا', RS: 'صربيا', SE: 'السويد', SI: 'سلوفينيا', SK: 'سلوفاكيا', VE: 'فنزويلا', ZA: 'جنوب أفريقيا' } }, vin: { 'default': 'الرجاء إدخال رقم VIN صالح.' }, zipCode: { 'default': 'الرجاء إدخال رمز بريدي صالح.', countryNotSupported: 'البلد ذو الرمز %s غير معتمد.', country: 'الرجاء إدخال رمز بريدي صالح في %s.', countries: { AT: 'النمسا', BR: 'البرازيل', CA: 'كندا', CH: 'سويسرا', CZ: 'التشيك', DE: 'ألمانيا', DK: 'الدنمارك', FR: 'فرنسا', GB: 'المملكة المتحدة', IE: 'أيرلندا', IT: 'إيطاليا', MA: 'المغرب', NL: 'هولندا', PT: 'البرتغال', RO: 'رومانيا', RU: 'روسيا', SE: 'السويد', SG: 'سنغافورة', SK: 'سلوفاكيا', US: 'الولايات المتحدة' } } }); }(window.jQuery));
Humsen/web/web-mobile/WebContent/plugins/validator/js/language/ar_MA.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/validator/js/language/ar_MA.js", "repo_id": "Humsen", "token_count": 9641 }
48
(function ($) { /** * Italian language package * Translated by @maramazza */ $.fn.bootstrapValidator.i18n = $.extend(true, $.fn.bootstrapValidator.i18n, { base64: { 'default': 'Si prega di inserire un valore codificato in Base 64' }, between: { 'default': 'Si prega di inserire un valore tra %s e %s', notInclusive: 'Si prega di scegliere rigorosamente un valore tra %s e %s' }, callback: { 'default': 'Si prega di inserire un valore valido' }, choice: { 'default': 'Si prega di inserire un valore valido', less: 'Si prega di scegliere come minimo l\'opzione %s', more: 'Si prega di scegliere al massimo l\'opzione %s', between: 'Si prega di scegliere l\'opzione tra %s e %s' }, color: { 'default': 'Si prega di inserire un colore valido' }, creditCard: { 'default': 'Si prega di inserire un numero di carta di credito valido' }, cusip: { 'default': 'Si prega di inserire un numero CUSIP valido' }, cvv: { 'default': 'Si prega di inserire un numero CVV valido' }, date: { 'default': 'Si prega di inserire una data valida', min: 'Si prega di inserire una data successiva al %s', max: 'Si prega di inserire una data antecedente il %s', range: 'Si prega di inserire una data compresa tra %s - %s' }, different: { 'default': 'Si prega di inserire un valore differente' }, digits: { 'default': 'Si prega di inserire solo numeri' }, ean: { 'default': 'Si prega di inserire un numero EAN valido' }, emailAddress: { 'default': 'Si prega di inserire un indirizzo email valido' }, file: { 'default': 'Si prega di scegliere un file valido' }, greaterThan: { 'default': 'Si prega di inserire un numero maggiore o uguale a %s', notInclusive: 'Si prega di inserire un numero maggiore di %s' }, grid: { 'default': 'Si prega di inserire un numero GRId valido' }, hex: { 'default': 'Si prega di inserire un numero esadecimale valido' }, hexColor: { 'default': 'Si prega di inserire un hex colore valido' }, iban: { 'default': 'Si prega di inserire un numero IBAN valido', countryNotSupported: 'Il codice del paese %s non e supportato', country: 'Si prega di inserire un numero IBAN valido per %s', countries: { AD: 'Andorra', AE: 'Emirati Arabi Uniti', AL: 'Albania', AO: 'Angola', AT: 'Austria', AZ: 'Azerbaijan', BA: 'Bosnia-Erzegovina', BE: 'Belgio', BF: 'Burkina Faso', BG: 'Bulgaria', BH: 'Bahrain', BI: 'Burundi', BJ: 'Benin', BR: 'Brasile', CH: 'Svizzera', CI: 'Costa d\'Avorio', CM: 'Cameron', CR: 'Costa Rica', CV: 'Capo Verde', CY: 'Cipro', CZ: 'Republica Ceca', DE: 'Germania', DK: 'Danimarca', DO: 'Repubblica Domenicana', DZ: 'Algeria', EE: 'Estonia', ES: 'Spagna', FI: 'Finlandia', FO: 'Isole Faroe', FR: 'Francia', GB: 'Regno Unito', GE: 'Georgia', GI: 'Gibilterra', GL: 'Groenlandia', GR: 'Grecia', GT: 'Guatemala', HR: 'Croazia', HU: 'Ungheria', IE: 'Irlanda', IL: 'Israele', IR: 'Iran', IS: 'Islanda', IT: 'Italia', JO: 'Giordania', KW: 'Kuwait', KZ: 'Kazakhstan', LB: 'Libano', LI: 'Liechtenstein', LT: 'Lituania', LU: 'Lussemburgo', LV: 'Lettonia', MC: 'Monaco', MD: 'Moldavia', ME: 'Montenegro', MG: 'Madagascar', MK: 'Macedonia', ML: 'Mali', MR: 'Mauritania', MT: 'Malta', MU: 'Mauritius', MZ: 'Mozambico', NL: 'Olanda', NO: 'Norvegia', PK: 'Pachistan', PL: 'Polonia', PS: 'Palestina', PT: 'Portogallo', QA: 'Qatar', RO: 'Romania', RS: 'Serbia', SA: 'Arabia Saudita', SE: 'Svezia', SI: 'Slovenia', SK: 'Slovacchia', SM: 'San Marino', SN: 'Senegal', TN: 'Tunisia', TR: 'Turchia', VG: 'Isole Vergini, Inghilterra' } }, id: { 'default': 'Si prega di inserire un numero di identificazione valido', countryNotSupported: 'Il codice nazione %s non e supportato', country: 'Si prega di inserire un numero di identificazione valido per %s', countries: { BA: 'Bosnia-Erzegovina', BG: 'Bulgaria', BR: 'Brasile', CH: 'Svizzera', CL: 'Chile', CN: 'Cina', CZ: 'Republica Ceca', DK: 'Danimarca', EE: 'Estonia', ES: 'Spagna', FI: 'Finlandia', HR: 'Croazia', IE: 'Irlanda', IS: 'Islanda', LT: 'Lituania', LV: 'Lettonia', ME: 'Montenegro', MK: 'Macedonia', NL: 'Paesi Bassi', RO: 'Romania', RS: 'Serbia', SE: 'Svezia', SI: 'Slovenia', SK: 'Slovacchia', SM: 'San Marino', TH: 'Thailandia', ZA: 'Sudafrica' } }, identical: { 'default': 'Si prega di inserire un valore identico' }, imei: { 'default': 'Si prega di inserire un numero IMEI valido' }, imo: { 'default': 'Si prega di inserire un numero IMO valido' }, integer: { 'default': 'Si prega di inserire un numero valido' }, ip: { 'default': 'Please enter a valid IP address', ipv4: 'Si prega di inserire un indirizzo IPv4 valido', ipv6: 'Si prega di inserire un indirizzo IPv6 valido' }, isbn: { 'default': 'Si prega di inserire un numero ISBN valido' }, isin: { 'default': 'Si prega di inserire un numero ISIN valido' }, ismn: { 'default': 'Si prega di inserire un numero ISMN valido' }, issn: { 'default': 'Si prega di inserire un numero ISSN valido' }, lessThan: { 'default': 'Si prega di inserire un valore minore o uguale a %s', notInclusive: 'Si prega di inserire un valore minore di %s' }, mac: { 'default': 'Si prega di inserire un valido MAC address' }, meid: { 'default': 'Si prega di inserire un numero MEID valido' }, notEmpty: { 'default': 'Si prega di non lasciare il campo vuoto' }, numeric: { 'default': 'Si prega di inserire un numero con decimali valido' }, phone: { 'default': 'Si prega di inserire un numero di telefono valido', countryNotSupported: 'Il codice nazione %s non e supportato', country: 'Si prega di inserire un numero di telefono valido per %s', countries: { BR: 'Brasile', CN: 'Cina', CZ: 'Republica Ceca', DE: 'Germania', DK: 'Danimarca', ES: 'Spagna', FR: 'Francia', GB: 'Regno Unito', MA: 'Marocco', PK: 'Pakistan', RO: 'Romania', RU: 'Russia', SK: 'Slovacchia', TH: 'Thailandia', US: 'Stati Uniti d\'America', VE: 'Venezuelano' } }, regexp: { 'default': 'Inserisci un valore che corrisponde al modello' }, remote: { 'default': 'Si prega di inserire un valore valido' }, rtn: { 'default': 'Si prega di inserire un numero RTN valido' }, sedol: { 'default': 'Si prega di inserire un numero SEDOL valido' }, siren: { 'default': 'Si prega di inserire un numero SIREN valido' }, siret: { 'default': 'Si prega di inserire un numero SIRET valido' }, step: { 'default': 'Si prega di inserire uno step valido di %s' }, stringCase: { 'default': 'Si prega di inserire solo caratteri minuscoli', upper: 'Si prega di inserire solo caratteri maiuscoli' }, stringLength: { 'default': 'Si prega di inserire un valore con lunghezza valida', less: 'Si prega di inserire meno di %s caratteri', more: 'Si prega di inserire piu di %s caratteri', between: 'Si prega di inserire un numero di caratteri compreso tra %s e %s' }, uri: { 'default': 'Si prega di inserire un URI valido' }, uuid: { 'default': 'Si prega di inserire un numero UUID valido', version: 'Si prega di inserire un numero di versione UUID %s valido' }, vat: { 'default': 'Si prega di inserire un valore di IVA valido', countryNotSupported: 'Il codice nazione %s non e supportato', country: 'Si prega di inserire un valore di IVA valido per %s', countries: { AT: 'Austria', BE: 'Belgio', BG: 'Bulgaria', BR: 'Brasiliano', CH: 'Svizzera', CY: 'Cipro', CZ: 'Republica Ceca', DE: 'Germania', DK: 'Danimarca', EE: 'Estonia', ES: 'Spagna', FI: 'Finlandia', FR: 'Francia', GB: 'Regno Unito', GR: 'Grecia', EL: 'Grecia', HU: 'Ungheria', HR: 'Croazia', IE: 'Irlanda', IS: 'Islanda', IT: 'Italia', LT: 'Lituania', LU: 'Lussemburgo', LV: 'Lettonia', MT: 'Malta', NL: 'Olanda', NO: 'Norvegia', PL: 'Polonia', PT: 'Portogallo', RO: 'Romania', RU: 'Russia', RS: 'Serbia', SE: 'Svezia', SI: 'Slovenia', SK: 'Slovacchia', VE: 'Venezuelano', ZA: 'Sud Africano' } }, vin: { 'default': 'Si prega di inserire un numero VIN valido' }, zipCode: { 'default': 'Si prega di inserire un codice postale valido', countryNotSupported: 'Il codice nazione %s non e supportato', country: 'Si prega di inserire un codice postale valido per %s', countries: { AT: 'Austria', BR: 'Brasile', CA: 'Canada', CH: 'Svizzera', CZ: 'Republica Ceca', DE: 'Germania', DK: 'Danimarca', FR: 'Francia', GB: 'Regno Unito', IE: 'Irlanda', IT: 'Italia', MA: 'Marocco', NL: 'Paesi Bassi', PT: 'Portogallo', RO: 'Romania', RU: 'Russia', SE: 'Svezia', SG: 'Singapore', SK: 'Slovacchia', US: 'Stati Uniti d\'America' } } }); }(window.jQuery));
Humsen/web/web-mobile/WebContent/plugins/validator/js/language/it_IT.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/validator/js/language/it_IT.js", "repo_id": "Humsen", "token_count": 7803 }
49
(function ($) { /** * Simplified Chinese language package * Translated by @shamiao */ $.fn.bootstrapValidator.i18n = $.extend(true, $.fn.bootstrapValidator.i18n, { base64: { 'default': '请输入有效的Base64编码' }, between: { 'default': '请输入在 %s 和 %s 之间的数值', notInclusive: '请输入在 %s 和 %s 之间(不含两端)的数值' }, callback: { 'default': '请输入有效的值' }, choice: { 'default': '请输入有效的值', less: '请至少选中 %s 个选项', more: '最多只能选中 %s 个选项', between: '请选择 %s 至 %s 个选项' }, color: { 'default': '请输入有效的颜色值' }, creditCard: { 'default': '请输入有效的信用卡号码' }, cusip: { 'default': '请输入有效的美国CUSIP代码' }, cvv: { 'default': '请输入有效的CVV代码' }, date: { 'default': '请输入有效的日期', min: '请输入 %s 或之后的日期', max: '请输入 %s 或以前的日期', range: '请输入 %s 和 %s 之间的日期' }, different: { 'default': '请输入不同的值' }, digits: { 'default': '请输入有效的数字' }, ean: { 'default': '请输入有效的EAN商品编码' }, emailAddress: { 'default': '请输入有效的邮件地址' }, file: { 'default': '请选择有效的文件' }, greaterThan: { 'default': '请输入大于等于 %s 的数值', notInclusive: '请输入大于 %s 的数值' }, grid: { 'default': '请输入有效的GRId编码' }, hex: { 'default': '请输入有效的16进制数' }, hexColor: { 'default': '请输入有效的16进制颜色值' }, iban: { 'default': '请输入有效的IBAN(国际银行账户)号码', countryNotSupported: '不支持 %s 国家或地区', country: '请输入有效的 %s 国家或地区的IBAN(国际银行账户)号码', countries: { AD: '安道​​尔', AE: '阿联酋', AL: '阿尔巴尼亚', AO: '安哥拉', AT: '奥地利', AZ: '阿塞拜疆', BA: '波斯尼亚和黑塞哥维那', BE: '比利时', BF: '布基纳法索', BG: '保加利亚', BH: '巴林', BI: '布隆迪', BJ: '贝宁', BR: '巴西', CH: '瑞士', CI: '科特迪瓦', CM: '喀麦隆', CR: '哥斯达黎加', CV: '佛得角', CY: '塞浦路斯', CZ: '捷克共和国', DE: '德国', DK: '丹麦', DO: '多米尼加共和国', DZ: '阿尔及利亚', EE: '爱沙尼亚', ES: '西班牙', FI: '芬兰', FO: '法罗群岛', FR: '法国', GB: '英国', GE: '格鲁吉亚', GI: '直布罗陀', GL: '格陵兰岛', GR: '希腊', GT: '危地马拉', HR: '克罗地亚', HU: '匈牙利', IE: '爱尔兰', IL: '以色列', IR: '伊朗', IS: '冰岛', IT: '意大利', JO: '约旦', KW: '科威特', KZ: '哈萨克斯坦', LB: '黎巴嫩', LI: '列支敦士登', LT: '立陶宛', LU: '卢森堡', LV: '拉脱维亚', MC: '摩纳哥', MD: '摩尔多瓦', ME: '黑山', MG: '马达加斯加', MK: '马其顿', ML: '马里', MR: '毛里塔尼亚', MT: '马耳他', MU: '毛里求斯', MZ: '莫桑比克', NL: '荷兰', NO: '挪威', PK: '巴基斯坦', PL: '波兰', PS: '巴勒斯坦', PT: '葡萄牙', QA: '卡塔尔', RO: '罗马尼亚', RS: '塞尔维亚', SA: '沙特阿拉伯', SE: '瑞典', SI: '斯洛文尼亚', SK: '斯洛伐克', SM: '圣马力诺', SN: '塞内加尔', TN: '突尼斯', TR: '土耳其', VG: '英属维尔京群岛' } }, id: { 'default': '请输入有效的身份证件号码', countryNotSupported: '不支持 %s 国家或地区', country: '请输入有效的 %s 国家或地区的身份证件号码', countries: { BA: '波黑', BG: '保加利亚', BR: '巴西', CH: '瑞士', CL: '智利', CN: '中国', CZ: '捷克共和国', DK: '丹麦', EE: '爱沙尼亚', ES: '西班牙', FI: '芬兰', HR: '克罗地亚', IE: '爱尔兰', IS: '冰岛', LT: '立陶宛', LV: '拉脱维亚', ME: '黑山', MK: '马其顿', NL: '荷兰', RO: '罗马尼亚', RS: '塞尔维亚', SE: '瑞典', SI: '斯洛文尼亚', SK: '斯洛伐克', SM: '圣马力诺', TH: '泰国', ZA: '南非' } }, identical: { 'default': '请输入相同的值' }, imei: { 'default': '请输入有效的IMEI(手机串号)' }, imo: { 'default': '请输入有效的国际海事组织(IMO)号码' }, integer: { 'default': '请输入有效的整数值' }, ip: { 'default': '请输入有效的IP地址', ipv4: '请输入有效的IPv4地址', ipv6: '请输入有效的IPv6地址' }, isbn: { 'default': '请输入有效的ISBN(国际标准书号)' }, isin: { 'default': '请输入有效的ISIN(国际证券编码)' }, ismn: { 'default': '请输入有效的ISMN(印刷音乐作品编码)' }, issn: { 'default': '请输入有效的ISSN(国际标准杂志书号)' }, lessThan: { 'default': '请输入小于等于 %s 的数值', notInclusive: '请输入小于 %s 的数值' }, mac: { 'default': '请输入有效的MAC物理地址' }, meid: { 'default': '请输入有效的MEID(移动设备识别码)' }, notEmpty: { 'default': '请填写必填项目' }, numeric: { 'default': '请输入有效的数值,允许小数' }, phone: { 'default': '请输入有效的电话号码', countryNotSupported: '不支持 %s 国家或地区', country: '请输入有效的 %s 国家或地区的电话号码', countries: { BR: '巴西', CN: '中国', CZ: '捷克共和国', DE: '德国', DK: '丹麦', ES: '西班牙', FR: '法国', GB: '英国', MA: '摩洛哥', PK: '巴基斯坦', RO: '罗马尼亚', RU: '俄罗斯', SK: '斯洛伐克', TH: '泰国', US: '美国', VE: '委内瑞拉' } }, regexp: { 'default': '请输入符合正则表达式限制的值' }, remote: { 'default': '请输入有效的值' }, rtn: { 'default': '请输入有效的RTN号码' }, sedol: { 'default': '请输入有效的SEDOL代码' }, siren: { 'default': '请输入有效的SIREN号码' }, siret: { 'default': '请输入有效的SIRET号码' }, step: { 'default': '请输入在基础值上,增加 %s 的整数倍的数值' }, stringCase: { 'default': '只能输入小写字母', upper: '只能输入大写字母' }, stringLength: { 'default': '请输入符合长度限制的值', less: '最多只能输入 %s 个字符', more: '需要输入至少 %s 个字符', between: '请输入 %s 至 %s 个字符' }, uri: { 'default': '请输入一个有效的URL地址' }, uuid: { 'default': '请输入有效的UUID', version: '请输入版本 %s 的UUID' }, vat: { 'default': '请输入有效的VAT(税号)', countryNotSupported: '不支持 %s 国家或地区', country: '请输入有效的 %s 国家或地区的VAT(税号)', countries: { AT: '奥地利', BE: '比利时', BG: '保加利亚', BR: '巴西', CH: '瑞士', CY: '塞浦路斯', CZ: '捷克共和国', DE: '德国', DK: '丹麦', EE: '爱沙尼亚', ES: '西班牙', FI: '芬兰', FR: '法语', GB: '英国', GR: '希腊', EL: '希腊', HU: '匈牙利', HR: '克罗地亚', IE: '爱尔兰', IS: '冰岛', IT: '意大利', LT: '立陶宛', LU: '卢森堡', LV: '拉脱维亚', MT: '马耳他', NL: '荷兰', NO: '挪威', PL: '波兰', PT: '葡萄牙', RO: '罗马尼亚', RU: '俄罗斯', RS: '塞尔维亚', SE: '瑞典', SI: '斯洛文尼亚', SK: '斯洛伐克', VE: '委内瑞拉', ZA: '南非' } }, vin: { 'default': '请输入有效的VIN(美国车辆识别号码)' }, zipCode: { 'default': '请输入有效的邮政编码', countryNotSupported: '不支持 %s 国家或地区', country: '请输入有效的 %s 国家或地区的邮政编码', countries: { AT: '奥地利', BR: '巴西', CA: '加拿大', CH: '瑞士', CZ: '捷克共和国', DE: '德国', DK: '丹麦', FR: '法国', GB: '英国', IE: '爱尔兰', IT: '意大利', MA: '摩洛哥', NL: '荷兰', PT: '葡萄牙', RO: '罗马尼亚', RU: '俄罗斯', SE: '瑞典', SG: '新加坡', SK: '斯洛伐克', US: '美国' } } }); }(window.jQuery));
Humsen/web/web-mobile/WebContent/plugins/validator/js/language/zh_CN.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/validator/js/language/zh_CN.js", "repo_id": "Humsen", "token_count": 9254 }
50
@charset "UTF-8"; #fh5co-main { width: 60%; float: left; margin: 0 2.5%; transition: 0.5s; -moz-transition: 0.5s; /* Firefox 4 */ -webkit-transition: 0.5s; /* Safari 和 Chrome */ -o-transition: 0.5s; /* Opera */ } #fh5co-main .fh5co-narrow-content { position: relative; width: 93%; margin: 0 auto; padding: 4em 0; clear: both; } .fh5co-heading { font-size: 18px; margin-bottom: 2em; font-weight: 500; letter-spacing: 2px; } .blog-entry { width: 100%; float: left; background: #f3f3f1; } .blog-entry .desc { padding: 0 25px 20px 25px; } .blog-entry .desc span { display: block; margin-bottom: 20px; font-size: 13px; letter-spacing: 1px; } .blog-entry .desc .lead { font-size: 12px; letter-spacing: 2px; color: #000; } .fh5co-feature { text-align: left; width: 100%; float: left; margin-bottom: 40px; position: relative; } .fh5co-feature .fh5co-icon { position: absolute; top: 0; left: 0; width: 100px; height: 100px; display: table; text-align: center; background: rgba(0, 0, 0, 0.05); -webkit-border-radius: 50%; -moz-border-radius: 50%; -ms-border-radius: 50%; border-radius: 50%; } .fh5co-feature .fh5co-icon i { display: table-cell; vertical-align: middle; color: #228896; font-size: 40px; height: 100px; } .fh5co-feature .fh5co-text { padding-left: 120px; width: 100%; } .fh5co-feature .fh5co-text h3 { font-weight: 500; margin-bottom: 20px; color: rgba(0, 0, 0, 0.8); font-size: 14px; letter-spacing: .2em; } .fh5co-feature .fh5co-text h2, .fh5co-feature .fh5co-text h3 { margin: 0; padding: 0; }
Humsen/web/web-pc/WebContent/css/navigation/middle.css/0
{ "file_path": "Humsen/web/web-pc/WebContent/css/navigation/middle.css", "repo_id": "Humsen", "token_count": 742 }
51
/** * @author 何明胜 * * 2017年10月18日 */ $(function(){ // 加载文章细节后, 自动显示markdown showMarkdown(); }); /** * 解析markdown html * */ function showMarkdown() { editormd.markdownToHTML('content', { htmlDecode : 'style,script,iframe', // you can filter tags decode emoji : true, taskList : true, tex : true, // 默认不解析 flowChart : true, // 默认不解析 sequenceDiagram : true, // 默认不解析 }); }
Humsen/web/web-pc/WebContent/js/article/article-markdown.js/0
{ "file_path": "Humsen/web/web-pc/WebContent/js/article/article-markdown.js", "repo_id": "Humsen", "token_count": 221 }
52
/** * 留言区函数 * * @author 何明胜 * * 2017年9月25日 */ /** 加载插件 * */ $.ajax({ url : '/plugins/plugins.html', // 这里是静态页的地址 async : false, type : 'GET', // 静态页用get方法,否则服务器会抛出405错误 success : function(data) { $($('head')[0]).find('script:first').after(data); } }); $(function() { /** 顶部导航栏 **/ $.ajax({ url : '/module/navigation/topbar.html', // 这里是静态页的地址 async : false, type : 'GET', // 静态页用get方法,否则服务器会抛出405错误 success : function(data) { $('#menuBarNo').before(data); } }); /** 登录控制 **/ $.ajax({ url : '/module/login/login.html', // 这里是静态页的地址 async : false, type : 'GET', // 静态页用get方法,否则服务器会抛出405错误 success : function(data) { $('#menuBarNo').before(data); } }); /** 左侧导航栏 **/ $.ajax({ url : '/module/navigation/leftbar.html', // 这里是静态页的地址 async : false, type : 'GET', // 静态页用get方法,否则服务器会抛出405错误 success : function(data) { $('#fh5co-main').before(data); } }); /** 右侧导航栏 **/ $.ajax({ url : '/module/navigation/rightbar.html', // 这里是静态页的地址 async : false, type : 'GET', // 静态页用get方法,否则服务器会抛出405错误 success : function(data) { $('#fh5co-main').after(data); } }); }); // 初始化 $(function() { Comment.allocate({ parent : $('#message_box'), // 你想要将这个评论放到页面哪个元素中 id : 0, getCmtUrl : '/message.hms', setCmtUrl : '/message.hms' }) }); /** * 执行初始化的函数 */ Comment.allocate = function(options) { // 构造函数 var oCmt = new Comment(options); if (oCmt.belong == undefined || !oCmt.getCmtUrl || !oCmt.setCmtUrl) { return null; } ; // 初始化 oCmt.init(options); return oCmt; }; /** * 构造函数 * * @param options * @returns */ function Comment(options) { this.belong = options.id; this.getCmtUrl = options.getCmtUrl; this.setCmtUrl = options.setCmtUrl; this.lists = []; this.keys = {}; this.offset = 5; } var fn = Comment.prototype; /** * 初始化函数 */ fn.init = function(options) { // 初始化node this.initNode(options); // 将内容放进容器 this.parent.html(this.body); // 初始化事件 this.initEvent(); // 获取列表 this.getList(); }; /** * 初始化结点或者缓存DOM */ fn.initNode = function(options) { // init wrapper box if (!!options.parent) { this.parent = options.parent[0].nodeType == 1 ? options.parent : $('#' + options.parent); } if (!this.parent) { this.parent = $('div'); $('body').append(this.parent); } // init content this.body = (function() { var strHtml = '<div class="m-comment">' + '<div class="cmt-form" >' + '<textarea class="cmt-text form-control meessage-input" placeholder="请输入留言..."></textarea>' + '<button class="btn btn-success btn-sm u-button btn-submit-commit">提交评论</button>' + '<hr class="commit-hr">' + '</div>' + '<div class="cmt-content">' + '<div class="u-loading1"></div>' + '<div class="no-cmt">暂时没有评论</div>' + '<ul class="cmt-list"></ul>' + '<div class="f-clear">' + '<div class="pager-box"></div>' + '</div>' + '</div>' + '</div>'; return $(strHtml); })(); // init other node this.text = this.body.find('.cmt-text').eq(0); this.cmtBtn = this.body.find('.u-button').eq(0); this.noCmt = this.body.find('.no-cmt').eq(0); this.cmtList = this.body.find('.cmt-list').eq(0); this.loading = this.body.find('.u-loading1').eq(0); this.pagerBox = this.body.find('.pager-box').eq(0); }; /** * 初始化列表 */ fn.resetList = function() { this.loading.css('display', 'block') this.noCmt.css('display', 'none'); this.cmtList.html(''); }; /** * ajax获取 */ fn.getList = function() { var self = this; this.resetList(); $.ajax({ url : self.getCmtUrl, type : 'get', dataType : 'json', data : { type : 'query_all', messageId : self.belong }, success : function(data) { if (!data) { $.confirm({ content : '获取评论列表失败', autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); return !1; } // 增加reponse字段和处理时间 for ( var i in data) { data[i].response = []; data[i].messageDate = new Date(data[i].messageDate.time) .format('yyyy-MM-dd hh:mm:ss') } // 整理评论列表 self.initList(data); self.loading.css('display', 'none'); // 显示评论列表 if (self.lists.length == 0) { $.confirm({ content : '暂时没有评论', autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); // 暂时没有评论 self.noCmt.css('display', 'block'); } else { // 设置分页器 var total = Math.ceil(self.lists.length / self.offset); self.pager = new Pager({ index : 1, total : total, parent : self.pagerBox[0], onchange : self.doChangePage.bind(self), label : { prev : '<', next : '>' } }); } }, error : function(XMLHttpRequest, textStatus) { $.confirm({ title : '获取评论列表出错', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); } }); }; /** * 初始化节点 * * this.lists放的都是评论(parent为0的留言) 通过遍历获取的数据,如果parent为0,就push进this.lists; * 否则parent不为0表示这是个回复,就找到对应的评论,把该回复push进那条评论的response中。 * 但是还有个问题,就是因为id是不断增长的,可能中间有些评论被删除了, * 所以id和index并不一定匹配,所以借助this.keys保存id和index的对应关系。 */ fn.initList = function(data) { this.lists = []; // 保存评论列表 this.keys = {}; // 保存评论id和index对应表 var index = 0; // 遍历处理 for (var i = 0, len = data.length; i < len; i++) { var t = data[i], id = t['messageId']; if (t['messageParent'] == 0) { this.keys[id] = index++; this.lists.push(t); } else { var parentId = t['messageParent'], parentIndex = this.keys[parentId]; this.lists[parentIndex]['response'].push(t);// 这里response可能会有问题 } } }; /** * onchange函数,默认页数为1,保存在参数obj.index中 */ fn.doChangePage = function(obj) { this.showList(obj.index); }; /** * 显示列表函数 代码自动运行 */ fn.showList = (function() { /* 生成一条评论字符串 */ function oneLi(_obj) { var str1 = ''; // 处理回复 for (var i = 0, len = _obj.response.length; i < len; i++) { var t = _obj.response[i]; t.messageContent = t.messageContent.replace(/\<\;/g, '<'); t.messageContent = t.messageContent.replace(/\>\;/g, '>'); str1 += '<li class="f-clear"><table><tbody><tr><td>' + '<span class="username">' + t.messageUsername + ':</span></td><td>' + '<span class="child-content">' + t.messageContent + '</span></td></tr></tbody></table>' + '</li>' } // 处理评论 var headImg = ''; if (_obj.messageUsername == 'kang') { headImg = 'kang_head.jpg'; } else { var index = Math.floor(Math.random() * 9); headImg = 'head-' + index + '.jpg' } _obj.messageContent = _obj.messageContent.replace(/\<\;/g, '<'); _obj.messageContent = _obj.messageContent.replace(/\>\;/g, '>'); var str2 = '<li class="f-clear">' + '<hr class="commit-hr1"/>' + '<div class="user-head">' + '<img src="/images/message/' + headImg + '" class="message-head-img"/>' + '</div>' + '<div class="content c-float-left">' + '<div class="f-clear">' + '<span class="username user-float-left">' + _obj.messageUsername + '</span>' + '<span class="time user-float-left">' + _obj.messageDate + '</span>' + '</div>' + '<span class="parent-content">' + _obj.messageContent + '</span>' + '<ul class="child-comment">' + str1 + '</ul>' + '</div>' + '<div class="respone-box g-col-2 f-float-right">' + '<a href="javascript:void(0);" class="f-show response" data-id="' + _obj.messageId + '">[回复]</a>' + '</div>' + '</li>'; return str2; } var page = 1; return function(page) { var len = this.lists.length, end = len - (page - 1) * this.offset, start = end - this.offset < 0 ? 0 : end - this.offset, current = this.lists .slice(start, end); var cmtList = ''; for (var i = current.length - 1; i >= 0; i--) { var t = current[i], index = this.keys[t['messageId']]; current[i]['index'] = index; cmtList += oneLi(t); } this.cmtList.html(cmtList); }; })(); /** * 初始化按钮点击事件 */ fn.initEvent = function() { // 提交按钮点击 this.cmtBtn.on('click', this.addCmt.bind(this, this.cmtBtn, this.text, 0)); // 点击回复,点击取消回复,点击回复中的提交评论按钮 this.cmtList.on('click', this.doClickResponse.bind(this)); }; fn.addCmt = function(_btn, _text, _parent) { // 防止多次点击 if (_btn.attr('data-disabled') == 'true') { return !1; } // 处理提交空白 var value = _text.val().replace(/^\s+|\s+$/g, ''); value = value.replace(/[\r\n]/g, '<br >'); if (!value) { $.confirm({ title : '', content : '内容不能为空', autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); return !1; } // 禁止点击 _btn.attr('data-disabled', 'true'); _btn.html('评论提交中...'); // 提交处理 /** * todo 暂时全部设置为游客 */ var self = this; var email = '940706904@qq.com'; var username = '游客'; /* * username = $.cookie('user'); if (!username) { alert('游客') username = * '游客'; } email = $.cookie('email'); if (!email) { email = * 'default@163.com'; } */ var now = $.nowDateHMS(); // 将参数封装到对象里 var new_message = {}; new_message.messageBelong = self.belong; new_message.messageParent = _parent; new_message.messageEmail = email; new_message.messageUsername = username; new_message.messageContent = value; new_message.messageDate = now; $.ajax({ type : 'get', dataType : 'json', url : this.setCmtUrl, data : { type : 'create_one', newMessage : JSON.stringify(new_message), /* * belong: self.belong, parent: _parent, email: email, username: * username, content: value */ }, success : function(_data) { // 解除禁止点击 _btn.attr('data-disabled', ''); _btn.html('提交评论'); if (!_data) { $.confirm({ content : '评论失败,请重新评论', autoClose : 'ok|2000', type : 'green', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); return !1; } if (_data['result'] == 1) { // 评论成功 $.confirm({ title : false, content : '评论成功', autoClose : 'ok|1500', type : 'green', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); var id = _data['messageId']; var time = now; /* * time = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + * now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + * ':' + now.getSeconds(); */ if (_parent == 0) { var index = self.lists.length; if (!self.pager) { // 设置分页器 self.noCmt.css('display', 'none'); var total = Math.ceil(self.lists.length / self.offset); self.pager = new Pager({ index : 1, total : total, parent : self.pagerBox[0], onchange : self.doChangePage.bind(self), label : { prev : '<', next : '>' } }); } self.keys[id] = index; self.lists.push({ 'messageId' : id, 'messageUsername' : username, 'messageDate' : time, 'messageContent' : value, 'response' : [] }); self.showList(1); self.pager._$setIndex(1); } else { var index = self.keys[_parent], page = self.pager.__index; self.lists[index]['response'].push({ 'messageId' : id, 'messageUsername' : username, 'messageDate' : time, 'messageContent' : value }); self.showList(page); } self.text.val(''); } else { $.confirm({ title : '', content : '评论失败,请重新评论', autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); } }, error : function(XMLHttpRequest, textStatus) { $.confirm({ title : '评论出错,请重新评论', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'green', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); // 解除禁止点击 _btn.attr('data-disabled', ''); _btn.html('提交评论'); } }); } /** * doClickResponse 函数 */ fn.doClickResponse = function(_event) { var target = $(_event.target); var id = target.attr('data-id'); if (target.hasClass('response') && target.attr('data-disabled') != 'true') { // 点击回复 var oDiv = document.createElement('div'); oDiv.className = 'cmt-form'; var replyHtml = ''; // 判断是否是手机 if ($.isMobile()) { replyHtml += '<textarea class="cmt-text comment-input mobile-reply" placeholder="请输入回复评论..."></textarea>'; replyHtml += '<div class="reply-div-mobile">'; } else { replyHtml += '<textarea class="cmt-text comment-input" placeholder="请输入回复评论..."></textarea>'; replyHtml += '<div class="reply-div-pc">'; } oDiv.innerHTML = replyHtml + '<button class="u-button resBtn" data-id="' + id + '">提交评论</button>' + '<a href="javascript:void(0);" class="cancel cancel-reply">[取消回复]</a>' + '</div>'; target.parent().parent().append(oDiv); oDiv = null; target.attr('data-disabled', 'true'); } else if (target.hasClass('cancel')) { // 点击取消回复 var ppNode = target.parent().parent().parent(), oRes = ppNode.find( '.response').eq(0); target.parent().parent().remove(); oRes.attr('data-disabled', ''); } else if (target.hasClass('resBtn')) { // 点击评论 var oText = target.parent().parent().find('.cmt-text').eq(0); var parent = target.attr('data-id'); this.addCmt(target, oText, parent); } else { // 其他情况 return !1; } };
Humsen/web/web-pc/WebContent/js/message/message.js/0
{ "file_path": "Humsen/web/web-pc/WebContent/js/message/message.js", "repo_id": "Humsen", "token_count": 7582 }
53
<!-- 此处修改记得更新 后端通用模板 --> <!-- 左侧固定栏 --> <link rel="stylesheet" href="/css/navigation/leftbar.css" /> <!-- 加载新版本特性 --> <script src="/js/navigation/leftbar.js"></script> <div id="bar_left"> <!-- 加载新版特性 --> <div id="txt_versionFeature" class="sidebar-module"></div> <!-- 加载文章分类 --> <div id="txt_articleCategory" class="sidebar-module category-hide"> <h4>文章分类</h4> <ol class="list-unstyled category-show"></ol> </div> </div>
Humsen/web/web-pc/WebContent/module/navigation/leftbar.html/0
{ "file_path": "Humsen/web/web-pc/WebContent/module/navigation/leftbar.html", "repo_id": "Humsen", "token_count": 250 }
54
table.dataTable { clear: both; margin: 0.5em 0 !important; max-width: none !important; width: 100%; } table.dataTable td, table.dataTable th { -webkit-box-sizing: content-box; box-sizing: content-box; } table.dataTable td.dataTables_empty, table.dataTable th.dataTables_empty { text-align: center; } table.dataTable.nowrap th, table.dataTable.nowrap td { white-space: nowrap; } div.dataTables_wrapper { position: relative; } div.dataTables_wrapper div.dataTables_length label { float: left; text-align: left; margin-bottom: 0; } div.dataTables_wrapper div.dataTables_length select { width: 75px; margin-bottom: 0; } div.dataTables_wrapper div.dataTables_filter label { float: right; margin-bottom: 0; } div.dataTables_wrapper div.dataTables_filter input { display: inline-block !important; width: auto !important; margin-bottom: 0; margin-left: 0.5em; } div.dataTables_wrapper div.dataTables_info { padding-top: 2px; } div.dataTables_wrapper div.dataTables_paginate { float: right; margin: 0; } div.dataTables_wrapper div.dataTables_processing { position: absolute; top: 50%; left: 50%; width: 200px; margin-left: -100px; margin-top: -26px; text-align: center; padding: 1rem 0; } table.dataTable thead > tr > th.sorting_asc, table.dataTable thead > tr > th.sorting_desc, table.dataTable thead > tr > th.sorting, table.dataTable thead > tr > td.sorting_asc, table.dataTable thead > tr > td.sorting_desc, table.dataTable thead > tr > td.sorting { padding-right: 1.5rem; } table.dataTable thead > tr > th:active, table.dataTable thead > tr > td:active { outline: none; } table.dataTable thead .sorting, table.dataTable thead .sorting_asc, table.dataTable thead .sorting_desc, table.dataTable thead .sorting_asc_disabled, table.dataTable thead .sorting_desc_disabled { cursor: pointer; } table.dataTable thead .sorting, table.dataTable thead .sorting_asc, table.dataTable thead .sorting_desc, table.dataTable thead .sorting_asc_disabled, table.dataTable thead .sorting_desc_disabled { background-repeat: no-repeat; background-position: center right; } table.dataTable thead .sorting { background-image: url("../images/sort_both.png"); } table.dataTable thead .sorting_asc { background-image: url("../images/sort_asc.png"); } table.dataTable thead .sorting_desc { background-image: url("../images/sort_desc.png"); } table.dataTable thead .sorting_asc_disabled { background-image: url("../images/sort_asc_disabled.png"); } table.dataTable thead .sorting_desc_disabled { background-image: url("../images/sort_desc_disabled.png"); } div.dataTables_scrollHead table { margin-bottom: 0 !important; } div.dataTables_scrollBody table { border-top: none; margin-top: 0 !important; margin-bottom: 0 !important; } div.dataTables_scrollBody table tbody tr:first-child th, div.dataTables_scrollBody table tbody tr:first-child td { border-top: none; } div.dataTables_scrollFoot table { margin-top: 0 !important; border-top: none; }
Humsen/web/web-pc/WebContent/plugins/DataTables/css/dataTables.foundation.css/0
{ "file_path": "Humsen/web/web-pc/WebContent/plugins/DataTables/css/dataTables.foundation.css", "repo_id": "Humsen", "token_count": 1090 }
55
/*! DataTables UIkit 3 integration */ /** * This is a tech preview of UIKit integration with DataTables. */ (function( factory ){ if ( typeof define === 'function' && define.amd ) { // AMD define( ['jquery', 'datatables.net'], function ( $ ) { return factory( $, window, document ); } ); } else if ( typeof exports === 'object' ) { // CommonJS module.exports = function (root, $) { if ( ! root ) { root = window; } if ( ! $ || ! $.fn.dataTable ) { // Require DataTables, which attaches to jQuery, including // jQuery if needed and have a $ property so we can access the // jQuery object that is used $ = require('datatables.net')(root, $).$; } return factory( $, root, root.document ); }; } else { // Browser factory( jQuery, window, document ); } }(function( $, window, document, undefined ) { 'use strict'; var DataTable = $.fn.dataTable; /* Set the defaults for DataTables initialisation */ $.extend( true, DataTable.defaults, { dom: "<'row uk-grid'<'uk-width-1-2'l><'uk-width-1-2'f>>" + "<'row uk-grid dt-merge-grid'<'uk-width-1-1'tr>>" + "<'row uk-grid dt-merge-grid'<'uk-width-2-5'i><'uk-width-3-5'p>>", renderer: 'uikit' } ); /* Default class modification */ $.extend( DataTable.ext.classes, { sWrapper: "dataTables_wrapper uk-form dt-uikit", sFilterInput: "uk-form-small", sLengthSelect: "uk-form-small", sProcessing: "dataTables_processing uk-panel" } ); /* UIkit paging button renderer */ DataTable.ext.renderer.pageButton.uikit = function ( settings, host, idx, buttons, page, pages ) { var api = new DataTable.Api( settings ); var classes = settings.oClasses; var lang = settings.oLanguage.oPaginate; var aria = settings.oLanguage.oAria.paginate || {}; var btnDisplay, btnClass, counter=0; var attach = function( container, buttons ) { var i, ien, node, button; var clickHandler = function ( e ) { e.preventDefault(); if ( !$(e.currentTarget).hasClass('disabled') && api.page() != e.data.action ) { api.page( e.data.action ).draw( 'page' ); } }; for ( i=0, ien=buttons.length ; i<ien ; i++ ) { button = buttons[i]; if ( $.isArray( button ) ) { attach( container, button ); } else { btnDisplay = ''; btnClass = ''; switch ( button ) { case 'ellipsis': btnDisplay = '<i class="uk-icon-ellipsis-h"></i>'; btnClass = 'uk-disabled disabled'; break; case 'first': btnDisplay = '<i class="uk-icon-angle-double-left"></i> ' + lang.sFirst; btnClass = (page > 0 ? '' : ' uk-disabled disabled'); break; case 'previous': btnDisplay = '<i class="uk-icon-angle-left"></i> ' + lang.sPrevious; btnClass = (page > 0 ? '' : 'uk-disabled disabled'); break; case 'next': btnDisplay = lang.sNext + ' <i class="uk-icon-angle-right"></i>'; btnClass = (page < pages-1 ? '' : 'uk-disabled disabled'); break; case 'last': btnDisplay = lang.sLast + ' <i class="uk-icon-angle-double-right"></i>'; btnClass = (page < pages-1 ? '' : ' uk-disabled disabled'); break; default: btnDisplay = button + 1; btnClass = page === button ? 'uk-active' : ''; break; } if ( btnDisplay ) { node = $('<li>', { 'class': classes.sPageButton+' '+btnClass, 'id': idx === 0 && typeof button === 'string' ? settings.sTableId +'_'+ button : null } ) .append( $(( -1 != btnClass.indexOf('disabled') || -1 != btnClass.indexOf('active') ) ? '<span>' : '<a>', { 'href': '#', 'aria-controls': settings.sTableId, 'aria-label': aria[ button ], 'data-dt-idx': counter, 'tabindex': settings.iTabIndex } ) .html( btnDisplay ) ) .appendTo( container ); settings.oApi._fnBindAction( node, {action: button}, clickHandler ); counter++; } } } }; // IE9 throws an 'unknown error' if document.activeElement is used // inside an iframe or frame. var activeEl; try { // Because this approach is destroying and recreating the paging // elements, focus is lost on the select button which is bad for // accessibility. So we want to restore focus once the draw has // completed activeEl = $(host).find(document.activeElement).data('dt-idx'); } catch (e) {} attach( $(host).empty().html('<ul class="uk-pagination uk-pagination-right"/>').children('ul'), buttons ); if ( activeEl ) { $(host).find( '[data-dt-idx='+activeEl+']' ).focus(); } }; return DataTable; }));
Humsen/web/web-pc/WebContent/plugins/DataTables/js/dataTables.uikit.js/0
{ "file_path": "Humsen/web/web-pc/WebContent/plugins/DataTables/js/dataTables.uikit.js", "repo_id": "Humsen", "token_count": 1980 }
56
"use strict"; var os = require("os"); var gulp = require("gulp"); var gutil = require("gulp-util"); var sass = require("gulp-ruby-sass"); var jshint = require("gulp-jshint"); var uglify = require("gulp-uglifyjs"); var rename = require("gulp-rename"); var concat = require("gulp-concat"); var notify = require("gulp-notify"); var header = require("gulp-header"); var minifycss = require("gulp-minify-css"); //var jsdoc = require("gulp-jsdoc"); //var jsdoc2md = require("gulp-jsdoc-to-markdown"); var pkg = require("./package.json"); var dateFormat = require("dateformatter").format; var replace = require("gulp-replace"); pkg.name = "Editor.md"; pkg.today = dateFormat; var headerComment = ["/*", " * <%= pkg.name %>", " *", " * @file <%= fileName(file) %> ", " * @version v<%= pkg.version %> ", " * @description <%= pkg.description %>", " * @license MIT License", " * @author <%= pkg.author %>", " * {@link <%= pkg.homepage %>}", " * @updateTime <%= pkg.today('Y-m-d') %>", " */", "\r\n"].join("\r\n"); var headerMiniComment = "/*! <%= pkg.name %> v<%= pkg.version %> | <%= fileName(file) %> | <%= pkg.description %> | MIT License | By: <%= pkg.author %> | <%= pkg.homepage %> | <%=pkg.today('Y-m-d') %> */\r\n"; var scssTask = function(fileName, path) { path = path || "scss/"; var distPath = "css"; return sass(path + fileName + ".scss", { style: "expanded", sourcemap: false, noCache : true }) .pipe(gulp.dest(distPath)) .pipe(header(headerComment, {pkg : pkg, fileName : function(file) { var name = file.path.split(file.base); return name[1].replace("\\", ""); }})) .pipe(gulp.dest(distPath)) .pipe(rename({ suffix: ".min" })) .pipe(gulp.dest(distPath)) .pipe(minifycss()) .pipe(gulp.dest(distPath)) .pipe(header(headerMiniComment, {pkg : pkg, fileName : function(file) { var name = file.path.split(file.base); return name[1].replace("\\", ""); }})) .pipe(gulp.dest(distPath)) .pipe(notify({ message: fileName + ".scss task completed!" })); }; gulp.task("scss", function() { return scssTask("editormd"); }); gulp.task("scss2", function() { return scssTask("editormd.preview"); }); gulp.task("scss3", function() { return scssTask("editormd.logo"); }); gulp.task("js", function() { return gulp.src("./src/editormd.js") .pipe(jshint("./.jshintrc")) .pipe(jshint.reporter("default")) .pipe(header(headerComment, {pkg : pkg, fileName : function(file) { var name = file.path.split(file.base); return name[1].replace(/[\\\/]?/, ""); }})) .pipe(gulp.dest("./")) .pipe(rename({ suffix: ".min" })) .pipe(uglify()) // {outSourceMap: true, sourceRoot: './'} .pipe(gulp.dest("./")) .pipe(header(headerMiniComment, {pkg : pkg, fileName : function(file) { var name = file.path.split(file.base + ( (os.platform() === "win32") ? "\\" : "/") ); return name[1].replace(/[\\\/]?/, ""); }})) .pipe(gulp.dest("./")) .pipe(notify({ message: "editormd.js task complete" })); }); gulp.task("amd", function() { var replaceText1 = [ 'var cmModePath = "codemirror/mode/";', ' var cmAddonPath = "codemirror/addon/";', '', ' var codeMirrorModules = [', ' "jquery", "marked", "prettify",', ' "katex", "raphael", "underscore", "flowchart", "jqueryflowchart", "sequenceDiagram",', '', ' "codemirror/lib/codemirror",', ' cmModePath + "css/css",', ' cmModePath + "sass/sass",', ' cmModePath + "shell/shell",', ' cmModePath + "sql/sql",', ' cmModePath + "clike/clike",', ' cmModePath + "php/php",', ' cmModePath + "xml/xml",', ' cmModePath + "markdown/markdown",', ' cmModePath + "javascript/javascript",', ' cmModePath + "htmlmixed/htmlmixed",', ' cmModePath + "gfm/gfm",', ' cmModePath + "http/http",', ' cmModePath + "go/go",', ' cmModePath + "dart/dart",', ' cmModePath + "coffeescript/coffeescript",', ' cmModePath + "nginx/nginx",', ' cmModePath + "python/python",', ' cmModePath + "perl/perl",', ' cmModePath + "lua/lua",', ' cmModePath + "r/r", ', ' cmModePath + "ruby/ruby", ', ' cmModePath + "rst/rst",', ' cmModePath + "smartymixed/smartymixed",', ' cmModePath + "vb/vb",', ' cmModePath + "vbscript/vbscript",', ' cmModePath + "velocity/velocity",', ' cmModePath + "xquery/xquery",', ' cmModePath + "yaml/yaml",', ' cmModePath + "erlang/erlang",', ' cmModePath + "jade/jade",', '', ' cmAddonPath + "edit/trailingspace", ', ' cmAddonPath + "dialog/dialog", ', ' cmAddonPath + "search/searchcursor", ', ' cmAddonPath + "search/search", ', ' cmAddonPath + "scroll/annotatescrollbar", ', ' cmAddonPath + "search/matchesonscrollbar", ', ' cmAddonPath + "display/placeholder", ', ' cmAddonPath + "edit/closetag", ', ' cmAddonPath + "fold/foldcode",', ' cmAddonPath + "fold/foldgutter",', ' cmAddonPath + "fold/indent-fold",', ' cmAddonPath + "fold/brace-fold",', ' cmAddonPath + "fold/xml-fold", ', ' cmAddonPath + "fold/markdown-fold",', ' cmAddonPath + "fold/comment-fold", ', ' cmAddonPath + "mode/overlay", ', ' cmAddonPath + "selection/active-line", ', ' cmAddonPath + "edit/closebrackets", ', ' cmAddonPath + "display/fullscreen",', ' cmAddonPath + "search/match-highlighter"', ' ];', '', ' define(codeMirrorModules, factory);' ].join("\r\n"); var replaceText2 = [ "if (typeof define == \"function\" && define.amd) {", " $ = arguments[0];", " marked = arguments[1];", " prettify = arguments[2];", " katex = arguments[3];", " Raphael = arguments[4];", " _ = arguments[5];", " flowchart = arguments[6];", " CodeMirror = arguments[9];", " }" ].join("\r\n"); gulp.src("src/editormd.js") .pipe(rename({ suffix: ".amd" })) .pipe(gulp.dest('./')) .pipe(header(headerComment, {pkg : pkg, fileName : function(file) { var name = file.path.split(file.base); return name[1].replace(/[\\\/]?/, ""); }})) .pipe(gulp.dest("./")) .pipe(replace("/* Require.js define replace */", replaceText1)) .pipe(gulp.dest('./')) .pipe(replace("/* Require.js assignment replace */", replaceText2)) .pipe(gulp.dest('./')) .pipe(rename({ suffix: ".min" })) .pipe(uglify()) //{outSourceMap: true, sourceRoot: './'} .pipe(gulp.dest("./")) .pipe(header(headerMiniComment, {pkg : pkg, fileName : function(file) { var name = file.path.split(file.base + ( (os.platform() === "win32") ? "\\" : "/") ); return name[1].replace(/[\\\/]?/, ""); }})) .pipe(gulp.dest("./")) .pipe(notify({ message: "amd version task complete"})); }); var codeMirror = { path : { src : { mode : "lib/codemirror/mode", addon : "lib/codemirror/addon" }, dist : "lib/codemirror" }, modes : [ "css", "sass", "shell", "sql", "clike", "php", "xml", "markdown", "javascript", "htmlmixed", "gfm", "http", "go", "dart", "coffeescript", "nginx", "python", "perl", "lua", "r", "ruby", "rst", "smartymixed", "vb", "vbscript", "velocity", "xquery", "yaml", "erlang", "jade", ], addons : [ "edit/trailingspace", "dialog/dialog", "search/searchcursor", "search/search", "scroll/annotatescrollbar", "search/matchesonscrollbar", "display/placeholder", "edit/closetag", "fold/foldcode", "fold/foldgutter", "fold/indent-fold", "fold/brace-fold", "fold/xml-fold", "fold/markdown-fold", "fold/comment-fold", "mode/overlay", "selection/active-line", "edit/closebrackets", "display/fullscreen", "search/match-highlighter" ] }; gulp.task("cm-mode", function() { var modes = [ codeMirror.path.src.mode + "/meta.js" ]; for(var i in codeMirror.modes) { var mode = codeMirror.modes[i]; modes.push(codeMirror.path.src.mode + "/" + mode + "/" + mode + ".js"); } return gulp.src(modes) .pipe(concat("modes.min.js")) .pipe(gulp.dest(codeMirror.path.dist)) .pipe(uglify()) // {outSourceMap: true, sourceRoot: codeMirror.path.dist} .pipe(gulp.dest(codeMirror.path.dist)) .pipe(header(headerMiniComment, {pkg : pkg, fileName : function(file) { var name = file.path.split(file.base + "\\"); return (name[1]?name[1]:name[0]).replace(/\\/g, ""); }})) .pipe(gulp.dest(codeMirror.path.dist)) .pipe(notify({ message: "codemirror-mode task complete!" })); }); gulp.task("cm-addon", function() { var addons = []; for(var i in codeMirror.addons) { var addon = codeMirror.addons[i]; addons.push(codeMirror.path.src.addon + "/" + addon + ".js"); } return gulp.src(addons) .pipe(concat("addons.min.js")) .pipe(gulp.dest(codeMirror.path.dist)) .pipe(uglify()) //{outSourceMap: true, sourceRoot: codeMirror.path.dist} .pipe(gulp.dest(codeMirror.path.dist)) .pipe(header(headerMiniComment, {pkg : pkg, fileName : function(file) { var name = file.path.split(file.base + "\\"); return (name[1]?name[1]:name[0]).replace(/\\/g, ""); }})) .pipe(gulp.dest(codeMirror.path.dist)) .pipe(notify({ message: "codemirror-addon.js task complete" })); }); /* gulp.task("jsdoc", function(){ return gulp.src(["./src/editormd.js", "README.md"]) .pipe(jsdoc.parser()) .pipe(jsdoc.generator("./docs/html")); }); gulp.task("jsdoc2md", function() { return gulp.src("src/js/editormd.js") .pipe(jsdoc2md()) .on("error", function(err){ gutil.log(gutil.colors.red("jsdoc2md failed"), err.message); }) .pipe(rename(function(path) { path.extname = ".md"; })) .pipe(gulp.dest("docs/markdown")); }); */ gulp.task("watch", function() { gulp.watch("scss/editormd.scss", ["scss"]); gulp.watch("scss/editormd.preview.scss", ["scss", "scss2"]); gulp.watch("scss/editormd.logo.scss", ["scss", "scss3"]); gulp.watch("src/editormd.js", ["js", "amd"]); }); gulp.task("default", function() { gulp.run("scss"); gulp.run("scss2"); gulp.run("scss3"); gulp.run("js"); gulp.run("amd"); gulp.run("cm-addon"); gulp.run("cm-mode"); });
Humsen/web/web-pc/WebContent/plugins/editormd/js/Gulpfile.js/0
{ "file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/js/Gulpfile.js", "repo_id": "Humsen", "token_count": 6950 }
57
// 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.defineOption("rulers", false, function(cm, val, old) { if (old && old != CodeMirror.Init) { clearRulers(cm); cm.off("refresh", refreshRulers); } if (val && val.length) { setRulers(cm); cm.on("refresh", refreshRulers); } }); function clearRulers(cm) { for (var i = cm.display.lineSpace.childNodes.length - 1; i >= 0; i--) { var node = cm.display.lineSpace.childNodes[i]; if (/(^|\s)CodeMirror-ruler($|\s)/.test(node.className)) node.parentNode.removeChild(node); } } function setRulers(cm) { var val = cm.getOption("rulers"); var cw = cm.defaultCharWidth(); var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left; var minH = cm.display.scroller.offsetHeight + 30; for (var i = 0; i < val.length; i++) { var elt = document.createElement("div"); elt.className = "CodeMirror-ruler"; var col, cls = null, conf = val[i]; if (typeof conf == "number") { col = conf; } else { col = conf.column; if (conf.className) elt.className += " " + conf.className; if (conf.color) elt.style.borderColor = conf.color; if (conf.lineStyle) elt.style.borderLeftStyle = conf.lineStyle; if (conf.width) elt.style.borderLeftWidth = conf.width; cls = val[i].className; } elt.style.left = (left + col * cw) + "px"; elt.style.top = "-50px"; elt.style.bottom = "-20px"; elt.style.minHeight = minH + "px"; cm.display.lineSpace.insertBefore(elt, cm.display.cursorDiv); } } function refreshRulers(cm) { clearRulers(cm); setRulers(cm); } });
Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/display/rulers.js/0
{ "file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/display/rulers.js", "repo_id": "Humsen", "token_count": 918 }
58
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../../mode/css/css")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../../mode/css/css"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var pseudoClasses = {link: 1, visited: 1, active: 1, hover: 1, focus: 1, "first-letter": 1, "first-line": 1, "first-child": 1, before: 1, after: 1, lang: 1}; CodeMirror.registerHelper("hint", "css", function(cm) { var cur = cm.getCursor(), token = cm.getTokenAt(cur); var inner = CodeMirror.innerMode(cm.getMode(), token.state); if (inner.mode.name != "css") return; var start = token.start, end = cur.ch, word = token.string.slice(0, end - start); if (/[^\w$_-]/.test(word)) { word = ""; start = end = cur.ch; } var spec = CodeMirror.resolveMode("text/css"); var result = []; function add(keywords) { for (var name in keywords) if (!word || name.lastIndexOf(word, 0) == 0) result.push(name); } var st = inner.state.state; if (st == "pseudo" || token.type == "variable-3") { add(pseudoClasses); } else if (st == "block" || st == "maybeprop") { add(spec.propertyKeywords); } else if (st == "prop" || st == "parens" || st == "at" || st == "params") { add(spec.valueKeywords); add(spec.colorKeywords); } else if (st == "media" || st == "media_parens") { add(spec.mediaTypes); add(spec.mediaFeatures); } if (result.length) return { list: result, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end) }; }); });
Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/hint/css-hint.js/0
{ "file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/hint/css-hint.js", "repo_id": "Humsen", "token_count": 810 }
59