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 fill-rule="nonzero" d="M14.935 7.204l-6-3L4 6.319v12.648l5.065-2.17 6 3L20 17.68V5.033l-5.065 2.17zM2 5l7-3 6 3 6.303-2.701a.5.5 0 0 1 .697.46V19l-7 3-6-3-6.303 2.701a.5.5 0 0 1-.697-.46V5zm4 6h2v2H6v-2zm4 0h2v2h-2v-2zm5.998-.063L17.236 9.7l1.06 1.06-1.237 1.238 1.237 1.238-1.06 1.06-1.238-1.237-1.237 1.237-1.061-1.06 1.237-1.238-1.237-1.237L14.76 9.7l1.238 1.237z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/treasure-map-line.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/treasure-map-line.svg",
"repo_id": "owncloud",
"token_count": 329
} | 783 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M12 12.586l4.243 4.242-1.415 1.415L13 16.415V22h-2v-5.587l-1.828 1.83-1.415-1.415L12 12.586zM12 2a7.001 7.001 0 0 1 6.954 6.194 5.5 5.5 0 0 1-.953 10.784L18 17a6 6 0 0 0-11.996-.225L6 17v1.978a5.5 5.5 0 0 1-.954-10.784A7 7 0 0 1 12 2z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/upload-cloud-2-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/upload-cloud-2-fill.svg",
"repo_id": "owncloud",
"token_count": 225
} | 784 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M12 17c3.662 0 6.865 1.575 8.607 3.925l-1.842.871C17.347 20.116 14.847 19 12 19c-2.847 0-5.347 1.116-6.765 2.796l-1.841-.872C5.136 18.574 8.338 17 12 17zm0-15a5 5 0 0 1 5 5v3a5 5 0 0 1-10 0V7a5 5 0 0 1 5-5z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/user-6-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/user-6-fill.svg",
"repo_id": "owncloud",
"token_count": 211
} | 785 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M12 14v8H4a8 8 0 0 1 8-8zm0-1c-3.315 0-6-2.685-6-6s2.685-6 6-6 6 2.685 6 6-2.685 6-6 6zm9.446 7.032l1.504 1.504-1.414 1.414-1.504-1.504a4 4 0 1 1 1.414-1.414zM18 20a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/user-search-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/user-search-fill.svg",
"repo_id": "owncloud",
"token_count": 212
} | 786 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0H24V24H0z"/>
<path d="M16 4c.552 0 1 .448 1 1v4.2l5.213-3.65c.226-.158.538-.103.697.124.058.084.09.184.09.286v12.08c0 .276-.224.5-.5.5-.103 0-.203-.032-.287-.09L17 14.8V19c0 .552-.448 1-1 1H2c-.552 0-1-.448-1-1V5c0-.552.448-1 1-1h14zM8 8v3H5v2h2.999L8 16h2l-.001-3H13v-2h-3V8H8z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/video-add-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/video-add-fill.svg",
"repo_id": "owncloud",
"token_count": 249
} | 787 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M2.8 5.2L7 8l4.186-5.86a1 1 0 0 1 1.628 0L17 8l4.2-2.8a1 1 0 0 1 1.547.95l-1.643 13.967a1 1 0 0 1-.993.883H3.889a1 1 0 0 1-.993-.883L1.253 6.149A1 1 0 0 1 2.8 5.2zM12 15a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/vip-crown-2-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/vip-crown-2-fill.svg",
"repo_id": "owncloud",
"token_count": 212
} | 788 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M8.889 16H5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1h3.889l5.294-4.332a.5.5 0 0 1 .817.387v15.89a.5.5 0 0 1-.817.387L8.89 16zm9.974.591l-1.422-1.422A3.993 3.993 0 0 0 19 12c0-1.43-.75-2.685-1.88-3.392l1.439-1.439A5.991 5.991 0 0 1 21 12c0 1.842-.83 3.49-2.137 4.591z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/volume-down-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/volume-down-fill.svg",
"repo_id": "owncloud",
"token_count": 253
} | 789 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M22 6h-7a6 6 0 1 0 0 12h7v2a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h18a1 1 0 0 1 1 1v2zm-7 2h8v8h-8a4 4 0 1 1 0-8zm0 3v2h3v-2h-3z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/wallet-3-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/wallet-3-fill.svg",
"repo_id": "owncloud",
"token_count": 186
} | 790 |
<template>
<div
:data-test-item-name="name"
:aria-label="accessibleLabel === '' ? null : accessibleLabel"
:aria-hidden="accessibleLabel === '' ? 'true' : null"
:focusable="accessibleLabel === '' ? 'false' : null"
:role="accessibleLabel === '' ? null : 'img'"
>
<span
class="oc-avatar-item"
:style="{
backgroundColor,
'--icon-color': iconColor,
'--width': avatarWidth
}"
>
<oc-icon v-if="hasIcon" :name="icon" :size="iconSize" :fill-type="iconFillType" />
</span>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import OcIcon from '../OcIcon/OcIcon.vue'
export default defineComponent({
name: 'OcAvatarItem',
status: 'ready',
release: '10.0.0',
components: {
OcIcon
},
props: {
/**
* Name of the public link used as an accessible label
*/
name: {
type: String,
required: true
},
/**
* Icon that should be used for the avatar
*/
icon: {
type: String,
required: false,
default: null
},
/**
* Color that should be used for the icon
*/
iconColor: {
type: String,
required: false,
default: 'var(--oc-color-text-inverse)'
},
/**
* Fill-type that should be used for the icon
*/
iconFillType: {
type: String,
required: false,
default: 'fill'
},
/**
* Describes the size of the avatar icon e.g.(small)
*/
iconSize: {
type: String,
required: false,
default: 'small'
},
/**
* Background color that should be used for the avatar. If empty
* a random color will be picked
*/
background: {
type: String,
required: false,
default: 'var(--oc-color-swatch-passive-default)'
},
/**
* Accessibility label used as alt. Use only in case the avatar is used alone.
* In case the avatar is used next to username or display name leave empty.
* If not specified, avatar will get `aria-hidden="true"`.
**/
accessibleLabel: {
type: String,
required: false,
default: ''
},
/**
* Describes the width of the avatar
*/
width: {
type: Number,
required: false,
default: 30
}
},
computed: {
avatarWidth() {
return this.width + 'px'
},
hasIcon() {
return this.icon !== null
},
backgroundColor() {
return this.background || this.pickBackgroundColor
},
pickBackgroundColor() {
const backgroundColors = [
'#b82015',
'#c21c53',
'#9C27B0',
'#673AB7',
'#3F51B5',
'#106892',
'#055c68',
'#208377',
'#1a761d',
'#476e1a',
'#636d0b',
'#8e5c11',
'#795548',
'#465a64'
]
return backgroundColors[Math.floor(Math.random() * backgroundColors.length)]
}
}
})
</script>
<style lang="scss">
.oc-avatar-item {
align-items: center;
background-position: center;
background-repeat: no-repeat;
background-size: 18px;
border-radius: 50%;
display: inline-flex;
height: var(--width);
justify-content: center;
width: var(--width);
.oc-icon > svg {
fill: var(--icon-color) !important;
}
}
</style>
<docs>
```js
<h3>Empty OcAvatarItem</h3>
<oc-avatar-item name="Public link" accessible-label="Public link" />
<h3>OcAvatarItem with icon and default background</h3>
<oc-avatar-item name="Public link" icon="close" accessible-label="Public link" />
<h3>OcAvatarItem with icon and custom background</h3>
<oc-avatar-item name="Public link" icon="close" background="#465a64" accessible-label="Public link" />
<h3>OcAvatarItem with icon and custom background and custom width and iconsize</h3>
<oc-avatar-item :width="100" iconSize="large" name="Public link" icon="close" background="#465a64" accessible-label="Public link" />
```
</docs>
| owncloud/web/packages/design-system/src/components/OcAvatarItem/OcAvatarItem.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcAvatarItem/OcAvatarItem.vue",
"repo_id": "owncloud",
"token_count": 1673
} | 791 |
import { shallowMount, mount } from 'web-test-helpers'
import Drop from './OcDrop.vue'
import { getSizeClass } from '../../utils/sizeClasses'
const dom = ({ position = 'auto', mode = 'click', paddingSize = 'medium' } = {}) => {
document.body.innerHTML = ''
const wrapper = mount(
{
template:
'<div><p id="trigger">trigger</p><oc-drop :position="position" :mode="mode" :padding-size="paddingSize" toggle="#trigger">show</oc-drop></div>',
components: { 'oc-drop': Drop }
},
{
attachTo: document.body,
data: () => ({ position, mode, paddingSize })
}
)
const drop = wrapper.findComponent({ name: 'oc-drop' })
const tippy = drop.vm.$data.tippy
return { wrapper, drop, tippy }
}
describe('OcDrop', () => {
it('handles dropId prop', () => {
for (let i = 0; i < 5; i++) {
const wrapper = shallowMount(Drop)
expect(wrapper.attributes().id).toBe(`oc-drop-${i + 1}`)
}
for (let i = 0; i < 5; i++) {
const id = `custom-drop-id-${i}`
const wrapper = shallowMount(Drop, {
props: {
dropId: id
}
})
expect(wrapper.attributes().id).toBe(id)
}
})
it('handles position prop validator', () => {
;[
'top',
'right',
'bottom',
'left',
'auto',
'top-start',
'top-end',
'right-start',
'right-end',
'bottom-start',
'bottom-end',
'left-start',
'left-end',
'auto-start',
'auto-end'
].forEach((pos) => {
expect(Drop.props.position.validator(pos)).toBeTruthy()
})
expect(Drop.props.position.validator('unknown')).toBeFalsy()
})
it('handles mode prop', () => {
;['click', 'hover'].forEach((pos) => {
expect(Drop.props.mode.validator(pos)).toBeTruthy()
})
expect(Drop.props.mode.validator('unknown')).toBeFalsy()
})
it.each(['xsmall', 'small', 'medium', 'large', 'xlarge', 'xxlarge', 'remove'])(
'handles padding size prop for value %s',
(size) => {
const { drop } = dom({ paddingSize: size })
expect(drop.html().includes(`oc-p-${getSizeClass(size)}`)).toBeTruthy()
}
)
describe('tippy', () => {
it('inits tippy', () => {
const { wrapper, drop, tippy } = dom()
expect(tippy).toBeTruthy()
expect(tippy.reference).toBe(wrapper.find('#trigger').element)
expect(tippy.props.content).toBe(drop.vm.$refs.drop)
})
it('updates tippy', async () => {
const { wrapper, tippy } = dom()
await wrapper.setData({
position: 'left',
mode: 'hover'
})
expect(tippy.props.placement).toBe('left')
expect(tippy.props.trigger).toBe('mouseenter focus')
})
it('renders tippy', async () => {
const { wrapper } = dom()
const trigger = wrapper.find('#trigger')
const wait = async () => {
await wrapper.vm.$nextTick()
return new Promise((resolve) => setTimeout(resolve, 100))
}
await trigger.trigger('click') // show
await wait()
expect(wrapper.findComponent(Drop).exists()).toBeTruthy()
expect(trigger.attributes()['aria-expanded']).toBe('true')
expect(wrapper.element).toMatchSnapshot()
await trigger.trigger('click') // hide
await wait()
expect(trigger.attributes()['aria-expanded']).toBe('false')
expect(wrapper.element).toMatchSnapshot()
await wrapper.setData({
mode: 'hover'
})
await trigger.trigger('mouseenter') // show
await wait()
expect(trigger.attributes()['aria-expanded']).toBe('true')
expect(wrapper.element).toMatchSnapshot()
})
})
})
| owncloud/web/packages/design-system/src/components/OcDrop/OcDrop.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcDrop/OcDrop.spec.ts",
"repo_id": "owncloud",
"token_count": 1544
} | 792 |
<template>
<img :src="src" :alt="alt" :aria-hidden="`${!alt}`" :title="title" :loading="loadingType" />
</template>
<script lang="ts">
import { PropType } from 'vue'
import { defineComponent } from 'vue'
/**
* Images can be displayed using this component.
*
*/
export default defineComponent({
name: 'OcImg',
status: 'ready',
release: '1.0.0',
props: {
/**
* Image source, path to image
*
**/
src: {
required: true,
type: String,
default: null
},
/**
* The alt-attribute of the image.
*/
alt: {
type: String,
required: false,
default: ''
},
/**
* The title of the image. Displayed when hover.
*/
title: {
type: String,
required: false,
default: null
},
/**
* Defines whether the image gets loaded immediately or once it comes near the user's viewport
*/
loadingType: {
type: String as PropType<'lazy' | 'eager'>,
required: false,
default: 'eager',
validator: (value: string) => {
return ['eager', 'lazy'].includes(value)
}
}
},
computed: {
ariaHidden() {
return this.alt.length === 0
}
}
})
</script>
<docs>
```js
<h3>Example image, with width set explicitly:</h3>
<oc-img width="200" height="300" src="https://picsum.photos/200/300/?random" title="I am random" alt="example image" />
<h3>Example grayschale image:</h3>
<oc-img src="https://picsum.photos/g/200/300" title="Grayscale" alt="example grayschale image" />
<h3>Example using a SVG file:</h3>
<oc-img width="100" src="icons/folder.svg" title="i am a folder" alt="folder icon" />
```
</docs>
| owncloud/web/packages/design-system/src/components/OcImage/OcImage.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcImage/OcImage.vue",
"repo_id": "owncloud",
"token_count": 695
} | 793 |
<template>
<div class="oc-page-size">
<label
class="oc-page-size-label"
:for="selectId"
data-testid="oc-page-size-label"
v-text="label"
/>
<oc-select
:input-id="selectId"
class="oc-page-size-select"
data-testid="oc-page-size-select"
:model-value="selected"
:options="options"
:clearable="false"
:searchable="false"
@update:model-value="emitChange"
/>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import uniqueId from '../../utils/uniqueId'
import OcSelect from '../OcSelect/OcSelect.vue'
/**
* Select how many items will be displayed per page
*/
export default defineComponent({
name: 'OcPageSize',
status: 'ready',
release: '8.0.0',
components: { OcSelect },
props: {
/**
* All possible sizes that the user can pick from
*/
options: {
type: Array,
required: true
},
/**
* Label of the select
*/
label: {
type: String,
required: true
},
/**
* Selected size
* @model
*/
selected: {
type: [String, Number],
required: true
},
/**
* An ID of the select component.
* Default value is a unique ID with prefix `oc-page-size`
*/
selectId: {
type: String,
required: false,
default: () => uniqueId('oc-page-size-')
}
},
emits: ['change'],
methods: {
emitChange(value) {
/**
* Triggers when a value is selected
*
* @event change
* @property {number|string} value selected value
*/
this.$emit('change', value)
}
}
})
</script>
<style lang="scss">
.oc-page-size {
align-items: center;
display: flex;
gap: var(--oc-space-xsmall);
&-select,
&-select .vs__dropdown-menu {
min-width: var(--oc-size-width-xsmall);
}
}
</style>
<docs>
```js
<template>
<div>
<oc-page-size v-model="selected" label="Items per page" :options="[100, 500, 1000, 'All']" />
Selected: {{ selected }}
</div>
</template>
<script>
export default {
data: () => ({
selected: 100,
})
}
</script>
```
</docs>
| owncloud/web/packages/design-system/src/components/OcPageSize/OcPageSize.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcPageSize/OcPageSize.vue",
"repo_id": "owncloud",
"token_count": 941
} | 794 |
<template>
<span :class="$_ocSpinner_class" :aria-label="ariaLabel" tabindex="-1" role="img" />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { getSizeClass } from '../../utils/sizeClasses'
/**
* Remote actions can take an undefined portion of time. The spinner gives feedback to the users about an actions being processed.
*
* ## Accessibility
* ### Making spinners accessible for screen readers
*
* 1. Making them (only!) programmatically focusable with `tabindex="-1"`. **This is already included in the component.**
* 2. Giving them the [ARIA role](https://developers.google.com/web/fundamentals/accessibility/semantics-aria) of "img" (image) to change the semantics of the spinner element from something meaningless (div) to something meaningful (image). **This is already included in the component.**
* 3. Giving them an accessible name ([explainer for the term](https://developer.paciellogroup.com/blog/2017/04/what-is-an-accessible-name/)) via aria-label/the ariaLabel prop. An element that has an accessible name, but no role is ignored by assistive technology
* 4. During an action of the application that shows the spinner to visual users, the spinner should programmatically receive focus (see 1.), so that the accessible name of it (default: Loading, see 2.) is read out by screen reader software. After completion of the loading process the focus should be sent to a reasonable place of the newly loaded content.
*
*
*/
export default defineComponent({
name: 'OcSpinner',
status: 'ready',
release: '1.0.0',
props: {
/**
* Descriptive text to be read to screen-readers, strongly recommended unless the component is used inside a DOM node that is already `aria-hidden="true"`.
*/
ariaLabel: {
type: String,
required: false,
default: ''
},
/**
* The size of the spinner. Defaults to medium.
* `xsmall, small, medium, large, xlarge, xxlarge` and `xxxlarge`
*/
size: {
type: String,
default: 'medium',
validator: (value: string) => {
return ['xsmall', 'small', 'medium', 'large', 'xlarge', 'xxlarge', 'xxxlarge'].includes(
value
)
}
}
},
computed: {
$_ocSpinner_class() {
return ['oc-spinner', `oc-spinner-${getSizeClass(this.size)}`]
}
}
})
</script>
<style lang="scss">
@mixin oc-spinner-size($factor) {
height: round(calc($oc-size-icon-default * $factor / 2)) * 2;
width: round(calc($oc-size-icon-default * $factor / 2)) * 2;
}
.oc-spinner {
@include oc-spinner-size(1);
color: var(--oc-color-text-default);
display: inline-block;
&::after {
animation: ball-clip-rotate 1s linear infinite;
background: transparent;
border: 1px solid currentColor;
border-bottom-color: transparent;
border-radius: 100%;
content: '';
display: block;
height: 100%;
width: 100%;
}
&,
&::after {
box-sizing: border-box;
position: relative;
}
&-xs {
@include oc-spinner-size(0.5);
}
&-s {
@include oc-spinner-size(0.7);
}
&-search {
@include oc-spinner-size(0.8);
}
&-m {
@include oc-spinner-size(1);
}
&-l {
@include oc-spinner-size(1.5);
}
&-xl {
@include oc-spinner-size(2);
}
&-xxl {
@include oc-spinner-size(4);
}
&-xxxl {
@include oc-spinner-size(8);
}
}
@keyframes ball-clip-rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<docs>
```js
<div class="oc-flex oc-flex-middle">
<oc-spinner aria-label="Loading with extra small spinner" size="xsmall" class="oc-mr-s" />
<oc-spinner aria-label="Loading with small spinner" size="small" class="oc-mr-s" />
<oc-spinner aria-label="Loading with default sized spinner" class="oc-mr-s" />
<oc-spinner aria-label="Loading with medium spinner" size="medium" class="oc-mr-s" />
<oc-spinner aria-label="Loading with large spinner" size="large" class="oc-mr-s" />
<oc-spinner aria-label="Loading with extra large spinner" size="xlarge" class="oc-mr-s" />
<oc-spinner aria-label="Loading with extra extra large spinner" size="xxlarge" class="oc-mr-s" />
<oc-spinner aria-label="Loading with extra extra extra large spinner" size="xxxlarge" />
</div>
```
</docs>
| owncloud/web/packages/design-system/src/components/OcSpinner/OcSpinner.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcSpinner/OcSpinner.vue",
"repo_id": "owncloud",
"token_count": 1561
} | 795 |
import { shallowMount } from 'web-test-helpers'
import OcTextarea from './OcTextarea.vue'
const defaultProps = {
label: 'label'
}
describe('OcTextarea', () => {
function getShallowWrapper(props = {}) {
return shallowMount(OcTextarea, {
props: {
...defaultProps,
...props
}
})
}
const selectors = {
textareaMessage: '.oc-textarea-message span',
textArea: '.oc-textarea'
}
describe('id prop', () => {
const wrapper = getShallowWrapper({
id: 'test-textarea-id',
descriptionMessage: 'hello'
})
it('should set provided id to the textarea', () => {
expect(wrapper.find('textarea').attributes().id).toBe('test-textarea-id')
})
it('should set label target for provided id', () => {
expect(wrapper.find('label').attributes().for).toBe('test-textarea-id')
})
it('should set message id according to provided id', () => {
expect(wrapper.find(selectors.textareaMessage).attributes().id).toBe(
'test-textarea-id-message'
)
})
})
describe('label prop', () => {
it('should set provided label to the textarea', () => {
const wrapper = getShallowWrapper()
expect(wrapper.find('label').text()).toBe('label')
})
})
describe('when a description message is provided', () => {
const wrapper = getShallowWrapper({ descriptionMessage: 'You should pass.' })
it('should add the description class to the textarea message', () => {
expect(wrapper.find(selectors.textareaMessage).attributes().class).toContain(
'oc-textarea-description'
)
})
it('should show the description message as the input message text', () => {
expect(wrapper.find(selectors.textareaMessage).text()).toBe('You should pass.')
})
})
describe('when a warning message is provided', () => {
const wrapper = getShallowWrapper({ warningMessage: 'You may pass.' })
it('should add the warning class to the textarea', () => {
expect(wrapper.find('textarea').attributes().class).toContain('oc-textarea-warning')
})
it('should add the warning class to the textarea message', () => {
expect(wrapper.find(selectors.textareaMessage).attributes().class).toContain(
'oc-textarea-warning'
)
})
it('should show the warning message as the textarea message text', () => {
expect(wrapper.find(selectors.textareaMessage).text()).toBe('You may pass.')
})
})
describe('when an error message is provided', () => {
const wrapper = getShallowWrapper({ errorMessage: 'You shall not pass.' })
it('should add the error class to the textarea', () => {
expect(wrapper.find('textarea').attributes().class).toContain('oc-textarea-danger')
})
it('should add the error class to the textarea message', () => {
expect(wrapper.find(selectors.textareaMessage).attributes().class).toContain(
'oc-textarea-danger'
)
})
it('should show the error message as the textarea message text', () => {
expect(wrapper.find(selectors.textareaMessage).text()).toBe('You shall not pass.')
})
it('should set the input aria-invalid attribute to true', () => {
expect(wrapper.find('textarea').attributes('aria-invalid')).toBe('true')
})
})
describe('message priority', () => {
it('should give error message top priority', () => {
const wrapper = getShallowWrapper({
errorMessage: 'You shall not pass.',
warningMessage: 'You may pass.',
descriptionMessage: 'Your should pass.'
})
const messageEl = wrapper.find('.oc-textarea-message span')
expect(messageEl.attributes().class).toBe(
'oc-textarea-description oc-textarea-warning oc-textarea-danger'
)
expect(messageEl.text()).toBe('You shall not pass.')
})
it('should give warning message priority over description message', () => {
const wrapper = getShallowWrapper({
warningMessage: 'You may pass.',
descriptionMessage: 'Your should pass.'
})
const messageEl = wrapper.find(selectors.textareaMessage)
expect(messageEl.attributes().class).toBe('oc-textarea-description oc-textarea-warning')
expect(messageEl.text()).toBe('You may pass.')
})
})
describe('input events', () => {
it('should emit an input event on typing', async () => {
const wrapper = getShallowWrapper()
expect(wrapper.emitted('update:modelValue')).toBeFalsy()
await wrapper.find('textarea').setValue('a')
expect(wrapper.emitted('update:modelValue')).toBeTruthy()
expect(wrapper.emitted('update:modelValue')[0][0]).toBe('a')
})
})
describe('change events', () => {
it('should emit a change event if submitOnEnter is true', async () => {
const wrapper = getShallowWrapper({ submitOnEnter: true })
expect(wrapper.emitted().change).toBeFalsy()
await wrapper.find('textarea').trigger('keydown.enter')
expect(wrapper.emitted().change).toBeTruthy()
})
it("shouldn't emit a change event if submitOnEnter is false", async () => {
const wrapper = getShallowWrapper({ submitOnEnter: false })
expect(wrapper.emitted().change).toBeFalsy()
await wrapper.find('textarea').trigger('keydown.enter')
expect(wrapper.emitted().change).toBeFalsy()
})
})
})
| owncloud/web/packages/design-system/src/components/OcTextarea/OcTextarea.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcTextarea/OcTextarea.spec.ts",
"repo_id": "owncloud",
"token_count": 1918
} | 796 |
<template>
<tr
ref="observerTarget"
tabindex="-1"
@click="$emit('click', $event)"
@contextmenu="$emit('contextmenu', $event)"
@dragstart="$emit('dragstart', $event)"
@drop="$emit('drop', $event)"
@dragenter="$emit('dragenter', $event)"
@dragleave="$emit('dragleave', $event)"
@dragover="$emit('dragover', $event)"
@mouseleave="$emit('mouseleave', $event)"
>
<oc-td v-if="isHidden" :colspan="lazyColspan">
<span class="shimmer" />
</oc-td>
<slot v-else />
</tr>
</template>
<script lang="ts">
import { customRef, computed, ref, unref, defineComponent } from 'vue'
import { useIsVisible } from '../../composables'
import OcTd from '../_OcTableCellData/_OcTableCellData.vue'
export default defineComponent({
name: 'OcTr',
status: 'ready',
release: '1.0.0',
components: { OcTd },
props: {
lazy: {
type: Object,
required: false,
default: null
}
},
emits: [
'contextmenu',
'click',
'dragstart',
'drop',
'dragenter',
'dragleave',
'dragover',
'mouseleave'
],
setup(props, ctx) {
const observerTarget = customRef((track, trigger) => {
let $el
return {
get() {
track()
return $el
},
set(value) {
$el = value
trigger()
}
}
})
const lazyColspan = computed(() => {
return props.lazy ? props.lazy.colspan : 1
})
const { isVisible } = props.lazy
? useIsVisible({
...props.lazy,
target: observerTarget
})
: { isVisible: ref(true) }
const isHidden = computed(() => !unref(isVisible))
return {
observerTarget,
isHidden,
lazyColspan
}
}
})
</script>
<style lang="scss">
.shimmer {
background-color: var(--oc-color-input-text-muted);
bottom: 12px;
display: inline-block;
left: var(--oc-space-small);
opacity: 0.2;
overflow: hidden;
position: absolute;
right: var(--oc-space-small);
top: 12px;
&::after {
animation: shimmer 2s infinite;
background-image: linear-gradient(
90deg,
rgba(#fff, 0) 0,
rgba(#fff, 0.2) 20%,
rgba(#fff, 0.5) 60%,
rgba(#fff, 0)
);
bottom: 0;
content: '';
left: 0;
position: absolute;
right: 0;
top: 0;
transform: translateX(-100%);
}
@keyframes shimmer {
100% {
transform: translateX(100%);
}
}
}
</style>
| owncloud/web/packages/design-system/src/components/_OcTableRow/_OcTableRow.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/_OcTableRow/_OcTableRow.vue",
"repo_id": "owncloud",
"token_count": 1135
} | 797 |
// 1. Your custom variables and variable overwrites.
@import "../assets/tokens/ods";
@import "theme/variables";
// 2. Import Vendor.
@import "../../node_modules/tippy.js/dist/tippy";
// 3. Your custom mixin overwrites.
@import "theme/background";
@import "theme/helper";
@import "theme/login";
@import "theme/oc-animations";
@import "theme/oc-card";
@import "theme/oc-flex";
@import "theme/oc-form";
@import "theme/oc-label";
@import "theme/oc-height";
@import "theme/oc-position";
@import "theme/oc-spacing-negative";
@import "theme/oc-spacing";
@import "theme/oc-text";
@import "theme/oc-visibility";
@import "theme/oc-width";
@import "theme/tooltip";
| owncloud/web/packages/design-system/src/styles/styles.scss/0 | {
"file_path": "owncloud/web/packages/design-system/src/styles/styles.scss",
"repo_id": "owncloud",
"token_count": 234
} | 798 |
/*
* Hidden
* `hidden` attribute also set here to make it stronger
*/
[hidden],
.oc-hidden {
display: none !important;
}
/* Phone landscape and bigger */
@media (min-width: $oc-breakpoint-small-default) {
.oc-hidden\@s {
display: none !important;
}
}
/* Tablet landscape and bigger */
@media (min-width: $oc-breakpoint-medium-default) {
.oc-hidden\@m {
display: none !important;
}
}
/* Desktop and bigger */
@media (min-width: $oc-breakpoint-large-default) {
.oc-hidden\@l {
display: none !important;
}
}
/* Large screen and bigger */
@media (min-width: $oc-breakpoint-xlarge) {
.oc-hidden\@xl {
display: none !important;
}
}
/*
* Visible
*/
.oc-invisible {
visibility: hidden !important;
}
/* Phone portrait and smaller */
@media (max-width: $oc-breakpoint-xsmall-max) {
.oc-visible\@s {
display: none !important;
}
}
/* Phone landscape and smaller */
@media (max-width: $oc-breakpoint-small-max) {
.oc-visible\@m {
display: none !important;
}
}
/* Tablet landscape and smaller */
@media (max-width: $oc-breakpoint-medium-max) {
.oc-visible\@l {
display: none !important;
}
}
/* Desktop and smaller */
@media (max-width: $oc-breakpoint-large-max) {
.oc-visible\@xl {
display: none !important;
}
}
/*
* Special SR classes
*/
/// Used to hide an element visually, but keeping it accessible for
/// accessibility tools.
.oc-invisible-sr {
border: 0 !important;
clip: rect(1px, 1px, 1px, 1px) !important;
height: 1px !important;
overflow: hidden !important;
padding: 0 !important;
// Need to make sure we override any existing styles.
position: absolute !important;
top: 0;
white-space: nowrap;
width: 1px !important;
}
| owncloud/web/packages/design-system/src/styles/theme/oc-visibility.scss/0 | {
"file_path": "owncloud/web/packages/design-system/src/styles/theme/oc-visibility.scss",
"repo_id": "owncloud",
"token_count": 623
} | 799 |
let num = 0
export default function uniqueId(prefix?) {
prefix = prefix || ''
num += 1
return prefix + num
}
| owncloud/web/packages/design-system/src/utils/uniqueId.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/utils/uniqueId.ts",
"repo_id": "owncloud",
"token_count": 36
} | 800 |
{
"name": "web-app-admin-settings",
"version": "0.0.0",
"private": true,
"description": "ownCloud admin settings",
"license": "AGPL-3.0",
"devDependencies": {
"web-test-helpers": "workspace:*"
},
"dependencies": {
"deep-object-diff": "^1.1.9",
"email-validator": "^2.0.4",
"mark.js": "^8.11.1"
},
"peerDependencies": {
"@ownclouders/web-client": "workspace:*",
"@ownclouders/web-pkg": "workspace:*",
"axios": "1.6.5",
"design-system": "workspace:@ownclouders/design-system@*",
"fuse.js": "6.6.2",
"lodash-es": "4.17.21",
"pinia": "2.1.7",
"uuid": "9.0.1",
"vue-concurrency": "5.0.0",
"web-app-admin-settings": "workspace:*"
}
}
| owncloud/web/packages/web-app-admin-settings/package.json/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/package.json",
"repo_id": "owncloud",
"token_count": 346
} | 801 |
<template>
<ul class="oc-list">
<li
v-for="(member, index) in members"
:key="index"
class="oc-flex oc-flex-middle oc-mb-s"
data-testid="space-members-list"
>
<oc-avatar
v-if="member.kind === 'user'"
:user-name="member.displayName"
:width="36"
class="oc-mr-s"
/><oc-avatar-item
v-else
:width="36"
icon-size="medium"
:icon="groupIcon"
name="group"
class="oc-mr-s"
/>
{{ member.displayName }}
</li>
</ul>
</template>
<script lang="ts">
import { computed, defineComponent, PropType } from 'vue'
import { ShareTypes } from '@ownclouders/web-client/src/helpers/share'
import { SpaceRole } from '@ownclouders/web-client/src/helpers'
export default defineComponent({
name: 'MembersRoleSection',
props: {
members: {
type: Array as PropType<SpaceRole[]>,
required: true
}
},
setup() {
const groupIcon = computed(() => {
return ShareTypes.group.icon
})
return { groupIcon }
}
})
</script>
| owncloud/web/packages/web-app-admin-settings/src/components/Spaces/SideBar/MembersRoleSection.vue/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/src/components/Spaces/SideBar/MembersRoleSection.vue",
"repo_id": "owncloud",
"token_count": 486
} | 802 |
import { useModals, UserAction } from '@ownclouders/web-pkg'
import { computed } from 'vue'
import { useGettext } from 'vue3-gettext'
import CreateGroupModal from '../../../components/Groups/CreateGroupModal.vue'
export const useGroupActionsCreateGroup = () => {
const { dispatchModal } = useModals()
const { $gettext } = useGettext()
const actions = computed((): UserAction[] => [
{
name: 'create-group',
icon: 'add',
componentType: 'button',
class: 'oc-groups-actions-create-group',
label: () => $gettext('New group'),
isVisible: () => true,
handler: () => {
dispatchModal({
title: $gettext('Create group'),
customComponent: CreateGroupModal
})
}
}
])
return {
actions
}
}
| owncloud/web/packages/web-app-admin-settings/src/composables/actions/groups/useGroupActionsCreateGroup.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/src/composables/actions/groups/useGroupActionsCreateGroup.ts",
"repo_id": "owncloud",
"token_count": 313
} | 803 |
import { defineStore } from 'pinia'
import { ref, unref } from 'vue'
import { Group } from '@ownclouders/web-client/src/generated'
export const useGroupSettingsStore = defineStore('groupSettings', () => {
const groups = ref<Group[]>([])
const selectedGroups = ref<Group[]>([])
const setGroups = (data: Group[]) => {
groups.value = data
}
const upsertGroup = (group: Group) => {
const existing = unref(groups).some(({ id }) => id === group.id)
if (existing) {
Object.assign(existing, { ...group, members: [] })
return
}
unref(groups).push({ ...group, members: [] })
}
const removeGroups = (values: Group[]) => {
groups.value = unref(groups).filter((group) => !values.find(({ id }) => id === group.id))
}
const setSelectedGroups = (data: Group[]) => {
selectedGroups.value = data
}
const addSelectedGroup = (data: Group) => {
unref(selectedGroups).push(data)
}
const reset = () => {
groups.value = []
selectedGroups.value = []
}
return {
groups,
upsertGroup,
setGroups,
removeGroups,
reset,
selectedGroups,
addSelectedGroup,
setSelectedGroups
}
})
export type GroupSettingsStore = ReturnType<typeof useGroupSettingsStore>
| owncloud/web/packages/web-app-admin-settings/src/composables/stores/groupSettings.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/src/composables/stores/groupSettings.ts",
"repo_id": "owncloud",
"token_count": 451
} | 804 |
import MembersPanel from '../../../../../src/components/Groups/SideBar/MembersPanel.vue'
import { defaultPlugins, shallowMount } from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { Group } from '@ownclouders/web-client/src/generated'
import MembersRoleSection from '../../../../../src/components/Groups/SideBar/MembersRoleSection.vue'
const groupMock = mock<Group>({
id: '1',
groupTypes: [],
members: [{ displayName: 'Albert Einstein' }]
})
const selectors = {
membersRolePanelStub: 'members-role-section-stub'
}
describe('MembersPanel', () => {
it('should render all members accordingly to their role assignments', () => {
const { wrapper } = getWrapper()
expect(wrapper.html()).toMatchSnapshot()
})
it('should filter members accordingly to the entered search term', async () => {
const { wrapper } = getWrapper()
wrapper.vm.filterTerm = 'ein'
await wrapper.vm.$nextTick
expect(wrapper.findAll(selectors.membersRolePanelStub).length).toBe(1)
expect(
wrapper.findComponent<typeof MembersRoleSection>(selectors.membersRolePanelStub).props()
.groupMembers[0].displayName
).toEqual('Albert Einstein')
})
it('should display an empty result if no matching members found', async () => {
const { wrapper } = getWrapper()
wrapper.vm.filterTerm = 'no-match'
await wrapper.vm.$nextTick
expect(wrapper.findAll(selectors.membersRolePanelStub).length).toBe(0)
expect(wrapper.html()).toMatchSnapshot()
})
})
function getWrapper({ group = groupMock } = {}) {
return {
wrapper: shallowMount(MembersPanel, {
global: {
plugins: [...defaultPlugins()],
provide: { group: group }
}
})
}
}
| owncloud/web/packages/web-app-admin-settings/tests/unit/components/Groups/SideBar/MembersPanel.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/components/Groups/SideBar/MembersPanel.spec.ts",
"repo_id": "owncloud",
"token_count": 594
} | 805 |
import DetailsPanel from '../../../../../src/components/Users/SideBar/DetailsPanel.vue'
import { PartialComponentProps, defaultPlugins, shallowMount } from 'web-test-helpers'
const defaultUser = { displayName: 'user', memberOf: [] }
describe('DetailsPanel', () => {
describe('computed method "user"', () => {
it('should be set if only one user is given', () => {
const { wrapper } = getWrapper({ props: { user: defaultUser, users: [defaultUser] } })
expect(wrapper.vm.user).toEqual(defaultUser)
})
it('should not be set if no users are given', () => {
const { wrapper } = getWrapper({
props: { user: null, users: [] }
})
expect(wrapper.vm.user).toEqual(null)
})
it('should not be set if multiple users are given', () => {
const { wrapper } = getWrapper({
props: { user: null, users: [defaultUser, { displayName: 'user2' }] }
})
expect(wrapper.vm.user).toEqual(null)
})
})
describe('computed method "noUsers"', () => {
it('should be true if no users are given', () => {
const { wrapper } = getWrapper({
props: { user: null, users: [] }
})
expect(wrapper.vm.noUsers).toBeTruthy()
})
it('should be false if users are given', () => {
const { wrapper } = getWrapper({ props: { user: defaultUser, users: [defaultUser] } })
expect(wrapper.vm.noUsers).toBeFalsy()
})
})
describe('computed method "multipleUsers"', () => {
it('should be false if no users are given', () => {
const { wrapper } = getWrapper({ props: { user: null, users: [] } })
expect(wrapper.vm.multipleUsers).toBeFalsy()
})
it('should be false if one user is given', () => {
const { wrapper } = getWrapper({ props: { user: defaultUser, users: [defaultUser] } })
expect(wrapper.vm.multipleUsers).toBeFalsy()
})
it('should be true if multiple users are given', () => {
const { wrapper } = getWrapper({
props: { user: null, users: [defaultUser, { displayName: 'user2' }] }
})
expect(wrapper.vm.multipleUsers).toBeTruthy()
})
})
})
function getWrapper({ props }: { props: PartialComponentProps<typeof DetailsPanel> }) {
return {
wrapper: shallowMount(DetailsPanel, {
props: {
users: [],
roles: [],
...props
},
global: {
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-app-admin-settings/tests/unit/components/Users/SideBar/DetailsPanel.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/components/Users/SideBar/DetailsPanel.spec.ts",
"repo_id": "owncloud",
"token_count": 931
} | 806 |
import { useUserActionsEditQuota } from '../../../../../src/composables/actions/users/useUserActionsEditQuota'
import { defaultComponentMocks, getComposableWrapper, writable } from 'web-test-helpers'
import { unref } from 'vue'
import { useCapabilityStore, useModals } from '@ownclouders/web-pkg'
describe('useUserActionsEditQuota', () => {
describe('isVisible property', () => {
it('should be false when not resource given', () => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [] })).toBe(false)
}
})
})
it('should be true when the current user has the "set-space-quota"-permission', () => {
const userMock = {
id: '1',
drive: {
name: 'some-drive',
quota: {}
}
}
getWrapper({
canEditSpaceQuota: true,
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [userMock] })).toBe(true)
}
})
})
it('should be false when the current user does not have the "set-space-quota"-permission', () => {
const userMock = {
id: '1',
drive: {
name: 'some-drive',
quota: {}
}
}
getWrapper({
canEditSpaceQuota: false,
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [userMock] })).toBe(false)
}
})
})
it('should false if included in capability readOnlyUserAttributes list', () => {
getWrapper({
setup: ({ actions }) => {
const userMock = {
id: '1',
drive: {
name: 'some-drive',
quota: {}
}
}
const capabilityStore = useCapabilityStore()
writable(capabilityStore).graphUsersReadOnlyAttributes = ['drive.quota']
expect(unref(actions)[0].isVisible({ resources: [userMock] })).toEqual(false)
}
})
})
})
describe('handler', () => {
it('should create a modal', () => {
getWrapper({
setup: async ({ actions }) => {
const { dispatchModal } = useModals()
await unref(actions)[0].handler({ resources: [] })
expect(dispatchModal).toHaveBeenCalled()
}
})
})
})
})
function getWrapper({
canEditSpaceQuota = false,
setup
}: {
canEditSpaceQuota?: boolean
setup: (instance: ReturnType<typeof useUserActionsEditQuota>) => void
}) {
const mocks = defaultComponentMocks()
return {
wrapper: getComposableWrapper(
() => {
const instance = useUserActionsEditQuota()
setup(instance)
},
{
mocks,
pluginOptions: {
abilities: canEditSpaceQuota ? [{ action: 'set-quota-all', subject: 'Drive' }] : []
}
}
)
}
}
| owncloud/web/packages/web-app-admin-settings/tests/unit/composables/actions/users/useUserActionsEditQuota.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/composables/actions/users/useUserActionsEditQuota.spec.ts",
"repo_id": "owncloud",
"token_count": 1281
} | 807 |
{
"name": "web-app-files",
"version": "0.0.0",
"private": true,
"description": "ownCloud web files",
"license": "AGPL-3.0",
"dependencies": {
"mark.js": "^8.11.1"
},
"devDependencies": {
"@vueuse/core": "^10.3.0",
"web-test-helpers": "workspace:*"
},
"peerDependencies": {
"@ownclouders/web-client": "workspace:*",
"@ownclouders/web-pkg": "workspace:*",
"@uppy/core": "3.3.0",
"@uppy/dashboard": "3.4.1",
"@uppy/onedrive": "3.1.1",
"@vueuse/core": "^10.3.0",
"axios": "1.6.5",
"design-system": "workspace:@ownclouders/design-system@*",
"email-validator": "^2.0.4",
"filesize": "^10.1.0",
"fuse.js": "6.6.2",
"lodash-es": "4.17.21",
"luxon": "3.2.1",
"p-queue": "^6.6.2",
"pinia": "2.1.7",
"qs": "6.11.2",
"uuid": "9.0.1",
"vue-concurrency": "5.0.0",
"vue-router": "4.2.5",
"vue3-gettext": "2.4.0",
"web-app-files": "workspace:*",
"web-app-search": "workspace:*",
"web-runtime": "workspace:*",
"dompurify": "^3.0.6"
}
}
| owncloud/web/packages/web-app-files/package.json/0 | {
"file_path": "owncloud/web/packages/web-app-files/package.json",
"repo_id": "owncloud",
"token_count": 563
} | 808 |
<template>
<div>
<h2 class="oc-px-m oc-py-s oc-invisible-sr">
{{ title }}
<span class="oc-text-medium">({{ items.length }})</span>
</h2>
<no-content-message
v-if="!items.length"
class="files-empty oc-flex-stretch"
icon="share-forward"
>
<template #message>
<span>{{ emptyMessage }}</span>
</template>
</no-content-message>
<resource-table
v-else
v-model:selectedIds="selectedResourcesIds"
:is-side-bar-open="isSideBarOpen"
:fields-displayed="displayedFields"
sidebar-closed
:are-thumbnails-displayed="displayThumbnails"
:resources="resourceItems"
:are-resources-clickable="resourceClickable"
:target-route-callback="resourceTargetRouteCallback"
:header-position="fileListHeaderY"
:sort-by="sortBy"
:sort-dir="sortDir"
:grouping-settings="groupingSettings"
@file-click="triggerDefaultAction"
@row-mounted="rowMounted"
@sort="sortHandler"
>
<template #syncEnabled="{ resource }">
<div
:key="resource.getDomSelector()"
class="oc-text-nowrap oc-flex oc-flex-middle oc-flex-right"
>
<oc-icon
v-if="resource.syncEnabled"
v-oc-tooltip="$gettext('Synced with your devices')"
name="loop-right"
class="sync-enabled"
/>
</div>
</template>
<template #contextMenu="{ resource }">
<context-actions
v-if="isResourceInSelection(resource)"
:action-options="{ space: getMatchingSpace(resource), resources: selectedResources }"
/>
</template>
<template #quickActions="{ resource }">
<oc-button
size="small"
appearance="raw"
:class="['oc-ml-s', 'oc-p-s', hideShareAction.class]"
@click.stop="hideShareAction.handler({ space: null, resources: [resource] })"
>
<oc-icon size="small" :name="resource.hidden ? 'eye' : 'eye-off'" fill-type="line" />
<span>{{ hideShareAction.label({ space: null, resources: [resource] }) }}</span>
</oc-button>
</template>
<template #footer>
<div v-if="showMoreToggle && hasMore" class="oc-width-1-1 oc-text-center oc-mt">
<oc-button
id="files-shared-with-me-show-all"
appearance="raw"
gap-size="xsmall"
size="small"
:data-test-expand="(!showMore).toString()"
@click="toggleShowMore"
>
{{ toggleMoreLabel }}
<oc-icon :name="'arrow-' + (showMore ? 'up' : 'down') + '-s'" fill-type="line" />
</oc-button>
</div>
<list-info
v-else
class="oc-width-1-1 oc-my-s"
:files="countFiles"
:folders="countFolders"
/>
</template>
</resource-table>
</div>
</template>
<script lang="ts">
import {
ResourceTable,
useCapabilityStore,
useConfigStore,
useFileActions,
useFileActionsToggleHideShare,
useResourcesStore
} from '@ownclouders/web-pkg'
import { computed, defineComponent, PropType, unref } from 'vue'
import { debounce } from 'lodash-es'
import { ImageDimension } from '@ownclouders/web-pkg'
import { VisibilityObserver } from '@ownclouders/web-pkg'
import { SortDir, useGetMatchingSpace } from '@ownclouders/web-pkg'
import { createLocationSpaces } from '@ownclouders/web-pkg'
import ListInfo from '../../components/FilesList/ListInfo.vue'
import { IncomingShareResource } from '@ownclouders/web-client/src/helpers/share'
import { ContextActions } from '@ownclouders/web-pkg'
import { NoContentMessage } from '@ownclouders/web-pkg'
import { useSelectedResources } from '@ownclouders/web-pkg'
import { RouteLocationNamedRaw } from 'vue-router'
import { CreateTargetRouteOptions } from '@ownclouders/web-pkg'
import { createFileRouteOptions } from '@ownclouders/web-pkg'
const visibilityObserver = new VisibilityObserver()
export default defineComponent({
components: {
ResourceTable,
ContextActions,
ListInfo,
NoContentMessage
},
props: {
title: {
type: String,
required: true
},
emptyMessage: {
type: String,
required: false,
default: ''
},
items: {
type: Array as PropType<IncomingShareResource[]>,
required: true
},
sortBy: {
type: String,
required: false,
default: undefined
},
sortDir: {
type: String,
required: false,
default: undefined,
validator: (value: string) => {
return (
value === undefined || [SortDir.Asc.toString(), SortDir.Desc.toString()].includes(value)
)
}
},
sortHandler: {
type: Function as PropType<any>,
required: true
},
showMoreToggle: {
type: Boolean,
default: false
},
showMoreToggleCount: {
type: Number,
default: 3
},
resourceClickable: {
type: Boolean,
default: true
},
displayThumbnails: {
type: Boolean,
default: true
},
isSideBarOpen: {
type: Boolean,
default: false
},
fileListHeaderY: {
type: Number,
default: 0
},
/**
* This is only relevant for CERN and can be ignored in any other cases.
*/
groupingSettings: {
type: Object,
required: false,
default: null
}
},
setup() {
const capabilityStore = useCapabilityStore()
const configStore = useConfigStore()
const { getMatchingSpace } = useGetMatchingSpace()
const { triggerDefaultAction } = useFileActions()
const { actions: hideShareActions } = useFileActionsToggleHideShare()
const hideShareAction = computed(() => unref(hideShareActions)[0])
const { updateResourceField } = useResourcesStore()
const resourceTargetRouteCallback = ({
path,
fileId,
resource
}: CreateTargetRouteOptions): RouteLocationNamedRaw => {
return createLocationSpaces(
'files-spaces-generic',
createFileRouteOptions(getMatchingSpace(resource), { path, fileId })
)
}
return {
capabilityStore,
configStore,
triggerDefaultAction,
hideShareAction,
resourceTargetRouteCallback,
...useSelectedResources(),
getMatchingSpace,
updateResourceField
}
},
data: () => ({
showMore: false
}),
computed: {
displayedFields() {
return ['name', 'syncEnabled', 'sharedBy', 'sdate', 'sharedWith']
},
countFiles() {
return this.items.filter((s) => s.type !== 'folder').length
},
countFolders() {
return this.items.filter((s) => s.type === 'folder').length
},
toggleMoreLabel() {
return this.showMore ? this.$gettext('Show less') : this.$gettext('Show more')
},
hasMore() {
return this.items.length > this.showMoreToggleCount
},
resourceItems() {
if (!this.showMoreToggle || this.showMore) {
return this.items
}
return this.items.slice(0, this.showMoreToggleCount)
}
},
beforeUnmount() {
visibilityObserver.disconnect()
},
methods: {
rowMounted(resource: IncomingShareResource, component) {
const loadPreview = async () => {
const preview = await this.$previewService.loadPreview(
{
space: this.getMatchingSpace(resource),
resource,
dimensions: ImageDimension.Thumbnail
},
true
)
if (preview) {
this.updateResourceField({ id: resource.id, field: 'thumbnail', value: preview })
}
}
const debounced = debounce(({ unobserve }) => {
unobserve()
loadPreview()
}, 250)
visibilityObserver.observe(component.$el, {
onEnter: debounced,
onExit: debounced.cancel
})
},
toggleShowMore() {
this.showMore = !this.showMore
}
}
})
</script>
<style lang="scss" scoped>
.oc-files-actions-hide-share-trigger:hover {
background-color: var(--oc-color-background-secondary) !important;
}
</style>
| owncloud/web/packages/web-app-files/src/components/Shares/SharedWithMeSection.vue/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/components/Shares/SharedWithMeSection.vue",
"repo_id": "owncloud",
"token_count": 3480
} | 809 |
<template>
<div id="oc-files-sharing-sidebar" class="oc-position-relative">
<div class="oc-flex">
<h3 v-translate class="oc-text-bold oc-text-medium oc-m-rm">Share with people</h3>
<oc-contextual-helper
v-if="helpersEnabled"
class="oc-pl-xs"
v-bind="inviteCollaboratorHelp"
/>
</div>
<invite-collaborator-form
v-if="canShare({ resource, space })"
key="new-collaborator"
class="oc-my-s"
/>
<p
v-else
key="no-reshare-permissions-message"
data-testid="files-collaborators-no-reshare-permissions-message"
v-text="noSharePermsMessage"
/>
<div v-if="hasSharees" class="avatars-wrapper oc-flex oc-flex-middle oc-flex-between">
<h4 class="oc-text-bold oc-my-rm" v-text="sharedWithLabel" />
</div>
<template v-if="hasSharees">
<portal-target
name="app.files.sidebar.sharing.shared-with.top"
:slot-props="{ space, resource }"
:multiple="true"
/>
<ul
id="files-collaborators-list"
class="oc-list oc-list-divider oc-overflow-hidden"
:class="{ 'oc-mb-l': showSpaceMembers, 'oc-m-rm': !showSpaceMembers }"
:aria-label="$gettext('Share receivers')"
>
<li v-for="collaborator in displayCollaborators" :key="collaborator.id">
<collaborator-list-item
:share="collaborator"
:resource-name="resource.name"
:deniable="isShareDeniable(collaborator)"
:modifiable="isShareModifiable(collaborator)"
:is-share-denied="isShareDenied(collaborator)"
:shared-parent-route="getSharedParentRoute(collaborator)"
:is-locked="resource.locked"
@on-delete="deleteShareConfirmation"
@on-set-deny="setDenyShare"
/>
</li>
<portal-target
name="app.files.sidebar.sharing.shared-with.bottom"
:slot-props="{ space, resource }"
:multiple="true"
/>
</ul>
<div v-if="showShareToggle" class="oc-flex oc-flex-center">
<oc-button
appearance="raw"
class="toggle-shares-list-btn"
@click="toggleShareListCollapsed"
>
{{ collapseButtonTitle }}
</oc-button>
</div>
</template>
<template v-if="showSpaceMembers">
<h4 class="oc-text-bold oc-my-s" v-text="spaceMemberLabel" />
<ul
id="space-collaborators-list"
class="oc-list oc-list-divider oc-overflow-hidden oc-m-rm"
:aria-label="spaceMemberLabel"
>
<li v-for="(collaborator, i) in displaySpaceMembers" :key="i">
<collaborator-list-item
:share="collaborator"
:resource-name="resource.name"
:deniable="isSpaceMemberDeniable(collaborator)"
:modifiable="false"
:is-share-denied="isSpaceMemberDenied(collaborator)"
@on-set-deny="setDenyShare"
/>
</li>
</ul>
<div v-if="showMemberToggle" class="oc-flex oc-flex-center">
<oc-button appearance="raw" @click="toggleMemberListCollapsed">
{{ collapseButtonTitle }}
</oc-button>
</div>
</template>
</div>
</template>
<script lang="ts">
import { storeToRefs } from 'pinia'
import {
useGetMatchingSpace,
useModals,
useUserStore,
useMessages,
useSpacesStore,
useCapabilityStore,
useConfigStore,
useSharesStore,
useResourcesStore,
useCanShare
} from '@ownclouders/web-pkg'
import { isLocationSharesActive } from '@ownclouders/web-pkg'
import { textUtils } from '../../../helpers/textUtils'
import { ShareTypes } from '@ownclouders/web-client/src/helpers/share'
import InviteCollaboratorForm from './Collaborators/InviteCollaborator/InviteCollaboratorForm.vue'
import CollaboratorListItem from './Collaborators/ListItem.vue'
import {
shareInviteCollaboratorHelp,
shareInviteCollaboratorHelpCern
} from '../../../helpers/contextualHelpers'
import { computed, defineComponent, inject, ref, Ref, unref } from 'vue'
import {
isProjectSpaceResource,
Resource,
SpaceResource,
CollaboratorShare
} from '@ownclouders/web-client/src/helpers'
import { getSharedAncestorRoute } from '@ownclouders/web-pkg'
export default defineComponent({
name: 'FileShares',
components: {
InviteCollaboratorForm,
CollaboratorListItem
},
setup() {
const userStore = useUserStore()
const capabilityStore = useCapabilityStore()
const capabilityRefs = storeToRefs(capabilityStore)
const { getMatchingSpace } = useGetMatchingSpace()
const { dispatchModal } = useModals()
const { canShare } = useCanShare()
const resourcesStore = useResourcesStore()
const { removeResources } = resourcesStore
const { ancestorMetaData } = storeToRefs(resourcesStore)
const spacesStore = useSpacesStore()
const { spaceMembers } = storeToRefs(spacesStore)
const configStore = useConfigStore()
const { options: configOptions } = storeToRefs(configStore)
const sharesStore = useSharesStore()
const { addShare, deleteShare } = sharesStore
const { collaboratorShares } = storeToRefs(sharesStore)
const { user } = storeToRefs(userStore)
const resource = inject<Ref<Resource>>('resource')
const space = inject<Ref<SpaceResource>>('space')
const sharesListCollapsed = ref(!configStore.options.sidebar.shares.showAllOnLoad)
const toggleShareListCollapsed = () => {
sharesListCollapsed.value = !unref(sharesListCollapsed)
}
const memberListCollapsed = ref(!configStore.options.sidebar.shares.showAllOnLoad)
const toggleMemberListCollapsed = () => {
memberListCollapsed.value = !unref(memberListCollapsed)
}
const currentUserIsMemberOfSpace = computed(() => {
return unref(spaceMembers).some((member) => member.sharedWith?.id === unref(user)?.id)
})
const getSharedAncestor = (fileId: string) => {
return Object.values(unref(ancestorMetaData)).find((a) => a.id === fileId)
}
const matchingSpace = computed(() => {
return getMatchingSpace(unref(resource))
})
const collaborators = computed(() => {
const collaboratorsComparator = (c1: CollaboratorShare, c2: CollaboratorShare) => {
// Sorted by: type, direct, display name, creation date
const name1 = c1.sharedWith.displayName.toLowerCase().trim()
const name2 = c2.sharedWith.displayName.toLowerCase().trim()
const c1UserShare = ShareTypes.containsAnyValue(ShareTypes.individuals, [c1.shareType])
const c2UserShare = ShareTypes.containsAnyValue(ShareTypes.individuals, [c2.shareType])
const c1DirectShare = !c1.indirect
const c2DirectShare = !c2.indirect
if (c1UserShare === c2UserShare) {
if (c1DirectShare === c2DirectShare) {
return textUtils.naturalSortCompare(name1, name2)
}
return c1DirectShare ? -1 : 1
}
return c1UserShare ? -1 : 1
}
return unref(collaboratorShares).sort(collaboratorsComparator)
})
return {
addShare,
deleteShare,
user,
resource,
space,
matchingSpace,
sharesListCollapsed,
toggleShareListCollapsed,
memberListCollapsed,
toggleMemberListCollapsed,
currentUserIsMemberOfSpace,
hasShareCanDenyAccess: capabilityRefs.sharingDenyAccess,
getSharedAncestor,
configStore,
configOptions,
dispatchModal,
spaceMembers,
removeResources,
collaborators,
ancestorMetaData,
canShare,
...useMessages()
}
},
computed: {
inviteCollaboratorHelp() {
const cernFeatures = this.configOptions.cernFeatures
if (cernFeatures) {
const options = {
configStore: this.configStore
}
const mergedHelp = shareInviteCollaboratorHelp(options)
mergedHelp.list = [...shareInviteCollaboratorHelpCern(options).list, ...mergedHelp.list]
return mergedHelp
}
return shareInviteCollaboratorHelp({
configStore: this.configStore
})
},
helpersEnabled() {
return this.configOptions.contextHelpers
},
sharedWithLabel() {
return this.$gettext('Shared with')
},
spaceMemberLabel() {
return this.$gettext('Space members')
},
collapseButtonTitle() {
return this.sharesListCollapsed ? this.$gettext('Show more') : this.$gettext('Show less')
},
hasSharees() {
return this.displayCollaborators.length > 0
},
displayCollaborators() {
if (this.collaborators.length > 3 && this.sharesListCollapsed) {
return this.collaborators.slice(0, 3)
}
return this.collaborators
},
displaySpaceMembers() {
if (this.spaceMembers.length > 3 && this.memberListCollapsed) {
return this.spaceMembers.slice(0, 3)
}
return this.spaceMembers
},
showShareToggle() {
return this.collaborators.length > 3
},
showMemberToggle() {
return this.spaceMembers.length > 3
},
noSharePermsMessage() {
const translatedFile = this.$gettext("You don't have permission to share this file.")
const translatedFolder = this.$gettext("You don't have permission to share this folder.")
return this.resource.type === 'file' ? translatedFile : translatedFolder
},
showSpaceMembers() {
return (
this.space?.driveType === 'project' &&
this.resource.type !== 'space' &&
this.currentUserIsMemberOfSpace
)
}
},
methods: {
getDeniedShare(collaborator: CollaboratorShare) {
// FIXME: currently not supported by sharing NG
return undefined
},
isShareDenied(collaborator: CollaboratorShare) {
// FIXME: currently not supported by sharing NG
return false
},
getDeniedSpaceMember(collaborator: CollaboratorShare) {
// FIXME: currently not supported by sharing NG
return undefined
},
isSpaceMemberDenied(collaborator: CollaboratorShare) {
// FIXME: currently not supported by sharing NG
return false
},
isSpaceMemberDeniable(collaborator: CollaboratorShare) {
// FIXME: currently not supported by sharing NG
return false
},
isShareDeniable(collaborator: CollaboratorShare) {
// FIXME: currently not supported by sharing NG
return false
},
async setDenyShare({ value, share }: { value: boolean; share: CollaboratorShare }) {
if (value === true) {
try {
await this.addShare({
clientService: this.$clientService,
space: this.space,
resource: this.resource,
options: {}
})
this.showMessage({
title: this.$gettext('Access was denied successfully')
})
} catch (e) {
console.error(e)
this.showErrorMessage({
title: this.$gettext('Failed to deny access'),
errors: [e]
})
}
} else {
try {
await this.deleteShare({
clientService: this.$clientService,
space: this.space,
resource: this.resource,
collaboratorShare:
share.shareType === ShareTypes.spaceUser.value ||
share.shareType === ShareTypes.spaceGroup.value
? this.getDeniedSpaceMember(share)
: this.getDeniedShare(share),
loadIndicators: false
})
this.showMessage({
title: this.$gettext('Access was granted successfully')
})
} catch (e) {
console.error(e)
this.showErrorMessage({
title: this.$gettext('Failed to grant access'),
errors: [e]
})
}
}
},
deleteShareConfirmation(collaboratorShare: CollaboratorShare) {
this.dispatchModal({
variation: 'danger',
title: this.$gettext('Remove share'),
confirmText: this.$gettext('Remove'),
message: this.$gettext('Are you sure you want to remove this share?'),
hasInput: false,
onConfirm: async () => {
const lastShareId = this.collaborators.length === 1 ? this.collaborators[0].id : undefined
const loadIndicators = this.collaborators.filter((c) => !c.indirect).length === 1
try {
await this.deleteShare({
clientService: this.$clientService,
space: this.space,
resource: this.resource,
collaboratorShare,
loadIndicators
})
this.showMessage({
title: this.$gettext('Share was removed successfully')
})
if (lastShareId && isLocationSharesActive(this.$router, 'files-shares-with-others')) {
this.removeResources([{ id: lastShareId }] as Resource[])
}
} catch (error) {
console.error(error)
this.showErrorMessage({
title: this.$gettext('Failed to remove share'),
errors: [error]
})
}
}
})
},
getSharedParentRoute(collaborator: CollaboratorShare) {
if (!collaborator.indirect) {
return null
}
const sharedAncestor = this.getSharedAncestor(collaborator.resourceId)
if (!sharedAncestor) {
return null
}
return getSharedAncestorRoute({
sharedAncestor,
matchingSpace: this.space || this.matchingSpace
})
},
isShareModifiable(collaborator: CollaboratorShare) {
if (collaborator.indirect) {
return false
}
if (isProjectSpaceResource(this.space) && !this.space.isManager(this.user)) {
return false
}
return true
}
}
})
</script>
<style>
.avatars-wrapper {
height: 40px;
}
</style>
| owncloud/web/packages/web-app-files/src/components/SideBar/Shares/FileShares.vue/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/components/SideBar/Shares/FileShares.vue",
"repo_id": "owncloud",
"token_count": 5889
} | 810 |
import { FolderViewExtension } from '@ownclouders/web-pkg'
import { useGettext } from 'vue3-gettext'
import { ResourceTable, ResourceTiles } from '@ownclouders/web-pkg'
export const useFolderViews = (): FolderViewExtension[] => {
const { $gettext } = useGettext()
return [
{
id: 'com.github.owncloud.web.files.folder-view.resource-table',
type: 'folderView',
scopes: ['resource', 'space', 'favorite'],
folderView: {
name: 'resource-table',
label: $gettext('Switch to default table view'),
icon: {
name: 'menu-line',
fillType: 'none'
},
component: ResourceTable
}
},
{
id: 'com.github.owncloud.web.files.folder-view.resource-table-condensed',
type: 'folderView',
scopes: ['resource'],
folderView: {
name: 'resource-table-condensed',
label: $gettext('Switch to condensed table view'),
icon: {
name: 'menu-line-condensed',
fillType: 'none'
},
component: ResourceTable
}
},
{
id: 'com.github.owncloud.web.files.folder-view.resource-tiles',
type: 'folderView',
scopes: ['resource', 'space', 'favorite'],
folderView: {
name: 'resource-tiles',
label: $gettext('Switch to tiles view'),
icon: {
name: 'apps-2',
fillType: 'line'
},
component: ResourceTiles
}
}
]
}
| owncloud/web/packages/web-app-files/src/composables/extensions/useFolderViews.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/composables/extensions/useFolderViews.ts",
"repo_id": "owncloud",
"token_count": 659
} | 811 |
export * as fileList from './filesList'
| owncloud/web/packages/web-app-files/src/helpers/ui/index.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/helpers/ui/index.ts",
"repo_id": "owncloud",
"token_count": 12
} | 812 |
export interface FolderLoaderOptions {
loadShares?: boolean
}
| owncloud/web/packages/web-app-files/src/services/folder/types.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/services/folder/types.ts",
"repo_id": "owncloud",
"token_count": 15
} | 813 |
import { useScrollTo } from '@ownclouders/web-pkg'
export const useScrollToMock = (
options: Partial<ReturnType<typeof useScrollTo>> = {}
): ReturnType<typeof useScrollTo> => {
return {
scrollToResource: vi.fn(),
scrollToResourceFromRoute: vi.fn(),
...options
}
}
| owncloud/web/packages/web-app-files/tests/mocks/useScrollToMock.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/mocks/useScrollToMock.ts",
"repo_id": "owncloud",
"token_count": 100
} | 814 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`ResourceDetails component > renders resource details correctly 1`] = `
"<div class="resource-details oc-flex oc-flex-column oc-flex-middle">
<div class="oc-width-1-3@l oc-width-1-2@m oc-width-3-4">
<div class="file_info oc-flex oc-flex-between oc-p-s">
<div class="oc-flex oc-flex-middle"><span class="oc-icon oc-icon-l oc-icon-passive oc-resource-icon oc-resource-icon-folder file_info__icon oc-mr-s oc-position-relative"><!----></span>
<div class="file_info__body oc-text-overflow">
<h3 data-testid="files-info-name" class="oc-font-semibold"><span class="oc-resource-name oc-display-inline-block" data-test-resource-name="image.jpg" title="image.jpg"><span class="oc-resource-basename oc-text-break">image.jpg</span>
<!--v-if--></span>
</h3>
</div>
</div>
</div>
<div data-v-5080a6a4="" id="oc-file-details-sidebar" class="oc-mb">
<div data-v-5080a6a4="">
<div data-v-5080a6a4="" class="details-icon-wrapper oc-width-1-1 oc-flex oc-flex-middle oc-flex-center oc-mb"><span data-v-5080a6a4="" class="oc-icon oc-icon-xxxl oc-icon-passive oc-resource-icon oc-resource-icon-folder details-icon"><!----></span></div>
<!--v-if-->
<table data-v-5080a6a4="" class="details-table oc-width-1-1" aria-label="Overview of the information about the selected file">
<col data-v-5080a6a4="" class="oc-width-1-3">
<col data-v-5080a6a4="" class="oc-width-2-3">
<!--v-if-->
<tr data-v-5080a6a4="" data-testid="timestamp">
<th data-v-5080a6a4="" scope="col" class="oc-pr-s oc-font-semibold">Last modified</th>
<td data-v-5080a6a4=""><span data-v-5080a6a4="">Oct 21, 2015, 7:28 AM</span></td>
</tr>
<!--v-if-->
<!--v-if-->
<!--v-if-->
<tr data-v-5080a6a4="" data-testid="ownerDisplayName">
<th data-v-5080a6a4="" scope="col" class="oc-pr-s oc-font-semibold">Owner</th>
<td data-v-5080a6a4="">
<p data-v-5080a6a4="" class="oc-m-rm">admin <span data-v-5080a6a4="" data-msgid="(me)" data-current-language="en">(me)</span></p>
</td>
</tr>
<tr data-v-5080a6a4="" data-testid="sizeInfo">
<th data-v-5080a6a4="" scope="col" class="oc-pr-s oc-font-semibold">Size</th>
<td data-v-5080a6a4="">24 kB</td>
</tr>
<!--v-if-->
<!--v-if-->
<portal-target data-v-5080a6a4="" name="app.files.sidebar.file.details.table" slot-props="[object Object]" multiple="true"></portal-target>
<!--v-if-->
</table>
</div>
</div>
<ul class="oc-list oc-my-rm oc-mx-rm oc-mt-s" id="oc-files-actions-sidebar"></ul>
</div>
</div>"
`;
| owncloud/web/packages/web-app-files/tests/unit/components/FilesList/__snapshots__/ResourceDetails.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/components/FilesList/__snapshots__/ResourceDetails.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 1403
} | 815 |
import FileShares from 'web-app-files/src/components/SideBar/Shares/FileShares.vue'
import { mock } from 'vitest-mock-extended'
import { Resource } from '@ownclouders/web-client'
import { SpaceResource } from '@ownclouders/web-client/src/helpers'
import { v4 as uuidV4 } from 'uuid'
import { CollaboratorShare, ShareRole, ShareTypes } from '@ownclouders/web-client/src/helpers/share'
import {
defaultPlugins,
mount,
shallowMount,
defaultComponentMocks,
defaultStubs
} from 'web-test-helpers'
import CollaboratorListItem from '../../../../../src/components/SideBar/Shares/Collaborators/ListItem.vue'
import { CapabilityStore, useCanShare, useModals } from '@ownclouders/web-pkg'
import { User } from '@ownclouders/web-client/src/generated'
vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({
...(await importOriginal<any>()),
useCanShare: vi.fn()
}))
const getCollaborator = (): CollaboratorShare => ({
id: uuidV4(),
sharedWith: {
id: 'einstein',
displayName: 'Albert Einstein'
},
sharedBy: {
id: 'admin',
displayName: 'Admin'
},
permissions: [],
role: mock<ShareRole>(),
resourceId: uuidV4(),
indirect: false,
shareType: ShareTypes.user.value
})
describe('FileShares', () => {
describe('invite collaborator form', () => {
it('renders the form when the resource can be shared', () => {
const resource = mock<Resource>({ isReceivedShare: () => false, canShare: () => true })
const { wrapper } = getWrapper({ resource, canShare: true })
expect(wrapper.find('invite-collaborator-form-stub').exists()).toBeTruthy()
})
it('does not render the form when the resource can not be shared', () => {
const resource = mock<Resource>({ isReceivedShare: () => false, canShare: () => false })
const { wrapper } = getWrapper({ resource, canShare: false })
expect(wrapper.find('invite-collaborator-form-stub').exists()).toBeFalsy()
})
it('does render the form when the resource is a received share and re-sharing is enabled', () => {
const resource = mock<Resource>({ isReceivedShare: () => true, canShare: () => true })
const { wrapper } = getWrapper({ resource })
expect(wrapper.find('invite-collaborator-form-stub').exists()).toBeTruthy()
})
})
describe('collaborators list', () => {
let collaborators
beforeEach(() => {
collaborators = [getCollaborator(), getCollaborator(), getCollaborator(), getCollaborator()]
})
it('renders sharedWithLabel and sharee list', () => {
const { wrapper } = getWrapper({ collaborators })
expect(wrapper.find('#files-collaborators-list').exists()).toBeTruthy()
expect(wrapper.findAll('#files-collaborators-list li').length).toBe(collaborators.length)
expect(wrapper.html()).toMatchSnapshot()
})
it('reacts on delete events', async () => {
const { wrapper } = getWrapper({ collaborators })
const { dispatchModal } = useModals()
wrapper
.findComponent<typeof CollaboratorListItem>('collaborator-list-item-stub')
.vm.$emit('onDelete')
await wrapper.vm.$nextTick()
expect(dispatchModal).toHaveBeenCalledTimes(1)
})
it('correctly passes the shared parent route to the collaborator list item for indirect shares', () => {
const indirectCollaborator = { ...getCollaborator(), indirect: true }
const ancestorMetaData = {
'/somePath': { id: indirectCollaborator.resourceId }
}
const { wrapper } = getWrapper({ collaborators: [indirectCollaborator], ancestorMetaData })
const listItemStub = wrapper.findComponent<typeof CollaboratorListItem>(
'collaborator-list-item-stub'
)
expect(listItemStub.props('sharedParentRoute')).toBeTruthy()
expect(listItemStub.props('modifiable')).toBeFalsy()
})
it('toggles the share list', async () => {
const showAllOnLoad = true
const { wrapper } = getWrapper({ mountType: mount, collaborators })
expect(wrapper.vm.sharesListCollapsed).toBe(!showAllOnLoad)
await wrapper.find('.toggle-shares-list-btn').trigger('click')
expect(wrapper.vm.sharesListCollapsed).toBe(showAllOnLoad)
})
it('share should be modifiable if its personal space share', () => {
const space = mock<SpaceResource>({ driveType: 'personal' })
const { wrapper } = getWrapper({ space, mountType: shallowMount, collaborators })
expect(wrapper.vm.isShareModifiable(collaborators[0])).toBe(true)
})
it('share should not be modifiable if its not personal space share', () => {
const space = mock<SpaceResource>({ driveType: 'project' })
const { wrapper } = getWrapper({ space, mountType: shallowMount, collaborators })
expect(wrapper.vm.isShareModifiable(collaborators[0])).toBe(false)
})
it('share should not be modifiable if collaborator is indirect', () => {
const space = mock<SpaceResource>({ driveType: 'personal' })
const { wrapper } = getWrapper({ space, mountType: shallowMount, collaborators })
collaborators[0]['indirect'] = true
expect(wrapper.vm.isShareModifiable(collaborators[0])).toBe(false)
})
it('share should not be modifiable if user is not manager', () => {
const space = mock<SpaceResource>({ driveType: 'project' })
;(space as any).isManager = vi.fn(() => false)
collaborators[0]['indirect'] = true
const { wrapper } = getWrapper({ space, mountType: shallowMount, collaborators })
expect(wrapper.vm.isShareModifiable(collaborators[0])).toBe(false)
})
})
describe('current space', () => {
it('loads space members if a space is given and the current user is member', () => {
const user = { id: '1' } as User
const space = mock<SpaceResource>({ driveType: 'project' })
const spaceMembers = [
{ sharedWith: { id: user.id } },
{ sharedWith: { id: '2' } }
] as CollaboratorShare[]
const collaborator = getCollaborator()
collaborator.sharedWith = {
...collaborator.sharedWith,
id: user.id
}
const { wrapper } = getWrapper({ space, collaborators: [collaborator], user, spaceMembers })
expect(wrapper.find('#files-collaborators-list').exists()).toBeTruthy()
expect(wrapper.findAll('#files-collaborators-list li').length).toBe(1)
expect(wrapper.html()).toMatchSnapshot()
})
it('does not load space members if a space is given but the current user not a member', () => {
const user = { id: '1' } as User
const space = mock<SpaceResource>({ driveType: 'project' })
const spaceMembers = [{ collaborator: { name: `${user}-2` } }]
const collaborator = getCollaborator()
collaborator.sharedWith = {
...collaborator.sharedWith,
id: user.id
}
const { wrapper } = getWrapper({ space, collaborators: [collaborator], user, spaceMembers })
expect(wrapper.find('#space-collaborators-list').exists()).toBeFalsy()
})
})
describe('"deleteShareConfirmation" method', () => {
it('dispatches a modal', () => {
const { wrapper } = getWrapper()
const { dispatchModal } = useModals()
wrapper.vm.deleteShareConfirmation(mock<CollaboratorShare>())
expect(dispatchModal).toHaveBeenCalled()
})
})
})
function getWrapper({
mountType = shallowMount,
resource = mock<Resource>({ isReceivedShare: () => false, canShare: () => true }),
space = mock<SpaceResource>(),
collaborators = [],
spaceMembers = [],
user = undefined,
showAllOnLoad = true,
ancestorMetaData = {},
canShare = true
} = {}) {
vi.mocked(useCanShare).mockReturnValue({ canShare: () => canShare })
const capabilities = {
files_sharing: { deny_access: false }
} satisfies Partial<CapabilityStore['capabilities']>
return {
wrapper: mountType(FileShares, {
global: {
plugins: [
...defaultPlugins({
piniaOptions: {
userState: { user },
spacesState: { spaceMembers },
capabilityState: { capabilities },
configState: {
options: { contextHelpers: true, sidebar: { shares: { showAllOnLoad } } }
},
sharesState: { collaboratorShares: collaborators },
resourcesStore: { ancestorMetaData }
}
})
],
mocks: defaultComponentMocks(),
provide: { resource, space },
stubs: {
...defaultStubs,
OcButton: false,
'invite-collaborator-form': true,
'collaborator-list-item': true
}
}
})
}
}
| owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/FileShares.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/FileShares.spec.ts",
"repo_id": "owncloud",
"token_count": 3177
} | 816 |
import { accentuateItem } from '../../../../src/helpers/ui/filesList'
describe('accentuateItem', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('highlights given data-item-id', () => {
document.body.innerHTML =
'<table><tbody><tr data-item-id="1"><td>1</td></tr><tr data-item-id="2"><td>2</td></tr></tbody></table>'
const trs = document.getElementsByTagName('tr')
accentuateItem('1', 50)
expect(trs[0].classList.contains('oc-table-accentuated')).toBe(true)
expect(trs[1].classList.contains('oc-table-accentuated')).toBe(false)
vi.advanceTimersByTime(100)
expect(trs[0].classList.contains('oc-table-accentuated')).toBe(false)
expect(trs[1].classList.contains('oc-table-accentuated')).toBe(false)
accentuateItem('2', 50)
expect(trs[0].classList.contains('oc-table-accentuated')).toBe(false)
expect(trs[1].classList.contains('oc-table-accentuated')).toBe(true)
// do not fail in setTimeout if element went away
trs[1].remove()
vi.advanceTimersByTime(100)
})
})
| owncloud/web/packages/web-app-files/tests/unit/helpers/ui/filesList.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/helpers/ui/filesList.spec.ts",
"repo_id": "owncloud",
"token_count": 450
} | 817 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`TrashOverview > view states > should render spaces list 1`] = `
"<div class="oc-flex">
<div data-v-39c970be="" class="files-view-wrapper oc-width-expand">
<div data-v-39c970be="" id="files-view">
<app-bar-stub viewmodedefault="resource-table" breadcrumbs="[object Object]" breadcrumbscontextactionsitems="" viewmodes="" hasbulkactions="false" hasviewoptions="false" hashiddenfiles="false" hasfileextensions="false" haspagination="false" showactionsonselection="false" issidebaropen="false"></app-bar-stub>
<div class="trash-bin-filters oc-flex oc-flex-right oc-flex-wrap oc-flex-bottom oc-mx-m oc-mb-m">
<div class=""><label class="oc-label" for="spaces-filter">Search</label>
<div class="oc-position-relative">
<!--v-if--> <input id="spaces-filter" autocomplete="off" aria-invalid="false" class="oc-text-input oc-input oc-rounded" type="text">
<!--v-if-->
</div>
<!--v-if-->
<!--v-if-->
</div>
</div>
<table class="oc-table oc-table-hover oc-table-sticky has-item-context-menu spaces-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-icon oc-pl-s" 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-name oc-pr-s" style="top: 0px;" aria-sort="ascending"><span class="oc-table-thead-content header-text">Name</span> <button type="button" aria-label="Sort by name" 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-button-sort">
<!--v-if-->
<!-- @slot Content of the button --> <span class="oc-icon oc-icon-s oc-icon-passive"><!----></span>
</button></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-icon oc-pl-s"><span class="oc-icon oc-icon-m oc-icon-passive oc-pl-m"><!----></span></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-name oc-pr-s">
<router-link-stub to="[object Object]" 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-display-block"></router-link-stub>
</td>
</tr>
<tr tabindex="-1" class="oc-tbody-tr oc-tbody-tr-2" data-item-id="2" 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-icon oc-pl-s"><span class="oc-icon oc-icon-m oc-icon-passive oc-pl-m"><!----></span></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-name oc-pr-s">
<router-link-stub to="[object Object]" 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-display-block"></router-link-stub>
</td>
</tr>
<tr tabindex="-1" class="oc-tbody-tr oc-tbody-tr-3" data-item-id="3" 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-icon oc-pl-s"><span class="oc-icon oc-icon-m oc-icon-passive oc-pl-m"><!----></span></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-name oc-pr-s">
<router-link-stub to="[object Object]" 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-display-block"></router-link-stub>
</td>
</tr>
</tbody>
<tfoot class="oc-table-footer">
<tr class="oc-table-footer-row">
<td colspan="2" class="oc-table-footer-cell">
<!-- @slot Footer of the table -->
<div class="oc-text-nowrap oc-text-center oc-width-1-1 oc-my-s">
<p class="oc-text-muted">3 trashes in total</p>
<!--v-if-->
</div>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
<!--v-if-->
<file-side-bar-stub isopen="false"></file-side-bar-stub>
</div>"
`;
| owncloud/web/packages/web-app-files/tests/unit/views/trash/__snapshots__/Overview.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/views/trash/__snapshots__/Overview.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 2423
} | 818 |
<template>
<div id="incoming" class="sciencemesh-app">
<div>
<div class="oc-flex oc-flex-middle oc-px-m oc-py-s">
<oc-icon name="user-received" />
<h2 class="oc-px-s" v-text="$gettext('Accept invitations')" />
<oc-contextual-helper class="oc-pl-xs" v-bind="helperContent" />
</div>
<br />
<br />
<div class="oc-flex oc-flex-column oc-flex-middle oc-flex-center">
<div class="oc-width-1-2">
<oc-text-input
ref="tokenInput"
v-model="token"
:label="$gettext('Enter invite token')"
:clear-button-enabled="true"
/>
<br />
<oc-select
v-model="provider"
:label="$gettext('Select institution of inviter')"
:options="providers"
class="oc-mb-m"
:loading="loading"
>
<template #option="{ full_name, domain }">
<span class="option">
<strong v-text="full_name" />
</span>
<span class="option" v-text="domain" />
</template>
<template #no-options> No institutions found with this name </template>
<template #selected-option="{ full_name, domain }">
<strong class="oc-mr-s" v-text="full_name" />
<small
v-oc-tooltip="domain"
v-text="domain.length > 17 ? domain.slice(0, 20) + '...' : domain"
/>
</template>
</oc-select>
<div v-if="providerError" class="oc-text-input-message">
<span
class="oc-text-input-danger"
v-text="$gettext('Unknown institution. Check invitation url or select from list')"
/>
</div>
</div>
<br />
<br />
<oc-button size="small" :disabled="acceptInvitationButtonDisabled" @click="acceptInvite">
<oc-icon name="add" />
<span v-text="$gettext('Accept invitation')" />
</oc-button>
</div>
</div>
</div>
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, ref, unref } from 'vue'
import {
queryItemAsString,
useClientService,
useRoute,
useRouter,
useMessages,
useConfigStore
} from '@ownclouders/web-pkg'
import { $gettext } from '@ownclouders/web-pkg/src/router/utils'
import { useGettext } from 'vue3-gettext'
import { onBeforeRouteUpdate, RouteLocationNormalized } from 'vue-router'
import { providerListSchema } from '../schemas'
import { OcTextInput } from '@ownclouders/design-system/src/components'
export default defineComponent({
emits: ['highlightNewConnections'],
setup(props, { emit }) {
const { showErrorMessage } = useMessages()
const router = useRouter()
const clientService = useClientService()
const configStore = useConfigStore()
const { $gettext } = useGettext()
const token = ref(undefined)
const provider = ref(undefined)
const providers = ref([])
const loading = ref(true)
const providerError = ref(false)
const tokenInput = ref<InstanceType<typeof OcTextInput>>()
const helperContent = computed(() => {
return {
text: $gettext(
'Once you accept the invitation, the inviter will be added to your connections.'
)
}
})
const acceptInvitationButtonDisabled = computed(() => {
return !unref(token) || !unref(provider) || unref(provider).full_name === 'Unknown provider'
})
const errorPopup = (error: Error) => {
console.error(error)
showErrorMessage({
title: $gettext('Error'),
desc: $gettext('An error occurred'),
errors: [error]
})
}
const acceptInvite = async () => {
try {
await clientService.httpAuthenticated.post('/sciencemesh/accept-invite', {
token: unref(token),
providerDomain: unref(provider).domain
})
token.value = undefined
provider.value = undefined
const { token: currentToken, providerDomain, ...query } = unref(route).query
router.replace({
name: 'ocm-app-invitations',
query
})
emit('highlightNewConnections')
} catch (error) {
errorPopup(error)
}
}
const listProviders = async () => {
try {
const { data: allProviders } = await clientService.httpAuthenticated.get(
'/sciencemesh/list-providers',
{
schema: providerListSchema
}
)
providers.value = allProviders.filter((p) => !isMyProviderSelectedProvider(p))
} catch (error) {
errorPopup(error)
} finally {
loading.value = false
}
}
const scrollToForm = () => {
const el = document.getElementById('sciencemesh-accept-invites')
if (el) {
el.scrollIntoView()
}
}
const isMyProviderSelectedProvider = (p) => {
return p.domain === new URL(configStore.serverUrl).hostname
}
const handleParams = (to: RouteLocationNormalized) => {
const tokenQuery = to.query.token
if (tokenQuery) {
token.value = queryItemAsString(tokenQuery)
unref(tokenInput).focus()
scrollToForm()
}
const providerDomainQuery = to.query.providerDomain
if (providerDomainQuery) {
let matchedProvider = unref(providers)?.find(
(p) => p.domain === queryItemAsString(providerDomainQuery)
)
if (matchedProvider) {
provider.value = matchedProvider
providerError.value = false
} else {
provider.value = {
full_name: 'Unknown provider',
domain: queryItemAsString(providerDomainQuery)
}
providerError.value = true
}
}
}
const route = useRoute()
onMounted(async () => {
await listProviders()
handleParams(unref(route))
})
onBeforeRouteUpdate((to, from) => {
handleParams(to)
})
return {
tokenInput,
helperContent,
token,
provider,
providers,
loading,
providerError,
acceptInvitationButtonDisabled,
acceptInvite
}
},
methods: { $gettext }
})
</script>
<style lang="scss" scoped>
.option {
display: block;
}
</style>
| owncloud/web/packages/web-app-ocm/src/views/IncomingInvitations.vue/0 | {
"file_path": "owncloud/web/packages/web-app-ocm/src/views/IncomingInvitations.vue",
"repo_id": "owncloud",
"token_count": 2845
} | 819 |
import { defineWebApplication } from '@ownclouders/web-pkg'
import translations from '../l10n/translations.json'
import * as app from './App.vue'
import { useGettext } from 'vue3-gettext'
import { getMimeTypes } from './mimeTypes'
const { default: App, appId } = app
export default defineWebApplication({
setup({ applicationConfig }) {
const { $gettext } = useGettext()
const routes = [
{
path: '/:driveAliasAndItem(.*)?',
component: App,
name: 'media',
meta: {
authContext: 'hybrid',
title: $gettext('Preview'),
patchCleanPath: true
}
}
]
const routeName = 'preview-media'
const appInfo = {
name: $gettext('Preview'),
id: appId,
icon: 'eye',
extensions: getMimeTypes(applicationConfig?.mimeTypes).map((mimeType) => ({
mimeType,
routeName,
label: $gettext('Preview')
}))
}
return {
appInfo,
routes,
translations
}
}
})
| owncloud/web/packages/web-app-preview/src/index.ts/0 | {
"file_path": "owncloud/web/packages/web-app-preview/src/index.ts",
"repo_id": "owncloud",
"token_count": 443
} | 820 |
{
"name": "@ownclouders/web-client",
"version": "0.0.1",
"description": "ownCloud web client",
"license": "AGPL-3.0",
"main": "src/index.ts",
"private": false,
"author": "ownCloud GmbH <devops@owncloud.com>",
"homepage": "https://github.com/owncloud/web/tree/master/packages/web-client",
"repository": {
"type": "git",
"url": "https://github.com/owncloud/web",
"directory": "packages/web-client"
},
"scripts": {
"generate-openapi": "rm -rf src/generated && docker run --rm -v \"${PWD}/src:/local\" openapitools/openapi-generator-cli generate -i https://raw.githubusercontent.com/owncloud/libre-graph-api/main/api/openapi-spec/v1.0.yaml -g typescript-axios -o /local/generated"
},
"peerDependencies": {
"@ownclouders/web-client": "workspace:*",
"@casl/ability": "^6.3.3",
"axios": "1.6.5",
"fast-xml-parser": "4.3.3",
"lodash-es": "^4.17.21",
"luxon": "3.2.1",
"@microsoft/fetch-event-source": "^2.0.1",
"webdav": "5.3.1",
"xml-js": "^1.6.11",
"zod": "3.22.4"
}
}
| owncloud/web/packages/web-client/package.json/0 | {
"file_path": "owncloud/web/packages/web-client/package.json",
"repo_id": "owncloud",
"token_count": 472
} | 821 |
export interface Item {
// FIXME: ideally the id should not be optional, but the generated interfaces for User and Group currently need this.
id?: string
}
| owncloud/web/packages/web-client/src/helpers/item.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/helpers/item.ts",
"repo_id": "owncloud",
"token_count": 38
} | 822 |
export * from './types'
| owncloud/web/packages/web-client/src/helpers/user/index.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/helpers/user/index.ts",
"repo_id": "owncloud",
"token_count": 8
} | 823 |
export * from './dav'
| owncloud/web/packages/web-client/src/webdav/constants/index.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/webdav/constants/index.ts",
"repo_id": "owncloud",
"token_count": 9
} | 824 |
import { isPublicSpaceResource, SpaceResource } from '../helpers'
import { WebDavOptions } from './types'
import { urlJoin } from '../utils'
import { buildAuthHeader, DAV } from './client'
import { unref } from 'vue'
export const RestoreFileFactory = (dav: DAV, { accessToken }: WebDavOptions) => {
return {
restoreFile(
space: SpaceResource,
{ id }: { id: string | number },
{ path: restorePath }: { path: string },
{ overwrite }: { overwrite?: boolean }
) {
if (isPublicSpaceResource(space)) {
return
}
const restoreWebDavPath = urlJoin(space.webDavPath, restorePath)
const headers = buildAuthHeader(unref(accessToken))
return dav.move(urlJoin(space.webDavTrashPath, id), restoreWebDavPath, { overwrite, headers })
}
}
}
| owncloud/web/packages/web-client/src/webdav/restoreFile.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/webdav/restoreFile.ts",
"repo_id": "owncloud",
"token_count": 294
} | 825 |
{
"name": "@ownclouders/web-pkg",
"version": "0.0.3",
"description": "ownCloud web pkg",
"license": "AGPL-3.0",
"main": "src/index.ts",
"types": "types.d.ts",
"private": false,
"author": "ownCloud GmbH <devops@owncloud.com>",
"homepage": "https://github.com/owncloud/web/tree/master/packages/web-pkg",
"repository": {
"type": "git",
"url": "https://github.com/owncloud/web",
"directory": "packages/web-pkg"
},
"devDependencies": {
"web-test-helpers": "workspace:*",
"zod": "^3.22.4",
"@toast-ui/editor": "^3.2.2",
"@toast-ui/editor-plugin-code-syntax-highlight": "^3.1.0",
"prismjs": "^1.29.0"
},
"peerDependencies": {
"@casl/ability": "^6.3.3",
"@casl/vue": "^2.2.1",
"@microsoft/fetch-event-source": "^2.0.1",
"@ownclouders/web-client": "workspace:*",
"@sentry/vue": "7.101.0",
"@uppy/core": "3.3.0",
"@uppy/drop-target": "^2.0.0",
"@uppy/tus": "^3.1.0",
"@uppy/utils": "^5.3.0",
"@uppy/xhr-upload": "^3.0.1",
"@vueuse/core": "^10.0.0",
"axios": "1.6.5",
"deepmerge": "^4.2.2",
"design-system": "workspace:@ownclouders/design-system@*",
"dompurify": "^3.0.6",
"filesize": "^10.1.0",
"fuse.js": "6.6.2",
"js-generate-password": "^0.1.9",
"lodash-es": "^4.17.21",
"luxon": "3.2.1",
"mark.js": "^8.11.1",
"p-queue": "^6.6.2",
"password-sheriff": "^1.1.1",
"pinia": "2.1.7",
"qs": "6.11.2",
"semver": "7.5.4",
"uuid": "9.0.1",
"vue-concurrency": "5.0.0",
"vue-router": "4.2.5",
"vue3-gettext": "2.4.0",
"vitest": "1.2.1"
}
}
| owncloud/web/packages/web-pkg/package.json/0 | {
"file_path": "owncloud/web/packages/web-pkg/package.json",
"repo_id": "owncloud",
"token_count": 868
} | 826 |
<template>
<div class="oc-text-center oc-flex oc-flex-center oc-flex-middle oc-height-1-1">
<oc-spinner size="xlarge" />
<p v-translate class="oc-invisible">Loading app</p>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: 'LoadingScreen'
})
</script>
| owncloud/web/packages/web-pkg/src/components/AppTemplates/PartialViews/LoadingScreen.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/AppTemplates/PartialViews/LoadingScreen.vue",
"repo_id": "owncloud",
"token_count": 126
} | 827 |
<template>
<span
v-oc-tooltip="tooltip"
class="oc-resource-name"
:class="[{ 'oc-display-inline-block': !truncateName }]"
:data-test-resource-path="fullPath"
:data-test-resource-name="fullName"
:data-test-resource-type="type"
:title="htmlTitle"
>
<span v-if="truncateName" class="oc-text-truncate">
<span class="oc-resource-basename" v-text="displayName" />
</span>
<span v-else class="oc-resource-basename oc-text-break" v-text="displayName" /><span
v-if="extension && isExtensionDisplayed"
class="oc-resource-extension"
v-text="displayExtension"
/>
</span>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import path from 'path'
export default defineComponent({
name: 'ResourceName',
props: {
/**
* The name of the resource
*/
name: {
type: String,
required: true
},
/**
* The prefix that will be shown in the path
*/
pathPrefix: {
type: String,
required: false,
default: ''
},
/**
* The extension of the resource, if there is one
*/
extension: {
type: String,
required: false,
default: ''
},
/**
* The type of the resource
*/
type: {
type: String,
required: true
},
/**
* A full path of the resource
*/
fullPath: {
type: String,
required: true
},
/**
* Asserts whether the resource path should be displayed
*/
isPathDisplayed: {
type: Boolean,
required: false,
default: false
},
/**
* Asserts whether the resource extension should be displayed
*/
isExtensionDisplayed: {
type: Boolean,
required: false,
default: true
},
/**
* Asserts whether the resource name should be truncated if it's too long
*/
truncateName: {
type: Boolean,
required: false,
default: true
}
},
computed: {
tooltip() {
return this.pathTooltip
},
fullName() {
return (this.displayPath || '') + this.name
},
displayName() {
if (this.extension) {
return this.name.slice(0, -this.extension.length - 1)
}
return this.name
},
displayExtension() {
return this.extension ? '.' + this.extension : ''
},
displayPath() {
if (!this.isPathDisplayed) {
return null
}
const pathSplit = this.fullPath.replace(/^\//, '').split('/')
if (pathSplit.length < 2) {
return null
}
if (pathSplit.length === 2) {
return pathSplit[0] + '/'
}
return `…/${pathSplit[pathSplit.length - 2]}/`
},
pathTooltip() {
if (!this.isPathDisplayed) {
return null
}
if (this.displayPath === this.fullPath) {
return null
}
if (this.pathPrefix) {
return path.join(this.pathPrefix, this.fullPath)
}
return this.fullPath
},
htmlTitle() {
if (this.tooltip) {
return
}
if (this.isExtensionDisplayed) {
return `${this.displayName}${this.displayExtension}`
}
return this.displayName
}
}
})
</script>
<style lang="scss">
.oc-resource {
&-name {
display: flex;
min-width: 0;
&:hover {
text-decoration: underline;
text-decoration-color: var(--oc-color-text-default);
}
}
&-basename,
&-extension {
color: var(--oc-color-text-default);
white-space: pre;
}
&-path {
color: var(--oc-color-text-muted);
white-space: pre;
}
}
</style>
| owncloud/web/packages/web-pkg/src/components/FilesList/ResourceName.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/FilesList/ResourceName.vue",
"repo_id": "owncloud",
"token_count": 1606
} | 828 |
export { default as ResourceConflictModal } from './ResourceConflictModal.vue'
export { default as SpaceMoveInfoModal } from './SpaceMoveInfoModal.vue'
export { default as EmojiPickerModal } from './EmojiPickerModal.vue'
| owncloud/web/packages/web-pkg/src/components/Modals/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/Modals/index.ts",
"repo_id": "owncloud",
"token_count": 72
} | 829 |
export { default as SpaceDetails } from './SpaceDetails.vue'
export { default as SpaceDetailsMultiple } from './SpaceDetailsMultiple.vue'
| owncloud/web/packages/web-pkg/src/components/SideBar/Spaces/Details/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/SideBar/Spaces/Details/index.ts",
"repo_id": "owncloud",
"token_count": 36
} | 830 |
import kebabCase from 'lodash-es/kebabCase'
import { isIncomingShareResource } from '@ownclouders/web-client/src/helpers/share'
import { routeToContextQuery } from '../../appDefaults'
import { isLocationTrashActive } from '../../../router'
import { computed, unref } from 'vue'
import { useRouter } from '../../router'
import { useGettext } from 'vue3-gettext'
import {
Action,
FileAction,
FileActionOptions,
useFileActionsOpenShortcut,
useIsSearchActive,
useWindowOpen
} from '../../actions'
import {
useFileActionsEnableSync,
useFileActionsToggleHideShare,
useFileActionsCopy,
useFileActionsDisableSync,
useFileActionsDelete,
useFileActionsDownloadArchive,
useFileActionsDownloadFile,
useFileActionsFavorite,
useFileActionsMove,
useFileActionsNavigate,
useFileActionsRename,
useFileActionsRestore,
useFileActionsCreateSpaceFromResource
} from './index'
import { useAppsStore, useConfigStore, useResourcesStore } from '../../piniaStores'
import { ApplicationFileExtension } from '../../../apps'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { storeToRefs } from 'pinia'
export const EDITOR_MODE_EDIT = 'edit'
export const EDITOR_MODE_CREATE = 'create'
export interface GetFileActionsOptions extends FileActionOptions {
omitSystemActions?: boolean
}
export const useFileActions = () => {
const appsStore = useAppsStore()
const configStore = useConfigStore()
const router = useRouter()
const { $gettext } = useGettext()
const isSearchActive = useIsSearchActive()
const { openUrl } = useWindowOpen()
const resourcesStore = useResourcesStore()
const { currentFolder } = storeToRefs(resourcesStore)
const { actions: enableSyncActions } = useFileActionsEnableSync()
const { actions: hideShareActions } = useFileActionsToggleHideShare()
const { actions: copyActions } = useFileActionsCopy()
const { actions: deleteActions } = useFileActionsDelete()
const { actions: disableSyncActions } = useFileActionsDisableSync()
const { actions: downloadArchiveActions } = useFileActionsDownloadArchive()
const { actions: downloadFileActions } = useFileActionsDownloadFile()
const { actions: favoriteActions } = useFileActionsFavorite()
const { actions: moveActions } = useFileActionsMove()
const { actions: navigateActions } = useFileActionsNavigate()
const { actions: renameActions } = useFileActionsRename()
const { actions: restoreActions } = useFileActionsRestore()
const { actions: createSpaceFromResource } = useFileActionsCreateSpaceFromResource()
const { actions: openShortcutActions } = useFileActionsOpenShortcut()
const systemActions = computed((): Action[] => [
...unref(openShortcutActions),
...unref(downloadArchiveActions),
...unref(downloadFileActions),
...unref(deleteActions),
...unref(moveActions),
...unref(copyActions),
...unref(renameActions),
...unref(createSpaceFromResource),
...unref(restoreActions),
...unref(enableSyncActions),
...unref(hideShareActions),
...unref(disableSyncActions),
...unref(favoriteActions),
...unref(navigateActions)
])
const editorActions = computed(() => {
return appsStore.fileExtensions
.map((fileExtension): FileAction => {
const appInfo = appsStore.apps[fileExtension.app]
return {
name: `editor-${fileExtension.app}`,
label: () => {
if (fileExtension.label) {
return $gettext(fileExtension.label)
}
return $gettext('Open in %{app}', { app: appInfo.name }, true)
},
icon: fileExtension.icon || appInfo.icon,
...(appInfo.iconFillType && {
iconFillType: appInfo.iconFillType
}),
img: appInfo.img,
handler: (options) =>
openEditor(
fileExtension,
options.space,
options.resources[0],
EDITOR_MODE_EDIT,
options.space.shareId
),
isVisible: ({ resources }) => {
if (resources.length !== 1) {
return false
}
if (
!unref(isSearchActive) &&
(isLocationTrashActive(router, 'files-trash-generic') ||
(isIncomingShareResource(resources[0]) && !resources[0].syncEnabled))
) {
return false
}
if (resources[0].extension && fileExtension.extension) {
return resources[0].extension.toLowerCase() === fileExtension.extension.toLowerCase()
}
if (resources[0].mimeType && fileExtension.mimeType) {
return (
resources[0].mimeType.toLowerCase() === fileExtension.mimeType.toLowerCase() ||
resources[0].mimeType.split('/')[0].toLowerCase() ===
fileExtension.mimeType.toLowerCase()
)
}
return false
},
hasPriority: fileExtension.hasPriority,
componentType: 'button',
class: `oc-files-actions-${kebabCase(appInfo.name).toLowerCase()}-trigger`
}
})
.sort((first, second) => {
// Ensure default are listed first
if (second.hasPriority !== first.hasPriority && second.hasPriority) {
return 1
}
return 0
})
})
const routeOptsHelper = (
appFileExtension: ApplicationFileExtension,
space: SpaceResource,
resource: Resource,
mode: string,
shareId: string
) => {
return {
name: appFileExtension.routeName || appFileExtension.app,
params: {
driveAliasAndItem: space.getDriveAliasAndItem(resource),
filePath: resource.path,
fileId: resource.fileId,
mode
},
query: {
...(shareId && { shareId }),
...(resource.fileId && configStore.options.routing.idBased && { fileId: resource.fileId }),
...(appFileExtension.app === 'external' && { app: appFileExtension.name }),
...routeToContextQuery(unref(router.currentRoute))
}
}
}
const openEditor = (
appFileExtension: ApplicationFileExtension,
space: SpaceResource,
resource: Resource,
mode: string,
shareId: string = undefined
) => {
const routeOpts = routeOptsHelper(appFileExtension, space, resource, mode, shareId)
if (configStore.options.openAppsInTab) {
const path = router.resolve(routeOpts).href
const target = `${appFileExtension.routeName}-${resource.path}`
openUrl(path, target, true)
return
}
router.push(routeOpts)
}
// TODO: Make user-configurable what is a defaultAction for a filetype/mimetype
// returns the _first_ action from actions array which we now construct from
// available mime-types coming from the app-provider and existing actions
const triggerDefaultAction = (options: FileActionOptions) => {
const action = getDefaultAction(options)
action.handler({ ...options })
}
const triggerAction = (name: string, options: FileActionOptions) => {
const action = getAllAvailableActions(options).filter((action) => action.name === name)[0]
if (!action) {
throw new Error(`Action not found: '${name}'`)
}
action.handler(options)
}
const getDefaultEditorAction = (options: FileActionOptions): Action | null => {
return getDefaultAction({ ...options, omitSystemActions: true })
}
const getDefaultAction = (options: GetFileActionsOptions): Action | null => {
const filterCallback = (action) =>
action.isVisible({
...options,
parent: unref(currentFolder)
})
// first priority: handlers from config
const enabledEditorActions = unref(editorActions).filter(filterCallback)
// prioritize apps that have hasPriority set
const appActions = enabledEditorActions.sort(
(a, b) => Number(b.hasPriority) - Number(a.hasPriority)
)
if (appActions.length) {
return appActions[0]
}
// fallback: system actions
return options.omitSystemActions ? null : unref(systemActions).filter(filterCallback)[0]
}
const getAllAvailableActions = (options: FileActionOptions) => {
return [...unref(editorActions), ...unref(systemActions)].filter((action) => {
return action.isVisible(options)
})
}
return {
editorActions,
systemActions,
getDefaultAction,
getDefaultEditorAction,
getAllAvailableActions,
openEditor,
triggerAction,
triggerDefaultAction
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActions.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActions.ts",
"repo_id": "owncloud",
"token_count": 3260
} | 831 |
import { isSameResource } from '../../../helpers/resource'
import {
createLocationPublic,
createLocationSpaces,
isLocationPublicActive,
isLocationSharesActive,
isLocationTrashActive
} from '../../../router'
import { isIncomingShareResource } from '@ownclouders/web-client/src/helpers/share'
import merge from 'lodash-es/merge'
import { isShareSpaceResource, SpaceResource } from '@ownclouders/web-client/src/helpers'
import { createFileRouteOptions } from '../../../helpers/router'
import { useGetMatchingSpace } from '../../spaces'
import { useRouter } from '../../router'
import { computed, unref } from 'vue'
import { useGettext } from 'vue3-gettext'
import { FileAction } from '../types'
import { useResourcesStore } from '../../piniaStores'
import { storeToRefs } from 'pinia'
export const useFileActionsNavigate = () => {
const router = useRouter()
const { $gettext } = useGettext()
const { getMatchingSpace } = useGetMatchingSpace()
const resourcesStore = useResourcesStore()
const { currentFolder } = storeToRefs(resourcesStore)
const getSpace = (space: SpaceResource) => {
return space ? space : getMatchingSpace(space)
}
const routeName = computed(() => {
if (isLocationPublicActive(router, 'files-public-link')) {
return createLocationPublic('files-public-link')
}
return createLocationSpaces('files-spaces-generic')
})
const actions = computed((): FileAction[] => [
{
name: 'navigate',
icon: 'folder-open',
label: () => $gettext('Open folder'),
isVisible: ({ resources }) => {
if (isLocationTrashActive(router, 'files-trash-generic')) {
return false
}
if (resources.length !== 1) {
return false
}
if (unref(currentFolder) !== null && isSameResource(resources[0], unref(currentFolder))) {
return false
}
if (!resources[0].isFolder || resources[0].type === 'space') {
return false
}
if (isIncomingShareResource(resources[0]) && !resources[0].syncEnabled) {
return false
}
return true
},
componentType: 'router-link',
route: ({ space, resources }) => {
if (
isShareSpaceResource(space) &&
(isLocationSharesActive(router, 'files-shares-with-others') ||
isLocationSharesActive(router, 'files-shares-via-link'))
) {
// FIXME: This is a hacky way to resolve re-shares, but we don't have other options currently
return { name: 'resolvePrivateLink', params: { fileId: resources[0].fileId } }
}
return merge(
{},
unref(routeName),
createFileRouteOptions(getSpace(space), {
path: resources[0].path,
fileId: resources[0].fileId
})
)
},
class: 'oc-files-actions-navigate-trigger'
}
])
return {
actions
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsNavigate.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsNavigate.ts",
"repo_id": "owncloud",
"token_count": 1151
} | 832 |
export * from './useSpaceActionsDelete'
export * from './useSpaceActionsDisable'
export * from './useSpaceActionsDuplicate'
export * from './useSpaceActionsEditDescription'
export * from './useSpaceActionsEditQuota'
export * from './useSpaceActionsEditReadmeContent'
export * from './useSpaceActionsRename'
export * from './useSpaceActionsRestore'
export * from './useSpaceActionsShowMembers'
export * from './useSpaceActionsNavigateToTrash'
export * from './useSpaceActionsSetIcon'
| owncloud/web/packages/web-pkg/src/composables/actions/spaces/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/spaces/index.ts",
"repo_id": "owncloud",
"token_count": 148
} | 833 |
export * from './types'
export * from './useAppConfig'
export * from './useAppDefaults'
export * from './useAppFileHandling'
export * from './useAppFolderHandling'
export * from './useAppMeta'
export * from './useAppNavigation'
export * from './useDocumentTitle'
| owncloud/web/packages/web-pkg/src/composables/appDefaults/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/appDefaults/index.ts",
"repo_id": "owncloud",
"token_count": 84
} | 834 |
import { eventBus } from '../../services/eventBus'
import { RouteLocation } from 'vue-router'
import omit from 'lodash-es/omit'
import { BreadcrumbItem } from 'design-system/src/components/OcBreadcrumb/types'
import { v4 as uuidv4 } from 'uuid'
import { SpaceResource } from '@ownclouders/web-client/src'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import { useGetMatchingSpace } from '../spaces'
export const useBreadcrumbsFromPath = () => {
const { isResourceAccessible } = useGetMatchingSpace()
const breadcrumbsFromPath = ({
route,
space,
resourcePath
}: {
route: RouteLocation
space: SpaceResource
resourcePath: string
}): BreadcrumbItem[] => {
const pathSplit = (p = '') => p.split('/').filter(Boolean)
const current = pathSplit(route.path)
const resource = pathSplit(resourcePath)
return resource.map((text, i) => {
const isAccessible = isResourceAccessible({
space,
path: urlJoin(...resource.slice(0, i + 1), { leadingSlash: true })
})
return {
id: uuidv4(),
allowContextActions: true,
text,
...(isAccessible && {
to: {
path: '/' + [...current].splice(0, current.length - resource.length + i + 1).join('/'),
query: omit(route.query, 'fileId', 'page') // TODO: we need the correct fileId in the query. until we have that we must omit it because otherwise we would correct the path to the one of the (wrong) fileId.
}
}),
isStaticNav: false
} as BreadcrumbItem
})
}
const concatBreadcrumbs = (...items: BreadcrumbItem[]): BreadcrumbItem[] => {
const last = items.pop()
return [
...items,
{
id: uuidv4(),
allowContextActions: last.allowContextActions,
text: last.text,
onClick: () => eventBus.publish('app.files.list.load'),
isTruncationPlaceholder: last.isTruncationPlaceholder,
isStaticNav: last.isStaticNav
}
]
}
return { breadcrumbsFromPath, concatBreadcrumbs }
}
| owncloud/web/packages/web-pkg/src/composables/breadcrumbs/useBreadcrumbsFromPath.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/breadcrumbs/useBreadcrumbsFromPath.ts",
"repo_id": "owncloud",
"token_count": 822
} | 835 |
export * from './useResourceRouteResolver'
| owncloud/web/packages/web-pkg/src/composables/filesList/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/filesList/index.ts",
"repo_id": "owncloud",
"token_count": 12
} | 836 |
import { computed, ComputedRef, unref, MaybeRef } from 'vue'
import { queryItemAsString } from '../appDefaults'
import { useRouteQuery, useRouteQueryPersisted } from '../router'
import { PaginationConstants } from './constants'
import { eventBus } from '../../services'
import { findIndex } from 'lodash-es'
import { useRoute, useRouter } from 'vue-router'
interface PaginationOptions<T> {
items: MaybeRef<Array<T>>
page?: MaybeRef<number>
perPage?: MaybeRef<number>
perPageDefault?: string
perPageQueryName?: string
perPageStoragePrefix: string
}
interface PaginationResult<T> {
items: ComputedRef<Array<T>>
total: ComputedRef<number>
page: ComputedRef<number>
perPage: ComputedRef<number>
}
export function usePagination<T>(options: PaginationOptions<T>): PaginationResult<T> {
const router = useRouter()
const route = useRoute()
const page = createPageRef<T>(options)
const perPage = createPerPageRef<T>(options)
const total = computed(() => {
return Math.ceil(unref(options.items).length / unref(perPage)) || 1
})
const items = computed(() => {
if (!unref(perPage)) {
return unref(options.items)
}
const start = (unref(page) - 1) * unref(perPage)
const end = start + unref(perPage)
return unref(options.items).slice(start, end)
})
eventBus.subscribe(
'app.files.navigate.page',
({
resourceId,
forceScroll,
topbarElement
}: {
resourceId: string
forceScroll: boolean
topbarElement: string
}) => {
const index = findIndex(unref(options.items), (item: any) => item.id === resourceId)
if (index >= 0) {
const page = Math.ceil((index + 1) / Number(unref(perPage)))
router.push({ ...unref(route), query: { ...unref(route).query, page } }).then(() => {
eventBus.publish('app.files.navigate.scrollTo', {
resourceId,
forceScroll,
topbarElement
})
})
}
}
)
return {
items,
total,
page,
perPage
}
}
function createPageRef<T>(options: PaginationOptions<T>): ComputedRef<number> {
if (options.page) {
return computed(() => unref(options.page))
}
const pageQuery = useRouteQuery('page', '1')
return computed(() => parseInt(queryItemAsString(unref(pageQuery))))
}
function createPerPageRef<T>(options: PaginationOptions<T>): ComputedRef<number> {
if (options.perPage) {
return computed(() => unref(options.perPage))
}
const perPageQuery = useRouteQueryPersisted({
name: options.perPageQueryName || PaginationConstants.perPageQueryName,
defaultValue: options.perPageDefault || PaginationConstants.perPageDefault,
storagePrefix: options.perPageStoragePrefix
})
return computed(() => parseInt(queryItemAsString(unref(perPageQuery))))
}
| owncloud/web/packages/web-pkg/src/composables/pagination/usePagination.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/pagination/usePagination.ts",
"repo_id": "owncloud",
"token_count": 1044
} | 837 |
import {
CollaboratorShare,
LinkShare,
Share,
GraphShareRoleIdMap,
ShareRole,
ShareTypes,
isProjectSpaceResource,
getGraphItemId
} from '@ownclouders/web-client/src/helpers'
import { defineStore } from 'pinia'
import { Ref, ref, unref } from 'vue'
import {
AddLinkOptions,
AddShareOptions,
DeleteLinkOptions,
DeleteShareOptions,
UpdateLinkOptions,
UpdateShareOptions
} from './types'
import { useResourcesStore } from '../resources'
import { UnifiedRoleDefinition } from '@ownclouders/web-client/src/generated'
import { useUserStore } from '../user'
import {
buildLinkShare,
buildCollaboratorShare
} from '@ownclouders/web-client/src/helpers/share/functionsNG'
export const useSharesStore = defineStore('shares', () => {
const resourcesStore = useResourcesStore()
const userStore = useUserStore()
const loading = ref(false)
const collaboratorShares = ref<CollaboratorShare[]>([]) as Ref<CollaboratorShare[]>
const linkShares = ref<LinkShare[]>([]) as Ref<LinkShare[]>
const graphRoles = ref<ShareRole[]>([]) as Ref<ShareRole[]>
const setGraphRoles = (values: UnifiedRoleDefinition[]) => {
const ShareRoleIconMap = {
[GraphShareRoleIdMap.Viewer]: 'eye',
[GraphShareRoleIdMap.SpaceViewer]: 'eye',
[GraphShareRoleIdMap.FileEditor]: 'pencil',
[GraphShareRoleIdMap.FolderEditor]: 'pencil',
[GraphShareRoleIdMap.SpaceEditor]: 'pencil',
[GraphShareRoleIdMap.SpaceManager]: 'user-star'
}
const $gettext = (str: string) => str // dummy
const ShareRoleLabelMap = {
[GraphShareRoleIdMap.Viewer]: $gettext('Can view'),
[GraphShareRoleIdMap.SpaceViewer]: $gettext('Can view'),
[GraphShareRoleIdMap.FileEditor]: $gettext('Can edit'),
[GraphShareRoleIdMap.FolderEditor]: $gettext('Can edit'),
[GraphShareRoleIdMap.SpaceEditor]: $gettext('Can edit'),
[GraphShareRoleIdMap.SpaceManager]: $gettext('Can manage')
}
graphRoles.value = values.map((v) => ({
...v,
icon: ShareRoleIconMap[v.id] || 'user',
label: ShareRoleLabelMap[v.id] || v.displayName
}))
}
const upsertCollaboratorShare = (share: CollaboratorShare) => {
const existingShare = unref(collaboratorShares).find(({ id }) => id === share.id)
if (existingShare) {
Object.assign(existingShare, share)
return
}
unref(collaboratorShares).push(share)
}
const setCollaboratorShares = (values: CollaboratorShare[]) => {
collaboratorShares.value = values
}
const addCollaboratorShares = (values: CollaboratorShare[]) => {
unref(collaboratorShares).push(...values)
}
const removeCollaboratorShare = (share: CollaboratorShare) => {
collaboratorShares.value = unref(collaboratorShares).filter(({ id }) => id !== share.id)
}
const pruneShares = () => {
collaboratorShares.value = []
linkShares.value = []
loading.value = undefined
}
// remove loaded shares that are not within the current path
const removeOrphanedShares = () => {
const ancestorIds = Object.values(resourcesStore.ancestorMetaData).map(({ id }) => id)
if (!ancestorIds.length) {
collaboratorShares.value = []
linkShares.value = []
return
}
unref(collaboratorShares).forEach((share) => {
if (!ancestorIds.includes(share.resourceId)) {
removeCollaboratorShare(share)
}
})
unref(linkShares).forEach((share) => {
if (!ancestorIds.includes(share.resourceId)) {
removeLinkShare(share)
}
})
}
const setLinkShares = (values: LinkShare[]) => {
linkShares.value = values
}
const upsertLinkShare = (share: LinkShare) => {
const existingShare = unref(linkShares).find(({ id }) => id === share.id)
if (existingShare) {
Object.assign(existingShare, share)
return
}
// FIXME: use push as soon as we have a share date
unref(linkShares).unshift(share)
}
const removeLinkShare = (share: LinkShare) => {
linkShares.value = unref(linkShares).filter(({ id }) => id !== share.id)
}
const setLoading = (value: boolean) => {
loading.value = value
}
const updateFileShareTypes = (path: string) => {
const computeShareTypes = (shares: Share[]): any => {
const shareTypes = new Set()
shares.forEach((share) => {
shareTypes.add(share.shareType)
})
return Array.from(shareTypes)
}
const file = [...resourcesStore.resources, resourcesStore.currentFolder].find(
(f) => f?.path === path
)
if (!file || isProjectSpaceResource(file)) {
return
}
const allShares = [...unref(collaboratorShares), ...unref(linkShares)]
resourcesStore.updateResourceField({
id: file.id,
field: 'shareTypes',
value: computeShareTypes(allShares.filter((s) => !s.indirect))
})
const ancestorEntry = resourcesStore.ancestorMetaData[file.path] ?? null
if (ancestorEntry) {
resourcesStore.updateAncestorField({
path: ancestorEntry.path,
field: 'shareTypes',
value: computeShareTypes(allShares.filter((s) => !s.indirect))
})
}
}
const addShare = async ({
clientService,
space,
resource,
options
}: AddShareOptions): Promise<CollaboratorShare[]> => {
const {
data: { value: permissions }
} = await clientService.graphAuthenticated.permissions.invite(
space.id,
getGraphItemId(resource),
options
)
const builtShares = []
permissions.forEach((graphPermission) => {
builtShares.push(
buildCollaboratorShare({
graphPermission,
graphRoles: unref(graphRoles),
resourceId: resource.id,
spaceId: space.id,
user: userStore.user
})
)
})
addCollaboratorShares(builtShares)
updateFileShareTypes(resource.path)
resourcesStore.loadIndicators(resource.path)
return builtShares
}
const updateShare = async ({
clientService,
space,
resource,
collaboratorShare,
options
}: UpdateShareOptions) => {
const { data } = await clientService.graphAuthenticated.permissions.updatePermission(
space.id,
getGraphItemId(resource),
collaboratorShare.id,
{
roles: options.roles,
expirationDateTime: options.expirationDateTime
}
)
const share = buildCollaboratorShare({
graphPermission: data,
graphRoles: unref(graphRoles),
resourceId: resource.id,
spaceId: space.id,
user: userStore.user
})
upsertCollaboratorShare(share)
return share
}
const deleteShare = async ({
clientService,
space,
resource,
collaboratorShare,
loadIndicators = false
}: DeleteShareOptions) => {
await clientService.graphAuthenticated.permissions.deletePermission(
space.id,
getGraphItemId(resource),
collaboratorShare.id
)
removeCollaboratorShare(collaboratorShare)
updateFileShareTypes(resource.path)
if (loadIndicators) {
resourcesStore.loadIndicators(resource.path)
}
}
const addLink = async ({ clientService, space, resource, options }: AddLinkOptions) => {
const { data } = await clientService.graphAuthenticated.permissions.createLink(
space.id,
getGraphItemId(resource),
options
)
const link = buildLinkShare({
graphPermission: data,
user: userStore.user,
resourceId: resource.id
})
const selectedFiles = resourcesStore.selectedResources
const fileIsSelected =
selectedFiles.some(({ fileId }) => fileId === resource.fileId) ||
(selectedFiles.length === 0 && resourcesStore.currentFolder.fileId === resource.fileId)
upsertLinkShare(link)
updateFileShareTypes(resource.path)
if (!fileIsSelected) {
// we might need to update the share types for the ancestor resource as well
const ancestor = resourcesStore.ancestorMetaData[resource.path] ?? null
if (ancestor) {
const { shareTypes } = ancestor
if (!shareTypes.includes(ShareTypes.link.value)) {
resourcesStore.updateAncestorField({
path: ancestor.path,
field: 'shareTypes',
value: [...shareTypes, ShareTypes.link.value]
})
}
}
}
resourcesStore.loadIndicators(resource.path)
return link
}
const updateLink = async ({
clientService,
space,
resource,
linkShare,
options
}: UpdateLinkOptions) => {
let response
if (Object.hasOwn(options, 'password')) {
response = await clientService.graphAuthenticated.permissions.setPermissionPassword(
space.id,
getGraphItemId(resource),
linkShare.id,
{ password: options.password }
)
linkShare.hasPassword = !!options.password
} else {
response = await clientService.graphAuthenticated.permissions.updatePermission(
space.id,
getGraphItemId(resource),
linkShare.id,
{
link: {
...(options.type && { type: options.type }),
...(options.displayName && {
'@libre.graph.displayName': options.displayName
})
},
expirationDateTime: options.expirationDateTime
}
)
}
const link = buildLinkShare({
graphPermission: response.data,
user: userStore.user,
resourceId: resource.id
})
upsertLinkShare(link)
return link
}
const deleteLink = async ({
clientService,
space,
resource,
linkShare,
loadIndicators = false
}: DeleteLinkOptions) => {
await clientService.graphAuthenticated.permissions.deletePermission(
space.id,
getGraphItemId(resource),
linkShare.id
)
removeLinkShare(linkShare)
updateFileShareTypes(resource.path)
if (loadIndicators) {
resourcesStore.loadIndicators(resource.path)
}
}
return {
loading,
collaboratorShares,
linkShares,
graphRoles,
setGraphRoles,
setLoading,
setCollaboratorShares,
setLinkShares,
removeOrphanedShares,
pruneShares,
addShare,
updateShare,
deleteShare,
addLink,
updateLink,
deleteLink
}
})
export type SharesStore = ReturnType<typeof useSharesStore>
| owncloud/web/packages/web-pkg/src/composables/piniaStores/shares/shares.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/shares/shares.ts",
"repo_id": "owncloud",
"token_count": 3908
} | 838 |
import { ref, Ref, watch } from 'vue'
import { useRoute } from './useRoute'
import { useRouter } from './useRouter'
import { ActiveRouteDirectorFunc } from '../../router'
/**
* watches the current route and re-evaluates the provided active location director
* on each route name update.
*
* @param director
* @param comparatives
*/
export const useActiveLocation = <T extends string>(
director: ActiveRouteDirectorFunc<T>,
...comparatives: T[]
): Ref<boolean> => {
const value = ref(false)
const router = useRouter()
const currentRoute = useRoute()
watch(
currentRoute,
() => {
value.value = director(router, ...comparatives)
},
{ immediate: true }
)
return value
}
| owncloud/web/packages/web-pkg/src/composables/router/useActiveLocation.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/router/useActiveLocation.ts",
"repo_id": "owncloud",
"token_count": 228
} | 839 |
export * from './useService'
| owncloud/web/packages/web-pkg/src/composables/service/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/service/index.ts",
"repo_id": "owncloud",
"token_count": 9
} | 840 |
export const FolderViewModeConstants = {
// FIXME: we have a few places where we still match against hardcoded names, get rid of that and this constants
name: {
table: 'resource-table',
condensedTable: 'resource-table-condensed',
tiles: 'resource-tiles'
},
defaultModeName: 'resource-table',
queryName: 'view-mode',
tilesSizeDefault: 2,
tilesSizeMax: 6,
tilesSizeQueryName: 'tiles-size'
} as const
| owncloud/web/packages/web-pkg/src/composables/viewMode/constants.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/viewMode/constants.ts",
"repo_id": "owncloud",
"token_count": 137
} | 841 |
export * from './types'
| owncloud/web/packages/web-pkg/src/helpers/folderLink/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/folderLink/index.ts",
"repo_id": "owncloud",
"token_count": 8
} | 842 |
import { basename, join } from 'path'
import {
Resource,
SpaceResource,
extractExtensionFromFile
} from '@ownclouders/web-client/src/helpers'
export function renameResource(space: SpaceResource, resource: Resource, newPath: string) {
resource.name = basename(newPath)
resource.path = newPath
resource.webDavPath = join(space.webDavPath, newPath)
resource.extension = extractExtensionFromFile(resource)
return resource
}
| owncloud/web/packages/web-pkg/src/helpers/resource/renameResource.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/resource/renameResource.ts",
"repo_id": "owncloud",
"token_count": 133
} | 843 |
export * from './visibility'
| owncloud/web/packages/web-pkg/src/observer/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/observer/index.ts",
"repo_id": "owncloud",
"token_count": 9
} | 844 |
import * as uuid from 'uuid'
export class EventBus {
private topics: Map<string, { callback: (data?: unknown) => void; token: string }[]>
constructor() {
this.topics = new Map()
}
public subscribe(topic: string, callback: (data?: unknown) => void): string {
const subscription = {
token: uuid.v4(),
callback
}
const subscriptions = [subscription, ...(this.topics.get(topic) || [])]
this.topics.set(topic, subscriptions)
return subscription.token
}
public publish(topic: string, data?: unknown): void {
const subscriptions = this.topics.get(topic) || []
subscriptions.forEach((subscription) => subscription.callback(data))
}
public unsubscribe(topic: string, token: string): void {
if (!this.topics.has(topic)) {
return
}
this.topics.set(
topic,
this.topics.get(topic).filter((subscription) => subscription.token !== token)
)
}
}
export const eventBus = new EventBus()
| owncloud/web/packages/web-pkg/src/services/eventBus.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/services/eventBus.ts",
"repo_id": "owncloud",
"token_count": 338
} | 845 |
export const encodePath = (path = ''): string => {
return path.split('/').map(encodeURIComponent).join('/')
}
| owncloud/web/packages/web-pkg/src/utils/encodePath.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/utils/encodePath.ts",
"repo_id": "owncloud",
"token_count": 38
} | 846 |
import ContextMenuQuickAction from '../../../../src/components/ContextActions/ContextMenuQuickAction.vue'
import { defaultPlugins, mount } from 'web-test-helpers'
describe('ContextMenuQuickAction component', () => {
it('renders component', () => {
const { wrapper } = getWrapper()
expect(wrapper.html()).toMatchSnapshot()
})
it('triggers the "quickActionClicked"-event on click', async () => {
const { wrapper } = getWrapper()
await wrapper.find('button').trigger('click')
expect(wrapper.emitted('quickActionClicked')).toBeTruthy()
})
})
function getWrapper({ item = { id: '1' } } = {}) {
return {
wrapper: mount(ContextMenuQuickAction, {
props: {
item
},
global: {
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/ContextActions/ContextMenuQuickAction.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/ContextActions/ContextMenuQuickAction.spec.ts",
"repo_id": "owncloud",
"token_count": 288
} | 847 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`OcTile component > renders default space correctly 1`] = `
"<div class="oc-tile-card oc-card oc-card-default oc-rounded">
<resource-link-stub resource="[object Object]" folderlink="[object Object]" isresourceclickable="true" class="oc-card-media-top oc-flex oc-flex-center oc-flex-middle oc-m-rm" tabindex="-1">
<div class="oc-tile-card-selection"></div>
<!--v-if-->
<div class="oc-tile-card-preview oc-flex oc-flex-middle oc-flex-center">
<div class="oc-tile-card-hover"></div>
<resource-icon-stub resource="[object Object]" size="xlarge" class="tile-default-image oc-pt-xs"></resource-icon-stub>
</div>
</resource-link-stub>
<div class="oc-card-body oc-p-s">
<div class="oc-flex oc-flex-between oc-flex-middle">
<div class="oc-flex oc-flex-middle oc-text-truncate resource-name-wrapper">
<resource-list-item-stub resource="[object Object]" pathprefix="" folderlink="[object Object]" ispathdisplayed="false" parentfoldername="" parentfolderlinkiconadditionalattributes="[object Object]" isextensiondisplayed="true" isthumbnaildisplayed="true" isicondisplayed="false" isresourceclickable="true"></resource-list-item-stub>
</div>
<div class="oc-flex oc-flex-middle">
<!-- Slot for indicators !-->
<!-- Slot for individual actions -->
<!-- Slot for contextmenu -->
</div>
</div>
<!--v-if-->
</div>
</div>"
`;
exports[`OcTile component > renders disabled space correctly 1`] = `
"<div class="oc-tile-card oc-card oc-card-default oc-rounded state-trashed">
<resource-link-stub resource="[object Object]" folderlink="[object Object]" isresourceclickable="true" class="oc-card-media-top oc-flex oc-flex-center oc-flex-middle oc-m-rm" tabindex="-1">
<div class="oc-tile-card-selection"></div>
<oc-tag-stub type="span" size="medium" rounded="false" class="resource-disabled-indicator oc-position-absolute"><span>Disabled</span></oc-tag-stub>
<div class="oc-tile-card-preview oc-flex oc-flex-middle oc-flex-center">
<div class="oc-tile-card-hover"></div>
<resource-icon-stub resource="[object Object]" size="xlarge" class="tile-default-image oc-pt-xs"></resource-icon-stub>
</div>
</resource-link-stub>
<div class="oc-card-body oc-p-s">
<div class="oc-flex oc-flex-between oc-flex-middle">
<div class="oc-flex oc-flex-middle oc-text-truncate resource-name-wrapper">
<resource-list-item-stub resource="[object Object]" pathprefix="" folderlink="[object Object]" ispathdisplayed="false" parentfoldername="" parentfolderlinkiconadditionalattributes="[object Object]" isextensiondisplayed="true" isthumbnaildisplayed="true" isicondisplayed="false" isresourceclickable="true"></resource-list-item-stub>
</div>
<div class="oc-flex oc-flex-middle">
<!-- Slot for indicators !-->
<!-- Slot for individual actions -->
<!-- Slot for contextmenu -->
</div>
</div>
<!--v-if-->
</div>
</div>"
`;
| owncloud/web/packages/web-pkg/tests/unit/components/FilesList/__snapshots__/ResourceTile.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/FilesList/__snapshots__/ResourceTile.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 1144
} | 848 |
import { ref, unref } from 'vue'
import {
defaultPlugins,
defaultComponentMocks,
mount,
RouteLocation,
PartialComponentProps
} from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import ViewOptions from '../../../src/components/ViewOptions.vue'
import {
FolderViewModeConstants,
useResourcesStore,
useRouteQuery,
useRouteQueryPersisted
} from '../../../src/composables'
import { FolderView } from '../../../src'
import { OcPageSize, OcSwitch } from 'design-system/src/components'
vi.mock('../../../src/composables/router', async (importOriginal) => ({
...(await importOriginal<any>()),
useRouteQueryPersisted: vi.fn(),
useRouteQuery: vi.fn()
}))
const selectors = {
pageSizeSelect: '.oc-page-size',
hiddenFilesSwitch: '[data-testid="files-switch-hidden-files"]',
fileExtensionsSwitch: '[data-testid="files-switch-files-extensions-files"]',
viewModeSwitchBtns: '.viewmode-switch-buttons',
tileSizeSlider: '[data-testid="files-tiles-size-slider"]'
}
describe('ViewOptions component', () => {
describe('pagination', () => {
it('does not show when disabled', () => {
const { wrapper } = getWrapper({ props: { hasPagination: false } })
expect(wrapper.find(selectors.pageSizeSelect).exists()).toBeFalsy()
})
it('sets the correct initial files page limit', () => {
const perPage = '100'
const { wrapper } = getWrapper({ perPage })
expect(
wrapper.findComponent<typeof OcPageSize>(selectors.pageSizeSelect).props().selected
).toBe(perPage)
})
it('sets the correct files page limit', () => {
const perPage = '100'
const newItemsPerPage = '500'
const { wrapper, mocks } = getWrapper({ perPage })
wrapper.vm.setItemsPerPage(newItemsPerPage)
expect(mocks.$router.replace).toHaveBeenCalledWith(
expect.objectContaining({
query: expect.objectContaining({ 'items-per-page': newItemsPerPage })
})
)
})
it('resets the page to 1 if current page is > 1', () => {
const perPage = '100'
const newItemsPerPage = '500'
const { wrapper, mocks } = getWrapper({ perPage, currentPage: '2' })
wrapper.vm.setItemsPerPage(newItemsPerPage)
expect(mocks.$router.replace).toHaveBeenCalledWith(
expect.objectContaining({
query: expect.objectContaining({ 'items-per-page': newItemsPerPage, page: '1' })
})
)
})
})
describe('hidden files toggle', () => {
it('does not show when disabled', () => {
const { wrapper } = getWrapper({ props: { hasHiddenFiles: false } })
expect(wrapper.find(selectors.hiddenFilesSwitch).exists()).toBeFalsy()
})
it('toggles the setting to show/hide hidden files', () => {
const { wrapper } = getWrapper()
wrapper
.findComponent<typeof OcSwitch>(selectors.hiddenFilesSwitch)
.vm.$emit('update:checked', false)
const { setAreHiddenFilesShown } = useResourcesStore()
expect(setAreHiddenFilesShown).toHaveBeenCalled()
})
})
describe('file extension toggle', () => {
it('does not show when disabled', () => {
const { wrapper } = getWrapper({ props: { hasFileExtensions: false } })
expect(wrapper.find(selectors.fileExtensionsSwitch).exists()).toBeFalsy()
})
it('toggles the setting to show/hide file extensions', () => {
const { wrapper } = getWrapper()
wrapper
.findComponent<typeof OcSwitch>(selectors.fileExtensionsSwitch)
.vm.$emit('update:checked', false)
const { setAreFileExtensionsShown } = useResourcesStore()
expect(setAreFileExtensionsShown).toHaveBeenCalled()
})
})
describe('view mode switcher', () => {
it('does not show initially', () => {
const { wrapper } = getWrapper()
expect(wrapper.find(selectors.viewModeSwitchBtns).exists()).toBeFalsy()
})
it('shows if more than one viewModes are passed', () => {
const { wrapper } = getWrapper({
props: {
viewModes: [
mock<FolderView>({ name: '1', label: '' }),
mock<FolderView>({ name: '2', label: '' })
]
}
})
expect(wrapper.find(selectors.viewModeSwitchBtns).exists()).toBeTruthy()
})
})
describe('tile size slider', () => {
it('does not show initially', () => {
const { wrapper } = getWrapper()
expect(wrapper.find(selectors.tileSizeSlider).exists()).toBeFalsy()
})
it('shows if the viewModes include "resource-tiles"', () => {
const { wrapper } = getWrapper({
props: { viewModes: [mock<FolderView>({ name: FolderViewModeConstants.name.tiles })] }
})
expect(wrapper.find(selectors.tileSizeSlider).exists()).toBeTruthy()
})
it.each([1, 2, 3, 4, 5, 6])('applies the correct size step', (tileSize) => {
const { mocks } = getWrapper({
tileSize: tileSize.toString(),
props: { viewModes: [mock<FolderView>({ name: FolderViewModeConstants.name.tiles })] }
})
expect(unref(mocks.tileSizeQueryMock)).toBe(tileSize.toString())
})
})
})
function getWrapper({
perPage = '100',
viewMode = FolderViewModeConstants.name.table,
tileSize = '1',
props = {},
currentPage = '1'
}: {
perPage?: string
viewMode?: string
tileSize?: string
props?: PartialComponentProps<typeof ViewOptions>
currentPage?: string
} = {}) {
vi.mocked(useRouteQueryPersisted).mockImplementationOnce(() => ref(perPage))
vi.mocked(useRouteQueryPersisted).mockImplementationOnce(() => ref(viewMode))
const tileSizeQueryMock = ref(tileSize)
vi.mocked(useRouteQueryPersisted).mockImplementationOnce(() => tileSizeQueryMock)
vi.mocked(useRouteQuery).mockImplementationOnce(() => ref(currentPage))
const mocks = {
...defaultComponentMocks({ currentRoute: mock<RouteLocation>({ path: '/files' }) }),
tileSizeQueryMock
}
return {
mocks,
wrapper: mount(ViewOptions, {
props: {
perPageStoragePrefix: '',
...props
},
global: {
mocks,
provide: mocks,
stubs: { OcButton: true, OcPageSize: false, OcSelect: true },
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/ViewOptions.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/ViewOptions.spec.ts",
"repo_id": "owncloud",
"token_count": 2397
} | 849 |
import { ref, unref } from 'vue'
import { useFileActionsCreateLink } from '../../../../../src/composables/actions/files/useFileActionsCreateLink'
import {
useMessages,
useModals,
CapabilityStore,
useSharesStore
} from '../../../../../src/composables/piniaStores'
import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { Resource } from '@ownclouders/web-client'
import { SharingLinkType } from '@ownclouders/web-client/src/generated'
import { useLinkTypes } from '../../../../../src/composables/links/useLinkTypes'
vi.mock('../../../../../src/composables/links/useLinkTypes', () => ({
useLinkTypes: vi.fn()
}))
describe('useFileActionsCreateLink', () => {
describe('isVisible property', () => {
it('should return false if no resource selected', () => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ space: null, resources: [] })).toBeFalsy()
}
})
})
it('should return false if one resource can not be shared', () => {
getWrapper({
setup: ({ actions }) => {
const resources = [mock<Resource>({ canShare: () => false })]
expect(unref(actions)[0].isVisible({ space: null, resources })).toBeFalsy()
}
})
})
it('should return false if one resource is a disabled project space', () => {
getWrapper({
setup: ({ actions }) => {
const resources = [
mock<Resource>({ canShare: () => true, disabled: true, driveType: 'project' })
]
expect(unref(actions)[0].isVisible({ space: null, resources })).toBeFalsy()
}
})
})
it('should return true if all files can be shared', () => {
getWrapper({
setup: ({ actions }) => {
const resources = [
mock<Resource>({ canShare: () => true }),
mock<Resource>({ canShare: () => true })
]
expect(unref(actions)[0].isVisible({ space: null, resources })).toBeTruthy()
}
})
})
})
describe('handler', () => {
it('calls the createLink method and shows messages', () => {
getWrapper({
setup: async ({ actions }) => {
const { addLink } = useSharesStore()
// link action
await unref(actions)[0].handler({ resources: [mock<Resource>({ canShare: () => true })] })
expect(addLink).toHaveBeenCalledWith(
expect.objectContaining({
options: expect.objectContaining({ '@libre.graph.quickLink': false })
})
)
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalledTimes(1)
// quick link action
await unref(actions)[1].handler({ resources: [mock<Resource>({ canShare: () => true })] })
expect(addLink).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
options: expect.objectContaining({ '@libre.graph.quickLink': true })
})
)
}
})
})
it('shows a modal if enforced', () => {
getWrapper({
enforceModal: true,
setup: ({ actions }) => {
const { addLink } = useSharesStore()
const { dispatchModal } = useModals()
unref(actions)[0].handler({ resources: [mock<Resource>({ canShare: () => true })] })
expect(addLink).not.toHaveBeenCalled()
expect(dispatchModal).toHaveBeenCalledTimes(1)
}
})
})
it('shows a modal if password is enforced and link is not internal', () => {
getWrapper({
passwordEnforced: true,
defaultLinkType: SharingLinkType.View,
setup: ({ actions }) => {
const { addLink } = useSharesStore()
const { dispatchModal } = useModals()
unref(actions)[0].handler({ resources: [mock<Resource>({ canShare: () => true })] })
expect(addLink).not.toHaveBeenCalled()
expect(dispatchModal).toHaveBeenCalledTimes(1)
}
})
})
it('calls the onLinkCreatedCallback if given', () => {
const onLinkCreatedCallback = vi.fn()
getWrapper({
onLinkCreatedCallback,
setup: async ({ actions }) => {
await unref(actions)[0].handler({ resources: [mock<Resource>({ canShare: () => true })] })
expect(onLinkCreatedCallback).toHaveBeenCalledTimes(1)
}
})
})
it('does not show messages if disabled', () => {
getWrapper({
showMessages: false,
setup: async ({ actions }) => {
await unref(actions)[0].handler({ resources: [mock<Resource>({ canShare: () => true })] })
const { showMessage } = useMessages()
expect(showMessage).not.toHaveBeenCalled()
}
})
})
})
})
function getWrapper({
setup,
enforceModal = false,
passwordEnforced = false,
defaultLinkType = SharingLinkType.View,
onLinkCreatedCallback = undefined,
showMessages = true
}) {
vi.mocked(useLinkTypes).mockReturnValue(
mock<ReturnType<typeof useLinkTypes>>({ defaultLinkType: ref(defaultLinkType) })
)
const mocks = { ...defaultComponentMocks() }
const capabilities = {
files_sharing: { public: { password: { enforced_for: { read_only: passwordEnforced } } } }
} satisfies Partial<CapabilityStore['capabilities']>
return {
wrapper: getComposableWrapper(
() => {
const instance = useFileActionsCreateLink({
enforceModal,
showMessages,
onLinkCreatedCallback
})
setup(instance, { mocks })
},
{
provide: mocks,
pluginOptions: { piniaOptions: { capabilityState: { capabilities } } }
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCreateLink.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCreateLink.spec.ts",
"repo_id": "owncloud",
"token_count": 2401
} | 850 |
import { useSpaceActionsDisable } from '../../../../../src/composables/actions/spaces'
import { useMessages, useModals } from '../../../../../src/composables/piniaStores'
import { buildSpace, SpaceResource } from '@ownclouders/web-client/src/helpers'
import {
defaultComponentMocks,
mockAxiosResolve,
RouteLocation,
getComposableWrapper
} from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { unref } from 'vue'
import { Drive } from '@ownclouders/web-client/src/generated'
describe('disable', () => {
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 the space is not disabled', () => {
const spaceMock = mock<Drive>({
id: '1',
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
driveType: 'project',
special: null
})
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [buildSpace(spaceMock)] })).toBe(true)
}
})
})
it('should be false when the space is disabled', () => {
const spaceMock = mock<Drive>({
id: '1',
root: {
permissions: [{ roles: ['manager'], grantedToIdentities: [{ user: { id: '1' } }] }],
deleted: { state: 'trashed' }
},
special: null
})
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [buildSpace(spaceMock)] })).toBe(false)
}
})
})
it('should be false when current user is a viewer', () => {
const spaceMock = mock<Drive>({
id: '1',
root: {
permissions: [{ roles: ['viewer'], grantedToIdentities: [{ user: { id: '1' } }] }]
},
driveType: 'project',
special: null
})
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources: [buildSpace(spaceMock)] })).toBe(false)
}
})
})
})
describe('handler', () => {
it('should trigger the disable modal window', () => {
getWrapper({
setup: async ({ actions }) => {
const { dispatchModal } = useModals()
await unref(actions)[0].handler({
resources: [
mock<SpaceResource>({ id: '1', canDisable: () => true, driveType: 'project' })
]
})
expect(dispatchModal).toHaveBeenCalledTimes(1)
}
})
})
it('should not trigger the disable modal window without any resource', () => {
getWrapper({
setup: async ({ actions }) => {
const { dispatchModal } = useModals()
await unref(actions)[0].handler({
resources: [
mock<SpaceResource>({ id: '1', canDisable: () => false, driveType: 'project' })
]
})
expect(dispatchModal).toHaveBeenCalledTimes(0)
}
})
})
})
describe('method "disableSpace"', () => {
it('should show message on success', () => {
getWrapper({
setup: async ({ disableSpaces }, { clientService }) => {
clientService.graphAuthenticated.drives.disableDrive.mockResolvedValue(mockAxiosResolve())
await disableSpaces([
mock<SpaceResource>({ id: '1', canDisable: () => true, driveType: 'project' })
])
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalledTimes(1)
}
})
})
it('should show message on error', () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
getWrapper({
setup: async ({ disableSpaces }, { clientService }) => {
clientService.graphAuthenticated.drives.disableDrive.mockRejectedValue(new Error())
await disableSpaces([
mock<SpaceResource>({ id: '1', canDisable: () => true, driveType: 'project' })
])
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalledTimes(1)
}
})
})
})
})
function getWrapper({
setup
}: {
setup: (
instance: ReturnType<typeof useSpaceActionsDisable>,
{
clientService
}: {
clientService: ReturnType<typeof defaultComponentMocks>['$clientService']
}
) => void
}) {
const mocks = defaultComponentMocks({
currentRoute: mock<RouteLocation>({ name: 'files-spaces-projects' })
})
return {
mocks,
wrapper: getComposableWrapper(
() => {
const instance = useSpaceActionsDisable()
setup(instance, { clientService: mocks.$clientService })
},
{
mocks,
provide: mocks,
pluginOptions: {
piniaOptions: { userState: { user: { id: '1', onPremisesSamAccountName: 'alice' } } }
}
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsDisable.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsDisable.spec.ts",
"repo_id": "owncloud",
"token_count": 2197
} | 851 |
import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers'
import { CapabilityStore, useFolderLink } from '../../../../src/composables'
import { Resource, SpaceResource } from '@ownclouders/web-client'
describe('useFolderLink', () => {
it('getFolderLink should return the correct folder link', () => {
const resource = {
path: '/my-folder',
id: '2',
fileId: '2',
storageId: '1'
}
const wrapper = createWrapper()
const folderLink = wrapper.vm.getFolderLink(resource)
expect(folderLink).toEqual({
name: 'files-spaces-generic',
params: { driveAliasAndItem: 'personal/admin' },
query: { fileId: '2' }
})
})
it('getParentFolderLink should return the correct parent folder link', () => {
const resource = {
path: '/my-folder',
id: '2',
fileId: '2',
storageId: '1',
parentFolderId: '1'
}
const wrapper = createWrapper()
const parentFolderLink = wrapper.vm.getParentFolderLink(resource)
expect(parentFolderLink).toEqual({
name: 'files-spaces-generic',
params: { driveAliasAndItem: 'personal/admin' },
query: { fileId: '1' }
})
})
describe('getParentFolderName should return the correct parent folder name', () => {
it('should equal "Personal" if share jail is enabled', () => {
const resource = {
path: '/my-folder',
storageId: '1'
} as Resource
const wrapper = createWrapper()
const parentFolderName = wrapper.vm.getParentFolderName(resource)
expect(parentFolderName).toEqual('Personal')
})
it('should equal the space name if resource storage is representing a project space', () => {
const resource = {
path: '/my-folder',
storageId: '2'
} as Resource
const wrapper = createWrapper()
const parentFolderName = wrapper.vm.getParentFolderName(resource)
expect(parentFolderName).toEqual('New space')
})
it('should equal the "Shared with me" if resource is representing the root share', () => {
const resource = {
path: '/My share',
shareRoot: '/My share',
shareId: '1',
isShareRoot: () => true
} as Resource
const wrapper = createWrapper()
const parentFolderName = wrapper.vm.getParentFolderName(resource)
expect(parentFolderName).toEqual('Shared with me')
})
it('should equal the share name if resource is representing a file or folder in the root of a share', () => {
const resource = {
path: '/My share/test.txt',
shareRoot: '/My share',
shareId: '1'
} as Resource
const wrapper = createWrapper()
const parentFolderName = wrapper.vm.getParentFolderName(resource)
expect(parentFolderName).toEqual('My share')
})
})
})
const createWrapper = () => {
const spaces = [
{
id: '1',
fileId: '1',
driveType: 'personal',
getDriveAliasAndItem: () => 'personal/admin'
},
{
id: '2',
driveType: 'project',
name: 'New space',
getDriveAliasAndItem: vi.fn()
}
] as unknown as SpaceResource[]
const mocks = defaultComponentMocks({})
const capabilities = {
spaces: { projects: true }
} satisfies Partial<CapabilityStore['capabilities']>
return getComposableWrapper(
() => {
const {
getFolderLink,
getParentFolderLink,
getParentFolderName,
getParentFolderLinkIconAdditionalAttributes
} = useFolderLink()
return {
getFolderLink,
getParentFolderLink,
getParentFolderName,
getParentFolderLinkIconAdditionalAttributes
}
},
{
mocks,
provide: mocks,
pluginOptions: {
piniaOptions: { spacesState: { spaces }, capabilityState: { capabilities } }
}
}
)
}
| owncloud/web/packages/web-pkg/tests/unit/composables/folderLink/useFolderLink.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/folderLink/useFolderLink.spec.ts",
"repo_id": "owncloud",
"token_count": 1488
} | 852 |
import { useSpaceHelpers } from '../../../../src/composables/spaces'
import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers'
describe('useSpaceHelpers', () => {
it('should be valid', () => {
expect(useSpaceHelpers).toBeDefined()
})
describe('method "checkSpaceNameModalInput"', () => {
it('should not show an error message with a valid space name', () => {
getWrapper({
setup: ({ checkSpaceNameModalInput }) => {
checkSpaceNameModalInput('Space', (value) => {
expect(value).toEqual(null)
})
}
})
})
it('should show an error message with an empty name', () => {
getWrapper({
setup: ({ checkSpaceNameModalInput }) => {
checkSpaceNameModalInput('', (value) => {
expect(value).not.toEqual(null)
})
}
})
})
it('should show an error with an name longer than 255 characters', () => {
getWrapper({
setup: ({ checkSpaceNameModalInput }) => {
checkSpaceNameModalInput('n'.repeat(256), (value) => {
expect(value).not.toEqual(null)
})
}
})
})
it.each(['/', '\\', '.', ':', '?', '*', '"', '>', '<', '|'])(
'should show an error message with a name including a special character',
(specialChar) => {
getWrapper({
setup: ({ checkSpaceNameModalInput }) => {
checkSpaceNameModalInput(specialChar, (value) => {
expect(value).not.toEqual(null)
})
}
})
}
)
})
})
function getWrapper({ setup }: { setup: (instance: ReturnType<typeof useSpaceHelpers>) => void }) {
const mocks = defaultComponentMocks()
return {
wrapper: getComposableWrapper(
() => {
const instance = useSpaceHelpers()
setup(instance)
},
{
mocks
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/spaces/useSpaceHelpers.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/spaces/useSpaceHelpers.spec.ts",
"repo_id": "owncloud",
"token_count": 843
} | 853 |
describe('statusIndicator', () => {
describe('getIndicators', () => {
it.todo(
'should replace "=" to "" from the resource id if present and set the value as the indicator id'
)
describe('user share indicator', () => {
it.todo('should set "visible" as true if the resource is a user share')
it.todo('should set "visible" as false if the resource is not a user share')
it.todo('should set "type" as true if the resource is a direct user share')
it.todo('should set "type" as false if the resource is not a direct user share')
it.todo(
'should set "accessibleDescription" with direct share information if the resource is a direct user share'
)
it.todo(
'should set "accessibleDescription" with parent share information if the resource is not a direct user share'
)
it.todo('should set "handler" as "indicatorHandler"')
})
describe('link share indicator', () => {
it.todo('should set "visible" as true if the resource is a link share')
it.todo('should set "visible" as false if the resource is not a link share')
it.todo('should set "type" as true if the resource is a direct link share')
it.todo('should set "type" as false if the resource is not a direct link share')
it.todo(
'should set "accessibleDescription" with direct share information if the resource is a direct link share'
)
it.todo(
'should set "accessibleDescription" with parent share information if the resource is not a direct link share'
)
it.todo('should set "handler" as "indicatorHandler"')
})
})
})
| owncloud/web/packages/web-pkg/tests/unit/helpers/statusIndicator.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/statusIndicator.spec.ts",
"repo_id": "owncloud",
"token_count": 553
} | 854 |
{
"ignores": [
"web-runtime",
"easygettext",
"webfontloader",
"vue-inline-svg"
]
}
| owncloud/web/packages/web-runtime/.depcheckrc/0 | {
"file_path": "owncloud/web/packages/web-runtime/.depcheckrc",
"repo_id": "owncloud",
"token_count": 54
} | 855 |
<template>
<nav
id="applications-menu"
:aria-label="$gettext('Main navigation')"
class="oc-flex oc-flex-middle"
>
<oc-button
id="_appSwitcherButton"
ref="menubutton"
v-oc-tooltip="applicationSwitcherLabel"
appearance="raw-inverse"
variation="brand"
class="oc-topbar-menu-burger"
:aria-label="applicationSwitcherLabel"
>
<oc-icon name="grid" size="large" class="oc-flex" />
</oc-button>
<oc-drop
ref="menu"
drop-id="app-switcher-dropdown"
toggle="#_appSwitcherButton"
mode="click"
padding-size="small"
close-on-click
@show-drop="updateAppIcons"
>
<div class="oc-display-block oc-position-relative">
<oc-list class="applications-list">
<li v-for="(n, nid) in applicationsList" :key="`apps-menu-${nid}`">
<oc-button
:key="n.url ? 'apps-menu-external-link' : 'apps-menu-internal-link'"
:appearance="n.active ? 'raw-inverse' : 'raw'"
:variation="n.active ? 'primary' : 'passive'"
:class="{ 'oc-background-primary-gradient router-link-active': n.active }"
:data-test-id="n.id"
v-bind="getAdditionalAttributes(n)"
v-on="getAdditionalEventBindings(n)"
>
<oc-application-icon
:key="`apps-menu-icon-${nid}-${appIconKey}`"
:icon="n.icon"
:color-primary="n.color"
/>
<span v-text="$gettext(n.title)" />
</oc-button>
</li>
</oc-list>
</div>
</oc-drop>
</nav>
</template>
<script lang="ts">
import { defineComponent, PropType, ComponentPublicInstance, ref, computed, unref } from 'vue'
import { OcDrop } from 'design-system/src/components'
import OcApplicationIcon from 'design-system/src/components/OcApplicationIcon/OcApplicationIcon.vue'
import { useGettext } from 'vue3-gettext'
import * as uuid from 'uuid'
import {
ApplicationInformation,
EDITOR_MODE_EDIT,
resolveFileNameDuplicate,
useAppsStore,
useClientService,
useFileActions,
useGetMatchingSpace,
useResourcesStore,
useSpacesStore
} from '@ownclouders/web-pkg'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import { storeToRefs } from 'pinia'
export default defineComponent({
components: {
OcApplicationIcon
},
props: {
applicationsList: {
type: Array as PropType<any[]>,
required: false,
default: () => []
}
},
setup() {
const { openEditor } = useFileActions()
const clientService = useClientService()
const { $gettext } = useGettext()
const appIconKey = ref('')
const { getMatchingSpace } = useGetMatchingSpace()
const spacesStore = useSpacesStore()
const appsStore = useAppsStore()
const resourcesStore = useResourcesStore()
const { resources, currentFolder } = storeToRefs(resourcesStore)
const applicationSwitcherLabel = computed(() => {
return $gettext('Application Switcher')
})
const updateAppIcons = () => {
appIconKey.value = uuid.v4().replaceAll('-', '')
}
const onEditorApplicationClick = async (item: ApplicationInformation) => {
let destinationSpace = unref(currentFolder) ? getMatchingSpace(unref(currentFolder)) : null
let destinationFiles = unref(resources)
let filePath = unref(currentFolder)?.path
if (!destinationSpace || !unref(currentFolder).canCreate()) {
destinationSpace = spacesStore.personalSpace
destinationFiles = (await clientService.webdav.listFiles(destinationSpace)).children
filePath = ''
}
let fileName = $gettext('New file') + `.${item.defaultExtension}`
if (destinationFiles.some((f) => f.name === fileName)) {
fileName = resolveFileNameDuplicate(fileName, item.defaultExtension, destinationFiles)
}
const emptyResource = await clientService.webdav.putFileContents(destinationSpace, {
path: urlJoin(filePath, fileName)
})
const space = getMatchingSpace(emptyResource)
const appFileExtension = appsStore.fileExtensions.find(
({ app, extension }) => app === item.id && extension === item.defaultExtension
)
openEditor(appFileExtension, space, emptyResource, EDITOR_MODE_EDIT, space.shareId)
}
const getAdditionalEventBindings = (item: ApplicationInformation) => {
if (item.applicationMenu?.openAsEditor) {
return {
click: () => onEditorApplicationClick(item)
}
}
return {}
}
const getAdditionalAttributes = (item: any) => {
if (item.applicationMenu?.openAsEditor) {
return {}
}
return {
type: item.url ? 'a' : 'router-link',
target: item.target,
href: item.url,
to: item.path
}
}
return {
appIconKey,
updateAppIcons,
applicationSwitcherLabel,
getAdditionalAttributes,
getAdditionalEventBindings
}
},
mounted() {
;(this.$refs.menu as InstanceType<typeof OcDrop>)?.tippy?.setProps({
onHidden: () => (this.$refs.menubutton as ComponentPublicInstance).$el.focus(),
onShown: () =>
(this.$refs.menu as ComponentPublicInstance).$el.querySelector('a:first-of-type').focus()
})
}
})
</script>
<style lang="scss" scoped>
.oc-drop {
width: 280px;
}
.applications-list li {
margin: var(--oc-space-xsmall) 0;
&:first-child {
margin-top: 0;
}
&:last-child {
margin-bottom: 0;
}
a,
button {
padding: 5px;
border-radius: 8px;
gap: var(--oc-space-medium);
justify-content: flex-start;
width: 100%;
&.oc-button-primary-raw-inverse {
&:focus,
&:hover {
color: var(--oc-color-swatch-primary-contrast) !important;
}
}
&.oc-button-passive-raw {
&:focus,
&:hover {
color: var(--oc-color-swatch-passive-default) !important;
}
}
&:focus {
text-decoration: none;
}
&:hover {
background-color: var(--oc-color-background-hover);
text-decoration: none;
}
.icon-box {
display: inline-flex;
justify-content: center;
align-items: center;
width: 40px;
height: 40px;
}
.active-check {
position: absolute;
right: 1rem;
}
}
}
</style>
| owncloud/web/packages/web-runtime/src/components/Topbar/ApplicationsMenu.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/components/Topbar/ApplicationsMenu.vue",
"repo_id": "owncloud",
"token_count": 2719
} | 856 |
import { Router } from 'vue-router'
import { NextApplication } from './next'
import { convertClassicApplication } from './classic'
import { RuntimeError, ConfigStore } from '@ownclouders/web-pkg'
import { applicationStore } from '../store'
import { isObject } from 'lodash-es'
import type { Language } from 'vue3-gettext'
// import modules to provide them to applications
import * as vue from 'vue' // eslint-disable-line
import * as luxon from 'luxon' // eslint-disable-line
import * as vueGettext from 'vue3-gettext' // eslint-disable-line
import * as pinia from 'pinia' // eslint-disable-line
import * as webPkg from '@ownclouders/web-pkg'
import * as webClient from '@ownclouders/web-client'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import { App } from 'vue'
import { AppConfigObject, ClassicApplicationScript } from '@ownclouders/web-pkg'
export { NextApplication } from './next'
// shim requirejs, trust me it's there... :
const { requirejs, define } = window as any
// register modules with requirejs to provide them to applications
// keep in sync with packages/extension-sdk/index.mjs
const injectionMap = {
luxon,
pinia,
vue,
'vue3-gettext': vueGettext,
'@ownclouders/web-pkg': webPkg,
'@ownclouders/web-client': webClient,
'web-pkg': webPkg,
'web-client': webClient
}
for (const [key, value] of Object.entries(injectionMap)) {
define(key, () => value)
}
const loadScriptDynamicImport = async <T>(moduleUri: string) => {
return ((await import(/* @vite-ignore */ moduleUri)) as any).default as T
}
const loadScriptRequireJS = <T>(moduleUri: string) => {
return new Promise<T>((resolve, reject) =>
requirejs(
[moduleUri],
(app) => resolve(app),
(err) => reject(err)
)
)
}
/**
* sniffs arguments and decides if given manifest is of next or current application style.
*
* @param args
*/
export const buildApplication = async ({
app,
applicationPath,
applicationConfig,
router,
gettext,
supportedLanguages,
configStore
}: {
app: App
applicationPath: string
applicationConfig: AppConfigObject
router: Router
gettext: Language
supportedLanguages: { [key: string]: string }
configStore: ConfigStore
}): Promise<NextApplication> => {
if (applicationStore.has(applicationPath)) {
throw new RuntimeError('application already announced', applicationPath)
}
let applicationScript: ClassicApplicationScript
try {
if (applicationPath.includes('/')) {
if (
!applicationPath.startsWith('http://') &&
!applicationPath.startsWith('https://') &&
!applicationPath.startsWith('//')
) {
applicationPath = urlJoin(configStore.serverUrl, applicationPath)
}
if (applicationPath.endsWith('.mjs') || applicationPath.endsWith('.ts')) {
applicationScript = await loadScriptDynamicImport<ClassicApplicationScript>(applicationPath)
} else {
applicationScript = await loadScriptRequireJS<ClassicApplicationScript>(applicationPath)
}
} else {
const productionModule = window.WEB_APPS_MAP?.[applicationPath]
if (productionModule) {
applicationScript =
await loadScriptDynamicImport<ClassicApplicationScript>(productionModule)
} else {
throw new RuntimeError(
'cannot load application as only a name (and no path) is given and that name is not known to the application import map'
)
}
}
} catch (e) {
console.trace(e)
throw new RuntimeError('cannot load application', applicationPath, e)
}
let application: NextApplication
try {
/** add valuable sniffer to detect next applications, then implement next application factory */
if (!isObject(applicationScript.appInfo) && !applicationScript.setup) {
throw new RuntimeError('next applications not implemented yet, stay tuned')
} else {
application = convertClassicApplication({
app,
applicationScript,
applicationConfig,
router,
gettext,
supportedLanguages
})
}
} catch (err) {
throw new RuntimeError('cannot create application', err.message, applicationPath)
}
applicationStore.set(applicationPath, application)
return application
}
| owncloud/web/packages/web-runtime/src/container/application/index.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/container/application/index.ts",
"repo_id": "owncloud",
"token_count": 1417
} | 857 |
import { isEqual } from 'lodash-es'
import defaultTheme from '../../themes/owncloud/theme.json'
import { v4 as uuidV4 } from 'uuid'
import { ThemingConfig } from '@ownclouders/web-pkg'
export const loadTheme = async (location = '') => {
const defaultOwnCloudTheme = {
defaults: {
...defaultTheme.clients.web.defaults,
common: defaultTheme.common
},
themes: defaultTheme.clients.web.themes
}
if (location.split('.').pop() !== 'json') {
if (isEqual(process.env.NODE_ENV, 'development')) {
console.info(`Theme '${location}' does not specify a json file, using default theme.`)
}
return defaultOwnCloudTheme
}
try {
const response = await fetch(location, { headers: { 'X-Request-ID': uuidV4() } })
if (!response.ok) {
console.error(`Failed to load theme '${location}', invalid response. Using default theme.`)
return defaultOwnCloudTheme
}
const theme = await response.json()
try {
const parsedTheme = ThemingConfig.parse(theme)
return {
defaults: {
common: parsedTheme.common,
...parsedTheme.clients.web.defaults
},
themes: parsedTheme.clients.web.themes
}
} catch (error) {
console.error(
`Failed to load theme '${location}', invalid theme. Using default theme.`,
error
)
return defaultOwnCloudTheme
}
} catch (e) {
console.error(`Failed to load theme '${location}', using default theme.`)
return defaultOwnCloudTheme
}
}
| owncloud/web/packages/web-runtime/src/helpers/theme.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/helpers/theme.ts",
"repo_id": "owncloud",
"token_count": 590
} | 858 |
import qs from 'qs'
import AccessDeniedPage from '../pages/accessDenied.vue'
import Account from '../pages/account.vue'
import LoginPage from '../pages/login.vue'
import LogoutPage from '../pages/logout.vue'
import OidcCallbackPage from '../pages/oidcCallback.vue'
import ResolvePublicLinkPage from '../pages/resolvePublicLink.vue'
import ResolvePrivateLinkPage from '../pages/resolvePrivateLink.vue'
import { setupAuthGuard } from './setupAuthGuard'
import { patchRouter } from './patchCleanPath'
import {
createWebHashHistory,
createWebHistory,
createRouter,
RouteLocationNormalizedLoaded
} from 'vue-router'
export * from './helpers'
export { createRouter } from 'vue-router'
// just a dummy function to trick gettext tools
function $gettext(msg) {
return msg
}
export const base = document.querySelector('base')
const routes = [
{
path: '/login',
name: 'login',
component: LoginPage,
meta: { title: $gettext('Login'), authContext: 'anonymous' }
},
{
path: '/logout',
name: 'logout',
component: LogoutPage,
meta: { title: $gettext('Logout'), authContext: 'anonymous' }
},
{
path: '/web-oidc-callback',
name: 'oidcCallback',
component: OidcCallbackPage,
meta: { title: $gettext('Oidc callback'), authContext: 'anonymous' }
},
{
path: '/web-oidc-silent-redirect',
name: 'oidcSilentRedirect',
component: OidcCallbackPage,
meta: { title: $gettext('Oidc redirect'), authContext: 'anonymous' }
},
{
path: '/f/:fileId',
name: 'resolvePrivateLink',
component: ResolvePrivateLinkPage,
meta: { title: $gettext('Private link'), authContext: 'user' }
},
{
path: '/s/:token/:driveAliasAndItem(.*)?',
name: 'resolvePublicLink',
component: ResolvePublicLinkPage,
meta: { title: $gettext('Public link'), authContext: 'anonymous' }
},
{
path: '/o/:token/:driveAliasAndItem(.*)?',
name: 'resolvePublicOcmLink',
component: ResolvePublicLinkPage,
meta: { title: $gettext('OCM link'), authContext: 'anonymous' }
},
{
path: '/access-denied',
name: 'accessDenied',
component: AccessDeniedPage,
meta: { title: $gettext('Access denied'), authContext: 'anonymous' }
},
{
path: '/account',
name: 'account',
component: Account,
meta: { title: $gettext('Account'), authContext: 'hybrid' }
}
]
export const router = patchRouter(
createRouter({
parseQuery(query) {
return qs.parse(query, {
allowDots: true
})
},
stringifyQuery(obj) {
return qs.stringify(obj, {
allowDots: true
})
},
history: (base && createWebHistory(new URL(base.href).pathname)) || createWebHashHistory(),
routes
})
)
export const isRuntimeRoute = (route: RouteLocationNormalizedLoaded) => {
return routes.map((r) => r.name).includes(route.name.toString())
}
setupAuthGuard(router)
| owncloud/web/packages/web-runtime/src/router/index.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/router/index.ts",
"repo_id": "owncloud",
"token_count": 1078
} | 859 |
import SidebarNav from 'web-runtime/src/components/SidebarNav/SidebarNav.vue'
import sidebarNavItemFixtures from '../../../__fixtures__/sidebarNavItems'
import { defaultPlugins, mount } from 'web-test-helpers'
vi.mock('uuid', () => ({
v4: () => {
return '00000000-0000-0000-0000-000000000000'
}
}))
const slots = {
bottom: '<span class="footer">Footer</span>'
}
describe('OcSidebarNav', () => {
it('displays a bottom slot if given', () => {
const { wrapper } = getWrapper()
expect(wrapper.findAll('.footer').length).toBe(1)
})
it('renders navItems into a list', () => {
const { wrapper } = getWrapper()
expect(wrapper.html()).toMatchSnapshot()
})
it('expands the navbar in open state', () => {
const { wrapper } = getWrapper({ closed: false })
expect(wrapper.find('.oc-app-navigation-expanded').exists).toBeTruthy()
})
it('collapses the navbar in closed state', () => {
const { wrapper } = getWrapper({ closed: true })
expect(wrapper.find('.oc-app-navigation-collapsed').exists).toBeTruthy()
})
it('emits "update:nav-bar-closed" upon button click', async () => {
const { wrapper } = getWrapper()
await wrapper.find('.toggle-sidebar-button').trigger('click')
expect(wrapper.emitted('update:nav-bar-closed').length).toBeGreaterThan(0)
})
it('initially sets the highlighter to the active nav item', async () => {
const { wrapper } = getWrapper()
await wrapper.vm.$nextTick()
expect(wrapper.vm.highlighterAttrs).toEqual({
style: {
transform: 'translateY(0px)',
'transition-duration': '0.2s'
}
})
})
})
function getWrapper({ closed = false } = {}) {
return {
wrapper: mount(SidebarNav, {
slots,
props: {
navItems: sidebarNavItemFixtures,
closed
},
global: {
renderStubDefaultSlot: true,
plugins: [...defaultPlugins()],
stubs: { SidebarNavItem: true }
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/components/SidebarNav/SidebarNav.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/SidebarNav/SidebarNav.spec.ts",
"repo_id": "owncloud",
"token_count": 763
} | 860 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`ThemeSwitcher component > restores > dark theme if dark theme is saved in localstorage 1`] = `
"<div>
<oc-select-stub clearable="false" option-label="name" model-value="[object Object]" options="[object Object],[object Object],[object Object]"></oc-select-stub>
</div>"
`;
exports[`ThemeSwitcher component > restores > light theme if light theme is saved in localstorage 1`] = `
"<div>
<oc-select-stub model-value="[object Object]" clearable="false" option-label="name" options="[object Object],[object Object],[object Object]"></oc-select-stub>
</div>"
`;
| owncloud/web/packages/web-runtime/tests/unit/components/Topbar/__snapshots__/ThemeSwitcher.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Topbar/__snapshots__/ThemeSwitcher.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 199
} | 861 |
import { getAbilities } from 'web-runtime/src/services/auth/abilities'
describe('getAbilities', () => {
it('gets no abilities if empty permissions given', () => {
const abilities = getAbilities([])
expect(abilities.length).toBe(0)
})
it('gets correct abilities for subject "Account"', function () {
const abilities = getAbilities(['Accounts.ReadWrite.all'])
const expectedActions = ['create-all', 'delete-all', 'read-all', 'update-all']
expect(abilities).toEqual(expectedActions.map((action) => ({ action, subject: 'Account' })))
})
it('gets correct abilities for subject "Group"', function () {
const abilities = getAbilities(['Groups.ReadWrite.all'])
const expectedActions = ['create-all', 'delete-all', 'read-all', 'update-all']
expect(abilities).toEqual(expectedActions.map((action) => ({ action, subject: 'Group' })))
})
it.each([
{ permissions: [''], expectedActions: [] },
{ permissions: ['Favorites.List.own'], expectedActions: ['read'] },
{ permissions: ['Favorites.Write.own'], expectedActions: ['create', 'update'] }
])('gets correct abilities for subject "Favorites"', function (data) {
const abilities = getAbilities(data.permissions)
const expectedResult = data.expectedActions.map((action) => ({ action, subject: 'Favorite' }))
expect(abilities).toEqual(expectedResult)
})
it('gets correct abilities for subject "Language"', function () {
const abilities = getAbilities(['Language.ReadWrite.all'])
const expectedActions = ['read-all', 'update-all']
expect(abilities).toEqual(expectedActions.map((action) => ({ action, subject: 'Language' })))
})
it('gets correct abilities for subject "Logo"', function () {
const abilities = getAbilities(['Logo.Write.all'])
const expectedActions = ['update-all']
expect(abilities).toEqual(expectedActions.map((action) => ({ action, subject: 'Logo' })))
})
it('gets correct abilities for subject "Role"', function () {
const abilities = getAbilities(['Roles.ReadWrite.all'])
const expectedActions = ['create-all', 'delete-all', 'read-all', 'update-all']
expect(abilities).toEqual(expectedActions.map((action) => ({ action, subject: 'Role' })))
})
it('gets correct abilities for subject "PublicLink"', function () {
const abilities = getAbilities(['PublicLink.Write.all'])
const expectedActions = ['create-all']
expect(abilities).toEqual(expectedActions.map((action) => ({ action, subject: 'PublicLink' })))
})
it('gets correct abilities for subject "Share"', function () {
const abilities = getAbilities(['Shares.Write.all'])
const expectedActions = ['create-all', 'update-all']
expect(abilities).toEqual(expectedActions.map((action) => ({ action, subject: 'Share' })))
})
it('gets correct abilities for subject "Setting"', function () {
const abilities = getAbilities(['Settings.ReadWrite.all'])
const expectedActions = ['read-all', 'update-all']
expect(abilities).toEqual(expectedActions.map((action) => ({ action, subject: 'Setting' })))
})
it.each([
{ permissions: [''], expectedActions: [] },
{ permissions: ['Drives.Create.all'], expectedActions: ['create-all'] },
{ permissions: ['Drives.List.all'], expectedActions: ['read-all'] },
{ permissions: ['Drives.ReadWriteEnabled.all'], expectedActions: ['delete-all', 'update-all'] },
{ permissions: ['Drives.ReadWriteProjectQuota.all'], expectedActions: ['set-quota-all'] }
])('gets correct abilities for subject "Drive"', function (data) {
const abilities = getAbilities(data.permissions)
const expectedResult = data.expectedActions.map((action) => ({ action, subject: 'Drive' }))
expect(abilities).toEqual(expectedResult)
})
})
| owncloud/web/packages/web-runtime/tests/unit/services/auth/abilities.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/services/auth/abilities.spec.ts",
"repo_id": "owncloud",
"token_count": 1199
} | 862 |
import { createTestingPinia } from '@pinia/testing'
import defaultTheme from '../../../web-runtime/themes/owncloud/theme.json'
import { User, Group } from '../../../web-client/src/generated'
import { Message, Modal, WebThemeType } from '../../../web-pkg/src/composables/piniaStores'
import { Capabilities } from '../../../web-client/src/ocs'
import { mock } from 'vitest-mock-extended'
import { SpaceResource } from '../../../web-client/src'
import { OptionsConfig } from '../../../web-pkg/src/composables/piniaStores/config/types'
import { Resource, CollaboratorShare, LinkShare, ShareRole } from '../../../web-client/src/helpers'
import {
AncestorMetaData,
ApplicationFileExtension,
ClipboardActions
} from '../../../web-pkg/types'
export { createTestingPinia }
export type PiniaMockOptions = {
stubActions?: boolean
appsState?: { fileExtensions?: ApplicationFileExtension[] }
authState?: {
accessToken?: string
idpContextReady?: boolean
userContextReady?: boolean
publicLinkContextReady?: boolean
}
themeState?: { availableThemes?: WebThemeType[]; currentTheme?: WebThemeType }
clipboardState?: { action?: ClipboardActions; resources?: Resource[] }
configState?: {
server?: string
options?: OptionsConfig
}
messagesState?: { messages?: Message[] }
modalsState?: { modals?: Modal[] }
spaceSettingsStore?: {
spaces?: SpaceResource[]
selectedSpaces?: SpaceResource[]
}
groupSettingsStore?: {
groups?: Group[]
selectedGroups?: Group[]
}
userSettingsStore?: {
users?: User[]
selectedUsers?: User[]
}
resourcesStore?: {
resources?: Resource[]
currentFolder?: Resource
ancestorMetaData?: AncestorMetaData
selectedIds?: string[]
areFileExtensionsShown?: boolean
}
sharesState?: {
collaboratorShares?: CollaboratorShare[]
linkShares?: LinkShare[]
graphRoles?: ShareRole[]
loading?: boolean
}
spacesState?: { spaces?: SpaceResource[]; spaceMembers?: CollaboratorShare[] }
userState?: { user?: User }
capabilityState?: {
capabilities?: Partial<Capabilities['capabilities']>
isInitialized?: boolean
}
}
export function createMockStore({
stubActions = true,
appsState = {},
authState = {},
clipboardState = {},
configState = {},
themeState = {},
messagesState = {},
modalsState = {},
resourcesStore = {},
userSettingsStore = {},
groupSettingsStore = {},
spaceSettingsStore = {},
sharesState = {},
spacesState = {},
userState = {},
capabilityState = {}
}: PiniaMockOptions = {}) {
const defaultOwnCloudTheme = {
defaults: {
...defaultTheme.clients.web.defaults,
common: {
...defaultTheme.common,
urls: ['https://imprint.url.theme', 'https://privacy.url.theme']
}
},
themes: defaultTheme.clients.web.themes
}
return createTestingPinia({
stubActions,
initialState: {
apps: { ...appsState },
auth: { ...authState },
clipboard: { resources: [], ...clipboardState },
config: {
apps: [],
external_apps: [],
customTranslations: [],
oAuth2: {},
openIdConnect: {},
options: {},
server: '',
...configState
},
messages: { messages: [], ...messagesState },
modals: {
modals: [],
...modalsState
},
theme: {
currentTheme: {
...defaultOwnCloudTheme.defaults,
...defaultOwnCloudTheme.themes[0]
},
availableThemes: defaultOwnCloudTheme.themes,
...themeState
},
resources: { resources: [], ...resourcesStore },
shares: { collaboratorShares: [], linkShares: [], ...sharesState },
spaces: { spaces: [], spaceMembers: [], ...spacesState },
userSettings: { users: [], selectedUsers: [], ...userSettingsStore },
groupSettings: { groups: [], selectedGroups: [], ...groupSettingsStore },
spaceSettings: { spaces: [], selectedSpaces: [], ...spaceSettingsStore },
user: { user: { ...mock<User>({ id: '1' }), ...(userState?.user && { ...userState.user }) } },
capabilities: {
isInitialized: capabilityState?.isInitialized ? capabilityState.isInitialized : true,
capabilities: {
...mock<Capabilities['capabilities']>(),
...(capabilityState?.capabilities && { ...capabilityState.capabilities })
}
}
}
})
}
| owncloud/web/packages/web-test-helpers/src/mocks/pinia.ts/0 | {
"file_path": "owncloud/web/packages/web-test-helpers/src/mocks/pinia.ts",
"repo_id": "owncloud",
"token_count": 1588
} | 863 |
exports.command = function () {
this.execute(function () {
window.sumStartedAjaxRequests = 0
window.activeAjaxCount = 0
function isAllXhrComplete() {
window.activeAjaxCount--
}
;(function (open) {
XMLHttpRequest.prototype.open = function () {
this.addEventListener('loadend', isAllXhrComplete)
return open.apply(this, arguments)
}
})(XMLHttpRequest.prototype.open)
})
this.execute(function () {
;(function (send) {
XMLHttpRequest.prototype.send = function () {
window.activeAjaxCount++
window.sumStartedAjaxRequests++
return send.apply(this, arguments)
}
})(XMLHttpRequest.prototype.send)
})
this.execute(function () {
;(function (wrappedFetch) {
window.fetch = function () {
window.activeAjaxCount++
window.sumStartedAjaxRequests++
const fetchResult = wrappedFetch.apply(this, arguments)
fetchResult.then(function () {
window.activeAjaxCount--
})
fetchResult.catch(function () {
window.activeAjaxCount--
})
return fetchResult
}
})(window.fetch)
})
return this
}
| owncloud/web/tests/acceptance/customCommands/initAjaxCounters.js/0 | {
"file_path": "owncloud/web/tests/acceptance/customCommands/initAjaxCounters.js",
"repo_id": "owncloud",
"token_count": 503
} | 864 |
Feature: copy files and folders
As a user
I want to copy files and folders
So that I can work safely on a copy without changing the original
Background:
Given the administrator has set the default folder for received shares to "Shares" in the server
And user "Alice" has been created with default attributes and without skeleton files in the server
Scenario Outline: copy a file into a folder (problematic characters)
Given user "Alice" has uploaded file "lorem.txt" to "lorem.txt" in the server
And user "Alice" has created folder "simple-empty-folder" in the server
And user "Alice" has logged in using the webUI
And the user has browsed to the personal page
When the user renames file "lorem.txt" to <file_name> using the webUI
And the user renames folder "simple-empty-folder" to <folder_name> using the webUI
And the user copies file <file_name> into folder <folder_name> using the webUI
Then breadcrumb for folder <folder_name> should be displayed on the webUI
And file <file_name> should be listed on the webUI
Examples:
| file_name | folder_name |
| "'single'" | "folder-with-'single'" |
| "\"double\" quotes" | "folder-with\"double\" quotes" |
| "question?" | "folder-with-question?" |
| "&and#hash" | "folder-with-&and#hash" |
@issue-3755
Scenario: copy files on a public share
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created folder "simple-folder/simple-empty-folder" in the server
And user "Alice" has uploaded file "data.zip" to "simple-folder/data.zip" in the server
And user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions in the server
When the public uses the webUI to access the last public link created by user "Alice" in a new session
And the user copies file "data.zip" into folder "simple-empty-folder" using the webUI
Then breadcrumb for folder "simple-empty-folder" should be displayed on the webUI
And file "data.zip" should be listed on the webUI
And as "Alice" file "simple-folder/simple-empty-folder/data.zip" should exist in the server
And as "Alice" file "simple-folder/data.zip" should exist in the server
| owncloud/web/tests/acceptance/features/webUIFilesCopy/copy.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUIFilesCopy/copy.feature",
"repo_id": "owncloud",
"token_count": 762
} | 865 |
@public_link_share-feature-required
Feature: Edit public link shares
As a user
I want to edit public share
So that I can manage the the shares
Background:
Given user "Alice" has been created with default attributes and without skeleton files in the server
Scenario: user edits a name of an already existing public link
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has logged in using the webUI
And user "Alice" has created a public link with following settings in the server
| path | simple-folder |
| name | Public-link |
| permissions | read |
| password | #Passw0rd |
When the user renames the public link named "Public-link" of folder "simple-folder" to "simple-folder Share"
And the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session
Then file "lorem.txt" should be listed on the webUI
Scenario: user edits the password of an already existing public link
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | simple-folder |
| name | Public-link |
| permissions | read, update, create, delete |
| password | #Passw0rd |
And user "Alice" has logged in using the webUI
When the user tries to edit the public link named "Public-link" of folder "simple-folder" changing the password to "#Passw0rd123"
And the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd123" in a new session
Then file "lorem.txt" should be listed on the webUI
@issue-3830
Scenario: user edits the password of an already existing public link and tries to access with old password
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions and password "#Passw0rd" in the server
And user "Alice" has created a public link with following settings in the server
| path | simple-folder |
| name | Public-link |
| permissions | read, update, create, delete |
| password | #Passw0rd |
And user "Alice" has logged in using the webUI
When the user tries to edit the public link named "Public-link" of folder "simple-folder" changing the password to "#Passw0rd123"
And the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session
Then the public should not get access to the publicly shared file
@issue-ocis-reva-292
Scenario: user edits the permission of an already existing public link from read-write to read
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | simple-folder |
| name | Public-link |
| permissions | read, update, create, delete |
And user "Alice" has logged in using the webUI
When the user tries to edit the public link named "Public-link" of folder "simple-folder" changing the role to "Viewer"
And the public uses the webUI to access the last public link created by user "Alice" in a new session
Then file "lorem.txt" should be listed on the webUI
And it should not be possible to delete file "lorem.txt" using the webUI
@issue-ocis-reva-292 @disablePreviews
Scenario: user edits the permission of an already existing public link from read to read-write
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created folder "simple-folder/simple-empty-folder" in the server
And user "Alice" has created file "simple-folder/lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | simple-folder |
| name | Public-link |
| permissions | read |
And user "Alice" has logged in using the webUI
When the user tries to edit the public link named "Public-link" of folder "simple-folder" changing the role to "Editor"
And the public uses the webUI to access the last public link created by user "Alice" in a new session
And the user deletes the following elements using the webUI
| name |
| simple-empty-folder |
And the user deletes the following elements using the webUI
| name-parts |
| lorem.txt |
Then the deleted elements should not be listed on the webUI
And the deleted elements should not be listed on the webUI after a page reload
@issue-ocis-reva-389
Scenario: user removes the public link of a file using webUI
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has logged in using the webUI
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | Public-link |
| permissions | read |
When the user removes the public link named "Public-link" of file "lorem.txt" using the webUI
Then user "Alice" should not have any public link in the server
Scenario: user edits the permission of an already existing public link from read-write to read-create
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created file "simple-folder/simple.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | simple-folder |
| name | Public-link |
| permissions | read, update, create, delete |
And user "Alice" has logged in using the webUI
When the user tries to edit the public link named "Public-link" of folder "simple-folder" changing the role to "Contributor"
And the public uses the webUI to access the last public link created by user "Alice" in a new session
And the user uploads file "lorem.txt" using the webUI
Then file "simple.txt" should be listed on the webUI
And file "lorem.txt" should be listed on the webUI
@skipOnOC10
Scenario: assign password to already created public share
Given user "Alice" has created file "lorem.txt" in the server
And user "Alice" has created a public link with following settings in the server
| path | lorem.txt |
| name | Public-link |
And user "Alice" has logged in using the webUI
When the user tries to edit the public link named "Public-link" of folder "lorem.txt" adding a password "#Password123"
And the public uses the webUI to access the last public link created by user "Alice" with password "#Password123" in a new session
And the user closes the text editor using the webUI
Then file "lorem.txt" should be listed on the webUI as single share
| owncloud/web/tests/acceptance/features/webUISharingPublicBasic/publicLinkEdit.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUISharingPublicBasic/publicLinkEdit.feature",
"repo_id": "owncloud",
"token_count": 2402
} | 866 |
const userSettings = require('../helpers/userSettings')
const _ = require('lodash')
const fetch = require('node-fetch')
const { join } = require('./path')
const backendHelper = require('../helpers/backendHelper')
/**
*
* @param {string} userId
*
* @returns {{Authorization: string}}
*/
const createAuthHeader = function (userId) {
const password = userSettings.getPasswordForUser(userId)
return {
Authorization: 'Basic ' + Buffer.from(userId + ':' + password).toString('base64')
}
}
/**
*
* @param {string} userId
*
* @returns {{<header>: string}}
*/
const createOCSRequestHeaders = function (userId) {
return {
...createAuthHeader(userId),
'OCS-APIREQUEST': true
}
}
/**
*
* @param {node-fetch.Response} response
* @param {string} message
*
* @throws Error
* @returns {node-fetch.Response}
*/
const checkStatus = function (response, message = '') {
if (response.ok) {
// response.status >= 200 && response.status < 300
return response
} else {
throw Error(
`HTTP Request Failed: ${message}, Status: ${response.status} ${response.statusCode}`
)
}
}
/**
*
* @param {Object} response the response body in json
* @param {string} message
*
* @throws Error
* @returns {Object} the body of the response
*/
const checkOCSStatus = function (response, message = '') {
const statusCode = _.get(response, 'ocs.meta.statuscode')
const ocsMessage = _.get(response, 'ocs.meta.message')
if (statusCode === 200) {
return response
} else {
throw Error(`OCS Request Failed: ${message}, Status: ${statusCode}, Message: ${ocsMessage}`)
}
}
/**
*
* @param {string} path
* @param {object} params
* @param {string} userId
* @param {object} header
*
* @returns {node-fetch}
*/
const requestEndpoint = function (path, params, userId = 'admin', header = {}) {
const headers = { ...createAuthHeader(userId), ...header }
const options = { ...params, headers }
const url = join(backendHelper.getCurrentBackendUrl(), 'remote.php/dav', path)
return fetch(url, options)
}
/**
*
* @param {string} path
* @param {object} params
* @param {string} userId
* @param {object} header
*
* @returns {node-fetch}
*/
const requestOCSEndpoint = function (path, params, userId = 'admin', header = {}) {
const headers = { ...createOCSRequestHeaders(userId), ...header }
const options = { ...params, headers }
const separator = path.includes('?') ? '&' : '?'
const url = join(
backendHelper.getCurrentBackendUrl(),
'ocs/v2.php',
path + separator + 'format=json'
)
return fetch(url, options)
}
module.exports = {
checkStatus,
checkOCSStatus,
// ocs request methods
getOCS: (url, userId, body, header) =>
requestOCSEndpoint(url, { body, method: 'GET' }, userId, header),
postOCS: (url, userId, body, header) =>
requestOCSEndpoint(url, { body, method: 'POST' }, userId, header),
deleteOCS: (url, userId, body, header) =>
requestOCSEndpoint(url, { body, method: 'DELETE' }, userId, header),
propfind: (url, userId, body, header) =>
requestEndpoint(url, { body, method: 'PROPFIND' }, userId, header)
}
| owncloud/web/tests/acceptance/helpers/httpHelper.js/0 | {
"file_path": "owncloud/web/tests/acceptance/helpers/httpHelper.js",
"repo_id": "owncloud",
"token_count": 1076
} | 867 |
module.exports = {
commands: {
getSharedViaPath: async function () {
const sharedViaXpath =
this.elements.detailsTable.selector + this.elements.dataCellSharedVia.selector
let text = ''
await this.useXpath()
.waitForElementVisible(sharedViaXpath)
.getText('xpath', sharedViaXpath, function (result) {
if (typeof result.value === 'string') {
text = result.value
}
})
console.log(text)
return text
}
},
elements: {
detailsTable: {
selector: '//*[@id="oc-file-details-sidebar"]//table[contains(@class, "details-table")]',
locateStrategy: 'xpath'
},
dataCellSharedVia: {
// inside detailsTable
selector: '//tr[@data-testid="shared-via"]/td',
locateStrategy: 'xpath'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/FilesPageElement/detailsDialog.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/FilesPageElement/detailsDialog.js",
"repo_id": "owncloud",
"token_count": 367
} | 868 |
module.exports = {
url: function () {
return this.api.launchUrl
},
elements: {
body: 'body',
usernameInput: {
selector: '#user'
},
passwordInput: {
selector: '#password'
},
loginSubmitButton: {
selector: '#submit'
},
invalidCredentialsMessage: {
selector: '#lost-password'
}
},
commands: [
{
/**
*
* @param {string} username
* @param {string} password
* @param expectedToSucced
*/
login: async function (username, password, expectedToSucced = true) {
await this.waitForElementVisible('@usernameInput')
.clearValue('@usernameInput')
.setValue('@usernameInput', username)
.clearValue('@passwordInput')
.setValue('@passwordInput', password)
.click('@loginSubmitButton')
if (expectedToSucced) {
await this.waitForElementNotPresent('@usernameInput')
} else {
await this.waitForElementPresent('@usernameInput')
}
return this
},
getLoginErrorMessage: async function () {
let errorMessage
await this.api.assert.visible(this.elements.usernameInput.selector)
await this.api.assert.visible(this.elements.passwordInput.selector)
await this.api.assert.visible(this.elements.loginSubmitButton.selector)
await this.waitForElementVisible('@invalidCredentialsMessage').getText(
'@invalidCredentialsMessage',
(result) => {
errorMessage = result.value
}
)
return errorMessage
},
waitTillLoaded: async function () {
await this.waitForElementVisible(this.elements.usernameInput.selector)
await this.waitForElementVisible(this.elements.passwordInput.selector)
await this.waitForElementVisible(this.elements.loginSubmitButton.selector)
}
}
]
}
| owncloud/web/tests/acceptance/pageObjects/ownCloudLoginPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/ownCloudLoginPage.js",
"repo_id": "owncloud",
"token_count": 812
} | 869 |
/* eslint-disable no-unused-expressions */
const { client } = require('nightwatch-api')
const assert = require('assert')
const { Given, When, Then, Before } = require('@cucumber/cucumber')
const webdav = require('../helpers/webdavHelper')
const _ = require('lodash')
const loginHelper = require('../helpers/loginHelper')
const xpathHelper = require('../helpers/xpath')
const path = require('../helpers/path')
const util = require('util')
const { SHARE_STATE } = require('../helpers/sharingHelper')
const appSideBar = client.page.FilesPageElement.appSideBar()
const appBarActions = client.page.appBarActions()
let deletedElements
let unsharedElements
Before(() => {
deletedElements = []
unsharedElements = []
})
When('the user browses to the files page', () => {
return client.page.personalPage().navigateAndWaitTillLoaded()
})
When('the user browses to the favorites page', function () {
return client.page.favoritesPage().navigateAndWaitTillLoaded()
})
Given('the user has browsed to the favorites page', function () {
return client.page.favoritesPage().navigateAndWaitTillLoaded()
})
When('the user browses to the shared-with-me page', function () {
return client.page.sharedWithMePage().navigateAndWaitTillLoaded()
})
When('the user browses to the shared-with-me page in accepted shares view', function () {
return client.page.sharedWithMePage().navigateToAcceptedAndWaitUntilLoaded()
})
When('the user browses to the shared-with-me page in declined shares view', function () {
return client.page.sharedWithMePage().navigateToDeclinedAndWaitUntilLoaded()
})
Given('the user has browsed to the shared-with-me page', function () {
return client.page.sharedWithMePage().navigateAndWaitTillLoaded()
})
Given('the user has browsed to the shared-with-others page', function () {
return client.page.sharedWithOthersPage().navigateAndWaitTillLoaded()
})
Given('the user has browsed to the shared-via-link page', function () {
return client.page.sharedViaLinkPage().navigateAndWaitTillLoaded()
})
When('the user browses to the shared-with-others page', function () {
return client.page.sharedWithOthersPage().navigateAndWaitTillLoaded()
})
When('the user browses to the shared-with-others page using the webUI', async function () {
await client.page.webPage().navigateToUsingMenu('Shares')
await appBarActions.navigateToSharesSubPage('Shared with others')
return client
})
When('the user browses to the shared-via-link page using the webUI', async function () {
await client.page.webPage().navigateToUsingMenu('Shares')
await appBarActions.navigateToSharesSubPage('Shared via link')
return client
})
Given('the user has browsed to the trashbin page', function () {
return client.page.trashbinPage().navigateAndWaitTillLoaded()
})
When('the user browses to the trashbin page', function () {
return client.page.trashbinPage().navigateAndWaitTillLoaded()
})
Given('the user has browsed to the favorites page using the webUI', function () {
return client.page.webPage().navigateToUsingMenu('Favorites')
})
When('the user browses to the favorites page using the webUI', function () {
return client.page.webPage().navigateToUsingMenu('Favorites')
})
When('the user browses to the files page using the webUI', function () {
let menuItem = 'All files'
if (client.globals.ocis) {
menuItem = 'Personal'
}
return client.page.webPage().navigateToUsingMenu(menuItem)
})
Then('the files table should be displayed', () => {
return client.page.FilesPageElement.filesList().waitForElementVisible('@anyAfterLoading')
})
Given('the user has browsed to the personal page', function () {
let menuItem = 'All files'
if (client.globals.ocis) {
menuItem = 'Personal'
}
return client.page.personalPage().navigateToBreadcrumb(menuItem)
})
When('the user opens folder {string} directly on the webUI', async function (folder) {
folder = encodeURIComponent(path.normalize(folder))
await client.page.personalPage().navigateAndWaitTillLoaded(folder)
})
When(
'the user browses to display the {string} details of file {string}',
async function (accordionItem, filename) {
const api = client.page.FilesPageElement
await client.initAjaxCounters()
await api.filesList().openSideBar(filename)
await api.appSideBar().activatePanel(accordionItem)
await client.waitForOutstandingAjaxCalls()
return client
}
)
When(
'the user/public creates a folder with the name {string} using the webUI',
function (folderName) {
return client.page.personalPage().createFolder(folderName)
}
)
When('the user creates a file with the name {string} using the webUI', function (fileName) {
return client.page.personalPage().createFile(fileName)
})
When('the user creates a folder with default name using the webUI', function () {
return client.page.personalPage().createFolder(null)
})
When(
'the user tries to create a folder with the invalid name {string} using the webUI',
function (folderName) {
return client.page.personalPage().createFolder(folderName, false)
}
)
Given('the user has opened folder {string}', (folder) =>
client.page.FilesPageElement.filesList().navigateToFolder(folder)
)
When('the user opens folder {string} using the webUI', (folder) =>
client.page.FilesPageElement.filesList().navigateToFolder(folder)
)
Given('the user has opened the share dialog for file/folder {string}', function (fileName) {
return client.page.FilesPageElement.filesList().openSharingDialog(fileName)
})
When('the user closes the app-sidebar using the webUI', async function () {
return await client.page.FilesPageElement.appSideBar().closeSidebarIfOpen()
})
When('the user browses to folder {string} using the breadcrumb on the webUI', (resource) =>
client.page.personalPage().navigateToBreadcrumb(resource)
)
When('the user deletes file/folder {string} using the webUI', function (element) {
return client.page.FilesPageElement.filesList().deleteFile(element)
})
When('the user tries to delete file/folder {string} using the webUI', function (element) {
return client.page.FilesPageElement.filesList().deleteFile(element)
})
When('the user tries to delete single share {string} using the webUI', function (element) {
return client.page.FilesPageElement.filesList().deleteSingleShare(element)
})
Given('the user has deleted file/folder/resource {string} using the webUI', function (element) {
return client.page.FilesPageElement.filesList().deleteFile(element)
})
When('the user deletes the following elements using the webUI', async function (table) {
for (const line of table.rows()) {
await client.page.FilesPageElement.filesList().deleteFile(line[0])
deletedElements.push(line[0])
}
return client.page.personalPage()
})
Then('there should be no breadcrumb displayed on the webUI', function () {
return assertBreadCrumbIsNotDisplayed()
})
Then(
'non-clickable breadcrumb for folder {string} should be present on the webUI',
function (resource) {
return assertBreadcrumbIsPresentFor(resource, false, true)
}
)
Then('breadcrumb for folder {string} should be displayed on the webUI', function (resource) {
return assertBreadcrumbIsDisplayedFor(resource, true, true)
})
When('the user/public uploads file {string} using the webUI', function (element) {
const uploadPath = path.join(client.globals.mountedUploadDir, element)
return client.page.personalPage().uploadFile(uploadPath)
})
When('the user uploads a created file {string} using the webUI', function (element) {
const uploadPath = path.join(client.globals.mountedUploadDir, element)
return client.page.personalPage().uploadFile(uploadPath)
})
When(
'the user uploads a created file {string} with overwrite using the webUI',
async function (file) {
const uploadPath = path.join(client.globals.mountedUploadDir, file)
await client.page.personalPage().selectFileForUpload(uploadPath)
await client.page.personalPage().confirmFileOverwrite()
return this
}
)
When('the public uploads file/folder {string} in files-drop page', function (element) {
const rootUploadDir = client.globals.mountedUploadDir
const filePath = path.join(rootUploadDir, element)
return client.page
.filesDropPage()
.initAjaxCounters()
.uploadFile(filePath)
.waitForOutstandingAjaxCalls()
})
Then('the following files should be listed on the files-drop page:', async function (filesToCheck) {
filesToCheck = filesToCheck.raw().map(([file]) => file)
const actualFiles = await client.page.filesDropPage().getUploadedFiles()
const filesNotUploaded = _.difference(filesToCheck, actualFiles)
assert.strictEqual(
filesNotUploaded.length,
0,
'Could not find following files: \n' + filesNotUploaded
)
})
When('the user unshares file/folder {string} using the webUI', function (element) {
return client.page.FilesPageElement.filesList().declineShare(element)
})
When('the user uploads folder {string} using the webUI', function (element) {
const rootUploadDir = client.globals.mountedUploadDir
const name = path.join(rootUploadDir, element)
return client.page.personalPage().uploadFolder(name)
})
Then('it should not be possible to create files using the webUI', async function () {
const canCreate = await client.page.personalPage().canCreateFiles()
await assert.strictEqual(canCreate, true, 'Create action must not be enabled')
})
Then('the create button should not be visible on the webUI', async function () {
const canCreate = await client.page.personalPage().isCreateFolderVisible()
await assert.strictEqual(canCreate, false)
})
Then('it should be possible to create files using the webUI', async function () {
const canCreate = await client.page.personalPage().canCreateFiles()
await assert.strictEqual(canCreate, false, 'Create action must be enabled')
})
When(
'the user renames file/folder {string} to {string} using the webUI',
function (fromName, toName) {
return client.page.FilesPageElement.filesList().renameFile(fromName, toName)
}
)
When(
'the user renames single share {string} to {string} using the webUI',
function (fromName, toName) {
return client.page.FilesPageElement.filesList().renameSingleShare(fromName, toName)
}
)
Given('the user has renamed file/folder {string} to {string}', function (fromName, toName) {
return client.page.FilesPageElement.filesList().renameFile(fromName, toName)
})
When(
'the user tries to rename file/folder {string} to {string} using the webUI',
function (fromName, toName) {
return client.page.FilesPageElement.filesList().renameFile(fromName, toName, false)
}
)
When(
'the user tries to rename single share {string} to {string} using the webUI',
function (fromName, toName) {
return client.page.FilesPageElement.filesList().renameSingleShare(fromName, toName, false)
}
)
When('the user renames the following file/folder using the webUI', async function (dataTable) {
for (const { fromName, toName } of dataTable.hashes()) {
await client.page.FilesPageElement.filesList().renameFile(fromName, toName)
}
return client
})
Given('the user has marked file/folder {string} as favorite using the webUI', function (path) {
return client.page.FilesPageElement.filesList().markFavorite(path)
})
When('the user marks file/folder {string} as favorite using the webUI', function (path) {
return client.page.FilesPageElement.filesList().markFavorite(path)
})
When('the user unmarks the favorited file/folder {string} using the webUI', function (path) {
return client.page.FilesPageElement.filesList().unmarkFavorite(path)
})
When('the user marks file/folder {string} as favorite using the webUI sidebar', function (path) {
return client.page.FilesPageElement.filesList().markFavorite(path)
})
When(
'the user unmarks the favorited file/folder {string} using the webUI sidebar',
function (path) {
return client.page.FilesPageElement.filesList().unmarkFavorite(path)
}
)
Then('there should be no files/folders/resources listed on the webUI', assertNoResourcesListed)
Then(
'there should be no files/folders/resources listed on the webUI after a page reload',
async function () {
await client.refresh()
return assertNoResourcesListed()
}
)
async function assertNoResourcesListed() {
let currentUrl = null
await client.url((result) => {
currentUrl = result.value
})
// only check empty message in regular file lists, not files drop page
if (currentUrl.indexOf('/public/drop/') === -1) {
await client.page.FilesPageElement.filesList().waitForNoContentMessageVisible()
return
}
const allRowsResult = await client.page.FilesPageElement.filesList().allFileRows()
return assert.ok(
allRowsResult.value.length === 0,
`No resources are listed, ${allRowsResult.length} found`
)
}
Then('there should be a not found error page displayed on the webUI', async function () {
return await client.page.FilesPageElement.filesList().waitForNotFoundMessageVisible()
})
Then('file {string} should be listed on the webUI', (file) => {
return client.page.FilesPageElement.filesList().waitForFileVisible(file, 'file')
})
Then('folder {string} should be listed on the webUI', (folder) => {
return client.page.FilesPageElement.filesList().waitForFileVisible(folder, 'folder')
})
Then('file/folder {string} should be listed on the webUI as single share', (resource) => {
return client.page.FilesPageElement.filesList().waitForFileVisibleAsSingleShare(resource)
})
Then('file/folder with path {string} should be listed on the webUI', function (path) {
return client.page.FilesPageElement.filesList().waitForFileVisible(path)
})
Then('the last uploaded folder should be listed on the webUI', async function () {
const folder = client.sessionId
await client.page.FilesPageElement.filesList().waitForFileVisible(folder)
return client
})
Then('file {string} should not be listed on the webUI', function (file) {
return client.page.FilesPageElement.filesList()
.isElementListed(file, 'file', false)
.then((state) => {
const message = state
? `Error: File '${file}' is listed on the filesList`
: `File '${file}' is not listed on the filesList`
return client.assert.ok(!state, message)
})
})
Then('folder {string} should not be listed on the webUI', (folder) => {
return client.page.FilesPageElement.filesList()
.isElementListed(folder, 'folder', false)
.then((state) => {
const message = state
? `Error: Folder '${folder}' is listed on the filesList`
: `Folder '${folder}' is not listed on the filesList`
return client.assert.ok(!state, message)
})
})
Then('the unshared elements should be in declined state on the webUI', async function () {
for (const element of unsharedElements) {
const isDeclined = await client.page
.sharedWithMePage()
.hasShareStatusByFilename(SHARE_STATE.declined, element)
assert.ok(isDeclined, `Expected resource '${element}' to be in 'Declined' state but didn't.`)
}
return client
})
Then('the deleted elements should not be listed on the webUI', function () {
return assertDeletedElementsAreNotListed()
})
Then('the deleted elements should not be listed on the webUI after a page reload', function () {
client.refresh()
return assertDeletedElementsAreNotListed()
})
Then('the versions list should contain {int} entries', async function (expectedNumber) {
const count = await client.page.FilesPageElement.versionsDialog().getVersionsCount()
return assert.strictEqual(count, expectedNumber)
})
Then(
'the versions list for resource {string} should contain {int} entry/entries',
async function (resourceName, expectedNumber) {
const api = client.page.FilesPageElement
await client.initAjaxCounters()
await api.filesList().openSideBar(resourceName)
await api.appSideBar().activatePanel('versions')
await client.waitForOutstandingAjaxCalls()
const count = await api.versionsDialog().getVersionsCount()
assert.strictEqual(count, expectedNumber)
await api.appSideBar().closeSidebarIfOpen()
return this
}
)
/**
* Expects to have opened the `details` panel for the correct resource before
*/
Then('the shared-via path in the details dialog should be {string}', async function (expectedPath) {
const api = client.page.FilesPageElement
const actualPath = await api.detailsDialog().getSharedViaPath()
assert.strictEqual(actualPath, expectedPath)
return this
})
When('the user restores the file to last version using the webUI', function () {
return client.page.FilesPageElement.versionsDialog().restoreToPreviousVersion()
})
When('the user/public reloads the current page of the webUI', function () {
return client.refresh()
})
Given('the user has reloaded the current page of the webUI', function () {
return client.refresh()
})
When('the user marks all files for batch action using the webUI', function () {
return client.page.FilesPageElement.filesList().checkAllFiles()
})
When('the user batch deletes the marked files permanently using the webUI', function () {
return client.page.trashbinPage().deleteSelectedPermanently()
})
When('the user/public batch deletes the marked files using the webUI', function () {
return client.page.personalPage().deleteAllCheckedFiles()
})
When('the user batch unshares these files using the webUI', async function (shares) {
for (const item of shares.rows()) {
await client.page.FilesPageElement.filesList().toggleFileOrFolderCheckbox('enable', item[0])
unsharedElements.push(item[0])
}
return client.page.sharedWithMePage().unshareAllCheckedFiles()
})
When(
'the user batch deletes these files permanently using the webUI',
async function (fileOrFolders) {
for (const item of fileOrFolders.rows()) {
await client.page.FilesPageElement.filesList().toggleFileOrFolderCheckbox('enable', item[0])
}
return client.page.trashbinPage().deleteSelectedPermanently()
}
)
When('the user batch deletes these files using the webUI', async function (fileOrFolders) {
for (const item of fileOrFolders.rows()) {
await client.page.FilesPageElement.filesList().toggleFileOrFolderCheckbox('enable', item[0])
deletedElements.push(item[0])
}
return client.page.personalPage().deleteAllCheckedFiles()
})
When('the user batch declines these shares using the webUI', async function (fileOrFolders) {
for (const item of fileOrFolders.rows()) {
await client.page.FilesPageElement.filesList().toggleFileOrFolderCheckbox('enable', item[0])
}
return client.page.sharedWithMePage().batchDeclineShares()
})
When(
'the user unmarks these files for batch action using the webUI',
async function (fileOrFolders) {
for (const item of fileOrFolders.rows()) {
await client.page.FilesPageElement.filesList().toggleFileOrFolderCheckbox('disable', item[0])
}
}
)
When(
'the user/public marks these files for batch action using the webUI',
async function (fileOrFolders) {
for (const item of fileOrFolders.rows()) {
await client.page.FilesPageElement.filesList().toggleFileOrFolderCheckbox('enable', item[0])
}
}
)
Then('these files should be selected on the webUI', async function (fileOrFolders) {
for (const item of fileOrFolders.rows()) {
const status = await client.page.FilesPageElement.filesList().isResourceSelected(item[0])
assert.strictEqual(true, status, item + ' is expected to be selected but is not selected')
}
})
Then('these files should not be selected on the webUI', async function (fileOrFolders) {
for (const item of fileOrFolders.rows()) {
const status = await client.page.FilesPageElement.filesList().isResourceSelected(item[0])
assert.strictEqual(false, status, item + ' is expected not to be selected but is selected')
}
})
When('the user clears the trashbin', function () {
return client.page.trashbinPage().clearTrashbin()
})
When('the user batch restores the marked files using the webUI', function () {
return client.page.trashbinPage().restoreSelected()
})
When('the user opens the sidebar for file/folder {string} on the webUI', function (item) {
return client.page.FilesPageElement.filesList().openSideBar(item)
})
When(
'the user opens the details dialog for file/folder/resource {string} using the webUI',
function (item) {
return client.page.FilesPageElement.filesList().openDetailsDialog(item)
}
)
When('the user switches to {string} panel in details panel using the webUI', function (item) {
return client.page.FilesPageElement.appSideBar().activatePanel(item)
})
const theseResourcesShouldNotBeListed = async function (table) {
for (const entry of table.rows()) {
const state = await client.page.FilesPageElement.filesList().isElementListed(
entry[0],
'file',
false
)
assert.ok(!state, `Expected resource '${entry[0]}' to be 'not present' but found 'present'`)
}
}
/**
* needs a heading line in the table
*/
Then('these folders/files/resources should not be listed on the webUI', function (table) {
return theseResourcesShouldNotBeListed(table)
})
/**
* needs a heading line in the table
*/
Then(
'as {string} these folders/files/resources should not be listed on the webUI',
async function (user, entryList) {
if (user !== client.globals.currentUser) {
await loginHelper.reLoginAsUser(user)
}
return theseResourcesShouldNotBeListed(entryList)
}
)
/**
* currently this only works with the files page, on other pages the user cannot navigate into subfolders
*
* needs a heading line in the table
*/
Then(
'these folders/files/resources should not be listed in the folder {string} on the webUI',
async function (folder, entryList) {
await client.page.personalPage().navigateAndWaitTillLoaded(folder)
return theseResourcesShouldNotBeListed(entryList)
}
)
Then(
'file/folder/resource {string} should not be listed in the folder {string} on the webUI',
async function (file, target) {
await client.page.personalPage().navigateAndWaitTillLoaded(target)
return client.page.FilesPageElement.filesList()
.isElementListed(file, 'file', false)
.then((state) => {
return client.assert.ok(!state, `Error: Folder '${file}' is listed on the '${target}'`)
})
}
)
/**
* currently this only works with the files page, on other pages the user cannot navigate into subfolders
*
* needs a heading line in the table
*/
Then(
'as {string} these folders/files/resources should not be listed in the folder {string} on the webUI',
async function (user, folder, entryList) {
if (user !== client.globals.currentUser) {
await loginHelper.reLoginAsUser(user)
}
await client.page.personalPage().navigateAndWaitTillLoaded(folder)
return theseResourcesShouldNotBeListed(entryList)
}
)
When(
'the user renames file {string} to {string} through context-menu using the webUI',
function (fromName, toName) {
return client.page.FilesPageElement.filesList().renameFileFromContextMenu(
fromName,
toName,
false
)
}
)
Then('file {string} should be listed on the sidebar', async function (file) {
await client.page.FilesPageElement.filesList().openSideBar(file)
await client.page.FilesPageElement.appSideBar().isSideBarOpenForResource(file)
})
/**
*
* @param {DataTable} entryList the list needs a heading line
*/
const theseResourcesShouldBeListed = async function (entryList) {
if (entryList.rows().length <= 0) {
throw Error('Gherkin entry list is empty. Missing heading?')
}
for (const item of entryList.rows()) {
await client.page.FilesPageElement.filesList().waitForFileVisible(item[0])
}
return client
}
const assertBreadCrumbIsNotDisplayed = function () {
const breadcrumbXpath = client.page.personalPage().elements.breadcrumb.selector
return client.expect.element(breadcrumbXpath).to.not.be.present
}
/**
*
* @param {string} resource
* @param {boolean} clickable
* @param {boolean} nonClickable
*/
const assertBreadcrumbIsDisplayedFor = async function (resource, clickable, nonClickable) {
const breadcrumbElement = client.page
.personalPage()
.getBreadcrumbSelector(clickable, nonClickable)
const resourceBreadcrumbXpath = util.format(
breadcrumbElement.selector,
xpathHelper.buildXpathLiteral(resource)
)
let isBreadcrumbVisible
try {
await client.waitForElementVisible({
selector: resourceBreadcrumbXpath,
locateStrategy: 'xpath'
})
isBreadcrumbVisible = true
} catch (e) {
isBreadcrumbVisible = false
}
// Try to look for a mobile breadcrumbs in case it has not been found
if (!isBreadcrumbVisible) {
await appSideBar.closeSidebarIfOpen()
const mobileBreadcrumbMobileXpath = util.format(
client.page.personalPage().elements.breadcrumbMobileReferencedToOpenSidebarButton.selector,
xpathHelper.buildXpathLiteral(resource)
)
try {
await client.waitForElementVisible({
selector: mobileBreadcrumbMobileXpath,
locateStrategy: 'xpath'
})
isBreadcrumbVisible = true
} catch (e) {
isBreadcrumbVisible = false
}
}
return client.assert.strictEqual(
isBreadcrumbVisible,
true,
`Resource ${resourceBreadcrumbXpath} expected to be visible but is not visible .`
)
}
/**
*
* @param {string} resource
* @param {boolean} clickable
* @param {boolean} nonClickable
*/
const assertBreadcrumbIsPresentFor = async function (resource, clickable, nonClickable) {
const breadcrumbElement = client.page
.personalPage()
.getBreadcrumbSelector(clickable, nonClickable)
const resourceBreadcrumbXpath = util.format(
breadcrumbElement.selector,
xpathHelper.buildXpathLiteral(resource)
)
let isBreadcrumbPresent = false
// lets hope that the breadcrumbs would not take longer than the "NEW" button
await client.waitForElementPresent({
selector: client.page.personalPage().elements.newFileMenuButtonAnyState.selector,
abortOnFailure: false
})
try {
await client.waitForElementPresent({
selector: resourceBreadcrumbXpath,
locateStrategy: 'xpath'
})
isBreadcrumbPresent = true
} catch (e) {
isBreadcrumbPresent = false
}
// Try to look for a mobile breadcrumbs in case it has not been found
if (!isBreadcrumbPresent) {
await appSideBar.closeSidebarIfOpen()
const mobileBreadcrumbMobileXpath = util.format(
client.page.personalPage().elements.breadcrumbMobile.selector,
xpathHelper.buildXpathLiteral(resource)
)
try {
await client.waitForElementPresent({
selector: mobileBreadcrumbMobileXpath,
locateStrategy: 'xpath'
})
isBreadcrumbPresent = true
} catch (e) {
isBreadcrumbPresent = false
}
}
return client.assert.strictEqual(
isBreadcrumbPresent,
true,
`Resource ${resourceBreadcrumbXpath} expected to be visible but is not visible .`
)
}
/**
* needs a heading line in the table
*/
Then('these files/folders/resources should be listed on the webUI', function (entryList) {
return theseResourcesShouldBeListed(entryList)
})
/**
* currently this only works with the files page, on other pages the user cannot navigate into subfolders
*
* needs a heading line in the table
*/
Then(
'these files/folders/resources should be listed in the folder {string} on the webUI',
async function (folder, entryList) {
await client.page.personalPage().navigateAndWaitTillLoaded()
await client.page.personalPage().navigateToFolder(folder)
return theseResourcesShouldBeListed(entryList)
}
)
/**
* needs a heading line in the table
*/
Then(
'as {string} these files/folders/resources should be listed on the webUI',
async function (user, entryList) {
if (user !== client.globals.currentUser) {
await loginHelper.reLoginAsUser(user)
}
return theseResourcesShouldBeListed(entryList)
}
)
/**
* currently this only works with the files page, on other pages the user cannot navigate into subfolders
*
* needs a heading line in the table
*/
Then(
'as {string} these files/folders/resources should be listed in the folder {string} on the webUI',
async function (user, folder, entryList) {
if (user !== client.globals.currentUser) {
await loginHelper.reLoginAsUser(user)
}
await client.page.personalPage().navigateAndWaitTillLoaded(folder)
return theseResourcesShouldBeListed(entryList)
}
)
Then(
'file/folder {string} should be marked as favorite on the webUI',
async function (resourceName) {
const selector =
client.page.FilesPageElement.fileActionsMenu().elements.unmarkFavoriteButtonInAccordion
await client.page.FilesPageElement.filesList().openSideBar(resourceName)
await client.page.FilesPageElement.appSideBar().activatePanel('actions')
client.expect.element(selector).to.be.present
await client.page.FilesPageElement.appSideBar().closeSidebarIfOpen()
return client
}
)
Then(
'file/folder {string} should not be marked as favorite on the webUI',
async function (resourceName) {
const selector =
client.page.FilesPageElement.fileActionsMenu().elements.favoriteButtonInAccordion
await client.page.FilesPageElement.filesList().openSideBar(resourceName)
await client.page.FilesPageElement.appSideBar().activatePanel('actions')
client.expect.element(selector).to.be.present
await client.page.FilesPageElement.appSideBar().closeSidebarIfOpen()
return client
}
)
Then(
/the count of files and folders shown on the webUI should be (\d+)/,
async function (noOfItems) {
const itemsCount = await client.page.FilesPageElement.filesList().countFilesAndFolders()
return client.assert.equal(itemsCount, noOfItems)
}
)
Then('the app-sidebar should be visible', async function () {
const visible = await client.page.FilesPageElement.appSideBar().isSideBarOpen()
assert.strictEqual(visible, true, 'app-sidebar should be visible, but is not')
})
Then('the app-sidebar should be invisible', async function () {
const visible = await client.page.FilesPageElement.appSideBar().isSideBarOpen(false)
assert.strictEqual(visible, false, 'app-sidebar should be invisible, but is not')
})
Then('the {string} details panel should be visible', async function (panel) {
const expanded = await client.page.FilesPageElement.appSideBar().isPanelActive(panel)
assert.strictEqual(expanded, true, `'${panel}-panel' should be active, but is not`)
})
const assertElementsAreListed = async function (elements) {
for (const element of elements) {
const state = await client.page.FilesPageElement.filesList().isElementListed(element)
assert.ok(state, `Expected resource '${element}' to be 'present' but found 'not present'`)
}
return client
}
const assertElementsAreNotListed = async function (elements) {
for (const element of elements) {
const state = await client.page.FilesPageElement.filesList().isElementListed(
element,
'any',
false
)
assert.ok(!state, `Expected resource '${element}' to be 'not present' but found 'present'`)
}
return client
}
const assertDeletedElementsAreNotListed = function () {
return assertElementsAreNotListed(deletedElements)
}
const assertDeletedElementsAreListed = function () {
return assertElementsAreListed(deletedElements)
}
When(
/^the user restores (file|folder) "([^"]*)" from the trashbin using the webUI$/,
function (elementType, element) {
return client.page.FilesPageElement.filesList().restoreFile(element, elementType)
}
)
Then('the following files/folders/resources should be listed on the webUI', function (table) {
return assertElementsAreListed([].concat.apply([], table.rows()))
})
Then(
'file/folder {string} should be listed in the folder {string} on the webUI',
async function (file, folder) {
const api = client.page.FilesPageElement.filesList()
await api.navigateToFolder(folder)
await api.waitForFileVisible(file)
return client
}
)
Then(
'file/folder {string} should be listed in the folder {string} on the webUI as single share',
async function (file, folder) {
await client.page.FilesPageElement.filesList().navigateToFolder(folder)
return client.page.FilesPageElement.filesList().waitForFileVisibleAsSingleShare(file)
}
)
Then('the deleted elements should be listed on the webUI', function () {
return assertDeletedElementsAreListed()
})
Then(
'file/folder {string} should not be listed in shared-with-others page on the webUI',
async function (filename) {
await client.page.sharedWithOthersPage().navigateAndWaitTillLoaded()
const state = await client.page.FilesPageElement.filesList().isElementListed(
filename,
'any',
false
)
assert.ok(
!state,
`Error: Resource ${filename} is present on the shared-with-others page on the webUI`
)
}
)
Then(
'file/folder {string} should be listed in shared-with-others page on the webUI',
async function (filename) {
await client.page.sharedWithOthersPage().navigateAndWaitTillLoaded()
await client.page.FilesPageElement.filesList().waitForFileVisible(filename)
return client
}
)
When('the user/public creates the following folders using the webUI', async function (entryList) {
for (const entry of entryList.rows()) {
await client.page.personalPage().createFolder(entry[0])
}
})
When('the user browses to the folder {string} on the files page', (folderName) => {
const targetFolder = folderName === '/' ? '' : folderName
return client.page.personalPage().navigateAndWaitTillLoaded(targetFolder)
})
Then(
'as user {string} the clipboard content should match permalink of resource {string}',
async function (userId, folderName) {
const folderData = await webdav.getProperties(folderName, userId, ['oc:privatelink'])
return client.getClipBoardContent(function (value) {
assert.strictEqual(folderData['oc:privatelink'], value)
})
}
)
When(
/^the user opens the actions sidebar panel of (file|folder) "([^"]*)" on the webUI$/,
async function (elementType, resource) {
await client.page.FilesPageElement.filesList().openFileActionsMenu(resource, elementType)
}
)
Then(
/^the app-sidebar for (file|folder) "([^"]*)" should be visible on the webUI$/,
async function (elementType, resource) {
const visible = await client.page.FilesPageElement.appSideBar().isSideBarOpenForResource(
resource,
elementType
)
assert.strictEqual(visible, true, 'app-sidebar should be visible, but is not')
}
)
Then(
'the {string} preview of thumbnail should be visible in the {string} panel',
function (previewSize, panelName) {
return client.page.FilesPageElement.appSideBar().isThumbnailVisible(previewSize, panelName)
}
)
When('the user deletes the file {string} from the deleted files list', function (element) {
return client.page.FilesPageElement.filesList().deleteImmediately(element)
})
async function isPossibleToDeleteResourceOnWebUI(resource) {
return !(await client.page.FilesPageElement.filesList().isActionAttributeDisabled(
'delete',
resource
))
}
Then(
'it should not be possible to delete file/folder {string} using the webUI',
async function (resource) {
assert.strictEqual(
await isPossibleToDeleteResourceOnWebUI(resource),
false,
`expected delete function of ${resource} to be disabled but it is enabled`
)
}
)
Then(
'it should not be possible to delete file {string} as single share using the webUI',
function (resource) {
return client.page.personalPage().checkForNonPresentDeleteButtonInSingleShareView()
}
)
Then(
'it should be possible to delete file/folder {string} using the webUI',
async function (resource) {
assert.strictEqual(
await isPossibleToDeleteResourceOnWebUI(resource),
true,
`expected delete function of ${resource} to be enabled but it is disabled`
)
}
)
Then(
'it should not be possible to rename file/folder {string} using the webUI',
async function (resource) {
const state = await client.page.FilesPageElement.filesList().isActionAttributeDisabled(
'rename',
resource
)
assert.ok(state, `expected property disabled of ${resource} to be 'true' but found ${state}`)
}
)
When('the user uploads overwriting file {string} using the webUI', async function (file) {
const uploadPath = path.join(client.globals.mountedUploadDir, file)
await client.page.personalPage().selectFileForUpload(uploadPath)
await client.page.personalPage().confirmFileOverwrite()
return this
})
When(
'the user tries to create a file with already existing name {string} using the webUI',
function (fileName) {
return client.page.personalPage().createFile(fileName, false)
}
)
Then('the create file/folder button should be disabled', function () {
return client.page.personalPage().checkForButtonDisabled()
})
Then('the following file should not be listed on the webUI', async function (table) {
const name = table
.hashes()
.map((data) => data['name-parts'])
.join('')
const state = await client.page.FilesPageElement.filesList().isElementListed(name, 'any', false)
return assert.ok(!state, `Element ${name} is present on the filesList!`)
})
Then('the user deletes the following file using the webUI', function (table) {
const name = table
.hashes()
.map((data) => data['name-parts'])
.join('')
return client.page.FilesPageElement.filesList().deleteFile(name)
})
Then('the user deletes the following single share using the webUI', function (table) {
const name = table
.hashes()
.map((data) => data['name-parts'])
.join('')
return client.page.FilesPageElement.filesList().deleteSingleShare(name)
})
Then('the user should be redirected to the files-drop page', function () {
return client.page.filesDropPage().waitForPage()
})
Then('the user should be redirected to the public links page', function () {
return client.page.publicLinkFilesPage().waitForPage()
})
Then(
'file/folder {string} shared by {string} should not be listed on the webUI',
async function (element, sharer) {
const found = await client.page.sharedWithMePage().isSharePresent(element, sharer)
assert.ok(
!found,
element + ' shared by ' + sharer + ' was present but was not expected to be present'
)
}
)
When('the user downloads file/folder {string} using the webUI', function (file) {
return client.page.FilesPageElement.filesList().downloadFile(file)
})
Then(
'the following resources should have share indicators on the webUI',
async function (dataTable) {
for (const { fileName, expectedIndicators } of dataTable.hashes()) {
const indicatorsArray =
await client.page.FilesPageElement.filesList().getShareIndicatorsForResourceWithRetry(
fileName,
true
)
const expectedIndicatorsArray = expectedIndicators.split(',').map((s) => s.trim())
assert.ok(
_.intersection(indicatorsArray, expectedIndicatorsArray).length ===
expectedIndicatorsArray.length,
`Expected share indicators to be the same for "${fileName}": expected [` +
expectedIndicatorsArray.join(', ') +
'] got [' +
indicatorsArray.join(', ') +
']'
)
}
}
)
Then(
'the following resources should not have share indicators on the webUI',
async function (dataTable) {
for (const [fileName] of dataTable.raw()) {
const indicatorsArray =
await client.page.FilesPageElement.filesList().getShareIndicatorsForResource(
fileName,
false
)
assert.ok(!indicatorsArray.length, `Expected no share indicators present for "${fileName}"`)
}
}
)
async function _setFilesTableSort(column, isDesc) {
await client.page.FilesPageElement.filesList().setSort(column, isDesc)
}
When(
'the user has set the sort order of the {string} column to descending order',
async function (column) {
await _setFilesTableSort(column, true)
}
)
When(
'the user has set the sort order of the {string} column to ascending order',
async function (column) {
await _setFilesTableSort(column, false)
}
)
Then('quick action {string} should be displayed on the webUI', function (action) {
return client.page.FilesPageElement.filesRow().isQuickActionVisible(action)
})
When(
'the user moves file/folder {string} into folder {string} using the webUI',
function (resource, target) {
return client.page.FilesPageElement.filesList().moveResource(resource, target)
}
)
When(
'the user tries to move file/folder {string} into folder {string} using the webUI',
function (resource, target) {
return (
client.page.FilesPageElement.filesList()
.moveResource(resource, target)
// while moving resource, after clicking the "Paste here" button, the button should disappear but if it doesn't
// we throw "ElementPresentError" error. So, all the error except "ElementPresentError" is caught and thrown back
// Also, when no error is thrown, the button seems to disappear, so an error should be thrown in such case as well.
.then(() => {
throw new Error('ElementPresentError')
})
.catch((err) => {
if (err.message !== 'ElementPresentError') {
throw new Error(err)
}
})
)
}
)
When(
'the user batch moves these files/folders into folder {string} using the webUI',
async function (target, resources) {
for (const item of resources.rows()) {
await client.page.FilesPageElement.filesList().toggleFileOrFolderCheckbox('enable', item[0])
}
return client.page.FilesPageElement.filesList().moveMultipleResources(target)
}
)
When(
'the user copies file/folder {string} into folder {string} using the webUI',
function (resource, target) {
return client.page.FilesPageElement.filesList().copyResource(resource, target)
}
)
When(
'the user tries to copy file/folder {string} into folder {string} using the webUI',
function (resource, target) {
return client.page.FilesPageElement.filesList()
.copyResource(resource, target)
.catch((error) => {
// while copying resource, after clicking the "Paste here" button, the button should disappear but if it doesn't
// we throw "ElementPresentError" error. So, all the error except "ElementPresentError" is caught and thrown back
if (error.message !== 'ElementPresentError') {
throw error
}
})
}
)
When(
'the user batch copies these files/folders into folder {string} using the webUI',
async function (target, resources) {
for (const item of resources.rows()) {
await client.page.FilesPageElement.filesList().toggleFileOrFolderCheckbox('enable', item[0])
}
return await client.page.FilesPageElement.filesList().copyMultipleResources(target)
}
)
When(
'the user creates a markdown file with the name {string} using the webUI',
function (fileName) {
return client.page.personalPage().createMarkdownFile(fileName)
}
)
Then('the user should be in the root directory on the webUI', async function () {
const isUserInRootDirectory = await client.page.personalPage().isRootDirectory()
assert.ok(!isUserInRootDirectory, 'Expected user in the root directory but found elsewhere')
})
Then('the search bar should not be visible on the webUI', async function () {
await client.page.FilesPageElement.filesList().waitForLoadingFinished(false)
const isVisible = await client.page.personalPage().isSearchBarVisible()
assert.strictEqual(isVisible, false, 'Expected search bar to be invisible but is visible')
})
Then('the search bar should be visible on the webUI', async function () {
await client.page.FilesPageElement.filesList().waitForLoadingFinished(false)
const isVisible = await client.page.personalPage().isSearchBarVisible()
assert.strictEqual(isVisible, true, 'Expected search bar to be visible but is not visible')
})
Then(
/^the preview image of file "([^"]*)" (should|should not) be displayed in the file list view on the webUI$/,
function (fileName, shouldOrShouldnot) {
return client.page.FilesPageElement.filesList().checkPreviewImage(
fileName,
shouldOrShouldnot === 'should'
)
}
)
Then(
'only the following items with default items should be visible in the actions menu on the webUI',
async function (table) {
const visibleItems =
await client.page.FilesPageElement.appSideBar().getActionsMenuItemsExceptDefaults()
const tableItems = table.rows()
const expectedVisibleItems = []
tableItems.forEach((element) => {
element instanceof Array
? expectedVisibleItems.push(element[0])
: expectedVisibleItems.push(element)
})
const isPresent = _.isEqual(_.sortBy(expectedVisibleItems), _.sortBy(visibleItems))
assert.strictEqual(
isPresent,
true,
`only '${expectedVisibleItems}' actions menu item(s) was expected to be visible but found '${visibleItems}' instead.`
)
}
)
When('the user closes rename dialog', function () {
return client.page.FilesPageElement.filesList().closeRenameDialog()
})
Then('notifications should be displayed on the webUI with the text', async function (message) {
const actualMessages = await client.page.webPage().getPopupErrorMessages()
const isMessageShown = assertIncludesMessage(actualMessages, message)
assert.strictEqual(isMessageShown, true, `Expected '${message}' but not found`)
})
function assertIncludesMessage(messageArr, message) {
if (messageArr.includes(message)) {
return true
} else {
return false
}
}
When('the user marks the file/folder {string} using the webUI', function (fileName) {
return client.page.FilesPageElement.filesList().toggleFileOrFolderCheckbox('enable', fileName)
})
Then('the following batch action buttons should not be visible', async function (dataTable) {
const batchButtons = dataTable.hashes()
for (const batchButton of batchButtons) {
const isBatchButtonVisible = await appBarActions.isBatchActionButtonVisible(
batchButton.buttonName,
false
)
assert.strictEqual(
isBatchButtonVisible,
false,
`Expected "${batchButton.buttonName}" action button not to be visible but was`
)
}
})
Then('the following batch action buttons should be visible', async function (dataTable) {
const batchButtons = dataTable.hashes()
for (const batchButton of batchButtons) {
const isBatchButtonVisible = await appBarActions.isBatchActionButtonVisible(
batchButton.buttonName
)
assert.strictEqual(
isBatchButtonVisible,
true,
`Expected "${batchButton.buttonName}" action button to be visible but was not`
)
}
})
| owncloud/web/tests/acceptance/stepDefinitions/filesContext.js/0 | {
"file_path": "owncloud/web/tests/acceptance/stepDefinitions/filesContext.js",
"repo_id": "owncloud",
"token_count": 14940
} | 870 |
#!/bin/bash
source .drone.env
echo "$OCIS_BRANCH"
# Run git ls-remote to get the latest commit ID
latest_commit_id=$(git ls-remote https://github.com/owncloud/ocis.git "refs/heads/$OCIS_BRANCH" | cut -f 1)
# Specify the path to the drone.env file
env_file="./.drone.env"
sed -i "s/^OCIS_COMMITID=.*/OCIS_COMMITID=$latest_commit_id/" "$env_file"
cat $env_file
exit 0
| owncloud/web/tests/drone/get-latest-ocis-commit-id.sh/0 | {
"file_path": "owncloud/web/tests/drone/get-latest-ocis-commit-id.sh",
"repo_id": "owncloud",
"token_count": 152
} | 871 |
Feature: Integrate with online office suites like Collabora and OnlyOffice
As a user
I want to work on different docs, sheets, slides etc.., using online office suites like Collabora or OnlyOffice
So that the collaboration is seamless
# To run this feature we need to run the external app-provider service along with wopi, OnlyOffice, Collabora services
# This is a minimal test for the integration of ocis with different online office suites like Collabora and OnlyOffice
Background:
Given "Admin" creates following users using API
| id |
| Alice |
And "Alice" logs in
And "Alice" opens the "files" app
Scenario: create an OpenDocument file with Collabora
When "Alice" creates the following resources
| resource | type | content |
| OpenDocument.odt | OpenDocument | OpenDocument Content |
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | role | password |
| OpenDocument.odt | Can edit | %public% |
And "Alice" logs out
And "Anonymous" opens the public link "Link"
And "Anonymous" unlocks the public link with password "%public%"
Then "Anonymous" should see the content "OpenDocument Content" in editor "Collabora"
Scenario: create a Microsoft Word file with OnlyOffice
When "Alice" creates the following resources
| resource | type | content |
| MicrosoftWord.docx | Microsoft Word | Microsoft Word Content |
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | role | password |
| MicrosoftWord.docx | Can edit | %public% |
And "Alice" logs out
And "Anonymous" opens the public link "Link"
And "Anonymous" unlocks the public link with password "%public%"
Then "Anonymous" should see the content "Microsoft Word Content" in editor "OnlyOffice"
| owncloud/web/tests/e2e/cucumber/features/app-provider/officeSuites.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/app-provider/officeSuites.feature",
"repo_id": "owncloud",
"token_count": 622
} | 872 |
Feature: Group actions
As a user
I want to check group operations like:
- sharing a resource by several users
- accepting multiple shares by using a batch action
Scenario: copy and move resources in personal space
Given "Admin" creates following user using API
| id |
| Alice |
| Brian |
| Carol |
| David |
| Edith |
And "Admin" creates following group using API
| id |
| sales |
| finance |
| security |
And "Admin" adds user to the group using API
| user | group |
| Brian | sales |
| Brian | finance |
| Brian | security |
And "Brian" logs in
# disabling auto accepting to check accepting share
And "Brian" disables auto-accepting using API
And "Alice" logs in
And "Alice" creates the following folders in personal space using API
| name |
| sharedFolder |
| folder1 |
| folder2 |
| folder3 |
| folder4 |
| folder5 |
| parentFolder/SubFolder |
And "Alice" shares the following resource using API
| resource | recipient | type | role |
| folder1 | Brian | user | Can edit |
| folder2 | Brian | user | Can edit |
| folder3 | Brian | user | Can edit |
| folder4 | Brian | user | Can edit |
| folder5 | Brian | user | Can edit |
| parentFolder | Brian | user | Can edit |
And "Alice" opens the "files" app
# multiple share
And "Alice" shares the following resources using the sidebar panel
| resource | recipient | type | role |
| sharedFolder | Brian | user | Can edit |
| sharedFolder | Carol | user | Can edit |
| sharedFolder | David | user | Can edit |
| sharedFolder | Edith | user | Can edit |
| sharedFolder | sales | group | Can edit |
| sharedFolder | finance | group | Can edit |
| sharedFolder | security | group | Can edit |
And "Brian" opens the "files" app
And "Brian" navigates to the shared with me page
And "Brian" enables the sync for all shares using the batch actions
And "Alice" logs out
And "Brian" logs out
| owncloud/web/tests/e2e/cucumber/features/smoke/groupActions.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/groupActions.feature",
"repo_id": "owncloud",
"token_count": 969
} | 873 |
Feature: spaces participant management
Scenario: participant management
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
| David |
| Edith |
And "Admin" creates following group using API
| id |
| sales |
| security |
And "Admin" adds user to the group using API
| user | group |
| David | sales |
| Edith | security |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Alice" logs in
And "Alice" creates the following project space using API
| name | id |
| team | team.1 |
And "Alice" opens the "files" app
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "team.1"
And "Alice" adds following users to the project space
| user | role | kind |
| Brian | Can edit | user |
| Carol | Can view | user |
| sales | Can view | group |
| security | Can edit | group |
When "Brian" logs in
And "Brian" navigates to the projects space page
And "Brian" navigates to the project space "team.1"
And "Brian" creates the following resources
| resource | type |
| parent | folder |
And "Brian" uploads the following resources
| resource | to |
| lorem.txt | parent |
When "David" logs in
And "David" navigates to the projects space page
And "David" navigates to the project space "team.1"
Then "David" should see folder "parent" but should not be able to edit
And "David" logs out
When "Edith" logs in
And "Edith" navigates to the projects space page
And "Edith" navigates to the project space "team.1"
And "Edith" creates the following resources
| resource | type |
| edith | folder |
And "Edith" uploads the following resources
| resource | to |
| lorem.txt | edith |
And "Edith" logs out
When "Carol" logs in
And "Carol" navigates to the projects space page
And "Carol" navigates to the project space "team.1"
Then "Carol" should see folder "parent" but should not be able to edit
# page reload is necessary to fetch all the changes made by user Brian
When "Alice" reloads the spaces page
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | role | password |
| parent | Can edit | %public% |
And "Anonymous" opens the public link "Link"
And "Anonymous" unlocks the public link with password "%public%"
And "Anonymous" uploads the following resources in public link page
| resource |
| textfile.txt |
And "Anonymous" deletes the following resources from public link using sidebar panel
| resource | from |
| lorem.txt | |
When "Brian" deletes the following resources using the sidebar panel
| resource | from |
| textfile.txt | parent |
When "Carol" navigates to the trashbin of the project space "team.1"
Then "Carol" should not be able to delete following resources from the trashbin
| resource |
| parent/lorem.txt |
| parent/textfile.txt |
And "Carol" should not be able to restore following resources from the trashbin
| resource |
| parent/lorem.txt |
| parent/textfile.txt |
When "Brian" navigates to the trashbin of the project space "team.1"
Then "Brian" should be able to restore following resource from the trashbin
| resource |
| parent/lorem.txt |
And "Brian" should not be able to delete following resource from the trashbin
| resource |
| parent/textfile.txt |
When "Alice" navigates to the projects space page
And "Alice" navigates to the project space "team.1"
And "Alice" removes access to following users from the project space
| user |
| Brian |
When "Brian" navigates to the projects space page
Then "Brian" should not be able to see space "team.1"
And "Brian" logs out
When "Alice" changes the roles of the following users in the project space
| user | role |
| Carol | Can manage |
And "Carol" navigates to the trashbin of the project space "team.1"
Then "Carol" should be able to delete following resource from the trashbin
| resource |
| parent/textfile.txt |
And "Carol" logs out
And "Alice" as project manager removes their own access to the project space
Then "Alice" should not be able to see space "team.1"
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/spaces/participantManagement.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/spaces/participantManagement.feature",
"repo_id": "owncloud",
"token_count": 1712
} | 874 |
import { DataTable, Then, When } from '@cucumber/cucumber'
import { expect } from '@playwright/test'
import { World } from '../../environment'
import { objects } from '../../../support'
import { ICollaborator } from '../../../support/objects/app-files/share/collaborator'
const parseShareTable = function (stepTable: DataTable, usersEnvironment) {
return stepTable.hashes().reduce((acc, stepRow) => {
const { resource, recipient, type, role, resourceType, expirationDate } = stepRow
if (!acc[resource]) {
acc[resource] = []
}
acc[resource].push({
collaborator:
type === 'group'
? usersEnvironment.getGroup({ key: recipient })
: usersEnvironment.getUser({ key: recipient }),
role,
type,
resourceType,
expirationDate
})
return acc
}, [])
}
When(
/^"([^"]*)" shares the following resource(?:s)? using the (sidebar panel|quick action|direct url navigation)$/,
async function (this: World, stepUser: string, actionType: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
const shareInfo = parseShareTable(stepTable, this.usersEnvironment)
for (const resource of Object.keys(shareInfo)) {
await shareObject.create({
resource,
recipients: shareInfo[resource],
via:
actionType === 'quick action'
? 'QUICK_ACTION'
: 'sidebar panel'
? 'SIDEBAR_PANEL'
: 'URL_NAVIGATION'
})
}
}
)
When(
'{string} enables the sync for the following share(s)',
async function (this: World, stepUser: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
for (const info of stepTable.hashes()) {
await shareObject.enableSync({ resource: info.name })
}
}
)
When(
'{string} updates following sharee role(s)',
async function (this: World, stepUser: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
const shareInfo = parseShareTable(stepTable, this.usersEnvironment)
for (const resource of Object.keys(shareInfo)) {
await shareObject.changeShareeRole({
resource,
recipients: shareInfo[resource]
})
}
}
)
When(
'{string} removes following sharee(s)',
async function (this: World, stepUser: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
const shareInfo = parseShareTable(stepTable, this.usersEnvironment)
for (const resource of Object.keys(shareInfo)) {
await shareObject.removeSharee({ resource, recipients: shareInfo[resource] })
}
}
)
Then(
'{string} should see the following recipient(s)',
async function (this: World, stepUser: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
const shareInfo = parseShareTable(stepTable, this.usersEnvironment)
for (const resource of Object.keys(shareInfo)) {
await shareObject.checkSharee({ resource, recipients: shareInfo[resource] })
}
}
)
Then(
/"([^"]*)" (should|should not) be able to reshare the following resource(?:s)?$/,
async function (this: World, stepUser: string, condition: string, stepTable: DataTable) {
const ableToShare = condition === 'should'
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
for (const { resource } of stepTable.hashes()) {
const hasSharePermission = await shareObject.hasPermissionToShare(resource)
expect(hasSharePermission).toBe(ableToShare)
}
}
)
When(
'{string} navigates to the shared with me page',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const pageObject = new objects.applicationFiles.page.shares.WithMe({ page })
await pageObject.navigate()
}
)
When(
'{string} navigates to the shared with others page',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const pageObject = new objects.applicationFiles.page.shares.WithOthers({ page })
await pageObject.navigate()
}
)
When(
'{string} disables the sync for the following share(s)',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
for (const resource of stepTable.hashes()) {
await shareObject.disableSync({ resource: resource.name })
}
}
)
When(
'{string} enables the sync for the following share(s) using the context menu',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
for (const resource of stepTable.hashes()) {
await shareObject.enableSync({ resource: resource.name, via: 'CONTEXT_MENU' })
}
}
)
When(
'{string} enables the sync for all shares using the batch actions',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
await shareObject.syncAll()
}
)
When(
'{string} disables the sync for the following share(s) using the context menu',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
for (const resource of stepTable.hashes()) {
await shareObject.disableSync({ resource: resource.name, via: 'CONTEXT_MENU' })
}
}
)
When(
'{string} creates quick link of the resource {string} with password {string} from the context menu',
async function (
this: World,
stepUser: string,
resource: string,
password: string
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
const linkObject = new objects.applicationFiles.Link({ page })
password = password === '%public%' ? linkObject.securePassword : password
await shareObject.createQuickLink({
resource,
password
})
}
)
When(
'{string} should not be able to open the folder/file {string}',
async function (this: World, stepUser: string, resource: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
expect(await shareObject.resourceIsNotOpenable(resource)).toBe(true)
}
)
When(
/"([^"]*)" (should|should not) see a sync status for the (?:folder|file) "([^"]*)"?$/,
async function (
this: World,
stepUser: string,
condition: string,
resource: string
): Promise<void> {
const shouldSee = condition === 'should'
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
expect(await shareObject.resourceIsSynced(resource)).toBe(shouldSee)
}
)
Then(
/"([^"]*)" (should|should not) be able to see the following shares$/,
async function (
this: World,
stepUser: string,
condition: string,
stepTable: DataTable
): Promise<void> {
const shouldExist = condition === 'should'
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
for (const { resource, owner } of stepTable.hashes()) {
const isAcceptedSharePresent = await shareObject.isAcceptedSharePresent(resource, owner)
expect(isAcceptedSharePresent, '${resource} does not exist in accepted share').toBe(
shouldExist
)
}
}
)
When(
/^"([^"]*)" (grants|denies) access to the following resources(?:s)? for (group|user) "([^"]*)" using the sidebar panel?$/,
async function (
this: World,
stepUser: string,
actionType: string,
collaboratorType: 'user' | 'group',
collaborator: string,
stepTable: DataTable
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
for (const { resource } of stepTable.hashes()) {
await shareObject.setDenyShare({
resource,
deny: actionType === 'denies',
collaborator: {
collaborator:
collaboratorType === 'group'
? this.usersEnvironment.getGroup({ key: collaborator })
: this.usersEnvironment.getUser({ key: collaborator }),
type: collaboratorType
} as ICollaborator
})
}
}
)
When(
/^"([^"]*)" sets the expiration date of share "([^"]*)" of (group|user) "([^"]*)" to "([^"]*)"?$/,
async function (
this: World,
stepUser: string,
resource: string,
collaboratorType: 'user' | 'group',
collaboratorName: string,
expirationDate: string
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
await shareObject.addExpirationDate({
resource,
collaborator: {
collaborator:
collaboratorType === 'group'
? this.usersEnvironment.getGroup({ key: collaboratorName })
: this.usersEnvironment.getUser({ key: collaboratorName }),
type: collaboratorType
} as ICollaborator,
expirationDate
})
}
)
When(
/^"([^"]*)" checks the following access details of share "([^"]*)" for (user|group) "([^"]*)"$/,
async function (
this: World,
stepUser: string,
resource: string,
collaboratorType: string,
collaboratorName: string,
stepTable: DataTable
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const shareObject = new objects.applicationFiles.Share({ page })
const expectedDetails = stepTable.rowsHash()
const actualDetails = await shareObject.getAccessDetails({
resource,
collaborator: {
collaborator:
collaboratorType === 'group'
? this.usersEnvironment.getGroup({ key: collaboratorName })
: this.usersEnvironment.getUser({ key: collaboratorName }),
type: collaboratorType
} as ICollaborator
})
expect(actualDetails).toMatchObject(expectedDetails)
}
)
| owncloud/web/tests/e2e/cucumber/steps/ui/shares.ts/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/steps/ui/shares.ts",
"repo_id": "owncloud",
"token_count": 3823
} | 875 |
import { ApplicationEntity, User } from '../../types'
import { checkResponseStatus, request } from '../http'
import join from 'join-path'
interface ApplicationsResponse {
value: ApplicationEntity[]
}
export const getApplicationEntity = async (admin: User): Promise<ApplicationEntity> => {
const response = await request({
method: 'GET',
path: join('graph', 'v1.0', 'applications'),
user: admin
})
checkResponseStatus(response, 'Failed while getting application id')
const resBody = (await response.json()) as ApplicationsResponse
return resBody.value[0]
}
export const createTagsForResource = async ({
user,
resourceId,
tags
}: {
user: User
resourceId: string
tags: Array<string>
}): Promise<void> => {
const body = {
resourceId,
tags
}
const response = await request({
method: 'PUT',
path: join('graph', 'v1.0', 'extensions', 'org.libregraph', 'tags'),
body: JSON.stringify(body),
user: user
})
checkResponseStatus(response, 'Failed while creating tags of a resource.')
}
| owncloud/web/tests/e2e/support/api/graph/utils.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/graph/utils.ts",
"repo_id": "owncloud",
"token_count": 331
} | 876 |
import fs from 'fs'
import path from 'path'
import { config } from '../../config'
import { File } from '../types'
export class FilesEnvironment {
getFile({ name }: { name: string }): File {
const relPath = path.join(config.assets, name)
if (!fs.existsSync(relPath)) {
throw new Error('TODO: fixture files')
}
return { name, path: path.resolve(relPath) }
}
}
| owncloud/web/tests/e2e/support/environment/file.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/environment/file.ts",
"repo_id": "owncloud",
"token_count": 138
} | 877 |
export { General } from './general'
export { Spaces } from './spaces'
export { Users } from './users'
export { Groups } from './groups'
| owncloud/web/tests/e2e/support/objects/app-admin-settings/page/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/page/index.ts",
"repo_id": "owncloud",
"token_count": 41
} | 878 |
import { Page } from '@playwright/test'
export class Overview {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
async navigate(): Promise<void> {
await this.#page.locator('//a[@data-nav-name="files-trash-overview"]').click()
await this.#page.locator('#app-loading-spinner').waitFor({ state: 'detached' })
}
}
| owncloud/web/tests/e2e/support/objects/app-files/page/trashbin/overview.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/page/trashbin/overview.ts",
"repo_id": "owncloud",
"token_count": 128
} | 879 |
export * as sidebar from './sidebar'
export * as editor from './editor'
| owncloud/web/tests/e2e/support/objects/app-files/utils/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/utils/index.ts",
"repo_id": "owncloud",
"token_count": 21
} | 880 |
import { User } from '../types'
export const dummyUserStore = new Map<string, User>([
[
'admin',
{
id: 'admin',
displayName: process.env.ADMIN_USERNAME || 'admin',
password: process.env.ADMIN_PASSWORD || 'admin',
email: 'admin@example.org'
}
],
[
'alice',
{
id: 'alice',
displayName: 'Alice Hansen',
password: '1234',
email: 'alice@example.org'
}
],
[
'brian',
{
id: 'brian',
displayName: 'Brian Murphy',
password: '1234',
email: 'brian@example.org'
}
],
[
'carol',
{
id: 'carol',
displayName: 'Carol King',
password: '1234',
email: 'carol@example.org'
}
],
[
'david',
{
id: 'david',
displayName: 'David William Goodall',
password: '1234',
email: 'david@example.org'
}
],
[
'edith',
{
id: 'edith',
displayName: 'Edith Anne Widder',
password: '1234',
email: 'edith@example.org'
}
],
[
'max',
{
id: 'max',
displayName: 'Max Testing',
password: '12345678',
email: 'maxtesting@owncloud.com'
}
]
])
export const createdUserStore = new Map<string, User>()
| owncloud/web/tests/e2e/support/store/user.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/store/user.ts",
"repo_id": "owncloud",
"token_count": 606
} | 881 |
import { defineConfig, PluginOption, UserConfig, ViteDevServer } from 'vite'
import { mergeConfig, searchForWorkspaceRoot } from 'vite'
import vue from '@vitejs/plugin-vue'
import EnvironmentPlugin from 'vite-plugin-environment'
import { viteStaticCopy } from 'vite-plugin-static-copy'
import { treatAsCommonjs } from 'vite-plugin-treat-umd-as-commonjs'
import visualizer from 'rollup-plugin-visualizer'
import compression from 'rollup-plugin-gzip'
import ejs from 'ejs'
import { basename, join } from 'path'
import { existsSync, readdirSync, readFileSync } from 'fs'
// build config
import packageJson from './package.json'
import { compilerOptions } from './vite.config.common'
import { getUserAgentRegex } from 'browserslist-useragent-regexp'
import browserslistToEsbuild from 'browserslist-to-esbuild'
import fetch from 'node-fetch'
import { Agent } from 'https'
const buildConfig = {
requirejs: {},
cdn: process.env.CDN === 'true',
documentation_url: process.env.DOCUMENTATION_URL,
...(process.env.REQUIRE_TIMEOUT && {
requirejs: { waitSeconds: parseInt(process.env.REQUIRE_TIMEOUT) }
})
}
const projectRootDir = searchForWorkspaceRoot(process.cwd())
const { version } = packageJson
const supportedBrowsersRegex = getUserAgentRegex({ allowHigherVersions: true })
const stripScssMarker = '/* STYLES STRIP IMPORTS MARKER */'
// determine inputs
const input = readdirSync('packages').reduce(
(acc, i) => {
if (!i.startsWith('web-app')) {
return acc
}
for (const extension of ['js', 'ts']) {
const root = join('packages', i, 'src', `index.${extension}`)
if (existsSync(root)) {
acc[i] = root
break
}
}
return acc
},
{
'index.html': 'index.html',
'oidc-silent-redirect.html': 'oidc-silent-redirect.html',
'oidc-callback.html': 'oidc-callback.html'
}
)
const getJson = async (url: string) => {
return (
await fetch(url, {
...(url.startsWith('https:') && {
agent: new Agent({ rejectUnauthorized: false })
})
})
).json()
}
type ConfigJsonResponseBody = {
options: Record<string, any>
}
const getConfigJson = async (url: string) => {
const configJson = (await getJson(url)) as ConfigJsonResponseBody
// enable previews and enable lazy resources, which are disabled for fast tests
configJson.options.disablePreviews = false
configJson.options.displayResourcesLazy = true
return configJson
}
export const historyModePlugins = () =>
[
{
name: 'base-href',
transformIndexHtml: {
handler() {
return [
{
injectTo: 'head-prepend',
tag: 'base',
attrs: {
href: '/'
}
}
]
}
}
}
] as const
export default defineConfig(({ mode, command }) => {
const production = mode === 'production'
/**
When setting `OWNCLOUD_WEB_CONFIG_URL` make sure to configure the oauth/oidc client
# oCIS
For oCIS instances you can use `./dev/docker/ocis.idp.config.yaml`.
In docker setups you need to mount it to `/etc/ocis/idp.yaml`.
E.g. with docker-compose you could add a volume to the ocis container like this:
- /home/youruser/projects/oc-web/dev/docker/ocis.idp.config.yaml:/etc/ocis/idp.yaml
To use the oCIS deployment examples start vite like this:
OWNCLOUD_WEB_CONFIG_URL="https://ocis.owncloud.test/config.json" pnpm vite
*/
const configUrl =
process.env.OWNCLOUD_WEB_CONFIG_URL || 'https://host.docker.internal:9200/config.json'
const config: UserConfig = {
...(!production && {
server: {
port: 9201,
https: {
key: readFileSync('./dev/docker/traefik/certificates/server.key'),
cert: readFileSync('./dev/docker/traefik/certificates/server.crt')
}
}
})
}
return mergeConfig(
{
base: '',
publicDir: 'packages/web-container',
build: {
// TODO: Vue3: We currently cannot inline styles of components because @vite/plugin-vue2 does not support it
// c.f. https://github.com/vitejs/vite-plugin-vue2/issues/18
// That's why we need to put all styles of our monorepo apps into a monolithic css file for now
// Once the above issue is resolved or we switch to @vitejs/plugin-vue, we can remove the `cssCodeSplit` setting here
cssCodeSplit: false,
rollupOptions: {
preserveEntrySignatures: 'strict',
input,
output: {
dir: 'dist',
chunkFileNames: join('js', 'chunks', '[name]-[hash].mjs'),
entryFileNames: join('js', '[name]-[hash].mjs'),
manualChunks: (id) => {
if (id.includes('node_modules')) {
return 'vendor'
}
}
}
},
target: browserslistToEsbuild()
},
server: {
host: 'host.docker.internal',
strictPort: true
},
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "${projectRootDir}/packages/design-system/src/styles/styles";${stripScssMarker}`
}
}
},
resolve: {
dedupe: ['vue3-gettext'],
alias: {
crypto: join(projectRootDir, 'polyfills/crypto.js'),
buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6',
path: 'rollup-plugin-node-polyfills/polyfills/path',
util: 'rollup-plugin-node-polyfills/polyfills/util',
// xml-js
stream: 'rollup-plugin-node-polyfills/polyfills/stream',
string_decoder: 'rollup-plugin-node-polyfills/polyfills/string-decoder',
process: 'rollup-plugin-node-polyfills/polyfills/process-es6',
events: 'rollup-plugin-node-polyfills/polyfills/events'
}
},
plugins: [
// We need to "undefine" `define` which is set by requirejs loaded in index.html
treatAsCommonjs() as any as PluginOption, // treatAsCommonjs currently returns a Plugin_2 instance
// In order to avoid multiple definitions of the global styles we import via additionalData into every component
// we also insert a marker, so we can remove the global definitions after processing.
// The downside of this approach is that @extend does not work because it modifies the global styles, thus we emit
// a warning if `@extend` is used in the code base.
{
name: '@ownclouders/vite-plugin-strip-css',
transform(src: string, id) {
if (id.endsWith('.vue') && !id.includes('node_modules') && src.includes('@extend')) {
console.warn(
'You are using @extend in your component. This is likely not working in your styles. Please use mixins instead.',
id.replace(`${projectRootDir}/`, '')
)
}
if (id.includes('lang.scss')) {
const split = src.split(stripScssMarker)
const newSrc = split[split.length - 1]
return {
code: newSrc,
map: null
}
}
}
},
EnvironmentPlugin({
PACKAGE_VERSION: version
}),
vue({
template: {
compilerOptions
}
}),
viteStaticCopy({
targets: (() => {
const targets = [
...['fonts', 'icons'].map((name) => ({
src: `packages/design-system/src/assets/${name}/*`,
dest: `${name}`
})),
{
src: `./packages/web-runtime/themes/*`,
dest: `themes`
},
{
src: 'node_modules/requirejs/require.js',
dest: 'js'
}
]
return targets
})()
}),
{
name: '@ownclouders/vite-plugin-runtime-config',
configureServer(server: ViteDevServer) {
server.middlewares.use(async (request, response, next) => {
if (request.url === '/config.json') {
try {
const configJson = await getConfigJson(configUrl)
response.statusCode = 200
response.setHeader('Content-Type', 'application/json')
response.end(JSON.stringify(configJson))
} catch (e) {
response.statusCode = 502
response.setHeader('Content-Type', 'application/json')
response.end(JSON.stringify(e))
}
return
}
next()
})
}
},
{
name: '@ownclouders/vite-plugin-docs',
transform(src, id) {
if (id.includes('type=docs')) {
return {
code: 'export default {}',
map: null
}
}
}
},
{
name: 'ejs',
transformIndexHtml: {
order: 'pre',
handler(html, { filename }) {
if (basename(filename) !== 'index.html') {
return
}
return ejs.render(html, {
data: {
buildConfig,
title: process.env.TITLE || 'ownCloud',
compilationTimestamp: new Date().getTime(),
supportedBrowsersRegex: supportedBrowsersRegex
}
})
}
}
},
{
name: 'import-map',
transformIndexHtml: {
handler(html, { bundle, filename }) {
if (basename(filename) !== 'index.html') {
return
}
// Build an import map for loading internal (as in: shipped and built within this mono repo) apps
let moduleNames: string[]
let buildModulePath: any
if (bundle) {
moduleNames = Object.keys(bundle)
// We are in production mode here and need to provide paths relative to the module that contains the import, i.e. web-runtime-*.mjs
// so it works when oC Web is hosted in a sub folder, e.g. when using the oC 10 integration app
buildModulePath = (moduleName) => moduleName.replace('js/', './')
} else {
// We are in development mode here, so we can just use absolute module paths
moduleNames = Object.keys(input)
buildModulePath = (moduleName) => `/packages/${moduleName}/src/index`
}
const re = new RegExp(/(web-app-.*)/)
const map = Object.fromEntries(
moduleNames
.map((m) => {
const appName = re.exec(bundle?.[m]?.name || m)?.[1]
if (appName) {
return [appName, buildModulePath(m)]
}
})
.filter(Boolean)
)
return [
{
tag: 'script',
children: `window.WEB_APPS_MAP = ${JSON.stringify(map)}`
}
]
}
}
},
...(command === 'serve' ? historyModePlugins() : []),
compression(),
process.env.REPORT !== 'true'
? null
: visualizer({
filename: join('dist', 'report.html')
})
]
},
config
)
})
| owncloud/web/vite.config.ts/0 | {
"file_path": "owncloud/web/vite.config.ts",
"repo_id": "owncloud",
"token_count": 5591
} | 882 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.