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="M18 20.002V15h2v7.002H4V15h2v5.002h12zM7.5 18v-2h9v2h-9zm.077-4.38l.347-1.97 8.864 1.563-.348 1.97-8.863-1.563zm1.634-5.504l1-1.732 7.794 4.5-1 1.732-7.794-4.5zm3.417-4.613l1.532-1.286 5.785 6.895-1.532 1.285-5.785-6.894z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/stack-overflow-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/stack-overflow-line.svg", "repo_id": "owncloud", "token_count": 245 }
782
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M8 8v8h8V8H8zM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V7z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/stop-mini-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/stop-mini-line.svg", "repo_id": "owncloud", "token_count": 148 }
783
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M21 18a2 2 0 0 1-2 2h-1.8l1.8 1.5v.5H5v-.5L6.8 20H5a2 2 0 0 1-2-2V7a4 4 0 0 1 4-4h6v8h8v7zm-2-5H5v5h14v-5zM7.5 14a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3zm9 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3zM11 5H7a2 2 0 0 0-1.995 1.85L5 7v4h6V5zm7.5-4a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9zm0 5.167c-.491 0-.94.177-1.289.47l-.125.115L18.5 8.167l1.413-1.416a1.994 1.994 0 0 0-1.413-.584zm0-2.667a4.65 4.65 0 0 0-3.128 1.203l-.173.165.944.942a3.323 3.323 0 0 1 2.357-.977 3.32 3.32 0 0 1 2.201.83l.156.147.943-.943A4.652 4.652 0 0 0 18.5 3.5z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/subway-wifi-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/subway-wifi-line.svg", "repo_id": "owncloud", "token_count": 437 }
784
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0H24V24H0z"/> <path d="M12.485 3.121l7.758 1.94c.445.11.757.51.757.97V7h1c1.1 0 2 .9 2 2v3c0 1.657-1.343 3-3 3h-.421c-.535 1.35-1.552 2.486-2.896 3.158l-4.789 2.395c-.563.281-1.225.281-1.788 0l-4.79-2.395C4.974 17.486 3.957 16.35 3.422 15H3c-1.657 0-3-1.343-3-3V9c0-1.105.895-2 2-2h1v-.97c0-.458.312-.858.757-.97l7.758-1.939c.318-.08.652-.08.97 0zM12 5.061l-7 1.75v5.98c0 1.516.856 2.9 2.211 3.579L12 18.764l4.789-2.394C18.144 15.692 19 14.307 19 12.792v-5.98l-7-1.75zM3 9H2v3c0 .552.448 1 1 1V9zm19 0h-1v4c.552 0 1-.448 1-1V9z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/surgical-mask-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/surgical-mask-line.svg", "repo_id": "owncloud", "token_count": 409 }
785
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M8 10.255V5a4 4 0 1 1 8 0v5.255a7 7 0 1 1-8 0zm3 1.871A4.002 4.002 0 0 0 12 20a4 4 0 0 0 1-7.874V5h-2v7.126z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/temp-hot-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/temp-hot-fill.svg", "repo_id": "owncloud", "token_count": 157 }
786
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M6.382 5.968A8.962 8.962 0 0 1 12 4c2.125 0 4.078.736 5.618 1.968l1.453-1.453 1.414 1.414-1.453 1.453a9 9 0 1 1-14.064 0L3.515 5.93l1.414-1.414 1.453 1.453zM13 12V7.495L8 14h3v4.5l5-6.5h-3zM8 1h8v2H8V1z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/timer-flash-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/timer-flash-fill.svg", "repo_id": "owncloud", "token_count": 219 }
787
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M17.2 20l1.8 1.5v.5H5v-.5L6.8 20H5a2 2 0 0 1-2-2V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4v11a2 2 0 0 1-2 2h-1.8zM7 5a2 2 0 0 0-2 2v11h14V7a2 2 0 0 0-2-2H7zm5 12a2 2 0 1 1 0-4 2 2 0 0 1 0 4zM6 7h12v4H6V7z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/train-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/train-line.svg", "repo_id": "owncloud", "token_count": 226 }
788
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M8 8c1.075 0 3.497-.673 3.497-4.5V2h1.5v6H18v2h-5.003v2.91C13 15.39 13 16.595 13 17c-.002 2.208 1.615 3.4 4.785 3.4V22h-2.242c-2.402.002-4.546-2.035-4.546-4.545V10H7V8h1z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/tumblr-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/tumblr-line.svg", "repo_id": "owncloud", "token_count": 197 }
789
<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="M13 2.05c5.053.501 9 4.765 9 9.95v1h-9v6a2 2 0 1 0 4 0v-1h2v1a4 4 0 1 1-8 0v-6H2v-1c0-5.185 3.947-9.449 9-9.95V2a1 1 0 0 1 2 0v.05zM19.938 11a8.001 8.001 0 0 0-15.876 0h15.876z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/umbrella-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/umbrella-line.svg", "repo_id": "owncloud", "token_count": 215 }
790
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M11 14.062V20h2v-5.938c3.946.492 7 3.858 7 7.938H4a8.001 8.001 0 0 1 7-7.938zM12 13c-3.315 0-6-2.685-6-6s2.685-6 6-6 6 2.685 6 6-2.685 6-6 6z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/user-2-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/user-2-fill.svg", "repo_id": "owncloud", "token_count": 183 }
791
<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="M17.841 15.659l.176.177.178-.177a2.25 2.25 0 0 1 3.182 3.182l-3.36 3.359-3.358-3.359a2.25 2.25 0 0 1 3.182-3.182zM12 14v2a6 6 0 0 0-6 6H4a8 8 0 0 1 7.75-7.996L12 14zm0-13c3.315 0 6 2.685 6 6a5.998 5.998 0 0 1-5.775 5.996L12 13c-3.315 0-6-2.685-6-6a5.998 5.998 0 0 1 5.775-5.996L12 1zm0 2C9.79 3 8 4.79 8 7s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/user-heart-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/user-heart-line.svg", "repo_id": "owncloud", "token_count": 307 }
792
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zM7 12a5 5 0 0 0 10 0h-2a3 3 0 0 1-6 0H7z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/user-smile-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/user-smile-fill.svg", "repo_id": "owncloud", "token_count": 151 }
793
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M19.39 3.161l1.413 1.414-2.475 2.475 2.475 2.475L18.328 12l2.475 2.476-2.475 2.475 2.475 2.475-1.414 1.414-3.889-3.89 2.475-2.474L15.5 12l2.475-2.475L15.5 7.05l3.89-3.889zm-6.503.578a.5.5 0 0 1 .113.316v15.89a.5.5 0 0 1-.817.387L6.89 15.999 3 16a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1h3.889l5.294-4.332a.5.5 0 0 1 .704.07z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/volume-vibrate-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/volume-vibrate-fill.svg", "repo_id": "owncloud", "token_count": 282 }
794
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M20.444 3.5L13.81 14.99 17.857 22h-2.31l-4.045-7.009H11.5L18.134 3.5h2.31zM8.31 7l2.422 4.196-.002.001L7.67 16.5H5.361l3.06-5.305L6.002 7H8.31z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/xing-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/xing-line.svg", "repo_id": "owncloud", "token_count": 182 }
795
export const extractInitials = (userName) => { return userName .split(/[ -]/) .map((part) => part.replace(/[^\p{L}\p{Nd}]/giu, '')) .filter(Boolean) .map((part) => part.charAt(0)) .slice(0, 3) .join('') .toUpperCase() }
owncloud/web/packages/design-system/src/components/OcAvatar/extractInitials.ts/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcAvatar/extractInitials.ts", "repo_id": "owncloud", "token_count": 123 }
796
import { RouteLocationRaw } from 'vue-router' export interface BreadcrumbItem { id?: string text: string to?: RouteLocationRaw allowContextActions?: boolean onClick?: () => void isTruncationPlaceholder?: boolean isStaticNav?: boolean }
owncloud/web/packages/design-system/src/components/OcBreadcrumb/types.ts/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcBreadcrumb/types.ts", "repo_id": "owncloud", "token_count": 76 }
797
<template> <div class="oc-filter-chip oc-flex" :class="{ 'oc-filter-chip-toggle': isToggle, 'oc-filter-chip-raw': raw }" > <oc-button :id="id" class="oc-filter-chip-button oc-pill" :class="{ 'oc-filter-chip-button-selected': filterActive }" appearance="raw" @click="isToggle ? $emit('toggleFilter') : false" > <oc-icon :class="filterActive ? 'oc-filter-check-icon-active' : 'oc-filter-check-icon-inactive'" name="check" size="small" color="var(--oc-color-text-inverse)" /> <span class="oc-text-truncate oc-filter-chip-label" v-text="!!selectedItemNames.length ? selectedItemNames[0] : filterLabel" /> <span v-if="selectedItemNames.length > 1" v-text="` +${selectedItemNames.length - 1}`" /> <oc-icon v-if="!filterActive && !isToggle" name="arrow-down-s" size="small" /> </oc-button> <oc-drop v-if="!isToggle" :toggle="'#' + id" class="oc-filter-chip-drop" mode="click" padding-size="small" :close-on-click="closeOnClick" @hide-drop="$emit('hideDrop')" @show-drop="$emit('showDrop')" > <slot /> </oc-drop> <oc-button v-if="filterActive" v-oc-tooltip="$gettext('Clear filter')" class="oc-filter-chip-clear oc-px-xs" appearance="raw" @click="$emit('clearFilter')" > <oc-icon name="close" size="small" color="var(--oc-color-text-inverse)" /> </oc-button> </div> </template> <script lang="ts"> import { computed, defineComponent } from 'vue' import uniqueId from '../../utils/uniqueId' export default defineComponent({ name: 'OcFilterChip', status: 'ready', release: '15.0.0', props: { id: { type: String, required: false, default: () => uniqueId('oc-filter-chip-') }, /** * Label which is displayed when no items are selected. */ filterLabel: { type: String, required: true }, /** * An array of selected item names. It is being ignored when `isToggle` is set to `true`. */ selectedItemNames: { type: Array, required: false, default: () => [] }, /** * Display the filter chip as a on/off toggle. */ isToggle: { type: Boolean, default: false }, /** * Whether the toggle filter is active. It only has an effect if `isToggle` is set to `true`. */ isToggleActive: { type: Boolean, default: false }, /** * Whether the filter chip should be displayed as a raw button. */ raw: { type: Boolean, default: false }, /** * Whether the drop should be closed when clicking on an item. */ closeOnClick: { type: Boolean, default: false } }, emits: ['clearFilter', 'hideDrop', 'showDrop', 'toggleFilter'], setup(props) { const filterActive = computed(() => { if (props.isToggle) { return props.isToggleActive } return !!props.selectedItemNames.length }) return { filterActive } } }) </script> <style lang="scss"> .oc-filter-chip { &-button.oc-pill { align-items: center; background-color: var(--oc-color-background-default) !important; color: var(--oc-color-text-muted) !important; border: 1px solid var(--oc-color-text-muted); box-sizing: border-box; display: inline-flex; gap: var(--oc-space-xsmall); text-decoration: none; font-size: var(--oc-font-size-xsmall); line-height: 1rem; max-width: 150px; padding: var(--oc-space-xsmall) var(--oc-space-small) !important; height: 100%; } &-button-selected.oc-pill, &-button-selected.oc-pill:hover { background-color: var(--oc-color-swatch-primary-default) !important; color: var(--oc-color-text-inverse) !important; border-top-left-radius: 99px !important; border-bottom-left-radius: 99px !important; border-top-right-radius: 0px !important; border-bottom-right-radius: 0px !important; border: 0; } &-clear, &-clear:hover { background-color: var(--oc-color-swatch-primary-default) !important; color: var(--oc-color-text-inverse) !important; border-top-left-radius: 0px !important; border-bottom-left-radius: 0px !important; border-top-right-radius: 99px !important; border-bottom-right-radius: 99px !important; } &-clear:not(.oc-filter-chip-toggle .oc-filter-chip-clear), &-clear:hover:not(.oc-filter-chip-toggle .oc-filter-chip-clear) { margin-left: 1px; } } .oc-filter-chip-raw { .oc-filter-chip-button { background-color: transparent !important; border: none !important; } } .oc-filter-check-icon-active { transition: all 0.25s ease-in; transform: scale(1) !important; } .oc-filter-check-icon-inactive { transition: all 0.25 ease-in; transform: scale(0) !important; width: 0px !important; } </style>
owncloud/web/packages/design-system/src/components/OcFilterChip/OcFilterChip.vue/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcFilterChip/OcFilterChip.vue", "repo_id": "owncloud", "token_count": 2087 }
798
import { shallowMount } from 'web-test-helpers' import Modal from './OcModal.vue' const defaultProps = { title: 'Example title', message: 'Example message' } const inputProps = { title: 'Create new folder', hasInput: true, inputValue: 'New folder', inputLabel: 'Folder name' } describe('OcModal', () => { it('displays correct variation', () => { const wrapper = shallowMount(Modal, { props: { ...defaultProps, variation: 'danger' }, global: { renderStubDefaultSlot: true } }) expect(wrapper.findAll('.oc-modal-danger').length).toBe(1) }) it('hides icon if not specified', () => { const wrapper = shallowMount(Modal, { global: { renderStubDefaultSlot: true }, props: { ...defaultProps } }) expect(wrapper.findAll('.oc-icon').length).toBe(0) expect(wrapper.html()).toMatchSnapshot() }) it('overrides props message with slot', () => { const wrapper = shallowMount(Modal, { global: { renderStubDefaultSlot: true }, props: { ...defaultProps }, slots: { content: '<p>Slot message</p>' } }) expect(wrapper.find('.oc-modal-body-message > p').text()).toMatch('Slot message') expect(wrapper.html()).toMatchSnapshot() }) it('matches snapshot', () => { const wrapper = shallowMount(Modal, { global: { renderStubDefaultSlot: true }, props: { ...defaultProps, icon: 'info' } }) expect(wrapper.html()).toMatchSnapshot() }) it('displays input', () => { const wrapper = shallowMount(Modal, { global: { renderStubDefaultSlot: true }, props: inputProps }) expect(wrapper.findAll('.oc-modal-body-input').length).toBe(1) expect(wrapper.html()).toMatchSnapshot() }) })
owncloud/web/packages/design-system/src/components/OcModal/OcModal.spec.ts/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcModal/OcModal.spec.ts", "repo_id": "owncloud", "token_count": 732 }
799
<template> <span> <input :id="id" v-model="model" type="radio" name="radio" :class="classes" :aria-checked="option === modelValue" :value="option" :disabled="disabled" /> <label :for="id" :class="labelClasses" v-text="label" /> </span> </template> <script lang="ts"> import { defineComponent } from 'vue' import { getSizeClass } from '../../utils/sizeClasses' import uniqueId from '../../utils/uniqueId' /** * The radio element. Can be grouped to give the user to choose between different options. */ export default defineComponent({ name: 'OcRadio', status: 'ready', release: '1.0.0', props: { /** * Id for the radio. If it's empty, a generated one will be used. */ id: { type: String, required: false, default: () => uniqueId('oc-radio-') }, /** * Disables the radio button */ disabled: { type: Boolean, default: false }, /** * The model of the radio button or radio button group. It determines, based on the option this radio button * represents, whether or not this radio button is checked. Provide it as value or bind it with v-model. * * When used in a radio group, provide a variable that tracks which of the `option` values of the group is checked. * * Can be any type. **/ // eslint-disable-next-line vue/require-prop-types modelValue: { type: [String, Number, Boolean, Object], required: false, default: false }, /** * The value of this radio button. Can be omitted if the radio button is not used in a group. * * Can be of any type. */ // eslint-disable-next-line vue/require-prop-types option: { required: false, default: null }, /** * Label of the Radio. * * Always required for aria-label property. If you want to hide the label, use `hideLabel` property. **/ label: { type: String, required: true, default: null }, /** * Is the label of the Radio visually hidden? **/ hideLabel: { type: Boolean, required: false, default: false }, /** * Size of the Radio. Valid values are `small`, `medium` and `large`. * If not specified, defaults to `medium` */ size: { type: String, required: false, default: 'medium', validator: (size: string) => ['small', 'medium', 'large'].includes(size) } }, emits: ['update:modelValue'], computed: { model: { get() { return this.modelValue }, set(value) { this.$emit('update:modelValue', value) } }, classes() { return ['oc-radio', 'oc-radio-' + getSizeClass(this.size)] }, labelClasses() { return { 'oc-invisible-sr': this.hideLabel, 'oc-cursor-pointer': !this.disabled } } } }) </script> <style lang="scss"> @mixin oc-form-check-size($factor) { height: $oc-size-form-check-default * $factor; width: $oc-size-form-check-default * $factor; } .oc-radio { -webkit-appearance: none; -moz-appearance: none; border: 1px solid var(--oc-color-swatch-brand-default); border-radius: 50%; box-sizing: border-box; background-color: var(--oc-color-input-bg); background-position: 50% 50%; background-repeat: no-repeat; display: inline-block; margin: 0; overflow: hidden; transition: 0.2s ease-in-out; transition-property: background-color, border; vertical-align: middle; width: 1rem; &:not(:disabled) { cursor: pointer; } &:checked { background-color: var(--oc-color-background-highlight) !important; } &.oc-radio-s { @include oc-form-check-size(0.7); } &.oc-radio-m { @include oc-form-check-size(1); } &.oc-radio-l { @include oc-form-check-size(1.5); } } label > .oc-radio + span { margin-left: var(--oc-space-xsmall); } </style> <docs> ```js <template> <div> <section> <h3 class="oc-heading-divider oc-mt-s"> Radio button group </h3> <div class="oc-mb-s"> <oc-radio v-for="o in availableOptions" :key="'option-' + o" v-model="selectedOption" :option="o" :label="o" class="oc-mr-s" /> </div> Selected option: {{ selectedOption || "None" }} </section> </div> </template> <script> export default { data: () => ({ availableOptions: ["Water", "Wine", "Beer"], selectedOption: null }) } </script> ``` </docs>
owncloud/web/packages/design-system/src/components/OcRadio/OcRadio.vue/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcRadio/OcRadio.vue", "repo_id": "owncloud", "token_count": 1943 }
800
import { shallowMount } from 'web-test-helpers' import Table from './OcTableSimple.vue' describe('OcTableSimple', () => { it('adds hover', () => { const wrapper = shallowMount(Table, { props: { hover: true } }) expect(wrapper.classes()).toContain('oc-table-simple-hover') }) })
owncloud/web/packages/design-system/src/components/OcTableSimple/OcTableSimple.spec.ts/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcTableSimple/OcTableSimple.spec.ts", "repo_id": "owncloud", "token_count": 127 }
801
<template> <tbody> <slot /> </tbody> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ name: 'OcTbody', status: 'ready', release: '2.1.0' }) </script>
owncloud/web/packages/design-system/src/components/_OcTableBody/_OcTableBody.vue/0
{ "file_path": "owncloud/web/packages/design-system/src/components/_OcTableBody/_OcTableBody.vue", "repo_id": "owncloud", "token_count": 85 }
802
export { default as OcTooltip } from './OcTooltip'
owncloud/web/packages/design-system/src/directives/index.ts/0
{ "file_path": "owncloud/web/packages/design-system/src/directives/index.ts", "repo_id": "owncloud", "token_count": 18 }
803
// Ported from UiKit until we change UI frameworks /* ======================================================================== Component: Flex ========================================================================== */ .oc-flex { display: flex; } .oc-flex-inline { display: inline-flex; } /* * Remove pseudo elements created by micro clearfix as precaution */ .oc-flex::before, .oc-flex::after, .oc-flex-inline::before, .oc-flex-inline::after { display: none; } /* Alignment ========================================================================== */ /* * Align items along the main axis of the current line of the flex container * Row: Horizontal */ // Default .oc-flex-left { justify-content: flex-start; } .oc-flex-center { justify-content: center; } .oc-flex-right { justify-content: flex-end; } .oc-flex-between { justify-content: space-between; } .oc-flex-around { justify-content: space-around; } /* Phone landscape and bigger */ @media (min-width: $oc-breakpoint-small-default) { .oc-flex-left\@s { justify-content: flex-start; } .oc-flex-center\@s { justify-content: center; } .oc-flex-right\@s { justify-content: flex-end; } .oc-flex-between\@s { justify-content: space-between; } .oc-flex-around\@s { justify-content: space-around; } } /* Tablet landscape and bigger */ @media (min-width: $oc-breakpoint-medium-default) { .oc-flex-left\@m { justify-content: flex-start; } .oc-flex-center\@m { justify-content: center; } .oc-flex-right\@m { justify-content: flex-end; } .oc-flex-between\@m { justify-content: space-between; } .oc-flex-around\@m { justify-content: space-around; } } /* Desktop and bigger */ @media (min-width: $oc-breakpoint-large-default) { .oc-flex-left\@l { justify-content: flex-start; } .oc-flex-center\@l { justify-content: center; } .oc-flex-right\@l { justify-content: flex-end; } .oc-flex-between\@l { justify-content: space-between; } .oc-flex-around\@l { justify-content: space-around; } } /* Large screen and bigger */ @media (min-width: $oc-breakpoint-xlarge) { .oc-flex-left\@xl { justify-content: flex-start; } .oc-flex-center\@xl { justify-content: center; } .oc-flex-right\@xl { justify-content: flex-end; } .oc-flex-between\@xl { justify-content: space-between; } .oc-flex-around\@xl { justify-content: space-around; } } /* * Align items in the cross axis of the current line of the flex container * Row: Vertical */ // Default .oc-flex-stretch { align-items: stretch; } .oc-flex-top { align-items: flex-start; } .oc-flex-middle { align-items: center; } .oc-flex-bottom { align-items: flex-end; } /* Direction ========================================================================== */ // Default .oc-flex-row { flex-direction: row; } .oc-flex-row-reverse { flex-direction: row-reverse; } .oc-flex-column { flex-direction: column; } .oc-flex-column-reverse { flex-direction: column-reverse; } /* Wrap ========================================================================== */ // Default .oc-flex-nowrap { flex-wrap: nowrap; } .oc-flex-wrap { flex-wrap: wrap; } .oc-flex-wrap-reverse { flex-wrap: wrap-reverse; } /* * Aligns items within the flex container when there is extra space in the cross-axis * Only works if there is more than one line of flex items */ // Default .oc-flex-wrap-stretch { align-content: stretch; } .oc-flex-wrap-top { align-content: flex-start; } .oc-flex-wrap-middle { align-content: center; } .oc-flex-wrap-bottom { align-content: flex-end; } .oc-flex-wrap-between { align-content: space-between; } .oc-flex-wrap-around { align-content: space-around; } /* Item ordering ========================================================================== */ /* * Default is 0 */ .oc-flex-first { order: -1; } .oc-flex-last { order: 99; } /* Phone landscape and bigger */ @media (min-width: $oc-breakpoint-small-default) { .oc-flex-first\@s { order: -1; } .oc-flex-last\@s { order: 99; } } /* Tablet landscape and bigger */ @media (min-width: $oc-breakpoint-medium-default) { .oc-flex-first\@m { order: -1; } .oc-flex-last\@m { order: 99; } } /* Desktop and bigger */ @media (min-width: $oc-breakpoint-large-default) { .oc-flex-first\@l { order: -1; } .oc-flex-last\@l { order: 99; } } /* Large screen and bigger */ @media (min-width: $oc-breakpoint-xlarge) { .oc-flex-first\@xl { order: -1; } .oc-flex-last\@xl { order: 99; } } /* Item dimensions ========================================================================== */ /* * Initial: 0 1 auto * Content dimensions, but shrinks */ /* * No Flex: 0 0 auto * Content dimensions */ .oc-flex-none { flex: none; } /* * Relative Flex: 1 1 auto * Space is allocated considering content */ .oc-flex-auto { flex: auto; } /* * Absolute Flex: 1 1 0% * Space is allocated solely based on flex */ .oc-flex-1 { flex: 1; }
owncloud/web/packages/design-system/src/styles/theme/oc-flex.scss/0
{ "file_path": "owncloud/web/packages/design-system/src/styles/theme/oc-flex.scss", "repo_id": "owncloud", "token_count": 1633 }
804
--- font: family: value: 'Inter, sans-serif' size: default: value: 0.875rem xsmall: value: 0.72rem small: value: 0.86rem medium: value: 1rem large: value: 1.14rem xlarge: value: 1.29rem weight: default: value: '400' thin: value: '100' extralight: value: '200' light: value: '300' normal: value: '400' medium: value: '500' semibold: value: '600' bold: value: '700' extrabold: value: '800' black: value: '900'
owncloud/web/packages/design-system/src/tokens/ods/font.yaml/0
{ "file_path": "owncloud/web/packages/design-system/src/tokens/ods/font.yaml", "repo_id": "owncloud", "token_count": 315 }
805
// ATTENTION: this is a .mjs (instead of a .ts) file on purpose, // because we don't want to transpile it before publishing // c.f. https://github.com/vitejs/vite/issues/5370 import { mergeConfig, searchForWorkspaceRoot } from 'vite' import { join } from 'path' import { cwd } from 'process' import { readFileSync } from 'fs' import vue from '@vitejs/plugin-vue' import serve from 'rollup-plugin-serve' const distDir = 'dist' const certsDir = process.env.OWNCLOUD_CERTS_DIR const defaultHttps = () => certsDir && { key: readFileSync(join(certsDir, 'server.key')), cert: readFileSync(join(certsDir, 'server.crt')) } export const defineConfig = (overrides = {}) => { return ({ mode }) => { const isProduction = mode === 'production' const isServing = !isProduction // read package name from vite workspace const packageJson = JSON.parse( readFileSync(join(searchForWorkspaceRoot(cwd()), 'package.json')).toString() ) const name = overrides.name || packageJson.name // take vite standard config and reuse it for rollup-plugin-serve config const { https = defaultHttps(), port = 9210, host = 'localhost' } = overrides?.server || {} const isHttps = !!https if (isServing) { console.log( `>>> Serving extension at http${isHttps ? 's' : ''}://${host}:${port}/js/${name}.js` ) } return mergeConfig( { server: { host, port, strictPort: true, ...(isHttps && https) }, build: { cssCodeSplit: true, minify: isProduction, rollupOptions: { // keep in sync with packages/web-runtime/src/container/application/index.ts external: [ 'vue', 'luxon', 'pinia', 'vue3-gettext', '@ownclouders/web-client', '@ownclouders/web-pkg', 'web-client', 'web-pkg' ], preserveEntrySignatures: 'strict', input: { [name]: './src/index.ts' }, output: { format: 'amd', dir: distDir, chunkFileNames: join('js', 'chunks', '[name]-[hash].mjs'), entryFileNames: join('js', `[name]${isProduction ? '-[hash]' : ''}.js`) }, plugins: [ isServing && serve({ headers: { 'access-control-allow-origin': '*' }, contentBase: distDir, ...(https && { https }), ...(port && { port }) }) ] } }, plugins: [ vue({ // set to true when switching to esm customElement: false }) ] }, overrides ) } }
owncloud/web/packages/extension-sdk/index.mjs/0
{ "file_path": "owncloud/web/packages/extension-sdk/index.mjs", "repo_id": "owncloud", "token_count": 1439 }
806
<template> <div class="oc-mt-xl"> <div v-if="noGroups" class="oc-flex group-info oc-text-center"> <oc-icon name="group-2" size="xxlarge" /> <p v-translate>Select a group to view details</p> </div> <div v-if="multipleGroups" class="oc-flex group-info"> <oc-icon name="group-2" size="xxlarge" /> <p>{{ multipleGroupsSelectedText }}</p> </div> <div v-if="group"> <GroupInfoBox :group="group" /> <table class="details-table" :aria-label="$gettext('Overview of the information about the selected group')" > <tr> <th scope="col" class="oc-pr-s" v-text="$gettext('Group name')" /> <td v-text="group.displayName" /> </tr> </table> </div> </div> </template> <script lang="ts"> import { defineComponent, PropType } from 'vue' import GroupInfoBox from './GroupInfoBox.vue' import { Group } from '@ownclouders/web-client/src/generated' export default defineComponent({ name: 'DetailsPanel', components: { GroupInfoBox }, props: { groups: { type: Array as PropType<Group[]>, required: true } }, computed: { group() { return this.groups.length === 1 ? this.groups[0] : null }, noGroups() { return !this.groups.length }, multipleGroups() { return this.groups.length > 1 }, multipleGroupsSelectedText() { return this.$gettext('%{count} groups selected', { count: this.groups.length.toString() }) } } }) </script> <style lang="scss"> .group-info { align-items: center; flex-direction: column; } .group-info-display-name { font-size: 1.5rem; } .details-table { text-align: left; tr { height: 1.5rem; } th { font-weight: 600; } } </style>
owncloud/web/packages/web-app-admin-settings/src/components/Groups/SideBar/DetailsPanel.vue/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/src/components/Groups/SideBar/DetailsPanel.vue", "repo_id": "owncloud", "token_count": 763 }
807
<template> <div class="oc-mt-xl"> <div v-if="noUsers" class="oc-flex user-info oc-text-center"> <oc-icon name="user" size="xxlarge" /> <p v-translate>Select a user to view details</p> </div> <div v-if="multipleUsers" class="oc-flex group-info"> <oc-icon name="group" size="xxlarge" /> <p>{{ multipleUsersSelectedText }}</p> </div> <div v-if="_user"> <UserInfoBox :user="_user" /> <table class="details-table" :aria-label="$gettext('Overview of the information about the selected user')" > <tr> <th scope="col" class="oc-pr-s" v-text="$gettext('User name')" /> <td v-text="_user.onPremisesSamAccountName" /> </tr> <tr> <th scope="col" class="oc-pr-s" v-text="$gettext('First and last name')" /> <td v-text="_user.displayName" /> </tr> <tr> <th scope="col" class="oc-pr-s" v-text="$gettext('Email')" /> <td> <span v-text="_user.mail" /> </td> </tr> <tr> <th scope="col" class="oc-pr-s" v-text="$gettext('Role')" /> <td> <span v-if="_user.appRoleAssignments" v-text="roleDisplayName" /> </td> </tr> <tr> <th scope="col" class="oc-pr-s" v-text="$gettext('Login')" /> <td> <span v-text="loginDisplayValue" /> </td> </tr> <tr> <th scope="col" class="oc-pr-s" v-text="$gettext('Quota')" /> <td> <span v-if="showUserQuota" v-text="quotaDisplayValue" /> <span v-else> <span class="oc-mr-xs">-</span> <oc-contextual-helper :text=" $gettext('To see an individual quota, the user needs to have logged in once.') " /> </span> </td> </tr> <tr> <th scope="col" class="oc-pr-s" v-text="$gettext('Groups')" /> <td> <span v-if="_user.memberOf.length" v-text="groupsDisplayValue" /> <span v-else> <span class="oc-mr-xs">-</span> <oc-contextual-helper :text="$gettext('No groups assigned.')" /> </span> </td> </tr> </table> </div> </div> </template> <script lang="ts"> import { computed, defineComponent } from 'vue' import UserInfoBox from './UserInfoBox.vue' import { PropType } from 'vue' import { AppRole, User } from '@ownclouders/web-client/src/generated' import { formatFileSize } from '@ownclouders/web-pkg' import { useGettext } from 'vue3-gettext' export default defineComponent({ name: 'DetailsPanel', components: { UserInfoBox }, props: { user: { type: Object as PropType<User>, required: false, default: null }, users: { type: Array, required: true }, roles: { type: Array as PropType<AppRole[]>, required: true } }, setup(props) { const { $gettext, current: currentLanguage } = useGettext() return { $gettext, currentLanguage, // HACK: make sure _user has a proper type _user: computed(() => props.user as User) } }, computed: { noUsers() { return !this.users.length }, multipleUsers() { return this.users.length > 1 }, multipleUsersSelectedText() { return this.$gettext('%{count} users selected', { count: this.users.length.toString() }) }, roleDisplayName() { const assignedRole = this.user.appRoleAssignments[0] return ( this.$gettext( this.roles.find((role) => role.id === assignedRole?.appRoleId)?.displayName || '' ) || '-' ) }, groupsDisplayValue() { return this.user.memberOf .map((group) => group.displayName) .sort() .join(', ') }, showUserQuota() { return 'total' in (this.user.drive?.quota || {}) }, quotaDisplayValue() { return this.user.drive.quota.total === 0 ? this.$gettext('No restriction') : formatFileSize(this.user.drive.quota.total, this.currentLanguage) }, loginDisplayValue() { return this.user.accountEnabled === false ? this.$gettext('Forbidden') : this.$gettext('Allowed') } } }) </script> <style lang="scss"> .details-table { text-align: left; tr { height: 1.5rem; } th { font-weight: 600; } } </style>
owncloud/web/packages/web-app-admin-settings/src/components/Users/SideBar/DetailsPanel.vue/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/src/components/Users/SideBar/DetailsPanel.vue", "repo_id": "owncloud", "token_count": 2195 }
808
import { eventBus } from '@ownclouders/web-pkg' import { SideBarEventTopics } from '@ownclouders/web-pkg' import { useGettext } from 'vue3-gettext' import { computed } from 'vue' import { UserAction } from '@ownclouders/web-pkg' export const useUserActionsEdit = () => { const { $gettext } = useGettext() const actions = computed((): UserAction[] => [ { name: 'edit', icon: 'pencil', label: () => $gettext('Edit'), handler: () => eventBus.publish(SideBarEventTopics.openWithPanel, 'EditPanel'), isVisible: ({ resources }) => { return resources.length === 1 }, componentType: 'button', class: 'oc-users-actions-edit-trigger' } ]) return { actions } }
owncloud/web/packages/web-app-admin-settings/src/composables/actions/users/useUserActionsEdit.ts/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/src/composables/actions/users/useUserActionsEdit.ts", "repo_id": "owncloud", "token_count": 280 }
809
<template> <div> <app-template ref="template" :loading="loadResourcesTask.isRunning || !loadResourcesTask.last" :breadcrumbs="breadcrumbs" :side-bar-active-panel="sideBarActivePanel" :side-bar-available-panels="sideBarAvailablePanels" :side-bar-panel-context="sideBarPanelContext" :is-side-bar-open="isSideBarOpen" :show-batch-actions="!!selectedSpaces.length" :batch-actions="batchActions" :batch-action-items="selectedSpaces" :show-view-options="true" > <template #sideBarHeader> <space-info v-if="selectedSpaces.length === 1" :space-resource="selectedSpaces[0]" class="sidebar-panel__space_info" /> </template> <template #mainContent> <no-content-message v-if="!spaces.length" id="admin-settings-spaces-empty" class="spaces-empty" icon="layout-grid" > <template #message> <span v-translate>No spaces in here</span> </template> </no-content-message> <div v-else> <spaces-list :class="{ 'spaces-table-squashed': isSideBarOpen }"> <template #contextMenu> <context-actions :items="selectedSpaces" /> </template> </spaces-list> </div> </template> </app-template> </div> </template> <script lang="ts"> import AppTemplate from '../components/AppTemplate.vue' import SpacesList from '../components/Spaces/SpacesList.vue' import ContextActions from '../components/Spaces/ContextActions.vue' import MembersPanel from '../components/Spaces/SideBar/MembersPanel.vue' import ActionsPanel from '../components/Spaces/SideBar/ActionsPanel.vue' import { NoContentMessage, SideBarPanel, SideBarPanelContext, SpaceAction, SpaceDetails, SpaceDetailsMultiple, SpaceInfo, SpaceNoSelection, eventBus, queryItemAsString, useClientService, useRouteQuery, useSideBar, useSpaceActionsDelete, useSpaceActionsDisable, useSpaceActionsRestore, useSpaceActionsEditQuota, useConfigStore } from '@ownclouders/web-pkg' import { buildSpace, SpaceResource } from '@ownclouders/web-client/src/helpers' import { computed, defineComponent, onBeforeUnmount, onMounted, ref, unref } from 'vue' import { useTask } from 'vue-concurrency' import { useGettext } from 'vue3-gettext' import { useSpaceSettingsStore } from '../composables' import { storeToRefs } from 'pinia' export default defineComponent({ name: 'SpacesView', components: { SpacesList, AppTemplate, NoContentMessage, ContextActions, SpaceInfo }, provide() { return { resource: computed(() => this.selectedSpaces[0]) } }, setup() { const clientService = useClientService() const { $gettext } = useGettext() const { isSideBarOpen, sideBarActivePanel } = useSideBar() const configStore = useConfigStore() const loadResourcesEventToken = ref(null) let updateQuotaForSpaceEventToken: string const template = ref(null) const spaceSettingsStore = useSpaceSettingsStore() const { spaces, selectedSpaces } = storeToRefs(spaceSettingsStore) const currentPageQuery = useRouteQuery('page', '1') const currentPage = computed(() => { return parseInt(queryItemAsString(unref(currentPageQuery))) }) const itemsPerPageQuery = useRouteQuery('items-per-page', '1') const itemsPerPage = computed(() => { return parseInt(queryItemAsString(unref(itemsPerPageQuery))) }) const loadResourcesTask = useTask(function* (signal) { const { data: { value: drivesResponse } } = yield clientService.graphAuthenticated.drives.listAllDrives( 'name asc', 'driveType eq project' ) const drives = drivesResponse.map((space) => buildSpace({ ...space, serverUrl: configStore.serverUrl }) ) spaceSettingsStore.setSpaces(drives) }) const breadcrumbs = computed(() => [ { text: $gettext('Administration Settings'), to: { path: '/admin-settings' } }, { text: $gettext('Spaces'), onClick: () => { spaceSettingsStore.setSelectedSpaces([]) loadResourcesTask.perform() } } ]) const { actions: deleteActions } = useSpaceActionsDelete() const { actions: disableActions } = useSpaceActionsDisable() const { actions: editQuotaActions } = useSpaceActionsEditQuota() const { actions: restoreActions } = useSpaceActionsRestore() const batchActions = computed((): SpaceAction[] => { return [ ...unref(editQuotaActions), ...unref(restoreActions), ...unref(deleteActions), ...unref(disableActions) ].filter((item) => item.isVisible({ resources: unref(selectedSpaces) })) }) const sideBarPanelContext = computed<SideBarPanelContext<unknown, unknown, SpaceResource>>( () => { return { parent: null, items: unref(selectedSpaces) } } ) const sideBarAvailablePanels = [ { name: 'SpaceNoSelection', icon: 'layout-grid', title: () => $gettext('Details'), component: SpaceNoSelection, isRoot: () => true, isVisible: ({ items }) => items.length === 0 }, { name: 'SpaceDetails', icon: 'layout-grid', title: () => $gettext('Details'), component: SpaceDetails, componentAttrs: () => ({ showSpaceImage: false, showShareIndicators: false }), isRoot: () => true, isVisible: ({ items }) => items.length === 1 }, { name: 'SpaceDetailsMultiple', icon: 'layout-grid', title: () => $gettext('Details'), component: SpaceDetailsMultiple, componentAttrs: ({ items }) => ({ selectedSpaces: items }), isRoot: () => true, isVisible: ({ items }) => items.length > 1 }, { name: 'SpaceActions', icon: 'slideshow-3', title: () => $gettext('Actions'), component: ActionsPanel, isVisible: ({ items }) => items.length === 1 }, { name: 'SpaceMembers', icon: 'group', title: () => $gettext('Members'), component: MembersPanel, isVisible: ({ items }) => items.length === 1 } ] satisfies SideBarPanel<unknown, unknown, SpaceResource>[] onMounted(async () => { await loadResourcesTask.perform() loadResourcesEventToken.value = eventBus.subscribe( 'app.admin-settings.list.load', async () => { await loadResourcesTask.perform() selectedSpaces.value = [] const pageCount = Math.ceil(unref(spaces).length / unref(itemsPerPage)) if (unref(currentPage) > 1 && unref(currentPage) > pageCount) { // reset pagination to avoid empty lists (happens when deleting all items on the last page) currentPageQuery.value = pageCount.toString() } } ) updateQuotaForSpaceEventToken = eventBus.subscribe( 'app.admin-settings.spaces.space.quota.updated', ({ spaceId, quota }) => { const space = unref(spaces).find((s) => s.id === spaceId) if (space) { space.spaceQuota = quota } } ) }) onBeforeUnmount(() => { spaceSettingsStore.reset() eventBus.unsubscribe('app.admin-settings.list.load', unref(loadResourcesEventToken)) eventBus.unsubscribe( 'app.admin-settings.spaces.space.quota.updated', updateQuotaForSpaceEventToken ) }) return { isSideBarOpen, sideBarActivePanel, spaces, loadResourcesTask, breadcrumbs, batchActions, selectedSpaces, sideBarAvailablePanels, sideBarPanelContext, template } } }) </script>
owncloud/web/packages/web-app-admin-settings/src/views/Spaces.vue/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/src/views/Spaces.vue", "repo_id": "owncloud", "token_count": 3311 }
810
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`MembersRoleSection > should render all members accordingly 1`] = ` "<ul class="oc-list"> <li class="oc-flex oc-flex-middle oc-mb-s" data-testid="space-members-list"> <oc-avatar-stub src="" username="einstein" accessiblelabel="" width="36" class="oc-mr-s"></oc-avatar-stub> einstein </li> <li class="oc-flex oc-flex-middle oc-mb-s" data-testid="space-members-list"> <oc-avatar-item-stub name="group" icon="group" iconcolor="var(--oc-color-text-inverse)" iconfilltype="fill" iconsize="medium" background="var(--oc-color-swatch-passive-default)" accessiblelabel="" width="36" class="oc-mr-s"></oc-avatar-item-stub> physic-lovers </li> </ul>" `;
owncloud/web/packages/web-app-admin-settings/tests/unit/components/Spaces/SideBar/__snapshots__/MembersRoleSection.spec.ts.snap/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/components/Spaces/SideBar/__snapshots__/MembersRoleSection.spec.ts.snap", "repo_id": "owncloud", "token_count": 274 }
811
import { useModals } from '@ownclouders/web-pkg' import { useGroupActionsCreateGroup } from '../../../../../src/composables/actions/groups/useGroupActionsCreateGroup' import { unref } from 'vue' import { getComposableWrapper } from 'web-test-helpers' describe('useGroupActionsCreateGroup', () => { describe('method "handler"', () => { it('creates a modal', () => { getWrapper({ setup: async ({ actions }) => { const { dispatchModal } = useModals() await unref(actions)[0].handler() expect(dispatchModal).toHaveBeenCalled() } }) }) }) }) function getWrapper({ setup }: { setup: (instance: ReturnType<typeof useGroupActionsCreateGroup>) => void }) { return { wrapper: getComposableWrapper(() => { const instance = useGroupActionsCreateGroup() setup(instance) }) } }
owncloud/web/packages/web-app-admin-settings/tests/unit/composables/actions/groups/useGroupActionsCreateGroup.spec.ts/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/composables/actions/groups/useGroupActionsCreateGroup.spec.ts", "repo_id": "owncloud", "token_count": 334 }
812
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`Spaces view > loading states > should render spaces list after loading has been finished 1`] = ` "<div> <main class="oc-flex oc-height-1-1 app-content oc-width-1-1"> <div id="admin-settings-wrapper" class="oc-width-expand oc-height-1-1 oc-position-relative"> <div id="admin-settings-app-bar" class="oc-app-bar oc-py-s"> <div class="admin-settings-app-bar-controls oc-flex oc-flex-between oc-flex-middle"> <oc-breadcrumb-stub items="[object Object],[object Object]" id="admin-settings-breadcrumb" variation="default" contextmenupadding="medium" maxwidth="-1" truncationoffset="2" showcontextactions="false" class="oc-flex oc-flex-middle"></oc-breadcrumb-stub> <portal-target name="app.runtime.mobile.nav"></portal-target> <div class="oc-flex"> <view-options-stub perpagestorageprefix="admin-settings" hashiddenfiles="false" hasfileextensions="false" haspagination="true" paginationoptions="20,50,100,250" perpagequeryname="items-per-page" perpagedefault="50" viewmodedefault="resource-table" viewmodes=""></view-options-stub> </div> </div> <div class="admin-settings-app-bar-actions oc-flex oc-flex-middle oc-mt-xs"> <!--v-if--> </div> </div> <div> <spaces-list-stub class=""></spaces-list-stub> </div> </div> <!--v-if--> </main> </div>" `;
owncloud/web/packages/web-app-admin-settings/tests/unit/views/__snapshots__/Spaces.spec.ts.snap/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/views/__snapshots__/Spaces.spec.ts.snap", "repo_id": "owncloud", "token_count": 601 }
813
{ "name": "external", "version": "0.0.0", "private": true, "description": "ownCloud web integration of the reva app provider", "license": "AGPL-3.0", "devDependencies": { "web-test-helpers": "workspace:*" }, "peerDependencies": { "@ownclouders/web-client": "workspace:*", "@ownclouders/web-pkg": "workspace:*", "uuid": "9.0.1", "vue-concurrency": "5.0.0", "vue3-gettext": "2.4.0", "zod": "3.22.4" } }
owncloud/web/packages/web-app-external/package.json/0
{ "file_path": "owncloud/web/packages/web-app-external/package.json", "repo_id": "owncloud", "token_count": 208 }
814
<template> <span class="oc-flex oc-flex-middle"> <div v-oc-tooltip="dropButtonTooltip"> <oc-button :id="editShareBtnId" class="collaborator-edit-dropdown-options-btn" appearance="raw" :disabled="isLocked" > <oc-icon name="more-2" /> </oc-button> </div> <oc-drop ref="expirationDateDrop" :toggle="'#' + editShareBtnId" mode="click" padding-size="small" > <oc-list class="collaborator-edit-dropdown-options-list" :aria-label="shareEditOptions"> <li v-if="canEditOrDelete && isExpirationSupported" class="oc-rounded oc-menu-item-hover"> <oc-datepicker v-model="enteredExpirationDate" :min-date="minExpirationDate" :max-date="maxExpirationDate" :locale="$language.current" :is-required="isExpirationDateEnforced" class="files-recipient-expiration-datepicker oc-flex" data-testid="recipient-datepicker" > <template #default="{ togglePopover }"> <oc-button class="files-collaborators-expiration-button oc-p-s action-menu-item" data-testid="recipient-datepicker-btn" appearance="raw" @click="togglePopover" > <oc-icon name="calendar-event" fill-type="line" size="medium" variation="passive" /> <span v-if="isExpirationDateSet" class="oc-ml-s" v-text="$gettext('Expires %{expires}', { expires: dateExpire })" /> <span v-else v-text="$gettext('Set expiration date')" /> </oc-button> <oc-button v-if="isRemoveExpirationPossible" class="remove-expiration-date" data-testid="collaborator-remove-expiration-btn" appearance="raw" :aria-label="$gettext('Remove expiration date')" @click="removeExpirationDate" > <oc-icon name="close" /> </oc-button> </template> </oc-datepicker> </li> <li v-for="(option, i) in options" :key="i" class="oc-rounded oc-menu-item-hover"> <template v-if="option.enabled"> <div v-if="option.hasSwitch" class="action-menu-item item-has-switch oc-p-s oc-flex oc-flex-center" > <oc-icon :name="option.icon" fill-type="line" size="medium" variation="passive" /> <oc-switch class="oc-ml-s oc-flex oc-width-1-1 oc-button-justify-content-space-between" :checked="isShareDenied" :class="option.class" :label="option.title" @update:checked="option.method" /> </div> <oc-button v-else appearance="raw" class="oc-p-s action-menu-item" :class="option.class" v-bind="option.additionalAttributes || {}" @click="option.method" > <oc-icon :name="option.icon" fill-type="line" size="medium" variation="passive" /> <span v-text="option.title" /> </oc-button> </template> </li> </oc-list> </oc-drop> </span> </template> <script lang="ts"> import { computed, defineComponent, inject, Ref } from 'vue' import { DateTime } from 'luxon' import uniqueId from 'design-system/src/utils/uniqueId' import { OcDrop } from 'design-system/src/components' import { Resource } from '@ownclouders/web-client/src' import { isProjectSpaceResource } from '@ownclouders/web-client/src/helpers' import { formatRelativeDateFromDateTime, useCapabilityStore, useConfigStore } from '@ownclouders/web-pkg' import { useGettext } from 'vue3-gettext' import { storeToRefs } from 'pinia' export default defineComponent({ name: 'EditDropdown', props: { expirationDate: { type: String, required: false, default: undefined }, shareCategory: { type: String, required: false, default: null, validator: function (value: string) { return ['user', 'group'].includes(value) || !value } }, canEditOrDelete: { type: Boolean, required: true }, isShareDenied: { type: Boolean, default: false }, deniable: { type: Boolean, default: false }, isLocked: { type: Boolean, default: false } }, emits: [ 'expirationDateChanged', 'removeShare', 'showAccessDetails', 'setDenyShare', 'notifyShare' ], setup(props, { emit }) { const capabilityStore = useCapabilityStore() const capabilityRefs = storeToRefs(capabilityStore) const language = useGettext() const configStore = useConfigStore() const toggleShareDenied = (value: boolean) => { emit('setDenyShare', value) } const dropButtonTooltip = computed(() => { if (props.isLocked) { return language.$gettext('Resource is temporarily locked, unable to manage share') } return '' }) const dateExpire = computed(() => formatRelativeDateFromDateTime( DateTime.fromISO(props.expirationDate).endOf('day'), language.current ) ) return { configStore, resource: inject<Ref<Resource>>('resource'), toggleShareDenied, dateExpire, userExpirationDate: capabilityRefs.sharingUserExpireDate, groupExpirationDate: capabilityRefs.sharingGroupExpireDate, dropButtonTooltip } }, data: function () { return { enteredExpirationDate: null } }, computed: { options() { return [ { title: isProjectSpaceResource(this.resource) ? this.$gettext('Remove member') : this.$gettext('Remove share'), method: this.removeShare, class: 'remove-share', enabled: this.canEditOrDelete, icon: 'delete-bin-5', additionalAttributes: { 'data-testid': 'collaborator-remove-share-btn' } }, { title: this.$gettext('Access details'), method: this.showAccessDetails, enabled: true, icon: 'information', class: 'show-access-details' }, { title: this.$gettext('Deny access'), method: this.toggleShareDenied, enabled: this.deniable, icon: 'stop-circle', class: 'deny-share', hasSwitch: true }, { title: this.$gettext('Notify via mail'), method: () => this.$emit('notifyShare'), enabled: this.configStore.options.isRunningOnEos, icon: 'mail', class: 'notify-via-mail' } ] }, editShareBtnId() { return uniqueId('files-collaborators-edit-button-') }, shareEditOptions() { return this.$gettext('Context menu of the share') }, editingUser() { return this.shareCategory === 'user' }, editingGroup() { return this.shareCategory === 'group' }, isExpirationSupported() { return this.editingUser || this.editingGroup }, isExpirationDateSet() { return !!this.expirationDate }, isRemoveExpirationPossible() { return ( this.canEditOrDelete && this.isExpirationSupported && this.isExpirationDateSet && !this.isExpirationDateEnforced ) }, isDefaultExpirationEnabled() { if (this.editingUser) { return this.userExpirationDate.enabled } if (this.editingGroup) { return this.groupExpirationDate.enabled } return this.userExpirationDate.enabled || this.groupExpirationDate.enabled }, defaultExpirationDate() { if (!this.isDefaultExpirationEnabled) { return null } const userMaxExpirationDays = parseInt(this.userExpirationDate.days) const groupMaxExpirationDays = parseInt(this.groupExpirationDate.days) let days = 0 if (this.editingUser) { days = userMaxExpirationDays } else if (this.editingGroup) { days = groupMaxExpirationDays } else if (userMaxExpirationDays && groupMaxExpirationDays) { days = Math.min(userMaxExpirationDays, groupMaxExpirationDays) } else { days = userMaxExpirationDays || groupMaxExpirationDays } const date = new Date() date.setDate(new Date().getDate() + days) return date }, isExpirationDateEnforced() { if (this.editingUser) { return this.userExpirationDate?.enforced } if (this.editingGroup) { return this.groupExpirationDate?.enforced } return this.userExpirationDate?.enforced || this.groupExpirationDate?.enforced }, maxExpirationDate() { if (!this.isExpirationDateEnforced) { return null } return this.defaultExpirationDate }, minExpirationDate() { const date = new Date() date.setDate(new Date().getDate() + 1) return date } }, watch: { enteredExpirationDate: { handler: 'updateExpirationDate' } }, methods: { updateExpirationDate() { this.$emit('expirationDateChanged', { expirationDateTime: DateTime.fromJSDate(this.enteredExpirationDate).endOf('day').toISO() }) ;(this.$refs.expirationDateDrop as InstanceType<typeof OcDrop>).hide() }, removeExpirationDate() { this.$emit('expirationDateChanged', { expirationDateTime: null }) ;(this.$refs.expirationDateDrop as InstanceType<typeof OcDrop>).hide() }, removeShare() { this.$emit('removeShare') }, showAccessDetails() { this.$emit('showAccessDetails') } } }) </script> <style lang="scss"> .collaborator-edit-dropdown-options-list .action-menu-item { width: 100%; justify-content: flex-start; color: var(--oc-color-swatch-passive-default); gap: var(--oc-space-small); } </style>
owncloud/web/packages/web-app-files/src/components/SideBar/Shares/Collaborators/EditDropdown.vue/0
{ "file_path": "owncloud/web/packages/web-app-files/src/components/SideBar/Shares/Collaborators/EditDropdown.vue", "repo_id": "owncloud", "token_count": 4668 }
815
<template> <div id="oc-file-versions-sidebar" class="-oc-mt-s"> <oc-loader v-if="areVersionsLoading" /> <ul v-else-if="versions.length" class="oc-m-rm oc-position-relative"> <li class="spacer oc-pb-l" aria-hidden="true"></li> <li v-for="(item, index) in versions" :key="index" class="version-item oc-pb-m oc-position-relative" > <div class="version-details"> <span v-oc-tooltip="formatVersionDate(item)" class="version-date oc-font-semibold" data-testid="file-versions-file-last-modified-date" >{{ formatVersionDateRelative(item) }}</span > - <span class="version-filesize" data-testid="file-versions-file-size">{{ formatVersionFileSize(item) }}</span> </div> <oc-list id="oc-file-versions-sidebar-actions" class="oc-pt-xs"> <li v-if="isRevertible"> <oc-button data-testid="file-versions-revert-button" appearance="raw" :aria-label="$gettext('Restore')" class="version-action-item oc-width-1-1 oc-rounded oc-button-justify-content-left oc-button-gap-m oc-py-s oc-px-m oc-display-block" @click="revertToVersion(item)" > <oc-icon name="history" class="oc-icon-m oc-mr-s -oc-mt-xs" fill-type="line" /> {{ $gettext('Restore') }} </oc-button> </li> <li> <oc-button data-testid="file-versions-download-button" appearance="raw" :aria-label="$gettext('Download')" class="version-action-item oc-width-1-1 oc-rounded oc-button-justify-content-left oc-button-gap-m oc-py-s oc-px-m oc-display-block" @click="downloadVersion(item)" > <oc-icon name="file-download" class="oc-icon-m oc-mr-s" fill-type="line" /> {{ $gettext('Download') }} </oc-button> </li> </oc-list> </li> </ul> <div v-else> <p v-translate data-testid="file-versions-no-versions">No Versions available for this file</p> </div> </div> </template> <script lang="ts"> import { DavPermission } from '@ownclouders/web-client/src/webdav/constants' import { formatRelativeDateFromHTTP, formatDateFromJSDate, formatFileSize, useClientService, useDownloadFile, useResourcesStore } from '@ownclouders/web-pkg' import { computed, defineComponent, inject, Ref, ref, unref, watch } from 'vue' import { isShareSpaceResource, Resource, SpaceResource } from '@ownclouders/web-client/src/helpers' import { useTask } from 'vue-concurrency' import { useGettext } from 'vue3-gettext' export default defineComponent({ name: 'FileVersions', props: { isReadOnly: { type: Boolean, required: false, default: false } }, setup(props) { const clientService = useClientService() const { current: currentLanguage } = useGettext() const { downloadFile } = useDownloadFile({ clientService }) const { updateResourceField } = useResourcesStore() const space = inject<Ref<SpaceResource>>('space') const resource = inject<Ref<Resource>>('resource') const versions = ref<Resource[]>([]) const fetchVersionsTask = useTask(function* () { try { versions.value = yield clientService.webdav.listFileVersions(unref(resource).fileId) } catch (e) { console.error(e) } }) const areVersionsLoading = computed(() => { return !fetchVersionsTask.last || fetchVersionsTask.isRunning }) watch( [() => unref(resource)?.id, () => unref(resource)?.etag], ([id, etag]) => { if (!id || !etag) { return } fetchVersionsTask.perform() }, { immediate: true } ) const isRevertible = computed(() => { if (props.isReadOnly) { return false } if (isShareSpaceResource(unref(space)) || unref(resource).isReceivedShare()) { if (unref(resource).permissions !== undefined) { return unref(resource).permissions.includes(DavPermission.Updateable) } } return true }) const revertToVersion = async (version: Resource) => { await clientService.webdav.restoreFileVersion(unref(space), unref(resource), version.name) const restoredResource = await clientService.webdav.getFileInfo(unref(space), unref(resource)) const fieldsToUpdate = ['size', 'mdate'] as const for (const field of fieldsToUpdate) { if (Object.prototype.hasOwnProperty.call(unref(resource), field)) { updateResourceField({ id: unref(resource).id, field: field, value: restoredResource[field] }) } } fetchVersionsTask.perform() } const downloadVersion = (version: Resource) => { return downloadFile(unref(space), unref(resource), version.name) } const formatVersionDateRelative = (version: Resource) => { return formatRelativeDateFromHTTP(version.mdate, currentLanguage) } const formatVersionDate = (version: Resource) => { return formatDateFromJSDate(new Date(version.mdate), currentLanguage) } const formatVersionFileSize = (version: Resource) => { return formatFileSize(version.size, currentLanguage) } return { space, resource, versions, areVersionsLoading, isRevertible, revertToVersion, downloadVersion, formatVersionDateRelative, formatVersionDate, formatVersionFileSize, // HACK: exported for unit tests fetchVersionsTask } } }) </script> <style lang="scss" scoped> #oc-file-versions-sidebar { > ul { list-style: none; .spacer { border-left: 1px solid var(--oc-color-border); margin-left: calc(-1 * var(--oc-space-large)) !important; } > li.version-item { border-left: 1px solid var(--oc-color-border); margin-left: calc(-1 * var(--oc-space-large)) !important; padding-left: var(--oc-space-medium); padding-bottom: var(--oc-space-medium); margin-top: calc(-1 * var(--oc-space-small)); &::before { content: ''; display: block; width: 11px; height: 11px; position: absolute; left: -6px; top: 4px; background-color: var(--oc-color-border); border-radius: 50%; } button.version-action-item { &:hover { color: var(--oc-color-primary-contrast); background-color: var(--oc-color-background-hover); } .oc-icon { vertical-align: middle; } } &:last-child { border-left: 1px solid transparent; } } } } </style>
owncloud/web/packages/web-app-files/src/components/SideBar/Versions/FileVersions.vue/0
{ "file_path": "owncloud/web/packages/web-app-files/src/components/SideBar/Versions/FileVersions.vue", "repo_id": "owncloud", "token_count": 3057 }
816
import { nextTick, computed, unref, Ref } from 'vue' import { folderService } from '../../services/folder' import { fileList } from '../../helpers/ui' import { usePagination, useSort, SortDir, SortField, useRouteName, useResourcesStore } from '@ownclouders/web-pkg' import { useSideBar } from '@ownclouders/web-pkg' import { queryItemAsString, useRouteQuery } from '@ownclouders/web-pkg' import { determineResourceTableSortFields, determineResourceTilesSortFields } from '@ownclouders/web-pkg' import { Task } from 'vue-concurrency' import { Resource } from '@ownclouders/web-client' import { useSelectedResources, SelectedResourcesResult } from '@ownclouders/web-pkg' import { ReadOnlyRef } from '@ownclouders/web-pkg' import { useFileListHeaderPosition, useViewMode, useViewSize, FolderViewModeConstants } from '@ownclouders/web-pkg' import { ScrollToResult, useScrollTo } from '@ownclouders/web-pkg' interface ResourcesViewDefaultsOptions<T, U extends any[]> { loadResourcesTask?: Task<T, U> } type ResourcesViewDefaultsResult<T extends Resource, TT, TU extends any[]> = { fileListHeaderY: Ref<any> refreshFileListHeaderPosition(): void loadResourcesTask: Task<TT, TU> areResourcesLoading: ReadOnlyRef<boolean> storeItems: ReadOnlyRef<T[]> sortFields: ReadOnlyRef<SortField[]> paginatedResources: Ref<T[]> paginationPages: ReadOnlyRef<number> paginationPage: ReadOnlyRef<number> handleSort({ sortBy, sortDir }: { sortBy: string; sortDir: SortDir }): void sortBy: ReadOnlyRef<string> sortDir: ReadOnlyRef<SortDir> viewMode: ReadOnlyRef<string> viewSize: ReadOnlyRef<number> selectedResources: Ref<Resource[]> selectedResourcesIds: Ref<string[]> isResourceInSelection(resource: Resource): boolean isSideBarOpen: Ref<boolean> sideBarActivePanel: Ref<string> } & SelectedResourcesResult & ScrollToResult export const useResourcesViewDefaults = <T extends Resource, TT, TU extends any[]>( options: ResourcesViewDefaultsOptions<TT, TU> = {} ): ResourcesViewDefaultsResult<T, TT, TU> => { const loadResourcesTask = options.loadResourcesTask || folderService.getTask() const areResourcesLoading = computed(() => { return loadResourcesTask.isRunning || !loadResourcesTask.last }) const resourcesStore = useResourcesStore() const storeItems = computed(() => resourcesStore.activeResources) as unknown as Ref<T[]> const { refresh: refreshFileListHeaderPosition, y: fileListHeaderY } = useFileListHeaderPosition() const currentRoute = useRouteName() const currentViewModeQuery = useRouteQuery( `${unref(currentRoute)}-${FolderViewModeConstants.queryName}`, FolderViewModeConstants.defaultModeName ) const currentViewMode = computed((): string => queryItemAsString(currentViewModeQuery.value)) const viewMode = useViewMode(currentViewMode) const currentTilesSizeQuery = useRouteQuery('tiles-size', '1') const currentTilesSize = computed((): string => String(currentTilesSizeQuery.value)) const viewSize = useViewSize(currentTilesSize) const sortFields = computed((): SortField[] => { if (unref(viewMode) === FolderViewModeConstants.name.tiles) { return determineResourceTilesSortFields(unref(storeItems)[0]) } return determineResourceTableSortFields(unref(storeItems)[0]) }) const { sortBy, sortDir, items, handleSort } = useSort<T>({ items: storeItems, fields: sortFields }) const { items: paginatedResources, total: paginationPages, page: paginationPage } = usePagination<T>({ items, perPageStoragePrefix: 'files' }) const accentuateItem = async (id: string) => { await nextTick() fileList.accentuateItem(id) } resourcesStore.$onAction((action) => { if (action.name === 'upsertResource') { accentuateItem(action.args[0].id) } }) return { fileListHeaderY, refreshFileListHeaderPosition, loadResourcesTask, areResourcesLoading, storeItems, sortFields, viewMode, viewSize, paginatedResources, paginationPages, paginationPage, handleSort, sortBy, sortDir, ...useSelectedResources(), ...useSideBar(), ...useScrollTo() } }
owncloud/web/packages/web-app-files/src/composables/resourcesViewDefaults/useResourcesViewDefaults.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/src/composables/resourcesViewDefaults/useResourcesViewDefaults.ts", "repo_id": "owncloud", "token_count": 1370 }
817
import { Router } from 'vue-router' import { useTask } from 'vue-concurrency' import { useRouter, useClientService, useUserStore, UserStore, SpacesStore, useSpacesStore, CapabilityStore, useCapabilityStore, useConfigStore, ConfigStore, ResourcesStore, useResourcesStore, SharesStore, useSharesStore } from '@ownclouders/web-pkg' import { unref } from 'vue' import { ClientService } from '@ownclouders/web-pkg' import { FolderLoaderSpace, FolderLoaderFavorites, FolderLoaderSharedViaLink, FolderLoaderSharedWithMe, FolderLoaderSharedWithOthers, FolderLoaderTrashbin } from './folder/index' export * from './folder/types' export type FolderLoaderTask = any export type TaskContext = { clientService: ClientService configStore: ConfigStore userStore: UserStore spacesStore: SpacesStore router: Router capabilityStore: CapabilityStore resourcesStore: ResourcesStore sharesStore: SharesStore } export interface FolderLoader { isEnabled(): boolean isActive(router: Router): boolean getTask(options: TaskContext): FolderLoaderTask } export class FolderService { private readonly loaders: FolderLoader[] constructor() { this.loaders = [ new FolderLoaderSpace(), new FolderLoaderFavorites(), new FolderLoaderSharedViaLink(), new FolderLoaderSharedWithMe(), new FolderLoaderSharedWithOthers(), new FolderLoaderTrashbin() ] } public getTask(): FolderLoaderTask { const userStore = useUserStore() const spacesStore = useSpacesStore() const capabilityStore = useCapabilityStore() const router = useRouter() const clientService = useClientService() const configStore = useConfigStore() const resourcesStore = useResourcesStore() const sharesStore = useSharesStore() const loader = this.loaders.find((l) => l.isEnabled() && l.isActive(unref(router))) if (!loader) { console.error('No folder loader found for route') return } return useTask(function* (...args) { const context = { clientService, configStore, userStore, spacesStore, capabilityStore, resourcesStore, sharesStore, router } try { yield loader.getTask(context).perform(...args) } catch (e) { console.error(e) } }) } } export const folderService = new FolderService()
owncloud/web/packages/web-app-files/src/services/folder.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/src/services/folder.ts", "repo_id": "owncloud", "token_count": 836 }
818
<template> <div class="oc-flex oc-width-1-1"> <app-loading-spinner /> </div> </template> <script lang="ts"> import { computed, defineComponent, unref } from 'vue' import { useRoute, useRouter, useSpacesStore } from '@ownclouders/web-pkg' import { AppLoadingSpinner } from '@ownclouders/web-pkg' import { urlJoin } from '@ownclouders/web-client/src/utils' import { createFileRouteOptions } from '@ownclouders/web-pkg' import { createLocationSpaces } from '@ownclouders/web-pkg' // 'personal/home' is used as personal drive alias from static contexts // (i.e. places where we can't load the actual personal space) const fakePersonalDriveAlias = 'personal/home' export default defineComponent({ name: 'DriveRedirect', components: { AppLoadingSpinner }, props: { driveAliasAndItem: { type: String, required: false, default: '' } }, setup(props) { const router = useRouter() const route = useRoute() const spacesStore = useSpacesStore() const personalSpace = computed(() => { return spacesStore.spaces.find((space) => space.driveType === 'personal') }) const itemPath = computed(() => { return props.driveAliasAndItem.startsWith(fakePersonalDriveAlias) ? urlJoin(props.driveAliasAndItem.slice(fakePersonalDriveAlias.length)) : '/' }) if (!unref(personalSpace)) { router.replace(createLocationSpaces('files-spaces-projects')) } else { const { params, query } = createFileRouteOptions(unref(personalSpace), { path: unref(itemPath) }) router .replace({ ...unref(route), params: { ...unref(route).params, ...params }, query }) // avoid NavigationDuplicated error in console .catch(() => {}) } } }) </script>
owncloud/web/packages/web-app-files/src/views/spaces/DriveRedirect.vue/0
{ "file_path": "owncloud/web/packages/web-app-files/src/views/spaces/DriveRedirect.vue", "repo_id": "owncloud", "token_count": 718 }
819
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`CreateAndUpload component > action buttons > should show and be enabled if file creation is possible 1`] = ` "<div class="create-and-upload-actions oc-flex-inline oc-mr-s"><span><button type="button" aria-label="Create new files or folders" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-primary oc-button-primary-filled" id="new-file-menu-btn"><!--v-if--> <!-- @slot Content of the button --> <oc-icon-stub name="add" filltype="fill" accessiblelabel="" type="span" size="medium" variation="passive" color=""></oc-icon-stub> <span>New</span></button></span> <oc-drop-stub dropid="new-file-menu-drop" popperoptions="[object Object]" toggle="#new-file-menu-btn" position="bottom-start" mode="click" closeonclick="true" isnested="false" paddingsize="small" class="oc-width-auto"> <oc-list-stub raw="false" id="create-list" class=""> <li class="create-list-folder oc-menu-item-hover"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw" id="new-folder-btn"> <!--v-if--> <!-- @slot Content of the button --> <resource-icon-stub resource="[object Object]" size="medium"></resource-icon-stub> <span>Folder</span> </button></li> <li class="create-list-file oc-menu-item-hover"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw"> <!--v-if--> <!-- @slot Content of the button --> <resource-icon-stub resource="[object Object]" size="medium"></resource-icon-stub> <span class="create-list-file-item-text">Plain text file</span> <!--v-if--> </button></li> <li class="create-list-file oc-menu-item-hover"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw"> <!--v-if--> <!-- @slot Content of the button --> <resource-icon-stub resource="[object Object]" size="medium"></resource-icon-stub> <span class="create-list-file-item-text">Mark-down file</span> <!--v-if--> </button></li> <li class="create-list-file oc-menu-item-hover"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw"> <!--v-if--> <!-- @slot Content of the button --> <resource-icon-stub resource="[object Object]" size="medium"></resource-icon-stub> <span class="create-list-file-item-text">Draw.io document</span> <!--v-if--> </button></li> <!--v-if--> <li class="create-list-shortcut oc-menu-item-hover"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw" id="new-shortcut-btn"> <!--v-if--> <!-- @slot Content of the button --> <oc-icon-stub name="external-link" filltype="fill" accessiblelabel="" type="span" size="medium" variation="passive" color=""></oc-icon-stub> <span>Shortcut</span> <!--v-if--> </button></li> </oc-list-stub> </oc-drop-stub> <span><button type="button" aria-label="Upload files or folders" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-outline" id="upload-menu-btn"><!--v-if--> <!-- @slot Content of the button --> <oc-icon-stub name="upload" filltype="line" accessiblelabel="" type="span" size="medium" variation="passive" color=""></oc-icon-stub> <span>Upload</span></button></span> <oc-drop-stub dropid="upload-menu-drop" popperoptions="[object Object]" toggle="#upload-menu-btn" position="bottom-start" mode="click" closeonclick="true" isnested="false" paddingsize="small" class="oc-width-auto"> <oc-list-stub raw="false" id="upload-list" class=""> <li class="oc-menu-item-hover"> <resource-upload-stub btnlabel="" btnclass="oc-width-1-1" isfolder="false"></resource-upload-stub> </li> <li class="oc-menu-item-hover"> <resource-upload-stub btnlabel="" btnclass="oc-width-1-1" isfolder="true"></resource-upload-stub> </li> </oc-list-stub> <!--v-if--> </oc-drop-stub> <!--v-if--> </div>" `; exports[`CreateAndUpload component > file handlers > should show entries for all new file handlers 1`] = ` "<div class="create-and-upload-actions oc-flex-inline oc-mr-s"><span><button type="button" aria-label="Create new files or folders" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-primary oc-button-primary-filled" id="new-file-menu-btn"><!--v-if--> <!-- @slot Content of the button --> <oc-icon-stub name="add" filltype="fill" accessiblelabel="" type="span" size="medium" variation="passive" color=""></oc-icon-stub> <span>New</span></button></span> <oc-drop-stub dropid="new-file-menu-drop" popperoptions="[object Object]" toggle="#new-file-menu-btn" position="bottom-start" mode="click" closeonclick="true" isnested="false" paddingsize="small" class="oc-width-auto"> <oc-list-stub raw="false" id="create-list" class=""> <li class="create-list-folder oc-menu-item-hover"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw" id="new-folder-btn"> <!--v-if--> <!-- @slot Content of the button --> <resource-icon-stub resource="[object Object]" size="medium"></resource-icon-stub> <span>Folder</span> </button></li> <li class="create-list-file oc-menu-item-hover"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw"> <!--v-if--> <!-- @slot Content of the button --> <resource-icon-stub resource="[object Object]" size="medium"></resource-icon-stub> <span class="create-list-file-item-text">Plain text file</span> <!--v-if--> </button></li> <li class="create-list-file oc-menu-item-hover"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw"> <!--v-if--> <!-- @slot Content of the button --> <resource-icon-stub resource="[object Object]" size="medium"></resource-icon-stub> <span class="create-list-file-item-text">Mark-down file</span> <!--v-if--> </button></li> <li class="create-list-file oc-menu-item-hover"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw"> <!--v-if--> <!-- @slot Content of the button --> <resource-icon-stub resource="[object Object]" size="medium"></resource-icon-stub> <span class="create-list-file-item-text">Draw.io document</span> <!--v-if--> </button></li> <!--v-if--> <li class="create-list-shortcut oc-menu-item-hover"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw" id="new-shortcut-btn"> <!--v-if--> <!-- @slot Content of the button --> <oc-icon-stub name="external-link" filltype="fill" accessiblelabel="" type="span" size="medium" variation="passive" color=""></oc-icon-stub> <span>Shortcut</span> <!--v-if--> </button></li> </oc-list-stub> </oc-drop-stub> <span><button type="button" aria-label="Upload files or folders" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-outline" id="upload-menu-btn"><!--v-if--> <!-- @slot Content of the button --> <oc-icon-stub name="upload" filltype="line" accessiblelabel="" type="span" size="medium" variation="passive" color=""></oc-icon-stub> <span>Upload</span></button></span> <oc-drop-stub dropid="upload-menu-drop" popperoptions="[object Object]" toggle="#upload-menu-btn" position="bottom-start" mode="click" closeonclick="true" isnested="false" paddingsize="small" class="oc-width-auto"> <oc-list-stub raw="false" id="upload-list" class=""> <li class="oc-menu-item-hover"> <resource-upload-stub btnlabel="" btnclass="oc-width-1-1" isfolder="false"></resource-upload-stub> </li> <li class="oc-menu-item-hover"> <resource-upload-stub btnlabel="" btnclass="oc-width-1-1" isfolder="true"></resource-upload-stub> </li> </oc-list-stub> <!--v-if--> </oc-drop-stub> <!--v-if--> </div>" `;
owncloud/web/packages/web-app-files/tests/unit/components/AppBar/__snapshots__/CreateAndUpload.spec.ts.snap/0
{ "file_path": "owncloud/web/packages/web-app-files/tests/unit/components/AppBar/__snapshots__/CreateAndUpload.spec.ts.snap", "repo_id": "owncloud", "token_count": 3473 }
820
import ExpirationDatepicker from 'web-app-files/src/components/SideBar/Shares/Collaborators/InviteCollaborator/ExpirationDatepicker.vue' import { ShareTypes } from '@ownclouders/web-client/src/helpers/share' import merge from 'lodash-es/merge' import { DateTime } from 'luxon' import { defaultPlugins, mount } from 'web-test-helpers' import { nextTick } from 'vue' import { useCapabilityStore } from '@ownclouders/web-pkg' const bareCapabilities = { user: { expire_date: {} }, group: { expire_date: {} } } const enabledCapabilities = merge({}, bareCapabilities, { user: { expire_date: { enabled: true, days: 1 } }, group: { expire_date: { enabled: true, days: 2 } } }) const enforcedCapabilities = merge({}, enabledCapabilities, { user: { expire_date: { enforced: true } }, group: { expire_date: { enforced: true } } }) describe('InviteCollaborator ExpirationDatepicker', () => { it('renders a button to open the datepicker and set an expiration date', () => { const { wrapper } = createWrapper({ sharingCapabilities: bareCapabilities }) expect(wrapper.find('[data-testid="recipient-datepicker-btn"]').exists()).toBe(true) }) it('does not allow to select a date from the past', () => { const { wrapper } = createWrapper({ sharingCapabilities: bareCapabilities, stubOcDatepicker: true }) const minDate = wrapper.find('[data-testid="recipient-datepicker"]').attributes()['min-date'] expect(DateTime.now().toISODate()).toBe(DateTime.fromJSDate(new Date(minDate)).toISODate()) }) it('does not set any maximum date if no user or group is selected', () => { const { wrapper } = createWrapper({ sharingCapabilities: enabledCapabilities, stubOcDatepicker: true }) const maxDate = wrapper.find('[data-testid="recipient-datepicker"]').attributes()['max-date'] expect(maxDate).toBe(undefined) }) it('pre selects and enforces the default expiration date for users', async () => { const { wrapper } = createWrapper({ sharingCapabilities: enabledCapabilities, stubOcDatepicker: true }) await wrapper.setProps({ shareTypes: [ShareTypes.user.value] }) const selectedDate = wrapper .find('[data-testid="recipient-datepicker"]') .attributes().modelvalue expect( DateTime.now().plus({ days: enabledCapabilities.user.expire_date.days }).toISODate() ).toBe(DateTime.fromJSDate(new Date(selectedDate)).toISODate()) const capabilityStore = useCapabilityStore() capabilityStore.capabilities.files_sharing = enforcedCapabilities as any await nextTick() const maxDate = wrapper.find('[data-testid="recipient-datepicker"]').attributes()['max-date'] expect( DateTime.now().plus({ days: enabledCapabilities.user.expire_date.days }).toISODate() ).toBe(DateTime.fromJSDate(new Date(maxDate)).toISODate()) }) it('pre selects and enforces the default expiration date for groups', async () => { const { wrapper } = createWrapper({ sharingCapabilities: enabledCapabilities, stubOcDatepicker: true }) await wrapper.setProps({ shareTypes: [ShareTypes.group.value] }) const selectedDate = wrapper .find('[data-testid="recipient-datepicker"]') .attributes().modelvalue expect( DateTime.now().plus({ days: enabledCapabilities.group.expire_date.days }).toISODate() ).toBe(DateTime.fromJSDate(new Date(selectedDate)).toISODate()) const capabilityStore = useCapabilityStore() capabilityStore.capabilities.files_sharing = enforcedCapabilities as any await nextTick() const maxDate = wrapper.find('[data-testid="recipient-datepicker"]').attributes()['max-date'] expect( DateTime.now().plus({ days: enabledCapabilities.group.expire_date.days }).toISODate() ).toBe(DateTime.fromJSDate(new Date(maxDate)).toISODate()) }) it('pre selects and enforces the smallest expiration date if user and group shareTypes are provided', async () => { const { wrapper } = createWrapper({ sharingCapabilities: enabledCapabilities, stubOcDatepicker: true }) await wrapper.setProps({ shareTypes: [ShareTypes.group.value, ShareTypes.user.value] }) const selectedDate = wrapper .find('[data-testid="recipient-datepicker"]') .attributes().modelvalue expect( DateTime.now().plus({ days: enabledCapabilities.user.expire_date.days }).toISODate() ).toBe(DateTime.fromJSDate(new Date(selectedDate)).toISODate()) const capabilityStore = useCapabilityStore() capabilityStore.capabilities.files_sharing = enforcedCapabilities as any await nextTick() const maxDate = wrapper.find('[data-testid="recipient-datepicker"]').attributes()['max-date'] expect( DateTime.now().plus({ days: enabledCapabilities.user.expire_date.days }).toISODate() ).toBe(DateTime.fromJSDate(new Date(maxDate)).toISODate()) }) it('emits an event if date changes', async () => { const { wrapper } = createWrapper({ sharingCapabilities: enabledCapabilities, stubOcDatepicker: true }) expect(wrapper.emitted().optionChange).toBeFalsy() const capabilityStore = useCapabilityStore() capabilityStore.capabilities.files_sharing = enabledCapabilities as any await wrapper.setProps({ shareTypes: [ShareTypes.user.value] }) await nextTick() expect(wrapper.emitted().optionChange.length).toBe(1) expect(DateTime.fromISO(wrapper.emitted().optionChange[0][0].expirationDate).toISODate()).toBe( DateTime.now().plus({ days: enabledCapabilities.user.expire_date.days }).toISODate() ) await wrapper.setProps({ shareTypes: [ShareTypes.group.value] }) await nextTick() await nextTick() expect(wrapper.emitted().optionChange.length).toBe(2) expect(DateTime.fromISO(wrapper.emitted().optionChange[1][0].expirationDate).toISODate()).toBe( DateTime.now().plus({ days: enabledCapabilities.group.expire_date.days }).toISODate() ) await wrapper.setProps({ shareTypes: [] }) await nextTick() expect(wrapper.emitted().optionChange.length).toBe(3) expect(wrapper.emitted().optionChange[2][0].expirationDate).toBe(null) const manualDate = DateTime.now().plus({ days: 5 }) wrapper.vm.dateCurrent = manualDate.toJSDate() await nextTick() expect(wrapper.emitted().optionChange.length).toBe(4) expect(DateTime.fromISO(wrapper.emitted().optionChange[3][0].expirationDate).toISODate()).toBe( manualDate.toISODate() ) wrapper.vm.dateCurrent = null await wrapper.setProps({ shareTypes: [ShareTypes.user.value, ShareTypes.group.value] }) await nextTick() expect(wrapper.emitted().optionChange.length).toBe(5) expect(DateTime.fromISO(wrapper.emitted().optionChange[4][0].expirationDate).toISODate()).toBe( DateTime.now().plus({ days: enabledCapabilities.user.expire_date.days }).toISODate() ) }) }) const createWrapper = ({ sharingCapabilities = {}, stubOcDatepicker = false } = {}) => { const capabilities = { files_sharing: sharingCapabilities } return { wrapper: mount(ExpirationDatepicker, { global: { stubs: { OcDatepicker: stubOcDatepicker }, plugins: [...defaultPlugins({ piniaOptions: { capabilityState: { capabilities } } })] } }) } }
owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/Collaborators/InviteCollaborator/ExpirationDatepicker.spec.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/Collaborators/InviteCollaborator/ExpirationDatepicker.spec.ts", "repo_id": "owncloud", "token_count": 2645 }
821
import { DateTime } from 'luxon' import FileVersions from 'web-app-files/src/components/SideBar/Versions/FileVersions.vue' import { defaultComponentMocks, defaultStubs } from 'web-test-helpers' import { mock, mockDeep } from 'vitest-mock-extended' import { Resource } from '@ownclouders/web-client' import { ShareResource, ShareSpaceResource } from '@ownclouders/web-client/src/helpers' import { DavPermission } from '@ownclouders/web-client/src/webdav/constants' import { defaultPlugins, mount, shallowMount } from 'web-test-helpers' import { useDownloadFile, useResourcesStore } from '@ownclouders/web-pkg' import { computed } from 'vue' vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({ ...(await importOriginal<any>()), useDownloadFile: vi.fn() })) const yesterday = DateTime.now().minus({ days: 1 }).toHTTP() const sevenDaysBefore = DateTime.now().minus({ days: 7 }).toHTTP() const defaultVersions = [ mock<Resource>({ name: '1625818937', size: '23', mimeType: 'text/plain', etag: '82add182994ade91e3d5bc47571ea731', mdate: yesterday, type: '' }), mock<Resource>({ name: '1625637401', size: '11', mimeType: 'text/plain', etag: '311b3319ebc7063069a15ee02b926298', mdate: sevenDaysBefore, type: '' }) ] const loadingStubSelector = 'oc-loader-stub' const versionTableStubSelector = 'oc-simple-table-stub' const selectors = { noVersionsMessage: '[data-testid="file-versions-no-versions"]', lastModifiedDate: '[data-testid="file-versions-file-last-modified-date"]', resourceSize: '[data-testid="file-versions-file-size"]', revertVersionButton: '[data-testid="file-versions-revert-button"]', downloadVersionButton: '[data-testid="file-versions-download-button"]' } describe('FileVersions', () => { describe('versions are loading', () => { const { wrapper } = getMountedWrapper({ mountType: shallowMount, loadingStateDelay: 500 }) it('should show oc loader component', () => { expect(wrapper.find(loadingStubSelector).exists()).toBeTruthy() }) it('should not show versions list', () => { expect(wrapper.find(versionTableStubSelector).exists()).toBeFalsy() }) it('should not show no versions message', () => { expect(wrapper.find(selectors.noVersionsMessage).exists()).toBeFalsy() }) }) describe('versions are loaded', () => { it('should not show oc loader component', async () => { const { wrapper } = getMountedWrapper({ mountType: shallowMount }) await wrapper.vm.fetchVersionsTask.last await wrapper.vm.$nextTick() expect(wrapper.find(loadingStubSelector).exists()).toBeFalsy() }) it('should show no versions message if there are no versions', async () => { const { wrapper } = getMountedWrapper({ mountType: shallowMount, versions: [] }) await wrapper.vm.fetchVersionsTask.last const noVersionsMessageElement = wrapper.find(selectors.noVersionsMessage) expect(noVersionsMessageElement.text()).toBe('No Versions available for this file') }) describe('when the file has versions', () => { describe('versions list', () => { it('should show last modified date of each version', async () => { const { wrapper } = getMountedWrapper({ mountType: shallowMount }) await wrapper.vm.fetchVersionsTask.last const dateElement = wrapper.findAll(selectors.lastModifiedDate) expect(dateElement.length).toBe(2) expect(dateElement.at(0).text()).toBe('1 day ago') expect(dateElement.at(1).text()).toBe('7 days ago') }) it('should show content length of each version', async () => { const { wrapper } = getMountedWrapper({ mountType: shallowMount }) await wrapper.vm.fetchVersionsTask.last const contentLengthElement = wrapper.findAll(selectors.resourceSize) expect(contentLengthElement.length).toBe(2) expect(contentLengthElement.at(0).text()).toBe('23 B') expect(contentLengthElement.at(1).text()).toBe('11 B') }) describe('row actions', () => { describe('reverting to a specific version', () => { it('should be possible for a non-share', async () => { const { wrapper } = getMountedWrapper() await wrapper.vm.fetchVersionsTask.last const revertVersionButton = wrapper.findAll(selectors.revertVersionButton) expect(revertVersionButton.length).toBe(defaultVersions.length) }) it('should be possible for a share with write permissions', async () => { const resource = mockDeep<ShareResource>({ permissions: DavPermission.Updateable }) const space = mockDeep<ShareSpaceResource>({ driveType: 'share' }) const { wrapper } = getMountedWrapper({ resource, space }) await wrapper.vm.fetchVersionsTask.last const revertVersionButton = wrapper.findAll(selectors.revertVersionButton) expect(revertVersionButton.length).toBe(defaultVersions.length) }) it('should not be possible for a share with read-only permissions', async () => { const resource = mockDeep<ShareResource>({ permissions: '' }) const space = mockDeep<ShareSpaceResource>({ driveType: 'share' }) const { wrapper } = getMountedWrapper({ resource, space }) await wrapper.vm.fetchVersionsTask.last const revertVersionButton = wrapper.findAll(selectors.revertVersionButton) expect(revertVersionButton.length).toBe(0) }) it('should call UPDATE_RESOURCE_FIELD mutation when revert button is clicked', async () => { const { wrapper } = getMountedWrapper() await wrapper.vm.fetchVersionsTask.last const revertVersionButton = wrapper.findAll(selectors.revertVersionButton) const { updateResourceField } = useResourcesStore() expect(revertVersionButton.length).toBe(defaultVersions.length) expect(updateResourceField).not.toHaveBeenCalled() await revertVersionButton.at(0).trigger('click') await wrapper.vm.$nextTick() expect(updateResourceField).toHaveBeenCalledTimes(2) }) }) it('should call downloadFile method when download version button is clicked', async () => { const { wrapper, mocks } = getMountedWrapper() await wrapper.vm.fetchVersionsTask.last const downloadVersionButton = wrapper.findAll(selectors.downloadVersionButton) expect(downloadVersionButton.length).toBe(defaultVersions.length) expect(mocks.downloadFile).not.toHaveBeenCalled() await downloadVersionButton.at(0).trigger('click') expect(mocks.downloadFile).toHaveBeenCalledTimes(1) }) }) }) }) }) }) function getMountedWrapper({ mountType = mount, space = undefined, versions = defaultVersions, resource = mock<Resource>({ id: '1', size: 0, mdate: '' }), loadingStateDelay = 0 } = {}) { const downloadFile = vi.fn() vi.mocked(useDownloadFile).mockReturnValue({ downloadFile }) const mocks = { ...defaultComponentMocks(), downloadFile } mocks.$clientService.webdav.getFileInfo.mockResolvedValue(mock<Resource>({ id: '1' })) mocks.$clientService.webdav.listFileVersions.mockImplementation(() => { if (loadingStateDelay > 0) { return new Promise((res) => setTimeout(() => res(versions), loadingStateDelay)) } return new Promise((res) => res(versions)) }) return { wrapper: mountType(FileVersions, { global: { mocks, renderStubDefaultSlot: true, provide: { space: computed(() => space), resource: computed(() => resource), ...mocks }, stubs: { ...defaultStubs, 'oc-td': true, 'oc-tr': true, 'oc-tbody': true, 'oc-table-simple': true, 'oc-resource-icon': true, OcButton: false }, plugins: [...defaultPlugins()] } }), mocks } }
owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Versions/FileVersions.spec.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Versions/FileVersions.spec.ts", "repo_id": "owncloud", "token_count": 3187 }
822
import SharedWithOthers from '../../../../src/views/shares/SharedWithOthers.vue' import { useResourcesViewDefaults } from 'web-app-files/src/composables' import { useResourcesViewDefaultsMock } from 'web-app-files/tests/mocks/useResourcesViewDefaultsMock' import { ref } from 'vue' import { defaultStubs, RouteLocation } from 'web-test-helpers' import { mock, mockDeep } from 'vitest-mock-extended' import { Resource } from '@ownclouders/web-client' import { defaultPlugins, mount, defaultComponentMocks } from 'web-test-helpers' import { ShareResource, ShareTypes } from '@ownclouders/web-client/src/helpers' import { useSortMock } from '../../../mocks/useSortMock' import { ResourceTable } from '@ownclouders/web-pkg' vi.mock('web-app-files/src/composables') vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({ ...(await importOriginal<any>()), useSort: vi.fn().mockImplementation(() => useSortMock()), queryItemAsString: vi.fn(), useRouteQuery: vi.fn(), useFileActions: vi.fn() })) describe('SharedWithOthers view', () => { it('appBar always present', () => { const { wrapper } = getMountedWrapper() expect(wrapper.find('app-bar-stub').exists()).toBeTruthy() }) it('sideBar always present', () => { const { wrapper } = getMountedWrapper() expect(wrapper.find('file-side-bar-stub').exists()).toBeTruthy() }) describe('different files view states', () => { it('shows the loading spinner during loading', () => { const { wrapper } = getMountedWrapper({ loading: true }) expect(wrapper.find('oc-spinner-stub').exists()).toBeTruthy() }) it('shows the no-content-message after loading', () => { const { wrapper } = getMountedWrapper() expect(wrapper.find('oc-spinner-stub').exists()).toBeFalsy() expect(wrapper.find('.no-content-message').exists()).toBeTruthy() }) it('shows the files table when files are available', () => { const mockedFiles = [mockDeep<Resource>(), mockDeep<Resource>()] const { wrapper } = getMountedWrapper({ files: mockedFiles }) expect(wrapper.find('.no-content-message').exists()).toBeFalsy() expect(wrapper.find('resource-table-stub').exists()).toBeTruthy() expect( wrapper.findComponent<typeof ResourceTable>('resource-table-stub').props().resources.length ).toEqual(mockedFiles.length) }) }) describe('filter', () => { describe('share type', () => { it('shows filter if multiple share types are present', () => { const { wrapper } = getMountedWrapper({ files: [ mock<ShareResource>({ shareTypes: [ShareTypes.user.value] }), mock<ShareResource>({ shareTypes: [ShareTypes.group.value] }) ] }) expect(wrapper.find('.share-type-filter').exists()).toBeTruthy() }) it('does not show filter if only one share type is present', () => { const { wrapper } = getMountedWrapper({ files: [mock<ShareResource>({ shareTypes: [ShareTypes.user.value] })] }) expect(wrapper.find('.share-type-filter').exists()).toBeFalsy() }) }) }) }) function getMountedWrapper({ mocks = {}, files = [], loading = false } = {}) { vi.mocked(useResourcesViewDefaults).mockImplementation(() => useResourcesViewDefaultsMock({ paginatedResources: ref(files), areResourcesLoading: ref(loading) }) ) const defaultMocks = { ...defaultComponentMocks({ currentRoute: mock<RouteLocation>({ name: 'files-shares-with-others' }) }), ...(mocks && mocks) } return { mocks: defaultMocks, wrapper: mount(SharedWithOthers, { global: { plugins: [...defaultPlugins()], mocks: defaultMocks, provide: defaultMocks, stubs: { ...defaultStubs, ItemFilter: true } } }) } }
owncloud/web/packages/web-app-files/tests/unit/views/shares/SharedWithOthers.spec.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/tests/unit/views/shares/SharedWithOthers.spec.ts", "repo_id": "owncloud", "token_count": 1449 }
823
export * from './useAvailableProviders'
owncloud/web/packages/web-app-search/src/composables/index.ts/0
{ "file_path": "owncloud/web/packages/web-app-search/src/composables/index.ts", "repo_id": "owncloud", "token_count": 11 }
824
{ "name": "web-app-webfinger", "version": "0.0.0", "private": true, "description": "ownCloud webfinger resolver", "license": "AGPL-3.0", "devDependencies": { "web-test-helpers": "workspace:*" }, "peerDependencies": { "@ownclouders/web-client": "workspace:*", "@ownclouders/web-pkg": "workspace:*", "design-system": "workspace:@ownclouders/design-system@*", "web-app-webfinger": "workspace:*" } }
owncloud/web/packages/web-app-webfinger/package.json/0
{ "file_path": "owncloud/web/packages/web-app-webfinger/package.json", "repo_id": "owncloud", "token_count": 184 }
825
/* tslint:disable */ /* eslint-disable */ /** * Libre Graph API * Libre Graph is a free API for cloud collaboration inspired by the MS Graph API. * * The version of the OpenAPI document: v1.0.4 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "https://ocis.ocis-traefik.latest.owncloud.works/graph".replace(/\/+$/, ""); /** * * @export */ export const COLLECTION_FORMATS = { csv: ",", ssv: " ", tsv: "\t", pipes: "|", }; /** * * @export * @interface RequestArgs */ export interface RequestArgs { url: string; options: AxiosRequestConfig; } /** * * @export * @class BaseAPI */ export class BaseAPI { protected configuration: Configuration | undefined; constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; this.basePath = configuration.basePath || this.basePath; } } }; /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { constructor(public field: string, msg?: string) { super(msg); this.name = "RequiredError" } }
owncloud/web/packages/web-client/src/generated/base.ts/0
{ "file_path": "owncloud/web/packages/web-client/src/generated/base.ts", "repo_id": "owncloud", "token_count": 545 }
826
import { extractDomSelector, extractExtensionFromFile, extractStorageId } from '../resource' import { ShareTypes } from './type' import { buildWebDavSpacesPath } from '../space' import { DriveItem, Identity, Permission, UnifiedRoleDefinition, User } from '../../generated' import { CollaboratorShare, GraphSharePermission, IncomingShareResource, LinkShare, OutgoingShareResource } from './types' import { urlJoin } from '../../utils' import { uniq } from 'lodash-es' export const getShareResourceRoles = ({ driveItem, graphRoles }: { driveItem: DriveItem graphRoles: UnifiedRoleDefinition[] }) => { return driveItem.remoteItem?.permissions.reduce<UnifiedRoleDefinition[]>((acc, permission) => { permission.roles?.forEach((roleId) => { const role = graphRoles.find(({ id }) => id === roleId) if (role && !acc.some(({ id }) => id === role.id)) { acc.push(role) } }) return acc }, []) } export const getShareResourcePermissions = ({ driveItem, shareRoles }: { driveItem: DriveItem shareRoles: UnifiedRoleDefinition[] }): GraphSharePermission[] => { if (!shareRoles.length) { // the server lists plain permissions if it doesn't find a corresponding role const permissions = driveItem.remoteItem?.permissions.reduce<GraphSharePermission[]>( (acc, permission) => { const permissions = permission['@libre.graph.permissions.actions'] as GraphSharePermission[] if (permissions) { acc.push(...permissions) } return acc }, [] ) return [...new Set(permissions)] } const permissions = shareRoles.reduce((acc, role) => { role.rolePermissions.forEach((permission) => { acc.push(...permission.allowedResourceActions) }) return acc }, []) return [...new Set(permissions)] } export function buildIncomingShareResource({ driveItem, graphRoles }: { driveItem: DriveItem graphRoles: UnifiedRoleDefinition[] }): IncomingShareResource { const resourceName = driveItem.name || driveItem.remoteItem.name const storageId = extractStorageId(driveItem.remoteItem.id) const shareTypes = uniq( driveItem.remoteItem.permissions.map((p) => p.grantedToV2.group ? ShareTypes.group.value : ShareTypes.user.value ) ) const sharedWith = driveItem.remoteItem.permissions.map(({ grantedToV2 }) => { const identity = grantedToV2.group || grantedToV2.user return { ...identity, shareType: grantedToV2.group ? ShareTypes.group.value : ShareTypes.user.value } }) const sharedBy = driveItem.remoteItem.permissions.reduce<Identity[]>((acc, permission) => { const sharedBy = permission.invitation.invitedBy.user if (!acc.some(({ id }) => id === sharedBy.id)) { acc.push(sharedBy) } return acc }, []) const shareRoles = getShareResourceRoles({ driveItem, graphRoles }) const sharePermissions = getShareResourcePermissions({ driveItem, shareRoles }) const resource: IncomingShareResource = { id: driveItem.id, shareId: driveItem.remoteItem.permissions[0].id, driveId: driveItem.parentReference?.driveId, path: '/', name: resourceName, fileId: driveItem.remoteItem.id, storageId, parentFolderId: driveItem.parentReference?.id, sdate: driveItem.lastModifiedDateTime, // FIXME: share date is missing in API indicators: [], tags: [], webDavPath: buildWebDavSpacesPath(driveItem.id, '/'), sharedBy, owner: driveItem.remoteItem.createdBy?.user, sharedWith, shareTypes, isFolder: !!driveItem.folder, type: !!driveItem.folder ? 'folder' : 'file', mimeType: driveItem.file?.mimeType || 'httpd/unix-directory', syncEnabled: driveItem['@client.synchronize'], hidden: driveItem['@UI.Hidden'], shareRoles, sharePermissions, outgoing: false, canRename: () => driveItem['@client.synchronize'], canDownload: () => sharePermissions.includes(GraphSharePermission.readBasic), canUpload: () => sharePermissions.includes(GraphSharePermission.createUpload), canCreate: () => sharePermissions.includes(GraphSharePermission.createChildren), canBeDeleted: () => sharePermissions.includes(GraphSharePermission.deleteStandard), canEditTags: () => sharePermissions.includes(GraphSharePermission.createChildren), isMounted: () => false, isReceivedShare: () => true, canShare: () => false, canDeny: () => false, getDomSelector: () => extractDomSelector(driveItem.id) } resource.extension = extractExtensionFromFile(resource) return resource } export function buildOutgoingShareResource({ driveItem, user }: { driveItem: DriveItem user: User }): OutgoingShareResource { const storageId = extractStorageId(driveItem.id) const path = urlJoin(driveItem.parentReference.path, driveItem.name) const resource: OutgoingShareResource = { id: driveItem.id, shareId: driveItem.permissions[0].id, driveId: driveItem.parentReference?.driveId, path, name: driveItem.name, fileId: driveItem.id, storageId, parentFolderId: driveItem.parentReference?.id, sdate: driveItem.lastModifiedDateTime, // FIXME: share date is missing in API indicators: [], tags: [], webDavPath: buildWebDavSpacesPath(storageId, path), sharedBy: [{ id: user.id, displayName: user.displayName }], owner: { id: user.id, displayName: user.displayName }, sharedWith: driveItem.permissions.map((p) => { if (p.link) { return { id: p.id, displayName: p.link['@libre.graph.displayName'], shareType: ShareTypes.link.value } } if (p.grantedToV2.group) { return { ...p.grantedToV2.group, shareType: ShareTypes.group.value } } return { ...p.grantedToV2.user, shareType: ShareTypes.user.value } }), shareTypes: driveItem.permissions.map((p) => { if (p.link) { return ShareTypes.link.value } if (p.grantedToV2.group) { return ShareTypes.group.value } return ShareTypes.user.value }), isFolder: !!driveItem.folder, type: !!driveItem.folder ? 'folder' : 'file', mimeType: driveItem.file?.mimeType || 'httpd/unix-directory', outgoing: true, canRename: () => true, canDownload: () => true, canUpload: () => true, canCreate: () => true, canBeDeleted: () => true, canEditTags: () => true, isMounted: () => false, isReceivedShare: () => true, canShare: () => true, canDeny: () => true, getDomSelector: () => extractDomSelector(driveItem.id) } resource.extension = extractExtensionFromFile(resource) return resource } export function buildCollaboratorShare({ graphPermission, graphRoles, resourceId, spaceId, user, indirect = false }: { graphPermission: Permission graphRoles: UnifiedRoleDefinition[] resourceId: string spaceId: string user: User indirect?: boolean }): CollaboratorShare { const role = graphRoles.find(({ id }) => id === graphPermission.roles?.[0]) const isSpace = resourceId === spaceId let shareType: number if (graphPermission.grantedToV2.group) { shareType = isSpace ? ShareTypes.spaceGroup.value : ShareTypes.group.value } else { shareType = isSpace ? ShareTypes.spaceUser.value : ShareTypes.user.value } return { id: graphPermission.id, resourceId, indirect, shareType, role, sharedBy: { id: user.id, displayName: user.displayName }, sharedWith: graphPermission.grantedToV2.user || graphPermission.grantedToV2.group, permissions: (graphPermission['@libre.graph.permissions.actions'] ? graphPermission['@libre.graph.permissions.actions'] : role.rolePermissions.flatMap((p) => p.allowedResourceActions)) as GraphSharePermission[], expirationDateTime: graphPermission.expirationDateTime } } export function buildLinkShare({ graphPermission, user, resourceId, indirect = false }: { graphPermission: Permission user: User resourceId: string indirect?: boolean }): LinkShare { return { id: graphPermission.id, resourceId, indirect, shareType: ShareTypes.link.value, sharedBy: { id: user.id, displayName: user.displayName }, hasPassword: graphPermission.hasPassword, expirationDateTime: graphPermission.expirationDateTime, displayName: graphPermission.link['@libre.graph.displayName'], isQuickLink: graphPermission.link['@libre.graph.quickLink'], type: graphPermission.link.type, webUrl: graphPermission.link.webUrl, preventsDownload: graphPermission.link.preventsDownload } }
owncloud/web/packages/web-client/src/helpers/share/functionsNG.ts/0
{ "file_path": "owncloud/web/packages/web-client/src/helpers/share/functionsNG.ts", "repo_id": "owncloud", "token_count": 3100 }
827
export * from './encodePath' export * from './urlJoin'
owncloud/web/packages/web-client/src/utils/index.ts/0
{ "file_path": "owncloud/web/packages/web-client/src/utils/index.ts", "repo_id": "owncloud", "token_count": 19 }
828
import { SpaceResource } from '../helpers' import { urlJoin } from '../utils' import { DAV } from './client' import { WebDavOptions } from './types' // eslint-disable-next-line @typescript-eslint/no-unused-vars export const GetPublicFileUrlFactory = (dav: DAV, options: WebDavOptions) => { return { getPublicFileUrl(space: SpaceResource, publicLinkToken: string): string { return dav.getFileUrl(urlJoin('public-files', publicLinkToken)) } } }
owncloud/web/packages/web-client/src/webdav/getPublicFileUrl.ts/0
{ "file_path": "owncloud/web/packages/web-client/src/webdav/getPublicFileUrl.ts", "repo_id": "owncloud", "token_count": 159 }
829
import { buildSpace, ProjectSpaceResource } from '../../../../src/helpers/space' import { mock } from 'vitest-mock-extended' import { Ability } from '@ownclouders/web-client/src/helpers/resource/types' import { Drive, User } from '@ownclouders/web-client/src/generated' describe('buildSpace', () => { const id = '1' describe('isViewer', () => { it.each([ { role: 'viewer', expectedResult: true }, { role: 'editor', expectedResult: false }, { role: 'manager', expectedResult: false } ])('returns true for a viewer of the space', (data) => { const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.role], grantedToIdentities: [{ user: { id } }] }] } }) ) as ProjectSpaceResource expect(space.isViewer(mock<User>({ id }))).toBe(data.expectedResult) }) }) describe('isEditor', () => { it.each([ { role: 'viewer', expectedResult: false }, { role: 'editor', expectedResult: true }, { role: 'manager', expectedResult: false } ])('returns true for a editor of the space', (data) => { const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.role], grantedToIdentities: [{ user: { id } }] }] } }) ) as ProjectSpaceResource expect(space.isEditor(mock<User>({ id }))).toBe(data.expectedResult) }) }) describe('isManager', () => { it.each([ { role: 'viewer', expectedResult: false }, { role: 'editor', expectedResult: false }, { role: 'manager', expectedResult: true } ])('returns true for a manager of the space', (data) => { const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.role], grantedToIdentities: [{ user: { id } }] }] } }) ) as ProjectSpaceResource expect(space.isManager(mock<User>({ id }))).toBe(data.expectedResult) }) }) it.each([ { role: 'viewer', expectedResult: false }, { role: 'editor', expectedResult: true }, { role: 'manager', expectedResult: true } ])('canUpload', (data) => { const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.role], grantedToIdentities: [{ user: { id } }] }] } }) ) as ProjectSpaceResource expect(space.canUpload({ user: mock<User>({ id }) })).toBe(data.expectedResult) }) it.each([ { userCan: false, spaceRole: 'manager', spaceDisabled: true, expectedResult: true }, { userCan: false, spaceRole: 'editor', spaceDisabled: true, expectedResult: false }, { userCan: false, spaceRole: 'viewer', spaceDisabled: true, expectedResult: false }, { userCan: true, spaceRole: 'viewer', spaceDisabled: true, expectedResult: true }, { userCan: true, spaceRole: 'viewer', spaceDisabled: false, expectedResult: false } ])('canBeDeleted', (data) => { const ability = mock<Ability>({ can: () => data.userCan }) const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.spaceRole], grantedToIdentities: [{ user: { id } }] }], ...(data.spaceDisabled && { deleted: { state: 'trashed' } }) } }) ) as ProjectSpaceResource expect(space.canBeDeleted({ user: mock<User>({ id }), ability })).toBe(data.expectedResult) }) it.each([ { spaceRole: 'manager', expectedResult: true }, { spaceRole: 'editor', expectedResult: false }, { spaceRole: 'viewer', expectedResult: false } ])('canRename', (data) => { const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.spaceRole], grantedToIdentities: [{ user: { id } }] }] } }) ) as ProjectSpaceResource expect(space.canRename({ user: mock<User>({ id }) })).toBe(data.expectedResult) }) it.each([ { spaceRole: 'manager', expectedResult: true }, { spaceRole: 'editor', expectedResult: false }, { spaceRole: 'viewer', expectedResult: false } ])('canEditDescription', (data) => { const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.spaceRole], grantedToIdentities: [{ user: { id } }] }] } }) ) as ProjectSpaceResource expect(space.canEditDescription({ user: mock<User>({ id }) })).toBe(data.expectedResult) }) it.each([ { spaceRole: 'manager', spaceDisabled: true, expectedResult: true }, { spaceRole: 'editor', spaceDisabled: true, expectedResult: false }, { spaceRole: 'viewer', spaceDisabled: true, expectedResult: false } ])('canRestore', (data) => { const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.spaceRole], grantedToIdentities: [{ user: { id } }] }], ...(data.spaceDisabled && { deleted: { state: 'trashed' } }) } }) ) as ProjectSpaceResource expect(space.canRestore({ user: mock<User>({ id }) })).toBe(data.expectedResult) }) it.each([ { userCan: false, spaceRole: 'manager', spaceDisabled: false, expectedResult: true }, { userCan: false, spaceRole: 'editor', spaceDisabled: false, expectedResult: false }, { userCan: false, spaceRole: 'viewer', spaceDisabled: false, expectedResult: false }, { userCan: true, spaceRole: 'viewer', spaceDisabled: false, expectedResult: true }, { userCan: true, spaceRole: 'viewer', spaceDisabled: true, expectedResult: false } ])('canDisable', (data) => { const ability = mock<Ability>({ can: () => data.userCan }) const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.spaceRole], grantedToIdentities: [{ user: { id } }] }], ...(data.spaceDisabled && { deleted: { state: 'trashed' } }) } }) ) as ProjectSpaceResource expect(space.canDisable({ user: mock<User>({ id }), ability })).toBe(data.expectedResult) }) it.each([ { role: 'manager', expectedResult: true }, { role: 'editor', expectedResult: false }, { role: 'viewer', expectedResult: false } ])('canShare', (data) => { const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.role], grantedToIdentities: [{ user: { id } }] }] } }) ) as ProjectSpaceResource expect(space.canShare({ user: mock<User>({ id }) })).toBe(data.expectedResult) }) it.each([ { role: 'manager', expectedResult: true }, { role: 'editor', expectedResult: true }, { role: 'viewer', expectedResult: false } ])('canEditImage', (data) => { const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.role], grantedToIdentities: [{ user: { id } }] }] } }) ) as ProjectSpaceResource expect(space.canEditImage({ user: mock<User>({ id }) })).toBe(data.expectedResult) }) it.each([ { role: 'manager', expectedResult: true }, { role: 'editor', expectedResult: true }, { role: 'viewer', expectedResult: false } ])('canEditReadme', (data) => { const space = buildSpace( mock<Drive>({ special: null, root: { permissions: [{ roles: [data.role], grantedToIdentities: [{ user: { id } }] }] } }) ) as ProjectSpaceResource expect(space.canEditReadme({ user: mock<User>({ id }) })).toBe(data.expectedResult) }) })
owncloud/web/packages/web-client/tests/unit/helpers/space/functions.spec.ts/0
{ "file_path": "owncloud/web/packages/web-client/tests/unit/helpers/space/functions.spec.ts", "repo_id": "owncloud", "token_count": 3419 }
830
export * from './composables'
owncloud/web/packages/web-pkg/src/cern/index.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/cern/index.ts", "repo_id": "owncloud", "token_count": 10 }
831
export { default as ActionMenuItem } from './ActionMenuItem.vue' export { default as ContextActionMenu } from './ContextActionMenu.vue' export { default as ContextMenuQuickAction } from './ContextMenuQuickAction.vue'
owncloud/web/packages/web-pkg/src/components/ContextActions/index.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/components/ContextActions/index.ts", "repo_id": "owncloud", "token_count": 59 }
832
export type InlineFilterOption = { name: string label: string }
owncloud/web/packages/web-pkg/src/components/Filters/types.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/components/Filters/types.ts", "repo_id": "owncloud", "token_count": 21 }
833
<template> <div class="oc-location-search oc-position-small oc-position-center-right oc-mt-rm" @click.stop> <div v-if="currentSelection"> <oc-filter-chip :is-toggle="false" :is-toggle-active="false" :filter-label="currentSelectionTitle" :selected-item-names="[]" class="oc-search-bar-filter" raw close-on-click > <template #default> <oc-button v-for="(option, index) in locationOptions" :key="index" appearance="raw" size="medium" justify-content="space-between" class="search-bar-filter-item oc-flex oc-flex-middle oc-width-1-1 oc-py-xs oc-px-s" :class="{ 'oc-mt-s': isIndexGreaterZero(index) }" :disabled="!option.enabled" :data-test-id="option.id" @click="onOptionSelected(option)" > <span>{{ option.title }}</span> <div v-if="option.id === currentSelection.id" class="oc-flex"> <oc-icon name="check" /> </div> </oc-button> </template ></oc-filter-chip> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, ref, Ref, unref, watch } from 'vue' import { useGettext } from 'vue3-gettext' import { SearchLocationFilterConstants, useRouteQuery } from '../composables' type LocationOption = { id: string title: string enabled: Ref<boolean> | boolean } export default defineComponent({ name: 'SearchBarFilter', props: { currentFolderAvailable: { type: Boolean, default: false } }, emits: ['update:modelValue'], setup(props, { emit }) { const { $gettext } = useGettext() const useScopeQueryValue = useRouteQuery('useScope') const currentSelection = ref<LocationOption>() const userSelection = ref<LocationOption>() const currentSelectionTitle = computed(() => $gettext(currentSelection.value?.title)) const locationOptions = computed<LocationOption[]>(() => [ { id: SearchLocationFilterConstants.currentFolder, title: $gettext('Current folder'), enabled: props.currentFolderAvailable }, { id: SearchLocationFilterConstants.allFiles, title: $gettext('All files'), enabled: true } ]) const isIndexGreaterZero = (index): boolean => { return parseInt(index) > 0 } watch( () => props.currentFolderAvailable, () => { if (unref(useScopeQueryValue)) { const useScope = unref(useScopeQueryValue).toString() === 'true' if (useScope) { currentSelection.value = unref(locationOptions).find( ({ id }) => id === SearchLocationFilterConstants.currentFolder ) return } currentSelection.value = unref(locationOptions).find( ({ id }) => id === SearchLocationFilterConstants.allFiles ) return } if (!props.currentFolderAvailable) { currentSelection.value = unref(locationOptions).find( ({ id }) => id === SearchLocationFilterConstants.allFiles ) return } if (unref(userSelection)) { currentSelection.value = unref(locationOptions).find( ({ id }) => id === unref(userSelection).id ) return } currentSelection.value = unref(locationOptions).find( ({ id }) => id === SearchLocationFilterConstants.allFiles ) }, { immediate: true } ) const onOptionSelected = (option: LocationOption) => { userSelection.value = option currentSelection.value = option emit('update:modelValue', { value: option }) } return { currentSelection, currentSelectionTitle, isIndexGreaterZero, onOptionSelected, locationOptions } } }) </script> <style lang="scss"> .oc-location-search { z-index: 9999; margin-right: 34px !important; float: right; .oc-drop { width: 180px; } } .search-bar-filter-item { &:hover { background-color: var(--oc-color-background-hover) !important; } } </style>
owncloud/web/packages/web-pkg/src/components/SearchBarFilter.vue/0
{ "file_path": "owncloud/web/packages/web-pkg/src/components/SearchBarFilter.vue", "repo_id": "owncloud", "token_count": 1844 }
834
<template> <quota-select id="quota-select-batch-action-form" :label="$gettext('Quota')" :total-quota="selectedOption" :max-quota="maxQuota" @selected-option-change="changeSelectedQuotaOption" /> <div v-if="warningMessage" class="oc-mt-s"> <span class="oc-text-input-warning" v-text="warningMessage" /> <oc-contextual-helper v-if="warningMessageContextualHelperData" class="oc-pl-xs" v-bind="warningMessageContextualHelperData" /> </div> </template> <script lang="ts"> import { computed, defineComponent, unref, PropType, ref, onMounted, watch } from 'vue' import { useGettext } from 'vue3-gettext' import QuotaSelect from '../QuotaSelect.vue' import { SpaceResource } from '@ownclouders/web-client/src' import { Modal, useClientService, useMessages, useSpacesStore, useCapabilityStore, useResourcesStore } from '../../composables' import { useRouter } from '../../composables/router' import { eventBus } from '../../services' import { Drive } from '@ownclouders/web-client/src/generated' import { storeToRefs } from 'pinia' export default defineComponent({ name: 'SpaceQuotaModal', components: { QuotaSelect }, props: { modal: { type: Object as PropType<Modal>, required: true }, spaces: { type: Array as PropType<SpaceResource[]>, required: true }, warningMessage: { type: String, default: '' }, warningMessageContextualHelperData: { type: Object, default: () => ({}) }, resourceType: { type: String, required: false, default: 'space', validator: (value: string) => { return ['space', 'user'].includes(value) } } }, emits: ['update:confirmDisabled'], setup(props, { emit, expose }) { const { showMessage, showErrorMessage } = useMessages() const capabilityStore = useCapabilityStore() const capabilityRefs = storeToRefs(capabilityStore) const { $gettext, $ngettext } = useGettext() const clientService = useClientService() const router = useRouter() const spacesStore = useSpacesStore() const { updateResourceField } = useResourcesStore() const selectedOption = ref(0) const getSuccessMessage = (count: number) => { if (props.resourceType === 'space') { return $ngettext( 'Space quota was changed successfully', 'Quota of %{count} spaces was changed successfully', count, { count: count.toString() } ) } if (props.resourceType === 'user') { return $ngettext( 'User quota was changed successfully', 'Quota of %{count} users was changed successfully', count, { count: count.toString() } ) } return $gettext('Quota was changed successfully') } const getErrorMessage = (count: number) => { if (props.resourceType === 'space') { return $ngettext( 'Failed to change space quota', 'Failed to change quota for %{count} spaces', count, { count: count.toString() } ) } if (props.resourceType === 'user') { return $ngettext( 'Failed to change user quota', 'Failed to change quota for %{count} users', count, { count: count.toString() } ) } return $gettext('Failed to change quota') } const confirmButtonDisabled = computed(() => { return !props.spaces.some((space) => space.spaceQuota.total !== unref(selectedOption)) }) watch( confirmButtonDisabled, () => { emit('update:confirmDisabled', unref(confirmButtonDisabled)) }, { immediate: true } ) const changeSelectedQuotaOption = (option) => { selectedOption.value = option.value } const onConfirm = async () => { const client = clientService.graphAuthenticated const requests = props.spaces.map(async (space): Promise<void> => { const { data: driveData } = await client.drives.updateDrive( space.id.toString(), { quota: { total: unref(selectedOption) } } as Drive, {} ) if (unref(router.currentRoute).name === 'admin-settings-spaces') { eventBus.publish('app.admin-settings.spaces.space.quota.updated', { spaceId: space.id, quota: driveData.quota }) } if (unref(router.currentRoute).name === 'admin-settings-users') { eventBus.publish('app.admin-settings.users.user.quota.updated', { spaceId: space.id, quota: driveData.quota }) } spacesStore.updateSpaceField({ id: space.id, field: 'spaceQuota', value: driveData.quota }) updateResourceField({ id: space.id, field: 'spaceQuota', value: driveData.quota }) }) const results = await Promise.allSettled<Array<unknown>>(requests) const succeeded = results.filter((r) => r.status === 'fulfilled') if (succeeded.length) { showMessage({ title: getSuccessMessage(succeeded.length) }) } const errors = results.filter((r) => r.status === 'rejected') if (errors.length) { console.error(errors) errors.forEach(console.error) showErrorMessage({ title: getErrorMessage(errors.length), errors: (errors as PromiseRejectedResult[]).map((f) => f.reason) }) } } expose({ onConfirm }) onMounted(() => { selectedOption.value = props.spaces[0]?.spaceQuota?.total || 0 }) return { selectedOption, confirmButtonDisabled, changeSelectedQuotaOption, maxQuota: capabilityRefs.spacesMaxQuota, // unit tests onConfirm } } }) </script>
owncloud/web/packages/web-pkg/src/components/Spaces/QuotaModal.vue/0
{ "file_path": "owncloud/web/packages/web-pkg/src/components/Spaces/QuotaModal.vue", "repo_id": "owncloud", "token_count": 2394 }
835
import { useFileActionsDeleteResources } from '../helpers' import { isLocationPublicActive, isLocationSpacesActive, isLocationTrashActive, isLocationCommonActive } from '../../../router' import { isProjectSpaceResource } from '@ownclouders/web-client/src/helpers' import { useRouter } from '../../router' import { useGettext } from 'vue3-gettext' import { FileAction, FileActionOptions } from '../types' import { computed } from 'vue' import { useUserStore, useCapabilityStore } from '../../piniaStores' export const useFileActionsDelete = () => { const userStore = useUserStore() const capabilityStore = useCapabilityStore() const router = useRouter() const { displayDialog, filesList_delete } = useFileActionsDeleteResources() const { $gettext } = useGettext() const handler = ({ space, resources, deletePermanent }: FileActionOptions & { deletePermanent: boolean }) => { if (isLocationCommonActive(router, 'files-common-search')) { resources = resources.filter( (r) => r.canBeDeleted() && !r.isShareRoot() && !isProjectSpaceResource(r) ) } if (deletePermanent) { displayDialog(space, resources) return } filesList_delete(resources) } const actions = computed((): FileAction[] => [ { name: 'delete', icon: 'delete-bin-5', label: () => $gettext('Delete'), handler: ({ space, resources }) => handler({ space, resources, deletePermanent: false }), isVisible: ({ space, resources }) => { if ( !isLocationSpacesActive(router, 'files-spaces-generic') && !isLocationPublicActive(router, 'files-public-link') && !isLocationCommonActive(router, 'files-common-search') ) { return false } if (resources.length === 0) { return false } if ( isLocationSpacesActive(router, 'files-spaces-generic') && space?.driveType === 'share' && resources[0].path === '/' ) { return false } if (resources.length === 1 && resources[0].locked) { return false } if (isLocationCommonActive(router, 'files-common-search')) { return resources.some( (r) => r.canBeDeleted() && !r.isShareRoot() && !isProjectSpaceResource(r) ) } const deleteDisabled = resources.some((resource) => { return !resource.canBeDeleted() }) return !deleteDisabled }, componentType: 'button', class: 'oc-files-actions-delete-trigger' }, { // this menu item is ONLY for the trashbin (permanently delete a file/folder) name: 'delete-permanent', icon: 'delete-bin-5', label: () => $gettext('Delete'), handler: ({ space, resources }) => handler({ space, resources, deletePermanent: true }), isVisible: ({ space, resources }) => { if (!isLocationTrashActive(router, 'files-trash-generic')) { return false } if (!capabilityStore.filesPermanentDeletion) { return false } if ( isProjectSpaceResource(space) && !space.canRemoveFromTrashbin({ user: userStore.user }) ) { return false } return resources.length > 0 }, componentType: 'button', class: 'oc-files-actions-delete-permanent-trigger' } ]) return { actions } }
owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsDelete.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsDelete.ts", "repo_id": "owncloud", "token_count": 1408 }
836
import { isLocationTrashActive } from '../../../router' import { eventBus } from '../../../services/eventBus' import { SideBarEventTopics } from '../../sideBar' import { computed, unref } from 'vue' import { useGettext } from 'vue3-gettext' import { useIsFilesAppActive } from '../helpers' import { useRouter } from '../../router' import { FileAction } from '../types' import { useResourcesStore } from '../../piniaStores' export const useFileActionsShowDetails = () => { const router = useRouter() const resourcesStore = useResourcesStore() const { $gettext } = useGettext() const isFilesAppActive = useIsFilesAppActive() const actions = computed((): FileAction[] => [ { name: 'show-details', icon: 'information', componentType: 'button', class: 'oc-files-actions-show-details-trigger', label: () => $gettext('Details'), // we don't have details in the trashbin, yet. // remove trashbin route rule once we have them. isVisible: ({ resources }) => { // sidebar is currently only available inside files app if (!unref(isFilesAppActive)) { return false } if (isLocationTrashActive(router, 'files-trash-generic')) { return false } return resources.length > 0 }, handler({ resources }) { resourcesStore.setSelection(resources.map(({ id }) => id)) eventBus.publish(SideBarEventTopics.open) } } ]) return { actions } }
owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsShowDetails.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsShowDetails.ts", "repo_id": "owncloud", "token_count": 549 }
837
import { unref, computed } from 'vue' import { useGettext } from 'vue3-gettext' import { useSpaceHelpers } from '../../spaces' import { useClientService } from '../../clientService' import { useAbility } from '../../ability' import { useRoute } from '../../router' import { SpaceAction, SpaceActionOptions } from '../types' import { SpaceResource } from '@ownclouders/web-client' import { useMessages, useModals, useSpacesStore, useUserStore } from '../../piniaStores' export const useSpaceActionsRename = () => { const { showMessage, showErrorMessage } = useMessages() const userStore = useUserStore() const { $gettext } = useGettext() const ability = useAbility() const clientService = useClientService() const route = useRoute() const { checkSpaceNameModalInput } = useSpaceHelpers() const { dispatchModal } = useModals() const spacesStore = useSpacesStore() const renameSpace = (space: SpaceResource, name: string) => { const graphClient = clientService.graphAuthenticated return graphClient.drives .updateDrive(space.id, { name }, {}) .then(() => { if (unref(route).name === 'admin-settings-spaces') { space.name = name } spacesStore.updateSpaceField({ id: space.id, field: 'name', value: name }) showMessage({ title: $gettext('Space name was changed successfully') }) }) .catch((error) => { console.error(error) showErrorMessage({ title: $gettext('Failed to rename space'), errors: [error] }) }) } const handler = ({ resources }: SpaceActionOptions) => { if (resources.length !== 1) { return } dispatchModal({ title: $gettext('Rename space') + ' ' + resources[0].name, confirmText: $gettext('Rename'), hasInput: true, inputLabel: $gettext('Space name'), inputValue: resources[0].name, onConfirm: (name: string) => renameSpace(resources[0], name), onInput: checkSpaceNameModalInput }) } const actions = computed((): SpaceAction[] => [ { name: 'rename', icon: 'pencil', label: () => { return $gettext('Rename') }, handler, isVisible: ({ resources }) => { if (resources.length !== 1) { return false } return resources[0].canRename({ user: userStore.user, ability }) }, componentType: 'button', class: 'oc-files-actions-rename-trigger' } ]) return { actions, // HACK: exported for unit tests: renameSpace } }
owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsRename.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsRename.ts", "repo_id": "owncloud", "token_count": 969 }
838
import { Ref, ref, unref } from 'vue' import { RouteLocation, Router, RouteParams } from 'vue-router' import { MaybeRef } from '../../utils' import { FileContext } from './types' import { LocationQuery } from '../router' import { Resource } from '@ownclouders/web-client' import { useFileRouteReplace } from '../router/useFileRouteReplace' interface AppNavigationOptions { router: Router currentFileContext: MaybeRef<FileContext> } export interface AppNavigationResult { closeApp(): void replaceInvalidFileRoute(context: MaybeRef<FileContext>, resource: Resource): boolean closed: Ref<boolean> } export const contextRouteNameKey = 'contextRouteName' const contextRouteParamsKey = 'contextRouteParams' const contextRouteQueryKey = 'contextRouteQuery' /* vue-router type bindings do not allow nested objects because they are not handled by default. We override parseQuery and stringifyQuery and handle it there. That's why we have types that match the router types and break them here once on purpose in encapsulated functions */ export const routeToContextQuery = (location: RouteLocation): LocationQuery => { const { params, query } = location const contextQuery = {} const contextQueryItems = ['fileId', 'shareId'].concat( (location as any).meta?.contextQueryItems || [] ) as string[] for (const queryItem of contextQueryItems) { contextQuery[queryItem] = query[queryItem] } return { [contextRouteNameKey]: location.name, [contextRouteParamsKey]: params, [contextRouteQueryKey]: contextQuery } as any } export const contextQueryToFileContextProps = ( query: LocationQuery ): { routeName: string; routeParams: RouteParams; routeQuery: LocationQuery } => { return { routeName: queryItemAsString(query[contextRouteNameKey]), routeParams: query[contextRouteParamsKey] as any, routeQuery: query[contextRouteQueryKey] as any } } export const queryItemAsString = ( queryItem: string | number | Exclude<string | number, null | undefined>[] ): string => { if (Array.isArray(queryItem)) { return queryItem[0].toString() } return queryItem?.toString() } export function useAppNavigation({ router, currentFileContext }: AppNavigationOptions): AppNavigationResult { const navigateToContext = (context: MaybeRef<FileContext>) => { const { fileName, routeName, routeParams, routeQuery } = unref(context) if (!unref(routeName)) { return router.push({ path: '/' }) } return router.push({ name: unref(routeName), params: unref(routeParams), query: { ...unref(routeQuery), scrollTo: unref(fileName) } }) } const { replaceInvalidFileRoute: replaceInvalidFileRouteGeneric } = useFileRouteReplace({ router }) const replaceInvalidFileRoute = (context: MaybeRef<FileContext>, resource: Resource) => { const ctx = unref(context) return replaceInvalidFileRouteGeneric({ space: unref(ctx.space), resource, path: unref(ctx.item), fileId: unref(ctx.itemId) }) } const closed = ref(false) const closeApp = () => { closed.value = true return navigateToContext(currentFileContext) } return { replaceInvalidFileRoute, closeApp, closed } }
owncloud/web/packages/web-pkg/src/composables/appDefaults/useAppNavigation.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/appDefaults/useAppNavigation.ts", "repo_id": "owncloud", "token_count": 1048 }
839
import { computed, Ref, ref, unref, watch } from 'vue' import { buildShareSpaceResource, SpaceResource } from '@ownclouders/web-client/src/helpers' import { useRouteQuery } from '../router' import { useSpacesLoading } from './useSpacesLoading' import { queryItemAsString } from '../appDefaults' import { urlJoin } from '@ownclouders/web-client/src/utils' import { useClientService } from '../clientService' import { useSpacesStore, useConfigStore } from '../piniaStores' import { onUnmounted } from 'vue' interface DriveResolverOptions { driveAliasAndItem?: Ref<string> } interface DriveResolverResult { space: Ref<SpaceResource> item: Ref<string> itemId: Ref<string> loading: Ref<boolean> } export const useDriveResolver = (options: DriveResolverOptions = {}): DriveResolverResult => { const spacesStore = useSpacesStore() const { areSpacesLoading } = useSpacesLoading() const shareId = useRouteQuery('shareId') const fileIdQueryItem = useRouteQuery('fileId') const fileId = computed(() => { return queryItemAsString(unref(fileIdQueryItem)) }) const configStore = useConfigStore() const clientService = useClientService() const spaces = computed(() => spacesStore.spaces) const space = ref<SpaceResource>(null) const item: Ref<string> = ref(null) const loading = ref(false) const getSpaceByDriveAliasAndItem = (driveAliasAndItem: string) => { const driveAliasAndItemSegments = driveAliasAndItem.split('/') return unref(spaces).find((s) => { if (!driveAliasAndItem.startsWith(s.driveAlias)) { return false } const driveAliasSegments = s.driveAlias.split('/') if ( driveAliasAndItemSegments.length < driveAliasSegments.length || driveAliasAndItemSegments.slice(0, driveAliasSegments.length).join('/') !== s.driveAlias ) { return false } return s }) } // clean up global state as the watchers aren't triggered anymore when navigating away onUnmounted(() => { const driveAliasAndItem = unref(options.driveAliasAndItem) if (!driveAliasAndItem?.startsWith('personal/') && !driveAliasAndItem?.startsWith('project/')) { spacesStore.setCurrentSpace(null) } }) watch( [options.driveAliasAndItem, areSpacesLoading], async ([driveAliasAndItem, areSpacesLoading], [driveAliasAndItemOld, areSpacesLoadingOld]) => { if (driveAliasAndItem === driveAliasAndItemOld && areSpacesLoading === areSpacesLoadingOld) { return } if (!driveAliasAndItem || driveAliasAndItem.startsWith('virtual/')) { space.value = null item.value = null return } const isOnlyItemPathChanged = unref(space) && driveAliasAndItem.startsWith(unref(space).driveAlias) if (isOnlyItemPathChanged) { item.value = urlJoin(driveAliasAndItem.slice(unref(space).driveAlias.length), { leadingSlash: true }) return } let matchingSpace = null let path = null if (driveAliasAndItem.startsWith('public/') || driveAliasAndItem.startsWith('ocm/')) { const [publicLinkToken, ...item] = driveAliasAndItem.split('/').slice(1) matchingSpace = unref(spaces).find((s) => s.id === publicLinkToken) path = item.join('/') } else if ( driveAliasAndItem.startsWith('share/') || driveAliasAndItem.startsWith('ocm-share/') ) { const [shareName, ...item] = driveAliasAndItem.split('/').slice(1) const driveAliasPrefix = driveAliasAndItem.startsWith('ocm-share/') ? 'ocm-share' : 'share' matchingSpace = buildShareSpaceResource({ driveAliasPrefix, shareId: queryItemAsString(unref(shareId)), shareName: unref(shareName), serverUrl: configStore.serverUrl }) path = item.join('/') } else { if (unref(fileId)) { matchingSpace = unref(spaces).find((s) => { return unref(fileId).startsWith(`${s.fileId}`) }) } else { matchingSpace = getSpaceByDriveAliasAndItem(driveAliasAndItem) } if (!matchingSpace) { if ( !spacesStore.mountPointsInitialized && configStore.options.routing.fullShareOwnerPaths ) { loading.value = true await spacesStore.loadMountPoints({ graphClient: clientService.graphAuthenticated }) } matchingSpace = getSpaceByDriveAliasAndItem(driveAliasAndItem) } if (matchingSpace) { path = driveAliasAndItem.slice(matchingSpace.driveAlias.length) } } space.value = matchingSpace item.value = urlJoin(path, { leadingSlash: true }) loading.value = false }, { immediate: true, deep: true } ) watch( space, (s: SpaceResource) => { spacesStore.setCurrentSpace(s) if (!s || ['public', 'share', 'personal', 'mountpoint'].includes(s.driveType)) { return } // FIXME: move loading to FileSideBar.vue spacesStore.loadSpaceMembers({ graphClient: clientService.graphAuthenticated, space: s }) }, { immediate: true } ) return { space, item, itemId: fileId, loading } }
owncloud/web/packages/web-pkg/src/composables/driveResolver/useDriveResolver.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/driveResolver/useDriveResolver.ts", "repo_id": "owncloud", "token_count": 2062 }
840
import { computed } from 'vue' import { getExpirationRules } from '../../helpers' import { useGettext } from 'vue3-gettext' import { useCapabilityStore } from '../piniaStores' export const useExpirationRules = () => { const capabilityStore = useCapabilityStore() const { current: currentLanguage } = useGettext() const expirationRules = computed(() => getExpirationRules({ capabilityStore, currentLanguage })) return { expirationRules } }
owncloud/web/packages/web-pkg/src/composables/links/useExpirationRules.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/links/useExpirationRules.ts", "repo_id": "owncloud", "token_count": 125 }
841
export * from './config' export * from './types'
owncloud/web/packages/web-pkg/src/composables/piniaStores/config/index.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/config/index.ts", "repo_id": "owncloud", "token_count": 16 }
842
export * from './usePreviewService'
owncloud/web/packages/web-pkg/src/composables/previewService/index.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/previewService/index.ts", "repo_id": "owncloud", "token_count": 10 }
843
import { Router } from 'vue-router' import { useService } from '../service' export const useRouter = (): Router => { return useService('$router') }
owncloud/web/packages/web-pkg/src/composables/router/useRouter.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/router/useRouter.ts", "repo_id": "owncloud", "token_count": 49 }
844
export * from './useSort' export * from './constants'
owncloud/web/packages/web-pkg/src/composables/sort/index.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/sort/index.ts", "repo_id": "owncloud", "token_count": 18 }
845
import { eventBus } from '../services' import { RouteLocation } from 'vue-router' import omit from 'lodash-es/omit' import { BreadcrumbItem } from 'design-system/src/components/OcBreadcrumb/types' import { v4 as uuidv4 } from 'uuid' export const breadcrumbsFromPath = ( currentRoute: RouteLocation, resourcePath: string ): BreadcrumbItem[] => { const pathSplit = (p = '') => p.split('/').filter(Boolean) const current = pathSplit(currentRoute.path) const resource = pathSplit(resourcePath) return resource.map( (text, i) => ({ id: uuidv4(), allowContextActions: true, text, to: { path: '/' + [...current].splice(0, current.length - resource.length + i + 1).join('/'), query: omit(currentRoute.query, 'fileId', 'page') // TODO: we need the correct fileId in the query. until we have that we must omit it because otherwise we would correct the path to the one of the (wrong) fileId. }, isStaticNav: false }) as BreadcrumbItem ) } export const concatBreadcrumbs = (...items: BreadcrumbItem[]): BreadcrumbItem[] => { const last = items.pop() return [ ...items, { id: uuidv4(), allowContextActions: last.allowContextActions, text: last.text, onClick: () => eventBus.publish('app.files.list.load'), isTruncationPlaceholder: last.isTruncationPlaceholder, isStaticNav: last.isStaticNav } ] }
owncloud/web/packages/web-pkg/src/helpers/breadcrumbs.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/helpers/breadcrumbs.ts", "repo_id": "owncloud", "token_count": 552 }
846
import { dirname } from 'path' import { extractNameWithoutExtension, Resource, SpaceResource } from '@ownclouders/web-client/src/helpers' export const resolveFileNameDuplicate = ( name: string, extension: string, existingResources: Resource[], iteration = 1 ) => { let potentialName if (!extension) { potentialName = `${name} (${iteration})` } else { const nameWithoutExtension = extractNameWithoutExtension({ name, extension } as Resource) potentialName = `${nameWithoutExtension} (${iteration}).${extension}` } const hasConflict = existingResources.some((f) => f.name === potentialName) if (!hasConflict) { return potentialName } return resolveFileNameDuplicate(name, extension, existingResources, iteration + 1) } export const isResourceBeeingMovedToSameLocation = ( sourceSpace: SpaceResource, resource: Resource, targetSpace: SpaceResource, targetFolder: Resource ) => { return sourceSpace.id === targetSpace.id && dirname(resource.path) === targetFolder.path }
owncloud/web/packages/web-pkg/src/helpers/resource/conflictHandling/conflictUtils.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/helpers/resource/conflictHandling/conflictUtils.ts", "repo_id": "owncloud", "token_count": 312 }
847
import { ShareTypes } from '@ownclouders/web-client/src/helpers/share' import { eventBus } from '../services' import { SideBarEventTopics } from '../composables/sideBar' import { createLocationShares } from '../router' import { Resource } from '@ownclouders/web-client' import { AncestorMetaData } from '../types' // dummy to trick gettext string extraction into recognizing strings const $gettext = (str) => { return str } const isUserShare = (shareTypes) => { return ShareTypes.containsAnyValue(ShareTypes.authenticated, shareTypes ?? []) } const isLinkShare = (shareTypes) => { return ShareTypes.containsAnyValue(ShareTypes.unauthenticated, shareTypes ?? []) } const shareUserIconDescribedBy = ({ isDirect }) => { return isDirect ? $gettext('This item is directly shared with others.') : $gettext('This item is shared with others through one of the parent folders.') } const shareLinkDescribedBy = ({ isDirect }) => { return isDirect ? $gettext('This item is directly shared via links.') : $gettext('This item is shared via links through one of the parent folders.') } const getUserIndicator = ({ resource, isDirect, isIncoming = false }) => { return { id: `files-sharing-${resource.getDomSelector()}`, accessibleDescription: shareUserIconDescribedBy({ isDirect }), label: isIncoming ? $gettext('Shared with you') : $gettext('Show invited people'), icon: 'group', target: 'sharing', category: 'sharing', type: isDirect ? 'user-direct' : 'user-indirect', fillType: 'line', handler: (resource, panel, $router) => { if (isIncoming) { $router.push(createLocationShares('files-shares-with-me')) return } eventBus.publish(SideBarEventTopics.openWithPanel, `${panel}#peopleShares`) } } } const getLinkIndicator = ({ resource, isDirect }) => { return { id: `file-link-${resource.getDomSelector()}`, accessibleDescription: shareLinkDescribedBy({ isDirect }), label: $gettext('Show links'), icon: 'link', target: 'sharing', category: 'sharing', type: isDirect ? 'link-direct' : 'link-indirect', fillType: 'line', handler: (resource, panel) => { eventBus.publish(SideBarEventTopics.openWithPanel, `${panel}#linkShares`) } } } const getLockedIndicator = ({ resource }) => { return { id: `resource-locked-${resource.getDomSelector()}`, accessibleDescription: $gettext('Item locked'), label: $gettext('This item is locked'), icon: 'lock', category: 'system', type: 'resource-locked', fillType: 'line' } } const getProcessingIndicator = ({ resource }) => { return { id: `resource-processing-${resource.getDomSelector()}`, accessibleDescription: $gettext('Item in processing'), label: $gettext('This item is in processing'), icon: 'loop-right', category: 'system', type: 'resource-processing', fillType: 'line' } } export const getIndicators = ({ resource, ancestorMetaData }: { resource: Resource ancestorMetaData: AncestorMetaData }) => { const indicators = [] if (resource.locked) { indicators.push(getLockedIndicator({ resource })) } if (resource.processing) { indicators.push(getProcessingIndicator({ resource })) } const parentShareTypes = Object.values(ancestorMetaData).reduce((acc: any, data: any) => { acc.push(...(data.shareTypes || [])) return acc }, []) const isDirectUserShare = isUserShare(resource.shareTypes) if (isDirectUserShare || isUserShare(parentShareTypes)) { indicators.push(getUserIndicator({ resource, isDirect: isDirectUserShare })) } else if (resource.isReceivedShare()) { indicators.push(getUserIndicator({ resource, isDirect: false, isIncoming: true })) } const isDirectLinkShare = isLinkShare(resource.shareTypes) if (isDirectLinkShare || isLinkShare(parentShareTypes)) { indicators.push(getLinkIndicator({ resource, isDirect: isDirectLinkShare })) } return indicators }
owncloud/web/packages/web-pkg/src/helpers/statusIndicators.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/helpers/statusIndicators.ts", "repo_id": "owncloud", "token_count": 1335 }
848
import { RouteLocationNamedRaw, RouteRecordRaw } from 'vue-router' import { RouteComponents } from './router' import { createLocation, isLocationActiveDirector, $gettext } from './utils' type spaceTypes = 'files-spaces-projects' | 'files-spaces-generic' export const createLocationSpaces = (name: spaceTypes, location = {}): RouteLocationNamedRaw => createLocation(name, location) export const locationSpacesProjects = createLocationSpaces('files-spaces-projects') export const locationSpacesGeneric = createLocationSpaces('files-spaces-generic') // FIXME: `isLocationSpacesActive('files-spaces-generic') returns true for 'files-spaces-projects' as well // TODO: if that's fixed, adjust the `loaderSpaceGeneric#isActive` and `loaderShare#isActive` export const isLocationSpacesActive = isLocationActiveDirector<spaceTypes>( locationSpacesProjects, locationSpacesGeneric ) export const buildRoutes = (components: RouteComponents): RouteRecordRaw[] => [ { path: '/spaces', component: components.App, children: [ { path: 'projects', name: locationSpacesProjects.name, component: components.Spaces.Projects, meta: { authContext: 'user', title: $gettext('Spaces') } }, { path: ':driveAliasAndItem(.*)?', name: locationSpacesGeneric.name, component: components.Spaces.DriveResolver, meta: { authContext: 'user', patchCleanPath: true, contextQueryItems: ['sort-by', 'sort-dir'] } } ] } ]
owncloud/web/packages/web-pkg/src/router/spaces.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/router/spaces.ts", "repo_id": "owncloud", "token_count": 574 }
849
import { Resource, SpaceResource } from '@ownclouders/web-client' import { z } from 'zod' export const ProcessorType = z.enum(['fit', 'resize', 'fill', 'thumbnail']) export type ProcessorType = z.infer<typeof ProcessorType> export interface BuildQueryStringOptions { preview?: number scalingup?: number a?: number etag?: string dimensions?: [number, number] processor?: ProcessorType } export interface LoadPreviewOptions { space: SpaceResource resource: Resource dimensions?: [number, number] processor?: ProcessorType }
owncloud/web/packages/web-pkg/src/services/preview/types.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/services/preview/types.ts", "repo_id": "owncloud", "token_count": 156 }
850
import ErrorScreen from '../../../../src/components/AppTemplates/PartialViews/ErrorScreen.vue' import { defaultPlugins, mount } from 'web-test-helpers' describe('The external app error screen component', () => { test('displays an icon and a paragraph', () => { const wrapper = mount(ErrorScreen, { props: { message: 'Error when loading the application' }, global: { stubs: { OcIcon: true }, plugins: [...defaultPlugins()] } }) expect(wrapper.html()).toMatchSnapshot() }) })
owncloud/web/packages/web-pkg/tests/unit/components/AppTemplates/ErrorScreen.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/AppTemplates/ErrorScreen.spec.ts", "repo_id": "owncloud", "token_count": 219 }
851
import { shallowMount } from 'web-test-helpers' import Name from '../../../../src/components/FilesList/ResourceName.vue' const fullPath = 'images/nature/forest.jpg' const name = 'forest.jpg' const extension = 'jpg' const type = 'file' describe('OcResourceName', () => { it("doesn't add extension to hidden folder", () => { const wrapper = shallowMount(Name, { props: { fullPath: '.hidden', name: '.hidden', extension: '', type: 'folder' } }) expect(wrapper.find('.oc-resource-basename').text()).toMatch('.hidden') expect(wrapper.find('.oc-resource-extension').exists()).toBeFalsy() expect(wrapper.html()).toMatchSnapshot() }) it('renders folder names with dots completely in the basename', () => { const wrapper = shallowMount(Name, { props: { fullPath: 'folder.with.dots', name: 'folder.with.dots', extension: '', type: 'folder' } }) expect(wrapper.find('.oc-resource-basename').text()).toMatch('folder.with.dots') expect(wrapper.find('.oc-resource-extension').exists()).toBeFalsy() expect(wrapper.html()).toMatchSnapshot() }) it('has properties for resource path, name and type', () => { const wrapper = shallowMount(Name, { props: { fullPath, name, extension, type } }) const node = wrapper.find('.oc-resource-name') expect(node.attributes('data-test-resource-type')).toMatch(type) expect(node.attributes('data-test-resource-name')).toMatch(name) expect(node.attributes('data-test-resource-path')).toMatch('/' + name) }) it('truncates very long name per default', () => { const wrapper = shallowMount(Name, { props: { fullPath: 'super-long-file-name-which-will-be-truncated-when-exceeding-the-screen-space-while-still-preserving-the-file-extension-at-the-end.txt', name: '.super-long-file-name-which-will-be-truncated-when-exceeding-the-screen-space-while-still-preserving-the-file-extension-at-the-end.txt', extension: 'txt', type: 'file' } }) expect(wrapper.html()).toMatchSnapshot() }) it('does not truncate a very long name when disabled', () => { const wrapper = shallowMount(Name, { props: { fullPath: 'super-long-file-name-which-will-be-truncated-when-exceeding-the-screen-space-while-still-preserving-the-file-extension-at-the-end.txt', name: '.super-long-file-name-which-will-be-truncated-when-exceeding-the-screen-space-while-still-preserving-the-file-extension-at-the-end.txt', extension: 'txt', type: 'file', truncateName: false } }) expect(wrapper.html()).toMatchSnapshot() }) it('shows the name as HTML title if the path is not displayed', () => { const wrapper = shallowMount(Name, { props: { fullPath: 'folder', name: 'folder', extension: '', type: 'folder', isPathDisplayed: false } }) expect(wrapper.html()).toMatchSnapshot() }) it('does not show the name as HTML title if the path is being displayed', () => { const wrapper = shallowMount(Name, { props: { fullPath: 'folder', name: 'folder', extension: '', type: 'folder', isPathDisplayed: true } }) expect(wrapper.html()).toMatchSnapshot() }) })
owncloud/web/packages/web-pkg/tests/unit/components/FilesList/ResourceName.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/FilesList/ResourceName.spec.ts", "repo_id": "owncloud", "token_count": 1409 }
852
import NoContentMessage from '../../../src/components/NoContentMessage.vue' import { defaultPlugins, shallowMount } from 'web-test-helpers' describe('NoContentMessage', () => { describe('icon prop', () => { it('should render the provided icon', () => { const { wrapper } = getWrapper() const iconEl = wrapper.find('oc-icon-stub') expect(iconEl.exists()).toBeTruthy() expect(iconEl.attributes().name).toBe('mdi-test-icon') }) }) describe('named slots', () => { it('should render slot html for message', () => { const { wrapper } = getWrapper({ message: ` <p class="test message">This is a test message</p> ` }) const messageDiv = wrapper.findAll('.oc-text-muted').at(0) const slotEl = messageDiv.find('p') expect(messageDiv.exists()).toBeTruthy() expect(slotEl.exists()).toBeTruthy() expect(slotEl.attributes().class).toBe('test message') expect(slotEl.text()).toBe('This is a test message') }) it('should render slot html for callToAction', () => { const { wrapper } = getWrapper({ callToAction: ` <button class="test action">Click here</button> ` }) const actionDiv = wrapper.findAll('.oc-text-muted').at(1) const slotEl = actionDiv.find('button') expect(slotEl.exists()).toBeTruthy() expect(slotEl.attributes().class).toBe('test action') expect(slotEl.text()).toBe('Click here') }) }) }) function getWrapper(slots = {}) { return { wrapper: shallowMount(NoContentMessage, { slots: slots, props: { icon: 'mdi-test-icon' }, global: { plugins: [...defaultPlugins()] } }) } }
owncloud/web/packages/web-pkg/tests/unit/components/NoContentMessage.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/NoContentMessage.spec.ts", "repo_id": "owncloud", "token_count": 695 }
853
import SpaceDetailsMultiple from '../../../../../../src/components/SideBar/Spaces/Details/SpaceDetailsMultiple.vue' import { defaultPlugins, shallowMount } from 'web-test-helpers' const spaceMock = { type: 'space', name: ' space', id: '1', mdate: 'Wed, 21 Oct 2015 07:28:00 GMT', spaceQuota: { used: 100, total: 1000, remaining: 900 } } describe('Multiple Details SideBar Panel', () => { it('displays the details side panel', () => { const { wrapper } = createWrapper(spaceMock) expect(wrapper.html()).toMatchSnapshot() }) }) function createWrapper(spaceResource) { return { wrapper: shallowMount(SpaceDetailsMultiple, { global: { plugins: [...defaultPlugins()] }, props: { selectedSpaces: [spaceResource] } }) } }
owncloud/web/packages/web-pkg/tests/unit/components/sidebar/Spaces/Details/SpaceDetailsMultiple.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/sidebar/Spaces/Details/SpaceDetailsMultiple.spec.ts", "repo_id": "owncloud", "token_count": 304 }
854
import { mock } from 'vitest-mock-extended' import { ref, unref } from 'vue' import { defaultComponentMocks, RouteLocation, getComposableWrapper } from 'web-test-helpers' import { useFileActionsOpenShortcut, useRoute } from '../../../../../src' import { Resource } from '@ownclouders/web-client' import { GetFileContentsResponse } from '@ownclouders/web-client/src/webdav/getFileContents' vi.mock('../../../../../src/composables/router', async (importOriginal) => ({ ...(await importOriginal<any>()), useRoute: vi.fn() })) window = Object.create(window) Object.defineProperty(window, 'location', { value: { href: 'https://demo.owncloud.com' }, writable: true }) Object.defineProperty(window, 'open', { writable: true }) window.open = vi.fn() // @vitest-environment jsdom describe('openShortcut', () => { describe('computed property "actions"', () => { describe('method "isVisible"', () => { it.each([ { resources: [], expectedStatus: false }, { resources: [mock<Resource>({ extension: 'txt' })], expectedStatus: false }, { resources: [mock<Resource>({ extension: 'url', canDownload: () => false })], expectedStatus: false }, { resources: [mock<Resource>({ extension: 'url', canDownload: () => true })], expectedStatus: true } ])('should be set correctly', ({ resources, expectedStatus }) => { getWrapper({ setup: ({ actions }) => { expect(unref(actions)[0].isVisible({ resources, space: null })).toBe(expectedStatus) } }) }) }) describe('method "handler"', () => { it('adds http(s) protocol if missing and opens the url in a new tab', () => { getWrapper({ getFileContentsValue: '[InternetShortcut]\nURL=owncloud.com', setup: async ({ actions }) => { await unref(actions)[0].handler({ resources: [mock<Resource>()], space: null }) expect(window.open).toHaveBeenCalledWith('https://owncloud.com') } }) }) it('omits xss code and opens the url in a new tab', () => { getWrapper({ getFileContentsValue: '[InternetShortcut]\nURL=https://owncloud.com?default=<script>alert(document.cookie)</script>', setup: async ({ actions }) => { await unref(actions)[0].handler({ resources: [mock<Resource>()], space: null }) expect(window.open).toHaveBeenCalledWith('https://owncloud.com?default=') } }) }) it('opens the url in the same window if url links to OCIS instance', () => { getWrapper({ getFileContentsValue: '[InternetShortcut]\nURL=https://demo.owncloud.com', setup: async ({ actions }) => { await unref(actions)[0].handler({ resources: [mock<Resource>()], space: null }) expect(window.location.href).toBe('https://demo.owncloud.com') } }) }) }) }) describe('method "extractUrl"', () => { it('extracts url correctly', () => { getWrapper({ setup: ({ extractUrl }) => { expect(extractUrl('[InternetShortcut]\n' + 'URL=https://owncloud.com')).toEqual( 'https://owncloud.com' ) } }) }) it('throws error if url cannot be extracted', () => { getWrapper({ setup: ({ extractUrl }) => { expect(() => extractUrl('�������')).toThrow('unable to extract url') } }) }) }) }) function getWrapper({ setup, getFileContentsValue = null }: { getFileContentsValue?: string setup: (instance: ReturnType<typeof useFileActionsOpenShortcut>) => void }) { const mocks = { ...defaultComponentMocks({ currentRoute: mock<RouteLocation>({ name: 'files-spaces-generic' }) }) } mocks.$clientService.webdav.getFileContents.mockResolvedValue( mock<GetFileContentsResponse>({ body: getFileContentsValue }) ) vi.mocked(useRoute).mockImplementation(() => ref(mock<RouteLocation>({ name: 'files-spaces-generic', path: '/files/' })) ) return { wrapper: getComposableWrapper( () => { const instance = useFileActionsOpenShortcut() setup(instance) }, { mocks, provide: mocks } ) } }
owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsOpenShortcut.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsOpenShortcut.spec.ts", "repo_id": "owncloud", "token_count": 1966 }
855
import { useSpaceActionsSetIcon } from '../../../../../src/composables/actions/spaces/useSpaceActionsSetIcon' import { useMessages, useModals } from '../../../../../src/composables/piniaStores' import { defaultComponentMocks, mockAxiosResolve, RouteLocation, getComposableWrapper } from 'web-test-helpers' import { unref } from 'vue' import { SpaceResource } from '@ownclouders/web-client/src' import { mock } from 'vitest-mock-extended' describe('setIcon', () => { beforeEach(() => { const createElementMock = vi.spyOn(document, 'createElement') createElementMock.mockImplementation(() => { return { insertBefore: vi.fn(), toBlob: () => new Blob(), getContext: () => ({ fillText: vi.fn() }) } as any }) }) describe('isVisible property', () => { it('should be false when no resource given', () => { getWrapper({ setup: ({ actions }) => { expect(unref(actions)[0].isVisible({ resources: [] })).toBe(false) } }) }) it('should be false when multiple resources are given', () => { getWrapper({ setup: ({ actions }) => { expect( unref(actions)[0].isVisible({ resources: [mock<SpaceResource>(), mock<SpaceResource>()] }) ).toBe(false) } }) }) it('should be false when permission is not granted', () => { getWrapper({ setup: ({ actions }) => { expect( unref(actions)[0].isVisible({ resources: [mock<SpaceResource>({ canEditImage: () => false })] }) ).toBe(false) } }) }) it('should be true when permission is granted', () => { getWrapper({ setup: ({ actions }) => { expect( unref(actions)[0].isVisible({ resources: [mock<SpaceResource>({ canEditImage: () => true })] }) ).toBe(true) } }) }) }) describe('handler', () => { it('should trigger the setIcon modal window with one resource', () => { getWrapper({ setup: async ({ actions }) => { const { dispatchModal } = useModals() await unref(actions)[0].handler({ resources: [{ id: '1' } as SpaceResource] }) expect(dispatchModal).toHaveBeenCalledTimes(1) } }) }) it('should not trigger the setIcon modal window with no resource', () => { getWrapper({ setup: async ({ actions }) => { const { dispatchModal } = useModals() await unref(actions)[0].handler({ resources: [] }) expect(dispatchModal).toHaveBeenCalledTimes(0) } }) }) }) describe('method "setIconSpace"', () => { it('should show message on success', () => { getWrapper({ setup: async ({ setIconSpace }, { clientService }) => { clientService.graphAuthenticated.drives.updateDrive.mockResolvedValue(mockAxiosResolve()) await setIconSpace(mock<SpaceResource>(), '🐻') const { showMessage } = useMessages() expect(showMessage).toHaveBeenCalledTimes(1) } }) }) it('should show message on error', () => { vi.spyOn(console, 'error').mockImplementation(() => undefined) getWrapper({ setup: async ({ setIconSpace }, { clientService }) => { clientService.graphAuthenticated.drives.updateDrive.mockRejectedValue(new Error()) await setIconSpace(mock<SpaceResource>(), '🐻') const { showErrorMessage } = useMessages() expect(showErrorMessage).toHaveBeenCalledTimes(1) } }) }) }) }) function getWrapper({ setup }: { setup: ( instance: ReturnType<typeof useSpaceActionsSetIcon>, { clientService }: { clientService: ReturnType<typeof defaultComponentMocks>['$clientService'] } ) => void }) { const mocks = defaultComponentMocks({ currentRoute: mock<RouteLocation>({ name: 'files-spaces-generic' }) }) return { mocks, wrapper: getComposableWrapper( () => { const instance = useSpaceActionsSetIcon() setup(instance, { clientService: mocks.$clientService }) }, { mocks, provide: mocks } ) } }
owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsSetIcon.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsSetIcon.spec.ts", "repo_id": "owncloud", "token_count": 1857 }
856
import { getComposableWrapper, mockAxiosResolve } from 'web-test-helpers' import { useSpacesStore, sortSpaceMembers } from '../../../../src/composables/piniaStores' import { createPinia, setActivePinia } from 'pinia' import { mock, mockDeep } from 'vitest-mock-extended' import { CollaboratorShare, GraphShareRoleIdMap, SpaceResource } from '@ownclouders/web-client/src/helpers' import { Graph } from '@ownclouders/web-client' import { Drive } from '@ownclouders/web-client/src/generated' describe('spaces', () => { beforeEach(() => { setActivePinia(createPinia()) }) describe('method "sortSpaceMembers"', () => { it('always puts space managers first', () => { const members = [ mock<CollaboratorShare>({ role: { id: GraphShareRoleIdMap.SpaceEditor }, sharedWith: { displayName: 'user1' } }), mock<CollaboratorShare>({ role: { id: GraphShareRoleIdMap.SpaceManager }, sharedWith: { displayName: 'user2' } }) ] const sortedMembers = sortSpaceMembers(members) expect(sortedMembers[0].role.id).toEqual(GraphShareRoleIdMap.SpaceManager) }) }) describe('computed "personalSpace"', () => { it('returns the personal space of a user', () => { getWrapper({ setup: (instance) => { instance.spaces = [ mock<SpaceResource>({ id: '1', isOwner: () => false, driveType: 'project' }), mock<SpaceResource>({ id: '2', isOwner: () => true, driveType: 'personal' }) ] expect(instance.personalSpace.id).toEqual('2') } }) }) }) describe('method "setSpacesInitialized"', () => { it('correctly sets spacesInitialized', () => { getWrapper({ setup: (instance) => { instance.setSpacesInitialized(true) expect(instance.spacesInitialized).toEqual(true) instance.setSpacesInitialized(false) expect(instance.spacesInitialized).toEqual(false) } }) }) }) describe('method "setMountPointsInitialized"', () => { it('correctly sets mountPointsInitialized', () => { getWrapper({ setup: (instance) => { instance.setMountPointsInitialized(true) expect(instance.mountPointsInitialized).toEqual(true) instance.setMountPointsInitialized(false) expect(instance.mountPointsInitialized).toEqual(false) } }) }) }) describe('method "setSpacesLoading"', () => { it('correctly sets spacesLoading', () => { getWrapper({ setup: (instance) => { instance.setSpacesLoading(true) expect(instance.spacesLoading).toEqual(true) instance.setSpacesLoading(false) expect(instance.spacesLoading).toEqual(false) } }) }) }) describe('method "setCurrentSpace"', () => { it('correctly sets the current space', () => { getWrapper({ setup: (instance) => { expect(instance.currentSpace).not.toBeDefined() const space = mock<SpaceResource>() instance.setCurrentSpace(space) expect(instance.currentSpace).toEqual(space) } }) }) }) describe('method "addSpaces"', () => { it('correctly adds given spaces', () => { getWrapper({ setup: (instance) => { expect(instance.spaces.length).toBe(0) const spaces = [mock<SpaceResource>({ id: '1' }), mock<SpaceResource>({ id: '2' })] instance.addSpaces(spaces) expect(instance.spaces).toEqual(spaces) } }) }) }) describe('method "removeSpace"', () => { it('correctly removes a given space', () => { getWrapper({ setup: (instance) => { const spaces = [mock<SpaceResource>({ id: '1' })] instance.addSpaces(spaces) expect(instance.spaces).toEqual(spaces) instance.removeSpace(spaces[0]) expect(instance.spaces.length).toBe(0) } }) }) }) describe('method "upsertSpace"', () => { it('updates a given space if it exsits', () => { getWrapper({ setup: (instance) => { const space = mock<SpaceResource>({ id: '1', name: 'foo' }) instance.addSpaces([space]) expect(instance.spaces.length).toBe(1) expect(instance.spaces[0].name).toEqual('foo') instance.upsertSpace({ ...space, name: 'bar' }) expect(instance.spaces.length).toBe(1) expect(instance.spaces[0].name).toEqual('bar') } }) }) it('adds a given space if it does not exsit', () => { getWrapper({ setup: (instance) => { const space = mock<SpaceResource>({ id: '1', name: 'foo' }) instance.addSpaces([space]) expect(instance.spaces.length).toBe(1) expect(instance.spaces[0].name).toEqual('foo') instance.upsertSpace(mock<SpaceResource>({ id: '2', name: 'bar' })) expect(instance.spaces.length).toBe(2) } }) }) }) describe('method "updateSpaceField"', () => { it('correctly updates a field of a space', () => { getWrapper({ setup: (instance) => { const space = mock<SpaceResource>({ id: '1', name: 'foo' }) instance.addSpaces([space]) expect(instance.spaces.length).toBe(1) expect(instance.spaces[0].name).toEqual('foo') instance.updateSpaceField({ id: space.id, field: 'name', value: 'bar' }) expect(instance.spaces[0].name).toEqual('bar') } }) }) }) describe('method "loadSpaces"', () => { it('correctly loads personal and project spaces', () => { getWrapper({ setup: async (instance) => { const drives = [mock<Drive>({ id: '1' })] const graphClient = mockDeep<Graph>() graphClient.drives.listMyDrives.mockResolvedValue(mockAxiosResolve({ value: drives })) await instance.loadSpaces({ graphClient }) expect(graphClient.drives.listMyDrives).toHaveBeenCalledTimes(2) expect(graphClient.drives.listMyDrives).toHaveBeenNthCalledWith( 1, 'name asc', 'driveType eq personal' ) expect(graphClient.drives.listMyDrives).toHaveBeenNthCalledWith( 2, 'name asc', 'driveType eq project' ) expect(instance.spaces.length).toBe(2) expect(instance.spacesLoading).toBeFalsy() expect(instance.spacesInitialized).toBeTruthy() } }) }) }) describe('method "loadMountPoints"', () => { it('correctly loads mount points', () => { getWrapper({ setup: async (instance) => { const drives = [mock<Drive>({ id: '1' })] const graphClient = mockDeep<Graph>() graphClient.drives.listMyDrives.mockResolvedValue(mockAxiosResolve({ value: drives })) await instance.loadMountPoints({ graphClient }) expect(graphClient.drives.listMyDrives).toHaveBeenCalledTimes(1) expect(graphClient.drives.listMyDrives).toHaveBeenCalledWith( 'name asc', 'driveType eq mountpoint' ) expect(instance.spaces.length).toBe(1) expect(instance.mountPointsInitialized).toBeTruthy() } }) }) }) describe('method "reloadProjectSpaces"', () => { it('correctly reloads project spaces', () => { getWrapper({ setup: async (instance) => { const drives = [mock<Drive>({ id: '1' })] const graphClient = mockDeep<Graph>() graphClient.drives.listMyDrives.mockResolvedValue(mockAxiosResolve({ value: drives })) await instance.reloadProjectSpaces({ graphClient }) expect(graphClient.drives.listMyDrives).toHaveBeenCalledTimes(1) expect(graphClient.drives.listMyDrives).toHaveBeenCalledWith( 'name asc', 'driveType eq project' ) expect(instance.spaces.length).toBe(1) } }) }) }) describe('method "upsertSpaceMember"', () => { it('correctly adds space members', () => { getWrapper({ setup: (instance) => { const member = mock<CollaboratorShare>({ id: '1' }) instance.upsertSpaceMember({ member }) expect(instance.spaceMembers.length).toBe(1) expect(instance.spaceMembers[0].id).toBe(member.id) } }) }) it('correctly updates space members', () => { getWrapper({ setup: (instance) => { const member = mock<CollaboratorShare>({ id: '1', indirect: false }) instance.upsertSpaceMember({ member }) expect(instance.spaceMembers.length).toBe(1) expect(instance.spaceMembers[0].indirect).toBe(member.indirect) instance.upsertSpaceMember({ member: { ...member, indirect: true } }) expect(instance.spaceMembers.length).toBe(1) expect(instance.spaceMembers[0].indirect).toBe(true) } }) }) }) }) function getWrapper({ setup }: { setup: (instance: ReturnType<typeof useSpacesStore>) => void }) { return { wrapper: getComposableWrapper( () => { const instance = useSpacesStore() setup(instance) }, { pluginOptions: { pinia: false } } ) } }
owncloud/web/packages/web-pkg/tests/unit/composables/piniaStores/spaces.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/piniaStores/spaces.spec.ts", "repo_id": "owncloud", "token_count": 4094 }
857
import { getParentPaths } from '../../../src/helpers/path' describe('build an array of parent paths from a provided path', () => { it('should return an empty array on an empty path', () => { const paths = getParentPaths('', false) expect(paths).toHaveLength(0) }) it('should return an empty array on "/" as path', () => { const paths = getParentPaths('/', false) expect(paths).toHaveLength(0) }) it('should prepend resulting paths with a "/" if none was given', () => { const paths = getParentPaths('a/b/c', false) expect(paths).toEqual(['/a/b', '/a']) }) it('should make no difference between "a/b/c" and "/a/b/c" with includeCurrent=false', () => { const paths1 = getParentPaths('a/b/c', false) const paths2 = getParentPaths('/a/b/c', false) expect(paths1).toEqual(paths2) }) it('should make no difference between "a/b/c" and "/a/b/c" with includeCurrent=true', () => { const paths1 = getParentPaths('a/b/c', true) const paths2 = getParentPaths('/a/b/c', true) expect(paths1).toEqual(paths2) }) it('should have different results for different values of includeCurrent', () => { const paths1 = getParentPaths('a/b/c', true) const paths2 = getParentPaths('a/b/c', false) expect(paths1).not.toEqual(paths2) }) it('should not interpret a trailing slash as yet another path segment', () => { const paths = getParentPaths('/a/b/c/', true) expect(paths).toEqual(['/a/b/c', '/a/b', '/a']) }) it('should include the provided path in the result if includeCurrent=true', () => { const paths = getParentPaths('a/b/c', true) expect(paths).toEqual(['/a/b/c', '/a/b', '/a']) }) })
owncloud/web/packages/web-pkg/tests/unit/helpers/path.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/path.spec.ts", "repo_id": "owncloud", "token_count": 635 }
858
import { EventBus } from '../../../src/services/eventBus' describe('EventBus', () => { it('can handle load', () => { const bus = new EventBus() let val for (let i = 0; i < 1000; i++) { bus.subscribe(`evt.${i}`, (v) => (val = v)) } for (let i = 0; i < 1000; i++) { const msg = `msg - ${i}` bus.publish(`evt.${i}`, msg) expect(val).toBe(msg) } val = 'untouched' for (let i = 0; i < 1000; i++) { bus.publish(`evt.unknown.${i}`, `unknown - ${i}`) } expect(val).toBe('untouched') }) it('calls multiple subscriptions for the same topic', () => { const bus = new EventBus() const fn = vi.fn() const topic = 'evt.1' bus.subscribe(topic, fn) bus.subscribe(topic, fn) bus.publish(topic) expect(fn).toHaveBeenCalledTimes(2) }) it('can unsubscribe a subscriber from a topic', () => { const bus = new EventBus() const fn = vi.fn() const topic = 'evt.1' const evt1Token = bus.subscribe(topic, fn) bus.publish(topic) expect(fn).toHaveBeenCalledTimes(1) bus.unsubscribe(topic, '') bus.publish(topic) expect(fn).toHaveBeenCalledTimes(2) bus.unsubscribe(topic, evt1Token) bus.publish(topic) expect(fn).toHaveBeenCalledTimes(2) }) })
owncloud/web/packages/web-pkg/tests/unit/services/eventBus.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/services/eventBus.spec.ts", "repo_id": "owncloud", "token_count": 564 }
859
<template> <oc-text-input v-model="currentPassword" :label="$gettext('Current password')" type="password" :fix-message-line="true" /> <oc-text-input v-model="newPassword" :label="$gettext('New password')" type="password" :fix-message-line="true" @change="validatePasswordConfirm" /> <oc-text-input v-model="newPasswordConfirm" :label="$gettext('Repeat new password')" type="password" :fix-message-line="true" :error-message="passwordConfirmErrorMessage" @change="validatePasswordConfirm" /> </template> <script lang="ts"> import { computed, defineComponent, ref, PropType, unref, watch } from 'vue' import { useGettext } from 'vue3-gettext' import { Modal, useClientService, useMessages } from '@ownclouders/web-pkg' export default defineComponent({ name: 'EditPasswordModal', props: { modal: { type: Object as PropType<Modal>, required: true } }, emits: ['update:confirmDisabled'], setup(props, { emit, expose }) { const { showMessage, showErrorMessage } = useMessages() const clientService = useClientService() const { $gettext } = useGettext() const currentPassword = ref('') const newPassword = ref('') const newPasswordConfirm = ref('') const passwordConfirmErrorMessage = ref('') const confirmButtonDisabled = computed(() => { return ( !unref(currentPassword).trim().length || !unref(newPassword).trim().length || unref(newPassword) !== unref(newPasswordConfirm) ) }) watch( confirmButtonDisabled, () => { emit('update:confirmDisabled', unref(confirmButtonDisabled)) }, { immediate: true } ) const onConfirm = () => { return clientService.graphAuthenticated.users .changeOwnPassword(unref(currentPassword).trim(), unref(newPassword).trim()) .then(() => { showMessage({ title: $gettext('Password was changed successfully') }) }) .catch((error) => { console.error(error) showErrorMessage({ title: $gettext('Failed to change password'), errors: [error] }) }) } expose({ onConfirm }) return { currentPassword, newPassword, newPasswordConfirm, passwordConfirmErrorMessage, // unit tests confirmButtonDisabled } }, methods: { validatePasswordConfirm() { this.passwordConfirmErrorMessage = '' if ( this.newPassword.trim().length && this.newPasswordConfirm.trim().length && this.newPassword !== this.newPasswordConfirm ) { this.passwordConfirmErrorMessage = this.$gettext( 'Password and password confirmation must be identical' ) return false } return true } } }) </script>
owncloud/web/packages/web-runtime/src/components/EditPasswordModal.vue/0
{ "file_path": "owncloud/web/packages/web-runtime/src/components/EditPasswordModal.vue", "repo_id": "owncloud", "token_count": 1130 }
860
export * from './useHead'
owncloud/web/packages/web-runtime/src/composables/head/index.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/composables/head/index.ts", "repo_id": "owncloud", "token_count": 9 }
861
/** * typescript breaks in current setup when importing json, investigate and fix * as workaround export it from a js file */ import CoreTranslations from '../../l10n/translations.json' import ClientTranslations from '@ownclouders/web-client/l10n/translations.json' // FIXME: import PkgTranslations from '../../../web-pkg/l10n/translations.json' import OdsTranslations from 'design-system/l10n/translations.json' export const coreTranslations = CoreTranslations export const clientTranslations = ClientTranslations export const pkgTranslations = PkgTranslations export const odsTranslations = OdsTranslations
owncloud/web/packages/web-runtime/src/defaults/json.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/defaults/json.ts", "repo_id": "owncloud", "token_count": 168 }
862
<template> <app-loading-spinner v-if="isLoading" /> <main v-else id="account" class="oc-height-1-1 oc-m"> <h1 id="account-page-title" class="oc-page-title oc-m-rm oc-invisible-sr">{{ pageTitle }}</h1> <div v-if="showAccountSection"> <div class="oc-flex oc-flex-between oc-flex-bottom oc-width-1-1"> <h2 class="oc-text-bold" v-text="$gettext('Account Information')" /> <oc-button v-if="accountEditLink" variation="primary" type="a" :href="accountEditLink.href" target="_blank" data-testid="account-page-edit-url-btn" > <oc-icon name="edit" /> <span v-text="$gettext('Edit')" /> </oc-button> </div> <dl class="account-page-info oc-flex oc-flex-wrap"> <div class="account-page-info-username oc-mb oc-width-1-2@s"> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('Username')" /> <dd> {{ user.onPremisesSamAccountName }} </dd> </div> <div class="account-page-info-displayname oc-mb oc-width-1-2@s"> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('First and last name')" /> <dd> {{ user.displayName }} </dd> </div> <div class="account-page-info-email oc-mb oc-width-1-2@s"> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('Email')" /> <dd> <template v-if="user.mail">{{ user.mail }}</template> <span v-else v-text="$gettext('No email has been set up')" /> </dd> </div> <div class="account-page-info-groups oc-mb oc-width-1-2@s"> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('Group memberships')" /> <dd data-testid="group-names"> <span v-if="groupNames">{{ groupNames }}</span> <span v-else data-testid="group-names-empty" v-text="$gettext('You are not part of any group')" /> </dd> </div> <div v-if="showLogout" class="account-page-logout-all-devices oc-mb oc-width-1-2@s"> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('Logout from active devices')" /> <dd data-testid="logout"> <oc-button appearance="raw" type="a" :href="logoutUrl" target="_blank" data-testid="account-page-logout-url-btn" > <span v-text="$gettext('Show devices')" /> </oc-button> </dd> </div> <div v-if="showChangePassword" class="account-page-password oc-mb oc-width-1-2@s"> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('Password')" /> <dd data-testid="password"> <oc-button appearance="raw" variation="primary" data-testid="account-page-edit-password-btn" @click="showEditPasswordModal" > <span v-text="$gettext('Set new password')" /> </oc-button> </dd> </div> </dl> </div> <div> <div class="oc-flex oc-width-1-1"> <h2 class="oc-text-bold" v-text="$gettext('Preferences')" /> </div> <dl class="account-page-preferences oc-flex oc-flex-wrap"> <div class="account-page-info-language oc-mb oc-width-1-2@s"> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('Language')" /> <dd data-testid="language" class="oc-width-1-3"> <oc-select v-if="languageOptions" :placeholder="$gettext('Please choose...')" :model-value="selectedLanguageValue" :clearable="false" :options="languageOptions" @update:model-value="updateSelectedLanguage" /> </dd> </div> <div class="account-page-info-theme oc-mb oc-width-1-2@s"> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('Theme')" /> <dd data-testid="theme" class="oc-width-1-3"> <theme-switcher /> </dd> </div> <div v-if="showNotifications" class="account-page-notification oc-mb oc-width-1-2@s"> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('Notifications')" /> <dd data-testid="notification-mails"> <oc-checkbox :model-value="disableEmailNotificationsValue" size="large" :label="$gettext('Receive notification mails')" data-testid="account-page-notification-mails-checkbox" @update:model-value="updateDisableEmailNotifications" /> </dd> </div> <div v-if="showWebDavDetails" class="account-page-view-options oc-mb oc-width-1-2@s"> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('View options')" /> <dd data-testid="view-options"> <oc-checkbox :model-value="viewOptionWebDavDetailsValue" size="large" :label="$gettext('Show WebDAV information in file details')" data-testid="account-page-webdav-details-checkbox" @update:model-value="updateViewOptionsWebDavDetails" /> </dd> </div> </dl> </div> <div v-if="showGdprExport" class="account-page-gdpr-export oc-width-1-1"> <h2 class="oc-text-bold oc-mb" v-text="$gettext('GDPR')" /> <dt class="oc-text-normal oc-text-muted" v-text="$gettext('GDPR export')" /> <dd data-testid="gdpr-export"> <gdpr-export /> </dd> </div> </main> </template> <script lang="ts"> import { storeToRefs } from 'pinia' import EditPasswordModal from '../components/EditPasswordModal.vue' import { SettingsBundle, LanguageOption, SettingsValue } from '../helpers/settings' import { computed, defineComponent, onMounted, unref, ref } from 'vue' import { useAuthStore, useCapabilityStore, useClientService, useConfigStore, useMessages, useModals, useResourcesStore, useSpacesStore, useUserStore } from '@ownclouders/web-pkg' import { useTask } from 'vue-concurrency' import { useGettext } from 'vue3-gettext' import { setCurrentLanguage } from 'web-runtime/src/helpers/language' import GdprExport from 'web-runtime/src/components/Account/GdprExport.vue' import { AppLoadingSpinner } from '@ownclouders/web-pkg' import { SSEAdapter } from '@ownclouders/web-client/src/sse' import { supportedLanguages } from '../defaults/languages' import { User } from '@ownclouders/web-client/src/generated' import ThemeSwitcher from 'web-runtime/src/components/ThemeSwitcher.vue' export default defineComponent({ name: 'AccountPage', components: { AppLoadingSpinner, GdprExport, ThemeSwitcher }, setup() { const { showMessage, showErrorMessage } = useMessages() const userStore = useUserStore() const authStore = useAuthStore() const language = useGettext() const { $gettext } = language const clientService = useClientService() const resourcesStore = useResourcesStore() const valuesList = ref<SettingsValue[]>() const graphUser = ref<User>() const accountBundle = ref<SettingsBundle>() const selectedLanguageValue = ref<LanguageOption>() const disableEmailNotificationsValue = ref<boolean>() const viewOptionWebDavDetailsValue = ref<boolean>(resourcesStore.areWebDavDetailsShown) const { dispatchModal } = useModals() const spacesStore = useSpacesStore() const capabilityStore = useCapabilityStore() const configStore = useConfigStore() // FIXME: Use settings service capability when we have it const isSettingsServiceSupported = computed(() => !configStore.options.runningOnEos) const { user } = storeToRefs(userStore) const showGdprExport = computed(() => { return ( authStore.userContextReady && capabilityStore.personalDataExport && spacesStore.personalSpace ) }) const showChangePassword = computed(() => { return authStore.userContextReady && !capabilityStore.graphUsersChangeSelfPasswordDisabled }) const showAccountSection = computed(() => authStore.userContextReady) const showWebDavDetails = computed(() => authStore.userContextReady) const showNotifications = computed( () => authStore.userContextReady && unref(isSettingsServiceSupported) ) const showLogout = computed(() => authStore.userContextReady && configStore.options.logoutUrl) const loadValuesListTask = useTask(function* () { if (!authStore.userContextReady || !unref(isSettingsServiceSupported)) { return } try { const { data: { values } } = yield clientService.httpAuthenticated.post('/api/v0/settings/values-list', { account_uuid: 'me' }) valuesList.value = values || [] } catch (e) { console.error(e) showErrorMessage({ title: $gettext('Unable to load account data…'), errors: [e] }) valuesList.value = [] } }).restartable() const loadAccountBundleTask = useTask(function* () { if (!authStore.userContextReady || !unref(isSettingsServiceSupported)) { return } try { const { data: { bundles } } = yield clientService.httpAuthenticated.post('/api/v0/settings/bundles-list', {}) accountBundle.value = bundles?.find((b) => b.extension === 'ocis-accounts') } catch (e) { console.error(e) showErrorMessage({ title: $gettext('Unable to load account data…'), errors: [e] }) accountBundle.value = undefined } }).restartable() const loadGraphUserTask = useTask(function* () { if (!authStore.userContextReady) { return } try { const { data } = yield clientService.graphAuthenticated.users.getMe() graphUser.value = data } catch (e) { console.error(e) showErrorMessage({ title: $gettext('Unable to load account data…'), errors: [e] }) graphUser.value = undefined } }).restartable() const isLoading = computed(() => { return ( loadValuesListTask.isRunning || !loadValuesListTask.last || loadAccountBundleTask.isRunning || !loadAccountBundleTask.last || loadGraphUserTask.isRunning || !loadGraphUserTask.last ) }) const languageOptions = Object.keys(supportedLanguages).map((langCode) => ({ label: supportedLanguages[langCode], value: langCode })) const groupNames = computed(() => { return unref(user) .memberOf.map((group) => group.displayName) .join(', ') }) const saveValue = async ({ identifier, valueOptions }: { identifier: string valueOptions: Record<string, any> }) => { const valueId = unref(valuesList)?.find((cV) => cV.identifier.setting === identifier)?.value ?.id const value = { bundleId: unref(accountBundle)?.id, settingId: unref(accountBundle)?.settings?.find((s) => s.name === identifier)?.id, resource: { type: 'TYPE_USER' }, accountUuid: 'me', ...valueOptions, ...(valueId && { id: valueId }) } try { await clientService.httpAuthenticated.post('/api/v0/settings/values-save', { value: { accountUuid: 'me', ...value } }) /** * Edge case: we need to reload the values list to retrieve the valueId if not set, * otherwise the backend saves multiple entries */ if (!valueId) { loadValuesListTask.perform() } return value } catch (e) { throw e } } const updateSelectedLanguage = async (option: LanguageOption) => { try { selectedLanguageValue.value = option setCurrentLanguage({ language, languageSetting: option.value }) if (authStore.userContextReady) { await clientService.graphAuthenticated.users.editMe({ preferredLanguage: option.value }) if (capabilityStore.supportSSE) { ;(clientService.sseAuthenticated as SSEAdapter).updateLanguage(language.current) } if (spacesStore.personalSpace) { // update personal space name with new translation spacesStore.updateSpaceField({ id: spacesStore.personalSpace.id, field: 'name', value: $gettext('Personal') }) } } showMessage({ title: $gettext('Preference saved.') }) } catch (e) { console.error(e) showErrorMessage({ title: $gettext('Unable to save preference…'), errors: [e] }) } } const updateDisableEmailNotifications = async (option: boolean) => { try { await saveValue({ identifier: 'disable-email-notifications', valueOptions: { boolValue: !option } }) disableEmailNotificationsValue.value = option showMessage({ title: $gettext('Preference saved.') }) } catch (e) { console.error(e) showErrorMessage({ title: $gettext('Unable to save preference…'), errors: [e] }) } } const updateViewOptionsWebDavDetails = (option: boolean) => { try { resourcesStore.setAreWebDavDetailsShown(option) viewOptionWebDavDetailsValue.value = option showMessage({ title: $gettext('Preference saved.') }) } catch (e) { console.error(e) showErrorMessage({ title: $gettext('Unable to save preference…'), errors: [e] }) } } onMounted(async () => { await loadAccountBundleTask.perform() await loadValuesListTask.perform() await loadGraphUserTask.perform() selectedLanguageValue.value = unref(languageOptions)?.find( (languageOption) => languageOption.value === (unref(graphUser)?.preferredLanguage || language.current) ) const disableEmailNotificationsConfiguration = unref(valuesList)?.find( (cV) => cV.identifier.setting === 'disable-email-notifications' ) disableEmailNotificationsValue.value = disableEmailNotificationsConfiguration ? !disableEmailNotificationsConfiguration.value?.boolValue : true }) const showEditPasswordModal = () => { dispatchModal({ title: $gettext('Change password'), customComponent: EditPasswordModal }) } return { clientService, languageOptions, selectedLanguageValue, updateSelectedLanguage, updateDisableEmailNotifications, updateViewOptionsWebDavDetails, accountEditLink: computed(() => configStore.options.accountEditLink), showLogout, showGdprExport, showNotifications, showAccountSection, showChangePassword, showWebDavDetails, groupNames, user, logoutUrl: computed(() => configStore.options.logoutUrl), isLoading, disableEmailNotificationsValue, viewOptionWebDavDetailsValue, loadAccountBundleTask, loadGraphUserTask, loadValuesListTask, showEditPasswordModal } }, computed: { pageTitle() { return this.$gettext(this.$route.meta.title as string) } } }) </script> <style lang="scss" scoped> dd { margin-left: 0; } main { overflow-y: auto; } </style>
owncloud/web/packages/web-runtime/src/pages/account.vue/0
{ "file_path": "owncloud/web/packages/web-runtime/src/pages/account.vue", "repo_id": "owncloud", "token_count": 7079 }
863
import { buildUrl, OpenIdConnectConfig } from '@ownclouders/web-pkg' import { v4 as uuidV4 } from 'uuid' import { router } from 'web-runtime/src/router' async function get(url) { return await fetch(url, { headers: { 'X-Request-ID': uuidV4() } }) .then((res) => { return res.json() }) .catch((err) => { console.error('Error: ', err) }) } async function post(url, data) { return await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Request-ID': uuidV4() }, body: JSON.stringify(data) }) .then((res) => { return res.json() }) .catch((err) => { console.error('Error: ', err) }) } export async function registerClient(openIdConfig: OpenIdConnectConfig) { const clientData = JSON.parse(sessionStorage.getItem('dynamicClientData')) if (clientData !== null) { // eslint-disable-next-line camelcase const client_secret_expires_at = clientData.client_secret_expires_at || 0 // eslint-disable-next-line camelcase if (client_secret_expires_at === 0 || Date.now() < client_secret_expires_at * 1000) { return JSON.parse(clientData) } } sessionStorage.removeItem('dynamicClientData') const wellKnown = await get(`${openIdConfig.authority}/.well-known/openid-configuration`) const resp = await post(wellKnown.registration_endpoint, { redirect_uris: [buildUrl(router, '/oidc-callback.html')], client_name: `ownCloud Web on ${window.location.origin}` }) sessionStorage.setItem('dynamicClientData', JSON.stringify(resp)) return resp }
owncloud/web/packages/web-runtime/src/services/clientRegistration.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/services/clientRegistration.ts", "repo_id": "owncloud", "token_count": 604 }
864
import Notifications from 'web-runtime/src/components/Topbar/Notifications.vue' import { Notification } from 'web-runtime/src/helpers/notifications' import { mock } from 'vitest-mock-extended' import { defaultComponentMocks, defaultPlugins, shallowMount } from 'web-test-helpers' import { SpaceResource } from '@ownclouders/web-client' import { RouterLink, RouteLocationNamedRaw, RouteLocationNormalizedLoaded } from 'vue-router' import { AxiosResponse } from 'axios' const selectors = { notificationBellStub: 'notification-bell-stub', avatarImageStub: 'avatar-image-stub', noNewNotifications: '.oc-notifications-no-new', markAll: '.oc-notifications-mark-all', notificationsLoading: '.oc-notifications-loading', notificationItem: '.oc-notifications-item', notificationSubject: '.oc-notifications-subject', notificationMessage: '.oc-notifications-message', notificationLink: '.oc-notifications-link' } vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({ ...(await importOriginal<any>()), useServerSentEvents: vi.fn() })) describe('Notification component', () => { it('renders the notification bell and no notifications if there are none', () => { const { wrapper } = getWrapper() expect(wrapper.find(selectors.notificationBellStub).exists()).toBeTruthy() expect(wrapper.find(selectors.noNewNotifications).exists()).toBeTruthy() expect(wrapper.find(selectors.markAll).exists()).toBeFalsy() }) it('renders a set of notifications', async () => { const notifications = [mock<Notification>({ messageRich: undefined })] const { wrapper } = getWrapper({ notifications }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last expect(wrapper.find(selectors.noNewNotifications).exists()).toBeFalsy() expect(wrapper.findAll(selectors.notificationItem).length).toBe(notifications.length) }) it('renders the loading state', async () => { const notifications = [mock<Notification>({ messageRich: undefined })] const { wrapper } = getWrapper({ notifications }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last wrapper.vm.loading = true await wrapper.vm.$nextTick() expect(wrapper.find(selectors.notificationsLoading).exists()).toBeTruthy() }) it('marks all notifications as read', async () => { const notifications = [mock<Notification>({ messageRich: undefined })] const { wrapper, mocks } = getWrapper({ notifications }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last await wrapper.find(selectors.markAll).trigger('click') await wrapper.vm.$nextTick() expect(wrapper.find(selectors.notificationItem).exists()).toBeFalsy() expect(mocks.$clientService.httpAuthenticated.delete).toHaveBeenCalledTimes(1) }) describe('avatar', () => { it('loads based on the username', async () => { const notification = mock<Notification>({ messageRich: undefined, user: 'einstein' }) const { wrapper } = getWrapper({ notifications: [notification] }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last const avatarImageStub = wrapper.findComponent<any>(selectors.avatarImageStub) expect(avatarImageStub.attributes('userid')).toEqual(notification.user) expect(avatarImageStub.attributes('user-name')).toEqual(notification.user) }) it('loads based on the rich parameters', async () => { const displayname = 'Albert Einstein' const name = 'einstein' const notification = mock<Notification>({ messageRich: undefined, messageRichParameters: { user: { displayname, name } } }) const { wrapper } = getWrapper({ notifications: [notification] }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last const avatarImageStub = wrapper.findComponent<any>(selectors.avatarImageStub) expect(avatarImageStub.attributes('userid')).toEqual(name) expect(avatarImageStub.attributes('user-name')).toEqual(displayname) }) }) describe('subject', () => { it('displays if no message given', async () => { const notification = mock<Notification>({ messageRich: undefined, message: undefined }) const { wrapper } = getWrapper({ notifications: [notification] }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last expect(wrapper.find(selectors.notificationSubject).exists()).toBeTruthy() }) }) describe('message', () => { it('displays simple message if messageRich not given', async () => { const notification = mock<Notification>({ messageRich: undefined, message: 'some message' }) const { wrapper } = getWrapper({ notifications: [notification] }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last wrapper.vm.showDrop() await wrapper.vm.$nextTick() expect(wrapper.find(selectors.notificationMessage).text()).toEqual(notification.message) }) it('displays rich message and interpolates the text', async () => { const notification = mock<Notification>({ messageRich: '{user} shared {resource} with you', messageRichParameters: { user: { displayname: 'Albert Einstein' }, resource: { name: 'someFile.txt' } } }) const { wrapper } = getWrapper({ notifications: [notification] }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last wrapper.vm.showDrop() await wrapper.vm.$nextTick() expect(wrapper.find(selectors.notificationMessage).text()).toEqual( 'Albert Einstein shared someFile.txt with you' ) }) }) describe('link', () => { it('displays if given directly', async () => { const notification = mock<Notification>({ messageRich: undefined, link: 'http://some-link.com' }) const { wrapper } = getWrapper({ notifications: [notification] }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last expect(wrapper.find(selectors.notificationLink).exists()).toBeTruthy() }) describe('if given via messageRichParameters', () => { it('renders notification as link for shares', async () => { const notification = mock<Notification>({ messageRich: '{user} shared {resource} with you', object_type: 'share', messageRichParameters: { user: { displayname: 'Albert Einstein' }, resource: { name: 'someFile.txt' }, share: { id: '1' } } }) const { wrapper } = getWrapper({ notifications: [notification] }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last wrapper.vm.showDrop() await wrapper.vm.$nextTick() const routerLink = wrapper.findComponent<typeof RouterLink>( `${selectors.notificationItem} router-link-stub` ) expect((routerLink.props('to') as RouteLocationNamedRaw).name).toEqual( 'files-shares-with-me' ) expect((routerLink.props('to') as RouteLocationNamedRaw).query).toEqual({ scrollTo: notification.messageRichParameters.share.id }) }) it('renders notification as link for spaces', async () => { const spaceMock = mock<SpaceResource>({ fileId: '1', getDriveAliasAndItem: () => 'driveAlias', disabled: false }) const notification = mock<Notification>({ messageRich: '{user} added you to space {space}', object_type: 'storagespace', messageRichParameters: { user: { displayname: 'Albert Einstein' }, space: { name: 'someFile.txt', id: `${spaceMock.fileId}!2` } } }) const { wrapper } = getWrapper({ notifications: [notification], spaces: [spaceMock] }) await wrapper.vm.fetchNotificationsTask.perform() await wrapper.vm.fetchNotificationsTask.last wrapper.vm.showDrop() await wrapper.vm.$nextTick() const routerLink = wrapper.findComponent<typeof RouterLink>( `${selectors.notificationItem} router-link-stub` ) expect((routerLink.props('to') as RouteLocationNormalizedLoaded).params).toEqual({ driveAliasAndItem: 'driveAlias' }) }) }) }) }) function getWrapper({ mocks = {}, notifications = [], spaces = [] } = {}) { const localMocks = { ...defaultComponentMocks(), ...mocks } localMocks.$clientService.httpAuthenticated.get.mockResolvedValue( mock<AxiosResponse>({ data: { ocs: { data: notifications } }, headers: {} }) ) return { mocks: localMocks, wrapper: shallowMount(Notifications, { global: { renderStubDefaultSlot: true, plugins: [...defaultPlugins({ piniaOptions: { spacesState: { spaces } } })], mocks: localMocks, provide: localMocks, stubs: { 'avatar-image': true, OcButton: false } } }) } }
owncloud/web/packages/web-runtime/tests/unit/components/Topbar/Notifications.spec.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Topbar/Notifications.spec.ts", "repo_id": "owncloud", "token_count": 3444 }
865
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`account page > account information section > displays basic user information 1`] = ` "<dl data-v-f2ac0579="" class="account-page-info oc-flex oc-flex-wrap"> <div data-v-f2ac0579="" class="account-page-info-username oc-mb oc-width-1-2@s"> <dt data-v-f2ac0579="" class="oc-text-normal oc-text-muted">Username</dt> <dd data-v-f2ac0579="">some-username</dd> </div> <div data-v-f2ac0579="" class="account-page-info-displayname oc-mb oc-width-1-2@s"> <dt data-v-f2ac0579="" class="oc-text-normal oc-text-muted">First and last name</dt> <dd data-v-f2ac0579="">some-displayname</dd> </div> <div data-v-f2ac0579="" class="account-page-info-email oc-mb oc-width-1-2@s"> <dt data-v-f2ac0579="" class="oc-text-normal oc-text-muted">Email</dt> <dd data-v-f2ac0579="">some-email</dd> </div> <div data-v-f2ac0579="" class="account-page-info-groups oc-mb oc-width-1-2@s"> <dt data-v-f2ac0579="" class="oc-text-normal oc-text-muted">Group memberships</dt> <dd data-v-f2ac0579="" data-testid="group-names"><span data-v-f2ac0579="" data-testid="group-names-empty">You are not part of any group</span></dd> </div> <div data-v-f2ac0579="" class="account-page-logout-all-devices oc-mb oc-width-1-2@s"> <dt data-v-f2ac0579="" class="oc-text-normal oc-text-muted">Logout from active devices</dt> <dd data-v-f2ac0579="" data-testid="logout"> <oc-button-stub data-v-f2ac0579="" appearance="raw" type="a" href="https://account-manager/logout" target="_blank" data-testid="account-page-logout-url-btn"></oc-button-stub> </dd> </div> <!--v-if--> </dl>" `; exports[`account page > account information section > group membership > displays group names 1`] = `"<dd data-v-f2ac0579="" data-testid="group-names"><span data-v-f2ac0579="">one, two, three</span></dd>"`; exports[`account page > header section > edit url button > should be displayed if defined via config 1`] = `"<oc-button-stub data-v-f2ac0579="" variation="primary" type="a" href="/" target="_blank" data-testid="account-page-edit-url-btn"></oc-button-stub>"`; exports[`account page > public link context > should render a limited view 1`] = ` "<main data-v-f2ac0579="" id="account" class="oc-height-1-1 oc-m"> <h1 data-v-f2ac0579="" id="account-page-title" class="oc-page-title oc-m-rm oc-invisible-sr">Some Title</h1> <!--v-if--> <div data-v-f2ac0579=""> <div data-v-f2ac0579="" class="oc-flex oc-width-1-1"> <h2 data-v-f2ac0579="" class="oc-text-bold">Preferences</h2> </div> <dl data-v-f2ac0579="" class="account-page-preferences oc-flex oc-flex-wrap"> <div data-v-f2ac0579="" class="account-page-info-language oc-mb oc-width-1-2@s"> <dt data-v-f2ac0579="" class="oc-text-normal oc-text-muted">Language</dt> <dd data-v-f2ac0579="" data-testid="language" class="oc-width-1-3"> <oc-select-stub data-v-f2ac0579="" id="oc-select-1" filter="[Function]" disabled="false" optionlabel="label" getoptionlabel="[Function]" searchable="true" clearable="false" loading="false" fixmessageline="false" multiple="false" readonly="false" placeholder="Please choose..." options="[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]"></oc-select-stub> </dd> </div> <div data-v-f2ac0579="" class="account-page-info-theme oc-mb oc-width-1-2@s"> <dt data-v-f2ac0579="" class="oc-text-normal oc-text-muted">Theme</dt> <dd data-v-f2ac0579="" data-testid="theme" class="oc-width-1-3"> <theme-switcher-stub data-v-f2ac0579=""></theme-switcher-stub> </dd> </div> <!--v-if--> <!--v-if--> </dl> </div> <!--v-if--> </main>" `;
owncloud/web/packages/web-runtime/tests/unit/pages/__snapshots__/account.spec.ts.snap/0
{ "file_path": "owncloud/web/packages/web-runtime/tests/unit/pages/__snapshots__/account.spec.ts.snap", "repo_id": "owncloud", "token_count": 1616 }
866
{ "name": "web-test-helpers", "private": true, "main": "src/index.ts", "peerDependencies": { "@casl/ability": "^6.3.3", "@casl/vue": "^2.2.1", "axios": "1.6.5", "pinia": "2.1.7", "vue-router": "4.2.5", "vue3-gettext": "2.4.0" }, "devDependencies": { "@pinia/testing": "^0.1.3" } }
owncloud/web/packages/web-test-helpers/package.json/0
{ "file_path": "owncloud/web/packages/web-test-helpers/package.json", "repo_id": "owncloud", "token_count": 182 }
867
prefer-workspace-packages: true packages: - 'packages/*' - 'tests/*'
owncloud/web/pnpm-workspace.yaml/0
{ "file_path": "owncloud/web/pnpm-workspace.yaml", "repo_id": "owncloud", "token_count": 27 }
868
/** * waits till a css property equals the given value * @param selector * @param locateStrategy 'css selector' or 'xpath' * @param property the CSS property * @param value the status to wail till * @param timeout defaults to this.globals.waitForConditionTimeout * @returns {exports} */ module.exports.command = function ({ selector, locateStrategy = 'css selector', property, value, timeout = this.globals.waitForConditionTimeout }) { if (locateStrategy === 'xpath') { this.useXpath() } else if (locateStrategy === 'css selector') { this.useCss() } else { this.assert.fail('invalid locateStrategy') } this.expect.element(selector).to.have.css(property).which.equals(value).before(timeout) return this }
owncloud/web/tests/acceptance/customCommands/waitForCSSPropertyEquals.js/0
{ "file_path": "owncloud/web/tests/acceptance/customCommands/waitForCSSPropertyEquals.js", "repo_id": "owncloud", "token_count": 243 }
869
Feature: rename folders As a user I want to rename folders So that I can organise my data structure Background: Given user "Alice" has been created with default attributes and without skeleton files in the server And user "Alice" has created folder "simple-folder" in the server And user "Alice" has created folder "simple-empty-folder" in the server And user "Alice" has uploaded file "lorem.txt" to "lorem.txt" in the server @ocisSmokeTest Scenario Outline: Rename a folder Given user "Alice" has logged in using the webUI When the user renames folder "simple-folder" to <to_folder_name> using the webUI Then folder <to_folder_name> should be listed on the webUI When the user reloads the current page of the webUI Then folder <to_folder_name> should be listed on the webUI Examples: | to_folder_name | | 'an other simple name' | | '"quotes1"' | | "'quotes2'" | | "home" | | 'सिमप्ले फोल्देर$%#?&@' | Scenario Outline: Rename a folder that has special characters in its name Given user "Alice" has created folder <from_name> in the server And user "Alice" has logged in using the webUI When the user renames folder <from_name> to <to_name> using the webUI Then folder <to_name> should be listed on the webUI When the user reloads the current page of the webUI Then folder <to_name> should be listed on the webUI Examples: | from_name | to_name | | "'single'quotes" | "single-quotes" | | "strängé नेपाली folder" | "strängé नेपाली folder-#?2" | | "Sample,Folder,With,Comma" | "Simple,Folder,With,Commä" | Scenario: Rename a folder using special characters and check its existence after page reload Given user "Alice" has logged in using the webUI When the user renames folder "simple-folder" to "लोरेम।तयक्स्त $%&" using the webUI And the user reloads the current page of the webUI Then folder "लोरेम।तयक्स्त $%&" should be listed on the webUI When the user renames folder "लोरेम।तयक्स्त $%&" to '"double"quotes' using the webUI And the user reloads the current page of the webUI Then folder '"double"quotes' should be listed on the webUI When the user renames folder '"double"quotes' to "no-double-quotes" using the webUI And the user reloads the current page of the webUI Then folder "no-double-quotes" should be listed on the webUI When the user renames folder 'no-double-quotes' to "hash#And&QuestionMark?At@FolderName" using the webUI And the user reloads the current page of the webUI Then folder "hash#And&QuestionMark?At@FolderName" should be listed on the webUI @issue-964 Scenario: Rename a folder using spaces at front and/or back of the name Given user "Alice" has logged in using the webUI When the user renames folder "simple-folder" to " space at start" using the webUI And the user reloads the current page of the webUI Then folder " space at start" should be listed on the webUI When the user renames folder " space at start" to " multiple spaces all over" using the webUI And the user reloads the current page of the webUI Then folder " multiple spaces all over" should be listed on the webUI Scenario: Rename a file using spaces at end is prohibited Given user "Alice" has logged in using the webUI When the user tries to rename folder "simple-folder" to "space at end " using the webUI Then the error message 'The name cannot end with whitespace' should be displayed on the webUI dialog prompt When the user reloads the current page of the webUI And folder "space at end " should not be listed on the webUI And the user tries to rename folder "simple-folder" to " multiple space all over " using the webUI Then the error message 'The name cannot end with whitespace' should be displayed on the webUI dialog prompt And the user reloads the current page of the webUI And folder "simple-folder" should be listed on the webUI And folder " multiple space all over " should not be listed on the webUI Scenario: Rename a folder using both double and single quotes Given user "Alice" has logged in using the webUI When the user renames the following folder using the webUI | fromName | toName | | simple-folder | '"First 'single" quotes" ' | | simple-empty-folder | Test" 'me o'ut" | And the user reloads the current page of the webUI Then these folders should be listed on the webUI | folders | | '"First 'single" quotes" ' | | Test" 'me o'ut" | When the user renames the following folder using the webUI | fromName | toName | | '"First 'single" quotes" ' | a normal folder | | Test" 'me o'ut" | another normal folder | And the user reloads the current page of the webUI Then these folders should be listed on the webUI | folders | | a normal folder | | another normal folder | Scenario: Rename a folder putting a name of a file which already exists Given user "Alice" has logged in using the webUI When the user tries to rename folder "simple-folder" to "lorem.txt" using the webUI Then the error message 'The name "lorem.txt" is already taken' should be displayed on the webUI dialog prompt Scenario: Rename a folder to .. Given user "Alice" has logged in using the webUI When the user tries to rename folder "simple-folder" to ".." using the webUI Then the error message 'The name cannot be equal to ".."' should be displayed on the webUI dialog prompt Scenario: Rename a folder to . Given user "Alice" has logged in using the webUI When the user tries to rename folder "simple-folder" to "." using the webUI Then the error message 'The name cannot be equal to "."' should be displayed on the webUI dialog prompt Scenario: Rename a folder to .part (on ocis) Given user "Alice" has logged in using the webUI When the user renames folder "simple-folder" to "simple.part" using the webUI Then folder "simple.part" should be listed on the webUI Scenario Outline: Rename a folder to a name with dot Given user "Alice" has logged in using the webUI When the user renames folder "simple-folder" to "<to_name>" using the webUI Then folder "<to_name>" should be listed on the webUI Examples: | to_name | | fo. | | fo.1 | | fo.xyz |
owncloud/web/tests/acceptance/features/webUIRenameFolders/renameFolders.feature/0
{ "file_path": "owncloud/web/tests/acceptance/features/webUIRenameFolders/renameFolders.feature", "repo_id": "owncloud", "token_count": 2452 }
870
@files_trashbin-app-required Feature: files and folders exist in the trashbin after being deleted As a user I want deleted files and folders to be available in the trashbin So that I can recover data easily Background: Given user "Alice" has been created with default attributes and without skeleton files in the server And user "Alice" has uploaded file "lorem.txt" to "lorem.txt" in the server And user "Alice" has uploaded file "lorem-big.txt" to "lorem-big.txt" in the server And user "Alice" has uploaded file "new-lorem.txt" to "textfile0.txt" in the server And user "Alice" has uploaded file "testavatar.png" to "testimage.png" in the server And user "Alice" has created file "sample,1.txt" in the server And user "Alice" has created file "strängé filename (duplicate #2 &).txt" in the server And user "Alice" has created folder "Folder,With,Comma" in the server And user "Alice" has created folder "strängé नेपाली folder" in the server And user "Alice" has created folder "simple-folder" in the server And user "Alice" has uploaded file "lorem.txt" to "simple-folder/lorem.txt" in the server And user "Alice" has uploaded file "lorem.txt" to "strängé नेपाली folder/lorem.txt" in the server And user "Alice" has logged in using the webUI @issue-1910 Scenario: trashbin list appears empty when no deleted files exist When the user browses to the trashbin page Then there should be no resources listed on the webUI Scenario: Delete folders with dot in the name and check they are in the trashbin Given user "Alice" has created the following folders in the server | folders | | fo. | | fo.1 | | fo...1.. | | ... | | ..fo | | fo.xyz | And the following folders have been deleted by user "Alice" in the server | name | | fo. | | fo.1 | | fo...1.. | | ... | | ..fo | | fo.xyz | When the user browses to the trashbin page Then the deleted elements should be listed on the webUI
owncloud/web/tests/acceptance/features/webUITrashbinFilesFolders/trashbinFilesFolders.feature/0
{ "file_path": "owncloud/web/tests/acceptance/features/webUITrashbinFilesFolders/trashbinFilesFolders.feature", "repo_id": "owncloud", "token_count": 750 }
871
const fetch = require('node-fetch') const { client } = require('nightwatch-api') const { BACKENDS } = require('./backendHelper') const passwords = { admin: process.env.ADMIN_PASSWORD || 'admin', regular: process.env.REGULAR_USER_PASSWORD || '123456', alt1: process.env.ALT1_USER_PASSWORD || '1234', alt2: process.env.ALT2_USER_PASSWORD || 'AaBb2Cc3Dd4', alt3: process.env.ALT3_USER_PASSWORD || 'aVeryLongPassword42TheMeaningOfLife', alt4: process.env.ALT4_USER_PASSWORD || 'ThisIsThe4thAlternatePwd', alt11: process.env.ALT11_USER_PASSWORD || 'E-leven' } const adminUsername = process.env.ADMIN_USERNAME || 'admin' module.exports = { passwords, // list of default users defaultUsers: { admin: { displayname: adminUsername, password: passwords.admin }, regularuser: { displayname: 'Regular User', password: passwords.regular, email: 'regularuser@example.org' }, user0: { displayname: 'Regular User', password: passwords.regular, email: 'user0@example.org' }, Alice: { displayname: 'Alice Hansen', password: passwords.alt1, email: 'alice@example.org' }, Brian: { displayname: 'Brian Murphy', password: passwords.alt2, email: 'brian@example.org' }, Carol: { displayname: 'Carol King', password: passwords.alt3, email: 'carol@example.org' }, David: { displayname: 'David Lopez', password: passwords.alt4, email: 'david@example.org' }, user11: { displayname: 'User Eleven', password: passwords.alt11, email: 'user11@example.org' }, usergrp: { displayname: 'User Grp', password: passwords.regular, email: 'usergrp@example.org' }, sharee1: { displayname: 'Sharee One', password: passwords.regular, email: 'sharee1@example.org' }, // These users are available by default only in ocis backend when not using ldap Einstein: { displayname: 'Albert Einstein', password: 'relativity', email: 'einstein@example.org' }, Richard: { displayname: 'Richard Feynman', password: 'superfluidity', email: 'richard@example.org' }, Marie: { displayname: 'Marie Curie', password: 'radioactivity', email: 'marie@example.org' }, Moss: { displayname: 'Maurice Moss', password: 'vista', email: 'moss@example.org' } }, createdUsers: {}, createdRemoteUsers: {}, createdGroups: [], state: null, fetchState: function () { return fetch(client.globals.middlewareUrl + '/state') .then((res) => res.json()) .then((data) => { this.state = data }) }, /** * gets the password of a previously created user * if the user was not created yet, gets the password from the default Users list * if the user is not in that list either, returns the userId as password * * @param {string} userId * @returns {string} */ getPasswordForUser: function (userId) { if (userId in this.createdUsers) { return this.createdUsers[userId].password } else if (userId in this.defaultUsers) { return this.defaultUsers[userId].password } else { // user was not created yet and is not in the default users list, let the userId be the password return userId } }, /** * gets the display name of a previously created user * if the user was not created yet, gets the display name from the default Users list * if the user is not in that list either, returns the userId as display name * * @param {string} userId * @returns {string} */ getDisplayNameForUser: async function (userId, fetchState = true) { if (fetchState) { await this.fetchState() } let user = {} if (userId in this.state.created_users) { user = this.state.created_users[userId] } else if (userId in this.defaultUsers) { user = this.defaultUsers[userId] } else { return userId } if ('displayname' in user && user.displayname !== null) { return user.displayname } else { return userId } }, /** * gets the username of a previously created user from displayName * * @param {string} displayName */ getUsernameFromDisplayname: async function (displayName) { await this.fetchState() for (const userid in this.state.created_users) { if (this.state.created_users[userid].displayname === displayName) { return userid } } }, /** * * @returns {module.exports.createdUsers|{}} */ getCreatedUsers: async function (server = BACKENDS.local) { await this.fetchState() for (const userId in this.state.created_users) { this.state.created_users[userId].displayName = await this.getDisplayNameForUser(userId) } for (const userId in this.state.created_remote_users) { this.state.created_remote_users[userId].displayName = await this.getDisplayNameForUser(userId) } switch (server) { case BACKENDS.local: return this.state.created_users case BACKENDS.remote: return this.state.created_remote_users default: throw new Error('Invalid value for server. want = "REMOTE"/"LOCAL", got = ' + server) } }, /** * * @returns {Array} */ getCreatedGroups: function () { this.fetchState() return this.state.created_groups } }
owncloud/web/tests/acceptance/helpers/userSettings.js/0
{ "file_path": "owncloud/web/tests/acceptance/helpers/userSettings.js", "repo_id": "owncloud", "token_count": 2140 }
872
module.exports = { commands: { /** * @returns {Promise<number>} */ getVersionsCount: async function () { let count = 0 await this.api.elements('@versionsList', function (result) { count = result.value.length }) return count }, /** * @returns {*} */ restoreToPreviousVersion: function () { return this.waitForElementVisible('@restorePreviousVersion') .initAjaxCounters() .click('@restorePreviousVersion') .waitForOutstandingAjaxCalls() } }, elements: { versionsList: { selector: '//div[@id="oc-file-versions-sidebar"]//li[contains(@class,"version-item")]', locateStrategy: 'xpath' }, restorePreviousVersion: { selector: '(//div[contains(@id,"oc-file-versions")]//li[contains(@class,"version-item")])[1]//button[1]', locateStrategy: 'xpath' } } }
owncloud/web/tests/acceptance/pageObjects/FilesPageElement/versionsDialog.js/0
{ "file_path": "owncloud/web/tests/acceptance/pageObjects/FilesPageElement/versionsDialog.js", "repo_id": "owncloud", "token_count": 394 }
873
const { client } = require('nightwatch-api') const filesList = client.page.FilesPageElement.filesList() const filesActionsMenu = client.page.FilesPageElement.fileActionsMenu() const saveButtonSelector = '#app-save-action' module.exports = { commands: { /** * gets inner text from given html element * @param {string} element - css selectoreditorTextarea * * @returns {Promise<string>} */ getInnerText: async function (element) { let text = '' await this.waitForElementVisible(element).getText(element, (result) => (text = result.value)) return text }, /** * gets value from given html input element * @param {string} element - css selector * * @returns {Promise<string>} */ getInputValue: async function (element) { let content = '' await this.waitForElementVisible(element).getValue(element, (result) => { content = result.value }) return content }, getFileName: async function () { let fileName = '' await this.waitForElementVisible('@fileName').getAttribute( '@fileName', 'data-test-resource-name', (result) => { fileName = result.value } ) return fileName }, getContentFromEditor: async function () { const selector = await this.getEditorInputSelector() return this.getInputValue(selector) }, getContentFromPanel: function () { return this.waitForElementVisible('@editorPreviewButton') .click('@editorPreviewButton') .waitForElementVisible('@editorPreviewPanel') .getInnerText('@editorPreviewPanel') }, getPreviewPanelElement: function () { return this.elements.editorPreviewPanel.selector }, getPreviewPanelButtonElement: function () { return this.elements.editorPreviewButton.selector }, saveFileEdit: function () { return this.waitForElementVisible('@saveButton') .click('@saveButton') .waitForElementVisible('@saveButtonDisabled') }, closeTextEditor: function () { return this.waitForElementVisible('@closeButton').click('@closeButton') }, /** * clears and updates textarea with new value * @param {string} content */ updateFileContent: async function (content) { const selector = await this.getEditorInputSelector() await this.waitForElementVisible(selector) .click(selector) .clearValue(selector) .setValue(selector, content) }, waitForPageLoaded: function () { return this.waitForElementVisible('@editor') }, /** * appends new content to the existing content * @param {string} content */ appendContentToFile: async function (content) { const selector = await this.getEditorInputSelector() await this.waitForElementVisible(selector) .sendKeys(selector, client.Keys.END) .setValue(selector, content) }, /** * @param {string} fileName */ openMdEditorUsingActionMenu: async function (fileName) { await filesList.openFileActionsMenu(fileName) await filesActionsMenu.textEditor() return this }, getEditorInputSelector: async function () { let selector = null await this.waitForElementVisible('@editor').getAttribute( '@editor', 'data-markdown-mode', (result) => { selector = result.value === 'true' ? '@editorMarkdownInputArea' : '@editorPlainTextInputArea' } ) return selector } }, elements: { editor: { selector: '#text-editor #text-editor-container' }, editorPlainTextInputArea: { selector: '#text-editor #text-editor-container .ww-mode .ProseMirror' }, editorMarkdownInputArea: { selector: '#text-editor #text-editor-container .md-mode .ProseMirror' }, editorPreviewButton: { selector: '#text-editor #text-editor-container .tab-item:nth-child(2)' }, editorPreviewPanel: { selector: '#text-editor #text-editor-container .toastui-editor-md-preview .toastui-editor-contents' }, saveButton: { selector: saveButtonSelector }, closeButton: { selector: '#app-top-bar-close' }, fileName: { selector: '.oc-resource-name' }, saveButtonDisabled: { selector: `${saveButtonSelector}:disabled` } } }
owncloud/web/tests/acceptance/pageObjects/textEditorPage.js/0
{ "file_path": "owncloud/web/tests/acceptance/pageObjects/textEditorPage.js", "repo_id": "owncloud", "token_count": 1742 }
874
const { client } = require('nightwatch-api') const { When, Then } = require('@cucumber/cucumber') require('url-search-params-polyfill') const sharingHelper = require('../helpers/sharingHelper') const assert = require('assert') const loginHelper = require('../helpers/loginHelper') let lastLinkShare = null When( 'the user (tries to )create/creates a new public link for file/folder/resource {string} using the webUI', async function (resource) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) return client.page.FilesPageElement.publicLinksDialog().addNewLink() } ) When( 'the user sets the role of the most recently created public link of resource {string} to {string}', async function (resource, newRole) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) await client.page.FilesPageElement.publicLinksDialog().changeLatestLinkRole(newRole) } ) Then( 'the link expiration date shown on the webUI should be {string} days', async function (expectedDays) { const expectedDate = sharingHelper.calculateDate(expectedDays) const expectedDateString = expectedDate.toString() const dateStringFromInputField = await client.page.FilesPageElement.publicLinksDialog().getExpirationDate() assert.strictEqual( dateStringFromInputField, expectedDateString, `Expected: Expiration date field with ${expectedDateString}, but found ${dateStringFromInputField}` ) } ) Then('the password input for the public link should appear on the webUI', function () { return client.page.publicLinkPasswordPage().waitForVisible() }) When( 'the user accesses the public link with password {string} using the webUI', function (password) { return client.page.publicLinkPasswordPage().submitPublicLinkPassword(password) } ) When( 'the public uses the webUI to access the last public link created by user {string} in a new session', function (linkCreator) { return loadPublicLink(linkCreator) } ) When( 'the public uses the webUI to access the last public link created by user {string} with password {string} in a new session', function (linkCreator, password) { return loadPublicLinkWithPassword(linkCreator, password) } ) When('the user navigates to the root of the last public link', function () { return client.page.publicLinkFilesPage().navigateToRootFolder(lastLinkShare.name) }) const loadPublicLink = async function (linkCreator, newSession = true) { lastLinkShare = await sharingHelper.fetchLastPublicLinkShare(linkCreator) if (newSession) { await loginHelper.startNewSession() } if (lastLinkShare.permissions === sharingHelper.PERMISSION_TYPES.create) { return client.page.filesDropPage().navigateAndWaitTillLoaded(lastLinkShare.token) } return client.page.publicLinkFilesPage().navigateAndWaitTillLoaded(lastLinkShare.token) } const loadPublicLinkWithPassword = async function (linkCreator, password, newSession = true) { lastLinkShare = await sharingHelper.fetchLastPublicLinkShare(linkCreator) if (newSession) { await loginHelper.startNewSession() } if (lastLinkShare.permissions === sharingHelper.PERMISSION_TYPES.create) { await client.page.filesDropPage().navigateAndWaitForPasswordPage(lastLinkShare.token) } else { await client.page.publicLinkFilesPage().navigateAndWaitForPasswordPage(lastLinkShare.token) } return client.page.publicLinkPasswordPage().submitPublicLinkPassword(password) } Then('the public should not get access to the publicly shared file', async function () { const message = await client.page .publicLinkPasswordPage() .submitLinkPasswordForm() // form is submitted as password input is filled in the step before this particular step in 'when' part .getResourceAccessDeniedMsg() return assert.strictEqual( 'This resource is password-protected', message, 'Resource protected message invalid, Found: ', message ) }) When( 'the user renames the most recently created public link of file/folder/resource {string} to {string}', async function (resource, newName) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) await client.page.FilesPageElement.publicLinksDialog().changeLatestLinkName(newName) } ) When( 'the user renames the public link named {string} of file/folder/resource {string} to {string}', async function (linkName, resource, newName) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) await client.page.FilesPageElement.publicLinksDialog().changeName(linkName, newName) } ) When( 'the user edits the public link named {string} of file/folder/resource {string} changing expireDate to {string}', async function (linkName, resource, expiry) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) await client.page.FilesPageElement.publicLinksDialog().changeExpirationDate(linkName, expiry) } ) Then( 'the user should see a password modal dialog with message {string} on the webUI', async function (expectedMessage) { const actualMessage = await client.page.FilesPageElement.publicLinksDialog().getErrorMessageFromModal() return client.assert.strictEqual(actualMessage, expectedMessage) } ) When( 'the user tries to edit the public link named {string} of file/folder/resource {string} changing the role to {string}', async function (linkName, resource, role) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) await client.page.FilesPageElement.publicLinksDialog().changeRole(linkName, role) } ) When( 'the user tries to edit the public link named {string} of file/folder/resource {string} changing the password to {string}', async function (linkName, resource, password) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) await client.page.FilesPageElement.publicLinksDialog().changePassword(linkName, password) } ) When( 'the user sets a password {string} for the public link in the modal', async function (password) { await client.page.FilesPageElement.publicLinksDialog().setRequiredPassword(password) } ) When( 'the user tries to edit the public link named {string} of file/folder/resource {string} adding a password {string}', async function (linkName, resource, password) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) await client.page.FilesPageElement.publicLinksDialog().addPassword(linkName, password) } ) When( 'the user opens the link edit dialog of file/folder/resource {string} with name {string} using the webUI', async function (resource, linkName) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) await client.page.FilesPageElement.publicLinksDialog().clickLinkEditBtn(linkName) } ) Then( 'it should not be possible to remove password for the link with name {string}', async function (linkName) { const isVisible = await client.page.FilesPageElement.publicLinksDialog().isRemovePasswordBtnVisible( linkName, false ) return assert.strictEqual( isVisible, false, `Expected "Remove password" button to be invisible but found visible` ) } ) When( 'the user tries to edit expiration of the public link named {string} of file {string} to past date {string}', async function (linkName, resource, pastDate) { const api = client.page.FilesPageElement await api.filesList().openPublicLinkDialog(resource) await api.publicLinksDialog().clickLinkEditBtn(linkName) const value = sharingHelper.calculateDate(pastDate) const dateToSet = new Date(Date.parse(value)) await api.publicLinksDialog().clickLinkEditExpirationBtn(linkName) const isDisabled = await api.expirationDatePicker().isExpiryDateDisabled(dateToSet) return assert.ok(isDisabled, 'Expected expiration date to be disabled but found not disabled') } ) When( 'the user removes the public link named {string} of file/folder/resource {string} using the webUI', async function (linkName, resource) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) return client.page.FilesPageElement.publicLinksDialog().removePublicLink(linkName) } ) When( 'the user cancels remove the public link named {string} of file/folder/resource {string} using the webUI', async function (linkName, resource) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) return client.page.FilesPageElement.publicLinksDialog().cancelRemovePublicLink(linkName) } ) Then( 'public link named {string} should not be listed on the public links list on the webUI', async function (linkName) { const isPresent = await client.page.FilesPageElement.publicLinksDialog().isPublicLinkPresent(linkName) return assert.ok( !isPresent, `expected public-link '${linkName}' to be 'not listed' but got found` ) } ) async function findMatchingPublicLinkByName(name, role, resource, via = null) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) const shares = await client.page.FilesPageElement.publicLinksDialog().getPublicLinkList() const share = shares.find((link) => link.name === name) if (!share) { assert.fail( `Link with name "${name}" was expected to be in share list but was not present. Found links: ` + shares.map((share) => share.name) ) } assert.strictEqual(role, share.role) if (via !== null) { assert.ok(share.viaLabel, 'Expected "shared via" icon to be displayed but was not visible') } } Then( 'a link named {string} should be listed with role {string} in the public link list of file/folder/resource {string} on the webUI', async function (name, role, resource) { await findMatchingPublicLinkByName(name, role, resource) } ) Then( 'a link named {string} should be listed with role {string} in the public link list of file/folder/resource {string} via {string} on the webUI', async function (name, role, resource, via) { await findMatchingPublicLinkByName(name, role, resource, via) } ) Then( 'the user should see an error message on the public link share dialog saying {string}', async function (expectedMessage) { const actualMessage = await client.page.FilesPageElement.publicLinksDialog().getErrorMessage() return client.assert.strictEqual(actualMessage, expectedMessage) } ) Then( 'the user should see an error message on the public link edit modal dialog saying {string}', async function (expectedMessage) { const actualMessage = await client.page.FilesPageElement.publicLinksDialog().getErrorMessageFromModal() return client.assert.strictEqual(actualMessage, expectedMessage) } ) When( 'the user copies the url of public link named {string} of file/folder/resource {string} using the webUI', async function (linkName, resource) { await client.page.FilesPageElement.filesList().openPublicLinkDialog(resource) return client.page.FilesPageElement.publicLinksDialog().copyPublicLinkURI(linkName) } ) Then('the tokens should be unique for each public links on the webUI', async function () { const publicLinkUrls = await client.page.FilesPageElement.publicLinksDialog().getPublicLinkUrls() const isUnique = publicLinkUrls.length === new Set(publicLinkUrls).size return assert.ok(isUnique) }) When( 'the user creates a public link via quick action for resource {string} using the webUI', function (resource) { return client.page.FilesPageElement.filesList().useQuickAction(resource, 'quicklink') } )
owncloud/web/tests/acceptance/stepDefinitions/publicLinkContext.js/0
{ "file_path": "owncloud/web/tests/acceptance/stepDefinitions/publicLinkContext.js", "repo_id": "owncloud", "token_count": 3523 }
875
import { Browser } from '@playwright/test' export const state: { browser: Browser } = { browser: undefined }
owncloud/web/tests/e2e/cucumber/environment/shared.ts/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/environment/shared.ts", "repo_id": "owncloud", "token_count": 36 }
876
Feature: link Background: Given "Admin" creates following user using API | id | | Alice | Scenario: public link When "Alice" logs in And "Alice" creates the following folders in personal space using API | name | | folderPublic | And "Alice" creates the following files into personal space using API | pathToFile | content | | folderPublic/lorem.txt | lorem ipsum | And "Alice" opens the "files" app And "Alice" creates a public link creates a public link of following resource using the sidebar panel | resource | role | password | | folderPublic | Secret File Drop | %public% | And "Alice" renames the most recently created public link of resource "folderPublic" to "myPublicLink" And "Alice" edits the public link named "myPublicLink" of resource "folderPublic" changing role to "Secret File Drop" And "Alice" sets the expiration date of the public link named "myPublicLink" of resource "folderPublic" to "+5 days" When "Anonymous" opens the public link "myPublicLink" And "Anonymous" unlocks the public link with password "%public%" And "Anonymous" drop uploads following resources | resource | | textfile.txt | And "Alice" edits the public link named "myPublicLink" of resource "folderPublic" changing role to "Can edit" And "Anonymous" refreshes the old link And "Anonymous" downloads the following public link resources using the sidebar panel | resource | type | | lorem.txt | file | | textfile.txt | file | And "Anonymous" uploads the following resources in public link page | resource | | new-lorem.txt | And "Anonymous" renames the following public link resources | resource | as | | lorem.txt | lorem_new.txt | | textfile.txt | textfile_new.txt | | new-lorem.txt | test.txt | # currently upload folder feature is not available in playwright # And "Anonymous" uploads the following resources in public link page # | resource | # | filesForUpload/PARENT | And "Alice" removes the public link named "myPublicLink" of resource "folderPublic" And "Anonymous" should not be able to open the old link "myPublicLink" And "Alice" logs out Scenario: Quick link Given "Alice" logs in And "Alice" creates the following folders in personal space using API | name | | folderPublic | And "Alice" creates the following files into personal space using API | pathToFile | content | | folderPublic/lorem.txt | lorem ipsum | And "Alice" opens the "files" app When "Alice" creates quick link of the resource "folderPublic" with password "%public%" from the context menu And "Anonymous" opens the public link "Link" And "Anonymous" unlocks the public link with password "%public%" And "Anonymous" downloads the following public link resources using the sidebar panel | resource | type | | lorem.txt | file | And "Alice" logs out Scenario: public link for folder and file (by authenticated user) Given "Admin" creates following user using API | id | | Brian | | Carol | And "Alice" logs in And "Alice" creates the following folders in personal space using API | name | | folderPublic | And "Alice" creates the following files into personal space using API | pathToFile | content | | folderPublic/shareToBrian.txt | some text | | folderPublic/shareToBrian.md | readme | And "Alice" uploads the following local file into personal space using API | localFile | to | | filesForUpload/simple.pdf | simple.pdf | | filesForUpload/testavatar.jpg | testavatar.jpg | And "Alice" shares the following resource using API | resource | recipient | type | role | | folderPublic | Brian | user | Can edit | | simple.pdf | Brian | user | Can edit | | testavatar.jpg | Brian | user | Can edit | And "Alice" opens the "files" app And "Alice" creates a public link creates a public link of following resource using the sidebar panel | resource | password | | folderPublic | %public% | And "Alice" renames the most recently created public link of resource "folderPublic" to "folderLink" And "Alice" creates a public link creates a public link of following resource using the sidebar panel | resource | password | | folderPublic/shareToBrian.txt | %public% | And "Alice" renames the most recently created public link of resource "folderPublic/shareToBrian.txt" to "textLink" And "Alice" creates a public link creates a public link of following resource using the sidebar panel | resource | password | | folderPublic/shareToBrian.md | %public% | And "Alice" renames the most recently created public link of resource "folderPublic/shareToBrian.md" to "markdownLink" And "Alice" creates a public link creates a public link of following resource using the sidebar panel | resource | password | | simple.pdf | %public% | And "Alice" renames the most recently created public link of resource "simple.pdf" to "pdfLink" And "Alice" creates a public link creates a public link of following resource using the sidebar panel | resource | password | | testavatar.jpg | %public% | And "Alice" renames the most recently created public link of resource "testavatar.jpg" to "imageLink" And "Alice" logs out # authenticated user with access to resources. should be redirected to shares with me page And "Brian" logs in When "Brian" opens the public link "folderLink" And "Brian" unlocks the public link with password "%public%" And "Brian" downloads the following public link resources using the sidebar panel | resource | type | | shareToBrian.txt | file | And "Brian" uploads the following resources | resource | | lorem.txt | When "Brian" opens the public link "textLink" And "Brian" unlocks the public link with password "%public%" Then "Brian" is in a text-editor And "Brian" closes the file viewer When "Brian" opens the public link "markdownLink" And "Brian" unlocks the public link with password "%public%" Then "Brian" is in a text-editor And "Brian" closes the file viewer And "Brian" downloads the following public link resources using the single share view | resource | type | | shareToBrian.md | file | When "Brian" opens the public link "pdfLink" And "Brian" unlocks the public link with password "%public%" Then "Brian" is in a pdf-viewer And "Brian" closes the file viewer And "Brian" downloads the following public link resources using the single share view | resource | type | | simple.pdf | file | When "Brian" opens the public link "imageLink" And "Brian" unlocks the public link with password "%public%" # https://github.com/owncloud/ocis/issues/8602 Then "Brian" is in a image-viewer And "Brian" closes the file viewer And "Brian" downloads the following public link resources using the single share view | resource | type | | testavatar.jpg | file | And "Brian" logs out # authenticated user without access to resources. should be redirected to the public links page And "Carol" logs in When "Carol" opens the public link "folderLink" And "Carol" unlocks the public link with password "%public%" # https://github.com/owncloud/web/issues/10473 And "Carol" downloads the following public link resources using the sidebar panel | resource | type | | lorem.txt | file | When "Carol" opens the public link "textLink" And "Carol" unlocks the public link with password "%public%" Then "Carol" is in a text-editor And "Carol" closes the file viewer When "Carol" opens the public link "markdownLink" And "Carol" unlocks the public link with password "%public%" Then "Carol" is in a text-editor And "Carol" closes the file viewer And "Carol" downloads the following public link resources using the single share view | resource | type | | shareToBrian.md | file | When "Carol" opens the public link "pdfLink" And "Carol" unlocks the public link with password "%public%" Then "Carol" is in a pdf-viewer And "Carol" closes the file viewer And "Carol" downloads the following public link resources using the single share view | resource | type | | simple.pdf | file | When "Carol" opens the public link "imageLink" And "Carol" unlocks the public link with password "%public%" # https://github.com/owncloud/ocis/issues/8602 Then "Carol" is in a image-viewer And "Carol" closes the file viewer And "Carol" downloads the following public link resources using the single share view | resource | type | | testavatar.jpg | file | And "Carol" logs out # Anonymous user When "Anonymous" opens the public link "folderLink" And "Anonymous" unlocks the public link with password "%public%" And "Anonymous" downloads the following public link resources using the sidebar panel | resource | type | | lorem.txt | file | When "Anonymous" opens the public link "textLink" And "Anonymous" unlocks the public link with password "%public%" Then "Anonymous" is in a text-editor And "Anonymous" closes the file viewer When "Anonymous" opens the public link "markdownLink" And "Anonymous" unlocks the public link with password "%public%" Then "Anonymous" is in a text-editor And "Anonymous" closes the file viewer And "Anonymous" downloads the following public link resources using the single share view | resource | type | | shareToBrian.md | file | When "Anonymous" opens the public link "pdfLink" And "Anonymous" unlocks the public link with password "%public%" Then "Anonymous" is in a pdf-viewer And "Anonymous" closes the file viewer And "Anonymous" downloads the following public link resources using the single share view | resource | type | | simple.pdf | file | When "Anonymous" opens the public link "imageLink" And "Anonymous" unlocks the public link with password "%public%" # https://github.com/owncloud/ocis/issues/8602 Then "Anonymous" is in a image-viewer And "Anonymous" closes the file viewer And "Anonymous" downloads the following public link resources using the single share view | resource | type | | testavatar.jpg | file | Scenario: add banned password for public link When "Alice" logs in And "Alice" creates the following files into personal space using API | pathToFile | content | | lorem.txt | some text | And "Alice" opens the "files" app And "Alice" creates a public link creates a public link of following resource using the sidebar panel | resource | password | | lorem.txt | %public% | When "Alice" tries to sets a new password "ownCloud-1" of the public link named "Link" of resource "lorem.txt" # https://github.com/owncloud/ocis/issues/8624 Then "Alice" should see an error message """ unfortunately, your password is commonly used. please pick a harder-to-guess password for your safety """ And "Alice" closes the public link password dialog box When "Alice" tries to sets a new password "ownCloud-1" of the public link named "Link" of resource "lorem.txt" # https://github.com/owncloud/ocis/issues/8624 Then "Alice" should see an error message """ unfortunately, your password is commonly used. please pick a harder-to-guess password for your safety """ And "Alice" reveals the password of the public link And "Alice" hides the password of the public link And "Alice" generates the password for the public link And "Alice" copies the password of the public link And "Alice" sets the password of the public link And "Anonymous" opens the public link "Link" And "Anonymous" unlocks the public link with password "%copied_password%" And "Alice" logs out
owncloud/web/tests/e2e/cucumber/features/shares/link.feature/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/features/shares/link.feature", "repo_id": "owncloud", "token_count": 4123 }
877
Feature: Trashbin delete As a user I want to delete files and folders from the trashbin So that I can control my trashbin space and which files are kept in that space Background: Given "Admin" creates following user using API | id | | Alice | | Brian | And "Alice" logs in Scenario: delete files and folders from trashbin Given "Alice" creates the following resources | resource | type | | FOLDER | folder | | PARENT/CHILD | folder | And "Alice" uploads the following resources | resource | to | | new-lorem.txt | FOLDER | | PARENT/parent.txt | PARENT | | PARENT/simple.pdf | PARENT | | PARENT/CHILD/child.txt | PARENT/CHILD | | data.tar.gz | | | lorem.txt | | | lorem-big.txt | | And "Alice" opens the "files" app And "Alice" deletes the following resources using the batch action | resource | | FOLDER | | PARENT | | data.tar.gz | | lorem.txt | | lorem-big.txt | And "Alice" navigates to the trashbin When "Alice" deletes the following resources from trashbin using the batch action | resource | | lorem.txt | | PARENT | And "Alice" empties the trashbin And "Alice" logs out Scenario: delete and restore a file inside a received shared folder Given "Alice" creates the following resources | resource | type | | folderToShare | folder | And "Alice" uploads the following resource | resource | to | | lorem.txt | folderToShare | And "Alice" shares the following resource using the sidebar panel | resource | recipient | type | role | resourceType | | folderToShare | Brian | user | Can edit | folder | And "Brian" logs in And "Brian" navigates to the shared with me page And "Brian" opens folder "folderToShare" When "Brian" deletes the following resources using the sidebar panel | resource | | lorem.txt | And "Brian" navigates to the trashbin Then following resources should not be displayed in the trashbin for user "Brian" | resource | | folderToShare/lorem.txt | And "Alice" navigates to the trashbin And following resources should be displayed in the trashbin for user "Alice" | resource | | folderToShare/lorem.txt | And "Alice" restores the following resource from trashbin | resource | | folderToShare/lorem.txt | And "Alice" opens the "files" app And "Alice" opens folder "folderToShare" And following resources should be displayed in the files list for user "Alice" | resource | | lorem.txt | And "Brian" navigates to the shared with me page And "Brian" opens folder "folderToShare" And following resources should be displayed in the files list for user "Brian" | resource | | lorem.txt | And "Brian" logs out And "Alice" logs out
owncloud/web/tests/e2e/cucumber/features/smoke/trashbinDelete.feature/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/trashbinDelete.feature", "repo_id": "owncloud", "token_count": 1295 }
878
import { When } from '@cucumber/cucumber' import { World } from '../../environment' import { objects } from '../../../support' When( '{string} navigates to the project spaces management page', async function (this: World, stepUser: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const pageObject = new objects.applicationAdminSettings.page.Spaces({ page }) await pageObject.navigate() } ) When( '{string} opens the {string} app', async function (this: World, stepUser: string, stepApp: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const applicationObject = new objects.runtime.Application({ page }) await applicationObject.open({ name: stepApp }) } ) When('{string} reloads the page', async function (this: World, stepUser: string): Promise<void> { const { page } = this.actorsEnvironment.getActor({ key: stepUser }) const applicationObject = new objects.runtime.Application({ page }) await applicationObject.reloadPage() })
owncloud/web/tests/e2e/cucumber/steps/ui/application.ts/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/steps/ui/application.ts", "repo_id": "owncloud", "token_count": 316 }
879
#!/usr/bin/env bash SCRIPT_PATH=$(dirname "$0") SCRIPT_PATH=$(cd "${SCRIPT_PATH_REL}" && pwd) # absolute path FEATURES_DIR="${SCRIPT_PATH}/cucumber/features" PROJECT_ROOT=$(cd "$SCRIPT_PATH/../../" && pwd) SCRIPT_PATH_REL=${SCRIPT_PATH//"$PROJECT_ROOT/"/} E2E_COMMAND="pnpm test:e2e:cucumber" # run command defined in package.json ALL_SUITES=$(find "${FEATURES_DIR}"/ -type d | sort | rev | cut -d"/" -f1 | rev | grep -v '^[[:space:]]*$') FILTER_SUITES="" EXCLUDE_SUITES="" FEATURE_PATHS="" GLOB_FEATURE_PATHS="" FEATURE_PATHS_FROM_ARG="" SKIP_RUN_PARTS=true RUN_PART="" TOTAL_PARTS="" HELP_COMMAND=" COMMAND [options] [paths] Available options: --suites - suites to run. Comma separated values (folder names) e.g.: --suites smoke,shares --xsuites - exclude suites from running. Comma separated values e.g.: --xsuites spaces,search --run-part - part to run out of total parts (groups) e.g.: --run-part 2 (runs part 2 out of 4) --total-parts - total number of groups to divide into e.g.: --total-parts 4 (suites will be divided into 4 groups) --help, -h - show cli options " function log() { case $1 in info) echo -e "\e[0mINF: $2\e[0m" ;; error) echo -e "\e[31mERR: $2\e[0m" ;; warn) echo -e "\e[93mWRN: $2\e[0m"USAGE: ;; cmd) echo -e "\e[96mUSAGE: $2\e[0m" ;; *) echo -e "\e[0m$1\e[0m" ;; esac } while [[ $# -gt 0 ]]; do key="$1" case ${key} in --suites) FILTER_SUITES=$(echo "$2" | sed -E "s/,/\n/g") shift 2 ;; --xsuites) EXCLUDE_SUITES=$(echo "$2" | sed -E "s/,/\n/g") shift 2 ;; --run-part) SKIP_RUN_PARTS=false RUN_PART=$2 shift 2 ;; --total-parts) SKIP_RUN_PARTS=false TOTAL_PARTS=$2 shift 2 ;; --help | -h) log "$HELP_COMMAND" exit 0 ;; *) if [[ $1 =~ ^-.* ]]; then log error "Unknown option: '$1'" log "$HELP_COMMAND" exit 1 fi FEATURE_PATHS_FROM_ARG+=" $1" # maintain the white space shift ;; esac done function getFeaturePaths() { # $1 - paths to suite or feature file paths=$(echo "$1" | xargs) real_paths="" for path in $paths; do real_paths+=" $SCRIPT_PATH/$path" # maintain the white space a_path=$(echo "$path" | cut -d ":" -f1) if [[ ! -f $a_path && ! -d $a_path ]]; then log error "File or folder doesn't exist: '$a_path'" log info "Path must be relative to '$SCRIPT_PATH_REL'" exit 1 fi done FEATURE_PATHS=$(echo "$real_paths" | xargs) # remove trailing white spaces } function runE2E() { if [[ ! -d "$PROJECT_ROOT" ]]; then log error "Project root doesn't exist: '$PROJECT_ROOT'" fi cd "$PROJECT_ROOT" || exit 1 if [[ -n $GLOB_FEATURE_PATHS ]]; then $E2E_COMMAND "$GLOB_FEATURE_PATHS" # run without expanding glob pattern else # shellcheck disable=SC2086 $E2E_COMMAND $FEATURE_PATHS # do not enclose paths with quote fi exit $? } function checkSuites() { # $1 - suites (separated by space or newline) for e_suite in $1; do exists=false for a_suite in $ALL_SUITES; do if [[ "$e_suite" == "$a_suite" ]]; then exists=true fi done if [[ "$exists" == false ]]; then log error "Suite doesn't exist: '$e_suite'" exit 1 fi done } function buildSuitesPattern() { CURRENT_SUITES_COUNT=$(echo "$1" | wc -w) # count words suites=$(echo "$1" | xargs | sed -E "s/( )+/,/g") if [[ $CURRENT_SUITES_COUNT -gt 1 ]]; then suites="{$suites}" fi GLOB_FEATURE_PATHS="$FEATURES_DIR/$suites/**/*.feature" } # 1. [RUN E2E] run features from provided paths if [[ -n $FEATURE_PATHS_FROM_ARG && "$SKIP_RUN_PARTS" == true ]]; then getFeaturePaths "$FEATURE_PATHS_FROM_ARG" log info "Running e2e using paths. All cli options will be discarded" runE2E fi # check if suites exist if [[ -n $FILTER_SUITES ]]; then checkSuites "$FILTER_SUITES" ALL_SUITES=$FILTER_SUITES fi if [[ -n $EXCLUDE_SUITES ]]; then checkSuites "$EXCLUDE_SUITES" fi # exclude suites from running if [[ -n $EXCLUDE_SUITES ]]; then for exclude_suite in $EXCLUDE_SUITES; do ALL_SUITES=$(echo "${ALL_SUITES/$exclude_suite/}" | sed -E "/^( )*$/d") # remove suite and trim empty lines done fi if [[ "$SKIP_RUN_PARTS" != true ]]; then if [[ -z $RUN_PART ]]; then log error "Missing '--run-part'" log cmd "--run-part <number>" exit 1 fi if [[ -z $TOTAL_PARTS ]]; then log error "Missing '--total-parts'" log cmd "--total-parts <number>" exit 1 fi ALL_SUITES_COUNT=$(echo "${ALL_SUITES}" | wc -l) SUITES_PER_RUN=$((ALL_SUITES_COUNT / TOTAL_PARTS)) REMAINING_SUITES=$((ALL_SUITES_COUNT - (TOTAL_PARTS * SUITES_PER_RUN))) if [[ ${RUN_PART} -le ${REMAINING_SUITES} ]]; then SUITES_PER_RUN=$((SUITES_PER_RUN + 1)) PREVIOUS_SUITES_COUNT=$(((RUN_PART - 1) * SUITES_PER_RUN)) else PREV_MAX_SUITES=$((REMAINING_SUITES * (SUITES_PER_RUN + 1))) PREV_MIN_SUITES=$((((RUN_PART - 1) - REMAINING_SUITES) * SUITES_PER_RUN)) PREVIOUS_SUITES_COUNT=$((PREV_MAX_SUITES + PREV_MIN_SUITES)) fi GRAB_SUITES_UPTO=$((PREVIOUS_SUITES_COUNT + SUITES_PER_RUN)) ALL_SUITES=$(echo "${ALL_SUITES}" | head -n "$GRAB_SUITES_UPTO" | tail -n "$SUITES_PER_RUN") fi buildSuitesPattern "$ALL_SUITES" # 2. [RUN E2E] run the suites runE2E
owncloud/web/tests/e2e/run-e2e.sh/0
{ "file_path": "owncloud/web/tests/e2e/run-e2e.sh", "repo_id": "owncloud", "token_count": 2956 }
880
export { createShare } from './share'
owncloud/web/tests/e2e/support/api/share/index.ts/0
{ "file_path": "owncloud/web/tests/e2e/support/api/share/index.ts", "repo_id": "owncloud", "token_count": 11 }
881