text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
import { DateTime } from 'luxon' import ResourceTable from '../../../../src/components/FilesList/ResourceTable.vue' import { extractDomSelector, IncomingShareResource, Resource, ShareTypes, SpaceResource } from '@ownclouders/web-client/src/helpers' import { defaultPlugins, mount } from 'web-test-helpers' import { CapabilityStore } from '../../../../src/composables/piniaStores' import { displayPositionedDropdown } from '../../../../src/helpers/contextMenuDropdown' import { eventBus } from '../../../../src/services/eventBus' import { SideBarEventTopics } from '../../../../src/composables/sideBar' import { mock } from 'vitest-mock-extended' import { computed } from 'vue' import { Identity } from '@ownclouders/web-client/src/generated' const mockUseEmbedMode = vi.fn().mockReturnValue({ isLocationPicker: computed(() => false) }) vi.mock('../../../../src/helpers/contextMenuDropdown') vi.mock('../../../../src/composables/embedMode', () => ({ useEmbedMode: vi.fn().mockImplementation(() => mockUseEmbedMode()) })) const router = { push: vi.fn(), afterEach: vi.fn(), currentRoute: { name: 'some-route-name', query: {}, params: { driveAliasAndItem: '' } }, resolve: (r) => { return { href: r.name } } } const getCurrentDate = () => { return DateTime.fromJSDate(new Date()).minus({ days: 1 }).toFormat('EEE, dd MMM yyyy HH:mm:ss') } const fields = ['name', 'size', 'mdate', 'sdate', 'ddate', 'actions', 'sharedBy', 'sharedWith'] const sharedWith = [ { id: 'bob', displayName: 'Bob', shareType: ShareTypes.user.value }, { id: 'marie', displayName: 'Marie', shareType: ShareTypes.user.value }, { id: 'john', displayName: 'John Richards Emperor of long names', shareType: ShareTypes.user.value } ] as Array<{ shareType: number } & Identity> const owner = { id: 'bob', displayName: 'Bob' } as Resource['owner'] const sharedBy = [ { id: 'bob', displayName: 'Bob' } ] as Identity[] const indicators = [ { id: 'files-sharing', label: 'Shared with other people', visible: true, icon: 'group', handler: (resource, indicatorId) => alert(`Resource: ${resource.name}, indicator: ${indicatorId}`) }, { id: 'file-link', label: 'Shared via link', visible: true, icon: 'link' } ] const resourcesWithAllFields = [ { id: 'forest', driveId: 'forest', name: 'forest.jpg', path: 'images/nature/forest.jpg', extension: 'jpg', thumbnail: 'https://cdn.pixabay.com/photo/2015/09/09/16/05/forest-931706_960_720.jpg', indicators, isFolder: false, type: 'file', tags: ['space', 'tag', 'moon'], size: '111000234', mdate: getCurrentDate(), sdate: getCurrentDate(), ddate: getCurrentDate(), owner, sharedBy, sharedWith, hidden: false, syncEnabled: true, outgoing: false, shareRoles: [], sharePermissions: [], shareTypes: [], canRename: vi.fn(), getDomSelector: () => extractDomSelector('forest') }, { id: 'notes', driveId: 'notes', name: 'notes.txt', path: '/Documents/notes.txt', extension: 'txt', indicators, isFolder: false, type: 'file', size: 'big', tags: ['space', 'tag'], mdate: getCurrentDate(), sdate: getCurrentDate(), ddate: getCurrentDate(), owner, sharedBy, sharedWith, hidden: false, syncEnabled: true, outgoing: false, shareRoles: [], sharePermissions: [], shareTypes: [], canRename: vi.fn(), getDomSelector: () => extractDomSelector('notes') }, { id: 'documents', driveId: 'documents', name: 'Documents', path: '/Documents', indicators, isFolder: true, type: 'folder', size: '-1', tags: [], mdate: getCurrentDate(), sdate: getCurrentDate(), ddate: getCurrentDate(), owner, sharedBy, sharedWith, hidden: false, syncEnabled: true, outgoing: false, shareRoles: [], sharePermissions: [], shareTypes: [], canRename: vi.fn(), getDomSelector: () => extractDomSelector('documents') }, { id: 'another-one==', driveId: 'another-one==', name: 'Another one', path: '/Another one', indicators, isFolder: true, type: 'folder', size: '237895', mdate: getCurrentDate(), sdate: getCurrentDate(), ddate: getCurrentDate(), owner, sharedBy, sharedWith, hidden: false, syncEnabled: true, outgoing: false, shareRoles: [], sharePermissions: [], shareTypes: [], tags: [], canRename: vi.fn(), getDomSelector: () => extractDomSelector('another-one==') } ] as IncomingShareResource[] const processingResourcesWithAllFields = [ { id: 'rainforest', driveId: 'rainforest', name: 'rainforest.jpg', path: 'images/nature/rainforest.jpg', extension: 'jpg', thumbnail: 'https://cdn.pixabay.com/photo/2015/09/09/16/05/forest-931706_960_720.jpg', indicators, isFolder: false, type: 'file', tags: ['space', 'tag', 'moon'], size: '111000234', mdate: getCurrentDate(), sdate: getCurrentDate(), ddate: getCurrentDate(), owner, sharedBy, sharedWith, hidden: false, syncEnabled: true, outgoing: false, shareRoles: [], sharePermissions: [], shareTypes: [], canRename: vi.fn(), getDomSelector: () => extractDomSelector('forest'), processing: true }, { id: 'personalnotes', driveId: 'personalnotes', name: 'personalnotes.txt', path: '/Documents/personalnotes.txt', extension: 'txt', indicators, isFolder: false, type: 'file', size: 'big', tags: ['space', 'tag'], mdate: getCurrentDate(), sdate: getCurrentDate(), ddate: getCurrentDate(), owner, sharedBy, sharedWith, hidden: false, syncEnabled: true, outgoing: false, shareRoles: [], sharePermissions: [], shareTypes: [], canRename: vi.fn(), getDomSelector: () => extractDomSelector('notes'), processing: true } ] as IncomingShareResource[] describe('ResourceTable', () => { it('displays all known fields of the resources', () => { const { wrapper } = getMountedWrapper() for (const field of fields) { expect(wrapper.findAll('.oc-table-header-cell-' + field).length).toEqual(1) expect(wrapper.findAll('.oc-table-data-cell-' + field).length).toEqual( resourcesWithAllFields.length ) } }) it('accepts resourceDomId closure', () => { const { wrapper } = getMountedWrapper({ props: { resourceDomSelector: (resource) => ['custom', resource.getDomSelector()].join('-') } }) resourcesWithAllFields.forEach((resource) => { ;['.oc-tbody-tr', '#resource-table-select', '#context-menu-drop'].forEach((baseSelector) => { expect( wrapper.find([baseSelector, 'custom', resource.getDomSelector()].join('-')).exists() ).toBeTruthy() }) }) }) it('formats the resource size to a human readable format', () => { const { wrapper } = getMountedWrapper() expect(wrapper.find('.oc-tbody-tr-forest .oc-table-data-cell-size').text()).toEqual('111 MB') expect(wrapper.find('.oc-tbody-tr-documents .oc-table-data-cell-size').text()).toEqual('--') expect(wrapper.find('.oc-tbody-tr-notes .oc-table-data-cell-size').text()).toEqual('?') }) describe('resource selection', () => { it('adds resources to selection model via checkboxes', () => { const { wrapper } = getMountedWrapper() wrapper.find('.resource-table-select-all .oc-checkbox').setValue(true) wrapper.find('.oc-tbody-tr-documents .oc-checkbox').setValue(true) expect(wrapper.emitted('update:selectedIds').length).toBe(2) }) it('does not add resources that are disabled to selection model via checkboxes', () => { const { wrapper } = getMountedWrapper({ addProcessingResources: true }) wrapper.find('.resource-table-select-all .oc-checkbox').setValue(true) expect(wrapper.emitted('update:selectedIds')[0][0]).not.toContain( processingResourcesWithAllFields[0].id ) expect(wrapper.emitted('update:selectedIds')[0][0]).not.toContain( processingResourcesWithAllFields[1].id ) }) describe('all rows already selected', () => { it('de-selects all resources via the select-all checkbox', async () => { const { wrapper } = getMountedWrapper({ props: { selectedIds: resourcesWithAllFields.map((resource) => resource.id) } }) await wrapper.find('.resource-table-select-all .oc-checkbox').setValue(false) expect(wrapper.emitted<string>('update:selectedIds')[0][0].length).toBe(0) }) }) describe('embed mode location target', () => { it('should not hide checkboxes when embed mode does not have location as target', () => { mockUseEmbedMode.mockReturnValue({ isLocationPicker: computed(() => false) }) const { wrapper } = getMountedWrapper() expect(wrapper.find('.resource-table-select-all').exists()).toBe(true) expect(wrapper.find('.resource-table-select-all .oc-checkbox').exists()).toBe(true) }) it('should hide checkboxes when embed mode has location as target', () => { mockUseEmbedMode.mockReturnValue({ isLocationPicker: computed(() => true) }) const { wrapper } = getMountedWrapper() expect(wrapper.find('.resource-table-select-all').exists()).toBe(false) expect(wrapper.find('.resource-table-select-all .oc-checkbox').exists()).toBe(false) }) }) }) describe('resource activation', () => { it('emits fileClick upon clicking on a resource name', async () => { const { wrapper } = getMountedWrapper() const tr = await wrapper.find('.oc-tbody-tr-forest .oc-resource-name') await tr.trigger('click') expect(wrapper.emitted().fileClick[0][0].resources[0].name).toMatch('forest.jpg') }) it('does not emit fileClick upon clicking on a disabled resource name', async () => { const { wrapper } = getMountedWrapper({ addProcessingResources: true }) const tr = await wrapper.find('.oc-tbody-tr-rainforest .oc-resource-name') await tr.trigger('click') expect(wrapper.emitted().fileClick).toBeUndefined() }) }) describe('resource details', () => { it('emits select event when clicking on the row', async () => { const { wrapper } = getMountedWrapper() const tableRow = await wrapper.find('.oc-tbody-tr-forest .oc-table-data-cell-size') await tableRow.trigger('click') expect(wrapper.emitted('update:selectedIds')).toBeTruthy() }) it('does not emit select event when clicking on the row of a disabled resource', async () => { const { wrapper } = getMountedWrapper({ addProcessingResources: true }) const tableRow = await wrapper.find('.oc-tbody-tr-rainforest .oc-table-data-cell-size') await tableRow.trigger('click') expect(wrapper.emitted('update:selectedIds')).toBeUndefined() }) }) describe('context menu', () => { it('emits select event on contextmenu click', async () => { const spyDisplayPositionedDropdown = vi.mocked(displayPositionedDropdown) const { wrapper } = getMountedWrapper() await wrapper.find('.oc-tbody-tr').trigger('contextmenu') expect(wrapper.emitted('update:selectedIds').length).toBe(1) expect(spyDisplayPositionedDropdown).toHaveBeenCalledTimes(1) }) it('does not emit select event on contextmenu click of disabled resource', async () => { const spyDisplayPositionedDropdown = vi.mocked(displayPositionedDropdown) const { wrapper } = getMountedWrapper({ addProcessingResources: true }) await wrapper.find('.oc-tbody-tr-rainforest').trigger('contextmenu') expect(wrapper.emitted('update:selectedIds')).toBeUndefined() expect(spyDisplayPositionedDropdown).not.toHaveBeenCalled() }) it('emits select event on clicking the three-dot icon in table row', async () => { const spyDisplayPositionedDropdown = vi.mocked(displayPositionedDropdown) const { wrapper } = getMountedWrapper() await wrapper .find('.oc-table-data-cell-actions .resource-table-btn-action-dropdown') .trigger('click') expect(wrapper.emitted('update:selectedIds').length).toBe(1) expect(spyDisplayPositionedDropdown).toHaveBeenCalledTimes(1) }) it('does not emit select event on clicking the three-dot icon in table row of a disabled resource', async () => { const spyDisplayPositionedDropdown = vi.mocked(displayPositionedDropdown) const { wrapper } = getMountedWrapper({ addProcessingResources: true }) await wrapper .find( '.oc-tbody-tr-rainforest .oc-table-data-cell-actions .resource-table-btn-action-dropdown' ) .trigger('click') expect(wrapper.emitted('update:selectedIds')).toBeUndefined() expect(spyDisplayPositionedDropdown).toHaveBeenCalledTimes(0) }) it('removes invalid chars from item ids for usage in html template', async () => { const { wrapper } = getMountedWrapper() const contextMenuTriggers = await wrapper.findAll('.resource-table-btn-action-dropdown') for (let i = 0; i < contextMenuTriggers.length; i++) { const id = contextMenuTriggers.at(i).attributes().id expect(id).not.toBeUndefined() expect(id).toEqual(expect.not.stringContaining('=')) } }) }) describe('hover effect', () => { it('is disabled by default', () => { const { wrapper } = getMountedWrapper({ props: { hover: false } }) expect(wrapper.find('table').classes()).not.toContain('oc-table-hover') }) it('can be enabled', () => { const { wrapper } = getMountedWrapper({ props: { hover: true } }) expect(wrapper.find('table').classes()).toContain('oc-table-hover') }) }) describe('tags', () => { describe('inline', () => { it.each([ { tags: [], tagCount: 0 }, { tags: ['1'], tagCount: 1 }, { tags: ['1', '2'], tagCount: 2 }, { tags: ['1', '2', '3'], tagCount: 2 }, { tags: ['1', '2', '3', '4'], tagCount: 2 } ])('render 2 tags max', (data) => { const { tags, tagCount } = data const resource = mock<Resource>({ id: '1', tags }) const { wrapper } = getMountedWrapper({ props: { resources: [resource] } }) const resourceRow = wrapper.find(`[data-item-id="${resource.id}"]`) expect(resourceRow.findAll('.resource-table-tag').length).toBe(tagCount) }) it('render router link if user is authenticated', () => { const resource = mock<Resource>({ id: '1', tags: ['1'] }) const { wrapper } = getMountedWrapper({ props: { resources: [resource] } }) const resourceRow = wrapper.find(`[data-item-id="${resource.id}"]`) expect(resourceRow.find('.resource-table-tag-wrapper').element.tagName).toEqual( 'ROUTER-LINK-STUB' ) }) it('do not render router link if user is not authenticated', () => { const resource = mock<Resource>({ id: '1', tags: ['1'] }) const { wrapper } = getMountedWrapper({ props: { resources: [resource] }, userContextReady: false }) const resourceRow = wrapper.find(`[data-item-id="${resource.id}"]`) expect(resourceRow.find('.resource-table-tag-wrapper').element.tagName).toEqual('SPAN') }) }) describe('"more"-button', () => { it.each([ { tags: [], renderButton: false }, { tags: ['1'], renderButton: false }, { tags: ['1', '2'], renderButton: false }, { tags: ['1', '2', '3'], renderButton: true }, { tags: ['1', '2', '3', '4'], renderButton: true } ])('does only render when the resource has 3 tags or more', (data) => { const { tags, renderButton } = data const resource = mock<Resource>({ id: '1', tags }) const { wrapper } = getMountedWrapper({ props: { resources: [resource] } }) const resourceRow = wrapper.find(`[data-item-id="${resource.id}"]`) expect(resourceRow.find('.resource-table-tag-more').exists()).toBe(renderButton) }) it('opens sidebar on click', async () => { const spyBus = vi.spyOn(eventBus, 'publish') const resource = mock<Resource>({ id: '1', tags: ['1', '2', '3'] }) const { wrapper } = getMountedWrapper({ props: { resources: [resource] } }) const resourceRow = wrapper.find(`[data-item-id="${resource.id}"]`) await resourceRow.find('.resource-table-tag-more').trigger('click') expect(spyBus).toHaveBeenCalledWith(SideBarEventTopics.open) }) }) }) }) function getMountedWrapper({ props = {}, userContextReady = true, addProcessingResources = false } = {}) { const capabilities = { files: { tags: true } } satisfies Partial<CapabilityStore['capabilities']> return { wrapper: mount(ResourceTable, { props: { resources: [ ...resourcesWithAllFields, ...(addProcessingResources ? processingResourcesWithAllFields : []) ], selection: [], hover: false, space: mock<SpaceResource>({ getDriveAliasAndItem: vi.fn() }), ...props }, global: { renderStubDefaultSlot: true, plugins: [ ...defaultPlugins({ piniaOptions: { authState: { userContextReady }, capabilityState: { capabilities }, configState: { options: { displayResourcesLazy: false } } } }) ], stubs: { OcButton: false, 'router-link': true }, mocks: { $route: router.currentRoute, $router: router }, provide: { $router: router, $route: router.currentRoute } } }) } }
owncloud/web/packages/web-pkg/tests/unit/components/FilesList/ResourceTable.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/FilesList/ResourceTable.spec.ts", "repo_id": "owncloud", "token_count": 7197 }
797
import QuotaSelect from '../../../src/components/QuotaSelect.vue' import { defaultPlugins, shallowMount } from 'web-test-helpers' describe('QuotaSelect', () => { describe('method "optionSelectable"', () => { it('should return true while option selectable property is not false', () => { const { wrapper } = getWrapper() expect(wrapper.vm.optionSelectable({ selectable: true })).toBeTruthy() expect(wrapper.vm.optionSelectable({})).toBeTruthy() }) it('should return false while option selectable property is false', () => { const { wrapper } = getWrapper() expect(wrapper.vm.optionSelectable({ selectable: false })).toBeFalsy() }) }) describe('method "createOption"', () => { it('should create option', () => { const { wrapper } = getWrapper() expect(wrapper.vm.createOption('3')).toEqual({ displayValue: '3 GB', value: 3 * Math.pow(10, 9) }) }) it('should contain error property while maxQuota will be exceeded', () => { const { wrapper } = getWrapper({ maxQuota: 3 * Math.pow(10, 9) }) expect(wrapper.vm.createOption('2000')).toHaveProperty('error') }) it('should contain error property while creating an invalid option', () => { const { wrapper } = getWrapper() expect(wrapper.vm.createOption('lorem ipsum')).toHaveProperty('error') expect(wrapper.vm.createOption('1,')).toHaveProperty('error') expect(wrapper.vm.createOption('1.')).toHaveProperty('error') }) }) describe('method "setOptions"', () => { it('should set options to default options', () => { const { wrapper } = getWrapper() wrapper.vm.setOptions() expect(wrapper.vm.options).toEqual(wrapper.vm.DEFAULT_OPTIONS) }) it('should contain default options and user defined option if set', () => { const { wrapper } = getWrapper({ totalQuota: 45 * Math.pow(10, 9) }) wrapper.vm.setOptions() expect(wrapper.vm.options).toEqual( expect.arrayContaining([ ...wrapper.vm.DEFAULT_OPTIONS, { displayValue: '45 GB', value: 45 * Math.pow(10, 9), selectable: true } ]) ) }) it('should only contain lower or equal options when max quota is set', () => { const { wrapper } = getWrapper({ totalQuota: 2 * Math.pow(10, 9), maxQuota: 4 * Math.pow(10, 9) }) wrapper.vm.setOptions() expect(wrapper.vm.options).toEqual( expect.arrayContaining([ { displayValue: '1 GB', value: Math.pow(10, 9) }, { displayValue: '2 GB', value: 2 * Math.pow(10, 9) } ]) ) }) it('should contain a non selectable option if preset quota is higher than max quota', () => { const { wrapper } = getWrapper({ totalQuota: 100 * Math.pow(10, 9), maxQuota: 4 * Math.pow(10, 9) }) wrapper.vm.setOptions() expect(wrapper.vm.options).toEqual( expect.arrayContaining([ { displayValue: '1 GB', value: Math.pow(10, 9) }, { displayValue: '2 GB', value: 2 * Math.pow(10, 9) }, { displayValue: '100 GB', value: 100 * Math.pow(10, 9), selectable: false } ]) ) }) }) }) function getWrapper({ totalQuota = 10 * Math.pow(10, 9), maxQuota = 0 } = {}) { return { wrapper: shallowMount(QuotaSelect, { data: () => { return { selectedOption: { value: 10 * Math.pow(10, 9) }, options: [] } }, props: { totalQuota, maxQuota, title: 'Personal quota' }, global: { plugins: [...defaultPlugins()] } }) } }
owncloud/web/packages/web-pkg/tests/unit/components/QuotaSelect.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/QuotaSelect.spec.ts", "repo_id": "owncloud", "token_count": 1760 }
798
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`Multiple Details SideBar Panel > displays the details side panel 1`] = ` "<div id="oc-spaces-details-multiple-sidebar"> <div class="spaces-preview oc-mb"> <div class="spaces-preview-body"> <oc-icon-stub name="layout-grid" filltype="fill" accessiblelabel="" type="span" size="xxlarge" variation="passive" color="" class="preview-icon"></oc-icon-stub> <p class="preview-text">1 space selected</p> </div> </div> <div> <table class="details-table" aria-label="Overview of the information about the selected spaces"> <tr> <th scope="col" class="oc-pr-s oc-font-semibold">Total quota:</th> <td>1 kB</td> </tr> <tr> <th scope="col" class="oc-pr-s oc-font-semibold">Remaining quota:</th> <td>900 B</td> </tr> <tr> <th scope="col" class="oc-pr-s oc-font-semibold">Used quota:</th> <td>100 B</td> </tr> <tr> <th scope="col" class="oc-pr-s oc-font-semibold">Enabled:</th> <td>1</td> </tr> <tr> <th scope="col" class="oc-pr-s oc-font-semibold">Disabled:</th> <td>0</td> </tr> </table> </div> </div>" `;
owncloud/web/packages/web-pkg/tests/unit/components/sidebar/Spaces/Details/__snapshots__/SpaceDetailsMultiple.spec.ts.snap/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/sidebar/Spaces/Details/__snapshots__/SpaceDetailsMultiple.spec.ts.snap", "repo_id": "owncloud", "token_count": 584 }
799
import { useFileActionsRestore } from '../../../../../src/composables/actions' import { createLocationTrash, createLocationSpaces } from '../../../../../src/router' import { mock } from 'vitest-mock-extended' import { defaultComponentMocks, getComposableWrapper, RouteLocation } from 'web-test-helpers' import { useMessages, useResourcesStore } from '../../../../../src/composables/piniaStores' import { unref } from 'vue' import { Resource } from '@ownclouders/web-client' import { ProjectSpaceResource, SpaceResource } from '@ownclouders/web-client/src/helpers' import { LoadingTaskCallbackArguments } from '../../../../../src/services/loadingService' import { Drive } from '@ownclouders/web-client/src/generated' import { AxiosResponse } from 'axios' describe('restore', () => { describe('isVisible property', () => { it('should be false when no resource is given', () => { getWrapper({ setup: ({ actions }, { space }) => { expect( unref(actions)[0].isVisible({ space, resources: [] as Resource[] }) ).toBe(false) } }) }) it('should be true when permission is sufficient', () => { getWrapper({ setup: ({ actions }, { space }) => { expect( unref(actions)[0].isVisible({ space, resources: [{ canBeRestored: () => true }] as Resource[] }) ).toBe(true) } }) }) it('should be false when permission is not sufficient', () => { getWrapper({ setup: ({ actions }, { space }) => { expect( unref(actions)[0].isVisible({ space, resources: [{ canBeRestored: () => false }] as Resource[] }) ).toBe(false) } }) }) it('should be false when location is invalid', () => { getWrapper({ invalidLocation: true, setup: ({ actions }, { space }) => { expect(unref(actions)[0].isVisible({ space, resources: [{}] as Resource[] })).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('method "restoreResources"', () => { it('should show message on success', () => { getWrapper({ setup: async ({ restoreResources }, { space }) => { await restoreResources( space, [{ id: '1', path: '/1' }], [], mock<LoadingTaskCallbackArguments>() ) const { showMessage } = useMessages() expect(showMessage).toHaveBeenCalledTimes(1) const { removeResources, resetSelection } = useResourcesStore() expect(removeResources).toHaveBeenCalledTimes(1) expect(resetSelection).toHaveBeenCalledTimes(1) } }) }) it('should show message on error', () => { vi.spyOn(console, 'error').mockImplementation(() => undefined) getWrapper({ resolveClearTrashBin: false, setup: async ({ restoreResources }, { space }) => { await restoreResources( space, [{ id: '1', path: '/1' }], [], mock<LoadingTaskCallbackArguments>() ) const { showErrorMessage } = useMessages() expect(showErrorMessage).toHaveBeenCalledTimes(1) const { removeResources } = useResourcesStore() expect(removeResources).toHaveBeenCalledTimes(0) } }) }) it('should request parent folder on collecting restore conflicts', () => { getWrapper({ setup: async ({ collectConflicts }, { space, clientService }) => { const resource = { id: '1', path: '1', name: '1' } as Resource await collectConflicts(space, [resource]) expect(clientService.webdav.listFiles).toHaveBeenCalledWith(expect.anything(), { path: '.' }) } }) }) it('should find conflict within resources', () => { getWrapper({ setup: async ({ collectConflicts }, { space }) => { const resourceOne = { id: '1', path: '1', name: '1' } as Resource const resourceTwo = { id: '2', path: '1', name: '1' } as Resource const { conflicts } = await collectConflicts(space, [resourceOne, resourceTwo]) expect(conflicts).toContain(resourceTwo) } }) }) it('should add files without conflict to resolved resources', () => { getWrapper({ setup: async ({ collectConflicts }, { space }) => { const resource = { id: '1', path: '1', name: '1' } as Resource const { resolvedResources } = await collectConflicts(space, [resource]) expect(resolvedResources).toContain(resource) } }) }) }) }) function getWrapper({ invalidLocation = false, resolveClearTrashBin: resolveRestore = true, driveType = 'personal', setup }: { invalidLocation?: boolean resolveClearTrashBin?: boolean driveType?: string setup: ( instance: ReturnType<typeof useFileActionsRestore>, { space }: { space: SpaceResource router: ReturnType<typeof defaultComponentMocks>['$router'] clientService: ReturnType<typeof defaultComponentMocks>['$clientService'] } ) => 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 }) } mocks.$clientService.webdav.listFiles.mockImplementation(() => { return Promise.resolve({ resource: mock<Resource>(), children: [] }) }) if (resolveRestore) { mocks.$clientService.webdav.restoreFile.mockResolvedValue(undefined) } else { mocks.$clientService.webdav.restoreFile.mockRejectedValue(new Error('')) } mocks.$clientService.graphAuthenticated.drives.getDrive.mockResolvedValue( mock<AxiosResponse>({ data: { value: mock<Drive>() } }) ) return { mocks, wrapper: getComposableWrapper( () => { const instance = useFileActionsRestore() setup(instance, { space: mocks.space, router: mocks.$router, clientService: mocks.$clientService }) }, { mocks, provide: mocks } ) } }
owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsRestore.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsRestore.spec.ts", "repo_id": "owncloud", "token_count": 2913 }
800
import { getComposableWrapper } from 'web-test-helpers' import { mock } from 'vitest-mock-extended' import { Resource, SpaceResource } from '@ownclouders/web-client' import { useFileActions, Action, useOpenWithDefaultApp } from '../../../../src/composables' vi.mock('../../../../src/composables/actions/files', async (importOriginal) => ({ ...(await importOriginal<any>()), useFileActions: vi.fn() })) describe('useOpenWithDefaultApp', () => { it('should be valid', () => { expect(useOpenWithDefaultApp).toBeDefined() }) describe('method "openWithDefaultApp"', () => { it('should call the default action handler for files', () => { getWrapper({ setup: ({ openWithDefaultApp }, { defaultEditorAction }) => { openWithDefaultApp({ space: mock<SpaceResource>(), resource: mock<Resource>({ isFolder: false }) }) expect(defaultEditorAction.handler).toHaveBeenCalled() } }) }) it('should not call the default action handler for folders', () => { getWrapper({ setup: ({ openWithDefaultApp }, { defaultEditorAction }) => { openWithDefaultApp({ space: mock<SpaceResource>(), resource: mock<Resource>({ isFolder: true }) }) expect(defaultEditorAction.handler).not.toHaveBeenCalled() } }) }) }) }) function getWrapper({ setup, defaultEditorAction = mock<Action>({ handler: vi.fn() }) }: { setup: ( instance: ReturnType<typeof useOpenWithDefaultApp>, mocks: { defaultEditorAction: any } ) => void defaultEditorAction?: any }) { vi.mocked(useFileActions).mockReturnValue( mock<ReturnType<typeof useFileActions>>({ getDefaultEditorAction: () => defaultEditorAction }) ) const mocks = { defaultEditorAction } return { wrapper: getComposableWrapper(() => { const instance = useOpenWithDefaultApp() setup(instance, mocks) }) } }
owncloud/web/packages/web-pkg/tests/unit/composables/actions/useOpenWithDefaultApp.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/useOpenWithDefaultApp.spec.ts", "repo_id": "owncloud", "token_count": 750 }
801
import { useRouteQuery } from '../../../../src/composables' import { Ref, nextTick, computed, ComputedRef, unref } from 'vue' import { getComposableWrapper, createRouter } from 'web-test-helpers' describe('useRouteQuery', () => { it('is reactive', async () => { const router = createRouter({ routes: [{ path: '/', redirect: null }] }) router.push('/') await router.isReady() let fooQuery: Ref let fooValue: ComputedRef const mocks = { $router: router } const wrapper = getComposableWrapper( () => { fooQuery = useRouteQuery('foo', '1') fooValue = computed(() => parseInt(fooQuery.value as string)) return { fooQuery, fooValue } }, { mocks, provide: mocks, template: `<div><div id="fooQuery">{{ fooQuery }}</div><div id="fooValue">{{ fooValue }}</div></div>` } ) expect(wrapper.find('#fooQuery').element.innerHTML).toBe('1') expect(wrapper.find('#fooValue').element.innerHTML).toBe('1') expect(typeof fooQuery.value).toBe('string') expect(fooQuery.value).toBe('1') expect(typeof fooValue.value).toBe('number') expect(fooValue.value).toBe(1) fooQuery.value = '2' // FIXME: why do we have to wait for so many ticks? // Why don't we have to do that for any other expectation in the whole file?! for (let i = 0; i < 33; i++) { await nextTick() } expect(wrapper.find('#fooQuery').element.innerHTML).toBe('2') expect(wrapper.find('#fooValue').element.innerHTML).toBe('2') await router.push({ path: '/', query: { foo: '3' } }) await nextTick() expect(wrapper.find('#fooQuery').element.innerHTML).toBe('3') expect(wrapper.find('#fooValue').element.innerHTML).toBe('3') await router.push({ path: '/', query: {} }) await nextTick() expect(wrapper.find('#fooQuery').element.innerHTML).toBe('1') expect(wrapper.find('#fooValue').element.innerHTML).toBe('1') }) it('has a default value if route query is not set', () => { const router = createRouter() const mocks = { $router: router } getComposableWrapper( async () => { const fooQuery = useRouteQuery('foo', 'defaultValue') expect(fooQuery.value).toBe('defaultValue') router.push({ path: '/', query: { foo: 'foo-1' } }) await nextTick() expect(fooQuery.value).toBe('foo-1') router.push({}) expect(fooQuery.value).toBe('defaultValue') }, { mocks, provide: mocks } ) }) it('should update on route query change', () => { const router = createRouter() const mocks = { $router: router } getComposableWrapper( async () => { const fooQuery = useRouteQuery('foo') const barQuery = useRouteQuery('bar') router.push({ path: '/', query: { foo: 'foo-1' } }) await nextTick() expect(fooQuery.value).toBe('foo-1') expect(barQuery.value).toBeFalsy() router.push({ query: { foo: 'foo-2' } }) expect(fooQuery.value).toBe('foo-2') expect(barQuery.value).toBeFalsy() router.push({ query: { foo: 'foo-3', bar: 'bar-1' } }) expect(fooQuery.value).toBe('foo-3') expect(barQuery.value).toBe('bar-1') }, { mocks, provide: mocks } ) }) it('should be undefined if route changes and query is not present', () => { const router = createRouter() const mocks = { $router: router } getComposableWrapper( async () => { const fooQuery = useRouteQuery('foo') router.push({ path: '/home', query: { foo: 'bar' } }) await nextTick() expect(fooQuery.value).toBe('bar') router.push({ path: '/sub' }) expect(fooQuery.value).toBeUndefined() }, { mocks, provide: mocks } ) }) it('should update route query', () => { const router = createRouter() const mocks = { $router: router } getComposableWrapper( async () => { const fooQuery = useRouteQuery('foo') router.push({ path: '/home' }) expect(fooQuery.value).toBeUndefined() fooQuery.value = 'changedThroughRef' await nextTick() expect(unref(router.currentRoute).query.foo).toBe('changedThroughRef') }, { mocks, provide: mocks } ) }) })
owncloud/web/packages/web-pkg/tests/unit/composables/router/useRouteQuery.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/router/useRouteQuery.spec.ts", "repo_id": "owncloud", "token_count": 1799 }
802
import { mock, mockDeep } from 'vitest-mock-extended' import { Resource } from '@ownclouders/web-client' import { ConflictDialog, ResolveConflict } from '../../../../../src/helpers/resource' import { useModals } from '../../../../../src/composables/piniaStores' import { setActivePinia } from 'pinia' import { createMockStore } from 'web-test-helpers' const getConflictDialogInstance = () => { return new ConflictDialog(vi.fn(), vi.fn()) } describe('conflict dialog', () => { describe('method "resolveAllConflicts"', () => { it('should return the resolved conflicts including the resource(s) and the strategy', async () => { const conflictDialog = getConflictDialogInstance() const strategy = mockDeep<ResolveConflict>() conflictDialog.resolveFileExists = vi.fn().mockImplementation(() => ({ strategy, doForAllConflicts: false })) const resource = mock<Resource>({ name: 'someFile.txt' }) const targetFolder = mock<Resource>({ path: '/' }) const targetFolderResources = [mock<Resource>({ path: '/someFile.txt' })] const resolvedConflicts = await conflictDialog.resolveAllConflicts( [resource], targetFolder, targetFolderResources ) expect(resolvedConflicts.length).toBe(1) expect(resolvedConflicts[0].resource).toEqual(resource) expect(resolvedConflicts[0].strategy).toEqual(strategy) }) }) describe('method "resolveFileExists"', () => { it('should create the modal in the end', () => { setActivePinia(createMockStore()) const { dispatchModal } = useModals() const conflictDialog = getConflictDialogInstance() conflictDialog.resolveFileExists(mock<Resource>(), 2, true) expect(dispatchModal).toHaveBeenCalledTimes(1) }) }) })
owncloud/web/packages/web-pkg/tests/unit/helpers/resource/conflictHandling/conflictDialog.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/resource/conflictHandling/conflictDialog.spec.ts", "repo_id": "owncloud", "token_count": 641 }
803
import { PasswordPolicyService } from '../../../src/services' import { createTestingPinia } from 'web-test-helpers' import { Language } from 'vue3-gettext' import { PasswordPolicyCapability } from '@ownclouders/web-client/src/ocs/capabilities' import { useCapabilityStore } from '../../../src/composables/piniaStores' describe('PasswordPolicyService', () => { describe('policy', () => { describe('contains the rules according to the capability', () => { it.each([ [{} as PasswordPolicyCapability, ['mustNotBeEmpty']], [{ min_characters: 2 } as PasswordPolicyCapability, ['atLeastCharacters']], [ { min_lowercase_characters: 2 } as PasswordPolicyCapability, ['atLeastLowercaseCharacters'] ], [ { min_uppercase_characters: 2 } as PasswordPolicyCapability, ['atLeastUppercaseCharacters'] ], [{ min_digits: 2 } as PasswordPolicyCapability, ['atLeastDigits']], [{ min_digits: 2 } as PasswordPolicyCapability, ['atLeastDigits']], [{ min_special_characters: 2 } as PasswordPolicyCapability, ['mustContain']], [ { max_characters: 72 } as PasswordPolicyCapability, ['mustNotBeEmpty', 'atMostCharacters'] ], [ { min_characters: 2, min_lowercase_characters: 2, min_uppercase_characters: 2, min_digits: 2, min_special_characters: 2, max_characters: 72 } as PasswordPolicyCapability, [ 'atLeastCharacters', 'atLeastUppercaseCharacters', 'atLeastLowercaseCharacters', 'atLeastDigits', 'mustContain', 'atMostCharacters' ] ] ])('capability "%s"', (capability: PasswordPolicyCapability, expected: Array<string>) => { const { passwordPolicyService, store } = getWrapper(capability) passwordPolicyService.initialize(store) expect(Object.keys(passwordPolicyService.getPolicy().rules)).toEqual(expected) }) }) describe('method "check"', () => { describe('test the password correctly against te defined rules', () => { it.each([ [{} as PasswordPolicyCapability, ['', 'o'], [false, true]], [ { min_characters: 2 } as PasswordPolicyCapability, ['', 'o', 'ow', 'ownCloud'], [false, false, true, true] ], [ { min_lowercase_characters: 2 } as PasswordPolicyCapability, ['', 'o', 'oWNCLOUD', 'ownCloud'], [false, false, false, true] ], [ { min_uppercase_characters: 2 } as PasswordPolicyCapability, ['', 'o', 'ownCloud', 'ownCLoud'], [false, false, false, true] ], [ { min_digits: 2 } as PasswordPolicyCapability, ['', '1', 'ownCloud1', 'ownCloud12'], [false, false, false, true] ], [ { min_special_characters: 2 } as PasswordPolicyCapability, ['', '!', 'ownCloud!', 'ownCloud!#'], [false, false, false, true] ], [ { max_characters: 2 } as PasswordPolicyCapability, ['ownCloud', 'ownC', 'ow', 'o'], [false, false, true, true] ], [ { min_characters: 8, min_lowercase_characters: 2, min_uppercase_characters: 2, min_digits: 2, min_special_characters: 2, max_characters: 72 } as PasswordPolicyCapability, ['öwnCloud', 'öwnCloudää', 'öwnCloudää12', 'öwnCloudäÄ12#!'], [false, false, false, true] ] ])( 'capability "%s, passwords "%s"', ( capability: PasswordPolicyCapability, passwords: Array<string>, expected: Array<boolean> ) => { const { passwordPolicyService, store } = getWrapper(capability) passwordPolicyService.initialize(store) const policy = passwordPolicyService.getPolicy() for (let i = 0; i < passwords.length; i++) { expect(policy.check(passwords[i])).toEqual(expected[i]) } } ) }) }) }) }) const getWrapper = (capability: PasswordPolicyCapability) => { createTestingPinia() const store = useCapabilityStore() store.capabilities.password_policy = capability return { store, passwordPolicyService: new PasswordPolicyService({ language: { current: 'en' } as Language }) } }
owncloud/web/packages/web-pkg/tests/unit/services/passwordPolicy.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/services/passwordPolicy.spec.ts", "repo_id": "owncloud", "token_count": 2209 }
804
<template> <nav id="mobile-nav"> <oc-button id="mobile-nav-button" appearance="raw"> {{ activeNavItem.name }} <oc-icon name="arrow-drop-down" /> </oc-button> <oc-drop drop-id="mobile-nav-drop" toggle="#mobile-nav-button" mode="click" padding-size="small" close-on-click > <oc-list> <li v-for="(item, index) in navItems" :key="index" class="mobile-nav-item oc-width-1-1"> <oc-button type="router-link" :appearance="item.active ? 'raw-inverse' : 'raw'" :variation="item.active ? 'primary' : 'passive'" :to="item.route" class="oc-display-block oc-p-s" :class="{ 'oc-background-primary-gradient router-link-active': item.active }" > <span class="oc-flex"> <oc-icon :name="item.icon" variation="inherit" /> <span class="oc-ml-m text" v-text="item.name" /> </span> </oc-button> </li> </oc-list> </oc-drop> </nav> </template> <script lang="ts"> import { computed, defineComponent, PropType, unref } from 'vue' import { NavItem } from '../helpers/navItems' export default defineComponent({ name: 'MobileNav', props: { navItems: { type: Array as PropType<NavItem[]>, required: true } }, setup(props) { const activeNavItem = computed(() => { return unref(props.navItems).find((n) => n.active) || props.navItems[0] }) return { activeNavItem } } }) </script>
owncloud/web/packages/web-runtime/src/components/MobileNav.vue/0
{ "file_path": "owncloud/web/packages/web-runtime/src/components/MobileNav.vue", "repo_id": "owncloud", "token_count": 727 }
805
export * from './useLayout'
owncloud/web/packages/web-runtime/src/composables/layout/index.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/composables/layout/index.ts", "repo_id": "owncloud", "token_count": 9 }
806
// just a dummy function to trick gettext tools function $gettext(msg: string): string { return msg } export const additionalTranslations = { admin: $gettext('Admin'), spaceAdmin: $gettext('Space Admin'), user: $gettext('User'), guest: $gettext('Guest'), activities: $gettext('Activities'), noActivities: $gettext('No activities'), virusDetectedActivity: $gettext( 'Virus "%{description}" detected. Please contact your administrator for more information.' ), virusScan: $gettext('Scan for viruses'), requestErrorDeniedByPolicy: $gettext('Operation denied due to security policies'), ocsErrorPasswordOnBannedList: $gettext( 'Unfortunately, your password is commonly used. please pick a harder-to-guess password for your safety' ), openAppFromSmartBanner: $gettext('OPEN') }
owncloud/web/packages/web-runtime/src/helpers/additionalTranslations.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/helpers/additionalTranslations.ts", "repo_id": "owncloud", "token_count": 235 }
807
<template> <div class="oc-login-card oc-position-center"> <img class="oc-login-logo" :src="logoImg" alt="" :aria-hidden="true" /> <div class="oc-login-card-body oc-width-medium"> <h2 class="oc-login-card-title" v-text="cardTitle" /> <p v-text="cardHint" /> </div> <div class="oc-login-card-footer oc-pt-rm"> <p> {{ footerSlogan }} </p> </div> </div> </template> <script lang="ts"> import { computed, defineComponent } from 'vue' import { useRouter, useThemeStore } from '@ownclouders/web-pkg' import { authService } from 'web-runtime/src/services/auth' import { useGettext } from 'vue3-gettext' import { storeToRefs } from 'pinia' export default defineComponent({ name: 'LogoutPage', setup() { const router = useRouter() const { $gettext } = useGettext() const themeStore = useThemeStore() const { currentTheme } = storeToRefs(themeStore) authService.logoutUser().then(() => { router.push({ name: 'login' }) }) const cardTitle = computed(() => { return $gettext('Logout in progress') }) const cardHint = computed(() => { return $gettext("Please wait while you're being logged out.") }) const footerSlogan = computed(() => currentTheme.value.common.slogan) const logoImg = computed(() => currentTheme.value.logo.login) return { logoImg, cardTitle, cardHint, footerSlogan } } }) </script>
owncloud/web/packages/web-runtime/src/pages/logout.vue/0
{ "file_path": "owncloud/web/packages/web-runtime/src/pages/logout.vue", "repo_id": "owncloud", "token_count": 585 }
808
import GdprExport from 'web-runtime/src/components/Account/GdprExport.vue' import { defaultComponentMocks, defaultPlugins, shallowMount } from 'web-test-helpers' import { mock, mockDeep } from 'vitest-mock-extended' import { ClientService } from '@ownclouders/web-pkg' import { Resource } from '@ownclouders/web-client/src' const selectors = { ocSpinnerStub: 'oc-spinner-stub', requestExportBtn: '[data-testid="request-export-btn"]', downloadExportBtn: '[data-testid="download-export-btn"]', exportInProgress: '[data-testid="export-in-process"]' } const downloadFile = vi.fn() vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({ ...(await importOriginal<any>()), useDownloadFile: vi.fn(() => ({ downloadFile })) })) describe('GdprExport component', () => { it('shows the loading spinner initially', () => { const { wrapper } = getWrapper() expect(wrapper.find(selectors.ocSpinnerStub).exists()).toBeTruthy() }) it('shows a "in progress"-hint', async () => { const { wrapper } = getWrapper(mock<Resource>({ processing: true })) await wrapper.vm.loadExportTask.last expect(wrapper.find(selectors.exportInProgress).exists()).toBeTruthy() }) describe('request button', () => { it('shows if no export is being processed', async () => { const { wrapper } = getWrapper(mock<Resource>({ processing: false })) await wrapper.vm.loadExportTask.last expect(wrapper.find(selectors.requestExportBtn).exists()).toBeTruthy() }) it('does not show when an export is being processed', async () => { const { wrapper } = getWrapper(mock<Resource>({ processing: true })) await wrapper.vm.loadExportTask.last expect(wrapper.find(selectors.requestExportBtn).exists()).toBeFalsy() }) it('triggers the export when being clicked', async () => { const { wrapper, mocks } = getWrapper(mock<Resource>({ processing: false })) await wrapper.vm.loadExportTask.last await wrapper.find(selectors.requestExportBtn).trigger('click') expect(mocks.$clientService.graphAuthenticated.users.exportPersonalData).toHaveBeenCalled() }) }) describe('download button', () => { it('shows if a gdpr export exists', async () => { const { wrapper } = getWrapper(mock<Resource>({ processing: false })) await wrapper.vm.loadExportTask.last expect(wrapper.find(selectors.downloadExportBtn).exists()).toBeTruthy() }) it('does not show if no export exists', async () => { const { wrapper } = getWrapper() await wrapper.vm.loadExportTask.last expect(wrapper.find(selectors.downloadExportBtn).exists()).toBeFalsy() }) it('triggers the download when being clicked', async () => { const { wrapper } = getWrapper(mock<Resource>({ processing: false })) await wrapper.vm.loadExportTask.last await wrapper.find(selectors.downloadExportBtn).trigger('click') expect(downloadFile).toHaveBeenCalled() }) }) }) function getWrapper(resource = undefined) { const clientService = mockDeep<ClientService>() if (resource) { clientService.webdav.getFileInfo.mockResolvedValue(resource) } else { clientService.webdav.getFileInfo.mockRejectedValue({ statusCode: 404 }) } const mocks = defaultComponentMocks() mocks.$clientService = clientService return { mocks, wrapper: shallowMount(GdprExport, { global: { mocks, provide: mocks, plugins: [...defaultPlugins()] } }) } }
owncloud/web/packages/web-runtime/tests/unit/components/Account/GdprExport.spec.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Account/GdprExport.spec.ts", "repo_id": "owncloud", "token_count": 1244 }
809
import { WebThemeType, useThemeStore } from '@ownclouders/web-pkg' import { mock } from 'vitest-mock-extended' import ThemeSwitcher from 'web-runtime/src/components/ThemeSwitcher.vue' import defaultTheme from 'web-runtime/themes/owncloud/theme.json' import { defaultPlugins, defaultStubs, mount } from 'web-test-helpers' const defaultOwnCloudTheme = { defaults: { ...defaultTheme.clients.web.defaults, common: defaultTheme.common }, themes: defaultTheme.clients.web.themes } describe('ThemeSwitcher component', () => { describe('restores', () => { it('light theme if light theme is saved in localstorage', async () => { const { wrapper } = getWrapper({ hasOnlyOneTheme: false }) const themeStore = useThemeStore() window.localStorage.setItem('oc_currentThemeName', 'Light Theme') themeStore.initializeThemes(defaultOwnCloudTheme) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() }) it('dark theme if dark theme is saved in localstorage', async () => { const { wrapper } = getWrapper() const themeStore = useThemeStore() window.localStorage.setItem('oc_currentThemeName', 'Dark Theme') themeStore.initializeThemes(defaultOwnCloudTheme) await wrapper.vm.$nextTick() expect(wrapper.html()).toMatchSnapshot() }) }) }) function getWrapper({ hasOnlyOneTheme = false } = {}) { const availableThemes = hasOnlyOneTheme ? [defaultTheme.clients.web.themes[0]] : defaultTheme.clients.web.themes return { wrapper: mount(ThemeSwitcher, { global: { plugins: [ ...defaultPlugins({ piniaOptions: { stubActions: false, themeState: { availableThemes, currentTheme: mock<WebThemeType>({ ...defaultOwnCloudTheme.defaults, ...defaultOwnCloudTheme.themes[0] }) } } }) ], stubs: { ...defaultStubs, 'oc-icon': true } } }) } }
owncloud/web/packages/web-runtime/tests/unit/components/Topbar/ThemeSwitcher.spec.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Topbar/ThemeSwitcher.spec.ts", "repo_id": "owncloud", "token_count": 838 }
810
import accessDenied from '../../../src/pages/accessDenied.vue' import { defaultComponentMocks, defaultPlugins, mount } from 'web-test-helpers' const selectors = { logInAgainButton: '#exitAnchor' } describe('access denied page', () => { it('renders component', () => { const { wrapper } = getWrapper() expect(wrapper.html()).toMatchSnapshot() }) describe('"Log in again" button', () => { it('navigates to "loginUrl" if set in config', () => { const loginUrl = 'https://myidp.int/login' const { wrapper } = getWrapper({ loginUrl }) const logInAgainButton = wrapper.find(selectors.logInAgainButton) const loginAgainUrl = new URL(logInAgainButton.attributes().href) loginAgainUrl.search = '' expect(logInAgainButton.exists()).toBeTruthy() expect(loginAgainUrl.toString()).toEqual(loginUrl) }) }) }) function getWrapper({ loginUrl = '' } = {}) { const mocks = { ...defaultComponentMocks() } return { mocks, wrapper: mount(accessDenied, { global: { plugins: [...defaultPlugins({ piniaOptions: { configState: { options: { loginUrl } } } })], mocks, provide: mocks } }) } }
owncloud/web/packages/web-runtime/tests/unit/pages/accessDenied.spec.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/tests/unit/pages/accessDenied.spec.ts", "repo_id": "owncloud", "token_count": 457 }
811
import { mount, VueWrapper } from '@vue/test-utils' import { defineComponent, nextTick } from 'vue' import { defaultPlugins, DefaultPluginsOptions } from './defaultPlugins' import { createRouter as _createRouter } from '../../web-runtime/src/router' import { createMemoryHistory, RouterOptions } from 'vue-router' import { DefinedComponent } from '@vue/test-utils/dist/types' export { mount, shallowMount } from '@vue/test-utils' vi.spyOn(console, 'warn').mockImplementation(() => undefined) export const getComposableWrapper = <T>( setup: (...args: any[]) => T, { mocks = undefined, provide = undefined, template = undefined, pluginOptions = undefined }: { mocks?: Record<string, unknown> provide?: Record<string, unknown> template?: string pluginOptions?: DefaultPluginsOptions } = {} ) => { return mount( defineComponent({ setup, template: template ? template : '<div></div>' }), { global: { plugins: [...defaultPlugins(pluginOptions)], ...(mocks && { mocks }), ...(provide && { provide }) } } ) } export const getOcSelectOptions = async ( wrapper: VueWrapper<unknown>, selector: string, options = { close: true } ) => { const selectElement = await wrapper.find(selector) await selectElement.find('input').trigger('click') await selectElement.find('.vs__dropdown-toggle').trigger('mousedown') const optionElements = selectElement.findAll<HTMLOptionElement>('.vs__dropdown-option') if (options.close) { await selectElement.find('.vs__search').trigger('blur') } return optionElements } export type { RouteLocation } from 'vue-router' export { RouterLinkStub } from '@vue/test-utils' export const createRouter = (options?: Partial<RouterOptions>) => _createRouter({ history: createMemoryHistory(), routes: [], strict: false, ...options }) export const writable = <T>(value: Readonly<T>): T => { return value as T } export const sleep = (ms: number) => { return new Promise((resolve) => setTimeout(resolve, ms)) } export const nextTicks = async (amount: number) => { for (let i = 0; i < amount - 1; i++) { await nextTick() } } export type ComponentProps<T extends DefinedComponent> = InstanceType<T>['$props'] export type PartialComponentProps<T extends DefinedComponent> = Partial<ComponentProps<T>>
owncloud/web/packages/web-test-helpers/src/helpers.ts/0
{ "file_path": "owncloud/web/packages/web-test-helpers/src/helpers.ts", "repo_id": "owncloud", "token_count": 819 }
812
sonar.projectKey=owncloud_web sonar.organization=owncloud-1 sonar.projectName=Web sonar.projectVersion=9.0.0-alpha.3 sonar.host.url=https://sonarcloud.io # ===================================================== # Meta-data for the project # ===================================================== sonar.links.homepage=https://github.com/owncloud/web sonar.links.ci=https://drone.owncloud.com/owncloud/web sonar.links.scm=https://github.com/owncloud/web sonar.links.issue=https://github.com/owncloud/web/issues # ===================================================== # Properties that will be shared amongst all modules # ===================================================== # SQ standard properties sonar.sources=. # Pull Requests sonar.pullrequest.provider=github sonar.pullrequest.github.repository=owncloud/web sonar.pullrequest.base=${env.SONAR_PULL_REQUEST_BASE} sonar.pullrequest.branch=${env.SONAR_PULL_REQUEST_BRANCH} sonar.pullrequest.key=${env.SONAR_PULL_REQUEST_KEY} # Properties specific to language plugins: sonar.javascript.lcov.reportPaths=coverage/lcov.info # Exclude files sonar.exclusions=docs/**,node_modules/**,deployments/**,**/tests/**,**/*.spec.ts,__mocks__/**,__fixtures__/**,dist/**,changelog/**,config/**,docker/**,release/**,**/package.json,package.json,rollup.config.js,nightwatch.conf.js,Makefile,Makefile.release,CHANGELOG.md,README.md,packages/web-client/src/generated/**,packages/web-test-helpers/**
owncloud/web/sonar-project.properties/0
{ "file_path": "owncloud/web/sonar-project.properties", "repo_id": "owncloud", "token_count": 468 }
813
const sleepWhenOutstandingAjaxCalls = function (result, retryWithZero) { // sleep in all cases, because even with zero calls we don't know if there isn't // one that might start in the next tick, so to be sure sleep again this.pause(this.globals.waitForConditionPollInterval) if (result.value > 0) { this.waitForOutstandingAjaxCalls(true) } else if (retryWithZero) { // retry in case another call just started this.waitForOutstandingAjaxCalls(false) } } exports.command = function (retryWithZero = true) { // init the ajax counter if it hasn't been initialized yet this.execute('return (typeof window.activeAjaxCount === "undefined")', [], function (result) { if (result.value === true) { throw Error( 'checking outstanding Ajax calls will not work without calling initAjaxCounter() first' ) } }) this.execute('return window.activeAjaxCount', [], (result) => sleepWhenOutstandingAjaxCalls.call(this, result, retryWithZero) ) return this }
owncloud/web/tests/acceptance/customCommands/waitForOutstandingAjaxCalls.js/0
{ "file_path": "owncloud/web/tests/acceptance/customCommands/waitForOutstandingAjaxCalls.js", "repo_id": "owncloud", "token_count": 338 }
814
# the tests skipped on OCIS are listed in issue https://github.com/owncloud/web/issues/7264 for further implementation in playwright Feature: Autocompletion of share-with names As a user I want to share files, with minimal typing, to the right people or groups So that I can efficiently share my files with other users or groups Background: Given the administrator has set the default folder for received shares to "Shares" in the server And these users have been created with default attributes and without skeleton files in the server but not initialized: | username | | regularuser | And these users have been created without initialization and without skeleton files in the server: | username | password | displayname | email | | two | %regular% | Brian Murphy | u2@oc.com.np | | u444 | %regular% | Four | u3@oc.com.np | And these groups have been created in the server: | groupname | | finance1 | | finance2 | And the setting "outgoing_server2server_share_enabled" of app "files_sharing" has been set to "no" in the server @issue-ocis-1317 @issue-ocis-1675 Scenario Outline: autocompletion of user having special characters in their displaynames Given these users have been created without initialization and without skeleton files in the server: | username | password | displayname | email | | normalusr | %regular% | <displayName> | msrmail@oc.com.np | And user "regularuser" has created file "data.zip" in the server And user "regularuser" has logged in using the webUI And the user has browsed to the personal page And the user has opened the share dialog for file "data.zip" When the user types "<search>" in the share-with-field Then only users and groups that contain the string "<search>" in their name or displayname should be listed in the autocomplete list on the webUI Examples: | displayName | search | | -_.ocusr | -_. | | _ocusr@ | _oc | @issue-ocis-1317 @issue-ocis-1675 Scenario Outline: autocompletion of groups having special characters in their names Given these groups have been created in the server: | groupname | | <group> | And user "regularuser" has created file "data.zip" in the server And user "regularuser" has logged in using the webUI And the user has browsed to the personal page And the user has opened the share dialog for file "data.zip" When the user types "<search>" in the share-with-field Then only users and groups that contain the string "<search>" in their name or displayname should be listed in the autocomplete list on the webUI Examples: | group | search | | @-_. | @-_ | | _ocgrp@ | _oc | | -_.ocgrp | -_. |
owncloud/web/tests/acceptance/features/webUISharingAutocompletion/shareAutocompletionSpecialChars.feature/0
{ "file_path": "owncloud/web/tests/acceptance/features/webUISharingAutocompletion/shareAutocompletionSpecialChars.feature", "repo_id": "owncloud", "token_count": 929 }
815
Feature: File Upload As a user I would like to be able to upload files via the WebUI So that I can store files in ownCloud Background: Given user "Alice" has been created with default attributes and without skeleton files in the server And user "Alice" has created folder "simple-folder" in the server And user "Alice" has uploaded file with content "initial content" to "lorem.txt" in the server And user "Alice" has uploaded file with content "initial content" to "simple-folder/lorem.txt" in the server And user "Alice" has logged in using the webUI @smokeTest @ocisSmokeTest Scenario: simple upload of a folder that does not exist before Given a folder "CUSTOM" has been created with the following files in separate sub-folders in the middleware | subFolder | file | | | lorem.txt | | sub1 | lorem.txt | | sub1 | new-lorem.txt | | sub2/sub3 | new-lorem.txt | When the user uploads folder "CUSTOM" using the webUI Then no message should be displayed on the webUI And folder "CUSTOM" should be listed on the webUI And as "Alice" folder "CUSTOM" should exist in the server And as "Alice" file "CUSTOM/lorem.txt" should exist in the server And as "Alice" file "CUSTOM/sub1/lorem.txt" should exist in the server And as "Alice" file "CUSTOM/sub1/new-lorem.txt" should exist in the server And as "Alice" file "CUSTOM/sub2/sub3/new-lorem.txt" should exist in the server And as "Alice" the content of "CUSTOM/lorem.txt" in the server should be the same as the content of local file "CUSTOM/lorem.txt" And as "Alice" the content of "CUSTOM/sub1/lorem.txt" in the server should be the same as the content of local file "CUSTOM/sub1/lorem.txt" And as "Alice" the content of "CUSTOM/sub1/new-lorem.txt" in the server should be the same as the content of local file "CUSTOM/sub1/new-lorem.txt" And as "Alice" the content of "CUSTOM/sub2/sub3/new-lorem.txt" in the server should be the same as the content of local file "CUSTOM/sub2/sub3/new-lorem.txt" @smokeTest @ocisSmokeTest Scenario: simple upload of a folder with subfolders that does not exist before When the user uploads folder "PARENT" using the webUI Then no message should be displayed on the webUI And folder "PARENT" should be listed on the webUI When the user browses to the folder "PARENT" on the files page Then the following resources should be listed on the webUI | entry_name | | parent.txt | | CHILD | And as "Alice" folder "PARENT" should exist in the server And as "Alice" file "PARENT/parent.txt" should exist in the server And as "Alice" folder "PARENT/CHILD" should exist in the server @smokeTest @ocisSmokeTest Scenario: Upload of a folder inside a subdirectory Given user "Alice" has created folder "simple-empty-folder" in the server And the user has reloaded the current page of the webUI When the user browses to the folder "simple-empty-folder" on the files page And the user uploads folder "PARENT" using the webUI Then no message should be displayed on the webUI And folder "PARENT" should be listed on the webUI When the user opens folder "PARENT" using the webUI Then the following resources should be listed on the webUI | entry_name | | parent.txt | | CHILD | And as "Alice" folder "simple-empty-folder/PARENT" should exist in the server And as "Alice" file "simple-empty-folder/PARENT/parent.txt" should exist in the server And as "Alice" folder "simple-empty-folder/PARENT/CHILD" should exist in the server @smokeTest @ocisSmokeTest Scenario: uploading a big file (when chunking is implemented this upload should be chunked) Given a file with the size of "30000000" bytes and the name "big-video.mp4" has been created locally in the middleware When the user uploads a created file "big-video.mp4" using the webUI Then no message should be displayed on the webUI And file "big-video.mp4" should be listed on the webUI And as "Alice" the content of "big-video.mp4" in the server should be the same as the content of local file "big-video.mp4" Scenario: conflict with a big file (when chunking is implemented this upload should be chunked) Given a file with the size of "30000000" bytes and the name "big-video.mp4" has been created locally in the middleware When the user renames file "lorem.txt" to "big-video.mp4" using the webUI And the user reloads the current page of the webUI And the user uploads a created file "big-video.mp4" with overwrite using the webUI Then file "big-video.mp4" should be listed on the webUI And as "Alice" the content of "big-video.mp4" in the server should be the same as the content of local file "big-video.mp4" @disablePreviews Scenario: overwrite an existing file in a sub-folder When the user opens folder "simple-folder" using the webUI And the user uploads overwriting file "lorem.txt" using the webUI Then file "lorem.txt" should be listed on the webUI And as "Alice" the content of "simple-folder/lorem.txt" in the server should be the same as the content of local file "lorem.txt" @issue-ocis-2258 @disablePreviews Scenario: upload overwriting a file into a public share Given user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions and password "#Passw0rd" in the server When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session And the user uploads overwriting file "lorem.txt" using the webUI Then file "lorem.txt" should be listed on the webUI And as "Alice" the content of "simple-folder/lorem.txt" in the server should be the same as the content of local file "lorem.txt" Scenario: simple upload of a folder, with comma in its name, that does not exist before When the user uploads folder "Folder,With,Comma" using the webUI Then no message should be displayed on the webUI And folder "Folder,With,Comma" should be listed on the webUI When the user browses to the folder "Folder,With,Comma" on the files page Then the following resources should be listed on the webUI | entry_name | | sunday,monday.txt | And as "Alice" folder "Folder,With,Comma" should exist in the server And as "Alice" file "Folder,With,Comma/sunday,monday.txt" should exist in the server
owncloud/web/tests/acceptance/features/webUIUpload/upload.feature/0
{ "file_path": "owncloud/web/tests/acceptance/features/webUIUpload/upload.feature", "repo_id": "owncloud", "token_count": 2107 }
816
module.exports = { /** * Returns an XPath string literal to use for searching values inside * element/attribute. * * This wraps them in single quotes, double quotes, or as a concat function, * as xpath expressions can contain single or double quotes but not both. * Also, xpath does not support escaping. * * {@link https://stackoverflow.com/q/1341847 Special Character in XPATH Query} * {@link https://stackoverflow.com/q/642125 Encoding XPath Expressions with both single and double quotes} * * @param {string} value * @returns {string} */ buildXpathLiteral: function (value) { if (!value.includes("'")) { // if we don't have any single quotes, then wrap them with single quotes return "'" + value + "'" } else if (!value.includes('"')) { // if we don't have any double quotes, then wrap them with double quotes return '"' + value + '"' } else { // use concat to find the literal in the xpath if they contain both quotes return "concat('" + value.replace(/'/g, "',\"'\",'") + "')" } } }
owncloud/web/tests/acceptance/helpers/xpath.js/0
{ "file_path": "owncloud/web/tests/acceptance/helpers/xpath.js", "repo_id": "owncloud", "token_count": 367 }
817
const util = require('util') module.exports = { commands: { isBatchActionButtonVisible: async function (batchButtonName, expectedVisible = true) { let result = false const batchActionButtonEl = { selector: this.getBatchActionButtonElementSelector(batchButtonName), locateStrategy: 'xpath' } await this.isVisible( { ...batchActionButtonEl, suppressNotFoundErrors: !expectedVisible }, (res) => { if (res.status === 0 && res.value === true) { result = res.value } } ) return result }, getBatchActionButtonElementSelector: function (batchButtonName) { return util.format(this.elements.batchActionButton.selector, batchButtonName) }, navigateToSharesSubPage: function (sharesSubPageButtonName) { const sharesSubPageBtn = { selector: util.format(this.elements.sharesSubPageButton.selector, sharesSubPageButtonName), locateStrategy: 'xpath' } return this.waitForElementVisible(sharesSubPageBtn).click(sharesSubPageBtn) } }, elements: { batchActionButton: { selector: '//div[contains(@class, "files-app-bar-actions")]//button/descendant-or-self::*[contains(text(),"%s")]', locateStrategy: 'xpath' }, sharesSubPageButton: { selector: '//nav[@id="shares-navigation"]//*[.="%s"]', locateStrategy: 'xpath' } } }
owncloud/web/tests/acceptance/pageObjects/appBarActions.js/0
{ "file_path": "owncloud/web/tests/acceptance/pageObjects/appBarActions.js", "repo_id": "owncloud", "token_count": 617 }
818
module.exports = { commands: { waitTillLoaded: function () { const element = this.elements.userDisabledMessage return this.useStrategy(element).waitForElementVisible(element) } }, elements: { userDisabledMessage: { locateStrategy: 'xpath', selector: '//li[normalize-space()="User disabled"]' } } }
owncloud/web/tests/acceptance/pageObjects/userDisabledPage.js/0
{ "file_path": "owncloud/web/tests/acceptance/pageObjects/userDisabledPage.js", "repo_id": "owncloud", "token_count": 135 }
819
const { client } = require('nightwatch-api') const assert = require('assert') const _ = require('lodash') const { Given, When, Then } = require('@cucumber/cucumber') const textEditor = client.page.textEditorPage() const filesList = client.page.FilesPageElement.filesList() Given('the user has opened file {string} in the text editor webUI', async (fileName) => { await filesList.clickOnFileName(fileName) await textEditor.waitForPageLoaded() const actualFileName = await textEditor.getFileName() return assertEqualText(fileName, actualFileName) }) When('the user opens file {string} in the text editor webUI', (fileName) => { return filesList.clickOnFileName(fileName) }) When('the user inputs the content {string} in the text editor webUI', async (content) => { return await textEditor.updateFileContent(content) }) When('the user appends the content {string} in the text editor webUI', async (content) => { return await textEditor.appendContentToFile(content) }) When('the user saves the file in the text editor webUI', async () => { return await textEditor.saveFileEdit() }) When('the user closes the text editor using the webUI', async () => { return await textEditor.closeTextEditor() }) Then('the file {string} should be displayed in the text editor webUI', async (fileName) => { const actualFileName = await textEditor.getFileName() return assertEqualText(fileName, actualFileName) }) Then('the file should have content {string} in the text editor webUI', async (content) => { const contentInEditor = await textEditor.getContentFromEditor() return assertEqualText(content, contentInEditor, 'content') }) Then('the file should not have content {string} in the text editor webUI', async (content) => { const contentInEditor = await textEditor.getContentFromEditor() return assertNotEqualText(content, contentInEditor, 'content') }) Then('the preview panel should have the content {string} on the webUI', async (content) => { const contentInPreview = await textEditor.getContentFromPanel() return assertEqualText(content, contentInPreview, 'content') }) When( 'the user opens file {string} in the text editor using the action menu option on the webUI', async (fileName) => { return await textEditor.openMdEditorUsingActionMenu(fileName) } ) Then( 'the preview panel should have {string} element with text {string}', async (tagName, innerText) => { return await assertHasElementWithText(tagName, innerText) } ) const assertEqualText = (expected, actual, type = 'file') => { let error = '' if (type === 'file') { error = 'File "' + expected + '" expected to be opened in the text editor but found "' + actual + '"' } else if (type === 'content') { error = 'File expected to have content "' + expected + '" but found "' + actual + '"' } return assert.strictEqual(actual, expected, error) } const assertNotEqualText = (expected, actual, type = 'file') => { let error = '' if (type === 'file') { error = 'File "' + expected + '" expected not to be opened in the text editor but found' } else if (type === 'content') { error = 'File expected not to have content "' + expected + '" but found.' } return assert.notStrictEqual(actual, expected, error) } const assertHasElementWithText = async (tagName, innerText) => { const previewPanel = textEditor.getPreviewPanelElement() const previewPanelButtonElement = textEditor.getPreviewPanelButtonElement() const searchElement = previewPanel + ' > ' + tagName let hasElement = false await client.waitForElementPresent(previewPanelButtonElement).click(previewPanelButtonElement) await client.waitForElementPresent(searchElement).getText(searchElement, (result) => { hasElement = _.isEqual(result.value, innerText) }) return assert.strictEqual( hasElement, true, 'Preview Panel expected to have element "' + tagName + '" with text "' + innerText + '" but not found' ) }
owncloud/web/tests/acceptance/stepDefinitions/textEditorContext.js/0
{ "file_path": "owncloud/web/tests/acceptance/stepDefinitions/textEditorContext.js", "repo_id": "owncloud", "token_count": 1188 }
820
import { World as CucumberWorld, IWorldOptions } from '@cucumber/cucumber' import { Pickle } from '@cucumber/messages' import { config } from '../../config' import { environment } from '../../support' import { state } from './shared' interface WorldOptions extends IWorldOptions { parameters: { [key: string]: string } } export class World extends CucumberWorld { feature: Pickle actorsEnvironment: environment.ActorsEnvironment filesEnvironment: environment.FilesEnvironment linksEnvironment: environment.LinksEnvironment spacesEnvironment: environment.SpacesEnvironment usersEnvironment: environment.UsersEnvironment constructor(options: WorldOptions) { super(options) this.usersEnvironment = new environment.UsersEnvironment() this.spacesEnvironment = new environment.SpacesEnvironment() this.filesEnvironment = new environment.FilesEnvironment() this.linksEnvironment = new environment.LinksEnvironment() this.actorsEnvironment = new environment.ActorsEnvironment({ context: { acceptDownloads: config.acceptDownloads, reportDir: config.reportDir, reportHar: config.reportHar, reportTracing: config.reportTracing, reportVideo: config.reportVideo }, browser: state.browser }) } }
owncloud/web/tests/e2e/cucumber/environment/world.ts/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/environment/world.ts", "repo_id": "owncloud", "token_count": 378 }
821
Feature: Application menu As a user I want to open the editor via the application menu So that I have instant access Scenario: Open text editor via application menu Given "Admin" creates following user using API | id | | Alice | And "Alice" logs in When "Alice" opens the "text-editor" app And "Alice" enters the text "Hello world" in editor "TextEditor" And "Alice" saves the file viewer And "Alice" closes the file viewer Then following resources should be displayed in the files list for user "Alice" | resource | | New file.txt | And "Alice" logs out
owncloud/web/tests/e2e/cucumber/features/smoke/applicationMenu.feature/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/applicationMenu.feature", "repo_id": "owncloud", "token_count": 200 }
822
Feature: Upload large resources As a user I want to upload large resources So that I can pause and resume the upload Scenario: Upload large resources in personal space Given "Admin" creates following user using API | id | | Alice | And the user creates a file "largefile.txt" of "1GB" size in the temp upload directory And "Alice" logs in And "Alice" opens the "files" app When "Alice" starts uploading the following large resources from the temp upload directory | resource | | largefile.txt | And "Alice" pauses the file upload And "Alice" cancels the file upload And "Alice" starts uploading the following large resources from the temp upload directory | resource | | largefile.txt | And "Alice" pauses the file upload And "Alice" resumes the file upload Then following resources should be displayed in the files list for user "Alice" | resource | | largefile.txt | And "Alice" logs out
owncloud/web/tests/e2e/cucumber/features/smoke/uploadResumable.feature/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/uploadResumable.feature", "repo_id": "owncloud", "token_count": 328 }
823
import { When } from '@cucumber/cucumber' import { World } from '../../environment' import { objects } from '../../../support' When( '{string} navigates to {string} details panel of file {string} of space {string} through the URL', async function ( this: World, stepUser: string, detailsPanel: string, resource: string, space: string ): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const user = this.usersEnvironment.getUser({ key: stepUser }) const urlNavObject = new objects.urlNavigation.URLNavigation({ page }) await urlNavObject.navigateToDetailsPanelOfResource({ resource, detailsPanel, user, space }) } ) When( /^"([^"]*)" opens the (?:resource|file|folder) "([^"]*)" of space "([^"]*)" through the URL$/, async function (this: World, stepUser: string, resource: string, space: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const user = this.usersEnvironment.getUser({ key: stepUser }) const urlNavObject = new objects.urlNavigation.URLNavigation({ page }) await urlNavObject.openResourceViaUrl({ resource, user, space }) } ) When( /^"([^"]*)" opens the file "([^"]*)" of space "([^"]*)" in (Collabora|OnlyOffice) through the URL for (mobile|desktop) client$/, async function ( this: World, stepUser: string, resource: string, space: string, editorName: string, client: string ): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const user = this.usersEnvironment.getUser({ key: stepUser }) const urlNavObject = new objects.urlNavigation.URLNavigation({ page }) await urlNavObject.openResourceViaUrl({ resource, user, space, editorName, client }) } ) When( '{string} opens space {string} through the URL', async function (this: World, stepUser: string, space: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const user = this.usersEnvironment.getUser({ key: stepUser }) const urlNavObject = new objects.urlNavigation.URLNavigation({ page }) await urlNavObject.openSpaceViaUrl({ user, space }) } )
owncloud/web/tests/e2e/cucumber/steps/ui/navigateByUrl.ts/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/steps/ui/navigateByUrl.ts", "repo_id": "owncloud", "token_count": 720 }
824
import { checkResponseStatus, request } from '../http' import { User } from '../../types' import join from 'join-path' import { getPersonalSpaceId, getSpaceIdBySpaceName } from '../graph' import { Response } from 'node-fetch' import convert from 'xml-js' import _ from 'lodash/object' import { createShare } from '../share' import { createTagsForResource } from '../graph/utils' export const folderExists = async ({ user, path }: { user: User path: string }): Promise<boolean> => { const getResponse = await request({ method: 'GET', path, user: user }) return getResponse.status === 200 } const createFolder = async ({ user, folder, webDavEndPathToRoot // the root of the WebDAV path. This is `spaces/<space-id>` for ocis or `files/<user>` for oC10 }: { user: User folder: string webDavEndPathToRoot: string }): Promise<void> => { const paths = folder.split('/') let parentFolder = '' for (const resource of paths) { const path = join('remote.php', 'dav', webDavEndPathToRoot, parentFolder, resource) // check if the folder exists already or not const folderExist = await folderExists({ user, path }) if (folderExist === false) { const response = await request({ method: 'MKCOL', path, user: user }) checkResponseStatus(response, 'Failed while creating folder') } parentFolder = join(parentFolder, resource) } } const createFile = async ({ user, pathToFile, content, webDavEndPathToRoot, // the root of the WebDAV path. This is `spaces/<space-id>` for ocis or `files/<user>` for oC10 mtimeDeltaDays }: { user: User pathToFile: string content: string | Buffer webDavEndPathToRoot: string mtimeDeltaDays?: string }): Promise<void> => { const today = new Date() const response = await request({ method: 'PUT', path: join('remote.php', 'dav', webDavEndPathToRoot, pathToFile), body: content, user: user, header: mtimeDeltaDays ? { 'X-OC-Mtime': today.getTime() / 1000 + parseInt(mtimeDeltaDays) * 86400 } : {} }) checkResponseStatus(response, `Failed while uploading file '${pathToFile}' in personal space`) } export const uploadFileInPersonalSpace = async ({ user, pathToFile, content, mtimeDeltaDays }: { user: User pathToFile: string content: string | Buffer mtimeDeltaDays?: string }): Promise<void> => { const webDavEndPathToRoot = 'spaces/' + (await getPersonalSpaceId({ user })) await createFile({ user, pathToFile, content, webDavEndPathToRoot, mtimeDeltaDays }) } export const createFolderInsideSpaceBySpaceName = async ({ user, folder, spaceName }: { user: User folder: string spaceName: string }): Promise<void> => { const webDavEndPathToRoot = 'spaces/' + (await getSpaceIdBySpaceName({ user, spaceType: 'project', spaceName })) await createFolder({ user, folder, webDavEndPathToRoot }) } export const createFolderInsidePersonalSpace = async ({ user, folder }: { user: User folder: string }): Promise<void> => { const webDavEndPathToRoot = 'spaces/' + (await getPersonalSpaceId({ user })) await createFolder({ user, folder, webDavEndPathToRoot }) } export const uploadFileInsideSpaceBySpaceName = async ({ user, pathToFile, spaceName, content = '' }: { user: User pathToFile: string spaceName: string content?: string | Buffer }): Promise<void> => { const webDavEndPathToRoot = 'spaces/' + (await getSpaceIdBySpaceName({ user, spaceType: 'project', spaceName })) await createFile({ user, pathToFile, content, webDavEndPathToRoot }) } export const getDataOfFileInsideSpace = async ({ user, pathToFileName, spaceType, spaceName }: { user: User pathToFileName: string spaceType: string spaceName: string }): Promise<Response> => { const body = '<?xml version="1.0"?>\n' + '<d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">\n' + ' <d:prop>\n' + ' <oc:permissions />\n' + ' <oc:favorite />\n' + ' <oc:fileid />\n' + ' <oc:file-parent />\n' + ' <oc:name />\n' + ' <oc:owner-id />\n' + ' <oc:owner-display-name />\n' + ' <oc:shareid />\n' + ' <oc:shareroot />\n' + ' <oc:share-types />\n' + ' <oc:privatelink />\n' + ' <d:getcontentlength />\n' + ' <oc:size />\n' + ' <d:getlastmodified />\n' + ' <d:getetag />\n' + ' <d:getcontenttype />\n' + ' <d:resourcetype />\n' + ' <oc:downloadURL />\n' + ' </d:prop>\n' + '</d:propfind>' const response = await request({ method: 'PROPFIND', path: join( 'remote.php', 'dav', 'spaces', await getSpaceIdBySpaceName({ user, spaceType, spaceName }), pathToFileName ), body: body, user: user }) checkResponseStatus(response, `Failed while getting information of file ${pathToFileName}`) const fileData = JSON.parse(convert.xml2json(await response.text(), { compact: true })) return _.get(fileData, '[d:multistatus][d:response]') } export const getIdOfFileInsideSpace = async ({ user, pathToFileName, spaceType, spaceName }: { user: User pathToFileName: string spaceType: string spaceName: string }): Promise<string> => { const fileDataResponse = await getDataOfFileInsideSpace({ user, pathToFileName, spaceType, spaceName }) // when there is a file inside the folder response comes as // [ [Object], [Object] ], so handel this case if (fileDataResponse.constructor.name === 'Array') { for (const key in fileDataResponse) { if (fileDataResponse[key]['d:propstat'][0]['d:prop']['oc:name']._text === pathToFileName) { return _.get(fileDataResponse[key], '[d:propstat][0][d:prop][oc:fileid]')._text } } } else { // extract file id form the response return _.get(fileDataResponse, '[d:propstat][0][d:prop][oc:fileid]')._text } } export const addMembersToTheProjectSpace = async ({ user, spaceName, shareWith, shareType, role }: { user: User spaceName: string shareWith: string shareType: string role: string }): Promise<void> => { const space_ref = await getSpaceIdBySpaceName({ user, spaceType: 'project', spaceName }) await createShare({ user, path: null, shareWith, shareType, role, name: null, space_ref }) } export const addTagToResource = async ({ user, resource, tags }: { user: User resource: string tags: string }): Promise<void> => { const resourceId = await getIdOfFileInsideSpace({ user, pathToFileName: resource, spaceType: 'personal', spaceName: user.displayName }) const tagNames = tags.split(',').map((tag) => tag.trim()) await createTagsForResource({ user, resourceId, tags: tagNames }) }
owncloud/web/tests/e2e/support/api/davSpaces/spaces.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/api/davSpaces/spaces.ts", "repo_id": "owncloud", "token_count": 2545 }
825
export { disableAutoAcceptShare } from './settings'
owncloud/web/tests/e2e/support/api/userSettings/index.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/api/userSettings/index.ts", "repo_id": "owncloud", "token_count": 13 }
826
import { Page } from '@playwright/test' import * as po from './actions' export class General { #page: Page constructor({ page }: { page: Page }) { this.#page = page } async uploadLogo({ path }: { path: string }): Promise<void> { await po.uploadLogo(path, this.#page) } async resetLogo(): Promise<void> { await po.resetLogo(this.#page) } }
owncloud/web/tests/e2e/support/objects/app-admin-settings/general/index.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/general/index.ts", "repo_id": "owncloud", "token_count": 133 }
827
import { WithMe } from './shares/withMe' import { Personal } from './spaces/personal' import { Projects } from './spaces/projects' import { WithOthers } from './shares/withOthers' export { Public } from './public' import { Overview } from './trashbin/overview' export const shares = { WithMe, WithOthers } export const spaces = { Personal, Projects } export const trashbin = { Overview }
owncloud/web/tests/e2e/support/objects/app-files/page/index.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/objects/app-files/page/index.ts", "repo_id": "owncloud", "token_count": 115 }
828
import { Page } from '@playwright/test' import util from 'util' import { sidebar, editor } from '../utils' import Collaborator, { ICollaborator } from '../share/collaborator' import { createLink } from '../link/actions' import { File } from '../../../types' const newSpaceMenuButton = '#new-space-menu-btn' const spaceNameInputField = '.oc-modal input' const actionConfirmButton = '.oc-modal-body-actions-confirm' const spaceIdSelector = `[data-item-id="%s"] .oc-resource-basename` const spacesRenameOptionSelector = '.oc-files-actions-rename-trigger:visible' const editSpacesSubtitleOptionSelector = '.oc-files-actions-edit-description-trigger:visible' const editQuotaOptionSelector = '.oc-files-actions-edit-quota-trigger:visible' const editImageOptionSelector = '.oc-files-actions-upload-space-image-trigger:visible' const downloadSpaceSelector = '.oc-files-actions-download-archive-trigger:visible' const spacesQuotaSearchField = '.oc-modal .vs__search' const selectedQuotaValueField = '.vs--open' const quotaValueDropDown = `.vs__dropdown-option :text-is("%s")` const editSpacesDescription = '.oc-files-actions-edit-readme-content-trigger:visible' const spacesDescriptionInputArea = '.md-mode .ProseMirror' const spacesDescriptionSaveTextFileInEditorButton = '#app-save-action:visible' const sideBarActions = '//ul[@id="oc-files-actions-sidebar"]//span[@class="oc-files-context-action-label"]' export const openActionsPanel = async (page: Page): Promise<void> => { await sidebar.open({ page }) await sidebar.openPanel({ page, name: 'space-actions' }) } export const openSharingPanel = async (page: Page): Promise<void> => { await sidebar.open({ page }) await sidebar.openPanel({ page, name: 'space-share' }) } /**/ export interface createSpaceArgs { name: string page: Page } export const createSpace = async (args: createSpaceArgs): Promise<string> => { const { page, name } = args await page.locator(newSpaceMenuButton).click() await page.locator(spaceNameInputField).fill(name) const postResponsePromise = page.waitForResponse( (postResp) => postResp.status() === 201 && postResp.request().method() === 'POST' && postResp.url().endsWith('drives') ) const mkcolResponsePromise = page.waitForResponse( (resp) => resp.status() === 201 && resp.request().method() === 'MKCOL' && resp.url().includes('.space') ) const putResponsePromise = page.waitForResponse( (resp) => resp.status() === 201 && resp.request().method() === 'PUT' && resp.url().endsWith('/.space/readme.md') ) const patchResponsePromise = page.waitForResponse( (resp) => resp.status() === 200 && resp.request().method() === 'PATCH' ) const [responses] = await Promise.all([ postResponsePromise, mkcolResponsePromise, putResponsePromise, patchResponsePromise, page.locator(actionConfirmButton).click() ]) const { id } = await responses.json() return id } /**/ export interface openSpaceArgs { id: string page: Page } export const openSpace = async (args: openSpaceArgs): Promise<void> => { const { page, id } = args await page.locator(util.format(spaceIdSelector, id)).click() } /**/ export const changeSpaceName = async (args: { page: Page id: string value: string }): Promise<void> => { const { page, value, id } = args await openActionsPanel(page) await page.locator(spacesRenameOptionSelector).click() await page.locator(spaceNameInputField).fill(value) await Promise.all([ page.waitForResponse( (resp) => resp.url().endsWith(encodeURIComponent(id)) && resp.status() === 200 && resp.request().method() === 'PATCH' ), page.locator(actionConfirmButton).click() ]) await sidebar.close({ page: page }) } /**/ export const changeSpaceSubtitle = async (args: { page: Page id: string value: string }): Promise<void> => { const { page, value, id } = args await openActionsPanel(page) await page.locator(editSpacesSubtitleOptionSelector).click() await page.locator(spaceNameInputField).fill(value) await Promise.all([ page.waitForResponse( (resp) => resp.url().endsWith(encodeURIComponent(id)) && resp.status() === 200 && resp.request().method() === 'PATCH' ), page.locator(actionConfirmButton).click() ]) await sidebar.close({ page: page }) } /**/ export const changeSpaceDescription = async (args: { page: Page value: string }): Promise<void> => { const { page, value } = args await openActionsPanel(page) const waitForUpdate = () => page.waitForResponse( (resp) => resp.url().endsWith('readme.md') && resp.status() === 200 && resp.request().method() === 'GET' ) await Promise.all([waitForUpdate(), page.locator(editSpacesDescription).click()]) await page.locator(spacesDescriptionInputArea).fill(value) await Promise.all([ page.waitForResponse((resp) => resp.status() === 204 && resp.request().method() === 'PUT'), page.waitForResponse((resp) => resp.status() === 207 && resp.request().method() === 'PROPFIND'), page.locator(spacesDescriptionSaveTextFileInEditorButton).click() ]) await editor.close(page) } /**/ export const changeQuota = async (args: { id: string page: Page value: string }): Promise<void> => { const { id, page, value } = args await openActionsPanel(page) await page.locator(editQuotaOptionSelector).click() const searchLocator = page.locator(spacesQuotaSearchField) await searchLocator.pressSequentially(value) await page.locator(selectedQuotaValueField).waitFor() await page.locator(util.format(quotaValueDropDown, `${value} GB`)).click() await Promise.all([ page.waitForResponse( (resp) => resp.url().endsWith(encodeURIComponent(id)) && resp.status() === 200 && resp.request().method() === 'PATCH' ), page.locator(actionConfirmButton).click() ]) await sidebar.close({ page: page }) } export interface SpaceMembersArgs { page: Page users: ICollaborator[] } export const addSpaceMembers = async (args: SpaceMembersArgs): Promise<void> => { const { page, users } = args await openSharingPanel(page) await Collaborator.inviteCollaborators({ page, collaborators: users }) await sidebar.close({ page: page }) } export interface canUserEditSpaceResourceArgs { resource: string page: Page } export const canUserEditSpaceResource = async ( args: canUserEditSpaceResourceArgs ): Promise<boolean> => { const { resource, page } = args const notExpectedActions = ['move', 'rename', 'delete'] await sidebar.open({ page: page, resource }) await sidebar.openPanel({ page: page, name: 'actions' }) const presentActions = await page.locator(sideBarActions).allTextContents() const presentActionsToLower = presentActions.map((actions) => actions.toLowerCase()) for (const actions of notExpectedActions) { if (presentActionsToLower.includes(actions)) { return true } } return false } export const reloadSpacePage = async (page): Promise<void> => { await page.reload() } export const changeSpaceImage = async (args: { id: string page: Page resource: File }): Promise<void> => { const { id, page, resource } = args await openActionsPanel(page) const [fileChooser] = await Promise.all([ page.waitForEvent('filechooser'), page.locator(editImageOptionSelector).click() ]) await Promise.all([ page.waitForResponse( (resp) => resp.url().endsWith(encodeURIComponent(id)) && resp.status() === 200 && resp.request().method() === 'PATCH' ), page.waitForResponse( (resp) => resp.url().endsWith(resource.name) && resp.status() === 207 && resp.request().method() === 'PROPFIND' ), page.waitForResponse( (resp) => resp.url().includes(resource.name) && resp.status() === 200 && resp.request().method() === 'GET' ), fileChooser.setFiles(resource.path) ]) await sidebar.close({ page: page }) } export interface removeAccessMembersArgs extends Omit<SpaceMembersArgs, 'users'> { users: Omit<ICollaborator, 'role'>[] removeOwnSpaceAccess?: boolean } export const removeAccessSpaceMembers = async (args: removeAccessMembersArgs): Promise<void> => { const { page, users, removeOwnSpaceAccess } = args await openSharingPanel(page) for (const collaborator of users) { await Collaborator.removeCollaborator({ page, collaborator, removeOwnSpaceAccess }) } } export const changeSpaceRole = async (args: SpaceMembersArgs): Promise<void> => { const { page, users } = args await openSharingPanel(page) for (const collaborator of users) { await Promise.all([ page.waitForResponse( (resp) => resp.url().includes('permissions') && resp.status() === 200 && resp.request().method() === 'PATCH' ), Collaborator.changeCollaboratorRole({ page, collaborator }) ]) } } export const createPublicLinkForSpace = async (args: { page: Page password: string }): Promise<string> => { const { page, password } = args await openSharingPanel(page) return createLink({ page: page, space: true, password: password }) } export const addExpirationDateToMember = async (args: { page: Page member: Omit<ICollaborator, 'role'> expirationDate: string }): Promise<void> => { const { page, member: collaborator, expirationDate } = args await openSharingPanel(page) await Collaborator.setExpirationDateForCollaborator({ page, collaborator, expirationDate }) } export const removeExpirationDateFromMember = async (args: { page: Page member: Omit<ICollaborator, 'role'> }): Promise<void> => { const { page, member: collaborator } = args await openSharingPanel(page) await Collaborator.removeExpirationDateFromCollaborator({ page, collaborator }) } export const downloadSpace = async (page: Page): Promise<string> => { await openActionsPanel(page) const [download] = await Promise.all([ page.waitForEvent('download'), page.locator(downloadSpaceSelector).click() ]) await sidebar.close({ page }) return download.suggestedFilename() }
owncloud/web/tests/e2e/support/objects/app-files/spaces/actions.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/objects/app-files/spaces/actions.ts", "repo_id": "owncloud", "token_count": 3446 }
829
export { actorStore } from './actor' export { createdLinkStore } from './link' export { createdSpaceStore } from './space' export { dummyUserStore, createdUserStore } from './user' export { dummyGroupStore, createdGroupStore } from './group' export { userRoleStore } from './role' export { keycloakRealmRoles } from './keycloak'
owncloud/web/tests/e2e/support/store/index.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/store/index.ts", "repo_id": "owncloud", "token_count": 97 }
830
const IntersectionObserverMock = vi.fn(() => ({ disconnect: vi.fn(), observe: vi.fn(), takeRecords: vi.fn(), unobserve: vi.fn() })) vi.stubGlobal('IntersectionObserver', IntersectionObserverMock) const ResizeObserverMock = vi.fn(() => ({ observe: vi.fn(), unobserve: vi.fn() })) vi.stubGlobal('ResizeObserver', ResizeObserverMock) vi.stubGlobal('define', vi.fn())
owncloud/web/tests/unit/config/vitest.init.ts/0
{ "file_path": "owncloud/web/tests/unit/config/vitest.init.ts", "repo_id": "owncloud", "token_count": 147 }
831
<?php //db connect function connect($host=DBHOST,$username=DBUSER,$password=DBPW,$databasename=DBNAME,$port=DBPORT){ $link=@mysqli_connect($host, $username, $password, $databasename, $port); if(mysqli_connect_errno()){ // exit(mysqli_connect_error()); exit('数据库连接失败,请检查config.inc.php配置文件'); } mysqli_set_charset($link,'utf8'); return $link; } //判断一下操作是否成功,如果错误返回bool值,如果成功,则返回结果集 function execute($link,$query){ $result=mysqli_query($link,$query); if(mysqli_errno($link)){//最近一次操作的错误编码,没错误返回0,没有输出 exit(mysqli_error($link));//有错误,返回编码,为true,则打印报错信息 } return $result; } //转义,避免fuck function escape($link,$data){ if(is_string($data)){ return mysqli_real_escape_string($link,$data); } if(is_array($data)){ foreach ($data as $key=>$val){ $data[$key]=escape($link,$val); } } return $data; } function check_login($link){ if(isset($_SESSION['pkxss']['username']) && isset($_SESSION['pkxss']['password'])){ $query="select * from users where username='{$_SESSION['pkxss']['username']}' and sha1(password)='{$_SESSION['pkxss']['password']}'"; $result=execute($link,$query); if(mysqli_num_rows($result)==1){ return true; }else{ return false; } }else{ return false; } } ?>
zhuifengshaonianhanlu/pikachu/pkxss/inc/mysql.inc.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/pkxss/inc/mysql.inc.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 793 }
832
<?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 = "rce_ping.php"){ $ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''); } $PIKA_ROOT_DIR = "../../"; include_once $PIKA_ROOT_DIR . 'header.php'; //header("Content-type:text/html; charset=gbk"); $result=''; if(isset($_POST['submit']) && $_POST['ipaddress']!=null){ $ip=$_POST['ipaddress']; // $check=explode('.', $ip);可以先拆分,然后校验数字以范围,第一位和第四位1-255,中间两位0-255 if(stristr(php_uname('s'), 'windows')){ // var_dump(php_uname('s')); $result.=shell_exec('ping '.$ip);//直接将变量拼接进来,没做处理 }else { $result.=shell_exec('ping -c 4 '.$ip); } } ?> <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="rce.php">rce</a> </li> <li class="active">exec "ping"</li> </ul><!-- /.breadcrumb --> <a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)" data-content="想一下ping命令在系统上是怎么用的"> 点一下提示~ </a> </div> <div class="page-content"> <div id="comm_main"> <p class="comm_title">Here, please enter the target IP address!</p> <form method="post"> <input class="ipadd" type="text" name="ipaddress" /> <input class="sub" type="submit" name="submit" value="ping" /> </form> <?php if($result){ echo "<pre>{$result}</pre>"; } ?> </div> </div><!-- /.page-content --> </div> </div><!-- /.main-content --> <?php include_once $PIKA_ROOT_DIR . 'footer.php'; ?>
zhuifengshaonianhanlu/pikachu/vul/rce/rce_ping.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/vul/rce/rce_ping.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 1380 }
833
<?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 = "ssrf.php"){ $ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''); } $PIKA_ROOT_DIR = "../../"; include_once $PIKA_ROOT_DIR.'header.php'; ?> <div class="main-content"> <div class="main-content-inner"> <div class="breadcrumbs ace-save-state" id="breadcrumbs"> <ul class="breadcrumb"> <li> <i class="ace-icon fa fa-home home-icon"></i> <a href="ssrf.php"></a> </li> <li class="active">概述</li> </ul> </div> <div class="page-content"> <b>SSRF(Server-Side Request Forgery:服务器端请求伪造)</b> <p>其形成的原因大都是由于服务端<b>提供了从其他服务器应用获取数据的功能</b>,但又没有对目标地址做严格过滤与限制</p> 导致攻击者可以传入任意的地址来让后端服务器对其发起请求,并返回对该目标地址请求的数据<br> <br> 数据流:攻击者----->服务器---->目标地址<br> <br> 根据后台使用的函数的不同,对应的影响和利用方法又有不一样 <pre style="width: 500px;"> PHP中下面函数的使用不当会导致SSRF: file_get_contents() fsockopen() curl_exec() </pre><br> 如果一定要通过后台服务器远程去对用户指定("或者预埋在前端的请求")的地址进行资源请求,<b>则请做好目标地址的过滤</b>。 <br> <br> 你可以根据"SSRF"里面的项目来搞懂问题的原因 </div><!-- /.page-content --> </div> </div><!-- /.main-content --> <?php include_once $PIKA_ROOT_DIR . 'footer.php'; ?>
zhuifengshaonianhanlu/pikachu/vul/ssrf/ssrf.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/vul/ssrf/ssrf.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 1330 }
834
<?php /** * Created by runner.han * There is nothing new under the sun */ $SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1); if ($SELF_PAGE = "xss_03.php"){ $ACTIVE = array('','','','','','','','active open','','','','','','','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''); } $PIKA_ROOT_DIR = "../../"; include_once $PIKA_ROOT_DIR.'header.php'; $html=''; if(isset($_GET['submit'])){ if(empty($_GET['message'])){ $html.="<p class='notice'>叫你输入个url,你咋不听?</p>"; } if($_GET['message'] == 'www.baidu.com'){ $html.="<p class='notice'>我靠,我真想不到你是这样的一个人</p>"; }else { //输出在a标签的href属性里面,可以使用javascript协议来执行js //防御:只允许http,https,其次在进行htmlspecialchars处理 $message=htmlspecialchars($_GET['message'],ENT_QUOTES); $html.="<a href='{$message}'> 阁下自己输入的url还请自己点一下吧</a>"; } } ?> <div class="main-content"> <div class="main-content-inner"> <div class="breadcrumbs ace-save-state" id="breadcrumbs"> <ul class="breadcrumb"> <li> <i class="ace-icon fa fa-home home-icon"></i> <a href="xss.php">xss</a> </li> <li class="active">xss之href输出</li> </ul><!-- /.breadcrumb --> <a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)" data-content="a标签里面的href,img里面的src属性,有什么特殊的么"> 点一下提示~ </a> </div> <div class="page-content"> <div id="xssr_main"> <p class="xssr_title">请输入一个你常用的网站url地址,我就知道你是什么人</p> <form method="get"> <input class="xssr_in" type="text" name="message" /> <input class="xssr_submit" type="submit" name="submit" value="submit" /> </form> <?php echo $html; ?> </div> </div><!-- /.page-content --> </div> </div><!-- /.main-content --> <?php include_once $PIKA_ROOT_DIR.'footer.php'; ?>
zhuifengshaonianhanlu/pikachu/vul/xss/xss_03.php/0
{ "file_path": "zhuifengshaonianhanlu/pikachu/vul/xss/xss_03.php", "repo_id": "zhuifengshaonianhanlu", "token_count": 1396 }
835
# 8th Wall Web Examples - AFrame - Flyer This example uses image targets to display information about jellyfish on a flyer. It uses the xrextras-named-image-target component to connect an <a-entity> to an image target by name while the xrextras-play-video component enables video playback. ![artgallery-screenshot](../../../images/screenshot-flyer.jpg) [Try the live demo here](https://templates.8thwall.app/flyer-aframe) ![flyer](./flyer.jpg) ## Uploading to Console To link the image targets to your app key, you will need to upload and enable each image to your app in console at console.8thwall.com.
8thwall/web/examples/aframe/flyer/README.md/0
{ "file_path": "8thwall/web/examples/aframe/flyer/README.md", "repo_id": "8thwall", "token_count": 178 }
0
/* globals AFRAME */ AFRAME.registerComponent('sky-recenter', { init() { const recenter = () => { this.el.emit('recenter') this.el.removeEventListener('sky-coaching-overlay.hide', recenter) } this.el.addEventListener('sky-coaching-overlay.hide', recenter) }, })
8thwall/web/examples/aframe/sky/sky-recenter.js/0
{ "file_path": "8thwall/web/examples/aframe/sky/sky-recenter.js", "repo_id": "8thwall", "token_count": 116 }
1
# 8th Wall Web Examples - Camera Pipeline - QR Code This example shows how to create an 8th Wall Web that accesses the camera pixels and processes them with a computer vision library. QR Code :----------: ![qrcode-screenshot](../../../images/screenshot-qrcode.png) [Try Demo (mobile)](https://apps.8thwall.com/8thWall/camerapipeline_qrcode) or scan on phone:<br> ![QR1](../../../images/qr-camerapipeline_qrcode.png)
8thwall/web/examples/camerapipeline/qrcode/README.md/0
{ "file_path": "8thwall/web/examples/camerapipeline/qrcode/README.md", "repo_id": "8thwall", "token_count": 142 }
2
/* Ported to JavaScript by Lazar Laszlo 2011 lazarsoft@gmail.com, www.lazarsoft.info */ /* * * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var FORMAT_INFO_MASK_QR = 0x5412; var FORMAT_INFO_DECODE_LOOKUP = new Array(new Array(0x5412, 0x00), new Array(0x5125, 0x01), new Array(0x5E7C, 0x02), new Array(0x5B4B, 0x03), new Array(0x45F9, 0x04), new Array(0x40CE, 0x05), new Array(0x4F97, 0x06), new Array(0x4AA0, 0x07), new Array(0x77C4, 0x08), new Array(0x72F3, 0x09), new Array(0x7DAA, 0x0A), new Array(0x789D, 0x0B), new Array(0x662F, 0x0C), new Array(0x6318, 0x0D), new Array(0x6C41, 0x0E), new Array(0x6976, 0x0F), new Array(0x1689, 0x10), new Array(0x13BE, 0x11), new Array(0x1CE7, 0x12), new Array(0x19D0, 0x13), new Array(0x0762, 0x14), new Array(0x0255, 0x15), new Array(0x0D0C, 0x16), new Array(0x083B, 0x17), new Array(0x355F, 0x18), new Array(0x3068, 0x19), new Array(0x3F31, 0x1A), new Array(0x3A06, 0x1B), new Array(0x24B4, 0x1C), new Array(0x2183, 0x1D), new Array(0x2EDA, 0x1E), new Array(0x2BED, 0x1F)); var BITS_SET_IN_HALF_BYTE = new Array(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); function FormatInformation(formatInfo) { this.errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); this.dataMask = (formatInfo & 0x07); this.__defineGetter__("ErrorCorrectionLevel", function() { return this.errorCorrectionLevel; }); this.__defineGetter__("DataMask", function() { return this.dataMask; }); this.GetHashCode=function() { return (this.errorCorrectionLevel.ordinal() << 3) | this.dataMask; } this.Equals=function( o) { var other = o; return this.errorCorrectionLevel == other.errorCorrectionLevel && this.dataMask == other.dataMask; } } FormatInformation.numBitsDiffering=function( a, b) { a ^= b; // a now has a 1 bit exactly where its bit differs with b's // Count bits set quickly with a series of lookups: return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(URShift(a, 4) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 8) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 12) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 16) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 20) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 24) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 28) & 0x0F)]; } FormatInformation.decodeFormatInformation=function( maskedFormatInfo) { var formatInfo = FormatInformation.doDecodeFormatInformation(maskedFormatInfo); if (formatInfo != null) { return formatInfo; } // Should return null, but, some QR codes apparently // do not mask this info. Try again by actually masking the pattern // first return FormatInformation.doDecodeFormatInformation(maskedFormatInfo ^ FORMAT_INFO_MASK_QR); } FormatInformation.doDecodeFormatInformation=function( maskedFormatInfo) { // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing var bestDifference = 0xffffffff; var bestFormatInfo = 0; for (var i = 0; i < FORMAT_INFO_DECODE_LOOKUP.length; i++) { var decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i]; var targetInfo = decodeInfo[0]; if (targetInfo == maskedFormatInfo) { // Found an exact match return new FormatInformation(decodeInfo[1]); } var bitsDifference = this.numBitsDiffering(maskedFormatInfo, targetInfo); if (bitsDifference < bestDifference) { bestFormatInfo = decodeInfo[1]; bestDifference = bitsDifference; } } // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits // differing means we found a match if (bestDifference <= 3) { return new FormatInformation(bestFormatInfo); } return null; }
8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/formatinf.js/0
{ "file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/formatinf.js", "repo_id": "8thwall", "token_count": 1630 }
3
/*jshint esversion: 6, asi: true, laxbreak: true*/ // namedimagetarget.js: Controls visibility, position, orientation, and scaling of a 3D object that // should attach to a real-world image target. This script should be attached to an entity of which // the target content is a child. The name of the image target should match its name as configured // on 8thwall.com. var namedimagetarget = pc.createScript('namedimagetarget'); namedimagetarget.attributes.add('name', {type: 'string'}) namedimagetarget.prototype.initialize = function() { XRExtras.PlayCanvas.trackImageTargetWithName(this) }
8thwall/web/gettingstarted/playcanvas/scripts/namedimagetarget.js/0
{ "file_path": "8thwall/web/gettingstarted/playcanvas/scripts/namedimagetarget.js", "repo_id": "8thwall", "token_count": 171 }
4
import type {ComponentDefinition} from 'aframe' import {ensureXrAndExtras} from '../ensure' declare const THREE: any declare const XRExtras: any const captureButtonComponent: ComponentDefinition = { schema: { captureMode: {default: 'standard'}, }, init() { ensureXrAndExtras().then(() => { if (this.removed) { return } this.added = true XRExtras.MediaRecorder.initRecordButton() XRExtras.MediaRecorder.setCaptureMode(this.data.captureMode) }) }, update() { if (this.added) { XRExtras.MediaRecorder.setCaptureMode(this.data.captureMode) } }, remove() { this.removed = true if (this.added) { XRExtras.MediaRecorder.removeRecordButton() } }, } const capturePreviewComponent: ComponentDefinition = { // This schema must be duplicated to mappings xr-primitives.js schema: { actionButtonShareText: {default: ''}, actionButtonViewText: {default: ''}, finalizeText: {default: ''}, }, init() { ensureXrAndExtras().then(() => { if (!this.removed) { this.added = true XRExtras.MediaRecorder.initMediaPreview(this.data) } }) }, remove() { this.removed = true if (this.added) { XRExtras.MediaRecorder.removeMediaPreview() } }, } interface CaptureComponentDefinition extends ComponentDefinition { includeSceneAudio: ({microphoneInput, audioProcessor}: { microphoneInput: any, audioProcessor: any }) => any } const captureConfigComponent: CaptureComponentDefinition = { // This schema must be duplicated to mappings xr-primitives.js schema: { enableEndCard: {type: 'boolean'}, shortLink: {type: 'string'}, coverImageUrl: {type: 'string'}, footerImageUrl: {type: 'string'}, maxDurationMs: {type: 'int'}, endCardCallToAction: {type: 'string'}, maxDimension: {type: 'int'}, watermarkImageUrl: {type: 'string'}, watermarkMaxWidth: {type: 'number'}, watermarkMaxHeight: {type: 'number'}, watermarkLocation: {type: 'string'}, fileNamePrefix: {type: 'string'}, requestMic: {type: 'string'}, includeSceneAudio: {type: 'boolean', default: true}, excludeSceneAudio: {type: 'boolean', default: false}, // deprecated }, init() { this.includeSceneAudio = this.includeSceneAudio.bind(this) }, update() { const config: any = { audioContext: THREE.AudioContext.getContext(), } if (this.attrValue.excludeSceneAudio !== undefined) { console.warn('"exclude-scene-audio" has been deprecated in favor of "include-scene-audio"') config.configureAudioOutput = this.data.excludeSceneAudio ? null : this.includeSceneAudio } else { config.configureAudioOutput = this.data.includeSceneAudio ? this.includeSceneAudio : null } Object.keys(this.data).forEach((key) => { // Ignore value if not specified if (this.attrValue[key] !== undefined && !['includeSceneAudio', 'excludeSceneAudio'].includes(key)) { config[key] = this.data[key] } }) XRExtras.MediaRecorder.configure(config) }, includeSceneAudio({microphoneInput, audioProcessor}) { const audioContext = audioProcessor.context // if the scene doesn't have any audio, then we'll create the listener for the scene. // That way, if they add sounds later, it will still connect without the user having to // re-call this function. if (!this.el.sceneEl.audioListener) { this.el.sceneEl.audioListener = new THREE.AudioListener() } // This connects the A-Frame audio to the audioProcessor so that all sound effects initialized // are part of the recorded video's audio. this.el.sceneEl.audioListener.gain.connect(audioProcessor) // This connects the A-Frame audio to the hardware output. That way, the user can also hear // the sound effects during the experience this.el.sceneEl.audioListener.gain.connect(audioContext.destination) // you must return a node at the end. This node is connected to the audioProcessor // automatically inside MediaRecorder return microphoneInput }, } export { captureButtonComponent, capturePreviewComponent, captureConfigComponent, CaptureComponentDefinition, }
8thwall/web/xrextras/src/aframe/components/recorder-components.ts/0
{ "file_path": "8thwall/web/xrextras/src/aframe/components/recorder-components.ts", "repo_id": "8thwall", "token_count": 1487 }
5
#loadingContainer { z-index: 800; font-family: 'Nunito-SemiBold', sans-serif; } #loadBackground { z-index: 10; background-color: #101118; pointer-events: auto; } .xrextras-old-style #loadBackground { background-color: white; } #requestingCameraPermissions { z-index: 11; position: absolute; top: 0; width: 100vw; text-align: center; color: white; font-size: 1.8em; font-family: 'Nunito-SemiBold', sans-serif; background-color: #464766; padding-top: 3vh; padding-bottom: 1.75vh; } #requestingCameraIcon { display: block; margin: 0 auto; margin-bottom: 2vh; height: 5.5vh; } #loadImage { position: absolute; margin-top: -2.5em; margin-left: -2.5em; top: 50%; left: 50%; height: 5em; width: 5em; transform: translate(-50%, -50%); } /* camera and micrphone permission related styles */ #cameraPermissionsErrorApple, #microphonePermissionsErrorApple { background-color: #101118; } .xrextras-old-style #cameraPermissionsErrorApple, .xrextras-old-style #microphonePermissionsErrorApple { background-color: white; } #cameraPermissionsErrorAppleMessage, #microphonePermissionsErrorAppleMessage { font-size: 1.75em; text-align: center; max-width: 90vw; margin-top: 5vh; margin-left: auto; margin-right: auto; color: white; } .xrextras-old-style #cameraPermissionsErrorAppleMessage, .xrextras-old-style #microphonePermissionsErrorAppleMessage { color: #323232; } .permissionIconIos { display: block; margin: 0 auto; margin-top: 17vh; text-align: center; } .permissionIconIos img { height: 20vw; } .permissionIconIos img + img { margin-left: 10vw; } .bottom-message { color: white; padding: 0 5vw; position: absolute; bottom: 10vh; text-align: center; font-size: 1.25em; } #cameraPermissionsErrorAndroid, #microphonePermissionsErrorAndroid { padding: 2vh 0; display: flex; flex-direction: column; pointer-events: auto; justify-content: space-around; align-items: center; background-color: #101118; } .xrextras-old-style #cameraPermissionsErrorAndroid, .xrextras-old-style #microphonePermissionsErrorAndroid { background-color: white; } /* device motion permission related styles */ #deviceMotionErrorApple { padding: 3vh 2vh; display: flex; flex-direction: column; pointer-events: auto; justify-content: space-around; align-items: center; background-color: #101118; color: white; } .xrextras-old-style #deviceMotionErrorApple { color: #2D2E43; background-color: white; } #linkOutViewAndroid, #copyLinkViewAndroid { background-color: #101118; } .xrextras-old-style #linkOutViewAndroid, .xrextras-old-style #copyLinkViewAndroid { background-color: #fff; } .permission-error { padding: 3vh 5vh; font-size: 3.5vh; color: #fff; background-color: #101118; } .xrextras-old-style .permission-error { color: #323232; background-color: white; } .permission-error>h1 { font-size: 1.3em; } .main-button { border: none; outline: none; background-color: #AD50FF; color: white; font-size: 2.5vh; display: block; margin-top: 2em; padding: 0.5em 1em; border-radius: 0.5em; } .xrextras-old-style .main-button { background-color: #7611B7; } .start-ar-button { position: fixed; bottom: 25%; left: 50%; transform: translateX(-50%); font-family: 'Nunito-SemiBold', sans-serif; font-weight: 800; font-size: 1.5em; text-align: center; color: white; text-decoration: none; border: none; background-color: #AD50FF; padding: 6px 13px; border-radius: 10px; } .xrextras-old-style .start-ar-button { background-color: #7611b7; } .permissionIcon { overflow: hidden; flex: 0 0 auto; margin-bottom: 2vh; } .permissionIcon img { display: block; margin: 0 auto; height: 5vh; } #cameraSelectionWorldTrackingError { z-index: 999; position: absolute; top: 0; width: 100vw; text-align: center; color: black; font-size: 3.7vh; background-color: white; padding: 3vh 0; } .loading-error-header { font-size: 3.5vh; flex: 0 0 auto; color: white; } .xrextras-old-style .loading-error-header { color: #323232; } .loading-error-footer { font-size: 3vh; line-height: 5.5vh; flex: 0 0 auto; text-align: center; width: 80vmin; color: white; } .xrextras-old-style .loading-error-footer { color: #323232; } .loading-error-footer img { display: block; height: 5vh; margin: 0 auto; margin-bottom: 2vh; } .loading-error-instructions { font-family: 'Nunito', sans-serif; color: #fff; font-size: 2.5vh; list-style: none; margin-left: 1em; counter-reset: line; flex: 0 0 auto; } .xrextras-old-style .loading-error-instructions { color: #2D2E43; } .loading-error-instructions>li { position: relative; margin-bottom: 4.5vh; } .loading-error-instructions>li>img { max-height: 3vh; vertical-align: middle; margin: 0 .5vh; } .loading-error-instructions>li:before { font-family: 'Nunito', sans-serif; position: absolute; width: 40px; height: 40px; border-radius: 3vh; color: #fff; background-color: #464766; text-align: center; left: -8vh; top: -1vh; font-size: 2.5vh; line-height: 5.5vh; counter-increment: line; content: counter(line); } .xrextras-old-style .loading-error-instructions>li:before { background-color: rgba(218, 209, 228, 128); } .highlight { color: white; font-family: 'Nunito-SemiBold', sans-serif; font-weight: 800; } .xrextras-old-style .highlight { color: #7611B7; } .camera-instruction-block { display: inline-block; background-color: #8083A2; padding: 1vh; } .xrextras-old-style .camera-instruction-block { background-color: #EBEBEB; } .camera-instruction-button { display: inline-block; padding: 1vh; background-color: #359AFF; color: white; font-size: 2vh; box-shadow: 0 .125vh .25vh rgba(0, 0, 0, 0.5); } body:not(.xrextras-old-style) .prompt-box-8w { background-color: #3A3B55; color: #fff; text-align: center; } body:not(.xrextras-old-style) .prompt-button-8w { background-color: #8083A2; border-radius: 10px; } body:not(.xrextras-old-style) .button-primary-8w { background-color: #AD50FF; } .fade-out { animation: fade-out 0.3s linear forwards; } @keyframes fade-out { 0% { opacity: 1; } 100% { opacity: 0; } } .spin { animation: spin 1.1s cubic-bezier(0.785, 0.135, 0.150, 0.860) infinite both; } @keyframes spin { 0% { transform: rotate(0); } 100% { transform: rotate(360deg); } } .scale { -webkit-animation: scale 1s cubic-bezier(0.455, 0.030, 0.515, 0.955) infinite alternate-reverse both; animation: scale 1s cubic-bezier(0.455, 0.030, 0.515, 0.955) infinite alternate-reverse both; } @keyframes scale { 0% { -webkit-transform: scale(0.5); transform: scale(0.5); } 100% { -webkit-transform: scale(1); transform: scale(1); } } .pulse { -webkit-animation: pulse 1s ease-in-out infinite both; animation: pulse 1s ease-in-out infinite both; } @keyframes pulse { 0% { -webkit-transform: scale(1); transform: scale(1); } 50% { -webkit-transform: scale(1.1); transform: scale(1.1); } 100% { -webkit-transform: scale(1); transform: scale(1); } }
8thwall/web/xrextras/src/loadingmodule/loading-module.css/0
{ "file_path": "8thwall/web/xrextras/src/loadingmodule/loading-module.css", "repo_id": "8thwall", "token_count": 2955 }
6
<svg focusable="false" viewBox="0 0 24 24" aria-hidden="true"> <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g transform="translate(6, 7)" fill="#4A90E2"> <g> <path d="M6.39209659,3.4962638 L6.39209659,9.59103653 C6.39209659, 9.98342289 6.07402841,10.3013206 5.6818125,10.3013206 C5.28959659, 10.3013206 4.97152841,9.98342289 4.97152841,9.59103653 L4.97152841, 3.4962638 L4.17516477,4.29262744 C3.89783523,4.56995698 3.44817614, 4.56995698 3.17084659,4.29262744 C2.89351705,4.01529789 2.89351705, 3.5656388 3.17084659,3.28830925 L5.17965341,1.27950244 C5.45698295, 1.00217289 5.90664205,1.00217289 6.18397159,1.27950244 L8.19277841, 3.28830925 C8.47010795,3.5656388 8.47010795,4.01529789 8.19277841, 4.29262744 C7.91561932,4.56995698 7.46578977,4.56995698 7.18846023, 4.29262744 L6.39209659,3.4962638 Z M9.94317614,4.96852841 C10.7277784, 4.96852841 11.3635739,5.60449432 11.3635739,6.38909659 L11.3635739, 13.4912557 C11.3635739,14.275858 10.7277784,14.9116534 9.94317614, 14.9116534 L1.42044886,14.9116534 C0.635846591,14.9116534 -0.000119318182, 14.275858 -0.000119318182,13.4912557 L-0.000119318182, 6.38909659 C-0.000119318182,5.60449432 0.635846591,4.96852841 1.42044886, 4.96852841 L2.1305625,4.96852841 C2.52294886,4.96852841 2.84084659, 5.28659659 2.84084659,5.6788125 C2.84084659,6.07102841 2.52294886, 6.38909659 2.1305625,6.38909659 L1.42044886,6.38909659 L1.42044886, 13.4912557 L9.94317614,13.4912557 L9.94317614,6.38909659 L9.23289205, 6.38909659 C8.84067614,6.38909659 8.52277841,6.07102841 8.52277841, 5.6788125 C8.52277841,5.28659659 8.84067614,4.96852841 9.23289205, 4.96852841 L9.94317614,4.96852841 Z" id="Fill-1"> </path> </g> </g> </g> </svg>
8thwall/web/xrextras/src/pwainstallermodule/ios-action-icon-svg.html/0
{ "file_path": "8thwall/web/xrextras/src/pwainstallermodule/ios-action-icon-svg.html", "repo_id": "8thwall", "token_count": 1129 }
7
## 1、对样式的操作 ### 1.1、点击按钮设置 div 的宽高和背景颜色 ```html <body> <input type="button" value="显示颜色" id="btn"> <div id="dv"></div> <script src="common.js"></script> <script> my$("btn").onclick = function () { my$("dv").style.width = "200px"; my$("dv").style.height = "100px"; my$("dv").style.backgroundColor = "pink"; }; </script> </body> ``` > 凡是 css 属性时由多个单词构成的,那么在 js 中设置的时候需要把 "-" 去掉,然后除第一个单词的首字母大写即可。 > > 比如:css里面的 `background-color`,在js里面的写法是 `backgroundColor`. ### 1.2、点击按钮隐藏和显示 div 标签 ```html <body> <input type="button" value="hide" id="btn"> <div id="dv" style="width: 200px; height: 100px; background-color: pink;"></div> <script src="common.js"></script> <script> my$("btn").onclick = function () { if(this.value === "hide") { my$("dv").style.display = "none"; this.value = "show"; }else if(this.value === "show") { my$("dv").style.display = "block"; // block是显示标签 this.value = "hide"; } }; </script> </body> ``` ### 1.3、网页开关灯 ```html <head> <meta charset="UTF-8"> <title>Title</title> <style> .cls { background-color: #000; } </style> </head> <body class=""> <input type="button" value="ON/OFF" id="btn"> <script src="common.js"></script> <script> my$("btn").onclick = function () { document.body.className = document.body.className !== "cls" ? "cls" : ""; }; </script> </body> ``` > document.body 可以选中 body 标签。 ### 1.4、点击小图在小图下显示大图 ```html <a href="images/big.png" id="ah"> <img src="images/small.png"> </a> <img src="" id="im"> <script src="common.js"></script> <script> my$("ah").onclick = function () { my$("im").src = this.href; return false; }; </script> ``` > 使用 ` return false; ` 阻止链接原本的跳转。 ### 1.5、列表高亮显示 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> ul { list-style: none; cursor: pointer; } </style> </head> <body> <ul> <li>哈哈哈</li> <li>哈哈哈</li> <li>哈哈哈</li> </ul> <script src="common.js"></script> <script> var liObjs = document.getElementsByTagName("li"); for(var i=0; i<liObjs.length; i++) { // 鼠标进入事件 liObjs[i].onmouseover = function () { this.style.backgroundColor = "pink"; }; // 鼠标离开事件 liObjs[i].onmouseout = function () { this.style.backgroundColor = ""; // 空表示恢复之前的颜色 }; } </script> </body> </html> ``` ### 1.6、通过 name 属性获取元素 ```html <input type="button" value="按钮" id="btn"><br> <input type="text" value="lvonve" name="nm1"><br> <input type="text" value="lvonve" name="nm2"><br> <input type="text" value="lvonve" name="nm1"><br> <input type="text" value="lvonve" name="nm3"><br> <input type="text" value="lvonve" name="nm1"><br> <script src="common.js"></script> <script> my$("btn").onclick = function () { var inputs = document.getElementsByName("nm1"); for (var i = 0; i < inputs.length; i++) { inputs[i].value = "Daotin"; } }; </script> ``` > **通过 name 属性获取元素适用于表单标签,基本标签没有 name 属性** > > 基本标签:`div,p,h1,ul,li,br`等 > > 表单标签:`input, select,option,form,textarea,datalist,label`等 ### 1.7、根据类样式的名字获取元素 ```html <head> <meta charset="UTF-8"> <title>Title</title> <style> .cls { background-color: yellow; } </style> </head> <body> <p class="cls">第一个p标签</p> <p>第二个p标签</p> <span class="cls">第一个span</span><br> <span>第二个span</span> <div>第一个div</div> <div class="cls">第二个div</div> <input type="button" value="按钮" id="btn"> <script src="common.js"></script> <script> my$("btn").onclick = function () { var objs = document.getElementsByClassName("cls"); for(var i=0; i<objs.length; i++) { objs[i].style.backgroundColor = "red"; } }; </script> </body> ``` > 注意:getElementsByClassName 在IE8等低版本浏览器不支持。 ## 2、获取元素的方式总结 **1、根据 id 的属性的值获取元素,返回值是一个元素对象** ```javascript document.getElementById("id属性的值"); ``` **2、根据标签名获取元素,返回值是包含多个元素对象的伪数组** ```javascript document.getElementsByTagName("标签名字"); ``` **3、根据 name 属性的值获取元素,返回值是包含多个元素对象的伪数组** ```javascript document.getElementsByName("name属性的值"); ``` **4、根据 class 类样式的名字获取元素,返回值是包含多个元素对象的伪数组** ```javascript document.getElementsByClassName("class类样式的值"); ``` **5、根据 CSS 选择器获取元素,返回值是一个元素对象** ```javascript document.querySelector("#id属性的值"); document.querySelector("标签的名字"); document.querySelector(".class类样式的值"); ``` **6、根据 CSS 选择器获取元素,返回值是包含多个元素对象的伪数组** ```javascript document.querySelectorAll("#id属性的值"); document.querySelectorAll("标签的名字"); document.querySelectorAll(".class类样式的值"); ``` > 注意区分是名字还是值。 ### **注意:以上方法获取的元素的集合都是伪数组。** 判断伪数组的方式是伪数组不能调用数组的方法。(Boolean(list.sort) == false)或者使用instanceof (list instanceof Array)。 **伪数组怎么变为真数组?** 定义一个空数组,把伪数组的所有内容复制过去即可。 ## 3、案例:模拟搜索框 ```html <head> <meta charset="UTF-8"> <title>Title</title> <style> input { color: gray; } </style> </head> <body> <input type="text" value="请输入搜索内容"> <script src="common.js"></script> <script> // 获取文本框对象 var inputObj = document.getElementsByTagName("input")[0]; // 为文本框注册获取焦点事件 inputObj.onfocus = function () { if(this.value === "请输入搜索内容") { this.value = ""; this.style.color = "#000"; } }; // 为文本框注册失去焦点事件 inputObj.onblur = function () { if(this.value.length === 0) { this.value = "请输入搜索内容"; this.style.color = "gray"; } }; </script> </body> ``` > 文本框注册失去焦点事件的时候使用 `this.value.length === 0`,而不使用 `this.value === "请输入搜索内容"` 是因为数字的比较比字符串的比较效率更高。
Daotin/Web/03-JavaScript/02-DOM/02-对样式的操作,获取元素的方式.md/0
{ "file_path": "Daotin/Web/03-JavaScript/02-DOM/02-对样式的操作,获取元素的方式.md", "repo_id": "Daotin", "token_count": 4032 }
8
## 一、this this 指的是某一对象。但是在不同的场景,this表示的是不同的对象。 下面大概分为5种情况: ### 1、window ```js // 第一种:this 指的就是 window function fn() { console.log(this); }; console.log(this); ``` ### 2、事件中的this ```js // 第二种:所有事件函数中的this,都是这个监听事件监听对象 //在事件函数中 this===e.currentTarget 也就是事件侦听的对象。在事件中使用this,其实事件函数内部实现极力就是使用call等将事件中的this改为 e.currentTarget。 // currentTarget始终是监听事件者,而target是事件的真正发出者。 document.querySelector(".div0").onclick=function (e) { console.log(this); console.log(e.target); console.log(e.currentTarget); }; ``` ### 3、对象中的this ```js // 第三种:对象中的this,this就是当前这个对象。 // 在对象的函数中,如果需要调用当前对象的其他函数或者属性时,必须加 this.属性名 或者 this.方法名. var obj={ a:1, c:function () { console.log(this.a); } }; ``` ### 4、面向对象中的this ```js // 第四种:面向对象中的this // ES5 面向对象写法 function Box(d) { this.d=d; } Box.prototype={ a:1, c:function () { // 这里的this就是box1 console.log(this.a+this.d); } }; var box1=new Box(10); box1.c(); // ES6 的面向对象写法 class Ball{ constructor(d){ this.d=d; this.a=1; } c(){ console.log(this.d+this.a) } } var ball1=new Ball(10); ball1.c(); ``` ### 5、call,apply和bind中的this ```js //第五种:call,apply和bind中的this // 这里的this就是被替换的对象 function fn2(a,b) { this.a=a; this.b=b; return this; } var obj1=fn2.call({},3,5); var obj2=fn2.call({c:6},10,12); console.log(obj1,obj2);// {a:3,b:5}, {a:3,b:5,c:6} ``` ## 二、apply 和 call 方法 **语法**: ```js //1、apply的使用语法: 函数名.apply(对象,[参数1, 参数2,... ]); 方法名.apply(对象,[参数1, 参数2,... ]); //2、call的使用语法: 函数名.call(对象,参数1, 参数2,... ); 方法名.call(对象,参数1, 参数2,... ); ``` 不同的是传入参数时,apple有两个参数,第二个参数是数组;call 从第二个参数开始是调用其的函数的所有参数。 > apple 和 call 都可以改变调用其的函数或方法中的 this 指向。this的指向为传入的对象。 > > 当传入对象的位置为 null 时,不改变this的执行,此时相当于函数的一般执行。 ### 1、函数调用apply和call ```js function f1(x, y) { console.log(x+y +this); // 这里面的this是window return x+y; } var r1 = f1.apply(null, [10,20]); // 打印30 window,传入的是null,所以this指向还是window console.log(r1); // 30 var r2 = f1.call(null, 10,20);// 打印30 window console.log(r2); // 30 ``` ```js //函数改变 this 的指向 var obj = {}; var r1 = f1.apply(obj, [10,20]); // 打印30 window,传入的是Obj,所以this指向是Obj console.log(r1); // 30 var r2 = f1.call(obj, 10,20);// 打印30 Obj console.log(r2); // 30 ``` 示例: ```js // 改变函数fn的this为array function fn(a, b) { this.push(a, b); console.log(this); }; fn.call(new Array, 1, 2);//[1, 2] ``` ### 2、方法调用apply和call ```js // 方法改变 this 的指向 function Person(age) { this.age = age; } Person.prototype.eat = function () { console.log(this.age); // this 指向实例对象 }; function Student(age) { this.age = age; } var per = new Person(18); var stu = new Student(20); per.eat.apply(stu); // 打印 20 per.eat.call(stu); // 打印 20 ``` > 由于 eat 方法已经指向了 Student 了,所以打印 20,而不是 18. 问题:我们知道函数也是对象,函数可以调用 apple 和 call 方法,但是这两个方法并不在这个函数这个对象的实例函数中,那么在哪里呢? > **解答:**所有的函数都是 Function 的实例对象,而 apply 和 call 就在 Function 构造函数的原型对象中。 ## 三、bind方法 bind 是复制的意思,也可以改变调用其的函数或方法的 this 指向,参数可以在复制的时候传进去,也可以在复制之后调用的时候传进去。 如果一个函数fn中的this是window,那么fn.bind(obj)就把fn中的this改为obj。但是fn还是一样的执行。 fn.bind(obj)(); 所以bind就是改this,没有其他。 > 使用语法: > > 1、函数名.bind(对象, 参数1, 参数2, ...); // 返回值是复制的这个函数 > > 2、方法名.bind(对象, 参数1, 参数2, ...); // 返回值是复制的这个方法 ### 1、函数调用 bind ```js function f1(x, y) { console.log(x + y + this); } // 1.参数在复制的时候传入 var ff = f1.bind(null,10,20); // 这只是复制的一份函数,不是调用,返回值才是 ff(); 或者 f1.bind(null)(10,20); // 2.参数在调用的时候传入 var ff = f1.bind(null); // 这只是复制的一份函数,不是调用,返回值才是 ff(10,20); ``` ### 2、方法调用 bind ```js function Person(age) { this.age = age; } Person.prototype.eat = function () { console.log(this.age); // this 指向实例对象 }; function Student(age) { this.age = age; } var per = new Person(18); var stu = new Student(20); var ff = per.eat.bind(stu); ff(); // 20 ``` ### 3、call,apply和bind的区别: > 1、call,apply 一调用函数就执行了,直接改变调用函数的this指向,然后执行。 > > 2、而bind的调用函数并没有直接执行。bind并不会改变调用它的this的指向,它的返回值是和调用它的函数本身,只是改变了this的指向。 ## 四、闭包 ### 1、闭包的概念 **闭包是指有权访问另一个函数作用域中变量的函数,创建闭包的最常见的方式就是在一个函数内创建另一个函数,通过另一个函数访问这个函数的局部变量,利用闭包可以突破作用链域,将函数内部的变量和方法传递到外部。** 当一个函数的返回值是另外一个函数,而返回的那个函数如果调用了其父函数内部的变量,且返回的这个函数在外部被执行就产生了闭包。 形成一个闭包很简单:创建闭包的最常见的方式就是在一个函数内创建另一个函数,通过另一个函数访问这个函数的局部变量。比如:有一个函数 A 中有一个函数或者对象 B,那么函数或者对象 B 可以访问函数 A 中的数据,那么函数 A 的作用域就形成了闭包。 也就是要求: - 必须有两个函数,并且是嵌套关系,外面的函数必须返回里面的函数。 - 在全局中必须接收返回函数作为变量存储. ### 2、闭包的模式 函数模式的闭包:函数中包含函数。 ```js function fn1() { var i=0; return function () { i++; console.log(i); } } // fn1的返回值是一个函数,函数也是对象,存在堆中。那么与此函数相关的内容,也会被存放在堆中。就不容易被清除。 var fn2=fn1(); fn2(); // 1 fn2(); // 2 fn2(); // 3 ``` 对象模式的闭包:函数中包含对象。 ```js var method=(function () { var i=0; return { a:1, b:2, c:function () { i++; console.log(i); } } })(); method.c(); // 1 method.c(); // 2 method.c(); // 3 ``` 面向对象方式的闭包: ```js var Box=(function () { function Box() { } Box.prototype={ }; return Box; })() ``` ### 3、闭包的特点 - 函数嵌套函数 - 函数内部可以引用外部的参数和变量 - 参数和变量不会被垃圾回收机制回收 ### 4、闭包的优缺点 也是缓存的数据,导致在闭包的范围内一直起作用,造成内存泄漏,不会被垃圾回收。 ### 5、闭包的应用 缓存数据,函数中的数据,外面可以使用。 如果想要缓存数据,就把这个数据放在外层的函数和里层的函数之间。这样不停的调用里层函数,相当于外层函数里的数据没有得到及时释放,就相当于缓存了数据。 ```js // 函数闭包 function A() { var num = 10; return function () { return num++; } } var func = A(); console.log(func()); console.log(func()); console.log(func()); ``` ```js // 对象闭包 function A() { var num = 10; return { age: num++ }; } var func = A(); console.log(func.age); ``` ## 五、沙箱 沙箱:一小块的真实环境,里面发生的事情不会影响到外面。相同的操作,相同的数据都不会和外面发生冲突。 作用:避免命名冲突。 比如:**自调用函数**里面就相当于一个沙箱环境。 ```js (function (){ }()); ```
Daotin/Web/03-JavaScript/04-JavaScript高级知识/05-apply与call,bind,闭包和沙箱.md/0
{ "file_path": "Daotin/Web/03-JavaScript/04-JavaScript高级知识/05-apply与call,bind,闭包和沙箱.md", "repo_id": "Daotin", "token_count": 5378 }
9
## 一、绑定事件 ### 1、事件名(不推荐) 语法: ```js // 元素.事件名(数据,事件处理函数); $("div").click({a:1,b:2}, function(e){ console.log(e.data); // {a:1,b:2} }); ``` > 注意:数据的解释参考 on绑定事件。 示例: ```js // 绑定鼠标进入,离开,点击事件 $("#btn").mouseenter(function () { console.log("mouseenter"); }); $("#btn").mouseleave(function () { console.log("mouseleave"); }); $("#btn").click(function () { console.log("click"); }); // 链式编程 $("#btn").mouseenter(function () { console.log("mouseenter"); }).mouseleave(function () { console.log("mouseleave"); }).click(function () { console.log("click"); }); ``` 示例:模拟css的hover事件 ```js $("div").hover(function(){ // 鼠标放上去触发的事件 // 类似mouseenter },function(){ // 鼠标离开触发的事件 // 类似mouseleave }) ``` ### ~~2、bind方法~~ > jQuery1.7 以前采用。 语法: ```js 元素.bind("事件名", 事件处理函数); ``` 示例: ```js $("#btn").bind("mouseenter", function () { console.log("bind:mouseenter"); }); $("#btn").bind("mouseleave", function () { console.log("bind:mouseleave"); }); $("#btn").bind("click", function () { console.log("bind:click"); }); // 链式编程 $("#btn").bind("mouseenter", function () { console.log("bind:mouseenter"); }).bind("mouseleave", function () { console.log("bind:mouseleave"); }).bind("click", function () { console.log("bind:click"); }); ``` ### ~~3、bind对象~~ 语法: ```js 元素.bind({"事件名1":事件处理函数1, "事件名2":事件处理函数2,...}); ``` 示例: ```js $("#btn").bind({ "mouseenter": function () { console.log("bind-obj:mouseenter"); }, "mouseleave": function () { console.log("bind-obj:mouseleave"); }, "click": function () { console.log("bind-obj:click"); } }); ``` > 使用 bind 对象的方式,只需要一个bind,可以绑定多个事件。 ### 4、delegate方法 语法:(父元素替子元素绑定事件) ```js 父元素.delegate("子元素","事件名",事件处理函数); ``` 示例: ```js // 为div下p标签绑定点击事件 $("#dv").delegate("p", "click", function () { //.... }); ``` ### 5、on(推荐) 我发现 delegate 方法内部调用的是 on 方法,那么 on 方法也可以绑定事件 > 注意:on 的参数顺序和 delegate 相反。 语法: ```js // ele绑定incident事件,事件处理函数incHandler ele.on("incident",function(){}) // 可以一次绑定多个事件 ele.on("incident1 incident2", function(){}); // 或者这样 ele.on({ "incident1":function(){}, "incident2":function(){} }); // 可以给子元素绑定事件 父元素.on("incident", "子元素", function(){}); // 子元素的位置可以传入参数 // 通过 event.data 获取额外数据,可以是数字、(字符串)、数组、对象, json等 元素.on("inclident", 数据, function(e){ console.log(e.data); // 获取传入的数据 }) ``` > 注意:当中间的数据为字符串时,会自动识别为子元素,这时打印 e.data 为undefined。 ### - 为元素绑定多个相同的事件 ```js // 方式一 $("#btn").click(function () { console.log("click1"); }).click(function () { console.log("click2"); }).click(function () { console.log("click3"); }); // 方式二 $("#btn").bind("click",function () { console.log("bind:click1"); }).bind("click",function () { console.log("bind:click2"); }).bind("click",function () { console.log("bind:click3"); }); ``` **注意:下面使用 bind 对象的方式,只会执行最后一个相同的绑定事件。** ```js $("#btn").bind({ "click": function () { console.log("bind-obj:click1"); }, "click": function () { console.log("bind-obj:click2"); }, "click": function () { console.log("bind-obj:click3"); } }); ``` ### - 为事件添加ID 在为元素绑定多个相同事件的时候,可以为绑定的事件加个id,这样在解绑的时候,可以单独针对其中一个或多个进行解绑,而不会把所有相同的事件全部解绑。 ```js $("div").on("click.a",function (e) { console.log("aaa") }); $("div").on("click.b",function (e) { console.log("bbb") }); // 解绑的其中一个的时候 $("div").off("click.a"); ``` ### 6、一次性事件 ```js 元素.one("事件",function(){}); //只能执行一次的事件 ``` ## 二、jQuery事件对象e jQuery中的事件对象e和DOM中的事件对象e不同。 jQuery中的事件对象对DOM的事件对象e进行了封装。`jQuery的 e.originalEvent == DOM中的e` ```js e.stopPropagation() //阻止事件冒泡 // 前提绑定了相同的事件。 e.preventDefault(); // 阻止默认事件 // 同时阻止事件冒泡和阻止默认事件 return false; ``` 示例:div拖动案例 ```html <script src="../js/jquery-1.12.4.js"></script> <script> $("<div></div>").appendTo("body") .css({ width: 50, height: 50, backgroundColor: "red", position: "absolute" }) .on("mousedown mouseup", function (e) { if (e.type === "mousedown") { $(document).on("mousemove", { div: this, x: e.offsetX, y: e.offsetY }, function (e) { $(e.data.div).css({ left: e.clientX - e.data.x, top: e.clientY - e.data.y }); }); } else if (e.type === "mouseup") { $(document).off("mousemove"); } }) </script> ``` ## 三、元素绑定事件的区别 先说结论:**通过调用事件名的方式和 bind 的方式只能绑定之前存在的元素,后添加的元素不能绑定事件;而 delegate 和 on 的方式绑定元素的方式可以。** 示例1: ```js // 事件名 $("#btn").click(function () { $("#dv").append($("<p>p标签</p>")); $("p").click(function () { alert("p被点了"); }); $("#dv").append($("<p>p标签2</p>")); }); // bind $("#btn").click(function () { $("#dv").append($("<p>p标签</p>")); $("p").bind("click", function () { alert("p被点了"); }); $("#dv").append($("<p>p标签2</p>")); }); ``` > 点击 p标签2 的时候不会弹出对话框。 示例2: ```js // delegate $("#btn").click(function () { $("#dv").append($("<p>p标签</p>")); $("#dv").delegate("p", "click", function () { alert("p被点了"); }); $("#dv").append($("<p>p标签2</p>")); }); // on $("#btn").click(function () { $("#dv").append($("<p>p标签</p>")); $("#dv").on("click", "p", function () { alert("p被点了"); }); $("#dv").append($("<p>p标签2</p>")); }); ``` > 后添加的 p 标签也会被绑定点击事件。 ## 三、解绑事件 用什么方式绑定的事件,最好用什么方式解绑事件。 ### ~~1、unbind 解绑事件~~ 语法: ```js // 解绑单个或多个事件 绑定事件的元素.unbind("事件名1 事件名2 ..."); // 解绑所有的事件 绑定事件的元素.unbind(); ``` > PS:unbind 也可以解绑 `元素.事件名(事件处理函数)` 方式的绑定事件。 ### 2、undelegate 解绑事件 语法: ```js // 解绑子元素单个或多个事件 父元素.undelegate("子元素", "事件1 事件2 ..."); // 解绑子元素的所有事件 父元素.undelegate(); ``` > 下面的写法是无效的:`父元素.undelegate("子元素");`,不能移除子元素的所有事件。 ### 3、off 解绑事件 > 1、当绑定事件的时候是:``on(事件,参数,有名字函数)` > > 解绑事件:`off(事件,有名字函数)` > > 2、当绑定事件的时候是:`on(事件,参数,匿名函数)` > > 解绑事件:`off(事件)` 语法: ```js // 父元素和子元素的所有事件都会解绑 父元素.off(); // 父元素和子元素的单个或多个事件解绑 父元素.off("事件1 事件2 ..."); // 子元素的所有事件解绑 父元素.off("", "子元素"); // 子元素的单个或多个事件解绑 父元素.off("事件1 事件2 ...", "子元素"); // 父元素中所有的子元素的所有事件解绑 父元素.off("", "**"); // 父元素中所有的子元素的单个或多个事件解绑 父元素.off("事件1 事件2 ...", "**"); ``` > 注意:子元素的所有事件解绑 。下面的写法是无效的。`父元素.off("子元素"); `
Daotin/Web/04-jQuery/06-jQuery绑定解绑事件.md/0
{ "file_path": "Daotin/Web/04-jQuery/06-jQuery绑定解绑事件.md", "repo_id": "Daotin", "token_count": 5107 }
10
## 一、基础知识 ### 1、屏幕 移动设备与PC设备最大的差异在于屏幕,这主要体现在**屏幕尺寸**和**屏幕分辨率**两个方面。 通常我们所指的屏幕尺寸,实际上指的是屏幕对角线的长度(一般用英寸来度量)。 而分辨率则一般用像素来度量 `px`,表示屏幕水平和垂直方向的像素数,例如 1920*1080 指的是屏幕垂直方向和水平方向分别有1920和1080个像素点而构成。 ### 2、长度单位 在Web开发中可以使用`px`(像素)、`em`、`pt`(点)、`in`(英寸)、`cm`(厘米)做为长度单位,我们最常用`px`(像素)做为长度单位。 我们可以将上述的几种长度单位划分成相对长度单位和绝对长度单位。 例如:iPhone3G/S和iPhone4/S的屏幕尺寸都为 3.5 英寸(in)但是屏幕分辨率却分别为 480x320px、960x480px,由此我们可以得出英寸是一个绝对长度单位,而像素是一个相对长度单位(像素并没有固定的长度)。 ### 3、像素密度 DPI(Dots Per Inch)是印刷行业中用来表示打印机每英寸可以喷的墨汁点数,计算机显示设备从打印机中借鉴了DPI的概念,由于计算机显示设备中的最小单位不是墨汁点而是像素,所以用PPI(Pixels Per Inch)值来表示屏幕每英寸的像素数量,我们将PPI、DPI都称为像素密度,但PPI应用更广泛,DPI在Android设备比较常见。 利用屏幕分辨率计算 PPI : ![](./images/1.png) ### 4、设备独立像素 随着技术发展,设备不断更新,出现了不同PPI的屏幕共存的状态(如iPhone3G/S为163PPI,iPhone4/S为326PPI),像素不再是统一的度量单位,这会造成同样尺寸的图像在不同PPI设备上的显示大小不一样。 如下图,假设你设计了一个163x163的蓝色方块,在PPI为163的屏幕上,那这个方块看起来正好就是1x1寸大小,在PPI为326的屏幕上,这个方块看起来就只有0.5x0.5寸大小了。 但是做为用户是不会关心这些细节的,他们只是希望在不同PPI的设备上看到的图像内容差不多大小,所以这时我们需要一个新的单位,这个新的单位能够保证图像内容在不同的PPI设备看上去大小应该差不多,这就是独立像素,在IOS设备上叫PT(Point),Android设备上叫DIP(Device independent Pixel)或DP。 举例说明就是iPhone 3G(PPI为163)1pt = 1px,iPhone 4(PPI为326)1pt = 2px。 通过上面例子我们不难发现 pt 同px是有一个对应(比例)关系的,这个对应(比例)关系是操作系统确定并处理,目的是确保不同PPI屏幕所能显示的图像大小是一致的,通过 `window.devicePixelRatio` 可以获得该比例值。 所以,我们如何处理在不同 pt/px 比例上使得显示相同大小的图片呢? 很简单,在美工设计图片的时候,多设计几种尺寸的图片。 ### 5、像素 #### 5.1、物理像素 物理像素指的是屏幕渲染图像的最小单位,属于屏幕的物理属性,不可人为进行改变,其值大小决定了屏幕渲染图像的品质,我们以上所讨论的都指的是物理像素。 获取屏幕的物理像素尺寸: `window.screen.width;` `window.screen.height;` #### 5.2、CSS像素 CSS像素,与设备无关像素,指的是通过CSS进行网页布局时用到的单位,其默认值(PC端)是和物理像素保持一致的(1个单位的CSS像素等于1个单位的物理像素),但是我们可通缩放来改变CSS像素的大小。 我们需要理解的是物理像素和CSS像素的一个关系,1个物理像素并不总是等于一个CSS像素,通过缩放,一个CSS像素可能大于1个物理像素,也可能小于1个物理像素。 ## 二、调试 ### 1、模拟调试 现代主流浏览器均支持移动开发模拟调试,通常按F12可以调起,其使用也比较简单,可以帮我们方便快捷定位问题。 ### 2、真机调试 模拟调试可以满足大部分的开发调试任务,但是由于移动设备种类繁多,环境也十分复杂,模拟调试容易出现差错,所以真机调试变的非常必要。 有两种方法可以实现真机调试: 1、将做好的网页上传至服务器或者本地搭建服务器,然后移动设备通过网络来访问。(重点) 2、借助第三方的调试工具,如weinre、debuggap、ghostlab(推荐) 等。 真机调试必须保证移动设备同服务器间的网络是相通的。 ## 三、视口 视口(viewport)是用来约束网站中最顶级块元素\<html>的,即它决定了\<html>的大小。 ### 1、PC 设备 在PC设备上viewport的大小取决于浏览器窗口的大小,以CSS像素做为度量单位。 通过以往CSS的知识,我们都能理解\<html>的大小是会影响到我们的网页布局的,而viewport又决定了\<html>的大小,所以viewport间接的决定并影响了我们网页的布局。 ```css /* 获取viewport的大小 */ document.documentElement.clientWidth; document.documentElement.clientHeight; ``` 在PC端,我们通过调整浏览器窗口可以改变 viewport 的大小,为了保证网页布局不发生错乱,需要给元素设定较大固定宽度。 ### 2、移动设备 移动设备屏幕普遍都是比较小的,但是大部分的网站又都是为PC设备来设计的,要想让移动设备也可以正常显示网页,移动设备不得不做一些处理,通过上面的例子我们可以知道只要viewport足够大,就能保证原本为PC设备设计的网页也能在移动设备上正常显示,移动设备厂商也的确是这样来处理的。 在移动设备上viewport不再受限于浏览器的窗口,而是允许开发人员自由设置viewport的大小,通常浏览 器会设置一个默认大小的 viewport,为了能够正常显示那些专为PC设计的网页,一般这个值的大小会大于屏幕的尺寸。 如下图为常见默认viewport大小(仅供参考): ![](./images/2.png) 从图中统计我们得知不同的移动厂商分别设置了一个默认的viewport的值,这个值保证大部分网页可以正常在移动设备下浏览。 但是由于我们手机的屏幕很小,而 viewport 的值却很大,所以页面所有的内容就会缩小以适应屏幕,所以用手机看起来,这些字体和图片就会特别小,这就像手机设置里面有个电脑版显示一样。 要解释上面的原因,需要进一步对移动设备的 viewport 进行分析,移动设备上有2个viewport(为了方便讲解人为定义的),分别是 `layout viewport` 和` ideal viewport`。 1、`layout viewport`(布局视口)指的是我们可以进行网页布局区域的大小,同样是以CSS像素做为计量单位,可以通过下面方式获取 ```css /* 获取layout viewport */ document.documentElement.clientWidth; document.documentElement.clientHeight; ``` 通过前面介绍我们知道,如果要保证为PC设计的网页在移动设备上布局不发生错乱,移动设备会默认设置一个较大的viewport(如IOS为980px),这个viewport实际指的是layout viewport。 2、`ideal viewport`(理想视口)设备屏幕区域,(以设备独立像素PT、DP做为单位)以CSS像素做为计量单位,其大小是不可能被改变,通过下面方式可以获取。 ```css /* 获取ideal viewport有两种情形 */ /* 新设备 */ window.screen.width; window.screen.height; /* 老设备 */ window.screen.width / window.devicePixelRatio; window.screen.height / window.devicePixelRatio; ``` 理解两个viewport后我们来解释**为什么网页会被缩放或出现水平滚动条**: 其原因在于移动设备浏览器会默认设置一个layout viewport,并且这个值会大于ideal viewport,那么我们也知道ideal viewport就是屏幕区域,layout viewport是我们布局网页的区域,那么最终layout viewport是要显示在ideal viewport里的,而layout viewport大于ideal viewport时,于是就出现滚动条了,那么为什么有的移动设备网页内容被缩放了呢?移动设备厂商认为将网页完整显示给用户才最合理,而不该出现滚动条,所以就将layout viewport进行了缩放,使其恰好完整显示在ideal viewport(屏幕)里,其缩放比例为ideal viewport / layout viewport。 ### 3、移动浏览器 移动端开发主要是针对IOS和Android两个操作系统平台的,除此之外还有Windows Phone。 移动端主要可以分成三大类,系统自带浏览器、应用内置浏览器、第三方浏览器。 #### 3.1、系统浏览器 指跟随移动设备操作系统一起安装的浏览器,一般不能卸载。比如 iPhone 的 safari 浏览器。 #### 3.2、应用内置浏览器 通常在移动设备上都会安装一些APP例如 QQ、微信、微博、淘宝等,这些APP里往往会内置一个浏览器,我们称这个浏览器为应用内置浏览器(也叫WebView),这个内置的浏览器一般功能比较简单,并且客户端开发人员可以更改这个浏览器的某些设置。 #### 3.3、第三方浏览器 指安装在手机的浏览器如FireFox、Chrome、360等等。 在IOS 和 Android 操作系统上自带浏览器、应用内置浏览器都是基于Webkit内核的。 ## 四、屏幕适配 经过分析我们得到,移动页面最理想的状态是,避免滚动条且不被默认缩放处理,我们可以通过设置 `<meta name="viewport" content="">`来进行控制,并改变浏览器默认的layout viewport的宽度。 ### 1、viewport 详解 viewport 是由苹果公司为了解决移动设备浏览器渲染页面而提出的解决方案,后来被其它移动设备厂商采纳,其使用参数如下: 通过设置属性 `content=""` 实现,中间以逗号分隔。 示例: ```html <meta name="viewport" content="width=device-width, initital-scale=1.0, user-scalable=no"> ``` > `width` :设置 layout viewport 宽度,其取值可为数值或者device-width。 > > `height`:设置layout viewport 高度,其取值可为数值或者device-height > > `initital-scale`:设置页面的初始缩放值,为一个数字,可以带小数。 > > `maximum-scale`:允许用户的最大缩放值,为一个数字,可以带小数。 > > `minimum-scale`:允许用户的最小缩放值,为一个数字,可以带小数。 > > `user-scalable`:是否允许用户进行缩放,值为"no"(不能缩放)或"yes"(可以缩放)。 注:device-width 和 device-height 就是 ideal viewport 的宽和高。 ### 2、控制缩放 设置 `<meta name="viewport" content="initial-scale=1">`,这时我们发现网页没有被浏览器设置缩放。 设置 `<meta name="viewport" content="width=device-width">`,这时我们发现网页也没有被浏览器设设置缩放。 当我们设置 `width=device-width`,也达到了 `initial-scale=1` 的效果,得知其实 `initial-scale = ideal viewport / layout viewport`。 两种方式都可以控制缩放,开发中一般同时设置 width=device-width 和 initial-scale=1.0(为了解决一些兼容问题)参见 [移动前端开发之viewport深入理解](http://www.cnblogs.com/2050/p/3877280.html) (http://www.cnblogs.com/2050/p/3877280.html),即: ```html <meta name="viewport" content="width=device-width, initial-scale=1.0"> ``` ​ ### 3、适配方案 **关于 em 和 rem** **em 是相对长度单位(参照父元素)**,其参照当前元素字号大小,如果当前元素未设置字号则会继承其祖先元素字号大小。 例如:` .box {font-size: 16px;}` 则 1em = 16px `.box {font-size: 32px;} `则 1em = 32px,0.5em = 16px **rem 相对长度单位(参照 html 元素)**,其参照根元素(html)字号大小。 例如 :`html {font-size: 16px;}` 则 1rem = 16px `html {font-size: 32px;}` 则 1rem = 32px,0.5rem = 16px. **vw:viewport width,视口宽度** (1vw = 1%视口宽度) **vh:viewport height 视口高度** (1vh = 1%视口高度) ### 4、移动端终极适配方案 网易淘宝适配方案:https://www.manster.me/?p=311
Daotin/Web/07-移动Web开发/01-屏幕相关基本知识,调试,视口,屏幕适配.md/0
{ "file_path": "Daotin/Web/07-移动Web开发/01-屏幕相关基本知识,调试,视口,屏幕适配.md", "repo_id": "Daotin", "token_count": 8116 }
11
/* Zepto 1.2.0 - zepto event ajax form ie fx selector touch - zeptojs.com/license */ (function(global, factory) { if (typeof define === 'function' && define.amd) define(function() { return factory(global) }) else factory(global) }(this, function(window) { var Zepto = (function() { var undefined, key, $, classList, emptyArray = [], concat = emptyArray.concat, filter = emptyArray.filter, slice = emptyArray.slice, document = window.document, elementDisplay = {}, classCache = {}, cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 }, fragmentRE = /^\s*<(\w+|!)[^>]*>/, singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rootNodeRE = /^(?:body|html)$/i, capitalRE = /([A-Z])/g, // special attributes that should be get/set via method calls methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'], adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ], table = document.createElement('table'), tableRow = document.createElement('tr'), containers = { 'tr': document.createElement('tbody'), 'tbody': table, 'thead': table, 'tfoot': table, 'td': tableRow, 'th': tableRow, '*': document.createElement('div') }, simpleSelectorRE = /^[\w-]*$/, class2type = {}, toString = class2type.toString, zepto = {}, camelize, uniq, tempParent = document.createElement('div'), propMap = { 'tabindex': 'tabIndex', 'readonly': 'readOnly', 'for': 'htmlFor', 'class': 'className', 'maxlength': 'maxLength', 'cellspacing': 'cellSpacing', 'cellpadding': 'cellPadding', 'rowspan': 'rowSpan', 'colspan': 'colSpan', 'usemap': 'useMap', 'frameborder': 'frameBorder', 'contenteditable': 'contentEditable' }, isArray = Array.isArray || function(object){ return object instanceof Array } zepto.matches = function(element, selector) { if (!selector || !element || element.nodeType !== 1) return false var matchesSelector = element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.matchesSelector if (matchesSelector) return matchesSelector.call(element, selector) // fall back to performing a selector: var match, parent = element.parentNode, temp = !parent if (temp) (parent = tempParent).appendChild(element) match = ~zepto.qsa(parent, selector).indexOf(element) temp && tempParent.removeChild(element) return match } function type(obj) { return obj == null ? String(obj) : class2type[toString.call(obj)] || "object" } function isFunction(value) { return type(value) == "function" } function isWindow(obj) { return obj != null && obj == obj.window } function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE } function isObject(obj) { return type(obj) == "object" } function isPlainObject(obj) { return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype } function likeArray(obj) { var length = !!obj && 'length' in obj && obj.length, type = $.type(obj) return 'function' != type && !isWindow(obj) && ( 'array' == type || length === 0 || (typeof length == 'number' && length > 0 && (length - 1) in obj) ) } function compact(array) { return filter.call(array, function(item){ return item != null }) } function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array } camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) } function dasherize(str) { return str.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/_/g, '-') .toLowerCase() } uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) } function classRE(name) { return name in classCache ? classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)')) } function maybeAddPx(name, value) { return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value } function defaultDisplay(nodeName) { var element, display if (!elementDisplay[nodeName]) { element = document.createElement(nodeName) document.body.appendChild(element) display = getComputedStyle(element, '').getPropertyValue("display") element.parentNode.removeChild(element) display == "none" && (display = "block") elementDisplay[nodeName] = display } return elementDisplay[nodeName] } function children(element) { return 'children' in element ? slice.call(element.children) : $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node }) } function Z(dom, selector) { var i, len = dom ? dom.length : 0 for (i = 0; i < len; i++) this[i] = dom[i] this.length = len this.selector = selector || '' } // `$.zepto.fragment` takes a html string and an optional tag name // to generate DOM nodes from the given html string. // The generated DOM nodes are returned as an array. // This function can be overridden in plugins for example to make // it compatible with browsers that don't support the DOM fully. zepto.fragment = function(html, name, properties) { var dom, nodes, container // A special case optimization for a single tag if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1)) if (!dom) { if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>") if (name === undefined) name = fragmentRE.test(html) && RegExp.$1 if (!(name in containers)) name = '*' container = containers[name] container.innerHTML = '' + html dom = $.each(slice.call(container.childNodes), function(){ container.removeChild(this) }) } if (isPlainObject(properties)) { nodes = $(dom) $.each(properties, function(key, value) { if (methodAttributes.indexOf(key) > -1) nodes[key](value) else nodes.attr(key, value) }) } return dom } // `$.zepto.Z` swaps out the prototype of the given `dom` array // of nodes with `$.fn` and thus supplying all the Zepto functions // to the array. This method can be overridden in plugins. zepto.Z = function(dom, selector) { return new Z(dom, selector) } // `$.zepto.isZ` should return `true` if the given object is a Zepto // collection. This method can be overridden in plugins. zepto.isZ = function(object) { return object instanceof zepto.Z } // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and // takes a CSS selector and an optional context (and handles various // special cases). // This method can be overridden in plugins. zepto.init = function(selector, context) { var dom // If nothing given, return an empty Zepto collection if (!selector) return zepto.Z() // Optimize for string selectors else if (typeof selector == 'string') { selector = selector.trim() // If it's a html fragment, create nodes from it // Note: In both Chrome 21 and Firefox 15, DOM error 12 // is thrown if the fragment doesn't begin with < if (selector[0] == '<' && fragmentRE.test(selector)) dom = zepto.fragment(selector, RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // If it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // If a function is given, call it when the DOM is ready else if (isFunction(selector)) return $(document).ready(selector) // If a Zepto collection is given, just return it else if (zepto.isZ(selector)) return selector else { // normalize array if an array of nodes is given if (isArray(selector)) dom = compact(selector) // Wrap DOM nodes. else if (isObject(selector)) dom = [selector], selector = null // If it's a html fragment, create nodes from it else if (fragmentRE.test(selector)) dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // And last but no least, if it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // create a new Zepto collection from the nodes found return zepto.Z(dom, selector) } // `$` will be the base `Zepto` object. When calling this // function just call `$.zepto.init, which makes the implementation // details of selecting nodes and creating Zepto collections // patchable in plugins. $ = function(selector, context){ return zepto.init(selector, context) } function extend(target, source, deep) { for (key in source) if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { if (isPlainObject(source[key]) && !isPlainObject(target[key])) target[key] = {} if (isArray(source[key]) && !isArray(target[key])) target[key] = [] extend(target[key], source[key], deep) } else if (source[key] !== undefined) target[key] = source[key] } // Copy all but undefined properties from one or more // objects to the `target` object. $.extend = function(target){ var deep, args = slice.call(arguments, 1) if (typeof target == 'boolean') { deep = target target = args.shift() } args.forEach(function(arg){ extend(target, arg, deep) }) return target } // `$.zepto.qsa` is Zepto's CSS selector implementation which // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`. // This method can be overridden in plugins. zepto.qsa = function(element, selector){ var found, maybeID = selector[0] == '#', maybeClass = !maybeID && selector[0] == '.', nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked isSimple = simpleSelectorRE.test(nameOnly) return (element.getElementById && isSimple && maybeID) ? // Safari DocumentFragment doesn't have getElementById ( (found = element.getElementById(nameOnly)) ? [found] : [] ) : (element.nodeType !== 1 && element.nodeType !== 9 && element.nodeType !== 11) ? [] : slice.call( isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagName maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class element.getElementsByTagName(selector) : // Or a tag element.querySelectorAll(selector) // Or it's not simple, and we need to query all ) } function filtered(nodes, selector) { return selector == null ? $(nodes) : $(nodes).filter(selector) } $.contains = document.documentElement.contains ? function(parent, node) { return parent !== node && parent.contains(node) } : function(parent, node) { while (node && (node = node.parentNode)) if (node === parent) return true return false } function funcArg(context, arg, idx, payload) { return isFunction(arg) ? arg.call(context, idx, payload) : arg } function setAttribute(node, name, value) { value == null ? node.removeAttribute(name) : node.setAttribute(name, value) } // access className property while respecting SVGAnimatedString function className(node, value){ var klass = node.className || '', svg = klass && klass.baseVal !== undefined if (value === undefined) return svg ? klass.baseVal : klass svg ? (klass.baseVal = value) : (node.className = value) } // "true" => true // "false" => false // "null" => null // "42" => 42 // "42.5" => 42.5 // "08" => "08" // JSON => parse if valid // String => self function deserializeValue(value) { try { return value ? value == "true" || ( value == "false" ? false : value == "null" ? null : +value + "" == value ? +value : /^[\[\{]/.test(value) ? $.parseJSON(value) : value ) : value } catch(e) { return value } } $.type = type $.isFunction = isFunction $.isWindow = isWindow $.isArray = isArray $.isPlainObject = isPlainObject $.isEmptyObject = function(obj) { var name for (name in obj) return false return true } $.isNumeric = function(val) { var num = Number(val), type = typeof val return val != null && type != 'boolean' && (type != 'string' || val.length) && !isNaN(num) && isFinite(num) || false } $.inArray = function(elem, array, i){ return emptyArray.indexOf.call(array, elem, i) } $.camelCase = camelize $.trim = function(str) { return str == null ? "" : String.prototype.trim.call(str) } // plugin compatibility $.uuid = 0 $.support = { } $.expr = { } $.noop = function() {} $.map = function(elements, callback){ var value, values = [], i, key if (likeArray(elements)) for (i = 0; i < elements.length; i++) { value = callback(elements[i], i) if (value != null) values.push(value) } else for (key in elements) { value = callback(elements[key], key) if (value != null) values.push(value) } return flatten(values) } $.each = function(elements, callback){ var i, key if (likeArray(elements)) { for (i = 0; i < elements.length; i++) if (callback.call(elements[i], i, elements[i]) === false) return elements } else { for (key in elements) if (callback.call(elements[key], key, elements[key]) === false) return elements } return elements } $.grep = function(elements, callback){ return filter.call(elements, callback) } if (window.JSON) $.parseJSON = JSON.parse // Populate the class2type map $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase() }) // Define methods that will be available on all // Zepto collections $.fn = { constructor: zepto.Z, length: 0, // Because a collection acts like an array // copy over these useful array functions. forEach: emptyArray.forEach, reduce: emptyArray.reduce, push: emptyArray.push, sort: emptyArray.sort, splice: emptyArray.splice, indexOf: emptyArray.indexOf, concat: function(){ var i, value, args = [] for (i = 0; i < arguments.length; i++) { value = arguments[i] args[i] = zepto.isZ(value) ? value.toArray() : value } return concat.apply(zepto.isZ(this) ? this.toArray() : this, args) }, // `map` and `slice` in the jQuery API work differently // from their array counterparts map: function(fn){ return $($.map(this, function(el, i){ return fn.call(el, i, el) })) }, slice: function(){ return $(slice.apply(this, arguments)) }, ready: function(callback){ // don't use "interactive" on IE <= 10 (it can fired premature) if (document.readyState === "complete" || (document.readyState !== "loading" && !document.documentElement.doScroll)) setTimeout(function(){ callback($) }, 0) else { var handler = function() { document.removeEventListener("DOMContentLoaded", handler, false) window.removeEventListener("load", handler, false) callback($) } document.addEventListener("DOMContentLoaded", handler, false) window.addEventListener("load", handler, false) } return this }, get: function(idx){ return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length] }, toArray: function(){ return this.get() }, size: function(){ return this.length }, remove: function(){ return this.each(function(){ if (this.parentNode != null) this.parentNode.removeChild(this) }) }, each: function(callback){ emptyArray.every.call(this, function(el, idx){ return callback.call(el, idx, el) !== false }) return this }, filter: function(selector){ if (isFunction(selector)) return this.not(this.not(selector)) return $(filter.call(this, function(element){ return zepto.matches(element, selector) })) }, add: function(selector,context){ return $(uniq(this.concat($(selector,context)))) }, is: function(selector){ return this.length > 0 && zepto.matches(this[0], selector) }, not: function(selector){ var nodes=[] if (isFunction(selector) && selector.call !== undefined) this.each(function(idx){ if (!selector.call(this,idx)) nodes.push(this) }) else { var excludes = typeof selector == 'string' ? this.filter(selector) : (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector) this.forEach(function(el){ if (excludes.indexOf(el) < 0) nodes.push(el) }) } return $(nodes) }, has: function(selector){ return this.filter(function(){ return isObject(selector) ? $.contains(this, selector) : $(this).find(selector).size() }) }, eq: function(idx){ return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1) }, first: function(){ var el = this[0] return el && !isObject(el) ? el : $(el) }, last: function(){ var el = this[this.length - 1] return el && !isObject(el) ? el : $(el) }, find: function(selector){ var result, $this = this if (!selector) result = $() else if (typeof selector == 'object') result = $(selector).filter(function(){ var node = this return emptyArray.some.call($this, function(parent){ return $.contains(parent, node) }) }) else if (this.length == 1) result = $(zepto.qsa(this[0], selector)) else result = this.map(function(){ return zepto.qsa(this, selector) }) return result }, closest: function(selector, context){ var nodes = [], collection = typeof selector == 'object' && $(selector) this.each(function(_, node){ while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector))) node = node !== context && !isDocument(node) && node.parentNode if (node && nodes.indexOf(node) < 0) nodes.push(node) }) return $(nodes) }, parents: function(selector){ var ancestors = [], nodes = this while (nodes.length > 0) nodes = $.map(nodes, function(node){ if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) { ancestors.push(node) return node } }) return filtered(ancestors, selector) }, parent: function(selector){ return filtered(uniq(this.pluck('parentNode')), selector) }, children: function(selector){ return filtered(this.map(function(){ return children(this) }), selector) }, contents: function() { return this.map(function() { return this.contentDocument || slice.call(this.childNodes) }) }, siblings: function(selector){ return filtered(this.map(function(i, el){ return filter.call(children(el.parentNode), function(child){ return child!==el }) }), selector) }, empty: function(){ return this.each(function(){ this.innerHTML = '' }) }, // `pluck` is borrowed from Prototype.js pluck: function(property){ return $.map(this, function(el){ return el[property] }) }, show: function(){ return this.each(function(){ this.style.display == "none" && (this.style.display = '') if (getComputedStyle(this, '').getPropertyValue("display") == "none") this.style.display = defaultDisplay(this.nodeName) }) }, replaceWith: function(newContent){ return this.before(newContent).remove() }, wrap: function(structure){ var func = isFunction(structure) if (this[0] && !func) var dom = $(structure).get(0), clone = dom.parentNode || this.length > 1 return this.each(function(index){ $(this).wrapAll( func ? structure.call(this, index) : clone ? dom.cloneNode(true) : dom ) }) }, wrapAll: function(structure){ if (this[0]) { $(this[0]).before(structure = $(structure)) var children // drill down to the inmost element while ((children = structure.children()).length) structure = children.first() $(structure).append(this) } return this }, wrapInner: function(structure){ var func = isFunction(structure) return this.each(function(index){ var self = $(this), contents = self.contents(), dom = func ? structure.call(this, index) : structure contents.length ? contents.wrapAll(dom) : self.append(dom) }) }, unwrap: function(){ this.parent().each(function(){ $(this).replaceWith($(this).children()) }) return this }, clone: function(){ return this.map(function(){ return this.cloneNode(true) }) }, hide: function(){ return this.css("display", "none") }, toggle: function(setting){ return this.each(function(){ var el = $(this) ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide() }) }, prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') }, next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') }, html: function(html){ return 0 in arguments ? this.each(function(idx){ var originHtml = this.innerHTML $(this).empty().append( funcArg(this, html, idx, originHtml) ) }) : (0 in this ? this[0].innerHTML : null) }, text: function(text){ return 0 in arguments ? this.each(function(idx){ var newText = funcArg(this, text, idx, this.textContent) this.textContent = newText == null ? '' : ''+newText }) : (0 in this ? this.pluck('textContent').join("") : null) }, attr: function(name, value){ var result return (typeof name == 'string' && !(1 in arguments)) ? (0 in this && this[0].nodeType == 1 && (result = this[0].getAttribute(name)) != null ? result : undefined) : this.each(function(idx){ if (this.nodeType !== 1) return if (isObject(name)) for (key in name) setAttribute(this, key, name[key]) else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name))) }) }, removeAttr: function(name){ return this.each(function(){ this.nodeType === 1 && name.split(' ').forEach(function(attribute){ setAttribute(this, attribute) }, this)}) }, prop: function(name, value){ name = propMap[name] || name return (1 in arguments) ? this.each(function(idx){ this[name] = funcArg(this, value, idx, this[name]) }) : (this[0] && this[0][name]) }, removeProp: function(name){ name = propMap[name] || name return this.each(function(){ delete this[name] }) }, data: function(name, value){ var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase() var data = (1 in arguments) ? this.attr(attrName, value) : this.attr(attrName) return data !== null ? deserializeValue(data) : undefined }, val: function(value){ if (0 in arguments) { if (value == null) value = "" return this.each(function(idx){ this.value = funcArg(this, value, idx, this.value) }) } else { return this[0] && (this[0].multiple ? $(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') : this[0].value) } }, offset: function(coordinates){ if (coordinates) return this.each(function(index){ var $this = $(this), coords = funcArg(this, coordinates, index, $this.offset()), parentOffset = $this.offsetParent().offset(), props = { top: coords.top - parentOffset.top, left: coords.left - parentOffset.left } if ($this.css('position') == 'static') props['position'] = 'relative' $this.css(props) }) if (!this.length) return null if (document.documentElement !== this[0] && !$.contains(document.documentElement, this[0])) return {top: 0, left: 0} var obj = this[0].getBoundingClientRect() return { left: obj.left + window.pageXOffset, top: obj.top + window.pageYOffset, width: Math.round(obj.width), height: Math.round(obj.height) } }, css: function(property, value){ if (arguments.length < 2) { var element = this[0] if (typeof property == 'string') { if (!element) return return element.style[camelize(property)] || getComputedStyle(element, '').getPropertyValue(property) } else if (isArray(property)) { if (!element) return var props = {} var computedStyle = getComputedStyle(element, '') $.each(property, function(_, prop){ props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop)) }) return props } } var css = '' if (type(property) == 'string') { if (!value && value !== 0) this.each(function(){ this.style.removeProperty(dasherize(property)) }) else css = dasherize(property) + ":" + maybeAddPx(property, value) } else { for (key in property) if (!property[key] && property[key] !== 0) this.each(function(){ this.style.removeProperty(dasherize(key)) }) else css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';' } return this.each(function(){ this.style.cssText += ';' + css }) }, index: function(element){ return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0]) }, hasClass: function(name){ if (!name) return false return emptyArray.some.call(this, function(el){ return this.test(className(el)) }, classRE(name)) }, addClass: function(name){ if (!name) return this return this.each(function(idx){ if (!('className' in this)) return classList = [] var cls = className(this), newName = funcArg(this, name, idx, cls) newName.split(/\s+/g).forEach(function(klass){ if (!$(this).hasClass(klass)) classList.push(klass) }, this) classList.length && className(this, cls + (cls ? " " : "") + classList.join(" ")) }) }, removeClass: function(name){ return this.each(function(idx){ if (!('className' in this)) return if (name === undefined) return className(this, '') classList = className(this) funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){ classList = classList.replace(classRE(klass), " ") }) className(this, classList.trim()) }) }, toggleClass: function(name, when){ if (!name) return this return this.each(function(idx){ var $this = $(this), names = funcArg(this, name, idx, className(this)) names.split(/\s+/g).forEach(function(klass){ (when === undefined ? !$this.hasClass(klass) : when) ? $this.addClass(klass) : $this.removeClass(klass) }) }) }, scrollTop: function(value){ if (!this.length) return var hasScrollTop = 'scrollTop' in this[0] if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset return this.each(hasScrollTop ? function(){ this.scrollTop = value } : function(){ this.scrollTo(this.scrollX, value) }) }, scrollLeft: function(value){ if (!this.length) return var hasScrollLeft = 'scrollLeft' in this[0] if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset return this.each(hasScrollLeft ? function(){ this.scrollLeft = value } : function(){ this.scrollTo(value, this.scrollY) }) }, position: function() { if (!this.length) return var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset() // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( $(elem).css('margin-top') ) || 0 offset.left -= parseFloat( $(elem).css('margin-left') ) || 0 // Add offsetParent borders parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0 parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0 // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left } }, offsetParent: function() { return this.map(function(){ var parent = this.offsetParent || document.body while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static") parent = parent.offsetParent return parent }) } } // for now $.fn.detach = $.fn.remove // Generate the `width` and `height` functions ;['width', 'height'].forEach(function(dimension){ var dimensionProperty = dimension.replace(/./, function(m){ return m[0].toUpperCase() }) $.fn[dimension] = function(value){ var offset, el = this[0] if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] : isDocument(el) ? el.documentElement['scroll' + dimensionProperty] : (offset = this.offset()) && offset[dimension] else return this.each(function(idx){ el = $(this) el.css(dimension, funcArg(this, value, idx, el[dimension]())) }) } }) function traverseNode(node, fun) { fun(node) for (var i = 0, len = node.childNodes.length; i < len; i++) traverseNode(node.childNodes[i], fun) } // Generate the `after`, `prepend`, `before`, `append`, // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods. adjacencyOperators.forEach(function(operator, operatorIndex) { var inside = operatorIndex % 2 //=> prepend, append $.fn[operator] = function(){ // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings var argType, nodes = $.map(arguments, function(arg) { var arr = [] argType = type(arg) if (argType == "array") { arg.forEach(function(el) { if (el.nodeType !== undefined) return arr.push(el) else if ($.zepto.isZ(el)) return arr = arr.concat(el.get()) arr = arr.concat(zepto.fragment(el)) }) return arr } return argType == "object" || arg == null ? arg : zepto.fragment(arg) }), parent, copyByClone = this.length > 1 if (nodes.length < 1) return this return this.each(function(_, target){ parent = inside ? target : target.parentNode // convert all methods to a "before" operation target = operatorIndex == 0 ? target.nextSibling : operatorIndex == 1 ? target.firstChild : operatorIndex == 2 ? target : null var parentInDocument = $.contains(document.documentElement, parent) nodes.forEach(function(node){ if (copyByClone) node = node.cloneNode(true) else if (!parent) return $(node).remove() parent.insertBefore(node, target) if (parentInDocument) traverseNode(node, function(el){ if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' && (!el.type || el.type === 'text/javascript') && !el.src){ var target = el.ownerDocument ? el.ownerDocument.defaultView : window target['eval'].call(target, el.innerHTML) } }) }) }) } // after => insertAfter // prepend => prependTo // before => insertBefore // append => appendTo $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){ $(html)[operator](this) return this } }) zepto.Z.prototype = Z.prototype = $.fn // Export internal API functions in the `$.zepto` namespace zepto.uniq = uniq zepto.deserializeValue = deserializeValue $.zepto = zepto return $ })() window.Zepto = Zepto window.$ === undefined && (window.$ = Zepto) ;(function($){ var _zid = 1, undefined, slice = Array.prototype.slice, isFunction = $.isFunction, isString = function(obj){ return typeof obj == 'string' }, handlers = {}, specialEvents={}, focusinSupported = 'onfocusin' in window, focus = { focus: 'focusin', blur: 'focusout' }, hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' } specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents' function zid(element) { return element._zid || (element._zid = _zid++) } function findHandlers(element, event, fn, selector) { event = parse(event) if (event.ns) var matcher = matcherFor(event.ns) return (handlers[zid(element)] || []).filter(function(handler) { return handler && (!event.e || handler.e == event.e) && (!event.ns || matcher.test(handler.ns)) && (!fn || zid(handler.fn) === zid(fn)) && (!selector || handler.sel == selector) }) } function parse(event) { var parts = ('' + event).split('.') return {e: parts[0], ns: parts.slice(1).sort().join(' ')} } function matcherFor(ns) { return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)') } function eventCapture(handler, captureSetting) { return handler.del && (!focusinSupported && (handler.e in focus)) || !!captureSetting } function realEvent(type) { return hover[type] || (focusinSupported && focus[type]) || type } function add(element, events, fn, data, selector, delegator, capture){ var id = zid(element), set = (handlers[id] || (handlers[id] = [])) events.split(/\s/).forEach(function(event){ if (event == 'ready') return $(document).ready(fn) var handler = parse(event) handler.fn = fn handler.sel = selector // emulate mouseenter, mouseleave if (handler.e in hover) fn = function(e){ var related = e.relatedTarget if (!related || (related !== this && !$.contains(this, related))) return handler.fn.apply(this, arguments) } handler.del = delegator var callback = delegator || fn handler.proxy = function(e){ e = compatible(e) if (e.isImmediatePropagationStopped()) return e.data = data var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args)) if (result === false) e.preventDefault(), e.stopPropagation() return result } handler.i = set.length set.push(handler) if ('addEventListener' in element) element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture)) }) } function remove(element, events, fn, selector, capture){ var id = zid(element) ;(events || '').split(/\s/).forEach(function(event){ findHandlers(element, event, fn, selector).forEach(function(handler){ delete handlers[id][handler.i] if ('removeEventListener' in element) element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture)) }) }) } $.event = { add: add, remove: remove } $.proxy = function(fn, context) { var args = (2 in arguments) && slice.call(arguments, 2) if (isFunction(fn)) { var proxyFn = function(){ return fn.apply(context, args ? args.concat(slice.call(arguments)) : arguments) } proxyFn._zid = zid(fn) return proxyFn } else if (isString(context)) { if (args) { args.unshift(fn[context], fn) return $.proxy.apply(null, args) } else { return $.proxy(fn[context], fn) } } else { throw new TypeError("expected function") } } $.fn.bind = function(event, data, callback){ return this.on(event, data, callback) } $.fn.unbind = function(event, callback){ return this.off(event, callback) } $.fn.one = function(event, selector, data, callback){ return this.on(event, selector, data, callback, 1) } var returnTrue = function(){return true}, returnFalse = function(){return false}, ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$|webkitMovement[XY]$)/, eventMethods = { preventDefault: 'isDefaultPrevented', stopImmediatePropagation: 'isImmediatePropagationStopped', stopPropagation: 'isPropagationStopped' } function compatible(event, source) { if (source || !event.isDefaultPrevented) { source || (source = event) $.each(eventMethods, function(name, predicate) { var sourceMethod = source[name] event[name] = function(){ this[predicate] = returnTrue return sourceMethod && sourceMethod.apply(source, arguments) } event[predicate] = returnFalse }) try { event.timeStamp || (event.timeStamp = Date.now()) } catch (ignored) { } if (source.defaultPrevented !== undefined ? source.defaultPrevented : 'returnValue' in source ? source.returnValue === false : source.getPreventDefault && source.getPreventDefault()) event.isDefaultPrevented = returnTrue } return event } function createProxy(event) { var key, proxy = { originalEvent: event } for (key in event) if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key] return compatible(proxy, event) } $.fn.delegate = function(selector, event, callback){ return this.on(event, selector, callback) } $.fn.undelegate = function(selector, event, callback){ return this.off(event, selector, callback) } $.fn.live = function(event, callback){ $(document.body).delegate(this.selector, event, callback) return this } $.fn.die = function(event, callback){ $(document.body).undelegate(this.selector, event, callback) return this } $.fn.on = function(event, selector, data, callback, one){ var autoRemove, delegator, $this = this if (event && !isString(event)) { $.each(event, function(type, fn){ $this.on(type, selector, data, fn, one) }) return $this } if (!isString(selector) && !isFunction(callback) && callback !== false) callback = data, data = selector, selector = undefined if (callback === undefined || data === false) callback = data, data = undefined if (callback === false) callback = returnFalse return $this.each(function(_, element){ if (one) autoRemove = function(e){ remove(element, e.type, callback) return callback.apply(this, arguments) } if (selector) delegator = function(e){ var evt, match = $(e.target).closest(selector, element).get(0) if (match && match !== element) { evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element}) return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1))) } } add(element, event, callback, data, selector, delegator || autoRemove) }) } $.fn.off = function(event, selector, callback){ var $this = this if (event && !isString(event)) { $.each(event, function(type, fn){ $this.off(type, selector, fn) }) return $this } if (!isString(selector) && !isFunction(callback) && callback !== false) callback = selector, selector = undefined if (callback === false) callback = returnFalse return $this.each(function(){ remove(this, event, callback, selector) }) } $.fn.trigger = function(event, args){ event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event) event._args = args return this.each(function(){ // handle focus(), blur() by calling them directly if (event.type in focus && typeof this[event.type] == "function") this[event.type]() // items in the collection might not be DOM elements else if ('dispatchEvent' in this) this.dispatchEvent(event) else $(this).triggerHandler(event, args) }) } // triggers event handlers on current element just as if an event occurred, // doesn't trigger an actual event, doesn't bubble $.fn.triggerHandler = function(event, args){ var e, result this.each(function(i, element){ e = createProxy(isString(event) ? $.Event(event) : event) e._args = args e.target = element $.each(findHandlers(element, event.type || event), function(i, handler){ result = handler.proxy(e) if (e.isImmediatePropagationStopped()) return false }) }) return result } // shortcut methods for `.bind(event, fn)` for each event type ;('focusin focusout focus blur load resize scroll unload click dblclick '+ 'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+ 'change select keydown keypress keyup error').split(' ').forEach(function(event) { $.fn[event] = function(callback) { return (0 in arguments) ? this.bind(event, callback) : this.trigger(event) } }) $.Event = function(type, props) { if (!isString(type)) props = type, type = props.type var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name]) event.initEvent(type, bubbles, true) return compatible(event) } })(Zepto) ;(function($){ var jsonpID = +new Date(), document = window.document, key, name, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, scriptTypeRE = /^(?:text|application)\/javascript/i, xmlTypeRE = /^(?:text|application)\/xml/i, jsonType = 'application/json', htmlType = 'text/html', blankRE = /^\s*$/, originAnchor = document.createElement('a') originAnchor.href = window.location.href // trigger a custom event and return false if it was cancelled function triggerAndReturn(context, eventName, data) { var event = $.Event(eventName) $(context).trigger(event, data) return !event.isDefaultPrevented() } // trigger an Ajax "global" event function triggerGlobal(settings, context, eventName, data) { if (settings.global) return triggerAndReturn(context || document, eventName, data) } // Number of active Ajax requests $.active = 0 function ajaxStart(settings) { if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart') } function ajaxStop(settings) { if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop') } // triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable function ajaxBeforeSend(xhr, settings) { var context = settings.context if (settings.beforeSend.call(context, xhr, settings) === false || triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false) return false triggerGlobal(settings, context, 'ajaxSend', [xhr, settings]) } function ajaxSuccess(data, xhr, settings, deferred) { var context = settings.context, status = 'success' settings.success.call(context, data, status, xhr) if (deferred) deferred.resolveWith(context, [data, status, xhr]) triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data]) ajaxComplete(status, xhr, settings) } // type: "timeout", "error", "abort", "parsererror" function ajaxError(error, type, xhr, settings, deferred) { var context = settings.context settings.error.call(context, xhr, type, error) if (deferred) deferred.rejectWith(context, [xhr, type, error]) triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type]) ajaxComplete(type, xhr, settings) } // status: "success", "notmodified", "error", "timeout", "abort", "parsererror" function ajaxComplete(status, xhr, settings) { var context = settings.context settings.complete.call(context, xhr, status) triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings]) ajaxStop(settings) } function ajaxDataFilter(data, type, settings) { if (settings.dataFilter == empty) return data var context = settings.context return settings.dataFilter.call(context, data, type) } // Empty function, used as default callback function empty() {} $.ajaxJSONP = function(options, deferred){ if (!('type' in options)) return $.ajax(options) var _callbackName = options.jsonpCallback, callbackName = ($.isFunction(_callbackName) ? _callbackName() : _callbackName) || ('Zepto' + (jsonpID++)), script = document.createElement('script'), originalCallback = window[callbackName], responseData, abort = function(errorType) { $(script).triggerHandler('error', errorType || 'abort') }, xhr = { abort: abort }, abortTimeout if (deferred) deferred.promise(xhr) $(script).on('load error', function(e, errorType){ clearTimeout(abortTimeout) $(script).off().remove() if (e.type == 'error' || !responseData) { ajaxError(null, errorType || 'error', xhr, options, deferred) } else { ajaxSuccess(responseData[0], xhr, options, deferred) } window[callbackName] = originalCallback if (responseData && $.isFunction(originalCallback)) originalCallback(responseData[0]) originalCallback = responseData = undefined }) if (ajaxBeforeSend(xhr, options) === false) { abort('abort') return xhr } window[callbackName] = function(){ responseData = arguments } script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName) document.head.appendChild(script) if (options.timeout > 0) abortTimeout = setTimeout(function(){ abort('timeout') }, options.timeout) return xhr } $.ajaxSettings = { // Default type of request type: 'GET', // Callback that is executed before request beforeSend: empty, // Callback that is executed if the request succeeds success: empty, // Callback that is executed the the server drops error error: empty, // Callback that is executed on request complete (both: error and success) complete: empty, // The context for the callbacks context: null, // Whether to trigger "global" Ajax events global: true, // Transport xhr: function () { return new window.XMLHttpRequest() }, // MIME types mapping // IIS returns Javascript as "application/x-javascript" accepts: { script: 'text/javascript, application/javascript, application/x-javascript', json: jsonType, xml: 'application/xml, text/xml', html: htmlType, text: 'text/plain' }, // Whether the request is to another domain crossDomain: false, // Default timeout timeout: 0, // Whether data should be serialized to string processData: true, // Whether the browser should be allowed to cache GET responses cache: true, //Used to handle the raw response data of XMLHttpRequest. //This is a pre-filtering function to sanitize the response. //The sanitized response should be returned dataFilter: empty } function mimeToDataType(mime) { if (mime) mime = mime.split(';', 2)[0] return mime && ( mime == htmlType ? 'html' : mime == jsonType ? 'json' : scriptTypeRE.test(mime) ? 'script' : xmlTypeRE.test(mime) && 'xml' ) || 'text' } function appendQuery(url, query) { if (query == '') return url return (url + '&' + query).replace(/[&?]{1,2}/, '?') } // serialize payload and append it to the URL for GET requests function serializeData(options) { if (options.processData && options.data && $.type(options.data) != "string") options.data = $.param(options.data, options.traditional) if (options.data && (!options.type || options.type.toUpperCase() == 'GET' || 'jsonp' == options.dataType)) options.url = appendQuery(options.url, options.data), options.data = undefined } $.ajax = function(options){ var settings = $.extend({}, options || {}), deferred = $.Deferred && $.Deferred(), urlAnchor, hashIndex for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key] ajaxStart(settings) if (!settings.crossDomain) { urlAnchor = document.createElement('a') urlAnchor.href = settings.url // cleans up URL for .href (IE only), see https://github.com/madrobby/zepto/pull/1049 urlAnchor.href = urlAnchor.href settings.crossDomain = (originAnchor.protocol + '//' + originAnchor.host) !== (urlAnchor.protocol + '//' + urlAnchor.host) } if (!settings.url) settings.url = window.location.toString() if ((hashIndex = settings.url.indexOf('#')) > -1) settings.url = settings.url.slice(0, hashIndex) serializeData(settings) var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url) if (hasPlaceholder) dataType = 'jsonp' if (settings.cache === false || ( (!options || options.cache !== true) && ('script' == dataType || 'jsonp' == dataType) )) settings.url = appendQuery(settings.url, '_=' + Date.now()) if ('jsonp' == dataType) { if (!hasPlaceholder) settings.url = appendQuery(settings.url, settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?') return $.ajaxJSONP(settings, deferred) } var mime = settings.accepts[dataType], headers = { }, setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] }, protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol, xhr = settings.xhr(), nativeSetHeader = xhr.setRequestHeader, abortTimeout if (deferred) deferred.promise(xhr) if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest') setHeader('Accept', mime || '*/*') if (mime = settings.mimeType || mime) { if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0] xhr.overrideMimeType && xhr.overrideMimeType(mime) } if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET')) setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded') if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name]) xhr.setRequestHeader = setHeader xhr.onreadystatechange = function(){ if (xhr.readyState == 4) { xhr.onreadystatechange = empty clearTimeout(abortTimeout) var result, error = false if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) { dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type')) if (xhr.responseType == 'arraybuffer' || xhr.responseType == 'blob') result = xhr.response else { result = xhr.responseText try { // http://perfectionkills.com/global-eval-what-are-the-options/ // sanitize response accordingly if data filter callback provided result = ajaxDataFilter(result, dataType, settings) if (dataType == 'script') (1,eval)(result) else if (dataType == 'xml') result = xhr.responseXML else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result) } catch (e) { error = e } if (error) return ajaxError(error, 'parsererror', xhr, settings, deferred) } ajaxSuccess(result, xhr, settings, deferred) } else { ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred) } } } if (ajaxBeforeSend(xhr, settings) === false) { xhr.abort() ajaxError(null, 'abort', xhr, settings, deferred) return xhr } var async = 'async' in settings ? settings.async : true xhr.open(settings.type, settings.url, async, settings.username, settings.password) if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name] for (name in headers) nativeSetHeader.apply(xhr, headers[name]) if (settings.timeout > 0) abortTimeout = setTimeout(function(){ xhr.onreadystatechange = empty xhr.abort() ajaxError(null, 'timeout', xhr, settings, deferred) }, settings.timeout) // avoid sending empty string (#319) xhr.send(settings.data ? settings.data : null) return xhr } // handle optional data/success arguments function parseArguments(url, data, success, dataType) { if ($.isFunction(data)) dataType = success, success = data, data = undefined if (!$.isFunction(success)) dataType = success, success = undefined return { url: url , data: data , success: success , dataType: dataType } } $.get = function(/* url, data, success, dataType */){ return $.ajax(parseArguments.apply(null, arguments)) } $.post = function(/* url, data, success, dataType */){ var options = parseArguments.apply(null, arguments) options.type = 'POST' return $.ajax(options) } $.getJSON = function(/* url, data, success */){ var options = parseArguments.apply(null, arguments) options.dataType = 'json' return $.ajax(options) } $.fn.load = function(url, data, success){ if (!this.length) return this var self = this, parts = url.split(/\s/), selector, options = parseArguments(url, data, success), callback = options.success if (parts.length > 1) options.url = parts[0], selector = parts[1] options.success = function(response){ self.html(selector ? $('<div>').html(response.replace(rscript, "")).find(selector) : response) callback && callback.apply(self, arguments) } $.ajax(options) return this } var escape = encodeURIComponent function serialize(params, obj, traditional, scope){ var type, array = $.isArray(obj), hash = $.isPlainObject(obj) $.each(obj, function(key, value) { type = $.type(value) if (scope) key = traditional ? scope : scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']' // handle data in serializeArray() format if (!scope && array) params.add(value.name, value.value) // recurse into nested objects else if (type == "array" || (!traditional && type == "object")) serialize(params, value, traditional, key) else params.add(key, value) }) } $.param = function(obj, traditional){ var params = [] params.add = function(key, value) { if ($.isFunction(value)) value = value() if (value == null) value = "" this.push(escape(key) + '=' + escape(value)) } serialize(params, obj, traditional) return params.join('&').replace(/%20/g, '+') } })(Zepto) ;(function($){ $.fn.serializeArray = function() { var name, type, result = [], add = function(value) { if (value.forEach) return value.forEach(add) result.push({ name: name, value: value }) } if (this[0]) $.each(this[0].elements, function(_, field){ type = field.type, name = field.name if (name && field.nodeName.toLowerCase() != 'fieldset' && !field.disabled && type != 'submit' && type != 'reset' && type != 'button' && type != 'file' && ((type != 'radio' && type != 'checkbox') || field.checked)) add($(field).val()) }) return result } $.fn.serialize = function(){ var result = [] this.serializeArray().forEach(function(elm){ result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value)) }) return result.join('&') } $.fn.submit = function(callback) { if (0 in arguments) this.bind('submit', callback) else if (this.length) { var event = $.Event('submit') this.eq(0).trigger(event) if (!event.isDefaultPrevented()) this.get(0).submit() } return this } })(Zepto) ;(function(){ // getComputedStyle shouldn't freak out when called // without a valid element as argument try { getComputedStyle(undefined) } catch(e) { var nativeGetComputedStyle = getComputedStyle window.getComputedStyle = function(element, pseudoElement){ try { return nativeGetComputedStyle(element, pseudoElement) } catch(e) { return null } } } })() ;(function($, undefined){ var prefix = '', eventPrefix, vendors = { Webkit: 'webkit', Moz: '', O: 'o' }, testEl = document.createElement('div'), supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i, transform, transitionProperty, transitionDuration, transitionTiming, transitionDelay, animationName, animationDuration, animationTiming, animationDelay, cssReset = {} function dasherize(str) { return str.replace(/([A-Z])/g, '-$1').toLowerCase() } function normalizeEvent(name) { return eventPrefix ? eventPrefix + name : name.toLowerCase() } if (testEl.style.transform === undefined) $.each(vendors, function(vendor, event){ if (testEl.style[vendor + 'TransitionProperty'] !== undefined) { prefix = '-' + vendor.toLowerCase() + '-' eventPrefix = event return false } }) transform = prefix + 'transform' cssReset[transitionProperty = prefix + 'transition-property'] = cssReset[transitionDuration = prefix + 'transition-duration'] = cssReset[transitionDelay = prefix + 'transition-delay'] = cssReset[transitionTiming = prefix + 'transition-timing-function'] = cssReset[animationName = prefix + 'animation-name'] = cssReset[animationDuration = prefix + 'animation-duration'] = cssReset[animationDelay = prefix + 'animation-delay'] = cssReset[animationTiming = prefix + 'animation-timing-function'] = '' $.fx = { off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined), speeds: { _default: 400, fast: 200, slow: 600 }, cssPrefix: prefix, transitionEnd: normalizeEvent('TransitionEnd'), animationEnd: normalizeEvent('AnimationEnd') } $.fn.animate = function(properties, duration, ease, callback, delay){ if ($.isFunction(duration)) callback = duration, ease = undefined, duration = undefined if ($.isFunction(ease)) callback = ease, ease = undefined if ($.isPlainObject(duration)) ease = duration.easing, callback = duration.complete, delay = duration.delay, duration = duration.duration if (duration) duration = (typeof duration == 'number' ? duration : ($.fx.speeds[duration] || $.fx.speeds._default)) / 1000 if (delay) delay = parseFloat(delay) / 1000 return this.anim(properties, duration, ease, callback, delay) } $.fn.anim = function(properties, duration, ease, callback, delay){ var key, cssValues = {}, cssProperties, transforms = '', that = this, wrappedCallback, endEvent = $.fx.transitionEnd, fired = false if (duration === undefined) duration = $.fx.speeds._default / 1000 if (delay === undefined) delay = 0 if ($.fx.off) duration = 0 if (typeof properties == 'string') { // keyframe animation cssValues[animationName] = properties cssValues[animationDuration] = duration + 's' cssValues[animationDelay] = delay + 's' cssValues[animationTiming] = (ease || 'linear') endEvent = $.fx.animationEnd } else { cssProperties = [] // CSS transitions for (key in properties) if (supportedTransforms.test(key)) transforms += key + '(' + properties[key] + ') ' else cssValues[key] = properties[key], cssProperties.push(dasherize(key)) if (transforms) cssValues[transform] = transforms, cssProperties.push(transform) if (duration > 0 && typeof properties === 'object') { cssValues[transitionProperty] = cssProperties.join(', ') cssValues[transitionDuration] = duration + 's' cssValues[transitionDelay] = delay + 's' cssValues[transitionTiming] = (ease || 'linear') } } wrappedCallback = function(event){ if (typeof event !== 'undefined') { if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below" $(event.target).unbind(endEvent, wrappedCallback) } else $(this).unbind(endEvent, wrappedCallback) // triggered by setTimeout fired = true $(this).css(cssReset) callback && callback.call(this) } if (duration > 0){ this.bind(endEvent, wrappedCallback) // transitionEnd is not always firing on older Android phones // so make sure it gets fired setTimeout(function(){ if (fired) return wrappedCallback.call(that) }, ((duration + delay) * 1000) + 25) } // trigger page reflow so new elements can animate this.size() && this.get(0).clientLeft this.css(cssValues) if (duration <= 0) setTimeout(function() { that.each(function(){ wrappedCallback.call(this) }) }, 0) return this } testEl = null })(Zepto) ;(function($){ var zepto = $.zepto, oldQsa = zepto.qsa, oldMatches = zepto.matches function visible(elem){ elem = $(elem) return !!(elem.width() || elem.height()) && elem.css("display") !== "none" } // Implements a subset from: // http://api.jquery.com/category/selectors/jquery-selector-extensions/ // // Each filter function receives the current index, all nodes in the // considered set, and a value if there were parentheses. The value // of `this` is the node currently being considered. The function returns the // resulting node(s), null, or undefined. // // Complex selectors are not supported: // li:has(label:contains("foo")) + li:has(label:contains("bar")) // ul.inner:first > li var filters = $.expr[':'] = { visible: function(){ if (visible(this)) return this }, hidden: function(){ if (!visible(this)) return this }, selected: function(){ if (this.selected) return this }, checked: function(){ if (this.checked) return this }, parent: function(){ return this.parentNode }, first: function(idx){ if (idx === 0) return this }, last: function(idx, nodes){ if (idx === nodes.length - 1) return this }, eq: function(idx, _, value){ if (idx === value) return this }, contains: function(idx, _, text){ if ($(this).text().indexOf(text) > -1) return this }, has: function(idx, _, sel){ if (zepto.qsa(this, sel).length) return this } } var filterRe = new RegExp('(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*'), childRe = /^\s*>/, classTag = 'Zepto' + (+new Date()) function process(sel, fn) { // quote the hash in `a[href^=#]` expression sel = sel.replace(/=#\]/g, '="#"]') var filter, arg, match = filterRe.exec(sel) if (match && match[2] in filters) { filter = filters[match[2]], arg = match[3] sel = match[1] if (arg) { var num = Number(arg) if (isNaN(num)) arg = arg.replace(/^["']|["']$/g, '') else arg = num } } return fn(sel, filter, arg) } zepto.qsa = function(node, selector) { return process(selector, function(sel, filter, arg){ try { var taggedParent if (!sel && filter) sel = '*' else if (childRe.test(sel)) // support "> *" child queries by tagging the parent node with a // unique class and prepending that classname onto the selector taggedParent = $(node).addClass(classTag), sel = '.'+classTag+' '+sel var nodes = oldQsa(node, sel) } catch(e) { console.error('error performing selector: %o', selector) throw e } finally { if (taggedParent) taggedParent.removeClass(classTag) } return !filter ? nodes : zepto.uniq($.map(nodes, function(n, i){ return filter.call(n, i, nodes, arg) })) }) } zepto.matches = function(node, selector){ return process(selector, function(sel, filter, arg){ return (!sel || oldMatches(node, sel)) && (!filter || filter.call(node, null, arg) === node) }) } })(Zepto) ;(function($){ var touch = {}, touchTimeout, tapTimeout, swipeTimeout, longTapTimeout, longTapDelay = 750, gesture function swipeDirection(x1, x2, y1, y2) { return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down') } function longTap() { longTapTimeout = null if (touch.last) { touch.el.trigger('longTap') touch = {} } } function cancelLongTap() { if (longTapTimeout) clearTimeout(longTapTimeout) longTapTimeout = null } function cancelAll() { if (touchTimeout) clearTimeout(touchTimeout) if (tapTimeout) clearTimeout(tapTimeout) if (swipeTimeout) clearTimeout(swipeTimeout) if (longTapTimeout) clearTimeout(longTapTimeout) touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null touch = {} } function isPrimaryTouch(event){ return (event.pointerType == 'touch' || event.pointerType == event.MSPOINTER_TYPE_TOUCH) && event.isPrimary } function isPointerEventType(e, type){ return (e.type == 'pointer'+type || e.type.toLowerCase() == 'mspointer'+type) } $(document).ready(function(){ var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType if ('MSGesture' in window) { gesture = new MSGesture() gesture.target = document.body } $(document) .bind('MSGestureEnd', function(e){ var swipeDirectionFromVelocity = e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null if (swipeDirectionFromVelocity) { touch.el.trigger('swipe') touch.el.trigger('swipe'+ swipeDirectionFromVelocity) } }) .on('touchstart MSPointerDown pointerdown', function(e){ if((_isPointerType = isPointerEventType(e, 'down')) && !isPrimaryTouch(e)) return firstTouch = _isPointerType ? e : e.touches[0] if (e.touches && e.touches.length === 1 && touch.x2) { // Clear out touch movement data if we have it sticking around // This can occur if touchcancel doesn't fire due to preventDefault, etc. touch.x2 = undefined touch.y2 = undefined } now = Date.now() delta = now - (touch.last || now) touch.el = $('tagName' in firstTouch.target ? firstTouch.target : firstTouch.target.parentNode) touchTimeout && clearTimeout(touchTimeout) touch.x1 = firstTouch.pageX touch.y1 = firstTouch.pageY if (delta > 0 && delta <= 250) touch.isDoubleTap = true touch.last = now longTapTimeout = setTimeout(longTap, longTapDelay) // adds the current touch contact for IE gesture recognition if (gesture && _isPointerType) gesture.addPointer(e.pointerId) }) .on('touchmove MSPointerMove pointermove', function(e){ if((_isPointerType = isPointerEventType(e, 'move')) && !isPrimaryTouch(e)) return firstTouch = _isPointerType ? e : e.touches[0] cancelLongTap() touch.x2 = firstTouch.pageX touch.y2 = firstTouch.pageY deltaX += Math.abs(touch.x1 - touch.x2) deltaY += Math.abs(touch.y1 - touch.y2) }) .on('touchend MSPointerUp pointerup', function(e){ if((_isPointerType = isPointerEventType(e, 'up')) && !isPrimaryTouch(e)) return cancelLongTap() // swipe if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) || (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30)) swipeTimeout = setTimeout(function() { if (touch.el){ touch.el.trigger('swipe') touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2))) } touch = {} }, 0) // normal tap else if ('last' in touch) // don't fire tap when delta position changed by more than 30 pixels, // for instance when moving to a point and back to origin if (deltaX < 30 && deltaY < 30) { // delay by one tick so we can cancel the 'tap' event if 'scroll' fires // ('tap' fires before 'scroll') tapTimeout = setTimeout(function() { // trigger universal 'tap' with the option to cancelTouch() // (cancelTouch cancels processing of single vs double taps for faster 'tap' response) var event = $.Event('tap') event.cancelTouch = cancelAll // [by paper] fix -> "TypeError: 'undefined' is not an object (evaluating 'touch.el.trigger'), when double tap if (touch.el) touch.el.trigger(event) // trigger double tap immediately if (touch.isDoubleTap) { if (touch.el) touch.el.trigger('doubleTap') touch = {} } // trigger single tap after 250ms of inactivity else { touchTimeout = setTimeout(function(){ touchTimeout = null if (touch.el) touch.el.trigger('singleTap') touch = {} }, 250) } }, 0) } else { touch = {} } deltaX = deltaY = 0 }) // when the browser window loses focus, // for example when a modal dialog is shown, // cancel all ongoing events .on('touchcancel MSPointerCancel pointercancel', cancelAll) // scrolling the window indicates intention of the user // to scroll, not tap or swipe, so cancel all ongoing events $(window).on('scroll', cancelAll) }) ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){ $.fn[eventName] = function(callback){ return this.on(eventName, callback) } }) })(Zepto) return Zepto }))
Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/zepto-master/dist/zepto.js/0
{ "file_path": "Daotin/Web/07-移动Web开发/案例源码/02-仿JD移动端/zepto-master/dist/zepto.js", "repo_id": "Daotin", "token_count": 28786 }
12
// Icon Sizes // ------------------------- /* makes the font 33% larger relative to the icon container */ .#{$fa-css-prefix}-lg { font-size: (4em / 3); line-height: (3em / 4); vertical-align: -15%; } .#{$fa-css-prefix}-2x { font-size: 2em; } .#{$fa-css-prefix}-3x { font-size: 3em; } .#{$fa-css-prefix}-4x { font-size: 4em; } .#{$fa-css-prefix}-5x { font-size: 5em; }
Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_larger.scss/0
{ "file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_larger.scss", "repo_id": "Daotin", "token_count": 162 }
13
## sea.js简单使用教程 1. 下载sea.js, 并引入 * 官网: http://seajs.org/ * github : https://github.com/seajs/seajs * 将sea.js导入项目: js/libs/sea.js 2. 创建项目结构 ``` |-js |-libs |-sea.js |-modules |-module1.js |-module2.js |-module3.js |-module4.js |-main.js |-index.html ``` 3. 定义sea.js的模块代码 * module1.js ``` define(function (require, exports, module) { //内部变量数据 var data = 'atguigu.com' //内部函数 function show() { console.log('module1 show() ' + data) } //向外暴露 exports.show = show }) ``` * module2.js ``` define(function (require, exports, module) { module.exports = { msg: 'I Will Back' } }) ``` * module3.js ``` define(function (require, exports, module) { const API_KEY = 'abc123' exports.API_KEY = API_KEY }) ``` * module4.js ``` define(function (require, exports, module) { //引入依赖模块(同步) var module2 = require('./module2') function show() { console.log('module4 show() ' + module2.msg) } exports.show = show //引入依赖模块(异步) require.async('./module3', function (m3) { console.log('异步引入依赖模块3 ' + m3.API_KEY) }) }) ``` * main.js : 主(入口)模块 ``` define(function (require) { var m1 = require('./module1') var m4 = require('./module4') m1.show() m4.show() }) ``` 4. index.html: ``` <!-- 使用seajs: 1. 引入sea.js库 2. 如何定义导出模块 : define() exports module.exports 3. 如何依赖模块: require() 4. 如何使用模块: seajs.use() --> <script type="text/javascript" src="js/libs/sea.js"></script> <script type="text/javascript"> seajs.use('./js/modules/main') </script> ```
Daotin/Web/09-模块化规范/06-CMD-SeaJS模块化教程.md/0
{ "file_path": "Daotin/Web/09-模块化规范/06-CMD-SeaJS模块化教程.md", "repo_id": "Daotin", "token_count": 1145 }
14
- [一、Vue组件](#%E4%B8%80vue%E7%BB%84%E4%BB%B6) - [二、定义组件](#%E4%BA%8C%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6) * [1、定义全局组件](#1%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E7%BB%84%E4%BB%B6) * [2、定义局部组件](#2%E5%AE%9A%E4%B9%89%E5%B1%80%E9%83%A8%E7%BB%84%E4%BB%B6) - [三、动态组件](#%E4%B8%89%E5%8A%A8%E6%80%81%E7%BB%84%E4%BB%B6) - [四、组件间传值](#%E5%9B%9B%E7%BB%84%E4%BB%B6%E9%97%B4%E4%BC%A0%E5%80%BC) * [1、父组件向子组件传值](#1%E7%88%B6%E7%BB%84%E4%BB%B6%E5%90%91%E5%AD%90%E7%BB%84%E4%BB%B6%E4%BC%A0%E5%80%BC) + [1.1、props类型验证](#11props%E7%B1%BB%E5%9E%8B%E9%AA%8C%E8%AF%81) + [1.2、props必填验证](#12props%E5%BF%85%E5%A1%AB%E9%AA%8C%E8%AF%81) + [1.3、props默认值](#13props%E9%BB%98%E8%AE%A4%E5%80%BC) + [1.4、props自定义匹配规则](#14props%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8C%B9%E9%85%8D%E8%A7%84%E5%88%99) + [1.5、prop 是单项数据流](#15prop-%E6%98%AF%E5%8D%95%E9%A1%B9%E6%95%B0%E6%8D%AE%E6%B5%81) * [非 Prop 的特性](#%E9%9D%9E-prop-%E7%9A%84%E7%89%B9%E6%80%A7) * [2、子组件向父组件传值](#2%E5%AD%90%E7%BB%84%E4%BB%B6%E5%90%91%E7%88%B6%E7%BB%84%E4%BB%B6%E4%BC%A0%E5%80%BC) * [3、子组件之间相互传值](#3%E5%AD%90%E7%BB%84%E4%BB%B6%E4%B9%8B%E9%97%B4%E7%9B%B8%E4%BA%92%E4%BC%A0%E5%80%BC) + [3.1、Tips](#31tips) - [三、组件切换](#%E4%B8%89%E7%BB%84%E4%BB%B6%E5%88%87%E6%8D%A2) * [1、方式一](#1%E6%96%B9%E5%BC%8F%E4%B8%80) * [2、方式二](#2%E6%96%B9%E5%BC%8F%E4%BA%8C) - [四、组件传值](#%E5%9B%9B%E7%BB%84%E4%BB%B6%E4%BC%A0%E5%80%BC) * [1、父组件向子组件传值](#1%E7%88%B6%E7%BB%84%E4%BB%B6%E5%90%91%E5%AD%90%E7%BB%84%E4%BB%B6%E4%BC%A0%E5%80%BC-1) * [2、父组件向子组件传方法](#2%E7%88%B6%E7%BB%84%E4%BB%B6%E5%90%91%E5%AD%90%E7%BB%84%E4%BB%B6%E4%BC%A0%E6%96%B9%E6%B3%95) * [3、使用 ref 获取DOM和组件的引用](#3%E4%BD%BF%E7%94%A8-ref-%E8%8E%B7%E5%8F%96dom%E5%92%8C%E7%BB%84%E4%BB%B6%E7%9A%84%E5%BC%95%E7%94%A8) --- ## 一、Vue组件 什么是组件: 组件的出现,就是为了拆分 Vue 实例的代码量的,能够让我们以不同的组件,来划分不同的功能模块,将来我们需要什么样的功能,就可以去调用对应的组件即可; **组件化和模块化的不同:** - 模块化: 是从代码逻辑的角度进行划分的;方便代码分层开发,保证每个功能模块的职能单一; - 组件化: 是从UI界面的角度进行划分的;前端的组件化,方便UI组件的重用; ## 二、定义组件 ### 1、定义全局组件 通过 `Vue.component(cname,option)`函数来定义 其中cname为字符串类型 代表组件名;option用于配置组件相关属性。 相关属性:例如:data computed methods template watch等等。 ```js // main.js import Vue from 'vue' // 全局组件 // 全局组件的定义一定要在new Vue之前。 // 定义之后到处可以使用,并且不需再声明 Vue.component('mydiv', { //不能在顶层元素使用v-for,因为顶层元素只能有一个 template: ` <div> <div v-for="item in goods">{{item.name}}</div> </div> `, data: function() { return { goods: [ { name: 'Daotin', age: 18 }, { name: 'lvonve', age: 19 }, { name: 'wenran', age: 20 } ] } } }); new Vue({ el: '#app', data:{} }); ``` 全局组件的使用: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="app"></div> <!--全局组件的使用--> <my-login></my-login> </body> </html> ``` > 注意: > > 0、不论是全局组件还是局部组件,组件的 template 属性指向的模板内容,必须有且只能有唯一的一个顶层元素,否则会报错。 > > 1、使用组件的时候,双标签和单标签的方式都可以。`<my-login></my-login>` 或者 `<my-login />` > > 2、组件的内部除了有 `template`,还有data,methods,watch,computed等所有vue实例的属性。 > > 3、使用 Vue.component 定义全局组件的时候,组件名称使用了 驼峰命名(如myLogin),则在调用组件的时候,需要把大写的驼峰改为小写的字母,同时在两个单词之前,使用 - 链接(`<my-login></my-login>`);如果不使用驼峰,则直接拿名称来使用即可; > > 4、全局组件定义之后可以可以直接使用,不需要import引入 > > 5、定义组件的时候,data为一个匿名函数,其返回值为一个对象。在这个返回对象里面填写需要的数据。 > > 6、定义全局组件的时候,必须在vue初始化之前完成,也就是必须放在new Vue()代码之前。 ### 2、定义局部组件 通过components : { componentname:option} 的形式注册过一个子组件后才能在当前组件内使用该组件。 定义局部组件,就是再vue实例中定义组件。 ```js // main.js import Vue from 'vue' // 子组件定义的时候,如果提出组件的配置(比如c),那么也要放在new Vue之前。 let c = { template: ` <div> <div v-for="item in names">{{item.name}}</div> </div> `, data: function() { return { names: [ { name: 'good1' }, { name: 'good2' }, { name: 'good3' } ] } } }; new Vue({ el: '#app', data: { username: 'daotin' }, // 定义局部组件 components: { goods:c } }); ``` 子组件的使用: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="app"></div> <!--局部组件的使用--> <goods></goods> </body> </html> ``` > 注意: > > 1、局部组件要使用的话,**在哪个组件使用,就要在哪个组件中定义**,也叫注册。 > > 2、定义子组件的时候,如果把option提出来写,也必须放在new Vue 之前。 ## 三、动态组件 定义三个子组件`Home.js, Goods.js, Users.js` > 一般组件的文件名首字母大写。 然后创建一个主组件App.js。在main.js里面这样做: 在main.js里面定义局部组件App,然后在main.js里面也可以定义template模板。 在main.js里面定义的模板会覆盖掉index.html里面的`<div id="app"></div>` 这里main.js里面的模板就是子组件App的内容,实际上这样写的目的就是在主页显示App的内容,所有其他组件比如Home.js等在App.js引入进行显示。 ```js new Vue({ el: '#app', data: {}, template: '<App/>', components: { App } }); ``` 看看各个文件的内容: ```js // Home.js export let Home = { template: ` <div> <h2>首页</h2> </div> ` } // Goods.js export let Goods = { template: ` <div> <ul> <li v-for="good in goods">{{good.goodsName}}</li> </ul> </div> `, data() { return { goods: [ { goodsName: '苹果' }, { goodsName: '香蕉' }, { goodsName: '梨' }, ] } }, } //Users.js export let Users = { template: ` <div> <ul> <li v-for="user in users">{{user.name}}</li> </ul> </div> `, data() { return { users: [ { name: 'lvonve' }, { name: 'daotin' }, { name: 'wenran' }, ] } }, } ``` 主组件App.js: ```js // 主组件 import { Home } from './pages/Home' import { Goods } from './pages/Goods' import { Users } from './pages/Users' export let App = { template: ` <div> <a href="javascript:;" @click="goPage(nav.name)" v-for="nav in navs">{{nav.text}}</a> <Component :is="currentPage" /> </div> `, data() { return { currentPage: 'Goods', navs: [ { text: '首页', name: 'Home' }, { text: '商品列表', name: 'Goods' }, { text: '用户列表', name: 'Users' } ] } }, methods: { goPage(pagename) { this.currentPage = pagename; } }, components: { Home, Goods, Users } } ``` 在主组件先import引入其他组件,然后使用局部组件的方式进行定义,之后使用`<Component is="Home" />` 类似于`<Home />` ,由于这里需要动态显示,所以is可变,就成了`<Component :is="currentPage" />` 这样点击不同的a标签就会显示不同的内容(默认显示Goods组件内容)。 ![](./images/7.gif) ## 四、组件间传值 ### 1、父组件向子组件传值 有这样一个需求,我们的Home,Goods,Users组件都需要有一个相同的头部组件Header,但是需要Header里面的内容不同,这就需要父组件Home,Goods,Users传给子组件Header不同的值来显示不同的内容。 定义一个Header组件。 ```js // Header.js export let Header = { template: ` <div> <h3> 我是Header组件 </h3> </div> ` } ``` 父组件怎么给子组件传值呢? 使用`props`。 父组件传递的方式:在子组件中自定义一个属性,名称随意,这里叫title,属性值为Home, ```js template: ` <div> <Header title="Home"/> <h2>首页</h2> </div> `, ``` 然后在子组件里面接收父组件传来的数据:使用props接收来自父组件的数据,接收属性为一个数组,里面的值就是传过来的属性名。 既然是数组,就可以接收多个父组件传过来的数据。 ```js export let Header = { // 使用props接收来自父组件的数据,接收属性为一个数组,里面的值就是传过来的属性名 props: ['title'], template: ` <div> <h3>我是Header组件</h3> <p>我来自{{title}}</p> </div> ` } ``` *(added in 20190711)* 如果想要将一个对象的所有属性一次性全部传入,有一种快捷的方式传入整个对象的属性,而不需要将对象的属性一个个的传入: ![](https://raw.githubusercontent.com/Daotin/pic/master/img/20190711101320.png) #### 1.1、props类型验证 我们上面props传递的都是字符串,如果不小心传递的是数组啊,对象啊什么的,显示的时候也只会以字符串的显示显示,如何对props传递的数据进行类型声明呢? 我们需要在子组件里面进行props声明: ```js export let Header = { props: { obj: Object, title: String }, template: ` <div> <h3>我是Header组件</h3> <p>我来自{{title}}</p> <p>{{obj}}</p> </div> ` } ``` 父组件传值的时候和之前一样: ```js import { Header } from '../components/Header' export let Home = { data() { return { title: 'Home', obj: { username: 'Daotin' } } }, template: ` <div> <Header :title="title" :obj="obj"/> <h2>首页</h2> </div> `, components: { Header } } ``` *(added in 20190711)* 1、prop的类型验证可以是**多个类型**。 ```js props: { handleData: { type: [Array,Object], default: () => { } }, } ``` 2、prop的类型验证 type 还可以是一个自定义的构造函数。 ![](https://raw.githubusercontent.com/Daotin/pic/master/img/20190711104244.png) #### 1.2、props必填验证 还有个问题是当父组件不填写title值的时候,子组件不显示,但是不会报错。 **如何设置子组件声明的值为必填属性呢?** 子组件这样设置: ```js export let Header = { props: { obj: Object, title: { type: String, required: true } }, template: ` <div> <h3>我是Header组件</h3> <p>我来自{{title}}</p> <p>{{obj}}</p> </div> ` } ``` 父组件如果不写`title`属性的话,会报以下错误: ![](./images/27.png) #### 1.3、props默认值 子组件: ```js export let Header = { props: { obj: Object, title: { type: String, default: 'Home' // required: true } }, template: ` <div> <h3>我是Header组件</h3> <p>我来自{{title}}</p> <p>{{obj}}</p> </div> ` } ``` 当子组件设置默认属性的时候,就不需要必填属性了,因为有了默认值肯定填写了。 #### 1.4、props自定义匹配规则 如果父组件传递的是个数组,我们想限制数组的长度怎么办?上面的属性都不可以限制,这时候就需要自定义匹配规则了。 这里我们限制传递过来的数组长度在3-10之间长度。 子组件: ```js export let Header = { props: { obj: Object, title: { type: String, default: 'Default Home' // required: true }, arr: { type: Array, required: true, validator: function(value) { // value就是父组件传递过来的数组 if (value.length >= 3 && value.length <= 10) { // 满足条件返回true return true; } else { // 不满足条件返回false return false; } } } }, template: ` <div> <h3>我是Header组件</h3> <p>我来自{{title}}</p> <p>{{obj}}</p> </div> ` } ``` 父组件这时传递个空数组: ```js import { Header } from '../components/Header' export let Home = { data() { return { title: 'Home', obj: { username: 'Daotin' }, arr: [] } }, template: ` <div> <Header :title="title" :obj="obj" :arr="arr"/> <h2>首页</h2> </div> `, components: { Header } } ``` 会报错如下,当我们传递的数组的长度满足的时候就不会报错了。 ![](./images/28.png) 但是我觉得这个提示不明显,我们可以手动报错。 ```js export let Header = { props: { obj: Object, title: { type: String, default: 'Default Home' // required: true }, arr: { type: Array, required: true, validator: function(value) { // value就是父组件传递过来的数组 if (value.length >= 3 && value.length <= 10) { return true; } else { // return false; throw new Error('数组的长度必须在3-10之间'); } } } }, template: ` <div> <h3>我是Header组件</h3> <p>我来自{{title}}</p> <p>{{obj}}</p> </div> ` } ``` ![](./images/29.png) 现在报错的信息就很明显了。 > 注意:注意那些 prop 会在一个**组件实例创建之前**进行验证,所以实例的属性 (如 data、computed 等) 在 default 或 validator 函数中是不可用的。 *(added in 20190711)* #### 1.5、prop 是单项数据流 所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外改变父级组件的状态,从而导致你的应用的数据流向难以理解。 额外的,**每次父级组件发生更新时,子组件中所有的 prop 都将会刷新为最新的值。**这意味着你不应该在一个子组件内部改变 prop。如果你这样做了,Vue 会在浏览器的控制台中发出警告。 ![](https://raw.githubusercontent.com/Daotin/pic/master/img/20190711101755.png) *(added in 20190711)* ### 非 Prop 的特性 一个非 prop 特性是指将一个属性传向一个子组件,但是该子组件并没有相应 prop 来接收。 也就是说,子组件中没有使用props定义一个属性A,但是如果你是父组件传入了子组件一个属性A,那么属性A会自动加在**子组件的根元素**上。 最典型的是在子组件上写了一个`class=“A”`,那么子组件的根元素上就有了`class=“A”` ```js <ChildComponent class="A" /> ``` > 注意: > > 对于绝大多数特性来说,从外部提供给组件的值会替换掉组件内部设置好的值。所以如果传入 type="text" 就会替换掉 type="date" 并把它破坏! > > 庆幸的是,class 和 style 特性会稍微智能一些,即子组件内部的class值和父组件传入的class值,两边的值会被合并起来,从而得到最终的值。 如果你不想让父组件传入的属性出现在子组件根元素上,可以在子组件选项中加入:`inheritAttrs: false` 即: ```vue Vue.component('my-component', { inheritAttrs: false, // ... }) ``` ### 2、子组件向父组件传值 在此之前先介绍个插件`string-loader` ,这个插件可以让我们组件的template属性的值提出到单独的html页面,便于书写。 - 安装插件 ``` npm i string-loader -D ``` - 配置config文件 ```json module: { rules: [ { test: /\.html$/, loader: 'string-loader' } ] }, ``` 这里创建一个子组件A.js和A组件的template文件A.html。 A组件如何使用外部的template呢? ```html <!--A.html--> <div> <h4> 我说A组件。 <span>count = {{count}}</span> <button @click="add">+</button> </h4> </div> ``` 首先要导入A.html文件才能使用,导入的方式和js一样。 ```js // A.js import htmlA from './A.html' export let A = { template: htmlA } ``` 然后用相同的方式创建B.js和B.html文件。然后在父组件Home.js引入使用A组件和B组件。 现在的代码结构如下: ```js // A.js import htmlA from './A.html' export let A = { props: ['title'], template: htmlA, data() { return { count: 0 } }, methods: { add() { this.count++; } } } // B.js import htmlB from './B.html' export let B = { props: ['cCount'], template: htmlB } // Home.js import { Header } from '../components/Header' import { A } from '../components/A' import { B } from '../components/B' export let Home = { template: ` <div> <Header :title="title"></Header> <h1>首页</h1> <A></A> <B></B> </div> `, data() { return { title: '首页的title', count: 0 } }, components: { Header, A, B } } ``` A.html和B.html ```html <!-- A.html --> <div> <h4> 我是A组件。 <span>count = {{count}}</span> <button @click="add">+</button> </h4> </div> <!-- B.html --> <div> <h4> 我是B组件。 <span>count = {{cCount}}</span> </h4> </div> ``` 此时的需求是点击A组件的按钮,A组件的count++,然后将count值传给Home父组件。 子组件传值给父组件使用:`子组件.$emit(事件名,发送给父组件的数据)` ```js // A.js import htmlA from './A.html' export let A = { props: ['title'], template: htmlA, data() { return { count: 0 } }, methods: { add() { this.count++; } }, // 监听数据的变化 watch: { count() { this.$emit('countChange', this.count); } } } ``` 我们在watch里面监听count值的变化,然后将count值使用`this.$emit('countChange', this.count);`发送给父组件,一旦count值发生变化,就会触发countChange事件,然后将this.count发送给父组件。 这时候在父组件监听这个countChange事件,拿到子组件传过来的count: ```js import { Header } from '../components/Header' import { A } from '../components/A' import { B } from '../components/B' export let Home = { template: ` <div> <Header :title="title"></Header> <h1>首页</h1> <A @countChange="change"></A> <B></B> </div> `, data() { return { title: '首页的title', count: 0 } }, methods: { change(count) { console.log(count); // 打印得到的子组件count值 this.count = count; } }, components: { Header, A, B } } ``` 如果想要change事件传多个值,比如还想传个一个参数为123,在第一个参数的位置,那么模板的写法就要修改: `<A @countChange="change(123, $event)"></A>` ,第二个参数`$event` 就相当于子组件传来的数据。 其实之前不写参数的时候,就类似与`<A @countChange="change($event)"></A>`这种写法。 ### 3、子组件之间相互传值 **方式一:中间人模式** 通过父组件间接传值(通过props的方式传值。) > 子组件A --> 父组件 --> 子组件B, **方式二:中央事件总线** 创建新的vue实例做中间人传话,分别调用emit()进行触发和on()进行监听。 创建一个`toolVue.js`文件: ```js import Vue from 'vue' export let media = new Vue(); ``` toolVue文件只负责创建一个vue实例,然后导出组件。 A,B组件引入toolVue组件。然后A的count变化的时候触发countChange函数,在B里面调用countChange函数得到A传递的数据。 ```js // A.js import { media } from '../toolVue' import htmlA from './A.html' export let A = { props: ['title'], template: htmlA, data() { return { count: 0 } }, methods: { add() { this.count++; } }, watch: { count() { // 通过media组件,当count变化时触发countChange,并传入count值 media.$emit('countChange', this.count); } }, components: { media } } ``` ```js // B.js import { media } from '../toolVue' import htmlB from './B.html' export let B = { // props: ['cCount'], template: htmlB, data() { return { cCount: 0 } }, components: { media }, mounted() { // 通过media,调用countChange函数,得到A的count值 // 注意这里面的this是media并不是B,所以要用箭头函数 media.$on('countChange', count => { this.cCount = count; }) }, } ``` 完成子组件A的count传递到子组件B。 > // 注意这里面的this是media并不是B,所以要用箭头函数 > media.$on('countChange', count => { > ​ this.cCount = count; > }) ![](./images/8.gif) #### 3.1、Tips **需要注意的是:如果是同一个页面的两个组件传递数据的时候,可能会发生接收的组件先监听事件,而后发送组件才发送数据,这样接收组件就接收不到数据了。** 解决办法:**给发送组件加个延时。** ```js // 发送组件 setTimeout(() => { media.$emit('hasUser', this.user); }, 50); ``` ```js // 接收组件 media.$on('hasUser', user => { this.user = user; }); ``` --- (---------下面是旧笔记---------) ## 三、组件切换 我们在登录注册一个网站的时候,经常看到两个按钮,一个登录,一个注册,如果你没有账号的话,需要先注册才能登录。我们在点击登录和注册的时候,网页会相应的切换,登录页面就是登陆组件,注册页面就是注册组件,那么点击登录和注册,如何实现组件的切换呢? ### 1、方式一 **使用`flag`标识符结合`v-if`和`v-else`切换组件** ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> </head> <body> <div id="box"> <!-- 给a注册点击事件,切换flag状态 --> <a href="javascript:;" @click.prevent="flag=true">登录</a> <a href="javascript:;" @click.prevent="flag=false">注册</a> <!-- 使用v-if v-else切换组件 --> <login v-if="flag"> </login> <register v-else="flag"> </register> </div> <script> Vue.component('login', { template: '<h3>登录组件</h3>' }); Vue.component('register', { template: '<h3>注册组件</h3>' }); var vm = new Vue({ el: "#box", data: { flag: true }, methods: {} }); </script> </body> </html> ``` **缺陷:**由于flag的值只有true和false,所以只能用于两个组件间 的切换,当大于两个组件的切换就不行了。 ### 2、方式二 **使用 component元素的`:is`属性来切换不同的子组件** 使用 `<component :is="componentId"></component>` 来指定要切换的组件。 componentId:为需要显示的组件名称,为一个字符串,可以使用变量指定。 `componentId: 'login'` // 默认显示登录组件。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> </head> <body> <div id="box"> <!-- 给a注册点击事件,切换flag状态 --> <a href="javascript:;" @click.prevent="componentId='login'">登录</a> <a href="javascript:;" @click.prevent="componentId='register'">注册</a> <component :is="componentId"></component> </div> <script> Vue.component('login', { template: '<h3>登录组件</h3>' }); Vue.component('register', { template: '<h3>注册组件</h3>' }); var vm = new Vue({ el: "#box", data: { componentId: 'login' // 默认显示登录 }, methods: {} }); </script> </body> </html> ``` **为组件切换添加过渡:** 很简单,只需要**用 transition 将 component 包裹起来**即可。 ```html <transition> <component :is="componentId"></component> </transition> ``` 示例: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> <link rel="stylesheet" href="./lib/animate.css"> <style> .loginDiv { width: 200px; height: 200px; background-color: red; } .registerDiv { width: 200px; height: 200px; background-color: blue; } </style> </head> <body> <div id="box"> <!-- 给a注册点击事件,切换flag状态 --> <a href="javascript:;" @click.prevent="componentId='login'">登录</a> <a href="javascript:;" @click.prevent="componentId='register'">注册</a> <transition mode="out-in" enter-active-class="animated bounceInRight" leave-active-class="animated bounceOutRight"> <component :is="componentId"></component> </transition> </div> <template id="login"> <div class="loginDiv"> </div> </template> <template id="register"> <div class="registerDiv"> </div> </template> <script> Vue.component('login', { template: '#login' }); Vue.component('register', { template: '#register' }); var vm = new Vue({ el: "#box", data: { componentId: 'login' }, methods: {} }); </script> </body> </html> ``` > `mode="out-in"`:可以设置切换组件的模式为先退出再进入。 ## 四、组件传值 ### 1、父组件向子组件传值 我们先通过一个例子看看子组件可不可以直接访问父组件的数据: ```html <body> <div id="box"> <mycom></mycom> </div> <template id="temp"> <h3>子组件 --- {{msg}}</h3> </template> <script> var vm = new Vue({ el: "#box", data: { msg: '父组件的msg' }, methods: {}, components: { mycom: { template: '#temp' } } }); </script> </body> ``` 由于 components 定义的是私有组件,我们直接在子组件中调用父组件的msg会报错。 ![](./images/15.png) 那么,怎么让子组件使用父组件的数据呢? **父组件可以在引用子组件的时候, 通过 属性绑定(v-bind:) 的形式, 把需要传递给子组件的数据,以属性绑定的形式,传递到子组件内部,供子组件使用 。** ```html <body> <div id="box"> <mycom v-bind:parentmsg="msg"></mycom> </div> <template id="temp"> <h3>子组件 --- 父组件:{{parentmsg}}</h3> </template> <script> var vm = new Vue({ el: "#box", data: { msg: '父组件的msg' }, methods: {}, components: { mycom: { template: "#temp", // 对传递给子组件的数据进行声明,子组件才能使用 props: ['parentmsg'] } } }); </script> </body> ``` 注意:父组件绑定的**属性名称不能有大写字母**,否则不会显示,并且在命令行会有提示: ![](./images/16.png) **组件data数据和props数据的区别:** - data数据是子组件私有的,可读可写; - props数据是父组件传递给子组件的,只能读,不能写。 **案例:发表评论功能** 父组件为评论列表,子组件为ID,评论者,内容和按钮的集合,在输入ID,评论者等内容,然后点击添加的时候,需要首先获取子组件的list列表,然后再添加新的列表项到列表中。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> </head> <body> <div id="box"> <mycom :plist="list"></mycom> <ul> <li v-for="item in list" :key="item.id"> ID:{{item.id}} --- 内容:{{item.content}} --- 评论人:{{item.user}} </li> </ul> </div> <template id="tmp1"> <div> <label> ID: <input type="text" v-model="id"> </label> <br> <label> 评论者: <input type="text" v-model="user"> </label> <br> <label> 内容: <textarea v-model="content"></textarea> </label> <br> <!-- 把父组件的数据作为子组件的函数参数传入 --> <input type="button" value="添加评论" @click="addContent(plist)"> </div> </template> <script> var vm = new Vue({ el: "#box", data: { list: [{ id: Date.now(), user: 'user1', content: 'what' }, { id: Date.now(), user: 'user2', content: 'are' }] }, methods: {}, components: { mycom: { template: '#tmp1', data: function () { return { id: '', user: '', content: '', } }, methods: { addContent(plist) { plist.unshift({ id: this.id, user: this.user, content: this.content }); } }, props: ['plist'] } } }); </script> </body> </html> ``` 把添加ID,评论人,内容作为子组件,把列表作为父组件,然后把添加的数据放到父组件列表上,由于要获取到父组件列表的数据,所以必然涉及到父组件向子组件传值的过程。这里还通过子组件方法参数来保存父组件的数据到子组件的数据中。 ### 2、父组件向子组件传方法 既然父组件可以向子组件传递数据,那么也可以向子组件传递方法。 ```html <body> <div id="box"> <mycom v-bind:parentmsg="msg" @parentfunc="show"></mycom> </div> <template id="temp"> <div> <input type="button" value="调用父组件方法" @click="sonClick"> <h3>子组件 --- 父组件:{{parentmsg}}</h3> </div> </template> <script> var vm = new Vue({ el: "#box", data: { msg: '父组件的msg' }, methods: { show(data1, data2) { console.log("这是父组件的show方法" + data1 + data2); } }, components: { mycom: { template: "#temp", // 对传递给子组件的数据进行声明,子组件才能使用 props: ['parentmsg'], methods: { sonClick() { // 调用父组件的show方法 this.$emit("parentfunc", 111, 222); } } } } }); </script> </body> ``` > 1、`@parentfunc="show"` 绑定父组件的show方法。 > > 2、`<input type="button" value="调用父组件方法" @click="sonClick">` 点击按钮调用父组件的show方法 > > 3、在 子组件的 sonClick 方法中使用 `this.$emit("parentfunc");` 来调用父组件的show方法 > > 4、父组件的show方法也可以传参,在调用的时候,实参从 this.$emit 的第二个参数开始传入。 > > **5、如果 this.$emit 的第二个参数传的是子组件的data数据,那么父组件的方法就可以获得子组件的数据,这也是把子组件的数据传递给父组件的方式。** ### 3、使用 ref 获取DOM和组件的引用 我们知道Vue不推荐直接获取DOM元素,那么在Vue里面怎么获取DOM及组件元素呢? 我们呢可以在元素上使用 `ref` 属性来获取元素。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> </head> <body> <div id="box"> <input type="button" value="获取元素" @click="getrefs" ref="mybtn"> <h3 ref="myh3">这是H3</h3> <mycom ref="mycom"></mycom> </div> <template id="tmp1"> </template> <script> // 定义组件 Vue.component('mycom', { template: '#tmp1', data: function () { return { msg: '子组件的msg', pmsg: '' } }, methods: { show(data) { console.log('调用子组件的show'); this.pmsg = data; console.log(this.pmsg); }, } }); var vm = new Vue({ el: "#box", data: { parentmsg: '父组件的msg' }, methods: { getrefs() { console.log(this.$refs.myh3); console.log(this.$refs.mycom.msg); this.$refs.mycom.show(this.parentmsg); } } }); </script> </body> </html> ``` ![](./images/17.png) **总结:** 1、ref 属性不仅可以获取DOM元素,也可以获取组件(无论全局还是私有组件)元素。 2、获取到组件元素后,就可以获取组件元素的data数据和methods方法。 **3、获取到组件中的方法后,可以传入VM的data数据,就可以把VM的data数据传入组件中。**
Daotin/Web/12-Vue/05-组件.md/0
{ "file_path": "Daotin/Web/12-Vue/05-组件.md", "repo_id": "Daotin", "token_count": 22135 }
15
## 动态组件 我们使用过多标签的`is`来进行组件之间的切换。 ```html <component :is="currentTabComponent"></component> ``` 这时每次切换到新的组件的时候,组件都会被从新加载,这意味着切换之前组件的状态不会被保存。 但是有些时候当在这些组件之间切换的时候,会想保持这些组件的状态,以避免反复重渲染导致的性能问题。 为了解决这个问题,我们可以用一个 `<keep-alive>` 元素将其动态组件包裹起来。 ```html <!-- 失活的组件将会被缓存!--> <keep-alive> <component :is="currentTabComponent"></component> </keep-alive> ``` > 注意:注意这个 `<keep-alive>` 要求被切换到的组件都有自己的名字,不论是通过组件的 `name` 选项还是局部/全局注册。
Daotin/Web/12-Vue/动态组件 & 异步组件.md/0
{ "file_path": "Daotin/Web/12-Vue/动态组件 & 异步组件.md", "repo_id": "Daotin", "token_count": 524 }
16
/* Navicat Premium Data Transfer Source Server : 阿里云MySQL Source Server Type : MySQL Source Server Version : 50718 Source Host : rm-wz9lp2i9322g0n06zvo.mysql.rds.aliyuncs.com:3306 Source Schema : web Target Server Type : MySQL Target Server Version : 50718 File Encoding : 65001 Date: 07/03/2018 09:59:25 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for code_library -- ---------------------------- DROP TABLE IF EXISTS `code_library`; CREATE TABLE `code_library` ( `code_id` int(32) NOT NULL AUTO_INCREMENT, `code_title` char(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL, `code_author` char(30) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL, `code_date` timestamp(0) NULL DEFAULT NULL, `code_read` int(32) NULL DEFAULT NULL, `code_summary` char(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL, `code_html_content` text CHARACTER SET utf8 COLLATE utf8_bin NULL, `code_md_content` text CHARACTER SET utf8 COLLATE utf8_bin NULL, `code_label` char(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL, `code_delete` int(32) NULL DEFAULT NULL, `code_category` int(32) NULL DEFAULT NULL, PRIMARY KEY (`code_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
Humsen/web/docs/数据库部署/第1步 - 创建数据库/code_library.sql/0
{ "file_path": "Humsen/web/docs/数据库部署/第1步 - 创建数据库/code_library.sql", "repo_id": "Humsen", "token_count": 553 }
17
package pers.husen.web.bean.vo; import java.util.Date; /** * @author 何明胜 * * 2017年9月28日 */ public class CodeLibraryVo extends ArticleCategoryVo{ private static final long serialVersionUID = 1L; private int codeId; private String codeTitle; private String codeAuthor; private Date codeDate; private int codeRead; private String codeSummary; private String codeHtmlContent; private String codeMdContent; private String codeLabel; private int codeDelete; private int codeCategory; private String userNickName; /** * @return the userNickName */ public String getUserNickName() { return userNickName; } /** * @param userNickName the userNickName to set */ public void setUserNickName(String userNickName) { this.userNickName = userNickName; } /** * @return the codeLabel */ public String getCodeLabel() { return codeLabel; } /** * @param codeLabel the codeLabel to set */ public void setCodeLabel(String codeLabel) { this.codeLabel = codeLabel; } /** * @return the codeId */ public int getCodeId() { return codeId; } /** * @param codeId the codeId to set */ public void setCodeId(int codeId) { this.codeId = codeId; } /** * @return the codeTitle */ public String getCodeTitle() { return codeTitle; } /** * @param codeTitle the codeTitle to set */ public void setCodeTitle(String codeTitle) { this.codeTitle = codeTitle; } /** * @return the codeAuthor */ public String getCodeAuthor() { return codeAuthor; } /** * @param codeAuthor the codeAuthor to set */ public void setCodeAuthor(String codeAuthor) { this.codeAuthor = codeAuthor; } /** * @return the codeDate */ public Date getCodeDate() { return codeDate; } /** * @param codeDate the codeDate to set */ public void setCodeDate(Date codeDate) { this.codeDate = codeDate; } /** * @return the codeRead */ public int getCodeRead() { return codeRead; } /** * @param codeRead the codeRead to set */ public void setCodeRead(int codeRead) { this.codeRead = codeRead; } /** * @return the codeSummary */ public String getCodeSummary() { return codeSummary; } /** * @param codeSummary the codeSummary to set */ public void setCodeSummary(String codeSummary) { this.codeSummary = codeSummary; } /** * @return the codeHtmlContent */ public String getCodeHtmlContent() { return codeHtmlContent; } /** * @param codeHtmlContent the codeHtmlContent to set */ public void setCodeHtmlContent(String codeHtmlContent) { this.codeHtmlContent = codeHtmlContent; } /** * @return the codeMdContent */ public String getCodeMdContent() { return codeMdContent; } /** * @param codeMdContent the codeMdContent to set */ public void setCodeMdContent(String codeMdContent) { this.codeMdContent = codeMdContent; } /** * @return the codeDelete */ public int getCodeDelete() { return codeDelete; } /** * @param codeDelete the codeDelete to set */ public void setCodeDelete(int codeDelete) { this.codeDelete = codeDelete; } /** * @return the codeCategory */ public int getCodeCategory() { return codeCategory; } /** * @param codeCategory the codeCategory to set */ public void setCodeCategory(int codeCategory) { this.codeCategory = codeCategory; } }
Humsen/web/web-core/src/pers/husen/web/bean/vo/CodeLibraryVo.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/bean/vo/CodeLibraryVo.java", "repo_id": "Humsen", "token_count": 1152 }
18
/** * 通用处理程序 * * @author 何明胜 * * 2017年10月21日 */ package pers.husen.web.common.handler;
Humsen/web/web-core/src/pers/husen/web/common/handler/package-info.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/common/handler/package-info.java", "repo_id": "Humsen", "token_count": 58 }
19
package pers.husen.web.config.listener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import pers.husen.web.config.ProjectDeployConfig; import pers.husen.web.config.Log4j2Config; /** * web启动时首先启动监听器,初始化一些配置,如路径 * * @author 何明胜 * * 2017年9月23日 */ public class WebInitConfigListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); // 获取当前web部署根目录 String deployRootDir = servletContext.getRealPath("/"); //将部署根目录赋值给全局变量 ProjectDeployConfig.setGlobalVariable(deployRootDir); //配置log4j new Log4j2Config().startLog4j2Config(); } @Override public void contextDestroyed(ServletContextEvent arg0) {} }
Humsen/web/web-core/src/pers/husen/web/config/listener/WebInitConfigListener.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/config/listener/WebInitConfigListener.java", "repo_id": "Humsen", "token_count": 383 }
20
package pers.husen.web.dao.impl; import java.util.ArrayList; import java.util.Date; import pers.husen.web.bean.vo.ReleaseFeatureVo; import pers.husen.web.dao.ReleaseFeatureDao; import pers.husen.web.dbutil.DbManipulationUtils; import pers.husen.web.dbutil.DbQueryUtils; import pers.husen.web.dbutil.mappingdb.ReleaseFeatureMapping; /** * * * @author 何明胜 * * 2017年10月17日 */ public class ReleaseFeatureDaoImpl implements ReleaseFeatureDao{ @Override public int insertReleaseFeature(ReleaseFeatureVo rVo) { String sql = "INSERT INTO release_feature " + "(release_author, release_date, release_number, release_content )" + "VALUES (?, ?, ?, ?)"; ArrayList<Object> paramList = new ArrayList<Object>(); Object obj = null; paramList.add((obj = rVo.getReleaseAuthor()) != null ? obj : new Date()); paramList.add((obj = rVo.getReleaseDate()) != null ? obj : ""); paramList.add((obj = rVo.getReleaseNumber()) != null ? obj : ""); paramList.add((obj = rVo.getReleaseContent()) != null ? obj : ""); return DbManipulationUtils.insertNewRecord(sql, paramList); } @Override public ReleaseFeatureVo queryLatestReleaseFeature() { String sql = "SELECT release_author, release_date, release_number, release_content, " + ReleaseFeatureMapping.RELEASE_ID + " FROM release_feature" + " WHERE release_id = (SELECT max(release_id) FROM release_feature)"; ArrayList<Object> paramList = new ArrayList<>(); return DbQueryUtils.queryBeanByParam(sql, paramList, ReleaseFeatureVo.class); } @Override public ReleaseFeatureVo queryReleaseById(int releaseId) { String sql = "SELECT release_author, release_date, release_number, release_content, " + ReleaseFeatureMapping.RELEASE_ID + " FROM release_feature" + " WHERE release_id = ?"; ArrayList<Object> paramList = new ArrayList<Object>(); paramList.add(releaseId); return DbQueryUtils.queryBeanByParam(sql, paramList, ReleaseFeatureVo.class); } @Override public int updateReleaseContentById(ReleaseFeatureVo rVo) { String sql = "UPDATE " + ReleaseFeatureMapping.DB_NAME + " SET " + ReleaseFeatureMapping.RELEASE_CONTENT + "=? " + "WHERE " + ReleaseFeatureMapping.RELEASE_ID + "=?"; ArrayList<Object> paramList = new ArrayList<Object>(); paramList.add(rVo.getReleaseContent()); paramList.add(rVo.getReleaseId()); return DbManipulationUtils.updateRecordByParam(sql, paramList); } }
Humsen/web/web-core/src/pers/husen/web/dao/impl/ReleaseFeatureDaoImpl.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/dao/impl/ReleaseFeatureDaoImpl.java", "repo_id": "Humsen", "token_count": 868 }
21
package pers.husen.web.dbutil.mappingdb; /** * 用户信息数据库 * * @author 何明胜 * * 2017年10月20日 */ public class UserInfoMapping { /** * 数据库名称 */ public static final String DB_NAME = "user_info"; public static final String USER_ID = "user_id"; public static final String USER_NAME = "user_name"; public static final String USER_NICK_NAME = "user_nick_name"; public static final String USER_PASSWORD = "user_password"; public static final String USER_EMAIL = "user_email"; public static final String USER_PHONE = "user_phone"; public static final String USER_AGE = "user_age"; public static final String USER_SEX = "user_sex"; public static final String USER_ADDRESS = "user_address"; public static final String USER_HEAD_URL = "user_head_url"; }
Humsen/web/web-core/src/pers/husen/web/dbutil/mappingdb/UserInfoMapping.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/dbutil/mappingdb/UserInfoMapping.java", "repo_id": "Humsen", "token_count": 291 }
22
package pers.husen.web.servlet.article; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import pers.husen.web.bean.vo.BlogArticleVo; import pers.husen.web.common.constants.CommonConstants; import pers.husen.web.common.constants.RequestConstants; import pers.husen.web.common.helper.TypeConvertHelper; import pers.husen.web.service.BlogArticleSvc; /** * 上传博客, 可能是新的,也可能是编辑 * * @author 何明胜 * * 2017年11月7日 */ @WebServlet(urlPatterns = "/blog/upload.hms") public class BlogUploadSvt extends HttpServlet { private static final long serialVersionUID = 1L; public BlogUploadSvt() { super(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取文章细节 String newArticle = request.getParameter("newArticle"); // 转化为json JSONObject jsonObject = JSONObject.fromObject(newArticle); // 转化为bean BlogArticleVo bVo = TypeConvertHelper.jsonObj2BlogBean(jsonObject); // 如果不是以逗号分隔的,关键字之间的多个空格都处理为一个 String blogLabel = bVo.getBlogLabel(); if (blogLabel.indexOf(CommonConstants.ENGLISH_COMMA) == -1 && blogLabel.indexOf(CommonConstants.CHINESE_COMMA) == -1) { bVo.setBlogLabel(blogLabel.replaceAll("\\s+", " ")); } if (blogLabel.indexOf(CommonConstants.CHINESE_COMMA) != -1) { bVo.setBlogLabel(blogLabel.replace(",", ",")); } BlogArticleSvc bSvc = new BlogArticleSvc(); PrintWriter out = response.getWriter(); String uploadType = request.getParameter("type"); /** 如果是修改博客 */ if (RequestConstants.REQUEST_TYPE_MODIFY.equals(uploadType)) { // 获取id int blogId = Integer.parseInt(request.getParameter("articleId")); // 设置id bVo.setBlogId(blogId); int insertResult = bSvc.updateBlogById(bVo); out.println(insertResult); return; } /** 如果是上传新博客 */ if (RequestConstants.REQUEST_TYPE_CREATE.equals(uploadType)) { int resultInsert = bSvc.insertBlogArticle(bVo); out.println(resultInsert); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Humsen/web/web-core/src/pers/husen/web/servlet/article/BlogUploadSvt.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/article/BlogUploadSvt.java", "repo_id": "Humsen", "token_count": 1007 }
23
package pers.husen.web.servlet.module; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import pers.husen.web.common.constants.ResponseConstants; import pers.husen.web.common.helper.ReadH5Helper; /** * @desc 留言区模块 * * @author 何明胜 * * @created 2017年12月20日 下午9:33:48 */ @WebServlet(urlPatterns = "/module/message.hms") public class MessageModuleSvt extends HttpServlet { private static final long serialVersionUID = 1L; public MessageModuleSvt() { super(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); ReadH5Helper.writeHtmlByName(ResponseConstants.MESSAGE_MODULE_TEMPLATE_PATH, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Humsen/web/web-core/src/pers/husen/web/servlet/module/MessageModuleSvt.java/0
{ "file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/module/MessageModuleSvt.java", "repo_id": "Humsen", "token_count": 432 }
24
@charset "UTF-8"; .index-hr { margin: 0; } #lwlhitokoto { border-left: 5px solid #0073d8; border-right: 5px solid #0073d8; background-color: #3288d31a; padding: 5px; text-align: center; color: #0073d8; margin: 0 0 42px 0; }
Humsen/web/web-mobile/WebContent/css/index/index.css/0
{ "file_path": "Humsen/web/web-mobile/WebContent/css/index/index.css", "repo_id": "Humsen", "token_count": 113 }
25
@charset "UTF-8"; /************** 新版编辑文章 ***************/ .editor-form-div { margin-top: 20px; } .article-type { width: initial; }
Humsen/web/web-mobile/WebContent/css/upload/editor-article.css/0
{ "file_path": "Humsen/web/web-mobile/WebContent/css/upload/editor-article.css", "repo_id": "Humsen", "token_count": 69 }
26
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html class="no-js"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>何明胜的个人网站</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="欢迎来到何明胜的个人网站.本站主要用于记录和分享本人的学习心得和编程经验,并分享常见可复用代码、推荐书籍以及软件等资源.本站源码已托管github,欢迎访问:https://github.com/HelloHusen/web" /> <meta name="keywords" content="何明胜,何明胜的个人网站,何明胜的博客,一格的程序人生" /> <meta name="author" content="何明胜,一格"> <!-- 网站图标 --> <link rel="shortcut icon" href="/images/favicon.ico"> <!-- jQuery --> <script src="/plugins/jquery/js/jquery-3.2.1.min.js"></script> <!-- 新版特性css --> <link rel="stylesheet" href="/css/index/version-feature.css"> <!-- 最新更新文章简介 --> <link rel="stylesheet" href="/css/index/article-profile.css"> <!-- 最新更新文章简介 --> <link rel="stylesheet" href="/css/index/index.css"> <!-- js文件 --> <script src="/js/index/index.js"></script> <!-- 加载新版本特性 --> <script type="text/javascript" src="/js/index/version-feature.js"></script> <!-- 加载最新3篇博客 --> <script type="text/javascript" src="/js/index/latestblog.js"></script> <!-- 加载最近3篇代码 --> <script type="text/javascript" src="/js/index/latestcode.js"></script> </head> <body> <input id="menuBarNo" type="hidden" value="0" /> <div id="fh5co-page"> <a href="#" class="js-fh5co-nav-toggle fh5co-nav-toggle"><i></i></a> <div id="fh5co-main"> <!-- 加载新版特性 --> <div class="fh5co-narrow-content version-div"> <div id="newVersionFeature" class="row"></div> </div> <hr class="index-hr" /> <div class="fh5co-narrow-content article-box-div"> <h2 class="fh5co-heading article-bar" data-animate-effect="fadeInLeft">最近更新的博客</h2> <a href="/module/blog.hms" class="read-more-article"><span class="glyphicon glyphicon-hand-right"></span>&nbsp;阅读更多博客</a> <div id="latestBlog" class="row"></div> </div> <hr class="index-hr" /> <div class="fh5co-narrow-content article-box-div"> <h2 class="fh5co-heading article-bar" data-animate-effect="fadeInLeft">最近更新的代码</h2> <a href="/module/code.hms" class="read-more-article"><span class="glyphicon glyphicon-hand-right"></span>&nbsp;阅读更多代码</a> <div id="latestCode" class="row"></div> </div> <script type="text/javascript" src="https://api.lwl12.com/hitokoto/main/get?encode=js&charset=utf-8"></script> <div id="lwlhitokoto"> <script> lwlhitokoto(); </script> </div> </div> </div> </body> </html>
Humsen/web/web-mobile/WebContent/index.jsp/0
{ "file_path": "Humsen/web/web-mobile/WebContent/index.jsp", "repo_id": "Humsen", "token_count": 1376 }
27
/** * @author 何明胜 * * 2017年9月27日 */ $(function(){ loadNewVersionFeature();//加载新版本特性 }); /** * 显示最新版本特性 * @returns */ function loadNewVersionFeature(){ $.ajax({ type : 'POST', url : '/latestRlseFetr.hms', dataType : 'json', success : function(response){ $('#newVersionFeature').append('<div class="col-md-6 animate-box fadeInLeft animated version-width" data-animate-effect="fadeInLeft">' + '<h2 class="fh5co-heading">新版特性</h2>' + '<div class="version-content">' + '<h5 class="version-heading">发布时间:' + new Date(response.releaseDate.time).format('yyyy-MM-dd hh:mm:ss') +'&nbsp; &nbsp; &nbsp; &nbsp;' + '版本:' + response.releaseNumber + '</h5>' + response.releaseContent + '</div>' + '</div>'); }, error : function(response, status){ $.confirm({ title: '新版特性加载出错', content: status + ' : ' +response, autoClose: 'ok|1000', type: 'green', buttons: { ok: { text: '确认', btnClass: 'btn-primary', }, } }); } }); }
Humsen/web/web-mobile/WebContent/js/index/version-feature.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/js/index/version-feature.js", "repo_id": "Humsen", "token_count": 565 }
28
<link rel="stylesheet" href="/css/login/email-check.css"> <form id="form_emailValidate" class="form-horizontal"> <div class="form-group form-group-div"> <label class="col-sm-3 control-label form-label">邮箱</label> <div class="col-sm-6 form-input-div"> <p id="txt_emailShow" class="form-control-static email-show"></p> </div> <a href="#" class="col-sm-3 control-label modify-email">修改</a> </div> <div class="form-group form-group-div"> <label for="txt_validateCode" class="col-sm-3 control-label form-label">验证码</label> <div class="col-sm-5 form-input-div" > <input type="text" class="form-control validate-code-input" id="txt_validateCode" name="validateCode" placeholder="请输入验证码"> </div> <button id="btn_sendCode" type="button" class="btn btn-default">获取验证码</button> </div> </form>
Humsen/web/web-mobile/WebContent/module/login/email_check.html/0
{ "file_path": "Humsen/web/web-mobile/WebContent/module/login/email_check.html", "repo_id": "Humsen", "token_count": 355 }
29
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" > <svg xmlns="http://www.w3.org/2000/svg"> <metadata>Generated by IcoMoon</metadata> <defs> <font id="icomoon" horiz-adv-x="1024"> <font-face units-per-em="1024" ascent="960" descent="-64" /> <missing-glyph horiz-adv-x="1024" /> <glyph unicode="&#x20;" d="" horiz-adv-x="512" /> <glyph unicode="&#xe1987;" d="M726.954 68.236l-91.855-56.319-21.517 106.748 113.371-50.43zM876.293 709.493l12.502 28.106c6.469 14.545 23.659 21.147 38.201 14.681l60.652-26.984c14.546-6.468 21.149-23.661 14.68-38.201l-12.502-28.106-113.536 50.505zM720.236 424.478l116.041 260.86-7.209 69.019h-130.248l-233.736-522.358-245.476 522.358h-133.528l-71.266-742.442h82.462l47.785 562.498 264.047-562.498h43.141l252.85 562.498 15.14-149.939zM761.891 11.915l-6.068 60.094 117.030 263.097 33.757-323.192-144.719 0.001zM621.638 137.007l113.54-50.503 246.486 554.111-113.536 50.506-246.489-554.114z" horiz-adv-x="1017" /> </font></defs></svg>
Humsen/web/web-mobile/WebContent/plugins/editormd/fonts/editormd-logo.svg/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/fonts/editormd-logo.svg", "repo_id": "Humsen", "token_count": 519 }
30
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var noOptions = {}; var nonWS = /[^\s\u00a0]/; var Pos = CodeMirror.Pos; function firstNonWS(str) { var found = str.search(nonWS); return found == -1 ? 0 : found; } CodeMirror.commands.toggleComment = function(cm) { var minLine = Infinity, ranges = cm.listSelections(), mode = null; for (var i = ranges.length - 1; i >= 0; i--) { var from = ranges[i].from(), to = ranges[i].to(); if (from.line >= minLine) continue; if (to.line >= minLine) to = Pos(minLine, 0); minLine = from.line; if (mode == null) { if (cm.uncomment(from, to)) mode = "un"; else { cm.lineComment(from, to); mode = "line"; } } else if (mode == "un") { cm.uncomment(from, to); } else { cm.lineComment(from, to); } } }; CodeMirror.defineExtension("lineComment", function(from, to, options) { if (!options) options = noOptions; var self = this, mode = self.getModeAt(from); var commentString = options.lineComment || mode.lineComment; if (!commentString) { if (options.blockCommentStart || mode.blockCommentStart) { options.fullLines = true; self.blockComment(from, to, options); } return; } var firstLine = self.getLine(from.line); if (firstLine == null) return; var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1); var pad = options.padding == null ? " " : options.padding; var blankLines = options.commentBlankLines || from.line == to.line; self.operation(function() { if (options.indent) { var baseString = firstLine.slice(0, firstNonWS(firstLine)); for (var i = from.line; i < end; ++i) { var line = self.getLine(i), cut = baseString.length; if (!blankLines && !nonWS.test(line)) continue; if (line.slice(0, cut) != baseString) cut = firstNonWS(line); self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut)); } } else { for (var i = from.line; i < end; ++i) { if (blankLines || nonWS.test(self.getLine(i))) self.replaceRange(commentString + pad, Pos(i, 0)); } } }); }); CodeMirror.defineExtension("blockComment", function(from, to, options) { if (!options) options = noOptions; var self = this, mode = self.getModeAt(from); var startString = options.blockCommentStart || mode.blockCommentStart; var endString = options.blockCommentEnd || mode.blockCommentEnd; if (!startString || !endString) { if ((options.lineComment || mode.lineComment) && options.fullLines != false) self.lineComment(from, to, options); return; } var end = Math.min(to.line, self.lastLine()); if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end; var pad = options.padding == null ? " " : options.padding; if (from.line > end) return; self.operation(function() { if (options.fullLines != false) { var lastLineHasText = nonWS.test(self.getLine(end)); self.replaceRange(pad + endString, Pos(end)); self.replaceRange(startString + pad, Pos(from.line, 0)); var lead = options.blockCommentLead || mode.blockCommentLead; if (lead != null) for (var i = from.line + 1; i <= end; ++i) if (i != end || lastLineHasText) self.replaceRange(lead + pad, Pos(i, 0)); } else { self.replaceRange(endString, to); self.replaceRange(startString, from); } }); }); CodeMirror.defineExtension("uncomment", function(from, to, options) { if (!options) options = noOptions; var self = this, mode = self.getModeAt(from); var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end); // Try finding line comments var lineString = options.lineComment || mode.lineComment, lines = []; var pad = options.padding == null ? " " : options.padding, didSomething; lineComment: { if (!lineString) break lineComment; for (var i = start; i <= end; ++i) { var line = self.getLine(i); var found = line.indexOf(lineString); if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1; if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment; if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment; lines.push(line); } self.operation(function() { for (var i = start; i <= end; ++i) { var line = lines[i - start]; var pos = line.indexOf(lineString), endPos = pos + lineString.length; if (pos < 0) continue; if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length; didSomething = true; self.replaceRange("", Pos(i, pos), Pos(i, endPos)); } }); if (didSomething) return true; } // Try block comments var startString = options.blockCommentStart || mode.blockCommentStart; var endString = options.blockCommentEnd || mode.blockCommentEnd; if (!startString || !endString) return false; var lead = options.blockCommentLead || mode.blockCommentLead; var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end); var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString); if (close == -1 && start != end) { endLine = self.getLine(--end); close = endLine.lastIndexOf(endString); } if (open == -1 || close == -1 || !/comment/.test(self.getTokenTypeAt(Pos(start, open + 1))) || !/comment/.test(self.getTokenTypeAt(Pos(end, close + 1)))) return false; // Avoid killing block comments completely outside the selection. // Positions of the last startString before the start of the selection, and the first endString after it. var lastStart = startLine.lastIndexOf(startString, from.ch); var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length); if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false; // Positions of the first endString after the end of the selection, and the last startString before it. firstEnd = endLine.indexOf(endString, to.ch); var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch); lastStart = (firstEnd == -1 || almostLastStart == -1) ? -1 : to.ch + almostLastStart; if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false; self.operation(function() { self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)), Pos(end, close + endString.length)); var openEnd = open + startString.length; if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length; self.replaceRange("", Pos(start, open), Pos(start, openEnd)); if (lead) for (var i = start + 1; i <= end; ++i) { var line = self.getLine(i), found = line.indexOf(lead); if (found == -1 || nonWS.test(line.slice(0, found))) continue; var foundEnd = found + lead.length; if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length; self.replaceRange("", Pos(i, found), Pos(i, foundEnd)); } }); return true; }); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/comment/comment.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/comment/comment.js", "repo_id": "Humsen", "token_count": 3132 }
31
// 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.registerGlobalHelper("fold", "comment", function(mode) { return mode.blockCommentStart && mode.blockCommentEnd; }, function(cm, start) { var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd; if (!startToken || !endToken) return; var line = start.line, lineText = cm.getLine(line); var startCh; for (var at = start.ch, pass = 0;;) { var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1); if (found == -1) { if (pass == 1) return; pass = 1; at = lineText.length; continue; } if (pass == 1 && found < start.ch) return; if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1)))) { startCh = found + startToken.length; break; } at = found - 1; } var depth = 1, lastLine = cm.lastLine(), end, endCh; outer: for (var i = line; i <= lastLine; ++i) { var text = cm.getLine(i), pos = i == line ? startCh : 0; for (;;) { var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos); if (nextOpen < 0) nextOpen = text.length; if (nextClose < 0) nextClose = text.length; pos = Math.min(nextOpen, nextClose); if (pos == text.length) break; if (pos == nextOpen) ++depth; else if (!--depth) { end = i; endCh = pos; break outer; } ++pos; } } if (end == null || line == end && endCh == startCh) return; return {from: CodeMirror.Pos(line, startCh), to: CodeMirror.Pos(end, endCh)}; }); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/fold/comment-fold.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/fold/comment-fold.js", "repo_id": "Humsen", "token_count": 773 }
32
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // Depends on csslint.js from https://github.com/stubbornella/csslint // declare global: CSSLint (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.registerHelper("lint", "css", function(text) { var found = []; if (!window.CSSLint) return found; var results = CSSLint.verify(text), messages = results.messages, message = null; for ( var i = 0; i < messages.length; i++) { message = messages[i]; var startLine = message.line -1, endLine = message.line -1, startCol = message.col -1, endCol = message.col; found.push({ from: CodeMirror.Pos(startLine, startCol), to: CodeMirror.Pos(endLine, endCol), message: message.message, severity : message.type }); } return found; }); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/lint/css-lint.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/lint/css-lint.js", "repo_id": "Humsen", "token_count": 412 }
33
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE /* Just enough of CodeMirror to run runMode under node.js */ // declare global: StringStream function splitLines(string){ return string.split(/\r?\n|\r/); }; function StringStream(string) { this.pos = this.start = 0; this.string = string; this.lineStart = 0; } StringStream.prototype = { eol: function() {return this.pos >= this.string.length;}, sol: function() {return this.pos == 0;}, peek: function() {return this.string.charAt(this.pos) || null;}, next: function() { if (this.pos < this.string.length) return this.string.charAt(this.pos++); }, eat: function(match) { var ch = this.string.charAt(this.pos); if (typeof match == "string") var ok = ch == match; else var ok = ch && (match.test ? match.test(ch) : match(ch)); if (ok) {++this.pos; return ch;} }, eatWhile: function(match) { var start = this.pos; while (this.eat(match)){} return this.pos > start; }, eatSpace: function() { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; return this.pos > start; }, skipToEnd: function() {this.pos = this.string.length;}, skipTo: function(ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true;} }, backUp: function(n) {this.pos -= n;}, column: function() {return this.start - this.lineStart;}, indentation: function() {return 0;}, match: function(pattern, consume, caseInsensitive) { if (typeof pattern == "string") { var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; var substr = this.string.substr(this.pos, pattern.length); if (cased(substr) == cased(pattern)) { if (consume !== false) this.pos += pattern.length; return true; } } else { var match = this.string.slice(this.pos).match(pattern); if (match && match.index > 0) return null; if (match && consume !== false) this.pos += match[0].length; return match; } }, current: function(){return this.string.slice(this.start, this.pos);}, hideFirstChars: function(n, inner) { this.lineStart += n; try { return inner(); } finally { this.lineStart -= n; } } }; exports.StringStream = StringStream; exports.startState = function(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true; }; var modes = exports.modes = {}, mimeModes = exports.mimeModes = {}; exports.defineMode = function(name, mode) { if (arguments.length > 2) mode.dependencies = Array.prototype.slice.call(arguments, 2); modes[name] = mode; }; exports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; }; exports.defineMode("null", function() { return {token: function(stream) {stream.skipToEnd();}}; }); exports.defineMIME("text/plain", "null"); exports.resolveMode = function(spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { spec = mimeModes[spec]; } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { spec = mimeModes[spec.name]; } if (typeof spec == "string") return {name: spec}; else return spec || {name: "null"}; }; exports.getMode = function(options, spec) { spec = exports.resolveMode(spec); var mfactory = modes[spec.name]; if (!mfactory) throw new Error("Unknown mode: " + spec); return mfactory(options, spec); }; exports.registerHelper = exports.registerGlobalHelper = Math.min; exports.runMode = function(string, modespec, callback, options) { var mode = exports.getMode({indentUnit: 2}, modespec); var lines = splitLines(string), state = (options && options.state) || exports.startState(mode); for (var i = 0, e = lines.length; i < e; ++i) { if (i) callback("\n"); var stream = new exports.StringStream(lines[i]); if (!stream.string && mode.blankLine) mode.blankLine(state); while (!stream.eol()) { var style = mode.token(stream, state); callback(stream.current(), style, i, stream.start, state); stream.start = stream.pos; } } }; require.cache[require.resolve("../../lib/codemirror")] = require.cache[require.resolve("./runmode.node")];
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/runmode/runmode.node.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/runmode/runmode.node.js", "repo_id": "Humsen", "token_count": 1576 }
34
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var Pos = CodeMirror.Pos; function findParagraph(cm, pos, options) { var startRE = options.paragraphStart || cm.getHelper(pos, "paragraphStart"); for (var start = pos.line, first = cm.firstLine(); start > first; --start) { var line = cm.getLine(start); if (startRE && startRE.test(line)) break; if (!/\S/.test(line)) { ++start; break; } } var endRE = options.paragraphEnd || cm.getHelper(pos, "paragraphEnd"); for (var end = pos.line + 1, last = cm.lastLine(); end <= last; ++end) { var line = cm.getLine(end); if (endRE && endRE.test(line)) { ++end; break; } if (!/\S/.test(line)) break; } return {from: start, to: end}; } function findBreakPoint(text, column, wrapOn, killTrailingSpace) { for (var at = column; at > 0; --at) if (wrapOn.test(text.slice(at - 1, at + 1))) break; if (at == 0) at = column; var endOfText = at; if (killTrailingSpace) while (text.charAt(endOfText - 1) == " ") --endOfText; return {from: endOfText, to: at}; } function wrapRange(cm, from, to, options) { from = cm.clipPos(from); to = cm.clipPos(to); var column = options.column || 80; var wrapOn = options.wrapOn || /\s\S|-[^\.\d]/; var killTrailing = options.killTrailingSpace !== false; var changes = [], curLine = "", curNo = from.line; var lines = cm.getRange(from, to, false); if (!lines.length) return null; var leadingSpace = lines[0].match(/^[ \t]*/)[0]; for (var i = 0; i < lines.length; ++i) { var text = lines[i], oldLen = curLine.length, spaceInserted = 0; if (curLine && text && !wrapOn.test(curLine.charAt(curLine.length - 1) + text.charAt(0))) { curLine += " "; spaceInserted = 1; } var spaceTrimmed = ""; if (i) { spaceTrimmed = text.match(/^\s*/)[0]; text = text.slice(spaceTrimmed.length); } curLine += text; if (i) { var firstBreak = curLine.length > column && leadingSpace == spaceTrimmed && findBreakPoint(curLine, column, wrapOn, killTrailing); // If this isn't broken, or is broken at a different point, remove old break if (!firstBreak || firstBreak.from != oldLen || firstBreak.to != oldLen + spaceInserted) { changes.push({text: [spaceInserted ? " " : ""], from: Pos(curNo, oldLen), to: Pos(curNo + 1, spaceTrimmed.length)}); } else { curLine = leadingSpace + text; ++curNo; } } while (curLine.length > column) { var bp = findBreakPoint(curLine, column, wrapOn, killTrailing); changes.push({text: ["", leadingSpace], from: Pos(curNo, bp.from), to: Pos(curNo, bp.to)}); curLine = leadingSpace + curLine.slice(bp.to); ++curNo; } } if (changes.length) cm.operation(function() { for (var i = 0; i < changes.length; ++i) { var change = changes[i]; cm.replaceRange(change.text, change.from, change.to); } }); return changes.length ? {from: changes[0].from, to: CodeMirror.changeEnd(changes[changes.length - 1])} : null; } CodeMirror.defineExtension("wrapParagraph", function(pos, options) { options = options || {}; if (!pos) pos = this.getCursor(); var para = findParagraph(this, pos, options); return wrapRange(this, Pos(para.from, 0), Pos(para.to - 1), options); }); CodeMirror.commands.wrapLines = function(cm) { cm.operation(function() { var ranges = cm.listSelections(), at = cm.lastLine() + 1; for (var i = ranges.length - 1; i >= 0; i--) { var range = ranges[i], span; if (range.empty()) { var para = findParagraph(cm, range.head, {}); span = {from: Pos(para.from, 0), to: Pos(para.to - 1)}; } else { span = {from: range.from(), to: range.to()}; } if (span.to.line >= at) continue; at = span.from.line; wrapRange(cm, span.from, span.to, {}); } }); }; CodeMirror.defineExtension("wrapRange", function(from, to, options) { return wrapRange(this, from, to, options || {}); }); CodeMirror.defineExtension("wrapParagraphsInRange", function(from, to, options) { options = options || {}; var cm = this, paras = []; for (var line = from.line; line <= to.line;) { var para = findParagraph(cm, Pos(line, 0), options); paras.push(para); line = para.to; } var madeChange = false; if (paras.length) cm.operation(function() { for (var i = paras.length - 1; i >= 0; --i) madeChange = madeChange || wrapRange(cm, Pos(paras[i].from, 0), Pos(paras[i].to - 1), options); }); return madeChange; }); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/wrap/hardwrap.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/wrap/hardwrap.js", "repo_id": "Humsen", "token_count": 2231 }
35
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-scss"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "scss"); } MT('url_with_quotation', "[tag foo] { [property background]:[atom url]([string test.jpg]) }"); MT('url_with_double_quotes', "[tag foo] { [property background]:[atom url]([string \"test.jpg\"]) }"); MT('url_with_single_quotes', "[tag foo] { [property background]:[atom url]([string \'test.jpg\']) }"); MT('string', "[def @import] [string \"compass/css3\"]"); MT('important_keyword', "[tag foo] { [property background]:[atom url]([string \'test.jpg\']) [keyword !important] }"); MT('variable', "[variable-2 $blue]:[atom #333]"); MT('variable_as_attribute', "[tag foo] { [property color]:[variable-2 $blue] }"); MT('numbers', "[tag foo] { [property padding]:[number 10px] [number 10] [number 10em] [number 8in] }"); MT('number_percentage', "[tag foo] { [property width]:[number 80%] }"); MT('selector', "[builtin #hello][qualifier .world]{}"); MT('singleline_comment', "[comment // this is a comment]"); MT('multiline_comment', "[comment /*foobar*/]"); MT('attribute_with_hyphen', "[tag foo] { [property font-size]:[number 10px] }"); MT('string_after_attribute', "[tag foo] { [property content]:[string \"::\"] }"); MT('directives', "[def @include] [qualifier .mixin]"); MT('basic_structure', "[tag p] { [property background]:[keyword red]; }"); MT('nested_structure', "[tag p] { [tag a] { [property color]:[keyword red]; } }"); MT('mixin', "[def @mixin] [tag table-base] {}"); MT('number_without_semicolon', "[tag p] {[property width]:[number 12]}", "[tag a] {[property color]:[keyword red];}"); MT('atom_in_nested_block', "[tag p] { [tag a] { [property color]:[atom #000]; } }"); MT('interpolation_in_property', "[tag foo] { #{[variable-2 $hello]}:[number 2]; }"); MT('interpolation_in_selector', "[tag foo]#{[variable-2 $hello]} { [property color]:[atom #000]; }"); MT('interpolation_error', "[tag foo]#{[error foo]} { [property color]:[atom #000]; }"); MT("divide_operator", "[tag foo] { [property width]:[number 4] [operator /] [number 2] }"); MT('nested_structure_with_id_selector', "[tag p] { [builtin #hello] { [property color]:[keyword red]; } }"); MT('indent_mixin', "[def @mixin] [tag container] (", " [variable-2 $a]: [number 10],", " [variable-2 $b]: [number 10])", "{}"); MT('indent_nested', "[tag foo] {", " [tag bar] {", " }", "}"); MT('indent_parentheses', "[tag foo] {", " [property color]: [variable darken]([variable-2 $blue],", " [number 9%]);", "}"); MT('indent_vardef', "[variable-2 $name]:", " [string 'val'];", "[tag tag] {", " [tag inner] {", " [property margin]: [number 3px];", " }", "}"); })();
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/css/scss_test.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/css/scss_test.js", "repo_id": "Humsen", "token_count": 1238 }
36
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("gas", function(_config, parserConfig) { 'use strict'; // If an architecture is specified, its initialization function may // populate this array with custom parsing functions which will be // tried in the event that the standard functions do not find a match. var custom = []; // The symbol used to start a line comment changes based on the target // architecture. // If no architecture is pased in "parserConfig" then only multiline // comments will have syntax support. var lineCommentStartSymbol = ""; // These directives are architecture independent. // Machine specific directives should go in their respective // architecture initialization function. // Reference: // http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops var directives = { ".abort" : "builtin", ".align" : "builtin", ".altmacro" : "builtin", ".ascii" : "builtin", ".asciz" : "builtin", ".balign" : "builtin", ".balignw" : "builtin", ".balignl" : "builtin", ".bundle_align_mode" : "builtin", ".bundle_lock" : "builtin", ".bundle_unlock" : "builtin", ".byte" : "builtin", ".cfi_startproc" : "builtin", ".comm" : "builtin", ".data" : "builtin", ".def" : "builtin", ".desc" : "builtin", ".dim" : "builtin", ".double" : "builtin", ".eject" : "builtin", ".else" : "builtin", ".elseif" : "builtin", ".end" : "builtin", ".endef" : "builtin", ".endfunc" : "builtin", ".endif" : "builtin", ".equ" : "builtin", ".equiv" : "builtin", ".eqv" : "builtin", ".err" : "builtin", ".error" : "builtin", ".exitm" : "builtin", ".extern" : "builtin", ".fail" : "builtin", ".file" : "builtin", ".fill" : "builtin", ".float" : "builtin", ".func" : "builtin", ".global" : "builtin", ".gnu_attribute" : "builtin", ".hidden" : "builtin", ".hword" : "builtin", ".ident" : "builtin", ".if" : "builtin", ".incbin" : "builtin", ".include" : "builtin", ".int" : "builtin", ".internal" : "builtin", ".irp" : "builtin", ".irpc" : "builtin", ".lcomm" : "builtin", ".lflags" : "builtin", ".line" : "builtin", ".linkonce" : "builtin", ".list" : "builtin", ".ln" : "builtin", ".loc" : "builtin", ".loc_mark_labels" : "builtin", ".local" : "builtin", ".long" : "builtin", ".macro" : "builtin", ".mri" : "builtin", ".noaltmacro" : "builtin", ".nolist" : "builtin", ".octa" : "builtin", ".offset" : "builtin", ".org" : "builtin", ".p2align" : "builtin", ".popsection" : "builtin", ".previous" : "builtin", ".print" : "builtin", ".protected" : "builtin", ".psize" : "builtin", ".purgem" : "builtin", ".pushsection" : "builtin", ".quad" : "builtin", ".reloc" : "builtin", ".rept" : "builtin", ".sbttl" : "builtin", ".scl" : "builtin", ".section" : "builtin", ".set" : "builtin", ".short" : "builtin", ".single" : "builtin", ".size" : "builtin", ".skip" : "builtin", ".sleb128" : "builtin", ".space" : "builtin", ".stab" : "builtin", ".string" : "builtin", ".struct" : "builtin", ".subsection" : "builtin", ".symver" : "builtin", ".tag" : "builtin", ".text" : "builtin", ".title" : "builtin", ".type" : "builtin", ".uleb128" : "builtin", ".val" : "builtin", ".version" : "builtin", ".vtable_entry" : "builtin", ".vtable_inherit" : "builtin", ".warning" : "builtin", ".weak" : "builtin", ".weakref" : "builtin", ".word" : "builtin" }; var registers = {}; function x86(_parserConfig) { lineCommentStartSymbol = "#"; registers.ax = "variable"; registers.eax = "variable-2"; registers.rax = "variable-3"; registers.bx = "variable"; registers.ebx = "variable-2"; registers.rbx = "variable-3"; registers.cx = "variable"; registers.ecx = "variable-2"; registers.rcx = "variable-3"; registers.dx = "variable"; registers.edx = "variable-2"; registers.rdx = "variable-3"; registers.si = "variable"; registers.esi = "variable-2"; registers.rsi = "variable-3"; registers.di = "variable"; registers.edi = "variable-2"; registers.rdi = "variable-3"; registers.sp = "variable"; registers.esp = "variable-2"; registers.rsp = "variable-3"; registers.bp = "variable"; registers.ebp = "variable-2"; registers.rbp = "variable-3"; registers.ip = "variable"; registers.eip = "variable-2"; registers.rip = "variable-3"; registers.cs = "keyword"; registers.ds = "keyword"; registers.ss = "keyword"; registers.es = "keyword"; registers.fs = "keyword"; registers.gs = "keyword"; } function armv6(_parserConfig) { // Reference: // http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf // http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf lineCommentStartSymbol = "@"; directives.syntax = "builtin"; registers.r0 = "variable"; registers.r1 = "variable"; registers.r2 = "variable"; registers.r3 = "variable"; registers.r4 = "variable"; registers.r5 = "variable"; registers.r6 = "variable"; registers.r7 = "variable"; registers.r8 = "variable"; registers.r9 = "variable"; registers.r10 = "variable"; registers.r11 = "variable"; registers.r12 = "variable"; registers.sp = "variable-2"; registers.lr = "variable-2"; registers.pc = "variable-2"; registers.r13 = registers.sp; registers.r14 = registers.lr; registers.r15 = registers.pc; custom.push(function(ch, stream) { if (ch === '#') { stream.eatWhile(/\w/); return "number"; } }); } var arch = (parserConfig.architecture || "x86").toLowerCase(); if (arch === "x86") { x86(parserConfig); } else if (arch === "arm" || arch === "armv6") { armv6(parserConfig); } function nextUntilUnescaped(stream, end) { var escaped = false, next; while ((next = stream.next()) != null) { if (next === end && !escaped) { return false; } escaped = !escaped && next === "\\"; } return escaped; } function clikeComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (ch === "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch === "*"); } return "comment"; } return { startState: function() { return { tokenize: null }; }, token: function(stream, state) { if (state.tokenize) { return state.tokenize(stream, state); } if (stream.eatSpace()) { return null; } var style, cur, ch = stream.next(); if (ch === "/") { if (stream.eat("*")) { state.tokenize = clikeComment; return clikeComment(stream, state); } } if (ch === lineCommentStartSymbol) { stream.skipToEnd(); return "comment"; } if (ch === '"') { nextUntilUnescaped(stream, '"'); return "string"; } if (ch === '.') { stream.eatWhile(/\w/); cur = stream.current().toLowerCase(); style = directives[cur]; return style || null; } if (ch === '=') { stream.eatWhile(/\w/); return "tag"; } if (ch === '{') { return "braket"; } if (ch === '}') { return "braket"; } if (/\d/.test(ch)) { if (ch === "0" && stream.eat("x")) { stream.eatWhile(/[0-9a-fA-F]/); return "number"; } stream.eatWhile(/\d/); return "number"; } if (/\w/.test(ch)) { stream.eatWhile(/\w/); if (stream.eat(":")) { return 'tag'; } cur = stream.current().toLowerCase(); style = registers[cur]; return style || null; } for (var i = 0; i < custom.length; i++) { style = custom[i](ch, stream, state); if (style) { return style; } } }, lineComment: lineCommentStartSymbol, blockCommentStart: "/*", blockCommentEnd: "*/" }; }); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/gas/gas.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/gas/gas.js", "repo_id": "Humsen", "token_count": 3868 }
37
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "javascript"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("locals", "[keyword function] [variable foo]([def a], [def b]) { [keyword var] [def c] [operator =] [number 10]; [keyword return] [variable-2 a] [operator +] [variable-2 c] [operator +] [variable d]; }"); MT("comma-and-binop", "[keyword function](){ [keyword var] [def x] [operator =] [number 1] [operator +] [number 2], [def y]; }"); MT("destructuring", "([keyword function]([def a], [[[def b], [def c] ]]) {", " [keyword let] {[def d], [property foo]: [def c][operator =][number 10], [def x]} [operator =] [variable foo]([variable-2 a]);", " [[[variable-2 c], [variable y] ]] [operator =] [variable-2 c];", "})();"); MT("class_body", "[keyword class] [variable Foo] {", " [property constructor]() {}", " [property sayName]() {", " [keyword return] [string-2 `foo${][variable foo][string-2 }oo`];", " }", "}"); MT("class", "[keyword class] [variable Point] [keyword extends] [variable SuperThing] {", " [property get] [property prop]() { [keyword return] [number 24]; }", " [property constructor]([def x], [def y]) {", " [keyword super]([string 'something']);", " [keyword this].[property x] [operator =] [variable-2 x];", " }", "}"); MT("module", "[keyword module] [string 'foo'] {", " [keyword export] [keyword let] [def x] [operator =] [number 42];", " [keyword export] [keyword *] [keyword from] [string 'somewhere'];", "}"); MT("import", "[keyword function] [variable foo]() {", " [keyword import] [def $] [keyword from] [string 'jquery'];", " [keyword module] [def crypto] [keyword from] [string 'crypto'];", " [keyword import] { [def encrypt], [def decrypt] } [keyword from] [string 'crypto'];", "}"); MT("const", "[keyword function] [variable f]() {", " [keyword const] [[ [def a], [def b] ]] [operator =] [[ [number 1], [number 2] ]];", "}"); MT("for/of", "[keyword for]([keyword let] [variable of] [keyword of] [variable something]) {}"); MT("generator", "[keyword function*] [variable repeat]([def n]) {", " [keyword for]([keyword var] [def i] [operator =] [number 0]; [variable-2 i] [operator <] [variable-2 n]; [operator ++][variable-2 i])", " [keyword yield] [variable-2 i];", "}"); MT("quotedStringAddition", "[keyword let] [variable f] [operator =] [variable a] [operator +] [string 'fatarrow'] [operator +] [variable c];"); MT("quotedFatArrow", "[keyword let] [variable f] [operator =] [variable a] [operator +] [string '=>'] [operator +] [variable c];"); MT("fatArrow", "[variable array].[property filter]([def a] [operator =>] [variable-2 a] [operator +] [number 1]);", "[variable a];", // No longer in scope "[keyword let] [variable f] [operator =] ([[ [def a], [def b] ]], [def c]) [operator =>] [variable-2 a] [operator +] [variable-2 c];", "[variable c];"); MT("spread", "[keyword function] [variable f]([def a], [meta ...][def b]) {", " [variable something]([variable-2 a], [meta ...][variable-2 b]);", "}"); MT("comprehension", "[keyword function] [variable f]() {", " [[([variable x] [operator +] [number 1]) [keyword for] ([keyword var] [def x] [keyword in] [variable y]) [keyword if] [variable pred]([variable-2 x]) ]];", " ([variable u] [keyword for] ([keyword var] [def u] [keyword of] [variable generateValues]()) [keyword if] ([variable-2 u].[property color] [operator ===] [string 'blue']));", "}"); MT("quasi", "[variable re][string-2 `fofdlakj${][variable x] [operator +] ([variable re][string-2 `foo`]) [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]"); MT("quasi_no_function", "[variable x] [operator =] [string-2 `fofdlakj${][variable x] [operator +] [string-2 `foo`] [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]"); MT("indent_statement", "[keyword var] [variable x] [operator =] [number 10]", "[variable x] [operator +=] [variable y] [operator +]", " [atom Infinity]", "[keyword debugger];"); MT("indent_if", "[keyword if] ([number 1])", " [keyword break];", "[keyword else] [keyword if] ([number 2])", " [keyword continue];", "[keyword else]", " [number 10];", "[keyword if] ([number 1]) {", " [keyword break];", "} [keyword else] [keyword if] ([number 2]) {", " [keyword continue];", "} [keyword else] {", " [number 10];", "}"); MT("indent_for", "[keyword for] ([keyword var] [variable i] [operator =] [number 0];", " [variable i] [operator <] [number 100];", " [variable i][operator ++])", " [variable doSomething]([variable i]);", "[keyword debugger];"); MT("indent_c_style", "[keyword function] [variable foo]()", "{", " [keyword debugger];", "}"); MT("indent_else", "[keyword for] (;;)", " [keyword if] ([variable foo])", " [keyword if] ([variable bar])", " [number 1];", " [keyword else]", " [number 2];", " [keyword else]", " [number 3];"); MT("indent_funarg", "[variable foo]([number 10000],", " [keyword function]([def a]) {", " [keyword debugger];", "};"); MT("indent_below_if", "[keyword for] (;;)", " [keyword if] ([variable foo])", " [number 1];", "[number 2];"); MT("multilinestring", "[keyword var] [variable x] [operator =] [string 'foo\\]", "[string bar'];"); MT("scary_regexp", "[string-2 /foo[[/]]bar/];"); MT("indent_strange_array", "[keyword var] [variable x] [operator =] [[", " [number 1],,", " [number 2],", "]];", "[number 10];"); var jsonld_mode = CodeMirror.getMode( {indentUnit: 2}, {name: "javascript", jsonld: true} ); function LD(name) { test.mode(name, jsonld_mode, Array.prototype.slice.call(arguments, 1)); } LD("json_ld_keywords", '{', ' [meta "@context"]: {', ' [meta "@base"]: [string "http://example.com"],', ' [meta "@vocab"]: [string "http://xmlns.com/foaf/0.1/"],', ' [property "likesFlavor"]: {', ' [meta "@container"]: [meta "@list"]', ' [meta "@reverse"]: [string "@beFavoriteOf"]', ' },', ' [property "nick"]: { [meta "@container"]: [meta "@set"] },', ' [property "nick"]: { [meta "@container"]: [meta "@index"] }', ' },', ' [meta "@graph"]: [[ {', ' [meta "@id"]: [string "http://dbpedia.org/resource/John_Lennon"],', ' [property "name"]: [string "John Lennon"],', ' [property "modified"]: {', ' [meta "@value"]: [string "2010-05-29T14:17:39+02:00"],', ' [meta "@type"]: [string "http://www.w3.org/2001/XMLSchema#dateTime"]', ' }', ' } ]]', '}'); LD("json_ld_fake", '{', ' [property "@fake"]: [string "@fake"],', ' [property "@contextual"]: [string "@identifier"],', ' [property "user@domain.com"]: [string "@graphical"],', ' [property "@ID"]: [string "@@ID"]', '}'); })();
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/javascript/test.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/javascript/test.js", "repo_id": "Humsen", "token_count": 3092 }
38
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../javascript/javascript")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../javascript/javascript"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("pegjs", function (config) { var jsMode = CodeMirror.getMode(config, "javascript"); function identifier(stream) { return stream.match(/^[a-zA-Z_][a-zA-Z0-9_]*/); } return { startState: function () { return { inString: false, stringType: null, inComment: false, inChracterClass: false, braced: 0, lhs: true, localState: null }; }, token: function (stream, state) { if (stream) //check for state changes if (!state.inString && !state.inComment && ((stream.peek() == '"') || (stream.peek() == "'"))) { state.stringType = stream.peek(); stream.next(); // Skip quote state.inString = true; // Update state } if (!state.inString && !state.inComment && stream.match(/^\/\*/)) { state.inComment = true; } //return state if (state.inString) { while (state.inString && !stream.eol()) { if (stream.peek() === state.stringType) { stream.next(); // Skip quote state.inString = false; // Clear flag } else if (stream.peek() === '\\') { stream.next(); stream.next(); } else { stream.match(/^.[^\\\"\']*/); } } return state.lhs ? "property string" : "string"; // Token style } else if (state.inComment) { while (state.inComment && !stream.eol()) { if (stream.match(/\*\//)) { state.inComment = false; // Clear flag } else { stream.match(/^.[^\*]*/); } } return "comment"; } else if (state.inChracterClass) { while (state.inChracterClass && !stream.eol()) { if (!(stream.match(/^[^\]\\]+/) || stream.match(/^\\./))) { state.inChracterClass = false; } } } else if (stream.peek() === '[') { stream.next(); state.inChracterClass = true; return 'bracket'; } else if (stream.match(/^\/\//)) { stream.skipToEnd(); return "comment"; } else if (state.braced || stream.peek() === '{') { if (state.localState === null) { state.localState = jsMode.startState(); } var token = jsMode.token(stream, state.localState); var text = stream.current(); if (!token) { for (var i = 0; i < text.length; i++) { if (text[i] === '{') { state.braced++; } else if (text[i] === '}') { state.braced--; } }; } return token; } else if (identifier(stream)) { if (stream.peek() === ':') { return 'variable'; } return 'variable-2'; } else if (['[', ']', '(', ')'].indexOf(stream.peek()) != -1) { stream.next(); return 'bracket'; } else if (!stream.eatSpace()) { stream.next(); } return null; } }; }, "javascript"); });
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/pegjs/pegjs.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/pegjs/pegjs.js", "repo_id": "Humsen", "token_count": 1679 }
39
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "xml"), mname = "xml"; function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), mname); } MT("matching", "[tag&bracket <][tag top][tag&bracket >]", " text", " [tag&bracket <][tag inner][tag&bracket />]", "[tag&bracket </][tag top][tag&bracket >]"); MT("nonmatching", "[tag&bracket <][tag top][tag&bracket >]", " [tag&bracket <][tag inner][tag&bracket />]", " [tag&bracket </][tag&error tip][tag&bracket&error >]"); MT("doctype", "[meta <!doctype foobar>]", "[tag&bracket <][tag top][tag&bracket />]"); MT("cdata", "[tag&bracket <][tag top][tag&bracket >]", " [atom <![CDATA[foo]", "[atom barbazguh]]]]>]", "[tag&bracket </][tag top][tag&bracket >]"); // HTML tests mode = CodeMirror.getMode({indentUnit: 2}, "text/html"); MT("selfclose", "[tag&bracket <][tag html][tag&bracket >]", " [tag&bracket <][tag link] [attribute rel]=[string stylesheet] [attribute href]=[string \"/foobar\"][tag&bracket >]", "[tag&bracket </][tag html][tag&bracket >]"); MT("list", "[tag&bracket <][tag ol][tag&bracket >]", " [tag&bracket <][tag li][tag&bracket >]one", " [tag&bracket <][tag li][tag&bracket >]two", "[tag&bracket </][tag ol][tag&bracket >]"); MT("valueless", "[tag&bracket <][tag input] [attribute type]=[string checkbox] [attribute checked][tag&bracket />]"); MT("pThenArticle", "[tag&bracket <][tag p][tag&bracket >]", " foo", "[tag&bracket <][tag article][tag&bracket >]bar"); })();
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/xml/test.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/xml/test.js", "repo_id": "Humsen", "token_count": 734 }
40
.cm-s-colorforth.CodeMirror { background: #000000; color: #f8f8f8; } .cm-s-colorforth .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; } .cm-s-colorforth .CodeMirror-guttermarker { color: #FFBD40; } .cm-s-colorforth .CodeMirror-guttermarker-subtle { color: #78846f; } .cm-s-colorforth .CodeMirror-linenumber { color: #bababa; } .cm-s-colorforth .CodeMirror-cursor { border-left: 1px solid white !important; } .cm-s-colorforth span.cm-comment { color: #ededed; } .cm-s-colorforth span.cm-def { color: #ff1c1c; font-weight:bold; } .cm-s-colorforth span.cm-keyword { color: #ffd900; } .cm-s-colorforth span.cm-builtin { color: #00d95a; } .cm-s-colorforth span.cm-variable { color: #73ff00; } .cm-s-colorforth span.cm-string { color: #007bff; } .cm-s-colorforth span.cm-number { color: #00c4ff; } .cm-s-colorforth span.cm-atom { color: #606060; } .cm-s-colorforth span.cm-variable-2 { color: #EEE; } .cm-s-colorforth span.cm-variable-3 { color: #DDD; } .cm-s-colorforth span.cm-property {} .cm-s-colorforth span.cm-operator {} .cm-s-colorforth span.cm-meta { color: yellow; } .cm-s-colorforth span.cm-qualifier { color: #FFF700; } .cm-s-colorforth span.cm-bracket { color: #cc7; } .cm-s-colorforth span.cm-tag { color: #FFBD40; } .cm-s-colorforth span.cm-attribute { color: #FFF700; } .cm-s-colorforth span.cm-error { color: #f00; } .cm-s-colorforth .CodeMirror-selected { background: #333d53 !important; } .cm-s-colorforth span.cm-compilation { background: rgba(255, 255, 255, 0.12); } .cm-s-colorforth .CodeMirror-activeline-background {background: #253540 !important;}
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/colorforth.css/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/colorforth.css", "repo_id": "Humsen", "token_count": 728 }
41
/* Solarized theme for code-mirror http://ethanschoonover.com/solarized */ /* Solarized color pallet http://ethanschoonover.com/solarized/img/solarized-palette.png */ .solarized.base03 { color: #002b36; } .solarized.base02 { color: #073642; } .solarized.base01 { color: #586e75; } .solarized.base00 { color: #657b83; } .solarized.base0 { color: #839496; } .solarized.base1 { color: #93a1a1; } .solarized.base2 { color: #eee8d5; } .solarized.base3 { color: #fdf6e3; } .solarized.solar-yellow { color: #b58900; } .solarized.solar-orange { color: #cb4b16; } .solarized.solar-red { color: #dc322f; } .solarized.solar-magenta { color: #d33682; } .solarized.solar-violet { color: #6c71c4; } .solarized.solar-blue { color: #268bd2; } .solarized.solar-cyan { color: #2aa198; } .solarized.solar-green { color: #859900; } /* Color scheme for code-mirror */ .cm-s-solarized { line-height: 1.45em; color-profile: sRGB; rendering-intent: auto; } .cm-s-solarized.cm-s-dark { color: #839496; background-color: #002b36; text-shadow: #002b36 0 1px; } .cm-s-solarized.cm-s-light { background-color: #fdf6e3; color: #657b83; text-shadow: #eee8d5 0 1px; } .cm-s-solarized .CodeMirror-widget { text-shadow: none; } .cm-s-solarized .cm-keyword { color: #cb4b16 } .cm-s-solarized .cm-atom { color: #d33682; } .cm-s-solarized .cm-number { color: #d33682; } .cm-s-solarized .cm-def { color: #2aa198; } .cm-s-solarized .cm-variable { color: #268bd2; } .cm-s-solarized .cm-variable-2 { color: #b58900; } .cm-s-solarized .cm-variable-3 { color: #6c71c4; } .cm-s-solarized .cm-property { color: #2aa198; } .cm-s-solarized .cm-operator {color: #6c71c4;} .cm-s-solarized .cm-comment { color: #586e75; font-style:italic; } .cm-s-solarized .cm-string { color: #859900; } .cm-s-solarized .cm-string-2 { color: #b58900; } .cm-s-solarized .cm-meta { color: #859900; } .cm-s-solarized .cm-qualifier { color: #b58900; } .cm-s-solarized .cm-builtin { color: #d33682; } .cm-s-solarized .cm-bracket { color: #cb4b16; } .cm-s-solarized .CodeMirror-matchingbracket { color: #859900; } .cm-s-solarized .CodeMirror-nonmatchingbracket { color: #dc322f; } .cm-s-solarized .cm-tag { color: #93a1a1 } .cm-s-solarized .cm-attribute { color: #2aa198; } .cm-s-solarized .cm-header { color: #586e75; } .cm-s-solarized .cm-quote { color: #93a1a1; } .cm-s-solarized .cm-hr { color: transparent; border-top: 1px solid #586e75; display: block; } .cm-s-solarized .cm-link { color: #93a1a1; cursor: pointer; } .cm-s-solarized .cm-special { color: #6c71c4; } .cm-s-solarized .cm-em { color: #999; text-decoration: underline; text-decoration-style: dotted; } .cm-s-solarized .cm-strong { color: #eee; } .cm-s-solarized .cm-error, .cm-s-solarized .cm-invalidchar { color: #586e75; border-bottom: 1px dotted #dc322f; } .cm-s-solarized.cm-s-dark .CodeMirror-selected { background: #073642; } .cm-s-solarized.cm-s-dark.CodeMirror ::selection { background: rgba(7, 54, 66, 0.99); } .cm-s-solarized.cm-s-dark.CodeMirror ::-moz-selection { background: rgba(7, 54, 66, 0.99); } .cm-s-solarized.cm-s-light .CodeMirror-selected { background: #eee8d5; } .cm-s-solarized.cm-s-light.CodeMirror ::selection { background: #eee8d5; } .cm-s-solarized.cm-s-lightCodeMirror ::-moz-selection { background: #eee8d5; } /* Editor styling */ /* Little shadow on the view-port of the buffer view */ .cm-s-solarized.CodeMirror { -moz-box-shadow: inset 7px 0 12px -6px #000; -webkit-box-shadow: inset 7px 0 12px -6px #000; box-shadow: inset 7px 0 12px -6px #000; } /* Gutter border and some shadow from it */ .cm-s-solarized .CodeMirror-gutters { border-right: 1px solid; } /* Gutter colors and line number styling based of color scheme (dark / light) */ /* Dark */ .cm-s-solarized.cm-s-dark .CodeMirror-gutters { background-color: #002b36; border-color: #00232c; } .cm-s-solarized.cm-s-dark .CodeMirror-linenumber { text-shadow: #021014 0 -1px; } /* Light */ .cm-s-solarized.cm-s-light .CodeMirror-gutters { background-color: #fdf6e3; border-color: #eee8d5; } /* Common */ .cm-s-solarized .CodeMirror-linenumber { color: #586e75; padding: 0 5px; } .cm-s-solarized .CodeMirror-guttermarker-subtle { color: #586e75; } .cm-s-solarized.cm-s-dark .CodeMirror-guttermarker { color: #ddd; } .cm-s-solarized.cm-s-light .CodeMirror-guttermarker { color: #cb4b16; } .cm-s-solarized .CodeMirror-gutter .CodeMirror-gutter-text { color: #586e75; } .cm-s-solarized .CodeMirror-lines .CodeMirror-cursor { border-left: 1px solid #819090; } /* Active line. Negative margin compensates left padding of the text in the view-port */ .cm-s-solarized.cm-s-dark .CodeMirror-activeline-background { background: rgba(255, 255, 255, 0.10); } .cm-s-solarized.cm-s-light .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0.10); }
Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/solarized.css/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/solarized.css", "repo_id": "Humsen", "token_count": 2149 }
42
/*! * Code block dialog plugin for Editor.md * * @file code-block-dialog.js * @author pandao * @version 1.2.0 * @updateTime 2015-03-07 * {@link https://github.com/pandao/editor.md} * @license MIT */ (function() { var factory = function (exports) { var cmEditor; var pluginName = "code-block-dialog"; // for CodeBlock dialog select var codeLanguages = exports.codeLanguages = { asp : ["ASP", "vbscript"], actionscript : ["ActionScript(3.0)/Flash/Flex", "clike"], bash : ["Bash/Bat", "shell"], css : ["CSS", "css"], c : ["C", "clike"], cpp : ["C++", "clike"], csharp : ["C#", "clike"], coffeescript : ["CoffeeScript", "coffeescript"], d : ["D", "d"], dart : ["Dart", "dart"], delphi : ["Delphi/Pascal", "pascal"], erlang : ["Erlang", "erlang"], go : ["Golang", "go"], groovy : ["Groovy", "groovy"], html : ["HTML", "text/html"], java : ["Java", "clike"], json : ["JSON", "text/json"], javascript : ["Javascript", "javascript"], lua : ["Lua", "lua"], less : ["LESS", "css"], markdown : ["Markdown", "gfm"], "objective-c" : ["Objective-C", "clike"], php : ["PHP", "php"], perl : ["Perl", "perl"], python : ["Python", "python"], r : ["R", "r"], rst : ["reStructedText", "rst"], ruby : ["Ruby", "ruby"], sql : ["SQL", "sql"], sass : ["SASS/SCSS", "sass"], shell : ["Shell", "shell"], scala : ["Scala", "clike"], swift : ["Swift", "clike"], vb : ["VB/VBScript", "vb"], xml : ["XML", "text/xml"], yaml : ["YAML", "yaml"] }; exports.fn.codeBlockDialog = function() { var _this = this; var cm = this.cm; var lang = this.lang; var editor = this.editor; var settings = this.settings; var cursor = cm.getCursor(); var selection = cm.getSelection(); var classPrefix = this.classPrefix; var dialogName = classPrefix + pluginName, dialog; var dialogLang = lang.dialog.codeBlock; cm.focus(); if (editor.find("." + dialogName).length > 0) { dialog = editor.find("." + dialogName); dialog.find("option:first").attr("selected", "selected"); dialog.find("textarea").val(selection); this.dialogShowMask(dialog); this.dialogLockScreen(); dialog.show(); } else { var dialogHTML = "<div class=\"" + classPrefix + "code-toolbar\">" + dialogLang.selectLabel + "<select><option selected=\"selected\" value=\"\">" + dialogLang.selectDefaultText + "</option></select>" + "</div>" + "<textarea placeholder=\"coding now....\" style=\"display:none;\">" + selection + "</textarea>"; dialog = this.createDialog({ name : dialogName, title : dialogLang.title, width : 780, height : 565, mask : settings.dialogShowMask, drag : settings.dialogDraggable, content : dialogHTML, lockScreen : settings.dialogLockScreen, maskStyle : { opacity : settings.dialogMaskOpacity, backgroundColor : settings.dialogMaskBgColor }, buttons : { enter : [lang.buttons.enter, function() { var codeTexts = this.find("textarea").val(); var langName = this.find("select").val(); if (langName === "") { alert(lang.dialog.codeBlock.unselectedLanguageAlert); return false; } if (codeTexts === "") { alert(lang.dialog.codeBlock.codeEmptyAlert); return false; } langName = (langName === "other") ? "" : langName; cm.replaceSelection(["```" + langName, codeTexts, "```"].join("\n")); if (langName === "") { cm.setCursor(cursor.line, cursor.ch + 3); } this.hide().lockScreen(false).hideMask(); return false; }], cancel : [lang.buttons.cancel, function() { this.hide().lockScreen(false).hideMask(); return false; }] } }); } var langSelect = dialog.find("select"); if (langSelect.find("option").length === 1) { for (var key in codeLanguages) { var codeLang = codeLanguages[key]; langSelect.append("<option value=\"" + key + "\" mode=\"" + codeLang[1] + "\">" + codeLang[0] + "</option>"); } langSelect.append("<option value=\"other\">" + dialogLang.otherLanguage + "</option>"); } var mode = langSelect.find("option:selected").attr("mode"); var cmConfig = { mode : (mode) ? mode : "text/html", theme : settings.theme, tabSize : 4, autofocus : true, autoCloseTags : true, indentUnit : 4, lineNumbers : true, lineWrapping : true, extraKeys : {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }}, foldGutter : true, gutters : ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], matchBrackets : true, indentWithTabs : true, styleActiveLine : true, styleSelectedText : true, autoCloseBrackets : true, showTrailingSpace : true, highlightSelectionMatches : true }; var textarea = dialog.find("textarea"); var cmObj = dialog.find(".CodeMirror"); if (dialog.find(".CodeMirror").length < 1) { cmEditor = exports.$CodeMirror.fromTextArea(textarea[0], cmConfig); cmObj = dialog.find(".CodeMirror"); cmObj.css({ "float" : "none", margin : "8px 0", border : "1px solid #ddd", fontSize : settings.fontSize, width : "100%", height : "390px" }); cmEditor.on("change", function(cm) { textarea.val(cm.getValue()); }); } else { cmEditor.setValue(cm.getSelection()); } langSelect.change(function(){ var _mode = $(this).find("option:selected").attr("mode"); cmEditor.setOption("mode", _mode); }); }; }; // CommonJS/Node.js if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { module.exports = factory; } else if (typeof define === "function") // AMD/CMD/Sea.js { if (define.amd) { // for Require.js define(["editormd"], function(editormd) { factory(editormd); }); } else { // for Sea.js define(function(require) { var editormd = require("./../../editormd"); factory(editormd); }); } } else { factory(window.editormd); } })();
Humsen/web/web-mobile/WebContent/plugins/editormd/plugins/code-block-dialog/code-block-dialog.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/plugins/code-block-dialog/code-block-dialog.js", "repo_id": "Humsen", "token_count": 4456 }
43
/*! * Preformatted text dialog plugin for Editor.md * * @file preformatted-text-dialog.js * @author pandao * @version 1.2.0 * @updateTime 2015-03-07 * {@link https://github.com/pandao/editor.md} * @license MIT */ (function() { var factory = function (exports) { var cmEditor; var pluginName = "preformatted-text-dialog"; exports.fn.preformattedTextDialog = function() { var _this = this; var cm = this.cm; var lang = this.lang; var editor = this.editor; var settings = this.settings; var cursor = cm.getCursor(); var selection = cm.getSelection(); var classPrefix = this.classPrefix; var dialogLang = lang.dialog.preformattedText; var dialogName = classPrefix + pluginName, dialog; cm.focus(); if (editor.find("." + dialogName).length > 0) { dialog = editor.find("." + dialogName); dialog.find("textarea").val(selection); this.dialogShowMask(dialog); this.dialogLockScreen(); dialog.show(); } else { var dialogContent = "<textarea placeholder=\"coding now....\" style=\"display:none;\">" + selection + "</textarea>"; dialog = this.createDialog({ name : dialogName, title : dialogLang.title, width : 780, height : 540, mask : settings.dialogShowMask, drag : settings.dialogDraggable, content : dialogContent, lockScreen : settings.dialogLockScreen, maskStyle : { opacity : settings.dialogMaskOpacity, backgroundColor : settings.dialogMaskBgColor }, buttons : { enter : [lang.buttons.enter, function() { var codeTexts = this.find("textarea").val(); if (codeTexts === "") { alert(dialogLang.emptyAlert); return false; } codeTexts = codeTexts.split("\n"); for (var i in codeTexts) { codeTexts[i] = " " + codeTexts[i]; } codeTexts = codeTexts.join("\n"); if (cursor.ch !== 0) { codeTexts = "\r\n\r\n" + codeTexts; } cm.replaceSelection(codeTexts); this.hide().lockScreen(false).hideMask(); return false; }], cancel : [lang.buttons.cancel, function() { this.hide().lockScreen(false).hideMask(); return false; }] } }); } var cmConfig = { mode : "text/html", theme : settings.theme, tabSize : 4, autofocus : true, autoCloseTags : true, indentUnit : 4, lineNumbers : true, lineWrapping : true, extraKeys : {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }}, foldGutter : true, gutters : ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], matchBrackets : true, indentWithTabs : true, styleActiveLine : true, styleSelectedText : true, autoCloseBrackets : true, showTrailingSpace : true, highlightSelectionMatches : true }; var textarea = dialog.find("textarea"); var cmObj = dialog.find(".CodeMirror"); if (dialog.find(".CodeMirror").length < 1) { cmEditor = exports.$CodeMirror.fromTextArea(textarea[0], cmConfig); cmObj = dialog.find(".CodeMirror"); cmObj.css({ "float" : "none", margin : "0 0 5px", border : "1px solid #ddd", fontSize : settings.fontSize, width : "100%", height : "410px" }); cmEditor.on("change", function(cm) { textarea.val(cm.getValue()); }); } else { cmEditor.setValue(cm.getSelection()); } }; }; // CommonJS/Node.js if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { module.exports = factory; } else if (typeof define === "function") // AMD/CMD/Sea.js { if (define.amd) { // for Require.js define(["editormd"], function(editormd) { factory(editormd); }); } else { // for Sea.js define(function(require) { var editormd = require("./../../editormd"); factory(editormd); }); } } else { factory(window.editormd); } })();
Humsen/web/web-mobile/WebContent/plugins/editormd/plugins/preformatted-text-dialog/preformatted-text-dialog.js/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/plugins/preformatted-text-dialog/preformatted-text-dialog.js", "repo_id": "Humsen", "token_count": 3149 }
44
/* * jQuery FlexSlider v2.6.0 * http://www.woothemes.com/flexslider/ * * Copyright 2012 WooThemes * Free to use under the GPLv2 and later license. * http://www.gnu.org/licenses/gpl-2.0.html * * Contributing author: Tyler Smith (@mbmufffin) * */ /* ==================================================================================================================== * FONT-FACE * ====================================================================================================================*/ /*@font-face { font-family: 'flexslider-icon'; src: url('fonts/flexslider-icon.eot'); src: url('fonts/flexslider-icon.eot?#iefix') format('embedded-opentype'), url('fonts/flexslider-icon.woff') format('woff'), url('fonts/flexslider-icon.ttf') format('truetype'), url('fonts/flexslider-icon.svg#flexslider-icon') format('svg'); font-weight: normal; font-style: normal; }*/ /* ==================================================================================================================== * RESETS * ====================================================================================================================*/ .flex-container a:hover, .flex-slider a:hover { outline: none; } .slides, .slides > li, .flex-control-nav, .flex-direction-nav { margin: 0; padding: 0; list-style: none; } .flex-pauseplay span { text-transform: capitalize; } /* ==================================================================================================================== * BASE STYLES * ====================================================================================================================*/ .flexslider { margin: 0; padding: 0; } .flexslider .slides > li { display: none; -webkit-backface-visibility: hidden; } .flexslider .slides img { width: 100%; display: block; } .flexslider .slides:after { /*content: "\0020";*/ display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } html[xmlns] .flexslider .slides { display: block; } * html .flexslider .slides { height: 1%; } .no-js .flexslider .slides > li:first-child { display: block; } /* ==================================================================================================================== * DEFAULT THEME * ====================================================================================================================*/ .flexslider { margin: 0 0 60px; background: #ffffff; border: 4px solid #ffffff; position: relative; zoom: 1; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: '' 0 1px 4px rgba(0, 0, 0, 0.2); -moz-box-shadow: '' 0 1px 4px rgba(0, 0, 0, 0.2); -o-box-shadow: '' 0 1px 4px rgba(0, 0, 0, 0.2); box-shadow: '' 0 1px 4px rgba(0, 0, 0, 0.2); } .flexslider .slides { zoom: 1; } .flexslider .slides img { height: auto; -moz-user-select: none; } .flex-viewport { max-height: 2000px; -webkit-transition: all 1s ease; -moz-transition: all 1s ease; -ms-transition: all 1s ease; -o-transition: all 1s ease; transition: all 1s ease; } .loading .flex-viewport { max-height: 300px; } .carousel li { margin-right: 5px; } .flex-direction-nav { *height: 0; } .flex-direction-nav a { text-decoration: none; display: block; width: 40px; height: 40px; margin: -20px 0 0; position: absolute; top: 50%; z-index: 10; overflow: hidden; opacity: 0; cursor: pointer; color: rgba(0, 0, 0, 0.8); text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.3); -webkit-transition: all 0.3s ease-in-out; -moz-transition: all 0.3s ease-in-out; -ms-transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; } .flex-direction-nav a:before { font-family: "flexslider-icon"; font-size: 40px; display: inline-block; content: '\f001'; color: rgba(0, 0, 0, 0.8); text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.3); } .flex-direction-nav a.flex-next:before { content: '\f002'; } .flex-direction-nav .flex-prev { left: -50px; } .flex-direction-nav .flex-next { right: -50px; text-align: right; } .flexslider:hover .flex-direction-nav .flex-prev { opacity: 0.7; left: 10px; } .flexslider:hover .flex-direction-nav .flex-prev:hover { opacity: 1; } .flexslider:hover .flex-direction-nav .flex-next { opacity: 0.7; right: 10px; } .flexslider:hover .flex-direction-nav .flex-next:hover { opacity: 1; } .flex-direction-nav .flex-disabled { opacity: 0!important; filter: alpha(opacity=0); cursor: default; z-index: -1; } .flex-pauseplay a { display: block; width: 20px; height: 20px; position: absolute; bottom: 5px; left: 10px; opacity: 0.8; z-index: 10; overflow: hidden; cursor: pointer; color: #000; } .flex-pauseplay a:before { font-family: "flexslider-icon"; font-size: 20px; display: inline-block; content: '\f004'; } .flex-pauseplay a:hover { opacity: 1; } .flex-pauseplay a.flex-play:before { content: '\f003'; } .flex-control-nav { width: 100%; position: absolute; bottom: -40px; text-align: center; } .flex-control-nav li { margin: 0 6px; display: inline-block; zoom: 1; *display: inline; } .flex-control-paging li a { width: 11px; height: 11px; display: block; background: #666; background: rgba(0, 0, 0, 0.5); cursor: pointer; text-indent: -9999px; -webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3); -moz-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3); -o-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3); box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3); -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; } .flex-control-paging li a:hover { background: #333; background: rgba(0, 0, 0, 0.7); } .flex-control-paging li a.flex-active { background: #000; background: rgba(0, 0, 0, 0.9); cursor: default; } .flex-control-thumbs { margin: 5px 0 0; position: static; overflow: hidden; } .flex-control-thumbs li { width: 25%; float: left; margin: 0; } .flex-control-thumbs img { width: 100%; height: auto; display: block; opacity: .7; cursor: pointer; -moz-user-select: none; -webkit-transition: all 1s ease; -moz-transition: all 1s ease; -ms-transition: all 1s ease; -o-transition: all 1s ease; transition: all 1s ease; } .flex-control-thumbs img:hover { opacity: 1; } .flex-control-thumbs .flex-active { opacity: 1; cursor: default; } /* ==================================================================================================================== * RESPONSIVE * ====================================================================================================================*/ @media screen and (max-width: 860px) { .flex-direction-nav .flex-prev { opacity: 1; left: 10px; } .flex-direction-nav .flex-next { opacity: 1; right: 10px; } }
Humsen/web/web-mobile/WebContent/plugins/template/css/flexslider.css/0
{ "file_path": "Humsen/web/web-mobile/WebContent/plugins/template/css/flexslider.css", "repo_id": "Humsen", "token_count": 2442 }
45
/** * @author 何明胜 * * 2017年12月20日 */ /** 加载插件 * */ $.ajax({ url : '/plugins/plugins.html', async : false, type : 'GET', success : function(data) { $($('head')[0]).find('script:first').after(data); } }); $(function() { /** 顶部导航栏 * */ $.ajax({ url : '/module/navigation/topbar.html', async : false, type : 'GET', success : function(data) { $('#menuBarNo').before(data); } }); /** 登录控制 * */ $.ajax({ url : '/module/login/login.html', async : false, type : 'GET', success : function(data) { $('#menuBarNo').before(data); } }); /** 左侧导航栏 * */ $.ajax({ url : '/module/navigation/leftbar.html', async : false, type : 'GET', success : function(data) { $('#fh5co-main').before(data); } }); /** 右侧导航栏 * */ $.ajax({ url : '/module/navigation/rightbar.html', async : false, type : 'GET', success : function(data) { $('#fh5co-main').after(data); } }); }); $(function() { getJsonData(); }); /** * 加载文章细节 * * @returns */ function getJsonData() { $.ajax({ type : 'POST', async : false, url : '/code.hms', dataType : 'json', data : { codeId : $.getUrlParam('codeId') ? $.getUrlParam('codeId') : 0, type : 'json_return', }, success : function(response) { loadDetail(response) }, error : function(XMLHttpRequest, textStatus) { $.confirm({ title : '查询出错', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); } }); } /** * 加载详细数据 * * @param data * @returns */ function loadDetail(data) { var codeBody = '<div>' + '<h2 class="text-align-center"><input id="hiden_codeId" type="hidden" value="' + data.codeId + '" />' + '<a href=#>' + data.codeTitle + '</a>' + '</h2>' + ' <span class="fh5co-post-date">' + new Date(data.codeDate.time).format('yyyy-MM-dd hh:mm:ss') + '</span>' + ' <span class="fh5co-post-date">作者:' + data.userNickName + '</span>' + ' <span class="fh5co-post-date">浏览' + data.codeRead + '次</span>' + ' <span class="fh5co-post-date">关键字:' + keywordsProcess(data.codeLabel) + '</span>'; if (isSuperAdminOrSelf(data.codeAuthor)) { codeBody += '<a href="/editor/article.hms?codeId=' + data.codeId + '" target="_blank" role="button" class="btn btn-default btn-sm">编辑</a> ' + '<a id="btn_deleteCode" href="javascript:void(0)" role="button" class="btn btn-danger btn-sm">删除</a>'; } codeBody += '<p>' + data.codeHtmlContent + "</p>" + '</div>'; $('#content').append(codeBody); loadBtnNeighbors(data.codeId); } /** * 是否是管理员 * * @returns */ function isSuperAdminOrSelf(author) { if ($.cookie('username') == 'husen') { return true; } if ($.cookie('username') == author) { return true; } return false; } /** * 文章标签处理 * * @param blogLabel * @returns */ function keywordsProcess(codeLabel) { var keyWordsStrBuf = []; var colorArray = ["primary" , "success", "info", "warning", "danger"]; if (typeof codeLabel != 'undefined' && codeLabel != "") { var keyWordsArray; if (codeLabel.indexOf(',') != -1) { keyWordsArray = codeLabel.split(","); } else { keyWordsArray = codeLabel.split(/\s+/); } for (var index = 0; index < keyWordsArray.length; index++) { keyWordsStrBuf += '<span class="label label-' + colorArray[index] + '">' + keyWordsArray[index].trim() + '</span> '; } } return keyWordsStrBuf; } /** * 加载上下两篇按钮 * * @returns */ function loadBtnNeighbors(codeId) { var neighbors = '<nav>' + ' <ul class="pager">' + findPreviousCode(codeId) + findNextCode(codeId) + '</ul>' + '</nav>'; $('#content').prepend(neighbors); } /** * 查找上一篇代码 * @param codeId * @returns */ function findPreviousCode(codeId) { var previousCode = 0; $ .ajax({ type : 'POST', async : false, url : '/code/query.hms', dataType : 'json', data : { type : 'query_previous', codeId : codeId }, success : function(response) { if (response != 0) { previousCode = '<li class="previous"><a href="/code.hms?codeId=' + response + '"><span class="glyphicon glyphicon-hand-left" aria-hidden="true"></span> 上一篇</a></li>'; }else { previousCode = '<li class="previous disabled"><a href="#"><span class="glyphicon glyphicon-hand-left" aria-hidden="true"></span> 上一篇</a></li>'; } }, error : function(XMLHttpRequest, textStatus) { $.confirm({ title : '查询出错', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); } }); return previousCode; } /** * 查找下一篇代码 * @param codeId * @returns */ function findNextCode(codeId) { var nextCode = 0; $ .ajax({ type : 'POST', async : false, url : '/code/query.hms', dataType : 'json', data : { type : 'query_next', codeId : codeId }, success : function(response) { if (response != 0) { nextCode = '<li class="next"><a href="/code.hms?codeId=' + response + '">下一篇 <span class="glyphicon glyphicon-hand-right" aria-hidden="true"></span></a></li>'; }else { nextCode = '<li class="next disabled"><a href="#">下一篇 <span class="glyphicon glyphicon-hand-right" aria-hidden="true"></span></a></li>'; } }, error : function(XMLHttpRequest, textStatus) { $.confirm({ title : '查询出错', content : textStatus + ' : ' + XMLHttpRequest.status, autoClose : 'ok|2000', type : 'red', buttons : { ok : { text : '确认', btnClass : 'btn-primary', }, } }); } }); return nextCode; }
Humsen/web/web-pc/WebContent/js/article/code-template.js/0
{ "file_path": "Humsen/web/web-pc/WebContent/js/article/code-template.js", "repo_id": "Humsen", "token_count": 2843 }
46
<link rel="stylesheet" href="/css/personal_center/modify-email.css"> <!-- 修改用户密码脚本 --> <script src="/js/personal_center/modify-email.js"></script> <form id="form_modifyEmail" class="form-horizontal modify-email-form"> <div class="form-group"> <label class="col-sm-3 control-label" for="txt_modifyEmail">新邮箱</label> <div class="col-sm-6"> <input type="text" class="form-control form-div-input" id="txt_modifyEmail" name="email" placeholder="请输入新的邮箱"> </div> </div> <div class="form-group"> <label for="txt_validateCode2" class="col-sm-3 control-label">验证码</label> <div class="col-sm-4" > <input type="text" class="form-control" id="txt_validateCode2" name="validateCode" placeholder="请输入验证码"> </div> <button id="btn_sendValidateCode" type="button" class="btn btn-default">获取验证码</button> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-2"> <a id="btn_modifyEmailBind" class="btn btn-default" href="#" role="button">提交</a> </div> </div> </form>
Humsen/web/web-pc/WebContent/personal_center/modify_email1.html/0
{ "file_path": "Humsen/web/web-pc/WebContent/personal_center/modify_email1.html", "repo_id": "Humsen", "token_count": 476 }
47
/* * Styling for DataTables with Semantic UI */ table.dataTable.table { margin: 0; } table.dataTable.table thead th, table.dataTable.table thead td { position: relative; } table.dataTable.table thead th.sorting, table.dataTable.table thead th.sorting_asc, table.dataTable.table thead th.sorting_desc, table.dataTable.table thead td.sorting, table.dataTable.table thead td.sorting_asc, table.dataTable.table thead td.sorting_desc { padding-right: 20px; } table.dataTable.table thead th.sorting:after, table.dataTable.table thead th.sorting_asc:after, table.dataTable.table thead th.sorting_desc:after, table.dataTable.table thead td.sorting:after, table.dataTable.table thead td.sorting_asc:after, table.dataTable.table thead td.sorting_desc:after { position: absolute; top: 12px; right: 8px; display: block; font-family: Icons; } table.dataTable.table thead th.sorting:after, table.dataTable.table thead td.sorting:after { content: "\f0dc"; color: #ddd; font-size: 0.8em; } table.dataTable.table thead th.sorting_asc:after, table.dataTable.table thead td.sorting_asc:after { content: "\f0de"; } table.dataTable.table thead th.sorting_desc:after, table.dataTable.table thead td.sorting_desc:after { content: "\f0dd"; } table.dataTable.table td, table.dataTable.table th { -webkit-box-sizing: content-box; box-sizing: content-box; } table.dataTable.table td.dataTables_empty, table.dataTable.table th.dataTables_empty { text-align: center; } table.dataTable.table.nowrap th, table.dataTable.table.nowrap td { white-space: nowrap; } div.dataTables_wrapper div.dataTables_length select { vertical-align: middle; min-height: 2.7142em; } div.dataTables_wrapper div.dataTables_length .ui.selection.dropdown { min-width: 0; } div.dataTables_wrapper div.dataTables_filter input { margin-left: 0.5em; } div.dataTables_wrapper div.dataTables_info { padding-top: 13px; white-space: nowrap; } div.dataTables_wrapper div.dataTables_processing { position: absolute; top: 50%; left: 50%; width: 200px; margin-left: -100px; text-align: center; } div.dataTables_wrapper div.row.dt-table { padding: 0; } div.dataTables_wrapper div.dataTables_scrollHead table.dataTable { border-bottom-right-radius: 0; border-bottom-left-radius: 0; border-bottom: none; } div.dataTables_wrapper div.dataTables_scrollBody thead .sorting:after, div.dataTables_wrapper div.dataTables_scrollBody thead .sorting_asc:after, div.dataTables_wrapper div.dataTables_scrollBody thead .sorting_desc:after { display: none; } div.dataTables_wrapper div.dataTables_scrollBody table.dataTable { border-radius: 0; border-top: none; border-bottom-width: 0; } div.dataTables_wrapper div.dataTables_scrollBody table.dataTable.no-footer { border-bottom-width: 1px; } div.dataTables_wrapper div.dataTables_scrollFoot table.dataTable { border-top-right-radius: 0; border-top-left-radius: 0; border-top: none; }
Humsen/web/web-pc/WebContent/plugins/DataTables/css/dataTables.semanticui.css/0
{ "file_path": "Humsen/web/web-pc/WebContent/plugins/DataTables/css/dataTables.semanticui.css", "repo_id": "Humsen", "token_count": 1084 }
48
/** * BootstrapValidator (http://bootstrapvalidator.com) * The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3 * * @author http://twitter.com/nghuuphuoc * @copyright (c) 2013 - 2014 Nguyen Huu Phuoc * @license Commercial: http://bootstrapvalidator.com/license/ * Non-commercial: http://creativecommons.org/licenses/by-nc-nd/3.0/ */ .bv-form .help-block { margin-bottom: 0; } .bv-form .tooltip-inner { text-align: left; } .nav-tabs li.bv-tab-success > a { color: #3c763d; } .nav-tabs li.bv-tab-error > a { color: #a94442; } .bv-form .bv-icon-no-label { top: 0; } .bv-form .bv-icon-input-group { top: 0; z-index: 100; }
Humsen/web/web-pc/WebContent/plugins/validator/css/bootstrapValidator.css/0
{ "file_path": "Humsen/web/web-pc/WebContent/plugins/validator/css/bootstrapValidator.css", "repo_id": "Humsen", "token_count": 309 }
49
(function($) { /** * Greek language package * Translated by @pRieStaKos */ $.fn.bootstrapValidator.i18n = $.extend(true, $.fn.bootstrapValidator.i18n, { base64: { 'default': 'Παρακαλώ εισάγετε μια έγκυρη κωδικοποίηση base 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': 'Παρακαλώ εισάγετε ένα έγκυρο email' }, file: { 'default': 'Παρακαλώ επιλέξτε ένα έγκυρο αρχείο' }, greaterThan: { 'default': 'Παρακαλώ εισάγετε μια τιμή μεγαλύτερη ή ίση με %s', notInclusive: 'Παρακαλώ εισάγετε μια τιμή μεγαλύτερη από %s' }, grid: { 'default': 'Παρακαλώ εισάγετε έναν έγκυρο αριθμό GRId' }, hex: { 'default': 'Παρακαλώ εισάγετε έναν έγκυρο δεκαεξαδικό αριθμό' }, hexColor: { 'default': 'Παρακαλώ εισάγετε ένα έγκυρο χρώμα hex' }, 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: 'Cape Verde', 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: 'Παρακαλώ εισάγετε ένα έγκυρο αριθμό έκδοσης %s' }, vat: { 'default': 'Παρακαλώ εισάγετε ένα έγκυρο αριθμό ΦΠΑ', countryNotSupported: 'Ο κωδικός χώρας %s δεν υποστηρίζεται', country: 'Παρακαλώ εισάγετε ένα έγκυρο αριθμό ΦΠΑ στην %s', 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-pc/WebContent/plugins/validator/js/language/gr_EL.js/0
{ "file_path": "Humsen/web/web-pc/WebContent/plugins/validator/js/language/gr_EL.js", "repo_id": "Humsen", "token_count": 11596 }
50
(function($) { /** * Thai language package * Translated by @figgaro */ $.fn.bootstrapValidator.i18n = $.extend(true, $.fn.bootstrapValidator.i18n, { base64: { 'default': 'กรุณาระบุ base 64 encoded ให้ถูกต้อง' }, between: { 'default': 'กรุณาระบุค่าระหว่าง %s และ %s', notInclusive: 'กรุณาระบุค่าระหว่าง %s และ %s เท่านั้น' }, callback: { 'default': 'กรุณาระบุค่าให้ถูก' }, choice: { 'default': 'กรุณาระบุค่าให้ถูกต้อง', less: 'โปรดเลือกตัวเลือก %s ที่ต่ำสุด', more: 'โปรดเลือกตัวเลือก %s ที่สูงสุด', between: 'กรุณาเลือก %s - %s ที่มีอยู่' }, color: { 'default': 'กรุณาระบุค่าสี color ให้ถูกต้อง' }, 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': 'กรุณาระบุค่าสี hex color ให้ถูกต้อง' }, 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: 'Liechtenstein', 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 address ให้ถูกต้อง', ipv4: 'โปรดระบุ IPv4 address ให้ถูกต้อง', ipv6: 'โปรดระบุ IPv6 address ให้ถูกต้อง' }, isbn: { 'default': 'โปรดระบุหมายเลข ISBN ให้ถูกต้อง' }, isin: { 'default': 'โปรดระบุหมายเลข ISIN ให้ถูกต้อง' }, ismn: { 'default': 'โปรดระบุหมายเลข ISMN ให้ถูกต้อง' }, issn: { 'default': 'โปรดระบุหมายเลข ISSN ให้ถูกต้อง' }, lessThan: { 'default': 'โปรดระบุค่าน้อยกว่าหรือเท่ากับ %s', notInclusive: 'โปรดระบุค่าน้อยกว่า %s' }, mac: { 'default': 'โปรดระบุหมายเลข MAC address ให้ถูกต้อง' }, 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': 'โปรดระบุจำนวนภาษีมูลค่าเพิ่ม', countryNotSupported: 'ประเทศ %s ไม่รองรับ', country: 'โปรดระบุจำนวนภาษีมูลค่าเพิ่มใน %s', 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-pc/WebContent/plugins/validator/js/language/th_TH.js/0
{ "file_path": "Humsen/web/web-pc/WebContent/plugins/validator/js/language/th_TH.js", "repo_id": "Humsen", "token_count": 13091 }
51
#发送邮箱 email.from.user=123@qq.com email.from.password=123456 #接收邮箱 email.to.user=123@qq.com
Humsen/web/web-pc/config/config_template.properties/0
{ "file_path": "Humsen/web/web-pc/config/config_template.properties", "repo_id": "Humsen", "token_count": 58 }
52
# Translation of Odoo Server. # This file contains the translation of the following modules: # * web_advanced_search_x2x # # Translators: # Peter Hageman <hageman.p@gmail.com>, 2017 msgid "" msgstr "" "Project-Id-Version: Odoo Server 10.0\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2018-01-03 03:49+0000\n" "PO-Revision-Date: 2023-05-05 11:22+0000\n" "Last-Translator: Bosd <c5e2fd43-d292-4c90-9d1f-74ff3436329a@anonaddy.me>\n" "Language-Team: Dutch (Netherlands) (https://www.transifex.com/oca/" "teams/23907/nl_NL/)\n" "Language: nl_NL\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: \n" "Plural-Forms: nplurals=2; plural=n != 1;\n" "X-Generator: Weblate 4.14.1\n" #. module: web_advanced_search #. odoo-javascript #: code:addons/web_advanced_search/static/src/js/utils.esm.js:0 #, python-format msgid " and " msgstr " en " #. module: web_advanced_search #. odoo-javascript #: code:addons/web_advanced_search/static/src/js/utils.esm.js:0 #, python-format msgid " is not " msgstr " is niet " #. module: web_advanced_search #. odoo-javascript #: code:addons/web_advanced_search/static/src/js/utils.esm.js:0 #, python-format msgid " or " msgstr " of " #. module: web_advanced_search #. odoo-javascript #: code:addons/web_advanced_search/static/src/search/filter_menu/advanced_filter_item.xml:0 #, python-format msgid "Add Advanced Filter" msgstr "Voeg geavanceerde filter toe" #~ msgid "is in selection" #~ msgstr "Is in selectie"
OCA/web/web_advanced_search/i18n/nl_NL.po/0
{ "file_path": "OCA/web/web_advanced_search/i18n/nl_NL.po", "repo_id": "OCA", "token_count": 623 }
53
/** @odoo-module **/ /* Copyright 2018 Tecnativa - Jairo Llopis Copyright 2020 Tecnativa - Alexandre Díaz Copyright 2022 Camptocamp SA - Iván Todorovich License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). */ import {_t} from "web.core"; const JOIN_MAPPING = { "&": _t(" and "), "|": _t(" or "), "!": _t(" is not "), }; const HUMAN_DOMAIN_METHODS = { DomainTree: function () { const human_domains = []; _.each(this.children, (child) => { human_domains.push(HUMAN_DOMAIN_METHODS[child.template].apply(child)); }); return `(${human_domains.join(JOIN_MAPPING[this.operator])})`; }, DomainSelector: function () { const result = HUMAN_DOMAIN_METHODS.DomainTree.apply(this, arguments); // Remove surrounding parenthesis return result.slice(1, -1); }, DomainLeaf: function () { const chain = []; let operator = this.operator_mapping[this.operator], value = `"${this.value}"`; // Humanize chain const chain_splitted = this.chain.split("."); const len = chain_splitted.length; for (let x = 0; x < len; ++x) { const element = chain_splitted[x]; chain.push( _.findWhere(this.fieldSelector.popover.pages[x], {name: element}) .string || element ); } // Special beautiness for some values if (this.operator === "=" && _.isBoolean(this.value)) { operator = this.operator_mapping[this.value ? "set" : "not set"]; value = ""; } else if (_.isArray(this.value)) { value = `["${this.value.join('", "')}"]`; } return `${chain.join("→")} ${operator || this.operator} ${value}`.trim(); }, }; export function getHumanDomain(domainSelector) { return HUMAN_DOMAIN_METHODS.DomainSelector.apply(domainSelector); }
OCA/web/web_advanced_search/static/src/js/utils.esm.js/0
{ "file_path": "OCA/web/web_advanced_search/static/src/js/utils.esm.js", "repo_id": "OCA", "token_count": 868 }
54
# Translation of Odoo Server. # This file contains the translation of the following modules: # * web_chatter_position # msgid "" msgstr "" "Project-Id-Version: Odoo Server 16.0\n" "Report-Msgid-Bugs-To: \n" "PO-Revision-Date: 2023-12-20 02:38+0000\n" "Last-Translator: jappi00 <jappi2000@ewetel.net>\n" "Language-Team: none\n" "Language: de\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: \n" "Plural-Forms: nplurals=2; plural=n != 1;\n" "X-Generator: Weblate 4.17\n" #. module: web_chatter_position #: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__bottom msgid "Bottom" msgstr "Unten" #. module: web_chatter_position #: model:ir.model.fields,field_description:web_chatter_position.field_res_users__chatter_position msgid "Chatter Position" msgstr "Chatter-Position" #. module: web_chatter_position #: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__auto msgid "Responsive" msgstr "Responsiv" #. module: web_chatter_position #: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__sided msgid "Sided" msgstr "Seitlich" #. module: web_chatter_position #: model:ir.model,name:web_chatter_position.model_res_users msgid "User" msgstr "Benutzer"
OCA/web/web_chatter_position/i18n/de.po/0
{ "file_path": "OCA/web/web_chatter_position/i18n/de.po", "repo_id": "OCA", "token_count": 516 }
55
/** @odoo-module **/ /* Copyright 2023 Camptocamp SA (https://www.camptocamp.com). License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). */ import {FormCompiler} from "@web/views/form/form_compiler"; import {FormController} from "@web/views/form/form_controller"; import {MailFormCompiler} from "@mail/views/form/form_compiler"; import {append} from "@web/core/utils/xml"; import {patch} from "@web/core/utils/patch"; /** * So, you've landed here and you have no idea what this is about. Don't worry, you're * not the only one. Here's a quick summary of what's going on: * * In core, the chatter position depends on the size of the screen and wether there is * an attachment viewer or not. There are 3 possible positions, and for each position a * different chatter instance is displayed. * * So, in fact, we have 3 chatter instances running, and we switch their visibility * depending on the desired position. * * A) Bottom position * https://github.com/odoo/odoo/blob/2ef010907/addons/mail/static/src/views/form/form_compiler.js#L160 * Condition: `!this.props.hasAttachmentViewer and uiService.size < ${SIZES.XXL}` * * This is the bottom position you would except. However it can only be there until * XXL screen sizes, because the container is a flexbox and changes from row to * column display. It's hidden in the presence of an attachment viewer. * * B) Bottom In-sheet position * https://github.com/odoo/odoo/blob/2ef010907/addons/mail/static/src/views/form/form_compiler.js#L181 * Condition: `this.props.hasAttachmentViewer` * * This is the bottom position that's used when there's an attachment viewer in place. * It's rendered within the form sheet, possibly to by-pass the flexbox issue * beforementioned. It's only instanciated when there's an attachment viewer. * * C) Sided position * https://github.com/odoo/odoo/blob/2ef010907/addons/mail/static/src/views/form/form_compiler.js#L83 * Condition: `!hasAttachmentViewer() and uiService.size >= ${SIZES.XXL}` * * This is the sided position, hidden in the presence of an attachment viewer. * It's the better half of `A`. * * The patches and overrides you see below are here to alter these conditions to force * a specific position regardless of the screen size, depending on an user setting. */ patch(MailFormCompiler.prototype, "web_chatter_position", { /** * Patch the visibility of the Sided chatter (`C` above). * * @override */ compile() { const res = this._super.apply(this, arguments); const chatterContainerHookXml = res.querySelector( ".o_FormRenderer_chatterContainer" ); if (!chatterContainerHookXml) { return res; } // Don't patch anything if the setting is "auto": this is the core behaviour if (odoo.web_chatter_position === "auto") { return res; } else if (odoo.web_chatter_position === "sided") { chatterContainerHookXml.setAttribute("t-if", "!hasAttachmentViewer()"); } else if (odoo.web_chatter_position === "bottom") { chatterContainerHookXml.setAttribute("t-if", false); } return res; }, }); patch(FormCompiler.prototype, "web_chatter_position", { /** * Patch the css classes of the `Form`, to include an extra `h-100` class. * Without it, the form sheet will not be full height in some situations, * looking a bit weird. * * @override */ compileForm() { const res = this._super.apply(this, arguments); if (odoo.web_chatter_position === "sided") { const classes = res.getAttribute("t-attf-class"); res.setAttribute("t-attf-class", `${classes} h-100`); } return res; }, /** * Patch the visibility of bottom chatters (`A` and `B` above). * `B` may not exist in some situations, so we ensure it does by creating it. * * @override */ compile(node, params) { const res = this._super.apply(this, arguments); const chatterContainerHookXml = res.querySelector( ".o_FormRenderer_chatterContainer:not(.o-isInFormSheetBg)" ); if (!chatterContainerHookXml) { return res; } if (chatterContainerHookXml.parentNode.classList.contains("o_form_sheet")) { return res; } // Don't patch anything if the setting is "auto": this is the core behaviour if (odoo.web_chatter_position === "auto") { return res; // For "sided", we have to remote the bottom chatter // (except if there is an attachment viewer, as we have to force bottom) } else if (odoo.web_chatter_position === "sided") { const formSheetBgXml = res.querySelector(".o_form_sheet_bg"); if (!formSheetBgXml) { return res; } chatterContainerHookXml.setAttribute("t-if", false); // For "bottom", we keep the chatter in the form sheet // (the one used for the attachment viewer case) // If it's not there, we create it. } else if (odoo.web_chatter_position === "bottom") { if (params.hasAttachmentViewerInArch) { const sheetBgChatterContainerHookXml = res.querySelector( ".o_FormRenderer_chatterContainer.o-isInFormSheetBg" ); sheetBgChatterContainerHookXml.setAttribute("t-if", true); chatterContainerHookXml.setAttribute("t-if", false); } else { const formSheetBgXml = res.querySelector(".o_form_sheet_bg"); if (!formSheetBgXml) { return res; } const sheetBgChatterContainerHookXml = chatterContainerHookXml.cloneNode(true); sheetBgChatterContainerHookXml.classList.add("o-isInFormSheetBg"); sheetBgChatterContainerHookXml.setAttribute("t-if", true); append(formSheetBgXml, sheetBgChatterContainerHookXml); const sheetBgChatterContainerXml = sheetBgChatterContainerHookXml.querySelector("ChatterContainer"); sheetBgChatterContainerXml.setAttribute("isInFormSheetBg", "true"); chatterContainerHookXml.setAttribute("t-if", false); } } return res; }, }); patch(FormController.prototype, "web_chatter_position", { /** * Patch the css classes of the form container, to include an extra `flex-row` class. * Without it, it'd go for flex columns direction and it won't look good. * * @override */ get className() { const result = this._super(); if (odoo.web_chatter_position === "sided") { result["flex-row"] = true; } return result; }, });
OCA/web/web_chatter_position/static/src/js/web_chatter_position.esm.js/0
{ "file_path": "OCA/web/web_chatter_position/static/src/js/web_chatter_position.esm.js", "repo_id": "OCA", "token_count": 2861 }
56
# Translation of Odoo Server. # This file contains the translation of the following modules: # * web_company_color # msgid "" msgstr "" "Project-Id-Version: Odoo Server 12.0\n" "Report-Msgid-Bugs-To: \n" "PO-Revision-Date: 2020-07-08 05:19+0000\n" "Last-Translator: 黎伟杰 <674416404@qq.com>\n" "Language-Team: none\n" "Language: zh_CN\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: \n" "Plural-Forms: nplurals=1; plural=0;\n" "X-Generator: Weblate 3.10\n" #. module: web_company_color #: model_terms:ir.ui.view,arch_db:web_company_color.view_company_form msgid "" "<span class=\"fa fa-info fa-2x me-2\"/>\n" " In order for the changes to take effect, please " "refresh\n" " the page." msgstr "" #. module: web_company_color #: model:ir.model.fields,field_description:web_company_color.field_res_company__color_button_bg msgid "Button Background Color" msgstr "" #. module: web_company_color #: model:ir.model.fields,field_description:web_company_color.field_res_company__color_button_bg_hover msgid "Button Background Color Hover" msgstr "" #. module: web_company_color #: model:ir.model.fields,field_description:web_company_color.field_res_company__color_button_text msgid "Button Text Color" msgstr "" #. module: web_company_color #: model_terms:ir.ui.view,arch_db:web_company_color.view_company_form msgid "Colors" msgstr "" #. module: web_company_color #: model:ir.model,name:web_company_color.model_res_company msgid "Companies" msgstr "公司" #. module: web_company_color #: model:ir.model.fields,field_description:web_company_color.field_res_company__company_colors msgid "Company Colors" msgstr "公司颜色" #. module: web_company_color #: model_terms:ir.ui.view,arch_db:web_company_color.view_company_form msgid "Company Styles" msgstr "公司风格" #. module: web_company_color #: model_terms:ir.ui.view,arch_db:web_company_color.view_company_form msgid "Compute colors from logo" msgstr "" #. module: web_company_color #: model:ir.model.fields,field_description:web_company_color.field_res_company__color_link_text msgid "Link Text Color" msgstr "" #. module: web_company_color #: model:ir.model.fields,field_description:web_company_color.field_res_company__color_link_text_hover msgid "Link Text Color Hover" msgstr "" #. module: web_company_color #: model:ir.model.fields,field_description:web_company_color.field_res_company__color_navbar_bg msgid "Navbar Background Color" msgstr "导航栏背景颜色" #. module: web_company_color #: model:ir.model.fields,field_description:web_company_color.field_res_company__color_navbar_bg_hover msgid "Navbar Background Color Hover" msgstr "导航栏鼠标悬停背景颜色" #. module: web_company_color #: model:ir.model.fields,field_description:web_company_color.field_res_company__color_navbar_text msgid "Navbar Text Color" msgstr "导航栏文字颜色" #. module: web_company_color #: model:ir.model,name:web_company_color.model_ir_qweb msgid "Qweb" msgstr "Qweb" #. module: web_company_color #: model:ir.model.fields,field_description:web_company_color.field_res_company__scss_modif_timestamp msgid "SCSS Modif. Timestamp" msgstr "SCSS修改时间戳" #~ msgid "Navbar Colors" #~ msgstr "导航栏颜色" #~ msgid "" #~ "<span class=\"fa fa-info fa-2x\"/>\n" #~ " In order for the changes to take effect, please " #~ "refresh\n" #~ " the page." #~ msgstr "" #~ "<span class=\"fa fa-info fa-2x\"/>\n" #~ " 为了使更改生效,请刷新\n" #~ " 这个页面。"
OCA/web/web_company_color/i18n/zh_CN.po/0
{ "file_path": "OCA/web/web_company_color/i18n/zh_CN.po", "repo_id": "OCA", "token_count": 1534 }
57
================================================= Show confirmation dialogue before copying records ================================================= .. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! This file is generated by oca-gen-addon-readme !! !! changes will be overwritten. !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! source digest: sha256:9ffbec2bd468094a5f6c980516e3b71c413f095cd4eeab7b7bd24c50c5cf91ab !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! .. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png :target: https://odoo-community.org/page/development-status :alt: Beta .. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html :alt: License: AGPL-3 .. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fweb-lightgray.png?logo=github :target: https://github.com/OCA/web/tree/16.0/web_copy_confirm :alt: OCA/web .. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png :target: https://translation.odoo-community.org/projects/web-16-0/web-16-0-web_copy_confirm :alt: Translate me on Weblate .. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png :target: https://runboat.odoo-community.org/builds?repo=OCA/web&target_branch=16.0 :alt: Try me on Runboat |badge1| |badge2| |badge3| |badge4| |badge5| This module will show a confirmation dialog when the user selects the `Duplicate` option from the `Action` dropdown in the standard form view. **Table of contents** .. contents:: :local: Changelog ========= 14.0.1.0.0 (2020-01-04) ~~~~~~~~~~~~~~~~~~~~~~~ * [PORT] Ported to V14 Bug Tracker =========== Bugs are tracked on `GitHub Issues <https://github.com/OCA/web/issues>`_. In case of trouble, please check there if your issue has already been reported. If you spotted it first, help us to smash it by providing a detailed and welcomed `feedback <https://github.com/OCA/web/issues/new?body=module:%20web_copy_confirm%0Aversion:%2016.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_. Do not contact contributors directly about support or help with technical issues. Credits ======= Authors ~~~~~~~ * Dynapps Contributors ~~~~~~~~~~~~ * Stefan Rijnhart <stefan@opener.amsterdam> * Robin Conjour <rconjour@demolium.com> * Dhara Solanki <dhara.solanki@initos.com> Maintainers ~~~~~~~~~~~ This module is maintained by the OCA. .. image:: https://odoo-community.org/logo.png :alt: Odoo Community Association :target: https://odoo-community.org OCA, or the Odoo Community Association, is a nonprofit organization whose mission is to support the collaborative development of Odoo features and promote its widespread use. This module is part of the `OCA/web <https://github.com/OCA/web/tree/16.0/web_copy_confirm>`_ project on GitHub. You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
OCA/web/web_copy_confirm/README.rst/0
{ "file_path": "OCA/web/web_copy_confirm/README.rst", "repo_id": "OCA", "token_count": 1089 }
58
# Translation of Odoo Server. # This file contains the translation of the following modules: # * web_dark_mode # msgid "" msgstr "" "Project-Id-Version: Odoo Server 16.0\n" "Report-Msgid-Bugs-To: \n" "PO-Revision-Date: 2023-09-02 20:35+0000\n" "Last-Translator: Ivorra78 <informatica@totmaterial.es>\n" "Language-Team: none\n" "Language: es\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: \n" "Plural-Forms: nplurals=2; plural=n != 1;\n" "X-Generator: Weblate 4.17\n" #. module: web_dark_mode #. odoo-javascript #: code:addons/web_dark_mode/static/src/js/switch_item.esm.js:0 #: model:ir.model.fields,field_description:web_dark_mode.field_res_users__dark_mode #, python-format msgid "Dark Mode" msgstr "Modo Oscuro" #. module: web_dark_mode #: model:ir.model.fields,field_description:web_dark_mode.field_res_users__dark_mode_device_dependent msgid "Device Dependent Dark Mode" msgstr "Modo Oscuro en Función del Dispositivo" #. module: web_dark_mode #: model:ir.model,name:web_dark_mode.model_ir_http msgid "HTTP Routing" msgstr "Enrutamiento HTTP" #. module: web_dark_mode #: model:ir.model,name:web_dark_mode.model_res_users msgid "User" msgstr "Usuario"
OCA/web/web_dark_mode/i18n/es.po/0
{ "file_path": "OCA/web/web_dark_mode/i18n/es.po", "repo_id": "OCA", "token_count": 494 }
59
/** @odoo-module **/ import {browser} from "@web/core/browser/browser"; import {registry} from "@web/core/registry"; export function darkModeSwitchItem(env) { return { type: "switch", id: "color_scheme.switch", description: env._t("Dark Mode"), callback: () => { env.services.color_scheme.switchColorScheme(); }, isChecked: env.services.cookie.current.color_scheme === "dark", sequence: 40, }; } export const colorSchemeService = { dependencies: ["cookie", "orm", "ui", "user"], async start(env, {cookie, orm, ui, user}) { registry.category("user_menuitems").add("darkmode", darkModeSwitchItem); if (!cookie.current.color_scheme) { const match_media = window.matchMedia("(prefers-color-scheme: dark)"); const dark_mode = match_media.matches; cookie.setCookie("color_scheme", dark_mode ? "dark" : "light"); if (dark_mode) browser.location.reload(); } return { async switchColorScheme() { const scheme = cookie.current.color_scheme === "dark" ? "light" : "dark"; cookie.setCookie("color_scheme", scheme); await orm.write("res.users", [user.userId], { dark_mode: scheme === "dark", }); ui.block(); browser.location.reload(); }, }; }, }; registry.category("services").add("color_scheme", colorSchemeService);
OCA/web/web_dark_mode/static/src/js/switch_item.esm.js/0
{ "file_path": "OCA/web/web_dark_mode/static/src/js/switch_item.esm.js", "repo_id": "OCA", "token_count": 715 }
60