text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
export * from './apps'
export * from './auth'
export * from './capabilities'
export * from './clipboard'
export * from './config'
export * from './extensionRegistry'
export * from './messages'
export * from './modals'
export * from './resources'
export * from './shares'
export * from './spaces'
export * from './theme'
export * from './user'
| owncloud/web/packages/web-pkg/src/composables/piniaStores/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/index.ts",
"repo_id": "owncloud",
"token_count": 113
} | 900 |
import {
Resource,
buildShareSpaceResource,
isMountPointSpaceResource,
OCM_PROVIDER_ID
} from '@ownclouders/web-client/src/helpers'
import { computed, unref } from 'vue'
import { useClientService } from '../clientService'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import { useLoadFileInfoById } from './useLoadFileInfoById'
import { useSpacesStore, useConfigStore } from '../piniaStores'
export const useGetResourceContext = () => {
const clientService = useClientService()
const configStore = useConfigStore()
const { loadFileInfoByIdTask } = useLoadFileInfoById({ clientService })
const spacesStore = useSpacesStore()
const spaces = computed(() => spacesStore.spaces)
const getMatchingSpaceByFileId = (id: Resource['id']) => {
return unref(spaces).find((space) => id.toString().startsWith(space.id.toString()))
}
const getMatchingMountPoint = (id: Resource['id']) => {
return unref(spaces).find(
(space) => isMountPointSpaceResource(space) && space.root?.remoteItem?.id === id
)
}
// get context for a resource when only having its id. be careful, this might be very expensive!
const getResourceContext = async (id: string) => {
let path: string
let resource: Resource
let space = getMatchingSpaceByFileId(id)
if (space) {
path = await clientService.webdav.getPathForFileId(id)
resource = await clientService.webdav.getFileInfo(space, { path })
return { space, resource, path }
}
// no matching space found => the file doesn't lie in own spaces => it's a share.
// do PROPFINDs on parents until root of accepted share is found in `mountpoint` spaces
await spacesStore.loadMountPoints({ graphClient: clientService.graphAuthenticated })
let mountPoint = getMatchingMountPoint(id)
resource = await loadFileInfoByIdTask.perform(id)
const sharePathSegments = mountPoint ? [] : [unref(resource).name]
let tmpResource = unref(resource)
while (!mountPoint) {
tmpResource = await loadFileInfoByIdTask.perform(tmpResource.parentFolderId)
mountPoint = getMatchingMountPoint(tmpResource.id)
if (!mountPoint) {
sharePathSegments.unshift(tmpResource.name)
}
}
space = buildShareSpaceResource({
driveAliasPrefix: resource.storageId?.startsWith(OCM_PROVIDER_ID) ? 'ocm-share' : 'share',
shareId: mountPoint.nodeId,
shareName: mountPoint.name,
serverUrl: configStore.serverUrl
})
path = urlJoin(...sharePathSegments)
return { space, resource, path }
}
return {
getResourceContext
}
}
| owncloud/web/packages/web-pkg/src/composables/resources/useGetResourceContext.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/resources/useGetResourceContext.ts",
"repo_id": "owncloud",
"token_count": 876
} | 901 |
export abstract class SearchLocationFilterConstants {
static readonly allFiles: string = 'all-files'
static readonly currentFolder: string = 'current-folder'
}
| owncloud/web/packages/web-pkg/src/composables/search/constants.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/search/constants.ts",
"repo_id": "owncloud",
"token_count": 42
} | 902 |
import { buildSpace, SpaceResource } from '@ownclouders/web-client/src/helpers'
import { Drive } from '@ownclouders/web-client/src/generated'
import { useGettext } from 'vue3-gettext'
import { useClientService } from '../clientService'
import { useConfigStore } from '../piniaStores'
export const useCreateSpace = () => {
const clientService = useClientService()
const { $gettext } = useGettext()
const configStore = useConfigStore()
const createSpace = async (name: string) => {
const { graphAuthenticated } = clientService
const { data: createdSpace } = await graphAuthenticated.drives.createDrive({ name }, {})
const spaceResource = buildSpace({
...createdSpace,
serverUrl: configStore.serverUrl
})
return await createDefaultMetaFolder(spaceResource)
}
const createDefaultMetaFolder = async (space: SpaceResource) => {
const { graphAuthenticated, webdav } = clientService
await webdav.createFolder(space, { path: '.space' })
const file = await webdav.putFileContents(space, {
path: '.space/readme.md',
content: $gettext('Here you can add a description for this Space.')
})
const { data: updatedDriveData } = await graphAuthenticated.drives.updateDrive(
space.id as string,
{
special: [
{
specialFolder: {
name: 'readme'
},
id: file.id as string
}
]
} as Drive,
{}
)
return buildSpace({ ...updatedDriveData, serverUrl: configStore.serverUrl })
}
return { createSpace, createDefaultMetaFolder }
}
| owncloud/web/packages/web-pkg/src/composables/spaces/useCreateSpace.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/spaces/useCreateSpace.ts",
"repo_id": "owncloud",
"token_count": 576
} | 903 |
export abstract class ClipboardActions {
static readonly Cut = 'cut'
static readonly Copy = 'copy'
}
| owncloud/web/packages/web-pkg/src/helpers/clipboardActions.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/clipboardActions.ts",
"repo_id": "owncloud",
"token_count": 31
} | 904 |
export enum ResolveStrategy {
SKIP,
REPLACE,
KEEP_BOTH,
MERGE
}
export interface ResolveConflict {
strategy: ResolveStrategy
doForAllConflicts: boolean
}
export enum TransferType {
COPY,
MOVE
}
| owncloud/web/packages/web-pkg/src/helpers/resource/conflictHandling/types.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/resource/conflictHandling/types.ts",
"repo_id": "owncloud",
"token_count": 77
} | 905 |
import { SortDir, SortField } from '../../composables/sort'
export const determineResourceTableSortFields = (firstResource): SortField[] => {
if (!firstResource) {
return []
}
return [
{
name: 'name',
sortable: true,
sortDir: SortDir.Asc
},
{
name: 'size',
sortable: true,
sortDir: SortDir.Desc
},
{
name: 'sharedWith',
sortable: (sharedWith) => {
if (sharedWith.length > 0) {
// Ensure the sharees are always sorted and that users
// take precedence over groups. Then return a string with
// all elements to ensure shares with multiple shares do
// not appear mixed within others with a single one
return sharedWith
.sort((a, b) => {
if (a.shareType !== b.shareType) {
return a.shareType < b.shareType ? -1 : 1
}
return a.displayName < b.displayName ? -1 : 1
})
.map((e) => e.displayName)
.join()
}
return false
},
sortDir: SortDir.Asc
},
{
name: 'owner',
sortable: 'displayName',
sortDir: SortDir.Asc
},
{
name: 'mdate',
sortable: (date) => new Date(date).valueOf(),
sortDir: SortDir.Desc
},
{
name: 'sdate',
sortable: (date) => new Date(date).valueOf(),
sortDir: SortDir.Desc
},
{
name: 'ddate',
sortable: (date) => new Date(date).valueOf(),
sortDir: SortDir.Desc
}
].filter((field) => Object.prototype.hasOwnProperty.call(firstResource, field.name))
}
| owncloud/web/packages/web-pkg/src/helpers/ui/resourceTable.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/ui/resourceTable.ts",
"repo_id": "owncloud",
"token_count": 759
} | 906 |
// Workaround https://github.com/npm/node-semver/issues/381
import major from 'semver/functions/major'
import rcompare from 'semver/functions/rcompare'
import { RuntimeError } from '../errors'
import { HttpError } from '@ownclouders/web-client/src/errors'
import { ClientService } from '../services'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import { triggerDownloadWithFilename } from '../helpers/download'
import { Ref, ref, computed, unref } from 'vue'
import { ArchiverCapability } from '@ownclouders/web-client/src/ocs/capabilities'
interface TriggerDownloadOptions {
dir?: string
files?: string[]
fileIds?: string[]
downloadSecret?: string
publicToken?: string
publicLinkPassword?: string
}
export class ArchiverService {
clientService: ClientService
serverUrl: string
capability: Ref<ArchiverCapability>
available: Ref<boolean>
fileIdsSupported: Ref<boolean>
constructor(
clientService: ClientService,
serverUrl: string,
archiverCapabilities: Ref<ArchiverCapability[]> = ref([])
) {
this.clientService = clientService
this.serverUrl = serverUrl
this.capability = computed(() => {
const archivers = unref(archiverCapabilities)
.filter((a) => a.enabled)
.sort((a1, a2) => rcompare(a1.version, a2.version))
return archivers.length ? archivers[0] : null
})
this.available = computed(() => {
return !!unref(this.capability)?.version
})
this.fileIdsSupported = computed(() => {
return major(unref(this.capability)?.version) >= 2
})
}
public async triggerDownload(options: TriggerDownloadOptions): Promise<string> {
if (!unref(this.available)) {
throw new RuntimeError('no archiver available')
}
if ((options.fileIds?.length || 0) + (options.files?.length || 0) === 0) {
throw new RuntimeError('requested archive with empty list of resources')
}
const downloadUrl = this.buildDownloadUrl({ ...options })
if (!downloadUrl) {
throw new RuntimeError('download url could not be built')
}
const url = options.publicToken
? downloadUrl
: await this.clientService.ocsUserContext.signUrl(downloadUrl)
try {
const response = await this.clientService.httpUnAuthenticated.get<ArrayBuffer>(url, {
headers: {
...(!!options.publicLinkPassword && {
Authorization:
'Basic ' +
Buffer.from(['public', options.publicLinkPassword].join(':')).toString('base64')
})
},
responseType: 'arraybuffer'
})
const blob = new Blob([response.data], { type: 'application/octet-stream' })
const objectUrl = URL.createObjectURL(blob)
const fileName = this.getFileNameFromResponseHeaders(response.headers)
triggerDownloadWithFilename(objectUrl, fileName)
return url
} catch (e) {
throw new HttpError('archive could not be fetched', e.response)
}
}
private buildDownloadUrl(options: TriggerDownloadOptions): string {
const queryParams = []
if (options.publicToken) {
queryParams.push(`public-token=${options.publicToken}`)
}
const majorVersion = major(unref(this.capability).version)
switch (majorVersion) {
case 2: {
queryParams.push(...options.fileIds.map((id) => `id=${id}`))
return this.url + '?' + queryParams.join('&')
}
case 1: {
// see https://github.com/owncloud/core/blob/e285879a8a79e692497937ebf340bc6b9c925b4f/apps/files/js/files.js#L315 for reference
// classic ui does a check whether the download started. not implemented here (yet?).
const downloadStartSecret = Math.random().toString(36).substring(2)
queryParams.push(
`dir=${encodeURIComponent(options.dir)}`,
...options.files.map((name) => `files[]=${encodeURIComponent(name)}`),
`downloadStartSecret=${downloadStartSecret}`
)
return this.url + '?' + queryParams.join('&')
}
default: {
return undefined
}
}
}
private get url(): string {
if (!this.available) {
throw new RuntimeError('no archiver available')
}
const capability = unref(this.capability)
if (/^https?:\/\//i.test(capability.archiver_url)) {
return capability.archiver_url
}
return urlJoin(this.serverUrl, capability.archiver_url)
}
private getFileNameFromResponseHeaders(headers) {
const fileName = headers['content-disposition']?.split('"')[1]
return decodeURI(fileName)
}
}
| owncloud/web/packages/web-pkg/src/services/archiver.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/services/archiver.ts",
"repo_id": "owncloud",
"token_count": 1701
} | 907 |
import Uppy, { BasePlugin, UppyFile, UIPlugin } from '@uppy/core'
import Tus from '@uppy/tus'
import { TusOptions } from '@uppy/tus'
import XHRUpload, { XHRUploadOptions } from '@uppy/xhr-upload'
import { Language } from 'vue3-gettext'
import { eventBus } from '../eventBus'
import DropTarget from '@uppy/drop-target'
import getFileType from '@uppy/utils/lib/getFileType'
import generateFileID from '@uppy/utils/lib/generateFileID'
import { urlJoin } from '@ownclouders/web-client/src/utils'
type UppyServiceTopics =
| 'uploadStarted'
| 'uploadCancelled'
| 'uploadCompleted'
| 'uploadSuccess'
| 'uploadError'
| 'filesSelected'
| 'progress'
| 'addedForUpload'
| 'upload-progress'
| 'drag-over'
| 'drag-out'
| 'drop'
export type uppyHeaders = {
[name: string]: string | number
}
interface UppyServiceOptions {
language: Language
}
export class UppyService {
uppy: Uppy
uploadInputs: HTMLInputElement[] = []
constructor({ language }: UppyServiceOptions) {
const { $gettext } = language
this.uppy = new Uppy({
autoProceed: false,
onBeforeFileAdded: (file, files) => {
if (file.id in files) {
file.meta.retry = true
}
file.meta.relativePath = this.getRelativeFilePath(file)
// id needs to be generated after the relative path has been set.
file.id = generateFileID(file)
return file
},
locale: {
strings: {
addedNumFiles: $gettext('Added %{numFiles} file(s)'), // for some reason this string is required and missing in uppy
authenticateWith: $gettext('Connect to %{pluginName}'),
authenticateWithTitle: $gettext('Please authenticate with %{pluginName} to select files'),
cancel: $gettext('Cancel'),
companionError: $gettext('Connection with Companion failed'),
loadedXFiles: $gettext('Loaded %{numFiles} files'),
loading: $gettext('Loading...'),
logOut: $gettext('Log out'),
publicLinkURLLabel: $gettext('Public Link URL'),
publicLinkURLDescription: $gettext(
'Please provide a URL to a public link without password protection.'
),
selectX: {
0: $gettext('Select %{smart_count}'),
1: $gettext('Select %{smart_count}')
},
signInWithGoogle: $gettext('Sign in with Google')
}
}
})
this.setUpEvents()
}
getRelativeFilePath = (file: UppyFile): string | undefined => {
const _file = file as any
const relativePath =
_file.webkitRelativePath ||
_file.relativePath ||
_file.data.relativePath ||
_file.data.webkitRelativePath
return relativePath ? urlJoin(relativePath) : undefined
}
addPlugin(plugin: any, opts: any) {
this.uppy.use(plugin, opts)
}
removePlugin(plugin: UIPlugin | BasePlugin) {
this.uppy.removePlugin(plugin)
}
getPlugin(name: string): UIPlugin | BasePlugin {
return this.uppy.getPlugin(name)
}
useTus({
tusMaxChunkSize,
tusHttpMethodOverride,
tusExtension,
onBeforeRequest,
headers
}: {
tusMaxChunkSize: number
tusHttpMethodOverride: boolean
tusExtension: string
onBeforeRequest?: (req: any) => void
headers: (file) => uppyHeaders
}) {
const chunkSize = tusMaxChunkSize || Infinity
const uploadDataDuringCreation = tusExtension.includes('creation-with-upload')
const tusPluginOptions = {
chunkSize: chunkSize,
removeFingerprintOnSuccess: true,
overridePatchMethod: !!tusHttpMethodOverride,
retryDelays: [0, 500, 1000],
uploadDataDuringCreation,
limit: 5,
headers,
onBeforeRequest,
onShouldRetry: (err, retryAttempt, options, next) => {
// status code 5xx means the upload is gone on the server side
if (err?.originalResponse?.getStatus() >= 500) {
return false
}
if (err?.originalResponse?.getStatus() === 401) {
return true
}
return next(err)
}
}
const xhrPlugin = this.uppy.getPlugin('XHRUpload')
if (xhrPlugin) {
this.uppy.removePlugin(xhrPlugin)
}
const tusPlugin = this.uppy.getPlugin('Tus')
if (tusPlugin) {
tusPlugin.setOptions(tusPluginOptions)
return
}
this.uppy.use(Tus, tusPluginOptions as unknown as TusOptions)
}
useXhr({ headers, xhrTimeout }: { headers: (file) => uppyHeaders; xhrTimeout: number }) {
const xhrPluginOptions: XHRUploadOptions = {
endpoint: '',
method: 'put',
headers,
formData: false,
timeout: xhrTimeout,
getResponseData() {
return {}
}
}
const tusPlugin = this.uppy.getPlugin('Tus')
if (tusPlugin) {
this.uppy.removePlugin(tusPlugin)
}
const xhrPlugin = this.uppy.getPlugin('XHRUpload')
if (xhrPlugin) {
xhrPlugin.setOptions(xhrPluginOptions)
return
}
this.uppy.use(XHRUpload, xhrPluginOptions)
}
tusActive() {
return !!this.uppy.getPlugin('Tus')
}
useDropTarget({ targetSelector }: { targetSelector: string }) {
if (this.uppy.getPlugin('DropTarget')) {
return
}
this.uppy.use(DropTarget, {
target: targetSelector,
onDragOver: (event) => {
this.publish('drag-over', event)
},
onDragLeave: (event) => {
this.publish('drag-out', event)
},
onDrop: (event) => {
this.publish('drop', event)
}
})
}
removeDropTarget() {
const dropTargetPlugin = this.uppy.getPlugin('DropTarget')
if (dropTargetPlugin) {
this.uppy.removePlugin(dropTargetPlugin)
}
}
subscribe(topic: UppyServiceTopics, callback: (data?: unknown) => void): string {
return eventBus.subscribe(topic, callback)
}
unsubscribe(topic: UppyServiceTopics, token: string): void {
eventBus.unsubscribe(topic, token)
}
publish(topic: UppyServiceTopics, data?: unknown): void {
eventBus.publish(topic, data)
}
private setUpEvents() {
this.uppy.on('progress', (value) => {
this.publish('progress', value)
})
this.uppy.on('upload-progress', (file, progress) => {
this.publish('upload-progress', { file, progress })
})
this.uppy.on('cancel-all', () => {
this.publish('uploadCancelled')
this.clearInputs()
})
this.uppy.on('complete', (result) => {
this.publish('uploadCompleted', result)
result.successful.forEach((file) => {
this.uppy.removeFile(file.id)
})
this.clearInputs()
})
this.uppy.on('upload-success', (file) => {
this.publish('uploadSuccess', file)
})
this.uppy.on('upload-error', (file, error) => {
this.publish('uploadError', { file, error })
})
}
registerUploadInput(el: HTMLInputElement) {
const listenerRegistered = el.getAttribute('listener')
if (listenerRegistered !== 'true') {
el.setAttribute('listener', 'true')
el.addEventListener('change', (event) => {
const target = event.target as HTMLInputElement
const files = Array.from(target.files) as unknown as UppyFile[]
this.addFiles(files)
})
this.uploadInputs.push(el)
}
}
removeUploadInput(el: HTMLInputElement) {
this.uploadInputs = this.uploadInputs.filter((input) => input !== el)
}
generateUploadId(file: File): string {
return generateFileID({
name: file.name,
size: file.size,
type: getFileType(file as unknown as UppyFile),
data: file
} as unknown as UppyFile)
}
addFiles(files: UppyFile[]) {
this.uppy.addFiles(files)
}
uploadFiles() {
return this.uppy.upload()
}
retryAllUploads() {
return this.uppy.retryAll()
}
pauseAllUploads() {
return this.uppy.pauseAll()
}
resumeAllUploads() {
return this.uppy.resumeAll()
}
cancelAllUploads() {
return this.uppy.cancelAll()
}
getCurrentUploads(): Record<string, unknown> {
return this.uppy.getState().currentUploads
}
isRemoteUploadInProgress(): boolean {
return this.uppy.getFiles().some((f) => f.isRemote && !(f as any).error)
}
clearInputs() {
this.uploadInputs.forEach((item) => {
item.value = null
})
}
}
| owncloud/web/packages/web-pkg/src/services/uppy/uppyService.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/services/uppy/uppyService.ts",
"repo_id": "owncloud",
"token_count": 3347
} | 908 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`The external app loading screen component > displays a spinner and a paragraph 1`] = `
"<div class="oc-text-center oc-flex oc-flex-center oc-flex-middle oc-height-1-1">
<oc-spinner-stub arialabel="" size="xlarge"></oc-spinner-stub>
<p class="oc-invisible" data-msgid="Loading app" data-current-language="en">Loading app</p>
</div>"
`;
| owncloud/web/packages/web-pkg/tests/unit/components/AppTemplates/__snapshots__/LoadingScreen.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/AppTemplates/__snapshots__/LoadingScreen.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 150
} | 909 |
import { defaultPlugins, shallowMount } from 'web-test-helpers'
import ResourceTile from '../../../../src/components/FilesList/ResourceTile.vue'
const getSpaceMock = (disabled = false) => ({
name: 'Space 1',
path: '',
type: 'space',
isFolder: true,
disabled,
getDriveAliasAndItem: () => '1'
})
describe('OcTile component', () => {
it('renders default space correctly', () => {
const wrapper = getWrapper({ resource: getSpaceMock() })
expect(wrapper.html()).toMatchSnapshot()
})
it('renders disabled space correctly', () => {
const wrapper = getWrapper({ resource: getSpaceMock(true) })
expect(wrapper.html()).toMatchSnapshot()
})
it('renders selected resource correctly', () => {
const wrapper = getWrapper({ resource: getSpaceMock(), isResourceSelected: true })
expect(wrapper.find('.oc-tile-card-selected').exists()).toBeTruthy()
})
it.each(['xlarge, xxlarge, xxxlarge'])(
'renders resource icon size correctly',
(resourceIconSize) => {
const wrapper = getWrapper({ resource: getSpaceMock(), resourceIconSize })
expect(wrapper.find('resource-icon-stub').attributes().size).toEqual(resourceIconSize)
}
)
function getWrapper(props = {}) {
return shallowMount(ResourceTile, {
props,
global: { plugins: [...defaultPlugins()], renderStubDefaultSlot: true }
})
}
})
| owncloud/web/packages/web-pkg/tests/unit/components/FilesList/ResourceTile.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/FilesList/ResourceTile.spec.ts",
"repo_id": "owncloud",
"token_count": 465
} | 910 |
import { mock } from 'vitest-mock-extended'
import { ResourcePreview } from '../../../../src/components'
import { SpaceResource } from '@ownclouders/web-client/src'
import { useGetMatchingSpace } from '../../../../src/composables/spaces/useGetMatchingSpace'
import {
defaultComponentMocks,
defaultPlugins,
shallowMount,
useGetMatchingSpaceMock
} from 'web-test-helpers'
import { useFileActions } from '../../../../src/composables/actions'
import { CapabilityStore } from '../../../../src/composables/piniaStores'
vi.mock('../../../../src/composables/spaces/useGetMatchingSpace', () => ({
useGetMatchingSpace: vi.fn()
}))
vi.mock('../../../../src/composables/actions', () => ({
useFileActions: vi.fn()
}))
const selectors = {
resourceListItemStub: 'resource-list-item-stub'
}
describe('Preview component', () => {
const driveAliasAndItem = '1'
vi.mocked(useGetMatchingSpace).mockImplementation(() => useGetMatchingSpaceMock())
it('should render preview component', () => {
const { wrapper } = getWrapper({
space: mock<SpaceResource>({
id: '1',
driveType: 'project',
name: 'New space',
getDriveAliasAndItem: () => driveAliasAndItem
})
})
expect(wrapper.html()).toMatchSnapshot()
})
it('should render resource component without file extension when areFileExtensionsShown is set to false', () => {
const { wrapper } = getWrapper({
areFileExtensionsShown: false,
space: mock<SpaceResource>({
id: '1',
driveType: 'project',
name: 'New space',
getDriveAliasAndItem: () => driveAliasAndItem
})
})
expect(
wrapper.findComponent<any>(selectors.resourceListItemStub).attributes().isextensiondisplayed
).toBe('false')
})
})
function getWrapper({
space = null,
searchResult = {
id: '1',
data: {
storageId: '1',
name: 'lorem.txt',
path: '/',
shareRoot: ''
}
},
areFileExtensionsShown = true
}: {
space?: SpaceResource
searchResult?: any
areFileExtensionsShown?: boolean
} = {}) {
vi.mocked(useGetMatchingSpace).mockImplementation(() =>
useGetMatchingSpaceMock({
isResourceAccessible() {
return true
},
getMatchingSpace() {
return space
}
})
)
vi.mocked(useFileActions).mockReturnValue(mock<ReturnType<typeof useFileActions>>())
const mocks = defaultComponentMocks()
const capabilities = {
spaces: { projects: true }
} satisfies Partial<CapabilityStore['capabilities']>
return {
wrapper: shallowMount(ResourcePreview, {
props: {
searchResult
},
global: {
provide: mocks,
renderStubDefaultSlot: true,
mocks,
plugins: [
...defaultPlugins({
piniaOptions: {
capabilityState: { capabilities },
configState: { options: { disablePreviews: true } },
resourcesStore: { areFileExtensionsShown }
}
})
]
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/Search/ResourcePreview.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/Search/ResourcePreview.spec.ts",
"repo_id": "owncloud",
"token_count": 1209
} | 911 |
import SpaceInfo from '../../../../../src/components/SideBar/Spaces/SpaceInfo.vue'
import { defaultPlugins, shallowMount } from 'web-test-helpers'
const spaceMock = {
type: 'space',
name: ' space',
id: '1',
mdate: 'Wed, 21 Oct 2015 07:28:00 GMT',
spaceQuota: {
used: 100
}
}
const selectors = {
name: '[data-testid="space-info-name"]',
subtitle: '[data-testid="space-info-subtitle"]'
}
describe('SpaceInfo', () => {
it('shows space info', () => {
const { wrapper } = createWrapper(spaceMock)
expect(wrapper.find(selectors.name).exists()).toBeTruthy()
expect(wrapper.find(selectors.subtitle).exists()).toBeTruthy()
expect(wrapper.html()).toMatchSnapshot()
})
})
function createWrapper(spaceResource) {
return {
wrapper: shallowMount(SpaceInfo, {
global: {
plugins: [...defaultPlugins()],
provide: { resource: spaceResource }
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/sidebar/Spaces/SpaceInfo.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/sidebar/Spaces/SpaceInfo.spec.ts",
"repo_id": "owncloud",
"token_count": 353
} | 912 |
import { useFileActionsSetImage } from '../../../../../src'
import { useMessages } from '../../../../../src/composables/piniaStores'
import { buildSpace, Resource, SpaceResource } from '@ownclouders/web-client/src/helpers'
import { mock } from 'vitest-mock-extended'
import {
defaultComponentMocks,
RouteLocation,
getComposableWrapper,
mockAxiosResolve
} from 'web-test-helpers'
import { unref } from 'vue'
import { Drive } from '@ownclouders/web-client/src/generated'
describe('setImage', () => {
describe('isVisible property', () => {
it('should be false when no resource given', () => {
const space = buildSpace(
mock<Drive>({
id: '1',
quota: {},
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
special: [{ specialFolder: { name: 'image' }, file: { mimeType: 'image/png' } }]
})
)
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ space, resources: [] as Resource[] })).toBe(false)
}
})
})
it('should be false when mimeType is not image', () => {
const space = buildSpace(
mock<Drive>({
id: '1',
quota: {},
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
special: [{ specialFolder: { name: 'image' }, file: { mimeType: 'image/png' } }]
})
)
getWrapper({
setup: ({ actions }) => {
expect(
unref(actions)[0].isVisible({
space,
resources: [{ id: '1', mimeType: 'text/plain' }] as Resource[]
})
).toBe(false)
},
isMimetypeSupported: false
})
})
it('should be true when the mimeType is image', () => {
const space = buildSpace(
mock<Drive>({
id: '1',
quota: {},
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
special: [{ specialFolder: { name: 'image' }, file: { mimeType: 'image/png' } }]
})
)
getWrapper({
setup: ({ actions }) => {
expect(
unref(actions)[0].isVisible({
space,
resources: [{ id: '1', mimeType: 'image/png' }] as Resource[]
})
).toBe(true)
}
})
})
it('should be false when the current user is a viewer', () => {
const space = buildSpace(
mock<Drive>({
id: '1',
quota: {},
root: {
permissions: [{ roles: ['viewer'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
special: [{ specialFolder: { name: 'image' }, file: { mimeType: 'image/png' } }]
})
)
getWrapper({
setup: ({ actions }) => {
expect(
unref(actions)[0].isVisible({
space,
resources: [{ id: '1', mimeType: 'image/png' }] as Resource[]
})
).toBe(false)
}
})
})
})
describe('handler', () => {
it('should show message on success', () => {
const driveMock = mock<Drive>({ special: [{ specialFolder: { name: 'image' } }] })
const space = mock<SpaceResource>({ id: '1' })
getWrapper({
setup: async ({ actions }, { clientService }) => {
clientService.graphAuthenticated.drives.updateDrive.mockResolvedValue(
mockAxiosResolve(driveMock)
)
await unref(actions)[0].handler({
space,
resources: [
{
webDavPath: '/spaces/1fe58d8b-aa69-4c22-baf7-97dd57479f22/subfolder/image.png',
name: 'image.png'
}
] as Resource[]
})
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalledTimes(1)
}
})
})
it('should show message on error', () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
const space = mock<SpaceResource>({ id: '1' })
getWrapper({
setup: async ({ actions }) => {
await unref(actions)[0].handler({
space,
resources: [
{
webDavPath: '/spaces/1fe58d8b-aa69-4c22-baf7-97dd57479f22/subfolder/image.png',
name: 'image.png'
}
] as Resource[]
})
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalledTimes(1)
}
})
})
})
})
function getWrapper({
setup,
isMimetypeSupported = true
}: {
setup: (
instance: ReturnType<typeof useFileActionsSetImage>,
options: {
clientService: ReturnType<typeof defaultComponentMocks>['$clientService']
}
) => void
isMimetypeSupported?: boolean
}) {
const mocks = {
...defaultComponentMocks({
currentRoute: mock<RouteLocation>({ name: 'files-spaces-generic' })
})
}
mocks.$previewService.isMimetypeSupported.mockReturnValue(isMimetypeSupported)
mocks.$clientService.webdav.getFileInfo.mockResolvedValue(mock<Resource>())
return {
wrapper: getComposableWrapper(
() => {
const instance = useFileActionsSetImage()
setup(instance, { clientService: mocks.$clientService })
},
{
mocks,
provide: mocks,
pluginOptions: {
piniaOptions: { userState: { user: { id: '1', onPremisesSamAccountName: 'alice' } } }
}
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsSetImage.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsSetImage.spec.ts",
"repo_id": "owncloud",
"token_count": 2714
} | 913 |
import { mock } from 'vitest-mock-extended'
import { SpaceResource } from '@ownclouders/web-client/src'
import { RouteLocation, getComposableWrapper } from 'web-test-helpers/src'
import { useBreadcrumbsFromPath } from '../../../../src/composables/breadcrumbs'
describe('useBreadcrumbsFromPath', () => {
describe('builds an array of breadcrumbitems', () => {
it('from a path', () => {
const wrapper = getWrapper()
const { breadcrumbsFromPath } = wrapper.vm as ReturnType<typeof useBreadcrumbsFromPath>
const breadCrumbs = breadcrumbsFromPath({
route: { path: '/files/spaces/personal/home/test' } as RouteLocation,
space: mock<SpaceResource>(),
resourcePath: '/test'
})
expect(breadCrumbs).toEqual([
{
id: expect.anything(),
isStaticNav: false,
allowContextActions: true,
text: 'test',
to: { path: '/files/spaces/personal/home/test', query: {} }
}
])
})
it('from an array of breadcrumbitems', () => {
const wrapper = getWrapper()
const { breadcrumbsFromPath, concatBreadcrumbs } = wrapper.vm as ReturnType<
typeof useBreadcrumbsFromPath
>
const initialBreadCrumbs = [{ text: 'Foo' }, { text: 'Bar' }]
const breadCrumbsFromPath = breadcrumbsFromPath({
route: { path: '/app/foo/bar?all=500' } as RouteLocation,
space: mock<SpaceResource>(),
resourcePath: '/bar'
})
const result = concatBreadcrumbs(...initialBreadCrumbs, ...breadCrumbsFromPath)
expect(result[0]).toMatchObject({ text: 'Foo' })
expect(result[1]).toMatchObject({ text: 'Bar' })
})
})
})
function getWrapper() {
return getComposableWrapper(() => {
return useBreadcrumbsFromPath()
})
}
| owncloud/web/packages/web-pkg/tests/unit/composables/breadcrumbs/useBreadcrumbsFromPath.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/breadcrumbs/useBreadcrumbsFromPath.spec.ts",
"repo_id": "owncloud",
"token_count": 732
} | 914 |
import { mock } from 'vitest-mock-extended'
import { useScrollTo } from '../../../../src/composables/scrollTo'
import { Resource } from '@ownclouders/web-client/src'
import { eventBus } from '../../../../src/services'
import { defaultComponentMocks } from 'web-test-helpers/src/mocks/defaultComponentMocks'
import { getComposableWrapper, RouteLocation } from 'web-test-helpers'
const mockResourceId = 'fakeResourceId'
const mockFilesTopBar = {
offsetHeight: 75
}
describe('useScrollTo', () => {
it('should be valid', () => {
expect(useScrollTo).toBeDefined()
})
describe('method "scrollToResource"', () => {
const getHTMLPageObject = () => ({
getBoundingClientRect: vi.fn(() => ({ bottom: 300, top: 0 })),
scrollIntoView: vi.fn(),
scrollBy: vi.fn(),
offsetHeight: 100
})
it('does nothing when no element was found', () => {
const htmlPageObject = getHTMLPageObject()
vi.spyOn(document, 'querySelectorAll').mockImplementation(() => [] as any)
vi.spyOn(document, 'getElementById').mockImplementation(() => mockFilesTopBar as any)
const mocks = defaultComponentMocks()
getComposableWrapper(
() => {
const { scrollToResource } = useScrollTo()
scrollToResource(mockResourceId)
expect(htmlPageObject.scrollIntoView).not.toHaveBeenCalled()
},
{ mocks, provide: mocks }
)
})
it('calls "scrollIntoView" when the page bottom is reached', () => {
const htmlPageObject = getHTMLPageObject()
vi.spyOn(document, 'querySelectorAll').mockImplementation(() => [htmlPageObject] as any)
vi.spyOn(document, 'getElementById').mockImplementation(() => mockFilesTopBar as any)
window.innerHeight = 100
const mocks = defaultComponentMocks()
getComposableWrapper(
() => {
const { scrollToResource } = useScrollTo()
scrollToResource(mockResourceId)
expect(htmlPageObject.scrollIntoView).toHaveBeenCalled()
},
{ mocks, provide: mocks }
)
})
it('calls "scrollIntoView" when the page top is reached', () => {
const htmlPageObject = getHTMLPageObject()
vi.spyOn(document, 'querySelectorAll').mockImplementation(() => [htmlPageObject] as any)
vi.spyOn(document, 'getElementById').mockImplementation(() => mockFilesTopBar as any)
window.innerHeight = 500
const mocks = defaultComponentMocks()
getComposableWrapper(
() => {
const { scrollToResource } = useScrollTo()
scrollToResource(mockResourceId)
expect(htmlPageObject.scrollIntoView).toHaveBeenCalled()
},
{ mocks, provide: mocks }
)
})
})
describe('method "scrollToResourceFromRoute"', () => {
const resourceId = 'someFileId'
it('does not scroll without the "scrollTo" param', () => {
const mocks = { ...defaultComponentMocks() }
getComposableWrapper(
() => {
const resource = mock<Resource>({ id: resourceId })
const { scrollToResourceFromRoute } = useScrollTo()
const querySelectorAllSpy = vi.spyOn(document, 'querySelectorAll')
scrollToResourceFromRoute([resource], 'files-app-bar')
expect(querySelectorAllSpy).not.toHaveBeenCalled()
},
{ mocks, provide: mocks }
)
})
it('does not scroll when no resource found', () => {
const mocks = {
...defaultComponentMocks({
currentRoute: mock<RouteLocation>({ query: { scrollTo: resourceId } })
})
}
getComposableWrapper(
() => {
const resource = mock<Resource>({ id: 'someOtherFileId' })
const { scrollToResourceFromRoute } = useScrollTo()
const querySelectorAllSpy = vi.spyOn(document, 'querySelectorAll')
scrollToResourceFromRoute([resource], 'files-app-bar')
expect(querySelectorAllSpy).not.toHaveBeenCalled()
},
{ mocks, provide: mocks }
)
})
it('does not scroll when resource is processing', () => {
const mocks = {
...defaultComponentMocks({
currentRoute: mock<RouteLocation>({ query: { scrollTo: resourceId } })
})
}
getComposableWrapper(
() => {
const resource = mock<Resource>({ id: resourceId, processing: true })
const { scrollToResourceFromRoute } = useScrollTo()
const querySelectorAllSpy = vi.spyOn(document, 'querySelectorAll')
scrollToResourceFromRoute([resource], 'files-app-bar')
expect(querySelectorAllSpy).not.toHaveBeenCalled()
},
{ mocks, provide: mocks }
)
})
it('scrolls to the resource when the "scrollTo" param is given and a resource is found', () => {
const store = { commit: vi.fn() }
const mocks = {
...defaultComponentMocks({
currentRoute: mock<RouteLocation>({ query: { scrollTo: resourceId } })
})
}
getComposableWrapper(
() => {
const resource = mock<Resource>({ id: resourceId })
const { scrollToResourceFromRoute } = useScrollTo()
const querySelectorAllSpy = vi.spyOn(document, 'querySelectorAll')
scrollToResourceFromRoute([resource], 'files-app-bar')
expect(querySelectorAllSpy).toHaveBeenCalled()
},
{
mocks,
provide: {
...mocks,
store
}
}
)
})
it('opens the sidebar when a resource is found and the "details" param is given', () => {
const store = { commit: vi.fn() }
const mocks = {
...defaultComponentMocks({
currentRoute: mock<RouteLocation>({
query: { scrollTo: resourceId, details: 'details' }
})
})
}
getComposableWrapper(
() => {
const busStub = vi.spyOn(eventBus, 'publish')
const resource = mock<Resource>({ id: resourceId })
const { scrollToResourceFromRoute } = useScrollTo()
scrollToResourceFromRoute([resource], 'files-app-bar')
expect(busStub).toHaveBeenCalled()
},
{
mocks,
provide: {
...mocks,
store
}
}
)
})
})
})
| owncloud/web/packages/web-pkg/tests/unit/composables/scrollTo/useScrollTo.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/scrollTo/useScrollTo.spec.ts",
"repo_id": "owncloud",
"token_count": 2665
} | 915 |
import {
ResolveConflict,
ResourceTransfer,
TransferType,
resolveFileNameDuplicate
} from '../../../../../src/helpers/resource/conflictHandling'
import { mock, mockDeep, mockReset } from 'vitest-mock-extended'
import { buildSpace, Resource } from '@ownclouders/web-client/src/helpers'
import { ListFilesResult } from '@ownclouders/web-client/src/webdav/listFiles'
import { Drive } from '@ownclouders/web-client/src/generated'
import { createTestingPinia } from 'web-test-helpers'
import {
ClientService,
LoadingService,
LoadingTaskCallbackArguments
} from '../../../../../src/services'
import { computed } from 'vue'
const clientServiceMock = mockDeep<ClientService>()
const loadingServiceMock = mock<LoadingService>({
addTask: (callback) => {
return callback(mock<LoadingTaskCallbackArguments>())
}
})
let resourcesToMove
let sourceSpace
let targetSpace
let targetFolder
describe('resourcesTransfer', () => {
beforeEach(() => {
createTestingPinia()
mockReset(clientServiceMock)
resourcesToMove = [
{
id: 'a',
name: 'a',
path: '/a',
type: 'folder'
},
{
id: 'b',
name: 'b',
path: '/b'
}
]
const spaceOptions = {
id: 'c42c9504-2c19-44fd-87cc-b4fc20ecbb54'
} as unknown as Drive
sourceSpace = buildSpace(spaceOptions)
targetSpace = buildSpace(spaceOptions)
targetFolder = {
id: 'target',
path: 'target',
webDavPath: '/target'
}
})
it.each([
{ name: 'a', extension: '', expectName: 'a (1)' },
{ name: 'a', extension: '', expectName: 'a (2)', existing: [{ name: 'a (1)' }] },
{ name: 'a (1)', extension: '', expectName: 'a (1) (1)' },
{ name: 'b.png', extension: 'png', expectName: 'b (1).png' },
{ name: 'b.png', extension: 'png', expectName: 'b (2).png', existing: [{ name: 'b (1).png' }] }
])('should name duplicate file correctly', (dataSet) => {
const existing = dataSet.existing ? [...resourcesToMove, ...dataSet.existing] : resourcesToMove
const result = resolveFileNameDuplicate(dataSet.name, dataSet.extension, existing)
expect(result).toEqual(dataSet.expectName)
})
it('should prevent recursive paste', async () => {
const resourcesTransfer = new ResourceTransfer(
sourceSpace,
resourcesToMove,
targetSpace,
resourcesToMove[0],
computed(() => mock<Resource>()),
clientServiceMock,
loadingServiceMock,
vi.fn(),
vi.fn()
)
const result = await resourcesTransfer.perform(TransferType.COPY)
expect(result.length).toBe(0)
})
describe('copyMoveResource without conflicts', () => {
it.each([TransferType.COPY, TransferType.MOVE])(
'should copy / move files without renaming them if no conflicts exist',
async (action: TransferType) => {
const listFilesResult: ListFilesResult = {
resource: {} as Resource,
children: []
}
clientServiceMock.webdav.listFiles.mockReturnValueOnce(
new Promise((resolve) => resolve(listFilesResult))
)
const resourcesTransfer = new ResourceTransfer(
sourceSpace,
resourcesToMove,
targetSpace,
targetFolder,
computed(() => mock<Resource>()),
clientServiceMock,
loadingServiceMock,
vi.fn(),
vi.fn()
)
const movedResources = await resourcesTransfer.perform(action)
const fn =
action === TransferType.COPY
? clientServiceMock.webdav.copyFiles
: clientServiceMock.webdav.moveFiles
expect(fn).toHaveBeenCalledTimes(resourcesToMove.length)
expect(movedResources.length).toBe(resourcesToMove.length)
for (let i = 0; i < resourcesToMove.length; i++) {
const input = resourcesToMove[i]
const output = movedResources[i]
expect(input.name).toBe(output.name)
}
}
)
})
it('should show message if conflict exists', async () => {
const targetFolderItems = [
{
id: 'a',
path: 'target/a',
webDavPath: '/target/a',
name: '/target/a'
}
]
const resourcesTransfer = new ResourceTransfer(
sourceSpace,
resourcesToMove,
targetSpace,
resourcesToMove[0],
computed(() => mock<Resource>()),
clientServiceMock,
loadingServiceMock,
vi.fn(),
vi.fn()
)
resourcesTransfer.resolveFileExists = vi
.fn()
.mockImplementation(() => Promise.resolve({ strategy: 0 } as ResolveConflict))
await resourcesTransfer.resolveAllConflicts(resourcesToMove, targetFolder, targetFolderItems)
expect(resourcesTransfer.resolveFileExists).toHaveBeenCalled()
})
it('should show error message if trying to overwrite parent', async () => {
const targetFolderItems = [
{
id: 'a',
path: 'target/a',
webDavPath: '/target/a',
name: '/target/a'
}
]
const resourcesTransfer = new ResourceTransfer(
sourceSpace,
resourcesToMove,
targetSpace,
resourcesToMove[0],
computed(() => mock<Resource>()),
clientServiceMock,
loadingServiceMock,
vi.fn(),
vi.fn()
)
const namingClash = await resourcesTransfer.isOverwritingParentFolder(
resourcesToMove[0],
targetFolder,
targetFolderItems
)
const noNamingClash = await resourcesTransfer.isOverwritingParentFolder(
resourcesToMove[1],
targetFolder,
targetFolderItems
)
expect(namingClash).toBeTruthy()
expect(noNamingClash).toBeFalsy()
})
})
| owncloud/web/packages/web-pkg/tests/unit/helpers/resource/conflictHandling/resourcesTransfer.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/resource/conflictHandling/resourcesTransfer.spec.ts",
"repo_id": "owncloud",
"token_count": 2305
} | 916 |
import { ClientService, PreviewService } from '../../../src/services'
import { mock, mockDeep } from 'vitest-mock-extended'
import { createTestingPinia } from 'web-test-helpers'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { AxiosResponse } from 'axios'
import {
useAuthStore,
useUserStore,
useCapabilityStore,
useConfigStore
} from '../../../src/composables/piniaStores'
import { User } from '@ownclouders/web-client/src/generated'
describe('PreviewService', () => {
describe('method "isMimetypeSupported"', () => {
it('should return true if mimeType is supported', () => {
const supportedMimeTypes = ['image/png']
const { previewService } = getWrapper({ supportedMimeTypes })
expect(previewService.isMimetypeSupported(supportedMimeTypes[0])).toBe(true)
})
it('should return true if no specific supported mimeTypes given', () => {
const { previewService } = getWrapper()
expect(previewService.isMimetypeSupported('image/png')).toBe(true)
})
it('should return false if mimeType is not supported', () => {
const supportedMimeTypes = ['image/png']
const { previewService } = getWrapper({ supportedMimeTypes })
expect(previewService.isMimetypeSupported('image/jpeg')).toBe(false)
})
})
describe('method "getSupportedMimeTypes"', () => {
it('reads the supported mime types from the capabilities', () => {
const supportedMimeTypes = ['image/png']
const { previewService } = getWrapper({ supportedMimeTypes })
expect(previewService.getSupportedMimeTypes()).toEqual(supportedMimeTypes)
})
it('filters the supported mime types from the capabilities', () => {
const supportedMimeTypes = ['image/png', 'text/plain']
const { previewService } = getWrapper({ supportedMimeTypes })
expect(previewService.getSupportedMimeTypes('image')).toEqual([supportedMimeTypes[0]])
})
})
describe('method "loadPreview"', () => {
it('does not load preview if no version specified', async () => {
const supportedMimeTypes = ['image/png']
const { previewService } = getWrapper({ supportedMimeTypes })
const preview = await previewService.loadPreview({
space: mock<SpaceResource>(),
resource: mock<Resource>()
})
expect(preview).toBeUndefined()
})
it('does not load preview if mimeType not supported', async () => {
const supportedMimeTypes = ['image/png']
const { previewService } = getWrapper({ supportedMimeTypes, version: '1' })
const preview = await previewService.loadPreview({
space: mock<SpaceResource>(),
resource: mock<Resource>({ mimeType: 'text/plain' })
})
expect(preview).toBeUndefined()
})
it('does not load preview for folders', async () => {
const supportedMimeTypes = ['image/png']
const { previewService } = getWrapper({ supportedMimeTypes, version: '1' })
const preview = await previewService.loadPreview({
space: mock<SpaceResource>(),
resource: mock<Resource>({ mimeType: supportedMimeTypes[0], type: 'folder' })
})
expect(preview).toBeUndefined()
})
describe('private files', () => {
it('loads preview', async () => {
const objectUrl = 'objectUrl'
const supportedMimeTypes = ['image/png']
const { previewService } = getWrapper({
supportedMimeTypes,
version: '1'
})
window.URL.createObjectURL = vi.fn().mockImplementation(() => objectUrl)
const preview = await previewService.loadPreview({
space: mock<SpaceResource>(),
resource: mock<Resource>({ mimeType: supportedMimeTypes[0], webDavPath: '/', etag: '' })
})
expect(preview).toEqual(objectUrl)
})
it('loads preview using cache', async () => {
const objectUrl = 'objectUrl'
const supportedMimeTypes = ['image/png']
const { previewService, clientService } = getWrapper({
supportedMimeTypes,
version: '1'
})
const resourceMock = mock<Resource>({
id: '1',
mimeType: supportedMimeTypes[0],
webDavPath: '/',
etag: ''
})
window.URL.createObjectURL = vi.fn().mockImplementation(() => objectUrl)
const preview = await previewService.loadPreview(
{ space: mock<SpaceResource>(), resource: resourceMock },
true
)
expect(preview).toEqual(objectUrl)
expect(clientService.httpAuthenticated.get).toHaveBeenCalledTimes(1)
const cachedPreview = await previewService.loadPreview(
{ space: mock<SpaceResource>(), resource: resourceMock },
true
)
expect(preview).toEqual(cachedPreview)
expect(clientService.httpAuthenticated.get).toHaveBeenCalledTimes(1)
})
})
describe('public files', () => {
it('loads preview', async () => {
const downloadURL = 'downloadURL'
const supportedMimeTypes = ['image/png']
const { previewService } = getWrapper({
supportedMimeTypes,
version: '1'
})
const preview = await previewService.loadPreview({
space: mock<SpaceResource>({ driveType: 'public' }),
resource: mock<Resource>({ mimeType: supportedMimeTypes[0], downloadURL, etag: '' })
})
expect(preview).toEqual(`${downloadURL}?scalingup=0&preview=1&a=1`)
})
})
})
})
const getWrapper = ({
supportedMimeTypes = [],
version = undefined,
accessToken = 'token'
} = {}) => {
const clientService = mockDeep<ClientService>()
clientService.httpAuthenticated.get.mockResolvedValue({ data: {}, status: 200 } as AxiosResponse)
clientService.httpUnAuthenticated.head.mockResolvedValue({
data: {},
status: 200
} as AxiosResponse)
createTestingPinia({ initialState: { user: { user: mock<User>() }, auth: { accessToken } } })
const userStore = useUserStore()
const authStore = useAuthStore()
const capabilityStore = useCapabilityStore()
const configStore = useConfigStore()
capabilityStore.capabilities.files = { thumbnail: { supportedMimeTypes, version } }
return {
previewService: new PreviewService({
configStore,
clientService,
userStore,
authStore,
capabilityStore
}),
clientService
}
}
| owncloud/web/packages/web-pkg/tests/unit/services/previewService.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/services/previewService.spec.ts",
"repo_id": "owncloud",
"token_count": 2388
} | 917 |
<template>
<oc-modal
v-if="modal"
:element-id="modal.elementId"
:element-class="modal.elementClass"
:title="modal.title"
:variation="modal.variation"
:icon="modal.icon"
:message="modal.message"
:has-input="modal.hasInput"
:input-description="modal.inputDescription"
:input-error="modal.inputError"
:input-label="modal.inputLabel"
:input-selection-range="modal.inputSelectionRange"
:input-type="modal.inputType"
:input-value="modal.inputValue"
:hide-actions="modal.hideActions"
:hide-confirm-button="modal.hideConfirmButton"
:button-cancel-text="modal.cancelText"
:button-confirm-text="modal.confirmText"
:button-confirm-disabled="modal.confirmDisabled"
:contextual-helper-label="modal.contextualHelperLabel"
:contextual-helper-data="modal.contextualHelperData"
:focus-trap-initial="modal.focusTrapInitial"
@cancel="onModalCancel"
@confirm="onModalConfirm"
@input="onModalInput"
>
<template v-if="modal.customComponent" #content>
<component
:is="modal.customComponent"
ref="customComponentRef"
:modal="modal"
v-bind="modal.customComponentAttrs?.() || {}"
@confirm="onModalConfirm"
@cancel="onModalCancel"
@update:confirm-disabled="onModalConfirmDisabled"
/>
</template>
</oc-modal>
</template>
<script lang="ts">
import { defineComponent, ref, unref } from 'vue'
import { storeToRefs } from 'pinia'
import { useLoadingService, useModals, CustomModalComponentInstance } from '@ownclouders/web-pkg'
export default defineComponent({
setup() {
const loadingService = useLoadingService()
const modalStore = useModals()
const { activeModal: modal } = storeToRefs(modalStore)
const { updateModal, removeModal } = modalStore
const customComponentRef = ref<CustomModalComponentInstance>()
const onModalConfirm = async (value?: string) => {
try {
updateModal(unref(modal)?.id, 'confirmDisabled', true)
if (unref(modal)?.onConfirm) {
await loadingService.addTask(async () => {
await unref(modal).onConfirm(value)
})
} else if (unref(customComponentRef)?.onConfirm) {
await loadingService.addTask(() => unref(customComponentRef).onConfirm())
}
} catch (error) {
updateModal(unref(modal)?.id, 'confirmDisabled', false)
return
}
removeModal(unref(modal)?.id)
}
const onModalCancel = () => {
if (unref(modal)?.onCancel) {
unref(modal).onCancel()
} else if (unref(customComponentRef)?.onCancel) {
unref(customComponentRef).onCancel()
}
removeModal(unref(modal)?.id)
}
const onModalInput = (value: string) => {
if (!unref(modal).onInput) {
return
}
// provide onError callback
const setError = (error: string) => updateModal(unref(modal).id, 'inputError', error)
unref(modal).onInput(value, setError)
}
const onModalConfirmDisabled = (value: boolean) => {
updateModal(unref(modal).id, 'confirmDisabled', value)
}
return {
customComponentRef,
modal,
onModalConfirm,
onModalCancel,
onModalInput,
onModalConfirmDisabled
}
}
})
</script>
| owncloud/web/packages/web-runtime/src/components/ModalWrapper.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/components/ModalWrapper.vue",
"repo_id": "owncloud",
"token_count": 1419
} | 918 |
import LayoutPlain from '../../layouts/Plain.vue'
import LayoutApplication from '../../layouts/Application.vue'
import LayoutLoading from '../../layouts/Loading.vue'
import { isPublicLinkContextRequired, isUserContextRequired } from '../../router'
import { computed, unref } from 'vue'
import { Router } from 'vue-router'
import { useRouter, useAuthStore, AuthStore } from '@ownclouders/web-pkg'
export interface LayoutOptions {
authStore?: AuthStore
router?: Router
}
const layoutTypes = ['plain', 'loading', 'application'] as const
type LayoutType = (typeof layoutTypes)[number]
export const useLayout = (options?: LayoutOptions) => {
const authStore = options?.authStore || useAuthStore()
const router = options?.router || useRouter()
const layoutType = computed<LayoutType>(() => {
const plainLayoutRoutes = [
'login',
'logout',
'oidcCallback',
'oidcSilentRedirect',
'resolvePublicLink',
'accessDenied'
]
if (
!unref(router.currentRoute).name ||
plainLayoutRoutes.includes(unref(router.currentRoute).name as string)
) {
return 'plain'
}
if (isPublicLinkContextRequired(router, unref(router.currentRoute))) {
return authStore.publicLinkContextReady ? 'application' : 'loading'
}
if (isUserContextRequired(router, unref(router.currentRoute))) {
return authStore.userContextReady ? 'application' : 'loading'
}
return 'application'
})
const layout = computed(() => {
switch (unref(layoutType)) {
case 'application':
return LayoutApplication
case 'loading':
return LayoutLoading
case 'plain':
default:
return LayoutPlain
}
})
return {
layout
}
}
| owncloud/web/packages/web-runtime/src/composables/layout/useLayout.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/composables/layout/useLayout.ts",
"repo_id": "owncloud",
"token_count": 619
} | 919 |
import { ConfigStore } from '@ownclouders/web-pkg'
import { v4 as uuidV4 } from 'uuid'
import merge from 'lodash-es/merge'
export const loadCustomTranslations = async ({
configStore
}: {
configStore: ConfigStore
}): Promise<unknown> => {
const customTranslations = {}
for (const customTranslation of configStore.customTranslations) {
const customTranslationResponse = await fetch(customTranslation.url, {
headers: { 'X-Request-ID': uuidV4() }
})
if (customTranslationResponse.status !== 200) {
console.error(
`translation file ${customTranslation} could not be loaded. HTTP status-code ${customTranslationResponse.status}`
)
continue
}
try {
const customTranslationJSON = await customTranslationResponse.json()
merge(customTranslations, customTranslationJSON)
} catch (e) {
console.error(`translation file ${customTranslation} could not be parsed. ${e}`)
}
}
return customTranslations
}
| owncloud/web/packages/web-runtime/src/helpers/customTranslations.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/helpers/customTranslations.ts",
"repo_id": "owncloud",
"token_count": 320
} | 920 |
<template>
<div class="oc-login-card oc-position-center">
<img class="oc-login-logo" :src="logoImg" alt="" :aria-hidden="true" />
<div class="oc-login-card-body">
<h1 v-translate class="oc-login-card-title">Missing or invalid config</h1>
<p v-translate>Please check if the file config.json exists and is correct.</p>
<p v-translate>Also, make sure to check the browser console for more information.</p>
</div>
<div class="oc-login-card-footer">
<p>
<span v-text="$gettext('For help visit our')" />
<a v-translate href="https://owncloud.dev/clients/web" target="_blank">documentation</a>
<span v-text="$gettext('or join our')" />
<a v-translate href="https://talk.owncloud.com/channel/web" target="_blank">chat</a>.
</p>
<p>
{{ footerSlogan }}
</p>
</div>
</div>
</template>
<script lang="ts">
import { computed, defineComponent } from 'vue'
import { useThemeStore } from '@ownclouders/web-pkg'
import { useHead } from '../composables/head'
import { storeToRefs } from 'pinia'
export default defineComponent({
name: 'MissingConfigPage',
setup() {
const themeStore = useThemeStore()
const { currentTheme } = storeToRefs(themeStore)
const logoImg = computed(() => currentTheme.value.logo.login)
const footerSlogan = computed(() => currentTheme.value.common.slogan)
useHead()
return {
logoImg,
footerSlogan
}
}
})
</script>
| owncloud/web/packages/web-runtime/src/pages/missingOrInvalidConfig.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/pages/missingOrInvalidConfig.vue",
"repo_id": "owncloud",
"token_count": 589
} | 921 |
import Avatar from 'web-runtime/src/components/Avatar.vue'
import { defaultComponentMocks, defaultPlugins, shallowMount } from 'web-test-helpers'
import { mock, mockDeep } from 'vitest-mock-extended'
import { CapabilityStore, ClientService } from '@ownclouders/web-pkg'
import { AxiosResponse } from 'axios'
import { nextTick } from 'vue'
import { OcAvatar } from 'design-system/src/components'
const propsData = {
userName: 'admin',
userid: 'admin',
width: 24
}
const ocSpinner = 'oc-spinner-stub'
const ocAvatar = 'oc-avatar-stub'
describe('Avatar component', () => {
window.URL.createObjectURL = vi.fn()
it('should set user when the component is mounted', () => {
const spySetUser = vi.spyOn(Avatar.methods, 'setUser')
getShallowWrapper()
expect(spySetUser).toHaveBeenCalledTimes(1)
expect(spySetUser).toHaveBeenCalledWith(propsData.userid)
})
describe('when the component is still loading', () => {
it('should render oc-spinner but not oc-avatar', () => {
const { wrapper } = getShallowWrapper(true)
const spinner = wrapper.find(ocSpinner)
const avatar = wrapper.find(ocAvatar)
expect(avatar.exists()).toBeFalsy()
expect(spinner.exists()).toBeTruthy()
expect(spinner.attributes().style).toEqual(
`width: ${propsData.width}px; height: ${propsData.width}px;`
)
})
})
describe('when the component is not loading anymore', () => {
it('should render oc-avatar but not oc-spinner', () => {
const { wrapper } = getShallowWrapper()
const spinner = wrapper.find(ocSpinner)
const avatar = wrapper.find(ocAvatar)
expect(spinner.exists()).toBeFalsy()
expect(avatar.exists()).toBeTruthy()
})
it('should set props on oc-avatar component', () => {
const { wrapper } = getShallowWrapper()
const avatar = wrapper.findComponent<typeof OcAvatar>(ocAvatar)
expect(avatar.props().width).toEqual(propsData.width)
expect(avatar.props().userName).toEqual(propsData.userName)
})
describe('when an avatar is not found', () => {
it('should set empty string to src prop on oc-avatar component', () => {
const { wrapper } = getShallowWrapper()
const avatar = wrapper.findComponent<typeof OcAvatar>(ocAvatar)
expect(avatar.props().src).toEqual('')
})
})
describe('when an avatar is found', () => {
const blob = 'blob:https://web.org/6fe8f675-6727'
it('should set blob as src prop on oc-avatar component', async () => {
global.URL.createObjectURL = vi.fn(() => blob)
const clientService = mockDeep<ClientService>()
clientService.httpAuthenticated.get.mockResolvedValue(
mock<AxiosResponse>({
status: 200,
data: blob
})
)
const { wrapper } = getShallowWrapper(false, clientService)
await nextTick()
await nextTick()
await nextTick()
await nextTick()
await nextTick()
const avatar = wrapper.findComponent<typeof OcAvatar>(ocAvatar)
expect(avatar.props().src).toEqual(blob)
})
})
})
})
function getShallowWrapper(loading = false, clientService = undefined) {
const mocks = { ...defaultComponentMocks() }
if (!clientService) {
clientService = mockDeep<ClientService>()
clientService.httpAuthenticated.get.mockResolvedValue(mock<AxiosResponse>({ status: 200 }))
}
mocks.$clientService = clientService
const capabilities = {
files_sharing: { user: { profile_picture: true } }
} satisfies Partial<CapabilityStore['capabilities']>
return {
wrapper: shallowMount(Avatar, {
props: propsData,
data() {
return {
loading
}
},
global: {
mocks,
plugins: [...defaultPlugins({ piniaOptions: { capabilityState: { capabilities } } })]
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/components/Avatar.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Avatar.spec.ts",
"repo_id": "owncloud",
"token_count": 1541
} | 922 |
import { computed } from 'vue'
import TopBar from 'web-runtime/src/components/Topbar/TopBar.vue'
import { defaultComponentMocks, defaultPlugins, shallowMount } from 'web-test-helpers'
const mockUseEmbedMode = vi.fn().mockReturnValue({ isEnabled: computed(() => false) })
vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({
...(await importOriginal<any>()),
useEmbedMode: vi.fn().mockImplementation(() => mockUseEmbedMode())
}))
describe('Top Bar component', () => {
it('Displays applications menu', () => {
const { wrapper } = getWrapper()
expect(wrapper.find('applications-menu-stub').exists()).toBeTruthy()
})
describe('notifications bell', () => {
it('should display in authenticated context if announced via capabilities', () => {
const { wrapper } = getWrapper({
capabilities: {
notifications: { 'ocs-endpoints': ['list', 'get', 'delete'] }
}
})
expect(wrapper.find('notifications-stub').exists()).toBeTruthy()
})
it('should not display in an unauthenticated context', () => {
const { wrapper } = getWrapper({
userContextReady: false,
capabilities: {
notifications: { 'ocs-endpoints': ['list', 'get', 'delete'] }
}
})
expect(wrapper.find('notifications-stub').exists()).toBeFalsy()
})
it('should not display if endpoint list is missing', () => {
const { wrapper } = getWrapper({
capabilities: { notifications: { 'ocs-endpoints': [] } }
})
expect(wrapper.find('notifications-stub').exists()).toBeFalsy()
})
})
it.each(['applications-menu', 'feedback-link', 'notifications', 'user-menu'])(
'should hide %s when mode is "embed"',
(componentName) => {
mockUseEmbedMode.mockReturnValue({
isEnabled: computed(() => true)
})
const { wrapper } = getWrapper()
expect(wrapper.find(`${componentName}-stub`).exists()).toBeFalsy()
}
)
it.each(['applications-menu', 'feedback-link', 'notifications', 'user-menu'])(
'should not hide %s when mode is not "embed"',
(componentName) => {
mockUseEmbedMode.mockReturnValue({
isEnabled: computed(() => false)
})
const { wrapper } = getWrapper({
capabilities: {
notifications: { 'ocs-endpoints': ['list', 'get', 'delete'] }
}
})
expect(wrapper.find(`${componentName}-stub`).exists()).toBeTruthy()
}
)
})
const getWrapper = ({ capabilities = {}, userContextReady = true } = {}) => {
const mocks = { ...defaultComponentMocks() }
return {
wrapper: shallowMount(TopBar, {
props: {
applicationsList: ['testApp']
},
global: {
plugins: [
...defaultPlugins({
piniaOptions: {
authState: { userContextReady },
capabilityState: { capabilities },
configState: { options: { disableFeedbackLink: false } }
}
})
],
stubs: { 'router-link': true, 'portal-target': true, notifications: true },
mocks,
provide: mocks
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/components/Topbar/TopBar.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Topbar/TopBar.spec.ts",
"repo_id": "owncloud",
"token_count": 1261
} | 923 |
import account from '../../../src/pages/account.vue'
import {
defaultComponentMocks,
defaultPlugins,
mockAxiosResolve,
shallowMount,
mockAxiosReject
} from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { AxiosResponse } from 'axios'
import { useMessages, useResourcesStore } from '@ownclouders/web-pkg'
import { LanguageOption, SettingsBundle, SettingsValue } from 'web-runtime/src/helpers/settings'
import { User } from '@ownclouders/web-client/src/generated'
const $route = {
meta: {
title: 'Some Title'
}
}
const selectors = {
pageTitle: '.oc-page-title',
loaderStub: 'oc-spinner-stub',
editUrlButton: '[data-testid="account-page-edit-url-btn"]',
editPasswordButton: '[data-testid="account-page-edit-password-btn"]',
logoutButton: '[data-testid="account-page-logout-url-btn"]',
accountPageInfo: '.account-page-info',
groupNames: '[data-testid="group-names"]',
groupNamesEmpty: '[data-testid="group-names-empty"]',
gdprExport: '[data-testid="gdpr-export"]'
}
describe('account page', () => {
describe('public link context', () => {
it('should render a limited view', async () => {
const { wrapper } = getWrapper({ isUserContext: false, isPublicLinkContext: true })
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
expect(wrapper.html()).toMatchSnapshot()
})
})
describe('header section', () => {
describe('edit url button', () => {
it('should be displayed if defined via config', async () => {
const { wrapper } = getWrapper({
accountEditLink: { href: '/' }
})
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
const editUrlButton = wrapper.find(selectors.editUrlButton)
expect(editUrlButton.html()).toMatchSnapshot()
})
it('should not be displayed if not defined via config', async () => {
const { wrapper } = getWrapper()
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
const editUrlButton = wrapper.find(selectors.editUrlButton)
expect(editUrlButton.exists()).toBeFalsy()
})
})
})
describe('account information section', () => {
it('displays basic user information', async () => {
const { wrapper } = getWrapper({
user: mock<User>({
onPremisesSamAccountName: 'some-username',
displayName: 'some-displayname',
mail: 'some-email',
memberOf: []
})
})
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
const accountPageInfo = wrapper.find(selectors.accountPageInfo)
expect(accountPageInfo.html()).toMatchSnapshot()
})
describe('group membership', () => {
it('displays message if not member of any groups', async () => {
const { wrapper } = getWrapper()
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
const groupNamesEmpty = wrapper.find(selectors.groupNamesEmpty)
expect(groupNamesEmpty.exists()).toBeTruthy()
})
it('displays group names', async () => {
const { wrapper } = getWrapper({
user: mock<User>({
memberOf: [{ displayName: 'one' }, { displayName: 'two' }, { displayName: 'three' }]
})
})
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
const groupNames = wrapper.find(selectors.groupNames)
expect(groupNames.html()).toMatchSnapshot()
})
})
describe('Logout from all devices link', () => {
it('should render the logout from active devices if logoutUrl is provided', async () => {
const { wrapper } = getWrapper()
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
expect(wrapper.find('[data-testid="logout"]').exists()).toBe(true)
})
it("shouldn't render the logout from active devices if logoutUrl isn't provided", async () => {
const { wrapper } = getWrapper()
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
wrapper.vm.logoutUrl = undefined
expect(wrapper.find('[data-testid="logout"]').exists()).toBe(true)
})
it('should use url from configuration manager', async () => {
const { wrapper } = getWrapper()
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
const logoutButton = wrapper.find(selectors.logoutButton)
expect(logoutButton.attributes('href')).toBe('https://account-manager/logout')
})
})
})
describe('Preferences section', () => {
describe('change password button', () => {
it('should be displayed if not disabled via capability', async () => {
const { wrapper } = getWrapper({
capabilities: { graph: { users: { change_password_self_disabled: false } } }
})
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
const editPasswordButton = wrapper.find(selectors.editPasswordButton)
expect(editPasswordButton.exists()).toBeTruthy()
})
it('should not be displayed if disabled via capability', async () => {
const { wrapper } = getWrapper({
capabilities: { graph: { users: { change_password_self_disabled: true } } }
})
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
const editPasswordButton = wrapper.find(selectors.editPasswordButton)
expect(editPasswordButton.exists()).toBeFalsy()
})
})
})
describe('Method "updateDisableEmailNotifications', () => {
it('should show a message on success', async () => {
const { wrapper, mocks } = getWrapper()
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
mocks.$clientService.httpAuthenticated.post.mockResolvedValueOnce(mockAxiosResolve({}))
await wrapper.vm.updateDisableEmailNotifications(true)
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalled()
})
it('should show a message on error', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
const { wrapper, mocks } = getWrapper()
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
mocks.$clientService.httpAuthenticated.post.mockImplementation(() => mockAxiosReject('err'))
await wrapper.vm.updateDisableEmailNotifications(true)
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalled()
})
})
describe('Method "updateSelectedLanguage', () => {
it('should show a message on success', async () => {
const { wrapper, mocks } = getWrapper({})
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
mocks.$clientService.graphAuthenticated.users.editMe.mockResolvedValueOnce(
mockAxiosResolve({})
)
await wrapper.vm.updateSelectedLanguage({ value: 'en' } as LanguageOption)
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalled()
})
it('should show a message on error', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
const { wrapper, mocks } = getWrapper({})
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
mocks.$clientService.graphAuthenticated.users.editMe.mockImplementation(() =>
mockAxiosReject('err')
)
await wrapper.vm.updateSelectedLanguage({ value: 'en' } as LanguageOption)
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalled()
})
})
describe('Method "updateViewOptionsWebDavDetails', () => {
it('should show a message on success', async () => {
const { wrapper } = getWrapper({})
await wrapper.vm.loadAccountBundleTask.last
await wrapper.vm.loadValuesListTask.last
await wrapper.vm.loadGraphUserTask.last
await wrapper.vm.updateViewOptionsWebDavDetails(true)
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalled()
const { setAreWebDavDetailsShown } = useResourcesStore()
expect(setAreWebDavDetailsShown).toHaveBeenCalled()
})
})
})
function getWrapper({
user = mock<User>({ memberOf: [] }),
capabilities = {},
accountEditLink = undefined,
spaces = [],
isPublicLinkContext = false,
isUserContext = true
} = {}) {
const mocks = {
...defaultComponentMocks(),
$route
}
mocks.$clientService.httpAuthenticated.post.mockImplementation((url) => {
let response = {}
if (url.endsWith('bundles-list')) {
response = { bundles: [mock<SettingsBundle>()] }
}
if (url.endsWith('values-list')) {
response = { values: [mock<SettingsValue>()] }
}
return Promise.resolve(mockAxiosResolve(response))
})
mocks.$clientService.graphAuthenticated.users.getMe.mockResolvedValue(
mock<AxiosResponse>({ data: { id: '1' } })
)
return {
mocks,
wrapper: shallowMount(account, {
global: {
plugins: [
...defaultPlugins({
piniaOptions: {
userState: { user },
authState: {
userContextReady: isUserContext,
publicLinkContextReady: isPublicLinkContext
},
spacesState: { spaces },
capabilityState: { capabilities },
configState: {
options: {
logoutUrl: 'https://account-manager/logout',
...(accountEditLink && { accountEditLink })
}
}
}
})
],
mocks,
provide: mocks,
stubs: {
'oc-button': true,
'oc-icon': true
}
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/pages/account.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/pages/account.spec.ts",
"repo_id": "owncloud",
"token_count": 4218
} | 924 |
export * from './mocks/defaultComponentMocks'
export * from './mocks/defaultStubs'
export * from './mocks'
export * from './defaultPlugins'
export * from './helpers'
| owncloud/web/packages/web-test-helpers/src/index.ts/0 | {
"file_path": "owncloud/web/packages/web-test-helpers/src/index.ts",
"repo_id": "owncloud",
"token_count": 55
} | 925 |
#!/usr/bin/env bash
# when deleting the tests suites from /features there might be the tests scenarios that might be in the expected to failure file
# this script checks if there are such scenarios in the expected to failure file which needs to be deleted
# helper functions
log_error() {
echo -e "\e[31m$1\e[0m"
}
log_info() {
echo -e "\e[37m$1\e[0m"
}
log_success() {
echo -e "\e[32m$1\e[0m"
}
SCRIPT_PATH=$(dirname "$0")
PATH_TO_SUITES="${SCRIPT_PATH}/features"
PATH_TO_EXPECTED_FAILURE_FILE="${SCRIPT_PATH}/expected-failures-with-ocis-server-ocis-storage.md"
# contains all the suites names inside tests/acceptance/features
AVAILABLE_SUITES=($(ls -l "$PATH_TO_SUITES" | grep '^d' | awk '{print $NF}'))
# regex to match [someSuites/someFeatureFile.feature:lineNumber]
SCENARIO_REGEX="\[([a-zA-Z0-9]+/[a-zA-Z0-9]+\.feature:[0-9]+)]"
# contains all those suites available in the expected to failure files in pattern [someSuites/someFeatureFile.feature:lineNumber]
EXPECTED_FAILURE_SCENARIOS=($(grep -Eo ${SCENARIO_REGEX} ${PATH_TO_EXPECTED_FAILURE_FILE}))
# get and store only the suites names from EXPECTED_FAILURE_SCENARIOS
EXPECTED_FAILURE_SUITES=()
for scenario in "${EXPECTED_FAILURE_SCENARIOS[@]}"; do
if [[ $scenario =~ \[([a-zA-Z0-9]+) ]]; then
suite="${BASH_REMATCH[1]}"
EXPECTED_FAILURE_SUITES+=("$suite")
fi
done
# also filter the duplicated suites name
EXPECTED_FAILURE_SUITES=($(echo "${EXPECTED_FAILURE_SUITES[@]}" | tr ' ' '\n' | sort | uniq))
# Check the existence of the suite
NONEXISTING_SCENARIOS=()
for suite in "${EXPECTED_FAILURE_SUITES[@]}"; do
if [[ " ${AVAILABLE_SUITES[*]} " != *" $suite "* ]]; then
pattern="(${suite}/[a-zA-Z0-9]+\\.feature:[0-9]+)"
NONEXISTING_SCENARIOS+=($(grep -Eo ${pattern} ${PATH_TO_EXPECTED_FAILURE_FILE}))
fi
done
count="${#NONEXISTING_SCENARIOS[@]}"
if [ "$count" -gt 0 ]; then
log_info "The following test scenarios do not exist anymore:"
log_info "They can be deleted from the '${PATH_TO_EXPECTED_FAILURE_FILE}'."
for scenario_path in "${NONEXISTING_SCENARIOS[@]}"; do
log_error "$scenario_path"
done
exit 1
fi
log_success "All the suites in the expected failure file exist in the test suites"
| owncloud/web/tests/acceptance/check-deleted-suites-in-expected-failure.sh/0 | {
"file_path": "owncloud/web/tests/acceptance/check-deleted-suites-in-expected-failure.sh",
"repo_id": "owncloud",
"token_count": 887
} | 926 |
## Scenarios from web tests that are expected to fail on OCIS with OCIS storage
Lines that contain a format like "[someSuite.someFeature.feature:n](https://github.com/owncloud/web/path/to/feature)"
are lines that document a specific expected failure. Follow that with a URL to the line in the feature file in GitHub.
Please follow this format for the actual expected failures.
Level-3 headings should be used for the references to the relevant issues. Include the issue title with a link to the issue in GitHub.
Other free text and markdown formatting can be used elsewhere in the document if needed. But if you want to explain something about the issue, then please post that in the issue itself.
| owncloud/web/tests/acceptance/expected-failures-with-ocis-server-ocis-storage.md/0 | {
"file_path": "owncloud/web/tests/acceptance/expected-failures-with-ocis-server-ocis-storage.md",
"repo_id": "owncloud",
"token_count": 164
} | 927 |
@ocis-reva-issue-194
Feature: Sharing files and folders with internal groups
As a user
I want to share files and folders with groups
So that those groups can access the files and folders
Background:
Given the administrator has set the default folder for received shares to "Shares" in the server
And these users have been created with default attributes and without skeleton files in the server:
| username |
| Alice |
| Brian |
| Carol |
@issue-5216
Scenario Outline: sharing files and folder with an internal problematic group name
Given these groups have been created in the server:
| groupname |
| <group> |
And user "Carol" has created folder "simple-folder" in the server
And user "Carol" has created file "testimage.jpg" in the server
And user "Alice" has been added to group "<group>" in the server
And user "Carol" has logged in using the webUI
When the user shares folder "simple-folder" with group "<group>" as "Viewer" using the webUI
And the user shares file "testimage.jpg" with group "<group>" as "Viewer" using the webUI
Then group "<group>" should be listed as "Can view" in the collaborators list for folder "simple-folder" on the webUI
And group "<group>" should be listed as "Can view" in the collaborators list for file "testimage.jpg" on the webUI
Examples:
| group |
| ?\?@#%@,; |
| नेपाली |
Scenario: Share file with a user and a group with same name
Given these groups have been created in the server:
| groupname |
| Alice |
And user "Brian" has been added to group "Alice" in the server
And user "Carol" has uploaded file with content "Carol file" to "/randomfile.txt" in the server
And user "Carol" has logged in using the webUI
When the user shares file "randomfile.txt" with user "Alice Hansen" as "Editor" using the webUI
And the user shares file "randomfile.txt" with group "Alice" as "Editor" using the webUI
And the user types "Alice" in the share-with-field
Then "group" "Alice" should not be listed in the autocomplete list on the webUI
And the content of file "Shares/randomfile.txt" for user "Alice" should be "Carol file" in the server
And the content of file "Shares/randomfile.txt" for user "Brian" should be "Carol file" in the server
Scenario: Share file with a group and a user with same name
Given these groups have been created in the server:
| groupname |
| Alice |
And user "Brian" has been added to group "Alice" in the server
And user "Carol" has uploaded file with content "Carol file" to "/randomfile.txt" in the server
And user "Carol" has logged in using the webUI
When the user shares file "randomfile.txt" with group "Alice" as "Editor" using the webUI
And the user shares file "randomfile.txt" with user "Alice Hansen" as "Editor" using the webUI
And the user types "Alice" in the share-with-field
Then "user" "Alice Hansen" should not be listed in the autocomplete list on the webUI
And the content of file "Shares/randomfile.txt" for user "Brian" should be "Carol file" in the server
And the content of file "Shares/randomfile.txt" for user "Alice" should be "Carol file" in the server
Scenario: Share file with a user and again with a group with same name but different case
Given these groups have been created in the server:
| groupname |
| ALICE |
And user "Brian" has been added to group "ALICE" in the server
And user "Carol" has uploaded file with content "Carol file" to "/randomfile.txt" in the server
And user "Carol" has logged in using the webUI
When the user shares file "randomfile.txt" with user "Alice Hansen" as "Editor" using the webUI
And the user shares file "randomfile.txt" with group "ALICE" as "Editor" using the webUI
And the user types "ALICE" in the share-with-field
Then "group" "ALICE" should not be listed in the autocomplete list on the webUI
And the content of file "Shares/randomfile.txt" for user "Brian" should be "Carol file" in the server
And the content of file "Shares/randomfile.txt" for user "Alice" should be "Carol file" in the server
Scenario: Share file with a group and again with a user with same name but different case
Given these groups have been created in the server:
| groupname |
| ALICE |
And user "Brian" has been added to group "ALICE" in the server
And user "Carol" has uploaded file with content "Carol file" to "/randomfile.txt" in the server
And user "Carol" has logged in using the webUI
When the user shares file "randomfile.txt" with group "ALICE" as "Editor" using the webUI
And the user shares file "randomfile.txt" with user "Alice Hansen" as "Editor" using the webUI
And the user types "Alice" in the share-with-field
Then "user" "Alice Hansen" should not be listed in the autocomplete list on the webUI
And the content of file "Shares/randomfile.txt" for user "Brian" should be "Carol file" in the server
And the content of file "Shares/randomfile.txt" for user "Alice" should be "Carol file" in the server
| owncloud/web/tests/acceptance/features/webUISharingInternalGroupsEdgeCases/shareWithGroupsEdgeCases.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUISharingInternalGroupsEdgeCases/shareWithGroupsEdgeCases.feature",
"repo_id": "owncloud",
"token_count": 1623
} | 928 |
Feature: File Upload
As a QA engineer
I would like to test uploads of all kind of funny filenames via the WebUI
These tests are written in a way that multiple file names are tested in one scenario
that is not academically correct but saves a lot of time
Background:
Given user "Alice" has been created with default attributes and without skeleton files in the server
And user "Alice" has logged in using the webUI
And the user browses to the files page
Scenario: simple upload of a file that does not exist before
When the user uploads file "new-'single'quotes.txt" using the webUI
Then file "new-'single'quotes.txt" should be listed on the webUI
And as "Alice" the content of "new-'single'quotes.txt" in the server should be the same as the content of local file "new-'single'quotes.txt"
When the user uploads file "new-strängé filename (duplicate #2 &).txt" using the webUI
Then file "new-strängé filename (duplicate #2 &).txt" should be listed on the webUI
And as "Alice" the content of "new-strängé filename (duplicate #2 &).txt" in the server should be the same as the content of local file "new-strängé filename (duplicate #2 &).txt"
When the user uploads file "zzzz-zzzz-will-be-at-the-end-of-the-folder-when-uploaded.txt" using the webUI
Then file "zzzz-zzzz-will-be-at-the-end-of-the-folder-when-uploaded.txt" should be listed on the webUI
And as "Alice" the content of "zzzz-zzzz-will-be-at-the-end-of-the-folder-when-uploaded.txt" in the server should be the same as the content of local file "zzzz-zzzz-will-be-at-the-end-of-the-folder-when-uploaded.txt"
@smokeTest @ocisSmokeTest
Scenario Outline: upload a new file into a sub folder
Given user "Alice" has created folder "<folder-to-upload-to>" in the server
And the user has reloaded the current page of the webUI
And a file with the size of "3000" bytes and the name "0" has been created locally in the middleware
When the user opens folder "<folder-to-upload-to>" using the webUI
And the user uploads a created file "0" using the webUI
Then file "0" should be listed on the webUI
And as "Alice" the content of "<folder-to-upload-to>/0" in the server should be the same as the content of local file "0"
When the user uploads file "new-'single'quotes.txt" using the webUI
Then file "new-'single'quotes.txt" should be listed on the webUI
And as "Alice" the content of "<folder-to-upload-to>/new-'single'quotes.txt" in the server should be the same as the content of local file "new-'single'quotes.txt"
When the user uploads file "new-strängé filename (duplicate #2 &).txt" using the webUI
Then file "new-strängé filename (duplicate #2 &).txt" should be listed on the webUI
And as "Alice" the content of "<folder-to-upload-to>/new-strängé filename (duplicate #2 &).txt" in the server should be the same as the content of local file "new-strängé filename (duplicate #2 &).txt"
When the user uploads file "zzzz-zzzz-will-be-at-the-end-of-the-folder-when-uploaded.txt" using the webUI
Then file "zzzz-zzzz-will-be-at-the-end-of-the-folder-when-uploaded.txt" should be listed on the webUI
And as "Alice" the content of "<folder-to-upload-to>/zzzz-zzzz-will-be-at-the-end-of-the-folder-when-uploaded.txt" in the server should be the same as the content of local file "zzzz-zzzz-will-be-at-the-end-of-the-folder-when-uploaded.txt"
Examples:
| folder-to-upload-to |
| 0 |
| 'single'quotes |
| strängé नेपाली folder |
Scenario: overwrite an existing file
Given user "Alice" has created file "'single'quotes.txt" in the server
And user "Alice" has created file "strängé filename (duplicate #2 &).txt" in the server
And user "Alice" has created file "zzzz-must-be-last-file-in-folder.txt" in the server
And the user has reloaded the current page of the webUI
When the user uploads overwriting file "'single'quotes.txt" using the webUI
Then file "'single'quotes.txt" should be listed on the webUI
And as "Alice" the content of "'single'quotes.txt" in the server should be the same as the content of local file "'single'quotes.txt"
When the user uploads overwriting file "strängé filename (duplicate #2 &).txt" using the webUI
Then file "strängé filename (duplicate #2 &).txt" should be listed on the webUI
And as "Alice" the content of "strängé filename (duplicate #2 &).txt" in the server should be the same as the content of local file "strängé filename (duplicate #2 &).txt"
When the user uploads overwriting file "zzzz-must-be-last-file-in-folder.txt" using the webUI
Then file "zzzz-must-be-last-file-in-folder.txt" should be listed on the webUI
And as "Alice" the content of "zzzz-must-be-last-file-in-folder.txt" in the server should be the same as the content of local file "zzzz-must-be-last-file-in-folder.txt"
Scenario Outline: upload a big file using difficult names (when chunking in implemented that upload should be chunked)
Given a file with the size of "30000000" bytes and the name <file-name> has been created locally in the middleware
When the user uploads a created file <file-name> using the webUI
Then file <file-name> should be listed on the webUI
And as "Alice" the content of <file-name> in the server should be the same as the content of local file <file-name>
Examples:
| file-name |
| "&#" |
| "TIÄFÜ" |
# upload into "simple-folder" because there is already a folder called "0" in the root
Scenario: Upload a big file called "0" (when chunking in implemented that upload should be chunked)
Given user "Alice" has created folder "simple-folder" in the server
And the user has browsed to the personal page
And a file with the size of "30000000" bytes and the name "0" has been created locally in the middleware
When the user opens folder "simple-folder" using the webUI
And the user uploads a created file "0" using the webUI
Then file "0" should be listed on the webUI
And as "Alice" the content of "simple-folder/0" in the server should be the same as the content of local file "0"
| owncloud/web/tests/acceptance/features/webUIUpload/uploadEdgecases.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUIUpload/uploadEdgecases.feature",
"repo_id": "owncloud",
"token_count": 2064
} | 929 |
const chromedriver = require('chromedriver')
const path = require('path')
const withHttp = (url) => (/^https?:\/\//i.test(url) ? url : `http://${url}`)
const RUN_WITH_LDAP = process.env.RUN_WITH_LDAP === 'true'
const LOCAL_LAUNCH_URL = withHttp(process.env.SERVER_HOST || 'https://host.docker.internal:9200')
const LOCAL_BACKEND_URL = withHttp(process.env.BACKEND_HOST || 'https://host.docker.internal:9200')
const REMOTE_BACKEND_URL = process.env.REMOTE_BACKEND_HOST
? withHttp(process.env.REMOTE_BACKEND_HOST || 'http://localhost:8080')
: undefined
const BACKEND_ADMIN_USERNAME = process.env.BACKEND_USERNAME || 'admin'
const BACKEND_ADMIN_PASSWORD = process.env.BACKEND_PASSWORD || 'admin'
const SELENIUM_HOST = process.env.SELENIUM_HOST || 'localhost'
const SELENIUM_PORT = process.env.SELENIUM_PORT || 4444
const LOCAL_UPLOAD_DIR = process.env.LOCAL_UPLOAD_DIR || '/uploads'
const OCIS_REVA_DATA_ROOT = process.env.OCIS_REVA_DATA_ROOT || '/var/tmp/ocis/storage/owncloud'
const LDAP_SERVER_URL = process.env.LDAP_SERVER_URL || 'ldap://127.0.0.1'
const LDAP_BASE_DN = process.env.LDAP_BASE_DN || 'cn=admin,dc=owncloud,dc=com'
const LDAP_ADMIN_PASSWORD = process.env.LDAP_ADMIN_PASSWORD || 'admin'
const TESTING_DATA_DIR = process.env.TESTING_DATA_DIR || './tests/testing-app/data/'
const OPENID_LOGIN = 'true'
const WEB_UI_CONFIG_FILE =
process.env.WEB_UI_CONFIG_FILE || path.join(__dirname, 'dist/config.json')
const SCREENSHOTS = process.env.SCREENSHOTS === 'true'
const MIDDLEWARE_HOST = withHttp(process.env.MIDDLEWARE_HOST || 'http://host.docker.internal:3000')
const config = {
page_objects_path: './pageObjects',
custom_commands_path: ['./customCommands'],
test_settings: {
default: {
// ocis doesn't have '#' in the url path anymore
launch_url: LOCAL_LAUNCH_URL,
globals: {
waitForConditionTimeout: 10000,
waitForNegativeConditionTimeout: 300,
waitForConditionPollInterval: 10,
mountedUploadDir: LOCAL_UPLOAD_DIR,
backend_url: LOCAL_BACKEND_URL,
remote_backend_url: REMOTE_BACKEND_URL,
backend_admin_username: BACKEND_ADMIN_USERNAME,
backend_admin_password: BACKEND_ADMIN_PASSWORD,
default_backend: 'LOCAL',
ocis: 'true',
ldap: RUN_WITH_LDAP,
openid_login: OPENID_LOGIN,
ldap_url: LDAP_SERVER_URL,
ocis_data_dir: OCIS_REVA_DATA_ROOT,
ldap_base_dn: LDAP_BASE_DN,
testing_data_dir: TESTING_DATA_DIR,
ldap_password: LDAP_ADMIN_PASSWORD,
webUIConfig: WEB_UI_CONFIG_FILE,
screenshots: SCREENSHOTS,
middlewareUrl: MIDDLEWARE_HOST
},
selenium_host: SELENIUM_HOST,
desiredCapabilities: {
browserName: 'chrome',
javascriptEnabled: true,
acceptSslCerts: true,
chromeOptions: {
args: ['disable-gpu', 'ignore-certificate-errors'],
w3c: false
},
loggingPrefs: { browser: 'ALL' }
},
webdriver: {
start_process: false,
port: SELENIUM_PORT,
use_legacy_jsonwire: false
}
},
local: {
globals: {
waitForConditionTimeout: 10000
},
webdriver: {
start_process: false,
server_path: chromedriver.path,
cli_args: ['--port=' + SELENIUM_PORT]
}
},
drone: {
selenium_host: 'selenium',
desiredCapabilities: {
chromeOptions: {
args: ['disable-gpu', 'disable-dev-shm-usage', 'ignore-certificate-errors'],
w3c: false
},
idleTimeout: 180
}
}
}
}
module.exports = config
| owncloud/web/tests/acceptance/nightwatch.conf.js/0 | {
"file_path": "owncloud/web/tests/acceptance/nightwatch.conf.js",
"repo_id": "owncloud",
"token_count": 1620
} | 930 |
const { join } = require('../helpers/path')
module.exports = {
url: function () {
return join(this.api.launchUrl, '/files/favorites/')
},
commands: {
/**
* like build-in navigate() but also waits till for the progressbar to appear and disappear
* @returns {*}
*/
navigateAndWaitTillLoaded: function () {
return this.navigate(this.url()).waitForElementPresent(
this.page.FilesPageElement.filesList().elements.anyAfterLoading
)
}
}
}
| owncloud/web/tests/acceptance/pageObjects/favoritesPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/favoritesPage.js",
"repo_id": "owncloud",
"token_count": 184
} | 931 |
const util = require('util')
const { client } = require('nightwatch-api')
const { join } = require('../helpers/path')
module.exports = {
url: function () {
return join(this.api.launchUrl, '/')
},
commands: {
/**
* @param {string} page
*/
navigateToUsingMenu: async function (page) {
const menuItemSelector = util.format(this.elements.menuItem.selector, page)
let isAppNavigationVisible = false
// Check if the navigation is visible
await this.isVisible(
{
selector: '@appNavigation',
timeout: this.api.globals.waitForNegativeConditionTimeout,
suppressNotFoundErrors: true
},
(result) => {
isAppNavigationVisible = result.value === true
}
)
// If app navigation is not visible, try to click on the menu button
if (!isAppNavigationVisible) {
this.click('@menuButton').waitForAnimationToFinish()
}
await this.useXpath().waitForElementVisible(menuItemSelector).click(menuItemSelector).useCss()
await this.api.page.FilesPageElement.filesList().waitForLoadingFinished()
return this
},
closeMessage: function () {
return this.waitForElementPresent('@messageCloseIcon')
.click('@messageCloseIcon')
.waitForElementNotPresent('@messageCloseIcon')
},
toggleNotificationDrawer: function () {
return this.waitForElementVisible('@notificationBell').click('@notificationBell')
},
/**
* gets list of notifications
*
* @return {Promise<array>}
*/
getNotifications: async function () {
const notifications = []
await this.toggleNotificationDrawer()
await this.waitForElementVisible('@notificationElement').api.elements(
'@notificationElement',
(result) => {
for (const element of result.value) {
this.api.elementIdText(element.ELEMENT, (text) => {
notifications.push(text.value)
})
}
}
)
await this.toggleNotificationDrawer()
return notifications
},
/**
* Perform accept action on the offered shares in the notifications
*/
acceptAllSharesInNotification: async function () {
const notifications = await this.getNotifications()
await this.toggleNotificationDrawer()
for (const element of notifications) {
const acceptShareButton = util.format(
this.elements.acceptSharesInNotifications.selector,
element
)
await this.useXpath()
.waitForElementVisible(acceptShareButton)
.click(acceptShareButton)
.waitForAjaxCallsToStartAndFinish()
.useCss()
}
},
/**
* Perform decline action on the offered shares in the notifications
*/
declineAllSharesInNotification: async function () {
const notifications = await this.getNotifications()
await this.toggleNotificationDrawer()
for (const element of notifications) {
const declineShareButton = util.format(
this.elements.declineSharesInNotifications.selector,
element
)
await this.useXpath()
.waitForElementVisible(declineShareButton)
.click(declineShareButton)
.waitForAjaxCallsToStartAndFinish()
}
},
/**
* Clear all error messages from the webUI
*
* @returns {Promise<void>}
*/
clearAllErrorMessages: async function () {
let notificationElements, cancelButtons
await this.api.element('@errorMessages', (result) => {
notificationElements = result.value.ELEMENT
})
if (!notificationElements) {
return
}
await this.api.elementIdElements(
notificationElements,
this.elements.clearErrorMessage.locateStrategy,
this.elements.clearErrorMessage.selector,
(res) => {
cancelButtons = res.value
}
)
for (const btn of cancelButtons) {
await this.api.elementIdClick(btn.ELEMENT).waitForAnimationToFinish()
}
},
browseToUserProfile: function () {
return this.click('@userMenuButton')
},
getDisplayedMessage: async function (type, titleOnly = false) {
let element = ''
let displayedmessage
let selector = titleOnly ? '@message' : '@messages'
if (type === 'error') {
selector = titleOnly ? '@errorMessage' : '@errorMessages'
} else if (type === 'modal error') {
selector = '@modalErrorMessage'
}
await this.waitForElementVisible(selector)
await this.api.element(selector, (result) => {
element = result.value.ELEMENT
})
await this.api.elementIdText(element, function (result) {
displayedmessage = result.value
})
return displayedmessage
},
followLink: function (linkSelector) {
return this.useXpath().waitForElementVisible(linkSelector).click(linkSelector).useCss()
},
getPopupErrorMessages: async function () {
const messages = []
await this.waitForElementVisible('@errorMessages')
await this.api.elements('@errorMessages', function ({ value }) {
value.forEach(async function ({ ELEMENT }) {
await client.elementIdText(ELEMENT, function ({ value }) {
messages.push(value)
})
})
})
return messages
},
hasErrorMessage: async function (expectedVisible = true) {
let visible = false
const timeout = expectedVisible
? this.api.globals.waitForConditionTimeout
: this.api.globals.waitForNegativeConditionTimeout
const selector = {
selector: this.elements.errorMessage.selector,
locateStrategy: this.elements.errorMessage.locateStrategy
}
await this.isVisible(
{ ...selector, suppressNotFoundErrors: !expectedVisible, timeout },
function ({ value }) {
visible = value === true
}
)
return visible
}
},
elements: {
message: {
selector:
'//*[contains(@class, "oc-notification-message")]//div[contains(@class, "oc-notification-message-title")]',
locateStrategy: 'xpath'
},
messages: {
selector: '//*[contains(@class, "oc-notification-message")]',
locateStrategy: 'xpath'
},
errorMessage: {
selector:
'//*[contains(@class, "oc-notification-message-danger")]//div[contains(@class, "oc-notification-message-title")]',
locateStrategy: 'xpath'
},
modalErrorMessage: {
selector:
'//div[@class=\'oc-modal-body\']/div[contains(@class, "oc-modal-body-message")]/span',
locateStrategy: 'xpath'
},
errorMessages: {
selector:
'//div[contains(@class, "oc-notification-message-danger")]//div[@class="oc-notification-message-title"]',
locateStrategy: 'xpath'
},
clearErrorMessage: {
selector:
'//*[contains(@class, "oc-notification-message-danger")]//button[contains(@aria-label, "Close")]',
locateStrategy: 'xpath'
},
notificationBell: {
selector: '#oc-notifications-bell'
},
ocDialogPromptAlert: {
selector: '.oc-modal .oc-text-input-message'
},
searchInputField: {
selector: '(//input[contains(@class, "oc-search-input")])[1]',
locateStrategy: 'xpath'
},
searchLoadingIndicator: {
selector: '#files-global-search-bar .oc-spinner'
},
searchGlobalButton: {
selector: '//button[.="Search all files ↵"]',
locateStrategy: 'xpath'
},
openSearchButton: {
selector: '.mobile-search-btn'
},
userMenuButton: {
selector: '#_userMenuButton'
},
menuButton: {
selector: '.oc-app-navigation-toggle'
},
menuItem: {
selector:
'//nav[contains(@class, "oc-sidebar-nav")]/ul/li/a/span/span[contains(text(),"%s")]',
locateStrategy: 'xpath'
},
logoutMenuItem: {
selector: '#oc-topbar-account-logout'
},
messageCloseIcon: {
selector: '.oc-alert-close-icon'
},
webContainer: {
selector: '#web'
},
appContainer: {
selector: '.app-container'
},
notificationElement: {
selector: '//div[@id="oc-notifications"]//div[contains(@class, "oc-notifications-message")]',
locateStrategy: 'xpath'
},
declineSharesInNotifications: {
selector:
'//div[@id="oc-notifications"]//span[contains(text(),\'%s\')]/../../div/button[contains(@class, "oc-button-passive")]',
locateStrategy: 'xpath'
},
acceptSharesInNotifications: {
selector:
'//div[@id="oc-notifications"]//span[contains(text(),\'%s\')]/../../div/button[contains(@class, "oc-button-primary")]',
locateStrategy: 'xpath'
},
appNavigation: {
selector: '#web-nav-sidebar'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/webPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/webPage.js",
"repo_id": "owncloud",
"token_count": 3691
} | 932 |
const { Then } = require('@cucumber/cucumber')
require('url-search-params-polyfill')
const httpHelper = require('../helpers/httpHelper')
const webdavHelper = require('../helpers/webdavHelper')
const { client } = require('nightwatch-api')
const { xml2js } = require('xml-js')
const _ = require('lodash')
const assert = require('assert')
/**
* Check if file exists using webdav requests
* @param {string} userId - username
* @param {string} element - path
* @returns {Promise<Response|Error>}
*/
function fileExists(userId, element) {
const davPath = webdavHelper.createDavPath(userId, element)
return httpHelper.propfind(davPath, userId)
}
const getResourceType = function (data) {
let resourceType
const result = xml2js(data, { compact: true })
const responses = _.get(result, 'd:multistatus.d:response')
if (responses instanceof Array) {
resourceType = _.get(responses[0], 'd:propstat.d:prop.d:resourcetype')
} else {
resourceType = _.get(responses, 'd:propstat.d:prop.d:resourcetype')
}
if (Object.keys(resourceType)[0] === 'd:collection') {
return 'folder'
} else {
return 'file'
}
}
const assertResourceType = function (data, resource, type = 'file') {
type = type.toLowerCase()
const foundType = getResourceType(data)
const exists = foundType === type
assert.strictEqual(
exists,
true,
`Expected "${resource}" to be a "${type}", but found "${foundType}"`
)
}
const fileOrFolderShouldExist = function (userId, element, type = 'file') {
return fileExists(userId, element)
.then(function (res) {
assert.strictEqual(res.status, 207, `Resource "${element}" should exist, but does not`)
return res.text()
})
.then(function (data) {
assertResourceType(data, element, type)
})
}
Then('as {string} the last uploaded folder should exist', function (userId) {
return fileOrFolderShouldExist(userId, client.sessionId, 'folder')
})
Then(
'as {string} the last uploaded folder should contain the following files inside the sub-folders:',
async function (user, files) {
files = files.raw().map((item) => item[0])
const sessionId = client.sessionId
const response = await webdavHelper.propfind(
`/files/${user}/${sessionId}`,
user,
[],
'infinity'
)
const result = xml2js(response, { compact: true })
const elements = _.get(result, 'd:multistatus.d:response')
if (elements === undefined) {
throw new Error('Received unexpected response:\n' + result)
}
const uploadedFilesHref = elements
.map((elem) => _.get(elem, 'd:href._text'))
.filter((item) => item)
const regexToExtractBaseName = RegExp(`/${sessionId}/upload[0-9]+file/(.*)`)
const uploadedFilesWithBaseName = uploadedFilesHref
// unmatched items return null, else is array
.map((file) => _.nth(file.match(regexToExtractBaseName), 1))
.filter((item) => item)
const filesNotFoundInUploads = _.difference(files, uploadedFilesWithBaseName)
assert.strictEqual(
filesNotFoundInUploads.length,
0,
'Could not find following files inside sub-folders of the session folder\n' +
filesNotFoundInUploads
)
}
)
| owncloud/web/tests/acceptance/stepDefinitions/webdavContext.js/0 | {
"file_path": "owncloud/web/tests/acceptance/stepDefinitions/webdavContext.js",
"repo_id": "owncloud",
"token_count": 1157
} | 933 |
Feature: general management
Scenario: logo can be changed in the admin settings
When "Admin" logs in
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the general management page
Then "Admin" should be able to upload a logo from the local file "filesForUpload/testavatar.png"
And "Admin" navigates to the general management page
And "Admin" should be able to reset the logo
And "Admin" logs out
| owncloud/web/tests/e2e/cucumber/features/admin-settings/general.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/admin-settings/general.feature",
"repo_id": "owncloud",
"token_count": 129
} | 934 |
Feature: access breadcrumb
As a user
I want to browse to parent folders using breadcrumb
So that I can access resources with ease
Scenario: breadcrumb navigation
Given "Admin" creates following user using API
| id |
| Alice |
And "Alice" logs in
And "Alice" creates the following resources
| resource | type |
| parent/folder%2Fwith%2FSlashes | folder |
And "Alice" opens folder "parent/folder%2Fwith%2FSlashes"
And "Alice" creates the following resources
| resource | type |
| 'single-double quotes" | folder |
And "Alice" opens folder "\'single-double quotes\""
And "Alice" creates the following resources
| resource | type |
| "inner" double quotes | folder |
And "Alice" opens folder "\"inner\" double quotes"
And "Alice" creates the following resources
| resource | type |
| sub-folder | folder |
And "Alice" opens folder "sub-folder"
When "Alice" navigates to folder "\"inner\" double quotes" via breadcrumb
And "Alice" navigates to folder "\'single-double quotes\"" via breadcrumb
And "Alice" navigates to folder "folder%2Fwith%2FSlashes" via breadcrumb
And "Alice" navigates to folder "parent" via breadcrumb
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/smoke/breadcrumb.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/breadcrumb.feature",
"repo_id": "owncloud",
"token_count": 484
} | 935 |
Feature: web can be navigated through urls
Scenario: navigate web directly through urls
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/file_inside_folder.txt | example text |
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| lorem.txt | some content |
| test.odt | some content |
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| lorem.txt | new content |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Alice" creates the following project space using API
| name | id |
| Development | team.1 |
And "Alice" creates the following file in space "Development" using API
| name | content |
| spaceTextfile.txt | This is test file. Cheers |
When "Alice" navigates to "versions" details panel of file "lorem.txt" of space "personal" through the URL
Then "Alice" restores following resources
| resource | to | version | openDetailsPanel |
| lorem.txt | / | 1 | false |
When "Alice" navigates to "sharing" details panel of file "lorem.txt" of space "personal" through the URL
Then "Alice" shares the following resource using the direct url navigation
| resource | recipient | type | role | resourceType |
| lorem.txt | Brian | user | Can view | file |
# file that has respective editor will open in the respective editor
When "Alice" opens the file "lorem.txt" of space "personal" through the URL
Then "Alice" is in a text-editor
And "Alice" closes the file viewer
# file without the respective editor will show the file in the file list
When "Alice" opens the file "test.odt" of space "personal" through the URL
Then following resources should be displayed in the files list for user "Alice"
| resource |
| FOLDER |
| lorem.txt |
| test.odt |
When "Alice" opens the folder "FOLDER" of space "personal" through the URL
And "Alice" opens the following file in texteditor
| resource |
| file_inside_folder.txt |
Then "Alice" is in a text-editor
And "Alice" closes the file viewer
When "Alice" opens space "Development" through the URL
And "Alice" opens the following file in texteditor
| resource |
| spaceTextfile.txt |
Then "Alice" is in a text-editor
And "Alice" closes the file viewer
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/smoke/urlJourneys.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/urlJourneys.feature",
"repo_id": "owncloud",
"token_count": 1071
} | 936 |
import { DataTable, Then, When } from '@cucumber/cucumber'
import { World } from '../../environment'
import { objects } from '../../../support'
import { expect } from '@playwright/test'
Then(
'{string} should see the following notification(s)',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const application = new objects.runtime.Application({ page })
const messages = await application.getNotificationMessages()
for (const { message } of stepTable.hashes()) {
expect(messages).toContain(message)
}
}
)
Then(
'{string} should see no notification(s)',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const application = new objects.runtime.Application({ page })
const messages = await application.getNotificationMessages()
expect(messages.length).toBe(0)
}
)
When(
'{string} marks all notifications as read',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const application = new objects.runtime.Application({ page })
await application.markNotificationsAsRead()
}
)
| owncloud/web/tests/e2e/cucumber/steps/ui/notifications.ts/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/steps/ui/notifications.ts",
"repo_id": "owncloud",
"token_count": 406
} | 937 |
export * from './openWithWeb'
| owncloud/web/tests/e2e/support/api/external/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/external/index.ts",
"repo_id": "owncloud",
"token_count": 10
} | 938 |
import join from 'join-path'
import { checkResponseStatus, request } from '../http'
import { User } from '../../types'
export const disableAutoAcceptShare = async ({ user }: { user: User }): Promise<void> => {
const body = JSON.stringify({
value: {
accountUuid: 'me',
bundleId: '2a506de7-99bd-4f0d-994e-c38e72c28fd9',
settingId: 'ec3ed4a3-3946-4efc-8f9f-76d38b12d3a9',
resource: {
type: 'TYPE_USER'
},
boolValue: false
}
})
const response = await request({
method: 'POST',
path: join('api', 'v0', 'settings', 'values-save'),
body: body,
user: user
})
checkResponseStatus(response, 'Failed while disabling auto-accept share')
}
| owncloud/web/tests/e2e/support/api/userSettings/settings.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/userSettings/settings.ts",
"repo_id": "owncloud",
"token_count": 292
} | 939 |
import { Page } from '@playwright/test'
import util from 'util'
import { selectUser } from '../users/actions'
const newGroupBtn = '#create-group-btn'
const createGroupInput = '#create-group-input-display-name'
const actionConfirmButton = '.oc-modal-body-actions-confirm'
const editActionBtnContextMenu = '.context-menu .oc-groups-actions-edit-trigger'
const editActionBtnQuickActions =
'[data-item-id="%s"] .oc-table-data-cell-actions .groups-table-btn-edit'
const groupTrSelector = 'tr'
const groupIdSelector = `[data-item-id="%s"] .groups-table-btn-action-dropdown`
const groupCheckboxSelector = `[data-item-id="%s"]:not(.oc-table-highlighted) input[type=checkbox]`
const deleteBtnContextMenu = '.context-menu .oc-groups-actions-delete-trigger'
const deleteBtnBatchAction = '#oc-appbar-batch-actions'
const editPanel = '.sidebar-panel__body-EditPanel:visible'
const closeEditPanel = '.sidebar-panel__header .header__close'
const userInput = '#%s-input'
const compareDialogConfirm = '.compare-save-dialog-confirm-btn'
export const createGroup = async (args: { page: Page; key: string }): Promise<Response> => {
const { page, key } = args
await page.locator(newGroupBtn).click()
await page.locator(createGroupInput).fill(key)
const [response] = await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().endsWith('groups') && resp.status() === 201 && resp.request().method() === 'POST'
),
page.locator(actionConfirmButton).click()
])
return await response.json()
}
export const getDisplayedGroups = async (args: { page: Page }): Promise<string[]> => {
const { page } = args
const groups = []
const result = page.locator(groupTrSelector)
const count = await result.count()
for (let i = 0; i < count; i++) {
groups.push(await result.nth(i).getAttribute('data-item-id'))
}
return groups
}
export const selectGroup = async (args: { page: Page; uuid: string }): Promise<void> => {
const { page, uuid } = args
const checkbox = page.locator(util.format(groupCheckboxSelector, uuid))
const checkBoxAlreadySelected = await checkbox.isChecked()
if (checkBoxAlreadySelected) {
return
}
await checkbox.click()
}
export const deleteGroupUsingContextMenu = async (args: {
page: Page
uuid: string
}): Promise<void> => {
const { page, uuid } = args
await page.locator(util.format(groupIdSelector, uuid)).click()
await page.locator(deleteBtnContextMenu).click()
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().endsWith(encodeURIComponent(uuid)) &&
resp.status() === 204 &&
resp.request().method() === 'DELETE'
),
page.locator(actionConfirmButton).click()
])
}
export const deleteGrouprUsingBatchAction = async (args: {
page: Page
groupIds: string[]
}): Promise<void> => {
const { page, groupIds } = args
await page.locator(deleteBtnBatchAction).click()
const checkResponses = []
for (const id of groupIds) {
checkResponses.push(
page.waitForResponse(
(resp) =>
resp.url().endsWith(encodeURIComponent(id)) &&
resp.status() === 204 &&
resp.request().method() === 'DELETE'
)
)
}
await Promise.all([...checkResponses, page.locator(actionConfirmButton).click()])
}
export const changeGroup = async (args: {
page: Page
uuid: string
attribute: string
value: string
}): Promise<void> => {
const { page, attribute, value, uuid } = args
await page.locator(util.format(userInput, attribute)).pressSequentially(value)
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().endsWith(encodeURIComponent(uuid)) &&
resp.status() === 204 &&
resp.request().method() === 'PATCH'
),
page.locator(compareDialogConfirm).click()
])
}
export const openEditPanel = async (args: {
page: Page
uuid: string
action: string
}): Promise<void> => {
const { page, uuid, action } = args
if (await page.locator(editPanel).count()) {
await page.locator(closeEditPanel).click()
}
switch (action) {
case 'context-menu':
await page.locator(util.format(groupIdSelector, uuid)).click()
await page.locator(editActionBtnContextMenu).click()
break
case 'quick-action':
await selectUser({ page, uuid })
await page.locator(util.format(editActionBtnQuickActions, uuid)).click()
break
default:
throw new Error(`${action} not implemented`)
}
}
| owncloud/web/tests/e2e/support/objects/app-admin-settings/groups/actions.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/groups/actions.ts",
"repo_id": "owncloud",
"token_count": 1612
} | 940 |
import { Download, Page } from '@playwright/test'
import { File } from '../../../types'
import util from 'util'
import path from 'path'
import * as po from '../resource/actions'
const passwordInput = 'input[type="password"]'
const fileUploadInput = '//input[@id="files-file-upload-input"]'
const dropUploadResourceSelector = '.upload-info-items [data-test-resource-name="%s"]'
const toggleUploadDetailsButton = '.upload-info-toggle-details-btn'
const uploadInfoSuccessLabelSelector = '.upload-info-success'
const publicLinkAuthorizeButton = '.oc-login-authorize-button'
export class Public {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
async open({ url }: { url: string }): Promise<void> {
await this.#page.goto(url)
}
async authenticate({ password }: { password: string }): Promise<void> {
await this.#page.locator(passwordInput).fill(password)
await this.#page.locator(publicLinkAuthorizeButton).click()
await this.#page.locator('#web-content').waitFor()
}
async dropUpload({ resources }: { resources: File[] }): Promise<void> {
const startUrl = this.#page.url()
await this.#page.locator(fileUploadInput).setInputFiles(resources.map((file) => file.path))
const names = resources.map((file) => path.basename(file.name))
await this.#page.locator(uploadInfoSuccessLabelSelector).waitFor()
await this.#page.locator(toggleUploadDetailsButton).click()
await Promise.all(
names.map((name) =>
this.#page.locator(util.format(dropUploadResourceSelector, name)).waitFor()
)
)
await this.#page.goto(startUrl)
}
async reload(): Promise<void> {
await this.#page.reload()
}
async download(args: Omit<po.downloadResourcesArgs, 'page'>): Promise<Download[]> {
const startUrl = this.#page.url()
const downloads = await po.downloadResources({ ...args, page: this.#page })
await this.#page.goto(startUrl)
return downloads
}
async rename(args: Omit<po.renameResourceArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.renameResource({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async upload(args: Omit<po.uploadResourceArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.uploadResource({ ...args, page: this.#page })
await this.#page.goto(startUrl)
await this.#page.locator('body').click()
}
async uploadInternal(
args: Omit<po.uploadResourceArgs, 'page'> & { link: string }
): Promise<void> {
// link is the public link url
const { link } = args
delete args.link
await po.uploadResource({ ...args, page: this.#page })
await this.#page.goto(link)
}
async delete(args: Omit<po.deleteResourceArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.deleteResource({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
async expectThatLinkIsDeleted({ url }: { url: string }): Promise<void> {
await po.expectThatPublicLinkIsDeleted({ page: this.#page, url })
}
async getContentOfOpenDocumentOrMicrosoftWordDocument({
page,
editorToOpen
}: {
page: Page
editorToOpen: string
}): Promise<string> {
return await po.openAndGetContentOfDocument({ page, editorToOpen })
}
async fillContentOfOpenDocumentOrMicrosoftWordDocument({
page,
text,
editorToOpen
}: {
page: Page
text: string
editorToOpen: string
}): Promise<void> {
return await po.fillContentOfDocument({ page, text, editorToOpen })
}
}
| owncloud/web/tests/e2e/support/objects/app-files/page/public.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/page/public.ts",
"repo_id": "owncloud",
"token_count": 1221
} | 941 |
import { Page } from '@playwright/test'
import { SpacesEnvironment, LinksEnvironment } from '../../../environment'
import { File } from '../../../types'
import * as po from './actions'
import { spaceWithSpaceIDNotExist } from './utils'
import { ICollaborator } from '../share/collaborator'
export class Spaces {
#page: Page
#spacesEnvironment: SpacesEnvironment
#linksEnvironment: LinksEnvironment
constructor({ page }: { page: Page }) {
this.#page = page
this.#spacesEnvironment = new SpacesEnvironment()
this.#linksEnvironment = new LinksEnvironment()
}
getSpaceID({ key }: { key: string }): string {
const { id } = this.#spacesEnvironment.getSpace({ key })
return id
}
async create({
key,
space
}: {
key: string
space: Omit<po.createSpaceArgs, 'page'>
}): Promise<void> {
const id = await po.createSpace({ ...space, page: this.#page })
this.#spacesEnvironment.createSpace({ key, space: { name: space.name, id } })
}
async open({ key }: { key: string }): Promise<void> {
const { id } = this.#spacesEnvironment.getSpace({ key })
await po.openSpace({ page: this.#page, id })
}
async changeName({ key, value }: { key: string; value: string }): Promise<void> {
const { id } = this.#spacesEnvironment.getSpace({ key })
await po.changeSpaceName({ id, value, page: this.#page })
}
async changeSubtitle({ key, value }: { key: string; value: string }): Promise<void> {
const { id } = this.#spacesEnvironment.getSpace({ key })
await po.changeSpaceSubtitle({ id, value, page: this.#page })
}
async changeDescription({ value }: { value: string }): Promise<void> {
await po.changeSpaceDescription({ value, page: this.#page })
}
async changeQuota({ key, value }: { key: string; value: string }): Promise<void> {
const { id } = this.#spacesEnvironment.getSpace({ key })
await po.changeQuota({ id, value, page: this.#page })
}
async addMembers(args: Omit<po.SpaceMembersArgs, 'page'>): Promise<void> {
await po.addSpaceMembers({ ...args, page: this.#page })
}
async removeAccessToMember(args: Omit<po.removeAccessMembersArgs, 'page'>): Promise<void> {
await po.removeAccessSpaceMembers({ ...args, page: this.#page })
}
async expectThatSpacesIdNotExist(space: string): Promise<void> {
const spaceID = this.getSpaceID({ key: space })
await spaceWithSpaceIDNotExist({ spaceID, page: this.#page })
}
async canUserEditResource(args: Omit<po.canUserEditSpaceResourceArgs, 'page'>): Promise<boolean> {
const startUrl = this.#page.url()
const canEdit = await po.canUserEditSpaceResource({ ...args, page: this.#page })
await this.#page.goto(startUrl)
return canEdit
}
async changeRoles(args: Omit<po.SpaceMembersArgs, 'page'>): Promise<void> {
await po.changeSpaceRole({ ...args, page: this.#page })
}
async reloadPage(): Promise<void> {
await po.reloadSpacePage(this.#page)
}
async changeSpaceImage({ key, resource }: { key: string; resource: File }): Promise<void> {
const { id } = this.#spacesEnvironment.getSpace({ key })
await po.changeSpaceImage({ id, resource, page: this.#page })
}
async createPublicLink({ password }: { password: string }): Promise<void> {
const url = await po.createPublicLinkForSpace({ page: this.#page, password })
this.#linksEnvironment.createLink({
key: 'Link',
link: { name: 'Link', url }
})
}
async addExpirationDate({
member,
expirationDate
}: {
member: Omit<ICollaborator, 'role'>
expirationDate: string
}): Promise<void> {
await po.addExpirationDateToMember({ member, expirationDate, page: this.#page })
}
async removeExpirationDate({ member }: { member: Omit<ICollaborator, 'role'> }): Promise<void> {
await po.removeExpirationDateFromMember({ member, page: this.#page })
}
downloadSpace(): Promise<string> {
return po.downloadSpace(this.#page)
}
}
| owncloud/web/tests/e2e/support/objects/app-files/spaces/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/spaces/index.ts",
"repo_id": "owncloud",
"token_count": 1312
} | 942 |
import { KeycloakRealmRole } from '../types'
export const keycloakRealmRoles = new Map<string, KeycloakRealmRole>()
| owncloud/web/tests/e2e/support/store/keycloak.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/store/keycloak.ts",
"repo_id": "owncloud",
"token_count": 40
} | 943 |
export default {}
| owncloud/web/tests/unit/stubs/empty.ts/0 | {
"file_path": "owncloud/web/tests/unit/stubs/empty.ts",
"repo_id": "owncloud",
"token_count": 4
} | 944 |
<?php
include_once "inc/config.inc.php";
include_once "inc/mysql.inc.php";
$html='';
try
{
$link = mysqli_connect(DBHOST,DBUSER,DBPW,DBNAME);
}
catch(Exception $e)
{
$html.=
"<p >
<a href='pkxss_install.php' style='color:red;'>
提示:欢迎使用xss后台,点击进行初始化安装!
</a>
</p>";
}
if (@$link)
{
header("location:pkxss_login.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pikachu Xss 后台</title>
<link rel="stylesheet" type="text/css" href="pkxss.css"/>
</head>
<body>
<div id="title">
<h1>欢迎使用 pikachu Xss 后台</h1>
<?php echo $html;?>
</div>
</body>
</html> | zhuifengshaonianhanlu/pikachu/pkxss/index.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/pkxss/index.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 440
} | 945 |
<?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 = "token_get_login.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)){
header("location:token_get.php");
}
$html='';
if(isset($_GET['submit'])){
if($_GET['username']!=null && $_GET['password']!=null){
//转义,防注入
$username=escape($link, $_GET['username']);
$password=escape($link, $_GET['password']);
$query="select * from member where username='$username' and pw=md5('$password')";
$result=execute($link, $query);
if(mysqli_num_rows($result)==1){
$data=mysqli_fetch_assoc($result);
$_SESSION['csrf']['username']=$username;
$_SESSION['csrf']['password']=sha1(md5($password));
header("location:token_get.php");
}else{
$html.="<p>登录失败,请重新登录</p>";
}
}
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="../csrf.php">CSRF</a>
</li>
<li class="active">CSRF Token login</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="这里一共有这么些用户vince/allen/kobe/grady/kevin/lucy/lili,密码全部是123456">
点一下提示~
</a>
</div>
<div class="page-content">
<div class="xss_form">
<div class="xss_form_main">
<h4 class="header blue lighter bigger">
<i class="ace-icon fa fa-coffee green"></i>
Please Enter Your Information
</h4>
<form method="get" action="token_get_login.php">
<!-- <fieldset>-->
<label>
<span>
<input type="text" name="username" placeholder="Username" />
<i class="ace-icon fa fa-user"></i>
</span>
</label>
</br>
<label>
<span>
<input type="password" name="password" placeholder="Password" />
<i class="ace-icon fa fa-lock"></i>
</span>
</label>
<div class="space"></div>
<div class="clearfix">
<label><input class="submit" name="submit" type="submit" value="Login" /></label>
</div>
</form>
<?php echo $html;?>
</div><!-- /.widget-main -->
</div><!-- /.widget-body -->
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/csrf/csrftoken/token_get_login.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/csrf/csrftoken/token_get_login.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2162
} | 946 |
<?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.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="sqli.php">sqli</a>
</li>
<li class="active">概述</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<div id="vul_info">
<dl>
<dt class="vul_title">Sql Inject(SQL注入)概述</dt>
<dd class="vul_detail"><br />
<p style="color: red;">哦,SQL注入漏洞,可怕的漏洞。</p><br />
在owasp发布的top10排行榜里,注入漏洞一直是危害排名第一的漏洞,其中注入漏洞里面首当其冲的就是数据库注入漏洞。<br />
<b>一个严重的SQL注入漏洞,可能会直接导致一家公司破产!</b><br />
SQL注入漏洞主要形成的原因是在数据交互中,前端的数据传入到后台处理时,没有做严格的判断,导致其传入的“数据”拼接到SQL语句中后,被当作SQL语句的一部分执行。
从而导致数据库受损(被脱裤、被删除、甚至整个服务器权限沦陷)。<br />
</dd>
<dd class="vul_detail">
在构建代码时,一般会从如下几个方面的策略来防止SQL注入漏洞:<br />
1.对传进SQL语句里面的变量进行过滤,不允许危险字符传入;<br />
2.使用参数化(Parameterized Query 或 Parameterized Statement);<br />
3.还有就是,目前有很多ORM框架会自动使用参数化解决注入问题,但其也提供了"拼接"的方式,所以使用时需要慎重!
</dd>
<br />
<dd class="vul_detail">
SQL注入在网络上非常热门,也有很多技术专家写过非常详细的关于SQL注入漏洞的文章,这里就不在多写了。<br/>
你可以通过“Sql Inject”对应的测试栏目,来进一步的了解该漏洞。
</dd>
</dl>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/sqli/sqli.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/sqli/sqli.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2045
} | 947 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "ssrf_curl.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$FILEDIR = $_SERVER['PHP_SELF'];
$RD = explode('/',$FILEDIR)[1] . '/';
$RD = $RD == 'vul/' ? '' : $RD;
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR.'header.php';
//payload:
//file:///etc/passwd 读取文件
//http://192.168.1.15:22 根据banner返回,错误提示,时间延迟扫描端口
if(isset($_GET['url']) && $_GET['url'] != null){
//接收前端URL没问题,但是要做好过滤,如果不做过滤,就会导致SSRF
$URL = $_GET['url'];
$CH = curl_init($URL);
curl_setopt($CH, CURLOPT_HEADER, FALSE);
curl_setopt($CH, CURLOPT_SSL_VERIFYPEER, FALSE);
$RES = curl_exec($CH);
curl_close($CH) ;
//ssrf的问是:前端传进来的url被后台使用curl_exec()进行了请求,然后将请求的结果又返回给了前端。
//除了http/https外,curl还支持一些其他的协议curl --version 可以查看其支持的协议,telnet
//curl支持很多协议,有FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE以及LDAP
echo $RES;
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="ssrf.php"></a>
</li>
<li class="active">概述</li>
</ul>
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="先了解一下php中curl相关函数的用法吧">
点一下提示~
</a>
</div>
<div class="page-content">
<a href="ssrf_curl.php?url=<?php echo 'http://127.0.0.1/'.$RD.'vul/ssrf/ssrf_info/info1.php';?>">累了吧,来读一首诗吧</a>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/ssrf/ssrf_curl.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/ssrf/ssrf_curl.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1388
} | 948 |
<?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_04.php"){
$ACTIVE = array('','','','','','','','active open','','','','','','','','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR.'header.php';
$jsvar='';
$html='';
//这里讲输入动态的生成到了js中,形成xss
//javascript里面是不会对tag和字符实体进行解释的,所以需要进行js转义
//讲这个例子主要是为了让你明白,输出点在js中的xss问题,应该怎么修?
//这里如果进行html的实体编码,虽然可以解决XSS的问题,但是实体编码后的内容,在JS里面不会进行翻译,这样会导致前端的功能无法使用。
//所以在JS的输出点应该使用\对特殊字符进行转义
if(isset($_GET['submit']) && $_GET['message'] !=null){
$jsvar=$_GET['message'];
// $jsvar=htmlspecialchars($_GET['message'],ENT_QUOTES);
if($jsvar == 'tmac'){
$html.="<img src='{$PIKA_ROOT_DIR}assets/images/nbaplayer/tmac.jpeg' />";
}
}
?>
<div class="main-content" xmlns="http://www.w3.org/1999/html">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="xss.php">xss</a>
</li>
<li class="active">xss之js输出</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="输入被动态的生成到了javascript中,如何是好。输入tmac试试-_-">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="xssr_main">
<p class="xssr_title">which NBA player do you like?</p>
<form method="get">
<input class="xssr_in" type="text" name="message" />
<input class="xssr_submit" type="submit" name="submit" value="submit" />
</form>
</br>
<p id="fromjs"></p>
<?php echo $html;?>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<script>
$ms='<?php echo $jsvar;?>';
if($ms.length != 0){
if($ms == 'tmac'){
$('#fromjs').text('tmac确实厉害,看那小眼神..')
}else {
// alert($ms);
$('#fromjs').text('无论如何不要放弃心中所爱..')
}
}
</script>
<?php
include_once $PIKA_ROOT_DIR.'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/xss/xss_04.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/xss/xss_04.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1665
} | 949 |
# 8th Wall Web Examples - AFrame - Alpha Video
This example uses an A-Frame component for background removal of an mp4 video file.
Check out the component [here](https://github.com/nikolaiwarner/aframe-chromakey-material/blob/master/README.md).

Use this image target to test:

[Try the live demo here](https://templates.8thwall.app/alpha-video-aframe)
or scan on phone:

| 8thwall/web/examples/aframe/alpha-video/README.md/0 | {
"file_path": "8thwall/web/examples/aframe/alpha-video/README.md",
"repo_id": "8thwall",
"token_count": 175
} | 0 |
# A-Frame: Manipulate 3D Model
[Try the live demo here](https://8thwall.8thwall.app/manipulate-aframe)
This example allows the user to position, scale, and rotate an object using raycasting and gesture inputs.

### Project Components
```xrextras-gesture-detector``` is required in your ```<a-scene>``` for xrextras gesture components
to function correctly.
- element: the element touch event listeners are added to (default: '')
```xrextras-hold-drag``` lifts up and drags around its entity on finger down/drag. The entity must receive raycasts.
- cameraId: the id of the ```<a-camera>```(default: 'camera')
- groundId: the id of the ground ```<a-entity>```(default: 'ground')
- dragDelay: the time required for the user's finger to be down before lifting the object (default: 300)
```xrextras-pinch-scale```
- min: smallest scale user can pinch to (default: 0.33)
- max: largest scale user can pinch to (default: 3)
- scale: sets initial scale. If set to 0, the object's initial scale is used (default: 0)
```xrextras-one-finger-rotate``` lets the user drag across the screen with one finger
to spin an object around its y axis.
- factor: increase this number to spin more given the same drag distance (default: 6)
```xrextras-two-finger-rotate``` lets the user drag across the screen with two fingers
to spin an object around its y axis.
- factor: increase this number to spin more given the same drag distance (default: 5)
Check out the source code for these XRExtras components on [Github](https://8th.io/xrextras-components).
| 8thwall/web/examples/aframe/manipulate/README.md/0 | {
"file_path": "8thwall/web/examples/aframe/manipulate/README.md",
"repo_id": "8thwall",
"token_count": 503
} | 1 |
import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import App from './App'
import reportWebVitals from './reportWebVitals'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
)
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()
| 8thwall/web/examples/aframe/reactapp/src/index.jsx/0 | {
"file_path": "8thwall/web/examples/aframe/reactapp/src/index.jsx",
"repo_id": "8thwall",
"token_count": 168
} | 2 |
# 8th Wall Web Examples - Babylon.js
Example 8th Wall Web projects using Babylon.js:
* [Tap to place](https://github.com/8thwall/web/tree/master/examples/babylonjs/placeground) - This interactive example allows the user to grow trees on the ground by tapping. This showcases raycasting, instantiating objects, importing 3D models, and animation.
Tap to place
:----------:

[Try Demo (mobile)](https://templates.8thwall.app/placeground-babylonjs)
or scan on phone:<br> 
| 8thwall/web/examples/babylonjs/README.md/0 | {
"file_path": "8thwall/web/examples/babylonjs/README.md",
"repo_id": "8thwall",
"token_count": 185
} | 3 |
/*
Ported to JavaScript by Lazar Laszlo 2011
lazarsoft@gmail.com, www.lazarsoft.info
*/
/*
*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function BitMatrix( width, height)
{
if(!height)
height=width;
if (width < 1 || height < 1)
{
throw "Both dimensions must be greater than 0";
}
this.width = width;
this.height = height;
var rowSize = width >> 5;
if ((width & 0x1f) != 0)
{
rowSize++;
}
this.rowSize = rowSize;
this.bits = new Array(rowSize * height);
for(var i=0;i<this.bits.length;i++)
this.bits[i]=0;
this.__defineGetter__("Width", function()
{
return this.width;
});
this.__defineGetter__("Height", function()
{
return this.height;
});
this.__defineGetter__("Dimension", function()
{
if (this.width != this.height)
{
throw "Can't call getDimension() on a non-square matrix";
}
return this.width;
});
this.get_Renamed=function( x, y)
{
var offset = y * this.rowSize + (x >> 5);
return ((URShift(this.bits[offset], (x & 0x1f))) & 1) != 0;
}
this.set_Renamed=function( x, y)
{
var offset = y * this.rowSize + (x >> 5);
this.bits[offset] |= 1 << (x & 0x1f);
}
this.flip=function( x, y)
{
var offset = y * this.rowSize + (x >> 5);
this.bits[offset] ^= 1 << (x & 0x1f);
}
this.clear=function()
{
var max = this.bits.length;
for (var i = 0; i < max; i++)
{
this.bits[i] = 0;
}
}
this.setRegion=function( left, top, width, height)
{
if (top < 0 || left < 0)
{
throw "Left and top must be nonnegative";
}
if (height < 1 || width < 1)
{
throw "Height and width must be at least 1";
}
var right = left + width;
var bottom = top + height;
if (bottom > this.height || right > this.width)
{
throw "The region must fit inside the matrix";
}
for (var y = top; y < bottom; y++)
{
var offset = y * this.rowSize;
for (var x = left; x < right; x++)
{
this.bits[offset + (x >> 5)] |= 1 << (x & 0x1f);
}
}
}
} | 8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/bitmat.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/bitmat.js",
"repo_id": "8thwall",
"token_count": 1037
} | 4 |
# 8th Wall Web Examples - Camera Pipeline - Simple Shaders
This example shows how to apply simple shaders to the camera feed.
Simple Shaders
:----------:

[Try Demo (mobile)](https://apps.8thwall.com/8thWall/camerapipeline_simpleshaders)
or scan on phone:<br> 
| 8thwall/web/examples/camerapipeline/simpleshaders/README.md/0 | {
"file_path": "8thwall/web/examples/camerapipeline/simpleshaders/README.md",
"repo_id": "8thwall",
"token_count": 134
} | 5 |
// Copyright (c) 2021 8th Wall, Inc.
/* globals XR8 XRExtras THREE */
const imageTargetPipelineModule = () => {
const modelFile = 'jellyfish-model.glb'
const videoFile = 'jellyfish-video.mp4'
const loader = new THREE.GLTFLoader() // This comes from GLTFLoader.js.
let model
let video, videoObj
// 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}) => {
// create the video element
video = document.createElement('video')
video.src = videoFile
video.setAttribute('preload', 'auto')
video.setAttribute('loop', '')
video.setAttribute('muted', '')
video.setAttribute('playsinline', '')
video.setAttribute('webkit-playsinline', '')
const texture = new THREE.VideoTexture(video)
texture.minFilter = THREE.LinearFilter
texture.magFilter = THREE.LinearFilter
texture.format = THREE.RGBFormat
texture.crossOrigin = 'anonymous'
videoObj = new THREE.Mesh(
new THREE.PlaneGeometry(0.75, 1),
new THREE.MeshBasicMaterial({map: texture})
)
// Hide video until image target is detected.
videoObj.visible = false
scene.add(videoObj)
video.load()
// Load 3D model
loader.load(
// resource URL
modelFile,
// loaded handler
(gltf) => {
model = gltf.scene
scene.add(model)
// Hide 3D model until image target is detected.
model.visible = false
}
)
// Add soft white light to the scene.
// This light cannot be used to cast shadows as it does not have a direction.
scene.add(new THREE.AmbientLight(0x404040, 5))
// 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)
}
// Places content over image target
const showTarget = ({detail}) => {
// When the image target named 'model-target' is detected, show 3D model.
// This string must match the name of the image target uploaded to 8th Wall.
if (detail.name === 'model-target') {
model.position.copy(detail.position)
model.quaternion.copy(detail.rotation)
model.scale.set(detail.scale, detail.scale, detail.scale)
model.visible = true
}
// When the image target named 'video-target' is detected, play video.
// This string must match the name of the image target uploaded to 8th Wall.
if (detail.name === 'video-target') {
videoObj.position.copy(detail.position)
videoObj.quaternion.copy(detail.rotation)
videoObj.scale.set(detail.scale, detail.scale, detail.scale)
videoObj.visible = true
video.play()
}
}
// Hides the image frame when the target is no longer detected.
const hideTarget = ({detail}) => {
if (detail.name === 'model-target') {
model.visible = false
}
if (detail.name === 'video-target') {
video.pause()
videoObj.visible = false
}
}
// Grab a handle to the threejs scene and set the camera position on pipeline startup.
const onStart = ({canvas}) => {
const {scene, camera} = XR8.Threejs.xrScene() // Get the 3js scene from XR
initXrScene({scene, camera}) // Add content to the scene and set starting camera position.
// prevent scroll/pinch gestures on canvas
canvas.addEventListener('touchmove', (event) => {
event.preventDefault()
})
// Sync the xr controller's 6DoF position and camera paremeters with our scene.
XR8.XrController.updateCameraProjectionMatrix({
origin: camera.position,
facing: camera.quaternion,
})
}
return {
// Camera pipeline modules need a name. It can be whatever you want but must be
// unique within your app.
name: 'threejs-flyer',
// 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,
// Listeners are called right after the processing stage that fired them. This guarantees that
// updates can be applied at an appropriate synchronized point in the rendering cycle.
listeners: [
{event: 'reality.imagefound', process: showTarget},
{event: 'reality.imageupdated', process: showTarget},
{event: 'reality.imagelost', process: hideTarget},
],
}
}
const onxrloaded = () => {
// If your app only interacts with image targets and not the world, disabling world tracking can
// improve speed.
XR8.XrController.configure({disableWorldTracking: true})
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.
imageTargetPipelineModule(), // Places 3d model and video content over detected image targets.
])
// 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/flyer/index.js/0 | {
"file_path": "8thwall/web/examples/threejs/flyer/index.js",
"repo_id": "8thwall",
"token_count": 2027
} | 6 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>8th Wall Web: A-Frame</title>
<!-- We've included a slightly modified version of A-Frame, which fixes some polish concerns -->
<script src="//cdn.8thwall.com/web/aframe/8frame-1.3.0.min.js"></script>
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<!-- Landing Pages - see https://www.8thwall.com/docs/web/#landing-pages -->
<script src='//cdn.8thwall.com/web/landing-page/landing-page.js'></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXX"></script>
</head>
<body>
<!-- Add the 'xrweb' attribute to your scene to make it an 8th Wall Web A-FRAME scene. -->
<a-scene
xrweb
xrextras-tap-recenter
landing-page
xrextras-loading
xrextras-runtime-error>
<a-camera position="0 8 8"></a-camera>
<a-entity
light="type: directional;
castShadow: true;
intensity: 0.8;
shadowCameraTop: 7;
shadowMapHeight: 1024;
shadowMapWidth: 1024;"
position="1 4.3 2.5">
</a-entity>
<a-entity
light="type: directional; castShadow: false; intensity: 0.5;"
position="-0.8 3 1.85">
</a-entity>
<a-light type="ambient" intensity="1"></a-light>
<a-box
position="-1.7 0.5 -2"
rotation="0 45 0"
material="roughness: 0.8; metalness: 0.2; color: #00EDAF;"
shadow>
</a-box>
<a-sphere
position="-1.175 1.25 -5.2"
radius="1.25"
material="roughness: 0.8; metalness: 0.2; color: #DD0065;"
shadow>
</a-sphere>
<a-cylinder
position="2 0.75 -1.85"
radius="0.5"
height="1.5"
material="roughness: 0.8; metalness: 0.2; color: #FCEE21;"
shadow>
</a-cylinder>
<a-circle
position="0 0 -4"
rotation="-90 0 0"
radius="4"
material="roughness: 0.8; metalness: 0.5; color: #AD50FF"
shadow>
</a-circle>
</a-scene>
</body>
</html>
| 8thwall/web/gettingstarted/aframe/index.html/0 | {
"file_path": "8thwall/web/gettingstarted/aframe/index.html",
"repo_id": "8thwall",
"token_count": 1109
} | 7 |
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=0.75, user-scalable=yes">
<title>8th Wall Web: three.js</title>
<!-- THREE.js must be supplied -->
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.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='https://cdn.8thwall.com/web/landing-page/landing-page.js'></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXXXXX"></script>
<!-- client code -->
<script src="index.js"></script>
</head>
<body>
<!-- The AR canvas -->
<canvas id="camerafeed" width="480" height="640"></canvas>
</body>
</html>
| 8thwall/web/gettingstarted/threejs/index.html/0 | {
"file_path": "8thwall/web/gettingstarted/threejs/index.html",
"repo_id": "8thwall",
"token_count": 394
} | 8 |
{
"name": "xrextras",
"version": "0.1.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"dev": "webpack server --devtool eval --mode development",
"clean": "rm -r dist/*"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/aframe": "^1.2.2",
"css-loader": "^6.8.1",
"html-loader": "^4.2.0",
"style-loader": "^3.3.3",
"text-loader": "^0.0.1",
"ts-loader": "^9.4.4",
"typescript": "^5.1.6",
"webpack": "^5.88.1",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
}
}
| 8thwall/web/xrextras/package.json/0 | {
"file_path": "8thwall/web/xrextras/package.json",
"repo_id": "8thwall",
"token_count": 323
} | 9 |
<div id="almostthereContainer" class="absolute-fill">
<!--Not on mobile -->
<div id="error_msg_device" class="hidden">
<div class="error-text-outer-container">
<div class="error-text-container error-margin-top-20">
<div id="qrcode"></div>
<br />
<div class="desktop-message">
<span>
To view, open camera on smartphone and scan code
</span>
</div>
<div class="desktop-hint">
<span style="font-size:15pt;line-height:20pt;letter-spacing:-.21;">
or visit <br /><span class="desktop-home-link"></span><br />
on a smartphone or tablet.
</span>
</div>
<img class="foreground-image poweredby-img desktop" src="//cdn.8thwall.com/web/img/almostthere/v2/poweredby-horiz-white-4.svg">
</div>
</div>
</div>
<!--iOS webview, reachable from button press -->
<div id="error_msg_open_in_safari" class="hidden absolute-fill">
<div class="error-text-outer-container">
<div class="error-text-container error-margin-top-5">
<span id="error_text_header_top" class="hidden open-header-top">
<h2>Open in Safari<br /> to view AR</h2>
</span>
<span id="error_text_header_bottom" class="hidden open-header-bottom">
<h2>Open in Safari<br /> to view AR</h2>
</span>
<img class="app-header-img">
<img class="foreground-image poweredby-img" src="//cdn.8thwall.com/web/img/almostthere/v2/poweredby-horiz-white-4.svg">
<br />
<img id="top_corner_open_safari" src="//cdn.8thwall.com/web/img/almostthere/v2/xtra-arrow.svg"
class="foreground-image arrow-top-corner hidden" />
<img id="top_close_open_safari" src="//cdn.8thwall.com/web/img/almostthere/v2/xtra-arrow.svg"
class="foreground-image arrow-top-close hidden" />
<img id="bottom_corner_open_safari" src="//cdn.8thwall.com/web/img/almostthere/v2/xtra-arrow.svg"
class="foreground-image arrow-bottom-corner hidden" />
<img id="bottom_close_open_safari" src="//cdn.8thwall.com/web/img/almostthere/v2/xtra-arrow.svg"
class="foreground-image arrow-bottom-close hidden" />
</div>
</div>
</div>
<!--iOS webview, requires copy/paste of link -->
<div id="error_unknown_webview" class="hidden">
<div class="error-text-outer-container">
<div class="error-text-container error-margin-top-5">
<span id="error_text_header_unknown" class="open-header-unknown">
<h2>Open in Safari<br /> to view AR</h2>
</span>
<img id="app_img" class="app-header-img unknown">
<br />
<span id="app_link" class="desktop-home-link mobile"></span>
<button id="error_copy_link_btn" class="copy-link-btn">Copy Link</button>
<img class="foreground-image poweredby-img" src="//cdn.8thwall.com/web/img/almostthere/v2/poweredby-horiz-white-4.svg">
</div>
</div>
</div>
<!--Missing Web Assembly, or iOS 11.2 (which has a WebAssembly regression)-->
<div id="error_msg_web_assembly_ios" class="hidden">
<div class="error-text-outer-container">
<div class="error-text-container error-margin-top-5">
<p><img class="foreground-image safari-hero-image" src="//cdn.8thwall.com/web/img/almostthere/v2/safari-fallback.png"></p>
<div class="error-text-header">You're almost there!</div>
<div class="error-text-detail">
To view this experience, please update to a newer version of iOS.
</div>
</div>
</div>
</div>
<div id="error_msg_web_assembly_android" class="hidden">
<div class="error-text-outer-container">
<div class="error-text-container error-margin-top-5">
<p><img src="//cdn.8thwall.com/web/img/almostthere/v1/google-chrome.png"></p>
<div class="error-text-header">You're almost there!</div>
<div class="error-text-detail">
Browser doesn't support WebAssembly. Please update your browser.
</div>
</div>
</div>
</div>
<!--Android unsupported browser -->
<div id="error_msg_android_almost_there" class="hidden">
<div class="error-text-outer-container">
<div class="error-text-container error-margin-top-5">
<p><img height="100px" src="//cdn.8thwall.com/web/img/almostthere/v1/google-chrome.png"></p>
<div class="error-text-header">You're almost there!</div>
<div id="error_msg_detail_android_almost_there" class="hidden error-text-detail">
To view this experience on your Android device, please open in Google Chrome or your
native browser.
</div>
<div id="error_msg_detail_huawei_almost_there" class="hidden error-text-detail">
To view this experience on your Huawei device, please open in Google Chrome or UC Browser.
</div>
<br />
<p><span class="desktop-home-link"></span></p>
<div id="android_copy_hint" class="error-text-hint">Open your browser and paste.</div>
</div>
</div>
</div>
</div>
| 8thwall/web/xrextras/src/almosttheremodule/almost-there-module.html/0 | {
"file_path": "8thwall/web/xrextras/src/almosttheremodule/almost-there-module.html",
"repo_id": "8thwall",
"token_count": 2132
} | 10 |
import {initMediaPreview, removeMediaPreview} from './media-preview'
import {initRecordButton, removeRecordButton, setCaptureMode} from './record-button'
import {configure} from './capture-config'
const create = () => ({
initMediaPreview,
removeMediaPreview,
initRecordButton,
removeRecordButton,
configure,
setCaptureMode,
})
let mediaRecorder = null
const MediaRecorderFactory = () => {
if (mediaRecorder === null) {
mediaRecorder = create()
}
return mediaRecorder
}
// TODO: export MediaRecorderFactory
const MediaRecorder = MediaRecorderFactory()
export {
MediaRecorder,
}
| 8thwall/web/xrextras/src/mediarecorder/mediarecorder.js/0 | {
"file_path": "8thwall/web/xrextras/src/mediarecorder/mediarecorder.js",
"repo_id": "8thwall",
"token_count": 183
} | 11 |
import '../fonts/fonts.css'
import './runtime-error-module.css'
import html from './runtime-error-module.html'
let runtimeerrorModule = null
const RuntimeErrorFactory = () => {
if (!runtimeerrorModule) {
runtimeerrorModule = create()
}
return runtimeerrorModule
}
const create = () => {
let started = false
let rootNode = null
const hideRuntimeError = () => {
if (!rootNode) {
return
}
rootNode.parentNode.removeChild(rootNode)
rootNode = null
}
const pipelineModule = () => ({
name: 'error',
onStart: () => { started = true },
onRemove: () => {
hideRuntimeError()
},
onException: (error) => {
// Only handle errors while running, not at startup.
if (!started) { return }
// Only add the error message once.
if (rootNode) { return }
// Log the error to the console to help with debugging.
console.error('[RuntimeError] XR caught an error; stopping.', error)
// Show the error message.
const e = document.createElement('template')
e.innerHTML = html.trim()
rootNode = e.content.firstChild
document.getElementsByTagName('body')[0].appendChild(rootNode)
document.getElementById('error_msg_unknown').classList.remove('hidden')
// Stop camera processing.
XR8.pause()
XR8.stop()
},
})
return {
// Adds a pipeline module that displays an error image and stops the camera
// feed when an error is encountered after the camera starts running.
pipelineModule,
hideRuntimeError,
}
}
export {
RuntimeErrorFactory,
}
| 8thwall/web/xrextras/src/runtimeerrormodule/runtime-error-module.js/0 | {
"file_path": "8thwall/web/xrextras/src/runtimeerrormodule/runtime-error-module.js",
"repo_id": "8thwall",
"token_count": 561
} | 12 |
## 一、网络监听接口
- ononline:网络连通时触发
- onoffline:网络断开时触发
```js
window.addEventListener("online", function(){});
window.addEventListener("offline", function(){});
```
## 二、全屏接口
全屏操作的主要方法和属性:
**1、requestFullScreen(); 开启全屏显示**
但是不同的浏览器需要添加的前缀不同:
chrome:webkit , firefox:moz ,IE:ms
于是就变成了 `webkitRequestFullScreen()`, `mozRequestFullScreen()`, `msRequestFullScreen()`。由于使用的方法不同,所以要做兼容性处理。
**2、cancelFullScreen(); 退出全屏显示**
退出全屏的操作也要加前缀,**并且调用其的元素只能是 ducument**,而不能是其他元素。
**3、fullscreenElement;是否是全屏状态**
判断是否为全屏状态也要加前缀,并且**调用其的元素只能是 ducument,而不能是其他元素**。(注意只有 firefox是驼峰写法,最符合 html5 标准)
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<img src="images/l1.jpg"><br>
<input type="button" value="进入全屏" id="btn1">
<input type="button" value="退出全屏" id="btn2">
<input type="button" value="是否全屏" id="btn3">
</div>
<script>
// 开启全屏显示
document.querySelector("#btn1").addEventListener("click", function () {
var divObj = document.querySelector("div");
if (divObj.requestFullscreen) {
divObj.requestFullscreen();
}
else if (divObj.webkitRequestFullScreen) {
divObj.webkitRequestFullScreen();
}
else if (divObj.mozRequestFullScreen) {
divObj.mozRequestFullScreen();
}
else if (divObj.msRequestFullScreen) {
divObj.msRequestFullScreen();
}
}, false);
// 退出全屏显示
document.querySelector("#btn2").addEventListener("click", function () {
if (document.cancelFullscreen) {
document.cancelFullscreen();
}
else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
}
else if (document.msCancelFullScreen) {
document.msCancelFullScreen();
}
}, false);
// 是否是全屏状态
document.querySelector("#btn3").addEventListener("click", function () {
if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
console.log("yes");
}
else {
console.log("no");
}
}, false);
</script>
</body>
</html>
```
## 三、应用程序缓存
主要应用在:当离线模式下,页面需要选择性缓存一些内容的时候。
```html
<!DOCTYPE html>
<!--manifest="应用程序缓存清单文件的路径 建议文件的扩展名是appcache,这个文件的本质就是一个文本文件"-->
<html lang="en" manifest="demo.appcache">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
img{
width: 300px;
display: block;
}
</style>
</head>
<body>
<img src="../images/l1.jpg" alt="">
<img src="../images/l2.jpg" alt="">
<img src="../images/l3.jpg" alt="">
<img src="../images/l4.jpg" alt="">
</body>
</html>
```
demo.appcache 文件
```
CACHE MANIFEST
#上面一句代码必须是当前文档的第一句
#后面写注释
#需要缓存的文件清单列表
CACHE:
#下面就是需要缓存的清单列表
../images/l1.jpg
../images/l2.jpg
# *:代表所有文件
#配置每一次都需要重新从服务器获取的文件清单列表
NETWORK:
../images/l3.jpg
#配置如果文件无法获取则使用指定的文件进行替代
FALLBACK:
../images/l4.jpg ../images/banner_1.jpg
# /:代表所有文件
```
## 四、文件读取接口
**FileReader**:主要是读取文件内容。
使用 `new FileReader` 生成的对象有下列几个方法,用于读取文件:
- `readAsText()`:读取文本文件,返回文本字符串,默认编码是UTF-8
- `readAsBinaryString()`:读取任意类型的文件,返回二进制字符串。**这个方法不是用来读取文件展示给用户看,而是存储文件**。例如:读取文件的内容,获取二进制数据,传递给后台,后台接收了数据之后,再将数据存储。
- `readAsDataURL()`:读取文件获取一段以data开头的字符串,这段字符串的本质就是DataURL。
DataURL是一种**将文件(这个文件一般就是指图像或者能够嵌入到文档的文件格式)嵌入到文档的一种格式**。DataURL是**将资源转换为base64编码的字符串形式,并且将这些内容直接存储在url中,这样做可以优化网站的加载速度和执行效率。**
- `abort()`:中断文件读取。
比如现在有一需求,选择图片并实时显示(类似在网页上更换头像,可以实时预览图片):
```html
<body>
<!--需求:即时预览:
即时:当用户选择完图片之后就立刻进行预览的处理 >>onchange
预览:通过文件读取对象的readAsDataURL()完成-->
<form action="">
文件: <input type="file" name="myFile" id="myFile" onchange="getFileContent();"> <br>
<div></div>
<input type="submit">
</form>
<img src="" alt="">
<script>
var div=document.querySelector("div");
function getFileContent(){
/*1.创建文件读取对象*/
var reader=new FileReader();
/*2.读取文件,获取DataURL
* 2.1.说明没有任何的返回值:void:但是读取完文件之后,它会将读取的结果存储在文件读取对象的result中
* 2.2.需要传递一个参数(binary large object):文件(图片或者其它可以嵌入到文档的类型)
* 2.3:文件存储在file表单元素的files属性中,它是一个数组,当有 multiple 属性的时候这个数组的值会有多个。*/
var file=document.querySelector("#myFile").files[0];
reader.readAsDataURL(file);
/*获取数据*/
/*FileReader提供一个完整的事件模型,用来捕获读取文件时的状态
* onabort:读取文件中断片时触发
* onerror:读取错误时触发
* onload:文件读取完成且成功时触发
* onloadend:文件读取完成时触发,无论成功还是失败
* onloadstart:开始读取时触发
* onprogress:读取文件过程中持续触发*/
reader.onload=function(){
//console.log(reader.result);
/*展示*/
document.querySelector("img").src=reader.result;
}
// 模拟进度条显示
reader.onprogress=function(e){
var percent= (e.loaded/ e.total)*100+"%";
div.style.width=percent;
}
}
</script>
</body>
```
> onchange:就是当文件内容发生变化时触发的事件。
## 五、地理定位接口
方法:
```js
// 参数1:获取地理信息成功之后的回调函数
// 参数2:获取地理信息失败之后的回调函数
// 参数3:调整获取当前地理信息的方式
// enableHighAccuracy:true/false:是否使用高精度
// timeout:设置超时时间,单位ms
// maximumAge:可以设置浏览器重新获取地理信息的时间间隔,单位是ms
navigator.geolocation.getCurrentPosition(success,error,option);
```
示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.de {
width: 300px;
height: 300px;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<div id="demo" class="de"></div>
<script>
var x = document.getElementById("demo");
function getLocation() {
/*能力测试*/
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError, {
/*enableHighAccuracy:true,
timeout:3000*/
});
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
/*成功获取定位之后的回调*/
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br />Longitude: " + position.coords.longitude;
}
/*获取定位失败之后的回调*/
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
getLocation();
</script>
</body>
</html>
```
> 获取地理位置成功,将会把获取到的地理信息以参数的形式传递给回调函数:
>
> position.coords.latitude 纬度
> position.coords.longitude 经度
> position.coords.accuracy 精度
> position.coords.altitude 海拔高度
> 注意:由于地理位置属于用户的隐私信息,一般浏览器不允许获取,只有在浏览器中开启之后才能够获取。然而,在中国使用PC端的浏览器是不允许获取到用户的信息的,手机端可以。


> 那么怎么在PC端的浏览器获取到用户的位置信息呢?
>
> 调用百度地图,高德地图等第三方提供的API接口获取用户信息。
| Daotin/Web/01-HTML/02-HTML5/03-网络监听,全屏,文件读取,地理定位接口,应用程序缓存.md/0 | {
"file_path": "Daotin/Web/01-HTML/02-HTML5/03-网络监听,全屏,文件读取,地理定位接口,应用程序缓存.md",
"repo_id": "Daotin",
"token_count": 5689
} | 13 |
# BFC的概念及案例
## BFC的概念
BFC(Block formatting context)直译为“块级格式化上下文”。它是一个独立的渲染区域,只有Block-level box(块)参与, 它规定了内部的Block-level Box如何布局,并且与这个区域外部毫不相干。
### BFC的布局规则
- 内部的Box会在垂直方向,一个接一个地放置。
- Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠
- 每个元素的margin box的左边, 与包含块border box的左边相接触
- BFC的区域不会与float box重叠。
- BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。
- 计算BFC的高度时,浮动元素也参与计算,所以会清除浮动。
### 哪些元素或属性能触发BFC
- 根元素 html
- float属性不为none
- position为absolute或fixed
- display为inline-block, table-cell, table-caption, flex, inline-flex
- overflow不为visible
## 案例一:两栏布局
**要求:左边固定宽度,右边宽度可变。**
**方式一:**
思路:左边固定宽度,浮动;右边不设置宽度,设置margin-left空出左边的宽度。
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.dv1 {
width: 200px;
height: 500px;
background-color: pink;
float: left;
}
.dv2 {
margin-left: 200px;
height: 500px;
background-color: peru;
}
</style>
</head>
<body>
<div class="dv1"></div>
<div class="dv2"></div>
</body>
</html>
```
**方式二:**
思路:BFC的区域不会与float box重叠。所以将右边设置为BFC区域。
这里是有 absolute 绝对定位。
```css
body {
position: relative;
}
.dv1 {
width: 200px;
height: 500px;
background-color: pink;
float: left;
}
.dv2 {
height: 500px;
background-color: peru;
position: absolute;
left: 200px;
right: 0;
}
```
注意:右边一定要加 right:0;
**方式三:**
思路:使用 overflow不为visible 将右边设置为BFC区域。
```css
.dv1 {
width: 200px;
height: 500px;
background-color: pink;
float: left;
}
.dv2 {
height: 500px;
background-color: peru;
overflow: hidden;
}
```
## 案例二:三栏布局
**要求:左边固定宽度,右边固定宽度,中间宽度自适应。**
**方案一:**
思路:使用两栏布局的方案一
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.dv1 {
width: 200px;
height: 500px;
background-color: pink;
float: left;
}
.dv2 {
height: 500px;
background-color: peru;
margin-left: 200px;
margin-right: 200px;
}
.dv3 {
width: 200px;
height: 500px;
background-color: pink;
float: right;
}
</style>
</head>
<body>
<div class="dv1"></div>
<div class="dv2"></div>
<div class="dv3"></div>
</body>
</html>
```
可以看到 dv3 掉了下来???
为什么呢?因为dv2是块级元素,单独占一行,所以dv3只能显示在下一行。
怎么办呢?我们将dv2和dv3的顺序调换一下,就好了:
```html
<div class="dv1"></div>
<div class="dv3"></div>
<div class="dv2"></div>
```
**方案二:**
思路:使用两栏布局的方案二
```css
body {
position: relative;
}
.dv1 {
width: 200px;
height: 500px;
background-color: pink;
float: left;
}
.dv2 {
height: 500px;
background-color: peru;
position: absolute;
left: 200px;
right: 200px;
}
.dv3 {
width: 200px;
height: 500px;
background-color: pink;
float: right;
}
```
**方案三:**
思路:使用两栏布局的方案三
```css
.dv1 {
width: 200px;
height: 500px;
background-color: pink;
float: left;
}
.dv2 {
height: 500px;
background-color: peru;
overflow: hidden;
}
.dv3 {
width: 200px;
height: 500px;
background-color: pink;
float: right;
}
```
结果也是dv3 被挤了下来。调换dv2和dv3的顺序即可。
**方案四:**
思路:使用弹性布局
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
display: flex;
}
.dv1 {
width: 200px;
height: 500px;
background-color: pink;
}
.dv2 {
width: 100%;
height: 500px;
background-color: red;
flex: 1;
}
.dv3 {
width: 200px;
height: 500px;
background-color: pink;
}
</style>
</head>
<body>
<div class="dv1"></div>
<div class="dv2"></div>
<div class="dv3"></div>
</body>
</html>
```
## 案例三:解决父元素与子元素之间的margin-top问题
原文链接:https://www.cnblogs.com/ranyonsue/p/5461749.html
### 问题描述
父元素的盒子包含一个子元素盒子,给子元素盒子一个垂直外边距margin-top的时候,父元素盒子也会往下走margin-top的值,而子元素和父元素的边距则没有发生变化,如下图:

源代码:
```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>
body,
html {
padding: 0;
margin: 0;
}
.parent {
width: 200px;
height: 200px;
background-color: #aaa;
}
.children {
width: 100px;
height: 100px;
background-color: yellow;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
</html>
```
### 原文分析
官方介绍:
In this specification, the expression *collapsing margins* means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.
**所有毗邻的两个或更多盒元素的margin将会合并为一个margin共享之。**
毗邻的定义为:同级或者嵌套的盒元素,并且它们之间没有非空内容、Padding或Border分隔。
这就是原因了。“嵌套”的盒元素也算“毗邻”,也会 Collapsing Margins。这个合并Margin其实很常见,就是文章段落元素`<p/>`,并列很多个的时候,每一个都有上下1em的margin,但相邻的`<p/>`之间只会显示1em的间隔而不是相加的2em。
### 解决办法
这个问题的避免方法很多,只要破坏它出现的条件就行。给 **Outer Div** 加上 padding/border,或者给 **Outer Div / Inner Div** 设置为 float/position:absolute(CSS2.1规定浮动元素和绝对定位元素不参与Margin折叠)。
1、修改父元素的高度,增加 padding-top 样式模拟(padding-top:1px;常用)
2、为父元素添加 overflow: hidden;样式即可(完美)
3、为父元素或者子元素声明浮动(float:left;可用)
4、为父元素添加 border-top(border-top: 1px solid transparent; 可用)
5、为父元素或者子元素声明绝对定位 。
## 案例四:清除浮动
来自笔记:CSS/03-链接伪类、背景、行高、盒子模型、浮动
清除浮动不是不用浮动,清除浮动产生的问题。
> 问题:当父盒子没有定义高度,嵌套的盒子浮动之后,下边的元素发生位置错误(占据父盒子的位置)。
### 方法一
**额外标签法:**在最后一个浮动元素后添加标签。
```css
clear: left | right | both /*用的最多的是clear:both;*/
```
### 方法二
给浮动元素的父集元素使用`overflow:hidden;`
> 注意:如果有内容出了盒子,不能使用这个方法。
### 方法三(推荐使用)
伪元素清除浮动。
> : after 相当于在当前盒子后加了一个盒子。
### 清除浮动总结:
1. 给父元素高度,缺点:高度无法自适应
2. 父元素加 overflow:hidden; 缺点:超出会被隐藏
3. 父元素加定位,absolute/fixed,缺点:脱离文档流。
4. 父元素加浮动,缺点:可能父元素的父元素继续塌陷
5. 父元素加inline-block,缺点:行内块的缺点。
6. 浮动元素的最后加一个额外标签,标签使用clear:both; 缺点:结果冗余
7. 万能清除法,伪元素清除浮动。
```css
content: ".";
display: block;
height: 0;
visibility: hidden;
clear:both;
overflow: hidden;
``` | Daotin/Web/02-CSS/01-CSS基础/BFC的概念,清除浮动.md/0 | {
"file_path": "Daotin/Web/02-CSS/01-CSS基础/BFC的概念,清除浮动.md",
"repo_id": "Daotin",
"token_count": 5352
} | 14 |
### 方法一:使用line-height
示例:
```html
<style>
div {
width: 500px;
height: 300px;
border: 1px solid red;
text-align: center;
line-height: 300px;
}
img {
vertical-align: middle;
}
</style>
</head>
<body>
<div>
<img src="1.png" alt="">
</div>
</body>
```
### 方法二:使用 table
示例:
```html
<style>
div {
width: 500px;
height: 300px;
border: 1px solid red;
text-align: center;
display: table; /*水平方向居中*/
}
span {
display: table-cell; /*垂直方法居中*/
vertical-align: middle;
}
</style>
</head>
<body>
<div>
<span>
<img src="1.png" alt="">
</span>
</div>
</body>
```
注意:行内块元素的外面需要包两层。一层为 display:table;一层为 display:table-cell;
span 设置了 display:table-cell 就相当于一个单元格,只有一个单元格的话,就自动水平居中了,之后设置vertical-align: middle;为每个单元格居中。 | Daotin/Web/02-CSS/01-CSS基础/行内块元素水平垂直居中的方法.md/0 | {
"file_path": "Daotin/Web/02-CSS/01-CSS基础/行内块元素水平垂直居中的方法.md",
"repo_id": "Daotin",
"token_count": 587
} | 15 |
## 1、变量的声明和初始化
```javascript
var number; // 变量的声明,没有赋值
var name = "Daotin"; // 变量的初始化
```
## 2、命名规则(驼峰命名)
- 变量命名必须以**字母**或是下标符号 "_" 或者 "$" 为开头。
- 变量名长度不能超过 255 个字符。
- 变量名中不允许使用空格,首个字不能为数字。
- 不用使用脚本语言中保留的关键字及保留符号作为变量名。
- 变量名区分大小写。
- 汉语可以作为变量名。但是不建议使用!
## 3、数据类型
**查看数据类型的方法:**` typeof name;` 或 `typeof(name); `
>PS:null 的数据类型是 Object。
**基础数据类型:**
` String,Number,Boolean,undefined、null `
**复杂数据类型:**
`Object,function,Array,Date,Error 等 `
## 4、Number
### 4.1、进制
```javascript
var num = 10; // 十进制
var num = 012; // 八进制:0开头
var num = 0xA; // 十六进制:0x开头
```
### 4.2、数值范围
最小值: `Number.MIN_VALUE` ,这个值为: `5e-324`
最大值: `Number.MAX_VALUE` ,这个值为: `1.7976931348623157e+308`
**无穷大**: `Infinity `
**无穷小**: `-Infinity`
### 4.3、不要用小数去验证小数
```javascript
var num1 = 0.1;
var num2 = 0.2;
console.log(num1+num2); // 0.30000000000000004
console.log(0.07*100); // 7.000000000000001
```
### 4.4、NaN
**NaN:(Not a Number)本来应该得到一个数值的,但是结果却并不是一个数值。**
```javascript
console.log("abc"/18); // 结果是NaN
```
> 1、undefined 和任何数值计算为 NaN;
> 2、NaN 与任何值都不相等,包括 NaN 本身。
> 3、isNaN(); 任何不能被转换为数值的值都会导致这个函数返回 true。
## 5、String
1. 使用**单引号**或者**双引号**均可。
2. 获取字符串的长度使用 `变量名.length`
3. 无法输出的字符,记得使用转义字符(\t , \\, \", \\ 等)
4. **字符串拼接**可以使用 + ,像在 Java 一样。
5. **当一个是字符串,另一个是数字,并且使用 乘,减,除 号的时候,字符串会转换成数字进行计算,转换失败返回NaN。**
6. js 没有字符类型只有字符串类型,字符串使用 "" 或者 '' 都是可以的。
7. 字符串是**常量不可变**的。
示例:
```javascript
var str = "hello";
str[0] = "w";
console.log(str); // 还是 hello
var str = "hello";
str = "world";
console.log(str); // 是 world,这个不是改变了当前str地址的字符串的值,而是str指向了新的字符串,旧的字符串的值仍然没有更改。
```
## 6、Boolean
Boolean类型只有两个字面量: true 和 false 。但是所有类型均有与这两个 Boolean 值等价的值。
**下面类型为 true:**true、除0数字、"something"、Object(任何对象)
**下面类型为 false:**false、0 、""(空字符串)、undefined 、null、NaN
## 7、undefined 与 null
虽然 undefined 和 null 都为 false,但是他们的区别是:
1. **在进行数字运算的时候,null + 10 = 10;undefined + 10 = NaN.**
2. **任何数据类型和 undefined 运算都是 NaN;**
3. **任何值和 null 运算,null 可看做 0 运算。** 与字符串 + 操作的时候,会当成字符串处理,不是0.
## 8、数据类型转换
### 8.1、其他类型转换成String
1. `变量 + ""` 或者 `变量 + "其他变量"`
2. `String(变量)`
3. `变量.toString();` // 注意:undefined 和 null 不可以
```javascript
var bool = true;
var num = 111;
var aaa;
var bbb = null;
console.log(typeof(bool+"")); // string
console.log(typeof(num+"")); // string
console.log(typeof(aaa+"")); // string
console.log((aaa+"")); // undefined
console.log(typeof(bbb+"")); // string
```
### 8.2、其他类型转换成 Number
此转换容易产生 NaN,一旦被转换的变量中含有非数字字符,都容易出现 NaN.
**1. 变量 -*/ 一个数字(除非有非数字字符会出现 NaN)**
```js
var num1 = "11" - 0;
var num2 = "11" * 1;
var num = "11" / 1;
```
**2. Number(变量);(有非数字字符会出现NaN)**
```js
Number("11");
Number(""); // 空字符串和空格返回 0
```
**3. parseInt() 和 parseFloat()(译为取整和取浮点数)**
空字符串:parseInt("") 和 parseFloat("") 返回 NaN。
**parseInt(变量):**如果变量中首字符为字母则结果为 NaN。否则取出现首个非数字前的整数。 `123 = parseInt(“123.123aaaa”);`
**parseFloat(变量):**如果变量中首字符为字母则结果为 NaN。否则取出现首个非数字前的浮点数。(如果没有小数的话取整) `123.123 = parseFloat(“123.123aaaa”);`
**4、注意:**
true 数值为 1;false 为0;
null 的数值类型为 0;
undefined 无数值类型或者为 NaN。
### 8.3、其他类型转换成 Boolean
任何数据类型都可以转换成 boolean 类型,所以和以上两个转换不同。将任意类型作为参数传入 `Boolean(参数)` 中,都可以转换成布尔值。
**下面类型为 true:**true、除0的数字、非空字符串、Object(任何对象)
**下面类型为 false:**false、0 、空字符串、undefined 、null、NaN
```js
Boolean(参数);
```
| Daotin/Web/03-JavaScript/01-JavaScript基础知识/02-变量.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/01-JavaScript基础知识/02-变量.md",
"repo_id": "Daotin",
"token_count": 3275
} | 16 |
## 一、什么是cookie
cookie 就是一种特殊的字符串。是存放于**指定网站的指定浏览器下面的文件夹下**。用来帮助页面记录用户操作(会话跟踪技术)
**cookie可以跨越一个域名下的多个网页,但不能跨越多个域名使用。**
cookie不支持本地文件,只能是网站下文件。
cookie 需要注意的属性有:名称,内容,域名,路径,创建时间,到期时间。
## 二、cookie 的创建与保存
使用document对象的cookie属性,cookie是以键值对(key=value)字符串的方式保存在文件里的。
```js
// 定义语法 document.cookie = "名称=内容"
document.cookie = "myname=Daotin";
document.cookie = "myage=18";
```
>
> 在cookie 里面,名称是唯一的标识;
>
> 如果定义的时候改变了名称,那么cookie会被覆盖;
>
> 如果定义的时候改变了名称后面的内容,那么cookie取到的内容也会改变。
## 三、cookie的读取
```js
// 取值,返回值为字符串
console.log(document.cookie); //"myname=Daotin; myage=18" (使用服务器模式打开网页才可以看到)
```
## 四、cookie失效时间
Cookie总是保存在客户端中,按在客户端中的存储位置,可分为内存(非持久)Cookie和硬盘(持久)Cookie。
- 内存Cookie由浏览器维护,保存在内存中,**浏览器关闭**(不是页面关闭)后就消失了,其存在时间是短暂的。
- 硬盘Cookie保存在硬盘里,有一个过期时间,除非用户手工清理或到了过期时间,硬盘Cookie不会被删除,其存在时间是长期的。如果 cookie 包含到期日期,则可视为持久性 cookie。 在指定的到期日期,cookie 将从磁盘中删除。
如果设置的是一个过期的时间,会自动删除。
```js
// 设置cookie 到期时间
var date = new Date();
date.setDate(date.getDate()+7); // 设置7天后的时间点
document.cookie = "myage=18; expires=" + date;
```
## 五、cookie注意点(中文编码问题)
- 一次创建多个cookie,可以使用 “&”进行分割:
- 在cookie 的名或值中不能有:分号(;)、逗号(,)、等号(=)以及空格。
- 对于中文怎么办?
1、中文编码 `encodeURIComponent("中文")` ,解码: `decodeURIComponent("%E4%B8%AD%E6%96%87")`
2、中文编码 `escape("中文")` ,解码:`unescape("%u4E2D%u6587")`
3、中文编码 `encodeURI("中文")` ,解码:`decodeURI("%E4%B8%AD%E6%96%87");`
- **同一路径下,cookie的key是唯一的,但是不同路径下,key的值可以重复。**
## 六、常见cookie应用
- 日期cookie :
当我们访问某些网站时,首页会显示:“你上次访问的时间是:2018.11.20” 的时候,日期是在 cookie 中保存着。
- 保存用户登录状态:
将用户id存储于一个cookie内,这样当用户下次访问该页面时就不需要重新登录了。
- 跟踪用户行为:
一个天气预报网站,能够根据用户选择的地区显示当地的天气情况。如果每次都需要选择所在地是烦琐的,当利用了 cookie后就会显得很人性化了,系统能够记住上一次访问的地区,当下次再打开该页面时,它就会自动显示上次用户所在地区的天气情况。
- 定制页面(如 md2all 网站):
如果网站提供了换肤或更换布局的功能,那么可以使用cookie来记录用户的选项,例如:背景色、分辨率等。当用户下次访问时,仍然可以保存上一次访问的界面风格。
## 七、封装函数实现cookie的增删改查
```js
// cookie的增加,删除,修改
function setCookie(key, value, days) {
if (days) {
var date = new Date();
date.setDate(date.getDate() + days);
document.cookie = key + "=" + value + ";expires=" + date;
} else {
document.cookie = key + "=" + value;
}
};
// cookie 的查找
function getCookie(key) {
var cookie = document.cookie;
if (cookie) {
var cookieStr = cookie.split("; ");
var item = cookieStr.filter(function (ele) {
return ele.split("=")[0] == key;
})[0];
if (item) {
return item.split('=')[1];
} else {
return "";
}
} else {
return "";
}
};
```
## 八、cookie 的路径问题
同一路径下的网页及其子目录下的网页可以共享cookie,路径不同时,不能访问 。
默认情况下,如果在某个页面创建了一个cookie,那么该页面所在目录中的其它页面也可以访问该cookie。
如果这个目录下还有子目录,则在子目录中也可以访问。
例如在 www.xxxx.com/html/a.html 中所创建的cookie,可以被 www.xxxx.com/html/b.html 或 www.xxx.com/ html/some/c.html 所访问,但不能被 www.xxxx.com/d.html 访问。
如果想控制cookie可以访问的目录,需要使用path参数设置cookie,语法:
` document.cookie="name=value; path=cookieDir";` 其中cookieDir表示可访问cookie的目录。
```js
例如:
document.cookie="userId=007; path=/temp"; //就表示当前cookie仅能在temp目录下使用。
document.cookie="userId=007; path=/"; //表示cookie在整个网站根目录下可用.
```
## 九、cookie的域名问题
必须在绑定域名的服务器上才可以设置域名.
并且只能设置绑定的域名,也就是说,不同服务器间的cookie文件不共享。主机名是指同一个域下的不同主机。
例如:www.google.com 和 www.gmail.google.com 就是两个不同的主机名。
默认情况下,一个主机中创建的cookie在另一个主机下是不能被访问的,但可以通过 domain参数来实现对其的控制,其语法格式为: `document.cookie="name=value; domain=cookieDomain";`
```js
// 以 google 为例,要实现跨主机访问,可以写为:
document.cookie="name=value;domain=.google.com";
```
这样,所有google.com下的主机都可以访问该cookie。
## 十、示例:利用cookie记录注册信息
**cookie_register**
注册用户信息,然后跳转到登录界面。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
ID: <input type="text" name="" id="txt"><br>
PWD: <input type="text" name="" id="pwd"><br>
<button>Register</button>
</body>
<script src="../js/daotin.js"></script>
<script>
var txt = document.getElementById("txt");
var pwd = document.getElementById("pwd");
var btn = document.getElementsByTagName("button")[0];
btn.onclick = function () {
var username = txt.value;
var userpwd = pwd.value;
if (username != "" && userpwd != "") {
if (!getCookie("username_" + username)) {
setCookie("username_" + username, username, 7);
setCookie("userpwd_" + username, userpwd, 7);
window.location.href = "cookie_login.html";
}
txt.value = "";
pwd.value = "";
} else {
alert("username or userpwd can not empty.");
}
};
</script>
</html>
```

**cookie_login**
在登录界面校验登录时输入的用户信息是否合法,合法则跳入所有cookie列表。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
ID: <input type="text" name="" id="txt"><br>
PWD: <input type="text" name="" id="pwd"><br>
<button>Login</button>
</body>
<script src="../js/daotin.js"></script>
<script>
var txt = document.getElementById("txt");
var pwd = document.getElementById("pwd");
var btn = document.getElementsByTagName("button")[0];
btn.onclick = function () {
var username = txt.value;
var userpwd = pwd.value;
if (getCookie("username_" + username)) {
if (getCookie("userpwd_" + username) == userpwd) {
window.location.href = "user_pwd_list.html";
} else {
alert("password is wrong.");
}
} else {
alert("username is not exist.");
}
};
</script>
</html>
```

**userInfo_list**
展示所有cookie信息。点击删除时,删除列表对应的cookie和浏览器中的对应cookie文件。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="box"></div>
<table border="1">
<tr>
<th>KEY</th>
<th>VALUE</th>
<th>DEL</th>
</tr>
</table>
</body>
<script src="../js/daotin.js"></script>
<script>
var box = document.getElementById("box");
var tableObj = document.getElementsByTagName("table")[0];
var delList = document.getElementsByTagName("a");
var cookie = document.cookie;
var cookieList = cookie.split("; ");
var itemList = cookieList.filter(function (item) {
return item.indexOf("username_") == 0;
});
// ["username_lvonve=lvonve", "username_daotin=daotin", "username_feng=feng"]
itemList.forEach(function (item) {
var itemName = item.split("=")[1];
var trObj = document.createElement("tr");
tableObj.appendChild(trObj);
var tdUserName = document.createElement("td");
var tdUserPwd = document.createElement("td");
var tdDel = document.createElement("td");
tdUserName.innerHTML = itemName;
tdUserPwd.innerHTML = getCookie("userpwd_" + itemName);
tdDel.innerHTML = "<a href='javascript:;'>del</a>";
trObj.appendChild(tdUserName);
trObj.appendChild(tdUserPwd);
trObj.appendChild(tdDel);
});
for (var i = 0; i < delList.length; i++) {
delList[i].onclick = function () {
var pwd = this.parentNode.previousElementSibling || this.parentNode.previousSibling;
var uname = pwd.previousElementSibling || pwd.previousSibling;
console.log(pwd.innerHTML);
setCookie("username_" + uname.innerHTML, "", -1);
setCookie("userpwd_" + uname.innerHTML, "", -1); //"userpwd_lvonve=111"
this.parentNode.parentNode.remove(); // 删除tr
window.location.reload();
};
}
</script>
</html>
```

| Daotin/Web/03-JavaScript/02-DOM/09-cookie增删改查.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/02-DOM/09-cookie增删改查.md",
"repo_id": "Daotin",
"token_count": 5992
} | 17 |
我们有时候逛网站的时候,有的图片网站的图片排列**在纵向上是错落有致的**,并不是高度统一的,如下图,这个效果是怎么做的呢?(下图是我截取花瓣网站的图片)

**解决思路:**
解决的思路就是先确定显示的列数,每一列都是一个li标签,然后图片是一张一张生成放上去的,在放上去的时候,判断四列中哪一个的高度最矮,然后在最矮的位置的li中插入图片,就这样一张一张插入,直到插入所有的图片,就显示这样的瀑布流。
**代码:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{margin: 0;padding: 0;}
ul{list-style: none;}
li{float: left;margin-left: 5px}
</style>
</head>
<body>
<script>
const COL=4;
// 存储li的数组
var arr=[];
// 最小高度数值列表
var minHeightList=[];
// 初始化函数执行
init();
/*
* 初始化函数
* 1、创建ul,并且放在body中
* 2、根据常数COL创建若干个li,这里循环COL次
* 3、创建li并且将li放在ul中,设置每个li的宽度
* 4、将创建好的li放在数组中
* 5、给最小高度数组放置数据0,也就是最小高度都是从0开始
* 6、加载图片
* */
function init() {
var ul=document.createElement("ul");
document.body.appendChild(ul);
for(var i=0;i<COL;i++){
var li=document.createElement("li");
ul.appendChild(li);
li.style.width=document.documentElement.clientWidth/COL-10+"px";
arr.push(li);
minHeightList.push(0);
}
loadImg();
}
/*
*
* 加载图片函数
* 1、新建一个图片
* 2、设置图片的num属性是2
* 3、给这个图片增加load事件侦听,加载图片后执行loadHandler函数
* 4、设置图片的地址是2-.jpg(我们所有图片都是2-,3-,4-这样的)
* */
function loadImg() {
var img=new Image();
img.num=2;
img.addEventListener("load",loadHandler);
img.src="img/"+img.num+"-.jpg";
}
/*
* 加载图片后执行的事件函数
* 1、求出最小高度数组中最小的值
* 2、求出这个最小值在数组中的下标
* 3、浅复制当前加载图片,并且设置这个图片的宽度
* 4、将图片放在和最小高度数组对应下标的li中
* 5、将这个图片的高度累加到最小高度数组对应的数值上
* 6、累加num值
* 7、判断num是否大于79,如果大于79删除事件加载侦听,并且标识加载完成
* 8、设置继续加载num所对应的图片
*
* */
function loadHandler(e) {
var min=Math.min.apply(null,minHeightList);
var index=minHeightList.indexOf(min);
var image=this.cloneNode(false);
image.style.width=document.documentElement.clientWidth/COL-10+"px";
arr[index].appendChild(image);
minHeightList[index]+=image.offsetHeight;
this.num++;
if(this.num>79){
this.removeEventListener("load",loadHandler);
console.log("加载完成");
return;
}
this.src="img/"+this.num+"-.jpg";
}
</script>
</body>
</html>
```
其中 loadHandler 中使用了浅拷贝,主要是不想在新创建一个img时要拷贝以前的src,num,事件等,因为都是一样的,所以直接浅拷贝就行。其实和下面方法等同(我其中有用jQuery的语法):
> 在这里使用浅拷贝和深拷贝是一样的,因为这里img元素没有子元素。
>
> DOM的浅拷贝和深拷贝的区别是:是否拷贝元素里面的子元素。
>
> 而jQuery的浅拷贝就相当于DOM的深拷贝,jQuery的深拷贝是将拷贝的元素的事件都拷贝下来。
```js
function loadHandler() {
let min = Math.min.apply(null, minHeight);
let minIndex = minHeight.indexOf(min);
arr[minIndex].append(this);
minHeight[minIndex] += this.getBoundingClientRect().height;
// // let im = this.cloneNode(false);
let im = new Image();
im.src = this.src;
im.num = this.num;
$(im).css("width", "100%");
$(im).on("load", loadHandler);
im.num++;
if (this.num > 78) {
$(im).off("load", loadHandler);
return;
}
im.src = `../images/img/${im.num}-.jpg`;
arr[minIndex].append(im);
minHeight[minIndex] += im.getBoundingClientRect().height;
}
```
最后的效果就是这样:

| Daotin/Web/03-JavaScript/02-DOM/案例02:瀑布流图片.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/02-DOM/案例02:瀑布流图片.md",
"repo_id": "Daotin",
"token_count": 3259
} | 18 |
面向对象
1、以后写代码不能有零散的代码。代码都在对象或者函数中。
2、常见的写法:
```js
var Method = (function(){
return {
fn: function() {
}
};
})();
// 调用的时候
Method.fn();
```
拖拽案例:
```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>
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div></div>
</body>
<script>
var Method = Method || (function () {
var mouseBind = null;
return {
drag: function (ele) {
// this --> Method
mouseBind = this.mouseHandler.bind(this);
ele.addEventListener("mousedown", mouseBind);
},
mouseHandler: function (e) {
if (e.type === "mousedown") {
// this -> ele
this.point = {
x: e.offsetX,
y: e.offsetY
};
document.addEventListener("mousemove", mouseBind);
e.currentTarget.addEventListener("mouseup", mouseBind);
this.ele = e.currentTarget;
} else if (e.type === "mousemove") {
// this -> Method
// e.currentTarget -> document
Object.assign(this.ele.style, {
left: e.x - this.point.x + "px",
top: e.y - this.point.y + "px"
});
} else if (e.type === "mouseup") {
document.removeEventListener("mousemove", mouseBind);
e.currentTarget.removeEventListener("mouseup", mouseBind);
}
}
}
})();
Method.drag(document.querySelector("div"));
</script>
</html>
```
下面是不用 bind 的写法:
```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>
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div></div>
</body>
<script>
// var Method = Method || (function () {
// var mouseBind = null;
// return {
// drag: function (ele) {
// // this --> Method
// mouseBind = this.mouseHandler.bind(this);
// ele.addEventListener("mousedown", mouseBind);
// },
// mouseHandler: function (e) {
// if (e.type === "mousedown") {
// // this -> ele
// this.point = {
// x: e.offsetX,
// y: e.offsetY
// };
// document.addEventListener("mousemove", mouseBind);
// e.currentTarget.addEventListener("mouseup", mouseBind);
// this.ele = e.currentTarget;
// } else if (e.type === "mousemove") {
// // this -> Method
// // e.currentTarget -> document
// Object.assign(this.ele.style, {
// left: e.x - this.point.x + "px",
// top: e.y - this.point.y + "px"
// });
// } else if (e.type === "mouseup") {
// document.removeEventListener("mousemove", mouseBind);
// e.currentTarget.removeEventListener("mouseup", mouseBind);
// }
// }
// }
// })();
var Method = Method || (function () {
return {
drag: function (ele) {
// this --> Method
ele.addEventListener("mousedown", this.mouseHandler);
ele.self = this;
},
mouseHandler: function (e) {
if (e.type === "mousedown") {
// this -> ele
document.point = {
x: e.offsetX,
y: e.offsetY
};
document.addEventListener("mousemove", this.self.mouseHandler);
this.addEventListener("mouseup", this.self.mouseHandler);
document.ele = this;
} else if (e.type === "mousemove") {
// this -> document
Object.assign(this.ele.style, {
left: e.x - this.point.x + "px",
top: e.y - this.point.y + "px"
});
} else if (e.type === "mouseup") {
document.removeEventListener("mousemove", this.self.mouseHandler);
this.removeEventListener("mouseup", this.self.mouseHandler);
}
}
}
})();
Method.drag(document.querySelector("div"));
</script>
</html>
```
| Daotin/Web/03-JavaScript/04-JavaScript高级知识/案例02:DIV拖拽.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/04-JavaScript高级知识/案例02:DIV拖拽.md",
"repo_id": "Daotin",
"token_count": 3050
} | 19 |
## 操作数据库
### 新增数据库
> `create database 数据库名称 [库选项];` // create dabase mydb charset utf8;
### 查询数据库
> `show databases;` // 查看所有数据库
>
> `show databases like pattern; ` //查看指定部分的数据库(模糊匹配)show databases like 'my%
>
> `show create database 数据库名称;` // 查看数据库的创建语句 show create database mydb;
### 更新数据库
> `alter database 数据库名 [库选项];` // alter database mydb charset gbk;
### 删除数据库
> `drop database 数据库名字;`
## 操作数据表
### 新增数据表
> create table [if not exists] 数据库名.表名(
>
> 字段名字 数据类型,
>
> 字段名字 数据类型
>
> )[表选项];
> create table if not exists mydb.mytable(
>
> name varchar(10),
>
> age int
>
> )charset utf8;
>
> 或者:
>
> use mydb;
>
> create table if not exists mytable(
>
> name varchar(10),
>
> age int
>
> )charset utf8;
### 查看数据表
> `use mydb;`
>
>
>
> `show tables;` // 查找所有数据表
>
> `show tables like ‘pattern’;` // show tables like ‘my%’;
>
> `show create table 表名;` // 查看表的创建语句
>
> `desc/describe/show columns from 表名;` // 查看表结构(表中的字段信息)
>
> desc mytable;
> describe mytable;
> show columns from mytable;
### 修改数据表
> `rename table 老表名 to 新表名;` // 修改表名 // rename table mytable to mt;
>
> `alter table 表名 表选项 [=] 值;` // 修改表选项 alter table mytable charset = GBK;
> `Alter table 表名 add [column] 字段名 数据类型 [列属性] [位置];` // 新增字段
>
> -- 给mytable增加ID放到第一个位置
> alter table mytable
> add column id int
> first;
>
> -- mysql会自动寻找分号: 语句结束符
>
> -- after 字段名 :增加在某个字段之后
>
> `alter table 表名 modify 字段名 数据类型 [属性][位置];` // 修改字段:
>
> -- 将mytable的number学号字段变成固定长度,且放到第二位(id之后)
> alter table mytable
> modify number char(10) after id;
>
> `Alter table 表名 change 旧字段 新字段名 数据类型 [属性] [位置];` // 重命名字段
>
> -- 修改mytable中的gender字段更名为sex
> alter table my_student
> change gender sex varchar(10);
>
> `Alter table 表名 drop 字段名;` // 删除字段
>
> -- 删除mytable中的年龄字段(age)
> alter table mytable drop age;
### 删除数据表
> `Drop table 表名1,表名2...;` // 可以一次性删除多张表 drop table mytable;
## 数据操作
### 新增数据
> `insert into 表名 values(值列表)[,(值列表)];` // 可以一次性插入多条记录
>
> -- 插入数据(要求数据的值出现的顺序必须与表中设计的字段出现的顺序一致)
> insert into mytable values(1,'itcast0001','Jim','male'),
> (2,'itcast0002','Hanmeimei','female');
>
> `insert into 表名 (字段列表) values (值列表)[,(值列表)];`
>
> -- 插入数据: 指定字段列表
> insert into mytable(username,userpwd,usertel) values('leson1','good','15871437346')
### 查看数据
> `Select */字段列表 from 表名 [where条件];`
>
> -- 查看所有数据
> select * from mytable;
>
> -- 查看指定字段,指定条件数据
> select id,number,sex,name from mytable where id = 1; -- 查看满足id为1的学生信息
### 更新数据
> `update 表名 set 字段 = 值 [where条件];` // 建议都有where: 又不是更新全部
>
> -- 更新数据name为'jim'的sex值
> update mytable set sex = 'female' where name = 'jim';
### 删除数据
> `delete from 表名 [where条件];`
>
> -- 删除数据(删除sex为male的字段数据)
> delete from mytable where sex = 'male'; | Daotin/Web/05-PHP&数据库/02-mysql的增删改查快速查找.md/0 | {
"file_path": "Daotin/Web/05-PHP&数据库/02-mysql的增删改查快速查找.md",
"repo_id": "Daotin",
"token_count": 2082
} | 20 |
## 一、Less简介
LESS 是一种动态的样式表语言,通过简洁明了的语法定义,使编写 CSS 的工作变得非常简单,本质上,LESS 包含一套自定义的语法及一个解析器。

## 二、less 安装
1、下载安装 node.js 环境。(官网:https://nodejs.org/zh-cn/)
2、安装完成后验证 node 环境是否安装成功。
在命令行中输入:`node -v ` 出现 node 的版本号表示安装成功。
3、安装 less 工具(需要联网)。
在命令行中输入:`npm install -g less` 即可下载安装。
4、安装后验证 less 是否安装成功。
命令行输入:`lessc -v` 出现 less 版本号,即表示安装成功。

## 三、编译
浏览器只能识别 CSS,Less 只是用来提升CSS可维护性的一个工具,所最终需要将LESS编译成CSS。
编译方式有两种:
1、一种是使用命令行的方式手工编译。
在我们编写好一个 less 文件后,可以使用命令行输入以下指令将 less 文件编译成 css 文件。
```
lessc .\test.less .\test.css
```
这种手工编译的方式效率比较低下,一般我们都会借助一些编辑器来完成自动编译。
2、这里我使用 vscode,使用很简单,只需要安装插件 “**Easy LESS**” ,那么编写的 less 文件在保存时会自动在 less 文件相同的目录下生成 css 文件。

## 四、语法
### 1、注释
注释的方式有两种:`//` 或者 `/**/` 。
但是这两种注释有区别:这两种样式在 less 中都是注释,但是 `//` 注释不会进行编译,也就是不会在生成的 css 文件中显示,而 `/**/` 注释则会在 css 文件中对应显示。
```less
/*注释 才会编译*/
//这也是样式,但是不会进行编译
```
### 2、变量
语法格式为:`@变量名:值;` ,比如 `@baseColor: #ccc;`
使用的时候: `div { color: @baseColor;}`
```less
/*变量 @变量名:值; */
@baseColor:#e92322;
a{
color: @baseColor;
}
```
### 3、混入(类似于函数)
语法:`.样式名(@变量名 :默认值) {具体样式}`
```less
/*混入:可以将一个定义好的样式引入到另外一个样式中 类似于函数的调用*/
/*.addRadius{
border-radius: 10px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
}*/
/*相当于定义一个函数的参数*/
.addRadius(@r:10px){
border-radius: @r;
-webkit-border-radius: @r;
-moz-border-radius: @r;
}
div{
width: 200px;
height: 200px;
/*引入已经写好的圆角样式*/
/*传入参数*/
.addRadius(5px);
}
```
### 4、嵌套
嵌套可以实现选择器的继承,可以减少代码量,同时使用代码结构更加清晰。
```less
/* 以前我们写的样式
.jd_header{}
.jd_header > div{}
.jd_header > div > h3{}
.jd_header > div > h3::before{}
.jd_header > div > a{}
.jd_header > div > a:hover{}
*/
/*嵌套:实现选择器的继承,可以减少代码量,同时使用代码结构更加清晰*/
.jd_header{
width: 100%;
height: 200px;
.addRadius();
// 加 > 表示直接子元素
> div{
// 加 & 表示中间没有空格为 div::before,如果没有 & 则是 div ::before 就错了。
&::before{
content: "";
}
width: 100%;
// div下面的直接子元素a
>a{
text-decoration: underline;
// a::hover,中间没有空格
&:hover{
text-decoration: none;
}
}
> h3{
height: 20px;
}
ul{
list-style: none;
}
}
}
```
## 五、less 文件引入
我们之前编写好 less 文件之后,都是自动解析成 css 然后添加到 html 文件中。如果 css 的文件很多的话,就要引入很多个 link 标签,那么可不可以直接引入 less 文件呢?
当然可以。
语法:
```html
<link rel="stylesheet/less" href="./index.less">
```
只是在 stylesheet 后面加上 less 的说明。
只是引入 less 文件是不可以的,还需要**引入解析 less 的 js 插件**。
```html
<script src="./js/less.js"></script>
```
看起来好麻烦哦,为什么要引入 less 文件,它有什么好处吗?
好处是:不管有多少 less 文件,只需要引入一个 less 文件就可以了,其他需要的 less 文件都包含在引入的这个 less 文件中。
**如何在 less 文件中引入其他 less 文件呢?**
语法:
```less
@import "other1.less"; // other.less 为其他 less 文件的路径名称
@import "other2.less";
@import "other3.less";
```
这样,不管有多少个 less 文件,都可以写到一个待引入的 less 文件中。
| Daotin/Web/07-移动Web开发/08-Less.md/0 | {
"file_path": "Daotin/Web/07-移动Web开发/08-Less.md",
"repo_id": "Daotin",
"token_count": 2876
} | 21 |
@baseColor: #e92322;
/* 头部块 */
.wjs-header {
height: 50px;
line-height: 50px;
border-bottom: 1px solid #ccc;
.row {
height: 100%;
text-align: center;
> div:nth-of-type(-n+3) {
border-right: 1px solid #ccc;
}
.code {
display: block;
position: relative;
> img {
display: none;
position: absolute;
border: 1px solid #ccc;
border-top: none;
left: 50%;
transform: translateX(-50%);
top: 49px;
}
&:hover {
> img {
display: block;
}
}
}
> div:nth-last-of-type(1) {
> .btn-danger {
background-color: @baseColor;
border-color: @baseColor;
}
> .btn {
padding: 3px 15px;
}
> .btn-link {
text-decoration: none;
color: #aaa;
}
}
}
}
/*导航条*/
.wjs-nav {
&.navbar {
margin-bottom: 0;
}
.navbar-brand {
height: 80px;
line-height: 50px;
font-size: 40px;
> span:nth-of-type(1) {
color: @baseColor;
}
> span:nth-of-type(2) {
color: #333;
}
}
.navbar-toggle {
margin-top: 23px;;
}
.navbar-nav {
> li {
height: 80px;
> a {
height: 80px;
line-height: 50px;
font-size: 16px;
&:hover, &:active {
color: #777;
border-bottom: 3px solid @baseColor;
}
}
}
.active {
a,a:hover,a:active {
background-color: transparent;
border-bottom: 3px solid @baseColor;
}
}
}
}
/*轮播图*/
/*
w<768px-移动端:图片会随着屏幕的缩小自动适应--缩小
img的宽度为100%,通过img标签来实现
w>=768px:
图片做为背景,当屏幕宽度变宽的时候,会显示更多的图片的两边区域
1.background-image添加图片
2.添加background-position:center center
3.background-size:cover
*/
.wjs-banner {
.bigImg {
width: 100%;
height: 410px;
/*去除图片基线*/
display: block;
background-position:center center;
background-size: cover;
}
.smallImg {
// width: 100%;
// display: block;
img {
width: 100%;
/*去除图片基线*/
display: block;
}
}
}
/*信息块*/
.wjs-info {
padding: 20px;
.wjs_icon {
font-size: 26px;
}
.row {
> div {
margin: 10px 0;
> a:hover {
color: @baseColor;
}
}
}
}
/*预约块*/
.wjs-reverse {
height: 60px;
line-height: 60px;
border-top: 1px solid #ccc;
border-bottom: 1px solid #ccc;
.wjs_icon {
font-size: 18px;
}
a:hover {
color: @baseColor;
}
.col-sm-9 {
> a:last-of-type {
color: @baseColor;
border-bottom: 1px dashed @baseColor;
}
}
}
/*产品块*/
.wjs-product{
clear: both;
background-color: #eee;
li {
height: 100px;
line-height: 100px;
padding: 0 10px;
> a {
margin: 0;
border: none;
line-height: 50px;
}
a:hover {
border: none;
border-bottom: 3px solid @baseColor;
}
&.active {
> a,a:hover,a:focus{
background-color: transparent;
border: none;
border-bottom: 3px solid @baseColor;
}
}
}
}
/*产品块*/
.wjs-product {
.tabs-parent {
width: 100%;
overflow: hidden;
}
.wjs-pBox {
height: 100%;
background-color: #fff;
margin-top: 20px;
position: relative;
box-shadow: 1px 1px 5px #ccc;
> .wjs-pLeft {
height: 100%;
margin-right: 100px;
padding: 10px 0;
font-size: 12px;
position: relative;
> p {
font-size: 16px;
text-align: center;
}
.row {
margin-left: 0;
margin-right: 0;
> div:nth-of-type(even) {
text-align: right;
}
}
}
> .wjs-pRight {
width: 100px;
height: 100%;
position: absolute;
right: 0;
top: 0;
border-left: 1px dashed #ccc;
text-align: center;
padding-top: 40px;
> .wjs-pRight-tip {
width: 100%;
span {
font-size: 12px;
border-radius: 3px;
cursor: pointer;
}
span:first-of-type {
border: 1px solid @baseColor;
color: @baseColor;
}
span:last-of-type {
border: 1px solid blue;
color: blue;
}
}
> b {
font-size: 40px;
color: @baseColor;
}
> sub {
bottom: 0;
color: @baseColor;
}
&::before, &::after {
content: "";
width: 10%;
height: 10px;
border-radius: 5px;
background-color: #eee;
position: absolute;
left: -5px;
}
&::before {
top: -5px;
}
&::after {
bottom: -5px;
}
}
&.active {
background-color: @baseColor;
.wjs-pLeft {
color: #fff;
&::before {
content: "\e915";
font-family: "wjs";
position: absolute;
left: 0;
top: -4px;
font-size: 26px;
}
}
.wjs-pRight {
b,sub,p {
color: #fff;
}
}
}
}
}
/*新闻块*/
.wjs-news {
padding: 20px;
.wjs_nTitle{
line-height:50px;
font-size: 25px;
border-bottom: 1px solid #ccc;
text-align: center;
position: relative;
&::before{
content: "";
width: 8px;
height: 8px;
border-radius: 4px;
border: 1px solid #ccc;
position: absolute;
bottom: -4px;
right: -8px;
}
}
/*设置li元素间的虚线*/
.wjs_newsLine {
width: 1px;
height: 100%;
position: absolute;
border-left: 1px dashed @baseColor;
left:45px;
top:0;
}
.nav-tabs {
border-bottom: none;
> li {
margin-bottom:60px;
> a {
background-color: #ccc;
width: 60px;
height: 60px;
border: none;
border-radius: 50%;
}
> a:hover {
border: none;
background-color: @baseColor;
}
&.active {
> a {
border: none;
background-color: @baseColor;
}
}
.wjs_icon{
font-size: 30px;
color: #fff;
}
}
> li:last-of-type {
margin-bottom: 0;
}
/*媒体查询设置li元素的样式*/
@media screen and (min-width: 768px) and (max-width: 992px) {
li {
margin: 20px 30px;
}
}
@media screen and (max-width: 768px) {
li {
margin: 20px 0;
width: 25%;
}
}
}
.tab-content {
.wjs_newslist {
list-style: none;
> li {
line-height:60px;
}
}
}
}
/*合作块*/
.wjs-partner {
background-color: #eee;
padding: 20px;
text-align: center;
h3 {
width: 100%;
}
ul {
list-style: none;
display: inline-block;
> li {
float: left;
margin: 0 15px;
}
.wjs_icon {
font-size: 80px;
}
}
} | Daotin/Web/07-移动Web开发/案例源码/03-微金所/css/wjs-index.less/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/css/wjs-index.less",
"repo_id": "Daotin",
"token_count": 5825
} | 22 |
// Rotated & Flipped Icons
// -------------------------
.@{fa-css-prefix}-rotate-90 { .fa-icon-rotate(90deg, 1); }
.@{fa-css-prefix}-rotate-180 { .fa-icon-rotate(180deg, 2); }
.@{fa-css-prefix}-rotate-270 { .fa-icon-rotate(270deg, 3); }
.@{fa-css-prefix}-flip-horizontal { .fa-icon-flip(-1, 1, 0); }
.@{fa-css-prefix}-flip-vertical { .fa-icon-flip(1, -1, 2); }
// Hook for IE8-9
// -------------------------
:root .@{fa-css-prefix}-rotate-90,
:root .@{fa-css-prefix}-rotate-180,
:root .@{fa-css-prefix}-rotate-270,
:root .@{fa-css-prefix}-flip-horizontal,
:root .@{fa-css-prefix}-flip-vertical {
filter: none;
}
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/less/rotated-flipped.less/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/less/rotated-flipped.less",
"repo_id": "Daotin",
"token_count": 290
} | 23 |
## 一、ECMAScript 5 严格模式
### 1、概述
除了正常运行模式,ECMAscript 5添加了第二种运行模式:"严格模式"(strict mode)。顾名思义,这种模式使得Javascript在更严格的条件下运行。
### 2、目的
- 消除Javascript语法的一些不合理、不严谨之处,减少一些怪异行为;
- 消除代码运行的一些不安全之处,保证代码运行的安全;
- 提高编译器效率,增加运行速度;
- 为未来新版本的Javascript做好铺垫。
"严格模式"体现了Javascript更合理、更安全、更严谨的发展方向,包括IE 10在内的主流浏览器,都已经支持它,许多大项目已经开始全面拥抱它。
另一方面,同样的代码,在"严格模式"中,可能会有不一样的运行结果;一些在"正常模式"下可以运行的语句,在"严格模式"下将不能运行。掌握这些内容,有助于更细致深入地理解Javascript,让你变成一个更好的程序员。
### 3、使用
1、将"use strict"放在脚本文件的第一行,则整个脚本都将以"严格模式"运行。**如果这行语句不在第一行,则无效,整个脚本以"正常模式"运行。**如果不同模式的代码文件合并成一个文件,这一点需要特别注意。
(严格地说,只要前面不是产生实际运行结果的语句,"use strict"可以不在第一行,比如直接跟在一个空的分号后面。)
```html
<script>
"use strict";
//...
</script>
```
2、针对单个函数
将"use strict"放在函数体的第一行,则整个函数以"严格模式"运行。
```js
function strict(){
"use strict";
return "这是严格模式。";
}
```
## 二、语法和行为改变
### 1、全局变量必须用var显示声明变量
在正常模式中,如果一个变量没有声明就赋值,默认是全局变量。严格模式禁止这种用法,全局变量必须显式声明。
```html
<script type="text/javascript">
"use strict";
v = 1; // 报错,v未声明
//name = "Daotin";
for (i = 0; i < 2; i++) { // 报错,i未声明
}
</script>
```
> 不能使用 name,因为 name 是window的一个保留属性,默认为空。
### 2、禁止自定义的函数中的this指向window
```html
<script>
"use strict";
function foo() {
console.log(this);
}
foo();
</script>
```
没有 "use strict" 的时候,打印 window对象,有 "use strict" 的时候,打印undefined。
### 3、严格模式会创建eval作用域
eval会解析语句中的字符串。
```html
<script>
"use strict";
var name = 'Daotin';
eval('var name = "lvonve"; console.log(name)');
console.log(name);
</script>
```
如果不加 "use strict"; ,两次打印的结构都为 lvonve;加了的话,打印结果为 lvonve和Daotin。也就相当于给eval创建了一个作用域。
### 4、对象不能有重名的属性
正常模式下,如果对象有多个重名属性,最后赋值的那个属性会覆盖前面的值。严格模式下,这属于语法错误。
(但是在浏览器console下面并没有显示错误信息。)
```html
<script>
"use strict";
var o = {
p: 1,
p: 2
}; // 语法错误
</script>
```
### 5、禁止删除变量
严格模式下无法删除变量。只有configurable设置为true的对象属性,才能被删除。
```js
"use strict";
var x;
delete x; // 语法错误
var o = Object.create(null, {'x': {
value: 1,
configurable: true
}});
delete o.x; // 删除成功
```
| Daotin/Web/08-ES6语法/01-ES5严格模式.md/0 | {
"file_path": "Daotin/Web/08-ES6语法/01-ES5严格模式.md",
"repo_id": "Daotin",
"token_count": 2298
} | 24 |
## 1、学习资源
MongoDB学习教程:https://piaosanlang.gitbooks.io/mongodb/content/
MongoDB教程:http://www.mongodb.org.cn/tutorial/
## 2、关于MongoDB
MongoDB是面向文档型的数据库。
在MySql里面我们是一个个的数据表,但是在MongoDB里面是一个个的集合,集合里面是一个个的文档。
在MySql里面的数据表中是一行一行的数据,但是在MongoDB里面的文档中是一个对象的集合,每个对象类似一行的数据。
MongoDB是以键值对的形式保存数据的。
## 3、MongoDB的安装
略。
在MongoDB的安装目录下的bin下有两个重要的程序。
`mongo.exe` 和 `mongod.exe`
其中`mongod.exe`是启动MongoDB的程序。程序启动后运行`mongo.exe` ,然后就可以在特定的MongoDB命令行中执行指令进行数据的增删改查。
MongoDB的启动指令:(E:\MongoDB\data 自己存放数据库的位置)
```js
.\mongod.exe --dbpath E:\MongoDB\data
// 然后运行
mongo.exe 就可以执行mongoDB的指令了。
```
## 4、MongoDB一些指令
### 4.1、常用指令
```js
show dbs // 查看已经存在的数据库
use 数据库名 //切换到指定的数据库(无论数据库是否存在 均可切换成功)
db // 查看当前所在的数据库
db.getCollectionNames() //查看当前数据库下一共有哪些文档集合
db.集合名.insert(文档) //向指定的集合录入一条文档(如果集合不存在会自动创建)
//例如: db.users.insert({user:"daotin",age:18})
db.集合名.insert([文档1,文档2]) // 向指定的集合插入多条文档
// 例如:db.users.insert([{user:"lvonve",age:10},{user:"wenran", age:20}])
// 插入多条数据或单条数据的其他写法
//db.集合名.insertMany([文档1,文档2]) 插入多条数据
//db.集合名.insertOne(文档) 插入单条数据
db.users.insert([
{username:"马云",age:58,height:167,friends:["马化腾","许家印","雷军","李彦宏","柳传志"]},
{username:"许家印",age:52,height:177,friends:["马化腾","雷军","柳传志"]},
{username:"雷军",age:48,height:174,friends:["马化腾","董明珠","柳传志"]},
{username:"雷德承",age:18,height:180,friends:["马化腾","王健林","柳传志"]},
{username:"王思聪",age:32,height:179,friends:["林更新","林缓存","陈赫","雷军"]}
])
```
### 4.2、查询语句
> 查询的方式都是以对象的形式查询的
```js
db.集合名.find() // 查询指定的集合内所有数据
//{ "_id" : ObjectId("5c18e0aef024bd18615cc516"), "user" : "daotin", "age" : 18 }
//{ "_id" : ObjectId("5c18e188dc1d4d80df2f4ae6"), "user" : "lvonve", "age" : 10 }
//{ "_id" : ObjectId("5c18e188dc1d4d80df2f4ae7"), "user" : "wenran", "age" : 20 }
// 查询指定字段
db.集合名.find({筛选条件},{显示字段})
// 显示字段
// 显示user字段,不显示_id字段
db.users.find({},{_id:0, user:1}) // 显示的字段值为1,不显示的字段值为0
// 筛选条件
//条件格式: 属性名:{条件操作符:值}
//条件操作符
// $gt : 大于
// $gte : 大于等于
// $lt : 小于
// $lte : 小于等于
// $in : 包含其中任意一个 注意 $in操作符的值必须为数组类型
// $all : 包含所有 值同上,必须为数组类型
// $nin : 不包含其中任意一个 值要求同上
// $ne : 不等于
// $not : 对已定义好的条件进行取反 {属性:{$not:{条件}}}
// $mod : 取模 (取余) $mod:[x,y] 取所有除x余y的值
db.users.find({age:{$gt:35}},{_id:0}) // 筛选条件为年龄大于35
db.users.find({friends:{$in:["林更新"]}},{_id:0}) // 筛选条件为friends字段有林更新的。
db.users.find({friends:{$in:["林更新","雷军"]}},{_id:0}) // 筛选条件为friends字段有林更新或者有雷军的。
db.users.find({friends:{$all:["马化腾","雷军"]}},{_id:0}) // 筛选条件为friends字段同时包含马化腾和雷军
db.users.find({friends:{$nin:["马化腾","雷军"]}},{_id:0}) // 筛选条件为friends字段不包含马化腾或者不包含雷军即可
db.users.find({age:18},{_id:0}) // 筛选条件为age为18的文档
db.users.find({age:{$ne:18}},{_id:0}) // 筛选条件为age不为18的文档
db.users.find({age:{$ne:18}},{_id:0}) // 筛选条件为age不为18的文档
db.users.find({age:{$not:{$gt:18}}},{_id:0}) // 筛选条件为年龄不大于18
db.users.find({age:{$mod:[3,0]}},{_id:0}) // 筛选条件为age/3余数为0的文档
// 模糊查询🎅🏼
// https://blog.csdn.net/comhaqs/article/details/23822479
1、db.goods.find({name:/joe/ig})
2、db.goods.find({name:{$regex:/joe/ig}})
3、db.goods.find({goodsName:{$regex: "joe", $options:"ig"}})
var reg = new RegExp("joe", "ig");
4、db.goods.find({name:reg})
5、db.goods.find({name:{$regex:reg}})
// 以上5种写法均可
```
**条件“且”和“或”**
```js
// 条件:且
db.users.find({条件1,条件2},{_id:0})
// db.users.find({age:{$gt:35},friends:{$in:["雷军"]}},{_id:0}) // 年龄大于35,并且friends中有雷军的
// 条件:或
db.users.find({$or:[{条件1},{条件2}]},{_id:0})
// db.users.find({$or:[{age:{$gt:35}},{friends:{$in:["雷军"]}}]},{_id:0}) // 年龄大于35,或者friends中有雷军的
// 条件:且和或都有
db.users.find({条件1,$or:[{条件2},{条件3}]},{_id:0}) // 满足条件1,并且满足条件2或者条件3中的一个
// db.users.find({age:{$gt:30},$or:[{height:{$lt:175}},{friends:{$in:["许家印"]}}]},{_id:0}) // 年龄大于30 ,并且身高小于175或者认识许家印
```
**其他条件操作**
```js
.limit(n) //取满足条件的头n条数据
.skip(n) //跳过n条数据再取数据
.count() //对满足条件的数据进行计数
.sort({第一排序条件,第二排序条件,.....}) //按照属性进行排序
.skip(m).limit(n) //跳过m条数据 再取头n条数据 (调用顺序没有讲究,但是作用效果均为先跳过数据再取数据)
//示例
db.users.find({},{_id:0}).limit(3) // 取users集合中所有文档的前3个
db.users.find({},{_id:0}).limit(3).skip(3) // 取users集合中敲过前三个后取目前文档的前3个
db.users.find({},{_id:0,age:1}).sort({age:1})// 按照年龄升序排列(正数为升序)
db.users.find({},{_id:0,age:1}).sort({age:-1})// 按照年龄降序排列(负数为升序)
db.users.find({},{_id:0,age:1,height:1}).sort({age:1,height:1})// 按照年龄升序排列,如果年龄相同,按照身高升序排列
db.users.find({age:{$gt:35}},{_id:0}).count((err,count)=>{console.log(count)}) // 统计年龄大于35岁的文档个数
// 设计翻页的时候,一般会这么用:
db.users.find().limit(y).skip((x-1)*y)
```
### 4.3、修改语句
> `db.集合名.update(query,{修改器:{属性:值}},option)`
> option 为可选参数, 为对象类型,其下有两个属性:
> `multi` : 布尔值,是否修改所有符合条件的数据,默认false
> `upsert` : 布尔值,当没有符合条件的数据时,是否创建该数据,默认false
```js
//修改器
// $set : 重新赋值
// $inc : 对值进行叠加(值为正)或递减(值为负) 适用于数字类型的值
// $unset : 删除整个属性(包括属性名及属性值)
//数组修改器
// $push : 给数组类型的值添加一个新元素
// $addToSet : 给数组类型的值添加一个新元素 (该方法不会重复添加已经存在的值,同时也不会影响原来已经存在的重复值)
// $pop : 从尾部删除一条数据 (值的大小不会对结果产生影响 永远只会操作一条数据) (值为正 从尾部删除一条数据 值为负 从头部删除一条数据)
// $pull : 按条件删除数组内元素 {$pull:{属性:值}} 删除指定值的元素
//示例:
db.users.update({username:"马云"},{$set:{age:55}}) // 设置马云文档的age为55
db.users.update({username:"马云"},{$inc:{age:2}})) // 设置马云的age在原来的基础上+2,如果是-2的话是减2
db.users.update({username:"马云"},{$unset:{age:1}}) // 删除马云的age属性,这里age设置的值可以任意。
db.users.update({username:"马云"},{$push:{friends:"Daotin"}}) // 给马云的friends属性的最后增加一个值“Daotin”
db.users.update({username:"马云"},{$pop:{friends:0}}) // 给马云的friends属性从最后删除一个值。这里指令friends的值可随意。
db.users.update({username:"王思聪"},{$pull:{friends:"林更新"}}) // 删除马云的friends属性中的林更新
```
> 注意:在默认情况下,修改操作只会操作第一条符合条件的数据。
### 4.4、删除语句
> `db.集合名.remove(query,option)`
> option:为可选参数,为对象类型,拥有属性
> `justOne`: 是否只删除第一条符合条件的数据,默认false
```js
//示例
db.users.remove({user:"lvonve"}) // 删除user属性值为lvonve的所有文档
```
> 注意:默认情况下 会删除所有符合条件的数据
| Daotin/Web/10-Node.js/04-MongoDB基本增删改查.md/0 | {
"file_path": "Daotin/Web/10-Node.js/04-MongoDB基本增删改查.md",
"repo_id": "Daotin",
"token_count": 5573
} | 25 |
## 项目github仓库
[vue-demo](https://github.com/Daotin/vue-demo)
## vue项目结构

## webpack+vue项目代码结构:

## 简要描述
main.js加载主组件App.js,App.js又是一个空的组件,里面主要放三部分:
Entry组件,Login组件,Register组件。
Entry组件下包括Home,List,Detail,ShoppingCar子组件,这些子组件有会包含Components文件夹下的更小的组件。
Login组件,显示登录界面。
Register组件,显示注册界面。
> Components文件夹下的小组件的数据都是父组件传入的。
| Daotin/Web/12-Vue/12-vue项目结构.md/0 | {
"file_path": "Daotin/Web/12-Vue/12-vue项目结构.md",
"repo_id": "Daotin",
"token_count": 380
} | 26 |
## 一、react内容插槽
定义一个slot组件,然后往这个组件中添加数据,父组件调用这个子组件:
```jsx
import { Slot } from './Slot';
ReactDOM.render(<Slot>我是插入的内容</Slot></Slot>, document.getElementById('app'));
```
slot组件:通过`this.props.children`获取插入的内容。
```jsx
export class Slot extends React.Component {
constructor() {
super();
}
render() {
return (
<div>{this.props.children}</div>
);
}
}
```
## 二、react的生命周期

react的生命周期大概分为:
加载期:
- 加载前:`componentWillMount`
- 加载后:`componentDidMount`
更新期:
- 接收props之前 `componentWillReceiveProps` (仅在props发生变化时触发,会先于shouldComponentUpdate 触发,当接收props参数的时候。)
- 允许更新 `shouldComponentUpdate` (以下在props和state发生变化时均会触发)
shouldComponentUpdate函数返回false表示阻止更新。
- 更新前 `componentWillUpdate`
- 更新后 `componentDidUpdate`
卸载期:
- 卸载前 `componentWillUnmount`
- (没有卸载后)
我觉得上图已经很清晰展示这些函数什么时候会被调用,当然还有个在线图表可以参考:http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
这些函数还有参数:
`shouldComponentUpdate(props,state)`: // props和state代表即将到来的值
`componentWillUpdate(props,state)`:// props和state代表即将到来的值
`componentDidUpdate(props,state)`:// props和state代表修改前的值
`componentWillReceiveProps(willProps)` // willProps代表即将到来的值 | Daotin/Web/13-React/03-react内容插槽,生命周期函数.md/0 | {
"file_path": "Daotin/Web/13-React/03-react内容插槽,生命周期函数.md",
"repo_id": "Daotin",
"token_count": 929
} | 27 |
## 一、组件相关知识
### 1、*ngIf
`*ngIf` 用来控制一个元素是否显示。
示例:
```typescript
// home.component.html
<button *ngIf="isShow">按钮</button>
// home.component.ts
isShow: boolean = false;
```
### 2、*ngFor
`*ngFor`用来循环遍历一个数组。
示例:
```typescript
// home.component.html
<ul>
<li *ngFor="let item of list;let i = index">{{i}}, {{item}}</li>
</ul>
// home.component.ts
list: Array<string> = [
'Daotin', 'lvonve', 'wenran'
];
```
> i是索引,item是list中的每一项。
## 二、事件绑定
```typescript
/* home.component.html */
<button (click)="add()">add</button>
<p>{{count}}</p>
/* home.component.ts */
count: number = 0;
add() {
this.count++;
}
```
> 注意:add后面一定要加`()`
## 三、数据双向绑定
```typescript
/* home.component.html */
<input type="text" [(ngModel)]="txt">
<p>{{txt}}</p>
/* home.component.ts */
txt: string = '';
```
## 四、管道(过滤器)
angular中的管道就类似于vue中的过滤器的概念。
首先看看angular内置的管道:
### 1、日期管道
```typescript
/* home.component.html */
<span>当前日期:{{time | date:"yyyy-MM-dd HH:mm:ss"}}</span>
/* home.component.ts */
time: any = new Date();
```
### 2、数字管道
```typescript
/* home.component.html */
<p>{{12345.12345 | number:"4.2-4"}}</p> // 12,345.1235
//4.2-4 表示:整数至少4位,小数至少2位最多4位
/* home.component.ts */
```
### 3、大小写管道
```typescript
/* home.component.html */
<p>{{"abcDEF" | uppercase}}</p>
<p>{{"abcDEF" | lowercase}}</p>
/* home.component.ts */
```
### 4、创建自定义管道
在pipes目录下创建才cny管道(用于转换一个数字为两位小数的价格)。
```c
ng g pipe pipes/cny // 简写ng g p pipes/cny
```
创建的管道如下:
```typescript
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
// 调用管道时的名称
name: 'cny'
})
export class CnyPipe implements PipeTransform {
/**
*
* @param value 管道之前的原始值
* @param args 管道之后的参数
*/
// transform(value: any, args?: any): any {
// return null;
// }
transform(value: number, tag: string = '¥', num: number = 2): any {
return tag + value.toFixed(num);
}
}
```
使用自定义的管道:
```typescript
/* home.component.html */
<p>{{12345.12345 | cny : "$" : 3}}</p> // $12345.123
```
| Daotin/Web/14-Angular/02-组件相关,事件绑定,数据双向绑定,管道.md/0 | {
"file_path": "Daotin/Web/14-Angular/02-组件相关,事件绑定,数据双向绑定,管道.md",
"repo_id": "Daotin",
"token_count": 1263
} | 28 |
/** 文章目录 */
INSERT INTO article_category(category_id, category_name, create_date, category_delete) VALUES (0, '所有文章', '2017-12-12 18:11:34', 0);
/** 博客demo */
INSERT INTO blog_details(blog_id, blog_title, blog_author, blog_date, blog_read, blog_summary, blog_html_content, blog_md_content, blog_label, blog_delete, blog_category) VALUES (1, '第一篇博客', 'husen', '2018-02-10 20:22:36', 0, '博客demo', '这是测试博客的第一篇文章', '这是测试博客的第一篇文章', '博客 测试', 0, 0);
/** 代码demo */
INSERT INTO code_library(code_id, code_title, code_author, code_date, code_read, code_summary, code_html_content, code_md_content, code_label, code_delete, code_category) VALUES (1, '第一篇代码', 'husen', '2018-02-10 20:25:38', 0, '代码demo', '这是测试代码的第一篇文章', '这是测试代码的第一篇文章', '代码 测试', 0, 0);
/** 版本特性 */
INSERT INTO release_feature(release_id, release_author, release_date, release_number, release_content) VALUES (0, '何明胜', '2017-09-30 16:20:29', 'V1.0.3', '<p>1、主页显示版本特性、最近更新及其他栏目导航</p>
<p>2、实现发表博客、查看博客、浏览量统计、选择每页显示的博客数量等</p>
<p>3、实现上传代码至代码库、查看代码组件、浏览量统计、分页显示等</p>
<p>4、实现留言、回复留言、分页浏览功能</p>
<p>5、实现下载、下载统计、联系站长发送邮件等基本功能</p>
<p>6、实现登录注册功能、网站单日访问量与总访问量统计、实现在线人数统计</p>');
/** 用户信息 初始密码均为123123 */
INSERT INTO user_info(user_id, user_name, user_password, user_email, user_phone, user_age, user_sex, user_address, user_head_url, user_nick_name) VALUES (0, 'husen', 'cf5fe8a4669d7300ddac03170796e012', 'husen@hemingsheng.cn', NULL, NULL, NULL, NULL, NULL, '何明胜');
INSERT INTO user_info(user_id, user_name, user_password, user_email, user_phone, user_age, user_sex, user_address, user_head_url, user_nick_name) VALUES (1, 'super_admin', '2f0b3214c90231b9ad9f341bf1df8035', 'he_mingsheng@qq.com', NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO user_info(user_id, user_name, user_password, user_email, user_phone, user_age, user_sex, user_address, user_head_url, user_nick_name) VALUES (2, 'admin', 'c19380b712c30d00881bc9cfb3c74050', '940706904@qq.com', NULL, NULL, NULL, NULL, NULL, NULL);
/** 网站访问统计 */
INSERT INTO visit_total(visit_id, visit_date, visit_count) VALUES (0, '2017-09-29', 0); | Humsen/web/docs/数据库部署/第2步 - 初始化数据.sql/0 | {
"file_path": "Humsen/web/docs/数据库部署/第2步 - 初始化数据.sql",
"repo_id": "Humsen",
"token_count": 1289
} | 29 |
/**
* vo是view 展示层
*
* @author 何明胜
*
* 2017年10月18日
*/
package pers.husen.web.bean.vo; | Humsen/web/web-core/src/pers/husen/web/bean/vo/package-info.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/bean/vo/package-info.java",
"repo_id": "Humsen",
"token_count": 56
} | 30 |
package pers.husen.web.common.helper;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* 返回程序调用的堆栈轨迹
*
* @author 何明胜
*
* 2017年10月22日
*/
public class StackTrace2Str {
/**
* 返回 e.printStackTrace()的内容
* @param e
* @return
*/
public static String exceptionStackTrace2Str (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
// 将出错的栈信息输出到printWriter中
e.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
}
} | Humsen/web/web-core/src/pers/husen/web/common/helper/StackTrace2Str.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/common/helper/StackTrace2Str.java",
"repo_id": "Humsen",
"token_count": 249
} | 31 |
package pers.husen.web.dao;
import pers.husen.web.bean.vo.ReleaseFeatureVo;
/**
* 新版本特性接口
*
* @author 何明胜
*
* 2017年10月17日
*/
public interface ReleaseFeatureDao {
/**
* 插入新的版本特性
*
* @param releaseFeatureVo
* @return
*/
public int insertReleaseFeature(ReleaseFeatureVo releaseFeatureVo);
/**
* 查询最新的版本特性
*
* @return
*/
public ReleaseFeatureVo queryLatestReleaseFeature();
/**
* 根据id查询版本
* @param releaseId
* @return
*/
public ReleaseFeatureVo queryReleaseById(int releaseId);
/**
* 根据id修改版本信息
* @param rVo
* @return
*/
public int updateReleaseContentById(ReleaseFeatureVo rVo);
} | Humsen/web/web-core/src/pers/husen/web/dao/ReleaseFeatureDao.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dao/ReleaseFeatureDao.java",
"repo_id": "Humsen",
"token_count": 301
} | 32 |
package pers.husen.web.dbutil.assist;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
/**
* 博客文章工具类
*
* @author 何明胜
*
* 2017年9月21日
*/
public class TypeTransformUtils {
/**
* ResultSET -> beanList
*
* @param rs
* @param classType
* @return
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
* @throws InstantiationException
* @throws SecurityException
* @throws NoSuchMethodException
*/
public static <T> ArrayList<T> resultSet2BeanList(ResultSet rs, Class<T> classType)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException,
InstantiationException, SecurityException, NoSuchMethodException {
ArrayList<T> arrayList = new ArrayList<T>();
// 获取列的数量、类型和属性
ResultSetMetaData metaData = rs.getMetaData();
// 获取总列数
int count = metaData.getColumnCount();
while (rs.next()) {
T newInstance = classType.newInstance();
for (int i = 1; i <= count; i++) {
// 获取字段名
String fieldName = metaData.getColumnName(i).toLowerCase();
// 转换为驼峰形式
fieldName = underline2Camel(fieldName);
// 获取字段类型
Class<?> type = getDeclaredField(classType, fieldName);
// 拼接set函数名称
String firstChar = fieldName.substring(0, 1);
String pascalName = fieldName.replaceFirst(firstChar, firstChar.toUpperCase());
Method method = classType.getMethod("set" + pascalName, type);
// 判断读取数据的类型
if (type.equals(String.class)) {
method.invoke(newInstance, rs.getString(i));
} else if (type.equals(int.class) || type.equals(Integer.class)) {
method.invoke(newInstance, rs.getInt(i));
} else if (type.equals(Date.class)) {
// java.sql.Date -> java.util.Date
Date date = new Date(rs.getTimestamp(i).getTime());
method.invoke(newInstance, date);
} else if (type.equals(Boolean.class) || type.equals(boolean.class)) {
method.invoke(newInstance, rs.getBoolean(i));
}
}
arrayList.add(newInstance);
}
return arrayList;
}
/**
* ResultSET -> bean
*/
public static <T> T resultSet2Bean(ResultSet rs, Class<T> classType)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException,
InstantiationException, NoSuchFieldException, SecurityException, NoSuchMethodException {
T tVo = classType.newInstance();
// 获取列的数量、类型和属性
ResultSetMetaData metaData = rs.getMetaData();
// 获取总列数
int count = metaData.getColumnCount();
if (rs.next()) {
for (int i = 1; i <= count; i++) {
// 获取字段名
String fieldName = metaData.getColumnName(i).toLowerCase();
// 转换为驼峰形式
fieldName = underline2Camel(fieldName);
// 获取字段类型
Class<?> type = getDeclaredField(classType, fieldName);
// 拼接set函数名称
String firstChar = fieldName.substring(0, 1);
String pascalName = fieldName.replaceFirst(firstChar, firstChar.toUpperCase());
Method method = classType.getMethod("set" + pascalName, type);
// 判断读取数据的类型
if (type.equals(String.class)) {
method.invoke(tVo, rs.getString(i));
} else if (type.equals(int.class) || type.equals(Integer.class)) {
method.invoke(tVo, rs.getInt(i));
} else if (type.equals(Date.class)) {
// java.sql.Date -> java.util.Date
Date date = new Date(rs.getTimestamp(i).getTime());
method.invoke(tVo, date);
} else if (type.equals(Boolean.class) || type.equals(boolean.class)) {
method.invoke(tVo, rs.getBoolean(i));
}
}
}
return tVo;
}
/**
* 数据库字段下划线格式转javaBean驼峰格式
*
* @param underLine
* @return
*/
public static String underline2Camel(String underLine) {
String[] words = underLine.split("_");
StringBuilder builder = new StringBuilder();
// 拼接第一个字符
builder.append(words[0]);
// 如果数组不止一个单词
if (words.length > 1) {
for (int i = 1; i < words.length; i++) {
// 去掉下划线,首字母变为大写
String string = words[i];
String substring = string.substring(0, 1);
words[i] = string.replaceFirst(substring, substring.toUpperCase());
builder.append(words[i]);
}
}
return builder.toString();
}
/**
* 根据字段名称获取当前类及其父类中的变量
* @param <T>
* @param methodName
* @return
*/
public static <T> Class<?> getDeclaredField(Class<T> currClass, String methodName) {
Class<?> fieldClass = null;
for (Class<?> clazz = currClass; clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
fieldClass = clazz.getDeclaredField(methodName).getType();
return fieldClass;
} catch (Exception e) {
// 这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
// 如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
}
}
return null;
}
} | Humsen/web/web-core/src/pers/husen/web/dbutil/assist/TypeTransformUtils.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dbutil/assist/TypeTransformUtils.java",
"repo_id": "Humsen",
"token_count": 2316
} | 33 |
package pers.husen.web.service;
import java.util.ArrayList;
import pers.husen.web.bean.vo.FileDownloadVo;
import pers.husen.web.dao.FileDownloadDao;
import pers.husen.web.dao.impl.FileDownloadDaoImpl;
/**
* @author 何明胜
*
* 2017年9月29日
*/
public class FileDownloadSvc implements FileDownloadDao{
private static final FileDownloadDaoImpl fileDownloadDaoImpl = new FileDownloadDaoImpl();
@Override
public int queryFileTotalCount() {
return fileDownloadDaoImpl.queryFileTotalCount();
}
@Override
public ArrayList<FileDownloadVo> queryFileDownlaodPerPage(int pageSize, int pageNo) {
return fileDownloadDaoImpl.queryFileDownlaodPerPage(pageSize, pageNo);
}
@Override
public FileDownloadVo queryPerFileById(int fileId) {
return fileDownloadDaoImpl.queryPerFileById(fileId);
}
@Override
public int insertFileDownload(FileDownloadVo fVo) {
return fileDownloadDaoImpl.insertFileDownload(fVo);
}
@Override
public int updateFileDownCountByUrl(String fileUrl) {
return fileDownloadDaoImpl.updateFileDownCountByUrl(fileUrl);
}
} | Humsen/web/web-core/src/pers/husen/web/service/FileDownloadSvc.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/service/FileDownloadSvc.java",
"repo_id": "Humsen",
"token_count": 365
} | 34 |
package pers.husen.web.servlet.download;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import pers.husen.web.bean.vo.FileDownloadVo;
import pers.husen.web.common.constants.RequestConstants;
import pers.husen.web.common.handler.FileDownloadHandler;
import pers.husen.web.service.FileDownloadSvc;
/**
* 下载文件
*
* @author 何明胜
*
* 2017年10月20日
*/
@WebServlet(urlPatterns = "/file/download.hms")
public class FileDownloadSvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileDownloadSvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=UTF-8");
// 如果是请求下载文件
String filename = request.getParameter("filename");
if (filename != null) {
FileDownloadHandler fileDownloadHandler = new FileDownloadHandler();
fileDownloadHandler.fileDownloadHandler(request, response);
return;
}
PrintWriter out = response.getWriter();
String requestType = request.getParameter("type");
//如果是查询所有文件的数量
String queryTotalCount = RequestConstants.REQUEST_TYPE_QUERY + RequestConstants.MODE_TOTAL_NUM;
if(queryTotalCount.equals(requestType)) {
FileDownloadSvc fSvc = new FileDownloadSvc();
int count = fSvc.queryFileTotalCount();
out.println(count);
return;
}
//如果是查询某一页的文件
String queryOnePage = RequestConstants.REQUEST_TYPE_QUERY + RequestConstants.MODE_ONE_PAGE;
if(queryOnePage.equals(requestType)) {
int pageSize = Integer.parseInt(request.getParameter("pageSize"));
int pageNo = Integer.parseInt(request.getParameter("pageNo"));
FileDownloadSvc fSvc = new FileDownloadSvc();
ArrayList<FileDownloadVo> fVos = fSvc.queryFileDownlaodPerPage(pageSize, pageNo);
String json =JSONArray.fromObject(fVos).toString();
out.println(json);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/download/FileDownloadSvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/download/FileDownloadSvt.java",
"repo_id": "Humsen",
"token_count": 898
} | 35 |
package pers.husen.web.servlet.userinfo;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import pers.husen.web.bean.vo.UserInfoVo;
import pers.husen.web.service.UserInfoSvc;
/**
* @desc 查询所有用户
*
* @author 何明胜
*
* @created 2017年12月26日 下午2:58:15
*/
@WebServlet(urlPatterns = "/users/query.hms")
public class UsersQuerySvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public UsersQuerySvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=UTF-8");
Integer draw = Integer.parseInt(request.getParameter("draw"));
Integer start = Integer.parseInt(request.getParameter("start"));
Integer length = Integer.parseInt(request.getParameter("length"));
PrintWriter out = response.getWriter();
UserInfoVo uVo = new UserInfoVo();
UserInfoSvc uSvc = new UserInfoSvc();
Integer recordsTotal = uSvc.queryUserTotalCount(uVo);
ArrayList<UserInfoVo> uVos = uSvc.queryUserPerPage(uVo, length, start);
String json = JSONArray.fromObject(uVos).toString();
JSONObject jsonObject = new JSONObject();
jsonObject.put("draw", draw);
jsonObject.put("recordsTotal", recordsTotal);
jsonObject.put("recordsFiltered", recordsTotal);
jsonObject.element("data", json);
out.println(jsonObject);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/userinfo/UsersQuerySvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/userinfo/UsersQuerySvt.java",
"repo_id": "Humsen",
"token_count": 703
} | 36 |
@charset "UTF-8";
.footer-div {
margin-top: 20px;
}
.husen-name {
font-family: FZShuTi, LiSu, STCaiyun;
}
.web-pc-nav{
text-align: center;
margin-top: 30px;
}
/* #fh5co-main-menu a {
font-family: "Arial","Microsoft YaHei","黑体","宋体",sans-serif !important;
font-size: 20px !important;
} */ | Humsen/web/web-mobile/WebContent/css/navigation/left-menu-bar.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/css/navigation/left-menu-bar.css",
"repo_id": "Humsen",
"token_count": 148
} | 37 |
/**
* 网站顶部导航栏
*
* @author 何明胜
*
* 2017年10月18日
*/
$(document).ready(function(){
loadAccessStatistics();
//绑定切换主题事件
$('.choose-theme').children('button').click(nextThemeClick);
});
/**
* 加载当前网站访问统计
*
* @returns
*/
function loadAccessStatistics(){
$.ajax({
type : 'POST',
url : '/accessAtatistics.hms',
success : function(response, ststus){
var response = JSON.parse(response);
$('#accessToday').html('今日访问量:' + response.accessToday);
$('#accessTotal').html(', 总访问量:' + response.accessTotal);
$('#onlineCurrent').html('当前在线人数:' + response.onlineCurrent);
},
error : function(XMLHttpRequest, textStatus){
$.confirm({
title: '网站访问统计加载出错',
content: textStatus + ' : ' + XMLHttpRequest.status,
autoClose: 'ok|2000',
type: 'red',
buttons: {
ok: {
text: '确认',
btnClass: 'btn-primary',
},
}
});
}
});
}
/**
* 点击加载下一个主题
*
* @returns
*/
function nextThemeClick(){
var curr_theme_no = 0;
if(typeof $.cookie('theme_no') == 'undefined'){
$.cookie('theme_no', 0);
}else{
curr_theme_no = Number($.cookie('theme_no'));
$.cookie('theme_no', curr_theme_no+1);
}
curr_theme_no = (curr_theme_no+1)%5;
var img = '/images/background/bg-' + curr_theme_no + '.jpg';
$('body').css('background-image','url(' + img + ')');
} | Humsen/web/web-mobile/WebContent/js/navigation/topbar.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/js/navigation/topbar.js",
"repo_id": "Humsen",
"token_count": 735
} | 38 |
/*
* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*
* Uses the built in easing capabilities added In jQuery 1.1
* to offer multiple easing options
*
* TERMS OF USE - jQuery Easing
*
* Open source under the BSD License.
*
* Copyright © 2008 George McGinley Smith
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing,
{
def: 'easeOutQuad',
swing: function (x, t, b, c, d) {
//alert(jQuery.easing.default);
return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
},
easeInQuad: function (x, t, b, c, d) {
return c*(t/=d)*t + b;
},
easeOutQuad: function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
easeInOutQuad: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
easeInCubic: function (x, t, b, c, d) {
return c*(t/=d)*t*t + b;
},
easeOutCubic: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
},
easeInQuart: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
easeOutQuart: function (x, t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
easeInOutQuart: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInQuint: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t*t + b;
},
easeOutQuint: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
},
easeInOutQuint: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
},
easeInSine: function (x, t, b, c, d) {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
},
easeOutSine: function (x, t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeInOutSine: function (x, t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeInExpo: function (x, t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
easeOutExpo: function (x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
easeInOutExpo: function (x, t, b, c, d) {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
easeInCirc: function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
easeOutCirc: function (x, t, b, c, d) {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
easeInOutCirc: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
easeInElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
easeOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
easeInOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
easeInBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
easeInBounce: function (x, t, b, c, d) {
return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
},
easeOutBounce: function (x, t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
easeInOutBounce: function (x, t, b, c, d) {
if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
}
});
/*
*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright © 2001 Robert Penner
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/ | Humsen/web/web-mobile/WebContent/plugins/jquery/js/jquery.easing.1.3.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/jquery/js/jquery.easing.1.3.js",
"repo_id": "Humsen",
"token_count": 3613
} | 39 |
[flake8]
max-line-length = 88
max-complexity = 16
# B = bugbear
# B9 = bugbear opinionated (incl line length)
select = C,E,F,W,B,B9
# E203: whitespace before ':' (black behaviour)
# E501: flake8 line length (covered by bugbear B950)
# W503: line break before binary operator (black behaviour)
ignore = E203,E501,W503
per-file-ignores=
__init__.py:F401
| OCA/web/.flake8/0 | {
"file_path": "OCA/web/.flake8",
"repo_id": "OCA",
"token_count": 133
} | 40 |
exclude: |
(?x)
# NOT INSTALLABLE ADDONS
# END NOT INSTALLABLE ADDONS
# Files and folders generated by bots, to avoid loops
^setup/|/static/description/index\.html$|
# We don't want to mess with tool-generated files
.svg$|/tests/([^/]+/)?cassettes/|^.copier-answers.yml$|^.github/|
# Maybe reactivate this when all README files include prettier ignore tags?
^README\.md$|
# Library files can have extraneous formatting (even minimized)
/static/(src/)?lib/|
# Repos using Sphinx to generate docs don't need prettying
^docs/_templates/.*\.html$|
# Don't bother non-technical authors with formatting issues in docs
readme/.*\.(rst|md)$|
# You don't usually want a bot to modify your legal texts
(LICENSE.*|COPYING.*)
default_language_version:
python: python3
node: "16.17.0"
repos:
- repo: local
hooks:
# These files are most likely copier diff rejection junks; if found,
# review them manually, fix the problem (if needed) and remove them
- id: forbidden-files
name: forbidden files
entry: found forbidden files; remove them
language: fail
files: "\\.rej$"
- id: en-po-files
name: en.po files cannot exist
entry: found a en.po file
language: fail
files: '[a-zA-Z0-9_]*/i18n/en\.po$'
- repo: https://github.com/oca/maintainer-tools
rev: 969238e47c07d0c40573acff81d170f63245d738
hooks:
# update the NOT INSTALLABLE ADDONS section above
- id: oca-update-pre-commit-excluded-addons
- id: oca-fix-manifest-website
args: ["https://github.com/OCA/web"]
- id: oca-gen-addon-readme
args:
- --addons-dir=.
- --branch=16.0
- --org-name=OCA
- --repo-name=web
- --if-source-changed
- repo: https://github.com/OCA/odoo-pre-commit-hooks
rev: v0.0.25
hooks:
- id: oca-checks-odoo-module
- id: oca-checks-po
- repo: https://github.com/myint/autoflake
rev: v1.6.1
hooks:
- id: autoflake
args:
- --expand-star-imports
- --ignore-init-module-imports
- --in-place
- --remove-all-unused-imports
- --remove-duplicate-keys
- --remove-unused-variables
- repo: https://github.com/psf/black
rev: 22.8.0
hooks:
- id: black
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.7.1
hooks:
- id: prettier
name: prettier (with plugin-xml)
additional_dependencies:
- "prettier@2.7.1"
- "@prettier/plugin-xml@2.2.0"
args:
- --plugin=@prettier/plugin-xml
files: \.(css|htm|html|js|json|jsx|less|md|scss|toml|ts|xml|yaml|yml)$
- repo: https://github.com/pre-commit/mirrors-eslint
rev: v8.24.0
hooks:
- id: eslint
verbose: true
args:
- --color
- --fix
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
hooks:
- id: trailing-whitespace
# exclude autogenerated files
exclude: /README\.rst$|\.pot?$
- id: end-of-file-fixer
# exclude autogenerated files
exclude: /README\.rst$|\.pot?$
- id: debug-statements
- id: fix-encoding-pragma
args: ["--remove"]
- id: check-case-conflict
- id: check-docstring-first
- id: check-executables-have-shebangs
- id: check-merge-conflict
# exclude files where underlines are not distinguishable from merge conflicts
exclude: /README\.rst$|^docs/.*\.rst$
- id: check-symlinks
- id: check-xml
- id: mixed-line-ending
args: ["--fix=lf"]
- repo: https://github.com/asottile/pyupgrade
rev: v2.38.2
hooks:
- id: pyupgrade
args: ["--keep-percent-format"]
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
name: isort except __init__.py
args:
- --settings=.
exclude: /__init__\.py$
- repo: https://github.com/acsone/setuptools-odoo
rev: 3.1.8
hooks:
- id: setuptools-odoo-make-default
- id: setuptools-odoo-get-requirements
args:
- --output
- requirements.txt
- --header
- "# generated from manifests external_dependencies"
- repo: https://github.com/PyCQA/flake8
rev: 3.9.2
hooks:
- id: flake8
name: flake8
additional_dependencies: ["flake8-bugbear==21.9.2"]
- repo: https://github.com/OCA/pylint-odoo
rev: v8.0.19
hooks:
- id: pylint_odoo
name: pylint with optional checks
args:
- --rcfile=.pylintrc
- --exit-zero
verbose: true
- id: pylint_odoo
args:
- --rcfile=.pylintrc-mandatory
| OCA/web/.pre-commit-config.yaml/0 | {
"file_path": "OCA/web/.pre-commit-config.yaml",
"repo_id": "OCA",
"token_count": 2267
} | 41 |
========================
web_action_conditionable
========================
..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:4bc330cf2cd18ff1c39c729eeae66a68dde8f3252b6825de70919e0f45dcc9fc
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fweb-lightgray.png?logo=github
:target: https://github.com/OCA/web/tree/16.0/web_action_conditionable
:alt: OCA/web
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/web-16-0/web-16-0-web_action_conditionable
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
:target: https://runboat.odoo-community.org/builds?repo=OCA/web&target_branch=16.0
:alt: Try me on Runboat
|badge1| |badge2| |badge3| |badge4| |badge5|
Add support for conditions on create and delete actions on One2Many fields.
**Table of contents**
.. contents::
:local:
Usage
=====
Odoo by default support:
::
<tree delete="false" create="false">
with this module you can:
::
<tree delete="state=='draft'" create="state!='sent'">
It works in any tree view, so you can use it in One2many.
Bug Tracker
===========
Bugs are tracked on `GitHub Issues <https://github.com/OCA/web/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us to smash it by providing a detailed and welcomed
`feedback <https://github.com/OCA/web/issues/new?body=module:%20web_action_conditionable%0Aversion:%2016.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
Do not contact contributors directly about support or help with technical issues.
Credits
=======
Authors
~~~~~~~
* Cristian Salamea
Contributors
~~~~~~~~~~~~
* Cristian Salamea <cristian.salamea@gmail.com>
* André Paramés <github@andreparames.com> (https://www.acsone.eu/)
* Alexandre Díaz <alexandre.diaz@tecnativa.com>
* Sudhir Arya <sudhir@erpharbor.com>
* Jasper Jumelet <jasper.jumelet@codeforward.nl>
* `Trobz <https://trobz.com>`_:
* Nguyễn Minh Chiến <chien@trobz.com>
Other credits
~~~~~~~~~~~~~
The migration of this module from 15.0 to 16.0 was financially supported by Camptocamp
Maintainers
~~~~~~~~~~~
This module is maintained by the OCA.
.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
This module is part of the `OCA/web <https://github.com/OCA/web/tree/16.0/web_action_conditionable>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
| OCA/web/web_action_conditionable/README.rst/0 | {
"file_path": "OCA/web/web_action_conditionable/README.rst",
"repo_id": "OCA",
"token_count": 1240
} | 42 |
More powerful and easy to use search, especially for related fields.
| OCA/web/web_advanced_search/readme/DESCRIPTION.rst/0 | {
"file_path": "OCA/web/web_advanced_search/readme/DESCRIPTION.rst",
"repo_id": "OCA",
"token_count": 14
} | 43 |
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Copyright 2017-2018 Jairo Llopis <jairo.llopis@tecnativa.com>
Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
-->
<templates>
<t t-inherit="web.CustomFilterItem" t-inherit-mode="extension" owl="1">
<xpath expr="//select[@t-elif]" position="after">
<t
t-elif="['many2one', 'many2many', 'one2many'].includes(fieldType) and ['=', '!='].includes(selectedOperator.symbol)"
>
<RecordPicker
model="fields[condition.field].relation"
string="fields[condition.field].string"
context="fields[condition.field].context"
t-on-change="(ev) => this.onRelationalChanged(condition,ev)"
/>
</t>
</xpath>
</t>
</templates>
| OCA/web/web_advanced_search/static/src/search/filter_menu/custom_filter_item.xml/0 | {
"file_path": "OCA/web/web_advanced_search/static/src/search/filter_menu/custom_filter_item.xml",
"repo_id": "OCA",
"token_count": 456
} | 44 |
To use this module, you need to install some other addon that uses it, as it
doesn't provide any end-user functionality.
| OCA/web/web_calendar_slot_duration/readme/USAGE.rst/0 | {
"file_path": "OCA/web/web_calendar_slot_duration/readme/USAGE.rst",
"repo_id": "OCA",
"token_count": 29
} | 45 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_chatter_position
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2023-03-06 20:08+0000\n"
"Last-Translator: Ediz Duman <neps1192@gmail.com>\n"
"Language-Team: none\n"
"Language: tr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 4.14.1\n"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__bottom
msgid "Bottom"
msgstr "Alt"
#. module: web_chatter_position
#: model:ir.model.fields,field_description:web_chatter_position.field_res_users__chatter_position
msgid "Chatter Position"
msgstr "Sohbet Pozisyonu"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__auto
msgid "Responsive"
msgstr "Esnek"
#. module: web_chatter_position
#: model:ir.model.fields.selection,name:web_chatter_position.selection__res_users__chatter_position__sided
msgid "Sided"
msgstr ""
#. module: web_chatter_position
#: model:ir.model,name:web_chatter_position.model_res_users
msgid "User"
msgstr "Kullanıcı"
| OCA/web/web_chatter_position/i18n/tr.po/0 | {
"file_path": "OCA/web/web_chatter_position/i18n/tr.po",
"repo_id": "OCA",
"token_count": 518
} | 46 |
White color is omitted in the addition operation to support images without alpha channel.
| OCA/web/web_company_color/readme/ROADMAP.rst/0 | {
"file_path": "OCA/web/web_company_color/readme/ROADMAP.rst",
"repo_id": "OCA",
"token_count": 16
} | 47 |
This module will show a confirmation dialog when the user selects the
`Duplicate` option from the `Action` dropdown in the standard form view.
| OCA/web/web_copy_confirm/readme/DESCRIPTION.rst/0 | {
"file_path": "OCA/web/web_copy_confirm/readme/DESCRIPTION.rst",
"repo_id": "OCA",
"token_count": 33
} | 48 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_dark_mode
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: Automatically generated\n"
"Language-Team: none\n"
"Language: zh\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=1; plural=0;\n"
#. module: web_dark_mode
#. odoo-javascript
#: code:addons/web_dark_mode/static/src/js/switch_item.esm.js:0
#: model:ir.model.fields,field_description:web_dark_mode.field_res_users__dark_mode
#, python-format
msgid "Dark Mode"
msgstr ""
#. module: web_dark_mode
#: model:ir.model.fields,field_description:web_dark_mode.field_res_users__dark_mode_device_dependent
msgid "Device Dependent Dark Mode"
msgstr ""
#. module: web_dark_mode
#: model:ir.model,name:web_dark_mode.model_ir_http
msgid "HTTP Routing"
msgstr ""
#. module: web_dark_mode
#: model:ir.model,name:web_dark_mode.model_res_users
msgid "User"
msgstr ""
| OCA/web/web_dark_mode/i18n/zh.po/0 | {
"file_path": "OCA/web/web_dark_mode/i18n/zh.po",
"repo_id": "OCA",
"token_count": 410
} | 49 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.