text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0H24V24H0z"/>
<path d="M15 3c.552 0 1 .448 1 1v2h5c.552 0 1 .448 1 1v13c0 .552-.448 1-1 1H3c-.552 0-1-.448-1-1V7c0-.552.448-1 1-1h5V4c0-.552.448-1 1-1h6zm1 5H8v11h8V8zM4 8v11h2V8H4zm10-3h-4v1h4V5zm4 3v11h2V8h-2z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/suitcase-line.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/suitcase-line.svg",
"repo_id": "owncloud",
"token_count": 221
} | 780 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M4 5v14h16V5H4zM3 3h18a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zm12 4l3.5 3-3.5 3v-2h-4V9h4V7zM9 17l-3.5-3L9 11v2h4v2H9v2z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/swap-box-line.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/swap-box-line.svg",
"repo_id": "owncloud",
"token_count": 198
} | 781 |
<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.515 5l2.606-2.607a1 1 0 0 1 1.415 0l4.242 4.243a1 1 0 0 1 0 1.414L19 11.828V21a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1v-9.172L1.222 8.05a1 1 0 0 1 0-1.414l4.242-4.243a1 1 0 0 1 1.415 0L9.485 5h5.03zm.828 2H8.657L6.172 4.515 3.343 7.343 7 11v9h10v-9l3.657-3.657-2.829-2.828L15.343 7z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/t-shirt-line.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/t-shirt-line.svg",
"repo_id": "owncloud",
"token_count": 270
} | 782 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M22 12v9a1 1 0 0 1-1 1h-1a1 1 0 0 1-1-1v-1H5v1a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-9l2.48-5.788A2 2 0 0 1 6.32 5H9V3h6v2h2.681a2 2 0 0 1 1.838 1.212L22 12zM4.176 12h15.648l-2.143-5H6.32l-2.143 5zM6.5 17a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zm11 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/taxi-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/taxi-fill.svg",
"repo_id": "owncloud",
"token_count": 279
} | 783 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M20 10H4v9h16v-9zM3 3h18a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zm2 3v2h2V6H5zm4 0v2h2V6H9zm-4 5h3v5H5v-5z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/terminal-window-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/terminal-window-fill.svg",
"repo_id": "owncloud",
"token_count": 187
} | 784 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M8 7a5 5 0 1 0 0 10h8a5 5 0 0 0 0-10H8zm0-2h8a7 7 0 0 1 0 14H8A7 7 0 0 1 8 5zm0 10a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/toggle-line.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/toggle-line.svg",
"repo_id": "owncloud",
"token_count": 158
} | 785 |
<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="M8.95 8.537A7.5 7.5 0 1 1 7.537 9.95L4.662 7.075 2.186 9.55.772 8.136l6.364-6.364L8.55 3.186 6.075 5.661l2.876 2.876zM13.5 20a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/travesti-line.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/travesti-line.svg",
"repo_id": "owncloud",
"token_count": 197
} | 786 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M4.3 3H21v11.7l-4.7 4.7h-3.9l-2.5 2.4H7v-2.4H3V6.2L4.3 3zM5 17.4h4v2.4h.095l2.5-2.4h3.877L19 13.872V5H5v12.4zM15 8h2v4.7h-2V8zm0 0h2v4.7h-2V8zm-5 0h2v4.7h-2V8z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/twitch-line.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/twitch-line.svg",
"repo_id": "owncloud",
"token_count": 227
} | 787 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M4 19h16v-7h2v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-8h2v7zM14 9v6h-4V9H5l7-7 7 7h-5z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/upload-2-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/upload-2-fill.svg",
"repo_id": "owncloud",
"token_count": 151
} | 788 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M7.39 16.539a8 8 0 1 1 9.221 0l2.083 4.76a.5.5 0 0 1-.459.701H5.765a.5.5 0 0 1-.459-.7l2.083-4.761zm.729-5.569a4.002 4.002 0 0 0 7.762 0l-1.94-.485a2 2 0 0 1-3.882 0l-1.94.485z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/user-5-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/user-5-fill.svg",
"repo_id": "owncloud",
"token_count": 199
} | 789 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M14 14.252V22H4a8 8 0 0 1 10-7.748zM12 13c-3.315 0-6-2.685-6-6s2.685-6 6-6 6 2.685 6 6-2.685 6-6 6zm7.418 4h3.586v2h-3.586l1.829 1.828-1.414 1.415L15.59 18l4.243-4.243 1.414 1.415L19.418 17z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/user-received-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/user-received-fill.svg",
"repo_id": "owncloud",
"token_count": 209
} | 790 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M1 22a8 8 0 1 1 16 0H1zm8-9c-3.315 0-6-2.685-6-6s2.685-6 6-6 6 2.685 6 6-2.685 6-6 6zm9.246-9.816A9.97 9.97 0 0 1 19 7a9.97 9.97 0 0 1-.754 3.816l-1.677-1.22A7.99 7.99 0 0 0 17 7a7.99 7.99 0 0 0-.43-2.596l1.676-1.22zm3.302-2.4A13.942 13.942 0 0 1 23 7c0 2.233-.523 4.344-1.452 6.216l-1.645-1.196A11.955 11.955 0 0 0 21 7c0-1.792-.393-3.493-1.097-5.02L21.548.784z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/user-voice-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/user-voice-fill.svg",
"repo_id": "owncloud",
"token_count": 319
} | 791 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M5 7h2v10H5V7zm-4 3h2v4H1v-4zm8-8h2v18H9V2zm4 2h2v18h-2V4zm4 3h2v10h-2V7zm4 3h2v4h-2v-4z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/voiceprint-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/voiceprint-fill.svg",
"repo_id": "owncloud",
"token_count": 167
} | 792 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M22 8h-9a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h9v4a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h18a1 1 0 0 1 1 1v4zm-7 3h3v2h-3v-2z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/wallet-2-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/wallet-2-fill.svg",
"repo_id": "owncloud",
"token_count": 177
} | 793 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M10.5 17H4v-2h6.5a3.5 3.5 0 1 1-3.278 4.73l1.873-.703A1.5 1.5 0 1 0 10.5 17zM5 11h13.5a3.5 3.5 0 1 1-3.278 4.73l1.873-.703A1.5 1.5 0 1 0 18.5 13H5a3 3 0 0 1 0-6h8.5a1.5 1.5 0 1 0-1.405-2.027l-1.873-.702A3.501 3.501 0 0 1 17 5.5 3.5 3.5 0 0 1 13.5 9H5a1 1 0 1 0 0 2z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/windy-fill.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/windy-fill.svg",
"repo_id": "owncloud",
"token_count": 265
} | 794 |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g>
<path fill="none" d="M0 0h24v24H0z"/>
<path d="M12.344 17.963l-1.688 1.074-2.131-3.35c-.44 1.402-1.172 2.665-2.139 3.825-.402.483-.82.918-1.301 1.375-.155.147-.775.717-.878.82l-1.414-1.414c.139-.139.787-.735.915-.856.43-.408.795-.79 1.142-1.206 1.266-1.518 2.03-3.21 2.137-5.231H3v-2h4V7h-.868c-.689 1.266-1.558 2.222-2.618 2.857L2.486 8.143c1.395-.838 2.425-2.604 3.038-5.36l1.952.434c-.14.633-.303 1.227-.489 1.783H11.5v2H9v4h2.5v2H9.185l3.159 4.963zm3.838-.07L17.298 17H19V7h-4v10h.736l.446.893zM13 5h8v14h-3l-2.5 2-1-2H13V5z"/>
</g>
</svg>
| owncloud/web/packages/design-system/src/assets/icons/zhihu-line.svg/0 | {
"file_path": "owncloud/web/packages/design-system/src/assets/icons/zhihu-line.svg",
"repo_id": "owncloud",
"token_count": 392
} | 795 |
<template>
<oc-avatar-item
:width="width"
:icon-size="iconSize"
icon="global"
icon-fill-type="line"
icon-color="#D78841"
:name="name"
:accessible-label="accessibleLabel"
/>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import OcAvatarItem from '../OcAvatarItem/OcAvatarItem.vue'
export default defineComponent({
name: 'OcAvatarGuest',
status: 'ready',
release: '10.0.0',
components: { OcAvatarItem },
props: {
/**
* Name of the guest used as an accessible label
*/
name: {
type: String,
required: true
},
/**
* 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
},
/**
* Describes the size of the avatar icon e.g.(small)
*/
iconSize: {
type: String,
required: false,
default: 'small'
}
}
})
</script>
<docs>
```js
<oc-avatar-guest name="Guest" accessible-label="Guest" />
```
</docs>
| owncloud/web/packages/design-system/src/components/OcAvatarGuest/OcAvatarGuest.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcAvatarGuest/OcAvatarGuest.vue",
"repo_id": "owncloud",
"token_count": 552
} | 796 |
import Datepicker from './OcDatepicker.vue'
import { mount } from 'web-test-helpers'
describe('OcDatePicker', () => {
it('renders default scoped slot', () => {
const slotDefault = "<button id='default-slot'>Open datepicker</button>"
const wrapper = mount(Datepicker, {
slots: { default: slotDefault },
props: { value: null },
global: {
renderStubDefaultSlot: true
}
})
expect(wrapper.find('#default-slot').exists()).toBeTruthy()
})
})
| owncloud/web/packages/design-system/src/components/OcDatepicker/OcDatepicker.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcDatepicker/OcDatepicker.spec.ts",
"repo_id": "owncloud",
"token_count": 188
} | 797 |
<template>
<component
:is="type"
:class="[
{ 'oc-button-reset': type === 'button' },
'oc-icon',
sizeClass(size),
variationClass(variation)
]"
>
<inline-svg
:src="nameWithFillType"
:transform-source="transformSvgElement"
:aria-hidden="accessibleLabel === '' ? 'true' : null"
:aria-labelledby="accessibleLabel === '' ? null : svgTitleId"
:focusable="accessibleLabel === '' ? 'false' : null"
:style="color !== '' ? { fill: color } : {}"
@loaded="$emit('loaded')"
/>
</component>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import InlineSvg from 'vue-inline-svg'
import { AVAILABLE_SIZES } from '../../helpers/constants'
import { getSizeClass } from '../../utils/sizeClasses'
import uniqueId from '../../utils/uniqueId'
/**
* Icons are used to visually communicate core parts of the product and
* available actions. They can act as wayfinding tools to help users more
* easily understand where they are in the product.
*
* ## Accessibility
* You can pass a label to the icon via the `accessibleLabel` property. The component will automatically add a `title` element which is also referenced by its ID via `aria-labelledby`.
*
* Omit `accessibleLabel` if your icon has a decorative purpose only. In this case the component will:
* 1. set `aria-hidden` to `true`.
* 2. set `focusable` to `false`.
* 3. remove or empty all aria-related properties such as labels.
*/
/**
* InlineSvg by default expects the src to be a url, because we inline the SVG's this won't work.
* the download patch takes care of this by overwriting the native functionality and makes it compatible
*/
InlineSvg.name = 'inline-svg'
/*InlineSvg.methods.download = name => {
return (promise => {
if (promise.isPending) {
return promise
}
let isPending = true
let result = promise.then(
v => {
isPending = false
return v
},
e => {
isPending = false
throw e
}
)
result.isPending = function getIsPending() {
return isPending
}
return result
})(
new Promise((resolve, reject) => {
let svg
try {
svg = require("../../../assets/icons/" + name + ".svg")
} catch (e) {
return reject(e)
}
resolve(new DOMParser().parseFromString(svg, "image/svg+xml").documentElement)
})
)
}*/
export default defineComponent({
name: 'OcIcon',
status: 'ready',
release: '1.0.0',
components: {
InlineSvg
},
inheritAttrs: true,
props: {
/**
* The name of the icon to display.
*/
name: {
type: String,
default: 'info'
},
/**
* The fill type of the icon, fill or line
*/
fillType: {
type: String,
required: false,
default: 'fill',
validator: (value: string) => {
return ['fill', 'line', 'none'].includes(value)
}
},
/**
* Descriptive text to be read to screenreaders.
*/
accessibleLabel: {
type: String,
default: ''
},
/**
* The html element name used for the icon.
*/
type: {
type: String,
default: 'span'
},
/**
* The size of the icon. Defaults to small.
* `xsmall, small, medium, large, xlarge, xxlarge`
*/
size: {
type: String,
default: 'medium',
validator: (value) => {
return AVAILABLE_SIZES.some((e) => e === value)
}
},
/**
* Style variation to give additional meaning.
* Defaults to `passive`.
* Can be `passive, primary, danger, success, warning, brand or inherit`.
* `inherit` will not set any color but instead rely on a container element already
* setting the icon fill.
*/
variation: {
type: String,
default: 'passive',
validator: (value: string) => {
return ['passive', 'primary', 'danger', 'success', 'warning', 'brand', 'inherit'].includes(
value
)
}
},
/**
* Overwrite the color of the icon.
*/
color: {
type: String,
required: false,
default: ''
}
},
emits: ['loaded'],
computed: {
svgTitleId() {
return uniqueId('oc-icon-title-')
},
nameWithFillType() {
const path = 'icons/'
const fillType = this.fillType.toLowerCase()
if (fillType === 'none') {
return `${path}${this.name}.svg`
}
return `${path}${this.name}-${fillType}.svg`
}
},
methods: {
sizeClass(c) {
return this.prefix(getSizeClass(c))
},
variationClass(c) {
return this.prefix(c)
},
prefix(string) {
if (string !== null) {
return `oc-icon-${string}`
}
},
transformSvgElement(svg) {
if (this.accessibleLabel !== '') {
const title = document.createElement('title')
title.setAttribute('id', this.svgTitleId)
title.appendChild(document.createTextNode(this.accessibleLabel))
svg.insertBefore(title, svg.firstChild)
}
return svg
}
}
})
</script>
<style lang="scss">
@mixin oc-icon-size($factor) {
height: $oc-size-icon-default * $factor;
max-height: $oc-size-icon-default * $factor;
max-width: $oc-size-icon-default * $factor;
width: $oc-size-icon-default * $factor;
}
.oc-icon {
// SVG wrapper
display: inline-block;
vertical-align: baseline;
svg {
display: block;
}
&,
> svg {
@include oc-icon-size(1);
}
&-xs {
&,
> svg {
@include oc-icon-size(0.5);
}
}
&-s {
&,
> svg {
@include oc-icon-size(0.7);
}
}
&-m {
&,
> svg {
@include oc-icon-size(1);
}
}
&-l {
&,
> svg {
@include oc-icon-size(1.5);
}
}
&-xl {
&,
> svg {
@include oc-icon-size(2);
}
}
&-xxl {
&,
> svg {
@include oc-icon-size(4);
}
}
&-xxxl {
&,
> svg {
@include oc-icon-size(8);
}
}
&-primary > svg {
fill: var(--oc-color-swatch-primary-default);
}
&-passive > svg {
fill: var(--oc-color-swatch-passive-default);
}
&-warning > svg {
fill: var(--oc-color-swatch-warning-default);
}
&-success > svg {
fill: var(--oc-color-swatch-success-default);
}
&-danger > svg {
fill: var(--oc-color-swatch-danger-default);
}
&-brand > svg {
fill: var(--oc-color-swatch-brand-default);
}
}
</style>
<docs>
```js
<template>
<section>
<h3 class="oc-heading-divider">
Default icons
</h3>
<oc-icon name="close" accessible-label="Close"/>
<oc-icon name="delete-bin-5" accessible-label="Delete"/>
<oc-icon name="information" accessible-label="Information"/>
<oc-icon name="account-circle" accessible-label="Account"/>
<h3 class="oc-heading-divider">
Hover over the icons to see the effect of accessible labels
</h3>
<oc-icon size="large" name="account-circle" accessible-label="Account"/>
<h3 class="oc-heading-divider">
Default Icon color variations
</h3>
<oc-table-simple :hover="true">
<oc-thead>
<oc-tr>
<oc-th>Variation</oc-th>
<oc-th>Icons</oc-th>
</oc-tr>
</oc-thead>
<oc-tbody>
<oc-tr v-for="variation in variations" :key="'variation-' + variation.id">
<oc-td>{{ variation.name }}</oc-td>
<oc-td>
<oc-icon :variation="variation.name" name="close"/>
<oc-icon :variation="variation.name" name="delete-bin-5"/>
<oc-icon :variation="variation.name" name="information"/>
<oc-icon :variation="variation.name" name="account-circle"/>
</oc-td>
</oc-tr>
</oc-tbody>
</oc-table-simple>
<h3 class="oc-heading-divider">
If needed, you can pass custom colors to your Icon
</h3>
<oc-icon size="large" name="account-circle" color="lime"/>
<h3 class="oc-heading-divider">
Icon sizes
</h3>
<oc-table-simple :hover="true">
<oc-thead>
<oc-tr>
<oc-th>Size</oc-th>
<oc-th>Icons</oc-th>
</oc-tr>
</oc-thead>
<oc-tbody>
<oc-tr v-for="size in sizes" :key="size.name">
<oc-td>{{ size.name }}</oc-td>
<oc-td>
<oc-icon :size="size.name" name="close"/>
<oc-icon :size="size.name" name="delete-bin-5"/>
<oc-icon :size="size.name" name="information"/>
<oc-icon :size="size.name" name="account-circle"/>
</oc-td>
</oc-tr>
</oc-tbody>
</oc-table-simple>
</section>
</template>
<script>
export default {
computed: {
variations() {
return [{
id: "9828-4946-1277-7396",
name: "passive",
}, {
id: "7828-3285-4787-2127",
name: "primary",
}, {
id: "8376-8902-1172-2699",
name: "danger",
}, {
id: "4935-2899-4697-2615",
name: "success",
}, {
id: "2769-7633-8478-1257",
name: "warning",
}, {
id: "2324-8956-9042",
name: "brand",
}]
},
sizes() {
return [{
id: "6343-1519-1328-9822",
name: "xsmall",
}, {
id: "9041-7650-9126-4291",
name: "small",
}, {
id: "9665-6662-8676-4866",
name: "medium",
}, {
id: "9130-7140-3870-5438",
name: "large",
}, {
id: "5022-6406-9625-7093",
name: "xlarge",
}, {
id: "9337-2657-4486-1014",
name: "xxlarge",
}, {
id: "8234-4209-7553-9253",
name: "xxxlarge",
}]
},
},
}
</script>
```
</docs>
| owncloud/web/packages/design-system/src/components/OcIcon/OcIcon.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcIcon/OcIcon.vue",
"repo_id": "owncloud",
"token_count": 4571
} | 798 |
<template>
<div class="oc-notification oc-mb-s" :class="classes">
<slot />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
/**
* Notifications are used to inform users about errors, warnings and as confirmations for their actions. They will automatically disappear after a certain amount of time.
*
* The default slot can be filled with [OcNotificationMessage](#/oC%20Components/OcNotificationMessage) elements.
*
* ## Accessibility
*
* ### Notifications for screen reader users
* This component uses so called live regions in order to announce its content to screen readers once the notification appeared (this is not the normal modus operandi for screen readers, since their reading order is usually the DOM order – when the user does not take shortcuts). There are two types of live regions: `aria-live="polite"` (equivalent to `role="status"`) and `aria-live="assertive"` (equivalent to `role="alert"`). The latter directly interrupts the current output of the screen reader, the former waits until the current output is finished and reads the announcement afterwards. Since 'assertive' should be used sparingly, only `<oc-notfication-message>`'s "danger" status prop value uses `aria-live="assertive"` (and `role="alert"`). Using `aria-live` and `role="assertive|status"` simultaneously is for compatibility reasons regarding different browser and assistive technology pairings.
*/
export default defineComponent({
name: 'OcNotifications',
status: 'ready',
release: '1.0.0',
props: {
/**
* Position of the notifications.
* Valid values are: `top-left, top-center and top-right`
*/
position: {
type: String,
required: false,
default: 'top-center',
validator: (value: string) => {
return ['default', 'top-left', 'top-center', 'top-right'].includes(value)
}
}
},
computed: {
classes() {
return `oc-notification-${this.position}`
}
}
})
</script>
<style lang="scss">
.oc-notification {
box-sizing: border-box;
max-width: 100%;
width: 400px;
z-index: 1040;
&-top-left {
position: fixed;
top: var(--oc-space-small);
left: var(--oc-space-small);
}
&-top-center {
position: fixed;
top: var(--oc-space-small);
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
&-top-right {
position: fixed;
top: var(--oc-space-small);
right: var(--oc-space-small);
}
}
</style>
<docs>
```js
<template>
<section>
<h3 class="oc-heading-divider">
Notifications examples
</h3>
<oc-button @click="show('left')">Show left notifications</oc-button>
<oc-button @click="show('center')">Show center notifications</oc-button>
<oc-button @click="show('right')">Show right notifications</oc-button>
<oc-notifications position="top-left">
<oc-notification-message
v-for="item in messages.left"
:key="item.title"
:status="item.status"
:title="item.title"
:message="item.message"
:timeout="item.timeout"
@close="removeNotification('left', item)"
/>
</oc-notifications>
<oc-notifications position="top-center">
<oc-notification-message
v-for="item in messages.center"
:key="item.title"
:status="item.status"
:title="item.title"
:message="item.message"
:timeout="item.timeout"
@close="removeNotification('center', item)"
/>
</oc-notifications>
<oc-notifications position="top-right">
<oc-notification-message
v-for="(item, index) in messages.right"
:key="item.title"
:status="item.status"
:title="item.title"
:message="item.message"
:timeout="item.timeout"
@close="removeNotification('right', item)"
/>
</oc-notifications>
</section>
</template>
<script>
export default {
data: () => {
return {
messages: {
left: [],
center: [],
right: []
}
}
},
methods: {
removeNotification(position, item) {
this.messages[position] = this.messages[position].filter(el => el !== item);
},
show(position) {
this.messages[position] = [
{
title: 'Default without a message',
status: 'passive'
},
{
title: 'This is a primary notification with a long title that spans more than just one line',
message: 'And I have a message, too.',
status: 'primary'
},
{
title: 'This action could have consequences',
message: 'Are you sure?',
status: 'warning'
},
{
title: 'Folder created',
message: 'Just another day in paradise',
status: 'success'
},
{
title: 'Upload failed',
message: 'Holy Shoot. Something broke',
status: 'danger'
},
]
}
}
}
</script>
```
</docs>
| owncloud/web/packages/design-system/src/components/OcNotifications/OcNotifications.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcNotifications/OcNotifications.vue",
"repo_id": "owncloud",
"token_count": 2256
} | 799 |
import { defaultPlugins, mount } from 'web-test-helpers'
import OcSelect from './OcSelect.vue'
const selectors = {
ocSelect: '.oc-select',
selectedOptions: '.vs__selected-options .vs__selected',
deselectBtn: '.vs__selected-options .vs__deselect',
deselectLockIcon: '.vs__deselect-lock',
clearBtn: '.vs__clear',
searchInput: '.vs__search',
ocSpinner: '.oc-spinner',
warningMessage: '.oc-text-input-warning',
errorMessage: '.oc-text-input-danger',
descriptionMessage: '.oc-text-input-description'
}
describe('OcSelect', () => {
it('passes the options to the vue-select component', () => {
const options = [{ label: 'label1' }, { label: 'label2' }]
const wrapper = getWrapper({ options })
expect(
// options is just passed through, so it does not exist as prop on OcSelect, hence we need the any cast
wrapper.findComponent<typeof OcSelect>(selectors.ocSelect).props('options' as any)
).toEqual(options)
})
it('shows ocSpinner component when loading', () => {
const wrapper = getWrapper({ loading: true })
expect(wrapper.find(selectors.ocSpinner).exists()).toBeTruthy()
})
it('triggers the "search:input"-event on search input', async () => {
const wrapper = getWrapper()
await wrapper.find(selectors.searchInput).trigger('input')
expect(wrapper.emitted('search:input')).toBeDefined()
})
describe('clear button', () => {
it('is hidden by default', () => {
const options = [{ label: 'label1' }, { label: 'label2' }]
const wrapper = getWrapper({ options, modelValue: options[0] })
expect(wrapper.find(selectors.clearBtn).attributes('style')).toEqual('display: none;')
})
it('is visible if "clearable" is set to true', () => {
const options = [{ label: 'label1' }, { label: 'label2' }]
const wrapper = getWrapper({ options, modelValue: options[0], clearable: true })
expect(wrapper.find(selectors.clearBtn).attributes('style')).toBeUndefined()
})
})
describe('selected option', () => {
it('displays', () => {
const options = [{ label: 'label1' }, { label: 'label2' }]
const wrapper = getWrapper({ options, modelValue: options[0] })
expect(wrapper.findAll(selectors.selectedOptions).length).toBe(1)
expect(wrapper.findAll(selectors.selectedOptions).at(0).text()).toEqual(options[0].label)
})
it('displays with a custom label property', () => {
const options = [{ customLabel: 'label1' }, { customLabel: 'label2' }]
const wrapper = getWrapper({ options, modelValue: options[0], optionLabel: 'customLabel' })
expect(wrapper.findAll(selectors.selectedOptions).at(0).text()).toEqual(
options[0].customLabel
)
})
it('can be cleared if multi-select is allowed', () => {
const options = [{ label: 'label1' }, { label: 'label2' }]
const wrapper = getWrapper({ options, modelValue: options[0], multiple: true })
expect(wrapper.find(selectors.deselectBtn).exists()).toBeTruthy()
expect(wrapper.find(selectors.deselectLockIcon).exists()).toBeFalsy()
})
it('can not be cleared if readonly', () => {
const options = [{ label: 'label1', readonly: true }, { label: 'label2' }]
const wrapper = getWrapper({ options, modelValue: options[0], multiple: true })
expect(wrapper.find(selectors.deselectBtn).exists()).toBeFalsy()
expect(wrapper.find(selectors.deselectLockIcon).exists()).toBeTruthy()
})
})
describe('message', () => {
it('displays a warning message', () => {
const wrapper = getWrapper({ warningMessage: 'foo' })
expect(wrapper.find(selectors.warningMessage).exists()).toBeTruthy()
})
it('displays an error message', () => {
const wrapper = getWrapper({ errorMessage: 'foo' })
expect(wrapper.find(selectors.errorMessage).exists()).toBeTruthy()
})
it('displays a description message', () => {
const wrapper = getWrapper({ descriptionMessage: 'foo' })
expect(wrapper.find(selectors.descriptionMessage).exists()).toBeTruthy()
})
})
})
function getWrapper(props = {}) {
return mount(OcSelect, {
props,
global: {
plugins: [...defaultPlugins()]
}
})
}
| owncloud/web/packages/design-system/src/components/OcSelect/OcSelect.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcSelect/OcSelect.spec.ts",
"repo_id": "owncloud",
"token_count": 1522
} | 800 |
<template>
<div :class="$attrs.class">
<label class="oc-label" :for="id" v-text="label" />
<div class="oc-position-relative">
<oc-icon
v-if="readOnly"
name="lock"
size="small"
class="oc-mt-s oc-ml-s oc-position-absolute"
/>
<component
:is="inputComponent"
:id="id"
v-bind="additionalAttributes"
ref="input"
:aria-invalid="ariaInvalid"
class="oc-text-input oc-input oc-rounded"
:class="{
'oc-text-input-warning': !!warningMessage,
'oc-text-input-danger': !!errorMessage,
'oc-pl-l': !!readOnly
}"
:type="type"
:value="displayValue"
:disabled="disabled || readOnly"
v-on="additionalListeners"
@change="onChange(($event.target as HTMLInputElement).value)"
@input="onInput(($event.target as HTMLInputElement).value)"
@password-challenge-completed="$emit('passwordChallengeCompleted')"
@password-challenge-failed="$emit('passwordChallengeFailed')"
@focus="onFocus($event.target)"
/>
<oc-button
v-if="showClearButton"
:aria-label="clearButtonAccessibleLabelValue"
class="oc-pr-s oc-position-center-right oc-text-input-btn-clear"
appearance="raw"
@click="onClear"
>
<oc-icon name="close" size="small" variation="passive" />
</oc-button>
</div>
<div
v-if="showMessageLine"
class="oc-text-input-message"
:class="{
'oc-text-input-description': !!descriptionMessage,
'oc-text-input-warning': !!warningMessage,
'oc-text-input-danger': !!errorMessage
}"
>
<oc-icon
v-if="messageText !== null && !!descriptionMessage"
name="information"
size="small"
fill-type="line"
accessible-label="info"
aria-hidden="true"
/>
<span
:id="messageId"
:class="{
'oc-text-input-description': !!descriptionMessage,
'oc-text-input-warning': !!warningMessage,
'oc-text-input-danger': !!errorMessage
}"
v-text="messageText"
/>
</div>
<portal-target v-if="type === 'password'" name="app.design-system.password-policy" />
</div>
</template>
<script lang="ts">
import { defineComponent, HTMLAttributes, PropType } from 'vue'
import uniqueId from '../../utils/uniqueId'
import OcButton from '../OcButton/OcButton.vue'
import OcIcon from '../OcIcon/OcIcon.vue'
import OcTextInputPassword from '../_OcTextInputPassword/_OcTextInputPassword.vue'
import { PasswordPolicy } from '../../helpers'
/**
* Form Inputs are used to allow users to provide text input when the expected
* input is short. Form Input has a range of options and supports several text
* formats including numbers. For longer input, use the form `Textarea` element.*
*
* ## Accessibility
* The label is required and represents the name of the input.
*
* The description-message can be used additionally to give further information about the input field. When a
* description is given, it will be automatically referenced via the `aria-describedby` property.
* An error or warning will replace the description as well as the `aria-describedby` property until the error
* or warning is fixed.
*/
export default defineComponent({
name: 'OcTextInput',
components: { OcIcon, OcButton, OcTextInputPassword },
status: 'ready',
release: '1.0.0',
inheritAttrs: false,
props: {
/**
* The ID of the element.
*/
id: {
type: String,
required: false,
default: () => uniqueId('oc-textinput-')
},
/**
* The type of the form input field.
* `text, number, email, password`
*/
type: {
type: String,
default: 'text',
validator: (value: string) => {
return ['text', 'number', 'email', 'password'].includes(value)
}
},
/**
* Text value of the form input field.
* @model
*/
modelValue: {
type: String,
required: false,
default: null
},
/**
* Selection range to accomplish partial selection
*/
selectionRange: {
type: Array as unknown as PropType<[number, number]>,
required: false,
default: null
},
/**
* Whether or not the input element should have a dedicated button for clearing the input content.
*/
clearButtonEnabled: {
type: Boolean,
required: false,
default: false
},
/**
* The aria label for the clear button. Only used if it's enabled at all.
*/
clearButtonAccessibleLabel: {
type: String,
required: false,
default: ''
},
/**
* Value to show when no value is provided
* This does not set `value` automatically.
* The user needs to explicitly enter a text to set it as `value`.
*/
defaultValue: {
type: String,
required: false,
default: null
},
/**
* Disables the input field
*/
disabled: {
type: Boolean,
default: false
},
/**
* Accessible label of the form input field.
**/
label: {
type: String,
required: true,
default: null
},
/**
* A warning message which is shown below the input.
*/
warningMessage: {
type: String,
default: null
},
/**
* An error message which is shown below the input.
*/
errorMessage: {
type: String,
default: null
},
/**
* Whether or not vertical space below the input should be reserved for a one line message,
* so that content actually appearing there doesn't shift the layout.
*/
fixMessageLine: {
type: Boolean,
default: false
},
/**
* A description text which is shown below the input field.
*/
descriptionMessage: {
type: String,
default: null
},
/**
* Determines if the input field is read only.
*
* Read only field will be visualized by a lock item and additionally behaves like a disabled field.
* Read only takes effect if the server won't allow to change the value at all,
* disabled should be used instead, if the value can't be changed in a specific context.
*
* For example: If the backend doesn't allow to set the login states for users in general, use read only.
* If it's not allowed to change for the current logged-in User, use disabled.
*
*/
readOnly: {
type: Boolean,
default: false
},
/**
* Array of password policy rules, if type is password and password policy is given,
* the entered value will be checked against these rules.
*
* Password policy rules must be compliant with auth0/password-sheriff
* https://github.com/auth0/password-sheriff
*
*/
passwordPolicy: {
type: Object as PropType<PasswordPolicy>,
default: () => ({})
},
/**
* Method to generate random password
*/
generatePasswordMethod: {
type: Function as PropType<(...args: unknown[]) => string>,
required: false,
default: null
}
},
emits: [
'change',
'update:modelValue',
'focus',
'passwordChallengeCompleted',
'passwordChallengeFailed'
],
computed: {
showMessageLine() {
return (
this.fixMessageLine ||
!!this.warningMessage ||
!!this.errorMessage ||
!!this.descriptionMessage
)
},
messageId() {
return `${this.id}-message`
},
additionalListeners() {
if (this.type === 'password') {
return { passwordGenerated: this.onInput }
}
return {}
},
additionalAttributes() {
const additionalAttrs = {}
if (!!this.warningMessage || !!this.errorMessage || !!this.descriptionMessage) {
additionalAttrs['aria-describedby'] = this.messageId
}
// FIXME: placeholder usage is discouraged, we need to find a better UX concept
if (this.defaultValue) {
additionalAttrs['placeholder'] = this.defaultValue
}
if (this.type === 'password') {
additionalAttrs['password-policy'] = this.passwordPolicy
additionalAttrs['generate-password-method'] = this.generatePasswordMethod
additionalAttrs['has-warning'] = !!this.warningMessage
additionalAttrs['has-error'] = !!this.errorMessage
}
// Exclude listeners for events which are handled via methods in this component
// eslint-disable-next-line no-unused-vars
const { change, input, focus, class: classes, ...attrs } = this.$attrs
return { ...attrs, ...additionalAttrs }
},
ariaInvalid() {
return (!!this.errorMessage).toString() as HTMLAttributes['aria-invalid']
},
messageText() {
if (this.errorMessage) {
return this.errorMessage
}
if (this.warningMessage) {
return this.warningMessage
}
return this.descriptionMessage
},
showClearButton() {
return !this.disabled && this.clearButtonEnabled && this.modelValue !== null
},
clearButtonAccessibleLabelValue() {
return this.clearButtonAccessibleLabel || this.$gettext('Clear input')
},
displayValue() {
return this.modelValue || ''
},
inputComponent() {
return this.type === 'password' ? 'oc-text-input-password' : 'input'
}
},
methods: {
/**
* Puts focus on this input element
* @public
*/
focus() {
;(this.$refs.input as HTMLInputElement).focus()
},
onClear() {
this.focus()
this.onInput(null)
this.onChange(null)
},
onChange(value: string) {
/**
* Change event
* @type {event}
**/
this.$emit('change', value)
},
onInput(value: string) {
/**
* Input event
* @type {event}
**/
this.$emit('update:modelValue', value)
},
onFocus(target: HTMLInputElement) {
target.select()
if (this.selectionRange && this.selectionRange.length > 1) {
target.setSelectionRange(this.selectionRange[0], this.selectionRange[1])
}
/**
* Focus event - emitted as soon as the input field is focused
* @type {event}
**/
this.$emit('focus', target.value)
}
}
})
</script>
<style lang="scss">
.oc-text-input-message.oc-text-input-description {
display: flex;
align-items: center;
position: relative;
padding-left: var(--oc-space-large);
padding-top: calc(var(--oc-space-xsmall) - 2px);
.oc-icon {
position: absolute;
left: var(--oc-space-xsmall);
top: var(--oc-space-xsmall);
}
}
.oc-text-input {
&-description {
color: var(--oc-color-text-muted);
}
&-success,
&-success:focus {
border-color: var(--oc-color-swatch-success-default) !important;
color: var(--oc-color-swatch-success-default) !important;
}
&-warning,
&-warning:focus {
border-color: var(--oc-color-swatch-warning-default) !important;
color: var(--oc-color-swatch-warning-default) !important;
}
&-danger,
&-danger:focus {
border-color: var(--oc-color-swatch-danger-default) !important;
color: var(--oc-color-swatch-danger-default) !important;
}
&-message {
display: flex;
align-items: center;
margin-top: var(--oc-space-xsmall);
min-height: $oc-font-size-default * 1.5;
}
}
</style>
<docs>
```js
<template>
<section>
<h3 class="oc-heading-divider">
Input Types
</h3>
<oc-text-input class="oc-mb-s" label="Text"/>
<oc-text-input class="oc-mb-s" disabled label="Disabled" value="I am disabled"/>
<oc-text-input class="oc-mb-s" read-only="true" label="Read only" value="I am read only"/>
<oc-text-input class="oc-mb-s" type="number" label="Number"/>
<oc-text-input class="oc-mb-s" type="email" label="Email"/>
<oc-text-input class="oc-mb-s" type="password" label="Password"/>
<h3 class="oc-heading-divider">
Binding
</h3>
<oc-text-input label="Text" v-model="inputValue"/>
<oc-text-input disabled label="Text" v-model="inputValue"/>
<h3 class="oc-heading-divider">
Interactions
</h3>
<oc-button @click="_focus" class="oc-my-m">Focus input below</oc-button>
<oc-text-input label="Focus field" ref="inputForFocus"/>
<oc-button @click="_focusAndSelect" class="oc-my-m">Focus and select input below</oc-button>
<oc-text-input label="Select field" value="Will you select this existing text?" ref="inputForFocusSelect"/>
<oc-text-input label="Clear input" v-model="inputValueForClearing" :clear-button-enabled="true" />
<oc-text-input label="Input with default" v-model="inputValueWithDefault" :clear-button-enabled="true" default-value="Some default"/>
<p>
Value: {{ inputValueWithDefault !== null ? inputValueWithDefault : "null" }}
</p>
<h3 class="oc-heading-divider">
Messages
</h3>
<oc-text-input
label="Input with description message below"
class="oc-mb-s"
description-message="This is a description message."
:fix-message-line="true"
/>
<oc-text-input
label="Input with error and warning messages with reserved space below"
class="oc-mb-s"
v-model="valueForMessages"
:error-message="errorMessage"
:warning-message="warningMessage"
:fix-message-line="true"
/>
<oc-text-input
label="Input with error and warning messages without reserved space below"
class="oc-mb-s"
v-model="valueForMessages"
:error-message="errorMessage"
:warning-message="warningMessage"
/>
</section>
</template>
<script>
export default {
data: () => {
return {
inputValue: 'initial',
valueForMessages: '',
inputValueForClearing: 'clear me',
inputValueWithDefault: null,
}
},
computed: {
errorMessage() {
return this.valueForMessages.length === 0 ? 'Value is required.' : ''
},
warningMessage() {
return this.valueForMessages.endsWith(' ') ? 'Trailing whitespace should be avoided.' : ''
}
},
methods: {
_focus() {
this.$refs.inputForFocus.focus()
},
_focusAndSelect() {
this.$refs.inputForFocusSelect.focus()
}
}
}
</script>
```
</docs>
| owncloud/web/packages/design-system/src/components/OcTextInput/OcTextInput.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/OcTextInput/OcTextInput.vue",
"repo_id": "owncloud",
"token_count": 5740
} | 801 |
<template>
<tfoot>
<slot />
</tfoot>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: 'OcTfoot',
status: 'ready',
release: '2.1.0'
})
</script>
| owncloud/web/packages/design-system/src/components/_OcTableFooter/_OcTableFooter.vue/0 | {
"file_path": "owncloud/web/packages/design-system/src/components/_OcTableFooter/_OcTableFooter.vue",
"repo_id": "owncloud",
"token_count": 85
} | 802 |
import { createApp, defineComponent } from 'vue'
import DesignSystem from './index'
const options = {
tokens: {
breakpoints: {
'xsmall-max': '50px'
},
colorPalette: {
'background-default': '#ef23ab',
'swatch-brand-default': '#00FFFF'
},
fontSizes: {
default: '1.358rem'
},
sizes: {
'icon-default': '12pt'
},
spacing: {
small: '20px'
}
}
}
describe('Depending on what gets passed into the theming options', () => {
it('Sets correct custom CSS props from theming options', () => {
const app = createApp(
defineComponent({
template: '<div/>'
})
)
app.config.compilerOptions.whitespace = 'preserve'
app.use(DesignSystem, options)
app.mount('body')
expect(document.documentElement.style.getPropertyValue('--oc-breakpoint-xsmall-max')).toMatch(
'50px'
)
expect(
document.documentElement.style.getPropertyValue('--oc-color-background-default')
).toMatch('#ef23ab')
expect(
document.documentElement.style.getPropertyValue('--oc-color-swatch-brand-default')
).toMatch('#00FFFF')
expect(document.documentElement.style.getPropertyValue('--oc-font-size-default')).toMatch(
'1.358rem'
)
expect(document.documentElement.style.getPropertyValue('--oc-size-icon-default')).toMatch(
'12pt'
)
expect(document.documentElement.style.getPropertyValue('--oc-space-small')).toMatch('20px')
})
// eslint-disable-next-line
// it('Defaults to ODS colors where none are passed in theming options', () => {
// expect(document.documentElement.style.getPropertyValue('--oc-color')).toMatch("green")
// expect(document.documentElement.style.getPropertyValue('--oc-brand-primary-hover')).toMatch('#223959')
// })
})
| owncloud/web/packages/design-system/src/index.spec.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/index.spec.ts",
"repo_id": "owncloud",
"token_count": 694
} | 803 |
$directives: ("m": "margin", "p": "padding");
@each $directiveKey, $directiveValue in $directives {
.oc-#{$directiveKey} {
#{$directiveValue}: $oc-space-medium !important;
@each $directionKey, $directionValues in $directions {
&#{$directionKey} {
@each $direction in $directionValues {
#{$directiveValue}-#{$direction}: $oc-space-medium !important;
@each $sizeKey, $sizeValue in $sizes {
&-#{$sizeKey} {
#{$directiveValue}-#{$direction}: $sizeValue !important;
}
}
&-rm {
#{$directiveValue}-#{$direction}: 0 !important;
}
}
}
}
@each $sizeKey, $sizeValue in $sizes {
&-#{$sizeKey} {
#{$directiveValue}: $sizeValue !important;
}
}
&-rm {
#{$directiveValue}: 0 !important;
}
}
}
| owncloud/web/packages/design-system/src/styles/theme/oc-spacing.scss/0 | {
"file_path": "owncloud/web/packages/design-system/src/styles/theme/oc-spacing.scss",
"repo_id": "owncloud",
"token_count": 427
} | 804 |
const sizeClassMappings = {
xxxsmall: 'xxxs',
xxsmall: 'xxs',
xsmall: 'xs',
small: 's',
medium: 'm',
large: 'l',
xlarge: 'xl',
xxlarge: 'xxl',
xxxlarge: 'xxxl',
remove: 'rm'
}
export function getSizeClass(size) {
return sizeClassMappings[size]
}
| owncloud/web/packages/design-system/src/utils/sizeClasses.ts/0 | {
"file_path": "owncloud/web/packages/design-system/src/utils/sizeClasses.ts",
"repo_id": "owncloud",
"token_count": 116
} | 805 |
[main]
host = https://www.transifex.com
[o:owncloud-org:p:owncloud-web:r:admin-settings]
file_filter = locale/<lang>/LC_MESSAGES/app.po
minimum_perc = 0
source_file = template.pot
source_lang = en
type = PO
| owncloud/web/packages/web-app-admin-settings/l10n/.tx/config/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/l10n/.tx/config",
"repo_id": "owncloud",
"token_count": 85
} | 806 |
<template>
<div>
<oc-list id="oc-spaces-actions-sidebar" class-name="oc-mt-s">
<action-menu-item
v-for="(action, index) in actions"
:key="`action-${index}`"
class="oc-rounded"
:action="action"
:action-options="actionOptions"
/>
</oc-list>
</div>
</template>
<script lang="ts">
import { ActionMenuItem } from '@ownclouders/web-pkg'
import {
useSpaceActionsDelete,
useSpaceActionsDisable,
useSpaceActionsEditDescription,
useSpaceActionsEditQuota,
useSpaceActionsRename,
useSpaceActionsRestore
} from '@ownclouders/web-pkg'
import { computed, defineComponent, inject, unref } from 'vue'
import { SpaceResource } from '@ownclouders/web-client'
export default defineComponent({
name: 'ActionsPanel',
components: { ActionMenuItem },
setup() {
const resource = inject<SpaceResource>('resource')
const resources = computed(() => {
return [unref(resource)]
})
const actionOptions = computed(() => ({
resources: unref(resources)
}))
const { actions: deleteActions } = useSpaceActionsDelete()
const { actions: disableActions } = useSpaceActionsDisable()
const { actions: editDescriptionActions } = useSpaceActionsEditDescription()
const { actions: editQuotaActions } = useSpaceActionsEditQuota()
const { actions: renameActions } = useSpaceActionsRename()
const { actions: restoreActions } = useSpaceActionsRestore()
const actions = computed(() => {
return [
...unref(renameActions),
...unref(editDescriptionActions),
...unref(editQuotaActions),
...unref(restoreActions),
...unref(deleteActions),
...unref(disableActions)
].filter((item) => item.isVisible(unref(actionOptions)))
})
return {
actions,
actionOptions,
resources
}
}
})
</script>
<style lang="scss">
#oc-spaces-actions-sidebar {
> li a,
> li a:hover {
color: var(--oc-color-swatch-passive-default);
display: inline-flex;
gap: 10px;
vertical-align: top;
}
}
</style>
| owncloud/web/packages/web-app-admin-settings/src/components/Spaces/SideBar/ActionsPanel.vue/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/src/components/Spaces/SideBar/ActionsPanel.vue",
"repo_id": "owncloud",
"token_count": 804
} | 807 |
import { supportedLogoMimeTypes } from '../../../defaults'
import { computed, VNodeRef, unref } from 'vue'
import { Action, useMessages } from '@ownclouders/web-pkg'
import { useAbility, useClientService, useRouter } from '@ownclouders/web-pkg'
import { useGettext } from 'vue3-gettext'
export const useGeneralActionsUploadLogo = ({ imageInput }: { imageInput: VNodeRef }) => {
const { showMessage, showErrorMessage } = useMessages()
const { $gettext } = useGettext()
const ability = useAbility()
const clientService = useClientService()
const router = useRouter()
const uploadImage = async (ev: InputEvent) => {
const file = (ev.currentTarget as HTMLInputElement).files[0]
if (!file) {
return
}
if (!supportedLogoMimeTypes.includes(file.type)) {
return showErrorMessage({ title: $gettext('The file type is unsupported') })
}
try {
const httpClient = clientService.httpAuthenticated
const formData = new FormData()
formData.append('logo', file)
await httpClient.post('/branding/logo', formData as never, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
showMessage({ title: $gettext('Logo was uploaded successfully') })
setTimeout(() => {
router.go(0)
}, 1000)
} catch (e) {
console.error(e)
showErrorMessage({
title: $gettext('Failed to upload logo'),
errors: [e]
})
}
}
const actions = computed((): Action[] => [
{
name: 'upload-logo',
icon: 'image-add',
label: () => {
return $gettext('Upload logo')
},
isVisible: () => {
return ability.can('update-all', 'Logo')
},
handler: () => {
unref(imageInput).click()
},
componentType: 'button',
class: 'oc-general-actions-upload-logo-trigger'
}
])
return {
actions,
uploadImage
}
}
| owncloud/web/packages/web-app-admin-settings/src/composables/actions/general/useGeneralActionsUploadLogo.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/src/composables/actions/general/useGeneralActionsUploadLogo.ts",
"repo_id": "owncloud",
"token_count": 766
} | 808 |
import { onBeforeUnmount, onMounted, unref, Ref } from 'vue'
import { eventBus } from '@ownclouders/web-pkg'
import { KeyboardActions } from '@ownclouders/web-pkg'
import { findIndex, find } from 'lodash-es'
import { Resource } from '@ownclouders/web-client'
import { Item } from '@ownclouders/web-client/src/helpers'
export const useKeyboardTableMouseActions = (
keyActions: KeyboardActions,
paginatedResources: Ref<{ id: string }[]>,
selectedRows: Ref<Item[]>,
lastSelectedRowIndex: Ref<number>,
lastSelectedRowId: Ref<string | null>
) => {
let resourceListClickedMetaEvent
let resourceListClickedShiftEvent
const handleCtrlClickAction = (resource: Resource) => {
const rowIndex = findIndex(unref(selectedRows), { id: resource.id })
if (rowIndex >= 0) {
selectedRows.value = unref(selectedRows).filter((item) => item.id != resource.id)
} else {
unref(selectedRows).push(resource)
}
keyActions.resetSelectionCursor()
lastSelectedRowIndex.value = rowIndex >= 0 ? rowIndex : unref(selectedRows).length - 1
lastSelectedRowId.value = String(resource.id)
}
const handleShiftClickAction = ({ resource, skipTargetSelection }) => {
const parent = document.querySelectorAll(`[data-item-id='${resource.id}']`)[0]
const resourceNodes = Object.values(parent.parentNode.children)
const latestNode = resourceNodes.find(
(r) => r.getAttribute('data-item-id') === unref(lastSelectedRowId)
)
const clickedNode = resourceNodes.find((r) => r.getAttribute('data-item-id') === resource.id)
let latestNodeIndex = resourceNodes.indexOf(latestNode)
latestNodeIndex = latestNodeIndex === -1 ? 0 : latestNodeIndex
const clickedNodeIndex = resourceNodes.indexOf(clickedNode)
const minIndex = Math.min(latestNodeIndex, clickedNodeIndex)
const maxIndex = Math.max(latestNodeIndex, clickedNodeIndex)
for (let i = minIndex; i <= maxIndex; i++) {
const nodeId = resourceNodes[i].getAttribute('data-item-id')
if (skipTargetSelection && nodeId === resource.id) {
continue
}
const selectedRowIndex = findIndex(unref(selectedRows), { id: nodeId })
if (selectedRowIndex === -1) {
const selectedRow = find(paginatedResources.value, { id: nodeId })
unref(selectedRows).push(selectedRow)
}
}
lastSelectedRowIndex.value = findIndex(paginatedResources.value, { id: resource.id })
lastSelectedRowId.value = String(resource.id)
keyActions.resetSelectionCursor()
}
onMounted(() => {
resourceListClickedMetaEvent = eventBus.subscribe(
'app.resources.list.clicked.meta',
handleCtrlClickAction
)
resourceListClickedShiftEvent = eventBus.subscribe(
'app.resources.list.clicked.shift',
handleShiftClickAction
)
})
onBeforeUnmount(() => {
eventBus.unsubscribe('app.resources.list.clicked.meta', resourceListClickedMetaEvent)
eventBus.unsubscribe('app.resources.list.clicked.shift', resourceListClickedShiftEvent)
})
}
| owncloud/web/packages/web-app-admin-settings/src/composables/keyboardActions/useKeyboardTableMouseActions.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/src/composables/keyboardActions/useKeyboardTableMouseActions.ts",
"repo_id": "owncloud",
"token_count": 1070
} | 809 |
import DetailsPanel from '../../../../../src/components/Groups/SideBar/DetailsPanel.vue'
import { defaultPlugins, mount } from 'web-test-helpers'
describe('DetailsPanel', () => {
describe('computed method "group"', () => {
it('should be set if only one group is given', () => {
const { wrapper } = getWrapper({
propsData: { groups: [{ displayName: 'group', members: [] }] }
})
expect(wrapper.vm.group).toEqual({ displayName: 'group', members: [] })
})
it('should not be set if no groups are given', () => {
const { wrapper } = getWrapper({
propsData: { groups: [] }
})
expect(wrapper.vm.group).toEqual(null)
})
it('should not be set if multiple groups are given', () => {
const { wrapper } = getWrapper({
propsData: {
groups: [
{ displayName: 'group1', members: [] },
{ displayName: 'group2', members: [] }
]
}
})
expect(wrapper.vm.group).toEqual(null)
})
})
describe('computed method "noGroups"', () => {
it('should be true if no groups are given', () => {
const { wrapper } = getWrapper({
propsData: { groups: [] }
})
expect(wrapper.vm.noGroups).toBeTruthy()
})
it('should be false if groups are given', () => {
const { wrapper } = getWrapper({
propsData: { groups: [{ displayName: 'group', members: [] }] }
})
expect(wrapper.vm.noGroups).toBeFalsy()
})
})
describe('computed method "multipleGroups"', () => {
it('should be false if no groups are given', () => {
const { wrapper } = getWrapper({ propsData: { groups: [] } })
expect(wrapper.vm.multipleGroups).toBeFalsy()
})
it('should be false if one group is given', () => {
const { wrapper } = getWrapper({
propsData: { groups: [{ displayName: 'group', members: [] }] }
})
expect(wrapper.vm.multipleGroups).toBeFalsy()
})
it('should be true if multiple groups are given', () => {
const { wrapper } = getWrapper({
propsData: { groups: [{ displayName: 'group1' }, { displayName: 'group2', members: [] }] }
})
expect(wrapper.vm.multipleGroups).toBeTruthy()
})
})
})
function getWrapper({ propsData = {} } = {}) {
return {
wrapper: mount(DetailsPanel, {
props: {
groups: [],
...propsData
},
global: {
stubs: {
'avatar-image': true,
'oc-icon': true
},
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-app-admin-settings/tests/unit/components/Groups/SideBar/DetailsPanel.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/components/Groups/SideBar/DetailsPanel.spec.ts",
"repo_id": "owncloud",
"token_count": 1071
} | 810 |
import LoginModal from '../../../../src/components/Users/LoginModal.vue'
import {
defaultComponentMocks,
defaultPlugins,
mockAxiosResolve,
shallowMount
} from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { User } from '@ownclouders/web-client/src/generated'
import { Modal, useMessages } from '@ownclouders/web-pkg'
import { OcSelect } from 'design-system/src/components'
import { useUserSettingsStore } from '../../../../src/composables/stores/userSettings'
describe('LoginModal', () => {
it('renders the input including two options', () => {
const { wrapper } = getWrapper()
expect(wrapper.html()).toMatchSnapshot()
})
it('shows a warning when the current user is being selected', () => {
const { wrapper } = getWrapper([mock<User>({ id: '1' })])
expect(
wrapper.findComponent<typeof OcSelect>('oc-select-stub').props('warningMessage')
).toBeDefined()
})
describe('method "onConfirm"', () => {
it('updates the login for all given users', async () => {
const users = [mock<User>(), mock<User>()]
const { wrapper, mocks } = getWrapper(users)
mocks.$clientService.graphAuthenticated.users.editUser.mockResolvedValue(
mockAxiosResolve({ id: 'e3515ffb-d264-4dfc-8506-6c239f6673b5' })
)
mocks.$clientService.graphAuthenticated.users.getUser.mockResolvedValue(
mockAxiosResolve({ id: 'e3515ffb-d264-4dfc-8506-6c239f6673b5' })
)
await wrapper.vm.onConfirm()
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalled()
const { upsertUser } = useUserSettingsStore()
expect(upsertUser).toHaveBeenCalledTimes(users.length)
expect(mocks.$clientService.graphAuthenticated.users.editUser).toHaveBeenCalledTimes(
users.length
)
})
it('omits the currently logged in user', async () => {
const users = [mock<User>({ id: '1' }), mock<User>()]
const { wrapper, mocks } = getWrapper(users)
mocks.$clientService.graphAuthenticated.users.editUser.mockResolvedValue(
mockAxiosResolve({ id: 'e3515ffb-d264-4dfc-8506-6c239f6673b5' })
)
mocks.$clientService.graphAuthenticated.users.getUser.mockResolvedValue(
mockAxiosResolve({ id: 'e3515ffb-d264-4dfc-8506-6c239f6673b5' })
)
await wrapper.vm.onConfirm()
expect(mocks.$clientService.graphAuthenticated.users.editUser).toHaveBeenCalledTimes(1)
})
it('should show message on error', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
const users = [mock<User>(), mock<User>()]
const { wrapper, mocks } = getWrapper(users)
mocks.$clientService.graphAuthenticated.users.editUser.mockRejectedValue(new Error(''))
mocks.$clientService.graphAuthenticated.users.getUser.mockRejectedValue(new Error(''))
await wrapper.vm.onConfirm()
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalled()
})
})
})
function getWrapper(users = [mock<User>()]) {
const mocks = defaultComponentMocks()
return {
mocks,
wrapper: shallowMount(LoginModal, {
props: {
modal: mock<Modal>(),
users
},
global: {
provide: mocks,
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-app-admin-settings/tests/unit/components/Users/LoginModal.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/components/Users/LoginModal.spec.ts",
"repo_id": "owncloud",
"token_count": 1327
} | 811 |
import { useUserActionsEdit } from '../../../../../src/composables/actions/users/useUserActionsEdit'
import { mock } from 'vitest-mock-extended'
import { unref } from 'vue'
import { User } from '@ownclouders/web-client/src/generated'
import { getComposableWrapper } from 'web-test-helpers'
describe('useUserActionsEdit', () => {
describe('method "isVisible"', () => {
it.each([
{ resources: [mock<User>()], isVisible: true },
{ resources: [], isVisible: false },
{ resources: [mock<User>(), mock<User>()], isVisible: false }
])('should only return true for one user', ({ resources, isVisible }) => {
getWrapper({
setup: ({ actions }) => {
expect(unref(actions)[0].isVisible({ resources })).toEqual(isVisible)
}
})
})
})
})
function getWrapper({
setup
}: {
setup: (instance: ReturnType<typeof useUserActionsEdit>) => void
}) {
return {
wrapper: getComposableWrapper(() => {
const instance = useUserActionsEdit()
setup(instance)
})
}
}
| owncloud/web/packages/web-app-admin-settings/tests/unit/composables/actions/users/useUserActionsEdit.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/composables/actions/users/useUserActionsEdit.spec.ts",
"repo_id": "owncloud",
"token_count": 403
} | 812 |
import { Resource } from '@ownclouders/web-client/src'
import { AppWrapperRoute, defineWebApplication, useUserStore } from '@ownclouders/web-pkg'
import translations from '../l10n/translations.json'
import App from './App.vue'
import { useGettext } from 'vue3-gettext'
const applicationId = 'draw-io'
export default defineWebApplication({
setup() {
const { $gettext } = useGettext()
const userStore = useUserStore()
const routes = [
{
name: 'draw-io',
path: '/:driveAliasAndItem(.*)?',
component: AppWrapperRoute(App, {
applicationId,
importResourceWithExtension(resource: Resource) {
return resource.extension === 'vsdx' ? 'drawio' : null
}
}),
meta: {
authContext: 'hybrid',
patchCleanPath: true
}
}
]
return {
appInfo: {
name: 'Draw.io',
id: applicationId,
icon: 'grid',
color: '#EF6C00',
applicationMenu: {
enabled: () => {
return !!userStore.user
},
priority: 30,
openAsEditor: true
},
defaultExtension: 'drawio',
extensions: [
{
extension: 'drawio',
routeName: 'draw-io',
newFileMenu: {
menuTitle() {
return $gettext('Draw.io document')
}
}
},
{
extension: 'vsdx',
routeName: 'draw-io'
}
]
},
routes,
translations
}
}
})
| owncloud/web/packages/web-app-draw-io/src/index.ts/0 | {
"file_path": "owncloud/web/packages/web-app-draw-io/src/index.ts",
"repo_id": "owncloud",
"token_count": 799
} | 813 |
[main]
host = https://www.transifex.com
[o:owncloud-org:p:owncloud-web:r:files]
file_filter = locale/<lang>/LC_MESSAGES/app.po
minimum_perc = 0
source_file = template.pot
source_lang = en
type = PO
| owncloud/web/packages/web-app-files/l10n/.tx/config/0 | {
"file_path": "owncloud/web/packages/web-app-files/l10n/.tx/config",
"repo_id": "owncloud",
"token_count": 83
} | 814 |
<template>
<oc-text-input
:model-value="password"
:label="$gettext('Password')"
type="password"
:password-policy="inputPasswordPolicy"
:generate-password-method="inputGeneratePasswordMethod"
:fix-message-line="true"
:placeholder="link.hasPassword ? '●●●●●●●●' : null"
:error-message="errorMessage"
class="oc-modal-body-input"
@password-challenge-completed="$emit('update:confirmDisabled', false)"
@password-challenge-failed="$emit('update:confirmDisabled', true)"
@keydown.enter.prevent="$emit('confirm')"
@update:model-value="onInput"
/>
</template>
<script lang="ts">
import { defineComponent, ref, unref, PropType } from 'vue'
import { useGettext } from 'vue3-gettext'
import {
Modal,
useClientService,
useMessages,
usePasswordPolicyService,
useSharesStore
} from '@ownclouders/web-pkg'
import { LinkShare, Resource, SpaceResource } from '@ownclouders/web-client/src/helpers'
export default defineComponent({
name: 'SetLinkPasswordModal',
props: {
modal: { type: Object as PropType<Modal>, required: true },
space: { type: Object as PropType<SpaceResource>, required: true },
resource: { type: Object as PropType<Resource>, required: true },
link: { type: Object as PropType<LinkShare>, required: true }
},
emits: ['confirm', 'update:confirmDisabled'],
setup(props, { expose }) {
const { showMessage, showErrorMessage } = useMessages()
const clientService = useClientService()
const passwordPolicyService = usePasswordPolicyService()
const { $gettext } = useGettext()
const { updateLink } = useSharesStore()
const password = ref('')
const errorMessage = ref<string>()
const onInput = (value: string) => {
password.value = value
errorMessage.value = undefined
}
const onConfirm = async () => {
try {
await updateLink({
clientService,
space: props.space,
resource: props.resource,
linkShare: props.link,
options: { password: unref(password) }
})
showMessage({ title: $gettext('Link was updated successfully') })
} catch (e) {
// Human-readable error message is provided, for example when password is on banned list
if (e.response?.status === 400) {
errorMessage.value = $gettext(e.response.data.error.message)
return Promise.reject()
}
showErrorMessage({
title: $gettext('Failed to update link'),
errors: [e]
})
}
}
expose({ onConfirm })
return {
password,
onInput,
errorMessage,
passwordPolicyService,
inputPasswordPolicy: passwordPolicyService.getPolicy(),
inputGeneratePasswordMethod: () => passwordPolicyService.generatePassword(),
// unit tests
onConfirm
}
}
})
</script>
| owncloud/web/packages/web-app-files/src/components/Modals/SetLinkPasswordModal.vue/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/components/Modals/SetLinkPasswordModal.vue",
"repo_id": "owncloud",
"token_count": 1080
} | 815 |
<template>
<span v-if="selectedRole" class="oc-flex oc-flex-middle">
<span v-if="availableRoles.length === 1">
<oc-icon v-if="showIcon" :name="selectedRole.icon" class="oc-mr-s" />
<span v-text="inviteLabel" />
</span>
<div v-else v-oc-tooltip="dropButtonTooltip">
<oc-button
:id="roleButtonId"
class="files-recipient-role-select-btn"
appearance="raw"
gap-size="none"
:disabled="isLocked"
:aria-label="
mode === 'create' ? $gettext('Select permission') : $gettext('Edit permission')
"
>
<oc-icon v-if="showIcon" :name="selectedRole.icon" class="oc-mr-s" />
<span class="oc-text-truncate" v-text="inviteLabel" />
<oc-icon name="arrow-down-s" />
</oc-button>
</div>
<oc-drop
v-if="availableRoles.length > 1"
ref="rolesDrop"
:toggle="'#' + roleButtonId"
mode="click"
padding-size="small"
class="files-recipient-role-drop"
offset="0"
close-on-click
>
<oc-list
class="files-recipient-role-drop-list"
:aria-label="$gettext('Select role for the invitation')"
>
<li v-for="role in availableRoles" :key="role.id">
<oc-button
:id="`files-recipient-role-drop-btn-${getRoleName(role)}`"
ref="roleSelect"
justify-content="space-between"
class="files-recipient-role-drop-btn oc-p-s"
:class="{
'oc-background-primary-gradient': isSelectedRole(role),
selected: isSelectedRole(role)
}"
:appearance="isSelectedRole(role) ? 'raw-inverse' : 'raw'"
:variation="isSelectedRole(role) ? 'primary' : 'passive'"
@click="selectRole(role)"
>
<span class="oc-flex oc-flex-middle">
<oc-icon :name="role.icon" class="oc-pl-s oc-pr-m" variation="inherit" />
<role-item :role="role" />
</span>
<span class="oc-flex">
<oc-icon v-if="isSelectedRole(role)" name="check" variation="inherit" />
</span>
</oc-button>
</li>
</oc-list>
</oc-drop>
</span>
</template>
<script lang="ts">
import get from 'lodash-es/get'
import { storeToRefs } from 'pinia'
import RoleItem from '../Shared/RoleItem.vue'
import * as uuid from 'uuid'
import {
defineComponent,
inject,
PropType,
ComponentPublicInstance,
computed,
ref,
unref,
Ref
} from 'vue'
import { useAbility, useUserStore } from '@ownclouders/web-pkg'
import { Resource } from '@ownclouders/web-client'
import { useGettext } from 'vue3-gettext'
import { useSharesStore } from '@ownclouders/web-pkg'
import { ShareRole } from '@ownclouders/web-client/src/helpers'
export default defineComponent({
name: 'RoleDropdown',
components: { RoleItem },
props: {
existingRole: {
type: Object as PropType<ShareRole>,
required: false,
default: undefined
},
domSelector: {
type: String,
required: false,
default: undefined
},
mode: {
type: String,
required: false,
default: 'create'
},
showIcon: {
type: Boolean,
default: false
},
isLocked: {
type: Boolean,
default: false
}
},
emits: ['optionChange'],
setup(props, { emit }) {
const ability = useAbility()
const userStore = useUserStore()
const { user } = storeToRefs(userStore)
const sharesStore = useSharesStore()
const { graphRoles } = storeToRefs(sharesStore)
const { $gettext } = useGettext()
const dropButtonTooltip = computed(() => {
if (props.isLocked) {
return $gettext('Resource is temporarily locked, unable to manage share')
}
return ''
})
const availableRoles = inject<Ref<ShareRole[]>>('availableShareRoles')
const initialSelectedRole = props.existingRole ? props.existingRole : unref(availableRoles)[0]
const selectedRole = ref<ShareRole>(initialSelectedRole)
const isSelectedRole = (role: ShareRole) => {
return unref(selectedRole).id === role.id
}
const selectRole = (role: ShareRole) => {
selectedRole.value = role
emit('optionChange', unref(selectedRole))
}
// FIXME: only needed for e2e and acceptance tests, map id to human readable element id
const getRoleName = (role: ShareRole) => {
const map = {
'b1e2218d-eef8-4d4c-b82d-0f1a1b48f3b5': 'viewer',
'a8d5fe5e-96e3-418d-825b-534dbdf22b99': 'viewer',
'2d00ce52-1fc2-4dbc-8b95-a73b73395f5a': 'editor',
'fb6c3e19-e378-47e5-b277-9732f9de6e21': 'editor',
'58c63c02-1d89-4572-916a-870abc5a1b7d': 'editor',
'312c0871-5ef7-4b3a-85b6-0e4074c64049': 'manager',
'1c996275-f1c9-4e71-abdf-a42f6495e960': 'uploader'
}
return map[role.id]
}
return {
ability,
user,
dropButtonTooltip,
resource: inject<Resource>('resource'),
graphRoles,
selectedRole,
availableRoles,
isSelectedRole,
selectRole,
getRoleName
}
},
computed: {
roleButtonId() {
if (this.domSelector) {
return `files-collaborators-role-button-${this.domSelector}-${uuid.v4()}`
}
return 'files-collaborators-role-button-new'
},
inviteLabel() {
return this.$gettext(this.selectedRole?.label || '')
}
},
beforeUnmount() {
window.removeEventListener('keydown', this.cycleRoles)
},
mounted() {
window.addEventListener('keydown', this.cycleRoles)
},
methods: {
cycleRoles(event) {
// events only need to be captured if the roleSelect element is visible
if (!get(this.$refs.rolesDrop, 'tippy.state.isShown', false)) {
return
}
const { code } = event
const isArrowUp = code === 'ArrowUp'
const isArrowDown = code === 'ArrowDown'
// to cycle through the list of roles only up and down keyboard events are allowed
// if this is not the case we can return early and stop the script execution from here
if (!isArrowUp && !isArrowDown) {
return
}
// if there is only 1 or no roleSelect we can early return
// it does not make sense to cycle through it if value is less than 1
const roleSelect = (this.$refs.roleSelect as ComponentPublicInstance[]) || []
if (roleSelect.length <= 1) {
return
}
// obtain active role select in following priority chain:
// first try to get the focused select
// then try to get the selected select
// and if none of those applies we fall back to the first role select
const activeRoleSelect =
roleSelect.find((rs) => rs.$el === document.activeElement) ||
roleSelect.find((rs) => rs.$el.classList.contains('selected')) ||
roleSelect[0]
const activeRoleSelectIndex = roleSelect.indexOf(activeRoleSelect)
const activateRoleSelect = (idx) => roleSelect[idx].$el.focus()
// if the event key is arrow up
// and the next active role select index would be less than 0
// then activate the last available role select
if (isArrowUp && activeRoleSelectIndex - 1 < 0) {
activateRoleSelect(roleSelect.length - 1)
return
}
// if the event key is arrow down
// and the next active role select index would be greater or even to the available amount of role selects
// then activate the first available role select
if (isArrowDown && activeRoleSelectIndex + 1 >= roleSelect.length) {
activateRoleSelect(0)
return
}
// the only missing part is to navigate up or down, this only happens if:
// the next active role index is greater than 0
// the next active role index is less than the amount of all available role selects
activateRoleSelect(activeRoleSelectIndex + (isArrowUp ? -1 : 1))
}
}
})
</script>
<style lang="scss" scoped>
.files-recipient {
&-role-drop {
@media (max-width: $oc-breakpoint-medium-default) {
width: 100%;
}
@media (min-width: $oc-breakpoint-medium-default) {
width: 400px;
}
&-list {
li {
margin: var(--oc-space-xsmall) 0;
&:first-child {
margin-top: 0;
}
&:last-child {
margin-bottom: 0;
}
}
}
&-btn {
width: 100%;
gap: var(--oc-space-medium);
&:hover,
&:focus {
background-color: var(--oc-color-background-hover);
text-decoration: none;
}
}
}
&-role-select-btn {
max-width: 100%;
}
&-custom-permissions-drop-cancel-confirm-btns {
background: var(--oc-color-background-hover);
text-align: right;
}
}
.files-collaborators-permission-checkbox::v-deep {
.oc-checkbox {
border: 2px solid var(--oc-color-border);
}
label {
margin-left: var(--oc-space-small);
}
}
</style>
| owncloud/web/packages/web-app-files/src/components/SideBar/Shares/Collaborators/RoleDropdown.vue/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/components/SideBar/Shares/Collaborators/RoleDropdown.vue",
"repo_id": "owncloud",
"token_count": 3869
} | 816 |
import { computed, unref, VNodeRef } from 'vue'
import { SpaceResource } from '@ownclouders/web-client/src'
import { Drive } from '@ownclouders/web-client/src/generated'
import {
useClientService,
useLoadingService,
usePreviewService,
useUserStore,
useMessages,
useSpacesStore
} from '@ownclouders/web-pkg'
import { eventBus } from '@ownclouders/web-pkg'
import { useGettext } from 'vue3-gettext'
import { SpaceAction, SpaceActionOptions } from '@ownclouders/web-pkg'
import { useCreateSpace } from '@ownclouders/web-pkg'
import { buildSpace } from '@ownclouders/web-client/src/helpers'
export const useSpaceActionsUploadImage = ({ spaceImageInput }: { spaceImageInput: VNodeRef }) => {
const userStore = useUserStore()
const { showMessage, showErrorMessage } = useMessages()
const { $gettext } = useGettext()
const clientService = useClientService()
const loadingService = useLoadingService()
const previewService = usePreviewService()
const { createDefaultMetaFolder } = useCreateSpace()
const spacesStore = useSpacesStore()
let selectedSpace: SpaceResource = null
const handler = ({ resources }: SpaceActionOptions) => {
if (resources.length !== 1) {
return
}
selectedSpace = resources[0] as SpaceResource
unref(spaceImageInput)?.click()
}
const uploadImageSpace = async (ev) => {
const graphClient = clientService.graphAuthenticated
const file = ev.currentTarget.files[0]
if (!file) {
return
}
if (!previewService.isMimetypeSupported(file.type, true)) {
return showErrorMessage({ title: $gettext('The file type is unsupported') })
}
try {
await clientService.webdav.getFileInfo(selectedSpace, { path: '.space' })
} catch (_) {
spacesStore.updateSpaceField({
id: selectedSpace.id,
field: 'spaceReadmeData',
value: (await createDefaultMetaFolder(selectedSpace)).spaceReadmeData
})
}
return loadingService.addTask(async () => {
// overwriting the content-type header only works if the provided content is not of type object,
// therefore it has to be converted to a ArrayBuffer which allows the overwrite.
//
// https://github.com/perry-mitchell/webdav-client/blob/dd8d0dcc319297edc70077abd74b935361bc2412/source/tools/body.ts#L18
const content = await file.arrayBuffer()
const headers = {
'Content-Type': 'application/offset+octet-stream'
}
if (file.lastModifiedDate) {
headers['X-OC-Mtime'] = '' + file.lastModifiedDate.getTime() / 1000
} else if (file.lastModified) {
headers['X-OC-Mtime'] = '' + file.lastModified / 1000
}
try {
const { fileId } = await clientService.webdav.putFileContents(selectedSpace, {
path: `/.space/${file.name}`,
content,
headers,
overwrite: true
})
const { data } = await graphClient.drives.updateDrive(
selectedSpace.id.toString(),
{
special: [
{
specialFolder: {
name: 'image'
},
id: fileId
}
]
} as Drive,
{}
)
spacesStore.updateSpaceField({
id: selectedSpace.id.toString(),
field: 'spaceImageData',
value: data.special.find((special) => special.specialFolder.name === 'image')
})
showMessage({ title: $gettext('Space image was uploaded successfully') })
eventBus.publish('app.files.spaces.uploaded-image', buildSpace(data))
} catch (error) {
console.error(error)
showErrorMessage({
title: $gettext('Failed to upload space image'),
errors: [error]
})
}
})
}
const actions = computed((): SpaceAction[] => [
{
name: 'upload-space-image',
icon: 'image-add',
handler,
label: () => {
return $gettext('Edit image')
},
isVisible: ({ resources }) => {
if (resources.length !== 1) {
return false
}
return resources[0].canEditImage({ user: userStore.user })
},
componentType: 'button',
class: 'oc-files-actions-upload-space-image-trigger'
}
])
return {
actions,
uploadImageSpace
}
}
| owncloud/web/packages/web-app-files/src/composables/actions/spaces/useSpaceActionsUploadImage.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/composables/actions/spaces/useSpaceActionsUploadImage.ts",
"repo_id": "owncloud",
"token_count": 1749
} | 817 |
function _chunkify(t) {
// Adapted from http://my.opera.com/GreyWyvern/blog/show.dml/1671288
const tz = []
let x = 0
let y = -1
let n: number | boolean = 0
let c
while (x < t.length) {
c = t.charAt(x)
// only include the dot in strings
const m = (!n && c === '.') || (c >= '0' && c <= '9')
if (m !== n) {
// next chunk
y++
tz[y] = ''
n = m
}
tz[y] += c
x++
}
return tz
}
/**
* Compare two strings to provide a natural sort
* @param a first string to compare
* @param b second string to compare
* @return number Negative integer if b comes before a, positive integer if a comes before b
* or 0 if the strings are identical
*/
function naturalSortCompare(a, b) {
const aa = _chunkify(a)
const bb = _chunkify(b)
let x, aNum, bNum
for (x = 0; aa[x] && bb[x]; x++) {
if (aa[x] !== bb[x]) {
aNum = Number(aa[x])
bNum = Number(bb[x])
// note: == is correct here
// eslint-disable-next-line eqeqeq
if (aNum == aa[x] && bNum == bb[x]) {
return aNum - bNum
} else {
// Forcing 'en' locale to match the server-side locale which is
// always 'en'.
//
// Note: This setting isn't supported by all browsers but for the ones
// that do there will be more consistency between client-server sorting
return aa[x].localeCompare(bb[x], 'en')
}
}
}
return aa.length - bb.length
}
export const textUtils = {
naturalSortCompare
}
| owncloud/web/packages/web-app-files/src/helpers/textUtils.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/helpers/textUtils.ts",
"repo_id": "owncloud",
"token_count": 640
} | 818 |
import { FolderLoader, FolderLoaderTask, TaskContext } from '../folder'
import { Router } from 'vue-router'
import { useTask } from 'vue-concurrency'
import { isLocationPublicActive, isLocationSpacesActive } from '@ownclouders/web-pkg'
import {
isPersonalSpaceResource,
isPublicSpaceResource,
isShareSpaceResource,
SpaceResource
} from '@ownclouders/web-client/src/helpers'
import { unref } from 'vue'
import { FolderLoaderOptions } from './types'
import { authService } from 'web-runtime/src/services/auth'
import { useFileRouteReplace } from '@ownclouders/web-pkg'
import { IncomingShareResource } from '@ownclouders/web-client/src/helpers/share'
import { getIndicators } from '@ownclouders/web-pkg'
export class FolderLoaderSpace implements FolderLoader {
public isEnabled(): boolean {
return true
}
public isActive(router: Router): boolean {
// TODO: remove next check when isLocationSpacesActive doesn't return true for generic route when being on projects overview.
if (isLocationSpacesActive(router, 'files-spaces-projects')) {
return false
}
return (
isLocationSpacesActive(router, 'files-spaces-generic') ||
isLocationPublicActive(router, 'files-public-link')
)
}
public getTask(context: TaskContext): FolderLoaderTask {
const { router, clientService, resourcesStore } = context
const { webdav } = clientService
const { replaceInvalidFileRoute } = useFileRouteReplace({ router })
return useTask(function* (
signal1,
signal2,
space: SpaceResource,
path: string = null,
fileId: string | number = null,
options: FolderLoaderOptions = {}
) {
try {
resourcesStore.clearResourceList()
// eslint-disable-next-line prefer-const
let { resource: currentFolder, children: resources } = yield webdav.listFiles(space, {
path,
fileId
})
// if current folder has no id (= singe file public link) we must not correct the route
if (currentFolder.id) {
replaceInvalidFileRoute({ space, resource: currentFolder, path, fileId })
}
if (path === '/') {
if (isShareSpaceResource(space)) {
// FIXME: it would be cleaner to fetch the driveItem as soon as graph api is capable of it
currentFolder = {
...currentFolder,
id: space.shareId,
syncEnabled: true,
canShare: () => false
} as IncomingShareResource
} else if (!isPersonalSpaceResource(space) && !isPublicSpaceResource(space)) {
// note: in the future we might want to show the space as root for personal spaces as well (to show quota and the like). Currently not needed.
currentFolder = space
}
}
yield resourcesStore.loadAncestorMetaData({ folder: currentFolder, space, client: webdav })
if (options.loadShares) {
const ancestorMetaData = resourcesStore.ancestorMetaData
for (const file of resources) {
file.indicators = getIndicators({ resource: file, ancestorMetaData })
}
}
// TODO: remove when server returns share id for federated shares in propfind response
if (space.shareId) {
resources.forEach((r) => (r.shareId = space.shareId))
}
resourcesStore.initResourceList({ currentFolder, resources })
} catch (error) {
resourcesStore.setCurrentFolder(null)
console.error(error)
if (error.statusCode === 401) {
return authService.handleAuthError(unref(router.currentRoute))
}
}
}).restartable()
}
}
| owncloud/web/packages/web-app-files/src/services/folder/loaderSpace.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/src/services/folder/loaderSpace.ts",
"repo_id": "owncloud",
"token_count": 1375
} | 819 |
import { useBreadcrumbsFromPath } from '@ownclouders/web-pkg'
export const useBreadcrumbsFromPathMock = (
options: Partial<ReturnType<typeof useBreadcrumbsFromPath>> = {}
): ReturnType<typeof useBreadcrumbsFromPath> => {
return {
breadcrumbsFromPath: vi.fn(() => []),
concatBreadcrumbs: vi.fn((...args) => args),
...options
}
}
| owncloud/web/packages/web-app-files/tests/mocks/useBreadcrumbsFromPathMock.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/mocks/useBreadcrumbsFromPathMock.ts",
"repo_id": "owncloud",
"token_count": 129
} | 820 |
import { ActionExtension, useEmbedMode } from '@ownclouders/web-pkg'
import QuickActions from '../../../../src/components/FilesList/QuickActions.vue'
import { defaultComponentMocks, defaultPlugins, shallowMount } from 'web-test-helpers'
import { useExtensionRegistry } from '@ownclouders/web-pkg'
import { mock } from 'vitest-mock-extended'
import { ref } from 'vue'
import { useExtensionRegistryMock } from 'web-test-helpers/src/mocks/useExtensionRegistryMock'
import { Resource } from '@ownclouders/web-client'
vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({
...(await importOriginal<any>()),
useEmbedMode: vi.fn(),
useExtensionRegistry: vi.fn()
}))
const collaboratorAction = {
isVisible: vi.fn(() => true),
handler: vi.fn(),
icon: 'group-add',
id: 'collaborators',
name: 'show-shares',
label: () => 'Add people'
}
const quicklinkAction = {
isVisible: vi.fn(() => false),
handler: vi.fn(),
icon: 'link-add',
id: 'quicklink',
name: 'copy-quicklink',
label: () => 'Create and copy quicklink'
}
const testItem = {
id: '1',
icon: 'file',
name: 'lorem.txt',
path: '/lorem.txt',
size: '12220'
} as Resource
describe('QuickActions', () => {
describe('when multiple actions are provided', () => {
const { wrapper } = getWrapper()
it('should display all action buttons where "displayed" is set to true', () => {
const actionButtons = wrapper.findAll('.oc-button')
// there are two items provided as actions, with only one item set to display
expect(actionButtons.length).toBe(1)
const actionButton = actionButtons.at(0)
const iconEl = actionButton.find('oc-icon-stub')
expect(actionButton.exists()).toBeTruthy()
expect(actionButton.attributes().class).toContain('files-quick-action-show-shares')
expect(iconEl.exists()).toBeTruthy()
expect(iconEl.attributes().name).toBe('group-add')
expect(actionButton.attributes('aria-label')).toBe('Add people')
})
it('should not display action buttons where "displayed" is set to false', () => {
const linkActionButton = wrapper.find('.files-quick-action-copy-quicklink')
expect(linkActionButton.exists()).toBeFalsy()
})
})
describe('action handler', () => {
it('should call action handler on click', async () => {
const { wrapper } = getWrapper()
const handlerAction = collaboratorAction.handler.mockImplementation(() => undefined)
const actionButton = wrapper.find('.oc-button')
await actionButton.trigger('click')
expect(handlerAction).toHaveBeenCalledTimes(1)
})
})
it('does not show actions in embed mode', () => {
const { wrapper } = getWrapper({ embedModeEnabled: true })
expect(wrapper.findAll('.oc-button').length).toBe(0)
})
})
function getWrapper({ embedModeEnabled = false } = {}) {
vi.mocked(useEmbedMode).mockReturnValue(
mock<ReturnType<typeof useEmbedMode>>({ isEnabled: ref(embedModeEnabled) })
)
vi.mocked(useExtensionRegistry).mockImplementation(() =>
useExtensionRegistryMock({
requestExtensions: () =>
[
mock<ActionExtension>({ scopes: ['resource.quick-action'], action: collaboratorAction }),
mock<ActionExtension>({ scopes: ['resource.quick-action'], action: quicklinkAction })
] as any[]
})
)
return {
wrapper: shallowMount(QuickActions, {
props: {
item: testItem
},
global: {
stubs: { OcButton: false },
mocks: { ...defaultComponentMocks() },
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-app-files/tests/unit/components/FilesList/QuickActions.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/components/FilesList/QuickActions.spec.ts",
"repo_id": "owncloud",
"token_count": 1314
} | 821 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Collaborator ListItem component > share inheritance indicators > show when sharedParentRoute is given 1`] = `
"<div data-v-ccf14be2="" data-testid="collaborator-user-item-einstein" class="files-collaborators-collaborator oc-py-xs">
<div data-v-ccf14be2="" class="oc-width-1-1 oc-flex oc-flex-middle files-collaborators-collaborator-details">
<div data-v-ccf14be2="" class="oc-width-2-3 oc-flex oc-flex-middle">
<div data-v-ccf14be2="">
<avatar-image-stub data-v-ccf14be2="" userid="3" user-name="einstein" width="36" class="files-collaborators-collaborator-indicator"></avatar-image-stub>
</div>
<div data-v-ccf14be2="" class="oc-pl-s oc-text-truncate">
<div data-v-ccf14be2="" class="oc-text-truncate"><span data-v-ccf14be2="" aria-hidden="true" class="files-collaborators-collaborator-name">einstein</span> <span data-v-ccf14be2="" class="oc-invisible-sr">Share receiver name: einstein</span></div>
<div data-v-ccf14be2="">
<div data-v-ccf14be2="" class="oc-flex oc-flex-nowrap oc-flex-middle">
<role-dropdown-stub data-v-ccf14be2="" existingrole="undefined" domselector="1" mode="edit" showicon="false" islocked="false" class="files-collaborators-collaborator-role"></role-dropdown-stub>
</div>
</div>
</div>
</div>
<div data-v-ccf14be2="" class="oc-flex oc-flex-middle oc-width-1-3 files-collaborators-collaborator-navigation">
<div data-v-ccf14be2="" class="oc-resource-indicators oc-text-truncate">
<router-link-stub data-v-ccf14be2="" class="parent-folder oc-text-truncate" to="[object Object]"><span data-v-ccf14be2="" class="text">via</span>
<oc-icon-stub data-v-ccf14be2="" name="folder-2" size="small" fill-type="line" class="oc-px-xs"></oc-icon-stub> <span data-v-ccf14be2="" class="text oc-text-truncate">folder</span>
</router-link-stub>
</div>
<!--v-if-->
<edit-dropdown-stub data-v-ccf14be2="" sharecategory="user" caneditordelete="true" issharedenied="false" deniable="false" islocked="false" id="edit-drop-down-00000000-0000-0000-0000-000000000000" class="files-collaborators-collaborator-edit" data-testid="collaborator-edit"></edit-dropdown-stub>
<oc-info-drop-stub data-v-ccf14be2="" class="share-access-details-drop" title="Access details" list="[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]" mode="manual" target="#edit-drop-down-00000000-0000-0000-0000-000000000000"></oc-info-drop-stub>
</div>
</div>
</div>"
`;
| owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/Collaborators/__snapshots__/ListItem.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/Collaborators/__snapshots__/ListItem.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 1090
} | 822 |
import { mock, mockDeep } from 'vitest-mock-extended'
import { Language } from 'vue3-gettext'
import { ResourceConflict } from 'web-app-files/src/helpers/resource'
import { ResolveStrategy, UppyResource, useResourcesStore } from '@ownclouders/web-pkg'
import { Resource } from '@ownclouders/web-client/src/helpers'
import { createTestingPinia } from 'web-test-helpers/src'
const getResourceConflictInstance = ({
currentFiles = [mockDeep<Resource>()]
}: {
currentFiles?: Resource[]
} = {}) => {
createTestingPinia({ initialState: { resources: { resources: currentFiles } } })
const resourcesStore = useResourcesStore()
return new ResourceConflict(resourcesStore, mock<Language>())
}
describe('upload helper', () => {
describe('method "getConflicts"', () => {
it('should return file and folder conflicts', () => {
const fileName = 'someFile.txt'
const folderName = 'someFolder'
const currentFiles = [
mockDeep<Resource>({ name: fileName }),
mockDeep<Resource>({ name: folderName })
]
const filesToUpload = [
mockDeep<UppyResource>({ name: fileName, meta: { relativePath: '', relativeFolder: '' } }),
mockDeep<UppyResource>({
name: 'anotherFile',
meta: { relativePath: `/${folderName}/anotherFile` }
})
]
const instance = getResourceConflictInstance({ currentFiles })
const conflicts = instance.getConflicts(filesToUpload)
expect(conflicts.length).toBe(2)
expect(conflicts).toContainEqual({ name: fileName, type: 'file' })
expect(conflicts).toContainEqual({ name: folderName, type: 'folder' })
})
})
describe('method "displayOverwriteDialog"', () => {
it.each([ResolveStrategy.REPLACE, ResolveStrategy.KEEP_BOTH])(
'should return all files if user chooses replace or keep both for all',
async (strategy) => {
const uppyResource = mockDeep<UppyResource>({
name: 'test',
meta: {
relativeFolder: ''
}
})
const conflict = {
name: uppyResource.name,
type: 'file'
}
const instance = getResourceConflictInstance()
const resolveFileConflictMethod = vi.fn(() =>
Promise.resolve({ strategy, doForAllConflicts: true })
)
instance.resolveFileExists = resolveFileConflictMethod
const result = await instance.displayOverwriteDialog([uppyResource], [conflict])
expect(result.length).toBe(1)
expect(result).toEqual([uppyResource])
}
)
it('should return no files if user chooses skip for all', async () => {
const uppyResource = mockDeep<UppyResource>({ name: 'test' })
const conflict = { name: uppyResource.name, type: 'file' }
const instance = getResourceConflictInstance()
const resolveFileConflictMethod = vi.fn(() =>
Promise.resolve({ strategy: ResolveStrategy.SKIP, doForAllConflicts: true })
)
instance.resolveFileExists = resolveFileConflictMethod
const result = await instance.displayOverwriteDialog([uppyResource], [conflict])
expect(result.length).toBe(0)
})
it('should show dialog once if do for all conflicts is ticked', async () => {
const uppyResourceOne = mockDeep<UppyResource>({ name: 'test' })
const uppyResourceTwo = mockDeep<UppyResource>({ name: 'test2' })
const conflictOne = { name: uppyResourceOne.name, type: 'file' }
const conflictTwo = { name: uppyResourceTwo.name, type: 'file' }
const instance = getResourceConflictInstance()
const resolveFileConflictMethod = vi.fn(() =>
Promise.resolve({ strategy: ResolveStrategy.REPLACE, doForAllConflicts: true })
)
instance.resolveFileExists = resolveFileConflictMethod
await instance.displayOverwriteDialog(
[uppyResourceOne, uppyResourceTwo],
[conflictOne, conflictTwo]
)
expect(resolveFileConflictMethod).toHaveBeenCalledTimes(1)
})
it('should show dialog twice if do for all conflicts is ticked and folders and files are uploaded', async () => {
const uppyResourceOne = mockDeep<UppyResource>({ name: 'test' })
const uppyResourceTwo = mockDeep<UppyResource>({ name: 'folder' })
const conflictOne = {
name: uppyResourceOne.name,
type: 'file',
meta: { relativeFolder: '/' }
}
const conflictTwo = { name: uppyResourceTwo.name, type: 'folder' }
const instance = getResourceConflictInstance()
instance.resolveFileExists = vi.fn(() =>
Promise.resolve({ strategy: ResolveStrategy.REPLACE, doForAllConflicts: true })
)
await instance.displayOverwriteDialog(
[uppyResourceOne, uppyResourceTwo],
[conflictOne, conflictTwo]
)
expect(instance.resolveFileExists).toHaveBeenCalledTimes(2)
})
})
})
| owncloud/web/packages/web-app-files/tests/unit/helpers/resource/actions/upload.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/helpers/resource/actions/upload.spec.ts",
"repo_id": "owncloud",
"token_count": 1823
} | 823 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Projects view > different files view states > lists all available project spaces 1`] = `
"<div class="oc-flex oc-width-1-1">
<div data-v-39c970be="" class="files-view-wrapper oc-width-expand">
<div data-v-39c970be="" id="files-view">
<app-bar-stub viewmodedefault="resource-tiles" breadcrumbs="[object Object]" breadcrumbscontextactionsitems="" viewmodes="[object Object]" hasbulkactions="true" hasviewoptions="true" hashiddenfiles="false" hasfileextensions="false" haspagination="false" showactionsonselection="true" issidebaropen="false"></app-bar-stub>
<div class="spaces-list oc-mt-l">
<div class="spaces-list-filters oc-flex oc-flex-right oc-px-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>
<div class="resource-table" selectedids="" resource-type="space" are-thumbnails-displayed="true" resources="[object Object],[object Object]" fields-displayed="image,name,manager,members,totalQuota,usedQuota,remainingQuota,status,mdate" sort-fields="[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]" sort-by="undefined" sort-dir="desc" header-position="0" view-size="NaN"></div>
</div>
</div>
</div>
<!--v-if-->
<file-side-bar-stub isopen="false"></file-side-bar-stub>
</div>"
`;
| owncloud/web/packages/web-app-files/tests/unit/views/spaces/__snapshots__/Projects.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-app-files/tests/unit/views/spaces/__snapshots__/Projects.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 682
} | 824 |
<template>
<div class="sciencemesh">
<div class="oc-flex oc-flex-column sciencemesh-wrapper">
<div class="oc-flex sciencemesh-top">
<div id="sciencemesh-invite" class="oc-width-1-2">
<outgoing-invitations />
</div>
<div id="sciencemesh-accept-invites" class="oc-width-1-2">
<incoming-invitations @highlight-new-connections="highlightNewConnections" />
</div>
</div>
<div id="sciencemesh-connections">
<connections-panel
v-model:connections="connections"
:highlighted-connections="highlightedConnections.map((c) => c.id)"
:loading="loadingConnections"
/>
</div>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref, unref, Ref } from 'vue'
import ConnectionsPanel from './ConnectionsPanel.vue'
import IncomingInvitations from './IncomingInvitations.vue'
import OutgoingInvitations from './OutgoingInvitations.vue'
import {
useClientService,
useScrollTo,
FederatedConnection,
useMessages
} from '@ownclouders/web-pkg'
import { useGettext } from 'vue3-gettext'
import { buildConnection } from '../functions'
export default defineComponent({
components: {
IncomingInvitations,
OutgoingInvitations,
ConnectionsPanel
},
setup() {
const { showMessage } = useMessages()
const { scrollToResource } = useScrollTo()
const clientSerivce = useClientService()
const { $gettext } = useGettext()
const connections: Ref<FederatedConnection[]> = ref([])
const highlightedConnections: Ref<FederatedConnection[]> = ref([])
const highlightNewConnectionsInterval = ref(null)
const loadingConnections = ref(true)
const findAcceptedUsers = async () => {
try {
const { data: acceptedUsers } = await clientSerivce.httpAuthenticated.get<
FederatedConnection[]
>('/sciencemesh/find-accepted-users')
loadingConnections.value = false
connections.value = acceptedUsers.map(buildConnection)
} catch (error) {
connections.value = []
loadingConnections.value = false
}
}
const highlightNewConnections = async () => {
let oldConnections = [...unref(connections)]
await findAcceptedUsers()
if (oldConnections.length < unref(connections).length) {
highlightedConnections.value = unref(connections).filter(
(connection) => !oldConnections.map((c) => c.id).includes(connection.id)
)
if (unref(highlightedConnections).length === 1) {
scrollToResource(unref(highlightedConnections)[0].id)
showMessage({
title: $gettext('New federated connection'),
status: 'success',
desc: $gettext('You can share with and recieve shares from %{user} now', {
user: unref(highlightedConnections)[0].display_name
})
})
} else if (unref(highlightedConnections).length > 1) {
const newConnections = unref(highlightedConnections)
.map((c) => c.display_name)
.join(', ')
showMessage({
title: $gettext('New federated connections'),
status: 'success',
desc: $gettext('You can share with and receive shares from %{ connections } now', {
connections: newConnections
})
})
}
}
}
onMounted(async () => {
await findAcceptedUsers()
loadingConnections.value = false
highlightNewConnectionsInterval.value = setInterval(() => {
highlightNewConnections()
}, 10 * 1000)
})
onUnmounted(() => {
clearInterval(unref(highlightNewConnectionsInterval))
})
return {
highlightNewConnections,
connections,
highlightedConnections,
loadingConnections
}
}
})
</script>
<style lang="scss" scoped>
.sciencemesh {
background-color: var(--oc-color-background-hover);
}
.sciencemesh-wrapper {
height: 100%;
}
.sciencemesh-top {
height: 360px;
overflow: hidden;
@media (max-width: 1000px) {
flex-direction: column;
height: auto;
}
}
#sciencemesh-invite,
#sciencemesh-accept-invites {
margin: var(--oc-space-small);
overflow-y: auto;
}
#sciencemesh-invite,
#sciencemesh-accept-invites,
#sciencemesh-connections {
margin: var(--oc-space-small);
background-color: var(--oc-color-background-default);
border-radius: 15px;
padding: var(--oc-space-small);
@media (max-width: 1000px) {
width: auto;
}
}
#sciencemesh-connections {
flex: 1;
}
#sciencemesh-invite {
@media (max-width: 1000px) {
margin-bottom: var(--oc-space-small);
}
}
</style>
| owncloud/web/packages/web-app-ocm/src/views/App.vue/0 | {
"file_path": "owncloud/web/packages/web-app-ocm/src/views/App.vue",
"repo_id": "owncloud",
"token_count": 1901
} | 825 |
<template>
<video
ref="video"
:key="`media-video-${file.id}`"
controls
preload="preload"
:autoplay="isAutoPlayEnabled"
>
<source :src="file.url" :type="file.mimeType" />
</video>
</template>
<script lang="ts">
import { defineComponent, onBeforeUnmount, onMounted, PropType, ref } from 'vue'
import { CachedFile } from '../../helpers/types'
export default defineComponent({
name: 'MediaVideo',
props: {
file: {
type: Object as PropType<CachedFile>,
required: true
},
isAutoPlayEnabled: {
type: Boolean,
default: true
}
},
setup() {
const video = ref(null)
const resizeVideoDimensions = () => {
const stageMedia: HTMLElement = document.querySelector('.stage_media')
video.value.style.maxHeight = `${stageMedia.offsetHeight - 10}px`
video.value.style.maxWidth = `${stageMedia.offsetWidth - 10}px`
}
onMounted(() => {
resizeVideoDimensions()
window.addEventListener('resize', resizeVideoDimensions)
})
onBeforeUnmount(() => {
window.removeEventListener('resize', resizeVideoDimensions)
})
return {
video
}
}
})
</script>
| owncloud/web/packages/web-app-preview/src/components/Sources/MediaVideo.vue/0 | {
"file_path": "owncloud/web/packages/web-app-preview/src/components/Sources/MediaVideo.vue",
"repo_id": "owncloud",
"token_count": 467
} | 826 |
import List from '../../../src/views/List.vue'
import { defaultComponentMocks, mount } from 'web-test-helpers'
import { useAvailableProviders } from '../../../src/composables'
import { ref } from 'vue'
import { SearchProvider, queryItemAsString } from '@ownclouders/web-pkg'
import { mock } from 'vitest-mock-extended'
const mockProvider = mock<SearchProvider>({
id: 'p1',
available: true,
listSearch: {
search: vi.fn()
}
})
vi.mock('../../../src/composables/useAvailableProviders')
vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({
...(await importOriginal<any>()),
useRouteQuery: vi.fn(),
queryItemAsString: vi.fn()
}))
describe('search result List view', () => {
it('requests the listSearch from the current active provider', () => {
const { wrapper } = getWrapper()
expect(wrapper.vm.listSearch).toMatchObject(mockProvider.listSearch)
})
it('by default loading is true', () => {
const { wrapper } = getWrapper()
expect(wrapper.vm.loading).toBeTruthy()
})
it('triggers the search', async () => {
const { wrapper } = getWrapper()
await wrapper.vm.search('term')
expect(mockProvider.listSearch.search).toHaveBeenCalledTimes(1)
})
})
const getWrapper = () => {
vi.mocked(useAvailableProviders).mockReturnValue(ref([mockProvider]))
vi.mocked(queryItemAsString).mockReturnValue('p1')
const mocks = { ...defaultComponentMocks() }
return {
wrapper: mount(List, {
global: { mocks }
})
}
}
| owncloud/web/packages/web-app-search/tests/unit/views/List.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-app-search/tests/unit/views/List.spec.ts",
"repo_id": "owncloud",
"token_count": 523
} | 827 |
[main]
host = https://www.transifex.com
[o:owncloud-org:p:owncloud-web:r:client]
file_filter = locale/<lang>/LC_MESSAGES/app.po
minimum_perc = 0
source_file = template.pot
source_lang = en
type = PO
| owncloud/web/packages/web-client/l10n/.tx/config/0 | {
"file_path": "owncloud/web/packages/web-client/l10n/.tx/config",
"repo_id": "owncloud",
"token_count": 83
} | 828 |
export const call = function* <T>(p: Promise<T>): Generator<Promise<T>, T, T> {
return yield p
}
| owncloud/web/packages/web-client/src/helpers/call.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/helpers/call.ts",
"repo_id": "owncloud",
"token_count": 36
} | 829 |
export * from './functions'
export * from './types'
| owncloud/web/packages/web-client/src/helpers/space/index.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/helpers/space/index.ts",
"repo_id": "owncloud",
"token_count": 17
} | 830 |
import { parseXML } from 'webdav'
import { XMLParser } from 'fast-xml-parser'
import { prepareFileFromProps } from 'webdav/dist/node/tools/dav'
import { WebDavResponseResource, WebDavResponseTusSupport } from '../../helpers'
import { urlJoin } from '../../utils'
export const parseTusHeaders = (headers: Headers) => {
const result: WebDavResponseTusSupport = {}
const version = headers.get('tus-version')
if (!version) {
return null
}
result.version = version.split(',')
if (headers.get('tus-extension')) {
result.extension = headers.get('tus-extension').split(',')
}
if (headers.get('tus-resumable')) {
result.resumable = headers.get('tus-resumable')
}
if (headers.get('tus-max-size')) {
result.maxSize = parseInt(headers.get('tus-max-size'), 10)
}
return result
}
export const parseMultiStatus = async (xmlBody: string) => {
const parseFileName = (name: string) => {
const decoded = decodeURIComponent(name)
if (name?.startsWith('/remote.php/dav/')) {
// strip out '/remote.php/dav/' from the beginning
return urlJoin(decoded.replace('/remote.php/dav/', ''), {
leadingSlash: true,
trailingSlash: false
})
}
return decoded
}
const parsedXML = await parseXML(xmlBody)
return parsedXML.multistatus.response.map(({ href, propstat }) => {
const data = {
...prepareFileFromProps(propstat.prop, parseFileName(href), true),
processing: propstat.status === 'HTTP/1.1 425 TOO EARLY'
}
if (data.props.name) {
data.props.name = data.props.name.toString()
}
return data
}) as unknown as WebDavResponseResource[]
}
export const parseError = (xmlBody: string) => {
const parser = new XMLParser()
try {
const parsed = parser.parse(xmlBody)
if (parsed['d:error'] && parsed['d:error']['s:message']) {
const message = parsed['d:error']['s:message']
if (typeof message === 'string') {
return message
}
return ''
}
} catch (error) {
return 'Unknown error'
}
return 'Unknown error'
}
| owncloud/web/packages/web-client/src/webdav/client/parsers.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/webdav/client/parsers.ts",
"repo_id": "owncloud",
"token_count": 795
} | 831 |
import { SpaceResource, isShareSpaceResource, SHARE_JAIL_ID } from '../helpers'
import { WebDavOptions } from './types'
import { DAV, buildAuthHeader } from './client'
import { unref } from 'vue'
export const MoveFilesFactory = (dav: DAV, { accessToken }: WebDavOptions) => {
return {
moveFiles(
sourceSpace: SpaceResource,
{ path: sourcePath },
targetSpace: SpaceResource,
{ path: targetPath },
options?: { overwrite?: boolean }
) {
const headers = buildAuthHeader(unref(accessToken), sourceSpace)
if (isShareSpaceResource(sourceSpace) && sourcePath === '/') {
return dav.move(
`${sourceSpace.webDavPath}/${sourcePath || ''}`,
`/spaces/${SHARE_JAIL_ID}!${SHARE_JAIL_ID}/${targetPath || ''}`,
{ overwrite: options?.overwrite || false, headers }
)
}
return dav.move(
`${sourceSpace.webDavPath}/${sourcePath || ''}`,
`${targetSpace.webDavPath}/${targetPath || ''}`,
{ overwrite: options?.overwrite || false, headers }
)
}
}
}
| owncloud/web/packages/web-client/src/webdav/moveFiles.ts/0 | {
"file_path": "owncloud/web/packages/web-client/src/webdav/moveFiles.ts",
"repo_id": "owncloud",
"token_count": 435
} | 832 |
[main]
host = https://www.transifex.com
[o:owncloud-org:p:owncloud-web:r:pkg]
file_filter = locale/<lang>/LC_MESSAGES/app.po
minimum_perc = 0
source_file = template.pot
source_lang = en
type = PO
| owncloud/web/packages/web-pkg/l10n/.tx/config/0 | {
"file_path": "owncloud/web/packages/web-pkg/l10n/.tx/config",
"repo_id": "owncloud",
"token_count": 83
} | 833 |
import { defineComponent, h } from 'vue'
import AppWrapper from './AppWrapper.vue'
import { AppWrapperSlotArgs } from './types'
import { FileContentOptions, UrlForResourceOptions } from '../../composables'
import { Resource } from '@ownclouders/web-client/src'
export function AppWrapperRoute(
fileEditor: ReturnType<typeof defineComponent>,
options: {
applicationId: string
urlForResourceOptions?: UrlForResourceOptions
fileContentOptions?: FileContentOptions
importResourceWithExtension?: (resource: Resource) => string
}
) {
return defineComponent({
render() {
return h(
AppWrapper,
{
wrappedComponent: fileEditor,
...options
},
{
default: (slotArgs: AppWrapperSlotArgs) => {
return h(fileEditor, slotArgs)
}
}
)
}
})
}
| owncloud/web/packages/web-pkg/src/components/AppTemplates/AppWrapperRoute.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/AppTemplates/AppWrapperRoute.ts",
"repo_id": "owncloud",
"token_count": 335
} | 834 |
<template>
<component
:is="componentType"
v-bind="componentProps"
v-if="isResourceClickable"
:target="linkTargetBlank"
:aria-describedby="opensInNewWindowDescriptionId"
:draggable="false"
@dragstart.prevent.stop
@click="emitClick"
>
<slot :opens-in-new-window-description-id="opensInNewWindowDescriptionId" />
</component>
<span v-else>
<slot />
</span>
</template>
<script lang="ts">
import uniqueId from 'design-system/src/utils/uniqueId'
/**
* Wraps content in a resource link
*/
export default {
name: 'ResourceLink',
props: {
/**
* The resource folder link
*/
folderLink: {
type: Object,
required: false,
default: null
},
/**
* The resource to be displayed
*/
resource: {
type: Object,
required: true
},
/**
* Asserts whether clicking on the resource name triggers any action
*/
isResourceClickable: {
type: Boolean,
required: false,
default: true
}
},
emits: ['click'],
computed: {
isNavigatable() {
return this.resource.isFolder && !this.resource.disabled
},
componentType() {
return this.isNavigatable ? 'router-link' : 'oc-button'
},
componentProps() {
if (!this.isNavigatable) {
return {
appearance: 'raw',
gapSize: 'none',
justifyContent: 'left'
}
}
return {
to: this.folderLink
}
},
opensInNewWindowDescriptionId() {
if (this.resource.opensInNewWindow) {
return uniqueId('oc-link-description-')
}
return null
},
linkTargetBlank() {
if (this.isNavigatable && this.resource.opensInNewWindow) {
return '_blank'
}
return null
}
},
methods: {
emitClick() {
if (this.isNavigatable) {
return
}
/**
* Triggered when the resource is a file and the name is clicked
*/
this.$emit('click')
}
}
}
</script>
| owncloud/web/packages/web-pkg/src/components/FilesList/ResourceLink.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/FilesList/ResourceLink.vue",
"repo_id": "owncloud",
"token_count": 882
} | 835 |
<template>
<span class="oc-display-inline-block oc-mb-m" v-text="message" />
<div class="oc-my-m">
<oc-checkbox
v-if="conflictCount > 1"
v-model="checkboxValue"
size="medium"
:label="checkboxLabel"
:aria-label="checkboxLabel"
/>
</div>
<div class="oc-flex oc-flex-right oc-flex-middle oc-mt-m">
<div class="oc-modal-body-actions-grid">
<oc-button
class="oc-modal-body-actions-cancel oc-ml-s"
appearance="outline"
variation="passive"
@click="onCancel"
>{{ $gettext('Skip') }}
</oc-button>
<oc-button
class="oc-modal-body-actions-secondary oc-ml-s"
appearance="outline"
variation="passive"
@click="onConfirmSecondary"
>{{ $gettext('Replace') }}
</oc-button>
<oc-button
class="oc-modal-body-actions-confirm oc-ml-s"
appearance="filled"
variation="primary"
@click="onConfirm"
>{{ $gettext('Keep both') }}
</oc-button>
</div>
</div>
</template>
<script lang="ts">
import { computed, defineComponent, PropType, ref, unref } from 'vue'
import { useGettext } from 'vue3-gettext'
import { Modal, useModals } from '../../composables'
import { Resource } from '@ownclouders/web-client/src'
import { ResolveConflict, ResolveStrategy } from '../../helpers/resource'
export default defineComponent({
name: 'ResourceConflictModal',
props: {
modal: { type: Object as PropType<Modal>, required: true },
resource: { type: Object as PropType<Resource>, required: true },
conflictCount: { type: Number, required: true },
callbackFn: {
type: Function as PropType<(resolveConflict: ResolveConflict) => void>,
required: true
},
suggestMerge: { type: Boolean, default: true },
separateSkipHandling: { type: Boolean, default: false }
},
setup(props) {
const { removeModal } = useModals()
const { $gettext } = useGettext()
const checkboxValue = ref(false)
const checkboxLabel = computed(() => {
if (props.conflictCount < 2) {
return ''
}
if (!props.separateSkipHandling) {
return $gettext(
'Apply to all %{count} conflicts',
{ count: props.conflictCount.toString() },
true
)
} else if (props.resource.isFolder) {
return $gettext(
'Apply to all %{count} folders',
{ count: props.conflictCount.toString() },
true
)
} else {
return $gettext(
'Apply to all %{count} files',
{ count: props.conflictCount.toString() },
true
)
}
})
const message = computed(() =>
props.resource.isFolder
? $gettext(
'Folder with name "%{name}" already exists.',
{ name: props.resource.name },
true
)
: $gettext('File with name "%{name}" already exists.', { name: props.resource.name }, true)
)
const onConfirm = () => {
removeModal(props.modal.id)
props.callbackFn({
strategy: ResolveStrategy.KEEP_BOTH,
doForAllConflicts: unref(checkboxValue)
})
}
const onConfirmSecondary = () => {
removeModal(props.modal.id)
const strategy = props.suggestMerge ? ResolveStrategy.MERGE : ResolveStrategy.REPLACE
props.callbackFn({
strategy,
doForAllConflicts: unref(checkboxValue)
})
}
const onCancel = () => {
removeModal(props.modal.id)
props.callbackFn({
strategy: ResolveStrategy.SKIP,
doForAllConflicts: unref(checkboxValue)
})
}
return {
message,
checkboxValue,
checkboxLabel,
onConfirm,
onConfirmSecondary,
onCancel
}
}
})
</script>
| owncloud/web/packages/web-pkg/src/components/Modals/ResourceConflictModal.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/Modals/ResourceConflictModal.vue",
"repo_id": "owncloud",
"token_count": 1704
} | 836 |
<template>
<div id="oc-space-details-sidebar">
<div class="oc-space-details-sidebar-image oc-text-center">
<oc-spinner v-if="loadImageTask.isRunning" />
<div v-else-if="spaceImage" class="oc-position-relative">
<img :src="spaceImage" alt="" class="oc-mb-s" />
</div>
<oc-icon
v-else
name="layout-grid"
size="xxlarge"
class="space-default-image oc-px-m oc-py-m"
/>
</div>
<div
v-if="showShareIndicators && hasShares"
class="oc-flex oc-flex-middle oc-space-details-sidebar-members oc-mb-s oc-text-small"
style="gap: 15px"
>
<oc-button
v-if="hasMemberShares"
appearance="raw"
:aria-label="openSharesPanelMembersHint"
@click="expandSharesPanel"
>
<oc-icon name="group" />
</oc-button>
<oc-button
v-if="hasLinkShares"
appearance="raw"
:aria-label="openSharesPanelLinkHint"
@click="expandSharesPanel"
>
<oc-icon name="link" />
</oc-button>
<p v-text="shareLabel" />
<oc-button
appearance="raw"
:aria-label="openSharesPanelHint"
size="small"
@click="expandSharesPanel"
>
<span class="oc-text-small" v-text="$gettext('Show')" />
</oc-button>
</div>
<table class="details-table oc-width-1-1" :aria-label="detailsTableLabel">
<col class="oc-width-1-3" />
<col class="oc-width-2-3" />
<tr>
<th scope="col" class="oc-pr-s oc-font-semibold" v-text="$gettext('Last activity')" />
<td v-text="lastModifiedDate" />
</tr>
<tr v-if="resource.description">
<th scope="col" class="oc-pr-s oc-font-semibold" v-text="$gettext('Subtitle')" />
<td v-text="resource.description" />
</tr>
<tr>
<th scope="col" class="oc-pr-s oc-font-semibold" v-text="$gettext('Manager')" />
<td>
<span v-text="ownerUsernames" />
</td>
</tr>
<tr v-if="!resource.disabled">
<th scope="col" class="oc-pr-s oc-font-semibold" v-text="$gettext('Quota')" />
<td>
<space-quota :space-quota="resource.spaceQuota" />
</td>
</tr>
<web-dav-details v-if="showWebDavDetails" :space="resource" />
<portal-target
name="app.files.sidebar.space.details.table"
:slot-props="{ space: resource, resource }"
:multiple="true"
/>
</table>
</div>
</template>
<script lang="ts">
import { storeToRefs } from 'pinia'
import { defineComponent, inject, ref, Ref, computed, unref } from 'vue'
import { useTask } from 'vue-concurrency'
import {
getRelativeSpecialFolderSpacePath,
SpaceResource
} from '@ownclouders/web-client/src/helpers'
import {
usePreviewService,
useClientService,
useUserStore,
useSpacesStore,
useSharesStore,
useResourcesStore
} from '../../../../composables'
import SpaceQuota from '../../../SpaceQuota.vue'
import WebDavDetails from '../../WebDavDetails.vue'
import { formatDateFromISO } from '../../../../helpers'
import { eventBus } from '../../../../services/eventBus'
import { SideBarEventTopics } from '../../../../composables'
import { ImageDimension } from '../../../../constants'
import { ProcessorType } from '../../../../services'
export default defineComponent({
name: 'SpaceDetails',
components: { SpaceQuota, WebDavDetails },
props: {
showSpaceImage: {
type: Boolean,
required: false,
default: true
},
showShareIndicators: {
type: Boolean,
required: false,
default: true
}
},
setup(props) {
const userStore = useUserStore()
const previewService = usePreviewService()
const clientService = useClientService()
const spacesStore = useSpacesStore()
const resourcesStore = useResourcesStore()
const sharesStore = useSharesStore()
const { spaceMembers } = storeToRefs(spacesStore)
const resource = inject<Ref<SpaceResource>>('resource')
const spaceImage = ref('')
const { user } = storeToRefs(userStore)
const loadImageTask = useTask(function* (signal, ref) {
if (!ref.resource?.spaceImageData || !props.showSpaceImage) {
spaceImage.value = undefined
return
}
const imageResource = yield clientService.webdav.getFileInfo(unref(resource), {
path: getRelativeSpecialFolderSpacePath(unref(resource), 'image')
})
spaceImage.value = yield previewService.loadPreview({
space: unref(resource),
resource: imageResource,
dimensions: ImageDimension.Tile,
processor: ProcessorType.enum.fit
})
})
const linkShareCount = computed(() => sharesStore.linkShares.length)
const showWebDavDetails = computed(() => resourcesStore.areWebDavDetailsShown)
return {
loadImageTask,
spaceImage,
resource,
linkShareCount,
showWebDavDetails,
user,
spaceMembers
}
},
computed: {
hasShares() {
return this.hasMemberShares || this.hasLinkShares
},
shareLabel() {
if (this.hasMemberShares && !this.hasLinkShares) {
return this.memberShareLabel
}
if (!this.hasMemberShares && this.hasLinkShares) {
return this.linkShareLabel
}
switch (this.memberShareCount) {
case 1:
return this.$ngettext(
'This space has one member and %{linkShareCount} link.',
'This space has one member and %{linkShareCount} links.',
this.linkShareCount,
{ linkShareCount: this.linkShareCount.toString() }
)
default:
if (this.linkShareCount === 1) {
return this.$gettext('This space has %{memberShareCount} members and one link.', {
memberShareCount: this.memberShareCount.toString()
})
}
return this.$gettext(
'This space has %{memberShareCount} members and %{linkShareCount} links.',
{
memberShareCount: this.memberShareCount.toString(),
linkShareCount: this.linkShareCount.toString()
}
)
}
},
openSharesPanelHint() {
return this.$gettext('Open share panel')
},
openSharesPanelLinkHint() {
return this.$gettext('Open link list in share panel')
},
openSharesPanelMembersHint() {
return this.$gettext('Open member list in share panel')
},
detailsTableLabel() {
return this.$gettext('Overview of the information about the selected space')
},
lastModifiedDate() {
return formatDateFromISO(this.resource.mdate, this.$language.current)
},
ownerUsernames() {
return this.resource.spaceRoles.manager
.map((share) => {
if (share.id === this.user?.id) {
return this.$gettext('%{displayName} (me)', { displayName: share.displayName })
}
return share.displayName
})
.join(', ')
},
hasMemberShares() {
return this.memberShareCount > 0
},
hasLinkShares() {
return this.linkShareCount > 0
},
memberShareCount() {
return this.spaceMembers.length
},
memberShareLabel() {
return this.$ngettext(
'This space has %{memberShareCount} member.',
'This space has %{memberShareCount} members.',
this.memberShareCount,
{ memberShareCount: this.memberShareCount.toString() }
)
},
linkShareLabel() {
return this.$ngettext(
'%{linkShareCount} link giving access.',
'%{linkShareCount} links giving access.',
this.linkShareCount,
{ linkShareCount: this.linkShareCount.toString() }
)
}
},
watch: {
'resource.spaceImageData': {
handler() {
this.loadImageTask.perform(this)
},
deep: true
}
},
mounted() {
this.loadImageTask.perform(this)
},
methods: {
expandSharesPanel() {
eventBus.publish(SideBarEventTopics.setActivePanel, 'space-share')
}
}
})
</script>
<style lang="scss" scoped>
.oc-space-details-sidebar {
&-image img {
max-height: 150px;
object-fit: cover;
width: 100%;
}
}
.details-table {
text-align: left;
table-layout: fixed;
tr {
height: 1.5rem;
}
}
</style>
| owncloud/web/packages/web-pkg/src/components/SideBar/Spaces/Details/SpaceDetails.vue/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/components/SideBar/Spaces/Details/SpaceDetails.vue",
"repo_id": "owncloud",
"token_count": 3573
} | 837 |
import { useAbility as _useAbility } from '@casl/vue'
import { Ability } from '@ownclouders/web-client/src/helpers/resource/types'
export const useAbility = () => _useAbility<Ability>()
| owncloud/web/packages/web-pkg/src/composables/ability/useAbility.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/ability/useAbility.ts",
"repo_id": "owncloud",
"token_count": 60
} | 838 |
import { computed, unref } from 'vue'
import { isLocationCommonActive, isLocationSpacesActive } from '../../../router'
import { useGettext } from 'vue3-gettext'
import { FileAction, FileActionOptions, useIsFilesAppActive } from '../../actions'
import { useRouter } from '../../router'
import { useClientService } from '../../clientService'
import { useAbility } from '../../ability'
import { useMessages, useCapabilityStore, useResourcesStore } from '../../piniaStores'
import { useEventBus } from '../../eventBus'
export const useFileActionsFavorite = () => {
const { showErrorMessage } = useMessages()
const capabilityStore = useCapabilityStore()
const router = useRouter()
const { $gettext } = useGettext()
const clientService = useClientService()
const isFilesAppActive = useIsFilesAppActive()
const ability = useAbility()
const resourcesStore = useResourcesStore()
const eventBus = useEventBus()
const handler = async ({ space, resources }: FileActionOptions) => {
try {
const newValue = !resources[0].starred
await clientService.webdav.setFavorite(space, resources[0], newValue)
resourcesStore.updateResourceField({ id: resources[0].id, field: 'starred', value: newValue })
if (!newValue) {
eventBus.publish('app.files.list.removeFromFavorites', resources[0].id)
}
} catch (error) {
const title = $gettext(
'Failed to change favorite state of "%{file}"',
{ file: resources[0].name },
true
)
showErrorMessage({ title, errors: [error] })
}
}
const actions = computed((): FileAction[] => [
{
name: 'favorite',
icon: 'star',
handler,
label: ({ resources }) => {
if (resources[0].starred) {
return $gettext('Remove from favorites')
}
return $gettext('Add to favorites')
},
isVisible: ({ resources }) => {
if (
unref(isFilesAppActive) &&
!isLocationSpacesActive(router, 'files-spaces-generic') &&
!isLocationCommonActive(router, 'files-common-favorites')
) {
return false
}
if (resources.length !== 1) {
return false
}
return capabilityStore.filesFavorites && ability.can('create', 'Favorite')
},
componentType: 'button',
class: 'oc-files-actions-favorite-trigger'
}
])
return {
actions
}
}
| owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsFavorite.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsFavorite.ts",
"repo_id": "owncloud",
"token_count": 904
} | 839 |
import { computed } from 'vue'
export const useIsSearchActive = () =>
computed(() => !!document.getElementById('files-global-search-options'))
| owncloud/web/packages/web-pkg/src/composables/actions/helpers/useIsSearchActive.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/helpers/useIsSearchActive.ts",
"repo_id": "owncloud",
"token_count": 43
} | 840 |
import { useFileActions } from './files'
import { Resource, SpaceResource } from '@ownclouders/web-client'
export function useOpenWithDefaultApp() {
const { getDefaultEditorAction } = useFileActions()
const openWithDefaultApp = ({
space,
resource
}: {
space: SpaceResource
resource: Resource
}) => {
if (!resource || resource.isFolder) {
return
}
const fileActionsOptions = {
resources: [resource],
space: space
}
const defaultEditorAction = getDefaultEditorAction(fileActionsOptions)
if (defaultEditorAction) {
defaultEditorAction.handler({ ...fileActionsOptions })
}
}
return { openWithDefaultApp }
}
| owncloud/web/packages/web-pkg/src/composables/actions/useOpenWithDefaultApp.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/actions/useOpenWithDefaultApp.ts",
"repo_id": "owncloud",
"token_count": 232
} | 841 |
import { useClientService } from '../clientService'
import type { Router, RouteLocationNormalizedLoaded } from 'vue-router'
import type { Method, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ClientService } from '../../services'
import { AuthStore, useAuthStore } from '../piniaStores'
interface RequestOptions {
router?: Router
authStore?: AuthStore
clientService?: ClientService
currentRoute?: RouteLocationNormalizedLoaded
}
export interface RequestResult {
makeRequest(method: Method, url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>
}
export function useRequest(options: RequestOptions = {}): RequestResult {
const clientService = options.clientService ?? useClientService()
const authStore = options.authStore ?? useAuthStore()
const makeRequest = (
method: Method,
url: string,
config: AxiosRequestConfig = {}
): Promise<AxiosResponse> => {
const httpClient = authStore.accessToken
? clientService.httpAuthenticated
: clientService.httpUnAuthenticated
config.headers = config.headers || {}
if (authStore.publicLinkContextReady) {
if (authStore.publicLinkPassword) {
config.headers.Authorization =
'Basic ' +
Buffer.from(['public', authStore.publicLinkPassword].join(':')).toString('base64')
}
if (authStore.publicLinkToken) {
config.headers['public-token'] = authStore.publicLinkToken
}
}
config.method = method
config.url = url
return httpClient.request(config)
}
return {
makeRequest
}
}
| owncloud/web/packages/web-pkg/src/composables/authContext/useRequest.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/authContext/useRequest.ts",
"repo_id": "owncloud",
"token_count": 504
} | 842 |
export * from './useFileListHeaderPosition'
| owncloud/web/packages/web-pkg/src/composables/fileListHeaderPosition/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/fileListHeaderPosition/index.ts",
"repo_id": "owncloud",
"token_count": 12
} | 843 |
export abstract class PaginationConstants {
static readonly perPageDefault: string = '100'
static readonly perPageQueryName: string = 'items-per-page'
static readonly options = ['20', '50', '100', '250', '500']
}
| owncloud/web/packages/web-pkg/src/composables/pagination/constants.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/pagination/constants.ts",
"repo_id": "owncloud",
"token_count": 66
} | 844 |
import { defineStore } from 'pinia'
import { Ref, computed, ref, unref } from 'vue'
import {
extractStorageId,
isMountPointSpaceResource,
isProjectSpaceResource,
SpaceResource,
type Resource
} from '@ownclouders/web-client/src/helpers'
import { getIndicators, getParentPaths } from '../../helpers'
import { AncestorMetaData, AncestorMetaDataValue } from '../../types'
import { DavProperty, WebDAV } from '@ownclouders/web-client/src/webdav'
import { useSpacesStore } from './spaces'
import { useUserStore } from './user'
import { useConfigStore } from './config'
export const useResourcesStore = defineStore('resources', () => {
const configStore = useConfigStore()
const spacesStore = useSpacesStore()
const userStore = useUserStore()
const resources = ref<Resource[]>([]) as Ref<Resource[]>
const currentFolder = ref<Resource>()
const ancestorMetaData = ref<AncestorMetaData>({})
const activeResources = computed(() => {
let res = unref(resources)
if (!unref(areHiddenFilesShown)) {
res = res.filter((file) => !file.name.startsWith('.'))
}
return res
})
const totalResourcesSize = computed(() => {
return unref(resources)
.map((r) => (r.size ? parseInt(r.size.toString()) : 0))
.reduce((x, y) => x + y, 0)
})
const totalResourcesCount = computed(() => {
const fileCount = unref(resources).filter(({ type }) => type === 'file').length
const folderCount = unref(resources).filter(({ type }) => type === 'folder').length
const spaceCount = unref(resources).filter(isProjectSpaceResource).length
return {
files: fileCount,
folders: folderCount,
spaces: spaceCount
}
})
const setResources = (file: Resource[]) => {
resources.value = file
}
const removeResources = (values: Resource[]) => {
resources.value = unref(resources).filter((file) => !values.find(({ id }) => id === file.id))
}
const clearResources = () => {
resources.value = []
}
const upsertResource = (resource: Resource) => {
const existing = unref(resources).find(({ id }) => id === resource.id)
if (existing) {
Object.assign(existing, resource)
return
}
unref(resources).push(resource)
}
const upsertResources = (values: Resource[]) => {
const other = unref(resources).filter((f) => !values.some((r) => r.path === f.path))
resources.value = [...other, ...values]
}
const updateResourceField = <T extends Resource, K extends keyof Resource>({
id,
field,
value
}: {
id: T['id']
field: K
value: T[K]
}) => {
const resource = unref(resources).find((resource) => id === resource.id)
if (resource) {
resource[field] = value
}
}
const setCurrentFolder = (value: Resource) => {
currentFolder.value = value
}
const clearCurrentFolder = () => {
currentFolder.value = undefined
}
const initResourceList = (data: { resources: Resource[]; currentFolder: Resource }) => {
resources.value = data.resources
currentFolder.value = data.currentFolder
}
const clearResourceList = () => {
resources.value = []
currentFolder.value = undefined
selectedIds.value = []
}
const selectedIds = ref<string[]>([])
const latestSelectedId = ref<string>(null)
const selectedResources = computed(() => {
return unref(resources).filter((f) => unref(selectedIds).includes(f.id))
})
const setSelection = (ids: string[]) => {
const latestSelected = ids.find((id) => !unref(selectedIds).includes(id))
if (latestSelected) {
latestSelectedId.value = latestSelected
}
selectedIds.value = ids
}
const addSelection = (id: string) => {
latestSelectedId.value = id
if (!unref(selectedIds).includes(id)) {
unref(selectedIds).push(id)
}
}
const removeSelection = (id: string) => {
latestSelectedId.value = id
if (unref(selectedIds).includes(id)) {
delete unref(selectedIds)[id]
}
}
const toggleSelection = (id: string) => {
if (unref(selectedIds).includes(id)) {
removeSelection(id)
} else {
addSelection(id)
}
}
const resetSelection = () => {
selectedIds.value = []
}
const setLastSelectedId = (id: string) => {
latestSelectedId.value = id
}
const areHiddenFilesShown = ref(true)
const areFileExtensionsShown = ref(true)
const areWebDavDetailsShown = ref(false)
const setAreHiddenFilesShown = (value: boolean) => {
areHiddenFilesShown.value = value
window.localStorage.setItem('oc_hiddenFilesShown', value.toString())
}
const setAreFileExtensionsShown = (value: boolean) => {
areFileExtensionsShown.value = value
window.localStorage.setItem('oc_fileExtensionsShown', value.toString())
}
const setAreWebDavDetailsShown = (value: boolean) => {
areWebDavDetailsShown.value = value
window.localStorage.setItem('oc_webDavDetailsShown', value.toString())
}
const loadIndicators = (path: string) => {
const files = unref(resources).filter((f) => f.path.startsWith(path))
for (const resource of files) {
const indicators = getIndicators({
resource,
ancestorMetaData: unref(ancestorMetaData)
})
if (!indicators.length && !resource.indicators.length) {
continue
}
updateResourceField({ id: resource.id, field: 'indicators', value: indicators })
}
}
const setAncestorMetaData = (value: AncestorMetaData) => {
ancestorMetaData.value = value
}
const updateAncestorField = <
T extends AncestorMetaDataValue,
K extends keyof AncestorMetaDataValue
>({
path,
field,
value
}: {
path: T['path']
field: K
value: T[K]
}) => {
const resource = unref(ancestorMetaData)[path] ?? null
if (resource) {
resource[field] = value
}
}
const loadAncestorMetaData = ({
folder,
space,
client
}: {
folder: Resource
space: SpaceResource
client: WebDAV
}) => {
const data: AncestorMetaData = {
[folder.path]: {
id: folder.fileId,
shareTypes: folder.shareTypes,
parentFolderId: folder.parentFolderId,
spaceId: space.id,
path: folder.path
}
}
const promises = []
const davProperties = [DavProperty.FileId, DavProperty.ShareTypes, DavProperty.FileParent]
const parentPaths = getParentPaths(folder.path)
const spaces = spacesStore.spaces
const getMountPoints = () =>
spaces.filter(
(s) =>
isMountPointSpaceResource(s) && extractStorageId(s.root.remoteItem.rootId) === space.id
)
let fullyAccessibleSpace = true
if (configStore.options.routing.fullShareOwnerPaths) {
// keep logic in sync with "isResourceAccessible" from useGetMatchingSpace
const projectSpace = spaces.find((s) => isProjectSpaceResource(s) && s.id === space.id)
fullyAccessibleSpace = space.isOwner(userStore.user) || projectSpace?.isMember(userStore.user)
}
for (const path of parentPaths) {
const cachedData = unref(ancestorMetaData)[path] ?? null
if (cachedData?.spaceId === space.id) {
data[path] = cachedData
continue
}
// keep logic in sync with "isResourceAccessible" from useGetMatchingSpace
if (
!fullyAccessibleSpace &&
!getMountPoints().find((m) => path.startsWith(m.root.remoteItem.path))
) {
// no access to the parent resource
break
}
promises.push(
client.listFiles(space, { path }, { depth: 0, davProperties }).then(({ resource }) => {
data[path] = {
id: resource.fileId,
shareTypes: resource.shareTypes,
parentFolderId: resource.parentFolderId,
spaceId: space.id,
path
}
})
)
}
return Promise.all(promises).then(() => {
setAncestorMetaData(data)
})
}
return {
resources,
currentFolder,
activeResources,
totalResourcesCount,
totalResourcesSize,
setResources,
removeResources,
clearResources,
upsertResource,
upsertResources,
updateResourceField,
setCurrentFolder,
clearCurrentFolder,
initResourceList,
clearResourceList,
selectedIds,
latestSelectedId,
selectedResources,
setSelection,
addSelection,
removeSelection,
toggleSelection,
resetSelection,
setLastSelectedId,
areHiddenFilesShown,
areFileExtensionsShown,
areWebDavDetailsShown,
setAreHiddenFilesShown,
setAreFileExtensionsShown,
setAreWebDavDetailsShown,
loadIndicators,
ancestorMetaData,
setAncestorMetaData,
updateAncestorField,
loadAncestorMetaData
}
})
export type ResourcesStore = ReturnType<typeof useResourcesStore>
| owncloud/web/packages/web-pkg/src/composables/piniaStores/resources.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/resources.ts",
"repo_id": "owncloud",
"token_count": 3290
} | 845 |
import { RouteMeta } from 'vue-router'
type Dictionary<T> = { [key: string]: T }
export type QueryValue = string | (string | null)[]
export type LocationQuery = Dictionary<QueryValue>
export type ParamValue = string
export const authContextValues = ['anonymous', 'user', 'idp', 'publicLink', 'hybrid'] as const
export type AuthContext = (typeof authContextValues)[number]
export interface WebRouteMeta extends RouteMeta {
title?: string
authContext?: AuthContext
patchCleanPath?: boolean
contextQueryItems?: string[]
}
| owncloud/web/packages/web-pkg/src/composables/router/types.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/router/types.ts",
"repo_id": "owncloud",
"token_count": 148
} | 846 |
export * from './useSelectedResources'
| owncloud/web/packages/web-pkg/src/composables/selection/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/selection/index.ts",
"repo_id": "owncloud",
"token_count": 11
} | 847 |
export * from './useUpload'
| owncloud/web/packages/web-pkg/src/composables/upload/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/upload/index.ts",
"repo_id": "owncloud",
"token_count": 9
} | 848 |
export const triggerDownloadWithFilename = (url: string, name: string) => {
const a = document.createElement('a')
a.style.display = 'none'
document.body.appendChild(a)
a.href = url
// use download attribute to set desired file name
a.setAttribute('download', name)
// trigger the download by simulating click
a.click()
// cleanup
document.body.removeChild(a)
}
| owncloud/web/packages/web-pkg/src/helpers/download.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/download.ts",
"repo_id": "owncloud",
"token_count": 115
} | 849 |
export * from './sameResource'
export * from './conflictHandling'
export * from './filter'
export * from './icon'
export * from './isResourceTxtFileAlmostEmpty'
export * from './renameResource'
| owncloud/web/packages/web-pkg/src/helpers/resource/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/resource/index.ts",
"repo_id": "owncloud",
"token_count": 60
} | 850 |
export * from './client'
| owncloud/web/packages/web-pkg/src/http/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/http/index.ts",
"repo_id": "owncloud",
"token_count": 8
} | 851 |
import { HttpClient as _HttpClient } from '../../http'
import { client, Graph, OCS } from '@ownclouders/web-client'
import { Auth, AuthParameters } from './auth'
import axios, { AxiosInstance } from 'axios'
import { v4 as uuidV4 } from 'uuid'
import { WebDAV } from '@ownclouders/web-client/src/webdav'
import { Language } from 'vue3-gettext'
import { FetchEventSourceInit } from '@microsoft/fetch-event-source'
import { sse } from '@ownclouders/web-client/src/sse'
import { AuthStore, ConfigStore, UserStore } from '../../composables'
import { computed } from 'vue'
interface OcClient {
token: string
language: string
graph: Graph
ocs: OCS
}
interface HttpClient {
client: _HttpClient
language: string
token?: string
}
const createFetchOptions = (authParams: AuthParameters, language: string): FetchEventSourceInit => {
return {
headers: {
Authorization: `Bearer ${authParams.accessToken}`,
'Accept-Language': language,
'X-Request-ID': uuidV4(),
'X-Requested-With': 'XMLHttpRequest'
}
}
}
const createAxiosInstance = (authParams: AuthParameters, language: string): AxiosInstance => {
const auth = new Auth(authParams)
const axiosClient = axios.create({
headers: auth.getHeaders()
})
axiosClient.interceptors.request.use((config) => {
config.headers['X-Request-ID'] = uuidV4()
config.headers['X-Requested-With'] = 'XMLHttpRequest'
config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
config.headers['Accept-Language'] = language
return config
})
return axiosClient
}
export interface ClientServiceOptions {
configStore: ConfigStore
language: Language
authStore: AuthStore
userStore: UserStore
}
export class ClientService {
private configStore: ConfigStore
private language: Language
private authStore: AuthStore
private userStore: UserStore
private httpAuthenticatedClient: HttpClient
private httpUnAuthenticatedClient: HttpClient
private ocUserContextClient: OcClient
private ocPublicLinkContextClient: OcClient
private webdavClient: WebDAV
constructor(options: ClientServiceOptions) {
this.configStore = options.configStore
this.language = options.language
this.authStore = options.authStore
this.userStore = options.userStore
}
public get httpAuthenticated(): _HttpClient {
if (this.clientNeedsInit(this.httpAuthenticatedClient)) {
this.httpAuthenticatedClient = this.getHttpClient(true)
}
return this.httpAuthenticatedClient.client
}
public get httpUnAuthenticated(): _HttpClient {
if (this.clientNeedsInit(this.httpUnAuthenticatedClient, false)) {
this.httpUnAuthenticatedClient = this.getHttpClient()
}
return this.httpUnAuthenticatedClient.client
}
public get graphAuthenticated(): Graph {
if (this.clientNeedsInit(this.ocUserContextClient)) {
this.ocUserContextClient = this.getOcsClient({ accessToken: this.authStore.accessToken })
}
return this.ocUserContextClient.graph
}
public get sseAuthenticated(): EventSource {
return sse(
this.configStore.serverUrl,
createFetchOptions({ accessToken: this.authStore.accessToken }, this.currentLanguage)
)
}
public get ocsUserContext(): OCS {
if (this.clientNeedsInit(this.ocUserContextClient)) {
this.ocUserContextClient = this.getOcsClient({ accessToken: this.authStore.accessToken })
}
return this.ocUserContextClient.ocs
}
public ocsPublicLinkContext(password?: string): OCS {
if (this.clientNeedsInit(this.ocPublicLinkContextClient)) {
this.ocPublicLinkContextClient = this.getOcsClient({
publicLinkToken: this.authStore.accessToken,
publicLinkPassword: password
})
}
return this.ocPublicLinkContextClient.ocs
}
private getHttpClient(authenticated = false): HttpClient {
return {
...(!!authenticated && { token: this.authStore.accessToken }),
language: this.currentLanguage,
client: new _HttpClient({
baseURL: this.configStore.serverUrl,
headers: {
'Accept-Language': this.currentLanguage,
...(!!authenticated && { Authorization: 'Bearer ' + this.authStore.accessToken }),
'X-Requested-With': 'XMLHttpRequest',
'X-Request-ID': uuidV4()
}
})
}
}
private getOcsClient(authParams: AuthParameters): OcClient {
const { graph, ocs } = client(
this.configStore.serverUrl,
createAxiosInstance(authParams, this.currentLanguage),
computed(() => this.userStore.user)
)
return {
token: this.authStore.accessToken,
language: this.currentLanguage,
graph,
ocs
}
}
private clientNeedsInit(client, hasToken = true) {
return (
!client ||
(hasToken && client.token !== this.authStore.accessToken) ||
client.language !== this.currentLanguage
)
}
public get webdav(): WebDAV {
return this.webdavClient
}
public set webdav(webdav: WebDAV) {
this.webdavClient = webdav
}
get currentLanguage(): string {
return this.language.current
}
}
| owncloud/web/packages/web-pkg/src/services/client/client.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/services/client/client.ts",
"repo_id": "owncloud",
"token_count": 1794
} | 852 |
import { IconFillType } from '../helpers/resource'
import { Component } from 'vue'
export type FolderView = {
name: string
label: string
icon: {
name: string
fillType: IconFillType
}
isScrollable?: boolean
component: Component
componentAttrs?: () => Record<string, unknown>
}
| owncloud/web/packages/web-pkg/src/ui/types.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/ui/types.ts",
"repo_id": "owncloud",
"token_count": 96
} | 853 |
import ActionMenuItem from '../../../../src/components/ContextActions/ActionMenuItem.vue'
import { defaultPlugins, mount, shallowMount } from 'web-test-helpers'
const selectors = {
handler: '[data-testid="action-handler"]',
icon: '[data-testid="action-icon"]',
img: '[data-testid="action-img"]',
label: '[data-testid="action-label"]',
srHint: '[data-testid="action-sr-hint"]',
ariaLabel: '[aria-label="foo"]'
}
const fileActions = {
download: {
name: 'download-file',
icon: 'file-download',
handler: vi.fn(),
label: () => 'Download',
componentType: 'button',
class: 'oc-files-actions-download-file-trigger',
selector: '.oc-files-actions-download-file-trigger'
},
navigate: {
name: 'navigate',
icon: 'folder-open',
route: () => ({ name: 'files-personal' }),
label: () => 'Open Folder',
componentType: 'router-link',
class: 'oc-files-actions-navigate-trigger',
selector: '.oc-files-actions-navigate-trigger'
}
}
describe('ActionMenuItem component', () => {
it('renders an icon if there is one defined in the action', () => {
const action = fileActions.download
const { wrapper } = getWrapper(action)
expect(wrapper.find(selectors.icon).exists()).toBeTruthy()
expect(wrapper.find(selectors.icon).attributes().name).toBe(action.icon)
})
it('renders an image if there is one defined in the action', () => {
const action = { ...fileActions.download, img: 'https://owncloud.tld/img.png' }
const { wrapper } = getWrapper(action)
expect(wrapper.find(selectors.icon).exists()).toBeFalsy()
expect(wrapper.find(selectors.img).exists()).toBeTruthy()
expect(wrapper.find(selectors.img).attributes().src).toBe(action.img)
})
it('renders the action label', () => {
const action = fileActions.download
const { wrapper } = getWrapper(action)
expect(wrapper.find(selectors.label).exists()).toBeTruthy()
expect(wrapper.find(selectors.label).text()).toBe(action.label())
})
it('renders a tooltip for a disabled action', () => {
const action = { ...fileActions.download, disabledTooltip: () => 'Foo', isDisabled: () => true }
const { wrapper } = getWrapper(action)
expect(wrapper.find(fileActions.download.selector).attributes().arialabel).toBe(
action.disabledTooltip()
)
expect(wrapper.find(fileActions.download.selector).attributes().disabled).toBeTruthy()
})
describe('component is of type oc-button', () => {
it('calls the action handler on button click', async () => {
const action = fileActions.download
const spyHandler = action.handler
const { wrapper } = getWrapper(action, [], null, mount)
const button = wrapper.find(selectors.handler)
expect(button.exists()).toBeTruthy()
expect(button.element.tagName).toBe('BUTTON')
await button.trigger('click')
expect(spyHandler).toHaveBeenCalled()
})
})
describe('component is of type router-link', () => {
it('has a link', () => {
const action = fileActions.navigate
const { wrapper } = getWrapper(action, [], null, mount)
const link = wrapper.find(selectors.handler)
expect(link.exists()).toBeTruthy()
expect(link.element.tagName).toBe('ROUTER-LINK-STUB')
// FIXME: to.name cannot be accessed, because the attributes().to holds a string containing `[object Object]`.
// That doesn't allow checking the name of the router-link.
// expect(link.attributes().href).toBe(action.route)
})
})
})
function getWrapper(action, items = [], appearance = null, mountType = shallowMount) {
return {
wrapper: mountType(ActionMenuItem, {
props: {
action,
actionOptions: {},
items,
...(appearance && { appearance })
},
global: {
renderStubDefaultSlot: true,
stubs: {
'router-link': true
},
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/ContextActions/ActionMenuItem.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/ContextActions/ActionMenuItem.spec.ts",
"repo_id": "owncloud",
"token_count": 1463
} | 854 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`OcResource > displays parent folder name default if calculated name is empty 1`] = `
"<div class="oc-resource oc-text-overflow"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-left oc-button-gap-undefined oc-button-passive oc-button-passive-raw oc-resource-link" draggable="false">
<!--v-if-->
<!-- @slot Content of the button --> <span class="oc-icon oc-icon-l oc-icon-passive oc-resource-icon oc-resource-icon-file"><!----></span>
</button>
<div class="oc-resource-details oc-text-overflow oc-pl-s"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-left oc-button-gap-undefined oc-button-passive oc-button-passive-raw oc-text-overflow" draggable="false">
<!--v-if-->
<!-- @slot Content of the button -->
<!--v-if--> <span class="oc-resource-name" data-test-resource-path="example.pdf" data-test-resource-name="example.pdf" data-test-resource-type="file"><span class="oc-text-truncate"><span class="oc-resource-basename">example</span></span><span class="oc-resource-extension">.pdf</span></span>
</button>
<div class="oc-resource-indicators"><span style="cursor: default;" class="parent-folder oc-text-truncate"><span class="oc-icon oc-icon-s oc-icon-passive"><!----></span> <span class="text oc-text-truncate">Example parent folder name</span></span></div>
</div>
</div>"
`;
| owncloud/web/packages/web-pkg/tests/unit/components/FilesList/__snapshots__/ResourceListItem.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/FilesList/__snapshots__/ResourceListItem.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 525
} | 855 |
import { OcProgress } from 'design-system/src/components'
import { SpaceQuota } from '../../../src/components'
import { defaultPlugins, shallowMount } from 'web-test-helpers'
describe('SpaceQuota component', () => {
it('renders the space storage quota label', () => {
const { wrapper } = getWrapper({ total: 10, used: 1, state: 'normal' })
expect(wrapper.find('.space-quota').exists()).toBeTruthy()
expect(wrapper.html()).toMatchSnapshot()
})
it.each([
{ state: 'normal', expectedVariation: 'primary' },
{ state: 'nearing', expectedVariation: 'warning' },
{ state: 'critical', expectedVariation: 'warning' },
{ state: 'exceeded', expectedVariation: 'danger' }
])('renders the progress variant correctly', (dataSet) => {
const { wrapper } = getWrapper({ total: 10, used: 1, state: dataSet.state })
const progressBar = wrapper.findComponent<typeof OcProgress>('.space-quota oc-progress-stub')
expect(progressBar.exists()).toBeTruthy()
expect(progressBar.props().variation).toBe(dataSet.expectedVariation)
})
})
function getWrapper(spaceQuota) {
return {
wrapper: shallowMount(SpaceQuota, {
props: {
spaceQuota
},
global: {
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/SpaceQuota.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/SpaceQuota.spec.ts",
"repo_id": "owncloud",
"token_count": 460
} | 856 |
import { mock } from 'vitest-mock-extended'
import { unref } from 'vue'
import { Resource } from '@ownclouders/web-client'
import { defaultComponentMocks, RouteLocation, getComposableWrapper } from 'web-test-helpers'
import { useFileActionsCopy } from '../../../../../src/composables/actions/files'
import { useClipboardStore } from '../../../../../src/composables/piniaStores'
describe('copy', () => {
describe('search context', () => {
describe('computed property "actions"', () => {
describe('handler', () => {
it.each([
{
resources: [{ id: '1' }, { id: '2' }] as Resource[],
copyAbleResources: ['1', '2']
},
{
resources: [
{ id: '1' },
{ id: '2' },
{ id: '3' },
{ id: '4', fileId: '5', canDownload: () => true, driveType: 'project' }
] as Resource[],
copyAbleResources: ['1', '2', '3']
}
])('should filter non copyable resources', ({ resources, copyAbleResources }) => {
getWrapper({
searchLocation: true,
setup: ({ actions }) => {
unref(actions)[0].handler({ space: null, resources })
const clipboardStore = useClipboardStore()
expect(clipboardStore.copyResources).toHaveBeenCalledWith(
resources.filter((r) => copyAbleResources.includes(r.id as string))
)
}
})
})
})
})
})
})
function getWrapper({
searchLocation = false,
setup
}: {
searchLocation: boolean
setup: (instance: ReturnType<typeof useFileActionsCopy>) => void
}) {
const routeName = searchLocation ? 'files-common-search' : 'files-spaces-generic'
const mocks = {
...defaultComponentMocks({ currentRoute: mock<RouteLocation>({ name: routeName }) }),
space: { driveType: 'personal', spaceRoles: { viewer: [], editor: [], manager: [] } }
}
return {
mocks,
wrapper: getComposableWrapper(
() => {
const instance = useFileActionsCopy()
setup(instance)
},
{
mocks,
provide: mocks
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCopy.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCopy.spec.ts",
"repo_id": "owncloud",
"token_count": 967
} | 857 |
import { useFileActionsDeleteResources } from '../../../../../src/composables/actions'
import { mockDeep } from 'vitest-mock-extended'
import { FolderResource, SpaceResource } from '@ownclouders/web-client/src/helpers'
import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers'
import { nextTick } from 'vue'
const currentFolder = {
id: '1',
path: '/folder'
}
describe('deleteResources', () => {
describe('method "filesList_delete"', () => {
it('should call the delete action on a resource in the file list', () => {
getWrapper({
currentFolder,
setup: async ({ filesList_delete }, { router }) => {
await filesList_delete([{ id: '2', path: '/folder/fileToDelete.txt' }])
await nextTick()
expect(router.push).toHaveBeenCalledTimes(0)
}
})
})
it('should call the delete action on the current folder', () => {
const resourcesToDelete = [currentFolder]
getWrapper({
currentFolder,
setup: async ({ filesList_delete }, { router }) => {
await filesList_delete(resourcesToDelete)
// FIXME: well...
await nextTick()
await nextTick()
await nextTick()
await nextTick()
await nextTick()
await nextTick()
await nextTick()
await nextTick()
await nextTick()
expect(router.push).toHaveBeenCalledTimes(1)
}
})
})
})
})
function getWrapper({
currentFolder,
setup
}: {
currentFolder: FolderResource
setup: (
instance: ReturnType<typeof useFileActionsDeleteResources>,
{
space,
router
}: {
space: SpaceResource
router: ReturnType<typeof defaultComponentMocks>['$router']
}
) => void
}) {
const mocks = {
...defaultComponentMocks(),
space: mockDeep<SpaceResource>()
}
mocks.$clientService.webdav.deleteFile.mockResolvedValue(undefined)
return {
mocks,
wrapper: getComposableWrapper(
() => {
const instance = useFileActionsDeleteResources()
setup(instance, { space: mocks.space, router: mocks.$router })
},
{
mocks,
provide: mocks,
pluginOptions: { piniaOptions: { resourcesStore: { currentFolder } } }
}
)
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/helpers/useFileActionsDeleteResources.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/helpers/useFileActionsDeleteResources.spec.ts",
"repo_id": "owncloud",
"token_count": 955
} | 858 |
import { defineComponent } from 'vue'
import { useFileListHeaderPosition } from '../../../../../src/composables/fileListHeaderPosition'
import { defaultPlugins, mount } from 'web-test-helpers'
export const createWrapper = () =>
mount(
defineComponent({
setup() {
const { y, refresh } = useFileListHeaderPosition()
return { y, refresh }
},
template: `<div>{{ y }}</div>`
}),
{
attachTo: document.body,
global: {
plugins: [...defaultPlugins()]
}
}
)
export const createAppBar = (): {
createElement: () => void
resize: (height: number) => void
remove: () => void
} => {
const createElement = () => {
const appBar = document.createElement('div')
appBar.setAttribute('id', 'files-app-bar')
document.body.appendChild(appBar)
}
const resize = (height = 0) => {
document.getElementById('files-app-bar').getBoundingClientRect = vi
.fn()
.mockReturnValue({ height })
}
const remove = () => {
document.getElementById('files-app-bar').remove()
}
return { createElement, resize, remove }
}
| owncloud/web/packages/web-pkg/tests/unit/composables/fileListHeaderPosition/spec/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/fileListHeaderPosition/spec/index.ts",
"repo_id": "owncloud",
"token_count": 416
} | 859 |
import { ref, unref } from 'vue'
import { SortDir, SortOptions, useSort } from '../../../../src/composables'
import { Resource } from '@ownclouders/web-client/src/helpers/resource'
import { getComposableWrapper } from 'web-test-helpers'
describe('useSort', () => {
it('should be valid', () => {
expect(useSort).toBeDefined()
})
it('does not sort if no sort field was given', () => {
getComposableWrapper(() => {
const input: SortOptions<any> = {
items: [{ id: '3' }, { id: '4' }, { id: '6' }, { id: '1' }, { id: '2' }, { id: '5' }],
fields: [],
sortBy: ref(null),
sortDir: ref(null),
routeName: 'mocked'
}
const { items } = useSort(input)
expect(unref(items)).toMatchObject([
{ id: '3' },
{ id: '4' },
{ id: '6' },
{ id: '1' },
{ id: '2' },
{ id: '5' }
])
})
})
describe('sorting resources', () => {
const resources: Resource[] = [
{ id: '1', name: 'c.png', path: '', webDavPath: '', sdate: '2' },
{ id: '2', name: 'Dir4', path: '', webDavPath: '', sdate: '4', type: 'folder' },
{ id: '3', name: 'a.png', path: '', webDavPath: '', sdate: '3' },
{ id: '4', name: 'A.png', path: '', webDavPath: '', sdate: '6' },
{ id: '5', name: 'dir2', path: '', webDavPath: '', sdate: '7', type: 'folder' },
{ id: '6', name: 'b.png', path: '', webDavPath: '', sdate: '1' },
{ id: '7', name: 'Dir1', path: '', webDavPath: '', sdate: '5', type: 'folder' },
{ id: '8', name: 'dir11', path: '', webDavPath: '', sdate: '8', type: 'folder' },
{ id: '9', name: 'dir3', path: '', webDavPath: '', sdate: '9', type: 'folder' }
]
it('sorts resources by name', () => {
getComposableWrapper(() => {
const sortDir = ref(SortDir.Asc)
const input = {
items: ref<Resource[]>(resources),
fields: [
{
name: 'name',
sortable: true
},
{
name: 'sdate',
sortable: true
}
],
sortBy: ref('name'),
sortDir
}
const { items } = useSort<Resource>(input)
expect(unref(items).map((i) => i.name)).toMatchObject([
'Dir1',
'dir2',
'dir3',
'Dir4',
'dir11',
'a.png',
'A.png',
'b.png',
'c.png'
])
sortDir.value = SortDir.Desc
expect(unref(items).map((i) => i.name)).toMatchObject([
'c.png',
'b.png',
'a.png',
'A.png',
'dir11',
'Dir4',
'dir3',
'dir2',
'Dir1'
])
})
})
})
})
| owncloud/web/packages/web-pkg/tests/unit/composables/sort/useSort.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/sort/useSort.spec.ts",
"repo_id": "owncloud",
"token_count": 1460
} | 860 |
import { isSameResource } from '../../../../src'
describe('isSameResource', () => {
test('evaluates to false if one of the resources is nullish', () => {
expect(isSameResource(null, null)).toBe(false)
expect(isSameResource(undefined, undefined)).toBe(false)
expect(isSameResource(null, { id: '1', path: '', webDavPath: '' })).toBe(false)
expect(isSameResource(undefined, { id: '1', path: '', webDavPath: '' })).toBe(false)
expect(isSameResource({ id: '1', path: '', webDavPath: '' }, null)).toBe(false)
expect(isSameResource({ id: '1', path: '', webDavPath: '' }, undefined)).toBe(false)
})
test('evaluates to false if ids are different values', () => {
expect(
isSameResource({ id: '1', path: '', webDavPath: '' }, { id: '2', path: '', webDavPath: '' })
).toBe(false)
})
test('evaluates to true if ids are the same', () => {
expect(
isSameResource({ id: '1', path: '', webDavPath: '' }, { id: '1', path: '', webDavPath: '' })
).toBe(true)
})
})
| owncloud/web/packages/web-pkg/tests/unit/helpers/resource/sameResource.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/resource/sameResource.spec.ts",
"repo_id": "owncloud",
"token_count": 388
} | 861 |
import { urlJoin } from '@ownclouders/web-client/src/utils'
describe('proper-url-join', () => {
it.each([
[['http://foobar.com'], 'http://foobar.com'],
[['http://foobar.com/'], 'http://foobar.com'],
[['/', ''], '/'],
[['/', 'foo'], '/foo'],
[['/', 'foo/'], '/foo'],
[['foo/'], '/foo'],
[['/', undefined], '/'],
[['', { leadingSlash: true }], '/'],
[[undefined, { leadingSlash: true }], '/'],
[['/', 2], '/2'],
[['//', '/fol//der//', '//file'], '/fol/der/file'],
[['?&@'], '/?&@']
])('joins %s as %s', (args: any, expected: string) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
expect(urlJoin(...args)).toBe(expected)
})
})
| owncloud/web/packages/web-pkg/tests/unit/utils/urlJoin.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/utils/urlJoin.spec.ts",
"repo_id": "owncloud",
"token_count": 333
} | 862 |
<template>
<button class="skip-button" @click="skipToTarget"><slot /></button>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
props: {
/*
* The element to focus and to skip to
*/
target: {
type: String,
required: true
}
},
computed: {
targetElement() {
return document.getElementById(this.target)
}
},
methods: {
skipToTarget() {
this.targetElement.setAttribute('tabindex', '-1')
this.targetElement.focus()
this.targetElement.scrollIntoView()
}
}
})
</script>
<style scoped>
.skip-button {
position: absolute;
top: -100px;
left: 0;
z-index: 6;
-webkit-appearance: none;
border: none;
background-color: var(--oc-color-swatch-brand-default);
color: var(--oc-color-swatch-primary-contrast);
font: inherit;
padding: 0.25em 0.5em;
}
.skip-button:focus {
top: 0;
outline: none;
border: 1px dashed white;
}
</style>
| owncloud/web/packages/web-runtime/src/components/SkipTo.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/components/SkipTo.vue",
"repo_id": "owncloud",
"token_count": 388
} | 863 |
import { RouteRecordRaw, Router } from 'vue-router'
import clone from 'lodash-es/clone'
import { RuntimeApi } from './types'
import { ApiError, ExtensionRegistry, SidebarNavExtension } from '@ownclouders/web-pkg'
import { isEqual, isObject, isArray, merge } from 'lodash-es'
import { App, Component, computed, h } from 'vue'
import { ApplicationTranslations, AppNavigationItem } from '@ownclouders/web-pkg'
import type { Language } from 'vue3-gettext'
/**
* inject application specific routes into runtime
*
* @param applicationId
* @param router
* @param routes
*/
const announceRoutes = (applicationId: string, router: Router, routes: RouteRecordRaw[]): void => {
if (!isArray(routes)) {
throw new ApiError("routes can't be blank")
}
const namespaceRouteName = (name: string) => {
return name.startsWith(`${applicationId}-`) ? name : `${applicationId}-${name}`
}
routes
.map((applicationRoute) => {
if (!isObject(applicationRoute)) {
throw new ApiError("route can't be blank", applicationRoute)
}
const route = clone(applicationRoute)
if (route.name) {
route.name =
applicationId === route.name ? route.name : namespaceRouteName(String(route.name))
}
route.path = `/${encodeURI(applicationId)}${route.path}`
if (route.children) {
route.children = route.children.map((childRoute) => {
if (!isObject(applicationRoute)) {
throw new ApiError("route children can't be blank", applicationRoute, childRoute)
}
const r = clone(childRoute)
if (childRoute.name) {
r.name = namespaceRouteName(String(childRoute.name))
}
return r
})
}
return route
})
.forEach((route) => {
router.addRoute(route)
})
}
/**
* inject application specific navigation items into runtime
*
* @param applicationId
* @param extensionRegistry
* @param navigationItems
*/
const announceNavigationItems = (
applicationId: string,
extensionRegistry: ExtensionRegistry,
navigationItems: AppNavigationItem[]
): void => {
if (!isObject(navigationItems)) {
throw new ApiError("navigationItems can't be blank")
}
const navExtensions = navigationItems.map((navItem) => ({
id: `app.${applicationId}.${navItem.name}`,
type: 'sidebarNav',
navItem,
scopes: [`app.${applicationId}`]
})) as SidebarNavExtension[]
extensionRegistry.registerExtensions(computed(() => navExtensions))
}
/**
* inject application specific translations into runtime
*
* @param translations
* @param appTranslations
* @param supportedLanguages
*/
const announceTranslations = (
supportedLanguages: { [key: string]: string },
gettext: Language,
appTranslations: ApplicationTranslations
): void => {
if (!isObject(gettext.translations)) {
throw new ApiError("translations can't be blank")
}
Object.keys(supportedLanguages).forEach((lang) => {
if (gettext.translations[lang] && appTranslations[lang]) {
gettext.translations = merge(gettext.translations, { [lang]: appTranslations[lang] })
}
})
}
/**
* open a wormhole portal, this wraps vue-portal
*
* @param instance
* @param applicationId
* @param toApp
* @param toPortal
* @param order
* @param components
*/
const openPortal = (
applicationId: string,
instance: App,
toApp: string,
toPortal: string,
order: number,
components: Component[]
): void => {
instance.config.globalProperties.$wormhole.open({
to: ['app', toApp, toPortal].filter(Boolean).join('.'),
from: ['app', applicationId, toPortal, order].filter(Boolean).join('.'),
order: order,
content: () => components.map((c) => h(c))
})
}
/**
* expose router to the application
*
* @deprecated use with caution
*
* @param router
*/
const requestRouter = (router: Router): Router => {
if (isEqual(process.env.NODE_ENV, 'development')) {
console.warn('requestRouter // router api is deprecated, use with caution')
}
return router
}
/**
* exposed runtime api, this wraps all available api actions in a closure and provides application
* specific data to the implementations.
*
* each application get its own provisioned api!
*
* @param applicationName
* @param applicationId
* @param store
* @param router
* @param translations
* @param supportedLanguages
*/
export const buildRuntimeApi = ({
applicationName,
applicationId,
router,
gettext,
supportedLanguages,
extensionRegistry
}: {
applicationName: string
applicationId: string
gettext: Language
router: Router
supportedLanguages: { [key: string]: string }
extensionRegistry: ExtensionRegistry
}): RuntimeApi => {
if (!applicationName) {
throw new ApiError("applicationName can't be blank")
}
if (!applicationId) {
throw new ApiError("applicationId can't be blank")
}
return {
announceRoutes: (routes: RouteRecordRaw[]): void =>
announceRoutes(applicationId, router, routes),
announceNavigationItems: (navigationItems: AppNavigationItem[]): void =>
announceNavigationItems(applicationId, extensionRegistry, navigationItems),
announceTranslations: (appTranslations: ApplicationTranslations): void =>
announceTranslations(supportedLanguages, gettext, appTranslations),
requestRouter: (): Router => requestRouter(router),
openPortal: (
instance: App,
toApp: string,
toPortal: string,
order: number,
components: Component[]
): void => openPortal(applicationId, instance, toApp, toPortal, order, components)
}
}
| owncloud/web/packages/web-runtime/src/container/api.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/container/api.ts",
"repo_id": "owncloud",
"token_count": 1871
} | 864 |
import { RouteLocationNamedRaw } from 'vue-router'
export interface Notification {
notification_id: string
app: string
user: string
datetime: string
subject: string
message?: string
messageRich?: string
messageRichParameters?: any
object_type?: string
object_id?: string
link?: string
computedMessage?: string
computedLink?: RouteLocationNamedRaw
}
| owncloud/web/packages/web-runtime/src/helpers/notifications.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/helpers/notifications.ts",
"repo_id": "owncloud",
"token_count": 106
} | 865 |
<template>
<div
class="oc-link-resolve oc-height-viewport oc-flex oc-flex-column oc-flex-center oc-flex-middle"
>
<div class="oc-card oc-text-center oc-width-large">
<template v-if="isLoading">
<div class="oc-card-header">
<h2 key="public-link-loading">
<span v-text="$gettext('Loading public link…')" />
</h2>
</div>
<div class="oc-card-body">
<oc-spinner :aria-hidden="true" />
</div>
</template>
<template v-else-if="errorMessage">
<div class="oc-card-header oc-link-resolve-error-title">
<h2 key="public-link-error">
<span v-text="$gettext('An error occurred while loading the public link')" />
</h2>
</div>
<div class="oc-card-body oc-link-resolve-error-message">
<p class="oc-text-xlarge">{{ errorMessage }}</p>
</div>
</template>
<template v-else-if="isPasswordRequired">
<form @submit.prevent="resolvePublicLinkTask.perform(true)">
<div class="oc-card-header">
<h2>
<span v-text="$gettext('This resource is password-protected')" />
</h2>
</div>
<div class="oc-card-body">
<oc-text-input
ref="passwordInput"
v-model="password"
:error-message="wrongPasswordMessage"
:label="passwordFieldLabel"
type="password"
class="oc-mb-s"
/>
<oc-button
variation="primary"
appearance="filled"
class="oc-login-authorize-button"
:disabled="!password"
submit="submit"
>
<span v-text="$gettext('Continue')" />
</oc-button>
</div>
</form>
</template>
<div class="oc-card-footer oc-pt-rm">
<p>{{ footerSlogan }}</p>
</div>
</div>
</div>
</template>
<script lang="ts">
import { SharePermissionBit } from '@ownclouders/web-client/src/helpers/share'
import { authService } from '../services/auth'
import {
queryItemAsString,
useAuthStore,
useClientService,
useConfigStore,
useRoute,
useRouteParam,
useRouteQuery,
useRouter,
useThemeStore
} from '@ownclouders/web-pkg'
import { useTask } from 'vue-concurrency'
import { ref, unref, computed, defineComponent, onMounted } from 'vue'
import {
buildPublicSpaceResource,
isPublicSpaceResource,
PublicSpaceResource
} from '@ownclouders/web-client/src/helpers'
import isEmpty from 'lodash-es/isEmpty'
import { useGettext } from 'vue3-gettext'
// full import is needed here so it can be overwritten via CERN config
import { useLoadTokenInfo } from 'web-runtime/src/composables/tokenInfo'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import { RouteLocationNamedRaw } from 'vue-router'
import { dirname } from 'path'
import { storeToRefs } from 'pinia'
export default defineComponent({
name: 'ResolvePublicLink',
setup() {
const configStore = useConfigStore()
const clientService = useClientService()
const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const { $gettext } = useGettext()
const token = useRouteParam('token')
const redirectUrl = useRouteQuery('redirectUrl')
const themeStore = useThemeStore()
const { currentTheme } = storeToRefs(themeStore)
const password = ref('')
const isOcmLink = computed(() => {
const split = unref(route).path.split('/')?.[1]
return split === 'o'
})
const publicLinkType = computed(() => {
return unref(isOcmLink) ? 'ocm' : 'public-link'
})
const publicLinkSpace = computed(() =>
buildPublicSpaceResource({
id: unref(token),
driveType: 'public',
publicLinkType: unref(publicLinkType),
...(unref(password) && { publicLinkPassword: unref(password) })
})
)
const item = computed(() => {
return queryItemAsString(unref(route).params.driveAliasAndItem)
})
const detailsQuery = useRouteQuery('details')
const details = computed(() => {
return queryItemAsString(unref(detailsQuery))
})
// token info
const { loadTokenInfoTask } = useLoadTokenInfo({ clientService, authStore })
const tokenInfo = ref(null)
// generic public link loading
const isPasswordRequired = ref<boolean>()
const isPasswordRequiredTask = useTask(function* () {
if (!isEmpty(unref(tokenInfo))) {
return unref(tokenInfo).password_protected
}
try {
let space: PublicSpaceResource = {
...unref(publicLinkSpace),
publicLinkPassword: null
}
yield clientService.webdav.getFileInfo(space)
return false
} catch (error) {
if (error.statusCode === 401) {
return true
}
if (error.statusCode === 404) {
throw new Error($gettext('The resource could not be located, it may not exist anymore.'))
}
throw error
}
})
const loadPublicLinkTask = useTask(function* () {
try {
const resource = yield clientService.webdav.getFileInfo(unref(publicLinkSpace))
if (!isPublicSpaceResource(resource)) {
const e: any = new Error($gettext('The resource is not a public link.'))
e.resource = resource
throw e
}
return resource
} catch (e) {
if (e.statusCode === 401) {
throw e
}
throw new Error($gettext('The resource could not be located, it may not exist anymore.'))
}
})
const wrongPassword = computed(() => {
if (loadPublicLinkTask.isError) {
return loadPublicLinkTask.last.error.statusCode === 401
}
return false
})
// resolve public link. resolve into authenticated context if possible.
const redirectToPrivateLink = (fileId: string | number) => {
return router.push({
name: 'resolvePrivateLink',
params: { fileId: `${fileId}` },
...(unref(details) && {
query: {
details: unref(details)
}
})
})
}
const resolvePublicLinkTask = useTask(function* (signal, passwordRequired: boolean) {
if (unref(isOcmLink) && !configStore.options.ocm.openRemotely) {
throw new Error($gettext('Opening files from remote is disabled'))
}
if (!isEmpty(unref(tokenInfo)) && unref(tokenInfo)?.alias_link) {
redirectToPrivateLink(unref(tokenInfo).id)
return
}
const publicLink = yield loadPublicLinkTask.perform()
if (loadPublicLinkTask.isError) {
const e = loadPublicLinkTask.last.error
console.error(e, e.resource)
return
}
yield authService.resolvePublicLink(
unref(token),
unref(passwordRequired),
unref(passwordRequired) ? unref(password) : '',
unref(publicLinkType)
)
const url = queryItemAsString(unref(redirectUrl))
if (url) {
router.push({ path: url })
return
}
let fileId: string
const { resource, children } = yield clientService.webdav.listFiles(unref(publicLinkSpace), {
path: unref(item)
})
if (children.length === 1) {
// single shared file which means the actual resource is the first and only child element
fileId = children[0].fileId
} else {
fileId = resource.fileId
}
if (publicLink.publicLinkPermission === SharePermissionBit.Create) {
router.push({
name: 'files-public-upload',
params: { token: unref(token) },
query: { ...(!!fileId && { fileId }) }
})
return
}
let scrollTo: string
let path: string
if (['folder', 'space'].includes(resource.type)) {
fileId = resource.fileId
path = unref(item)
} else {
fileId = resource.parentFolderId
scrollTo = resource.fileId
path = dirname(unref(item))
}
const driveAliasAndItem = urlJoin(unref(isOcmLink) ? `ocm/` : `public/`, unref(token), path)
const targetLocation: RouteLocationNamedRaw = {
name: 'files-public-link',
query: {
...(configStore.options.openLinksWithDefaultApp && {
openWithDefaultApp: 'true'
}),
...(!!fileId && { fileId }),
...(!!scrollTo && { scrollTo }),
...(unref(details) && { details: unref(details) })
},
params: {
driveAliasAndItem
}
}
router.push(targetLocation)
})
const isLoading = computed<boolean>(() => {
if (unref(errorMessage)) {
return false
}
if (
loadTokenInfoTask.isRunning ||
!loadTokenInfoTask.last ||
isPasswordRequiredTask.isRunning ||
!isPasswordRequiredTask.last
) {
return true
}
if (!unref(isPasswordRequired)) {
return resolvePublicLinkTask.isRunning || !resolvePublicLinkTask.last
}
return false
})
const errorMessage = computed<string>(() => {
if (resolvePublicLinkTask.isError && resolvePublicLinkTask.last.error.statusCode !== 401) {
return resolvePublicLinkTask.last.error.message
}
if (loadTokenInfoTask.isError) {
return loadTokenInfoTask.last.error.message
}
if (isPasswordRequiredTask.isError) {
return isPasswordRequiredTask.last.error.message
}
return null
})
onMounted(async () => {
if (unref(isOcmLink)) {
await resolvePublicLinkTask.perform(false)
return
}
tokenInfo.value = await loadTokenInfoTask.perform(unref(token))
isPasswordRequired.value = await isPasswordRequiredTask.perform()
if (!unref(isPasswordRequired)) {
await resolvePublicLinkTask.perform(false)
}
})
const footerSlogan = computed(() => currentTheme.value.common.slogan)
const passwordFieldLabel = computed(() => {
return $gettext('Enter password for public link')
})
const wrongPasswordMessage = computed(() => {
if (unref(wrongPassword)) {
return $gettext('Incorrect password')
}
return null
})
return {
token,
isPasswordRequired,
password,
wrongPassword,
passwordFieldLabel,
wrongPasswordMessage,
isLoading,
errorMessage,
footerSlogan,
loadTokenInfoTask,
resolvePublicLinkTask,
isPasswordRequiredTask
}
}
})
</script>
<style lang="scss">
.oc-link-resolve {
.oc-card {
background: var(--oc-color-background-highlight);
border-radius: 15px;
}
.oc-text-input-message {
justify-content: center;
}
.oc-card-header h2,
.oc-card-footer p {
margin: 0;
}
}
</style>
| owncloud/web/packages/web-runtime/src/pages/resolvePublicLink.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/pages/resolvePublicLink.vue",
"repo_id": "owncloud",
"token_count": 4673
} | 866 |
import MobileNav from '../../../src/components/MobileNav.vue'
import { defaultPlugins, defaultComponentMocks, mount } from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { NavItem } from 'web-runtime/src/helpers/navItems'
const selectors = {
mobileNavBtn: '#mobile-nav-button',
mobileNavItem: '.mobile-nav-item'
}
const navItems = [
mock<NavItem>({ name: 'nav1', active: true }),
mock<NavItem>({ name: 'nav2', active: false })
]
describe('MobileNav component', () => {
it('renders the active nav item', () => {
const { wrapper } = getWrapper()
expect(wrapper.find(selectors.mobileNavBtn).exists()).toBeTruthy()
expect(wrapper.find(selectors.mobileNavBtn).text()).toEqual(navItems[0].name)
})
it('renders all nav items inside the drop menu', () => {
const { wrapper } = getWrapper()
expect(wrapper.findAll(selectors.mobileNavItem).length).toBe(navItems.length)
})
})
function getWrapper() {
const mocks = {
...defaultComponentMocks()
}
return {
wrapper: mount(MobileNav, {
props: {
navItems
},
global: {
plugins: [...defaultPlugins()],
mocks
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/components/MobileNav.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/MobileNav.spec.ts",
"repo_id": "owncloud",
"token_count": 450
} | 867 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`NotificationBell > should match snapshot 1`] = `
"<button data-v-25fb4be0="" type="button" aria-label="Notifications" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-brand oc-button-brand-raw-inverse" id="oc-notifications-bell">
<!--v-if-->
<!-- @slot Content of the button -->
<oc-icon-stub data-v-25fb4be0="" class="oc-cursor-pointer oc-flex oc-flex-middle" name="notification-3" fill-type="line"></oc-icon-stub>
<!--v-if-->
</button>"
`;
| owncloud/web/packages/web-runtime/tests/unit/components/Topbar/__snapshots__/NotificationBell.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Topbar/__snapshots__/NotificationBell.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 217
} | 868 |
import ResolvePublicLink from '../../../src/pages/resolvePublicLink.vue'
import { defaultPlugins, defaultComponentMocks, shallowMount, nextTicks } from 'web-test-helpers'
import { mockDeep } from 'vitest-mock-extended'
import { CapabilityStore, ClientService } from '@ownclouders/web-pkg'
import { Resource } from '@ownclouders/web-client'
import { authService } from 'web-runtime/src/services/auth'
import { useLoadTokenInfo } from '../../../src/composables/tokenInfo'
import { Task } from 'vue-concurrency'
vi.mock('web-runtime/src/services/auth')
vi.mock('web-runtime/src/composables/tokenInfo')
const selectors = {
cardFooter: '.oc-card-footer',
ocSpinnerStub: 'oc-spinner-stub',
submitButton: '.oc-login-authorize-button'
}
describe('resolvePublicLink', () => {
it('should display the configuration theme general slogan as the login card footer', () => {
const { wrapper } = getWrapper()
const slogan = wrapper.find(selectors.cardFooter)
expect(slogan.html()).toMatchSnapshot()
})
it('should display the loading spinner', () => {
const { wrapper } = getWrapper({ passwordRequired: true })
const loading = wrapper.find(selectors.ocSpinnerStub)
expect(loading.exists()).toBeTruthy()
})
describe('password required form', () => {
it('should display if password is required', async () => {
const { wrapper } = getWrapper({ passwordRequired: true })
await wrapper.vm.isPasswordRequiredTask.last
await nextTicks(4)
expect(wrapper.find('form').html()).toMatchSnapshot()
})
describe('submit button', () => {
it('should be set as disabled if "password" is empty', async () => {
const { wrapper } = getWrapper({ passwordRequired: true })
await wrapper.vm.isPasswordRequiredTask.last
await nextTicks(4)
expect(wrapper.find(selectors.submitButton).attributes().disabled).toBe('true')
})
it('should be set as enabled if "password" is not empty', async () => {
const { wrapper } = getWrapper({ passwordRequired: true })
await wrapper.vm.isPasswordRequiredTask.last
await nextTicks(4)
wrapper.vm.password = 'password'
await wrapper.vm.$nextTick()
expect(wrapper.find(selectors.submitButton).attributes().disabled).toBe('false')
})
it('should resolve the public link on click', async () => {
const resolvePublicLinkSpy = vi.spyOn(authService, 'resolvePublicLink')
const { wrapper } = getWrapper({ passwordRequired: true })
await wrapper.vm.isPasswordRequiredTask.last
await nextTicks(4)
wrapper.vm.password = 'password'
await wrapper.vm.$nextTick()
await wrapper.find(selectors.submitButton).trigger('submit')
await wrapper.vm.resolvePublicLinkTask.last
expect(resolvePublicLinkSpy).toHaveBeenCalled()
})
})
})
})
function getWrapper({ passwordRequired = false } = {}) {
const tokenInfo = { password_protected: passwordRequired } as any
vi.mocked(useLoadTokenInfo).mockReturnValue({
loadTokenInfoTask: mockDeep<Task<any, any>>({
perform: () => tokenInfo,
isRunning: false,
isError: false
})
})
const $clientService = mockDeep<ClientService>()
$clientService.webdav.getFileInfo.mockResolvedValue(mockDeep<Resource>({ driveType: 'public' }))
const mocks = { ...defaultComponentMocks(), $clientService }
const capabilities = {
files_sharing: { federation: { incoming: true, outgoing: true } }
} satisfies Partial<CapabilityStore['capabilities']>
return {
wrapper: shallowMount(ResolvePublicLink, {
global: {
plugins: [...defaultPlugins({ piniaOptions: { capabilityState: { capabilities } } })],
mocks,
provide: mocks
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/pages/resolvePublicLink.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/pages/resolvePublicLink.spec.ts",
"repo_id": "owncloud",
"token_count": 1334
} | 869 |
export const defaultStubs = {
'app-bar': true,
'app-top-bar': true,
'context-actions': true,
'drive-redirect': true,
'generic-space': true,
'generic-trash': true,
'oc-loader': true,
'oc-pagination': true,
'oc-select': true,
'oc-spinner': true,
'oc-textarea': true,
'oc-tiles': false,
'resource-tile': true,
'resource-table': true,
'resource-upload': true,
'router-link': true,
'shared-with-me-section': true,
'file-side-bar': true,
'space-header': true,
'whitespace-context-menu': true,
translate: true
}
| owncloud/web/packages/web-test-helpers/src/mocks/defaultStubs.ts/0 | {
"file_path": "owncloud/web/packages/web-test-helpers/src/mocks/defaultStubs.ts",
"repo_id": "owncloud",
"token_count": 215
} | 870 |
exports.command = function clickElementAt(selector, x, y, mouseButton = 0) {
return this.moveToElement(selector, x, y).mouseButtonClick(mouseButton)
}
| owncloud/web/tests/acceptance/customCommands/clickElementAt.js/0 | {
"file_path": "owncloud/web/tests/acceptance/customCommands/clickElementAt.js",
"repo_id": "owncloud",
"token_count": 49
} | 871 |
Feature: create folders
As a user
I want to create folders
So that I can organise my data structure
Background:
Given user "Alice" has been created with default attributes and without skeleton files in the server
And user "Alice" has logged in using the webUI
And the user has reloaded the current page of the webUI
Scenario: Create a folder with default name
When the user creates a folder with default name using the webUI
Then folder "New folder" should be listed on the webUI
Scenario: Try to create a folder without name
When the user tries to create a folder with the invalid name "" using the webUI
Then the error message 'Folder name cannot be empty' should be displayed on the webUI dialog prompt
And the create folder button should be disabled
Scenario: Try to create a folder with existing name
Given user "Alice" has created folder "simple-folder" in the server
And the user has reloaded the current page of the webUI
When the user tries to create a folder with the invalid name "simple-folder" using the webUI
Then the error message 'simple-folder already exists' should be displayed on the webUI dialog prompt
And the create folder button should be disabled
Scenario: Try to create a folder with invalid name
When the user tries to create a folder with the invalid name "../folder" using the webUI
Then the error message 'Folder name cannot contain "/"' should be displayed on the webUI dialog prompt
And the create folder button should be disabled
Scenario: Try to create a folder with another invalid name
When the user tries to create a folder with the invalid name "folder/subfolder" using the webUI
Then the error message 'Folder name cannot contain "/"' should be displayed on the webUI dialog prompt
And the create folder button should be disabled
Scenario: Create folder with special characters in its name and browse to that folder
When the user creates a folder with the name "?&%0" using the webUI
And the user opens folder "?&%0" using the webUI
And the user reloads the current page of the webUI
Then the files table should be displayed
Scenario: Create a folder in a public share
Given user "Alice" has created folder "simple-empty-folder" in the server
And user "Alice" has shared folder "simple-empty-folder" with link with "read,create" permissions in the server
When the public uses the webUI to access the last public link created by user "Alice" in a new session
And the user creates a folder with the name "top-folder" using the webUI
And the user opens folder "top-folder" using the webUI
Then there should be no resources listed on the webUI
When the user creates a folder with the name "sub-folder" using the webUI
Then folder "sub-folder" should be listed on the webUI
When the user reloads the current page of the webUI
Then folder "sub-folder" should be listed on the webUI
Scenario: Create folders with dot in the name
When the user creates the following folders using the webUI
| folders |
| fo. |
| fo.1 |
| fo...1.. |
| fo.xyz |
Then the following folders should be listed on the webUI
| folders |
| fo. |
| fo.1 |
| fo...1.. |
| fo.xyz |
@skipOnOC10 @issue-5518
Scenario: User creates a folder with .part in the name
When the user creates a folder with the name "fo.part" using the webUI
Then folder "fo.part" should be listed on the webUI
| owncloud/web/tests/acceptance/features/webUICreateFilesFolders/createFolders.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUICreateFilesFolders/createFolders.feature",
"repo_id": "owncloud",
"token_count": 1018
} | 872 |
@disablePreviews
Feature: Sharing files and folders with internal users
As a user
I want to share files and folders with other users
So that those users can access the files and folders
Background:
Given the administrator has set the default folder for received shares to "Shares" in the server
And these users have been created with default attributes and without skeleton files in the server:
| username |
| Alice |
| Brian |
And user "Alice" has created folder "simple-folder" in the server
@issue-4310
Scenario: sharing indicator for user shares stays up to date
Given user "Carol" has been created with default attributes and without skeleton files in the server
And user "David" has been created with default attributes and without skeleton files in the server
And user "Alice" has uploaded file "testavatar.png" to "simple-folder/testimage.png" in the server
When user "Alice" has logged in using the webUI
Then the following resources should not have share indicators on the webUI
| simple-folder |
When the user shares folder "simple-folder" with user "Brian Murphy" as "Viewer" using the webUI
And the user shares folder "simple-folder" with user "Carol King" as "Viewer" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| simple-folder | user-direct |
When the user opens folder "simple-folder" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| testimage.png | user-indirect |
When the user shares file "testimage.png" with user "David Lopez" as "Viewer" using the webUI
# the indicator changes from user-indirect to user-direct to show the direct share
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| testimage.png | user-direct |
# removing the last collaborator reverts the indicator to user-indirect
When the user opens the share dialog for file "testimage.png" using the webUI
And the user deletes "David Lopez" as collaborator for the current file using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| testimage.png | user-indirect |
When the user opens folder "" directly on the webUI
And the user opens the share dialog for folder "simple-folder" using the webUI
And the user deletes "Carol King" as collaborator for the current file using the webUI
# because there is still another share left, the indicator stays
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| simple-folder | user-direct |
# deleting the last collaborator removes the indicator
When the user opens the share dialog for folder "simple-folder" using the webUI
And the user deletes "Brian Murphy" as collaborator for the current file using the webUI
Then the following resources should not have share indicators on the webUI
| simple-folder |
@issue-4167
Scenario: sharing indicator of items inside a shared folder two levels down
Given user "Alice" has created folder "/simple-folder/simple-empty-folder" in the server
And user "Alice" has created folder "/simple-folder/simple-empty-folder/new-folder" in the server
And user "Alice" has uploaded file with content "test" to "/simple-folder/simple-empty-folder/lorem.txt" in the server
And user "Alice" has shared folder "simple-folder" with user "Brian" in the server
When user "Alice" has logged in using the webUI
And the user opens the share dialog for folder "simple-folder" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| simple-folder | user-direct |
When the user opens folder "simple-folder" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| simple-empty-folder | user-indirect |
When the user opens folder "simple-empty-folder" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| new-folder | user-indirect |
| lorem.txt | user-indirect |
@issue-2060 @issue-4172
Scenario: no sharing indicator of items inside a not shared folder
Given user "Brian" has created folder "simple-folder" in the server
And user "Brian" has created folder "simple-folder/simple-empty-folder" in the server
And user "Brian" has created file "/simple-folder/lorem.txt" in the server
And user "Alice" has created file "textfile0.txt" in the server
And user "Alice" has shared file "/textfile0.txt" with user "Brian" in the server
When user "Brian" has logged in using the webUI
Then the following resources should not have share indicators on the webUI
| simple-folder |
When the user opens folder "simple-folder" using the webUI
Then the following resources should not have share indicators on the webUI
| simple-empty-folder |
| lorem.txt |
@issue-2060
Scenario: sharing indicator for file uploaded inside a shared folder
Given user "Alice" has shared folder "/simple-folder" with user "Brian" in the server
And user "Alice" has logged in using the webUI
When the user opens folder "simple-folder" using the webUI
And the user uploads file "new-lorem.txt" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| new-lorem.txt | user-indirect |
@issue-2060
Scenario: sharing indicator for folder created inside a shared folder
Given user "Alice" has shared folder "/simple-folder" with user "Brian" in the server
And user "Alice" has logged in using the webUI
When the user opens folder "simple-folder" using the webUI
And the user creates a folder with the name "sub-folder" using the webUI
Then the following resources should have share indicators on the webUI
| fileName | expectedIndicators |
| sub-folder | user-indirect |
| owncloud/web/tests/acceptance/features/webUISharingInternalUsersSharingIndicator/shareWithUsers.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUISharingInternalUsersSharingIndicator/shareWithUsers.feature",
"repo_id": "owncloud",
"token_count": 1919
} | 873 |
const _ = require('lodash')
const { client } = require('nightwatch-api')
const { passwords } = require('./userSettings')
/**
* Gets the password for the un-initialized users and replaces the password accordingly
*
* @param {string} input
* @returns {string}
*/
exports.replaceInlineCode = function (input) {
const codes = {
...passwords,
remote_backend_url: client.globals.remote_backend_url,
backend_url: client.globals.backend_url
}
const interpolate = /%([\s\S]+?)%/g
const compiled = _.template(input, { interpolate })
return compiled(codes)
}
exports.replaceInlineTable = function (dataTable) {
dataTable.raw().forEach((row) => {
row.forEach((cell, index, arr) => {
arr[index] = exports.replaceInlineCode(cell)
})
})
return dataTable
}
| owncloud/web/tests/acceptance/helpers/codify.js/0 | {
"file_path": "owncloud/web/tests/acceptance/helpers/codify.js",
"repo_id": "owncloud",
"token_count": 273
} | 874 |
/* eslint-disable no-unused-expressions */
const _ = require('lodash')
const timeoutHelper = require('../../helpers/timeoutHelper')
const xpathHelper = require('../../helpers/xpath')
const util = require('util')
module.exports = {
commands: {
isThumbnailVisible: function (previewSize, item) {
if (previewSize === 'big') {
return this.waitForElementVisible('@sidebar').waitForElementVisible(
'@fileInfoIconBigPreview'
)
} else {
const panelName = item === 'people' || item === 'links' ? 'sharing' : item
return this.waitForElementVisible('@sidebar').waitForElementVisible(
util.format(this.elements.fileInfoIconSmallPreview.selector, panelName)
)
}
},
closeSidebarIfOpen: async function (timeout = 300) {
if (!(await this.isSideBarOpen(false))) {
return this.api.page.FilesPageElement.filesList()
}
try {
await this.click({
selector: '@sidebarCloseBtn',
timeout: timeoutHelper.parseTimeout(timeout)
})
} catch (e) {
// do nothing
}
return this.api.page.FilesPageElement.filesList()
},
isSideBarOpen: async function (expectedToOpen = true) {
const element = this.elements.sidebar
let isVisible = false
const timeout = expectedToOpen
? this.api.globals.waitForConditionTimeout
: this.api.globals.waitForNegativeConditionTimeout
await this.isVisible(
{
locateStrategy: element.locateStrategy,
selector: element.selector,
timeout: timeoutHelper.parseTimeout(timeout),
suppressNotFoundErrors: !expectedToOpen
},
(result) => {
isVisible = result.value === true
}
)
return isVisible
},
isSideBarOpenForResource: async function (
resource,
elementType = 'any',
expectedToOpen = true
) {
if (!(await this.isSideBarOpen(expectedToOpen))) {
return false
}
const timeout = expectedToOpen
? this.api.globals.waitForConditionTimeout
: this.api.globals.waitForNegativeConditionTimeout
const selector = this.getResourceInfoSelector(resource, elementType)
let resourceInfoVisible = false
await this.isAnyElementVisible(
{
locateStrategy: 'xpath',
selector,
timeout: timeoutHelper.parseTimeout(timeout),
suppressNotFoundErrors: !expectedToOpen
},
(result) => (resourceInfoVisible = result.isVisible)
)
return resourceInfoVisible
},
getResourceInfoSelector: function (resource, elementType = 'any') {
const name = xpathHelper.buildXpathLiteral(resource)
const path = xpathHelper.buildXpathLiteral('/' + resource)
if (elementType === 'any') {
return util.format(this.elements.fileInfoResourceNameAnyType.selector, name, path)
}
const type = xpathHelper.buildXpathLiteral(elementType)
return util.format(this.elements.fileInfoResourceName.selector, name, path, type)
},
activatePanel: async function (item) {
const panelName = item === 'people' || item === 'links' ? 'collaborators' : item
const active = await this.isPanelActive(item, false)
if (!active) {
let backBtnVisible = false
await this.isVisible(
{
selector: '@sidebarBackBtn',
timeout: this.api.globals.waitForNegativeConditionTimeout,
suppressNotFoundErrors: true
},
(result) => {
backBtnVisible = result.value === true
}
)
if (backBtnVisible) {
await this.click({
selector: '@sidebarBackBtn'
})
await this.waitForAnimationToFinish() // wait for sliding animation to the root panel
}
const menuItemElement = this.elements[panelName + 'PanelMenuItem']
await this.click({
locateStrategy: menuItemElement.locateStrategy,
selector: menuItemElement.selector
})
.waitForAjaxCallsToStartAndFinish()
.waitForAnimationToFinish() // wait for sliding animation to the sub panel
}
const panelElement = this.elements[panelName + 'Panel']
return await this.waitForElementPresent(panelElement.locateStrategy, panelElement.selector)
},
getActionsMenuItemsExceptDefaults: async function () {
const defaultItems = ['add to favorites', 'copy', 'cut', 'rename', 'delete']
const items = []
let elements
await this.api.elements('@panelActionsItems', function (result) {
elements = result.value
})
for (const { ELEMENT } of elements) {
await this.api.elementIdText(ELEMENT, function (result) {
let notDefault = true
for (const item of defaultItems) {
if (_.isEqual(item, result.value.toLowerCase())) {
notDefault = false
break
}
}
notDefault ? items.push(result.value.toLowerCase()) : null
})
}
return items
},
isPanelActive: async function (panelName, expectToBeActive = true) {
panelName = panelName === 'people' ? 'collaborators' : panelName
const element = this.elements[panelName + 'Panel']
let isVisible = false
const timeout = expectToBeActive
? this.api.globals.waitForConditionTimeout
: this.api.globals.waitForNegativeConditionTimeout
await this.isVisible(
{
locateStrategy: element.locateStrategy,
selector: element.selector,
timeout: timeoutHelper.parseTimeout(timeout),
suppressNotFoundErrors: !expectToBeActive
},
(result) => {
isVisible = result.value === true
}
)
return isVisible
},
/**
* checks if it's possible to navigate into the given panel
*
* @param {string} panelName
* @param {number} timeout
* @returns {Promise<boolean>}
*/
isPanelSelectable: async function (panelName, expectToBeSelectable = true) {
panelName = panelName === 'people' ? 'collaborators' : panelName
const element = this.elements[panelName + 'PanelMenuItem']
let isVisible = false
const timeout = expectToBeSelectable
? this.api.globals.waitForConditionTimeout
: this.api.globals.waitForNegativeConditionTimeout
await this.isVisible(
{
locateStrategy: element.locateStrategy,
selector: element.selector,
timeout: timeoutHelper.parseTimeout(timeout),
suppressNotFoundErrors: !expectToBeSelectable
},
(result) => {
isVisible = result.value === true
}
)
return isVisible
},
isSharingPanelSelectable: async function (expectToBeSelectable = true) {
return await this.isPanelSelectable('people', expectToBeSelectable)
},
copyPrivateLink: function () {
return this.waitForElementVisible('@privateLinkURLCopyButton').click(
'@privateLinkURLCopyButton'
)
}
},
elements: {
sidebar: {
selector: '//*[@id="app-sidebar"]',
locateStrategy: 'xpath'
},
fileInfoIconBigPreview: {
selector: '#oc-file-details-sidebar .details-icon'
},
fileInfoIconSmallPreview: {
selector: '#sidebar-panel-%s .file_info__icon'
},
fileInfoResourceNameAnyType: {
selector: `//div[contains(@id, "app-sidebar")]//span[contains(@class, "oc-resource-name") and (@data-test-resource-name=%s or @data-test-resource-path=%s)]`,
locateStrategy: 'xpath'
},
fileInfoResourceName: {
selector: `//div[contains(@id, "app-sidebar")]//span[contains(@class, "oc-resource-name") and (@data-test-resource-name=%s or @data-test-resource-path=%s) and @data-test-resource-type=%s]`,
locateStrategy: 'xpath'
},
sidebarCloseBtn: {
selector:
'//div[contains(@id, "app-sidebar")]//*[contains(@class, "is-active-")]//button[contains(@class, "header__close")]',
locateStrategy: 'xpath'
},
sidebarBackBtn: {
selector:
'//div[contains(@id, "app-sidebar")]//*[contains(@class, "is-active-sub-panel")]//button[contains(@class, "header__back")]',
locateStrategy: 'xpath'
},
panelActionsItems: {
selector:
'//ul[@id="oc-files-actions-sidebar"]//span[@class="oc-files-context-action-label"]',
locateStrategy: 'xpath'
},
panelSelectButtons: {
selector:
'//div[contains(@id, "app-sidebar")]//div[contains(@class, "sidebar-panel__navigation")]/button',
locateStrategy: 'xpath'
},
collaboratorsPanel: {
selector:
'//*[@id="sidebar-panel-sharing"]//*[contains(@class, "sidebar-panel__body-content")]',
locateStrategy: 'xpath'
},
collaboratorsPanelMenuItem: {
selector: '//button[@id="sidebar-panel-sharing-select"]',
locateStrategy: 'xpath'
},
linksPanel: {
selector: '#oc-files-file-link'
},
linksPanelMenuItem: {
selector: '//button[@id="sidebar-panel-links-select"]',
locateStrategy: 'xpath'
},
actionsPanel: {
selector:
'//*[@id="sidebar-panel-actions"]//*[contains(@class, "sidebar-panel__body-content")]',
locateStrategy: 'xpath'
},
actionsPanelMenuItem: {
selector: '//button[@id="sidebar-panel-actions-select"]',
locateStrategy: 'xpath'
},
detailsPanel: {
selector:
'//*[@id="sidebar-panel-details"]//*[contains(@class, "sidebar-panel__body-content")]',
locateStrategy: 'xpath'
},
detailsPanelMenuItem: {
selector: '//button[@id="sidebar-panel-details-select"]',
locateStrategy: 'xpath'
},
privateLinkURLCopyButton: {
selector: '.oc-files-private-link-copy-url'
},
versionsPanel: {
selector:
'//*[@id="sidebar-panel-versions"]//*[contains(@class, "sidebar-panel__body-content")]',
locateStrategy: 'xpath'
},
versionsPanelMenuItem: {
selector: '//button[@id="sidebar-panel-versions-select"]',
locateStrategy: 'xpath'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/FilesPageElement/appSideBar.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/FilesPageElement/appSideBar.js",
"repo_id": "owncloud",
"token_count": 4314
} | 875 |
const { join } = require('../helpers/path')
module.exports = {
url: function () {
return join(this.api.launchUrl, '/login')
},
elements: {
body: 'body',
authenticateButton: {
selector: "//button//span[text()='Login' or text()='Log in']",
locateStrategy: 'xpath'
}
},
commands: [
{
authenticate: function () {
return this.waitForElementVisible('@authenticateButton').click('@authenticateButton')
},
waitForPage: function () {
return this.waitForElementVisible('@authenticateButton')
}
}
]
}
| owncloud/web/tests/acceptance/pageObjects/loginPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/loginPage.js",
"repo_id": "owncloud",
"token_count": 231
} | 876 |
const { client } = require('nightwatch-api')
const { When } = require('@cucumber/cucumber')
When('the user browses to the account page', function () {
return client.page.accountPage().navigateAndWaitTillLoaded()
})
| owncloud/web/tests/acceptance/stepDefinitions/accountContext.js/0 | {
"file_path": "owncloud/web/tests/acceptance/stepDefinitions/accountContext.js",
"repo_id": "owncloud",
"token_count": 67
} | 877 |
#!/bin/bash
source .drone.env
ocis_cache=$(mc find s3/$CACHE_BUCKET/ocis-build/$OCIS_COMMITID/ocis 2>&1 | grep 'Object does not exist')
if [[ "$ocis_cache" != "" ]]
then
echo "$OCIS_COMMITID doesn't exist"
exit 0
fi
exit 78
| owncloud/web/tests/drone/check-oCIS-cache.sh/0 | {
"file_path": "owncloud/web/tests/drone/check-oCIS-cache.sh",
"repo_id": "owncloud",
"token_count": 104
} | 878 |
Feature: users management
Scenario: user login can be managed in the admin settings
Given "Admin" logs in
And "Admin" creates following user using API
| id |
| Alice |
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the users management page
And "Admin" forbids the login for the following user "Alice" using the sidebar panel
Then "Alice" fails to log in
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the users management page
And "Admin" allows the login for the following user "Alice" using the sidebar panel
And "Admin" logs out
Then "Alice" logs in
And "Alice" logs out
Scenario: admin user can change personal quotas for users
Given "Admin" logs in
And "Admin" creates following users using API
| id |
| Alice |
| Brian |
And "Alice" logs in
And "Brian" logs in
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the users management page
When "Admin" changes the quota of the user "Alice" to "500" using the sidebar panel
Then "Alice" should have quota "500"
When "Admin" changes the quota to "20" for users using the batch action
| id |
| Alice |
| Brian |
Then "Alice" should have quota "20"
And "Brian" should have quota "20"
And "Brian" logs out
And "Alice" logs out
And "Admin" logs out
Scenario: user group assignments can be handled via batch actions
Given "Admin" logs in
And "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
And "Admin" creates following groups using API
| id |
| sales |
| finance |
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the users management page
And "Admin" adds the following users to the groups "sales,finance" using the batch actions
| user |
| Alice |
| Brian |
| Carol |
When "Admin" sets the following filter
| filter | values |
| groups | sales department,finance department |
Then "Admin" should see the following users
| user |
| Alice |
| Brian |
| Carol |
And "Admin" removes the following users from the groups "sales,finance" using the batch actions
| user |
| Alice |
| Brian |
When "Admin" reloads the page
Then "Admin" should see the following users
| user |
| Carol |
And "Admin" should not see the following users
| user |
| Alice |
| Brian |
And "Admin" logs out
Scenario: edit user
Given "Admin" logs in
And "Admin" creates following user using API
| id |
| Alice |
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the users management page
When "Admin" changes userName to "anna" for user "Alice" using the sidebar panel
And "Admin" changes displayName to "Anna Murphy" for user "anna" using the sidebar panel
And "Admin" changes email to "anna@example.org" for user "anna" using the sidebar panel
And "Admin" changes password to "password" for user "anna" using the sidebar panel
And "Admin" changes role to "Space Admin" for user "anna" using the sidebar panel
And "Admin" logs out
When "anna" logs in
Then "anna" should have self info:
| key | value |
| username | anna |
| displayname | Anna Murphy |
| email | anna@example.org |
And "anna" logs out
Scenario: assign user to groups
Given "Admin" logs in
And "Admin" creates following user using API
| id |
| Alice |
And "Admin" creates following groups using API
| id |
| sales |
| finance |
| security |
And "Admin" adds user to the group using API
| user | group |
| Alice | sales |
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the users management page
When "Admin" adds the user "Alice" to the groups "finance,security" using the sidebar panel
And "Admin" removes the user "Alice" from the group "sales" using the sidebar panel
And "Admin" logs out
When "Alice" logs in
Then "Alice" should have self info:
| key | value |
| groups | finance department, security department |
And "Alice" logs out
Scenario: delete user
Given "Admin" logs in
And "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
| David |
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the users management page
And "Admin" changes role to "Space Admin" for user "David" using the sidebar panel
When "Admin" sets the following filter
| filter | values |
| roles | User,Admin |
Then "Admin" should see the following users
| user |
| Alice |
| Brian |
| Carol |
And "Admin" should not see the following users
| user |
| David |
When "Admin" deletes the following users using the batch actions
| id |
| Alice |
| Brian |
And "Admin" deletes the following user using the context menu
| user |
| Carol |
Then "Admin" should not see the following users
| user |
| Alice |
| Brian |
| Carol |
And "Admin" logs out
Scenario: admin creates user
When "Admin" logs in
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the users management page
And "Admin" creates the following user
| name | displayname | email | password |
| max | Max Testing | maxtesting@owncloud.com | 12345678 |
And "Admin" logs out
When "Max" logs in
Then "Max" should have self info:
| key | value |
| username | max |
| displayname | Max Testing |
| email | maxtesting@owncloud.com |
And "Max" logs out
Scenario: edit panel can be opened via quick action and context menu
Given "Admin" logs in
And "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
And "Admin" opens the "admin-settings" app
And "Admin" navigates to the users management page
When "Admin" opens the edit panel of user "Brian" using the quick action
Then "Admin" should see the edit panel
When "Admin" opens the edit panel of user "Brian" using the context menu
Then "Admin" should see the edit panel
And "Admin" logs out
| owncloud/web/tests/e2e/cucumber/features/admin-settings/users.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/admin-settings/users.feature",
"repo_id": "owncloud",
"token_count": 2524
} | 879 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.