text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M2 4c0-.552.455-1 .992-1h18.016c.548 0 .992.445.992 1v14c0 .552-.455 1-.992 1H2.992A.994.994 0 0 1 2 18V4zm3 16h14v2H5v-2z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/tv-2-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/tv-2-fill.svg",
"repo_id": "owncloud",
"token_count": 160
} | 750 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M8 3v9a4 4 0 1 0 8 0V3h2v9a6 6 0 1 1-12 0V3h2zM4 20h16v2H4v-2z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/underline.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/underline.svg",
"repo_id": "owncloud",
"token_count": 134
} | 751 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M4 22a8 8 0 1 1 16 0H4zm9-5.917V20h4.659A6.009 6.009 0 0 0 13 16.083zM11 20v-3.917A6.009 6.009 0 0 0 6.341 20H11zm1-7c-3.315 0-6-2.685-6-6s2.685-6 6-6 6 2.685 6 6-2.685 6-6 6zm0-2c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/user-2-line.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/user-2-line.svg",
"repo_id": "owncloud",
"token_count": 243
} | 752 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M4 22a8 8 0 1 1 16 0h-2a6 6 0 1 0-12 0H4zm8-9c-3.315 0-6-2.685-6-6s2.685-6 6-6 6 2.685 6 6-2.685 6-6 6zm0-2c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/user-line.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/user-line.svg",
"repo_id": "owncloud",
"token_count": 201
} | 753 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M21.543 6.498C22 8.28 22 12 22 12s0 3.72-.457 5.502c-.254.985-.997 1.76-1.938 2.022C17.896 20 12 20 12 20s-5.893 0-7.605-.476c-.945-.266-1.687-1.04-1.938-2.022C2 15.72 2 12 2 12s0-3.72.457-5.502c.254-.985.997-1.76 1.938-2.022C6.107 4 12 4 12 4s5.896 0 7.605.476c.945.266 1.687 1.04 1.938 2.022zM10 15.5l6-3.5-6-3.5v7z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/youtube-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/youtube-fill.svg",
"repo_id": "owncloud",
"token_count": 276
} | 754 |
import { shallowMount } from 'web-test-helpers'
import Count from './OcAvatarCount.vue'
describe('OcAvatarCount', () => {
it('dynamically calculates font size', () => {
const wrapper = shallowMount(Count, {
props: {
size: 100,
count: 2
}
})
expect((wrapper.element as HTMLElement).style.fontSize).toMatch('40px')
expect(wrapper.html()).toMatchSnapshot()
})
})
| owncloud/web/packages/design-system/src/components/OcAvatarCount/OcAvatarCount.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcAvatarCount/OcAvatarCount.spec.ts",
"repo_id": "owncloud",
"token_count": 162
} | 755 |
import { defaultPlugins, shallowMount } from 'web-test-helpers/src'
import OcButton from './OcButton.vue'
describe('OcButton', () => {
it('should display slot html', () => {
const wrapper = getWrapperWithTestSlot()
const slot = wrapper.find('p')
expect(slot).toBeTruthy()
expect(slot.attributes('class')).toBe('text')
expect(slot.text()).toBe('Test button')
})
describe('click event', () => {
it('should emit click event when click is triggered', async () => {
const wrapper = getWrapperWithProps({})
await wrapper.trigger('click')
expect(wrapper.emitted('click')).toBeTruthy()
})
it.each`
type
${'a'}
${'router-link'}
`('should not emit click event when type is $type', async ({ type }) => {
const wrapper = getWrapperWithProps({ type: type })
await wrapper.trigger('click')
expect(wrapper.emitted('click')).toBeFalsy()
})
})
describe('when oc button is disabled', () => {
let wrapper
beforeEach(() => {
wrapper = getWrapperWithProps({ disabled: true })
})
it('should have disabled attribute set to disabled', () => {
// disabled: true => '' disabled: false => undefined ¯\_(ツ)_/¯
expect(wrapper.attributes('disabled')).toBe('')
})
it('should not emit click event', async () => {
await wrapper.trigger('click')
expect(wrapper.emitted('click')).toBeFalsy()
})
})
describe('different types of button', () => {
it.each`
type | expectLink | expectButton | expectRouterLink
${'a'} | ${true} | ${false} | ${false}
${'button'} | ${false} | ${true} | ${false}
${'router-link'} | ${false} | ${false} | ${true}
`('can behave as a $type', ({ type, expectLink, expectButton, expectRouterLink }) => {
const wrapper = getWrapperWithProps({ type: type })
expect(wrapper.find('a').exists()).toBe(expectLink)
expect(wrapper.find('button').exists()).toBe(expectButton)
expect(wrapper.find('router-link-stub').exists()).toBe(expectRouterLink)
})
})
describe('different sizes of button', () => {
it.each`
size | expectedClass
${'small'} | ${'oc-button-s'}
${'medium'} | ${'oc-button-m'}
${'large'} | ${'oc-button-l'}
${'x-small'} | ${'oc-button-undefined'}
`(
'when size prop is set as $size class $expectedClass should be assigned',
({ size, expectedClass }) => {
const wrapper = getWrapperWithProps({
size: size
})
expect(wrapper.attributes('class')).toContain(expectedClass)
}
)
})
describe('default prop values', () => {
it.each`
name | expected
${'size'} | ${'oc-button-m'}
${'variation'} | ${'oc-button-passive'}
${'justify content'} | ${'oc-button-justify-content-center'}
${'gap size'} | ${'oc-button-gap-m'}
${'appearance'} | ${'oc-button-passive-outline'}
`('should have attribute "$name" as "$expected"', ({ expected }) => {
const wrapper = getWrapperWithProps({})
expect(wrapper.attributes('class')).toContain(expected)
})
})
describe('invalid prop value', () => {
it.each(['appearance', 'size', 'submit', 'justifyContent', 'variation', 'gapSize', 'type'])(
'when prop "%s" is set to an invalid value"',
(prop) => {
expect(OcButton.props[prop].validator('not-valid')).toBeFalsy()
}
)
})
describe('oc button appearance', () => {
// appearance prop is combined with variation prop
describe('when appearance is "filled"', () => {
it('should not have extra appearance class', () => {
const wrapper = getWrapperWithProps({
appearance: 'filled'
})
expect(wrapper.attributes('class')).toContain('oc-button-passive')
expect(wrapper.attributes('class')).not.toContain('oc-button-passive-raw')
expect(wrapper.attributes('class')).not.toContain('oc-button-passive-outline')
})
})
describe('when oc button is initialized with variation and appearance', () => {
it.each`
variation | appearance | expectedClass
${'success'} | ${'raw'} | ${'oc-button-success oc-button-success-raw'}
${'success'} | ${'outline'} | ${'oc-button-success oc-button-success-outline'}
${'primary'} | ${'raw'} | ${'oc-button-primary oc-button-primary-raw'}
${'primary'} | ${'outline'} | ${'oc-button-primary-outline'}
`('should have extra appearance class', ({ variation, appearance, expectedClass }) => {
const wrapper = getWrapperWithProps({
appearance: appearance,
variation: variation
})
expect(wrapper.attributes('class')).toContain(expectedClass)
})
})
})
})
function getWrapperWithProps(props) {
return shallowMount(OcButton, { props, global: { plugins: [...defaultPlugins()] } })
}
function getWrapperWithTestSlot() {
const testSlots = { default: '<p class="text">Test button</p>' }
return shallowMount(OcButton, { slots: testSlots, global: { plugins: [...defaultPlugins()] } })
}
| owncloud/web/packages/design-system/src/components/OcButton/OcButton.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcButton/OcButton.spec.ts",
"repo_id": "owncloud",
"token_count": 2111
} | 756 |
import OcGrid from './OcGrid.vue'
import { mount } from 'web-test-helpers'
describe('OcGrid', () => {
function getWrapper(props = {}) {
return mount(OcGrid, {
props: props
})
}
describe('gutter', () => {
it.each(['small', 'medium', 'large', 'collapse'])(
'should set provided gutter value',
(gutter) => {
const wrapper = getWrapper({
gutter: gutter
})
expect(wrapper.attributes('class')).toBe('oc-grid-' + gutter)
}
)
it('should not accept invalid values', () => {
expect(OcGrid.props.gutter.validator('invalid')).toBeFalsy()
})
})
describe('when flex prop is true', () => {
it('should set grid flex class', () => {
const wrapper = getWrapper({ flex: true })
expect(wrapper.attributes('class')).toContain('oc-flex')
expect(wrapper.attributes('class')).toContain('oc-flex-middle')
})
})
})
| owncloud/web/packages/design-system/src/components/OcGrid/OcGrid.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcGrid/OcGrid.spec.ts",
"repo_id": "owncloud",
"token_count": 380
} | 757 |
<template>
<div class="oc-modal-background" aria-labelledby="oc-modal-title">
<focus-trap :active="true" :initial-focus="initialFocusRef">
<div
:id="elementId"
ref="ocModal"
:class="classes"
tabindex="0"
role="dialog"
aria-modal="true"
@keydown.esc="cancelModalAction"
>
<div class="oc-modal-title">
<oc-icon v-if="iconName !== ''" :name="iconName" :variation="variation" />
<h2 id="oc-modal-title" class="oc-text-truncate" v-text="title" />
</div>
<div class="oc-modal-body">
<div v-if="$slots.content" key="modal-slot-content" class="oc-modal-body-message">
<slot name="content" />
</div>
<template v-else>
<p
v-if="message"
key="modal-message"
class="oc-modal-body-message oc-mt-rm"
:class="{ 'oc-mb-rm': !hasInput || contextualHelperData }"
v-text="message"
/>
<div
v-if="contextualHelperData"
class="oc-modal-body-contextual-helper"
:class="{ 'oc-mb-rm': !hasInput }"
>
<span class="text" v-text="contextualHelperLabel" />
<oc-contextual-helper class="oc-pl-xs" v-bind="contextualHelperData" />
</div>
<oc-text-input
v-if="hasInput"
key="modal-input"
ref="ocModalInput"
v-model="userInputValue"
class="oc-modal-body-input"
:error-message="inputError"
:label="inputLabel"
:type="inputType"
:description-message="inputDescription"
:fix-message-line="true"
:selection-range="inputSelectionRange"
@update:model-value="inputOnInput"
@keydown.enter.prevent="confirm"
/>
</template>
</div>
<div v-if="!hideActions" class="oc-modal-body-actions oc-flex oc-flex-right">
<div class="oc-modal-body-actions-grid">
<oc-button
class="oc-modal-body-actions-cancel"
variation="passive"
appearance="outline"
@click="cancelModalAction"
>{{ buttonCancelText }}</oc-button
>
<oc-button
v-if="!hideConfirmButton"
class="oc-modal-body-actions-confirm oc-ml-s"
variation="primary"
appearance="filled"
:disabled="buttonConfirmDisabled || !!inputError"
@click="confirm"
>{{ buttonConfirmText }}</oc-button
>
</div>
</div>
</div>
</focus-trap>
</div>
</template>
<script lang="ts">
import { defineComponent, PropType, ComponentPublicInstance } from 'vue'
import OcButton from '../OcButton/OcButton.vue'
import OcIcon from '../OcIcon/OcIcon.vue'
import OcTextInput from '../OcTextInput/OcTextInput.vue'
import { FocusTrap } from 'focus-trap-vue'
import { FocusTargetOrFalse, FocusTargetValueOrFalse } from 'focus-trap'
/**
* Modals are generally used to force the user to focus on confirming or completing a single action.
*
* ## Background and position
* Every modal gets automatically added a background which spans the whole width and height.
* The modal itself is aligned to center both vertically and horizontally.
*
* ## Variations
* Only use the `danger` variation if the action cannot be undone.
*
* The overall variation defines the modal's top border, heading (including an optional item) text color and the
* variation of the confirm button, while the cancel buttons defaults to the `passive` variation. Both button's
* variations and appearances can be targeted individually (see examples and API docs below).
*
*/
export default defineComponent({
name: 'OcModal',
status: 'ready',
release: '1.3.0',
components: {
OcButton,
OcIcon,
OcTextInput,
FocusTrap
},
props: {
/**
* Optional modal id
*/
elementId: {
type: String,
required: false,
default: null
},
/**
* Optional modal class
*/
elementClass: {
type: String,
required: false,
default: null
},
/**
* Modal variation
* Defaults to `passive`.
* Can be `passive, primary, danger, success, warning`.
*/
variation: {
type: String,
required: false,
default: 'passive',
validator: (value: string) => {
return ['passive', 'primary', 'danger', 'success', 'warning', 'info'].includes(value)
}
},
/**
* Optional icon to be displayed next to the title
*/
icon: {
type: String,
required: false,
default: null
},
/**
* Modal title
*/
title: {
type: String,
required: true
},
/**
* Modal message. Can be replaced by content slot
*/
message: {
type: String,
required: false,
default: null
},
/**
* Contextual helper label
*/
contextualHelperLabel: {
type: String,
required: false,
default: ''
},
/**
* Contextual helper data
*/
contextualHelperData: {
type: Object,
required: false,
default: null
},
/**
* Text of the cancel button
*/
buttonCancelText: {
type: String,
required: false,
default: 'Cancel'
},
/**
* Text of the confirm button
*/
buttonConfirmText: {
type: String,
required: false,
default: 'Confirm'
},
/**
* Asserts whether the confirm action is disabled
*/
buttonConfirmDisabled: {
type: Boolean,
required: false,
default: false
},
/**
* Asserts whether the modal should render a confirm button
*/
hideConfirmButton: {
type: Boolean,
required: false,
default: false
},
/**
* Asserts whether the modal should render a text input
*/
hasInput: {
type: Boolean,
required: false,
default: false
},
/**
* Type of the input field
*/
inputType: {
type: String,
default: 'text'
},
/**
* Value of the input
*/
inputValue: {
type: String,
required: false,
default: null
},
/**
* Selection range for input to accomplish partial selection
*/
inputSelectionRange: {
type: Array as unknown as PropType<[number, number]>,
required: false,
default: null
},
/**
* Label of the text input field
*/
inputLabel: {
type: String,
required: false,
default: null
},
/**
* Additional description message for the input field
*/
inputDescription: {
type: String,
required: false,
default: null
},
/**
* Error message for the input field
*/
inputError: {
type: String,
required: false,
default: null
},
/**
* Overwrite default focused element
* Can be `#id, .class`.
*/
focusTrapInitial: {
type: String,
required: false,
default: null
},
/**
* Hide the actions at the bottom of the modal
*/
hideActions: {
type: Boolean,
default: false
}
},
emits: ['cancel', 'confirm', 'input'],
data() {
return {
userInputValue: null
}
},
computed: {
initialFocusRef(): FocusTargetOrFalse {
if (this.focusTrapInitial) {
return this.focusTrapInitial
}
return () => {
// FIXME: according to the types it's incorrect to pass this.$refs.ocModalInput
// but passing this.$refs.ocModalInput?.$el does not work …
return ((this.$refs.ocModalInput as ComponentPublicInstance as unknown as HTMLElement) ||
(this.$refs.ocModal as HTMLElement)) as FocusTargetValueOrFalse
}
},
classes() {
return ['oc-modal', `oc-modal-${this.variation}`, this.elementClass]
},
iconName() {
if (this.icon) {
return this.icon
}
switch (this.variation) {
case 'danger':
return 'alert'
case 'warning':
return 'error-warning'
case 'success':
return 'checkbox-circle'
case 'info':
return 'information'
default:
return ''
}
}
},
watch: {
inputValue: {
handler: 'inputAssignPropAsValue',
immediate: true
}
},
methods: {
cancelModalAction() {
/**
* The user clicked on the cancel button or hit the escape key
*/
this.$emit('cancel')
},
confirm() {
if (this.buttonConfirmDisabled || this.inputError) {
return
}
/**
* The user clicked on the confirm button. If input exists, emits its value
*
* @property {String} value Value of the input
*/
this.$emit('confirm', this.userInputValue)
},
inputOnInput(value) {
/**
* The user typed into the input
*
* @property {String} value Value of the input
*/
this.$emit('input', value)
},
inputAssignPropAsValue(value) {
this.userInputValue = value
}
}
})
</script>
<style lang="scss">
@mixin oc-modal-variation($color) {
span {
color: $color;
}
}
.oc-modal {
max-width: 500px;
width: 100%;
box-shadow: 5px 0 25px rgba(0, 0, 0, 0.3);
border: 1px solid var(--oc-color-input-border);
border-radius: 15px;
background-color: var(--oc-color-background-default);
&:focus {
outline: none;
}
&-background {
align-items: center;
background-color: rgba(0, 0, 0, 0.4);
display: flex;
flex-flow: row wrap;
height: 100%;
justify-content: center;
left: 0;
position: fixed;
top: 0;
width: 100%;
z-index: var(--oc-z-index-modal);
}
&-primary {
@include oc-modal-variation(var(--oc-color-swatch-primary-default));
}
&-success {
@include oc-modal-variation(var(--oc-color-swatch-success-default));
}
&-warning {
@include oc-modal-variation(var(--oc-color-swatch-warning-default));
}
&-danger {
@include oc-modal-variation(var(--oc-color-swatch-danger-default));
}
&-title {
align-items: center;
border-bottom: 1px solid var(--oc-color-input-border);
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: flex;
flex-flow: row wrap;
line-height: 1.625;
padding: var(--oc-space-medium) var(--oc-space-medium);
> .oc-icon {
margin-right: var(--oc-space-small);
}
> h2 {
font-size: 1rem;
font-weight: bold;
margin: 0;
}
}
&-body {
color: var(--oc-color-text-default);
line-height: 1.625;
padding: var(--oc-space-medium) var(--oc-space-medium) 0;
span {
color: var(--oc-color-text-default);
}
&-message {
margin-bottom: var(--oc-space-medium);
margin-top: var(--oc-space-small);
}
&-contextual-helper {
margin-bottom: var(--oc-space-medium);
}
.oc-input {
line-height: normal;
}
&-input {
/* FIXME: this is ugly, but required so that the bottom padding doesn't look off when reserving vertical space for error messages below the input. */
margin-bottom: -20px;
padding-bottom: var(--oc-space-medium);
.oc-text-input-message {
margin-bottom: var(--oc-space-xsmall);
}
}
&-actions {
text-align: right;
background: var(--oc-color-background-default);
border-bottom-right-radius: 15px;
border-bottom-left-radius: 15px;
padding: var(--oc-space-medium);
.oc-button {
border-radius: 4px;
}
&-grid {
display: inline-grid;
grid-auto-flow: column;
grid-auto-columns: 1fr;
}
}
}
.oc-text-input-password-wrapper {
button {
background-color: var(--oc-color-background-highlight) !important;
}
}
}
</style>
<docs>
```js
<div>
<oc-modal
icon="information"
title="Accept terms of use"
message="Do you accept our terms of use?"
button-cancel-text="Decline"
button-confirm-text="Accept"
class="oc-mb-l oc-position-relative"
/>
</div>
```
```js
<div>
<oc-modal
variation="danger"
icon="alert"
title="Delete file lorem.txt"
message="Are you sure you want to delete this file? All its content will be permanently removed. This action cannot be undone."
button-cancel-text="Cancel"
button-confirm-text="Delete"
class="oc-mb-l oc-position-relative"
/>
</div>
```
```js
<div>
<oc-modal
title="Create new folder"
button-cancel-text="Cancel"
button-confirm-text="Create"
:has-input="true"
input-value="New folder"
input-label="Folder name"
input-description="Enter a folder name"
input-error="This name is already taken, please choose another one"
class="oc-mb-l oc-position-relative"
/>
</div>
```
```js
<div>
<oc-modal
title="Rename file lorem.txt"
button-cancel-text="Cancel"
button-confirm-text="Rename"
class="oc-position-relative"
>
<template v-slot:content>
<oc-text-input
value="lorem.txt"
label="File name"
/>
</template>
</oc-modal>
</div>
```
```js
<div>
<oc-modal
icon="information"
title="Accept terms of use"
message="Do you accept our terms of use?"
button-cancel-text="Decline"
button-confirm-text="Accept"
class="oc-mb-l oc-position-relative"
/>
</div>
```
```js
<div>
<oc-modal
icon="information"
title="Accept terms of use"
message="Do you accept our terms of use?"
button-cancel-text="Decline"
button-confirm-text="Accept"
class="oc-mb-l oc-position-relative"
/>
</div>
```
```js
<div>
<oc-modal
icon="information"
title="Accept terms of use"
message="Do you accept our terms of use?"
button-cancel-text="Decline"
button-confirm-text="Accept"
contextual-helper-label="I need more information?"
:contextual-helper-data="{ title: 'This is more information' }"
class="oc-mb-l oc-position-relative"
/>
</div>
```
```js
<div>
<oc-modal
icon="info"
title="Accept terms of use"
message="Do you accept our terms of use?"
button-cancel-text="Decline"
button-confirm-text="Accept"
class="oc-mb-l oc-position-relative"
/>
</div>
```
</docs>
| owncloud/web/packages/design-system/src/components/OcModal/OcModal.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcModal/OcModal.vue",
"repo_id": "owncloud",
"token_count": 6465
} | 758 |
import { defaultPlugins, shallowMount } from 'web-test-helpers'
import Recipient from './OcRecipient.vue'
import { Recipient as RecipientType } from './types'
describe('OcRecipient', () => {
/**
* @param {Object} props
* @returns {Wrapper<Vue>}
*/
function getWrapper(props = undefined, slot = undefined) {
const slots = slot ? { append: slot } : {}
return shallowMount(Recipient, {
props: {
recipient: {
name: 'alice',
avatar: 'avatar.jpg',
hasAvatar: true,
isLoadingAvatar: false,
...props
}
},
slots,
global: { plugins: [...defaultPlugins()] }
})
}
it('displays recipient name', () => {
const wrapper = getWrapper()
expect(wrapper.find('[data-testid="recipient-name"]').text()).toEqual('alice')
})
it('displays avatar', () => {
const wrapper = getWrapper()
expect(wrapper.find('[data-testid="recipient-avatar"]').attributes('src')).toEqual('avatar.jpg')
})
it('displays a spinner if avatar has not been loaded yet', () => {
const wrapper = getWrapper({
isLoadingAvatar: true
})
expect(wrapper.find('[data-testid="recipient-avatar-spinner"]').exists()).toBeTruthy()
})
it('displays an icon if avatar is not enabled', () => {
const wrapper = getWrapper({
icon: {
name: 'person',
label: 'User'
},
hasAvatar: false
})
const icon = wrapper.find('[data-testid="recipient-icon"]')
expect(icon.exists()).toBeTruthy()
expect(icon.attributes().accessiblelabel).toEqual('User')
})
it('display content in the append slot', () => {
const wrapper = getWrapper({}, '<span id="test-slot">Hello world</span>')
expect(wrapper.find('#test-slot').exists()).toBeTruthy()
})
it.each([
['name is not defined', {}],
[
'name is not a string',
{
name: {
first: 'Alice'
}
}
],
[
'name is empty',
{
name: ''
}
],
['icon name is not defined', { name: 'Alice', icon: {} }],
['icon name is not a string', { name: 'Alice', icon: { name: { inverted: 'inverted' } } }],
['icon name is empty', { name: 'Alice', icon: { name: '' } }],
['icon label is not defined', { name: 'Alice', icon: { name: 'person' } }],
[
'icon label is not a string',
{ name: 'Alice', icon: { name: 'person', label: { long: 'Long label' } } }
],
['icon label is empty', { name: 'Alice', icon: { name: 'Alice', label: '' } }]
])('throws an error if %s', (def, prop: RecipientType) => {
expect(() => shallowMount(Recipient, { props: { recipient: prop } })).toThrow(
`Recipient ${def}`
)
})
})
| owncloud/web/packages/design-system/src/components/OcRecipient/OcRecipient.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcRecipient/OcRecipient.spec.ts",
"repo_id": "owncloud",
"token_count": 1119
} | 759 |
<template>
<table :class="tableClasses">
<slot />
</table>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
/**
* A table component with manually built layout.
*/
export default defineComponent({
name: 'OcTableSimple',
status: 'ready',
release: '2.1.0',
props: {
/**
* Whether or not table rows should be highlighted when hovered.
*/
hover: {
type: Boolean,
default: false
}
},
computed: {
tableClasses() {
const result = ['oc-table-simple']
if (this.hover) {
result.push('oc-table-simple-hover')
}
return result
}
}
})
</script>
<style lang="scss">
.oc-table-simple {
border-collapse: collapse;
border-spacing: 0;
width: 100%;
&-hover tr {
transition: background-color $transition-duration-short ease-in-out;
}
tr + tr {
border-top: 1px solid var(--oc-color-border);
}
&-hover tr:hover {
background-color: var(--oc-color-input-border);
}
}
</style>
<docs>
```js
<template>
<section>
<h3 class="oc-heading-divider">
A simple table
</h3>
<oc-table-simple :hover="true">
<oc-thead>
<oc-tr>
<oc-th>Resource</oc-th>
<oc-th>Last modified</oc-th>
</oc-tr>
</oc-thead>
<oc-tbody>
<oc-tr v-for="item in items" :key="'item-' + item.id">
<oc-td>{{ item.resource }}</oc-td>
<oc-td>{{ item.last_modified }}</oc-td>
</oc-tr>
</oc-tbody>
</oc-table-simple>
</section>
</template>
<script>
export default {
computed: {
items() {
return [{
id: "4b136c0a-5057-11eb-ac70-eba264112003",
resource: "hello-world.txt",
last_modified: 1609962211,
}, {
id: "8468c9f0-5057-11eb-924b-934c6fd827a2",
resource: "I am a folder",
last_modified: 1608887766,
}, {
id: "9c4cf97e-5057-11eb-8044-b3d5df9caa21",
resource: "this is fine.png",
last_modified: 1599999999,
}]
},
},
}
</script>
```
</docs>
| owncloud/web/packages/design-system/src/components/OcTableSimple/OcTableSimple.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcTableSimple/OcTableSimple.vue",
"repo_id": "owncloud",
"token_count": 1014
} | 760 |
import { shallowMount } from 'web-test-helpers'
import Cell from './_OcTableCell.vue'
describe('OcTableCell', () => {
it('Uses correct element', () => {
const wrapper = shallowMount(Cell, {
props: {
type: 'th',
alignH: 'right',
alignV: 'bottom',
width: 'shrink'
},
slots: {
default: 'Hello world!'
}
})
expect(wrapper.element.tagName).toBe('TH')
expect(wrapper.classes()).toContain('oc-table-cell-align-right')
expect(wrapper.classes()).toContain('oc-table-cell-align-bottom')
expect(wrapper.classes()).toContain('oc-table-cell-width-shrink')
expect(wrapper.html()).toMatchSnapshot()
})
})
| owncloud/web/packages/design-system/src/components/_OcTableCell/OcTableCell.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/_OcTableCell/OcTableCell.spec.ts",
"repo_id": "owncloud",
"token_count": 289
} | 761 |
import {
hexToRgb,
rgbToHex,
calculateShadeColor,
getLuminanace,
getContrastRatio,
generateHashedColorForString,
setDesiredContrastRatio,
cssRgbToHex,
getHexFromCssVar
} from './colors'
describe('hexToRgb', () => {
it('converts hex to rgb', () => {
expect(hexToRgb('#FF0000')).toEqual([255, 0, 0])
expect(hexToRgb('#00FF00')).toEqual([0, 255, 0])
expect(hexToRgb('#0000FF')).toEqual([0, 0, 255])
expect(hexToRgb('#FFFFFF')).toEqual([255, 255, 255])
expect(hexToRgb('#000000')).toEqual([0, 0, 0])
expect(hexToRgb('FF0000')).toEqual([255, 0, 0]) // Test without #
expect(hexToRgb('invalid')).toBeNull() // Test with invalid input
})
})
describe('rgbToHex', () => {
it('converts rgb to hex', () => {
expect(rgbToHex([255, 0, 0])).toBe('#ff0000')
expect(rgbToHex([0, 255, 0])).toBe('#00ff00')
expect(rgbToHex([0, 0, 255])).toBe('#0000ff')
expect(rgbToHex([255, 255, 255])).toBe('#ffffff')
expect(rgbToHex([0, 0, 0])).toBe('#000000')
})
})
describe('calculateShadeColor', () => {
it('shades a color', () => {
const initialColor = [100, 50, 50]
expect(calculateShadeColor(initialColor, 50)).toBe('#964b4b')
expect(calculateShadeColor(initialColor, -10)).toBe('#5a2d2d')
})
})
describe('getLuminanace', () => {
it('calculates luminance', () => {
expect(getLuminanace([255, 255, 255])).toBeCloseTo(1)
expect(getLuminanace([0, 0, 0])).toBeCloseTo(0)
})
})
describe('getContrastRatio', () => {
it('calculates contrast ratio', () => {
const colorA = [255, 255, 255]
const colorB = [0, 0, 0]
expect(getContrastRatio(colorA, colorB)).toBeGreaterThan(20)
})
})
describe('generateHashedColorForString', () => {
it('generates a hashed color', () => {
expect(generateHashedColorForString('owncloud')).toBe('#2F26F')
expect(generateHashedColorForString('example')).toMatch('#25116A')
})
})
describe('setDesiredContrastRatio', () => {
it('adjusts color for desired contrast ratio', () => {
const targetColor = [100, 100, 100]
const associatedColor = [255, 255, 255]
const desiredRatio = 3
expect(setDesiredContrastRatio(targetColor, associatedColor, desiredRatio)).toEqual([
142, 142, 142
])
})
})
describe('cssRgbToHex', () => {
it('converts css rgb value to hex', () => {
expect(cssRgbToHex('rgb(255, 0, 0)')).toBe('#ff0000')
expect(cssRgbToHex('rgba(0, 255, 0, 0.5)')).toBe('#00ff0080')
})
})
describe('getHexFromCssVar', () => {
it('retrieves hex value from CSS var', () => {
document.documentElement.style.setProperty('--color-primary', '#ff0000')
expect(getHexFromCssVar('--color-primary')).toBe('#ff0000')
document.documentElement.style.setProperty('--color-primary', 'rgb(0, 255, 0)')
expect(getHexFromCssVar('--color-primary')).toBe('#00ff00')
})
})
| owncloud/web/packages/design-system/src/helpers/colors.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/helpers/colors.spec.ts",
"repo_id": "owncloud",
"token_count": 1197
} | 762 |
// Name: Form
// Description: Styles for forms
//
// Component: `oc-input`
// `oc-select`
// `oc-textarea`
// `oc-radio`
// `oc-checkbox`
//
// ========================================================================
/* stylelint-disable */
@function str-replace($string, $search, $replace: "") {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
@mixin svg-fill($src, $color-default, $color-new) {
$replace-src: str-replace($src, $color-default, $color-new) !default;
$replace-src: str-replace($replace-src, "#", "%23");
background-image: url(quote($replace-src));
}
// Variables
// ========================================================================
$form-height: var(--oc-font-size-default) !default;
$form-line-height: $form-height !default;
$form-padding-horizontal: var(--oc-space-small) !default;
$form-padding-vertical: var(--oc-space-xsmall) !default;
$form-background: var(--oc-color-background-muted) !default;
$form-color: var(--oc-color-text-default) !default;
$form-focus-background: var(--oc-color-background-highlight) !default;
$form-focus-color: var(--oc-color-text-default) !default;
$form-disabled-background: var(--oc-color-background-muted) !default;
$form-disabled-color: var(--oc-color-text-muted) !default;
$form-placeholder-color: var(--oc-color-text-muted) !default;
$form-small-height: var(--oc-font-size-small) !default;
$form-small-padding-horizontal: var(--oc-space-small) !default;
$form-small-line-height: $form-small-height !default;
$form-small-font-size: var(--oc-font-size-small) !default;
$form-large-height: var(--oc-font-size-large) !default;
$form-large-padding-horizontal: var(--oc-space-medium) !default;
$form-large-line-height: $form-large-height !default;
$form-large-font-size: var(--oc-font-size-large) !default;
$form-danger-color: var(--oc-color-swatch-danger-default) !default;
$form-success-color: var(--oc-color-swatch-success-default) !default;
$form-width-xsmall: 50px !default;
$form-width-small: 130px !default;
$form-width-medium: 200px !default;
$form-width-large: 500px !default;
$form-select-padding-right: 20px !default;
$form-select-icon-color: var(--oc-color-text-default) !default;
$form-select-option-color: #444 !default;
$form-select-disabled-icon-color: var(--oc-color-text-muted) !default;
$form-datalist-padding-right: 20px !default;
$form-datalist-icon-color: var(--oc-color-text-default) !default;
$form-radio-background: var(--oc-color-background-muted) !default;
$form-radio-checked-background: $oc-color-swatch-primary-default !default;
$form-radio-checked-icon-color: var(--oc-color-input-text-default) !default;
$form-radio-checked-focus-background: $oc-color-swatch-primary-default !default;
$form-radio-disabled-background: $oc-color-background-muted !default;
$form-radio-disabled-icon-color: var(--oc-color-text-muted) !default;
$form-legend-font-size: var(--oc-font-size-large) !default;
$form-legend-line-height: 1.4 !default;
$form-stacked-margin-bottom: var(--oc-space-small) !default;
$form-horizontal-label-width: 200px !default;
$form-horizontal-label-margin-top: 7px !default;
$form-horizontal-controls-margin-left: 215px !default;
$form-horizontal-controls-text-padding-top: 7px !default;
$form-icon-width: var(--oc-size-icon-default) !default;
$form-icon-color: var(--oc-color-text-muted) !default;
$form-icon-hover-color: var(--oc-color-text-default) !default;
$internal-form-select-image: "data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2224%22%20height%3D%2216%22%20viewBox%3D%220%200%2024%2016%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%0A%20%20%20%20%3Cpolygon%20fill%3D%22#000%22%20points%3D%2212%201%209%206%2015%206%22%20%2F%3E%0A%20%20%20%20%3Cpolygon%20fill%3D%22#000%22%20points%3D%2212%2013%209%208%2015%208%22%20%2F%3E%0A%3C%2Fsvg%3E%0A" !default;
$internal-form-datalist-image: "data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2224%22%20height%3D%2216%22%20viewBox%3D%220%200%2024%2016%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%0A%20%20%20%20%3Cpolygon%20fill%3D%22#000%22%20points%3D%2212%2012%208%206%2016%206%22%20%2F%3E%0A%3C%2Fsvg%3E%0A" !default;
$internal-form-radio-image: "data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2216%22%20height%3D%2216%22%20viewBox%3D%220%200%2016%2016%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%0A%20%20%20%20%3Ccircle%20fill%3D%22#000%22%20cx%3D%228%22%20cy%3D%228%22%20r%3D%222%22%20%2F%3E%0A%3C%2Fsvg%3E" !default;
$internal-form-checkbox-image: "data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2214%22%20height%3D%2211%22%20viewBox%3D%220%200%2014%2011%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%0A%20%20%20%20%3Cpolygon%20fill%3D%22#000%22%20points%3D%2212%201%205%207.5%202%205%201%205.5%205%2010%2013%201.5%22%20%2F%3E%0A%3C%2Fsvg%3E%0A" !default;
$internal-form-checkbox-indeterminate-image: "data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2216%22%20height%3D%2216%22%20viewBox%3D%220%200%2016%2016%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%0A%20%20%20%20%3Crect%20fill%3D%22#000%22%20x%3D%223%22%20y%3D%228%22%20width%3D%2210%22%20height%3D%221%22%20%2F%3E%0A%3C%2Fsvg%3E" !default;
/* ========================================================================
Component: Form
========================================================================== */
/*
* 1. Define consistent box sizing.
* Default is `content-box` with following exceptions set to `border-box`
* `select`, `input[type="checkbox"]` and `input[type="radio"]`
* `input[type="search"]` in Chrome, Safari and Opera
* `input[type="color"]` in Firefox
* 2. Address margins set differently in Firefox/IE and Chrome/Safari/Opera.
* 3. Remove `border-radius` in iOS.
* 4. Change font properties to `inherit` in all browsers.
*/
.oc-input,
.oc-select,
.oc-textarea,
.oc-radio {
/* 3 */
border-radius: 0;
/* 1 */
box-sizing: border-box;
/* 4 */
font: inherit;
/* 2 */
margin: 0;
}
/*
* Show the overflow in Edge.
*/
.oc-input { overflow: visible; }
/*
* Remove the inheritance of text transform in Firefox.
*/
.oc-select { text-transform: none; }
/*
* 1. Change font properties to `inherit` in all browsers
* 2. Don't inherit the `font-weight` and use `bold` instead.
* NOTE: Both declarations don't work in Chrome, Safari and Opera.
*/
.oc-select optgroup {
/* 1 */
font: inherit;
/* 2 */
font-weight: bold;
}
/*
* Remove the default vertical scrollbar in IE 10+.
*/
.oc-textarea { overflow: auto; }
/*
* Remove the inner padding and cancel buttons in Chrome on OS X and Safari on OS X.
*/
.oc-input[type="search"]::-webkit-search-cancel-button,
.oc-input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; }
/*
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
.oc-input[type="number"]::-webkit-inner-spin-button,
.oc-input[type="number"]::-webkit-outer-spin-button { height: auto; }
/*
* Removes placeholder transparency in Firefox.
*/
.oc-input::placeholder,
.oc-textarea::placeholder { opacity: 1; }
/*
* Improves consistency of cursor style for clickable elements
*/
.oc-radio:not(:disabled) { cursor: pointer; }
/* Input, select and textarea
* Allowed: `text`, `password`, `datetime`, `datetime-local`, `date`, `month`,
`time`, `week`, `number`, `email`, `url`, `search`, `tel`, `color`
* Disallowed: `range`, `radio`, `checkbox`, `file`, `submit`, `reset` and `image`
========================================================================== */
/*
* Remove default style in iOS.
*/
.oc-input,
.oc-textarea { -webkit-appearance: none; }
/*
* 1. Prevent content overflow if a fixed width is used
* 2. Take the full width
* 3. Reset default
* 4. Style
*/
.oc-input,
.oc-select,
.oc-textarea {
background: $form-background;
/* 3 */
border: 0 none;
color: $form-color;
/* 1 */
max-width: 100%;
/* 2 */
width: 100%;
@if (mixin-exists(hook-form)) { @include hook-form(); }
}
/*
* Single-line
* 1. Allow any element to look like an `input` or `select` element
* 2. Make sure line-height is not larger than height
* Also needed to center the text vertically
*/
.oc-input {
-webkit-appearance: none;
background-clip: padding-box, border-box;
background-color: $form-focus-background;
background-origin: border-box;
border-radius: 0;
border-radius: 5px;
border: 1px solid var(--oc-color-input-border);
box-sizing: border-box;
color: var(--oc-color-input-text-default);
display: inline-block;
line-height: inherit;
margin: 0;
max-width: 100%;
outline: none;
overflow: visible;
padding: calc(var(--oc-space-xsmall) + 2px) 7px;
transition-duration: 0.2s;
transition-timing-function: ease-in-out;
transition-property: color, background-color;
vertical-align: middle;
width: 100%;
}
.oc-background-highlight .oc-input {
background-color: var(--oc-color-input-bg);
}
/* 2 */
.oc-input:not(input),
.oc-select:not(select) {
line-height: $form-line-height;
}
/*
* Multi-line
*/
.oc-textarea {
padding: $form-padding-vertical $form-padding-horizontal;
vertical-align: top;
}
/* Focus */
.oc-input:focus,
.oc-select:focus,
.oc-textarea:focus {
outline: none;
border-color: var(--oc-color-swatch-passive-default);
color: $form-focus-color;
}
.oc-background-highlight {
.oc-input:focus,
.oc-select:focus,
.oc-textarea:focus {
background-color: var(--oc-color-background-default);
}
}
/* Disabled */
.oc-input:disabled,
.oc-select:disabled {
background-color: $form-disabled-background;
color: $form-disabled-color;
cursor: not-allowed;
}
/*
* Placeholder
*/
.oc-input::input-placeholder { color: $form-placeholder-color !important; }
.oc-input::placeholder { color: $form-placeholder-color; }
.oc-textarea::input-placeholder { color: $form-placeholder-color !important; }
.oc-textarea::placeholder { color: $form-placeholder-color; }
/* Style modifier (`oc-input`, `oc-select` and `oc-textarea`)
========================================================================== */
/*
* Small
*/
.oc-form-small { font-size: $form-small-font-size; }
.oc-form-small:not(textarea):not([multiple]):not([size]) {
height: $form-small-height;
padding-left: $form-small-padding-horizontal;
padding-right: $form-small-padding-horizontal;
}
.oc-form-small:not(select):not(input):not(textarea) { line-height: $form-small-line-height; }
/*
* Large
*/
.oc-form-large { font-size: $form-large-font-size; }
.oc-form-large:not(textarea):not([multiple]):not([size]) {
height: $form-large-height;
padding-left: $form-large-padding-horizontal;
padding-right: $form-large-padding-horizontal;
}
.oc-form-large:not(select):not(input):not(textarea) { line-height: $form-large-line-height; }
/* Style modifier (`oc-input`, `oc-select` and `oc-textarea`)
========================================================================== */
/*
* Error
*/
.oc-form-danger,
.oc-form-danger:focus {
color: $form-danger-color;
}
/*
* Success
*/
.oc-form-success,
.oc-form-success:focus {
color: $form-success-color;
}
/*
* Blank
*/
.oc-form-blank {
background: none;
}
/* Width modifiers (`oc-input`, `oc-select` and `oc-textarea`)
========================================================================== */
/*
* Fixed widths
* Different widths for mini sized `input` and `select` elements
*/
input.oc-form-width-xsmall { width: $form-width-xsmall; }
select.oc-form-width-xsmall { width: ($form-width-xsmall + 25px); }
.oc-form-width-small { width: $form-width-small; }
.oc-form-width-medium { width: $form-width-medium; }
.oc-form-width-large { width: $form-width-large; }
/* Select
========================================================================== */
/*
* 1. Remove default style. Also works in Firefox
* 2. Style
* 3. Remove default style in IE 10/11
* 4. Set `color` for options in the select dropdown, because the inherited `color` might be too light.
*/
.oc-select:not([multiple]):not([size]) {
@include svg-fill($internal-form-select-image, "#000", $form-select-icon-color);
-webkit-appearance: none;
-moz-appearance: none;
background-position: 100% 50%;
background-repeat: no-repeat;
}
/* 3 */
.oc-select:not([multiple]):not([size])::-ms-expand { display: none; }
/* 4 */
.oc-select:not([multiple]):not([size]) option { color: $form-select-option-color; }
/*
* Disabled
*/
.oc-select:not([multiple]):not([size]):disabled { @include svg-fill($internal-form-select-image, "#000", $form-select-disabled-icon-color); }
/* Datalist
========================================================================== */
/*
* 1. Remove default style in Chrome
*/
.oc-input[list] {
background-position: 100% 50%;
background-repeat: no-repeat;
padding-right: $form-datalist-padding-right;
}
.oc-input[list]:hover,
.oc-input[list]:focus { @include svg-fill($internal-form-datalist-image, "#000", $form-datalist-icon-color); }
/* Radio and checkbox
* Note: Does not work in IE11
========================================================================== */
/*
* 1. Style
* 2. Make box more robust so it clips the child element
* 3. Vertical alignment
* 4. Remove default style
* 5. Fix black background on iOS
* 6. Center icons
*/
.oc-radio{
/* 4 */
-webkit-appearance: none;
-moz-appearance: none;
/* 5 */
background-color: $form-radio-background;
background-position: 50% 50%;
/* 6 */
background-repeat: no-repeat;
/* 1 */
display: inline-block;
/* 2 */
overflow: hidden;
vertical-align: middle;
}
.oc-radio { border-radius: 50%; }
/* Focus */
.oc-radio:focus {
outline: none;
}
/*
* Checked
*/
.oc-radio:checked {
background-color: $form-radio-checked-background;
}
/* Focus */
.oc-radio:checked:focus {
background-color: $form-radio-checked-focus-background;
}
/*
* Icons
*/
.oc-radio:checked { @include svg-fill($internal-form-radio-image, "#000", $form-radio-checked-icon-color); }
/*
* Disabled
*/
.oc-radio:disabled {
background-color: $form-radio-disabled-background;
}
.oc-radio:disabled:checked { @include svg-fill($internal-form-radio-image, "#000", $form-radio-disabled-icon-color); }
/* stylelint-enable */
| owncloud/web/packages/design-system/src/styles/theme/oc-form.scss/0 | {
"file_path": "owncloud/web/packages/design-system/src/styles/theme/oc-form.scss",
"repo_id": "owncloud",
"token_count": 5470
} | 763 |
---
size:
max-width:
logo:
value: 150px
max-height:
logo:
value: 60px
height:
small:
value: 50px
table-row:
value: 42px
width:
xsmall:
value: 100px
small:
value: 150px
medium:
value: 300px
icon-default:
value: 22px
form-check-default:
value: 14px
tiles:
resize-step:
value: 6rem
default:
value: 10rem
| owncloud/web/packages/design-system/src/tokens/ods/size.yaml/0 | {
"file_path": "owncloud/web/packages/design-system/src/tokens/ods/size.yaml",
"repo_id": "owncloud",
"token_count": 208
} | 764 |
{
"name": "@ownclouders/extension-sdk",
"version": "0.0.1-alpha.3",
"description": "ownCloud Web Extension SDK",
"license": "AGPL-3.0",
"main": "index.mjs",
"type": "module",
"private": false,
"author": "ownCloud GmbH <devops@owncloud.com>",
"homepage": "https://github.com/owncloud/web/tree/master/packages/extension-sdk",
"repository": {
"type": "git",
"url": "https://github.com/owncloud/web",
"directory": "packages/extension-sdk"
},
"dependencies": {
"@vitejs/plugin-vue": "^4.0.0",
"rollup-plugin-node-polyfills": "^0.2.1",
"rollup-plugin-serve": "^2.0.2"
},
"peerDependencies": {
"vite": "^5.0",
"sass": "1.69.7"
}
}
| owncloud/web/packages/extension-sdk/package.json/0 | {
"file_path": "owncloud/web/packages/extension-sdk/package.json",
"repo_id": "owncloud",
"token_count": 312
} | 765 |
<template>
<div id="group-edit-panel" class="oc-mt-xl">
<group-info-box :group="group" />
<form id="group-edit-form" class="oc-background-highlight oc-p-m" autocomplete="off">
<oc-text-input
id="displayName-input"
v-model="editGroup.displayName"
class="oc-mb-s"
:label="$gettext('Group name')"
:error-message="formData.displayName.errorMessage"
:fix-message-line="true"
@update:model-value="validateDisplayName"
/>
<compare-save-dialog
class="edit-compare-save-dialog oc-mb-l"
:original-object="group"
:compare-object="editGroup"
:confirm-button-disabled="invalidFormData"
@revert="revertChanges"
@confirm="onEditGroup(editGroup)"
></compare-save-dialog>
</form>
</div>
</template>
<script lang="ts">
import { defineComponent, PropType, ref } from 'vue'
import { Group } from '@ownclouders/web-client/src/generated'
import { CompareSaveDialog, eventBus, useMessages } from '@ownclouders/web-pkg'
import { MaybeRef, useClientService } from '@ownclouders/web-pkg'
import GroupInfoBox from './GroupInfoBox.vue'
import { useGroupSettingsStore } from '../../../composables'
import { useGettext } from 'vue3-gettext'
export default defineComponent({
name: 'EditPanel',
components: {
GroupInfoBox,
CompareSaveDialog
},
props: {
group: {
type: Object as PropType<Group>,
required: true,
default: null
}
},
emits: ['confirm'],
setup() {
const clientService = useClientService()
const { showErrorMessage } = useMessages()
const groupSettingsStore = useGroupSettingsStore()
const { $gettext } = useGettext()
const editGroup: MaybeRef<Group> = ref({})
const formData = ref({
displayName: {
errorMessage: '',
valid: true
}
})
const onEditGroup = async (editGroup: Group) => {
try {
const client = clientService.graphAuthenticated
await client.groups.editGroup(editGroup.id, editGroup)
const { data: updatedGroup } = await client.groups.getGroup(editGroup.id)
groupSettingsStore.upsertGroup(updatedGroup)
eventBus.publish('sidebar.entity.saved')
return updatedGroup
} catch (error) {
console.error(error)
showErrorMessage({
title: $gettext('Failed to edit group'),
errors: [error]
})
}
}
return {
clientService,
editGroup,
formData,
onEditGroup
}
},
computed: {
invalidFormData() {
return Object.values(this.formData)
.map((v: any) => !!v.valid)
.includes(false)
}
},
watch: {
group: {
handler: function () {
this.editGroup = { ...this.group }
},
deep: true,
immediate: true
}
},
methods: {
async validateDisplayName() {
this.formData.displayName.valid = false
if (this.editGroup.displayName.trim() === '') {
this.formData.displayName.errorMessage = this.$gettext('Group name cannot be empty')
return false
}
if (this.editGroup.displayName.length > 255) {
this.formData.displayName.errorMessage = this.$gettext(
'Group name cannot exceed 255 characters'
)
return false
}
if (this.group.displayName !== this.editGroup.displayName) {
try {
const client = this.clientService.graphAuthenticated
await client.groups.getGroup(this.editGroup.displayName)
this.formData.displayName.errorMessage = this.$gettext(
'Group "%{groupName}" already exists',
{
groupName: this.editGroup.displayName
}
)
return false
} catch (e) {}
}
this.formData.displayName.errorMessage = ''
this.formData.displayName.valid = true
return true
},
revertChanges() {
this.editGroup = { ...this.group }
Object.values(this.formData).forEach((formDataValue: any) => {
formDataValue.valid = true
formDataValue.errorMessage = ''
})
}
}
})
</script>
<style lang="scss">
#group-edit-panel {
#group-edit-form {
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.edit-compare-save-dialog {
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
.group-info {
align-items: center;
flex-direction: column;
}
.group-info-display-name {
font-size: 1.5rem;
}
}
</style>
| owncloud/web/packages/web-app-admin-settings/src/components/Groups/SideBar/EditPanel.vue/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/src/components/Groups/SideBar/EditPanel.vue",
"repo_id": "owncloud",
"token_count": 1929
} | 766 |
<template>
<div id="user-edit-panel" class="oc-mt-xl">
<UserInfoBox :user="user" />
<form id="user-edit-form" class="oc-background-highlight oc-p-m" autocomplete="off">
<div>
<oc-text-input
id="userName-input"
v-model="editUser.onPremisesSamAccountName"
class="oc-mb-s"
:label="$gettext('User name')"
:error-message="formData.userName.errorMessage"
:fix-message-line="true"
:read-only="isInputFieldReadOnly('user.onPremisesSamAccountName')"
@update:model-value="validateUserName"
/>
<oc-text-input
id="displayName-input"
v-model="editUser.displayName"
class="oc-mb-s"
:label="$gettext('First and last name')"
:error-message="formData.displayName.errorMessage"
:fix-message-line="true"
:read-only="isInputFieldReadOnly('user.displayName')"
@update:model-value="validateDisplayName"
/>
<oc-text-input
id="email-input"
v-model="editUser.mail"
class="oc-mb-s"
:label="$gettext('Email')"
:error-message="formData.email.errorMessage"
type="email"
:fix-message-line="true"
:read-only="isInputFieldReadOnly('user.mail')"
@change="validateEmail"
/>
<oc-text-input
id="password-input"
:model-value="editUser.passwordProfile?.password"
class="oc-mb-s"
:label="$gettext('Password')"
type="password"
:fix-message-line="true"
placeholder="●●●●●●●●"
:read-only="isInputFieldReadOnly('user.passwordProfile')"
@update:model-value="onUpdatePassword"
/>
<div class="oc-mb-s">
<oc-select
id="role-input"
:model-value="selectedRoleValue"
:label="$gettext('Role')"
option-label="displayName"
:options="translatedRoleOptions"
:clearable="false"
:read-only="isInputFieldReadOnly('user.appRoleAssignments')"
@update:model-value="onUpdateRole"
/>
<div class="oc-text-input-message"></div>
</div>
<div class="oc-mb-s">
<oc-select
id="login-input"
:disabled="isLoginInputDisabled"
:model-value="selectedLoginValue"
:label="$gettext('Login')"
:options="loginOptions"
:clearable="false"
:read-only="isInputFieldReadOnly('user.accountEnabled')"
@update:model-value="onUpdateLogin"
/>
<div class="oc-text-input-message"></div>
</div>
<quota-select
id="quota-select-form"
:key="'quota-select-' + user.id"
:disabled="isQuotaInputDisabled"
class="oc-mb-s"
:label="$gettext('Personal quota')"
:total-quota="editUser.drive?.quota?.total || 0"
:max-quota="maxQuota"
:fix-message-line="true"
:description-message="
isQuotaInputDisabled && !isInputFieldReadOnly('drive.quota')
? $gettext('To set an individual quota, the user needs to have logged in once.')
: ''
"
:read-only="isInputFieldReadOnly('drive.quota')"
@selected-option-change="changeSelectedQuotaOption"
/>
<group-select
class="oc-mb-s"
:read-only="isInputFieldReadOnly('user.memberOf')"
:selected-groups="editUser.memberOf"
:group-options="groupOptions"
@selected-option-change="changeSelectedGroupOption"
/>
</div>
<compare-save-dialog
class="edit-compare-save-dialog oc-mb-l"
:original-object="compareSaveDialogOriginalObject"
:compare-object="editUser"
:confirm-button-disabled="invalidFormData"
@revert="revertChanges"
@confirm="onEditUser({ user, editUser })"
></compare-save-dialog>
</form>
</div>
</template>
<script lang="ts">
import { computed, defineComponent, PropType, ref, unref } from 'vue'
import * as EmailValidator from 'email-validator'
import UserInfoBox from './UserInfoBox.vue'
import {
CompareSaveDialog,
QuotaSelect,
useUserStore,
useCapabilityStore,
useEventBus,
useMessages,
useConfigStore,
useSpacesStore
} from '@ownclouders/web-pkg'
import GroupSelect from '../GroupSelect.vue'
import { cloneDeep, isEmpty, isEqual, omit } from 'lodash-es'
import {
AppRole,
AppRoleAssignment,
Drive,
Group,
User
} from '@ownclouders/web-client/src/generated'
import { MaybeRef, useClientService } from '@ownclouders/web-pkg'
import { storeToRefs } from 'pinia'
import { diff } from 'deep-object-diff'
import { useUserSettingsStore } from '../../../composables/stores/userSettings'
import { useGettext } from 'vue3-gettext'
export default defineComponent({
name: 'EditPanel',
components: {
UserInfoBox,
CompareSaveDialog,
QuotaSelect,
GroupSelect
},
props: {
user: {
type: Object as PropType<User>,
required: false,
default: null
},
roles: {
type: Array as PropType<AppRole[]>,
required: true
},
groups: {
type: Array as PropType<Group[]>,
required: true
},
applicationId: {
type: String,
required: true
}
},
emits: ['confirm'],
setup(props) {
const capabilityStore = useCapabilityStore()
const capabilityRefs = storeToRefs(capabilityStore)
const clientService = useClientService()
const userStore = useUserStore()
const userSettingsStore = useUserSettingsStore()
const configStore = useConfigStore()
const spacesStore = useSpacesStore()
const eventBus = useEventBus()
const { showErrorMessage } = useMessages()
const { $gettext } = useGettext()
const editUser: MaybeRef<User> = ref({})
const formData = ref({
displayName: {
errorMessage: '',
valid: true
},
userName: {
errorMessage: '',
valid: true
},
email: {
errorMessage: '',
valid: true
}
})
const groupOptions = computed(() => {
const { memberOf: selectedGroups } = unref(editUser)
return props.groups.filter(
(g) => !selectedGroups.some((s) => s.id === g.id) && !g.groupTypes?.includes('ReadOnly')
)
})
const isLoginInputDisabled = computed(() => userStore.user.id === (props.user as User).id)
const isInputFieldReadOnly = (key) => {
return capabilityStore.graphUsersReadOnlyAttributes.includes(key)
}
const onUpdateUserAppRoleAssignments = (user: User, editUser: User) => {
const client = clientService.graphAuthenticated
return client.users.createUserAppRoleAssignment(user.id, {
appRoleId: editUser.appRoleAssignments[0].appRoleId,
resourceId: props.applicationId,
principalId: editUser.id
})
}
const onUpdateUserGroupAssignments = (user: User, editUser: User) => {
const client = clientService.graphAuthenticated
const groupsToAdd = editUser.memberOf.filter(
(editUserGroup) => !user.memberOf.some((g) => g.id === editUserGroup.id)
)
const groupsToDelete = user.memberOf.filter(
(editUserGroup) => !editUser.memberOf.some((g) => g.id === editUserGroup.id)
)
const requests = []
for (const groupToAdd of groupsToAdd) {
requests.push(client.groups.addMember(groupToAdd.id, user.id, configStore.serverUrl))
}
for (const groupToDelete of groupsToDelete) {
requests.push(client.groups.deleteMember(groupToDelete.id, user.id))
}
return Promise.all(requests)
}
const onUpdateUserDrive = async (editUser: User) => {
const client = clientService.graphAuthenticated
const updateDriveResponse = await client.drives.updateDrive(
editUser.drive.id,
{ quota: { total: editUser.drive.quota.total } } as Drive,
{}
)
if (editUser.id === userStore.user.id) {
// Load current user quota
spacesStore.updateSpaceField({
id: editUser.drive.id,
field: 'spaceQuota',
value: updateDriveResponse.data.quota
})
}
}
const onEditUser = async ({ user, editUser }) => {
try {
const client = clientService.graphAuthenticated
const graphEditUserPayloadExtractor = (user) => {
return omit(user, ['drive', 'appRoleAssignments', 'memberOf'])
}
const graphEditUserPayload = diff(
graphEditUserPayloadExtractor(user),
graphEditUserPayloadExtractor(editUser)
)
if (!isEmpty(graphEditUserPayload)) {
await client.users.editUser(editUser.id, graphEditUserPayload)
}
if (!isEqual(user.drive?.quota?.total, editUser.drive?.quota?.total)) {
await onUpdateUserDrive(editUser)
}
if (!isEqual(user.memberOf, editUser.memberOf)) {
await onUpdateUserGroupAssignments(user, editUser)
}
if (
!isEqual(user.appRoleAssignments[0]?.appRoleId, editUser.appRoleAssignments[0]?.appRoleId)
) {
await onUpdateUserAppRoleAssignments(user, editUser)
}
const { data: updatedUser } = await client.users.getUser(user.id)
userSettingsStore.upsertUser(updatedUser)
eventBus.publish('sidebar.entity.saved')
if (userStore.user.id === updatedUser.id) {
userStore.setUser(updatedUser)
}
return updatedUser
} catch (error) {
console.error(error)
showErrorMessage({
title: $gettext('Failed to edit user'),
errors: [error]
})
}
}
return {
maxQuota: capabilityRefs.spacesMaxQuota,
isInputFieldReadOnly,
isLoginInputDisabled,
editUser,
formData,
groupOptions,
clientService,
onEditUser,
// HACK: make sure _user has a proper type
_user: computed(() => props.user as User)
}
},
computed: {
loginOptions() {
return [
{
label: this.$gettext('Allowed'),
value: true
},
{
label: this.$gettext('Forbidden'),
value: false
}
]
},
selectedLoginValue() {
return this.loginOptions.find((option) =>
!('accountEnabled' in this.editUser)
? option.value === true
: this.editUser.accountEnabled === option.value
)
},
translatedRoleOptions() {
return this.roles.map((role) => {
return { ...role, displayName: this.$gettext(role.displayName) }
})
},
selectedRoleValue() {
const assignedRole = this.editUser?.appRoleAssignments?.[0]
return this.translatedRoleOptions.find((role) => role.id === assignedRole?.appRoleId)
},
invalidFormData() {
return Object.values(this.formData)
.map((v: any) => !!v.valid)
.includes(false)
},
showQuota() {
return this.editUser.drive?.quota
},
isQuotaInputDisabled() {
return typeof this.showQuota === 'undefined'
},
compareSaveDialogOriginalObject() {
return cloneDeep(this.user)
}
},
watch: {
user: {
handler: function () {
this.editUser = cloneDeep(this.user)
},
deep: true,
immediate: true
},
editUser: {
handler: function () {
/**
* Property accountEnabled won't be always set, but this still means, that login is allowed.
* So we actually don't need to change the property if missing and not set to forbidden in the UI.
* This also avoids the compare save dialog from displaying that there are unsaved changes.
*/
if (this.editUser.accountEnabled === true && !('accountEnabled' in this.user)) {
delete this.editUser.accountEnabled
}
},
deep: true
}
},
methods: {
changeSelectedQuotaOption(option) {
this.editUser.drive.quota.total = option.value
},
changeSelectedGroupOption(option: Group[]) {
this.editUser.memberOf = option
},
async validateUserName() {
this.formData.userName.valid = false
if (this.editUser.onPremisesSamAccountName.trim() === '') {
this.formData.userName.errorMessage = this.$gettext('User name cannot be empty')
return false
}
if (this.editUser.onPremisesSamAccountName.includes(' ')) {
this.formData.userName.errorMessage = this.$gettext('User name cannot contain white spaces')
return false
}
if (
this.editUser.onPremisesSamAccountName.length &&
!isNaN(parseInt(this.editUser.onPremisesSamAccountName[0]))
) {
this.formData.userName.errorMessage = this.$gettext('User name cannot start with a number')
return false
}
if (this.editUser.onPremisesSamAccountName.length > 255) {
this.formData.userName.errorMessage = this.$gettext(
'User name cannot exceed 255 characters'
)
return false
}
if (this.user.onPremisesSamAccountName !== this.editUser.onPremisesSamAccountName) {
try {
// Validate username by fetching the user. If the request succeeds, we throw a validation error
const client = this.clientService.graphAuthenticated
await client.users.getUser(this.editUser.onPremisesSamAccountName)
this.formData.userName.errorMessage = this.$gettext('User "%{userName}" already exists', {
userName: this.editUser.onPremisesSamAccountName
})
return false
} catch (e) {}
}
this.formData.userName.errorMessage = ''
this.formData.userName.valid = true
return true
},
validateDisplayName() {
this.formData.displayName.valid = false
if (this.editUser.displayName.trim() === '') {
this.formData.displayName.errorMessage = this.$gettext(
'First and last name cannot be empty'
)
return false
}
if (this.editUser.displayName.length > 255) {
this.formData.displayName.errorMessage = this.$gettext(
'First and last name cannot exceed 255 characters'
)
return false
}
this.formData.displayName.errorMessage = ''
this.formData.displayName.valid = true
return true
},
validateEmail() {
this.formData.email.valid = false
if (!EmailValidator.validate(this.editUser.mail)) {
this.formData.email.errorMessage = this.$gettext('Please enter a valid email')
return false
}
this.formData.email.errorMessage = ''
this.formData.email.valid = true
return true
},
revertChanges() {
this.editUser = cloneDeep(this.user)
Object.values(this.formData).forEach((formDataValue: any) => {
formDataValue.valid = true
formDataValue.errorMessage = ''
})
},
onUpdateRole(role) {
if (!this.editUser.appRoleAssignments.length) {
// FIXME: Add resourceId and principalId to be able to remove type cast
this.editUser.appRoleAssignments.push({
appRoleId: role.id
} as AppRoleAssignment)
return
}
this.editUser.appRoleAssignments[0].appRoleId = role.id
},
onUpdatePassword(password) {
this.editUser.passwordProfile = {
password
}
},
onUpdateLogin({ value }) {
this.editUser.accountEnabled = value
}
}
})
</script>
<style lang="scss">
#user-edit-panel {
#user-edit-form {
border-radius: 5px;
}
}
</style>
| owncloud/web/packages/web-app-admin-settings/src/components/Users/SideBar/EditPanel.vue/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/src/components/Users/SideBar/EditPanel.vue",
"repo_id": "owncloud",
"token_count": 6850
} | 767 |
import { computed } from 'vue'
import { useGettext } from 'vue3-gettext'
import { UserAction, useModals, useCapabilityStore } from '@ownclouders/web-pkg'
import LoginModal from '../../../components/Users/LoginModal.vue'
export const useUserActionsEditLogin = () => {
const { dispatchModal } = useModals()
const capabilityStore = useCapabilityStore()
const { $gettext, $ngettext } = useGettext()
const handler = ({ resources }) => {
dispatchModal({
title: $ngettext(
'Edit login for "%{user}"',
'Edit login for %{userCount} users',
resources.length,
{
user: resources[0].displayName,
userCount: resources.length.toString()
}
),
customComponent: LoginModal,
customComponentAttrs: () => ({
users: resources
})
})
}
const actions = computed((): UserAction[] => [
{
name: 'edit-login',
icon: 'login-circle',
componentType: 'button',
class: 'oc-users-actions-edit-login-trigger',
label: () => $gettext('Edit login'),
isVisible: ({ resources }) => {
if (capabilityStore.graphUsersReadOnlyAttributes.includes('user.accountEnabled')) {
return false
}
return resources.length > 0
},
handler
}
])
return {
actions
}
}
| owncloud/web/packages/web-app-admin-settings/src/composables/actions/users/useUserActionsEditLogin.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/src/composables/actions/users/useUserActionsEditLogin.ts",
"repo_id": "owncloud",
"token_count": 535
} | 768 |
<template>
<div>
<app-template
ref="template"
:breadcrumbs="breadcrumbs"
:side-bar-active-panel="sideBarActivePanel"
:side-bar-available-panels="sideBarAvailablePanels"
:side-bar-panel-context="sideBarPanelContext"
:is-side-bar-open="isSideBarOpen"
:side-bar-loading="sideBarLoading"
:show-batch-actions="!!selectedUsers.length"
:batch-actions="batchActions"
:batch-action-items="selectedUsers"
:show-view-options="true"
>
<template #topbarActions>
<div>
<oc-button
v-if="createUserAction.isVisible()"
id="create-user-btn"
class="oc-mr-s"
variation="primary"
appearance="filled"
@click="createUserAction.handler()"
>
<oc-icon :name="createUserAction.icon" />
<span v-text="createUserAction.label()" />
</oc-button>
</div>
</template>
<template #mainContent>
<app-loading-spinner v-if="loadResourcesTask.isRunning || !loadResourcesTask.last" />
<div v-else>
<users-list :roles="roles" :class="{ 'users-table-squashed': isSideBarOpen }">
<template #contextMenu>
<context-actions :items="selectedUsers" />
</template>
<template #filter>
<div class="oc-flex oc-flex-middle">
<div class="oc-mr-m oc-flex oc-flex-middle">
<oc-icon name="filter-2" class="oc-mr-xs" />
<span v-text="$gettext('Filter:')" />
</div>
<item-filter
:allow-multiple="true"
:filter-label="$gettext('Groups')"
:filterable-attributes="['displayName']"
:items="groups"
:option-filter-label="$gettext('Filter groups')"
:show-option-filter="true"
class="oc-mr-s"
display-name-attribute="displayName"
filter-name="groups"
@selection-change="filterGroups"
>
<template #image="{ item }">
<avatar-image :width="32" :userid="item.id" :user-name="item.displayName" />
</template>
<template #item="{ item }">
<div v-text="item.displayName" />
</template>
</item-filter>
<item-filter
:allow-multiple="true"
:filter-label="$gettext('Roles')"
:filterable-attributes="['displayName']"
:items="roles"
:option-filter-label="$gettext('Filter roles')"
:show-option-filter="true"
display-name-attribute="displayName"
filter-name="roles"
@selection-change="filterRoles"
>
<template #image="{ item }">
<avatar-image
:width="32"
:userid="item.id"
:user-name="$gettext(item.displayName)"
/>
</template>
<template #item="{ item }">
<div v-text="$gettext(item.displayName)" />
</template>
</item-filter>
</div>
<div class="oc-flex oc-flex-middle">
<oc-text-input
id="users-filter"
v-model.trim="filterTermDisplayName"
:label="$gettext('Search')"
autocomplete="off"
@keypress.enter="filterDisplayName"
/>
<oc-button
id="users-filter-confirm"
class="oc-ml-xs"
appearance="raw"
@click="filterDisplayName"
>
<oc-icon name="search" fill-type="line" />
</oc-button>
</div>
</template>
<template #noResults>
<no-content-message
v-if="isFilteringMandatory && !isFilteringActive"
icon="error-warning"
>
<template #message>
<span v-text="$gettext('Please specify a filter to see results')" />
</template>
</no-content-message>
<no-content-message v-else icon="user">
<template #message>
<span v-text="$gettext('No users in here')" />
</template>
</no-content-message>
</template>
</users-list>
</div>
</template>
</app-template>
</div>
</template>
<script lang="ts">
import AppTemplate from '../components/AppTemplate.vue'
import UsersList from '../components/Users/UsersList.vue'
import ContextActions from '../components/Users/ContextActions.vue'
import DetailsPanel from '../components/Users/SideBar/DetailsPanel.vue'
import EditPanel from '../components/Users/SideBar/EditPanel.vue'
import {
useUserActionsDelete,
useUserActionsRemoveFromGroups,
useUserActionsAddToGroups,
useUserActionsEditLogin,
useUserActionsEditQuota,
useUserActionsCreateUser
} from '../composables'
import { User, Group } from '@ownclouders/web-client/src/generated'
import {
AppLoadingSpinner,
ItemFilter,
NoContentMessage,
eventBus,
queryItemAsString,
useClientService,
useRoute,
useRouteQuery,
useRouter,
useSideBar,
SideBarPanel,
SideBarPanelContext,
useCapabilityStore,
useConfigStore
} from '@ownclouders/web-pkg'
import {
computed,
defineComponent,
ref,
onBeforeUnmount,
onMounted,
unref,
watch,
nextTick
} from 'vue'
import { useTask } from 'vue-concurrency'
import { useGettext } from 'vue3-gettext'
import Mark from 'mark.js'
import { format } from 'util'
import { omit } from 'lodash-es'
import { storeToRefs } from 'pinia'
import { useUserSettingsStore } from '../composables/stores/userSettings'
export default defineComponent({
name: 'UsersView',
components: {
NoContentMessage,
AppLoadingSpinner,
AppTemplate,
UsersList,
ContextActions,
ItemFilter
},
setup() {
const { $gettext } = useGettext()
const router = useRouter()
const route = useRoute()
const capabilityStore = useCapabilityStore()
const capabilityRefs = storeToRefs(capabilityStore)
const clientService = useClientService()
const configStore = useConfigStore()
const userSettingsStore = useUserSettingsStore()
const { users, selectedUsers } = storeToRefs(userSettingsStore)
const writableGroups = computed<Group[]>(() => {
return unref(groups).filter((g) => !g.groupTypes?.includes('ReadOnly'))
})
const { actions: createUserActions } = useUserActionsCreateUser()
const createUserAction = computed(() => unref(createUserActions)[0])
const { actions: deleteActions } = useUserActionsDelete()
const { actions: removeFromGroupsActions } = useUserActionsRemoveFromGroups({
groups: writableGroups
})
const { actions: addToGroupsActions } = useUserActionsAddToGroups({
groups: writableGroups
})
const { actions: editLoginActions } = useUserActionsEditLogin()
const { actions: editQuotaActions } = useUserActionsEditQuota()
const groups = ref([])
const roles = ref([])
const additionalUserDataLoadedForUserIds = ref([])
const applicationId = ref()
const selectedUserIds = computed(() =>
unref(selectedUsers).map((selectedUser) => selectedUser.id)
)
const isFilteringMandatory = ref(configStore.options.userListRequiresFilter)
const sideBarLoading = ref(false)
const template = ref()
const displayNameQuery = useRouteQuery('q_displayName')
const filterTermDisplayName = ref(queryItemAsString(unref(displayNameQuery)))
const markInstance = ref(null)
let editQuotaActionEventToken: string
const loadGroupsTask = useTask(function* (signal) {
const groupsResponse = yield clientService.graphAuthenticated.groups.listGroups(
'displayName',
['members']
)
groups.value = groupsResponse.data.value
})
const loadAppRolesTask = useTask(function* (signal) {
const applicationsResponse =
yield clientService.graphAuthenticated.applications.listApplications()
roles.value = applicationsResponse.data.value[0].appRoles
applicationId.value = applicationsResponse.data.value[0].id
})
const loadUsersTask = useTask(function* (signal) {
if (unref(isFilteringMandatory) && !unref(isFilteringActive)) {
return userSettingsStore.setUsers([])
}
const filter = Object.values(filters)
.reduce((acc, f: any) => {
if ('value' in f) {
if (unref(f.value)) {
acc.push(format(f.query, unref(f.value)))
}
return acc
}
const str = unref(f.ids)
.map((id) => format(f.query, id))
.join(' or ')
if (str) {
acc.push(`(${str})`)
}
return acc
}, [])
.filter(Boolean)
.join(' and ')
const usersResponse = yield clientService.graphAuthenticated.users.listUsers(
'displayName',
filter,
['appRoleAssignments']
)
userSettingsStore.setUsers(usersResponse.data.value || [])
})
const loadResourcesTask = useTask(function* (signal) {
yield loadUsersTask.perform()
yield loadGroupsTask.perform()
yield loadAppRolesTask.perform()
})
/**
* This function reloads the user with expanded attributes,
* this is necessary as we don't load all the data while listing the users
* for performance reasons
*/
const loadAdditionalUserDataTask = useTask(function* (signal, user, forceReload = false) {
/**
* Prevent load additional user data multiple times if not needed
*/
if (!forceReload && unref(additionalUserDataLoadedForUserIds).includes(user.id)) {
return
}
const { data } = yield clientService.graphAuthenticated.users.getUser(user.id)
unref(additionalUserDataLoadedForUserIds).push(user.id)
Object.assign(user, data)
})
const resetPagination = () => {
return router.push({ ...unref(route), query: { ...unref(route).query, page: '1' } })
}
const filters = {
groups: {
param: useRouteQuery('q_groups'),
query: `memberOf/any(m:m/id eq '%s')`,
ids: ref([])
},
roles: {
param: useRouteQuery('q_roles'),
query: `appRoleAssignments/any(m:m/appRoleId eq '%s')`,
ids: ref([])
},
displayName: {
param: useRouteQuery('q_displayName'),
query: `contains(displayName,'%s')`,
value: ref('')
}
}
const isFilteringActive = computed(() => {
return (
unref(filters.groups.ids)?.length ||
unref(filters.roles.ids)?.length ||
unref(filters.displayName.value)?.length
)
})
const filterGroups = (groups) => {
filters.groups.ids.value = groups.map((g) => g.id)
loadUsersTask.perform()
userSettingsStore.setSelectedUsers([])
additionalUserDataLoadedForUserIds.value = []
return resetPagination()
}
const filterRoles = (roles) => {
filters.roles.ids.value = roles.map((r) => r.id)
loadUsersTask.perform()
userSettingsStore.setSelectedUsers([])
additionalUserDataLoadedForUserIds.value = []
return resetPagination()
}
const filterDisplayName = async () => {
await router.push({
...unref(route),
query: {
...omit(unref(route).query, 'q_displayName'),
...(unref(filterTermDisplayName) && { q_displayName: unref(filterTermDisplayName) })
}
})
filters.displayName.value.value = unref(filterTermDisplayName)
loadUsersTask.perform()
userSettingsStore.setSelectedUsers([])
additionalUserDataLoadedForUserIds.value = []
return resetPagination()
}
watch(selectedUserIds, async () => {
sideBarLoading.value = true
await Promise.all(
unref(selectedUsers).map((user) => loadAdditionalUserDataTask.perform(user))
)
sideBarLoading.value = false
})
const batchActions = computed(() => {
return [
...unref(deleteActions),
...unref(editQuotaActions),
...unref(addToGroupsActions),
...unref(removeFromGroupsActions),
...unref(editLoginActions)
].filter((item) => item.isVisible({ resources: unref(selectedUsers) }))
})
const updateSpaceQuota = ({ spaceId, quota }) => {
const user = unref(users).find((u) => u.drive?.id === spaceId)
user.drive.quota = quota
userSettingsStore.upsertUser(user)
}
onMounted(async () => {
for (const f in filters) {
if (unref(filters[f]).hasOwnProperty('ids')) {
filters[f].ids.value = queryItemAsString(unref(filters[f].param))?.split('+') || []
}
if (unref(filters[f]).hasOwnProperty('value')) {
filters[f].value.value = queryItemAsString(unref(filters[f].param))
}
}
await loadResourcesTask.perform()
watch(
[users, displayNameQuery],
async () => {
await nextTick()
markInstance.value = new Mark('.mark-element')
unref(markInstance)?.unmark()
unref(markInstance)?.mark(queryItemAsString(unref(displayNameQuery)) || '', {
element: 'span',
className: 'mark-highlight'
})
},
{
immediate: true
}
)
editQuotaActionEventToken = eventBus.subscribe(
'app.admin-settings.users.user.quota.updated',
updateSpaceQuota
)
})
onBeforeUnmount(() => {
userSettingsStore.reset()
eventBus.unsubscribe('app.admin-settings.users.user.quota.updated', editQuotaActionEventToken)
})
const sideBarPanelContext = computed<SideBarPanelContext<unknown, unknown, User>>(() => {
return {
parent: null,
items: unref(selectedUsers)
}
})
const sideBarAvailablePanels = [
{
name: 'DetailsPanel',
icon: 'user',
title: () => $gettext('Details'),
component: DetailsPanel,
componentAttrs: ({ items }) => ({
user: items.length === 1 ? items[0] : null,
users: items,
roles: unref(roles)
}),
isRoot: () => true,
isVisible: () => true
},
{
name: 'EditPanel',
icon: 'pencil',
title: () => $gettext('Edit user'),
component: EditPanel,
isVisible: ({ items }) => items.length === 1,
componentAttrs: ({ items }) => ({
user: items.length === 1 ? items[0] : null,
roles: unref(roles),
groups: unref(groups),
applicationId: unref(applicationId)
})
}
] satisfies SideBarPanel<unknown, unknown, User>[]
return {
...useSideBar(),
maxQuota: capabilityRefs.spacesMaxQuota,
template,
selectedUsers,
sideBarLoading,
users,
roles,
groups,
loadResourcesTask,
loadAdditionalUserDataTask,
clientService,
batchActions,
filterGroups,
filterRoles,
filterDisplayName,
filterTermDisplayName,
writableGroups,
isFilteringActive,
isFilteringMandatory,
sideBarPanelContext,
sideBarAvailablePanels,
createUserAction,
userSettingsStore
}
},
computed: {
breadcrumbs() {
return [
{ text: this.$gettext('Administration Settings'), to: { path: '/admin-settings' } },
{
text: this.$gettext('Users'),
onClick: () => {
this.userSettingsStore.setSelectedUsers([])
this.loadResourcesTask.perform()
}
}
]
}
}
})
</script>
<style lang="scss" scoped>
#users-filter {
width: 16rem;
&-confirm {
margin-top: calc(0.2rem + var(--oc-font-size-default));
}
}
</style>
| owncloud/web/packages/web-app-admin-settings/src/views/Users.vue/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/src/views/Users.vue",
"repo_id": "owncloud",
"token_count": 7465
} | 769 |
import SpacesList from '../../../../src/components/Spaces/SpacesList.vue'
import { defaultComponentMocks, defaultPlugins, mount, shallowMount } from 'web-test-helpers'
import { SortDir, eventBus, queryItemAsString } from '@ownclouders/web-pkg'
import { displayPositionedDropdown } from '@ownclouders/web-pkg'
import { SideBarEventTopics } from '@ownclouders/web-pkg'
import { nextTick } from 'vue'
import { useSpaceSettingsStore } from '../../../../src/composables'
import { mock } from 'vitest-mock-extended'
import { OcTable } from 'design-system/src/components'
import { SpaceResource } from '@ownclouders/web-client'
const spaceMocks = [
{
id: '1',
name: '1 Some space',
disabled: false,
spaceRoles: {
manager: [
{ id: 'user1', displayName: 'user1' },
{ id: 'user2', displayName: 'user2' },
{ id: 'user3', displayName: 'user3' }
],
editor: [],
viewer: []
},
spaceQuota: {
total: 1000000000,
used: 0,
remaining: 1000000000
}
},
{
id: '2',
name: '2 Another space',
disabled: true,
spaceRoles: {
manager: [
{ id: 'user1', displayName: 'user1' },
{ id: 'user2', displayName: 'user2' },
{ id: 'user3', displayName: 'user3' }
],
editor: [{ id: 'user4', displayName: 'user4' }],
viewer: [{ id: 'user5', displayName: 'user5' }]
},
spaceQuota: {
total: 2000000000,
used: 500000000,
remaining: 1500000000
}
}
]
const selectors = {
ocTableStub: 'oc-table-stub'
}
vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({
...(await importOriginal<any>()),
displayPositionedDropdown: vi.fn(),
queryItemAsString: vi.fn()
}))
describe('SpacesList', () => {
it('should render all spaces in a table', () => {
const { wrapper } = getWrapper({ spaces: spaceMocks })
expect(wrapper.html()).toMatchSnapshot()
})
it.each(['name', 'members', 'totalQuota', 'usedQuota', 'remainingQuota', 'status'])(
'sorts by property "%s"',
async (prop) => {
const { wrapper } = getWrapper({ mountType: shallowMount, spaces: spaceMocks })
wrapper.vm.sortBy = prop
await wrapper.vm.$nextTick()
expect(
(
wrapper.findComponent<typeof OcTable>(selectors.ocTableStub).props()
.data[0] as SpaceResource
).id
).toBe(spaceMocks[0].id)
wrapper.vm.sortDir = SortDir.Desc
await wrapper.vm.$nextTick()
expect(
(
wrapper.findComponent<typeof OcTable>(selectors.ocTableStub).props()
.data[0] as SpaceResource
).id
).toBe(spaceMocks[1].id)
}
)
it('should set the sort parameters accordingly when calling "handleSort"', () => {
const { wrapper } = getWrapper({ spaces: [spaceMocks[0]] })
const sortBy = 'members'
const sortDir = 'desc'
wrapper.vm.handleSort({ sortBy, sortDir })
expect(wrapper.vm.sortBy).toEqual(sortBy)
expect(wrapper.vm.sortDir).toEqual(sortDir)
})
it('shows only filtered spaces if filter applied', async () => {
const { wrapper } = getWrapper({ spaces: spaceMocks })
wrapper.vm.filterTerm = 'Another'
await nextTick()
expect(wrapper.vm.items).toEqual([spaceMocks[1]])
})
it('should show the context menu on right click', async () => {
const spyDisplayPositionedDropdown = vi.mocked(displayPositionedDropdown)
// .mockImplementation(() => undefined)
const { wrapper } = getWrapper({ spaces: spaceMocks })
await wrapper.find(`[data-item-id="${spaceMocks[0].id}"]`).trigger('contextmenu')
expect(spyDisplayPositionedDropdown).toHaveBeenCalledTimes(1)
})
it('should show the context menu on context menu button click', async () => {
const spyDisplayPositionedDropdown = vi.mocked(displayPositionedDropdown)
const { wrapper } = getWrapper({ spaces: spaceMocks })
await wrapper.find('.spaces-table-btn-action-dropdown').trigger('click')
expect(spyDisplayPositionedDropdown).toHaveBeenCalledTimes(1)
})
it('should show the space details on details button click', async () => {
const eventBusSpy = vi.spyOn(eventBus, 'publish')
const { wrapper } = getWrapper({ spaces: spaceMocks })
await wrapper.find('.spaces-table-btn-details').trigger('click')
expect(eventBusSpy).toHaveBeenCalledWith(SideBarEventTopics.open)
})
describe('toggle selection', () => {
describe('selectSpaces method', () => {
it('selects all spaces', () => {
const spaces = [
mock<SpaceResource>({ id: '1', name: 'Some Space' }),
mock<SpaceResource>({ id: '2', name: 'Some other Space' })
]
const { wrapper } = getWrapper({ mountType: shallowMount, spaces })
wrapper.vm.selectSpaces(spaces)
const { setSelectedSpaces } = useSpaceSettingsStore()
expect(setSelectedSpaces).toHaveBeenCalledWith(spaces)
})
})
describe('selectSpace ', () => {
it('selects a space', async () => {
const spaces = [mock<SpaceResource>({ id: '1', name: 'Some Space' })]
const { wrapper } = getWrapper({ mountType: shallowMount, spaces })
wrapper.vm.selectSpace(spaces[0])
const { addSelectedSpace } = useSpaceSettingsStore()
expect(addSelectedSpace).toHaveBeenCalledWith(spaces[0])
})
it('de-selects a selected space', () => {
const spaces = [mock<SpaceResource>({ id: '1', name: 'Some Space' })]
const { wrapper } = getWrapper({ mountType: shallowMount, spaces, selectedSpaces: spaces })
wrapper.vm.selectSpace(spaces[0])
const { setSelectedSpaces } = useSpaceSettingsStore()
expect(setSelectedSpaces).toHaveBeenCalledWith([])
})
})
describe('unselectAllSpaces method', () => {
it('de-selects all selected spaces', () => {
const spaces = [mock<SpaceResource>({ id: '1', name: 'Some Space' })]
const { wrapper } = getWrapper({ mountType: shallowMount, spaces })
wrapper.vm.unselectAllSpaces()
const { setSelectedSpaces } = useSpaceSettingsStore()
expect(setSelectedSpaces).toHaveBeenCalledWith([])
})
})
})
})
function getWrapper({ mountType = mount, spaces = [], selectedSpaces = [] } = {}) {
vi.mocked(queryItemAsString).mockImplementationOnce(() => '1')
vi.mocked(queryItemAsString).mockImplementationOnce(() => '100')
const mocks = defaultComponentMocks()
return {
wrapper: mountType(SpacesList, {
props: {
headerPosition: 0
},
global: {
plugins: [
...defaultPlugins({
piniaOptions: {
spaceSettingsStore: { spaces, selectedSpaces }
}
})
],
mocks,
provide: mocks,
stubs: {
OcCheckbox: true
}
}
})
}
}
| owncloud/web/packages/web-app-admin-settings/tests/unit/components/Spaces/SpacesList.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/components/Spaces/SpacesList.spec.ts",
"repo_id": "owncloud",
"token_count": 2740
} | 770 |
import { useGroupActionsDelete } from '../../../../../src/composables/actions/groups/useGroupActionsDelete'
import { mock } from 'vitest-mock-extended'
import { unref } from 'vue'
import { Group } from '@ownclouders/web-client/src/generated'
import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers'
import { useGroupSettingsStore } from '../../../../../src/composables'
describe('useGroupActionsDelete', () => {
describe('method "isVisible"', () => {
it.each([
{ resources: [], isVisible: false },
{ resources: [mock<Group>({ groupTypes: [] })], isVisible: true },
{
resources: [mock<Group>({ groupTypes: [] }), mock<Group>({ groupTypes: [] })],
isVisible: true
}
])('should only return true if 1 or more groups are selected', ({ resources, isVisible }) => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources })).toEqual(isVisible)
}
})
})
it('should return false for read-only groups', () => {
getWrapper({
setup: ({ actions }) => {
const resources = [mock<Group>({ groupTypes: ['ReadOnly'] })]
expect(unref(actions)[0].isVisible({ resources })).toBeFalsy()
}
})
})
})
describe('method "deleteGroups"', () => {
it('should successfully delete all given gropups and reload the groups list', () => {
getWrapper({
setup: async ({ deleteGroups }, { clientService }) => {
const group = mock<Group>({ id: '1' })
await deleteGroups([group])
expect(clientService.graphAuthenticated.groups.deleteGroup).toHaveBeenCalledWith(group.id)
const { removeGroups } = useGroupSettingsStore()
expect(removeGroups).toHaveBeenCalled()
}
})
})
it('should handle errors', () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
getWrapper({
setup: async ({ deleteGroups }, { clientService }) => {
clientService.graphAuthenticated.groups.deleteGroup.mockRejectedValue({})
const group = mock<Group>({ id: '1' })
await deleteGroups([group])
expect(clientService.graphAuthenticated.groups.deleteGroup).toHaveBeenCalledWith(group.id)
const { removeGroups } = useGroupSettingsStore()
expect(removeGroups).toHaveBeenCalled()
}
})
})
})
})
function getWrapper({
setup
}: {
setup: (
instance: ReturnType<typeof useGroupActionsDelete>,
{
clientService
}: {
clientService: ReturnType<typeof defaultComponentMocks>['$clientService']
}
) => void
}) {
const mocks = defaultComponentMocks()
return {
wrapper: getComposableWrapper(
() => {
const instance = useGroupActionsDelete()
setup(instance, { clientService: mocks.$clientService })
},
{ mocks, provide: mocks }
)
}
}
| owncloud/web/packages/web-app-admin-settings/tests/unit/composables/actions/groups/useGroupActionsDelete.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/composables/actions/groups/useGroupActionsDelete.spec.ts",
"repo_id": "owncloud",
"token_count": 1162
} | 771 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Users view > list view > renders initially warning if filters are mandatory 1`] = `
"<div data-v-32efd9c6="">
<main data-v-32efd9c6="" class="oc-flex oc-height-1-1 app-content oc-width-1-1">
<div id="admin-settings-wrapper" class="oc-width-expand oc-height-1-1 oc-position-relative">
<div id="admin-settings-app-bar" class="oc-app-bar oc-py-s">
<div class="admin-settings-app-bar-controls oc-flex oc-flex-between oc-flex-middle">
<oc-breadcrumb-stub items="[object Object],[object Object]" id="admin-settings-breadcrumb" variation="default" contextmenupadding="medium" maxwidth="-1" truncationoffset="2" showcontextactions="false" class="oc-flex oc-flex-middle"></oc-breadcrumb-stub>
<portal-target name="app.runtime.mobile.nav"></portal-target>
<div class="oc-flex">
<view-options-stub perpagestorageprefix="admin-settings" hashiddenfiles="false" hasfileextensions="false" haspagination="true" paginationoptions="20,50,100,250" perpagequeryname="items-per-page" perpagedefault="50" viewmodedefault="resource-table" viewmodes=""></view-options-stub>
</div>
</div>
<div class="admin-settings-app-bar-actions oc-flex oc-flex-middle oc-mt-xs">
<div data-v-32efd9c6="">
<oc-button-stub data-v-32efd9c6="" type="button" disabled="false" size="medium" submit="button" variation="primary" appearance="filled" justifycontent="center" gapsize="medium" showspinner="false" id="create-user-btn" class="oc-mr-s"></oc-button-stub>
</div>
<!--v-if-->
</div>
</div>
<div data-v-32efd9c6="">
<div data-v-32efd9c6="" id="user-list" class="">
<div class="user-filters oc-flex oc-flex-between oc-flex-wrap oc-flex-bottom oc-mx-m oc-mb-m">
<div data-v-32efd9c6="" class="oc-flex oc-flex-middle">
<div data-v-32efd9c6="" class="oc-mr-m oc-flex oc-flex-middle"><span data-v-32efd9c6="" class="oc-icon oc-icon-m oc-icon-passive oc-mr-xs"><!----></span> <span data-v-32efd9c6="">Filter:</span></div>
<item-filter-stub data-v-32efd9c6="" filterlabel="Groups" items="undefined" filtername="groups" optionfilterlabel="Filter groups" showoptionfilter="true" allowmultiple="true" idattribute="id" displaynameattribute="displayName" filterableattributes="displayName" closeonclick="false" class="oc-mr-s"></item-filter-stub>
<item-filter-stub data-v-32efd9c6="" filterlabel="Roles" items="undefined" filtername="roles" optionfilterlabel="Filter roles" showoptionfilter="true" allowmultiple="true" idattribute="id" displaynameattribute="displayName" filterableattributes="displayName" closeonclick="false"></item-filter-stub>
</div>
<div data-v-32efd9c6="" class="oc-flex oc-flex-middle">
<div data-v-32efd9c6="" class=""><label class="oc-label" for="users-filter">Search</label>
<div class="oc-position-relative">
<!--v-if--> <input id="users-filter" modelmodifiers="[object Object]" autocomplete="off" aria-invalid="false" class="oc-text-input oc-input oc-rounded" type="text">
<!--v-if-->
</div>
<!--v-if-->
<!--v-if-->
</div>
<oc-button-stub data-v-32efd9c6="" type="button" disabled="false" size="medium" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" id="users-filter-confirm" class="oc-ml-xs"></oc-button-stub>
</div>
</div>
<no-content-message-stub data-v-32efd9c6="" icon="error-warning" iconfilltype="fill"></no-content-message-stub>
</div>
</div>
</div>
<!--v-if-->
</main>
</div>"
`;
exports[`Users view > list view > renders list initially 1`] = `
"<div data-v-32efd9c6="">
<main data-v-32efd9c6="" class="oc-flex oc-height-1-1 app-content oc-width-1-1">
<div id="admin-settings-wrapper" class="oc-width-expand oc-height-1-1 oc-position-relative">
<div id="admin-settings-app-bar" class="oc-app-bar oc-py-s">
<div class="admin-settings-app-bar-controls oc-flex oc-flex-between oc-flex-middle">
<oc-breadcrumb-stub items="[object Object],[object Object]" id="admin-settings-breadcrumb" variation="default" contextmenupadding="medium" maxwidth="-1" truncationoffset="2" showcontextactions="false" class="oc-flex oc-flex-middle"></oc-breadcrumb-stub>
<portal-target name="app.runtime.mobile.nav"></portal-target>
<div class="oc-flex">
<view-options-stub perpagestorageprefix="admin-settings" hashiddenfiles="false" hasfileextensions="false" haspagination="true" paginationoptions="20,50,100,250" perpagequeryname="items-per-page" perpagedefault="50" viewmodedefault="resource-table" viewmodes=""></view-options-stub>
</div>
</div>
<div class="admin-settings-app-bar-actions oc-flex oc-flex-middle oc-mt-xs">
<div data-v-32efd9c6="">
<oc-button-stub data-v-32efd9c6="" type="button" disabled="false" size="medium" submit="button" variation="primary" appearance="filled" justifycontent="center" gapsize="medium" showspinner="false" id="create-user-btn" class="oc-mr-s"></oc-button-stub>
</div>
<!--v-if-->
</div>
</div>
<div data-v-32efd9c6="">
<div data-v-32efd9c6="" id="user-list" class="">
<div class="user-filters oc-flex oc-flex-between oc-flex-wrap oc-flex-bottom oc-mx-m oc-mb-m">
<div data-v-32efd9c6="" class="oc-flex oc-flex-middle">
<div data-v-32efd9c6="" class="oc-mr-m oc-flex oc-flex-middle"><span data-v-32efd9c6="" class="oc-icon oc-icon-m oc-icon-passive oc-mr-xs"><!----></span> <span data-v-32efd9c6="">Filter:</span></div>
<item-filter-stub data-v-32efd9c6="" filterlabel="Groups" items="undefined" filtername="groups" optionfilterlabel="Filter groups" showoptionfilter="true" allowmultiple="true" idattribute="id" displaynameattribute="displayName" filterableattributes="displayName" closeonclick="false" class="oc-mr-s"></item-filter-stub>
<item-filter-stub data-v-32efd9c6="" filterlabel="Roles" items="undefined" filtername="roles" optionfilterlabel="Filter roles" showoptionfilter="true" allowmultiple="true" idattribute="id" displaynameattribute="displayName" filterableattributes="displayName" closeonclick="false"></item-filter-stub>
</div>
<div data-v-32efd9c6="" class="oc-flex oc-flex-middle">
<div data-v-32efd9c6="" class=""><label class="oc-label" for="users-filter">Search</label>
<div class="oc-position-relative">
<!--v-if--> <input id="users-filter" modelmodifiers="[object Object]" autocomplete="off" aria-invalid="false" class="oc-text-input oc-input oc-rounded" type="text">
<!--v-if-->
</div>
<!--v-if-->
<!--v-if-->
</div>
<oc-button-stub data-v-32efd9c6="" type="button" disabled="false" size="medium" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" id="users-filter-confirm" class="oc-ml-xs"></oc-button-stub>
</div>
</div>
<table class="oc-table oc-table-hover oc-table-sticky has-item-context-menu users-table">
<thead class="oc-thead">
<tr tabindex="-1" class="oc-table-header-row">
<th class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-shrink oc-text-nowrap oc-th oc-table-header-cell oc-table-header-cell-select oc-pl-s" style="top: 0px;"><span class="oc-table-thead-content"><span class="oc-ml-s"><input id="oc-checkbox-1" type="checkbox" name="checkbox" class="oc-checkbox oc-rounded oc-checkbox-l"> <label for="oc-checkbox-1" class="oc-invisible-sr oc-cursor-pointer">Select all users</label></span></span>
<!--v-if-->
</th>
<th class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-shrink oc-text-nowrap oc-th oc-table-header-cell oc-table-header-cell-avatar" style="top: 0px;"><span class="oc-table-thead-content header-text"></span>
<!--v-if-->
</th>
<th class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-auto oc-text-nowrap oc-th oc-table-header-cell oc-table-header-cell-onPremisesSamAccountName" style="top: 0px;" aria-sort="ascending"><span class="oc-table-thead-content header-text">User name</span>
<oc-button-stub type="button" disabled="false" size="medium" arialabel="Sort by onPremisesSamAccountName" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" class="oc-button-sort"></oc-button-stub>
</th>
<th class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-auto oc-text-nowrap oc-th oc-table-header-cell oc-table-header-cell-displayName" style="top: 0px;" aria-sort="none"><span class="oc-table-thead-content header-text">First and last name</span>
<oc-button-stub type="button" disabled="false" size="medium" arialabel="Sort by displayName" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" class="oc-invisible-sr oc-button-sort"></oc-button-stub>
</th>
<th class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-auto oc-text-nowrap oc-th oc-table-header-cell oc-table-header-cell-mail" style="top: 0px;" aria-sort="none"><span class="oc-table-thead-content header-text">Email</span>
<oc-button-stub type="button" disabled="false" size="medium" arialabel="Sort by mail" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" class="oc-invisible-sr oc-button-sort"></oc-button-stub>
</th>
<th class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-auto oc-text-nowrap oc-th oc-table-header-cell oc-table-header-cell-role" style="top: 0px;" aria-sort="none"><span class="oc-table-thead-content header-text">Role</span>
<oc-button-stub type="button" disabled="false" size="medium" arialabel="Sort by role" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" class="oc-invisible-sr oc-button-sort"></oc-button-stub>
</th>
<th class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-auto oc-text-nowrap oc-th oc-table-header-cell oc-table-header-cell-accountEnabled" style="top: 0px;" aria-sort="none"><span class="oc-table-thead-content header-text">Login</span>
<oc-button-stub type="button" disabled="false" size="medium" arialabel="Sort by accountEnabled" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" class="oc-invisible-sr oc-button-sort"></oc-button-stub>
</th>
<th class="oc-table-cell oc-table-cell-align-right oc-table-cell-align-middle oc-table-cell-width-auto oc-text-nowrap oc-th oc-table-header-cell oc-table-header-cell-actions oc-pr-s" style="top: 0px;"><span class="oc-table-thead-content header-text">Actions</span>
<!--v-if-->
</th>
</tr>
</thead>
<tbody class="has-item-context-menu">
<tr tabindex="-1" class="oc-tbody-tr oc-tbody-tr-1" data-item-id="1" draggable="false">
<td class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-shrink oc-td oc-table-data-cell oc-table-data-cell-select oc-pl-s"><span class="oc-ml-s"><input id="oc-checkbox-2" type="checkbox" name="checkbox" class="oc-checkbox oc-rounded oc-checkbox-l" value="[object Object]"> <label for="oc-checkbox-2" class="oc-invisible-sr oc-cursor-pointer">Select Admin</label></span></td>
<td class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-shrink oc-td oc-table-data-cell oc-table-data-cell-avatar">
<avatar-image width="32" userid="1" user-name="Admin"></avatar-image>
</td>
<td class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-auto oc-td oc-table-data-cell oc-table-data-cell-onPremisesSamAccountName"></td>
<td class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-auto oc-td oc-table-data-cell oc-table-data-cell-displayName mark-element">Admin</td>
<td class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-auto oc-td oc-table-data-cell oc-table-data-cell-mail">admin@example.org</td>
<td class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-auto oc-td oc-table-data-cell oc-table-data-cell-role">Admin</td>
<td class="oc-table-cell oc-table-cell-align-left oc-table-cell-align-middle oc-table-cell-width-auto oc-td oc-table-data-cell oc-table-data-cell-accountEnabled"><span class="oc-flex oc-flex-middle"><span class="oc-icon oc-icon-m oc-icon-passive oc-mr-s"><!----></span><span>Allowed</span></span></td>
<td class="oc-table-cell oc-table-cell-align-right oc-table-cell-align-middle oc-table-cell-width-auto oc-td oc-table-data-cell oc-table-data-cell-actions oc-pr-s">
<oc-button-stub type="button" disabled="false" size="medium" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" class="oc-mr-xs quick-action-button oc-p-xs users-table-btn-details"></oc-button-stub>
<oc-button-stub type="button" disabled="false" size="medium" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" class="oc-mr-xs quick-action-button oc-p-xs users-table-btn-edit"></oc-button-stub>
<oc-button-stub type="button" disabled="false" size="medium" arialabel="Show context menu" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" id="context-menu-trigger-1" class="users-table-btn-action-dropdown"></oc-button-stub>
</td>
</tr>
</tbody>
<tfoot class="oc-table-footer">
<tr class="oc-table-footer-row">
<td colspan="8" class="oc-table-footer-cell">
<!-- @slot Footer of the table -->
<!--v-if-->
<div class="oc-text-nowrap oc-text-center oc-width-1-1 oc-my-s">
<p class="oc-text-muted">1 users in total</p>
</div>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<!--v-if-->
</main>
</div>"
`;
| owncloud/web/packages/web-app-admin-settings/tests/unit/views/__snapshots__/Users.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/views/__snapshots__/Users.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 6709
} | 772 |
<template>
<iframe
v-if="appUrl && method === 'GET'"
:src="appUrl"
class="oc-width-1-1 oc-height-1-1"
:title="iFrameTitle"
allowfullscreen
/>
<div v-if="appUrl && method === 'POST' && formParameters" class="oc-height-1-1 oc-width-1-1">
<form :action="appUrl" target="app-iframe" method="post">
<input ref="subm" type="submit" :value="formParameters" class="oc-hidden" />
<div v-for="(item, key, index) in formParameters" :key="index">
<input :name="key" :value="item" type="hidden" />
</div>
</form>
<iframe
name="app-iframe"
class="oc-width-1-1 oc-height-1-1"
:title="iFrameTitle"
allowfullscreen
/>
</div>
</template>
<script lang="ts">
import { stringify } from 'qs'
import { PropType, computed, defineComponent, unref, nextTick, ref, watch, VNodeRef } from 'vue'
import { useTask } from 'vue-concurrency'
import { useGettext } from 'vue3-gettext'
import { Resource, SpaceResource } from '@ownclouders/web-client/src'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import {
isSameResource,
queryItemAsString,
useCapabilityStore,
useConfigStore,
useMessages,
useRequest,
useRouteQuery
} from '@ownclouders/web-pkg'
import {
isProjectSpaceResource,
isPublicSpaceResource,
isShareSpaceResource
} from '@ownclouders/web-client/src/helpers'
export default defineComponent({
name: 'ExternalApp',
props: {
space: { type: Object as PropType<SpaceResource>, required: true },
resource: { type: Object as PropType<Resource>, required: true },
isReadOnly: { type: Boolean, required: true }
},
emits: ['update:applicationName'],
setup(props, { emit }) {
const language = useGettext()
const { showErrorMessage } = useMessages()
const capabilityStore = useCapabilityStore()
const configStore = useConfigStore()
const { $gettext } = language
const { makeRequest } = useRequest()
const appNameQuery = useRouteQuery('app')
const appUrl = ref()
const formParameters = ref({})
const method = ref()
const subm: VNodeRef = ref()
const applicationName = computed(() => {
const appName = queryItemAsString(unref(appNameQuery))
emit('update:applicationName', appName)
return appName
})
const iFrameTitle = computed(() => {
return $gettext('"%{appName}" app content area', {
appName: unref(applicationName)
})
})
const errorPopup = (error) => {
showErrorMessage({
title: $gettext('An error occurred'),
desc: error,
errors: [error]
})
}
const loadAppUrl = useTask(function* (signal, viewMode: string) {
try {
if (props.isReadOnly && viewMode === 'write') {
showErrorMessage({ title: $gettext('Cannot open file in edit mode as it is read-only') })
return
}
const fileId = props.resource.fileId
const baseUrl = urlJoin(
configStore.serverUrl,
capabilityStore.filesAppProviders[0].open_url
)
const query = stringify({
file_id: fileId,
lang: language.current,
...(unref(applicationName) && { app_name: unref(applicationName) }),
...(viewMode && { view_mode: viewMode })
})
const url = `${baseUrl}?${query}`
const response = yield makeRequest('POST', url, {
validateStatus: () => true
})
if (response.status !== 200) {
switch (response.status) {
case 425:
errorPopup(
$gettext(
'This file is currently being processed and is not yet available for use. Please try again shortly.'
)
)
break
default:
errorPopup(response.data?.message)
}
const error = new Error('Error fetching app information')
throw error
}
if (!response.data.app_url || !response.data.method) {
const error = new Error('Error in app server response')
throw error
}
appUrl.value = response.data.app_url
method.value = response.data.method
if (response.data.form_parameters) {
formParameters.value = response.data.form_parameters
}
if (method.value === 'POST' && formParameters.value) {
// eslint-disable-next-line vue/valid-next-tick
yield nextTick()
unref(subm).click()
}
} catch (e) {
console.error('web-app-external error', e)
throw e
}
}).restartable()
const determineOpenAsPreview = (appName: string) => {
const openAsPreview = configStore.options.editor.openAsPreview
return (
openAsPreview === true || (Array.isArray(openAsPreview) && openAsPreview.includes(appName))
)
}
// switch to write mode when edit is clicked
const catchClickMicrosoftEdit = (event) => {
try {
if (JSON.parse(event.data)?.MessageId === 'UI_Edit') {
loadAppUrl.perform('write')
}
} catch (e) {}
}
watch(
applicationName,
(newAppName, oldAppName) => {
if (determineOpenAsPreview(newAppName) && newAppName !== oldAppName) {
window.addEventListener('message', catchClickMicrosoftEdit)
} else {
window.removeEventListener('message', catchClickMicrosoftEdit)
}
},
{
immediate: true
}
)
watch(
[props.resource],
([newResource], [oldResource]) => {
if (isSameResource(newResource, oldResource)) {
return
}
let viewMode = props.isReadOnly ? 'view' : 'write'
if (
determineOpenAsPreview(unref(applicationName)) &&
(isShareSpaceResource(props.space) ||
isPublicSpaceResource(props.space) ||
isProjectSpaceResource(props.space))
) {
viewMode = 'view'
}
loadAppUrl.perform(viewMode)
},
{ immediate: true, deep: true }
)
return {
appUrl,
formParameters,
iFrameTitle,
method,
subm
}
}
})
</script>
| owncloud/web/packages/web-app-external/src/App.vue/0 | {
"file_path": "owncloud/web/packages/web-app-external/src/App.vue",
"repo_id": "owncloud",
"token_count": 2641
} | 773 |
<template>
<div class="oc-text-nowrap oc-text-center">
<p
data-testid="files-list-footer-info"
:data-test-items="items"
:data-test-files="files"
:data-test-folders="folders"
:data-test-spaces="spaces"
:data-test-size="size"
class="oc-text-muted"
>
{{ text }}
</p>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { formatFileSize } from '@ownclouders/web-pkg'
export default defineComponent({
props: {
files: {
type: Number,
required: true
},
folders: {
type: Number,
required: true
},
spaces: {
type: Number,
default: 0,
required: false
},
showSpaces: {
type: Boolean,
default: false,
required: false
},
/**
* Total size in bytes. Unformatted strings and integers are allowed.
*/
size: {
type: [String, Number],
required: false,
default: null
}
},
computed: {
items() {
return this.files + this.folders + (this.showSpaces ? this.spaces : 0)
},
text() {
const filesStr = this.$ngettext('%{ filesCount } file', '%{ filesCount } files', this.files, {
filesCount: this.files.toString()
})
const foldersStr = this.$ngettext(
'%{ foldersCount } folder',
'%{ foldersCount } folders',
this.folders,
{
foldersCount: this.folders.toString()
}
)
const spacesStr = this.$ngettext(
'%{ spacesCount } space',
'%{ spacesCount } spaces',
this.spaces,
{
spacesCount: this.spaces.toString()
}
)
const itemSize = formatFileSize(this.size, this.$language.current)
const size = parseFloat(this.size?.toString())
if (this.showSpaces) {
return size > 0
? this.$ngettext(
'%{ itemsCount } item with %{ itemSize } in total (%{ filesStr}, %{foldersStr}, %{spacesStr})',
'%{ itemsCount } items with %{ itemSize } in total (%{ filesStr}, %{foldersStr}, %{spacesStr})',
this.items,
{
itemsCount: this.items.toString(),
itemSize,
filesStr,
foldersStr,
spacesStr
}
)
: this.$ngettext(
'%{ itemsCount } item in total (%{ filesStr}, %{foldersStr}, %{spacesStr})',
'%{ itemsCount } items in total (%{ filesStr}, %{foldersStr}, %{spacesStr})',
this.items,
{
itemsCount: this.items.toString(),
itemSize,
filesStr,
foldersStr,
spacesStr
}
)
} else {
return size > 0
? this.$ngettext(
'%{ itemsCount } item with %{ itemSize } in total (%{ filesStr}, %{foldersStr})',
'%{ itemsCount } items with %{ itemSize } in total (%{ filesStr}, %{foldersStr})',
this.items,
{
itemsCount: this.items.toString(),
itemSize,
filesStr,
foldersStr,
spacesStr
}
)
: this.$ngettext(
'%{ itemsCount } item in total (%{ filesStr}, %{foldersStr})',
'%{ itemsCount } items in total (%{ filesStr}, %{foldersStr})',
this.items,
{
itemsCount: this.items.toString(),
itemSize,
filesStr,
foldersStr,
spacesStr
}
)
}
}
}
})
</script>
| owncloud/web/packages/web-app-files/src/components/FilesList/ListInfo.vue/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/components/FilesList/ListInfo.vue",
"repo_id": "owncloud",
"token_count": 1932
} | 774 |
<template>
<div
:data-testid="`recipient-autocomplete-item-${item.displayName}`"
class="oc-flex oc-flex-middle oc-py-xs"
:class="collaboratorClass"
>
<avatar-image
v-if="isAnyUserShareType"
class="oc-mr-s"
:width="36"
:userid="item.id"
:user-name="item.displayName"
/>
<oc-avatar-item
v-else
:width="36"
:name="shareTypeKey"
:icon="shareTypeIcon"
icon-size="large"
icon-color="var(--oc-color-text)"
background="transparent"
class="oc-mr-s"
/>
<div class="files-collaborators-autocomplete-user-text oc-text-truncate">
<span class="files-collaborators-autocomplete-username" v-text="item.displayName" />
<template v-if="!isAnyPrimaryShareType">
<span
class="files-collaborators-autocomplete-share-type"
v-text="`(${$gettext(shareType.label)})`"
/>
</template>
<div v-if="item.mail" class="files-collaborators-autocomplete-mail" v-text="`${item.mail}`" />
</div>
</div>
</template>
<script lang="ts">
import { PropType } from 'vue'
import { CollaboratorAutoCompleteItem, ShareTypes } from '@ownclouders/web-client/src/helpers/share'
export default {
name: 'AutocompleteItem',
props: {
item: {
type: Object as PropType<CollaboratorAutoCompleteItem>,
required: true
}
},
computed: {
shareType() {
return ShareTypes.getByValue(this.item.shareType)
},
shareTypeIcon() {
return this.shareType.icon
},
shareTypeKey() {
return this.shareType.key
},
isAnyUserShareType() {
return [ShareTypes.user.key, ShareTypes.spaceUser.key].includes(this.shareType.key)
},
isAnyPrimaryShareType() {
return [
ShareTypes.user.key,
ShareTypes.spaceUser.key,
ShareTypes.group.key,
ShareTypes.spaceGroup.key
].includes(this.shareType.key)
},
collaboratorClass() {
return `files-collaborators-search-${this.shareType.key}`
}
}
}
</script>
<style lang="scss">
.files-collaborators-autocomplete-mail {
font-size: var(--oc-font-size-small);
}
</style>
| owncloud/web/packages/web-app-files/src/components/SideBar/Shares/Collaborators/InviteCollaborator/AutocompleteItem.vue/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/components/SideBar/Shares/Collaborators/InviteCollaborator/AutocompleteItem.vue",
"repo_id": "owncloud",
"token_count": 947
} | 775 |
<template>
<div>
<context-action-menu :menu-sections="menuSections" :action-options="_actionOptions" />
<input
id="space-image-upload-input"
ref="spaceImageInput"
type="file"
name="file"
multiple
tabindex="-1"
:accept="supportedSpaceImageMimeTypes"
@change="uploadImageSpace"
/>
</div>
</template>
<script lang="ts">
import { ContextActionMenu, useSpaceActionsNavigateToTrash } from '@ownclouders/web-pkg'
import { useFileActionsShowDetails } from '@ownclouders/web-pkg'
import { useSpaceActionsUploadImage } from 'web-app-files/src/composables'
import {
useSpaceActionsDelete,
useSpaceActionsDisable,
useSpaceActionsDuplicate,
useSpaceActionsEditDescription,
useSpaceActionsEditQuota,
useSpaceActionsEditReadmeContent,
useSpaceActionsRename,
useSpaceActionsRestore,
useSpaceActionsShowMembers,
useSpaceActionsSetIcon
} from '@ownclouders/web-pkg'
import { isLocationSpacesActive } from '@ownclouders/web-pkg'
import { computed, defineComponent, PropType, Ref, ref, toRef, unref, VNodeRef } from 'vue'
import { useRouter, usePreviewService } from '@ownclouders/web-pkg'
import { FileActionOptions, SpaceActionOptions } from '@ownclouders/web-pkg'
import { useFileActionsDownloadArchive } from '@ownclouders/web-pkg'
export default defineComponent({
name: 'SpaceContextActions',
components: { ContextActionMenu },
props: {
actionOptions: {
type: Object as PropType<SpaceActionOptions>,
required: true
}
},
setup(props) {
const router = useRouter()
const previewService = usePreviewService()
const actionOptions = toRef(props, 'actionOptions') as Ref<SpaceActionOptions>
const supportedSpaceImageMimeTypes = computed(() => {
return previewService.getSupportedMimeTypes('image/').join(',')
})
const { actions: deleteActions } = useSpaceActionsDelete()
const { actions: disableActions } = useSpaceActionsDisable()
const { actions: duplicateActions } = useSpaceActionsDuplicate()
const { actions: editQuotaActions } = useSpaceActionsEditQuota()
const { actions: editReadmeContentActions } = useSpaceActionsEditReadmeContent()
const { actions: editDescriptionActions } = useSpaceActionsEditDescription()
const { actions: setSpaceIconActions } = useSpaceActionsSetIcon()
const { actions: renameActions } = useSpaceActionsRename()
const { actions: restoreActions } = useSpaceActionsRestore()
const { actions: showDetailsActions } = useFileActionsShowDetails()
const { actions: showMembersActions } = useSpaceActionsShowMembers()
const { actions: downloadArchiveActions } = useFileActionsDownloadArchive()
const { actions: navigateToTrashActions } = useSpaceActionsNavigateToTrash()
const spaceImageInput: VNodeRef = ref(null)
const { actions: uploadImageActions, uploadImageSpace } = useSpaceActionsUploadImage({
spaceImageInput
})
const menuItemsMembers = computed(() => {
const fileHandlers = [...unref(showMembersActions), ...unref(downloadArchiveActions)]
// HACK: downloadArchiveActions requires FileActionOptions but we have SpaceActionOptions
return [...fileHandlers].filter((item) => item.isVisible(unref(actionOptions) as any))
})
const menuItemsPrimaryActions = computed(() => {
const fileHandlers = [
...unref(renameActions),
...unref(duplicateActions),
...unref(editDescriptionActions),
...unref(uploadImageActions),
...unref(setSpaceIconActions)
]
if (isLocationSpacesActive(router, 'files-spaces-generic')) {
fileHandlers.splice(2, 0, ...unref(editReadmeContentActions))
}
return [...fileHandlers].filter((item) => item.isVisible(unref(actionOptions)))
})
const menuItemsSecondaryActions = computed(() => {
const fileHandlers = [
...unref(editQuotaActions),
...unref(disableActions),
...unref(restoreActions),
...unref(navigateToTrashActions),
...unref(deleteActions)
]
return [...fileHandlers].filter((item) => item.isVisible(unref(actionOptions)))
})
const menuItemsSidebar = computed(() => {
const fileHandlers = [...unref(showDetailsActions)]
return [...fileHandlers].filter((item) =>
// HACK: showDetails provides FileAction[] but we have SpaceActionOptions, so we need to cast them to FileActionOptions
item.isVisible(unref(actionOptions) as unknown as FileActionOptions)
)
})
const menuSections = computed(() => {
const sections = []
if (unref(menuItemsMembers).length) {
sections.push({
name: 'members',
items: unref(menuItemsMembers)
})
}
if (unref(menuItemsPrimaryActions).length) {
sections.push({
name: 'primaryActions',
items: unref(menuItemsPrimaryActions)
})
}
if (unref(menuItemsSecondaryActions).length) {
sections.push({
name: 'secondaryActions',
items: unref(menuItemsSecondaryActions)
})
}
if (unref(menuItemsSidebar).length) {
sections.push({
name: 'sidebar',
items: unref(menuItemsSidebar)
})
}
return sections
})
return {
_actionOptions: actionOptions,
menuSections,
spaceImageInput,
uploadImageActions,
uploadImageSpace,
supportedSpaceImageMimeTypes
}
}
})
</script>
<style lang="scss">
#space-image-upload-input {
position: absolute;
left: -99999px;
}
</style>
| owncloud/web/packages/web-app-files/src/components/Spaces/SpaceContextActions.vue/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/components/Spaces/SpaceContextActions.vue",
"repo_id": "owncloud",
"token_count": 2087
} | 776 |
import {
Extension,
useRouter,
useSearch,
useFileActionsShowShares,
useFileActionsCopyQuickLink,
useCapabilityStore
} from '@ownclouders/web-pkg'
import { computed, unref } from 'vue'
import { SDKSearch } from './search'
import { useSideBarPanels } from './composables/extensions/useFileSideBars'
import { useFolderViews } from './composables/extensions/useFolderViews'
export const extensions = () => {
const capabilityStore = useCapabilityStore()
const router = useRouter()
const { search: searchFunction } = useSearch()
const { actions: showSharesActions } = useFileActionsShowShares()
const { actions: quickLinkActions } = useFileActionsCopyQuickLink()
const panels = useSideBarPanels()
const folderViews = useFolderViews()
return computed(
() =>
[
...folderViews,
...unref(panels),
{
id: 'com.github.owncloud.web.files.search',
type: 'search',
searchProvider: new SDKSearch(capabilityStore, router, searchFunction)
},
{
id: 'com.github.owncloud.web.files.quick-action.collaborator',
scopes: ['resource', 'resource.quick-action'],
type: 'action',
action: unref(showSharesActions)[0]
},
{
id: 'com.github.owncloud.web.files.quick-action.quicklink',
scopes: ['resource', 'resource.quick-action'],
type: 'action',
action: unref(quickLinkActions)[0]
}
] satisfies Extension[]
)
}
| owncloud/web/packages/web-app-files/src/extensions.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/extensions.ts",
"repo_id": "owncloud",
"token_count": 599
} | 777 |
export * from './loaderSpace'
export * from './loaderFavorites'
export * from './loaderSharedViaLink'
export * from './loaderSharedWithMe'
export * from './loaderSharedWithOthers'
export * from './loaderTrashbin'
export * from './types'
| owncloud/web/packages/web-app-files/src/services/folder/index.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/services/folder/index.ts",
"repo_id": "owncloud",
"token_count": 75
} | 778 |
<template>
<app-loading-spinner v-if="isLoading" />
<template v-else>
<app-banner :file-id="fileId"></app-banner>
<drive-redirect v-if="!space" :drive-alias-and-item="driveAliasAndItem" />
<generic-trash v-else-if="isTrashRoute" :space="space" :item-id="itemId" />
<generic-space v-else :space="space" :item="item" :item-id="itemId" />
</template>
</template>
<script lang="ts">
import DriveRedirect from './DriveRedirect.vue'
import GenericSpace from './GenericSpace.vue'
import GenericTrash from './GenericTrash.vue'
import { computed, defineComponent, onMounted, ref, unref } from 'vue'
import {
queryItemAsString,
useAuthStore,
useClientService,
useConfigStore,
useDriveResolver,
useGetMatchingSpace,
useRouteParam,
useRouteQuery,
useRouter
} from '@ownclouders/web-pkg'
import { useActiveLocation } from '@ownclouders/web-pkg'
import { createLocationSpaces, isLocationTrashActive } from '@ownclouders/web-pkg'
import {
isPublicSpaceResource,
PublicSpaceResource,
SharePermissionBit,
SpaceResource
} from '@ownclouders/web-client/src/helpers'
import { locationPublicUpload } from '@ownclouders/web-pkg'
import { createFileRouteOptions } from '@ownclouders/web-pkg'
import { AppLoadingSpinner } from '@ownclouders/web-pkg'
import { dirname } from 'path'
import AppBanner from '@ownclouders/web-pkg/src/components/AppBanner.vue'
export default defineComponent({
components: {
AppBanner,
DriveRedirect,
GenericSpace,
GenericTrash,
AppLoadingSpinner
},
setup() {
const authStore = useAuthStore()
const configStore = useConfigStore()
const clientService = useClientService()
const router = useRouter()
const driveAliasAndItem = useRouteParam('driveAliasAndItem')
const isTrashRoute = useActiveLocation(isLocationTrashActive, 'files-trash-generic')
const resolvedDrive = useDriveResolver({ driveAliasAndItem })
const { getInternalSpace } = useGetMatchingSpace()
const loading = ref(true)
const isLoading = computed(() => {
return unref(loading) || unref(resolvedDrive.loading)
})
const fileIdQueryItem = useRouteQuery('fileId')
const fileId = computed(() => {
return queryItemAsString(unref(fileIdQueryItem))
})
const getSpaceResource = async (): Promise<SpaceResource> => {
const space = unref(resolvedDrive.space)
try {
return (await clientService.webdav.getFileInfo(space)) as SpaceResource
} catch (e) {
console.error(e)
return space
}
}
const resolveToInternalLocation = async (path: string) => {
const internalSpace = getInternalSpace(unref(fileId).split('!')[0])
if (internalSpace) {
const resource = await clientService.webdav.getFileInfo(internalSpace, { path })
const resourceId = resource.type !== 'folder' ? resource.parentFolderId : resource.fileId
const resourcePath = resource.type !== 'folder' ? dirname(path) : path
resolvedDrive.space.value = internalSpace
resolvedDrive.item.value = resourcePath
const { params, query } = createFileRouteOptions(internalSpace, {
fileId: resourceId,
path: resourcePath
})
return router.push(
createLocationSpaces('files-spaces-generic', {
params,
query: {
...query,
scrollTo: unref(resource).fileId,
...(configStore.options.openLinksWithDefaultApp && {
openWithDefaultApp: 'true'
})
}
})
)
}
// no internal space found -> share -> resolve via private link as it holds all the necessary logic
return router.push({
name: 'resolvePrivateLink',
params: { fileId: unref(fileId) },
query: {
...(configStore.options.openLinksWithDefaultApp && {
openWithDefaultApp: 'true'
})
}
})
}
onMounted(async () => {
if (!unref(driveAliasAndItem) && unref(fileId)) {
return router.push({
name: 'resolvePrivateLink',
params: { fileId: unref(fileId) },
query: {
...(configStore.options.openLinksWithDefaultApp && {
openWithDefaultApp: 'true'
})
}
})
}
const space = unref(resolvedDrive.space)
if (space && isPublicSpaceResource(space)) {
const isRunningOnEos = configStore.options.runningOnEos
if (authStore.userContextReady && unref(fileId) && !isRunningOnEos) {
try {
const path = await clientService.webdav.getPathForFileId(unref(fileId))
await resolveToInternalLocation(path)
loading.value = false
return
} catch (e) {
// getPathForFileId failed means the user doesn't have internal access to the resource
}
}
let publicSpace = (await getSpaceResource()) as PublicSpaceResource
// FIXME: check for type once https://github.com/owncloud/ocis/issues/8740 is resolved
if (publicSpace.publicLinkPermission === SharePermissionBit.Create) {
router.push({
name: locationPublicUpload.name,
params: { token: space.id.toString() }
})
}
}
loading.value = false
})
return {
...resolvedDrive,
driveAliasAndItem,
isTrashRoute,
isLoading,
fileId
}
}
})
</script>
| owncloud/web/packages/web-app-files/src/views/spaces/DriveResolver.vue/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/views/spaces/DriveResolver.vue",
"repo_id": "owncloud",
"token_count": 2217
} | 779 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`CreateSpace component > should show the "New Space" button 1`] = `
"<button type="button" aria-label="Create a new space" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-primary oc-button-primary-filled" id="new-space-menu-btn">
<!--v-if-->
<!-- @slot Content of the button --> <span class="oc-icon oc-icon-m oc-icon-passive"><!----></span> <span data-msgid="New Space" data-current-language="en">New Space</span>
</button>"
`;
| owncloud/web/packages/web-app-files/tests/unit/components/AppBar/__snapshots__/CreateSpace.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/components/AppBar/__snapshots__/CreateSpace.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 196
} | 780 |
import { mock } from 'vitest-mock-extended'
import InviteCollaboratorForm from 'web-app-files/src/components/SideBar/Shares/Collaborators/InviteCollaborator/InviteCollaboratorForm.vue'
import {
defaultComponentMocks,
defaultPlugins,
RouteLocation,
shallowMount
} from 'web-test-helpers'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { useSharesStore } from '@ownclouders/web-pkg'
import {
CollaboratorAutoCompleteItem,
GraphShareRoleIdMap,
ShareRole
} from '@ownclouders/web-client/src/helpers'
import { Mock } from 'vitest'
import { Group, User } from '@ownclouders/web-client/src/generated'
import { AxiosResponse } from 'axios'
vi.mock('lodash-es', () => ({ debounce: (fn) => fn() }))
const folderMock = {
id: '1',
type: 'folder',
isFolder: true,
mdate: 'Wed, 21 Oct 2015 07:28:00 GMT',
size: '740',
isMounted: vi.fn(() => true),
name: 'lorem.txt',
privateLink: 'some-link',
canShare: vi.fn(() => true),
path: '/documents',
canDeny: () => false
} as Resource
const spaceMock = {
id: '1',
type: 'space'
}
describe('InviteCollaboratorForm', () => {
describe('renders correctly', () => {
it.todo('renders a select field for share receivers')
it.todo('renders an inviteDescriptionMessage')
it.todo('renders a role selector component')
it.todo('renders an expiration datepicker component')
it.todo('renders an invite-sharees button')
it.todo('renders an hidden-announcer')
})
describe('fetching recipients', () => {
it('fetches recipients upon mount', async () => {
const { wrapper, mocks } = getWrapper()
await wrapper.vm.fetchRecipientsTask.last
expect(mocks.$clientService.graphAuthenticated.users.listUsers).toHaveBeenCalledTimes(1)
expect(mocks.$clientService.graphAuthenticated.groups.listGroups).toHaveBeenCalledTimes(1)
})
it('fetches users and groups returned from the server', async () => {
const { wrapper } = getWrapper({ users: [{ id: '2' }], groups: [{ id: '2' }] })
await wrapper.vm.fetchRecipientsTask.last
expect(wrapper.vm.autocompleteResults.length).toBe(2)
})
})
describe('share action', () => {
it('clicking the invite-sharees button calls the "share"-action', async () => {
const { wrapper } = getWrapper()
const shareSpy = vi.spyOn(wrapper.vm, 'share')
const shareBtn = wrapper.find('#new-collaborators-form-create-button')
expect(shareBtn.exists()).toBeTruthy()
await wrapper.vm.$nextTick()
await shareBtn.trigger('click')
expect(shareSpy).toHaveBeenCalledTimes(0)
})
it.each([
{ storageId: undefined, resource: mock<Resource>(folderMock) },
{ storageId: undefined, resource: mock<SpaceResource>(spaceMock) },
{ storageId: '1', resource: mock<Resource>(folderMock) }
] as const)('calls the "addShare" action', async (dataSet) => {
const { wrapper } = getWrapper({
storageId: dataSet.storageId,
resource: dataSet.resource
})
wrapper.vm.selectedCollaborators = [mock<CollaboratorAutoCompleteItem>()]
const { addShare } = useSharesStore()
;(addShare as Mock).mockResolvedValue([])
await wrapper.vm.$nextTick()
await wrapper.vm.share()
expect(addShare).toHaveBeenCalled()
})
it.todo('resets focus upon selecting an invitee')
})
})
function getWrapper({
storageId = 'fake-storage-id',
resource = mock<Resource>(folderMock),
users = [],
groups = []
}: {
storageId?: string
resource?: Resource
users?: User[]
groups?: Group[]
} = {}) {
const mocks = defaultComponentMocks({
currentRoute: mock<RouteLocation>({ params: { storageId } })
})
mocks.$clientService.graphAuthenticated.users.listUsers.mockResolvedValue(
mock<AxiosResponse>({ data: { value: users } })
)
mocks.$clientService.graphAuthenticated.groups.listGroups.mockResolvedValue(
mock<AxiosResponse>({ data: { value: groups } })
)
const capabilities = { files_sharing: { federation: { incoming: true, outgoing: true } } }
return {
mocks,
wrapper: shallowMount(InviteCollaboratorForm, {
global: {
plugins: [
...defaultPlugins({
piniaOptions: {
capabilityState: { capabilities },
configState: { options: { concurrentRequests: { shares: { create: 1 } } } },
sharesState: {
graphRoles: [
mock<ShareRole>({ id: GraphShareRoleIdMap.Viewer }),
mock<ShareRole>({ id: GraphShareRoleIdMap.SpaceViewer })
]
}
}
})
],
provide: { ...mocks, resource },
mocks
}
})
}
}
| owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/Collaborators/InviteCollaborator/InviteCollaboratorForm.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/Collaborators/InviteCollaborator/InviteCollaboratorForm.spec.ts",
"repo_id": "owncloud",
"token_count": 1828
} | 781 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`PrivateLinkItem > should render a button 1`] = `
"<button type="button" aria-label="Copy private link to clipboard" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw oc-files-private-link-copy-url">
<!--v-if-->
<!-- @slot Content of the button --> <span>Private link</span> <span class="oc-icon oc-icon-m oc-icon-passive"><!----></span>
</button>"
`;
exports[`PrivateLinkItem > upon clicking it should copy the private link to the clipboard button, render a success message and change icon for half a second 1`] = `
"<button type="button" aria-label="Copy private link to clipboard" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw oc-files-private-link-copy-url">
<!--v-if-->
<!-- @slot Content of the button --> <span>Private link</span> <span class="oc-icon oc-icon-m oc-icon-passive"><!----></span>
</button>"
`;
exports[`PrivateLinkItem > upon clicking it should copy the private link to the clipboard button, render a success message and change icon for half a second 2`] = `
"<button type="button" aria-label="Copy private link to clipboard" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw oc-files-private-link-copy-url">
<!--v-if-->
<!-- @slot Content of the button --> <span>Private link</span> <span class="oc-icon oc-icon-m oc-icon-passive"><!----></span>
</button>"
`;
| owncloud/web/packages/web-app-files/tests/unit/components/SideBar/__snapshots__/PrivateLinkItem.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/components/SideBar/__snapshots__/PrivateLinkItem.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 540
} | 782 |
import DriveRedirect from '../../../../src/views/spaces/DriveRedirect.vue'
import { mock } from 'vitest-mock-extended'
import {
defaultPlugins,
mount,
defaultComponentMocks,
defaultStubs,
RouteLocation
} from 'web-test-helpers'
describe('DriveRedirect view', () => {
it('redirects to "projects" route if no personal space exist', () => {
const { mocks } = getMountedWrapper()
expect(mocks.$router.replace).toHaveBeenCalledWith({
name: 'files-spaces-projects'
})
})
})
function getMountedWrapper({ currentRouteName = 'files-spaces-generic' } = {}) {
const mocks = {
...defaultComponentMocks({ currentRoute: mock<RouteLocation>({ name: currentRouteName }) })
}
return {
mocks,
wrapper: mount(DriveRedirect, {
global: {
plugins: [...defaultPlugins()],
stubs: defaultStubs,
mocks,
provide: mocks
}
})
}
}
| owncloud/web/packages/web-app-files/tests/unit/views/spaces/DriveRedirect.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/views/spaces/DriveRedirect.spec.ts",
"repo_id": "owncloud",
"token_count": 348
} | 783 |
{
"name": "web-app-ocm",
"version": "0.0.0",
"description": "OCM",
"license": "AGPL-3.0",
"peerDependencies": {
"@ownclouders/web-client": "workspace:*",
"@ownclouders/web-pkg": "workspace:*",
"axios": "1.6.5",
"email-validator": "^2.0.4",
"fuse.js": "6.6.2",
"lodash-es": "4.17.21",
"vue-concurrency": "5.0.0",
"uuid": "9.0.1",
"zod": "3.22.4"
}
}
| owncloud/web/packages/web-app-ocm/package.json/0 | {
"file_path": "owncloud/web/packages/web-app-ocm/package.json",
"repo_id": "owncloud",
"token_count": 217
} | 784 |
{
"name": "preview",
"version": "0.0.0",
"private": true,
"description": "ownCloud Web Preview",
"license": "AGPL-3.0",
"devDependencies": {
"@panzoom/panzoom": "^4.5.1",
"web-test-helpers": "workspace:*"
},
"peerDependencies": {
"@ownclouders/web-client": "workspace:*",
"@ownclouders/web-pkg": "workspace:*",
"@vueuse/core": "^10.3.0",
"vue3-gettext": "2.4.0"
}
}
| owncloud/web/packages/web-app-preview/package.json/0 | {
"file_path": "owncloud/web/packages/web-app-preview/package.json",
"repo_id": "owncloud",
"token_count": 195
} | 785 |
import { SearchExtension, SearchProvider, useExtensionRegistry } from '@ownclouders/web-pkg'
import { computed, Ref } from 'vue'
export const useAvailableProviders = (): Ref<SearchProvider[]> => {
const extensionRegistry = useExtensionRegistry()
const availableProviders = computed(() => {
return extensionRegistry
.requestExtensions<SearchExtension>('search')
.map(({ searchProvider }) => searchProvider)
})
return availableProviders
}
| owncloud/web/packages/web-app-search/src/composables/useAvailableProviders.ts/0 | {
"file_path": "owncloud/web/packages/web-app-search/src/composables/useAvailableProviders.ts",
"repo_id": "owncloud",
"token_count": 137
} | 786 |
export * from './types'
export * from './webfingerDiscovery'
| owncloud/web/packages/web-app-webfinger/src/discovery/index.ts/0 | {
"file_path": "owncloud/web/packages/web-app-webfinger/src/discovery/index.ts",
"repo_id": "owncloud",
"token_count": 19
} | 787 |
/* tslint:disable */
/* eslint-disable */
/**
* Libre Graph API
* Libre Graph is a free API for cloud collaboration inspired by the MS Graph API.
*
* The version of the OpenAPI document: v1.0.4
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from "./configuration";
import type { RequestArgs } from "./base";
import type { AxiosInstance, AxiosResponse } from 'axios';
import { RequiredError } from "./base";
/**
*
* @export
*/
export const DUMMY_BASE_URL = 'https://example.com'
/**
*
* @throws {RequiredError}
* @export
*/
export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) {
if (paramValue === null || paramValue === undefined) {
throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`);
}
}
/**
*
* @export
*/
export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) {
if (configuration && configuration.apiKey) {
const localVarApiKeyValue = typeof configuration.apiKey === 'function'
? await configuration.apiKey(keyParamName)
: await configuration.apiKey;
object[keyParamName] = localVarApiKeyValue;
}
}
/**
*
* @export
*/
export const setBasicAuthToObject = function (object: any, configuration?: Configuration) {
if (configuration && (configuration.username || configuration.password)) {
object["auth"] = { username: configuration.username, password: configuration.password };
}
}
/**
*
* @export
*/
export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) {
if (configuration && configuration.accessToken) {
const accessToken = typeof configuration.accessToken === 'function'
? await configuration.accessToken()
: await configuration.accessToken;
object["Authorization"] = "Bearer " + accessToken;
}
}
/**
*
* @export
*/
export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) {
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? await configuration.accessToken(name, scopes)
: await configuration.accessToken;
object["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
}
function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void {
if (parameter == null) return;
if (typeof parameter === "object") {
if (Array.isArray(parameter)) {
(parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key));
}
else {
Object.keys(parameter).forEach(currentKey =>
setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`)
);
}
}
else {
if (urlSearchParams.has(key)) {
urlSearchParams.append(key, parameter);
}
else {
urlSearchParams.set(key, parameter);
}
}
}
/**
*
* @export
*/
export const setSearchParams = function (url: URL, ...objects: any[]) {
const searchParams = new URLSearchParams(url.search);
setFlattenedQueryParams(searchParams, objects);
url.search = searchParams.toString();
}
/**
*
* @export
*/
export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) {
const nonString = typeof value !== 'string';
const needsSerialization = nonString && configuration && configuration.isJsonMime
? configuration.isJsonMime(requestOptions.headers['Content-Type'])
: nonString;
return needsSerialization
? JSON.stringify(value !== undefined ? value : {})
: (value || "");
}
/**
*
* @export
*/
export const toPathString = function (url: URL) {
return url.pathname + url.search + url.hash
}
/**
*
* @export
*/
export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) {
return <T = unknown, R = AxiosResponse<T>>(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => {
const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || basePath) + axiosArgs.url};
return axios.request<T, R>(axiosRequestArgs);
};
}
| owncloud/web/packages/web-client/src/generated/common.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/generated/common.ts",
"repo_id": "owncloud",
"token_count": 1635
} | 788 |
export * from './constants'
export * from './functions'
export * from './permission'
export * from './type'
export * from './types'
| owncloud/web/packages/web-client/src/helpers/share/index.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/helpers/share/index.ts",
"repo_id": "owncloud",
"token_count": 43
} | 789 |
/**
* A copy of https://github.com/moxystudio/js-proper-url-join/blob/master/src/index.js
* but without the query handling.
*/
const urlRegExp = /^(\w+:\/\/[^/?]+)?(.*?)$/
export interface UrlJoinOptions {
/**
* Add a leading slash.
*
* **Default**: `true`
*/
leadingSlash?: boolean | 'keep' | undefined
/**
* Add a trailing slash.
*
* **Default**: `false`
*/
trailingSlash?: boolean | 'keep' | undefined
}
const normalizeParts = (parts) =>
parts
// Filter non-string or non-numeric values
.filter((part) => typeof part === 'string' || typeof part === 'number')
// Convert to strings
.map((part) => `${part}`)
// Remove empty parts
.filter((part) => part)
const parseParts = (parts) => {
const partsStr = parts.join('/')
const [, prefix = '', pathname = ''] = partsStr.match(urlRegExp) || []
return {
prefix,
pathname: {
parts: pathname.split('/').filter((part) => part !== ''),
hasLeading: /^\/+/.test(pathname),
hasTrailing: /\/+$/.test(pathname)
}
}
}
const buildUrl = (parsedParts, options: UrlJoinOptions) => {
const { prefix, pathname } = parsedParts
const { parts: pathnameParts, hasLeading, hasTrailing } = pathname
const { leadingSlash, trailingSlash } = options
const addLeading = leadingSlash === true || (leadingSlash === 'keep' && hasLeading)
const addTrailing = trailingSlash === true || (trailingSlash === 'keep' && hasTrailing)
// Start with prefix if not empty (http://google.com)
let url = prefix
// Add the parts
if (pathnameParts.length > 0) {
if (url || addLeading) {
url += '/'
}
url += pathnameParts.join('/')
}
// Add trailing to the end
if (addTrailing) {
url += '/'
}
// Add leading if URL is still empty
if (!url && addLeading) {
url += '/'
}
return url
}
export const urlJoin = (...parts) => {
const lastArg = parts[parts.length - 1]
let options
// If last argument is an object, then it's the options
// Note that null is an object, so we verify if is truthy
if (lastArg && typeof lastArg === 'object') {
options = lastArg
parts = parts.slice(0, -1)
}
// Parse options
options = {
leadingSlash: true,
trailingSlash: false,
...options
} as UrlJoinOptions
// Normalize parts before parsing them
parts = normalizeParts(parts)
// Split the parts into prefix, pathname
// (scheme://host)(/pathnameParts.join('/'))
const parsedParts = parseParts(parts)
// Finally build the url based on the parsedParts
return buildUrl(parsedParts, options)
}
| owncloud/web/packages/web-client/src/utils/urlJoin.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/utils/urlJoin.ts",
"repo_id": "owncloud",
"token_count": 921
} | 790 |
import { WebDAV, WebDavOptions } from './types'
import { CopyFilesFactory } from './copyFiles'
import { CreateFolderFactory } from './createFolder'
import { GetFileContentsFactory } from './getFileContents'
import { GetFileInfoFactory } from './getFileInfo'
import { GetFileUrlFactory } from './getFileUrl'
import { GetPublicFileUrlFactory } from './getPublicFileUrl'
import { ListFilesFactory } from './listFiles'
import { MoveFilesFactory } from './moveFiles'
import { PutFileContentsFactory } from './putFileContents'
import { DeleteFileFactory } from './deleteFile'
import { RestoreFileFactory } from './restoreFile'
import { RestoreFileVersionFactory } from './restoreFileVersion'
import { ClearTrashBinFactory } from './clearTrashBin'
import { SearchFactory } from './search'
import { GetPathForFileIdFactory } from './getPathForFileId'
import { DAV } from './client/dav'
import { ListFileVersionsFactory } from './listFileVersions'
import { ListFilesByIdFactory } from './listFilesById'
import { SetFavoriteFactory } from './setFavorite'
import { ListFavoriteFilesFactory } from './listFavoriteFiles'
export * from './constants'
export * from './types'
export const webdav = (options: WebDavOptions): WebDAV => {
const dav = new DAV({
accessToken: options.accessToken,
baseUrl: options.baseUrl,
language: options.language
})
const pathForFileIdFactory = GetPathForFileIdFactory(dav, options)
const { getPathForFileId } = pathForFileIdFactory
const listFilesFactory = ListFilesFactory(dav, pathForFileIdFactory, options)
const { listFiles } = listFilesFactory
const listFilesByIdFactory = ListFilesByIdFactory(dav, options)
const { listFilesById } = listFilesByIdFactory
const getFileInfoFactory = GetFileInfoFactory(listFilesFactory, options)
const { getFileInfo } = getFileInfoFactory
const { createFolder } = CreateFolderFactory(dav, getFileInfoFactory, options)
const getFileContentsFactory = GetFileContentsFactory(dav, options)
const { getFileContents } = getFileContentsFactory
const { putFileContents } = PutFileContentsFactory(dav, getFileInfoFactory, options)
const { getFileUrl, revokeUrl } = GetFileUrlFactory(dav, getFileContentsFactory, options)
const { getPublicFileUrl } = GetPublicFileUrlFactory(dav, options)
const { copyFiles } = CopyFilesFactory(dav, options)
const { moveFiles } = MoveFilesFactory(dav, options)
const { deleteFile } = DeleteFileFactory(dav, options)
const { restoreFile } = RestoreFileFactory(dav, options)
const { listFileVersions } = ListFileVersionsFactory(dav, options)
const { restoreFileVersion } = RestoreFileVersionFactory(dav, options)
const { clearTrashBin } = ClearTrashBinFactory(dav, options)
const { search } = SearchFactory(dav, options)
const { listFavoriteFiles } = ListFavoriteFilesFactory(dav, options)
const { setFavorite } = SetFavoriteFactory(dav, options)
return {
copyFiles,
createFolder,
deleteFile,
restoreFile,
restoreFileVersion,
getFileContents,
getFileInfo,
getFileUrl,
getPublicFileUrl,
getPathForFileId,
listFiles,
listFilesById,
listFileVersions,
moveFiles,
putFileContents,
revokeUrl,
clearTrashBin,
search,
listFavoriteFiles,
setFavorite
}
}
| owncloud/web/packages/web-client/src/webdav/index.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/webdav/index.ts",
"repo_id": "owncloud",
"token_count": 994
} | 791 |
vi.mock('@microsoft/fetch-event-source', () => ({
fetchEventSource: vi.fn()
}))
import { EventSourceMessage, fetchEventSource } from '@microsoft/fetch-event-source'
import { SSEAdapter, sse, MESSAGE_TYPE, RetriableError } from '../../src/sse'
const url = 'https://owncloud.test/'
describe('SSEAdapter', () => {
let mockFetch
beforeEach(() => {
mockFetch = vi.fn()
// Mock fetchEventSource and window.fetch
global.window.fetch = mockFetch
})
afterEach(() => {
vi.clearAllMocks()
})
test('it should initialize the SSEAdapter', () => {
const fetchOptions = { method: 'GET' }
const sseAdapter = new SSEAdapter(url, fetchOptions)
expect(sseAdapter.url).toBe(url)
expect(sseAdapter.fetchOptions).toBe(fetchOptions)
expect(sseAdapter.readyState).toBe(sseAdapter.CONNECTING)
})
test('it should call connect and set up event listeners', () => {
const fetchOptions = { method: 'GET' }
const sseAdapter = new SSEAdapter(url, fetchOptions)
const fetchEventSourceMock = vi.mocked(fetchEventSource)
expect(fetchEventSourceMock).toHaveBeenCalledWith(url, expect.any(Object))
expect(fetchEventSourceMock.mock.calls[0][1].onopen).toEqual(expect.any(Function))
fetchEventSourceMock.mock.calls[0][1].onopen(undefined)
expect(sseAdapter.readyState).toBe(sseAdapter.OPEN)
})
test('it should handle onmessage events', () => {
const fetchOptions = { method: 'GET' }
const sseAdapter = new SSEAdapter(url, fetchOptions)
const message = { data: 'Message data', event: MESSAGE_TYPE.NOTIFICATION } as EventSourceMessage
const messageListener = vi.fn()
sseAdapter.addEventListener(MESSAGE_TYPE.NOTIFICATION, messageListener)
const fetchEventSourceMock = vi.mocked(fetchEventSource)
fetchEventSourceMock.mock.calls[0][1].onmessage(message)
expect(messageListener).toHaveBeenCalledWith(expect.any(Object))
})
test('it should handle onclose events and throw RetriableError', () => {
const fetchOptions = { method: 'GET' }
new SSEAdapter(url, fetchOptions)
const fetchEventSourceMock = vi.mocked(fetchEventSource)
expect(() => {
// Simulate onclose
fetchEventSourceMock.mock.calls[0][1].onclose()
}).toThrow(RetriableError)
})
test('it should call fetchProvider with fetch options', () => {
const fetchOptions = { headers: { Authorization: 'Bearer xy' } }
const sseAdapter = new SSEAdapter(url, fetchOptions)
sseAdapter.fetchProvider(url, fetchOptions)
expect(mockFetch).toHaveBeenCalledWith(url, { ...fetchOptions })
})
test('it should update the access token in fetch options', () => {
const fetchOptions = { headers: { Authorization: 'Bearer xy' } }
const sseAdapter = new SSEAdapter(url, fetchOptions)
const token = 'new-token'
sseAdapter.updateAccessToken(token)
expect(sseAdapter.fetchOptions.headers.Authorization).toBe(`Bearer ${token}`)
})
test('it should close the SSEAdapter', () => {
const fetchOptions = { method: 'GET' }
const sseAdapter = new SSEAdapter(url, fetchOptions)
sseAdapter.close()
expect(sseAdapter.readyState).toBe(sseAdapter.CLOSED)
})
})
describe('sse', () => {
test('it should create and return an SSEAdapter instance', () => {
const fetchOptions = { method: 'GET' }
const eventSource = sse(url, fetchOptions)
expect(eventSource).toBeInstanceOf(SSEAdapter)
expect(eventSource.url).toBe(`${url}ocs/v2.php/apps/notifications/api/v1/notifications/sse`)
})
})
| owncloud/web/packages/web-client/tests/unit/sse.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-client/tests/unit/sse.spec.ts",
"repo_id": "owncloud",
"token_count": 1251
} | 792 |
<template>
<portal to="app.app-banner">
<div v-if="isAppBannerAvailable" class="app-banner hide-desktop" :hidden="isVisible === false">
<oc-button
variation="brand"
appearance="raw"
class="app-banner-exit"
aria-label="Close"
@click="close"
>
<oc-icon name="close" size="small" />
</oc-button>
<div
class="app-banner-icon"
:style="{ 'background-image': `url('${currentTheme.appBanner.icon}')` }"
></div>
<div class="info-container">
<div>
<div class="app-title">{{ currentTheme.appBanner.title }}</div>
<div class="app-publisher">{{ currentTheme.appBanner.publisher }}</div>
<div
v-if="currentTheme.appBanner.additionalInformation !== ''"
class="app-additional-info"
>
{{ $gettext(currentTheme.appBanner.additionalInformation) }}
</div>
</div>
</div>
<a
:href="appUrl"
target="_blank"
class="app-banner-cta"
rel="noopener"
aria-label="{{ $gettext(currentTheme.appBanner.ctaText) }}"
>{{ $gettext(currentTheme.appBanner.ctaText) }}</a
>
</div>
</portal>
</template>
<script lang="ts">
import { computed, defineComponent, ref, unref } from 'vue'
import { useRouter, useThemeStore } from '../composables'
import { buildUrl } from '../helpers/router'
import { useSessionStorage } from '@vueuse/core'
import { storeToRefs } from 'pinia'
export default defineComponent({
components: {},
props: {
fileId: {
type: String,
required: true
}
},
setup(props) {
const appBannerWasClosed = useSessionStorage('app_banner_closed', null)
const isVisible = ref<boolean>(unref(appBannerWasClosed) === null)
const router = useRouter()
const themeStore = useThemeStore()
const { currentTheme } = storeToRefs(themeStore)
const appBannerSettings = currentTheme.value.appBanner
const isAppBannerAvailable = computed(
() => appBannerSettings && Object.keys(appBannerSettings).length != 0
)
const appUrl = computed(() => {
return buildUrl(router, `/f/${props.fileId}`)
.toString()
.replace('https', currentTheme.value.appBanner?.appScheme)
})
const close = () => {
isVisible.value = false
useSessionStorage('app_banner_closed', 1)
}
return {
appUrl,
close,
currentTheme,
isAppBannerAvailable,
isVisible
}
}
})
</script>
<style scoped lang="scss">
.hide-desktop {
@media (min-width: 768px) {
display: none;
}
}
.app-banner {
overflow-x: hidden;
width: 100%;
height: 84px;
background: #f3f3f3;
font-family: Helvetica, sans, sans-serif;
z-index: 5;
}
.info-container {
position: absolute;
top: 10px;
left: 104px;
display: flex;
overflow-y: hidden;
width: 60%;
height: 64px;
align-items: center;
color: #000;
}
.app-banner-icon {
position: absolute;
top: 10px;
left: 30px;
width: 64px;
height: 64px;
border-radius: 15px;
background-size: 64px 64px;
}
.app-banner-cta {
position: absolute;
top: 32px;
right: 10px;
z-index: 1;
display: block;
padding: 0 10px;
min-width: 10%;
border-radius: 5px;
background: #f3f3f3;
color: #1474fc;
font-size: 18px;
text-align: center;
text-decoration: none;
}
.app-title {
font-size: 14px;
}
.app-publisher,
.app-additional-info {
font-size: 12px;
}
.app-banner-exit {
position: absolute;
top: 34px;
left: 9px;
margin: 0;
width: 12px;
height: 12px;
border: 0;
text-align: center;
display: inline;
}
</style>
| owncloud/web/packages/web-pkg/src/components/AppBanner.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/AppBanner.vue",
"repo_id": "owncloud",
"token_count": 1604
} | 793 |
<template>
<div>
<oc-list class="role-dropdown-list">
<li v-for="(type, i) in availableLinkTypes" :key="`role-dropdown-${i}`">
<oc-button
:id="`files-role-${getLinkId(type)}`"
:ref="(el: any) => (roleRefs[type] = el)"
:class="{
selected: isSelectedLinkType(type),
'oc-background-primary-gradient': isSelectedLinkType(type)
}"
:appearance="isSelectedLinkType(type) ? 'raw-inverse' : 'raw'"
:variation="isSelectedLinkType(type) ? 'primary' : 'passive'"
justify-content="space-between"
class="oc-p-s"
@click="updateSelectedLinkType(type)"
>
<span class="oc-flex oc-flex-middle">
<oc-icon
:name="getLinkRoleByType(type).icon"
class="oc-pl-s oc-pr-m"
variation="inherit"
/>
<span>
<span
class="role-dropdown-list-option-label oc-text-bold oc-display-block oc-width-1-1"
v-text="$gettext(getLinkRoleByType(type).displayName)"
/>
<span v-if="isSelectedLinkType(type)" class="oc-text-small">{{
$gettext(getLinkRoleByType(type).description)
}}</span>
</span>
</span>
<span class="oc-flex">
<oc-radio v-model="selectedType" :option="type" :hide-label="true" />
</span>
</oc-button>
</li>
</oc-list>
</div>
<div>
<oc-text-input
v-if="!onlyInternalLinksAllowed"
:key="passwordInputKey"
:model-value="password.value"
type="password"
:password-policy="passwordPolicy"
:generate-password-method="generatePasswordMethod"
:error-message="password.error"
:description-message="
selectedLinkTypeIsInternal
? $gettext('Password cannot be set for internal links')
: undefined
"
:fix-message-line="true"
:label="passwordEnforced ? `${$gettext('Password')}*` : $gettext('Password')"
class="link-modal-password-input oc-mt-l"
:disabled="selectedLinkTypeIsInternal"
@update:model-value="updatePassword"
/>
</div>
<div class="link-modal-actions oc-flex oc-flex-right oc-flex-middle oc-mt-m">
<oc-icon
v-if="selectedExpiry"
v-oc-tooltip="expirationDateTooltip"
class="oc-mr-s"
:aria-label="expirationDateTooltip"
name="calendar-event"
fill-type="line"
/>
<oc-button
v-if="!onlyInternalLinksAllowed"
id="link-modal-context-menu-toggle"
appearance="raw"
>
<oc-icon name="more-2" />
</oc-button>
<oc-drop
v-if="!onlyInternalLinksAllowed"
drop-id="link-modal-context-menu-drop"
toggle="#link-modal-context-menu-toggle"
padding-size="small"
mode="click"
>
<oc-list class="link-modal-context-menu">
<li class="oc-rounded oc-menu-item-hover">
<oc-datepicker
v-model="selectedExpiry"
class="link-expiry-picker oc-flex oc-width-1-1"
:min-date="expirationRules.min"
:max-date="expirationRules.max"
:locale="$language.current"
:is-required="expirationRules.enforced"
>
<template #default="{ togglePopover }">
<oc-button
appearance="raw"
class="oc-p-s action-menu-item link-expiry-picker-btn"
:disabled="selectedLinkTypeIsInternal"
@click="togglePopover"
>
<oc-icon name="calendar-event" fill-type="line" size="medium" />
<span
v-text="
selectedExpiry
? $gettext('Edit expiration date')
: $gettext('Set expiration date')
"
/>
</oc-button>
<oc-button
v-if="selectedExpiry"
:aria-label="$gettext('Remove expiration date')"
appearance="raw"
@click="selectedExpiry = undefined"
>
<oc-icon name="close" />
</oc-button>
</template>
</oc-datepicker>
</li>
</oc-list>
</oc-drop>
<oc-button
class="link-modal-cancel oc-modal-body-actions-cancel oc-ml-s"
appearance="outline"
variation="passive"
@click="$emit('cancel')"
>{{ $gettext('Cancel') }}
</oc-button>
<oc-button
class="link-modal-confirm oc-modal-body-actions-confirm oc-ml-s"
appearance="filled"
variation="primary"
@click="$emit('confirm')"
>{{ $gettext('Copy link') }}
</oc-button>
</div>
</template>
<script lang="ts">
import { DateTime } from 'luxon'
import { v4 as uuidV4 } from 'uuid'
import { useGettext } from 'vue3-gettext'
import { computed, defineComponent, PropType, ref, reactive, unref, onMounted } from 'vue'
import {
usePasswordPolicyService,
useEmbedMode,
useExpirationRules,
useLinkTypes,
Modal,
useSharesStore,
useClientService
} from '../composables'
import { LinkShare, SpaceResource } from '@ownclouders/web-client/src/helpers'
import { Resource } from '@ownclouders/web-client'
import { formatRelativeDateFromDateTime } from '../helpers'
import { OcButton } from 'design-system/src/components'
import { SharingLinkType } from '@ownclouders/web-client/src/generated'
export default defineComponent({
name: 'CreateLinkModal',
props: {
modal: { type: Object as PropType<Modal>, required: true },
resources: { type: Array as PropType<Resource[]>, required: true },
space: { type: Object as PropType<SpaceResource>, default: undefined },
isQuickLink: { type: Boolean, default: false },
callbackFn: {
type: Function as PropType<
(result: PromiseSettledResult<LinkShare>[]) => Promise<void> | void
>,
default: undefined
}
},
emits: ['cancel', 'confirm'],
setup(props, { expose }) {
const clientService = useClientService()
const { $gettext, current: currentLanguage } = useGettext()
const passwordPolicyService = usePasswordPolicyService()
const { isEnabled: isEmbedEnabled, postMessage } = useEmbedMode()
const { expirationRules } = useExpirationRules()
const {
defaultLinkType,
getAvailableLinkTypes,
getLinkRoleByType,
isPasswordEnforcedForLinkType
} = useLinkTypes()
const { addLink } = useSharesStore()
const passwordPolicy = passwordPolicyService.getPolicy()
const isFolder = computed(() => props.resources.every(({ isFolder }) => isFolder))
const passwordInputKey = ref(uuidV4())
const roleRefs = ref<Record<string, InstanceType<typeof OcButton>>>({})
const password = reactive({ value: '', error: undefined })
const selectedType = ref(unref(defaultLinkType))
const selectedExpiry = ref<DateTime>()
const availableLinkTypes = computed(() => getAvailableLinkTypes({ isFolder: unref(isFolder) }))
const passwordEnforced = computed(() => isPasswordEnforcedForLinkType(unref(selectedType)))
const selectedLinkTypeIsInternal = computed(
() => unref(selectedType) === SharingLinkType.Internal
)
const onlyInternalLinksAllowed = computed(
() => unref(availableLinkTypes).length === 1 && unref(selectedLinkTypeIsInternal)
)
const selectedExpiryDateRelative = computed(() =>
formatRelativeDateFromDateTime(
DateTime.fromJSDate(unref(selectedExpiry)).endOf('day'),
currentLanguage
)
)
const selectedExpiryDate = computed(() =>
formatRelativeDateFromDateTime(
DateTime.fromJSDate(unref(selectedExpiry)).endOf('day'),
currentLanguage
)
)
const expirationDateTooltip = computed(() => {
return $gettext(
'Expires %{timeToExpiry} (%{expiryDate})',
{ timeToExpiry: unref(selectedExpiryDateRelative), expiryDate: unref(selectedExpiryDate) },
true
)
})
const createLinks = () => {
return Promise.allSettled<LinkShare>(
props.resources.map((resource) =>
addLink({
clientService,
space: props.space,
resource,
options: {
type: unref(selectedType),
'@libre.graph.quickLink': props.isQuickLink,
password: unref(password).value,
expirationDateTime: unref(selectedExpiry),
displayName: $gettext('Link')
}
})
)
)
}
const onConfirm = async () => {
if (!unref(selectedLinkTypeIsInternal)) {
if (unref(passwordEnforced) && !unref(password).value) {
password.error = $gettext('Password must not be empty')
return Promise.reject()
}
if (!passwordPolicy.check(unref(password).value)) {
return Promise.reject()
}
}
const result = await createLinks()
const succeeded = result.filter(({ status }) => status === 'fulfilled')
if (succeeded.length && unref(isEmbedEnabled)) {
postMessage<string[]>(
'owncloud-embed:share',
(succeeded as PromiseFulfilledResult<LinkShare>[]).map(({ value }) => value.webUrl)
)
}
let userFacingErrors = []
const failed = result.filter(({ status }) => status === 'rejected')
if (failed.length) {
;(failed as PromiseRejectedResult[])
.map(({ reason }) => reason)
.forEach((e) => {
console.error(e)
// Human-readable error message is provided, for example when password is on banned list
if (e.response?.status === 400) {
userFacingErrors.push(e.response.data.error)
}
})
}
if (userFacingErrors.length) {
password.error = $gettext(userFacingErrors[0].message)
return Promise.reject()
}
if (props.callbackFn) {
props.callbackFn(result)
}
}
expose({ onConfirm })
const isSelectedLinkType = (type: SharingLinkType) => {
return unref(selectedType) === type
}
const updatePassword = (value: string) => {
password.value = value
password.error = undefined
}
const updateSelectedLinkType = (type: SharingLinkType) => {
selectedType.value = type
if (unref(selectedLinkTypeIsInternal)) {
password.value = ''
password.error = ''
selectedExpiry.value = undefined
// re-render password because it's the only way to remove policy messages
passwordInputKey.value = uuidV4()
}
}
// FIXME: only needed for e2e and acceptance tests, map id to human readable element id
const getLinkId = (type: SharingLinkType) => {
const id = getLinkRoleByType(type).id
const map = {
internal: 'internal',
view: 'viewer',
upload: 'contributor',
edit: 'editor',
createOnly: 'uploader',
blocksDownload: 'blocksDownload'
}
return map[id]
}
onMounted(() => {
const activeRoleOption = unref(roleRefs)[unref(selectedType)]
if (activeRoleOption) {
activeRoleOption.$el.focus()
}
})
return {
roleRefs,
password,
passwordEnforced,
passwordPolicy,
generatePasswordMethod: () => passwordPolicyService.generatePassword(),
passwordInputKey,
selectedExpiry,
expirationDateTooltip,
expirationRules,
availableLinkTypes,
selectedType,
selectedLinkTypeIsInternal,
onlyInternalLinksAllowed,
isSelectedLinkType,
updateSelectedLinkType,
updatePassword,
getLinkRoleByType,
getLinkId,
// unit tests
onConfirm
}
}
})
</script>
<style lang="scss" scoped>
.action-menu-item {
width: 100%;
justify-content: flex-start;
}
.role-dropdown-list span {
line-height: 1.3;
}
.role-dropdown-list li {
margin: var(--oc-space-xsmall) 0;
&:first-child {
margin-top: 0;
}
&:last-child {
margin-bottom: 0;
}
.oc-button {
text-align: left;
width: 100%;
gap: var(--oc-space-medium);
&:hover,
&:focus {
background-color: var(--oc-color-background-hover);
text-decoration: none;
}
}
.selected span {
color: var(--oc-color-swatch-primary-contrast);
}
}
</style>
| owncloud/web/packages/web-pkg/src/components/CreateLinkModal.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/CreateLinkModal.vue",
"repo_id": "owncloud",
"token_count": 5557
} | 794 |
<template>
<div class="item-filter oc-flex" :class="`item-filter-${filterName}`">
<oc-filter-chip
:filter-label="filterLabel"
:selected-item-names="selectedItems.map((i) => i[displayNameAttribute])"
:close-on-click="closeOnClick"
@clear-filter="clearFilter"
@show-drop="showDrop"
>
<template #default>
<oc-text-input
v-if="showOptionFilter && filterableAttributes.length"
ref="filterInputRef"
v-model="filterTerm"
class="item-filter-input oc-mb-m oc-mt-s"
autocomplete="off"
:label="optionFilterLabel === '' ? $gettext('Filter list') : optionFilterLabel"
/>
<div ref="itemFilterListRef">
<oc-list class="item-filter-list">
<li v-for="(item, index) in displayedItems" :key="index" class="oc-my-xs">
<oc-button
class="item-filter-list-item oc-flex oc-flex-middle oc-width-1-1 oc-p-xs"
:class="{
'item-filter-list-item-active': !allowMultiple && isItemSelected(item),
'oc-flex-left': allowMultiple,
'oc-flex-between': !allowMultiple
}"
justify-content="space-between"
appearance="raw"
:data-test-value="item[displayNameAttribute]"
@click="toggleItemSelection(item)"
>
<div class="oc-flex oc-flex-middle oc-text-truncate">
<oc-checkbox
v-if="allowMultiple"
size="large"
class="item-filter-checkbox oc-mr-s"
:label="$gettext('Toggle selection')"
:model-value="isItemSelected(item)"
hide-label
@update:model-value="toggleItemSelection(item)"
@click.stop
/>
<div>
<slot name="image" :item="item" />
</div>
<div class="oc-text-truncate oc-ml-s">
<slot name="item" :item="item" />
</div>
</div>
<div class="oc-flex">
<oc-icon v-if="!allowMultiple && isItemSelected(item)" name="check" />
</div>
</oc-button>
</li>
</oc-list>
</div>
</template>
</oc-filter-chip>
</div>
</template>
<script lang="ts">
import { PropType, defineComponent, nextTick, onMounted, ref, unref, watch } from 'vue'
import Fuse from 'fuse.js'
import Mark from 'mark.js'
import omit from 'lodash-es/omit'
import { useRoute, useRouteQuery, useRouter } from '../composables'
import { defaultFuseOptions } from '../helpers'
import { queryItemAsString } from '../composables/appDefaults'
export default defineComponent({
name: 'ItemFilter',
props: {
filterLabel: {
type: String,
required: true
},
filterName: {
type: String,
required: true
},
optionFilterLabel: {
type: String,
required: false,
default: ''
},
showOptionFilter: {
type: Boolean,
required: false,
default: false
},
items: {
type: Array,
required: true
},
allowMultiple: {
type: Boolean,
required: false,
default: false
},
idAttribute: {
type: String,
required: false,
default: 'id'
},
displayNameAttribute: {
type: String,
required: false,
default: 'name'
},
filterableAttributes: {
type: Array as PropType<Fuse.FuseOptionKey<unknown>[]>,
required: false,
default: () => []
},
closeOnClick: {
type: Boolean,
default: false
}
},
emits: ['selectionChange'],
setup: function (props, { emit, expose }) {
const router = useRouter()
const currentRoute = useRoute()
const filterInputRef = ref()
const selectedItems = ref([])
const displayedItems = ref(props.items)
const markInstance = ref(null)
const itemFilterListRef = ref(null)
const queryParam = `q_${props.filterName}`
const currentRouteQuery = useRouteQuery(queryParam)
const getId = (item) => {
return item[props.idAttribute]
}
const setRouteQuery = () => {
return router.push({
query: {
...omit(unref(currentRoute).query, [queryParam]),
...(!!unref(selectedItems).length && {
[queryParam]: unref(selectedItems)
.reduce((acc, item) => {
acc += `${getId(item)}+`
return acc
}, '')
.slice(0, -1)
})
}
})
}
const isItemSelected = (item) => {
return !!unref(selectedItems).find((s) => getId(s) === getId(item))
}
const toggleItemSelection = async (item) => {
if (isItemSelected(item)) {
selectedItems.value = unref(selectedItems).filter((s) => getId(s) !== getId(item))
} else {
if (!props.allowMultiple) {
selectedItems.value = []
}
selectedItems.value.push(item)
}
await setRouteQuery()
emit('selectionChange', unref(selectedItems))
}
const filterTerm = ref()
const filter = (items: unknown[], filterTerm) => {
if (!(filterTerm || '').trim()) {
return items
}
const fuse = new Fuse(items, {
...defaultFuseOptions,
keys: props.filterableAttributes
})
const results = fuse.search(filterTerm).map((r) => r.item)
return items.filter((item) => results.includes(item))
}
const clearFilter = () => {
selectedItems.value = []
emit('selectionChange', unref(selectedItems))
setRouteQuery()
}
const setDisplayedItems = (items) => {
displayedItems.value = items
}
const showDrop = async () => {
setDisplayedItems(props.items)
await nextTick()
unref(filterInputRef).focus()
}
watch(filterTerm, () => {
setDisplayedItems(filter(props.items, unref(filterTerm)))
if (unref(itemFilterListRef)) {
markInstance.value = new Mark(unref(itemFilterListRef))
unref(markInstance).unmark()
unref(markInstance).mark(unref(filterTerm), {
element: 'span',
className: 'mark-highlight'
})
}
})
const setSelectedItemsBasedOnQuery = () => {
const queryStr = queryItemAsString(unref(currentRouteQuery))
if (queryStr) {
const ids = queryStr.split('+')
selectedItems.value = props.items.filter((s: any) => ids.includes(getId(s)))
}
}
expose({ setSelectedItemsBasedOnQuery })
onMounted(() => {
setSelectedItemsBasedOnQuery()
})
return {
clearFilter,
displayedItems,
filterInputRef,
filterTerm,
isItemSelected,
itemFilterListRef,
queryParam,
selectedItems,
setDisplayedItems,
showDrop,
toggleItemSelection,
// expose to type
setSelectedItemsBasedOnQuery
}
}
})
</script>
<style lang="scss">
.item-filter {
&-list {
li {
&:first-child {
margin-top: 0 !important;
}
&:last-child {
margin-bottom: 0 !important;
}
}
&-item {
line-height: 1.5;
gap: 8px;
&:hover,
&-active {
background-color: var(--oc-color-background-hover) !important;
}
}
}
}
</style>
| owncloud/web/packages/web-pkg/src/components/ItemFilter.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/ItemFilter.vue",
"repo_id": "owncloud",
"token_count": 3559
} | 795 |
<template>
<div class="compare-save-dialog oc-width-1-1 oc-flex oc-flex-between oc-flex-middle">
<span v-if="saved" class="state-indicator oc-flex oc-flex-middle">
<oc-icon variation="success" name="checkbox-circle" />
<span v-translate class="changes-saved oc-ml-s">Changes saved</span>
</span>
<span v-else class="state-indicator">{{ unsavedChangesText }}</span>
<div>
<oc-button
:disabled="!unsavedChanges"
class="compare-save-dialog-revert-btn"
@click="$emit('revert')"
>
<span v-text="$gettext('Revert')" />
</oc-button>
<oc-button
appearance="filled"
variation="primary"
class="compare-save-dialog-confirm-btn"
:disabled="!unsavedChanges || confirmButtonDisabled"
@click="$emit('confirm')"
>
<span v-text="$gettext('Save')" />
</oc-button>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, onBeforeUnmount, onMounted, ref } from 'vue'
import isEqual from 'lodash-es/isEqual'
import { eventBus } from '../../services/eventBus'
export default defineComponent({
name: 'CompareSaveDialog',
props: {
originalObject: {
type: Object,
required: true
},
compareObject: {
type: Object,
required: true
},
confirmButtonDisabled: {
type: Boolean,
default: () => {
return false
}
}
},
emits: ['confirm', 'revert'],
setup() {
const saved = ref(false)
let savedEventToken
onMounted(() => {
savedEventToken = eventBus.subscribe('sidebar.entity.saved', () => {
saved.value = true
})
})
onBeforeUnmount(() => {
eventBus.unsubscribe('sidebar.entity.saved', savedEventToken)
})
return { saved }
},
computed: {
unsavedChanges() {
return !isEqual(this.originalObject, this.compareObject)
},
unsavedChangesText() {
return this.unsavedChanges ? this.$gettext('Unsaved changes') : this.$gettext('No changes')
}
},
watch: {
unsavedChanges() {
if (this.unsavedChanges) {
this.saved = false
}
},
'originalObject.id': function () {
this.saved = false
}
}
})
</script>
<style lang="scss" scoped>
.compare-save-dialog {
background: var(--oc-color-background-highlight);
flex-flow: row wrap;
}
.state-indicator {
line-height: 2rem;
}
.changes-saved {
color: var(--oc-color-swatch-success-default);
}
</style>
| owncloud/web/packages/web-pkg/src/components/SideBar/CompareSaveDialog.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/SideBar/CompareSaveDialog.vue",
"repo_id": "owncloud",
"token_count": 1065
} | 796 |
export { default as QuotaModal } from './QuotaModal.vue'
| owncloud/web/packages/web-pkg/src/components/Spaces/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/Spaces/index.ts",
"repo_id": "owncloud",
"token_count": 21
} | 797 |
import {
isLocationSharesActive,
isLocationSpacesActive,
createLocationShares
} from '../../../router'
import PQueue from 'p-queue'
import { IncomingShareResource } from '@ownclouders/web-client/src/helpers/share'
import { useClientService } from '../../clientService'
import { useLoadingService } from '../../loadingService'
import { useRouter } from '../../router'
import { computed } from 'vue'
import { useGettext } from 'vue3-gettext'
import { FileAction, FileActionOptions } from '../types'
import { useMessages, useConfigStore, useResourcesStore } from '../../piniaStores'
export const useFileActionsDisableSync = () => {
const { showMessage, showErrorMessage } = useMessages()
const router = useRouter()
const { $gettext, $ngettext } = useGettext()
const clientService = useClientService()
const loadingService = useLoadingService()
const configStore = useConfigStore()
const { updateResourceField } = useResourcesStore()
const handler = async ({ resources }: FileActionOptions<IncomingShareResource>) => {
const errors = []
const triggerPromises = []
const triggerQueue = new PQueue({
concurrency: configStore.options.concurrentRequests.resourceBatchActions
})
resources.forEach((resource) => {
triggerPromises.push(
triggerQueue.add(async () => {
try {
const { graphAuthenticated } = clientService
await graphAuthenticated.drives.deleteDriveItem(resource.driveId, resource.id)
updateResourceField<IncomingShareResource, any>({
id: resource.id,
field: 'syncEnabled',
value: false
})
} catch (error) {
console.error(error)
errors.push(error)
}
})
)
})
await Promise.all(triggerPromises)
if (errors.length === 0) {
if (isLocationSpacesActive(router, 'files-spaces-generic')) {
showMessage({
title: $ngettext(
'Sync for the selected share was disabled successfully',
'Sync for the selected shares was disabled successfully',
resources.length
)
})
router.push(createLocationShares('files-shares-with-me'))
}
return
}
showErrorMessage({
title: $ngettext(
'Failed to disable sync for the the selected share',
'Failed to disable sync for the selected shares',
resources.length
),
errors
})
}
const actions = computed((): FileAction<IncomingShareResource>[] => [
{
name: 'disable-sync',
icon: 'spam-3',
handler: (args) => loadingService.addTask(() => handler(args)),
label: () => $gettext('Disable sync'),
isVisible: ({ space, resources }) => {
if (
!isLocationSharesActive(router, 'files-shares-with-me') &&
!isLocationSpacesActive(router, 'files-spaces-generic')
) {
return false
}
if (resources.length === 0) {
return false
}
if (
isLocationSpacesActive(router, 'files-spaces-generic') &&
(space?.driveType !== 'share' || resources.length > 1 || resources[0].path !== '/')
) {
return false
}
return resources.some((resource) => resource.syncEnabled)
},
componentType: 'button',
class: 'oc-files-actions-disable-sync-trigger'
}
])
return {
actions
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsDisableSync.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsDisableSync.ts",
"repo_id": "owncloud",
"token_count": 1376
} | 798 |
import { isLocationTrashActive } from '../../../router'
import { ShareResource, isIncomingShareResource } from '@ownclouders/web-client/src/helpers/share'
import { eventBus } from '../../../services'
import { SideBarEventTopics } from '../../sideBar'
import { computed, unref } from 'vue'
import { useGettext } from 'vue3-gettext'
import { useIsFilesAppActive } from '../helpers'
import { useRouter } from '../../router'
import { FileAction, FileActionOptions } from '../types'
import { useCanShare } from '../../shares'
import { useResourcesStore } from '../../piniaStores'
export const useFileActionsShowShares = () => {
const router = useRouter()
const { $gettext } = useGettext()
const isFilesAppActive = useIsFilesAppActive()
const { canShare } = useCanShare()
const resourcesStore = useResourcesStore()
const handler = ({ resources }: FileActionOptions) => {
resourcesStore.setSelection(resources.map(({ id }) => id))
eventBus.publish(SideBarEventTopics.openWithPanel, 'sharing#peopleShares')
}
const actions = computed((): FileAction<ShareResource>[] => [
{
name: 'show-shares',
icon: 'user-add',
label: () => $gettext('Share'),
handler,
isVisible: ({ space, resources }) => {
// sidebar is currently only available inside files app
if (!unref(isFilesAppActive)) {
return false
}
if (isLocationTrashActive(router, 'files-trash-generic')) {
return false
}
if (resources.length !== 1) {
return false
}
if (isIncomingShareResource(resources[0]) && !resources[0].syncEnabled) {
return false
}
return canShare({ space, resource: resources[0] })
},
componentType: 'button',
class: 'oc-files-actions-show-shares-trigger'
}
])
return {
actions
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsShowShares.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsShowShares.ts",
"repo_id": "owncloud",
"token_count": 685
} | 799 |
import { SpaceResource } from '@ownclouders/web-client'
import { computed, unref } from 'vue'
import { SpaceAction, SpaceActionOptions } from '../types'
import { useRoute } from '../../router'
import { useAbility } from '../../ability'
import { useClientService } from '../../clientService'
import { useLoadingService } from '../../loadingService'
import { useGettext } from 'vue3-gettext'
import { isProjectSpaceResource } from '@ownclouders/web-client/src/helpers'
import { useMessages, useModals, useSpacesStore, useUserStore } from '../../piniaStores'
export const useSpaceActionsRestore = () => {
const { showMessage, showErrorMessage } = useMessages()
const userStore = useUserStore()
const { $gettext, $ngettext } = useGettext()
const ability = useAbility()
const clientService = useClientService()
const loadingService = useLoadingService()
const route = useRoute()
const { dispatchModal } = useModals()
const spacesStore = useSpacesStore()
const filterResourcesToRestore = (resources): SpaceResource[] => {
return resources.filter(
(r) => isProjectSpaceResource(r) && r.canRestore({ user: userStore.user, ability })
)
}
const restoreSpaces = async (spaces: SpaceResource[]) => {
const client = clientService.graphAuthenticated
const promises = spaces.map((space) =>
client.drives
.updateDrive(space.id.toString(), {} as any, {
headers: {
Restore: true
}
})
.then((updatedSpace) => {
if (unref(route).name === 'admin-settings-spaces') {
space.disabled = false
space.spaceQuota = updatedSpace.data.quota
}
spacesStore.updateSpaceField({ id: space.id, field: 'disabled', value: false })
return true
})
)
const results = await loadingService.addTask(() => {
return Promise.allSettled(promises)
})
const succeeded = results.filter((r) => r.status === 'fulfilled')
if (succeeded.length) {
const title =
succeeded.length === 1 && spaces.length === 1
? $gettext('Space "%{space}" was enabled successfully', { space: spaces[0].name })
: $ngettext(
'%{spaceCount} space was enabled successfully',
'%{spaceCount} spaces were enabled successfully',
succeeded.length,
{ spaceCount: succeeded.length.toString() },
true
)
showMessage({ title })
}
const failed = results.filter((r) => r.status === 'rejected')
if (failed.length) {
failed.forEach(console.error)
const title =
failed.length === 1 && spaces.length === 1
? $gettext('Failed to enabled space "%{space}"', { space: spaces[0].name })
: $ngettext(
'Failed to enable %{spaceCount} space',
'Failed to enable %{spaceCount} spaces',
failed.length,
{ spaceCount: failed.length.toString() },
true
)
showErrorMessage({
title,
errors: (failed as PromiseRejectedResult[]).map((f) => f.reason)
})
}
}
const handler = ({ resources }: SpaceActionOptions) => {
const allowedResources = filterResourcesToRestore(resources)
if (!allowedResources.length) {
return
}
const message = $ngettext(
'If you enable the selected space, it can be accessed again.',
'If you enable the %{count} selected spaces, they can be accessed again.',
allowedResources.length,
{ count: allowedResources.length.toString() }
)
const confirmText = $gettext('Enable')
dispatchModal({
title: $ngettext(
'Enable Space "%{space}"?',
'Enable %{spaceCount} Spaces?',
allowedResources.length,
{
space: allowedResources[0].name,
spaceCount: allowedResources.length.toString()
}
),
confirmText,
icon: 'alert',
message,
hasInput: false,
onConfirm: () => restoreSpaces(allowedResources)
})
}
const actions = computed((): SpaceAction[] => [
{
name: 'restore',
icon: 'play-circle',
label: () => $gettext('Enable'),
handler,
isVisible: ({ resources }) => {
return !!filterResourcesToRestore(resources).length
},
componentType: 'button',
class: 'oc-files-actions-restore-trigger'
}
])
return {
actions,
// HACK: exported for unit tests:
restoreSpaces
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsRestore.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsRestore.ts",
"repo_id": "owncloud",
"token_count": 1781
} | 800 |
import { storeToRefs } from 'pinia'
import { watch, Ref, unref } from 'vue'
import { useEventBus } from '../eventBus'
import { useThemeStore } from '../piniaStores'
import { EventBus } from '../../services'
interface DocumentTitleOptions {
titleSegments: Ref<string[]>
eventBus?: EventBus
}
export function useDocumentTitle({ titleSegments, eventBus }: DocumentTitleOptions): void {
const themeStore = useThemeStore()
const { currentTheme } = storeToRefs(themeStore)
eventBus = eventBus || useEventBus()
watch(
titleSegments,
(newTitleSegments) => {
const titleSegments = unref(newTitleSegments)
const glue = ' - '
const payload = {
shortDocumentTitle: titleSegments.join(glue),
fullDocumentTitle: [...titleSegments, currentTheme.value.common.name].join(glue)
}
eventBus.publish('runtime.documentTitle.changed', payload)
},
{ immediate: true, deep: true }
)
}
| owncloud/web/packages/web-pkg/src/composables/appDefaults/useDocumentTitle.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/appDefaults/useDocumentTitle.ts",
"repo_id": "owncloud",
"token_count": 324
} | 801 |
import { computed } from 'vue'
import { useSpacesStore } from '../piniaStores'
export const useSpacesLoading = () => {
const spacesStore = useSpacesStore()
const areSpacesLoading = computed(
() => !spacesStore.spacesInitialized || spacesStore.spacesLoading
)
return {
areSpacesLoading
}
}
| owncloud/web/packages/web-pkg/src/composables/driveResolver/useSpacesLoading.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/driveResolver/useSpacesLoading.ts",
"repo_id": "owncloud",
"token_count": 100
} | 802 |
import { computed, unref } from 'vue'
import { useAbility } from '../ability'
import { useCapabilityStore } from '../piniaStores'
import { SharingLinkType } from '@ownclouders/web-client/src/generated'
import { useGettext } from 'vue3-gettext'
import { ShareRole } from '@ownclouders/web-client/src/helpers'
export const useLinkTypes = () => {
const { $gettext } = useGettext()
const capabilityStore = useCapabilityStore()
const ability = useAbility()
const canCreatePublicLinks = computed(() => ability.can('create-all', 'PublicLink'))
const defaultLinkType = computed<SharingLinkType>(() => {
const canCreatePublicLink = ability.can('create-all', 'PublicLink')
if (!canCreatePublicLink) {
return SharingLinkType.Internal
}
const defaultPermissions = capabilityStore.sharingPublicDefaultPermissions
if (defaultPermissions === undefined || defaultPermissions === 1) {
return SharingLinkType.View
}
return SharingLinkType.Internal
})
const isPasswordEnforcedForLinkType = (type: SharingLinkType) => {
if (type === SharingLinkType.View) {
return capabilityStore.sharingPublicPasswordEnforcedFor.read_only
}
if (type === SharingLinkType.Upload) {
return capabilityStore.sharingPublicPasswordEnforcedFor.upload_only
}
if (type === SharingLinkType.CreateOnly) {
return capabilityStore.sharingPublicPasswordEnforcedFor.read_write
}
if (type === SharingLinkType.Edit) {
return capabilityStore.sharingPublicPasswordEnforcedFor.read_write_delete
}
return false
}
const getAvailableLinkTypes = ({ isFolder }: { isFolder: boolean }): SharingLinkType[] => {
if (!unref(canCreatePublicLinks)) {
return [SharingLinkType.Internal]
}
if (isFolder) {
return [
SharingLinkType.Internal,
SharingLinkType.View,
SharingLinkType.Upload,
SharingLinkType.Edit,
SharingLinkType.CreateOnly
]
}
return [SharingLinkType.Internal, SharingLinkType.View, SharingLinkType.Edit]
}
// links don't have roles in graph API, hence we need to define them here
const linkShareRoles = [
{
id: SharingLinkType.Internal,
displayName: $gettext('Invited people'),
label: $gettext('Only for invited people'),
description: $gettext('Link works only for invited people. Login is required.'),
icon: 'user'
},
{
id: SharingLinkType.View,
displayName: $gettext('Can view'),
label: $gettext('Anyone with the link can view'),
description: $gettext('Anyone with the link can view and download.'),
icon: 'eye'
},
{
id: SharingLinkType.Upload,
displayName: $gettext('Can upload'),
label: $gettext('Anyone with the link can upload'),
description: $gettext('Anyone with the link can view, download and upload.'),
icon: 'upload'
},
{
id: SharingLinkType.Edit,
displayName: $gettext('Can edit'),
label: $gettext('Anyone with the link can edit'),
description: $gettext('Anyone with the link can view, download and edit.'),
icon: 'pencil'
},
{
id: SharingLinkType.CreateOnly,
displayName: $gettext('Secret File Drop'),
label: $gettext('Secret File Drop'),
description: $gettext(
'Anyone with the link can only upload, existing content is not revealed.'
),
icon: 'inbox-unarchive'
}
] satisfies ShareRole[]
const getLinkRoleByType = (type: SharingLinkType): ShareRole => {
return linkShareRoles.find(({ id }) => id === type)
}
return {
defaultLinkType,
isPasswordEnforcedForLinkType,
getAvailableLinkTypes,
linkShareRoles,
getLinkRoleByType
}
}
| owncloud/web/packages/web-pkg/src/composables/links/useLinkTypes.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/links/useLinkTypes.ts",
"repo_id": "owncloud",
"token_count": 1306
} | 803 |
import { z } from 'zod'
const CustomTranslationSchema = z.object({
url: z.string()
})
export type CustomTranslation = z.infer<typeof CustomTranslationSchema>
const OAuth2ConfigSchema = z.object({
apiUrl: z.string().optional(),
authUrl: z.string().optional(),
clientId: z.string().optional(),
clientSecret: z.string().optional(),
logoutUrl: z.string().optional(),
metaDataUrl: z.string().optional(),
url: z.string().optional()
})
export type OAuth2Config = z.infer<typeof OAuth2ConfigSchema>
const OpenIdConnectConfigSchema = z.object({
authority: z.string().optional(),
client_id: z.string().optional(),
client_secret: z.string().optional(),
dynamic: z.string().optional(),
metadata_url: z.string().optional(),
response_type: z.string().optional(),
scope: z.string().optional()
})
export type OpenIdConnectConfig = z.infer<typeof OpenIdConnectConfigSchema>
const SentryConfigSchema = z.record(z.any())
export type SentryConfig = z.infer<typeof SentryConfigSchema>
const StyleConfigSchema = z.object({
href: z.string().optional()
})
export type StyleConfig = z.infer<typeof StyleConfigSchema>
const ScriptConfigSchema = z.object({
async: z.boolean().optional(),
src: z.string().optional()
})
export type ScriptConfig = z.infer<typeof ScriptConfigSchema>
const OptionsConfigSchema = z.object({
cernFeatures: z.boolean().optional(),
concurrentRequests: z
.object({
resourceBatchActions: z.number().optional(),
sse: z.number().optional(),
shares: z
.object({
create: z.number().optional(),
list: z.number().optional()
})
.optional()
})
.optional(),
contextHelpers: z.boolean().optional(),
contextHelpersReadMore: z.boolean().optional(),
defaultExtension: z.string().optional(),
disabledExtensions: z.array(z.string()).optional(),
disableFeedbackLink: z.boolean().optional(),
disablePreviews: z.boolean().optional(),
displayResourcesLazy: z.boolean().optional(),
displayThumbnails: z.boolean().optional(),
accountEditLink: z
.object({
href: z.string().optional()
})
.optional(),
editor: z
.object({
autosaveEnabled: z.boolean().optional(),
autosaveInterval: z.number().optional(),
openAsPreview: z.union([z.boolean(), z.array(z.string())]).optional()
})
.optional(),
embed: z
.object({
enabled: z.boolean().optional(),
target: z.string().optional(),
messagesOrigin: z.string().optional(),
delegateAuthentication: z.boolean().optional(),
delegateAuthenticationOrigin: z.string().optional()
})
.optional(),
feedbackLink: z
.object({
ariaLabel: z.string().optional(),
description: z.string().optional(),
href: z.string().optional()
})
.optional(),
hoverableQuickActions: z.boolean().optional(),
isRunningOnEos: z.boolean().optional(),
loginUrl: z.string().optional(),
logoutUrl: z.string().optional(),
ocm: z
.object({
openRemotely: z.boolean().optional()
})
.optional(),
openAppsInTab: z.boolean().optional(),
openLinksWithDefaultApp: z.boolean().optional(),
previewFileMimeTypes: z.array(z.string()).optional(),
routing: z
.object({
fullShareOwnerPaths: z.boolean().optional(),
idBased: z.boolean().optional()
})
.optional(),
runningOnEos: z.boolean().optional(),
sharingRecipientsPerPage: z.number().optional(),
sidebar: z
.object({
shares: z
.object({
showAllOnLoad: z.boolean().optional()
})
.optional()
})
.optional(),
tokenStorageLocal: z.boolean().optional(),
topCenterNotifications: z.boolean().optional(),
upload: z
.object({
companionUrl: z.string().optional(),
xhr: z
.object({
timeout: z.number().optional()
})
.optional()
})
.optional(),
userListRequiresFilter: z.boolean().optional()
})
export type OptionsConfig = z.infer<typeof OptionsConfigSchema>
const ExternalApp = z.object({
id: z.string(),
path: z.string(),
config: z.record(z.unknown()).optional()
})
export const RawConfigSchema = z.object({
server: z.string(),
theme: z.string(),
options: OptionsConfigSchema,
apps: z.array(z.string()).optional(),
external_apps: z.array(ExternalApp).optional(),
customTranslations: z.array(CustomTranslationSchema).optional(),
auth: OAuth2ConfigSchema.optional(),
openIdConnect: OpenIdConnectConfigSchema.optional(),
sentry: SentryConfigSchema.optional(),
scripts: z.array(ScriptConfigSchema).optional(),
styles: z.array(StyleConfigSchema).optional()
})
export type RawConfig = z.infer<typeof RawConfigSchema>
| owncloud/web/packages/web-pkg/src/composables/piniaStores/config/types.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/config/types.ts",
"repo_id": "owncloud",
"token_count": 1688
} | 804 |
import { useService } from '../service'
import { PreviewService } from '../../services/preview'
export const usePreviewService = (): PreviewService => {
return useService('$previewService')
}
| owncloud/web/packages/web-pkg/src/composables/previewService/usePreviewService.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/previewService/usePreviewService.ts",
"repo_id": "owncloud",
"token_count": 53
} | 805 |
export * from './useScrollTo'
| owncloud/web/packages/web-pkg/src/composables/scrollTo/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/scrollTo/index.ts",
"repo_id": "owncloud",
"token_count": 10
} | 806 |
import { ref, Ref, computed, unref, isRef, MaybeRef } from 'vue'
import { ReadOnlyRef } from '../../utils'
import { useRouteName, useRouter, useRouteQueryPersisted, QueryValue } from '../router'
import { SortConstants } from './constants'
import get from 'lodash-es/get'
export interface SortableItem {
type?: string
}
export enum SortDir {
Desc = 'desc',
Asc = 'asc'
}
export interface SortField {
name: string
prop?: string
// eslint-disable-next-line @typescript-eslint/ban-types
sortable?: MaybeRef<boolean | Function | string>
sortDir?: MaybeRef<SortDir>
label?: string
}
export interface SortOptions<T extends SortableItem> {
items: MaybeRef<Array<T>>
fields: MaybeRef<Array<SortField>>
sortBy?: MaybeRef<string>
sortByQueryName?: MaybeRef<string>
sortDir?: MaybeRef<SortDir>
sortDirQueryName?: MaybeRef<string>
routeName?: MaybeRef<string>
}
export interface SortResult<T> {
items: Ref<Array<T>>
sortBy: ReadOnlyRef<string>
sortDir: ReadOnlyRef<SortDir>
handleSort({ sortBy, sortDir }: { sortBy: string; sortDir: SortDir }): void
}
export function useSort<T extends SortableItem>(options: SortOptions<T>): SortResult<T> {
const router = useRouter()
const sortByRef = createSortByQueryRef(options)
const sortDirRef = createSortDirQueryRef(options)
const sortBy = computed(
(): string =>
firstQueryValue(unref(sortByRef)) || unref(firstSortableField(unref(fields))?.name)
)
const sortDir = computed((): SortDir => {
return (
sortDirFromQueryValue(unref(sortDirRef)) || defaultSortDirection(unref(sortBy), unref(fields))
)
})
const fields = options.fields
const items = computed<Array<T>>((): T[] => {
// cast to T[] to avoid: Type 'T[] | readonly T[]' is not assignable to type 'T[]'.
const sortItems = unref(options.items) as T[]
if (!unref(sortBy)) {
return sortItems
}
return sortHelper(sortItems, unref(fields), unref(sortBy), unref(sortDir))
})
const handleSort = ({ sortBy, sortDir }: { sortBy: string; sortDir: SortDir }) => {
// normally we would just set sortBy and sortDir here, but then the router could lose one of the two changes.
// hence we update the router directly by setting both values as query.
return router.replace({
query: {
...unref(router.currentRoute).query,
[unref(options.sortByQueryName) || SortConstants.sortByQueryName]: sortBy,
[unref(options.sortDirQueryName) || SortConstants.sortDirQueryName]: sortDir
}
})
}
return {
items,
sortBy,
sortDir,
handleSort
}
}
function createSortByQueryRef<T>(options: SortOptions<T>): Ref<QueryValue> {
if (options.sortBy) {
return isRef(options.sortBy) ? options.sortBy : ref(options.sortBy)
}
return useRouteQueryPersisted({
name: unref(options.sortByQueryName) || SortConstants.sortByQueryName,
defaultValue: unref(firstSortableField(unref(options.fields))?.name),
storagePrefix: unref(options.routeName) || unref(useRouteName())
})
}
function createSortDirQueryRef<T>(options: SortOptions<T>): Ref<QueryValue> {
if (options.sortDir) {
return isRef(options.sortDir) ? options.sortDir : ref(options.sortDir)
}
return useRouteQueryPersisted({
name: unref(options.sortDirQueryName) || SortConstants.sortDirQueryName,
defaultValue: unref(firstSortableField(unref(options.fields))?.sortDir),
storagePrefix: unref(options.routeName) || unref(useRouteName())
})
}
const firstSortableField = (fields: SortField[]): SortField => {
const sortableFields = fields.filter((f) => f.sortable)
if (sortableFields) {
return sortableFields[0]
}
return null
}
const defaultSortDirection = (name: string, fields: SortField[]): SortDir => {
const sortField = fields.find((f) => f.name === name)
if (sortField && sortField.sortDir) {
return unref(sortField.sortDir)
}
return SortDir.Desc
}
export const sortHelper = <T extends SortableItem>(
items: T[],
fields: SortField[],
sortBy: string,
sortDir: SortDir
) => {
const field = fields.find((f) => {
return f.name === sortBy
})
if (!field) {
return items
}
const { sortable } = field
const collator = new Intl.Collator(navigator.language, { sensitivity: 'base', numeric: true })
if (sortBy === 'name') {
const folders = [...items.filter((i) => i.type === 'folder')].sort((a, b) =>
compare(a, b, collator, sortBy, sortDir, sortable)
)
const files = [...items.filter((i) => i.type !== 'folder')].sort((a, b) =>
compare(a, b, collator, sortBy, sortDir, sortable)
)
if (sortDir === SortDir.Asc) {
return folders.concat(files)
}
return files.concat(folders)
}
return [...items].sort((a, b) =>
compare(a, b, collator, field.prop || field.name, sortDir, sortable)
)
}
const compare = (
a: SortableItem,
b: SortableItem,
collator: Intl.Collator,
sortBy: string,
sortDir: SortDir,
sortable
) => {
let aValue = get(a, sortBy)
let bValue = get(b, sortBy)
const modifier = sortDir === SortDir.Asc ? 1 : -1
if (sortable) {
if (typeof sortable === 'string') {
const genArrComp = (vals) => {
return vals.map((val) => val[sortable]).join('')
}
aValue = genArrComp(aValue)
bValue = genArrComp(bValue)
} else if (typeof sortable === 'function') {
aValue = sortable(aValue)
bValue = sortable(bValue)
}
}
if (!isNaN(aValue) && !isNaN(bValue)) {
return (aValue - bValue) * modifier
}
const c = collator.compare((aValue || '').toString(), (bValue || '').toString())
return c * modifier
}
const firstQueryValue = (value: QueryValue): string => {
return Array.isArray(value) ? value[0] : value
}
const sortDirFromQueryValue = (value: QueryValue): SortDir | null => {
switch (firstQueryValue(value)) {
case SortDir.Asc:
return SortDir.Asc
case SortDir.Desc:
return SortDir.Desc
}
return null
}
| owncloud/web/packages/web-pkg/src/composables/sort/useSort.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/sort/useSort.ts",
"repo_id": "owncloud",
"token_count": 2179
} | 807 |
class CacheElement<T> {
public value: T
public expires: number
constructor(value: T, ttl: number) {
this.value = value
this.expires = ttl ? new Date().getTime() + ttl : 0
}
get expired(): boolean {
return this.expires > 0 && this.expires < new Date().getTime()
}
}
interface CacheOptions {
ttl?: number
capacity?: number
}
export default class Cache<K, V> {
private map: Map<K, CacheElement<V>>
private readonly ttl: number
private readonly capacity: number
constructor(options: CacheOptions) {
this.ttl = options.ttl || 0
this.capacity = options.capacity || 0
this.map = new Map<K, CacheElement<V>>()
}
public set(key: K, value: V, ttl?: number): V {
this.evict()
this.map.set(key, new CacheElement<V>(value, isNaN(ttl) ? this.ttl : ttl))
return value
}
public get(key: K): V {
this.evict()
const entry = this.map.get(key)
if (entry) {
return entry.value
}
}
public delete(key: K): boolean {
return this.map.delete(key)
}
public clear(): void {
return this.map.clear()
}
public entries(): [K, V][] {
this.evict()
return [...this.map.entries()].map((kv) => [kv[0], kv[1].value])
}
public keys(): K[] {
this.evict()
return [...this.map.keys()]
}
public has(key: K): boolean {
this.evict()
return this.map.has(key)
}
public values(): V[] {
this.evict()
return [...this.map.values()].map((e) => e.value)
}
public evict(): void {
this.map.forEach((mv, mk) => {
if (mv.expired) {
this.delete(mk)
}
})
if (!this.capacity) {
return
}
for (const [k] of [...this.map.entries()]) {
if (this.map.size <= this.capacity) {
break
}
this.delete(k)
}
}
}
| owncloud/web/packages/web-pkg/src/helpers/cache/cache.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/cache/cache.ts",
"repo_id": "owncloud",
"token_count": 749
} | 808 |
export * from './conflictDialog'
export * from './conflictUtils'
export * from './transfer'
export * from './types'
| owncloud/web/packages/web-pkg/src/helpers/resource/conflictHandling/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/resource/conflictHandling/index.ts",
"repo_id": "owncloud",
"token_count": 37
} | 809 |
/**
* Takes an object from state and creates a copy of it with only the values (no watchers, etc.)
* Editing the copied object does not result in errors due to modifying the state.
* The copied object is still reactive.
* @param {Object} state Object in the state to be copied
* @return {Object} Copied object
*/
export function cloneStateObject(state: unknown): any {
if (state === undefined) {
throw new Error('cloneStateObject: cannot clone "undefined"')
}
return JSON.parse(JSON.stringify(state))
}
| owncloud/web/packages/web-pkg/src/helpers/store.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/store.ts",
"repo_id": "owncloud",
"token_count": 139
} | 810 |
import { RouteComponents } from './router'
import { RouteLocationNamedRaw, RouteRecordRaw } from 'vue-router'
import { $gettext, createLocation, isLocationActiveDirector } from './utils'
type trashTypes = 'files-trash-generic' | 'files-trash-overview'
export const createLocationTrash = (name: trashTypes, location = {}): RouteLocationNamedRaw =>
createLocation(name, location)
export const locationTrashGeneric = createLocationTrash('files-trash-generic')
export const locationTrashOverview = createLocationTrash('files-trash-overview')
export const isLocationTrashActive = isLocationActiveDirector<trashTypes>(
locationTrashGeneric,
locationTrashOverview
)
export const buildRoutes = (components: RouteComponents): RouteRecordRaw[] => [
{
path: '/trash',
component: components.App,
children: [
{
path: 'overview',
name: locationTrashOverview.name,
component: components.Trash.Overview,
meta: {
authContext: 'user',
title: $gettext('Trash overview')
}
},
{
name: locationTrashGeneric.name,
path: ':driveAliasAndItem(.*)?',
component: components.Spaces.DriveResolver,
meta: {
authContext: 'user',
patchCleanPath: true
}
}
]
}
]
| owncloud/web/packages/web-pkg/src/router/trash.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/router/trash.ts",
"repo_id": "owncloud",
"token_count": 491
} | 811 |
export * from './types'
export * from './uppyService'
| owncloud/web/packages/web-pkg/src/services/uppy/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/services/uppy/index.ts",
"repo_id": "owncloud",
"token_count": 18
} | 812 |
import LoadingScreen from '../../../../src/components/AppTemplates/PartialViews/LoadingScreen.vue'
import { defaultPlugins, mount } from 'web-test-helpers'
describe('The external app loading screen component', () => {
test('displays a spinner and a paragraph', () => {
const wrapper = mount(LoadingScreen, {
global: {
stubs: {
OcSpinner: true
},
plugins: [...defaultPlugins()]
}
})
expect(wrapper.html()).toMatchSnapshot()
})
})
| owncloud/web/packages/web-pkg/tests/unit/components/AppTemplates/LoadingScreen.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/AppTemplates/LoadingScreen.spec.ts",
"repo_id": "owncloud",
"token_count": 188
} | 813 |
import { shallowMount } from 'web-test-helpers'
import Size from '../../../../src/components/FilesList/ResourceSize.vue'
describe('OcResourceSize', () => {
it('shows a question mark for non-numeric values', () => {
const wrapper = shallowMount(Size, {
props: {
size: 'asdf'
}
})
expect(wrapper.find('.oc-resource-size').text()).toEqual('?')
})
it("shows '--' for values smaller than 0", () => {
const wrapper = shallowMount(Size, {
props: {
size: -42
}
})
expect(wrapper.find('.oc-resource-size').text()).toEqual('--')
})
it('shows reasonable decimal places', async () => {
const wrapper = shallowMount(Size, {
props: {
size: 24064
}
})
expect(wrapper.find('.oc-resource-size').text()).toEqual('24 kB')
await wrapper.setProps({
size: 44145049
})
expect(wrapper.find('.oc-resource-size').text()).toEqual('44.1 MB')
})
it('converts strings to numbers', () => {
const wrapper = shallowMount(Size, {
props: {
size: '24064'
}
})
expect(wrapper.find('.oc-resource-size').text()).toEqual('24 kB')
})
describe('language is not defined', () => {
it('returns size if language is undefined', () => {
const localThis = { $language: undefined, size: 100 }
expect(Size.computed.formattedSize.call(localThis)).toBe('100 B')
})
it('returns size if current language is missing', () => {
const localThis = { $language: {}, size: 100 }
expect(Size.computed.formattedSize.call(localThis)).toBe('100 B')
})
})
})
| owncloud/web/packages/web-pkg/tests/unit/components/FilesList/ResourceSize.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/FilesList/ResourceSize.spec.ts",
"repo_id": "owncloud",
"token_count": 636
} | 814 |
import { mock } from 'vitest-mock-extended'
import _ from 'lodash'
import {
defaultPlugins,
mount,
shallowMount,
RouterLinkStub,
defaultComponentMocks,
RouteLocation
} from 'web-test-helpers'
import Pagination from '../../../src/components/Pagination.vue'
const filesPersonalRoute = { name: 'files-personal', path: '/files/home' }
const selectors = {
filesPagination: '.files-pagination'
}
describe('Pagination', () => {
describe('when amount of pages is', () => {
describe('less than or equals one', () => {
it.each([-1, 0, 1])('should not show wrapper', (pages) => {
const { wrapper } = getWrapper({ currentPage: 0, pages })
expect(wrapper.find(selectors.filesPagination).exists()).toBeFalsy()
})
})
describe('greater than one', () => {
const { wrapper } = getWrapper({ currentPage: 1, pages: 2 })
it('should show wrapper', () => {
const paginationEl = wrapper.find('.files-pagination')
expect(paginationEl.exists()).toBeTruthy()
expect(paginationEl.attributes().pages).toBe('2')
})
it('should set provided current page', () => {
const paginationEl = wrapper.find(selectors.filesPagination)
expect(paginationEl.attributes().currentpage).toBe('1')
})
})
})
describe('current route', () => {
it('should use provided route to render pages', () => {
const { wrapper } = getWrapper({}, mount)
const links = wrapper.findAllComponents<any>(RouterLinkStub)
// three links (route to prev, next and last page)
expect(links.length).toBe(3)
expect(links.at(0).props().to.name).toBe(filesPersonalRoute.name)
expect(links.at(1).props().to.name).toBe(filesPersonalRoute.name)
expect(links.at(2).props().to.name).toBe(filesPersonalRoute.name)
})
})
})
function getWrapper(propsData = {}, mountType = shallowMount) {
const mocks = defaultComponentMocks({ currentRoute: mock<RouteLocation>(filesPersonalRoute) })
return {
wrapper: mountType(Pagination, {
props: _.merge({ currentPage: 1, pages: 10 }, propsData),
global: {
stubs: {
RouterLink: RouterLinkStub
},
mocks,
plugins: [...defaultPlugins()]
}
}),
mocks
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/Pagination.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/Pagination.spec.ts",
"repo_id": "owncloud",
"token_count": 884
} | 815 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Details SideBar Panel > displays the details side panel 1`] = `
"<div data-v-c7ea2f9c="" id="oc-space-details-sidebar">
<div data-v-c7ea2f9c="" class="oc-space-details-sidebar-image oc-text-center">
<oc-icon-stub data-v-c7ea2f9c="" name="layout-grid" filltype="fill" accessiblelabel="" type="span" size="xxlarge" variation="passive" color="" class="space-default-image oc-px-m oc-py-m"></oc-icon-stub>
</div>
<div data-v-c7ea2f9c="" class="oc-flex oc-flex-middle oc-space-details-sidebar-members oc-mb-s oc-text-small" style="gap: 15px;">
<oc-button-stub data-v-c7ea2f9c="" type="button" disabled="false" size="medium" arialabel="Open member list in share panel" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false"></oc-button-stub>
<!--v-if-->
<p data-v-c7ea2f9c="">This space has 1 member.</p>
<oc-button-stub data-v-c7ea2f9c="" type="button" disabled="false" size="small" arialabel="Open share panel" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false"></oc-button-stub>
</div>
<table data-v-c7ea2f9c="" class="details-table oc-width-1-1" aria-label="Overview of the information about the selected space">
<col data-v-c7ea2f9c="" class="oc-width-1-3">
<col data-v-c7ea2f9c="" class="oc-width-2-3">
<tr data-v-c7ea2f9c="">
<th data-v-c7ea2f9c="" scope="col" class="oc-pr-s oc-font-semibold">Last activity</th>
<td data-v-c7ea2f9c="">Invalid DateTime</td>
</tr>
<!--v-if-->
<tr data-v-c7ea2f9c="">
<th data-v-c7ea2f9c="" scope="col" class="oc-pr-s oc-font-semibold">Manager</th>
<td data-v-c7ea2f9c=""><span data-v-c7ea2f9c="">alice (me)</span></td>
</tr>
<tr data-v-c7ea2f9c="">
<th data-v-c7ea2f9c="" scope="col" class="oc-pr-s oc-font-semibold">Quota</th>
<td data-v-c7ea2f9c="">
<space-quota-stub data-v-c7ea2f9c="" spacequota="[object Object]"></space-quota-stub>
</td>
</tr>
<!--v-if-->
<portal-target data-v-c7ea2f9c="" name="app.files.sidebar.space.details.table" slot-props="[object Object]" multiple="true"></portal-target>
</table>
</div>"
`;
| owncloud/web/packages/web-pkg/tests/unit/components/sidebar/Spaces/Details/__snapshots__/SpaceDetails.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/sidebar/Spaces/Details/__snapshots__/SpaceDetails.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 994
} | 816 |
import { useFileActionsRename } from '../../../../../src/composables/actions'
import {
useMessages,
useModals,
useResourcesStore
} from '../../../../../src/composables/piniaStores'
import { mock, mockDeep } from 'vitest-mock-extended'
import { Resource, SpaceResource } from '@ownclouders/web-client/src/helpers'
import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers'
import { unref } from 'vue'
const currentFolder = {
id: '1',
path: '/folder'
}
describe('rename', () => {
describe('computed property "actions"', () => {
describe('isVisible property of returned element', () => {
it.each([
{ resources: [{ canRename: () => true }] as Resource[], expectedStatus: true },
{ resources: [{ canRename: () => false }] as Resource[], expectedStatus: false },
{
resources: [{ canRename: () => true }, { canRename: () => true }] as Resource[],
expectedStatus: false
},
{
resources: [{ canRename: () => true, locked: true }] as Resource[],
expectedStatus: false
}
])('should be set correctly', (inputData) => {
getWrapper({
setup: ({ actions }, { space }) => {
const resources = inputData.resources
expect(unref(actions)[0].isVisible({ space, resources })).toBe(inputData.expectedStatus)
}
})
})
})
})
describe('rename action handler', () => {
it('should trigger the rename modal window', () => {
getWrapper({
setup: async ({ actions }, { space }) => {
const { dispatchModal } = useModals()
const resources = [currentFolder]
await unref(actions)[0].handler({ space, resources })
expect(dispatchModal).toHaveBeenCalledTimes(1)
}
})
})
})
describe('method "getNameErrorMsg"', () => {
it('should not show an error if new name not taken', () => {
getWrapper({
setup: ({ getNameErrorMsg }) => {
const resourcesStore = useResourcesStore()
resourcesStore.resources = [{ name: 'file1', path: '/file1' }] as Resource[]
const message = getNameErrorMsg(
{ name: 'currentName', path: '/currentName' } as Resource,
'newName'
)
expect(message).toEqual(null)
}
})
})
it('should not show an error if new name already exists but in different folder', () => {
getWrapper({
setup: ({ getNameErrorMsg }) => {
const resourcesStore = useResourcesStore()
resourcesStore.resources = [{ name: 'file1', path: '/file1' }] as Resource[]
const message = getNameErrorMsg(
mock<Resource>({ name: 'currentName', path: '/favorites/currentName' }),
'file1'
)
expect(message).toEqual(null)
}
})
})
it.each([
{ currentName: 'currentName', newName: '', message: 'The name cannot be empty' },
{ currentName: 'currentName', newName: 'new/name', message: 'The name cannot contain "/"' },
{ currentName: 'currentName', newName: '.', message: 'The name cannot be equal to "."' },
{ currentName: 'currentName', newName: '..', message: 'The name cannot be equal to ".."' },
{
currentName: 'currentName',
newName: 'newname ',
message: 'The name cannot end with whitespace'
},
{
currentName: 'currentName',
newName: 'file1',
message: 'The name "file1" is already taken'
},
{
currentName: 'currentName',
newName: 'newname',
parentResources: [{ name: 'newname', path: '/newname' }],
message: 'The name "newname" is already taken'
}
])('should detect name errors and display error messages accordingly', (inputData) => {
getWrapper({
setup: ({ getNameErrorMsg }) => {
const resourcesStore = useResourcesStore()
resourcesStore.resources = [{ name: 'file1', path: '/file1' }] as Resource[]
const message = getNameErrorMsg(
mock<Resource>({ name: inputData.currentName, path: `/${inputData.currentName}` }),
inputData.newName,
inputData.parentResources
)
expect(message).toEqual(inputData.message)
}
})
})
})
describe('method "renameResource"', () => {
it('should call the rename action on a resource in the file list', () => {
getWrapper({
setup: async ({ renameResource }, { space }) => {
const resource = { id: '2', path: '/folder', webDavPath: '/files/admin/folder' }
await renameResource(space, resource, 'new name')
const { upsertResource } = useResourcesStore()
expect(upsertResource).toHaveBeenCalledTimes(1)
}
})
})
it('should call the rename action on the current folder', () => {
getWrapper({
setup: async ({ renameResource }, { space }) => {
await renameResource(space, currentFolder, 'new name')
const { upsertResource } = useResourcesStore()
expect(upsertResource).toHaveBeenCalledTimes(1)
}
})
})
it('should handle errors properly', () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
getWrapper({
setup: async ({ renameResource }, { space, clientService }) => {
clientService.webdav.moveFiles.mockRejectedValueOnce(new Error())
await renameResource(space, currentFolder, 'new name')
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalledTimes(1)
}
})
})
})
})
function getWrapper({
setup
}: {
setup: (
instance: ReturnType<typeof useFileActionsRename>,
{
space,
clientService
}: {
space: SpaceResource
clientService: ReturnType<typeof defaultComponentMocks>['$clientService']
}
) => void
}) {
const mocks = {
...defaultComponentMocks(),
space: mockDeep<SpaceResource>({
webDavPath: 'irrelevant'
})
}
return {
mocks,
wrapper: getComposableWrapper(
() => {
const instance = useFileActionsRename()
setup(instance, { space: mocks.space, clientService: mocks.$clientService })
},
{
mocks,
provide: mocks
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsRename.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsRename.spec.ts",
"repo_id": "owncloud",
"token_count": 2621
} | 817 |
import { unref } from 'vue'
import { SpaceResource } from '@ownclouders/web-client/src'
import { useSpaceActionsShowMembers } from '../../../../../src/composables/actions'
import { getComposableWrapper } from 'web-test-helpers'
describe('showMembers', () => {
describe('isVisible property', () => {
it('should be false when no resource given', () => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [] })).toBe(false)
}
})
})
it('should be true when a resource is given', () => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [{ id: '1' } as SpaceResource] })).toBe(
true
)
}
})
})
})
})
function getWrapper({
setup
}: {
setup: (instance: ReturnType<typeof useSpaceActionsShowMembers>) => void
}) {
return {
wrapper: getComposableWrapper(() => {
const instance = useSpaceActionsShowMembers()
setup(instance)
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsShowMembers.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsShowMembers.spec.ts",
"repo_id": "owncloud",
"token_count": 421
} | 818 |
import { useLocalStorage, usePreferredDark } from '@vueuse/core'
import { useThemeStore, WebThemeConfigType } from '../../../../src/composables/piniaStores'
import { mockDeep } from 'vitest-mock-extended'
import { createPinia, setActivePinia } from 'pinia'
import { ref } from 'vue'
vi.mock('@vueuse/core', () => {
return { useLocalStorage: vi.fn(() => ref('')), usePreferredDark: vi.fn(() => ref(false)) }
})
describe('useThemeStore', () => {
beforeEach(() => {
setActivePinia(createPinia())
})
describe('initializeThemes', () => {
it('sets availableThemes', () => {
const themeConfig = mockDeep<WebThemeConfigType>()
themeConfig.themes = [
{ name: 'light', designTokens: {}, isDark: false },
{ name: 'dark', designTokens: {}, isDark: true }
]
const store = useThemeStore()
store.initializeThemes(themeConfig)
expect(store.availableThemes.length).toBe(themeConfig.themes.length)
})
describe('currentTheme', () => {
it.each([true, false])('gets set based on the OS setting', (isDark) => {
vi.mocked(usePreferredDark).mockReturnValue(ref(isDark))
vi.mocked(useLocalStorage).mockReturnValue(ref(null))
const themeConfig = mockDeep<WebThemeConfigType>()
themeConfig.themes = [
{ name: 'light', designTokens: {}, isDark: false },
{ name: 'dark', designTokens: {}, isDark: true }
]
themeConfig.defaults = {}
const store = useThemeStore()
store.initializeThemes(themeConfig)
expect(store.currentTheme.name).toEqual(
themeConfig.themes.find((t) => t.isDark === isDark).name
)
})
it('falls back to the first theme if no match for the OS setting is found', () => {
vi.mocked(usePreferredDark).mockReturnValue(ref(true))
vi.mocked(useLocalStorage).mockReturnValue(ref(null))
const themeConfig = mockDeep<WebThemeConfigType>()
themeConfig.themes = [{ name: 'light', designTokens: {}, isDark: false }]
themeConfig.defaults = {}
const store = useThemeStore()
store.initializeThemes(themeConfig)
expect(store.currentTheme.name).toEqual('light')
})
})
})
})
| owncloud/web/packages/web-pkg/tests/unit/composables/piniaStores/theme.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/piniaStores/theme.spec.ts",
"repo_id": "owncloud",
"token_count": 887
} | 819 |
import { canBeMoved } from '../../../src/helpers/permissions'
describe('permissions helper', () => {
describe('canBeMoved function', () => {
it.each([
{ isReceivedShare: false, isMounted: false, canBeDeleted: true, parentPath: '' },
{ isReceivedShare: false, isMounted: false, canBeDeleted: true, parentPath: 'folder' },
{ isReceivedShare: true, isMounted: false, canBeDeleted: true, parentPath: 'folder' },
{ isReceivedShare: false, isMounted: true, canBeDeleted: true, parentPath: 'folder' }
])(
'should return true if the given resource can be deleted and if it is not mounted in root',
(input) => {
// resources are supposed to be external if it is a received share or is mounted
// resources are supposed to be mountedInRoot if its parentPath is an empty string and resource is external
expect(
canBeMoved(
{
isReceivedShare: () => input.isReceivedShare,
isMounted: () => input.isMounted,
canBeDeleted: () => input.canBeDeleted
},
input.parentPath
)
).toBeTruthy()
}
)
it.each([
{ isReceivedShare: false, isMounted: false, canBeDeleted: false, parentPath: '' },
{ isReceivedShare: false, isMounted: false, canBeDeleted: false, parentPath: 'folder' },
{ isReceivedShare: true, isMounted: false, canBeDeleted: false, parentPath: 'folder' },
{ isReceivedShare: false, isMounted: true, canBeDeleted: false, parentPath: 'folder' },
{ isReceivedShare: false, isMounted: true, canBeDeleted: true, parentPath: '' },
{ isReceivedShare: true, isMounted: false, canBeDeleted: true, parentPath: '' },
{ isReceivedShare: true, isMounted: true, canBeDeleted: true, parentPath: '' }
])(
'should return false if the given resource cannot be deleted or if it is mounted in root',
(input) => {
expect(
canBeMoved(
{
isReceivedShare: () => input.isReceivedShare,
isMounted: () => input.isMounted,
canBeDeleted: () => input.canBeDeleted
},
input.parentPath
)
).toBeFalsy()
}
)
})
})
| owncloud/web/packages/web-pkg/tests/unit/helpers/permissions.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/permissions.spec.ts",
"repo_id": "owncloud",
"token_count": 940
} | 820 |
import { LoadingService } from '../../../src/services/loadingService'
describe('LoadingService', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('adds a task and sets it inactive initially', () => {
const service = new LoadingService()
const action = new Promise((resolve) => {
resolve(true)
})
service.addTask(() => action)
expect(service.isLoading).toBeFalsy()
})
it('adds a task and sets it active after the debounce', () => {
const service = new LoadingService()
const action = new Promise((resolve) => {
resolve(true)
})
service.addTask(() => action)
vi.runAllTimers()
expect(service.isLoading).toBeTruthy()
})
it('removes a task after being finished', async () => {
const service = new LoadingService()
const action = new Promise((resolve) => {
resolve(true)
})
await service.addTask(() => action)
vi.runAllTimers()
expect(service.isLoading).toBeFalsy()
})
it('returns the current progress of a running task', () => {
const service = new LoadingService()
const expectedResult = {
1: 25,
2: 50,
3: 75,
4: 100
}
service.addTask(
({ setProgress }) => {
const promises = []
const actions = [1, 2, 3, 4]
for (const action of actions) {
promises.push(
new Promise((resolve) => {
resolve(true)
}).then(() => {
setProgress({ total: actions.length, current: action })
expect(service.currentProgress).toBe(expectedResult[action])
})
)
}
return Promise.all(promises)
},
{ indeterminate: false }
)
vi.runAllTimers()
})
})
| owncloud/web/packages/web-pkg/tests/unit/services/loadingService.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/services/loadingService.spec.ts",
"repo_id": "owncloud",
"token_count": 737
} | 821 |
<template>
<oc-notifications :position="notificationPosition">
<oc-notification-message
v-for="item in limitedMessages"
:key="item.id"
:title="item.title"
:message="item.desc"
:status="item.status"
:timeout="item.timeout"
:error-log-content="item.errorLogContent"
@close="deleteMessage(item)"
/>
</oc-notifications>
</template>
<script lang="ts">
import { Message, useConfigStore, useMessages } from '@ownclouders/web-pkg'
import { computed, defineComponent } from 'vue'
export default defineComponent({
name: 'MessageBar',
setup() {
const messageStore = useMessages()
const configStore = useConfigStore()
const notificationPosition = computed(() => {
if (configStore.options.topCenterNotifications) {
return 'top-center'
}
return 'default'
})
const limitedMessages = computed(() => {
return messageStore.messages ? messageStore.messages.slice(0, 5) : []
})
const deleteMessage = (message: Message) => {
messageStore.removeMessage(message)
}
return { notificationPosition, limitedMessages, deleteMessage }
}
})
</script>
| owncloud/web/packages/web-runtime/src/components/MessageBar.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/components/MessageBar.vue",
"repo_id": "owncloud",
"token_count": 422
} | 822 |
import { computed, unref } from 'vue'
import { useHead as _useHead } from '@vueuse/head'
import { getBackendVersion, getWebVersion } from 'web-runtime/src/container/versions'
import { useCapabilityStore, useThemeStore } from '@ownclouders/web-pkg'
import { storeToRefs } from 'pinia'
export const useHead = () => {
const themeStore = useThemeStore()
const capabilityStore = useCapabilityStore()
const { currentTheme } = storeToRefs(themeStore)
const favicon = computed(() => currentTheme.value.logo.favicon)
_useHead(
computed(() => {
return {
meta: [
{
name: 'generator',
content: [getWebVersion(), getBackendVersion({ capabilityStore })]
.filter(Boolean)
.join(', ')
}
],
...(unref(favicon) && { link: [{ rel: 'icon', href: unref(favicon) }] })
}
})
)
}
| owncloud/web/packages/web-runtime/src/composables/head/useHead.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/composables/head/useHead.ts",
"repo_id": "owncloud",
"token_count": 369
} | 823 |
//Please also make language adjustments in packages/web-pkg/src/components/TextEditor.vue
export const supportedLanguages = {
bg: 'български - Bulgarian',
cs: 'Čeština - Czech',
de: 'Deutsch - German',
en: 'English',
es: 'Español - Spanish',
fr: 'Français - French',
it: 'Italiano - Italian',
nl: 'Nederlands - Dutch',
ko: '한국어 - Korean',
sq: 'Shqipja - Albanian',
sv: 'Svenska - Swedish',
tr: 'Türkçe - Turkish',
zh: '汉语 - Chinese'
}
| owncloud/web/packages/web-runtime/src/defaults/languages.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/defaults/languages.ts",
"repo_id": "owncloud",
"token_count": 201
} | 824 |
<template>
<div class="oc-width-1-1 oc-height-1-1">
<app-loading-spinner v-if="autoRedirect" />
<div v-else class="oc-height-viewport oc-flex oc-flex-column oc-flex-center oc-flex-middle">
<div class="oc-login-card">
<img class="oc-login-logo" :src="logoImg" alt="" :aria-hidden="true" />
<div class="oc-login-card-body oc-width-medium">
<h2 class="oc-login-card-title">
<span v-text="$gettext('Welcome to %{productName}', { productName })" />
</h2>
<p v-translate>
Please click the button below to authenticate and get access to your data.
</p>
</div>
<div class="oc-login-card-footer oc-pt-rm">
<p>{{ footerSlogan }}</p>
</div>
</div>
<oc-button
id="authenticate"
size="large"
variation="primary"
appearance="filled"
class="oc-mt-m oc-width-medium oc-login-authorize-button"
@click="performLogin"
>
<span v-text="$gettext('Login')" />
</oc-button>
</div>
</div>
</template>
<script lang="ts">
import { authService } from '../services/auth'
import { queryItemAsString, useRouteQuery, useThemeStore } from '@ownclouders/web-pkg'
import { computed, defineComponent, unref } from 'vue'
import { AppLoadingSpinner } from '@ownclouders/web-pkg'
import { storeToRefs } from 'pinia'
export default defineComponent({
name: 'LoginPage',
components: {
AppLoadingSpinner
},
setup() {
const themeStore = useThemeStore()
const { currentTheme } = storeToRefs(themeStore)
const redirectUrl = useRouteQuery('redirectUrl')
const performLogin = () => {
authService.loginUser(queryItemAsString(unref(redirectUrl)))
}
const autoRedirect = computed(() => currentTheme.value.loginPage.autoRedirect)
if (unref(autoRedirect)) {
performLogin()
}
const productName = computed(() => currentTheme.value.common.name)
const logoImg = computed(() => currentTheme.value.logo.login)
const footerSlogan = computed(() => currentTheme.value.common.slogan)
return {
autoRedirect,
productName,
logoImg,
footerSlogan,
performLogin
}
}
})
</script>
| owncloud/web/packages/web-runtime/src/pages/login.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/pages/login.vue",
"repo_id": "owncloud",
"token_count": 947
} | 825 |
export default [
{
name: 'Personal',
icon: 'folder',
route: {
name: 'files-personal',
path: '/files/list/all'
},
active: true
},
{
name: 'Shares',
icon: 'share-forward',
route: {
name: 'files-shared-with-me',
path: '/files/list/shared-with-me'
},
active: false
},
{
name: 'Deleted files',
icon: 'delete',
route: {
name: 'files-trashbin',
path: '/files/list/trash-bin'
},
active: false
}
]
| owncloud/web/packages/web-runtime/tests/__fixtures__/sidebarNavItems.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/__fixtures__/sidebarNavItems.ts",
"repo_id": "owncloud",
"token_count": 236
} | 826 |
import SidebarToggle from '../../../../src/components/Topbar/SideBarToggle.vue'
import { eventBus } from '@ownclouders/web-pkg/src/services'
import { defaultPlugins, mount, defaultComponentMocks } from 'web-test-helpers'
const selectors = {
toggleSidebarBtn: '#files-toggle-sidebar'
}
describe('SidebarToggle component', () => {
it.each([true, false])(
'should show the "Toggle sidebar"-button with sidebar opened and closed',
(isSideBarOpen) => {
const { wrapper } = getWrapper({ isSideBarOpen })
expect(wrapper.find(selectors.toggleSidebarBtn).exists()).toBeTruthy()
expect(wrapper.html()).toMatchSnapshot()
}
)
it('publishes the toggle-event to the sidebar on click', async () => {
const { wrapper } = getWrapper()
const eventSpy = vi.spyOn(eventBus, 'publish')
await wrapper.find(selectors.toggleSidebarBtn).trigger('click')
expect(eventSpy).toHaveBeenCalled()
})
})
function getWrapper({ isSideBarOpen = false } = {}) {
const mocks = defaultComponentMocks()
return {
mocks,
wrapper: mount(SidebarToggle, {
props: { isSideBarOpen },
global: {
mocks,
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/components/Topbar/SidebarToggle.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Topbar/SidebarToggle.spec.ts",
"repo_id": "owncloud",
"token_count": 452
} | 827 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`resolvePublicLink > password required form > should display if password is required 1`] = `
"<form>
<div class="oc-card-header">
<h2><span>This resource is password-protected</span></h2>
</div>
<div class="oc-card-body">
<oc-text-input-stub id="oc-textinput-2" type="password" modelvalue="" clearbuttonenabled="false" clearbuttonaccessiblelabel="" disabled="false" label="Enter password for public link" fixmessageline="false" readonly="false" passwordpolicy="[object Object]" class="oc-mb-s"></oc-text-input-stub>
<oc-button-stub type="button" disabled="true" size="medium" submit="submit" variation="primary" appearance="filled" justifycontent="center" gapsize="medium" showspinner="false" class="oc-login-authorize-button"></oc-button-stub>
</div>
</form>"
`;
exports[`resolvePublicLink > should display the configuration theme general slogan as the login card footer 1`] = `
"<div class="oc-card-footer oc-pt-rm">
<p>ownCloud – A safe home for all your data</p>
</div>"
`;
| owncloud/web/packages/web-runtime/tests/unit/pages/__snapshots__/resolvePublicLink.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/pages/__snapshots__/resolvePublicLink.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 347
} | 828 |
import DesignSystem from '../../design-system'
import { createGettext } from 'vue3-gettext'
import { h } from 'vue'
import { abilitiesPlugin } from '@casl/vue'
import { createMongoAbility } from '@casl/ability'
import { AbilityRule } from '../../web-client/src/helpers/resource/types'
import { PiniaMockOptions, createMockStore } from './mocks'
export interface DefaultPluginsOptions {
abilities?: AbilityRule[]
designSystem?: boolean
gettext?: boolean
pinia?: boolean
piniaOptions?: PiniaMockOptions
}
export const defaultPlugins = ({
abilities = [],
designSystem = true,
gettext = true,
pinia = true,
piniaOptions = {}
}: DefaultPluginsOptions = {}) => {
const plugins = []
plugins.push({
install(app) {
app.use(abilitiesPlugin, createMongoAbility(abilities))
}
})
if (designSystem) {
plugins.push(DesignSystem)
}
if (gettext) {
plugins.push(createGettext({ translations: {}, silent: true }))
} else {
plugins.push({
install(app) {
// mock `v-translate` directive
app.directive('translate', {
inserted: () => undefined
})
}
})
}
if (pinia) {
plugins.push(createMockStore(piniaOptions))
}
plugins.push({
install(app) {
app.component('RouterLink', {
name: 'RouterLink',
props: {
tag: { type: String, default: 'a' },
to: { type: [String, Object], default: '' }
},
render() {
let path = this.$props.to
if (!!path && typeof path !== 'string') {
path = this.$props.to.path || this.$props.to.name
if (this.$props.to.params) {
path += '/' + Object.values(this.$props.to.params).join('/')
}
if (this.$props.to.query) {
path += '?' + Object.values(this.$props.to.query).join('&')
}
}
return h(this.tag, { attrs: { href: path } }, this.$slots.default)
}
})
}
})
return plugins
}
| owncloud/web/packages/web-test-helpers/src/defaultPlugins.ts/0 | {
"file_path": "owncloud/web/packages/web-test-helpers/src/defaultPlugins.ts",
"repo_id": "owncloud",
"token_count": 856
} | 829 |
import { pbkdf2 } from '@noble/hashes/pbkdf2'
import { sha512 } from '@noble/hashes/sha512'
export const pbkdf2Sync = (password, salt, c, dkLen) => {
return Buffer.from(pbkdf2(sha512, password, salt, { c, dkLen }))
}
| owncloud/web/polyfills/crypto.js/0 | {
"file_path": "owncloud/web/polyfills/crypto.js",
"repo_id": "owncloud",
"token_count": 95
} | 830 |
/**
*
* waits till the element is enabled, at that stage it is "clickable"
* this function seems to wait longer than waitForElementVisible() and waitForElementNotVisible() for animated elements
* for animated elements waitForElementVisible and waitForElementNotVisible already finish before the animation is finished
* elements behind the disappearing animated element might not be clickable yet when waitForElementNotVisible finish
* also when trying to use an element that is animated to appear, waitForElementVisible does not always wait long enough
*
* copied from: https://gist.github.com/deterralba/5862ec98613dbf073545a7d7e87a637d
* More info https://github.com/nightwatchjs/nightwatch/issues/705
*
* @param selector
* @param locateStrategy 'css selector' or 'xpath'
* @param timeout defaults to this.globals.waitForConditionTimeout
* @returns {exports}
*/
module.exports.command = function (
selector,
locateStrategy = 'css selector',
timeout = this.globals.waitForConditionTimeout
) {
let self = this
if (locateStrategy === 'xpath') {
self = this.useXpath()
} else if (locateStrategy === 'css selector') {
self = this.useCss()
} else {
return this.assert.fail('invalid locateStrategy')
}
self.expect.element(selector).enabled.before(timeout)
return self
}
| owncloud/web/tests/acceptance/customCommands/waitForElementEnabled.js/0 | {
"file_path": "owncloud/web/tests/acceptance/customCommands/waitForElementEnabled.js",
"repo_id": "owncloud",
"token_count": 382
} | 831 |
# Most of the tests in this file is skipped in OCIS most of the tests set minimum characters for search
# while it can be configured in OCIS too but not in the same manner as oc10
# the skipped tests are listed in issue https://github.com/owncloud/web/issues/7264 for further implementation in playwright
Feature: Autocompletion of share-with names
As a user
I want to share files, with minimal typing, to the right people or groups
So that I can efficiently share my files with other users or groups
Background:
Given the administrator has set the default folder for received shares to "Shares" in the server
# Users that are in the special known users already
And these users have been created with default attributes and without skeleton files in the server but not initialized:
| username |
| Alice |
| Carol |
| usergrp |
| regularuser |
# Some extra users to make the share autocompletion interesting
And these users have been created without initialization and without skeleton files in the server:
| username | password | displayname | email |
| two | %regular% | Brian Murphy | u2@oc.com.np |
| u444 | %regular% | Four | u3@oc.com.np |
| five | %regular% | User Group | five@oc.com.np |
| usersmith | %regular% | John Finn Smith | js@oc.com.np |
And these groups have been created in the server:
| groupname |
| finance1 |
| finance2 |
| finance3 |
| users-finance |
| other |
Scenario: autocompletion for a pattern that does not match any user or group
Given user "regularuser" has created folder "simple-folder" in the server
And user "regularuser" has logged in using the webUI
And the user has browsed to the personal page
And the user has opened the share dialog for folder "simple-folder"
When the user types "doesnotexist" in the share-with-field
Then the autocomplete list should not be displayed on the webUI
Scenario: autocompletion when minimum characters is the default (2) and not enough characters are typed
Given user "regularuser" has created folder "simple-folder" in the server
And user "regularuser" has logged in using the webUI
And the user has browsed to the personal page
And the user has opened the share dialog for folder "simple-folder"
When the user types "u" in the share-with-field
Then the autocomplete list should not be displayed on the webUI
Scenario: add collaborators in the invite list and remove some of them
Given user "regularuser" has created folder "simple-folder" in the server
And user "regularuser" has logged in using the webUI
And the user has opened the share dialog for folder "simple-folder"
When the user selects the following collaborators for the share as "Viewer" with "," permissions:
| collaborator | type |
| Alice Hansen | user |
| Carol King | user |
| John Finn Smith | user |
| finance1 | group |
| finance3 | group |
And the user removes "John Finn Smith" as a collaborator from the share
And the user removes "Carol King" as a collaborator from the share
And the user removes "finance3" as a collaborator from the share
Then user "John Finn Smith" should not be visible in the collaborators selected options in the webUI
And user "Carol King" should not be visible in the collaborators selected options in the webUI
And group "finance3" should not be visible in the collaborators selected options in the webUI
But user "Alice Hansen" should be visible in the collaborators selected options in the webUI
And group "finance1" should be visible in the collaborators selected options in the webUI
| owncloud/web/tests/acceptance/features/webUISharingAutocompletion/shareAutocompletion.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUISharingAutocompletion/shareAutocompletion.feature",
"repo_id": "owncloud",
"token_count": 1198
} | 832 |
@files_trashbin-app-required @ocis-reva-issue-112
Feature: Restore deleted files/folders
As a user
I would like to restore files/folders
So that I can recover accidentally deleted files/folders in ownCloud
Background:
Given user "Alice" has been created with default attributes and without skeleton files in the server
And user "Alice" has created file "sample,1.txt" in the server
And user "Alice" has created folder "Folder,With,Comma" in the server
And user "Alice" has logged in using the webUI
@smokeTest @ocisSmokeTest
Scenario: Restore files
Given user "Alice" has uploaded file "data.zip" to "data.zip" in the server
And the user has reloaded the current page of the webUI
When the user deletes file "data.zip" using the webUI
And the user deletes file "sample,1.txt" using the webUI
And the user browses to the trashbin page
Then file "data.zip" should be listed on the webUI
And file "sample,1.txt" should be listed on the webUI
When the user restores file "data.zip" from the trashbin using the webUI
And the user restores file "sample,1.txt" from the trashbin using the webUI
Then there should be no resources listed on the webUI
When the user browses to the files page
Then file "data.zip" should be listed on the webUI
And file "sample,1.txt" should be listed on the webUI
Scenario: Restore folder
Given user "Alice" has created folder "folder with space" in the server
And the user has browsed to the personal page
When the user deletes folder "folder with space" using the webUI
And the user deletes folder "Folder,With,Comma" using the webUI
And the user browses to the trashbin page
Then folder "folder with space" should be listed on the webUI
And folder "Folder,With,Comma" should be listed on the webUI
When the user restores folder "folder with space" from the trashbin using the webUI
And the user restores folder "Folder,With,Comma" from the trashbin using the webUI
Then there should be no resources listed on the webUI
When the user browses to the files page
Then folder "folder with space" should be listed on the webUI
And folder "Folder,With,Comma" should be listed on the webUI
@smokeTest @issue-1502
Scenario: Select some trashbin files and restore them in a batch
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has uploaded file "data.zip" to "data.zip" in the server
And user "Alice" has uploaded file "lorem.txt" to "lorem.txt" in the server
And user "Alice" has uploaded file "lorem-big.txt" to "lorem-big.txt" in the server
And the following files have been deleted by user "Alice" in the server
| name |
| data.zip |
| lorem.txt |
| lorem-big.txt |
| simple-folder |
| sample,1.txt |
| Folder,With,Comma |
And the user has browsed to the trashbin page
When the user marks these files for batch action using the webUI
| name |
| lorem.txt |
| lorem-big.txt |
| sample,1.txt |
| Folder,With,Comma |
And the user batch restores the marked files using the webUI
# You can delete the line below after the issue-1502 is fixed
And the user reloads the current page of the webUI
Then file "data.zip" should be listed on the webUI
And folder "simple-folder" should be listed on the webUI
But file "lorem.txt" should not be listed on the webUI
And file "lorem-big.txt" should not be listed on the webUI
And file "sample,1.txt" should not be listed on the webUI
And folder "Folder,With,Comma" should not be listed on the webUI
When the user browses to the files page
And file "lorem.txt" should be listed on the webUI
And file "lorem-big.txt" should be listed on the webUI
And file "sample,1.txt" should be listed on the webUI
And folder "Folder,With,Comma" should be listed on the webUI
But file "data.zip" should not be listed on the webUI
And folder "simple-folder" should not be listed on the webUI
@issue-1502
Scenario: Select all except for some trashbin files and restore them in a batch
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has uploaded file "data.zip" to "data.zip" in the server
And user "Alice" has uploaded file "lorem.txt" to "lorem.txt" in the server
And user "Alice" has uploaded file "lorem-big.txt" to "lorem-big.txt" in the server
And the following files have been deleted by user "Alice" in the server
| name |
| data.zip |
| lorem.txt |
| lorem-big.txt |
| simple-folder |
And the user has browsed to the trashbin page
When the user marks all files for batch action using the webUI
And the user unmarks these files for batch action using the webUI
| name |
| lorem.txt |
| lorem-big.txt |
And the user batch restores the marked files using the webUI
# You can delete the line below after the issue-1502 is fixed
And the user reloads the current page of the webUI
Then file "lorem.txt" should be listed on the webUI
And file "lorem-big.txt" should be listed on the webUI
But file "data.zip" should not be listed on the webUI
And folder "simple-folder" should not be listed on the webUI
When the user browses to the files page
Then file "data.zip" should be listed on the webUI
And folder "simple-folder" should be listed on the webUI
But file "lorem.txt" should not be listed on the webUI
And file "lorem-big.txt" should not be listed on the webUI
@skipOnOC10 @issue-core-38039
Scenario: Select all trashbin files and restore them in a batch
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has uploaded file "data.zip" to "data.zip" in the server
And user "Alice" has uploaded file "lorem.txt" to "lorem.txt" in the server
And user "Alice" has uploaded file "lorem-big.txt" to "lorem-big.txt" in the server
And the following files have been deleted by user "Alice" in the server
| name |
| data.zip |
| lorem.txt |
| lorem-big.txt |
| simple-folder |
And the user has browsed to the trashbin page
When the user marks all files for batch action using the webUI
And the user batch restores the marked files using the webUI
Then there should be no resources listed on the webUI
And there should be no resources listed on the webUI after a page reload
When the user browses to the files page
Then file "lorem.txt" should be listed on the webUI
And file "lorem-big.txt" should be listed on the webUI
And file "data.zip" should be listed on the webUI
And folder "simple-folder" should be listed on the webUI
@issue-1723
Scenario: Delete and restore a file that has the same name like a deleted folder
Given user "Alice" has uploaded file "lorem.txt" to "lorem.txt" in the server
And the following files have been deleted by user "Alice" in the server
| name |
| lorem.txt |
And user "Alice" has created folder "lorem.txt" in the server
And the following folders have been deleted by user "Alice" in the server
| name |
| lorem.txt |
When the user browses to the trashbin page
And the user restores file "lorem.txt" from the trashbin using the webUI
Then the "success" message with header "lorem.txt was restored successfully" should be displayed on the webUI
And file "lorem.txt" should not be listed on the webUI
And folder "lorem.txt" should be listed on the webUI
When the user browses to the files page using the webUI
Then file "lorem.txt" should be listed on the webUI
And folder "lorem.txt" should not be listed on the webUI
Scenario: Delete and restore a folder that has the same name like a deleted file
Given user "Alice" has created file "lorem.txt" in the server
And the following files have been deleted by user "Alice" in the server
| name |
| lorem.txt |
And user "Alice" has created folder "lorem.txt" in the server
And the following folders have been deleted by user "Alice" in the server
| name |
| lorem.txt |
When the user browses to the trashbin page
And the user restores folder "lorem.txt" from the trashbin using the webUI
Then the "success" message with header "lorem.txt was restored successfully" should be displayed on the webUI
And folder "lorem.txt" should not be listed on the webUI
And file "lorem.txt" should be listed on the webUI
When the user browses to the files page using the webUI
Then folder "lorem.txt" should be listed on the webUI
And file "lorem.txt" should not be listed on the webUI
@issue-1502
Scenario: Delete and restore folders with dot in the name
Given user "Alice" has created the following folders in the server
| folders |
| fo. |
| fo.1 |
| fo...1.. |
| fo.xyz |
And the following folders have been deleted by user "Alice" in the server
| name |
| fo. |
| fo.1 |
| fo...1.. |
| fo.xyz |
And the user has browsed to the trashbin page
When the user marks these files for batch action using the webUI
| name |
| fo. |
| fo.1 |
| fo...1.. |
| fo.xyz |
And the user batch restores the marked files using the webUI
And the user reloads the current page of the webUI
Then these folders should not be listed on the webUI
| name |
| fo. |
| fo.1 |
| fo...1.. |
| fo.xyz |
When the user browses to the files page
Then the following folders should be listed on the webUI
| name |
| fo. |
| fo.1 |
| fo...1.. |
| fo.xyz |
| owncloud/web/tests/acceptance/features/webUITrashbinRestore/trashbinRestore.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUITrashbinRestore/trashbinRestore.feature",
"repo_id": "owncloud",
"token_count": 3460
} | 833 |
const httpHelper = require('../helpers/httpHelper')
const convert = require('xml-js')
const _ = require('lodash/object')
const { normalize } = require('../helpers/path')
/**
*
* @param {string} userId
* @param {string} element
*/
exports.createDavPath = function (userId, element) {
const replaceEncoded = encodeURIComponent(element).replace(/%2F/g, '/')
return `files/${userId}/${replaceEncoded}`
}
/**
*
* @param {string} path
* @param {string} userId
* @param {array} properties
* @param {number} folderDepth
*/
exports.propfind = function (path, userId, properties, folderDepth = '1') {
const davPath = encodeURI(path)
let propertyBody = ''
properties.forEach((prop) => {
propertyBody += `<${prop}/>`
})
const body = `<?xml version="1.0"?>
<d:propfind
xmlns:d="DAV:"
xmlns:oc="http://owncloud.org/ns"
xmlns:ocs="http://open-collaboration-services.org/ns">
<d:prop>${propertyBody}</d:prop>
</d:propfind>`
return httpHelper
.propfind(davPath, userId, body, { Depth: folderDepth })
.then((res) => res.text())
}
/**
* Get file or folder properties using webDAV api.
*
* @param {string} path
* @param {string} userId
* @param {array} requestedProps
*/
exports.getProperties = function (path, userId, requestedProps) {
return new Promise((resolve, reject) => {
const trimmedPath = normalize(path) // remove a leading slash
const relativePath = `/files/${userId}/${trimmedPath}`
exports.propfind(relativePath, userId, requestedProps, 0).then((str) => {
const response = JSON.parse(convert.xml2json(str, { compact: true }))
const receivedProps = _.get(
response,
"['d:multistatus']['d:response']['d:propstat']['d:prop']"
)
if (receivedProps === undefined) {
const errMsg = "Could not find 'd:prop' inside response. Received:\n"
return reject(new Error(errMsg + JSON.stringify(str)))
}
const properties = {}
requestedProps.forEach((propertyName) => {
properties[propertyName] = receivedProps[propertyName]._text
})
return resolve(properties)
})
})
}
| owncloud/web/tests/acceptance/helpers/webdavHelper.js/0 | {
"file_path": "owncloud/web/tests/acceptance/helpers/webdavHelper.js",
"repo_id": "owncloud",
"token_count": 869
} | 834 |
const { join } = require('../helpers/path')
module.exports = {
url: function () {
return join(this.api.launchUrl, '/account/')
},
commands: {
/**
* like build-in navigate() but also waits for the account display element
* @returns {Promise}
*/
navigateAndWaitTillLoaded: function () {
return this.navigate(this.url()).waitForElementVisible('@accountDisplay')
},
/**
* return the visibility of the account display element
* @returns {Promise<boolean>}
*/
isPageVisible: async function () {
let isVisible = true
await this.api.element('@accountDisplay', (result) => {
isVisible = Object.keys(result.value).length > 0
})
return isVisible
}
},
elements: {
accountDisplay: {
selector: '#account-page-title'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/accountPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/accountPage.js",
"repo_id": "owncloud",
"token_count": 322
} | 835 |
const { join } = require('../helpers/path')
module.exports = {
url: function () {
return join(this.api.launchUrl, '/files/trash/')
},
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
)
},
clearTrashbin: function () {
return this.waitForElementVisible('@clearTrashbin')
.initAjaxCounters()
.click('@clearTrashbin')
.waitForElementVisible('@dialog')
.waitForAnimationToFinish() // wait for transition on the modal to finish
.click('@dialogConfirmBtnEnabled')
.waitForAjaxCallsToStartAndFinish()
.waitForElementNotPresent('@dialog')
},
restoreSelected: function () {
return this.waitForElementVisible('@restoreSelectedButton')
.initAjaxCounters()
.click('@restoreSelectedButton')
.waitForOutstandingAjaxCalls()
.waitForElementNotPresent('@restoreSelectedButton')
},
deleteSelectedPermanently: function () {
return this.waitForElementVisible('@deleteSelectedPermanentlyButton')
.click('@deleteSelectedPermanentlyButton')
.waitForElementVisible('@dialog')
.waitForAnimationToFinish() // wait for transition on the modal to finish
.click('@dialogConfirmBtnEnabled')
.waitForAjaxCallsToStartAndFinish()
.waitForElementNotPresent('@dialog')
}
},
elements: {
dialog: {
selector: '.oc-modal'
},
dialogConfirmBtnEnabled: {
selector: '.oc-modal-body-actions-confirm:enabled'
},
clearTrashbin: {
selector: '.oc-files-actions-empty-trash-bin-trigger:not([disabled])'
},
restoreSelectedButton: {
selector: '.oc-files-actions-restore-trigger'
},
deleteSelectedPermanentlyButton: {
selector: '.oc-files-actions-delete-permanent-trigger'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/trashbinPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/trashbinPage.js",
"repo_id": "owncloud",
"token_count": 831
} | 836 |
const { client } = require('nightwatch-api')
const { When, Then } = require('@cucumber/cucumber')
const assert = require('assert')
require('url-search-params-polyfill')
const userSettings = require('../helpers/userSettings')
const sharingHelper = require('../helpers/sharingHelper')
const { SHARE_STATE } = require('../helpers/sharingHelper')
const _ = require('lodash')
const util = require('util')
const { COLLABORATOR_PERMISSION_ARRAY, calculateDate } = require('../helpers/sharingHelper')
/**
*
* @param {string} file
* @param {string} sharee
* @param {boolean} shareWithGroup
* @param {string} role
* @param {string} permissions
* @param {boolean} remote
* @param {boolean} quickAction Asserts whether the quick actions should be used to open new collaborators panel
*/
const userSharesFileOrFolderWithUserOrGroup = async function (
file,
sharee,
shareWithGroup,
role,
permissions = undefined,
remote = false,
quickAction = false
) {
const api = client.page.FilesPageElement
if (quickAction) {
await api.filesList().useQuickAction(file, 'collaborators')
} else {
await api.filesList().openSharingDialog(file)
}
return api
.sharingDialog()
.shareWithUserOrGroup(sharee, shareWithGroup, role, permissions, remote, null)
}
/**
*
* @param {string} file
* @param {string} sharee
* @param {string} role
*/
const userSharesFileOrFolderWithUser = function (file, sharee, role) {
return userSharesFileOrFolderWithUserOrGroup(file, sharee, false, role)
}
/**
*
* @param {string} file
* @param {string} sharee
* @param {string} role
*/
const userSharesFileOrFolderWithRemoteUser = function (file, sharee, role) {
return userSharesFileOrFolderWithUserOrGroup(file, sharee, false, role, undefined, true)
}
/**
*
* @param {string} file
* @param {string} sharee
* @param {string} role
*/
const userSharesFileOrFolderWithGroup = function (file, sharee, role) {
return userSharesFileOrFolderWithUserOrGroup(file, sharee, true, role)
}
Then(
'the user should see an error message on the collaborator share dialog saying {string}',
async function (expectedMessage) {
const actualMessage = await client.page.FilesPageElement.sharingDialog().getErrorMessage()
return client.assert.strictEqual(actualMessage, expectedMessage)
}
)
/**
*
* @param {string} type user|group
* @param {string} name
* @param {string} role
* @param {string} resharedThrough
* @param {string} additionalInfo
* @returns {Promise}
*/
const assertCollaboratorslistContains = function (
type,
name,
{ role = undefined, resharedThrough = undefined, additionalInfo = undefined }
) {
if (type !== 'user' && type !== 'group' && type !== 'remote user') {
throw new Error(`illegal type "${type}"`)
}
return client.page.FilesPageElement.SharingDialog.collaboratorsDialog()
.getCollaboratorsList(null, name)
.then((shares) => {
const share = shares.find((share) => {
return (
name === share.displayName && (!share.shareType || type === share.shareType.toLowerCase())
)
})
if (!share) {
assert.fail(
`"${name}" with type "${type}" was expected to be in share list but was not present. Found collaborators: ` +
shares.map((share) => `name=${share.displayName} type=${share.shareType}`)
)
}
if (role) {
assert.strictEqual(role, share.role)
}
if (resharedThrough) {
assert.strictEqual(`Shared by ${resharedThrough}`, share.resharer)
}
if (additionalInfo) {
assert.strictEqual(`${additionalInfo}`, share.additionalInfo)
}
})
}
/**
*
* @param {string} type
* @param {string} name
* @returns {Promise}
*/
const assertCollaboratorslistDoesNotContain = async function (type, name) {
if (type !== 'user' && type !== 'group') {
throw new Error('illegal type')
}
const collaboratorsDialog = client.page.FilesPageElement.SharingDialog.collaboratorsDialog()
// return if there is no collaboartor list
if (!(await collaboratorsDialog.hasCollaboratorsList(false))) {
return
}
return collaboratorsDialog
.getCollaboratorsList(
{
displayName: collaboratorsDialog.elements.collaboratorInformationSubName
},
name,
client.globals.waitForNegativeConditionTimeout
)
.then((shares) => {
const share = shares.find((share) => {
return (
name === share.displayName && (!share.shareType || type === share.shareType.toLowerCase())
)
})
if (share) {
assert.fail(`"${name}" was expected to not be in share list but was present.`)
}
})
}
/**
* Get all the users whose userID or display name matches with the pattern entered in the search field and then
* return the display names of the result(users)
*
* @param {string} pattern
* @return {string[]} groupMatchingPattern
*/
const getUsersMatchingPattern = async function (pattern) {
// check if all created users that contain the pattern either in the display name or the username
// are listed in the autocomplete list
// in both cases the display name should be listed
const users = await userSettings.getCreatedUsers()
const usersID = Object.keys(users)
return usersID
.filter((id) => users[id].displayname.toLowerCase().includes(pattern) || id.includes(pattern))
.map((id) => users[id].displayname)
}
/**
* Get all the groups whose name matches with the pattern entered in the search field
*
* @param {string} pattern
* @return {string[]} groupMatchingPattern
*/
const getGroupsMatchingPattern = async function (pattern) {
const groups = await userSettings.getCreatedGroups()
const groupMatchingPattern = groups.filter((group) => group.toLowerCase().includes(pattern))
return groupMatchingPattern
}
/**
* Checks if the users or groups found in the autocomplete list consists of all the created users and groups
* with the matched pattern except the current user name and the already shared user or group name
*
* @param {string} pattern
* @param {string} alreadySharedUserOrGroup
* @param {string} userOrGroup
*/
const assertUsersGroupsWithPatternInAutocompleteListExcluding = async function (
pattern,
alreadySharedUserOrGroup,
userOrGroup
) {
const sharingDialog = client.page.FilesPageElement.sharingDialog()
const currentUserDisplayName = await userSettings.getDisplayNameForUser(
client.globals.currentUser
)
let usersMatchingPattern = await getUsersMatchingPattern(pattern)
usersMatchingPattern = usersMatchingPattern.filter((displayName) => {
return displayName !== currentUserDisplayName && displayName !== alreadySharedUserOrGroup
})
let groupMatchingPattern = await getGroupsMatchingPattern(pattern)
groupMatchingPattern = groupMatchingPattern.filter((group) => group !== alreadySharedUserOrGroup)
if (usersMatchingPattern.length + groupMatchingPattern.length > 5) {
await sharingDialog.displayAllCollaboratorsAutocompleteResults()
}
return sharingDialog
.assertUsersInAutocompleteList(usersMatchingPattern)
.assertGroupsInAutocompleteList(groupMatchingPattern)
.assertAlreadyExistingCollaboratorIsNotInAutocompleteList(alreadySharedUserOrGroup, userOrGroup)
}
/**
*
* @param {string} resource
* @param {string} sharee
* @param {string} days
* @param {boolean} shareWithGroup
* @param {boolean} remote
* @param {boolean} expectToSucceed
*/
const userSharesFileOrFolderWithUserOrGroupWithExpirationDate = async function ({
resource,
sharee,
days,
shareWithGroup = false,
remote = false
}) {
const api = client.page.FilesPageElement
await api.filesList().openSharingDialog(resource)
return api
.sharingDialog()
.shareWithUserOrGroup(sharee, shareWithGroup, 'Viewer', undefined, remote, days)
}
/**
* @param {string} collaborator
* @param {string} resource
* @param {string} value
*/
const checkCollaboratorsExpirationDate = async function (collaborator, resource, value) {
const api = client.page.FilesPageElement
await api.filesList().openSharingDialog(resource)
return api.sharingDialog().checkExpirationDate(collaborator, value)
}
When('the user types {string} in the share-with-field', async function (input) {
return await client.page.FilesPageElement.sharingDialog().enterAutoComplete(input)
})
When(
'the user sets custom permission for current role of collaborator {string} for folder/file {string} to {string} using the webUI',
async function (user, resource, permissions) {
const api = client.page.FilesPageElement
await api.filesList().openSharingDialog(resource)
return api.sharingDialog().changeCustomPermissionsTo(user, permissions)
}
)
When(
'the user disables all the custom permissions of collaborator {string} for file/folder {string} using the webUI',
async function (collaborator, resource) {
const api = client.page.FilesPageElement
await api.filesList().openSharingDialog(resource)
return api.sharingDialog().changeCustomPermissionsTo(collaborator)
}
)
const assertSharePermissions = async function (currentSharePermissions, permissions = undefined) {
let expectedPermissionArray
if (permissions !== undefined) {
expectedPermissionArray =
await client.page.FilesPageElement.sharingDialog().getArrayFromPermissionString(permissions)
}
for (let i = 0; i < COLLABORATOR_PERMISSION_ARRAY.length; i++) {
const permissionName = COLLABORATOR_PERMISSION_ARRAY[i]
if (permissions !== undefined) {
// check all the required permissions are set
if (expectedPermissionArray.includes(permissionName)) {
assert.strictEqual(
currentSharePermissions[permissionName],
true,
`Permission ${permissionName} is not set`
)
} else {
// check unexpected permissions are not set or absent from the array
assert.ok(!currentSharePermissions[permissionName], `Permission ${permissionName} is set`)
}
} else {
// check all the permissions are not set or absent from the array
assert.ok(!currentSharePermissions[permissionName], `Permission ${permissionName} is set`)
}
}
}
Then(
'custom permission/permissions {string} should be set for user/group {string} for file/folder {string} on the webUI',
async function (permissions, userOrGroup, resource) {
await client.page.FilesPageElement.filesList().openSharingDialog(resource)
const currentSharePermissions =
await client.page.FilesPageElement.sharingDialog().getDisplayedPermission(userOrGroup)
return assertSharePermissions(currentSharePermissions, permissions)
}
)
Then(
'no custom permissions should be set for collaborator {string} for file/folder {string} on the webUI',
async function (user, resource) {
await client.page.FilesPageElement.filesList().openSharingDialog(resource)
const currentSharePermissions =
await client.page.FilesPageElement.sharingDialog().getDisplayedPermission(user)
return assertSharePermissions(currentSharePermissions)
}
)
When(
'the user shares file/folder/resource {string} with group {string} as {string} using the webUI',
userSharesFileOrFolderWithGroup
)
When(
'the user shares file/folder/resource {string} with remote user {string} as {string} using the webUI',
userSharesFileOrFolderWithRemoteUser
)
Then(
'it should not be possible to share file/folder {string} using the webUI',
async function (resource) {
const appSideBar = client.page.FilesPageElement.appSideBar()
const filesList = client.page.FilesPageElement.filesList()
// assumes current webUI state as no sidebar open for any resource
const state = await filesList.isSharingButtonPresent(resource)
assert.ok(!state, `Error: Sharing button for resource ${resource} is not in disabled state`)
await filesList.openSideBar(resource)
const collaboratorsItemState = await appSideBar.isSharingPanelSelectable(false)
assert.ok(
!collaboratorsItemState,
`Error: Sidebar 'People' panel for resource ${resource} is present`
)
}
)
When(
'the user shares file/folder/resource {string} with user {string} as {string} using the webUI',
userSharesFileOrFolderWithUser
)
When(
'the user shares file/folder/resource {string} with user {string} as {string} with permission/permissions {string} using the webUI',
function (resource, shareWithUser, role, permissions) {
return userSharesFileOrFolderWithUserOrGroup(resource, shareWithUser, false, role, permissions)
}
)
When(
'the user selects the following collaborators for the share as {string} with {string} permissions:',
async function (role, permissions, usersTable) {
const users = usersTable.hashes()
const dialog = client.page.FilesPageElement.sharingDialog()
await dialog.shareWithUsersOrGroups(users, role, permissions, false)
}
)
When('the user removes {string} as a collaborator from the share', function (user) {
return client.page.FilesPageElement.sharingDialog().removePendingCollaboratorForShare(user)
})
Then(
/^(user|group) "([^"]*)" should not be visible in the collaborators selected options in the webUI$/,
async function (userOrGroup, userOrGroupName) {
const isUserOrGroupPresent =
await client.page.FilesPageElement.sharingDialog().isUserOrGroupPresentInSelectedCollaboratorsOptions(
userOrGroup,
userOrGroupName,
false
)
assert.strictEqual(
isUserOrGroupPresent,
false,
`${userOrGroup} "${userOrGroupName}" was present in the collaborators selected options.`
)
}
)
Then(
/^(user|group) "([^"]*)" should be visible in the collaborators selected options in the webUI$/,
async function (userOrGroup, userOrGroupName) {
const isUserOrGroupPresent =
await client.page.FilesPageElement.sharingDialog().isUserOrGroupPresentInSelectedCollaboratorsOptions(
userOrGroup,
userOrGroupName,
true
)
assert.strictEqual(
isUserOrGroupPresent,
true,
`${userOrGroup} "${userOrGroupName}" was not present in the collaborators selected options.`
)
}
)
When('the user shares with the selected collaborators', function () {
return client.page.FilesPageElement.sharingDialog()
.initAjaxCounters()
.confirmShare()
.waitForOutstandingAjaxCalls()
})
Then(
'all users and groups that contain the string {string} in their name should be listed in the autocomplete list on the webUI',
async function (pattern) {
const sharingDialog = client.page.FilesPageElement.sharingDialog()
const currentUserDisplayName = await userSettings.getDisplayNameForUser(
client.globals.currentUser
)
// check if all created users that contain the pattern either in the display name or the username
// are listed in the autocomplete list
// in both cases the display name should be listed
let usersMatchingPattern = await getUsersMatchingPattern(pattern)
usersMatchingPattern = usersMatchingPattern.filter((displayName) => {
return displayName !== currentUserDisplayName
})
// check if every created group that contains the pattern is listed in the autocomplete list
const groupMatchingPattern = await getGroupsMatchingPattern(pattern)
if (usersMatchingPattern.length + groupMatchingPattern.length > 5) {
await sharingDialog.displayAllCollaboratorsAutocompleteResults()
}
return sharingDialog
.assertUsersInAutocompleteList(usersMatchingPattern)
.assertGroupsInAutocompleteList(groupMatchingPattern)
}
)
Then(
'all users and groups that contain the string {string} in their name should be listed in the autocomplete list on the webUI except user {string}',
function (pattern, alreadySharedUser) {
return assertUsersGroupsWithPatternInAutocompleteListExcluding(
pattern,
alreadySharedUser,
'user'
)
}
)
Then(
'all users and groups that contain the string {string} in their name should be listed in the autocomplete list on the webUI except group {string}',
function (pattern, alreadySharedGroup) {
return assertUsersGroupsWithPatternInAutocompleteListExcluding(
pattern,
alreadySharedGroup,
'group'
)
}
)
Then(
'only users and groups that contain the string {string} in their name or displayname should be listed in the autocomplete list on the webUI',
async function (pattern) {
const createdUsers = await userSettings.getCreatedUsers()
const createdGroups = await userSettings.getCreatedGroups()
console.log(createdUsers, createdGroups)
return client.page.FilesPageElement.sharingDialog()
.getShareAutocompleteItemsList()
.then((itemsList) => {
itemsList.forEach((item) => {
const displayedName = item.split('\n')[0]
let found = false
for (const userId in createdUsers) {
const userDisplayName = createdUsers[userId].displayname
if (
userDisplayName === displayedName &&
(userDisplayName.toLowerCase().includes(pattern) ||
userId.toLowerCase().includes(pattern))
) {
found = true
}
}
createdGroups.forEach(function (groupId) {
if (displayedName === groupId && groupId.toLowerCase().includes(pattern)) {
found = true
}
})
assert.strictEqual(
found,
true,
`"${displayedName}" was listed in autocomplete list, but should not have been. ` +
'(check if that is a manually added user/group)'
)
})
})
}
)
Then(
'every item listed in the autocomplete list on the webUI should contain {string}',
function (pattern) {
return client.page.FilesPageElement.sharingDialog()
.getShareAutocompleteItemsList()
.then((itemsList) => {
itemsList.forEach((item) => {
if (!item.toLowerCase().includes(pattern)) {
assert.fail(`sharee ${item} does not contain pattern ${pattern}`)
}
})
})
}
)
Then(
'the users own name should not be listed in the autocomplete list on the webUI',
async function () {
const currentUserDisplayName = await userSettings.getDisplayNameForUser(
client.globals.currentUser
)
return client.page.FilesPageElement.sharingDialog()
.getShareAutocompleteItemsList()
.then((itemsList) => {
itemsList.forEach((item) => {
const displayedName = item.split('\n')[0]
assert.notStrictEqual(
displayedName,
currentUserDisplayName,
`Users own name: ${currentUserDisplayName} was not expected to be listed in the autocomplete list but was`
)
})
})
}
)
Then(
'{string} {string} should not be listed in the autocomplete list on the webUI',
function (type, displayName) {
return client.page.FilesPageElement.sharingDialog().assertCollaboratorsInAutocompleteList(
displayName,
type,
false
)
}
)
Then(
'{string} {string} should be listed in the autocomplete list on the webUI',
function (type, displayName) {
return client.page.FilesPageElement.sharingDialog().assertCollaboratorsInAutocompleteList(
displayName,
type
)
}
)
Then(
'the share permission denied message should be displayed in the sharing dialog on the webUI',
function () {
return client.page.FilesPageElement.sharingDialog().isSharePermissionMessageVisible()
}
)
Then(
'the link share permission denied message should be displayed in the sharing dialog on the webUI',
function () {
return client.page.FilesPageElement.sharingDialog().isLinkSharePermissionMessageVisible()
}
)
When(
'the user opens the share dialog for file/folder/resource {string} using the webUI',
function (file) {
return client.page.FilesPageElement.filesList().openSharingDialog(file)
}
)
When(
'the user opens the link share dialog for file/folder/resource {string} using the webUI',
function (file) {
return client.page.FilesPageElement.filesList().openPublicLinkDialog(file)
}
)
When(
'the user deletes {string} as collaborator for the current file/folder using the webUI',
function (user) {
return client.page.FilesPageElement.SharingDialog.collaboratorsDialog().deleteShareWithUserGroup(
user
)
}
)
When(
'the user deletes {string} as remote collaborator for the current file/folder using the webUI',
function (user) {
user = util.format('%s@%s', user, client.globals.remote_backend_url)
return client.page.FilesPageElement.SharingDialog.collaboratorsDialog().deleteShareWithUserGroup(
user
)
}
)
When(
'the user changes the collaborator role of {string} for file/folder {string} to {string} with permissions {string} using the webUI',
async function (collaborator, resource, newRole, permissions) {
const api = client.page.FilesPageElement
await api.filesList().openSharingDialog(resource)
return api.sharingDialog().changeCollaboratorRole(collaborator, newRole, permissions)
}
)
When(
'the user (tries to )edit/edits the collaborator expiry date of {string} of file/folder/resource {string} to {string} days/day using the webUI',
async function (collaborator, resource, days) {
const api = client.page.FilesPageElement
await api.filesList().openSharingDialog(resource)
return api.sharingDialog().changeCollaboratorExpiryDate(collaborator, days)
}
)
Then(
'user {string} should be listed as {string} in the collaborators list on the webUI',
function (user, role) {
return assertCollaboratorslistContains('user', user, { role })
}
)
Then(
'the share {string} shared with user {string} should have no expiration information displayed on the webUI',
async function (item, user) {
await client.page.FilesPageElement.filesList().openSharingDialog(item)
const elementID =
await client.page.FilesPageElement.SharingDialog.collaboratorsDialog().getCollaboratorExpirationInfo(
user
)
return assert.strictEqual(
elementID,
undefined,
'The expiration information was present unexpectedly'
)
}
)
Then(
'the expiration information displayed on the webUI of share {string} shared with user {string} should be {string} or {string}',
async function (item, user, information1, information2) {
await client.page.FilesPageElement.filesList().openSharingDialog(item)
const actualInfo =
await client.page.FilesPageElement.SharingDialog.collaboratorsDialog().getCollaboratorExpirationInfo(
user
)
if (actualInfo === information1) {
return true
} else {
return assert.strictEqual(
actualInfo,
information2,
`The expected expiration information was either '${information1}' or '${information2}', but got '${actualInfo}'`
)
}
}
)
Then(
'user {string} should be listed as {string} reshared through {string} in the collaborators list on the webUI',
function (user, role, resharedThrough) {
return assertCollaboratorslistContains('user', user, { role, resharedThrough })
}
)
Then(
'user {string} should be listed with additional info {string} in the collaborators list on the webUI',
function (user, additionalInfo) {
return assertCollaboratorslistContains('user', user, { additionalInfo })
}
)
Then(
'user {string} should be listed without additional info in the collaborators list on the webUI',
function (user) {
return assertCollaboratorslistContains('user', user, { additionalInfo: false })
}
)
Then(
'user {string} should be listed as {string} in the collaborators list for file/folder/resource {string} on the webUI',
async function (user, role, resource) {
await client.page.FilesPageElement.filesList().openSharingDialog(resource)
return assertCollaboratorslistContains('user', user, { role })
}
)
Then(
'group {string} should be listed as {string} in the collaborators list on the webUI',
function (group, role) {
return assertCollaboratorslistContains('group', group, { role })
}
)
Then(
'group {string} should be listed as {string} in the collaborators list for file/folder/resource {string} on the webUI',
async function (group, role, resource) {
await client.page.FilesPageElement.filesList().openSharingDialog(resource)
return assertCollaboratorslistContains('group', group, { role })
}
)
Then('user {string} should not be listed in the collaborators list on the webUI', function (user) {
return assertCollaboratorslistDoesNotContain('user', user)
})
Then(
'group {string} should not be listed in the collaborators list on the webUI',
function (group) {
return assertCollaboratorslistDoesNotContain('group', group)
}
)
Then(
'the user should not be able to share file/folder/resource {string} using the webUI',
async function (resource) {
const api = client.page.FilesPageElement
await api.filesList().openSharingDialog(resource)
return await api.sharingDialog().isSharePermissionMessageVisible()
}
)
Then(
'the collaborators list for file/folder/resource {string} should be empty',
async function (resource) {
const api = client.page.FilesPageElement
await api.filesList().openSharingDialog(resource)
const visible = await api.SharingDialog.collaboratorsDialog().hasCollaboratorsList(false)
assert.strictEqual(visible, false, 'Expected collaborators list to not exist, but it did')
}
)
Then('the expiration date field should be marked as required on the webUI', async function () {
await client.page.FilesPageElement.sharingDialog().waitForElementVisible(
'@requiredLabelInCollaboratorsExpirationDate'
)
})
Then(
'the expiration date for {string} should be disabled on the webUI',
async function (expiration) {
const dateToSet = calculateDate(expiration)
const isEnabled = await client.page.FilesPageElement.sharingDialog()
.openExpirationDatePicker()
.setExpirationDate(dateToSet)
return assert.strictEqual(
isEnabled,
false,
`The expiration date for ${expiration} was expected to be disabled, but is found enabled`
)
}
)
Then('the current collaborators list should have order {string}', async function (expectedNames) {
const actualNames = (
await client.page.FilesPageElement.SharingDialog.collaboratorsDialog().getCollaboratorsListNames()
).join(',')
assert.strictEqual(
actualNames,
expectedNames,
`Expected to have collaborators in order '${expectedNames}', Found: ${actualNames}`
)
})
Then(
'file/folder {string} shared by {string} should be in {string} state on the webUI',
async function (resource, sharer, expectedStatus) {
const shareStatus =
expectedStatus === 'Accepted'
? SHARE_STATE.accepted
: expectedStatus === 'Declined'
? SHARE_STATE.declined
: SHARE_STATE.pending
const hasShareStatus = await client.page
.sharedWithMePage()
.hasShareStatusByFilenameAndUser(shareStatus, resource, sharer)
return assert.ok(
hasShareStatus,
`Expected resource '${resource}' shared by '${sharer}' to be in state '${expectedStatus}' but isn't.`
)
}
)
When(
'the user declines share {string} offered by user {string} using the webUI',
async function (filename, user) {
await client.pause(200)
return client.page.FilesPageElement.filesList().declineShare(filename)
}
)
When(
'the user accepts share {string} offered by user {string} using the webUI',
async function (filename, user) {
await client.pause(200)
return client.page.FilesPageElement.filesList().acceptShare(filename)
}
)
Then('the autocomplete list should not be displayed on the webUI', async function () {
const isVisible = await client.page.FilesPageElement.sharingDialog().isAutocompleteListVisible()
return assert.ok(!isVisible, 'Expected: autocomplete list "not visible" but found "visible"')
})
Then(
'file/folder {string} should be marked as shared by {string} on the webUI',
async function (element, sharer) {
const username = await client.page.sharedWithMePage().getSharedByUser(element)
return assert.strictEqual(
username,
sharer,
`Expected username: '${sharer}', but found '${username}'`
)
}
)
Then('the following resources should have the following collaborators', async function (dataTable) {
for (const { fileName, expectedCollaborators } of dataTable.hashes()) {
const collaboratorsArray = await client.page
.sharedWithOthersPage()
.getCollaboratorsForResource(fileName)
const expectedCollaboratorsArray = expectedCollaborators.split(',').map((s) => s.trim())
assert.ok(
_.intersection(collaboratorsArray, expectedCollaboratorsArray).length ===
expectedCollaboratorsArray.length,
`Expected collaborators to be the same for "${fileName}": expected [` +
expectedCollaboratorsArray.join(', ') +
'] got [' +
collaboratorsArray.join(', ') +
']'
)
}
})
When(
'the user (tries to )share/shares file/folder/resource {string} with user {string} which expires in {string} day/days using the webUI',
function (resource, sharee, days) {
return userSharesFileOrFolderWithUserOrGroupWithExpirationDate({ resource, sharee, days })
}
)
When(
'the user (tries to )share/shares file/folder/resource {string} with group {string} which expires in {string} day/days using the webUI',
function (resource, sharee, days) {
return userSharesFileOrFolderWithUserOrGroupWithExpirationDate({
resource,
sharee,
days,
shareWithGroup: true
})
}
)
When('the user opens the sharing sidebar for file/folder {string}', function (file) {
return client.page.FilesPageElement.filesList().openSideBar(file)
})
When(
'the user shares file/folder/resource {string} with user {string} using the webUI',
function (resource, user) {
return userSharesFileOrFolderWithUser(resource, user, 'Viewer')
}
)
Then(
'the fields of the {string} collaborator for file/folder/resource {string} should contain expiration date with value {string} on the webUI',
function (collaborator, resource, value) {
return checkCollaboratorsExpirationDate(collaborator, resource, value)
}
)
Then(
'the share expiration date shown on the webUI should be {string} days',
async function (expectedDays) {
const expectedDate = sharingHelper.calculateDate(expectedDays)
const expectedDateString = expectedDate.toString()
const dateStringFromInputField =
await client.page.FilesPageElement.sharingDialog().getExpirationDateFromInputField()
assert.strictEqual(
dateStringFromInputField,
expectedDateString,
`Expected: Expiration date field with ${expectedDateString}, but found ${dateStringFromInputField}`
)
}
)
When(
'the user shares resource {string} with user {string} using the quick action on the webUI',
function (resource, user) {
return userSharesFileOrFolderWithUserOrGroup(
resource,
user,
false,
'Viewer',
undefined,
false,
true
)
}
)
| owncloud/web/tests/acceptance/stepDefinitions/sharingContext.js/0 | {
"file_path": "owncloud/web/tests/acceptance/stepDefinitions/sharingContext.js",
"repo_id": "owncloud",
"token_count": 10204
} | 837 |
// borrowed from https://github.com/orieken/playwright-cucumber-starter
// thanks @orieken if you will ever read this
function TypeScriptSnippetSyntax(snippetInterface) {
this.snippetInterface = snippetInterface
}
function addParameters(allParameterNames) {
let prefix = ''
if (allParameterNames.length > 0) {
prefix = ', '
}
return prefix + allParameterNames.join(', ')
}
TypeScriptSnippetSyntax.prototype.build = function ({
generatedExpressions,
functionName,
stepParameterNames
}) {
let functionKeyword = ''
const functionInterfaceKeywords = {
generator: `${functionKeyword}*`,
'async-await': `async ${functionKeyword}`,
promise: 'async '
}
if (this.snippetInterface) {
functionKeyword = `${functionKeyword}${functionInterfaceKeywords[this.snippetInterface]}`
}
const implementation = [
'const { feature, actorsEnvironment, usersEnvironment, filesEnvironment } = this\n',
'await new Promise(resolve => setTimeout(resolve, 10))'
]
.map((str) => ` ${str}`)
.join('\n')
const definitionChoices = generatedExpressions.map((generatedExpression, index) => {
const prefix = index === 0 ? '' : '// '
const allParameterNames = generatedExpression.parameterNames
.map((parameterName) => `${parameterName}: any`)
.concat(stepParameterNames.map((stepParameterName) => `${stepParameterName}: any`))
return (
`${prefix}${functionName}('` +
generatedExpression.source.replace(/'/g, "\\'") +
"', " +
functionKeyword +
'function (this: World' +
addParameters(allParameterNames) +
'): Promise<void> {\n'
)
})
return definitionChoices.join('') + `${implementation}\n});`
}
module.exports = TypeScriptSnippetSyntax
| owncloud/web/tests/e2e/cucumber/environment/snippets-syntax.js/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/environment/snippets-syntax.js",
"repo_id": "owncloud",
"token_count": 602
} | 838 |
Feature: share
Background:
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
And "Brian" logs in
Scenario: folder
# disabling auto accepting to check accepting share
Given "Brian" disables auto-accepting using API
And "Alice" logs in
And "Alice" creates the following folder in personal space using API
| name |
| folder_to_shared |
| folder_to_shared_2 |
| shared_folder |
And "Alice" opens the "files" app
And "Alice" uploads the following resource
| resource | to |
| lorem.txt | folder_to_shared |
| lorem-big.txt | folder_to_shared_2 |
When "Alice" shares the following resource using the sidebar panel
| resource | recipient | type | role | resourceType |
| folder_to_shared | Brian | user | Can edit | folder |
| shared_folder | Brian | user | Can edit | folder |
| folder_to_shared_2 | Brian | user | Can edit | folder |
And "Brian" opens the "files" app
And "Brian" navigates to the shared with me page
And "Brian" enables the sync for the following shares
| name |
| folder_to_shared |
| folder_to_shared_2 |
Then "Brian" should not see a sync status for the folder "shared_folder"
When "Brian" enables the sync for the following share using the context menu
| name |
| shared_folder |
And "Brian" disables the sync for the following share using the context menu
| name |
| shared_folder |
And "Brian" renames the following resource
| resource | as |
| folder_to_shared/lorem.txt | lorem_new.txt |
And "Brian" uploads the following resource
| resource | to |
| simple.pdf | folder_to_shared |
| testavatar.jpeg | folder_to_shared_2 |
When "Brian" deletes the following resources using the sidebar panel
| resource | from |
| lorem-big.txt | folder_to_shared_2 |
And "Alice" opens the "files" app
And "Alice" uploads the following resource
| resource | to | option |
| PARENT/simple.pdf | folder_to_shared | replace |
And "Brian" should not see the version of the file
| resource | to |
| simple.pdf | folder_to_shared |
And "Alice" removes following sharee
| resource | recipient |
| folder_to_shared_2 | Brian |
When "Alice" deletes the following resources using the sidebar panel
| resource | from |
| lorem_new.txt | folder_to_shared |
| folder_to_shared | |
And "Alice" logs out
Then "Brian" should not be able to see the following shares
| resource | owner |
| folder_to_shared_2 | Alice Hansen |
| folder_to_shared | Alice Hansen |
And "Brian" logs out
Scenario: file
Given "Alice" logs in
And "Alice" opens the "files" app
And "Alice" creates the following resources
| resource | type | content |
| shareToBrian.txt | txtFile | some text |
| shareToBrian.md | mdFile | readme |
| shareToBrian.drawio | drawioFile | |
| sharedFile.txt | txtFile | some text |
And "Alice" uploads the following resource
| resource |
| testavatar.jpeg |
| simple.pdf |
When "Alice" shares the following resource using the sidebar panel
| resource | recipient | type | role | resourceType |
| shareToBrian.txt | Brian | user | Can edit | file |
| shareToBrian.md | Brian | user | Can edit | file |
| testavatar.jpeg | Brian | user | Can view | file |
| simple.pdf | Brian | user | Can edit | file |
| sharedFile.txt | Brian | user | Can edit | file |
And "Brian" opens the "files" app
And "Brian" navigates to the shared with me page
And "Brian" disables the sync for the following share
| name |
| sharedFile.txt |
And "Brian" edits the following resources
| resource | content |
| shareToBrian.txt | new content |
| shareToBrian.md | new readme content |
And "Brian" opens the following file in mediaviewer
| resource |
| testavatar.jpeg |
And "Brian" closes the file viewer
And "Brian" opens the following file in pdfviewer
| resource |
| simple.pdf |
And "Brian" closes the file viewer
And "Alice" removes following sharee
| resource | recipient |
| shareToBrian.txt | Brian |
| shareToBrian.md | Brian |
And "Alice" logs out
Then "Brian" should not be able to see the following shares
| resource | owner |
| shareToBrian.txt | Alice Hansen |
| shareToBrian.md | Alice Hansen |
And "Brian" logs out
Scenario: share with expiration date
Given "Admin" creates following group using API
| id |
| sales |
And "Admin" adds user to the group using API
| user | group |
| Brian | sales |
And "Alice" logs in
And "Alice" creates the following folder in personal space using API
| name |
| myfolder |
| mainFolder |
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| new.txt | some content |
And "Alice" opens the "files" app
When "Alice" shares the following resource using the sidebar panel
| resource | recipient | type | role | resourceType | expirationDate |
| new.txt | Brian | user | Can edit | file | +5 days |
| myfolder | sales | group | Can view | folder | +10 days |
| mainFolder | Brian | user | Can edit | folder | |
# set expirationDate to existing share
And "Alice" sets the expiration date of share "mainFolder" of user "Brian" to "+5 days"
And "Alice" checks the following access details of share "mainFolder" for user "Brian"
| Name | Brian Murphy |
| Type | User |
And "Alice" sets the expiration date of share "myfolder" of group "sales" to "+3 days"
And "Alice" checks the following access details of share "myfolder" for group "sales"
| Name | sales department |
| Type | Group |
# remove share with group
When "Alice" removes following sharee
| resource | recipient | type |
| myfolder | sales | group |
And "Alice" logs out
And "Brian" navigates to the shared with me page
And "Brian" logs out
Scenario: receive two shares with same name
Given "Admin" creates following users using API
| id |
| Carol |
And "Alice" logs in
And "Alice" creates the following folder in personal space using API
| name |
| test-folder |
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| testfile.txt | example text |
And "Alice" opens the "files" app
And "Alice" shares the following resource using the sidebar panel
| resource | recipient | type | role |
| testfile.txt | Brian | user | Can view |
| test-folder | Brian | user | Can view |
And "Alice" logs out
And "Carol" logs in
And "Carol" creates the following folder in personal space using API
| name |
| test-folder |
And "Carol" creates the following files into personal space using API
| pathToFile | content |
| testfile.txt | example text |
And "Carol" opens the "files" app
And "Carol" shares the following resource using the sidebar panel
| resource | recipient | type | role |
| testfile.txt | Brian | user | Can view |
| test-folder | Brian | user | Can view |
And "Carol" logs out
When "Brian" navigates to the shared with me page
Then following resources should be displayed in the Shares for user "Brian"
| resource |
| testfile.txt |
| test-folder |
# https://github.com/owncloud/ocis/issues/8471
# | testfile (1).txt |
# | test-folder (1) |
And "Brian" logs out
Scenario: check file with same name but different paths are displayed correctly in shared with others page
Given "Admin" creates following users using API
| id |
| Carol |
And "Alice" logs in
And "Alice" creates the following folder in personal space using API
| name |
| test-folder |
And "Alice" creates the following files into personal space using API
| pathToFile | content |
| testfile.txt | example text |
| test-folder/testfile.txt | some text |
And "Alice" opens the "files" app
And "Alice" shares the following resource using API
| resource | recipient | type | role |
| testfile.txt | Brian | user | Can edit |
| test-folder/testfile.txt | Brian | user | Can edit |
And "Alice" navigates to the shared with others page
Then following resources should be displayed in the files list for user "Alice"
| resource |
| testfile.txt |
| test-folder/testfile.txt |
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/shares/share.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/shares/share.feature",
"repo_id": "owncloud",
"token_count": 3969
} | 839 |
Feature: Upload
As a user
I want to upload resources
So that I can store them in owncloud
Background:
Given "Admin" logs in
And "Admin" creates following user using API
| id |
| Alice |
And "Alice" logs in
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the users management page
When "Admin" changes the quota of the user "Alice" to "0.00008" using the sidebar panel
And "Admin" logs out
And "Alice" opens the "files" app
Scenario: Upload resources in personal space
Given "Alice" creates the following resources
| resource | type | content |
| new-lorem-big.txt | txtFile | new lorem big file |
| lorem.txt | txtFile | lorem file |
| textfile.txt | txtFile | some random content |
# Coverage for bug: https://github.com/owncloud/ocis/issues/8361
| comma,.txt | txtFile | comma |
When "Alice" uploads the following resources
| resource | option |
| new-lorem-big.txt | replace |
| lorem.txt | skip |
| textfile.txt | keep both |
And "Alice" creates the following resources
| resource | type | content |
| PARENT/parent.txt | txtFile | some text |
| PARENT/example.txt | txtFile | example text |
And "Alice" uploads the following resources via drag-n-drop
| resource |
| simple.pdf |
| testavatar.jpg |
And "Alice" tries to upload the following resource
| resource | error |
| lorem-big.txt | Not enough quota |
And "Alice" downloads the following resources using the sidebar panel
| resource | type |
| PARENT | folder |
# Coverage for bug: https://github.com/owncloud/ocis/issues/8361
| comma,.txt | file |
# https://github.com/owncloud/web/issues/6348
# Note: uploading folder with empty sub-folder should be done manually
# currently upload folder feature is not available in playwright
# And "Alice" uploads the following resources
# | resource |
# | FOLDER |
And "Alice" logs out
Scenario: upload multiple small files
When "Alice" uploads 50 small files in personal space
Then "Alice" should see the text "50 items with 600 B in total (50 files, 0 folders)" at the footer of the page
And "Alice" should see 50 resources in the personal space files view
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/smoke/upload.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/upload.feature",
"repo_id": "owncloud",
"token_count": 971
} | 840 |
import { DataTable, Then, When } from '@cucumber/cucumber'
import { expect } from '@playwright/test'
import { World } from '../../environment'
import { objects } from '../../../support'
When(
'{string} creates a public link creates a public link of following resource using the sidebar panel',
async function (this: World, stepUser: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
for (const info of stepTable.hashes()) {
await linkObject.create({
resource: info.resource,
role: info.role,
password: info.password === '%public%' ? linkObject.securePassword : info.password,
name: 'Link'
})
}
}
)
When(
'{string} creates a public link for the space with password {string} using the sidebar panel',
async function (this: World, stepUser: string, password: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const spaceObject = new objects.applicationFiles.Spaces({ page })
const linkObject = new objects.applicationFiles.Link({ page })
password = password === '%public%' ? linkObject.securePassword : password
await spaceObject.createPublicLink({ password })
}
)
When(
'{string} renames the most recently created public link of resource {string} to {string}',
async function (this: World, stepUser: string, resource: string, newName: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
const linkName = await linkObject.changeName({ resource, newName })
expect(linkName).toBe(newName)
}
)
When(
'{string} renames the most recently created public link of space to {string}',
async function (this: World, stepUser: any, newName: any): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
const linkName = await linkObject.changeName({ newName, space: true })
expect(linkName).toBe(newName)
}
)
When(
'{string} sets the expiration date of the public link named {string} of resource {string} to {string}',
async function (
this: World,
stepUser: string,
linkName: string,
resource: string,
expireDate: string
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
await linkObject.addExpiration({ resource, linkName, expireDate })
}
)
When(
'{string} changes the password of the public link named {string} of resource {string} to {string}',
async function (
this: World,
stepUser: string,
linkName: string,
resource: string,
newPassword: string
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
await linkObject.addPassword({ resource, linkName, newPassword })
}
)
When(
'{string} tries to sets a new password {string} of the public link named {string} of resource {string}',
async function (
this: World,
stepUser: string,
newPassword: string,
linkName: string,
resource: string
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
await linkObject.fillPassword({ resource, linkName, newPassword })
}
)
When(
/^"([^"]*)" (reveals|hides) the password of the public link$/,
async function (this: World, stepUser: string, showOrHide: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
await linkObject.showOrHidePassword({ showOrHide })
}
)
When(
'{string} closes the public link password dialog box',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
await linkObject.clickOnCancelButton()
}
)
When(
'{string} copies the password of the public link',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
await linkObject.copyEnteredPassword()
}
)
When(
'{string} generates the password for the public link',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
await linkObject.generatePassword()
}
)
When(
'{string} sets the password of the public link',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
await linkObject.setPassword()
}
)
When(
'{string} edits the public link named {string} of resource {string} changing role to {string}',
async function (
this: World,
stepUser: string,
linkName: any,
resource: string,
role: string
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
const roleText = await linkObject.changeRole({ linkName, resource, role })
expect(roleText.toLowerCase()).toBe(linkObject.roleDisplayText[role].toLowerCase())
}
)
When(
'{string} removes the public link named {string} of resource {string}',
async function (this: World, stepUser: string, name: string, resource: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
await linkObject.delete({ resourceName: resource, name })
}
)
Then(
'public link named {string} should be visible to {string}',
async function (this: World, linkName: string, stepUser: any): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const expectedPublicLink = this.linksEnvironment.getLink({ name: linkName })
const linkObject = new objects.applicationFiles.Link({ page })
const actualPublicLink = await linkObject.getPublicLinkUrl({ linkName, space: true })
expect(actualPublicLink).toBe(expectedPublicLink)
}
)
Then(
'public link named {string} of the resource {string} should be visible to {string}',
async function (this: World, linkName: string, resource: string, stepUser: any): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const expectedPublicLink = this.linksEnvironment.getLink({ name: linkName })
const linkObject = new objects.applicationFiles.Link({ page })
const actualPublicLink = await linkObject.getPublicLinkUrl({ linkName, resource })
expect(actualPublicLink).toBe(expectedPublicLink)
}
)
Then(
/^"([^"]*)" (should|should not) be able to edit the public link named "([^"]*)"$/,
async function (
this: World,
stepUser: any,
shouldOrShouldNot: string,
linkName: any
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
const isVisible = await linkObject.islinkEditButtonVisibile(linkName)
expect(isVisible).toBe(shouldOrShouldNot !== 'should not')
}
)
Then(
'{string} should see an error message',
async function (this: World, stepUser: any, errorMessage: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
const actualErrorMessage = await linkObject.checkErrorMessage()
expect(actualErrorMessage).toBe(errorMessage)
}
)
When(
'{string} edits the public link named {string} of the space changing role to {string}',
async function (this: World, stepUser: string, linkName: string, role: any): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const linkObject = new objects.applicationFiles.Link({ page })
const newPermission = await linkObject.changeRole({ linkName, role, space: true })
expect(newPermission.toLowerCase()).toBe(linkObject.roleDisplayText[role].toLowerCase())
}
)
When(
'{string} opens shared-with-me page from the internal link',
async function (this: World, stepUser: string): Promise<void> {
const actor = this.actorsEnvironment.getActor({ key: stepUser })
const pageObject = new objects.applicationFiles.page.shares.WithMe({ page: actor.page })
await pageObject.openShareWithMeFromInternalLink(actor)
}
)
| owncloud/web/tests/e2e/cucumber/steps/ui/links.ts/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/steps/ui/links.ts",
"repo_id": "owncloud",
"token_count": 2818
} | 841 |
export {
uploadFileInPersonalSpace,
createFolderInsideSpaceBySpaceName,
createFolderInsidePersonalSpace,
getIdOfFileInsideSpace,
uploadFileInsideSpaceBySpaceName,
addMembersToTheProjectSpace,
addTagToResource
} from './spaces'
| owncloud/web/tests/e2e/support/api/davSpaces/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/davSpaces/index.ts",
"repo_id": "owncloud",
"token_count": 71
} | 842 |
import join from 'join-path'
import { checkResponseStatus, request } from '../http'
import { User } from '../../types'
import { shareRoles } from '../../objects/app-files/share/collaborator'
export const shareTypes: Readonly<{
user: string
group: string
public: string
federated: string
space: string
}> = {
user: '0',
group: '1',
public: '3',
federated: '6',
space: '7'
}
export const createShare = async ({
user,
path,
shareWith,
shareType,
role,
name,
space_ref
}: {
user: User
path?: string
shareType: string
shareWith?: string
role?: string
name?: string
space_ref?: string
}): Promise<void> => {
const body = new URLSearchParams()
body.append('path', path)
body.append('shareWith', shareWith)
body.append('shareType', shareTypes[shareType])
body.append('role', shareRoles[role])
body.append('name', name)
if (space_ref) {
body.append('space_ref', space_ref)
}
const response = await request({
method: 'POST',
path: join('ocs', 'v2.php', 'apps', 'files_sharing', 'api', 'v1', 'shares'),
body: body,
user: user
})
checkResponseStatus(response, 'Failed while creating share')
}
| owncloud/web/tests/e2e/support/api/share/share.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/share/share.ts",
"repo_id": "owncloud",
"token_count": 418
} | 843 |
import { basename } from 'path'
import { expect } from '@playwright/test'
export const uploadLogo = async (path, page): Promise<void> => {
await page.click('#logo-context-btn')
const logoInput = await page.locator('#logo-upload-input')
await logoInput.setInputFiles(path)
await page.locator('.oc-notification-message').waitFor()
await page.reload()
const logoImg = await page.locator('.logo-wrapper img')
const logoSrc = await logoImg.getAttribute('src')
expect(logoSrc).toContain(basename(path))
}
export const resetLogo = async (page): Promise<void> => {
const imgBefore = await page.locator('.logo-wrapper img')
const srcBefore = await imgBefore.getAttribute('src')
await page.click('#logo-context-btn')
await page.click('.oc-general-actions-reset-logo-trigger')
await page.locator('.oc-notification-message').waitFor()
await page.reload()
const imgAfter = await page.locator('.logo-wrapper img')
const srcAfter = await imgAfter.getAttribute('src')
expect(srcAfter).not.toEqual(srcBefore)
}
| owncloud/web/tests/e2e/support/objects/app-admin-settings/general/actions.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/general/actions.ts",
"repo_id": "owncloud",
"token_count": 340
} | 844 |
import { Page } from '@playwright/test'
import * as po from './actions'
import { LinksEnvironment } from '../../../environment'
export class Link {
#page: Page
#linksEnvironment: LinksEnvironment
constructor({ page }: { page: Page }) {
this.#page = page
this.#linksEnvironment = new LinksEnvironment()
}
roleDisplayText = {
'Invited people': 'Only for invited people',
'Can view': 'Anyone with the link can view',
'Can upload': 'Anyone with the link can upload',
'Can edit': 'Anyone with the link can edit',
'Secret File Drop': 'Secret File drop'
}
securePassword = 'Pwd:12345'
async create(args: Omit<po.createLinkArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
const url = await po.createLink({ ...args, page: this.#page })
this.#linksEnvironment.createLink({
key: args.name,
link: { name: args.name, url }
})
await this.#page.goto(startUrl)
}
async changeName(args: Omit<po.changeNameArgs, 'page'>): Promise<string> {
const startUrl = this.#page.url()
const name = await po.changeName({ page: this.#page, ...args })
const currentLink = this.#linksEnvironment.getLink({ name: 'Link' })
this.#linksEnvironment.updateLinkName({
key: currentLink.name,
link: { ...currentLink, name }
})
await this.#page.goto(startUrl)
return name
}
async addExpiration(args: Omit<po.addExpirationArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.addExpiration({ page: this.#page, ...args })
await this.#page.goto(startUrl)
}
async addPassword(args: Omit<po.addPasswordArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.addPassword({ page: this.#page, ...args })
await this.#page.goto(startUrl)
}
async fillPassword(args: Omit<po.addPasswordArgs, 'page'>): Promise<void> {
await po.fillPassword({ page: this.#page, ...args })
}
async showOrHidePassword(args): Promise<void> {
return await po.showOrHidePassword({ page: this.#page, ...args })
}
async copyEnteredPassword(): Promise<void> {
return await po.copyEnteredPassword(this.#page)
}
async generatePassword(): Promise<void> {
return await po.generatePassword(this.#page)
}
async setPassword(): Promise<void> {
return await po.setPassword(this.#page)
}
async changeRole(args: Omit<po.changeRoleArgs, 'page'>): Promise<string> {
const startUrl = this.#page.url()
const role = await po.changeRole({ page: this.#page, ...args })
await this.#page.goto(startUrl)
return role
}
async delete(args: Omit<po.deleteLinkArgs, 'page'>): Promise<void> {
const startUrl = this.#page.url()
await po.deleteLink({ ...args, page: this.#page })
await this.#page.goto(startUrl)
}
getPublicLinkUrl(
args: Omit<po.publicLinkAndItsEditButtonVisibilityArgs, 'page'>
): Promise<string> {
return po.getPublicLinkVisibility({
...args,
page: this.#page
})
}
async islinkEditButtonVisibile(linkName): Promise<boolean> {
return await po.getLinkEditButtonVisibility({ page: this.#page, linkName })
}
async checkErrorMessage(): Promise<string> {
return await po.getPublicLinkPasswordErrorMessage(this.#page)
}
async clickOnCancelButton(): Promise<void> {
await po.clickOnCancelButton(this.#page)
}
}
| owncloud/web/tests/e2e/support/objects/app-files/link/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/link/index.ts",
"repo_id": "owncloud",
"token_count": 1168
} | 845 |
import { errors, Page } from '@playwright/test'
import util from 'util'
const acceptedShareItem =
'//*[@data-test-resource-name="%s"]/ancestor::tr//span[@data-test-user-name="%s"]'
const itemSelector = '.files-table [data-test-resource-name="%s"]'
const syncEnabled =
'//*[@data-test-resource-name="%s"]//ancestor::tr//span[contains(@class, "sync-enabled")]'
export const resourceIsNotOpenable = async ({
page,
resource
}: {
page: Page
resource: string
}): Promise<boolean> => {
const resourceLocator = page.locator(util.format(itemSelector, resource))
try {
await Promise.all([
page.waitForRequest((req) => req.method() === 'PROPFIND', { timeout: 500 }),
resourceLocator.click()
])
return false
} catch (e) {
return true
}
}
export const resourceIsSynced = ({
page,
resource
}: {
page: Page
resource: string
}): Promise<boolean> => {
return page.locator(util.format(syncEnabled, resource)).isVisible()
}
export const isAcceptedSharePresent = async ({
page,
resource,
owner,
timeout = 500
}: {
page: Page
resource: string
owner: string
timeout?: number
}): Promise<boolean> => {
let exist = true
await page
.locator(util.format(acceptedShareItem, resource, owner))
.waitFor({ timeout })
.catch((e) => {
if (!(e instanceof errors.TimeoutError)) {
throw e
}
exist = false
})
return exist
}
| owncloud/web/tests/e2e/support/objects/app-files/share/utils.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/share/utils.ts",
"repo_id": "owncloud",
"token_count": 519
} | 846 |
import { Group } from '../types'
export const dummyGroupStore = new Map<string, Group>([
[
'security',
{
id: 'security',
displayName: 'security department'
}
],
[
'sales',
{
id: 'sales',
displayName: 'sales department'
}
],
[
'finance',
{
id: 'finance',
displayName: 'finance department'
}
]
])
export const createdGroupStore = new Map<string, Group>()
| owncloud/web/tests/e2e/support/store/group.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/store/group.ts",
"repo_id": "owncloud",
"token_count": 191
} | 847 |
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { compilerOptions } from '../../../vite.config.common'
const root = path.resolve(__dirname, '../../../')
export default defineConfig({
plugins: [
vue({ template: { compilerOptions } }),
{
name: '@ownclouders/vite-plugin-docs',
transform(src, id) {
if (id.includes('type=docs')) {
return {
code: 'export default {}',
map: null
}
}
}
}
],
test: {
root,
globals: true,
environment: 'happy-dom',
clearMocks: true,
include: ['**/*.spec.ts'],
setupFiles: ['tests/unit/config/vitest.init.ts', 'core-js'],
exclude: [
'**/node_modules/**',
'**/dist/**',
'**/cypress/**',
'**/.{idea,git,cache,output,temp}/**',
'**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*',
'.pnpm-store/*',
'packages/design-system/tests/e2e/**',
'packages/design-system/docs/**'
],
alias: {
'vue-inline-svg': `${root}/tests/unit/stubs/empty.ts`,
webfontloader: `${root}/tests/unit/stubs/webfontloader.ts`
},
coverage: {
provider: 'v8',
reportsDirectory: `${root}/coverage`,
reporter: 'lcov'
}
}
})
| owncloud/web/tests/unit/config/vitest.config.ts/0 | {
"file_path": "owncloud/web/tests/unit/config/vitest.config.ts",
"repo_id": "owncloud",
"token_count": 625
} | 848 |
<?php
//全局session_start
session_start();
//全局居设置时区
date_default_timezone_set('Asia/Shanghai');
//全局设置默认字符
header('Content-type:text/html;charset=utf-8');
//定义数据库连接参数
define('DBHOST', 'localhost');//将localhost修改为数据库服务器的地址
define('DBUSER', 'root');//将root修改为连接mysql的用户名
define('DBPW', 'root');//将root修改为连接mysql的密码
define('DBNAME', 'pkxss');//自定义,建议不修改
define('DBPORT', '3306');//将3306修改为mysql的连接端口,默认tcp3306
?>
| zhuifengshaonianhanlu/pikachu/pkxss/inc/config.inc.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/pkxss/inc/config.inc.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 311
} | 849 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.