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="M12 3c4.284 0 8.22 1.497 11.31 3.996L12 21 .69 6.997C3.78 4.497 7.714 3 12 3zm0 2c-3.028 0-5.923.842-8.42 2.392l3.178 3.935C8.316 10.481 10.102 10 12 10c1.898 0 3.683.48 5.241 1.327L20.42 7.39C17.922 5.841 15.027 5 12 5z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/signal-wifi-2-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/signal-wifi-2-fill.svg", "repo_id": "owncloud", "token_count": 215 }
761
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M13.96 6.504l2.829-2.828a1 1 0 0 1 1.414 0l2.121 2.121a1 1 0 0 1 0 1.414l-2.828 2.829 1.767 1.768-1.414 1.414-7.07-7.071 1.413-1.414 1.768 1.767zM10.778 8.98l4.243 4.243L7.243 21H3v-4.243l7.778-7.778z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/sip-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/sip-fill.svg", "repo_id": "owncloud", "token_count": 213 }
762
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M6.027 17.43A8.003 8.003 0 0 1 9 2a8.003 8.003 0 0 1 7.458 5.099A5.5 5.5 0 0 1 18 17.978a6 6 0 0 0-11.973-.549zM13 16.267l1.964-1.134 1 1.732L14 18l1.964 1.134-1 1.732L13 19.732V22h-2v-2.268l-1.964 1.134-1-1.732L10 18l-1.964-1.134 1-1.732L11 16.268V14h2v2.268z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/snowy-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/snowy-fill.svg", "repo_id": "owncloud", "token_count": 253 }
763
<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.5 2.5L23 12l-5.5 9.5h-11L1 12l5.5-9.5h11zm-1.153 2H7.653L3.311 12l4.342 7.5h8.694l4.342-7.5-4.342-7.5zM11 15h2v2h-2v-2zm0-8h2v6h-2V7z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/spam-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/spam-line.svg", "repo_id": "owncloud", "token_count": 201 }
764
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M12 17l-5.878 3.59 1.598-6.7-5.23-4.48 6.865-.55L12 2.5l2.645 6.36 6.866.55-5.231 4.48 1.598 6.7L12 17zm0-2.344l2.817 1.72-.766-3.21 2.507-2.147-3.29-.264L12 7.708l-1.268 3.047-3.29.264 2.507 2.147-.766 3.21L12 14.657z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/star-s-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/star-s-line.svg", "repo_id": "owncloud", "token_count": 226 }
765
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M8 5h3v9H8v3H6v-3H3V5h3V2h2v3zM5 7v5h4V7H5zm13 3h3v9h-3v3h-2v-3h-3v-9h3V7h2v3zm-3 2v5h4v-5h-4z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/stock-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/stock-line.svg", "repo_id": "owncloud", "token_count": 177 }
766
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M5.596 4L10.5 9.928 15.404 4H18l-6.202 7.497L18 18.994V19h-2.59l-4.91-5.934L5.59 19H3v-.006l6.202-7.497L3 4h2.596zM21.55 16.58a.8.8 0 1 0-1.32-.36l-1.155.33A2.001 2.001 0 0 1 21 14a2 2 0 0 1 1.373 3.454L20.744 19H23v1h-4v-1l2.55-2.42z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/subscript.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/subscript.svg", "repo_id": "owncloud", "token_count": 240 }
767
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M6.341 14A6 6 0 1 1 12 18v-4H6.341zM6 20h9v2H6v-2zm-5-9h3v2H1v-2zm1 5h8v2H2v-2zm9-15h2v3h-2V1zM3.515 4.929l1.414-1.414L7.05 5.636 5.636 7.05 3.515 4.93zM16.95 18.364l1.414-1.414 2.121 2.121-1.414 1.414-2.121-2.121zm2.121-14.85l1.414 1.415-2.121 2.121-1.414-1.414 2.121-2.121zM23 11v2h-3v-2h3z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/sun-foggy-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/sun-foggy-fill.svg", "repo_id": "owncloud", "token_count": 291 }
768
<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="M12 3v18H7.6A4.6 4.6 0 0 1 3 16.4V7.6A4.6 4.6 0 0 1 7.6 3H12zm-2 2H7.6A2.6 2.6 0 0 0 5 7.6v8.8A2.6 2.6 0 0 0 7.6 19H10V5zm-2.5 5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zM14 3h2.4A4.6 4.6 0 0 1 21 7.6v8.8a4.6 4.6 0 0 1-4.6 4.6H14V3zm3 11.7a1.8 1.8 0 1 0 0-3.6 1.8 1.8 0 0 0 0 3.6z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/switch-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/switch-line.svg", "repo_id": "owncloud", "token_count": 296 }
769
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M15 21H9V10h6v11zm2 0V10h5v10a1 1 0 0 1-1 1h-4zM7 21H3a1 1 0 0 1-1-1V10h5v11zM22 8H2V4a1 1 0 0 1 1-1h18a1 1 0 0 1 1 1v4z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/table-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/table-fill.svg", "repo_id": "owncloud", "token_count": 173 }
770
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M12 11a5 5 0 0 1 5 5v6H7v-6a5 5 0 0 1 5-5zm-6.712 3.006a6.983 6.983 0 0 0-.28 1.65L5 16v6H2v-4.5a3.5 3.5 0 0 1 3.119-3.48l.17-.014zm13.424 0A3.501 3.501 0 0 1 22 17.5V22h-3v-6c0-.693-.1-1.362-.288-1.994zM5.5 8a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5zm13 0a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5zM12 2a4 4 0 1 1 0 8 4 4 0 0 1 0-8z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/team-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/team-fill.svg", "repo_id": "owncloud", "token_count": 298 }
771
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M11 5v10H9v-4a4 4 0 1 1 0-8h8v2h-2v10h-2V5h-2zM9 5a2 2 0 1 0 0 4V5zm8 12v-2.5l4 3.5-4 3.5V19H5v-2h12z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/text-direction-l.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/text-direction-l.svg", "repo_id": "owncloud", "token_count": 167 }
772
<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="M5 5v14h14V5H5zm0-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zm3 4h2a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1zm6 0h2a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1h-2a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/trello-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/trello-line.svg", "repo_id": "owncloud", "token_count": 253 }
773
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M17.654 1.7l-2.782 2.533a9.137 9.137 0 0 1 3.49 1.973c3.512 3.2 3.512 8.388 0 11.588-2.592 2.36-6.598 3.862-12.016 4.506l2.782-2.533a9.137 9.137 0 0 1-3.49-1.973c-3.512-3.2-3.533-8.369 0-11.588C8.23 3.846 12.237 2.344 17.655 1.7zM12 6c-3.866 0-7 2.686-7 6s3.134 6 7 6 7-2.686 7-6-3.134-6-7-6zm0 2.3c2.21 0 4 1.657 4 3.7s-1.79 3.7-4 3.7-4-1.657-4-3.7 1.79-3.7 4-3.7zm0 2c-1.138 0-2 .797-2 1.7 0 .903.862 1.7 2 1.7s2-.797 2-1.7c0-.903-.862-1.7-2-1.7z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/typhoon-line.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/typhoon-line.svg", "repo_id": "owncloud", "token_count": 388 }
774
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M7 20.981a6.5 6.5 0 0 1-2.936-12 8.001 8.001 0 0 1 15.872 0 6.5 6.5 0 0 1-2.936 12V21H7v-.019zM13 13h3l-4-5-4 5h3v4h2v-4z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/upload-cloud-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/upload-cloud-fill.svg", "repo_id": "owncloud", "token_count": 171 }
775
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M12 14v8H4a8 8 0 0 1 8-8zm0-1c-3.315 0-6-2.685-6-6s2.685-6 6-6 6 2.685 6 6-2.685 6-6 6zm2.595 5.812a3.51 3.51 0 0 1 0-1.623l-.992-.573 1-1.732.992.573A3.496 3.496 0 0 1 17 14.645V13.5h2v1.145c.532.158 1.012.44 1.405.812l.992-.573 1 1.732-.992.573a3.51 3.51 0 0 1 0 1.622l.992.573-1 1.732-.992-.573a3.496 3.496 0 0 1-1.405.812V22.5h-2v-1.145a3.496 3.496 0 0 1-1.405-.812l-.992.573-1-1.732.992-.572zM18 17a1 1 0 1 0 0 2 1 1 0 0 0 0-2z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/user-settings-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/user-settings-fill.svg", "repo_id": "owncloud", "token_count": 355 }
776
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M2 19h20v2H2v-2zM2 5l5 3 5-6 5 6 5-3v12H2V5z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/vip-crown-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/vip-crown-fill.svg", "repo_id": "owncloud", "token_count": 122 }
777
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M5.889 16H2a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1h3.889l5.294-4.332a.5.5 0 0 1 .817.387v15.89a.5.5 0 0 1-.817.387L5.89 16zm14.525-4l3.536 3.536-1.414 1.414L19 13.414l-3.536 3.536-1.414-1.414L17.586 12 14.05 8.464l1.414-1.414L19 10.586l3.536-3.536 1.414 1.414L20.414 12z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/volume-mute-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/volume-mute-fill.svg", "repo_id": "owncloud", "token_count": 249 }
778
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M2 9h19a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V9zm1-6h15v4H2V4a1 1 0 0 1 1-1zm12 11v2h3v-2h-3z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/wallet-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/wallet-fill.svg", "repo_id": "owncloud", "token_count": 163 }
779
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0H24V24H0z"/> <path d="M8 10.341v2.194C6.804 13.227 6 14.52 6 16c0 2.21 1.79 4 4 4 1.48 0 2.773-.804 3.465-2h2.193c-.823 2.33-3.046 4-5.658 4-3.314 0-6-2.686-6-6 0-2.613 1.67-4.835 4-5.659zM12 17c-1.657 0-3-1.343-3-3v-4c0-1.657 1.343-3 3-3s3 1.343 3 3v5h1.434c.648 0 1.253.314 1.626.836l.089.135 2.708 4.515-1.714 1.028L16.433 17H12zm0-15c1.38 0 2.5 1.12 2.5 2.5S13.38 7 12 7 9.5 5.88 9.5 4.5 10.62 2 12 2z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/wheelchair-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/wheelchair-fill.svg", "repo_id": "owncloud", "token_count": 327 }
780
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <g> <path fill="none" d="M0 0h24v24H0z"/> <path d="M11 15.934A7.501 7.501 0 0 1 12 1a7.5 7.5 0 0 1 1 14.934V18h5v2h-5v4h-2v-4H6v-2h5v-2.066z"/> </g> </svg>
owncloud/web/packages/design-system/src/assets/icons/women-fill.svg/0
{ "file_path": "owncloud/web/packages/design-system/src/assets/icons/women-fill.svg", "repo_id": "owncloud", "token_count": 152 }
781
import { shallowMount } from 'web-test-helpers' import Avatars from './OcAvatars.vue' const items = [ { id: 'bob', username: 'bob', displayName: 'Bob', avatar: 'https://images.unsplash.com/photo-1610216705422-caa3fcb6d158?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTB8fGZhY2V8ZW58MHwyfDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60', shareType: 0 }, { id: 'link0', link: 'fake url content', name: 'link 0', shareType: 3 }, { id: 'marie', username: 'marie', displayName: 'Marie', avatar: 'https://images.unsplash.com/photo-1584308972272-9e4e7685e80f?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mzh8fGZhY2V8ZW58MHwyfDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60', shareType: 0 }, { id: 'john', username: 'john', displayName: 'John Richards Emperor of long names', shareType: 0 }, { id: 'link1', link: 'fake url content', name: 'link 1', shareType: 3 } ] describe('OcAvatars', () => { it('displays tooltip', () => { const OcTooltip = vi.fn() const wrapper = shallowMount(Avatars, { props: { items, maxDisplayed: 2, isTooltipDisplayed: true, accessibleDescription: 'List of users' }, global: { directives: { OcTooltip } } }) expect(OcTooltip.mock.calls[0][1].value).toMatch('Bob, Marie +3') expect(wrapper.html()).toMatchSnapshot() }) it('prefers avatars over links when maxDisplayed is exceeded', () => { const OcTooltip = vi.fn() const wrapper = shallowMount(Avatars, { props: { items, maxDisplayed: 3, isTooltipDisplayed: true, accessibleDescription: 'List of users' }, global: { directives: { OcTooltip } } }) expect(OcTooltip.mock.calls[0][1].value).toMatch( 'Bob, Marie, John Richards Emperor of long names +2' ) expect(wrapper.html()).toMatchSnapshot() }) it('shows avatars first and links last', () => { const OcTooltip = vi.fn() const wrapper = shallowMount(Avatars, { props: { items, isTooltipDisplayed: true, accessibleDescription: 'List of users' }, global: { directives: { OcTooltip } } }) expect(OcTooltip.mock.calls[0][1].value).toMatch( 'Bob, Marie, John Richards Emperor of long names, link 0, link 1' ) expect(wrapper.html()).toMatchSnapshot() }) })
owncloud/web/packages/design-system/src/components/OcAvatars/OcAvatars.spec.ts/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcAvatars/OcAvatars.spec.ts", "repo_id": "owncloud", "token_count": 1193 }
782
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`OcDrop > tippy > renders tippy 1`] = ` <div> <p aria-describedby="tippy-10" aria-expanded="true" id="trigger" > trigger </p> <div data-tippy-root="" id="tippy-10" style="z-index: 9999; visibility: visible; position: absolute; left: 0px; top: auto; margin: 0px; right: auto; bottom: 0px; transform: translate(0px, 0px); max-height: -20px; overflow-y: auto; overflow-x: hidden;" > <div class="tippy-box" data-animation="fade" data-escaped="" data-placement="top" data-reference-hidden="" data-state="visible" data-theme="none" role="tooltip" style="max-width: 416px; transition-duration: 300ms;" tabindex="-1" > <div class="tippy-content" data-state="visible" style="transition-duration: 300ms;" > <div class="oc-drop oc-box-shadow-medium oc-rounded" id="oc-drop-15" > <div class="oc-card oc-card-body oc-background-secondary oc-p-m" > show </div> </div> </div> </div> </div> </div> `; exports[`OcDrop > tippy > renders tippy 2`] = ` <div> <p aria-expanded="false" id="trigger" > trigger </p> <div data-tippy-root="" id="tippy-10" style="z-index: 9999; visibility: hidden; position: absolute; left: 0px; top: auto; margin: 0px; right: auto; bottom: 0px; transform: translate(0px, 0px); max-height: -20px; overflow-y: auto; overflow-x: hidden; pointer-events: none;" > <div class="tippy-box" data-animation="fade" data-escaped="" data-placement="top" data-reference-hidden="" data-state="hidden" data-theme="none" role="tooltip" style="max-width: 416px; transition-duration: 250ms;" tabindex="-1" > <div class="tippy-content" data-state="hidden" style="transition-duration: 250ms;" > <div class="oc-drop oc-box-shadow-medium oc-rounded" id="oc-drop-15" > <div class="oc-card oc-card-body oc-background-secondary oc-p-m" > show </div> </div> </div> </div> </div> </div> `; exports[`OcDrop > tippy > renders tippy 3`] = ` <div> <p aria-describedby="tippy-10" aria-expanded="true" id="trigger" > trigger </p> <div data-tippy-root="" id="tippy-10" style="z-index: 9999; visibility: visible; position: absolute; left: 0px; top: auto; margin: 0px; right: auto; bottom: 0px; transform: translate(0px, 0px); max-height: -20px; overflow-y: auto; overflow-x: hidden;" > <div class="tippy-box" data-animation="fade" data-escaped="" data-placement="top" data-reference-hidden="" data-state="visible" data-theme="none" role="tooltip" style="max-width: 416px; transition-duration: 300ms;" tabindex="-1" > <div class="tippy-content" data-state="visible" style="transition-duration: 300ms;" > <div class="oc-drop oc-box-shadow-medium oc-rounded" id="oc-drop-15" > <div class="oc-card oc-card-body oc-background-secondary oc-p-m" > show </div> </div> </div> </div> </div> </div> `;
owncloud/web/packages/design-system/src/components/OcDrop/__snapshots__/OcDrop.spec.ts.snap/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcDrop/__snapshots__/OcDrop.spec.ts.snap", "repo_id": "owncloud", "token_count": 1814 }
783
<template> <oc-drop ref="drop" class="oc-width-1-1 oc-info-drop" :drop-id="dropId" :toggle="toggle" :mode="mode" close-on-click > <div class="info-drop-content"> <div v-if="title" class="oc-flex oc-flex-between info-header oc-border-b oc-pb-s"> <h4 class="oc-m-rm info-title" v-text="$gettext(title)" /> <oc-button appearance="raw"> <oc-icon name="close" fill-type="line" size="medium" variation="inherit" /> </oc-button> </div> <p class="info-text" v-text="$gettext(text)" /> <dl v-if="list.length" class="info-list"> <component :is="item.headline ? 'dt' : 'dd'" v-for="(item, index) in list" :key="index"> {{ $gettext(item.text) }} </component> </dl> <p v-if="endText" class="info-text-end" v-text="$gettext(endText)" /> <oc-button v-if="readMoreLink" type="a" appearance="raw" size="small" class="info-more-link" :href="readMoreLink" target="_blank" > {{ $gettext('Read more') }} </oc-button> </div> </oc-drop> </template> <script lang="ts"> import { defineComponent, PropType } from 'vue' import OcButton from '../OcButton/OcButton.vue' import OcIcon from '../OcIcon/OcIcon.vue' import OcDrop from '../OcDrop/OcDrop.vue' import uniqueId from '../../utils/uniqueId' export type ListElement = { text: string headline?: string } export default defineComponent({ name: 'OcInfoDrop', status: 'unreleased', components: { OcButton, OcIcon, OcDrop }, props: { /** * Id of the element */ dropId: { type: String, required: false, default: () => uniqueId('oc-info-drop-') }, /** * CSS selector for the element to be used as toggle. By default, the preceding element is used **/ toggle: { type: String, required: false, default: '' }, /** * Events that cause the drop to show. Multiple event names are separated by spaces * * @values click, hover, manual **/ mode: { type: String, required: false, default: 'click', validator: (value: string) => { return ['click', 'hover', 'manual'].includes(value) } }, /** * Element selector used as a target of the element */ target: { type: String, required: false, default: null }, /** * Title */ title: { type: String, required: false, default: '' }, /** * Text at the beginning */ text: { type: String, required: false, default: '' }, /** * List element */ list: { type: Array as PropType<ListElement[]>, required: false, default: () => [] }, /** * Text at the end */ endText: { type: String, required: false, default: '' }, /** * Read more link at the end */ readMoreLink: { type: String, required: false, default: '' } } }) </script> <style lang="scss"> .oc-info-drop { display: inline-block; .oc-button { vertical-align: middle; } .info-drop-content { font-size: var(--oc-font-size-medium); color: var(--oc-color-text-default); } .info-more-link { font-size: var(--oc-font-size-medium) !important; } .info-header { align-items: center; } .info-title { font-size: 1.125rem; font-weight: normal; } .info-list { dt { &:first-child { margin-top: 0; } font-weight: bold; margin-bottom: var(--oc-space-xsmall); margin-top: var(--oc-space-small); } dd { margin-left: 0; font-weight: normal; } } } </style> <docs> ## Examples A simple example, using only text. ```js <template> <div> <oc-info-drop v-bind="helperContent"/> </div> </template> <script> export default { computed: { helperContent() { return { text: "Invite persons or groups to access this file or folder.", } } }, } </script> ``` An example using Title, Text, List, End-Text and Read-More-Link properties. ```js <template> <div> <oc-info-drop v-bind="helperContent"/> </div> </template> <script> export default { computed: { helperContent() { return { title: 'Choose how access is granted ', text: "Share a file or folder by link", list: [ {text: "Only invited people can access", headline: true}, {text: "Only people from the list \"Invited people\" can access. If there is no list, no people are invited yet."}, {text: "Everyone with the link", headline: true }, {text: "Everyone with the link can access. Note: If you share this link with people from the list \"Invited people\", they need to login-in so that their individual assigned permissions can take effect. If they are not logged-in, the permissions of the link take effect." } ], endText: "Invited persons can not see who else has access", readMoreLink: "https://owncloud.design" } } }, } </script> ``` </docs>
owncloud/web/packages/design-system/src/components/OcInfoDrop/OcInfoDrop.vue/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcInfoDrop/OcInfoDrop.vue", "repo_id": "owncloud", "token_count": 2249 }
784
<template> <nav class="oc-pagination" :aria-label="$gettext('Pagination')"> <ol class="oc-pagination-list"> <li v-if="isPrevPageAvailable" class="oc-pagination-list-item"> <router-link class="oc-pagination-list-item-prev" :aria-label="$gettext('Go to the previous page')" :to="previousPageLink" > <oc-icon name="arrow-drop-left" fill-type="line" /> </router-link> </li> <li v-for="(page, index) in displayedPages" :key="index" class="oc-pagination-list-item"> <component :is="pageComponent(page)" :class="pageClass(page)" v-bind="bindPageProps(page)"> {{ page }} </component> </li> <li v-if="isNextPageAvailable" class="oc-pagination-list-item"> <router-link class="oc-pagination-list-item-next" :aria-label="$gettext('Go to the next page')" :to="nextPageLink" > <oc-icon name="arrow-drop-right" fill-type="line" /> </router-link> </li> </ol> </nav> </template> <script lang="ts"> import { defineComponent } from 'vue' import OcIcon from '../OcIcon/OcIcon.vue' /** * A list of links used for switching to different pages */ export default defineComponent({ name: 'OcPagination', status: 'ready', release: '7.2.0', components: { OcIcon }, props: { /** * Number of pages to be displayed */ pages: { type: Number, required: true }, /** * Currently active page */ currentPage: { type: Number, required: true }, /** * Number of pages to be displayed. It is required to use an odd number. * Pages will be equally split into two parts around the current page and remaining pages will be displayed as ellipsis */ maxDisplayed: { type: Number, required: false, default: null, validator: (value: number) => { if (value % 2 === 0) { // Since Vue doesn't support custom validator error message, log the error manually console.error('maxDisplayed needs to be an odd number') return false } return true } }, /** * Current route which is used to render pages */ currentRoute: { type: Object, required: true } }, computed: { displayedPages() { let pages = [] for (let i = 0; i < this.pages; i++) { pages.push(i + 1) } if (this.maxDisplayed && this.maxDisplayed + 1 < this.pages) { const currentPageIndex = this.$_currentPage - 1 const indentation = Math.floor(this.maxDisplayed / 2) pages = pages.slice( Math.max(0, currentPageIndex - indentation), currentPageIndex + indentation + 1 ) if (this.$_currentPage > 2) { pages[0] > 2 ? pages.unshift(1, '...') : pages.unshift(1) } if (this.$_currentPage < this.pages - 1) { pages[pages.length - 1] < this.pages - 1 ? pages.push('...', this.pages) : pages.push(this.pages) } return pages } return pages }, isPrevPageAvailable() { return this.$_currentPage > 1 }, isNextPageAvailable() { return this.$_currentPage < this.pages }, previousPageLink() { return this.bindPageLink(this.$_currentPage - 1) }, nextPageLink() { return this.bindPageLink(this.$_currentPage + 1) }, $_currentPage() { return Math.max(1, Math.min(this.currentPage, this.pages)) } }, methods: { pageLabel(page) { return this.$gettext('Go to page %{ page }', { page }) }, isCurrentPage(page) { return this.$_currentPage === page }, pageComponent(page) { return page === '...' || this.isCurrentPage(page) ? 'span' : 'router-link' }, bindPageProps(page) { if (page === '...') { return } if (this.isCurrentPage(page)) { return { 'aria-current': 'page' } } const link = this.bindPageLink(page) return { 'aria-label': this.pageLabel(page), to: link } }, pageClass(page) { const classes = ['oc-pagination-list-item-page'] if (this.isCurrentPage(page)) { classes.push('oc-pagination-list-item-current') } else if (page === '...') { classes.push('oc-pagination-list-item-ellipsis') } else { classes.push('oc-pagination-list-item-link') } return classes }, bindPageLink(page) { return { name: this.currentRoute.name, query: { ...this.currentRoute.query, page }, params: this.currentRoute.params } } } }) </script> <style lang="scss"> .oc-pagination { &-list { align-items: center; display: flex; flex-wrap: wrap; gap: var(--oc-space-small); list-style: none; margin: 0; padding: 0; &-item { &-page { border-radius: 4px; color: var(--oc-color-text-default); padding: var(--oc-space-xsmall) var(--oc-space-small); transition: background-color $transition-duration-short ease-in-out; &:not(span):hover { background-color: var(--oc-color-swatch-passive-default); color: var(--oc-color-text-inverse); text-decoration: none; } } &-current { background-color: var(--oc-color-swatch-passive-default); color: var(--oc-color-text-inverse); font-weight: bold; } &-prev, &-next { display: flex; > .oc-icon > svg { fill: var(--oc-color-text-default); } } &-prev { margin-right: var(--oc-space-small); } &-next { margin-left: var(--oc-space-small); } } } } </style> <docs> ## Examples ```js <div class="oc-flex oc-flex-column" style="gap: 20px;"> <oc-pagination :pages="3" :currentPage="3" :currentRoute="{ name: 'files' }" /> <oc-pagination :pages="4" :currentPage="1" :currentRoute="{ name: 'files' }" /> <oc-pagination :pages="5" :currentPage="3" :currentRoute="{ name: 'files' }" /> </div> ``` ### Truncate visible pages with ellipsis If the current page is close enough to the first or/and last page and ellipsis would hide only 1 page, ellipsis will be omitted and the actual page will be still displayed instead. ```js <div class="oc-flex oc-flex-column" style="gap: 20px;"> <oc-pagination :pages="5" :currentPage="3" :maxDisplayed="3" :currentRoute="{ name: 'files' }" /> <oc-pagination :pages="10" :currentPage="3" :maxDisplayed="3" :currentRoute="{ name: 'files' }" /> <oc-pagination :pages="54" :currentPage="28" :maxDisplayed="3" :currentRoute="{ name: 'files' }" /> <oc-pagination :pages="54" :currentPage="51" :maxDisplayed="5" :currentRoute="{ name: 'files' }" /> </div> ``` </docs>
owncloud/web/packages/design-system/src/components/OcPagination/OcPagination.vue/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcPagination/OcPagination.vue", "repo_id": "owncloud", "token_count": 3093 }
785
<template> <div class="oc-status-indicators"> <template v-for="indicator in indicators"> <oc-button v-if="hasHandler(indicator)" :id="indicator.id" :key="indicator.id" v-oc-tooltip="$gettext(indicator.label)" class="oc-status-indicators-indicator oc-ml-xs" :aria-label="$gettext(indicator.label)" :aria-describedby="getIndicatorDescriptionId(indicator)" appearance="raw" :data-testid="indicator.id" :data-test-indicator-type="indicator.type" @click="indicator.handler(resource, indicator.target, $router)" > <oc-icon :name="indicator.icon" size="small" :fill-type="indicator.fillType" variation="inherit" /> </oc-button> <oc-icon v-else :id="indicator.id" :key="indicator.id" v-oc-tooltip="$gettext(indicator.label)" tabindex="-1" size="small" class="oc-status-indicators-indicator oc-ml-xs" :name="indicator.icon" :fill-type="indicator.fillType" :accessible-label="$gettext(indicator.label)" :aria-describedby="getIndicatorDescriptionId(indicator)" :data-testid="indicator.id" :data-test-indicator-type="indicator.type" /> <p v-if="getIndicatorDescriptionId(indicator)" :id="getIndicatorDescriptionId(indicator)" :key="getIndicatorDescriptionId(indicator)" class="oc-invisible-sr" v-text="$gettext(indicator.accessibleDescription)" /> </template> </div> </template> <script lang="ts"> import { defineComponent, PropType, ref, unref } from 'vue' import OcIcon from '../OcIcon/OcIcon.vue' import OcButton from '../OcButton/OcButton.vue' import uniqueId from '../../utils/uniqueId' type Indicator = { id: string icon: string label: string handler?: any accessibleDescription?: string visible?: boolean target?: string type?: string fillType?: string } /** * Status indicators which can be attatched to a resource */ export default defineComponent({ name: 'OcStatusIndicators', status: 'ready', release: '2.0.1', components: { OcIcon, OcButton }, props: { /** * A resource to which the indicators are attatched to */ resource: { type: Object, required: true }, /** * An array of indicators to be displayed. Indicator object has following properties: * * Required: * id: Id of the indicator * icon: Icon of the indicator * label: String to be used as a accessible label and tooltip for the indicator * * Optional: * handler: An action to be triggered when the indicator is clicked. Receives the resource and a target string * accessibleDescription: A string to be used as a accessible description for the indicator. It renders an element only visible for screenreaders to provide additional context */ indicators: { type: Array as PropType<Indicator[]>, required: true }, target: { type: String, required: false, default: '' } }, setup() { const accessibleDescriptionIds = ref({} as Record<string, string>) const hasHandler = (indicator: Indicator): boolean => { return Object.prototype.hasOwnProperty.call(indicator, 'handler') } const getIndicatorDescriptionId = (indicator: Indicator): string | null => { if (!indicator.accessibleDescription) { return null } if (!unref(accessibleDescriptionIds)[indicator.id]) { unref(accessibleDescriptionIds)[indicator.id] = uniqueId('oc-indicator-description-') } return unref(accessibleDescriptionIds)[indicator.id] } return { accessibleDescriptionIds, hasHandler, getIndicatorDescriptionId } } }) </script> <style lang="scss"> .oc-status-indicators { align-items: center; display: flex; justify-content: flex-end; } </style> <docs> ```js <template> <oc-status-indicators :resource="resource" :indicators="indicators" /> </template> <script> export default { data: () => ({ resource: { name: "Documents", path: "/" }, indicators: [ { id: 'files-sharing', label: "Shared with other people", icon: 'group', handler: (resource, indicatorId) => alert(`Resource: ${resource.name}, indicator: ${indicatorId}`) }, { id: 'file-link', label: "Shared via link", icon: 'links', handler: (resource, indicatorId) => alert(`Resource: ${resource.name}, indicator: ${indicatorId}`) } ] }), } </script> ``` </docs>
owncloud/web/packages/design-system/src/components/OcStatusIndicators/OcStatusIndicators.vue/0
{ "file_path": "owncloud/web/packages/design-system/src/components/OcStatusIndicators/OcStatusIndicators.vue", "repo_id": "owncloud", "token_count": 1935 }
786
<template> <div class="all-tokens"> <table> <caption class="oc-invisible-sr"> {{ $gettext('A list of all defined design tokens') }} </caption> <thead> <tr> <th>{{ $gettext('Token Name') }}</th> <th>{{ $gettext('Value') }}</th> <th>{{ $gettext('Category') }}</th> </tr> </thead> <tbody> <tr v-for="(token, index) in tokens" :key="index" class="token"> <td v-if="token.name"> <code class="name">${{ token.name.replace(/_/g, '-') }}</code> </td> <td v-else>N/A</td> <td v-if="token.value"> <div v-if="token.name.startsWith('oc-color')" class="example color" :style="{ backgroundColor: token.value }" /> <code class="type">{{ token.value }} </code> </td> <td v-else>N/A</td> <td v-if="token.category"> {{ token.category }} </td> <td v-else>N/A</td> </tr> </tbody> </table> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' import designTokens from '../../assets/tokens/ods.json' /** * A list of available tokens in ownCloud Design System. Use these tokens in place * of hard-coded values in order to maintain a scalable and consistent system. * To edit these tokens and add more, see * [/src/tokens/](https://github.com/owncloud/owncloud-design-system/blob/master/src/tokens). */ export default defineComponent({ name: 'DocsAllTokens', data() { return { tokens: Object.values(designTokens) } } }) </script> <style lang="scss" scoped> @import '../../../docs/docs.tokens'; /* STYLES --------------------------------------------- */ .all-tokens { @include reset; margin-top: $space-l; font-family: $font-heading; font-weight: $weight-normal; line-height: $line-height-xs; color: $color-rich-black; margin-bottom: $space-s; font-style: normal; @media (max-width: 1000px) { overflow-x: auto; } table { border-collapse: collapse; border-spacing: 0; width: 100%; } thead th { padding: $space-s $space-l $space-s $space-s; background: $color-cloud; font-size: $size-s; color: $color-oxford-blue; text-transform: uppercase; letter-spacing: 1px; font-weight: $weight-semi-bold; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: left; // Chrome has a bug related to thead, this only works on th: position: -webkit-sticky; position: sticky; top: -1px; &:first-child { border-top-left-radius: $radius-default; border-bottom-left-radius: $radius-default; } &:last-child { border-top-right-radius: $radius-default; border-bottom-right-radius: $radius-default; } } tr { border-bottom: 1px solid #dfe3e6; &:last-child { border: 0; } } td { font-size: $size-s; padding: $space-s $space-l $space-s $space-s; &:first-child { font-weight: $weight-bold; white-space: nowrap; } } .type { line-height: $line-height-s; max-width: calc(100% - #{$space-m}); float: left; } .example { @include inline-space($space-xs); border-radius: $radius-default; background: $color-white; box-shadow: $shadow-s-inset, $shadow-s-inset, $shadow-s-inset; margin-top: $space-xx-small; width: $space-s; height: $space-s; float: left; } } </style> <docs> ```jsx <all-tokens /> ``` </docs>
owncloud/web/packages/design-system/src/components/_DocsAllTokens/_DocsAllTokens.vue/0
{ "file_path": "owncloud/web/packages/design-system/src/components/_DocsAllTokens/_DocsAllTokens.vue", "repo_id": "owncloud", "token_count": 1663 }
787
<template> <div> <oc-search-bar :value="query" :is-filter="true" :button-hidden="true" label="Filter icons by name" class="oc-mb" @input="updateQuery" /> <div class="oc-mb oc-px"> <strong>Displaying {{ filteredIcons.length }} out of {{ icons.length }} icons</strong> </div> <oc-table :fields="fields" :data="filteredIcons" :lazy="true"> <template #passive="{ item }"> <oc-icon :name="item.filename" :fill-type="item.fillType" size="large" variation="passive" /> </template> <template #primary="{ item }"> <oc-icon :name="item.filename" :fill-type="item.fillType" size="large" variation="primary" /> </template> <template #success="{ item }"> <oc-icon :name="item.filename" :fill-type="item.fillType" size="large" variation="success" /> </template> <template #warning="{ item }"> <oc-icon :name="item.filename" :fill-type="item.fillType" size="large" variation="warning" /> </template> <template #danger="{ item }"> <oc-icon :name="item.filename" :fill-type="item.fillType" size="large" variation="danger" /> </template> <template #filename="{ item }"> <highlighted-text :value="item.filename" :highlighted="query" /> </template> </oc-table> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' import OcIcon from '../OcIcon/OcIcon.vue' import OcTable from '../OcTable/OcTable.vue' import OcSearchBar from '../OcSearchBar/OcSearchBar.vue' import HighlightedText from '../_DocsHighlightedText/_DocsHighlightedText.vue' import { ref } from 'vue' const req = (require as any).context('../../../src/assets/icons/', true, /^\.\/.*\.svg$/) /** * All known icons in the ownCloud Design System * <p> * Icons made by <a href="https://remixicon.com/">Remixicon</a> and, in the case of the `resource-type-*` icons, <a href="https://fontawesome.com/">Font Awesome</a> (available under the [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/) license). * </p> */ export default defineComponent({ name: 'DocsIconList', components: { HighlightedText, OcSearchBar, OcIcon, OcTable }, setup() { const query = ref('') const updateQuery = (value) => { query.value = value } return { query, updateQuery } }, data() { return { icons: [] } }, computed: { filteredIcons() { return this.icons .filter((icon) => icon.includes(this.query)) .map((icon, index) => ({ id: index, filename: icon.replace('-fill', '').replace('-line', ''), fillType: icon.endsWith('-fill') ? 'fill' : icon.endsWith('-line') ? 'line' : 'none' })) }, fields() { return [ { name: 'passive', title: 'Passive', type: 'slot' }, { name: 'primary', title: 'Primary', type: 'slot' }, { name: 'success', title: 'Success', type: 'slot' }, { name: 'warning', title: 'Warning', type: 'slot' }, { name: 'danger', title: 'Danger', type: 'slot' }, { name: 'fillType', title: 'Fill type' }, { name: 'filename', title: 'Icon name', width: 'expand', type: 'slot' } ] } }, mounted() { this.icons = req.keys().map((filename) => { return filename.split('.').slice(0, -1).join('.').substring(2) }) } }) </script> <docs> ``` <docs-icon-list /> ``` </docs>
owncloud/web/packages/design-system/src/components/_docsIconList/_DocsIconList.vue/0
{ "file_path": "owncloud/web/packages/design-system/src/components/_docsIconList/_DocsIconList.vue", "repo_id": "owncloud", "token_count": 1879 }
788
$transition-duration-short: 200ms; $directions: ( "t": "top", "r": "right", "b": "bottom", "l": "left", "x": ("right", "left"), "y": ("top", "bottom") ); $sizes: ( "xs": $oc-space-xsmall, "s": $oc-space-small, "m": $oc-space-medium, "l": $oc-space-large, "xl": $oc-space-xlarge, "xxl": $oc-space-xxlarge ); $weights: ( "thin": $oc-font-weight-thin, "extralight": $oc-font-weight-extralight, "light": $oc-font-weight-light, "normal": $oc-font-weight-normal, "medium": $oc-font-weight-medium, "semibold": $oc-font-weight-semibold, "bold": $oc-font-weight-bold, "extrabold": $oc-font-weight-extrabold, "black": $oc-font-weight-black ); $global-control-height: 15px; $global-border-width: 2px;
owncloud/web/packages/design-system/src/styles/theme/_variables.scss/0
{ "file_path": "owncloud/web/packages/design-system/src/styles/theme/_variables.scss", "repo_id": "owncloud", "token_count": 326 }
789
.tippy-box { .tippy-content { word-wrap: break-word; } }
owncloud/web/packages/design-system/src/styles/theme/tooltip.scss/0
{ "file_path": "owncloud/web/packages/design-system/src/styles/theme/tooltip.scss", "repo_id": "owncloud", "token_count": 32 }
790
import { defineConfig, devices } from '@playwright/test' export default defineConfig({ testDir: './', testMatch: /.*\.spec\.ts/, fullyParallel: true, forbidOnly: process.env.CI === 'true', retries: process.env.CI === 'true' ? 2 : 0, workers: process.env.CI === 'true' ? 1 : undefined, reporter: 'html', projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] } } // Running these browsers currently produces an error in drone CI due to missing deps (even when they are installed first) // { // name: 'firefox', // use: { ...devices['Desktop Firefox'] } // }, // { // name: 'webkit', // use: { ...devices['Desktop Safari'] } // } // The mobile view of docs is currently pretty junky and causes various false negatives on mobile tests // { // name: 'Mobile Chrome', // use: { ...devices['Pixel 5'] } // }, // { // name: 'Mobile Safari', // use: { ...devices['iPhone 12'] } // } ], webServer: { command: 'NODE_ENV=production pnpm start', url: 'http://127.0.0.1:6060', reuseExistingServer: process.env.CI !== 'true', // Timeout is intentionally pretty high here due to the server boot taking a long time timeout: 5 * 60 * 1000 }, use: { baseURL: 'http://127.0.0.1:6060' } })
owncloud/web/packages/design-system/tests/e2e/playwright.config.ts/0
{ "file_path": "owncloud/web/packages/design-system/tests/e2e/playwright.config.ts", "repo_id": "owncloud", "token_count": 503 }
791
<template> <div> <h2 class="oc-py-s" v-text="$gettext('Appearance')" /> <div> <div class="oc-flex oc-flex-middle"> <h3 v-text="$gettext('Logo')" /> <oc-button v-if="menuItems.length" :id="`logo-context-btn`" v-oc-tooltip="$gettext('Show context menu')" :aria-label="$gettext('Show context menu')" appearance="raw" class="oc-ml-s" > <oc-icon name="more-2" /> </oc-button> <oc-drop :drop-id="`space-context-drop`" :toggle="`#logo-context-btn`" mode="click" close-on-click padding-size="small" > <context-action-menu :menu-sections="menuSections" :action-options="actionOptions" /> </oc-drop> </div> <div> <div class="logo-wrapper"> <img alt="" :src="currentTheme.logo.topbar" class="oc-p-xs" /> </div> <input id="logo-upload-input" ref="logoInput" type="file" name="file" tabindex="-1" :accept="supportedLogoMimeTypesAcceptValue" @change="uploadImage" /> </div> </div> </div> </template> <script lang="ts"> import { defineComponent, computed, unref, VNodeRef, ref } from 'vue' import { ContextActionMenu, useThemeStore } from '@ownclouders/web-pkg' import { useGeneralActionsResetLogo, useGeneralActionsUploadLogo } from '../../composables/actions/general' import { supportedLogoMimeTypes } from '../../defaults' import { storeToRefs } from 'pinia' export default defineComponent({ name: 'AppearanceSection', components: { ContextActionMenu }, setup() { const themeStore = useThemeStore() const { currentTheme } = storeToRefs(themeStore) const logoInput: VNodeRef = ref(null) const { actions: resetLogoActions } = useGeneralActionsResetLogo() const { actions: uploadLogoActions, uploadImage } = useGeneralActionsUploadLogo({ imageInput: logoInput }) const menuItems = computed(() => [...unref(uploadLogoActions), ...unref(resetLogoActions)].filter((i) => i.isVisible()) ) const actionOptions = computed(() => ({ resources: unref(menuItems) })) const menuSections = computed(() => [ { name: 'primaryActions', items: unref(menuItems) } ]) const supportedLogoMimeTypesAcceptValue = supportedLogoMimeTypes.join(',') return { actionOptions, currentTheme, menuItems, menuSections, supportedLogoMimeTypesAcceptValue, uploadImage, logoInput } } }) </script> <style lang="scss" scoped> #logo-upload-input { display: none; } .logo-wrapper { width: 280px; min-width: 280px; aspect-ratio: 16/9; max-height: 158px; img { border-radius: 10px; width: 100%; max-height: 100%; object-fit: cover; background: var(--oc-color-swatch-brand-default); } } </style>
owncloud/web/packages/web-app-admin-settings/src/components/General/AppearanceSection.vue/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/src/components/General/AppearanceSection.vue", "repo_id": "owncloud", "token_count": 1345 }
792
<template> <group-select :selected-groups="selectedOptions" :group-options="groups" @selected-option-change="changeSelectedGroupOption" /> </template> <script lang="ts"> import { defineComponent, PropType, ref, unref, watch } from 'vue' import { useGettext } from 'vue3-gettext' import { Group, User } from '@ownclouders/web-client/src/generated' import GroupSelect from './GroupSelect.vue' import { useClientService, Modal, useMessages, useConfigStore } from '@ownclouders/web-pkg' import { useUserSettingsStore } from '../../composables/stores/userSettings' export default defineComponent({ name: 'AddToGroupsModal', components: { GroupSelect }, props: { modal: { type: Object as PropType<Modal>, required: true }, groups: { type: Array as PropType<Group[]>, required: true }, users: { type: Array as PropType<User[]>, required: true } }, emits: ['update:confirmDisabled'], setup(props, { emit, expose }) { const { showMessage, showErrorMessage } = useMessages() const clientService = useClientService() const configStore = useConfigStore() const { $gettext, $ngettext } = useGettext() const userSettingsStore = useUserSettingsStore() const selectedOptions = ref<Group[]>([]) const changeSelectedGroupOption = (options: Group[]) => { selectedOptions.value = options } watch( selectedOptions, () => { emit('update:confirmDisabled', !unref(selectedOptions).length) }, { immediate: true } ) const onConfirm = async () => { const client = clientService.graphAuthenticated const usersToFetch = [] const promises = unref(selectedOptions).reduce((acc, group) => { for (const user of props.users) { if (!user.memberOf.find((userGroup) => userGroup.id === group.id)) { acc.push(client.groups.addMember(group.id, user.id, configStore.serverUrl)) if (!usersToFetch.includes(user.id)) { usersToFetch.push(user.id) } } } return acc }, []) if (!promises.length) { const title = $ngettext( 'Group assignment already added', 'Group assignments already added', props.users.length * unref(selectedOptions).length ) showMessage({ title }) return } const results = await Promise.allSettled(promises) const succeeded = results.filter((r) => r.status === 'fulfilled') if (succeeded.length) { const title = succeeded.length === 1 && unref(selectedOptions).length === 1 && props.users.length === 1 ? $gettext('Group assignment "%{group}" was added successfully', { group: unref(selectedOptions)[0].displayName }) : $ngettext( '%{groupAssignmentCount} group assignment was added successfully', '%{groupAssignmentCount} group assignments were added successfully', succeeded.length, { groupAssignmentCount: succeeded.length.toString() }, true ) showMessage({ title }) } const failed = results.filter((r) => r.status === 'rejected') if (failed.length) { failed.forEach(console.error) const title = failed.length === 1 && unref(selectedOptions).length === 1 && props.users.length === 1 ? $gettext('Failed to add group assignment "%{group}"', { group: unref(selectedOptions)[0].displayName }) : $ngettext( 'Failed to add %{groupAssignmentCount} group assignment', 'Failed to add %{groupAssignmentCount} group assignments', failed.length, { groupAssignmentCount: failed.length.toString() }, true ) showErrorMessage({ title, errors: (failed as PromiseRejectedResult[]).map((f) => f.reason) }) } try { const usersResponse = await Promise.all( usersToFetch.map((userId) => client.users.getUser(userId)) ) usersResponse.forEach(({ data }) => { userSettingsStore.upsertUser(data) }) } catch (e) { console.error(e) } } expose({ onConfirm }) return { selectedOptions, changeSelectedGroupOption, // unit tests onConfirm } } }) </script>
owncloud/web/packages/web-app-admin-settings/src/components/Users/AddToGroupsModal.vue/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/src/components/Users/AddToGroupsModal.vue", "repo_id": "owncloud", "token_count": 1900 }
793
import { eventBus } from '@ownclouders/web-pkg' import { SideBarEventTopics } from '@ownclouders/web-pkg' import { useGettext } from 'vue3-gettext' import { computed } from 'vue' import { GroupAction } from '@ownclouders/web-pkg' export const useGroupActionsEdit = () => { const { $gettext } = useGettext() const actions = computed((): GroupAction[] => [ { name: 'edit', icon: 'pencil', label: () => $gettext('Edit'), handler: () => eventBus.publish(SideBarEventTopics.openWithPanel, 'EditPanel'), isVisible: ({ resources }) => { return resources.length === 1 && !resources[0].groupTypes?.includes('ReadOnly') }, componentType: 'button', class: 'oc-groups-actions-edit-trigger' } ]) return { actions } }
owncloud/web/packages/web-app-admin-settings/src/composables/actions/groups/useGroupActionsEdit.ts/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/src/composables/actions/groups/useGroupActionsEdit.ts", "repo_id": "owncloud", "token_count": 295 }
794
import { defineStore } from 'pinia' import { ref, unref } from 'vue' import { SpaceResource } from '@ownclouders/web-client' export const useSpaceSettingsStore = defineStore('spaceSettings', () => { const spaces = ref<SpaceResource[]>([]) const selectedSpaces = ref<SpaceResource[]>([]) const setSpaces = (data: SpaceResource[]) => { spaces.value = data } const upsertSpace = (space: SpaceResource) => { const existing = unref(spaces).some(({ id }) => id === space.id) if (existing) { Object.assign(existing, space) return } unref(spaces).push(space) } const removeSpaces = (values: SpaceResource[]) => { spaces.value = unref(spaces).filter((space) => !values.find(({ id }) => id === space.id)) } const setSelectedSpaces = (data: SpaceResource[]) => { selectedSpaces.value = data } const addSelectedSpace = (data: SpaceResource) => { unref(selectedSpaces).push(data) } const reset = () => { spaces.value = [] selectedSpaces.value = [] } return { spaces, setSpaces, upsertSpace, removeSpaces, reset, selectedSpaces, addSelectedSpace, setSelectedSpaces } }) export type SpaceSettingsStore = ReturnType<typeof useSpaceSettingsStore>
owncloud/web/packages/web-app-admin-settings/src/composables/stores/spaceSettings.ts/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/src/composables/stores/spaceSettings.ts", "repo_id": "owncloud", "token_count": 447 }
795
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`MembersPanel > should display an empty result if no matching members found 1`] = ` "<div class="oc-ml-s"> <oc-text-input-stub id="oc-textinput-3" type="text" clearbuttonenabled="false" clearbuttonaccessiblelabel="" disabled="false" label="Filter members" fixmessageline="false" readonly="false" passwordpolicy="[object Object]" class="oc-text-truncate oc-mr-s oc-mt-m" modelvalue="no-match"></oc-text-input-stub> <div data-testid="space-members"> <div> <h3 class="oc-text-bold oc-text-medium">No members found</h3> </div> <!--v-if--> </div> </div>" `; exports[`MembersPanel > should render all members accordingly to their role assignments 1`] = ` "<div class="oc-ml-s"> <oc-text-input-stub id="oc-textinput-1" type="text" modelvalue="" clearbuttonenabled="false" clearbuttonaccessiblelabel="" disabled="false" label="Filter members" fixmessageline="false" readonly="false" passwordpolicy="[object Object]" class="oc-text-truncate oc-mr-s oc-mt-m"></oc-text-input-stub> <div data-testid="space-members"> <!--v-if--> <div class="oc-mb-m" data-testid="group-members"> <h3 class="oc-text-bold oc-text-medium">Members</h3> <members-role-section-stub groupmembers="undefined"></members-role-section-stub> </div> </div> </div>" `;
owncloud/web/packages/web-app-admin-settings/tests/unit/components/Groups/SideBar/__snapshots__/MembersPanel.spec.ts.snap/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/components/Groups/SideBar/__snapshots__/MembersPanel.spec.ts.snap", "repo_id": "owncloud", "token_count": 492 }
796
import { navItems, routes } from '../../src/index' import { Ability } from '@ownclouders/web-client/src/helpers/resource/types' import { mock } from 'vitest-mock-extended' const getAbilityMock = (hasPermission) => mock<Ability>({ can: () => hasPermission }) describe('admin settings index', () => { describe('navItems', () => { describe('general', () => { it.each([true, false])('should be enabled according to the permissions', (enabled) => { expect( navItems({ $ability: getAbilityMock(enabled) }) .find((n) => n.name === 'General') .isVisible() ).toBe(enabled) }) }) describe('user management', () => { it.each([true, false])('should be enabled according to the permissions', (enabled) => { expect( navItems({ $ability: getAbilityMock(enabled) }) .find((n) => n.name === 'Users') .isVisible() ).toBe(enabled) }) }) describe('group management', () => { it.each([true, false])('should be enabled according to the permissions', (enabled) => { expect( navItems({ $ability: getAbilityMock(enabled) }) .find((n) => n.name === 'Groups') .isVisible() ).toBe(enabled) }) }) describe('space management', () => { it.each([true, false])('should be enabled according to the permissions', (enabled) => { expect( navItems({ $ability: getAbilityMock(enabled) }) .find((n) => n.name === 'Spaces') .isVisible() ).toBe(enabled) }) }) }) describe('routes', () => { describe('default-route "/"', () => { it('should redirect to general if permission given', () => { const ability = mock<Ability>() ability.can.mockReturnValueOnce(true) expect( routes({ $ability: ability }) .find((n) => n.path === '/') .redirect().name ).toEqual('admin-settings-general') }) it('should redirect to user management if permission given', () => { const ability = mock<Ability>() ability.can.mockReturnValueOnce(false) ability.can.mockReturnValueOnce(true) expect( routes({ $ability: ability }) .find((n) => n.path === '/') .redirect().name ).toEqual('admin-settings-users') }) it('should redirect to group management if permission given', () => { const ability = mock<Ability>() ability.can.mockReturnValueOnce(false) ability.can.mockReturnValueOnce(false) ability.can.mockReturnValueOnce(true) expect( routes({ $ability: ability }) .find((n) => n.path === '/') .redirect().name ).toEqual('admin-settings-groups') }) it('should redirect to space management if permission given', () => { const ability = mock<Ability>() ability.can.mockReturnValueOnce(false) ability.can.mockReturnValueOnce(false) ability.can.mockReturnValueOnce(false) ability.can.mockReturnValueOnce(true) expect( routes({ $ability: ability }) .find((n) => n.path === '/') .redirect().name ).toEqual('admin-settings-spaces') }) it('should throw an error if permissions are insufficient', () => { const ability = mock<Ability>() ability.can.mockReturnValue(false) expect(routes({ $ability: ability }).find((n) => n.path === '/').redirect).toThrow() }) }) it.each([ { can: true, redirect: null }, { can: false, redirect: { path: '/' } } ])('redirects "/general" with sufficient permissions', ({ can, redirect }) => { const ability = mock<Ability>({ can: vi.fn(() => can) }) const route = routes({ $ability: ability }).find((n) => n.path === '/general') const nextMock = vi.fn() route.beforeEnter({}, {}, nextMock) const args = [...(redirect ? [redirect] : [])] expect(nextMock).toHaveBeenCalledWith(...args) }) it.each([ { can: true, redirect: null }, { can: false, redirect: { path: '/' } } ])('redirects "/users" with sufficient permissions', ({ can, redirect }) => { const ability = mock<Ability>({ can: vi.fn(() => can) }) const route = routes({ $ability: ability }).find((n) => n.path === '/users') const nextMock = vi.fn() route.beforeEnter({}, {}, nextMock) const args = [...(redirect ? [redirect] : [])] expect(nextMock).toHaveBeenCalledWith(...args) }) it.each([ { can: true, redirect: null }, { can: false, redirect: { path: '/' } } ])('redirects "/groups" with sufficient permissions', ({ can, redirect }) => { const ability = mock<Ability>({ can: vi.fn(() => can) }) const route = routes({ $ability: ability }).find((n) => n.path === '/groups') const nextMock = vi.fn() route.beforeEnter({}, {}, nextMock) const args = [...(redirect ? [redirect] : [])] expect(nextMock).toHaveBeenCalledWith(...args) }) it.each([ { can: true, redirect: null }, { can: false, redirect: { path: '/' } } ])('redirects "/spaces" with sufficient permissions', ({ can, redirect }) => { const ability = mock<Ability>({ can: vi.fn(() => can) }) const route = routes({ $ability: ability }).find((n) => n.path === '/spaces') const nextMock = vi.fn() route.beforeEnter({}, {}, nextMock) const args = [...(redirect ? [redirect] : [])] expect(nextMock).toHaveBeenCalledWith(...args) }) }) })
owncloud/web/packages/web-app-admin-settings/tests/unit/index.spec.ts/0
{ "file_path": "owncloud/web/packages/web-app-admin-settings/tests/unit/index.spec.ts", "repo_id": "owncloud", "token_count": 2360 }
797
<template> <div class="epub-reader oc-flex"> <oc-list class="epub-reader-chapters-list oc-pl-s oc-visible@l"> <li v-for="chapter in chapters" :key="chapter.id" class="epub-reader-chapters-list-item oc-py-s" :class="{ active: currentChapter.id === chapter.id }" > <oc-button class="oc-text-truncate" appearance="raw" @click="showChapter(chapter)"> <span v-oc-tooltip="chapter.label" class="oc-text-truncate oc-mr-s" v-text="chapter.label" /> </oc-button> </li> </oc-list> <div class="oc-width-1-1 oc-height-1-1"> <div class="epub-reader-controls oc-flex oc-flex-middle oc-m-s"> <div class="epub-reader-controls-font-size oc-flex oc-button-group"> <oc-button v-oc-tooltip="`${currentFontSizePercentage - FONT_SIZE_PERCENTAGE_STEP}%`" class="epub-reader-controls-font-size-decrease" :disabled="decreaseFontSizeDisabled" gap-size="none" @click="decreaseFontSize" > <oc-icon name="font-family" fill-type="none" size="small" /> <oc-icon name="subtract" size="xsmall" /> </oc-button> <oc-button v-oc-tooltip="$gettext('Reset font size')" class="epub-reader-controls-font-size-reset" gap-size="none" @click="resetFontSize" v-text="`${currentFontSizePercentage}%`" /> <oc-button v-oc-tooltip="`${currentFontSizePercentage + FONT_SIZE_PERCENTAGE_STEP}%`" class="epub-reader-controls-font-size-increase" :disabled="increaseFontSizeDisabled" gap-size="none" @click="increaseFontSize" > <oc-icon name="font-family" fill-type="none" size="small" /> <oc-icon name="add" size="xsmall" /> </oc-button> </div> <oc-select v-model="currentChapter" class="epub-reader-controls-chapters-select oc-width-1-1 oc-px-s oc-hidden@l" :options="chapters" :searchable="false" @update:model-value="showChapter" /> </div> <div class="oc-flex oc-flex-center oc-width-1-1 oc-height-1-1"> <div class="oc-flex oc-flex-middle oc-mx-l"> <oc-button class="epub-reader-navigate-left" :disabled="navigateLeftDisabled" appearance="raw" @click="navigateLeft" > <oc-icon name="arrow-left-s" fill-type="line" size="xlarge" /> </oc-button> </div> <div id="reader" ref="bookContainer" class="oc-flex oc-flex-center" /> <div class="oc-flex oc-flex-middle oc-mx-l"> <oc-button class="epub-reader-navigate-right" :disabled="navigateRightDisabled" appearance="raw" @click="navigateRight" > <oc-icon name="arrow-right-s" fill-type="line" size="xlarge" /> </oc-button> </div> </div> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, nextTick, PropType, ref, unref, watch } from 'vue' import { Resource } from '@ownclouders/web-client/src/helpers/resource/types' import { AppConfigObject, Key, useKeyboardActions, useLocalStorage, useThemeStore } from '@ownclouders/web-pkg' import ePub, { Book, NavItem, Rendition, Location } from 'epubjs' const DARK_THEME_CONFIG = { html: { '-webkit-filter': 'invert(1) hue-rotate(180deg)', filter: 'invert(1) hue-rotate(180deg)' }, img: { '-webkit-filter': 'invert(1) hue-rotate(180deg)', filter: 'invert(1) hue-rotate(180deg)' } } const LIGHT_THEME_CONFIG = { html: { background: 'white' } } const MAX_FONT_SIZE_PERCENTAGE = 150 const MIN_FONT_SIZE_PERCENTAGE = 50 const FONT_SIZE_PERCENTAGE_STEP = 10 export default defineComponent({ name: 'EpubReader', props: { applicationConfig: { type: Object as PropType<AppConfigObject>, required: true }, currentContent: { type: String, required: true }, isReadOnly: { type: Boolean, required: false }, resource: { type: Object as PropType<Resource>, required: true } }, emits: ['close'], setup(props) { const keyboardActions = useKeyboardActions() const bookContainer = ref<Element>() const chapters = ref<NavItem[]>([]) const currentChapter = ref<NavItem>() const navigateLeftDisabled = ref(false) const navigateRightDisabled = ref(false) const localStorageData = useLocalStorage(`oc_epubReader`, {}) const currentFontSizePercentage = ref(unref(localStorageData).fontSizePercentage || 100) const themeStore = useThemeStore() let book = ref<Book>() let rendition = ref<Rendition>() const navigateLeft = () => { unref(rendition).prev() } const navigateRight = () => { unref(rendition).next() } const showChapter = (chapter: NavItem) => { unref(rendition).display(chapter.href) } const increaseFontSize = () => { currentFontSizePercentage.value = Math.min( unref(currentFontSizePercentage) + FONT_SIZE_PERCENTAGE_STEP, MAX_FONT_SIZE_PERCENTAGE ) } const resetFontSize = () => { currentFontSizePercentage.value = 100 } const decreaseFontSize = () => { currentFontSizePercentage.value = Math.max( unref(currentFontSizePercentage) - FONT_SIZE_PERCENTAGE_STEP, MIN_FONT_SIZE_PERCENTAGE ) } const increaseFontSizeDisabled = computed(() => { return unref(currentFontSizePercentage) >= MAX_FONT_SIZE_PERCENTAGE }) const decreaseFontSizeDisabled = computed(() => { return unref(currentFontSizePercentage) <= MIN_FONT_SIZE_PERCENTAGE }) keyboardActions.bindKeyAction({ primary: Key.ArrowLeft }, () => navigateLeft()) keyboardActions.bindKeyAction({ primary: Key.ArrowRight }, () => navigateRight()) watch( () => props.currentContent, async () => { await nextTick() if (unref(book)) { unref(book).destroy() } const localStorageResourceData = useLocalStorage( `oc_epubReader_resource_${props.resource.id}`, {} ) book.value = ePub(props.currentContent) unref(book).loaded.navigation.then(({ toc }) => { chapters.value = toc currentChapter.value = toc?.[0] }) rendition.value = unref(book).renderTo(unref(bookContainer), { flow: 'paginated', width: 650, height: '90%' // Don't use full height to avoid cut-off text }) unref(rendition).themes.register('dark', DARK_THEME_CONFIG) unref(rendition).themes.register('light', LIGHT_THEME_CONFIG) unref(rendition).themes.select(themeStore.currentTheme.isDark ? 'dark' : 'light') unref(rendition).themes.fontSize(`${unref(currentFontSizePercentage)}%`) unref(rendition).display(unref(localStorageResourceData)?.currentLocation?.start?.cfi) unref(rendition).on('keydown', (event: KeyboardEvent) => { if (event.key === Key.ArrowLeft) { navigateLeft() } if (event.key === Key.ArrowRight) { navigateRight() } }) unref(rendition).on('relocated', () => { const currentLocation = unref(rendition).currentLocation() as any & Location localStorageResourceData.value = { currentLocation } navigateLeftDisabled.value = currentLocation.atStart === true navigateRightDisabled.value = currentLocation.atEnd === true const locationCfi = currentLocation.start.cfi const spineItem = unref(book).spine.get(locationCfi) const navItem = unref(book).navigation.get(spineItem.href) // Might be sub nav item and therefore undefined if (navItem) { currentChapter.value = navItem } }) }, { immediate: true } ) watch(currentFontSizePercentage, () => { unref(rendition).themes.fontSize(`${unref(currentFontSizePercentage)}%`) localStorageData.value = { ...unref(localStorageData), fontSizePercentage: unref(currentFontSizePercentage) } }) return { bookContainer, navigateLeft, navigateLeftDisabled, navigateRight, navigateRightDisabled, currentChapter, chapters, showChapter, resetFontSize, increaseFontSize, decreaseFontSize, increaseFontSizeDisabled, decreaseFontSizeDisabled, currentFontSizePercentage, FONT_SIZE_PERCENTAGE_STEP, rendition, book } } }) </script> <style lang="scss"> .epub-reader { &-chapters-list { background: var(--oc-color-background-muted); border-right: 1px solid var(--oc-color-border); width: 240px; overflow-y: auto; &-item:not(:last-child) { border-bottom: 1px solid var(--oc-color-border); } &-item.active { .oc-button { color: var(--oc-color-swatch-primary-default); } } } &-controls-font-size { flex-wrap: nowrap; &-reset { width: 58px; //prevent jumpy behaviour } } } </style>
owncloud/web/packages/web-app-epub-reader/src/App.vue/0
{ "file_path": "owncloud/web/packages/web-app-epub-reader/src/App.vue", "repo_id": "owncloud", "token_count": 4186 }
798
import Uppy, { UppyFile } from '@uppy/core' import BasePlugin from '@uppy/core/lib/BasePlugin.js' import { filesize } from 'filesize' import { basename, dirname, join } from 'path' import * as uuid from 'uuid' import { Language } from 'vue3-gettext' import { Ref, unref } from 'vue' import { RouteLocationNormalizedLoaded } from 'vue-router' import { SpaceResource } from '@ownclouders/web-client/src' import { urlJoin } from '@ownclouders/web-client/src/utils' import { ResourceConflict } from './helpers/resource' import { MessageStore, ResourcesStore, SpacesStore, UserStore, locationPublicLink } from '@ownclouders/web-pkg' import { locationSpacesGeneric, UppyService, UppyResource } from '@ownclouders/web-pkg' import { isPersonalSpaceResource, isShareSpaceResource } from '@ownclouders/web-client/src/helpers' import { ClientService, queryItemAsString } from '@ownclouders/web-pkg' export interface HandleUploadOptions { clientService: ClientService language: Language route: Ref<RouteLocationNormalizedLoaded> userStore: UserStore messageStore: MessageStore spacesStore: SpacesStore resourcesStore: ResourcesStore uppyService: UppyService id?: string space?: SpaceResource quotaCheckEnabled?: boolean directoryTreeCreateEnabled?: boolean conflictHandlingEnabled?: boolean } /** * Plugin to handle the file upload with uppy. The process goes through the following steps: * * 1. convert input files to uppy resources * 2. check quota if spaces are enabled * 3. handle potential naming conflicts * 4. create directory tree if needed * 5. start upload */ export class HandleUpload extends BasePlugin { id: string type: string uppy: Uppy clientService: ClientService language: Language route: Ref<RouteLocationNormalizedLoaded> space: SpaceResource userStore: UserStore messageStore: MessageStore spacesStore: SpacesStore resourcesStore: ResourcesStore uppyService: UppyService quotaCheckEnabled: boolean directoryTreeCreateEnabled: boolean conflictHandlingEnabled: boolean constructor(uppy: Uppy, opts: HandleUploadOptions) { super(uppy, opts) this.id = opts.id || 'HandleUpload' this.type = 'modifier' this.uppy = uppy this.clientService = opts.clientService this.language = opts.language this.route = opts.route this.space = opts.space this.userStore = opts.userStore this.messageStore = opts.messageStore this.spacesStore = opts.spacesStore this.resourcesStore = opts.resourcesStore this.uppyService = opts.uppyService this.quotaCheckEnabled = opts.quotaCheckEnabled ?? true this.directoryTreeCreateEnabled = opts.directoryTreeCreateEnabled ?? true this.conflictHandlingEnabled = opts.conflictHandlingEnabled ?? true this.handleUpload = this.handleUpload.bind(this) } removeFilesFromUpload(filesToUpload: UppyResource[]) { for (const file of filesToUpload) { this.uppy.removeFile(file.id) } } getUploadPluginName() { return this.uppy.getPlugin('Tus') ? 'tus' : 'xhrUpload' } /** * Converts the input files type UppyResources and updates the uppy upload queue */ prepareFiles(files: UppyFile[]): UppyResource[] { const filesToUpload: Record<string, UppyResource> = {} if (!this.resourcesStore.currentFolder && unref(this.route)?.params?.token) { // public file drop const publicLinkToken = queryItemAsString(unref(this.route).params.token) let endpoint = urlJoin( this.clientService.webdav.getPublicFileUrl(this.space, publicLinkToken), { trailingSlash: true } ) for (const file of files) { if (!this.uppy.getPlugin('Tus')) { endpoint = urlJoin(endpoint, encodeURIComponent(file.name)) } file[this.getUploadPluginName()] = { endpoint } file.meta = { ...file.meta, tusEndpoint: endpoint, uploadId: uuid.v4() } filesToUpload[file.id] = file as unknown as UppyResource } this.uppy.setState({ files: { ...this.uppy.getState().files, ...filesToUpload } }) return Object.values(filesToUpload) } const { id: currentFolderId, path: currentFolderPath } = this.resourcesStore.currentFolder const { name, params, query } = unref(this.route) const topLevelFolderIds: Record<string, string> = {} for (const file of files) { const relativeFilePath = file.meta.relativePath as string // Directory without filename const directory = !relativeFilePath || dirname(relativeFilePath) === '.' ? '' : dirname(relativeFilePath) let topLevelFolderId: string if (relativeFilePath) { const topLevelDirectory = relativeFilePath.split('/').filter(Boolean)[0] if (!topLevelFolderIds[topLevelDirectory]) { topLevelFolderIds[topLevelDirectory] = uuid.v4() } topLevelFolderId = topLevelFolderIds[topLevelDirectory] } const webDavUrl = this.space.getWebDavUrl({ path: currentFolderPath.split('/').map(encodeURIComponent).join('/') }) let endpoint = urlJoin(webDavUrl, directory.split('/').map(encodeURIComponent).join('/')) if (!this.uppy.getPlugin('Tus')) { endpoint = urlJoin(endpoint, encodeURIComponent(file.name)) } file[this.getUploadPluginName()] = { endpoint } file.meta = { ...file.meta, // file data name: file.name, mtime: (file.data as any).lastModified / 1000, // current path & space spaceId: this.space.id, spaceName: this.space.name, driveAlias: this.space.driveAlias, driveType: this.space.driveType, currentFolder: currentFolderPath, currentFolderId, // upload data uppyId: this.uppyService.generateUploadId(file as any), relativeFolder: directory, tusEndpoint: endpoint, uploadId: uuid.v4(), topLevelFolderId, // route data routeName: name as string, routeDriveAliasAndItem: queryItemAsString(params?.driveAliasAndItem) || '', routeShareId: queryItemAsString(query?.shareId) || '' } filesToUpload[file.id] = file as unknown as UppyResource } this.uppy.setState({ files: { ...this.uppy.getState().files, ...filesToUpload } }) return Object.values(filesToUpload) } checkQuotaExceeded(filesToUpload: UppyResource[]): boolean { let quotaExceeded = false const uploadSizeSpaceMapping = filesToUpload.reduce((acc, uppyResource) => { let targetUploadSpace: SpaceResource if (uppyResource.meta.routeName === locationPublicLink.name) { return acc } if (uppyResource.meta.routeName === locationSpacesGeneric.name) { targetUploadSpace = this.spacesStore.spaces.find( ({ id }) => id === uppyResource.meta.spaceId ) } if ( !targetUploadSpace || isShareSpaceResource(targetUploadSpace) || (isPersonalSpaceResource(targetUploadSpace) && !targetUploadSpace.isOwner(this.userStore.user)) ) { return acc } const existingFile = this.resourcesStore.resources.find( (c) => !uppyResource.meta.relativeFolder && c.name === uppyResource.name ) const existingFileSize = existingFile ? Number(existingFile.size) : 0 const matchingMappingRecord = acc.find( (mappingRecord) => mappingRecord.space.id === targetUploadSpace.id ) if (!matchingMappingRecord) { acc.push({ space: targetUploadSpace, uploadSize: uppyResource.data.size - existingFileSize }) return acc } matchingMappingRecord.uploadSize = uppyResource.data.size - existingFileSize return acc }, []) const { $gettext } = this.language uploadSizeSpaceMapping.forEach(({ space, uploadSize }) => { if (space.spaceQuota.remaining && space.spaceQuota.remaining < uploadSize) { let spaceName = space.name if (space.driveType === 'personal') { spaceName = $gettext('Personal') } this.messageStore.showErrorMessage({ title: $gettext('Not enough quota'), desc: $gettext( 'There is not enough quota on %{spaceName}, you need additional %{missingSpace} to upload these files', { spaceName, missingSpace: filesize((space.spaceQuota.remaining - uploadSize) * -1) } ) }) quotaExceeded = true } }) return quotaExceeded } /** * Creates the directory tree and removes files of failed directories from the upload queue. */ async createDirectoryTree(filesToUpload: UppyResource[]): Promise<UppyResource[]> { const { webdav } = this.clientService const space = this.space const { id: currentFolderId, path: currentFolderPath } = this.resourcesStore.currentFolder const routeName = filesToUpload[0].meta.routeName const routeDriveAliasAndItem = filesToUpload[0].meta.routeDriveAliasAndItem const routeShareId = filesToUpload[0].meta.routeShareId const failedFolders: string[] = [] const directoryTree: Record<string, any> = {} const topLevelIds: Record<string, string> = {} for (const file of filesToUpload.filter(({ meta }) => !!meta.relativeFolder)) { const folders = file.meta.relativeFolder.split('/').filter(Boolean) let current = directoryTree if (folders.length <= 1) { topLevelIds[file.meta.relativeFolder] = file.meta.topLevelFolderId } for (const folder of folders) { current[folder] = current[folder] || {} current = current[folder] } } const createDirectoryLevel = async (current: Record<string, any>, path = '') => { if (path) { const isRoot = path.split('/').length <= 1 path = urlJoin(path, { leadingSlash: true }) const uploadId = !isRoot ? uuid.v4() : topLevelIds[path] const relativeFolder = dirname(path) === '/' ? '' : dirname(path) const uppyResource = { id: uuid.v4(), name: basename(path), isFolder: true, type: 'folder', meta: { spaceId: space.id, spaceName: space.name, driveAlias: space.driveAlias, driveType: space.driveType, currentFolder: currentFolderPath, currentFolderId, relativeFolder, uploadId, routeName, routeDriveAliasAndItem, routeShareId } } if (failedFolders.includes(relativeFolder)) { // return if top level folder failed to create return } this.uppyService.publish('addedForUpload', [uppyResource]) try { const folder = await webdav.createFolder(space, { path: urlJoin(currentFolderPath, path), fetchFolder: isRoot }) this.uppyService.publish('uploadSuccess', { ...uppyResource, meta: { ...uppyResource.meta, fileId: folder?.fileId } }) } catch (error) { if (error.statusCode !== 405) { console.error(error) failedFolders.push(path) this.uppyService.publish('uploadError', { file: uppyResource, error }) } } } const foldersToBeCreated = Object.keys(current) const promises = [] for (const folder of foldersToBeCreated) { promises.push(createDirectoryLevel(current[folder], join(path, folder))) } return Promise.allSettled(promises) } await createDirectoryLevel(directoryTree) let filesToRemove: string[] = [] if (failedFolders.length) { // remove files of folders that could not be created filesToRemove = filesToUpload .filter((f) => failedFolders.some((r) => f.meta.relativeFolder.startsWith(r))) .map(({ id }) => id) for (const fileId of filesToRemove) { this.uppy.removeFile(fileId) } } return filesToUpload.filter(({ id }) => !filesToRemove.includes(id)) } /** * The handler that prepares all files to be uploaded and goes through all necessary steps. * Eventually triggers to upload in Uppy. */ async handleUpload(files: UppyFile[]) { if (!files.length) { return } let filesToUpload = this.prepareFiles(files) // quota check if (this.quotaCheckEnabled) { const quotaExceeded = this.checkQuotaExceeded(filesToUpload) if (quotaExceeded) { this.removeFilesFromUpload(filesToUpload) return this.uppyService.clearInputs() } } // name conflict handling if (this.conflictHandlingEnabled) { const conflictHandler = new ResourceConflict(this.resourcesStore, this.language) const conflicts = conflictHandler.getConflicts(filesToUpload) if (conflicts.length) { const dashboard = document.getElementsByClassName('uppy-Dashboard') if (dashboard.length) { ;(dashboard[0] as HTMLElement).style.display = 'none' } const result = await conflictHandler.displayOverwriteDialog(filesToUpload, conflicts) if (result.length === 0) { this.removeFilesFromUpload(filesToUpload) return this.uppyService.clearInputs() } filesToUpload = result const conflictMap = result.reduce<Record<string, UppyResource>>((acc, file) => { acc[file.id] = file return acc }, {}) this.uppy.setState({ files: { ...this.uppy.getState().files, ...conflictMap } }) } } this.uppyService.publish('uploadStarted') if (this.directoryTreeCreateEnabled) { filesToUpload = await this.createDirectoryTree(filesToUpload) } if (!filesToUpload.length) { this.uppyService.publish('uploadCompleted', { successful: [] }) return this.uppyService.clearInputs() } this.uppyService.publish('addedForUpload', filesToUpload) this.uppyService.uploadFiles() } install() { this.uppy.on('files-added', this.handleUpload) } uninstall() { this.uppy.off('files-added', this.handleUpload) } }
owncloud/web/packages/web-app-files/src/HandleUpload.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/src/HandleUpload.ts", "repo_id": "owncloud", "token_count": 5543 }
799
<template> <div> <input id="space-image-upload-input" ref="spaceImageInput" type="file" name="file" tabindex="-1" :accept="supportedSpaceImageMimeTypes" @change="uploadImageSpace" /> <oc-list id="oc-spaces-actions-sidebar" class-name="oc-mt-s"> <action-menu-item v-for="(action, index) in actions" :key="`action-${index}`" :action="action" :action-options="actionOptions" class="oc-rounded" /> </oc-list> </div> </template> <script lang="ts"> import { computed, defineComponent, inject, Ref, ref, unref, VNodeRef } from 'vue' import { Resource, SpaceResource } from '@ownclouders/web-client' import { ActionMenuItem, FileActionOptions, SpaceActionOptions, useSpaceActionsSetIcon } from '@ownclouders/web-pkg' import { usePreviewService } from '@ownclouders/web-pkg' import { useSpaceActionsDelete, useSpaceActionsDisable, useSpaceActionsDuplicate, useSpaceActionsEditDescription, useSpaceActionsEditQuota, useSpaceActionsEditReadmeContent, useSpaceActionsRename, useSpaceActionsRestore } from '@ownclouders/web-pkg' import { useSpaceActionsUploadImage } from 'web-app-files/src/composables' import { useFileActionsDownloadArchive } from '@ownclouders/web-pkg' export default defineComponent({ name: 'SpaceActions', components: { ActionMenuItem }, setup() { const previewService = usePreviewService() const resource = inject<Ref<SpaceResource>>('resource') const actionOptions = computed((): SpaceActionOptions & FileActionOptions<Resource> => ({ space: undefined, resources: [unref(resource)] })) const spaceImageInput: VNodeRef = ref(null) const supportedSpaceImageMimeTypes = computed(() => { return previewService.getSupportedMimeTypes('image/').join(',') }) const { actions: deleteActions } = useSpaceActionsDelete() const { actions: disableActions } = useSpaceActionsDisable() const { actions: duplicateActions } = useSpaceActionsDuplicate() const { actions: editDescriptionActions } = useSpaceActionsEditDescription() const { actions: editQuotaActions } = useSpaceActionsEditQuota() const { actions: editReadmeContentActions } = useSpaceActionsEditReadmeContent() const { actions: renameActions } = useSpaceActionsRename() const { actions: restoreActions } = useSpaceActionsRestore() const { actions: uploadImageActions, uploadImageSpace } = useSpaceActionsUploadImage({ spaceImageInput }) const { actions: setSpaceIconActions } = useSpaceActionsSetIcon() const { actions: downloadArchiveActions } = useFileActionsDownloadArchive() const actions = computed(() => [ ...unref(downloadArchiveActions), ...unref(renameActions), ...unref(duplicateActions), ...unref(editDescriptionActions), ...unref(uploadImageActions), ...unref(setSpaceIconActions), ...unref(editReadmeContentActions), ...unref(editQuotaActions), ...unref(restoreActions), ...unref(deleteActions), ...unref(disableActions) ].filter((item) => item.isVisible(unref(actionOptions))) ) return { actions, actionOptions, spaceImageInput, supportedSpaceImageMimeTypes, uploadImageActions, uploadImageSpace } } }) </script> <style lang="scss"> #space-image-upload-input { position: absolute; left: -99999px; } #oc-spaces-actions-sidebar { > li a, > li a:hover { color: var(--oc-color-swatch-passive-default); display: inline-flex; gap: 10px; vertical-align: top; } > li:hover { text-decoration: none !important; background-color: var(--oc-color-background-hover); } } </style>
owncloud/web/packages/web-app-files/src/components/SideBar/Actions/SpaceActions.vue/0
{ "file_path": "owncloud/web/packages/web-app-files/src/components/SideBar/Actions/SpaceActions.vue", "repo_id": "owncloud", "token_count": 1414 }
800
<template> <div class="link-details oc-flex oc-flex-between oc-flex-middle"> <div v-if="isModifiable"> <link-role-dropdown :model-value="currentLinkType" :available-link-type-options="availableLinkTypeOptions" drop-offset="0" @update:model-value="updateSelectedType" /> </div> <p v-else class="oc-my-rm"> <span v-oc-tooltip="$gettext(currentLinkRoleDescription)" class="link-current-role" v-text="$gettext(currentLinkRoleLabel)" /> </p> <oc-checkbox v-if="isRunningOnEos && isUploaderLink" :model-value="currentLinkNotifyUploads" :label="$gettext('Notify me about uploads')" @input="toggleNotifyUploads" /> <div :class="{ 'oc-pr-s': !isModifiable }" class="details-buttons"> <oc-button v-if="linkShare.indirect" v-oc-tooltip="viaTooltip" :area-label="viaTooltip" type="router-link" class="oc-files-file-link-via" appearance="raw" :to="viaRouterParams" > <oc-icon name="folder-shared" fill-type="line" /> </oc-button> <oc-icon v-if="linkShare.hasPassword" v-oc-tooltip="passwortProtectionTooltip" name="lock-password" fill-type="line" :aria-label="passwortProtectionTooltip" /> <oc-icon v-if="linkShare.expirationDateTime" v-oc-tooltip="expirationDateTooltip" class="oc-files-public-link-expires oc-ml-xs" :data-testid="`files-link-id-${linkShare.id}-expiration-date`" :aria-label="expirationDateTooltip" name="calendar-event" fill-type="line" /> <oc-icon v-if="isRunningOnEos && currentLinkNotifyUploadsExtraRecipients" v-oc-tooltip="$gettext('Uploads will be notified to a third party')" :aria-label="$gettext('Uploads will be notified to a third party')" name="mail-add" fill-type="line" /> <div v-if="isModifiable"> <oc-button :id="`edit-public-link-dropdown-toggl-${linkShare.id}`" appearance="raw" class="edit-drop-trigger" :data-testid="`files-link-id-${linkShare.id}-btn-edit`" > <oc-icon name="more-2" /> </oc-button> <oc-drop ref="editPublicLinkDropdown" :drop-id="`edit-public-link-dropdown`" :toggle="`#edit-public-link-dropdown-toggl-${linkShare.id}`" padding-size="small" mode="click" > <oc-list v-if="editOptions.length > 0" class="edit-public-link-dropdown-menu oc-pb-s oc-files-context-actions-border" > <li v-for="(option, i) in editOptions" :key="`public-link-edit-option-${i}`" class="oc-rounded oc-menu-item-hover" > <oc-datepicker v-if="option.showDatepicker" v-model="newExpiration" class="link-expiry-picker oc-flex oc-width-1-1" :min-date="expirationRules.min" :max-date="expirationRules.max" :locale="$language.current" :is-required="expirationRules.enforced" > <template #default="{ togglePopover }"> <oc-button :data-testid="`files-link-id-${linkShare.id}-edit-${option.id}`" appearance="raw" class="oc-p-s action-menu-item" :variation="option.variation" @click="togglePopover" > <oc-icon :name="option.icon" fill-type="line" size="medium" /> <span v-text="option.title" /> </oc-button> <oc-button v-if="option.remove && option.remove.isRemovable" :data-testid="`files-link-id-${linkShare.id}-edit-${option.id}`" :aria-label="option.remove.title" appearance="raw" @click="option.remove.method" > <oc-icon :name="option.remove.icon" /> </oc-button> </template> </oc-datepicker> <oc-button v-else appearance="raw" class="oc-p-s action-menu-item" :data-testid="`files-link-id-${linkShare.id}-edit-${option.id}`" @click="option.method" > <oc-icon :name="option.icon" fill-type="line" size="medium" /> <span v-text="option.title" /> </oc-button> </li> </oc-list> <oc-list class="edit-public-link-dropdown-menu" :class="{ 'oc-pt-s': editOptions.length > 0 }" > <li class="oc-rounded oc-menu-item-hover"> <oc-button appearance="raw" class="oc-p-s action-menu-item" :data-testid="`files-link-id-${linkShare.id}-edit-${deleteOption.id}`" @click="deleteOption.method" > <oc-icon :name="deleteOption.icon" fill-type="line" size="medium" /> <span v-text="deleteOption.title" /> </oc-button> </li> </oc-list> </oc-drop> </div> </div> </div> </template> <script lang="ts"> import { basename } from 'path' import { DateTime } from 'luxon' import * as EmailValidator from 'email-validator' import { createLocationSpaces, LinkRoleDropdown, useConfigStore, useLinkTypes, useModals, useSpacesStore } from '@ownclouders/web-pkg' import { LinkShare } from '@ownclouders/web-client/src/helpers/share' import { computed, defineComponent, inject, PropType, Ref, ref, unref } from 'vue' import { formatDateFromDateTime, formatRelativeDateFromDateTime } from '@ownclouders/web-pkg' import { Resource, SpaceResource } from '@ownclouders/web-client/src/helpers' import { createFileRouteOptions } from '@ownclouders/web-pkg' import { OcDrop } from 'design-system/src/components' import { usePasswordPolicyService, ExpirationRules } from '@ownclouders/web-pkg' import { useGettext } from 'vue3-gettext' import SetLinkPasswordModal from '../../../Modals/SetLinkPasswordModal.vue' import { storeToRefs } from 'pinia' import { SharingLinkType } from '@ownclouders/web-client/src/generated' export default defineComponent({ name: 'DetailsAndEdit', components: { LinkRoleDropdown }, props: { canRename: { type: Boolean, default: false }, expirationRules: { type: Object as PropType<ExpirationRules>, required: true }, isFolderShare: { type: Boolean, default: false }, isModifiable: { type: Boolean, default: false }, isPasswordEnforced: { type: Boolean, default: false }, isPasswordRemovable: { type: Boolean, default: false }, linkShare: { type: Object as PropType<LinkShare>, required: true } }, emits: ['removePublicLink', 'updateLink'], setup(props, { emit }) { const { dispatchModal } = useModals() const { $gettext, current } = useGettext() const configStore = useConfigStore() const passwordPolicyService = usePasswordPolicyService() const spacesStore = useSpacesStore() const { spaces } = storeToRefs(spacesStore) const { getAvailableLinkTypes, getLinkRoleByType } = useLinkTypes() const space = inject<Ref<SpaceResource>>('space') const resource = inject<Ref<Resource>>('resource') const currentLinkType = ref<SharingLinkType>(props.linkShare.type) const dateExpire = computed(() => { return formatRelativeDateFromDateTime( DateTime.fromISO(props.linkShare.expirationDateTime).endOf('day'), current ) }) const updateSelectedType = (type: SharingLinkType) => { currentLinkType.value = type const linkShare = props.linkShare linkShare.type = type emit('updateLink', { linkShare }) } const showPasswordModal = () => { dispatchModal({ title: props.linkShare.hasPassword ? $gettext('Edit password') : $gettext('Add password'), customComponent: SetLinkPasswordModal, customComponentAttrs: () => ({ space: unref(space), resource: unref(resource), link: props.linkShare }) }) } const availableLinkTypeOptions = computed(() => getAvailableLinkTypes({ isFolder: props.isFolderShare }) ) const isAliasLink = computed(() => { return props.linkShare.type === SharingLinkType.Internal }) const isUploaderLink = computed(() => { return props.linkShare.type === SharingLinkType.Upload }) const currentLinkRoleDescription = computed(() => { return getLinkRoleByType(unref(currentLinkType))?.description || '' }) const currentLinkRoleLabel = computed(() => { return getLinkRoleByType(unref(currentLinkType))?.label || '' }) return { space, resource, spaces, passwordPolicyService, dateExpire, updateSelectedType, currentLinkType, isRunningOnEos: computed(() => configStore.options.isRunningOnEos), showPasswordModal, dispatchModal, availableLinkTypeOptions, getLinkRoleByType, isAliasLink, isUploaderLink, currentLinkRoleDescription, currentLinkRoleLabel } }, data() { return { newExpiration: this.linkShare.expirationDateTime } }, computed: { editOptions() { const result = [] if (this.canRename) { result.push({ id: 'rename', title: this.$gettext('Rename'), icon: 'pencil', method: this.showRenameModal }) } if (this.linkShare.expirationDateTime) { result.push({ id: 'edit-expiration', title: this.$gettext('Expires %{expires}', { expires: this.dateExpire }), method: () => { this.$emit('updateLink', { linkShare: { ...this.linkShare, expirationDateTime: this.dateExpire } }) }, icon: 'calendar-event', showDatepicker: true, remove: { id: 'remove-expiration', title: this.$gettext('Remove expiration date'), icon: 'close', isRemovable: !this.expirationRules.enforced, method: () => this.$emit('updateLink', { linkShare: { ...this.linkShare, expirationDateTime: null } }) } }) } else if (!this.isAliasLink) { result.push({ id: 'add-expiration', title: this.$gettext('Set expiration date'), method: () => { this.$emit('updateLink', { linkShare: { ...this.linkShare, expirationDateTime: this.dateExpire } }) }, icon: 'calendar-event', showDatepicker: true }) } if (this.linkShare.hasPassword) { result.push({ id: 'edit-password', title: this.$gettext('Edit password'), icon: 'lock-password', method: this.showPasswordModal }) if (this.isPasswordRemovable) { result.push({ id: 'remove-password', title: this.$gettext('Remove password'), icon: 'lock-unlock', method: () => this.$emit('updateLink', { linkShare: this.linkShare, password: '' }) }) } } if (!this.linkShare.hasPassword && !this.isAliasLink) { result.push({ id: 'add-password', title: this.$gettext('Add password'), icon: 'lock-password', method: this.showPasswordModal }) } // FIXME cern code // if (this.isCurrentLinkRoleUploader && this.currentLinkNotifyUploads) { // result.push({ // id: 'add-notify-uploads-extra-recipients', // title: this.notifyUploadsExtraRecipientsMenuEntry, // icon: 'mail-add', // method: this.showNotifyUploadsExtraRecipientsModal // }) // } // if (this.currentLinkNotifyUploadsExtraRecipients) { // result.push({ // id: 'remove-notify-uploads-extra-recipients', // title: this.$gettext('Remove third party notification'), // icon: 'mail-close', // method: () => // this.updateLink({ // link: { // ...this.linkShare, // notifyUploadsExtraRecipients: '' // } // }) // }) // } return result }, deleteOption() { return { id: 'delete', title: this.$gettext('Delete link'), method: this.deleteLink, icon: 'delete-bin-5', variation: 'danger' } }, viaRouterParams() { const matchingSpace = (this.space || this.spaces.find((space) => space.id === this.resource.storageId)) as SpaceResource if (!matchingSpace) { return {} } return createLocationSpaces( 'files-spaces-generic', createFileRouteOptions(matchingSpace, { path: this.resource.path, fileId: this.resource.fileId }) ) }, localExpirationDate() { return formatDateFromDateTime( DateTime.fromISO(this.linkShare.expirationDateTime).endOf('day'), this.$language.current ) }, expirationDateRelative() { return formatRelativeDateFromDateTime( DateTime.fromISO(this.linkShare.expirationDateTime).endOf('day'), this.$language.current ) }, expirationDateTooltip() { return this.$gettext( 'Expires %{timeToExpiry} (%{expiryDate})', { timeToExpiry: this.expirationDateRelative, expiryDate: this.localExpirationDate }, true ) }, viaTooltip() { if (!this.linkShare.indirect) { return null } return ( this.$gettext('Navigate to the parent (%{folderName})'), { folderName: basename(this.resource.path) }, true ) }, passwortProtectionTooltip() { return this.$gettext('This link is password-protected') }, currentLinkNotifyUploads() { // FIXME cern code return undefined }, currentLinkNotifyUploadsExtraRecipients() { // FIXME cern code return undefined }, notifyUploadsExtraRecipientsMenuEntry() { if (this.currentLinkNotifyUploadsExtraRecipients) { return this.$gettext('Edit third party notification') } return this.$gettext('Notify a third party about uploads') } }, watch: { newExpiration(expirationDateTime: string) { this.$emit('updateLink', { linkShare: { ...this.linkShare, expirationDateTime } }) } }, methods: { deleteLink() { this.$emit('removePublicLink', { link: this.linkShare }) ;(this.$refs.editPublicLinkDropdown as InstanceType<typeof OcDrop>).hide() }, showRenameModal() { this.dispatchModal({ title: this.$gettext('Edit name'), confirmText: this.$gettext('Save'), hasInput: true, inputValue: this.linkShare.displayName, inputLabel: this.$gettext('Link name'), onInput: (name, setError) => { if (name.length > 255) { return setError(this.$gettext('Link name cannot exceed 255 characters')) } return setError(null) }, onConfirm: (displayName: string) => { const linkShare = this.linkShare linkShare.displayName = displayName this.$emit('updateLink', { linkShare }) } }) }, toggleNotifyUploads() { if (this.currentLinkNotifyUploads) { this.$emit('updateLink', { link: { ...this.linkShare, notifyUploads: false, notifyUploadsExtraRecipients: '' } }) } else { this.$emit('updateLink', { linkShare: { ...this.linkShare, notifyUploads: true } }) } }, showNotifyUploadsExtraRecipientsModal() { this.dispatchModal({ icon: 'mail-add', title: this.$gettext('Notify a third party about uploads'), confirmText: this.$gettext('Apply'), hasInput: true, inputDescription: this.$gettext( 'When a file is uploaded, this address will be notified as well.' ), inputValue: this.currentLinkNotifyUploadsExtraRecipients, inputLabel: this.$gettext('Email address'), inputType: 'email', onInput: (value, setError) => setError(this.getEmailValidationMsg(value)), onConfirm: () => { this.$emit('updateLink', { linkShare: { ...this.linkShare } }) } }) }, getEmailValidationMsg(email: string) { if (!EmailValidator.validate(email)) { return this.$gettext('Email is invalid') } if (email === '') { return this.$gettext("Email can't be empty") } return null } } }) </script> <style lang="scss" scoped> .details-buttons { min-width: 5rem !important; display: flex; justify-content: flex-end; } .edit-public-link-dropdown-menu { .action-menu-item { width: 100%; justify-content: flex-start; } } .oc-files-public-link-expires { margin-top: 1px; // to align with the other elements } </style>
owncloud/web/packages/web-app-files/src/components/SideBar/Shares/Links/DetailsAndEdit.vue/0
{ "file_path": "owncloud/web/packages/web-app-files/src/components/SideBar/Shares/Links/DetailsAndEdit.vue", "repo_id": "owncloud", "token_count": 8185 }
801
export * from './useKeyboardTableNavigation' export * from './useKeyboardTableMouseActions' export * from './useKeyboardTableActions' export * from './useKeyboardTableSpaceActions'
owncloud/web/packages/web-app-files/src/composables/keyboardActions/index.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/src/composables/keyboardActions/index.ts", "repo_id": "owncloud", "token_count": 54 }
802
export * from './avatarUrl'
owncloud/web/packages/web-app-files/src/helpers/user/index.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/src/helpers/user/index.ts", "repo_id": "owncloud", "token_count": 10 }
803
import { SDKSearch } from '../search' export default class Registry { static sdkSearch: SDKSearch }
owncloud/web/packages/web-app-files/src/services/registry.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/src/services/registry.ts", "repo_id": "owncloud", "token_count": 29 }
804
import Uppy, { UppyFile, State, UIPlugin } from '@uppy/core' import { HandleUpload } from '../../src/HandleUpload' import { mock, mockDeep } from 'vitest-mock-extended' import { Resource, SpaceResource } from '@ownclouders/web-client/src' import { RouteLocationNormalizedLoaded } from 'vue-router' import { ref, unref } from 'vue' import { ClientService, UppyService, UppyResource, locationSpacesGeneric, useUserStore, useMessages, useSpacesStore, useResourcesStore } from '@ownclouders/web-pkg' import { Language } from 'vue3-gettext' import { ResourceConflict } from 'web-app-files/src/helpers/resource/actions' import { createTestingPinia } from 'web-test-helpers' vi.mock('web-app-files/src/helpers/resource/actions') describe('HandleUpload', () => { it('installs the handleUpload callback when files are being added', () => { const { instance, mocks } = getWrapper() instance.install() expect(mocks.uppy.on).toHaveBeenCalledWith('files-added', instance.handleUpload) }) it('uninstalls the handleUpload callback when files are being added', () => { const { instance, mocks } = getWrapper() instance.uninstall() expect(mocks.uppy.off).toHaveBeenCalledWith('files-added', instance.handleUpload) }) it('removes files from the uppy upload queue', () => { const { instance, mocks } = getWrapper() const fileToRemove = mock<UppyResource>() instance.removeFilesFromUpload([fileToRemove]) expect(mocks.uppy.removeFile).toHaveBeenCalledWith(fileToRemove.id) }) it('correctly prepares all files that need to be uploaded', () => { const { instance, mocks } = getWrapper() mocks.uppy.getPlugin.mockReturnValue(mock<UIPlugin>()) const fileToUpload = mock<UppyFile>({ name: 'name' }) const processedFiles = instance.prepareFiles([fileToUpload]) const resourcesStore = useResourcesStore() const currentFolder = resourcesStore.currentFolder const route = unref(mocks.opts.route) expect(processedFiles[0].tus.endpoint).toEqual('/') expect(processedFiles[0].meta.name).toEqual(fileToUpload.name) expect(processedFiles[0].meta.spaceId).toEqual(mocks.opts.space.id) expect(processedFiles[0].meta.spaceName).toEqual(mocks.opts.space.name) expect(processedFiles[0].meta.driveAlias).toEqual(mocks.opts.space.driveAlias) expect(processedFiles[0].meta.driveType).toEqual(mocks.opts.space.driveType) expect(processedFiles[0].meta.currentFolder).toEqual(currentFolder.path) expect(processedFiles[0].meta.currentFolderId).toEqual(currentFolder.id) expect(processedFiles[0].meta.tusEndpoint).toEqual(currentFolder.path) expect(processedFiles[0].meta.relativeFolder).toEqual('') expect(processedFiles[0].meta.routeName).toEqual(route.name) expect(processedFiles[0].meta.routeDriveAliasAndItem).toEqual(route.params.driveAliasAndItem) expect(processedFiles[0].meta.routeShareId).toEqual(route.query.shareId) }) describe('method createDirectoryTree', () => { it('creates a directory for a single file with a relative folder given', async () => { const { instance, mocks } = getWrapper() mocks.uppy.getPlugin.mockReturnValue(mock<UIPlugin>()) const relativeFolder = '/relativeFolder' const fileToUpload = mock<UppyResource>({ name: 'name', meta: { relativeFolder } }) const createdFolder = mock<Resource>() mocks.opts.clientService.webdav.createFolder.mockResolvedValue(createdFolder) const result = await instance.createDirectoryTree([fileToUpload]) const resourcesStore = useResourcesStore() const currentFolder = resourcesStore.currentFolder expect(mocks.opts.uppyService.publish).toHaveBeenCalledWith( 'uploadSuccess', expect.objectContaining({ name: relativeFolder.split('/')[1], isFolder: true, type: 'folder', meta: expect.objectContaining({ spaceId: mocks.opts.space.id, spaceName: mocks.opts.space.name, driveAlias: mocks.opts.space.driveAlias, driveType: mocks.opts.space.driveType, currentFolder: currentFolder.path, currentFolderId: currentFolder.id, relativeFolder: '', routeName: fileToUpload.meta.routeName, routeDriveAliasAndItem: fileToUpload.meta.routeDriveAliasAndItem, routeShareId: fileToUpload.meta.routeShareId, fileId: createdFolder.fileId }) }) ) expect(mocks.opts.clientService.webdav.createFolder).toHaveBeenCalledTimes(1) expect(mocks.opts.clientService.webdav.createFolder).toHaveBeenCalledWith(mocks.opts.space, { path: relativeFolder, fetchFolder: true }) expect(result.length).toBe(1) }) it('filters out files whose folders could not be created', async () => { vi.spyOn(console, 'error').mockImplementation(() => undefined) const { instance, mocks } = getWrapper() mocks.uppy.getPlugin.mockReturnValue(mock<UIPlugin>()) const relativeFolder = '/relativeFolder' const fileToUpload = mock<UppyResource>({ name: 'name', meta: { relativeFolder } }) mocks.opts.clientService.webdav.createFolder.mockRejectedValue({}) const result = await instance.createDirectoryTree([fileToUpload]) expect(mocks.opts.uppyService.publish).toHaveBeenCalledWith('uploadError', expect.anything()) expect(mocks.uppy.removeFile).toHaveBeenCalled() expect(result.length).toBe(0) }) }) describe('method handleUpload', () => { it('prepares files and eventually triggers the upload in uppy', async () => { const { instance, mocks } = getWrapper() const prepareFilesSpy = vi.spyOn(instance, 'prepareFiles') await instance.handleUpload([mock<UppyFile>({ name: 'name' })]) expect(prepareFilesSpy).toHaveBeenCalledTimes(1) expect(mocks.opts.uppyService.publish).toHaveBeenCalledWith( 'addedForUpload', expect.anything() ) expect(mocks.opts.uppyService.uploadFiles).toHaveBeenCalledTimes(1) }) describe('quota check', () => { it('checks quota if check enabled', async () => { const { instance } = getWrapper() const checkQuotaExceededSpy = vi.spyOn(instance, 'checkQuotaExceeded') await instance.handleUpload([mock<UppyFile>({ name: 'name' })]) expect(checkQuotaExceededSpy).toHaveBeenCalled() }) it('does not check quota if check disabled', async () => { const { instance } = getWrapper({ quotaCheckEnabled: false }) const checkQuotaExceededSpy = vi.spyOn(instance, 'checkQuotaExceeded') await instance.handleUpload([mock<UppyFile>({ name: 'name' })]) expect(checkQuotaExceededSpy).not.toHaveBeenCalled() }) it.each([ { size: 100, remaining: 90, driveType: 'project', quotaExceeded: true }, { size: 10, remaining: 90, driveType: 'project', quotaExceeded: false }, { size: 100, remaining: 90, driveType: 'personal', quotaExceeded: true }, { size: 10, remaining: 90, driveType: 'personal', quotaExceeded: false } ])( 'returns a correct result after quota has been checked for own personal and project spaces', async ({ size, remaining, driveType, quotaExceeded }) => { const space = mock<SpaceResource>({ driveType, id: '1', spaceQuota: { remaining }, isOwner: () => true }) const { instance } = getWrapper({ spaces: [space] }) const result = await instance.checkQuotaExceeded([ mock<UppyResource>({ name: 'name', meta: { spaceId: '1', routeName: locationSpacesGeneric.name as any }, data: { size } }) ]) expect(result).toBe(quotaExceeded) } ) it('does not check quota for share spaces', async () => { const size = 100 const remaining = 90 const space = mock<SpaceResource>({ driveType: 'share', id: '1', spaceQuota: { remaining } }) const { instance } = getWrapper({ spaces: [space] }) const result = await instance.checkQuotaExceeded([ mock<UppyResource>({ name: 'name', meta: { spaceId: '1', routeName: locationSpacesGeneric.name as any }, data: { size } }) ]) expect(result).toBeFalsy() }) it("does not check quota for other's personal spaces", async () => { const size = 100 const remaining = 90 const space = mock<SpaceResource>({ driveType: 'personal', id: '1', spaceQuota: { remaining }, isOwner: () => false }) const { instance } = getWrapper({ spaces: [space] }) const result = await instance.checkQuotaExceeded([ mock<UppyResource>({ name: 'name', meta: { spaceId: '1', routeName: locationSpacesGeneric.name as any }, data: { size } }) ]) expect(result).toBeFalsy() }) }) describe('conflict handling check', () => { it('checks for conflicts if check enabled', async () => { const { instance, mocks } = getWrapper() await instance.handleUpload([mock<UppyFile>({ name: 'name' })]) expect(mocks.resourceConflict.getConflicts).toHaveBeenCalled() }) it('does not check for conflicts if check disabled', async () => { const { instance, mocks } = getWrapper({ conflictHandlingEnabled: false }) await instance.handleUpload([mock<UppyFile>({ name: 'name' })]) expect(mocks.resourceConflict.getConflicts).not.toHaveBeenCalled() }) it('does not start upload if all files were skipped in conflict handling', async () => { const { instance, mocks } = getWrapper({ conflicts: [{}], conflictHandlerResult: [] }) const removeFilesFromUploadSpy = vi.spyOn(instance, 'removeFilesFromUpload') await instance.handleUpload([mock<UppyFile>({ name: 'name' })]) expect(mocks.opts.uppyService.uploadFiles).not.toHaveBeenCalled() expect(mocks.opts.uppyService.clearInputs).toHaveBeenCalled() expect(removeFilesFromUploadSpy).toHaveBeenCalled() }) it('sets the result of the conflict handler as uppy file state', async () => { const conflictHandlerResult = [mock<UppyResource>({ id: '1' })] const { instance, mocks } = getWrapper({ conflicts: [{}], conflictHandlerResult }) await instance.handleUpload([mock<UppyFile>(), mock<UppyFile>()]) expect(mocks.uppy.setState).toHaveBeenCalledWith({ files: { [conflictHandlerResult[0].id]: conflictHandlerResult[0] } }) }) }) describe('create directory tree', () => { it('creates the directly tree if enabled', async () => { const { instance } = getWrapper() const createDirectoryTreeSpy = vi.spyOn(instance, 'createDirectoryTree') await instance.handleUpload([mock<UppyFile>({ name: 'name' })]) expect(createDirectoryTreeSpy).toHaveBeenCalled() }) it('does not create the directly tree if disabled', async () => { const { instance } = getWrapper({ directoryTreeCreateEnabled: false }) const createDirectoryTreeSpy = vi.spyOn(instance, 'createDirectoryTree') await instance.handleUpload([mock<UppyFile>({ name: 'name' })]) expect(createDirectoryTreeSpy).not.toHaveBeenCalled() }) }) }) }) const getWrapper = ({ conflictHandlingEnabled = true, directoryTreeCreateEnabled = true, quotaCheckEnabled = true, conflicts = [], conflictHandlerResult = [], spaces = [] } = {}) => { const resourceConflict = mock<ResourceConflict>() resourceConflict.getConflicts.mockReturnValue(conflicts) resourceConflict.displayOverwriteDialog.mockResolvedValue(conflictHandlerResult) vi.mocked(ResourceConflict).mockImplementation(() => resourceConflict) const route = mock<RouteLocationNormalizedLoaded>() route.params.driveAliasAndItem = '1' route.query.shareId = '1' const uppy = mockDeep<Uppy>() uppy.getState.mockReturnValue(mock<State>({ files: {} })) createTestingPinia({ initialState: { spaces: { spaces }, resources: { currentFolder: mock<Resource>({ path: '/' }), resources: [mock<Resource>()] } } }) const opts = { clientService: mockDeep<ClientService>(), language: mock<Language>(), route: ref(route), userStore: useUserStore(), messageStore: useMessages(), spacesStore: useSpacesStore(), resourcesStore: useResourcesStore(), space: mock<SpaceResource>(), uppyService: mock<UppyService>(), conflictHandlingEnabled, directoryTreeCreateEnabled, quotaCheckEnabled } const mocks = { uppy, opts, resourceConflict } const instance = new HandleUpload(uppy, opts) return { instance, mocks } }
owncloud/web/packages/web-app-files/tests/unit/HandleUpload.spec.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/tests/unit/HandleUpload.spec.ts", "repo_id": "owncloud", "token_count": 5042 }
805
import { merge } from 'lodash-es' import { shallowMount } from '@vue/test-utils' import List from 'web-app-files/src/components/Search/List.vue' import { useResourcesViewDefaults } from 'web-app-files/src/composables' import { useResourcesViewDefaultsMock } from 'web-app-files/tests/mocks/useResourcesViewDefaultsMock' import { createRouter, createMemoryHistory } from 'vue-router' import { defaultComponentMocks, defaultPlugins, mockAxiosResolve } from 'web-test-helpers/src' import { AppBar, ItemFilter, queryItemAsString, useResourcesStore } from '@ownclouders/web-pkg' import { ref } from 'vue' import { Resource } from '@ownclouders/web-client/src' import { mock } from 'vitest-mock-extended' import { Capabilities } from '@ownclouders/web-client/src/ocs' vi.mock('web-app-files/src/composables') vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({ ...(await importOriginal<any>()), queryItemAsString: vi.fn(), useAppDefaults: vi.fn(), useFileActions: vi.fn() })) const selectors = { noContentMessageStub: 'no-content-message-stub', resourceTableStub: 'resource-table-stub', tagFilter: '.files-search-filter-tags', lastModifiedFilter: '.files-search-filter-last-modified', titleOnlyFilter: '.files-search-filter-title-only', filter: '.files-search-result-filter' } describe('List component', () => { it('should render no-content-message if no resources found', () => { const { wrapper } = getWrapper() expect(wrapper.find(selectors.noContentMessageStub).exists()).toBeTruthy() }) it('should render resource table if resources found', () => { const { wrapper } = getWrapper({ resources: [mock<Resource>()] }) expect(wrapper.find(selectors.resourceTableStub).exists()).toBeTruthy() }) it('resets the initial store file state', () => { getWrapper({ resources: [mock<Resource>()] }) const { clearResourceList } = useResourcesStore() expect(clearResourceList).toHaveBeenCalled() }) it('should emit search event on mount', async () => { const { wrapper } = getWrapper() await wrapper.vm.loadAvailableTagsTask.last expect(wrapper.emitted('search').length).toBeGreaterThan(0) }) it('should emit search only if one of the queries changes', async () => { const $router = createRouter({ routes: [{ name: 'files-common-search', path: '/files-common-search', redirect: null }], history: createMemoryHistory() }) const { wrapper } = getWrapper({ mocks: { $router } }) let replacementCounter = 0 const queries = [{}, {}, {}, {}, {}, {}, {}, {}, { q_tags: 'foo' }, {}, {}, {}, {}] for (const query of queries) { await $router.replace({ name: 'files-common-search', query: merge( { q_titleOnly: 'q_titleOnly', q_tags: 'q_tags', q_lastModified: 'q_lastModified', useScope: 'useScope' }, query ) }) replacementCounter++ } await wrapper.vm.loadAvailableTagsTask.last expect(replacementCounter).toBe(queries.length) expect(wrapper.emitted('search').length).toBe(4) }) describe('breadcrumbs', () => { it('show "Search" when no search term given', () => { const { wrapper } = getWrapper() const appBar = wrapper.findComponent<typeof AppBar>('app-bar-stub') expect(appBar.props('breadcrumbs')[0].text).toEqual('Search') }) it('include the search term if given', () => { const searchTerm = 'term' const { wrapper } = getWrapper({ searchTerm }) const appBar = wrapper.findComponent<typeof AppBar>('app-bar-stub') expect(appBar.props('breadcrumbs')[0].text).toEqual(`Search results for "${searchTerm}"`) }) }) describe('filter', () => { describe('general', () => { it('should not be rendered if no filtering is available', async () => { const { wrapper } = getWrapper({ fullTextSearchEnabled: false, availableTags: [] }) await wrapper.vm.loadAvailableTagsTask.last expect(wrapper.find(selectors.filter).exists()).toBeFalsy() }) }) describe('tags', () => { it('should show all available tags', async () => { const tag = 'tag1' const { wrapper } = getWrapper({ availableTags: [tag] }) await wrapper.vm.loadAvailableTagsTask.last expect(wrapper.find(selectors.tagFilter).exists()).toBeTruthy() expect( wrapper.findComponent<typeof ItemFilter>(selectors.tagFilter).props('items') ).toEqual([{ label: tag, id: tag }]) }) it('should set initial filter when tags are given via query param', async () => { const searchTerm = 'term' const availableTags = ['tag1', 'tag2'] const { wrapper } = getWrapper({ availableTags, searchTerm, tagFilterQuery: availableTags.join('+') }) await wrapper.vm.loadAvailableTagsTask.last expect(wrapper.emitted('search')[0][0]).toEqual( `(name:"*${searchTerm}*" OR content:"${searchTerm}") AND tag:("${availableTags[0]}" OR "${availableTags[1]}")` ) }) }) describe('last modified', () => { it('should show available last modified values', async () => { const expectation = [ { label: 'today', id: 'today' }, { label: 'yesterday', id: 'yesterday' }, { label: 'this week', id: 'this week' }, { label: 'last week', id: 'last week' }, { label: 'last 7 days', id: 'last 7 days' }, { label: 'this month', id: 'this month' }, { label: 'last month', id: 'last month' }, { label: 'last 30 days', id: 'last 30 days' }, { label: 'this year', id: 'this year' }, { label: 'last year', id: 'last year' } ] const lastModifiedValues = { keywords: [ 'today', 'yesterday', 'this week', 'last week', 'last 7 days', 'this month', 'last month', 'last 30 days', 'this year', 'last year' ] } const { wrapper } = getWrapper({ availableLastModifiedValues: lastModifiedValues, availableTags: ['tag'] }) await wrapper.vm.loadAvailableTagsTask.last expect(wrapper.find(selectors.lastModifiedFilter).exists()).toBeTruthy() expect( wrapper.findComponent<typeof ItemFilter>(selectors.lastModifiedFilter).props('items') ).toEqual(expectation) }) it('should set initial filter when last modified is given via query param', async () => { const searchTerm = 'Screenshot' const lastModifiedFilterQuery = 'today' const { wrapper } = getWrapper({ searchTerm, lastModifiedFilterQuery }) await wrapper.vm.loadAvailableTagsTask.last expect(wrapper.emitted('search')[0][0]).toEqual( `(name:"*${searchTerm}*" OR content:"${searchTerm}") AND mtime:${lastModifiedFilterQuery}` ) }) }) describe('titleOnly', () => { it('should render filter if enabled via capabilities', () => { const { wrapper } = getWrapper({ fullTextSearchEnabled: true }) expect(wrapper.find(selectors.titleOnlyFilter).exists()).toBeTruthy() }) it('should not render filter if not enabled via capabilities', () => { const { wrapper } = getWrapper({ fullTextSearchEnabled: false }) expect(wrapper.find(selectors.titleOnlyFilter).exists()).toBeFalsy() }) it('should set initial filter when titleOnly is set active via query param', async () => { const searchTerm = 'term' const { wrapper } = getWrapper({ searchTerm, titleOnlyFilterQuery: 'true', fullTextSearchEnabled: true }) await wrapper.vm.loadAvailableTagsTask.last expect(wrapper.emitted('search')[0][0]).toEqual(`name:"*${searchTerm}*"`) }) }) }) }) function getWrapper({ availableTags = [], resources = [], searchTerm = '', tagFilterQuery = null, titleOnlyFilterQuery = null, fullTextSearchEnabled = true, availableLastModifiedValues = {}, lastModifiedFilterQuery = null, mocks = {} } = {}) { vi.mocked(queryItemAsString).mockImplementationOnce(() => searchTerm) vi.mocked(queryItemAsString).mockImplementationOnce(() => titleOnlyFilterQuery) vi.mocked(queryItemAsString).mockImplementationOnce(() => tagFilterQuery) vi.mocked(queryItemAsString).mockImplementationOnce(() => lastModifiedFilterQuery) const resourcesViewDetailsMock = useResourcesViewDefaultsMock({ paginatedResources: ref(resources) }) vi.mocked(useResourcesViewDefaults).mockImplementation(() => resourcesViewDetailsMock) const localMocks = { ...defaultComponentMocks(), ...mocks } localMocks.$clientService.graphAuthenticated.tags.getTags.mockResolvedValue( mockAxiosResolve({ value: availableTags }) ) const capabilities = { files: { tags: true }, search: { property: { mtime: availableLastModifiedValues, content: { enabled: fullTextSearchEnabled }, tags: { enabled: true } } } } satisfies Partial<Capabilities['capabilities']> return { mocks: localMocks, wrapper: shallowMount(List, { global: { mocks: localMocks, provide: localMocks, stubs: { FilesViewWrapper: false }, plugins: [...defaultPlugins({ piniaOptions: { capabilityState: { capabilities } } })] } }) } }
owncloud/web/packages/web-app-files/tests/unit/components/Search/List.spec.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/tests/unit/components/Search/List.spec.ts", "repo_id": "owncloud", "token_count": 3780 }
806
import { LinkShare } from '@ownclouders/web-client/src/helpers' import { useMessages } from '@ownclouders/web-pkg' import NameAndCopy from 'web-app-files/src/components/SideBar/Shares/Links/NameAndCopy.vue' import { defaultPlugins, mount } from 'web-test-helpers' const linkShare = { displayName: 'Example link', webUrl: 'https://some-url.com/abc' } as LinkShare // @vitest-environment jsdom describe('NameAndCopy', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) // ignore tippy warning vi.spyOn(console, 'warn').mockImplementation(undefined) it('should show link info component including a copy-to-clipboard button', () => { const { wrapper } = getWrapper() expect(wrapper.html()).toMatchSnapshot() }) it('upon clicking it should copy the private link to the clipboard button, render a success message and change icon for half a second', async () => { Object.assign(window.navigator, { clipboard: { writeText: vi.fn().mockImplementation(() => Promise.resolve()) } }) const { wrapper } = getWrapper() const { showMessage } = useMessages() expect(showMessage).not.toHaveBeenCalled() await wrapper.find('.oc-files-public-link-copy-url').trigger('click') expect(window.navigator.clipboard.writeText).toHaveBeenCalledWith(linkShare.webUrl) expect(wrapper.html()).toMatchSnapshot() expect(showMessage).toHaveBeenCalledTimes(1) vi.advanceTimersByTime(550) wrapper.vm.$nextTick(() => { expect(wrapper.html()).toMatchSnapshot() }) }) }) function getWrapper() { return { wrapper: mount(NameAndCopy, { props: { linkShare }, global: { plugins: [...defaultPlugins()], directives: { 'oc-tooltip': vi.fn() } } }) } }
owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/Links/NameAndCopy.spec.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/tests/unit/components/SideBar/Shares/Links/NameAndCopy.spec.ts", "repo_id": "owncloud", "token_count": 700 }
807
import { createPinia, setActivePinia } from 'pinia' import { navItems } from '../../src/index' import { useSpacesStore } from '@ownclouders/web-pkg' import { SpaceResource } from '@ownclouders/web-client' import { mock } from 'vitest-mock-extended' describe('Web app files', () => { beforeEach(() => { setActivePinia(createPinia()) const spacesStore = useSpacesStore() spacesStore.spacesInitialized = true }) describe('navItems', () => { describe('Personal', () => { it('should be enabled if user has a personal space', () => { const spacesStore = useSpacesStore() spacesStore.spaces = [ mock<SpaceResource>({ id: '1', driveType: 'personal', isOwner: () => true }) ] const items = navItems(undefined) expect(items[0].isVisible()).toBeTruthy() }) it('should be disabled if user has no a personal space', () => { const spacesStore = useSpacesStore() spacesStore.spaces = [ mock<SpaceResource>({ id: '1', driveType: 'project', isOwner: () => false }) ] const items = navItems(undefined) expect(items[0].isVisible()).toBeFalsy() }) }) }) })
owncloud/web/packages/web-app-files/tests/unit/index.spec.ts/0
{ "file_path": "owncloud/web/packages/web-app-files/tests/unit/index.spec.ts", "repo_id": "owncloud", "token_count": 466 }
808
[main] host = https://www.transifex.com [o:owncloud-org:p:owncloud-web:r:pdf-viewer] file_filter = locale/<lang>/LC_MESSAGES/app.po minimum_perc = 0 source_file = template.pot source_lang = en type = PO
owncloud/web/packages/web-app-pdf-viewer/l10n/.tx/config/0
{ "file_path": "owncloud/web/packages/web-app-pdf-viewer/l10n/.tx/config", "repo_id": "owncloud", "token_count": 86 }
809
import App from '../../src/App.vue' import { nextTick, ref } from 'vue' import { defaultComponentMocks, defaultPlugins, shallowMount } from 'web-test-helpers' import { useAppDefaultsMock } from 'web-test-helpers/src/mocks/useAppDefaultsMock' import { FileContext, useAppDefaults } from '@ownclouders/web-pkg' import { mock } from 'vitest-mock-extended' vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({ ...(await importOriginal<any>()), useAppDefaults: vi.fn(), useAppFileHandling: vi.fn() })) const activeFiles = [ { id: '1', name: 'bear.png', mimeType: 'image/png', path: 'personal/admin/bear.png' }, { id: '2', name: 'elephant.png', mimeType: 'image/png', path: 'personal/admin/elephant.png' }, { id: '3', name: 'wale_sounds.flac', mimeType: 'audio/flac', path: 'personal/admin/wale_sounds.flac' }, { id: '4', name: 'lonely_sloth_very_sad.gif', mimeType: 'image/gif', path: 'personal/admin/lonely_sloth_very_sad.gif' }, { id: '5', name: 'tiger_eats_plants.mp4', mimeType: 'video/mp4', path: 'personal/admin/tiger_eats_plants.mp4' }, { id: '6', name: 'happy_hippo.gif', mimeType: 'image/gif', path: 'personal/admin/happy_hippo.gif' }, { id: '7', name: 'sleeping_dog.gif', mimeType: 'image/gif', path: 'personal/admin/sleeping_dog.gif' }, { id: '8', name: 'cat_murr_murr.gif', mimeType: 'image/gif', path: 'personal/admin/cat_murr_murr.gif' }, { id: '9', name: 'labrador.gif', mimeType: 'image/gif', path: 'personal/admin/labrador.gif' } ] describe('Preview app', () => { describe('Method "preloadImages"', () => { it('should preload images if active file changes', async () => { const { wrapper } = createShallowMountWrapper() await nextTick() wrapper.vm.toPreloadImageIds = [] wrapper.vm.preloadImageCount = 3 wrapper.vm.setActiveFile('personal/admin/sleeping_dog.gif') await nextTick() expect(wrapper.vm.toPreloadImageIds).toEqual(['8', '9', '1', '6', '4']) }) }) }) function createShallowMountWrapper() { vi.mocked(useAppDefaults).mockImplementation(() => useAppDefaultsMock({ currentFileContext: ref( mock<FileContext>({ path: 'personal/admin/bear.png', space: { getDriveAliasAndItem: vi.fn().mockImplementation((file) => { return activeFiles.find((filteredFile) => filteredFile.id == file.id)?.path }) } }) ), activeFiles: ref(activeFiles) }) ) const mocks = defaultComponentMocks() mocks.$previewService.loadPreview.mockResolvedValue('') return { wrapper: shallowMount(App, { global: { plugins: [...defaultPlugins()], mocks, provide: mocks } }) } }
owncloud/web/packages/web-app-preview/tests/unit/app.spec.ts/0
{ "file_path": "owncloud/web/packages/web-app-preview/tests/unit/app.spec.ts", "repo_id": "owncloud", "token_count": 1292 }
810
<template> <div class="oc-text-editor oc-width-1-1 oc-height-1-1" :class="{ 'oc-text-editor-readonly': isReadOnly }" > <text-editor-component :resource="resource" :application-config="applicationConfig" :current-content="currentContent" :is-read-only="isReadOnly" @update:current-content="$emit('update:currentContent', $event)" /> </div> </template> <script lang="ts"> import { defineComponent, PropType } from 'vue' import { Resource } from '@ownclouders/web-client/src/helpers/resource/types' import { AppConfigObject, TextEditor as TextEditorComponent } from '@ownclouders/web-pkg' export default defineComponent({ name: 'TextEditor', components: { TextEditorComponent }, props: { applicationConfig: { type: Object as PropType<AppConfigObject>, required: true }, currentContent: { type: String, required: true }, isReadOnly: { type: Boolean, required: false }, resource: { type: Object as PropType<Resource>, required: true } }, emits: ['update:currentContent'] }) </script> <style lang="scss"> .oc-text-editor-readonly { //Toastui Editor doesn't have margins in view mode, adjusted for uniformity padding: 18px 25px; //Fixes in readonly mode vertical scrolling is not available height: calc(100vh - 52px); overflow: auto; } // Make url links limited in height and scrollable since base64 encoded images might be very long .toastui-editor-md-link-url { display: block; max-height: 100px; overflow: auto; } // Adjustments to match our theming .toastui-editor-defaultUI { border: none; } .toastui-editor-defaultUI-toolbar, .toastui-editor-md-tab-container { background-color: var(--oc-color-background-default) !important; } </style>
owncloud/web/packages/web-app-text-editor/src/App.vue/0
{ "file_path": "owncloud/web/packages/web-app-text-editor/src/App.vue", "repo_id": "owncloud", "token_count": 603 }
811
export * from './functions'
owncloud/web/packages/web-client/src/helpers/publicLink/index.ts/0
{ "file_path": "owncloud/web/packages/web-client/src/helpers/publicLink/index.ts", "repo_id": "owncloud", "token_count": 9 }
812
import { AxiosInstance } from 'axios' import { graph, Graph } from './graph' import { ocs, OCS } from './ocs' import { User } from './generated' import { Ref } from 'vue' export type { Graph } from './graph' export type { OCS } from './ocs' export * as errors from './errors' export * as helpers from './helpers' export * as webdav from './webdav' export type { Resource, SpaceResource, User } from './helpers' interface Client { graph: Graph ocs: OCS } export const client = (baseURI: string, axiosClient: AxiosInstance, user: Ref<User>): Client => { return { graph: graph(baseURI, axiosClient), ocs: ocs(baseURI, axiosClient, user) } }
owncloud/web/packages/web-client/src/index.ts/0
{ "file_path": "owncloud/web/packages/web-client/src/index.ts", "repo_id": "owncloud", "token_count": 230 }
813
import { FolderResource, SpaceResource } from '../helpers' import { GetFileInfoFactory } from './getFileInfo' import { urlJoin } from '../utils' import { DAV } from './client/dav' import { WebDavOptions } from './types' import { buildAuthHeader } from './client' import { unref } from 'vue' export const CreateFolderFactory = ( dav: DAV, getFileInfoFactory: ReturnType<typeof GetFileInfoFactory>, { accessToken }: WebDavOptions ) => { return { async createFolder( space: SpaceResource, { path, fetchFolder = true }: { path?: string; fetchFolder?: boolean } ): Promise<FolderResource> { const headers = buildAuthHeader(unref(accessToken), space) await dav.mkcol(urlJoin(space.webDavPath, path, { leadingSlash: true }), { headers }) if (fetchFolder) { return getFileInfoFactory.getFileInfo(space, { path }) } } } }
owncloud/web/packages/web-client/src/webdav/createFolder.ts/0
{ "file_path": "owncloud/web/packages/web-client/src/webdav/createFolder.ts", "repo_id": "owncloud", "token_count": 307 }
814
import { Resource, buildResource } from '../helpers' import { WebDavOptions } from './types' import { DavProperties, DavProperty, DavPropertyValue } from './constants' import { DAV, buildAuthHeader } from './client' import { unref } from 'vue' export interface SearchResource extends Resource { highlights: string } export type SearchOptions = { davProperties?: DavPropertyValue[] searchLimit?: number } export type SearchResult = { resources: SearchResource[] totalResults: number } export const SearchFactory = (dav: DAV, { accessToken }: WebDavOptions) => { return { async search( term: string, { davProperties = DavProperties.Default, searchLimit }: SearchOptions ): Promise<SearchResult> { const path = '/spaces/' const headers = buildAuthHeader(unref(accessToken)) const { range, results } = await dav.report(path, { pattern: term, limit: searchLimit, properties: davProperties, headers }) return { resources: results.map((r) => ({ ...buildResource(r), highlights: r.props[DavProperty.Highlights] || '' })), totalResults: range ? parseInt(range?.split('/')[1]) : null } } } }
owncloud/web/packages/web-client/src/webdav/search.ts/0
{ "file_path": "owncloud/web/packages/web-client/src/webdav/search.ts", "repo_id": "owncloud", "token_count": 453 }
815
import { App, ComponentCustomProperties, Ref } from 'vue' import { RouteLocationRaw, Router, RouteRecordRaw } from 'vue-router' import { Extension } from '../composables/piniaStores' import { IconFillType } from '../helpers' import { Resource, SpaceResource } from '@ownclouders/web-client' export interface AppReadyHookArgs { globalProperties: ComponentCustomProperties & Record<string, any> router: Router instance?: App portal?: any } export interface AppNavigationItem { isActive?: () => boolean activeFor?: { name?: string; path?: string }[] isVisible?: () => boolean fillType?: IconFillType icon?: string name: string | (() => string) route?: RouteLocationRaw handler?: () => void priority?: number } /** * ApplicationQuickAction describes an application action that is used in the runtime. * * @deprecated Quick actions should be registered as extension via the `files.quick-action` scope. */ export interface ApplicationQuickAction { id?: string label?: (...args) => string | string icon?: string iconFillType?: IconFillType handler?: (...args) => Promise<void> | void displayed?: (...args) => boolean | boolean } export type AppConfigObject = Record<string, any> export interface ApplicationMenuItem { enabled: () => boolean priority?: number openAsEditor?: boolean } export interface ApplicationFileExtension { app?: string extension?: string createFileHandler?: (arg: { fileName: string space: SpaceResource currentFolder: Resource }) => Promise<Resource> hasPriority?: boolean label?: string name?: string icon?: string mimeType?: string newFileMenu?: { menuTitle: () => string } routeName?: string } /** ApplicationInformation describes required information of an application */ export interface ApplicationInformation { color?: string id?: string name?: string icon?: string iconFillType?: IconFillType iconColor?: string img?: string isFileEditor?: boolean extensions?: ApplicationFileExtension[] defaultExtension?: string applicationMenu?: ApplicationMenuItem } /** * ApplicationTranslations is a map of language keys to translations */ export interface ApplicationTranslations { [lang: string]: { [key: string]: string | string[] } } /** ClassicApplicationScript reflects classic application script structure */ export interface ClassicApplicationScript { appInfo?: ApplicationInformation routes?: ((...args) => RouteRecordRaw[]) | RouteRecordRaw[] navItems?: ((...args) => AppNavigationItem[]) | AppNavigationItem[] translations?: ApplicationTranslations extensions?: Ref<Extension[]> initialize?: () => void ready?: (args: AppReadyHookArgs) => Promise<void> | void mounted?: (...args) => void // TODO: move this to its own type setup?: (args: { applicationConfig: AppConfigObject }) => ClassicApplicationScript } export type ApplicationSetupOptions = { applicationConfig: AppConfigObject } export const defineWebApplication = (args: { setup: (options: ApplicationSetupOptions) => ClassicApplicationScript }) => { return args }
owncloud/web/packages/web-pkg/src/apps/types.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/apps/types.ts", "repo_id": "owncloud", "token_count": 834 }
816
import { Resource } from '@ownclouders/web-client' import { AppConfigObject } from '../../apps/types' import { Ref } from 'vue' export interface AppWrapperSlotArgs { applicationConfig: AppConfigObject resource: Resource currentContent: Ref<string> isDirty: boolean isReadOnly: boolean url: string }
owncloud/web/packages/web-pkg/src/components/AppTemplates/types.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/components/AppTemplates/types.ts", "repo_id": "owncloud", "token_count": 94 }
817
<template> <oc-table v-bind="$attrs" id="files-space-table" :class="[ hoverableQuickActions && 'hoverable-quick-actions', { condensed: viewMode === FolderViewModeConstants.name.condensedTable, 'files-table': resourceType === 'file', 'files-table-squashed': resourceType === 'file' && isSideBarOpen, 'spaces-table': resourceType === 'space', 'spaces-table-squashed': resourceType === 'space' && isSideBarOpen } ]" :data="resources" :fields="fields" :highlighted="selectedIds" :disabled="disabledResources" :sticky="true" :header-position="headerPosition" :drag-drop="dragDrop" :hover="hover" :item-dom-selector="resourceDomSelector" :selection="selectedResources" :sort-by="sortBy" :sort-dir="sortDir" :lazy="lazyLoading" :grouping-settings="groupingSettings" padding-x="medium" @highlight="fileClicked" @row-mounted="rowMounted" @contextmenu-clicked="showContextMenu" @item-dropped="fileDropped" @item-dragged="fileDragged" @drop-row-styling="dropRowStyling" @sort="sort" @update:model-value="$emit('update:modelValue', $event)" > <template v-if="!isLocationPicker" #selectHeader> <div class="resource-table-select-all"> <oc-checkbox id="resource-table-select-all" size="large" :label="allResourcesCheckboxLabel" :hide-label="true" :model-value="areAllResourcesSelected" @update:model-value="toggleSelectionAll" /> </div> </template> <template v-if="!isLocationPicker" #select="{ item }"> <oc-checkbox :id="`resource-table-select-${resourceDomSelector(item)}`" :label="getResourceCheckboxLabel(item)" :hide-label="true" size="large" :model-value="isResourceSelected(item)" :outline="isLatestSelectedItem(item)" @update:model-value="setSelection($event, item)" @click.stop="fileClicked([item, $event, true])" /> </template> <template #name="{ item }"> <div class="resource-table-resource-wrapper" :class="[{ 'resource-table-resource-wrapper-limit-max-width': hasRenameAction(item) }]" > <slot name="image" :resource="item" /> <resource-list-item :key="`${item.path}-${resourceDomSelector(item)}-${item.thumbnail}`" :resource="item" :path-prefix="getPathPrefix(item)" :is-path-displayed="arePathsDisplayed" :parent-folder-name="getParentFolderName(item)" :is-thumbnail-displayed="shouldDisplayThumbnails(item)" :is-icon-displayed="!$slots['image']" :is-extension-displayed="areFileExtensionsShown" :is-resource-clickable="isResourceClickable(item)" :folder-link="getFolderLink(item)" :parent-folder-link="getParentFolderLink(item)" :parent-folder-link-icon-additional-attributes=" getParentFolderLinkIconAdditionalAttributes(item) " :class="{ 'resource-table-resource-cut': isResourceCut(item) }" @click="emitFileClick(item)" /> <oc-button v-if="hasRenameAction(item)" class="resource-table-edit-name" appearance="raw" @click="openRenameDialog(item)" > <oc-icon name="edit-2" fill-type="line" size="small" /> </oc-button> </div> <slot name="additionalResourceContent" :resource="item" /> </template> <template #syncEnabled="{ item }"> <!-- @slot syncEnabled column --> <slot name="syncEnabled" :resource="item" /> </template> <template #size="{ item }"> <resource-size :size="item.size || Number.NaN" /> </template> <template #tags="{ item }"> <component :is="userContextReady ? 'router-link' : 'span'" v-for="tag in item.tags.slice(0, 2)" :key="tag" v-bind="getTagComponentAttrs(tag)" class="resource-table-tag-wrapper" > <oc-tag v-oc-tooltip="getTagToolTip(tag)" class="resource-table-tag oc-ml-xs" :rounded="true" size="small" > <oc-icon name="price-tag-3" size="small" /> <span class="oc-text-truncate">{{ tag }}</span> </oc-tag> </component> <oc-tag v-if="item.tags.length > 2" size="small" class="resource-table-tag-more" @click="openTagsSidebar" > + {{ item.tags.length - 2 }} </oc-tag> </template> <template #manager="{ item }"> <slot name="manager" :resource="item" /> </template> <template #members="{ item }"> <slot name="members" :resource="item" /> </template> <template #totalQuota="{ item }"> <slot name="totalQuota" :resource="item" /> </template> <template #usedQuota="{ item }"> <slot name="usedQuota" :resource="item" /> </template> <template #remainingQuota="{ item }"> <slot name="remainingQuota" :resource="item" /> </template> <template #mdate="{ item }"> <span v-oc-tooltip="formatDate(item.mdate)" tabindex="0" v-text="formatDateRelative(item.mdate)" /> </template> <template #indicators="{ item }"> <oc-status-indicators v-if="item.indicators.length" :resource="item" :indicators="item.indicators" /> </template> <template #sdate="{ item }"> <span v-oc-tooltip="formatDate(item.sdate)" tabindex="0" v-text="formatDateRelative(item.sdate)" /> </template> <template #ddate="{ item }"> <span v-oc-tooltip="formatDate(item.ddate)" tabindex="0" v-text="formatDateRelative(item.ddate)" /> </template> <template #sharedBy="{ item }"> <oc-button appearance="raw-inverse" variation="passive" @click="openSharingSidebar(item)"> <oc-avatars class="resource-table-people" :items="getSharedByAvatarItems(item)" :is-tooltip-displayed="true" :accessible-description="getSharedByAvatarDescription(item)" /> </oc-button> </template> <template #sharedWith="{ item }"> <oc-button appearance="raw-inverse" variation="passive" @click="openSharingSidebar(item)"> <oc-avatars class="resource-table-people" :items="getSharedWithAvatarItems(item)" :stacked="true" :max-displayed="3" :is-tooltip-displayed="true" :accessible-description="getSharedWithAvatarDescription(item)" /> </oc-button> </template> <template #actions="{ item }"> <div class="resource-table-actions"> <!-- @slot Add quick actions before the `context-menu / three dot` button in the actions column --> <slot name="quickActions" :resource="item" /> <context-menu-quick-action ref="contextMenuButton" :item="item" :resource-dom-selector="resourceDomSelector" class="resource-table-btn-action-dropdown" @quick-action-clicked="showContextMenuOnBtnClick($event, item)" > <template #contextMenu> <slot name="contextMenu" :resource="item" /> </template> </context-menu-quick-action> </div> </template> <template v-if="$slots.footer" #footer> <!-- @slot Footer of the files table --> <slot name="footer" /> </template> </oc-table> <Teleport v-if="dragItem" to="body"> <resource-ghost-element ref="ghostElement" :preview-items="[dragItem, ...dragSelection]" /> </Teleport> </template> <script lang="ts"> import { defineComponent, PropType, computed, unref, ref, ComputedRef } from 'vue' import { useWindowSize } from '@vueuse/core' import { Resource } from '@ownclouders/web-client' import { extractDomSelector, SpaceResource } from '@ownclouders/web-client/src/helpers' import { ShareTypes, isIncomingShareResource, isShareResource } from '@ownclouders/web-client/src/helpers/share' import { SortDir, FolderViewModeConstants, useGetMatchingSpace, useFolderLink, useEmbedMode, useAuthStore, useCapabilityStore, useConfigStore, useClipboardStore, useResourcesStore } from '../../composables' import ResourceListItem from './ResourceListItem.vue' import ResourceGhostElement from './ResourceGhostElement.vue' import ResourceSize from './ResourceSize.vue' import { EVENT_TROW_MOUNTED, EVENT_FILE_DROPPED, ImageDimension } from '../../constants' import { eventBus } from '../../services' import { displayPositionedDropdown, formatDateFromJSDate, formatRelativeDateFromJSDate } from '../../helpers' import { isResourceTxtFileAlmostEmpty } from '../../helpers/resource' import { SideBarEventTopics } from '../../composables/sideBar' import ContextMenuQuickAction from '../ContextActions/ContextMenuQuickAction.vue' import { useResourceRouteResolver } from '../../composables/filesList/useResourceRouteResolver' import { ClipboardActions } from '../../helpers/clipboardActions' import { determineResourceTableSortFields } from '../../helpers/ui/resourceTable' import { useFileActionsRename } from '../../composables/actions' import { createLocationCommon } from '../../router' import get from 'lodash-es/get' // ODS component import is necessary here for CERN to overwrite OcTable import OcTable from 'design-system/src/components/OcTable/OcTable.vue' import { storeToRefs } from 'pinia' const TAGS_MINIMUM_SCREEN_WIDTH = 850 export default defineComponent({ components: { ContextMenuQuickAction, ResourceGhostElement, OcTable, ResourceListItem, ResourceSize }, props: { /** * Resources to be displayed in the table. * Required fields: * - name: The name of the resource containing the file extension in case of a file * - path: The full path of the resource * - type: The type of the resource. Can be `file` or `folder` * Optional fields: * - thumbnail * - size: The size of the resource * - modificationDate: The date of the last modification of the resource * - shareDate: The date when the share was created * - deletionDate: The date when the resource has been deleted * - syncEnabled: The sync status of the share * - opensInNewWindow: Open the link in a new window */ resources: { type: Array as PropType<Resource[]>, required: true }, /** * Closure function to mutate the resource id into a valid DOM selector. */ resourceDomSelector: { type: Function, required: false, default: (resource) => extractDomSelector(resource.id) }, /** * Asserts whether resources path should be shown in the resource name */ arePathsDisplayed: { type: Boolean, required: false, default: false }, /** * Asserts whether icons should be replaced with thumbnails for resources which provide them */ areThumbnailsDisplayed: { type: Boolean, required: false, default: true }, /** * V-model for the selection */ selectedIds: { type: Array as PropType<string[]>, default: () => [] }, /** * Asserts whether actions are available */ hasActions: { type: Boolean, required: false, default: true }, /** * Accepts a `path` and a `resource` param and returns a corresponding route object. */ targetRouteCallback: { type: Function, required: false, default: undefined }, /** * Asserts whether clicking on the resource name triggers any action */ areResourcesClickable: { type: Boolean, required: false, default: true }, /** * Top position of header used when the header is sticky in pixels */ headerPosition: { type: Number, required: false, default: 0 }, /** * Asserts whether resources in the table can be selected */ isSelectable: { type: Boolean, required: false, default: true }, /** * Sets specific css classes for when the side bar is (not) open */ isSideBarOpen: { type: Boolean, required: false, default: false }, /** * Sets the padding size for x axis * @values xsmall, small, medium, large, xlarge */ paddingX: { type: String, required: false, default: 'small', validator: (size: string) => /(xsmall|small|medium|large|xlarge)/.test(size) }, /** * Enable Drag & Drop events */ dragDrop: { type: Boolean, required: false, default: false }, /** * The active view mode. */ viewMode: { type: String as PropType< | typeof FolderViewModeConstants.name.condensedTable | typeof FolderViewModeConstants.name.table >, default: () => FolderViewModeConstants.defaultModeName, validator: ( value: | typeof FolderViewModeConstants.name.condensedTable | typeof FolderViewModeConstants.name.table ) => [FolderViewModeConstants.name.condensedTable, FolderViewModeConstants.name.table].includes( value ) }, /** * Enable hover effect */ hover: { type: Boolean, required: false, default: true }, /** * Show that the table is sorted by this column (no actual sorting takes place) */ sortBy: { type: String, required: false, default: undefined }, /** * Define what fields should be displayed in the table * If null, all fields are displayed */ fieldsDisplayed: { type: Array, required: false, default: null }, /** * Show that the table is sorted ascendingly/descendingly (no actual sorting takes place) */ sortDir: { type: String, required: false, default: undefined, validator: (value: string) => { return ( value === undefined || [SortDir.Asc.toString(), SortDir.Desc.toString()].includes(value) ) } }, /** * Space resource the provided resources originate from. Not required on meta pages like favorites, search, ... */ space: { type: Object as PropType<SpaceResource>, required: false, default: null }, resourceType: { type: String as PropType<'file' | 'space'>, default: 'file' }, /** * This is only relevant for CERN and can be ignored in any other cases. */ groupingSettings: { type: Object, required: false, default: null } }, emits: [ 'fileClick', 'sort', 'rowMounted', EVENT_FILE_DROPPED, 'update:selectedIds', 'update:modelValue' ], setup(props, context) { const capabilityStore = useCapabilityStore() const { getMatchingSpace } = useGetMatchingSpace() const { isLocationPicker } = useEmbedMode() const configStore = useConfigStore() const { options: configOptions } = storeToRefs(configStore) const clipboardStore = useClipboardStore() const { resources: clipboardResources, action: clipboardAction } = storeToRefs(clipboardStore) const authStore = useAuthStore() const { userContextReady } = storeToRefs(authStore) const resourcesStore = useResourcesStore() const { toggleSelection } = resourcesStore const { areFileExtensionsShown, latestSelectedId } = storeToRefs(resourcesStore) const dragItem = ref<Resource>() const ghostElement = ref() const { width } = useWindowSize() const hasTags = computed( () => capabilityStore.filesTags && width.value >= TAGS_MINIMUM_SCREEN_WIDTH ) const { actions: renameActions } = useFileActionsRename() const renameHandler = computed(() => unref(renameActions)[0].handler) const getTagToolTip = (text: string) => (text.length > 7 ? text : '') const isResourceDisabled = (resource: Resource) => { return resource.processing === true } const disabledResources: ComputedRef<Array<Resource['id']>> = computed(() => { return ( props.resources ?.filter((resource) => isResourceDisabled(resource) === true) ?.map((resource) => resource.id) || [] ) }) return { configOptions, dragItem, ghostElement, getTagToolTip, renameActions, renameHandler, FolderViewModeConstants, hasTags, disabledResources, isResourceDisabled, userContextReady, getMatchingSpace, clipboardResources, clipboardAction, ...useResourceRouteResolver( { space: ref(props.space), targetRouteCallback: computed(() => props.targetRouteCallback) }, context ), ...useFolderLink({ space: ref(props.space), targetRouteCallback: computed(() => props.targetRouteCallback) }), isLocationPicker, toggleSelection, areFileExtensionsShown, latestSelectedId } }, data() { return { constants: { ImageDimension, EVENT_TROW_MOUNTED } } }, computed: { fields() { if (this.resources.length === 0) { return [] } const firstResource = this.resources[0] const fields = [] if (this.isSelectable) { fields.push({ name: 'select', title: '', type: 'slot', headerType: 'slot', width: 'shrink' }) } const sortFields = determineResourceTableSortFields(firstResource) fields.push( ...[ { name: 'name', title: this.$gettext('Name'), type: 'slot', width: 'expand', wrap: 'truncate' }, { name: 'manager', prop: 'spaceRoles', title: this.$gettext('Manager'), type: 'slot' }, { name: 'members', title: this.$gettext('Members'), prop: 'spaceRoles', type: 'slot' }, { name: 'totalQuota', prop: 'spaceQuota.total', title: this.$gettext('Total quota'), type: 'slot', sortable: true }, { name: 'usedQuota', prop: 'spaceQuota.used', title: this.$gettext('Used quota'), type: 'slot', sortable: true }, { name: 'remainingQuota', prop: 'spaceQuota.remaining', title: this.$gettext('Remaining quota'), type: 'slot', sortable: true }, { name: 'indicators', title: this.$gettext('Status'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink' }, { name: 'size', title: this.$gettext('Size'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink' }, { name: 'syncEnabled', title: this.$gettext('Status'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink' }, { name: 'status', prop: 'disabled', title: this.$gettext('Status'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink' }, this.hasTags ? { name: 'tags', title: this.$gettext('Tags'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink' } : {}, { name: 'sharedBy', title: this.$gettext('Shared by'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink' }, { name: 'sharedWith', title: this.$gettext('Shared with'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink' }, { name: 'mdate', title: this.$gettext('Modified'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink', accessibleLabelCallback: (item) => this.formatDateRelative(item.mdate) + ' (' + this.formatDate(item.mdate) + ')' }, { name: 'sdate', title: this.$gettext('Shared on'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink', accessibleLabelCallback: (item) => this.formatDateRelative(item.sdate) + ' (' + this.formatDate(item.sdate) + ')' }, { name: 'ddate', title: this.$gettext('Deleted'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink', accessibleLabelCallback: (item) => this.formatDateRelative(item.ddate) + ' (' + this.formatDate(item.ddate) + ')' } ] .filter((field) => { let hasField if (field.prop) { hasField = get(firstResource, field.prop) !== undefined } else { hasField = Object.prototype.hasOwnProperty.call(firstResource, field.name) } if (!this.fieldsDisplayed) { return hasField } return hasField && this.fieldsDisplayed.includes(field.name) }) .map((field) => { const sortField = sortFields.find((f) => f.name === field.name) if (sortField) { Object.assign(field, { sortable: sortField.sortable, sortDir: sortField.sortDir }) } return field }) ) if (this.hasActions) { fields.push({ name: 'actions', title: this.$gettext('Actions'), type: 'slot', alignH: 'right', wrap: 'nowrap', width: 'shrink' }) } return fields }, lazyLoading() { return this.configOptions.displayResourcesLazy }, areAllResourcesSelected() { return this.selectedResources.length === this.resources.length - this.disabledResources.length }, selectedResources() { return this.resources.filter((resource) => this.selectedIds.includes(resource.id)) }, allResourcesCheckboxLabel() { return this.$gettext('Select all resources') }, contextMenuLabel() { return this.$gettext('Show context menu') }, hoverableQuickActions() { return this.configOptions.hoverableQuickActions }, dragSelection() { const selection = [...this.selectedResources] selection.splice( selection.findIndex((i) => i.id === this.dragItem.id), 1 ) return selection } }, methods: { isResourceSelected(item) { return this.selectedIds.includes(item.id) }, isResourceCut(resource) { if (this.clipboardAction !== ClipboardActions.Cut) { return false } return this.clipboardResources.some((r) => r.id === resource.id) }, shouldDisplayThumbnails(item) { return this.areThumbnailsDisplayed && !isResourceTxtFileAlmostEmpty(item) }, getTagLink(tag: string) { const currentTerm = unref(this.$router.currentRoute).query?.term return createLocationCommon('files-common-search', { query: { provider: 'files.sdk', q_tags: tag, ...(currentTerm && { term: currentTerm }) } }) }, getTagComponentAttrs(tag) { if (!this.userContextReady) { return {} } return { to: this.getTagLink(tag) } }, isLatestSelectedItem(item: Resource) { return item.id === this.latestSelectedId }, hasRenameAction(item: Resource) { return this.renameActions.filter((menuItem) => menuItem.isVisible({ space: this.space, resources: [item] }) ).length }, openRenameDialog(item: Resource) { this.renameHandler({ space: this.getMatchingSpace(item), resources: [item] }) }, openTagsSidebar() { eventBus.publish(SideBarEventTopics.open) }, openSharingSidebar(file: Resource) { let panelToOpen if (file.type === 'space') { panelToOpen = 'space-share' } else { panelToOpen = 'sharing' } eventBus.publish(SideBarEventTopics.openWithPanel, panelToOpen) }, async fileDragged(file: Resource, event) { if (!this.dragDrop) { return } await this.setDragItem(file, event) this.addSelectedResource(file) }, fileDropped(selector: HTMLElement, event) { if (!this.dragDrop) { return } const hasFilePayload = (event.dataTransfer.types || []).some((e) => e === 'Files') if (hasFilePayload) { return } this.dragItem = null const dropTarget = event.target const dropTargetTr = dropTarget.closest('tr') const dropItemId = dropTargetTr.dataset.itemId this.dropRowStyling(selector, true, event) this.$emit(EVENT_FILE_DROPPED, dropItemId) }, async setDragItem(item: Resource, event) { this.dragItem = item await this.$nextTick() this.ghostElement.$el.ariaHidden = 'true' this.ghostElement.$el.style.left = '-99999px' this.ghostElement.$el.style.top = '-99999px' event.dataTransfer.setDragImage(this.ghostElement.$el, 0, 0) event.dataTransfer.dropEffect = 'move' event.dataTransfer.effectAllowed = 'move' }, dropRowStyling(selector: HTMLElement, leaving: boolean, event) { const hasFilePayload = (event.dataTransfer?.types || []).some((e) => e === 'Files') if (hasFilePayload) { return } if (event.currentTarget?.contains(event.relatedTarget)) { return } const classList = document.getElementsByClassName(`oc-tbody-tr-${selector}`)[0].classList const className = 'highlightedDropTarget' leaving ? classList.remove(className) : classList.add(className) }, sort(opts) { this.$emit('sort', opts) }, addSelectedResource(file: Resource) { const isSelected = this.isResourceSelected(file) if (isSelected) { return } this.toggleSelection(file.id) }, showContextMenuOnBtnClick(data, item) { if (this.isResourceDisabled(item)) { return false } const { dropdown, event } = data if (dropdown?.tippy === undefined) { return } if (!this.isResourceSelected(item)) { this.emitSelect([item.id]) } displayPositionedDropdown(dropdown.tippy, event, this.$refs.contextMenuButton) }, showContextMenu(row, event, item) { event.preventDefault() if (this.isResourceDisabled(item)) { return false } const instance = row.$el.getElementsByClassName('resource-table-btn-action-dropdown')[0] if (instance === undefined) { return } if (!this.isResourceSelected(item)) { this.emitSelect([item.id]) } displayPositionedDropdown(instance._tippy, event, this.$refs.contextMenuButton) }, rowMounted(resource, component) { /** * Triggered whenever a row is mounted * @property {object} resource The resource which was mounted as table row * @property {object} component The table row component */ this.$emit('rowMounted', resource, component, this.constants.ImageDimension.Thumbnail) }, fileClicked(data) { /** * Triggered when the file row is clicked * @property {object} resource The resource for which the event is triggered */ const resource = data[0] if (this.isResourceDisabled(resource)) { return } const eventData = data[1] const skipTargetSelection = data[2] ?? false const isCheckboxClicked = eventData?.target.getAttribute('type') === 'checkbox' const contextActionClicked = eventData?.target?.closest('div')?.id === 'oc-files-context-menu' if (contextActionClicked) { return } if (eventData && eventData.metaKey) { return eventBus.publish('app.files.list.clicked.meta', resource) } if (eventData && eventData.shiftKey) { return eventBus.publish('app.files.list.clicked.shift', { resource, skipTargetSelection }) } if (isCheckboxClicked) { return } return this.emitSelect([resource.id]) }, formatDate(date) { return formatDateFromJSDate(new Date(date), this.$language.current) }, formatDateRelative(date) { return formatRelativeDateFromJSDate(new Date(date), this.$language.current) }, setSelection(selected, resource: Resource) { if (selected) { this.emitSelect([...this.selectedIds, resource.id]) } else { this.emitSelect(this.selectedIds.filter((id) => id !== resource.id)) } }, emitSelect(selectedIds: string[]) { eventBus.publish('app.files.list.clicked') this.$emit('update:selectedIds', selectedIds) }, toggleSelectionAll() { if (this.areAllResourcesSelected) { return this.emitSelect([]) } this.emitSelect( this.resources .filter((resource) => !this.disabledResources.includes(resource.id)) .map((resource) => resource.id) ) }, emitFileClick(resource: Resource) { const space = this.getMatchingSpace(resource) /** * Triggered when a default action is triggered on a file * @property {object} resource resource for which the event is triggered */ this.$emit('fileClick', { space, resources: [resource] }) }, isResourceClickable(resource: Resource) { if (!this.areResourcesClickable) { return false } // TODO: remove as soon as unsynced shares are accessible if (isIncomingShareResource(resource) && !resource.syncEnabled) { return false } return !this.disabledResources.includes(resource.id) }, getResourceCheckboxLabel(resource: Resource) { if (resource.type === 'folder') { return this.$gettext('Select folder') } return this.$gettext('Select file') }, getSharedWithAvatarDescription(resource: Resource) { if (!isShareResource(resource)) { return } const resourceType = resource.type === 'folder' ? this.$gettext('folder') : this.$gettext('file') const shareCount = resource.sharedWith.filter(({ shareType }) => [ShareTypes.user.value, ShareTypes.link.value].includes(shareType) ).length const linkCount = resource.sharedWith.filter( ({ shareType }) => shareType === ShareTypes.link.value ).length const shareText = shareCount > 0 ? this.$ngettext( 'This %{ resourceType } is shared via %{ shareCount } invite', 'This %{ resourceType } is shared via %{ shareCount } invites', shareCount ) : '' const linkText = linkCount > 0 ? this.$ngettext( 'This %{ resourceType } is shared via %{ linkCount } link', 'This %{ resourceType } is shared via %{ linkCount } links', linkCount ) : '' const description = [shareText, linkText].join(' ') return this.$gettext(description, { resourceType, shareCount: shareCount.toString(), linkCount: linkCount.toString() }) }, getSharedByAvatarDescription(resource: Resource) { if (!isShareResource(resource)) { return '' } const resourceType = resource.type === 'folder' ? this.$gettext('folder') : this.$gettext('file') return this.$gettext('This %{ resourceType } is shared by %{ user }', { resourceType, user: resource.sharedBy.map(({ displayName }) => displayName).join(', ') }) }, getSharedByAvatarItems(resource: Resource) { if (!isShareResource(resource)) { return [] } return resource.sharedBy.map((s) => ({ displayName: s.displayName, name: s.displayName, shareType: ShareTypes.user.value, username: s.id })) }, getSharedWithAvatarItems(resource: Resource) { if (!isShareResource(resource)) { return [] } return resource.sharedWith.map((s) => ({ displayName: s.displayName, name: s.displayName, shareType: s.shareType, username: s.id })) } } }) </script> <style lang="scss"> .oc-table.condensed > tbody > tr { height: 0 !important; } .resource-table { &-resource-cut { opacity: 0.6; } &-resource-wrapper { display: flex; align-items: center; &-limit-max-width { max-width: calc(100% - var(--oc-space-medium)); } &:hover > .resource-table-edit-name { svg { fill: var(--oc-color-text-default); } } } &-tag { max-width: 80px; } &-tag-more { cursor: pointer; border: 0 !important; vertical-align: text-bottom; } &-edit-name { display: inline-flex; margin-left: var(--oc-space-xsmall); svg { fill: var(--oc-color-text-muted); } } &-people { position: absolute; right: var(--oc-space-xsmall); top: 50%; transform: translateY(-50%); } &-actions { align-items: center; display: flex; flex-flow: row nowrap; gap: var(--oc-space-xsmall); justify-content: flex-end; } &-select-all { align-items: center; display: flex; justify-content: center; } } .hoverable-quick-actions.files-table { @media (pointer: fine) { tr:not([class*='oc-table-highlighted']) { .resource-table-edit-name, .resource-table-actions div:first-child { visibility: hidden; } } tr:not([class*='oc-table-highlighted']):hover { .resource-table-edit-name, .resource-table-actions div:first-child { visibility: visible; } } } } .spaces-table { .oc-table-header-cell-mdate, .oc-table-data-cell-mdate, .oc-table-header-cell-manager, .oc-table-data-cell-manager, .oc-table-header-cell-remainingQuota, .oc-table-data-cell-remainingQuota { display: none; @media only screen and (min-width: 960px) { display: table-cell; } } .oc-table-header-cell-totalQuota, .oc-table-data-cell-totalQuota, .oc-table-header-cell-usedQuota, .oc-table-data-cell-usedQuota { display: none; @media only screen and (min-width: 1200px) { display: table-cell; } } &-squashed { /** * squashed = right sidebar is open. * same media queries as above but +440px width of the right sidebar * (because the right sidebar steals 440px from the file list) */ .oc-table-header-cell-status, .oc-table-data-cell-status, .oc-table-header-cell-manager, .oc-table-data-cell-manager, .oc-table-header-cell-totalQuota, .oc-table-data-cell-totalQuota, .oc-table-header-cell-usedQuota, .oc-table-data-cell-usedQuota { display: none; @media only screen and (min-width: 1400px) { display: table-cell; } } .oc-table-header-cell-mdate, .oc-table-data-cell-mdate, .oc-table-header-cell-remainingQuota, .oc-table-data-cell-remainingQuota, .oc-table-header-cell-mdate, .oc-table-data-cell-mdate { display: none; @media only screen and (min-width: 1600px) { display: table-cell; } } } } // Hide files table columns .files-table { .oc-table-header-cell-size, .oc-table-data-cell-size, .oc-table-header-cell-sharedWith, .oc-table-data-cell-sharedWith, .oc-table-header-cell-sharedBy, .oc-table-data-cell-sharedBy, .oc-table-header-cell-status, .oc-table-data-cell-status { display: none; @media only screen and (min-width: 640px) { display: table-cell; } } .oc-table-header-cell-mdate, .oc-table-data-cell-mdate, .oc-table-header-cell-sdate, .oc-table-data-cell-sdate, .oc-table-header-cell-ddate, .oc-table-data-cell-ddate { display: none; @media only screen and (min-width: 960px) { display: table-cell; } } .oc-table-header-cell-sharedBy, .oc-table-data-cell-sharedBy, .oc-table-header-cell-tags, .oc-table-data-cell-tags, .oc-table-header-cell-indicators, .oc-table-data-cell-indicators { display: none; @media only screen and (min-width: 1200px) { display: table-cell; } } &-squashed { /** * squashed = right sidebar is open. * same media queries as above but +440px width of the right sidebar * (because the right sidebar steals 440px from the file list) */ .oc-table-header-cell-size, .oc-table-data-cell-size, .oc-table-header-cell-sharedWith, .oc-table-data-cell-sharedWith, .oc-table-header-cell-sharedBy, .oc-table-data-cell-sharedBy, .oc-table-header-cell-status, .oc-table-data-cell-status { display: none; @media only screen and (min-width: 1080px) { display: table-cell; } } .oc-table-header-cell-mdate, .oc-table-data-cell-mdate, .oc-table-header-cell-sdate, .oc-table-data-cell-sdate, .oc-table-header-cell-ddate, .oc-table-data-cell-ddate { display: none; @media only screen and (min-width: 1400px) { display: table-cell; } } .oc-table-header-cell-sharedBy, .oc-table-data-cell-sharedBy, .oc-table-header-cell-tags, .oc-table-data-cell-tags, .oc-table-header-cell-indicators, .oc-table-data-cell-indicators { display: none; @media only screen and (min-width: 1640px) { display: table-cell; } } } } // shared with me: on tablets hide shared with column and display sharedBy column instead #files-shared-with-me-view .files-table .oc-table-header-cell-sharedBy, #files-shared-with-me-view .files-table .oc-table-data-cell-sharedBy { @media only screen and (min-width: 640px) { display: table-cell; } } #files-shared-with-me-view .files-table .oc-table-header-cell-sharedWith, #files-shared-with-me-view .files-table .oc-table-data-cell-sharedWith { @media only screen and (max-width: 1199px) { display: none; } } // Show tooltip on status indicators without handler .oc-table-data-cell-indicators { span.oc-status-indicators-indicator { pointer-events: all; } } </style>
owncloud/web/packages/web-pkg/src/components/FilesList/ResourceTable.vue/0
{ "file_path": "owncloud/web/packages/web-pkg/src/components/FilesList/ResourceTable.vue", "repo_id": "owncloud", "token_count": 17194 }
818
<template> <oc-pagination v-if="pages > 1" :pages="pages" :current-page="currentPage" :max-displayed="3" :current-route="$route" class="files-pagination oc-flex oc-flex-center oc-my-s" /> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ props: { pages: { type: Number, required: true }, currentPage: { type: Number, required: true } }, watch: { currentPage: { handler: function () { document.getElementsByClassName('files-view-wrapper')[0]?.scrollTo(0, 0) } } } }) </script>
owncloud/web/packages/web-pkg/src/components/Pagination.vue/0
{ "file_path": "owncloud/web/packages/web-pkg/src/components/Pagination.vue", "repo_id": "owncloud", "token_count": 281 }
819
<template> <div class="oc-mt-xl"> <div class="oc-flex space-info oc-text-center"> <oc-icon name="layout-grid" size="xxlarge" /> <p v-translate>Select a space to view details</p> </div> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ name: 'SpaceNoSelection' }) </script> <style lang="scss"> .space-info { align-items: center; flex-direction: column; } </style>
owncloud/web/packages/web-pkg/src/components/SideBar/Spaces/SpaceNoSelection.vue/0
{ "file_path": "owncloud/web/packages/web-pkg/src/components/SideBar/Spaces/SpaceNoSelection.vue", "repo_id": "owncloud", "token_count": 174 }
820
import { LinkShare, isIncomingShareResource } from '@ownclouders/web-client/src/helpers/share' import { computed, unref } from 'vue' import { useClientService } from '../../clientService' import { useGettext } from 'vue3-gettext' import { FileAction, FileActionOptions } from '../types' import { useCanShare } from '../../shares' import { useClipboard } from '../../clipboard' import { Resource, SpaceResource } from '@ownclouders/web-client' import { useFileActionsCreateLink } from './useFileActionsCreateLink' import { useMessages, useUserStore } from '../../piniaStores' import { buildLinkShare } from '@ownclouders/web-client/src/helpers/share/functionsNG' import { getGraphItemId } from '@ownclouders/web-client/src/helpers' export const useFileActionsCopyQuickLink = () => { const { showMessage, showErrorMessage } = useMessages() const language = useGettext() const { $gettext } = language const clientService = useClientService() const { canShare } = useCanShare() const { copyToClipboard } = useClipboard() const userStore = useUserStore() const onLinkCreatedCallback = async (result: PromiseSettledResult<LinkShare>[]) => { const link = result.find( (val): val is PromiseFulfilledResult<LinkShare> => val.status === 'fulfilled' ) if (link?.value) { await copyQuickLinkToClipboard(link.value.webUrl) } } const { actions: createLinkActions } = useFileActionsCreateLink({ onLinkCreatedCallback, showMessages: false }) const createQuicklinkAction = computed<FileAction>(() => unref(createLinkActions).find(({ name }) => name === 'create-quick-links') ) const copyQuickLinkToClipboard = async (url: string) => { try { await copyToClipboard(url) showMessage({ title: $gettext('The link has been copied to your clipboard.') }) } catch (e) { console.error(e) showErrorMessage({ title: $gettext('Copy link failed'), errors: [e] }) } } const getExistingQuickLink = async ({ space, resource }: { space: SpaceResource resource: Resource }): Promise<LinkShare> => { const client = clientService.graphAuthenticated const { data } = await client.permissions.listPermissions(space.id, getGraphItemId(resource)) const permissions = data.value || [] const graphPermission = permissions.find((p) => p.link?.['@libre.graph.quickLink']) return graphPermission ? buildLinkShare({ graphPermission, user: userStore.user, resourceId: resource.id }) : null } const handler = async ({ space, resources }: FileActionOptions) => { const [resource] = resources const existingQuickLink = await getExistingQuickLink({ space, resource }) if (existingQuickLink) { return copyQuickLinkToClipboard(existingQuickLink.webUrl) } return unref(createQuicklinkAction).handler({ space, resources }) } const actions = computed((): FileAction[] => [ { name: 'copy-quicklink', icon: 'link', label: () => $gettext('Copy link'), handler, isVisible: ({ space, resources }) => { if (resources.length !== 1) { return false } if (isIncomingShareResource(resources[0]) && !resources[0].syncEnabled) { return false } return canShare({ space, resource: resources[0] }) }, componentType: 'button', class: 'oc-files-actions-copy-quicklink-trigger' } ]) return { actions } }
owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsCopyQuicklink.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsCopyQuicklink.ts", "repo_id": "owncloud", "token_count": 1222 }
821
import { isLocationCommonActive, isLocationPublicActive, isLocationSpacesActive } from '../../../router' import { computed, unref } from 'vue' import { useGettext } from 'vue3-gettext' import { useGetMatchingSpace } from '../../spaces' import { useClientService } from '../../clientService' import { useLoadingService } from '../../loadingService' import { useRouter } from '../../router' import { FileAction, FileActionOptions } from '../types' import { Resource, SpaceResource } from '@ownclouders/web-client' import { useClipboardStore, useResourcesStore } from '../../piniaStores' import { ClipboardActions, ResourceTransfer, TransferType } from '../../../helpers' import { storeToRefs } from 'pinia' export const useFileActionsPaste = () => { const router = useRouter() const clientService = useClientService() const loadingService = useLoadingService() const { getMatchingSpace } = useGetMatchingSpace() const { $gettext, $ngettext } = useGettext() const clipboardStore = useClipboardStore() const resourcesStore = useResourcesStore() const { currentFolder } = storeToRefs(resourcesStore) const isMacOs = computed(() => { return window.navigator.platform.match('Mac') }) const pasteShortcutString = computed(() => { if (unref(isMacOs)) { return $gettext('⌘ + V') } return $gettext('Ctrl + V') }) const pasteSelectedFiles = ({ targetSpace, sourceSpace, resources }: { targetSpace: SpaceResource sourceSpace: SpaceResource resources: Resource[] }) => { const copyMove = new ResourceTransfer( sourceSpace, resources, targetSpace, unref(currentFolder), currentFolder, clientService, loadingService, $gettext, $ngettext ) let movedResourcesPromise: Promise<Resource[]> if (clipboardStore.action === ClipboardActions.Cut) { movedResourcesPromise = copyMove.perform(TransferType.MOVE) } if (clipboardStore.action === ClipboardActions.Copy) { movedResourcesPromise = copyMove.perform(TransferType.COPY) } return movedResourcesPromise.then((movedResources) => { const loadingResources = [] const fetchedResources: Resource[] = [] for (const resource of movedResources) { loadingResources.push( (async () => { const movedResource = await clientService.webdav.getFileInfo(targetSpace, resource) fetchedResources.push(movedResource) })() ) } return Promise.all(loadingResources).then(() => { resourcesStore.upsertResources(fetchedResources) resourcesStore.loadIndicators(unref(currentFolder).path) }) }) } const handler = async ({ space: targetSpace }: FileActionOptions) => { const resourceSpaceMapping: Record<string, { space: SpaceResource; resources: Resource[] }> = clipboardStore.resources.reduce((acc, resource) => { if (resource.storageId in acc) { acc[resource.storageId].resources.push(resource) return acc } const matchingSpace = getMatchingSpace(resource) if (!(matchingSpace.id in acc)) { acc[matchingSpace.id] = { space: matchingSpace, resources: [] } } acc[matchingSpace.id].resources.push(resource) return acc }, {}) const promises = Object.values(resourceSpaceMapping).map( ({ space: sourceSpace, resources: resourcesToCopy }) => { return pasteSelectedFiles({ targetSpace, sourceSpace, resources: resourcesToCopy }) } ) await Promise.all(promises) clipboardStore.clearClipboard() } const actions = computed((): FileAction[] => [ { name: 'paste', icon: 'clipboard', handler, label: () => $gettext('Paste'), shortcut: unref(pasteShortcutString), isVisible: ({ resources }) => { if (clipboardStore.resources.length === 0) { return false } if ( !isLocationSpacesActive(router, 'files-spaces-generic') && !isLocationPublicActive(router, 'files-public-link') && !isLocationCommonActive(router, 'files-common-favorites') ) { return false } if (resources.length === 0) { return false } if (isLocationPublicActive(router, 'files-public-link') && unref(currentFolder)) { return unref(currentFolder).canCreate() } // copy can't be restricted in authenticated context, because // a user always has their home dir with write access return true }, componentType: 'button', class: 'oc-files-actions-copy-trigger' } ]) return { actions } }
owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsPaste.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/actions/files/useFileActionsPaste.ts", "repo_id": "owncloud", "token_count": 1768 }
822
import { SpaceResource } from '@ownclouders/web-client' import { computed, unref } from 'vue' import { SpaceAction, SpaceActionOptions } from '../types' import { useGettext } from 'vue3-gettext' import { useRoute, useRouter } from '../../router' import { useAbility } from '../../ability' import { useClientService } from '../../clientService' import { isProjectSpaceResource } from '@ownclouders/web-client/src/helpers' import { useMessages, useModals, useSpacesStore, useUserStore } from '../../piniaStores' export const useSpaceActionsDisable = () => { const { showMessage, showErrorMessage } = useMessages() const userStore = useUserStore() const { $gettext, $ngettext } = useGettext() const ability = useAbility() const clientService = useClientService() const route = useRoute() const router = useRouter() const { dispatchModal } = useModals() const spacesStore = useSpacesStore() const filterResourcesToDisable = (resources: SpaceResource[]): SpaceResource[] => { return resources.filter( (r) => isProjectSpaceResource(r) && r.canDisable({ user: userStore.user, ability }) ) } const disableSpaces = async (spaces: SpaceResource[]) => { const currentRoute = unref(route) const client = clientService.graphAuthenticated const promises = spaces.map((space) => client.drives.disableDrive(space.id.toString()).then(() => { if (currentRoute.name === 'files-spaces-generic') { router.push({ name: 'files-spaces-projects' }) } if (currentRoute.name === 'admin-settings-spaces') { space.disabled = true space.spaceQuota = { total: space.spaceQuota.total } } spacesStore.updateSpaceField({ id: space.id, field: 'disabled', value: true }) return true }) ) const results = await Promise.allSettled(promises) const succeeded = results.filter((r) => r.status === 'fulfilled') if (succeeded.length) { const title = succeeded.length === 1 && spaces.length === 1 ? $gettext('Space "%{space}" was disabled successfully', { space: spaces[0].name }) : $ngettext( '%{spaceCount} space was disabled successfully', '%{spaceCount} spaces were disabled successfully', succeeded.length, { spaceCount: succeeded.length.toString() }, true ) showMessage({ title }) } const failed = results.filter((r) => r.status === 'rejected') if (failed.length) { failed.forEach(console.error) const title = failed.length === 1 && spaces.length === 1 ? $gettext('Failed to disable space "%{space}"', { space: spaces[0].name }) : $ngettext( 'Failed to disable %{spaceCount} space', 'Failed to disable %{spaceCount} spaces', failed.length, { spaceCount: failed.length.toString() }, true ) showErrorMessage({ title, errors: (failed as PromiseRejectedResult[]).map((f) => f.reason) }) } } const handler = ({ resources }: SpaceActionOptions) => { const allowedResources = filterResourcesToDisable(resources) if (!allowedResources.length) { return } const message = $ngettext( 'If you disable the selected space, it can no longer be accessed. Only Space managers will still have access. Note: No files will be deleted from the server.', 'If you disable the %{count} selected spaces, they can no longer be accessed. Only Space managers will still have access. Note: No files will be deleted from the server.', allowedResources.length, { count: allowedResources.length.toString() } ) const confirmText = $gettext('Disable') dispatchModal({ title: $ngettext( 'Disable Space "%{space}"?', 'Disable %{spaceCount} Spaces?', allowedResources.length, { space: allowedResources[0].name, spaceCount: allowedResources.length.toString() } ), confirmText, message, hasInput: false, onConfirm: () => disableSpaces(allowedResources) }) } const actions = computed((): SpaceAction[] => [ { name: 'disable', icon: 'stop-circle', label: () => $gettext('Disable'), handler, isVisible: ({ resources }) => { return !!filterResourcesToDisable(resources).length }, componentType: 'button', class: 'oc-files-actions-disable-trigger' } ]) return { actions, // HACK: exported for unit tests: disableSpaces } }
owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsDisable.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/actions/spaces/useSpaceActionsDisable.ts", "repo_id": "owncloud", "token_count": 1763 }
823
import { computed, Ref } from 'vue' import type { AppConfigObject } from '../../apps' import { AppsStore } from '../piniaStores' export interface AppConfigOptions { appsStore: AppsStore applicationId: string } export interface AppConfigResult { applicationConfig: Ref<AppConfigObject> } export function useAppConfig(options: AppConfigOptions): AppConfigResult { const applicationConfig = computed( () => options.appsStore.externalAppConfig[options.applicationId] || {} ) return { applicationConfig } }
owncloud/web/packages/web-pkg/src/composables/appDefaults/useAppConfig.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/appDefaults/useAppConfig.ts", "repo_id": "owncloud", "token_count": 150 }
824
import { ClientService } from '../../services' import { useService } from '../service' export const useClientService = (): ClientService => { return useService('$clientService') }
owncloud/web/packages/web-pkg/src/composables/clientService/useClientService.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/clientService/useClientService.ts", "repo_id": "owncloud", "token_count": 49 }
825
export * from './useFolderLink'
owncloud/web/packages/web-pkg/src/composables/folderLink/index.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/folderLink/index.ts", "repo_id": "owncloud", "token_count": 10 }
826
import { useService } from '../service' import { PasswordPolicyService } from '../../services/passwordPolicy' export const usePasswordPolicyService = (): PasswordPolicyService => { return useService('$passwordPolicyService') }
owncloud/web/packages/web-pkg/src/composables/passwordPolicyService/usePasswordPolicyService.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/passwordPolicyService/usePasswordPolicyService.ts", "repo_id": "owncloud", "token_count": 56 }
827
import { defineStore } from 'pinia' import { computed, ref, unref } from 'vue' import { Graph, SpaceResource } from '@ownclouders/web-client' import { GraphShareRoleIdMap, buildSpace, extractStorageId, getGraphItemId, isPersonalSpaceResource, isProjectSpaceResource } from '@ownclouders/web-client/src/helpers' import type { CollaboratorShare } from '@ownclouders/web-client/src/helpers' import { useUserStore } from './user' import { ConfigStore, useConfigStore } from './config' import { buildCollaboratorShare } from '@ownclouders/web-client/src/helpers/share/functionsNG' import { useSharesStore } from './shares' export const sortSpaceMembers = (shares: CollaboratorShare[]) => { const sortedManagers = shares .filter((share) => share.role.id === GraphShareRoleIdMap.SpaceManager) .sort((a, b) => a.sharedWith.displayName.localeCompare(b.sharedWith.displayName)) const sortedRest = shares .filter((share) => share.role.id !== GraphShareRoleIdMap.SpaceManager) .sort((a, b) => a.sharedWith.displayName.localeCompare(b.sharedWith.displayName)) return [...sortedManagers, ...sortedRest] } export const getSpacesByType = async ({ graphClient, driveType, configStore }: { graphClient: Graph driveType: string configStore: ConfigStore }) => { const graphResponse = await graphClient.drives.listMyDrives( 'name asc', `driveType eq ${driveType}` ) if (!graphResponse.data) { return [] } const mountpoints = graphResponse.data.value.map((space) => buildSpace({ ...space, serverUrl: configStore.serverUrl }) ) if (driveType !== 'mountpoint' || !configStore.options.routing?.fullShareOwnerPaths) { return mountpoints } const rootSpaceDriveAliasMapping: Record<string, string> = {} graphResponse.data.value.forEach((space) => { const { rootId, driveAlias } = space.root.remoteItem rootSpaceDriveAliasMapping[rootId] = driveAlias }) const rootSpaces = Object.entries(rootSpaceDriveAliasMapping).map(([id, driveAlias]) => // FIXME: create proper buildRootSpace (or whatever function) buildSpace({ id: extractStorageId(id), name: driveAlias, // FIXME: set a proper name driveType: driveAlias.split('/')[0], // FIXME: can we retrieve this from api? driveAlias, path: '/', serverUrl: configStore.serverUrl }) ) return [...mountpoints, ...rootSpaces] } export const useSpacesStore = defineStore('spaces', () => { const userStore = useUserStore() const configStore = useConfigStore() const sharesStore = useSharesStore() const spaces = ref<SpaceResource[]>([]) const spaceMembers = ref<CollaboratorShare[]>([]) const currentSpace = ref<SpaceResource>() const spacesInitialized = ref(false) const mountPointsInitialized = ref(false) const spacesLoading = ref(false) const personalSpace = computed(() => { return unref(spaces).find((s) => isPersonalSpaceResource(s) && s.isOwner(userStore.user)) }) const setSpacesInitialized = (value: boolean) => { spacesInitialized.value = value } const setMountPointsInitialized = (value: boolean) => { mountPointsInitialized.value = value } const setSpacesLoading = (value: boolean) => { spacesLoading.value = value } const setCurrentSpace = (space: SpaceResource) => { currentSpace.value = space } const setSpaceMembers = (members: CollaboratorShare[]) => { spaceMembers.value = members } const addSpaces = (s: SpaceResource[]) => { unref(spaces).push(...s) } const removeSpace = (space: SpaceResource) => { spaces.value = unref(spaces).filter(({ id }) => id !== space.id) } const upsertSpace = (space: SpaceResource) => { const existingSpace = unref(spaces).find(({ id }) => id === space.id) if (existingSpace) { Object.assign(existingSpace, space) return } addSpaces([space]) } const updateSpaceField = <T extends SpaceResource, K extends keyof SpaceResource>({ id, field, value }: { id: T['id'] field: K value: T[K] }) => { const space = unref(spaces).find((space) => id === space.id) if (space) { space[field] = value } } const loadSpaces = async ({ graphClient }: { graphClient: Graph }) => { spacesLoading.value = true try { /** * FIXME: this is bad for two reasons: * 1. fetching by specific drive type is bad because if more drive types are being added it needs additional code. * as soon as the backend allows to filter by `driveType neq virtual` we want to use that here. * 2. fetching the mountpoint drives only on first access is kind of error prone, because mount points are * trying to be accessed in multiple code locations. all of them need to check now if mountpoints need to be * fetched first. but at the moment fetching mountpoints is kind of expensive, so we need to accept that for now. */ const [personalSpaces, projectSpaces] = await Promise.all([ getSpacesByType({ graphClient, driveType: 'personal', configStore }), getSpacesByType({ graphClient, driveType: 'project', configStore }) ]) addSpaces([...personalSpaces, ...projectSpaces]) spacesInitialized.value = true } finally { spacesLoading.value = false } } const loadMountPoints = async ({ graphClient }: { graphClient: Graph }) => { // fetching mount points is particularly expensive, so we do that only on first access. if (unref(mountPointsInitialized)) { return } try { const mountPointSpaces = await getSpacesByType({ graphClient, driveType: 'mountpoint', configStore }) addSpaces(mountPointSpaces) } finally { mountPointsInitialized.value = true } } const reloadProjectSpaces = async ({ graphClient }: { graphClient: Graph }) => { const projectSpaces = await getSpacesByType({ graphClient, driveType: 'project', configStore }) spaces.value = unref(spaces).filter((s) => !isProjectSpaceResource(s)) addSpaces(projectSpaces) } const loadSpaceMembers = async ({ graphClient, space }: { graphClient: Graph space: SpaceResource }) => { spaceMembers.value = [] const spaceShares: CollaboratorShare[] = [] const { data } = await graphClient.permissions.listPermissions(space.id, getGraphItemId(space)) const permissions = data.value || [] permissions.forEach((graphPermission) => { if (!graphPermission.link) { spaceShares.push( buildCollaboratorShare({ graphPermission, graphRoles: sharesStore.graphRoles, resourceId: space.id, spaceId: space.id, user: userStore.user }) ) } }) spaceMembers.value = sortSpaceMembers(spaceShares) } const upsertSpaceMember = ({ member }: { member: CollaboratorShare }) => { const existingMember = unref(spaceMembers).find(({ id }) => id === member.id) if (existingMember) { Object.assign(existingMember, member) return } unref(spaceMembers).push(member) } const removeSpaceMember = ({ member }: { member: CollaboratorShare }) => { const existingMember = unref(spaceMembers).find(({ id }) => id === member.id) spaceMembers.value = unref(spaceMembers).filter(({ id }) => existingMember.id !== id) } return { spaces, spacesInitialized, mountPointsInitialized, spacesLoading, spaceMembers, currentSpace, personalSpace, setSpacesInitialized, setMountPointsInitialized, setSpacesLoading, setCurrentSpace, setSpaceMembers, addSpaces, removeSpace, upsertSpace, updateSpaceField, loadSpaces, loadMountPoints, reloadProjectSpaces, loadSpaceMembers, upsertSpaceMember, removeSpaceMember } }) export type SpacesStore = ReturnType<typeof useSpacesStore>
owncloud/web/packages/web-pkg/src/composables/piniaStores/spaces.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/piniaStores/spaces.ts", "repo_id": "owncloud", "token_count": 2758 }
828
import { Ref } from 'vue' import { useRouter } from './useRouter' import { RouteLocationNormalizedLoaded } from 'vue-router' export const useRoute = (): Ref<RouteLocationNormalizedLoaded> => { return useRouter().currentRoute }
owncloud/web/packages/web-pkg/src/composables/router/useRoute.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/router/useRoute.ts", "repo_id": "owncloud", "token_count": 73 }
829
export * from './useCanShare'
owncloud/web/packages/web-pkg/src/composables/shares/index.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/shares/index.ts", "repo_id": "owncloud", "token_count": 10 }
830
import { onMounted, ref, unref } from 'vue' export const useTileSize = () => { const themeVarToPixels = (value: string) => { if (!value.endsWith('rem') && !value.endsWith('px')) { return 0 } if (value.endsWith('rem')) { const rem = parseInt(value.replace('rem', '').trim()) const fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize) return rem * fontSize } return parseInt(value.replace('px', '').trim()) } const baseSizePixels = ref(0) const stepSizePixels = ref(0) onMounted(() => { const styles = getComputedStyle(document.documentElement) baseSizePixels.value = themeVarToPixels(styles.getPropertyValue('--oc-size-tiles-default')) stepSizePixels.value = themeVarToPixels(styles.getPropertyValue('--oc-size-tiles-resize-step')) }) const calculateTileSizePixels = (viewSize: number) => { return unref(baseSizePixels) + (viewSize - 1) * unref(stepSizePixels) } const calculateTileSizeRem = (viewSize: number) => { const fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize) return calculateTileSizePixels(viewSize) / fontSize } return { calculateTileSizePixels, calculateTileSizeRem } }
owncloud/web/packages/web-pkg/src/composables/viewMode/useTileSize.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/composables/viewMode/useTileSize.ts", "repo_id": "owncloud", "token_count": 443 }
831
export const defaultFuseOptions = { ignoreLocation: true, threshold: 0, useExtendedSearch: true }
owncloud/web/packages/web-pkg/src/helpers/fuse.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/helpers/fuse.ts", "repo_id": "owncloud", "token_count": 32 }
832
import { Router } from 'vue-router' export const buildUrl = (router: Router, pathname) => { const base = document.querySelector('base') const isHistoryMode = !!base const baseUrl = new URL(window.location.href.split('#')[0]) baseUrl.search = '' if (isHistoryMode) { // in history mode we can't determine the base path, it must be provided by the document baseUrl.pathname = new URL(base.href).pathname } else { // in hash mode, auto-determine the base path by removing `/index.html` if (baseUrl.pathname.endsWith('/index.html')) { baseUrl.pathname = baseUrl.pathname.split('/').slice(0, -1).filter(Boolean).join('/') } } /** * build full url by either * - concatenating baseUrl and pathname (for unknown/non-router urls, e.g. `oidc-callback.html`) or * - resolving via router (for known routes) */ if (/\.(html?)$/i.test(pathname)) { baseUrl.pathname = [...baseUrl.pathname.split('/'), ...pathname.split('/')] .filter(Boolean) .join('/') } else { baseUrl[isHistoryMode ? 'pathname' : 'hash'] = router.resolve(pathname).href } return baseUrl.href }
owncloud/web/packages/web-pkg/src/helpers/router/buildUrl.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/helpers/router/buildUrl.ts", "repo_id": "owncloud", "token_count": 417 }
833
import { RouteComponents } from './router' import { RouteLocationNamedRaw, RouteRecordRaw } from 'vue-router' import { createLocation, $gettext, isLocationActiveDirector } from './utils' type commonTypes = 'files-common-favorites' | 'files-common-search' export const createLocationCommon = (name: commonTypes, location = {}): RouteLocationNamedRaw => createLocation(name, location) export const locationFavorites = createLocationCommon('files-common-favorites') export const locationSearch = createLocationCommon('files-common-search') export const isLocationCommonActive = isLocationActiveDirector<commonTypes>( locationFavorites, locationSearch ) export const buildRoutes = (components: RouteComponents): RouteRecordRaw[] => [ { path: '/search', component: components.App, children: [ { name: locationSearch.name, path: 'list/:page?', component: components.SearchResults, meta: { authContext: 'user', title: $gettext('Search results'), contextQueryItems: [ 'term', 'provider', 'q_tags', 'q_lastModified', 'q_titleOnly', 'q_mediaType', 'scope', 'useScope' ] } } ] }, { path: '/favorites', component: components.App, children: [ { name: locationFavorites.name, path: '', component: components.Favorites, meta: { authContext: 'user', title: $gettext('Favorite files') } } ] } ]
owncloud/web/packages/web-pkg/src/router/common.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/router/common.ts", "repo_id": "owncloud", "token_count": 668 }
834
import * as uuid from 'uuid' import { eventBus } from './eventBus' import { debounce } from 'lodash-es' export enum LoadingEventTopics { add = 'loading-service.add', remove = 'loading-service.remove', setProgress = 'loading-service.set-progress' } export interface LoadingTaskState { total: number current: number } export interface LoadingTask { id: string active: boolean state?: LoadingTaskState } export interface LoadingTaskCallbackArguments { setProgress: (args: LoadingTaskState) => void } // time until a loading task is being set active const DEFAULT_DEBOUNCE_TIME = 200 export class LoadingService { private tasks: LoadingTask[] = [] public get isLoading(): boolean { return this.tasks.some((e) => e.active) } /** * Get the current progress from 0 to 100. * Returns null if at least one task is indeterminate. */ public get currentProgress(): number | null { if (this.tasks.some((e) => !e.state && e.active)) { return null } const tasks = this.tasks.filter((e) => !!e.state && e.active) if (!tasks.length) { return null } const progress = tasks.reduce((acc, task) => { acc += task.state.current / task.state.total return acc }, 0) return Math.round((progress / tasks.length) * 100) } public addTask<T>( callback: ({ setProgress }: LoadingTaskCallbackArguments) => Promise<T>, { debounceTime = DEFAULT_DEBOUNCE_TIME, indeterminate = true }: { debounceTime?: number; indeterminate?: boolean } = {} ): Promise<T> { const task = { id: uuid.v4(), active: false, ...(!indeterminate && { state: { total: 0, current: 0 } }) } this.tasks.push(task) const debounced = debounce(() => { task.active = true eventBus.publish(LoadingEventTopics.add) }, debounceTime) debounced() const setProgress = ({ total, current }: LoadingTaskState) => { if (!indeterminate) { this.setProgress({ task, total, current }) } } return callback({ setProgress }).finally(() => { this.removeTask(task.id) }) } private removeTask(id: string): void { this.tasks = this.tasks.filter((e) => e.id !== id) eventBus.publish(LoadingEventTopics.remove) } private setProgress({ task, total, current }): void { if (!task.state) { task.state = { total: 0, current: 0 } } task.state.total = total task.state.current = current eventBus.publish(LoadingEventTopics.setProgress) } }
owncloud/web/packages/web-pkg/src/services/loadingService.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/services/loadingService.ts", "repo_id": "owncloud", "token_count": 923 }
835
import isPlainObject from 'lodash-es/isPlainObject' export const objectKeys = (obj: Record<string, unknown>): string[] => { const paths = [] const walk = (o, p = '') => Object.keys(o).forEach((key) => { if (isPlainObject(o[key])) { walk(o[key], `${p}${key}.`) } else { paths.push(`${p}${key}`) } }) walk(obj) return paths }
owncloud/web/packages/web-pkg/src/utils/objectKeys.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/src/utils/objectKeys.ts", "repo_id": "owncloud", "token_count": 172 }
836
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`ContextMenuQuickAction component > renders component 1`] = ` "<button type="button" aria-label="Show context menu" 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="context-menu-trigger-1"> <!--v-if--> <!-- @slot Content of the button --> <span class="oc-icon oc-icon-m oc-icon-passive"><!----></span> <div id="context-menu-drop-1" class="oc-drop oc-box-shadow-medium oc-rounded oc-overflow-hidden"> <div class="oc-card oc-card-body oc-background-secondary oc-p-s"></div> </div> </button>" `;
owncloud/web/packages/web-pkg/tests/unit/components/ContextActions/__snapshots__/ContextMenuQuickAction.spec.ts.snap/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/ContextActions/__snapshots__/ContextMenuQuickAction.spec.ts.snap", "repo_id": "owncloud", "token_count": 246 }
837
import ItemFilterInline from '../../../../src/components/Filters/ItemFilterInline.vue' import { InlineFilterOption } from '../../../../src/components/Filters/types' import { defaultComponentMocks, defaultPlugins, mount, PartialComponentProps } from 'web-test-helpers' import { queryItemAsString } from '../../../../src/composables/appDefaults' import { mock } from 'vitest-mock-extended' import { unref } from 'vue' vi.mock('../../../../src/composables/appDefaults', () => ({ appDefaults: vi.fn(), queryItemAsString: vi.fn() })) const selectors = { filterOption: '.item-inline-filter-option', filterOptionLabel: '.item-inline-filter-option-label', selectedOptionLabel: '.item-inline-filter-option-selected .item-inline-filter-option-label' } describe('ItemFilterInline', () => { const filterOptions = [ mock<InlineFilterOption>({ name: 'filter1', label: 'filter1' }), mock<InlineFilterOption>({ name: 'filter2', label: 'filter2' }) ] it('renders all given options', () => { const { wrapper } = getWrapper({ props: { filterOptions } }) expect(wrapper.findAll(selectors.filterOption).length).toBe(filterOptions.length) expect(wrapper.findAll(selectors.filterOption).at(0).text()).toEqual(filterOptions[0].label) expect(wrapper.findAll(selectors.filterOption).at(1).text()).toEqual(filterOptions[1].label) }) it('emits the "toggleFilter"-event on click on an option', async () => { const { wrapper } = getWrapper({ props: { filterOptions } }) await wrapper.find(selectors.filterOption).trigger('click') expect(wrapper.emitted('toggleFilter').length).toBeGreaterThan(0) }) describe('route query', () => { it('sets the active option as query param', async () => { const { wrapper, mocks } = getWrapper({ props: { filterOptions } }) const currentRouteQuery = unref(mocks.$router.currentRoute).query expect(mocks.$router.push).not.toHaveBeenCalled() await wrapper.find(selectors.filterOption).trigger('click') expect(currentRouteQuery[wrapper.vm.queryParam]).toBeDefined() expect(mocks.$router.push).toHaveBeenCalled() }) it('sets the active optin initially when given via query param', async () => { const initialQuery = filterOptions[1].name const { wrapper } = getWrapper({ initialQuery, props: { filterOptions } }) await wrapper.vm.$nextTick() expect(wrapper.find(selectors.selectedOptionLabel).text()).toEqual(initialQuery) }) }) }) function getWrapper({ props = {}, initialQuery = '' }: { props?: PartialComponentProps<typeof ItemFilterInline> initialQuery?: string } = {}) { vi.mocked(queryItemAsString).mockImplementation(() => initialQuery) const mocks = defaultComponentMocks() return { mocks, wrapper: mount(ItemFilterInline, { props: { filterName: 'InlineFilter', filterOptions: [], ...props }, global: { plugins: [...defaultPlugins()], mocks, provide: mocks } }) } }
owncloud/web/packages/web-pkg/tests/unit/components/Filters/ItemFilterInline.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/Filters/ItemFilterInline.spec.ts", "repo_id": "owncloud", "token_count": 1074 }
838
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`ItemFilter > can use a custom attribute as display name 1`] = ` "<div class="item-filter oc-flex item-filter-users"> <div class="oc-filter-chip oc-flex"><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 oc-filter-chip-button oc-pill" id="oc-filter-chip-3"> <!--v-if--> <!-- @slot Content of the button --> <span class="oc-icon oc-icon-s oc-icon-passive oc-filter-check-icon-inactive"><!----></span> <span class="oc-text-truncate oc-filter-chip-label">Users</span> <!--v-if--> <span class="oc-icon oc-icon-s oc-icon-passive"><!----></span> </button> <div id="oc-drop-4" class="oc-drop oc-box-shadow-medium oc-rounded oc-filter-chip-drop"> <div class="oc-card oc-card-body oc-background-secondary oc-p-s"> <!--v-if--> <div> <ul class="oc-list oc-my-rm oc-mx-rm item-filter-list"> <li class="oc-my-xs"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-space-between oc-button-gap-m oc-button-passive oc-button-passive-raw item-filter-list-item oc-flex oc-flex-middle oc-width-1-1 oc-p-xs oc-flex-between" data-test-value="Albert Einstein"> <!--v-if--> <!-- @slot Content of the button --> <div class="oc-flex oc-flex-middle oc-text-truncate"> <!--v-if--> <div></div> <div class="oc-text-truncate oc-ml-s">Albert Einstein</div> </div> <div class="oc-flex"> <!--v-if--> </div> </button></li> <li class="oc-my-xs"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-space-between oc-button-gap-m oc-button-passive oc-button-passive-raw item-filter-list-item oc-flex oc-flex-middle oc-width-1-1 oc-p-xs oc-flex-between" data-test-value="Marie Curie"> <!--v-if--> <!-- @slot Content of the button --> <div class="oc-flex oc-flex-middle oc-text-truncate"> <!--v-if--> <div></div> <div class="oc-text-truncate oc-ml-s">Marie Curie</div> </div> <div class="oc-flex"> <!--v-if--> </div> </button></li> </ul> </div> </div> </div> <!--v-if--> </div> </div>" `; exports[`ItemFilter > renders all items 1`] = ` "<div class="item-filter oc-flex item-filter-users"> <div class="oc-filter-chip oc-flex"><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 oc-filter-chip-button oc-pill" id="oc-filter-chip-1"> <!--v-if--> <!-- @slot Content of the button --> <span class="oc-icon oc-icon-s oc-icon-passive oc-filter-check-icon-inactive"><!----></span> <span class="oc-text-truncate oc-filter-chip-label">Users</span> <!--v-if--> <span class="oc-icon oc-icon-s oc-icon-passive"><!----></span> </button> <div id="oc-drop-2" class="oc-drop oc-box-shadow-medium oc-rounded oc-filter-chip-drop"> <div class="oc-card oc-card-body oc-background-secondary oc-p-s"> <!--v-if--> <div> <ul class="oc-list oc-my-rm oc-mx-rm item-filter-list"> <li class="oc-my-xs"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-space-between oc-button-gap-m oc-button-passive oc-button-passive-raw item-filter-list-item oc-flex oc-flex-middle oc-width-1-1 oc-p-xs oc-flex-between" data-test-value="Albert Einstein"> <!--v-if--> <!-- @slot Content of the button --> <div class="oc-flex oc-flex-middle oc-text-truncate"> <!--v-if--> <div></div> <div class="oc-text-truncate oc-ml-s">Albert Einstein</div> </div> <div class="oc-flex"> <!--v-if--> </div> </button></li> <li class="oc-my-xs"><button type="button" class="oc-button oc-rounded oc-button-m oc-button-justify-content-space-between oc-button-gap-m oc-button-passive oc-button-passive-raw item-filter-list-item oc-flex oc-flex-middle oc-width-1-1 oc-p-xs oc-flex-between" data-test-value="Marie Curie"> <!--v-if--> <!-- @slot Content of the button --> <div class="oc-flex oc-flex-middle oc-text-truncate"> <!--v-if--> <div></div> <div class="oc-text-truncate oc-ml-s">Marie Curie</div> </div> <div class="oc-flex"> <!--v-if--> </div> </button></li> </ul> </div> </div> </div> <!--v-if--> </div> </div>" `;
owncloud/web/packages/web-pkg/tests/unit/components/__snapshots__/ItemFilter.spec.ts.snap/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/components/__snapshots__/ItemFilter.spec.ts.snap", "repo_id": "owncloud", "token_count": 2536 }
839
import { mock } from 'vitest-mock-extended' import { nextTick, unref } from 'vue' import { useFileActionsCreateNewFolder } from '../../../../../src/composables/actions' import { useMessages, useModals, useResourcesStore } from '../../../../../src/composables/piniaStores' import { SpaceResource } from '@ownclouders/web-client/src' import { FolderResource, Resource } from '@ownclouders/web-client/src/helpers' import { RouteLocation, defaultComponentMocks, getComposableWrapper } from 'web-test-helpers/src' import { useScrollToMock } from '../../../../mocks/useScrollToMock' import { useScrollTo } from '../../../../../src/composables/scrollTo' vi.mock('../../../../../src/composables/scrollTo') describe('useFileActionsCreateNewFolder', () => { describe('checkFolderName', () => { it.each([ { input: '', output: 'Folder name cannot be empty' }, { input: '/', output: 'Folder name cannot contain "/"' }, { input: '.', output: 'Folder name cannot be equal to "."' }, { input: '..', output: 'Folder name cannot be equal to ".."' }, { input: 'myfolder', output: null } ])('should validate folder name %s', (data) => { const space = mock<SpaceResource>({ id: '1' }) getWrapper({ space, setup: ({ checkNewFolderName }) => { checkNewFolderName(data.input, (str: string) => { expect(str).toBe(data.output) }) } }) }) }) describe('addNewFolder', () => { it('create new folder', () => { const space = mock<SpaceResource>({ id: '1' }) getWrapper({ space, setup: async ({ addNewFolder }) => { await addNewFolder('myfolder') await nextTick() const { upsertResource } = useResourcesStore() expect(upsertResource).toHaveBeenCalled() const { showMessage } = useMessages() expect(showMessage).toHaveBeenCalledWith({ title: '"myfolder" was created successfully' }) // expect scrolltoresource to have been called } }) }) it('show error message if createFolder fails', () => { const consoleErrorMock = vi.spyOn(console, 'error').mockReturnThis() const space = mock<SpaceResource>({ id: '1' }) getWrapper({ resolveCreateFolder: false, space, setup: async ({ addNewFolder }) => { await addNewFolder('myfolder') await nextTick() const { showErrorMessage } = useMessages() expect(showErrorMessage).toHaveBeenCalledWith( expect.objectContaining({ title: 'Failed to create folder' }) ) consoleErrorMock.mockRestore() } }) }) }) describe('createNewFolderModal', () => { it('should show modal', () => { const space = mock<SpaceResource>({ id: '1' }) getWrapper({ space, setup: ({ actions }) => { const { dispatchModal } = useModals() unref(actions)[0].handler() expect(dispatchModal).toHaveBeenCalled() } }) }) }) }) function getWrapper({ resolveCreateFolder = true, space = undefined, setup }: { resolveCreateFolder?: boolean space?: SpaceResource setup: (instance: ReturnType<typeof useFileActionsCreateNewFolder>) => void }) { vi.mocked(useScrollTo).mockImplementation(() => useScrollToMock()) const mocks = { ...defaultComponentMocks({ currentRoute: mock<RouteLocation>({ name: 'files-spaces-generic' }) }), space } mocks.$clientService.webdav.createFolder.mockImplementation(() => { if (resolveCreateFolder) { return Promise.resolve({ id: '1', type: 'folder', isReceivedShare: vi.fn(), path: '/' } as FolderResource) } return Promise.reject('error') }) const currentFolder = mock<Resource>({ id: '1', path: '/' }) return { wrapper: getComposableWrapper( () => { const instance = useFileActionsCreateNewFolder({ space }) setup(instance) }, { mocks, provide: mocks, pluginOptions: { piniaOptions: { resourcesStore: { currentFolder } } } } ) } }
owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCreateNewFolder.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsCreateNewFolder.spec.ts", "repo_id": "owncloud", "token_count": 1718 }
840
import { useSpaceActionsEditDescription } from '../../../../../src/composables/actions' import { useMessages, useModals } from '../../../../../src/composables/piniaStores' import { defaultComponentMocks, mockAxiosResolve, RouteLocation, getComposableWrapper } from 'web-test-helpers' import { mock } from 'vitest-mock-extended' import { unref } from 'vue' import { SpaceResource } from '@ownclouders/web-client/src' describe('editDescription', () => { describe('handler', () => { it('should trigger the editDescription 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 editDescription modal window with no resource', () => { getWrapper({ setup: async ({ actions }) => { const { dispatchModal } = useModals() await unref(actions)[0].handler({ resources: [] }) expect(dispatchModal).toHaveBeenCalledTimes(0) } }) }) }) describe('method "editDescriptionSpace"', () => { it('should show message on success', () => { getWrapper({ setup: async ({ editDescriptionSpace }, { clientService }) => { clientService.graphAuthenticated.drives.updateDrive.mockResolvedValue(mockAxiosResolve()) await editDescriptionSpace(mock<SpaceResource>(), 'doesntmatter') const { showMessage } = useMessages() expect(showMessage).toHaveBeenCalledTimes(1) } }) }) it('should show message on error', () => { vi.spyOn(console, 'error').mockImplementation(() => undefined) getWrapper({ setup: async ({ editDescriptionSpace }, { clientService }) => { clientService.graphAuthenticated.drives.updateDrive.mockRejectedValue(new Error()) await editDescriptionSpace(mock<SpaceResource>(), 'doesntmatter') const { showErrorMessage } = useMessages() expect(showErrorMessage).toHaveBeenCalledTimes(1) } }) }) }) }) function getWrapper({ setup }: { setup: ( instance: ReturnType<typeof useSpaceActionsEditDescription>, { clientService }: { clientService: ReturnType<typeof defaultComponentMocks>['$clientService'] } ) => void }) { const mocks = defaultComponentMocks({ currentRoute: mock<RouteLocation>({ name: 'files-spaces-projects' }) }) return { mocks, wrapper: getComposableWrapper( () => { const instance = useSpaceActionsEditDescription() setup(instance, { clientService: mocks.$clientService }) }, { mocks, provide: mocks } ) } }
owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsEditDescription.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/spaces/useSpaceActionsEditDescription.spec.ts", "repo_id": "owncloud", "token_count": 1111 }
841
import { unref } from 'vue' import { useLinkTypes } from '../../../../src/composables/links/useLinkTypes' import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers' import { SharingLinkType } from '@ownclouders/web-client/src/generated' import { AbilityRule } from '@ownclouders/web-client/src/helpers' import { Capabilities } from '@ownclouders/web-client/src/ocs' import { PasswordEnforcedForCapability } from '@ownclouders/web-client/src/ocs/capabilities' describe('useLinkTypes', () => { it('should be valid', () => { expect(useLinkTypes).toBeDefined() }) describe('computed "defaultLinkType"', () => { it('is internal if user can not create public links', () => { getWrapper({ abilities: [], setup: ({ defaultLinkType }) => { expect(unref(defaultLinkType)).toBe(SharingLinkType.Internal) } }) }) it('is viewer if user can create public links and no default permissions are given', () => { getWrapper({ abilities: [{ action: 'create-all', subject: 'PublicLink' }], setup: ({ defaultLinkType }) => { expect(unref(defaultLinkType)).toBe(SharingLinkType.View) } }) }) it('is viewer if default permissions are 1', () => { getWrapper({ abilities: [{ action: 'create-all', subject: 'PublicLink' }], defaultPermissions: 1, setup: ({ defaultLinkType }) => { expect(unref(defaultLinkType)).toBe(SharingLinkType.View) } }) }) it('is internasl if default permissions are 0', () => { getWrapper({ abilities: [{ action: 'create-all', subject: 'PublicLink' }], defaultPermissions: 0, setup: ({ defaultLinkType }) => { expect(unref(defaultLinkType)).toBe(SharingLinkType.Internal) } }) }) }) describe('method "getAvailableLinkTypes"', () => { it('only returns the internal type if user can not create public links', () => { getWrapper({ abilities: [], setup: ({ getAvailableLinkTypes }) => { expect(getAvailableLinkTypes({ isFolder: true })).toEqual([SharingLinkType.Internal]) } }) }) it('returns all available types for folders accordingly', () => { getWrapper({ abilities: [{ action: 'create-all', subject: 'PublicLink' }], setup: ({ getAvailableLinkTypes }) => { expect(getAvailableLinkTypes({ isFolder: true })).toEqual([ SharingLinkType.Internal, SharingLinkType.View, SharingLinkType.Upload, SharingLinkType.Edit, SharingLinkType.CreateOnly ]) } }) }) it('returns all available types for files accordingly', () => { getWrapper({ abilities: [{ action: 'create-all', subject: 'PublicLink' }], setup: ({ getAvailableLinkTypes }) => { expect(getAvailableLinkTypes({ isFolder: false })).toEqual([ SharingLinkType.Internal, SharingLinkType.View, SharingLinkType.Edit ]) } }) }) }) describe('method "getLinkRoleByType"', () => { it.each([ SharingLinkType.Internal, SharingLinkType.View, SharingLinkType.Upload, SharingLinkType.Edit, SharingLinkType.CreateOnly ])('returns the link role by id', (type) => { getWrapper({ setup: ({ getLinkRoleByType, linkShareRoles }) => { expect(getLinkRoleByType(type)).toEqual(linkShareRoles.find(({ id }) => id === type)) } }) }) }) describe('method "isPasswordEnforcedForLinkType"', () => { it('returns true for view type if set via capabilities', () => { getWrapper({ passwordEnforcedFor: { read_only: true }, setup: ({ isPasswordEnforcedForLinkType }) => { expect(isPasswordEnforcedForLinkType(SharingLinkType.View)).toBeTruthy() } }) }) it('returns true for upload type if set via capabilities', () => { getWrapper({ passwordEnforcedFor: { upload_only: true }, setup: ({ isPasswordEnforcedForLinkType }) => { expect(isPasswordEnforcedForLinkType(SharingLinkType.Upload)).toBeTruthy() } }) }) it('returns true for create only type if set via capabilities', () => { getWrapper({ passwordEnforcedFor: { read_write: true }, setup: ({ isPasswordEnforcedForLinkType }) => { expect(isPasswordEnforcedForLinkType(SharingLinkType.CreateOnly)).toBeTruthy() } }) }) it('returns true for edit type if set via capabilities', () => { getWrapper({ passwordEnforcedFor: { read_write_delete: true }, setup: ({ isPasswordEnforcedForLinkType }) => { expect(isPasswordEnforcedForLinkType(SharingLinkType.Edit)).toBeTruthy() } }) }) }) }) function getWrapper({ setup, abilities = [], defaultPermissions = undefined, passwordEnforcedFor = undefined }: { setup: (instance: ReturnType<typeof useLinkTypes>) => void abilities?: AbilityRule[] defaultPermissions?: number passwordEnforcedFor?: PasswordEnforcedForCapability }) { const mocks = defaultComponentMocks() const capabilities = { files_sharing: { public: { default_permissions: defaultPermissions, password: { enforced_for: passwordEnforcedFor } } } } satisfies Partial<Capabilities['capabilities']> return { wrapper: getComposableWrapper( () => { const instance = useLinkTypes() setup(instance) }, { mocks, pluginOptions: { abilities, piniaOptions: { capabilityState: { capabilities } } } } ) } }
owncloud/web/packages/web-pkg/tests/unit/composables/links/useLinkTypes.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/links/useLinkTypes.spec.ts", "repo_id": "owncloud", "token_count": 2291 }
842
import { RouteLocation } from 'web-test-helpers/src' import { breadcrumbsFromPath, concatBreadcrumbs } from '../../../src/helpers/breadcrumbs' describe('builds an array of breadcrumbitems', () => { it('from a path', () => { const breadCrumbs = breadcrumbsFromPath( { path: '/files/spaces/personal/home/test' } as RouteLocation, '/test' ) expect(breadCrumbs).toEqual([ { id: expect.anything(), isStaticNav: false, allowContextActions: true, text: 'test', to: { path: '/files/spaces/personal/home/test', query: {} } } ]) }) it('from an array of breadcrumbitems', () => { const initialBreadCrumbs = [{ text: 'Foo' }, { text: 'Bar' }] const breadCrumbsFromPath = breadcrumbsFromPath( { path: '/app/foo/bar?all=500' } as RouteLocation, '/bar' ) const result = concatBreadcrumbs(...initialBreadCrumbs, ...breadCrumbsFromPath) expect(result[0]).toMatchObject({ text: 'Foo' }) expect(result[1]).toMatchObject({ text: 'Bar' }) }) })
owncloud/web/packages/web-pkg/tests/unit/helpers/breadcrumbs.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/breadcrumbs.spec.ts", "repo_id": "owncloud", "token_count": 432 }
843
import { HttpClient } from '../../../src/http' import { z } from 'zod' import { mock, mockDeep } from 'vitest-mock-extended' import axios, { AxiosInstance } from 'axios' const schema = z.object({ someProperty: z.string() }) type Schema = z.infer<typeof schema> describe('HttpClient', () => { const mockAxios = mockDeep<AxiosInstance>() vi.spyOn(axios, 'create').mockReturnValue(mockAxios) test('types', async () => { const fn = vi.fn().mockReturnValue({ data: {} }) const client = mock<HttpClient>({ delete: fn, get: fn, head: fn, options: fn, patch: fn, post: fn, put: fn, request: fn }) // delete { const { data: untypedResponse } = await client.delete('/foo') untypedResponse.property const { data: typedResponse } = await client.delete<Schema>('/foo') typedResponse.someProperty const { data: schemaResponse } = await client.delete('/foo', null, { schema }) schemaResponse.someProperty } // get { const { data: untypedResponse } = await client.get('/foo') // @ts-expect-error untypedResponse is unknown, so we cannot access a property without casting untypedResponse.property const { data: typedResponse } = await client.get<Schema>('/foo') typedResponse.someProperty const { data: schemaResponse } = await client.get('/foo', { schema }) schemaResponse.someProperty } // head { const { data: untypedResponse } = await client.head('/foo') untypedResponse.property const { data: typedResponse } = await client.head<Schema>('/foo') typedResponse.someProperty const { data: schemaResponse } = await client.head('/foo', { schema }) schemaResponse.someProperty } // options { const { data: untypedResponse } = await client.options('/foo') untypedResponse.property const { data: typedResponse } = await client.options<Schema>('/foo') typedResponse.someProperty const { data: schemaResponse } = await client.options('/foo', { schema }) schemaResponse.someProperty } // patch { const { data: untypedResponse } = await client.patch('/foo') untypedResponse.property const { data: typedResponse } = await client.patch<Schema>('/foo') typedResponse.someProperty const { data: schemaResponse } = await client.patch('/foo', null, { schema }) schemaResponse.someProperty } // post { const { data: untypedResponse } = await client.post('/foo') untypedResponse.property const { data: typedResponse } = await client.post<Schema>('/foo') typedResponse.someProperty const { data: schemaResponse } = await client.post('/foo', null, { schema }) schemaResponse.someProperty } // put { const { data: untypedResponse } = await client.put('/foo') untypedResponse.property const { data: typedResponse } = await client.put<Schema>('/foo') typedResponse.someProperty const { data: schemaResponse } = await client.put('/foo', null, { schema }) schemaResponse.someProperty } // request { const { data: untypedResponse } = await client.request({ url: '/foo' }) untypedResponse.property const { data: typedResponse } = await client.request<Schema>({ url: '/foo' }) typedResponse.someProperty const { data: schemaResponse } = await client.request({ url: '/foo', schema }) schemaResponse.someProperty } expect(true).toBe(true) }) test.each(['delete', 'get', 'head', 'options', 'patch', 'post', 'put'])('%s', (m) => { const client = new HttpClient() client[m]('url') mockAxios[m].mockResolvedValue({ data: undefined }) expect(mockAxios[m]).toHaveBeenCalledTimes(1) }) test('request', () => { const client = new HttpClient() client.request({ method: 'get' }) mockAxios.get.mockResolvedValue({ data: undefined }) expect(mockAxios.request).toHaveBeenCalledTimes(1) }) })
owncloud/web/packages/web-pkg/tests/unit/http/client.spec.ts/0
{ "file_path": "owncloud/web/packages/web-pkg/tests/unit/http/client.spec.ts", "repo_id": "owncloud", "token_count": 1522 }
844
# On OSX the PATH variable isn't exported unless "SHELL" is also set, see: http://stackoverflow.com/a/25506676 SHELL = /bin/bash NODE_MODULES = ../node_modules NODE_BINDIR = $(NODE_MODULES)/.bin export PATH := $(NODE_BINDIR):$(PATH) # Where to find apps (it can be multiple paths). APPS = $(shell find ../.. -maxdepth 1 -name 'web-app-*') ../../design-system ../../web-client ../../web-pkg # Where to find core folder CORE = .. # List of all files to extract INPUT_FILES = $(CORE) $(APPS) # Where to write the files generated by this makefile. OUTPUT_DIR = . # Core Template file TEMPLATE_FILE = ./template.pot # Available locales for the app. LOCALES = bg cs de es fr it nl ko sq sv tr zh # Name of the generated .po files for each available locale. LOCALE_FILES ?= $(foreach app,$(APPS),$(patsubst %,$(app)/l10n/locale/%/LC_MESSAGES/app.po,$(LOCALES))) $(patsubst %,./locale/%/LC_MESSAGES/app.po,$(LOCALES)) .PHONY: clean clean: rm -f $(foreach app,$(APPS),$(app)/l10n/template.pot); rm -f $(TEMPLATE_FILE); rm -rf $(foreach app,$(APPS),$(app)/l10n/locale); rm -rf locale; .PHONY: extract extract: $(TEMPLATE_FILE) # Create a main .pot template, then generate .po files for each available language. # Thanks to Systematic: https://github.com/Polyconseil/systematic/blob/866d5a/mk/main.mk#L167-L183 $(TEMPLATE_FILE): # Extract gettext strings from each apps templates files and create a POT dictionary template. # Generate .po files for each available language. @for app in $(INPUT_FILES); \ do \ if [ $$app = '../src' ]; then \ export OUT_DIR=.; \ else \ export OUT_DIR=$$app/l10n; \ fi; \ mkdir -p $$OUT_DIR; \ export GETTEXT_APP_SOURCES=`find $$app/src -name '*.vue' -o -name '*.js' -o -name '*.ts'`; \ node $(NODE_MODULES)/easygettext/src/extract-cli.js --attribute v-translate --output $$OUT_DIR/template.pot $$GETTEXT_APP_SOURCES; \ done; .PHONY: translations translations: $(OUTPUT_DIR)/translations.json # Generate translations.json file from all available apps .pot templates. .PHONY: $(OUTPUT_DIR)/translations.json $(OUTPUT_DIR)/translations.json: @for app in $(INPUT_FILES); \ do \ if [ $$app = '../src' ]; then \ export OUT_DIR=.; \ else \ export OUT_DIR=$$app/l10n; \ fi; \ mkdir -p $$OUT_DIR; \ gettext-compile --output $$OUT_DIR/translations.json $(patsubst %,$$OUT_DIR/locale/%/LC_MESSAGES/app.po,$(LOCALES)); \ done; \ .PHONY: push push: @for app in $(INPUT_FILES); \ do \ if [ $$app = '../src' ]; then \ export OUT_DIR=.; \ else \ export OUT_DIR=$$app/l10n; \ fi; \ cd $$OUT_DIR; \ tx push -s; \ done; \ .PHONY: pull pull: @for app in $(INPUT_FILES); \ do \ if [ $$app = '../src' ]; then \ export OUT_DIR=.; \ else \ export OUT_DIR=$$app/l10n; \ fi; \ cd $$OUT_DIR; \ tx pull -a; \ done; \
owncloud/web/packages/web-runtime/l10n/Makefile/0
{ "file_path": "owncloud/web/packages/web-runtime/l10n/Makefile", "repo_id": "owncloud", "token_count": 1169 }
845
<template> <oc-button id="oc-notifications-bell" v-oc-tooltip="notificationsLabel" appearance="raw-inverse" variation="brand" :aria-label="notificationsLabel" > <oc-icon class="oc-cursor-pointer oc-flex oc-flex-middle" name="notification-3" fill-type="line" /> <span v-if="notificationCount" :key="notificationCount" :class="{ shake: animate, badge: true }" v-text="notificationCountLabel" /> </oc-button> </template> <script lang="ts"> import { computed } from 'vue' import { useGettext } from 'vue3-gettext' import { ref } from 'vue' import { watch } from 'vue' export default { props: { notificationCount: { type: Number, default: 0 } }, setup(props) { const { $gettext } = useGettext() const animate = ref(false) const notificationsLabel = computed(() => $gettext('Notifications')) const notificationCountLabel = computed(() => { if (props.notificationCount > 99) { return '99+' } return `${props.notificationCount}` }) watch( () => props.notificationCount, () => { animate.value = true setTimeout(() => { animate.value = false }, 600) } ) return { animate, notificationsLabel, notificationCountLabel } } } </script> <style lang="scss" scoped> #oc-notifications-bell { position: relative; .badge { position: absolute; top: -6px; right: -9px; padding: var(--oc-space-xsmall); line-height: var(--oc-space-small); -webkit-border-radius: 30px; -moz-border-radius: 30px; border-radius: 30px; min-width: var(--oc-space-small); height: var(--oc-space-small); text-align: center; font-weight: 300; font-size: 11px; background: rgb(249, 54, 54); color: white; box-shadow: 0px 0px 2px 1px rgba(0, 0, 0, 0.5); } } .shake { animation: shake 0.6s cubic-bezier(0.46, 0.27, 0.59, 0.97) both; transform: translate3d(0, 0, 0); } @keyframes shake { 10%, 20%, 50%, 60% { transform: translate3d(-1px, 0, 0); } 30%, 40%, 70%, 80% { transform: translate3d(1px, 0, 0); } } </style>
owncloud/web/packages/web-runtime/src/components/Topbar/NotificationBell.vue/0
{ "file_path": "owncloud/web/packages/web-runtime/src/components/Topbar/NotificationBell.vue", "repo_id": "owncloud", "token_count": 977 }
846
import { registerClient } from '../services/clientRegistration' import { buildApplication, NextApplication } from './application' import { RouteLocationRaw, Router, RouteRecordNormalized } from 'vue-router' import { App, computed, watch } from 'vue' import { loadTheme } from '../helpers/theme' import { createGettext, GetTextOptions, Language } from 'vue3-gettext' import { getBackendVersion, getWebVersion } from './versions' import { useModals, useThemeStore, useUserStore, UserStore, useMessages, useSpacesStore, useAuthStore, AuthStore, useCapabilityStore, CapabilityStore, useExtensionRegistry, ExtensionRegistry, useAppsStore, AppsStore, useConfigStore, ConfigStore, RawConfig, useSharesStore, useResourcesStore, ResourcesStore, SpacesStore, MessageStore } from '@ownclouders/web-pkg' import { authService } from '../services/auth' import { ClientService, LoadingService, PasswordPolicyService, PreviewService, UppyService } from '@ownclouders/web-pkg' import { init as sentryInit } from '@sentry/vue' import { webdav } from '@ownclouders/web-client/src/webdav' import { v4 as uuidV4 } from 'uuid' import { merge } from 'lodash-es' import { AppConfigObject, resourceIconMappingInjectionKey, ResourceIconMapping } from '@ownclouders/web-pkg' import { MESSAGE_TYPE } from '@ownclouders/web-client/src/sse' import { getQueryParam } from '../helpers/url' import PQueue from 'p-queue' import { storeToRefs } from 'pinia' import { getExtensionNavItems } from '../helpers/navItems' import { RawConfigSchema, SentryConfig } from '@ownclouders/web-pkg/src/composables/piniaStores/config/types' import { onSSEFileLockingEvent, onSSEItemRenamedEvent, onSSEProcessingFinishedEvent, onSSEItemRestoredEvent, onSSEItemTrashedEvent } from './sse' const getEmbedConfigFromQuery = ( doesEmbedEnabledOptionExists: boolean ): RawConfig['options']['embed'] => { const config: RawConfig['options']['embed'] = {} if (!doesEmbedEnabledOptionExists) { config.enabled = getQueryParam('embed') === 'true' } // Can enable location picker in embed mode const embedTarget = getQueryParam('embed-target') if (embedTarget) { config.target = embedTarget } const delegateAuthentication = getQueryParam('embed-delegate-authentication') if (delegateAuthentication) { config.delegateAuthentication = delegateAuthentication === 'true' } const delegateAuthenticationOrigin = getQueryParam('embed-delegate-authentication-origin') if (delegateAuthentication) { config.delegateAuthenticationOrigin = delegateAuthenticationOrigin } return config } /** * fetch runtime configuration, this step is optional, all later steps can use a static * configuration object as well * * @remarks * does not check if the configuration is valid, for now be careful until a schema is declared * * @param path - path to main configuration */ export const announceConfiguration = async ({ path, configStore }: { path: string configStore: ConfigStore }) => { const request = await fetch(path, { headers: { 'X-Request-ID': uuidV4() } }) if (request.status !== 200) { throw new Error(`config could not be loaded. HTTP status-code ${request.status}`) } const data = await request.json().catch((error) => { throw new Error(`config could not be parsed. ${error}`) }) const rawConfig = RawConfigSchema.parse(data) const embedConfigFromQuery = getEmbedConfigFromQuery( rawConfig.options?.embed && Object.prototype.hasOwnProperty.call(rawConfig.options.embed, 'enabled') ) rawConfig.options = { ...rawConfig.options, embed: { ...rawConfig.options?.embed, ...embedConfigFromQuery } } configStore.loadConfig(rawConfig) } /** * announce auth client to the runtime, currently only openIdConnect is supported here * * @remarks * if config does not ship any options for openIdConnect this step get skipped * * @param configStore */ export const announceClient = async (configStore: ConfigStore): Promise<void> => { const openIdConnect = configStore.openIdConnect || {} if (!openIdConnect.dynamic) { return } const { client_id: clientId, client_secret: clientSecret } = await registerClient(openIdConnect) openIdConnect.client_id = clientId openIdConnect.client_secret = clientSecret } /** * announce applications to the runtime, it takes care that all requirements are fulfilled and then: * - bulk build all applications * - bulk register all applications, no other application is guaranteed to be registered here, don't request one * * @param app * @param configStore * @param store * @param router * @param translations * @param supportedLanguages */ export const initializeApplications = async ({ app, configStore, router, gettext, supportedLanguages }: { app: App configStore: ConfigStore router: Router gettext: Language supportedLanguages: { [key: string]: string } }): Promise<NextApplication[]> => { type RawApplication = { path?: string config?: AppConfigObject } const rawApplications: RawApplication[] = [ ...rewriteDeprecatedAppNames(configStore).map((application) => ({ path: `web-app-${application}` })), ...configStore.externalApps ] const applicationResults = await Promise.allSettled( rawApplications.map((rawApplication) => buildApplication({ app, applicationPath: rawApplication.path, applicationConfig: rawApplication.config, supportedLanguages, router, gettext, configStore }) ) ) const applications = applicationResults.reduce<NextApplication[]>((acc, applicationResult) => { // we don't want to fail hard with the full system when one specific application can't get loaded. only log the error. if (applicationResult.status !== 'fulfilled') { console.error(applicationResult.reason) } else { acc.push(applicationResult.value) } return acc }, []) await Promise.all(applications.map((application) => application.initialize())) return applications } /** * Bulk activate all applications, all applications are registered, it's safe to request a application api here * * @param applications */ export const announceApplicationsReady = async ({ app, appsStore, applications }: { app: App appsStore: AppsStore applications: NextApplication[] }): Promise<void> => { await Promise.all(applications.map((application) => application.ready())) const mapping: ResourceIconMapping = { mimeType: {}, extension: {} } appsStore.fileExtensions.forEach((editor) => { const meta = appsStore.apps[editor.app] const getIconDefinition = () => { return { name: meta.icon, ...(meta.iconFillType && { fillType: meta.iconFillType }), ...(meta.iconColor && { color: meta.iconColor }) } } if (editor.mimeType) { mapping.mimeType[editor.mimeType] = getIconDefinition() } if (editor.extension) { mapping.extension[editor.extension] = getIconDefinition() } }) app.provide(resourceIconMappingInjectionKey, mapping) } /** * Rewrites old names of renamed apps to their new name and prints a warning to adjust configuration to the respective new app name. * * @param {ConfigStore} configStore */ const rewriteDeprecatedAppNames = (configStore: ConfigStore) => { const appAliases = [ { name: 'preview', oldName: 'media-viewer' }, { name: 'text-editor', oldName: 'markdown-editor' } ] return configStore.apps.map((appName) => { const appAlias = appAliases.find((appAlias) => appAlias.oldName === appName) if (appAlias) { console.warn(`app "${appAlias.oldName}" has been renamed, use "${appAlias.name}" instead.`) return appAlias.name } return appName }) } /** * announce runtime theme to the runtime, this also takes care that the store * and designSystem has all needed information to render the customized ui * * @param themeLocation * @param vue * @param designSystem */ export const announceTheme = async ({ app, designSystem, configStore }: { app: App designSystem: any configStore: ConfigStore }): Promise<void> => { const themeStore = useThemeStore() const { initializeThemes } = themeStore const { currentTheme } = storeToRefs(themeStore) const webTheme = await loadTheme(configStore.theme) await initializeThemes(webTheme) app.use(designSystem, { tokens: currentTheme.value.designTokens }) } export const announcePiniaStores = () => { const appsStore = useAppsStore() const authStore = useAuthStore() const capabilityStore = useCapabilityStore() const extensionRegistry = useExtensionRegistry() const configStore = useConfigStore() const messagesStore = useMessages() const modalStore = useModals() const resourcesStore = useResourcesStore() const sharesStore = useSharesStore() const spacesStore = useSpacesStore() const userStore = useUserStore() return { appsStore, authStore, capabilityStore, extensionRegistry, configStore, resourcesStore, messagesStore, modalStore, sharesStore, spacesStore, userStore } } /** * announce runtime translations by injecting them into the getTextPlugin * * @param vue * @param options */ export const announceTranslations = ({ app, ...options }: { app: App } & Partial<GetTextOptions>): Language => { const gettext = createGettext({ defaultLanguage: navigator.language.substring(0, 2), silent: true, ...options }) app.use(gettext) return gettext } export const announceAdditionalTranslations = ({ gettext, translations }: { gettext: Language } & Pick<GetTextOptions, 'translations'>): void => { gettext.translations = merge(gettext.translations, translations) } /** * announce clientService and inject it into vue * * @param vue * @param configStore */ export const announceClientService = ({ app, configStore, userStore, authStore, capabilityStore }: { app: App configStore: ConfigStore userStore: UserStore authStore: AuthStore capabilityStore: CapabilityStore }): void => { const clientService = new ClientService({ configStore, language: app.config.globalProperties.$language, authStore, userStore }) app.config.globalProperties.$clientService = clientService app.config.globalProperties.$clientService.webdav = webdav({ accessToken: computed(() => authStore.accessToken), baseUrl: configStore.serverUrl, capabilities: computed(() => capabilityStore.capabilities), clientService: app.config.globalProperties.$clientService, language: computed(() => app.config.globalProperties.$language.current), user: computed(() => userStore.user) }) app.provide('$clientService', clientService) } /** * @param vue */ export const announceLoadingService = ({ app }: { app: App }): void => { const loadingService = new LoadingService() app.config.globalProperties.$loadingService = loadingService app.provide('$loadingService', loadingService) } /** * announce uppyService and inject it into vue * * @param vue */ export const announceUppyService = ({ app }: { app: App }): void => { app.config.globalProperties.$uppyService = new UppyService({ language: app.config.globalProperties.$language }) app.provide('$uppyService', app.config.globalProperties.$uppyService) } /** * @param vue * @param store * @param configStore */ export const announcePreviewService = ({ app, configStore, userStore, authStore, capabilityStore }: { app: App configStore: ConfigStore userStore: UserStore authStore: AuthStore capabilityStore: CapabilityStore }): void => { const clientService = app.config.globalProperties.$clientService const previewService = new PreviewService({ clientService, userStore, authStore, capabilityStore, configStore }) app.config.globalProperties.$previewService = previewService app.provide('$previewService', previewService) } /** * announce authService and inject it into vue * * @param vue * @param configStore * @param store * @param router */ export const announceAuthService = ({ app, configStore, router, userStore, authStore, capabilityStore }: { app: App configStore: ConfigStore router: Router userStore: UserStore authStore: AuthStore capabilityStore: CapabilityStore }): void => { const ability = app.config.globalProperties.$ability const language = app.config.globalProperties.$language const clientService = app.config.globalProperties.$clientService authService.initialize( configStore, clientService, router, ability, language, userStore, authStore, capabilityStore ) app.config.globalProperties.$authService = authService app.provide('$authService', authService) } /** * @param vue */ export const announcePasswordPolicyService = ({ app }: { app: App }): void => { const language = app.config.globalProperties.$language const passwordPolicyService = new PasswordPolicyService({ language }) app.config.globalProperties.passwordPolicyService = passwordPolicyService app.provide('$passwordPolicyService', passwordPolicyService) } /** * announce runtime defaults, this is usual the last needed announcement before rendering the actual ui * * @param vue * @param router */ export const announceDefaults = ({ appsStore, extensionRegistry, router, configStore }: { appsStore: AppsStore router: Router extensionRegistry: ExtensionRegistry configStore: ConfigStore }): void => { // set home route const appIds = appsStore.appIds let defaultExtensionId = configStore.options.defaultExtension if (!defaultExtensionId || appIds.indexOf(defaultExtensionId) < 0) { defaultExtensionId = appIds[0] } let route: RouteRecordNormalized | RouteLocationRaw = router.getRoutes().find((r) => { return r.path.startsWith(`/${defaultExtensionId}`) && r.meta?.entryPoint === true }) if (!route) { route = getExtensionNavItems({ extensionRegistry, appId: defaultExtensionId })[0]?.route } if (route) { router.addRoute({ path: '/', redirect: () => route }) } } /** * announce some version numbers * * @param capabilityStore */ export const announceVersions = ({ capabilityStore }: { capabilityStore: CapabilityStore }): void => { const versions = [getWebVersion(), getBackendVersion({ capabilityStore })].filter(Boolean) versions.forEach((version) => { console.log( `%c ${version} `, 'background-color: #041E42; color: #FFFFFF; font-weight: bold; border: 1px solid #FFFFFF; padding: 5px;' ) }) } /** * starts the sentry monitor * * @remarks * if config does not contain dsn sentry will not be started * * @param configStore * @param app */ export const startSentry = (configStore: ConfigStore, app: App): void => { if (configStore.sentry?.dsn) { const { dsn, environment = 'production', transportOptions, ...moreSentryOptions } = configStore.sentry sentryInit({ app, dsn, environment, attachProps: true, logErrors: true, transportOptions: transportOptions as SentryConfig['transportOptions'], ...moreSentryOptions }) } } /** * announceCustomScripts injects custom header scripts. * * @param configStore */ export const announceCustomScripts = ({ configStore }: { configStore?: ConfigStore }): void => { configStore.scripts.forEach(({ src = '', async = false }) => { if (!src) { return } const script = document.createElement('script') script.src = src script.async = async document.head.appendChild(script) }) } /** * announceCustomStyles injects custom header styles. * * @param configStore */ export const announceCustomStyles = ({ configStore }: { configStore?: ConfigStore }): void => { configStore.styles.forEach(({ href = '' }) => { if (!href) { return } const link = document.createElement('link') link.href = href link.type = 'text/css' link.rel = 'stylesheet' document.head.appendChild(link) }) } export const registerSSEEventListeners = ({ language, resourcesStore, spacesStore, messageStore, clientService, previewService, configStore, router }: { language: Language resourcesStore: ResourcesStore spacesStore: SpacesStore messageStore: MessageStore clientService: ClientService previewService: PreviewService configStore: ConfigStore router: Router }): void => { const resourceQueue = new PQueue({ concurrency: configStore.options.concurrentRequests.sse }) watch( () => resourcesStore.currentFolder, () => { resourceQueue.clear() } ) clientService.sseAuthenticated.addEventListener(MESSAGE_TYPE.ITEM_RENAMED, (msg) => onSSEItemRenamedEvent({ topic: MESSAGE_TYPE.ITEM_RENAMED, resourcesStore, spacesStore, msg, clientService, router }) ) clientService.sseAuthenticated.addEventListener(MESSAGE_TYPE.POSTPROCESSING_FINISHED, (msg) => onSSEProcessingFinishedEvent({ topic: MESSAGE_TYPE.POSTPROCESSING_FINISHED, resourcesStore, spacesStore, msg, clientService, previewService, resourceQueue }) ) clientService.sseAuthenticated.addEventListener(MESSAGE_TYPE.FILE_LOCKED, (msg) => onSSEFileLockingEvent({ topic: MESSAGE_TYPE.FILE_LOCKED, resourcesStore, spacesStore, msg, clientService }) ) clientService.sseAuthenticated.addEventListener(MESSAGE_TYPE.FILE_UNLOCKED, (msg) => onSSEFileLockingEvent({ topic: MESSAGE_TYPE.FILE_UNLOCKED, resourcesStore, spacesStore, msg, clientService }) ) clientService.sseAuthenticated.addEventListener(MESSAGE_TYPE.ITEM_TRASHED, (msg) => onSSEItemTrashedEvent({ topic: MESSAGE_TYPE.ITEM_TRASHED, language, resourcesStore, messageStore, msg }) ) clientService.sseAuthenticated.addEventListener(MESSAGE_TYPE.ITEM_RESTORED, (msg) => onSSEItemRestoredEvent({ topic: MESSAGE_TYPE.ITEM_RESTORED, resourcesStore, spacesStore, msg, clientService }) ) } export const setViewOptions = ({ resourcesStore }: { resourcesStore: ResourcesStore }) => { /** * Storage returns a string so we need to convert it into a boolean */ const areHiddenFilesShown = window.localStorage.getItem('oc_hiddenFilesShown') || 'false' const areHiddenFilesShownBoolean = areHiddenFilesShown === 'true' if (areHiddenFilesShownBoolean !== resourcesStore.areHiddenFilesShown) { resourcesStore.setAreHiddenFilesShown(areHiddenFilesShownBoolean) } const areFileExtensionsShown = window.localStorage.getItem('oc_fileExtensionsShown') || 'true' const areFileExtensionsShownBoolean = areFileExtensionsShown === 'true' if (areFileExtensionsShownBoolean !== resourcesStore.areFileExtensionsShown) { resourcesStore.setAreFileExtensionsShown(areFileExtensionsShownBoolean) } const areWebDavDetailsShown = window.localStorage.getItem('oc_webDavDetailsShown') || 'false' const areWebDavDetailsShownBoolean = areWebDavDetailsShown === 'true' if (areWebDavDetailsShownBoolean !== resourcesStore.areWebDavDetailsShown) { resourcesStore.setAreWebDavDetailsShown(areWebDavDetailsShownBoolean) } }
owncloud/web/packages/web-runtime/src/container/bootstrap.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/container/bootstrap.ts", "repo_id": "owncloud", "token_count": 6421 }
847
import { DesignSystem as designSystem, pages, translations, supportedLanguages } from './defaults' import { router } from './router' import { PortalTarget } from '@ownclouders/web-pkg' import { createHead } from '@vueuse/head' import { abilitiesPlugin } from '@casl/vue' import { createMongoAbility } from '@casl/ability' import merge from 'lodash-es/merge' import { announceConfiguration, initializeApplications, announceApplicationsReady, announceClient, announceDefaults, announceClientService, announceTheme, announcePiniaStores, announceCustomStyles, announceTranslations, announceVersions, announceUppyService, announceAuthService, startSentry, announceCustomScripts, announceLoadingService, announcePreviewService, announcePasswordPolicyService, announceAdditionalTranslations, registerSSEEventListeners, setViewOptions } from './container/bootstrap' import { applicationStore } from './container/store' import { buildPublicSpaceResource, isPersonalSpaceResource, isPublicSpaceResource, PublicSpaceResource } from '@ownclouders/web-client/src/helpers' import { loadCustomTranslations } from 'web-runtime/src/helpers/customTranslations' import { computed, createApp, watch } from 'vue' import PortalVue, { createWormhole } from 'portal-vue' import { createPinia } from 'pinia' import Avatar from './components/Avatar.vue' import focusMixin from './mixins/focusMixin' import { ArchiverService } from '@ownclouders/web-pkg' import { UnifiedRoleDefinition } from '@ownclouders/web-client/src/generated' export const bootstrapApp = async (configurationPath: string): Promise<void> => { const pinia = createPinia() const app = createApp(pages.success) app.use(pinia) const { appsStore, authStore, configStore, capabilityStore, extensionRegistry, spacesStore, userStore, resourcesStore, messagesStore, sharesStore } = announcePiniaStores() app.provide('$router', router) await announceConfiguration({ path: configurationPath, configStore }) startSentry(configStore, app) app.use(abilitiesPlugin, createMongoAbility([]), { useGlobalProperties: true }) const gettext = announceTranslations({ app, availableLanguages: supportedLanguages, translations }) announceUppyService({ app }) announceClientService({ app, configStore, userStore, authStore, capabilityStore }) // TODO: move to announceArchiverService function app.config.globalProperties.$archiverService = new ArchiverService( app.config.globalProperties.$clientService, configStore.serverUrl, computed( () => capabilityStore.filesArchivers || [ { enabled: true, version: '1.0.0', formats: ['tar', 'zip'], archiver_url: `${configStore.serverUrl}index.php/apps/files/ajax/download.php` } ] ) ) app.provide('$archiverService', app.config.globalProperties.$archiverService) announceLoadingService({ app }) announcePreviewService({ app, configStore, userStore, authStore, capabilityStore }) announcePasswordPolicyService({ app }) await announceClient(configStore) app.config.globalProperties.$wormhole = createWormhole() app.use(PortalVue, { wormhole: app.config.globalProperties.$wormhole, // do not register portal-target component so we can register our own wrapper portalTargetName: false }) app.component('PortalTarget', PortalTarget) const applicationsPromise = initializeApplications({ app, configStore, supportedLanguages, router, gettext }) const customTranslationsPromise = loadCustomTranslations({ configStore }) const themePromise = announceTheme({ app, designSystem, configStore }) const [customTranslations] = await Promise.all([ customTranslationsPromise, applicationsPromise, themePromise ]) announceAdditionalTranslations({ gettext, translations: merge(customTranslations) }) announceAuthService({ app, configStore, router, userStore, authStore, capabilityStore }) announceCustomStyles({ configStore }) announceCustomScripts({ configStore }) announceDefaults({ appsStore, router, extensionRegistry, configStore }) app.use(router) app.use(createHead()) app.component('AvatarImage', Avatar) app.mixin(focusMixin) app.mount('#owncloud') setViewOptions({ resourcesStore }) const applications = Array.from(applicationStore.values()) applications.forEach((application) => application.mounted(app)) watch( () => authStore.userContextReady || authStore.idpContextReady || authStore.publicLinkContextReady, async (newValue, oldValue) => { if (!newValue || newValue === oldValue) { return } announceVersions({ capabilityStore }) await announceApplicationsReady({ app, appsStore, applications }) }, { immediate: true } ) watch( () => authStore.userContextReady, async (userContextReady) => { if (!userContextReady) { return } const clientService = app.config.globalProperties.$clientService const previewService = app.config.globalProperties.$previewService const passwordPolicyService = app.config.globalProperties.passwordPolicyService passwordPolicyService.initialize(capabilityStore) // Register SSE event listeners if (capabilityStore.supportSSE) { registerSSEEventListeners({ language: gettext, resourcesStore, spacesStore, messageStore: messagesStore, clientService, previewService, configStore, router }) } // Load spaces to make them available across the application await spacesStore.loadSpaces({ graphClient: clientService.graphAuthenticated }) const personalSpace = spacesStore.spaces.find(isPersonalSpaceResource) if (!personalSpace) { return } spacesStore.updateSpaceField({ id: personalSpace.id, field: 'name', value: app.config.globalProperties.$gettext('Personal') }) // load sharing roles from graph API const { data } = await clientService.graphAuthenticated.roleManagement.listPermissionRoleDefinitions() // FIXME: graph type is wrong sharesStore.setGraphRoles(data as UnifiedRoleDefinition[]) }, { immediate: true } ) watch( () => authStore.publicLinkContextReady, (publicLinkContextReady) => { if (!publicLinkContextReady) { return } // Create virtual space for public link const publicLinkToken = authStore.publicLinkToken const publicLinkPassword = authStore.publicLinkPassword const publicLinkType = authStore.publicLinkType const space = buildPublicSpaceResource({ id: publicLinkToken, name: app.config.globalProperties.$gettext('Public files'), ...(publicLinkPassword && { publicLinkPassword }), serverUrl: configStore.serverUrl, publicLinkType: publicLinkType }) spacesStore.addSpaces([space]) spacesStore.setSpacesInitialized(true) }, { immediate: true } ) watch( // only needed if a public link gets re-resolved with a changed password prop (changed or removed). // don't need to set { immediate: true } on the watcher. () => authStore.publicLinkPassword, (publicLinkPassword: string | undefined) => { const publicLinkToken = authStore.publicLinkToken const space = spacesStore.spaces.find((space) => { return isPublicSpaceResource(space) && space.id === publicLinkToken }) if (!space) { return } ;(space as PublicSpaceResource).publicLinkPassword = publicLinkPassword } ) } export const bootstrapErrorApp = async (err: Error): Promise<void> => { const { capabilityStore, configStore } = announcePiniaStores() announceVersions({ capabilityStore }) const app = createApp(pages.failure) await announceTheme({ app, designSystem, configStore }) console.error(err) announceTranslations({ app, availableLanguages: supportedLanguages, translations }) app.mount('#owncloud') } ;(window as any).runtimeLoaded({ bootstrapApp, bootstrapErrorApp })
owncloud/web/packages/web-runtime/src/index.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/index.ts", "repo_id": "owncloud", "token_count": 2838 }
848
import { extractPublicLinkToken, isIdpContextRequired, isPublicLinkContextRequired, isUserContextRequired } from './index' import { Router, RouteLocation } from 'vue-router' import { contextRouteNameKey, queryItemAsString, useAuthStore, useEmbedMode } from '@ownclouders/web-pkg' import { authService } from '../services/auth/authService' import { unref } from 'vue' export const setupAuthGuard = (router: Router) => { router.beforeEach(async (to, from) => { const { isDelegatingAuthentication } = useEmbedMode() if (from && to.path === from.path && !hasContextRouteNameChanged(to, from)) { // note: except for the context route, query changes can never trigger re-init of the auth context return true } const authStore = useAuthStore() await authService.initializeContext(to) // vue-router currently (4.1.6) does not cancel navigations when a new one is triggered // we need to guard this case to be able to show the access denied page // and not be redirected to the login page if (authService.hasAuthErrorOccurred) { return to.name === 'accessDenied' || { name: 'accessDenied' } } if (isPublicLinkContextRequired(router, to)) { if (!authStore.publicLinkContextReady) { const publicLinkToken = extractPublicLinkToken(to) return { name: 'resolvePublicLink', params: { token: publicLinkToken }, query: { redirectUrl: to.fullPath } } } return true } if (isUserContextRequired(router, to)) { if (!authStore.userContextReady) { if (unref(isDelegatingAuthentication)) { return { path: '/web-oidc-callback' } } return { path: '/login', query: { redirectUrl: to.fullPath } } } return true } if (isIdpContextRequired(router, to)) { if (!authStore.idpContextReady) { if (unref(isDelegatingAuthentication)) { return { path: '/web-oidc-callback' } } return { path: '/login', query: { redirectUrl: to.fullPath } } } return true } return true }) router.afterEach((to) => { if (to.name !== 'accessDenied') { return } authService.hasAuthErrorOccurred = false }) } export const hasContextRouteNameChanged = (to: RouteLocation, from: RouteLocation): boolean => { if (!to.query[contextRouteNameKey] && !from.query[contextRouteNameKey]) { return false } return ( queryItemAsString(to.query[contextRouteNameKey]) !== queryItemAsString(from.query[contextRouteNameKey]) ) }
owncloud/web/packages/web-runtime/src/router/setupAuthGuard.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/src/router/setupAuthGuard.ts", "repo_id": "owncloud", "token_count": 971 }
849
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`OcSidebarNav > renders navItems into a list 1`] = ` "<div id="web-nav-sidebar" class="oc-app-navigation-expanded"><button type="button" aria-label="Toggle sidebar" class="oc-button oc-rounded oc-button-m oc-button-justify-content-center oc-button-gap-m oc-button-passive oc-button-passive-raw toggle-sidebar-button-expanded oc-pr-s toggle-sidebar-button oc-pb-s oc-pt-m"> <!--v-if--> <!-- @slot Content of the button --> <span class="oc-icon oc-icon-l oc-icon-passive"><!----></span> </button> <nav class="oc-sidebar-nav oc-mb-m oc-mt-s oc-px-xs" aria-label="Sidebar navigation menu"> <div id="nav-highlighter" class="oc-ml-s oc-background-primary-gradient" aria-hidden="true"></div> <ul class="oc-list oc-my-rm oc-mx-rm"> <sidebar-nav-item-stub index="00000000000000000000000000000000" icon="folder" name="Personal" active="true" target="[object Object]" filltype="fill" collapsed="false"></sidebar-nav-item-stub> <sidebar-nav-item-stub index="00000000000000000000000000000000" icon="share-forward" name="Shares" active="false" target="[object Object]" filltype="fill" collapsed="false"></sidebar-nav-item-stub> <sidebar-nav-item-stub index="00000000000000000000000000000000" icon="delete" name="Deleted files" active="false" target="[object Object]" filltype="fill" collapsed="false"></sidebar-nav-item-stub> </ul> </nav> <!-- @slot bottom content of the sidebar --> <span class="footer">Footer</span> </div>" `;
owncloud/web/packages/web-runtime/tests/unit/components/SidebarNav/__snapshots__/SidebarNav.spec.ts.snap/0
{ "file_path": "owncloud/web/packages/web-runtime/tests/unit/components/SidebarNav/__snapshots__/SidebarNav.spec.ts.snap", "repo_id": "owncloud", "token_count": 543 }
850
import UploadInfo from '../../../src/components/UploadInfo.vue' import { defaultPlugins, shallowMount, defaultComponentMocks } from 'web-test-helpers' import { ResourceListItem } from '@ownclouders/web-pkg' import { nextTick } from 'vue' const selectors = { overlay: '#upload-info', title: '.upload-info-title p', progress: '.upload-info-progress', success: '.upload-info-success', error: '.upload-info-danger', message: '.upload-info-message', info: { items: '.upload-info-items', item: '.upload-info-items li' } } describe('UploadInfo component', () => { it('should render the component in a hidden state per default', () => { const { wrapper } = getShallowWrapper() const overlay = wrapper.find(selectors.overlay) expect(overlay.exists()).toBeFalsy() }) it('should show the component', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true await nextTick() const overlay = wrapper.find(selectors.overlay) expect(overlay.exists()).toBeTruthy() }) describe('title', () => { it('should show that an upload is in progress', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.inPreparation = false wrapper.vm.filesInProgressCount = 1 wrapper.vm.runningUploads = 1 await nextTick() const uploadTitle = wrapper.find(selectors.title).text() expect(uploadTitle).toBe('1 item uploading...') }) it('should show that an upload was successful', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.successful = ['1'] await nextTick() const uploadTitle = wrapper.find(selectors.title).text() expect(uploadTitle).toBe('Upload complete') }) it('should show that an upload failed', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true ;(wrapper.vm.errors = [{ name: 'file', type: 'file' }]), await nextTick() const uploadTitle = wrapper.find(selectors.title).text() expect(uploadTitle).toBe('Upload failed') }) it('should show that an upload was cancelled', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.uploadsCancelled = true await nextTick() const uploadTitle = wrapper.find(selectors.title).text() expect(uploadTitle).toBe('Upload cancelled') }) it('should show that an upload is preparing', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.runningUploads = 1 wrapper.vm.inPreparation = true await nextTick() const uploadTitle = wrapper.find(selectors.title).text() expect(uploadTitle).toBe('Preparing upload...') }) it('should show that an upload is being finalized', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.filesInProgressCount = 1 wrapper.vm.runningUploads = 1 wrapper.vm.inFinalization = true await nextTick() const uploadTitle = wrapper.find(selectors.title).text() expect(uploadTitle).toBe('Finalizing upload...') }) }) describe('progress bar', () => { it('should show the progress bar when an upload is in progress', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.filesInProgressCount = 1 wrapper.vm.runningUploads = 1 await nextTick() const progressBar = wrapper.find(selectors.progress) expect(progressBar.exists()).toBeTruthy() }) }) describe('info', () => { it('should show the number of successful items', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.successful = ['1', '2'] await nextTick() const info = wrapper.find(selectors.success).text() expect(info).toBe('2 items uploaded') }) it('should show the number of failed items', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.errors = [{ name: 'file', type: 'file' }] wrapper.vm.successful = ['1'] await nextTick() const info = wrapper.find(selectors.error).text() expect(info).toBe('1 of 2 items failed') }) }) describe('details', () => { it('should hide the info by default', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true await nextTick() const info = wrapper.find(selectors.info.items) expect(info.exists()).toBeFalsy() }) it('should list all the uploaded files when the info is displayed', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.infoExpanded = true wrapper.vm.uploads = [ { name: 'file', type: 'file', meta: { uploadId: '1' } }, { name: 'file2', type: 'file', meta: { uploadId: '2' } } ] await nextTick() const info = wrapper.find(selectors.info.items) expect(info.exists()).toBeTruthy() const uploadedItems = wrapper.findAll(selectors.info.item) expect(uploadedItems.length).toBe(2) }) it('should show a message on the failed uploaded files', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.infoExpanded = true ;(wrapper.vm.uploads = [ { name: 'file', type: 'file', meta: { uploadId: '1' } }, { name: 'file2', type: 'file', meta: { uploadId: '2' } }, { name: 'file3', type: 'file', meta: { uploadId: '3' } } ]), (wrapper.vm.errors = { 1: new Error(), 2: new Error() }) await nextTick() const info = wrapper.find(selectors.info.items) expect(info.exists()).toBeTruthy() const infoMessages = wrapper.findAll(selectors.message) expect(infoMessages.length).toBe(2) expect(infoMessages.at(0).text()).toBe('Unknown error') expect(infoMessages.at(0).text()).toBe('Unknown error') }) it('folder is clickable', async () => { const { wrapper } = getShallowWrapper() wrapper.vm.showInfo = true wrapper.vm.infoExpanded = true wrapper.vm.uploads = [ { name: 'file', type: 'folder', isFolder: true, targetRoute: { params: { driveAliasAndItem: 'some/drive/alias' } }, path: '', meta: { uploadId: '1' } } ] await nextTick() const info = wrapper.find(selectors.info.items) expect(info.exists()).toBeTruthy() const resourceStub = wrapper.findComponent<typeof ResourceListItem>( `${selectors.info.item} resource-list-item-stub` ) expect(resourceStub.props().isResourceClickable).toBeTruthy() }) }) describe('getRemainingTime method', () => { it.each([ { ms: 1000, expected: 'Few seconds left' }, { ms: 1000 * 60 * 30, expected: '30 minutes left' }, { ms: 1000 * 60 * 60, expected: '1 hour left' }, { ms: 1000 * 60 * 60 * 2, expected: '2 hours left' } ])('should return the proper string', ({ ms, expected }) => { const { wrapper } = getShallowWrapper() const estimatedTime = wrapper.vm.getRemainingTime(ms) expect(estimatedTime).toBe(expected) }) }) }) function getShallowWrapper() { const mocks = { ...defaultComponentMocks() } return { mocks, wrapper: shallowMount(UploadInfo, { global: { plugins: [...defaultPlugins()], mocks } }) } }
owncloud/web/packages/web-runtime/tests/unit/components/UploadInfo.spec.ts/0
{ "file_path": "owncloud/web/packages/web-runtime/tests/unit/components/UploadInfo.spec.ts", "repo_id": "owncloud", "token_count": 2987 }
851
import { mock } from 'vitest-mock-extended' import { useExtensionRegistry } from '../../../web-pkg' export const useExtensionRegistryMock = ( options: Partial<ReturnType<typeof useExtensionRegistry>> = {} ): ReturnType<typeof useExtensionRegistry> => { return { ...mock<ReturnType<typeof useExtensionRegistry>>(), registerExtensions: () => undefined, requestExtensions: () => [], ...options } }
owncloud/web/packages/web-test-helpers/src/mocks/useExtensionRegistryMock.ts/0
{ "file_path": "owncloud/web/packages/web-test-helpers/src/mocks/useExtensionRegistryMock.ts", "repo_id": "owncloud", "token_count": 141 }
852
/** * setValue by sending the keys one, by one * running federation tests on chrome browser has a problem with sendKeys and drops incomplete string when sending a * whole string to the web modal dialogs * * @export * @param {string} selector * @param {string} inputValue * @returns */ exports.command = function setValueBySingleKeys(selector, inputValue) { if (inputValue) { const chars = inputValue.split('').slice(0, -2) const charsEnd = inputValue.split('').slice(-2) const charPromise = this.setValue(selector, chars) // Sometimes the autocomplete list is not displayed when the characters are entered very fast // So we add a small pause for entering the last two characters const charEndPromise = charsEnd.map((char) => this.setValue(selector, char).pause(100)) || [] return Promise.all([charPromise, ...charEndPromise]) } return this.pause(1) }
owncloud/web/tests/acceptance/customCommands/setValueBySingleKeys.js/0
{ "file_path": "owncloud/web/tests/acceptance/customCommands/setValueBySingleKeys.js", "repo_id": "owncloud", "token_count": 268 }
853
@openIdLogin @ocis-konnectd-issue-26 Feature: login users As a user I want to be able to log into my account So that I have access to my files As an admin I want only authorised users to log in So that unauthorised access is impossible Background: Given user "Alice" has been created with default attributes and without skeleton files in the server Scenario: admin login Given the user has browsed to the login page When the user clicks the authenticate button And the user logs in with username "admin" and password "admin" using the webUI Then the files table should be displayed Scenario: logging out Given user "Alice" has logged in using the webUI And the user has browsed to the personal page When the user logs out of the webUI Then the user should be redirected to the IdP login page @ocisSmokeTest Scenario: logging out redirects to the url with state attribute Given user "Alice" has logged in using the webUI And the user has browsed to the personal page When the user logs out of the webUI Then the user should be on page with the url containing "state=" When user "Alice" logs in using the webUI Then the files table should be displayed Scenario: try to login with invalid username Given the user has browsed to the login page When the user tries to log in with username "invalid" and password "1234" using the webUI Then the warning 'Logon failed. Please verify your credentials and try again.' should be displayed on the login page Scenario: try to login with valid username and invalid password Given the user has browsed to the login page When the user tries to log in with username "Alice" and password "invalid" using the webUI Then the warning 'Logon failed. Please verify your credentials and try again.' should be displayed on the login page
owncloud/web/tests/acceptance/features/webUILogin/openidLogin.feature/0
{ "file_path": "owncloud/web/tests/acceptance/features/webUILogin/openidLogin.feature", "repo_id": "owncloud", "token_count": 507 }
854
@mailhog @public_link_share-feature-required Feature: Share by public link with different roles As a user I want to share files through a publicly accessible link with different roles So that users who do not have an account on my ownCloud server can access them As an admin I want to limit the ability of a user to share files/folders through a publicly accessible link So that public sharing is limited according to organization policy 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 Scenario Outline: simple sharing by public link with read-only role Given user "Alice" has created file "simple-folder/lorem.txt" in the server And user "Alice" has logged in using the webUI When the user creates a new public link for folder "simple-folder" using the webUI And the user sets the role of the most recently created public link of resource "simple-folder" to "<role>" Then user "Alice" should have a share with these details in the server: | field | value | | share_type | public_link | | uid_owner | Alice | | permissions | <permissions> | | path | /simple-folder | # Once issue @issue-ocis-reva-383 is resolved uncomment lines below # | name | Link | # And a link named "Link" should be listed with role "<role>" in the public link list of folder "simple-folder" on the webUI When the public uses the webUI to access the last public link created by user "Alice" in a new session Then file "lorem.txt" should be listed on the webUI Examples: | role | permissions | | Viewer | read | @smokeTest @ocisSmokeTest @issue-ocis-reva-383 Scenario Outline: simple sharing by public link with different roles Given user "Alice" has created file "simple-folder/lorem.txt" in the server And user "Alice" has logged in using the webUI When the user creates a new public link for folder "simple-folder" using the webUI And the user sets the role of the most recently created public link of resource "simple-folder" to "<role>" Then user "Alice" should have a share with these details in the server: | field | value | | share_type | public_link | | uid_owner | Alice | | permissions | <permissions> | | path | /simple-folder | | name | Link | And a link named "Link" should be listed with role "<displayed-role>" in the public link list of folder "simple-folder" on the webUI When the public uses the webUI to access the last public link created by user "Alice" in a new session Then file "lorem.txt" should be listed on the webUI Examples: | role | displayed-role | permissions | | Viewer | Anyone with the link can view | read | | Editor | Anyone with the link can edit | read, update, create, delete | | Contributor | Anyone with the link can upload | read, create | @issue-ocis-reva-383 Scenario Outline: simple sharing by public link with different roles (ocis bug demonstration) Given user "Alice" has created file "simple-folder/lorem.txt" in the server And user "Alice" has logged in using the webUI When the user creates a new public link for folder "simple-folder" using the webUI And the user sets the role of the most recently created public link of resource "simple-folder" to "<role>" Then user "Alice" should have a share with these details in the server: | field | value | | share_type | public_link | | uid_owner | Alice | | permissions | <permissions> | | path | /simple-folder | When the public uses the webUI to access the last public link created by user "Alice" in a new session Then file "lorem.txt" should be listed on the webUI Examples: | role | permissions | | Editor | read, update, create, delete | | Contributor | read, create | @issue-ocis-reva-383 Scenario: sharing by public link with "Uploader" role Given user "Alice" has created file "simple-folder/fileInside" in the server And user "Alice" has logged in using the webUI And the user creates a new public link for folder "simple-folder" using the webUI And the user sets the role of the most recently created public link of resource "simple-folder" to "Uploader" Then user "Alice" should have a share with these details in the server: | field | value | | share_type | public_link | | uid_owner | Alice | | permissions | create | | path | /simple-folder | | name | Link | And a link named "Link" should be listed with role "Secret File Drop" in the public link list of folder "simple-folder" on the webUI When the public uses the webUI to access the last public link created by user "Alice" in a new session Then the user should be redirected to the files-drop page @issue-ocis-reva-383 Scenario: sharing by public link with "Uploader" role (ocis bug demonstration) Given user "Alice" has logged in using the webUI And the user creates a new public link for folder "simple-folder" using the webUI And the user sets the role of the most recently created public link of resource "simple-folder" to "Uploader" Then user "Alice" should have a share with these details in the server: | field | value | | share_type | public_link | | uid_owner | Alice | | permissions | create | | path | /simple-folder | When the public uses the webUI to access the last public link created by user "Alice" in a new session Then the user should be redirected to the files-drop page @issue-4582 @disablePreviews Scenario: creating a public link with "Editor" role makes it possible to delete files via the link Given user "Alice" has created the following folders in the server | entry_name | | simple-folder/simple-empty-folder | And user "Alice" has created the following files in the server | entry_name | | simple-folder/lorem.txt | | simple-folder/strängé filename (duplicate #2 &).txt | | simple-folder/zzzz-must-be-last-file-in-folder.txt | And user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions in the server When the public uses the webUI to access the last public link created by user "Alice" in a new session And the user deletes the following elements using the webUI | name | | simple-empty-folder | | lorem.txt | | strängé filename (duplicate #2 &).txt | And the user deletes the following elements using the webUI | name | | zzzz-must-be-last-file-in-folder.txt | Then the deleted elements should not be listed on the webUI And the deleted elements should not be listed on the webUI after a page reload @issue-4582 @disablePreviews Scenario: creating a public link with "Editor" role makes it possible to delete files via the link even with password set Given user "Alice" has created the following folders in the server | entry_name | | simple-folder/simple-empty-folder | And user "Alice" has created the following files in the server | entry_name | | simple-folder/lorem.txt | | simple-folder/strängé filename (duplicate #2 &).txt | | simple-folder/zzzz-must-be-last-file-in-folder.txt | And user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions and password "#Passw0rd" in the server When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session And the user deletes the following elements using the webUI | name | | simple-empty-folder | | lorem.txt | | strängé filename (duplicate #2 &).txt | | zzzz-must-be-last-file-in-folder.txt | Then the deleted elements should not be listed on the webUI @issue-ocis-270 Scenario: creating a public link with "Viewer" role only makes it impossible to delete files via the link Given user "Alice" has created file "simple-folder/lorem.txt" in the server And user "Alice" has shared folder "simple-folder" with link with "read" permissions in the server When the public uses the webUI to access the last public link created by user "Alice" in a new session Then it should not be possible to delete file "lorem.txt" using the webUI Scenario: creating a public link with "Editor" role makes it possible to upload a file Given user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions in the server When the public uses the webUI to access the last public link created by user "Alice" in a new session And the user uploads file "new-lorem.txt" using the webUI Then file "new-lorem.txt" should be listed on the webUI And as "Alice" file "simple-folder/new-lorem.txt" should exist in the server Scenario: creating a public link with "Editor" role makes it possible to upload a file inside a subdirectory with password set Given user "Alice" has created folder "simple-folder/simple-empty-folder" in the server And user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions and password "#Passw0rd" in the server When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session And the user opens folder "simple-empty-folder" using the webUI And the user uploads file "new-lorem.txt" using the webUI Then file "new-lorem.txt" should be listed on the webUI And as "Alice" file "simple-folder/simple-empty-folder/new-lorem.txt" should exist in the server Scenario: creating a public link with "Editor" role makes it possible to upload a folder Given user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions in the server When the public uses the webUI to access the last public link created by user "Alice" in a new session And the user uploads folder "PARENT" using the webUI Then folder "PARENT" should be listed on the webUI And folder "CHILD" should be listed in the folder "PARENT" on the webUI And file "child.txt" should be listed in the folder "CHILD" on the webUI And as "Alice" file "simple-folder/PARENT/CHILD/child.txt" should exist in the server Scenario: creating a public link with "Editor" role makes it possible to upload a folder inside a subdirectory Given user "Alice" has created folder "simple-folder/simple-empty-folder" in the server And user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions in the server When the public uses the webUI to access the last public link created by user "Alice" in a new session And the user opens folder "simple-empty-folder" using the webUI And the user uploads folder "PARENT" using the webUI Then folder "PARENT" should be listed on the webUI And folder "CHILD" should be listed in the folder "PARENT" on the webUI And file "child.txt" should be listed in the folder "CHILD" on the webUI And as "Alice" file "simple-folder/simple-empty-folder/PARENT/CHILD/child.txt" should exist in the server Scenario: creating a public link with "Editor" role makes it possible to upload files via the link even with password set Given user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions and password "#Passw0rd" in the server When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session And the user uploads file "new-lorem.txt" using the webUI Then file "new-lorem.txt" should be listed on the webUI And as "Alice" file "simple-folder/new-lorem.txt" should exist in the server Scenario: creating a public link with "Editor" role makes it possible to upload files inside a subdirectory Given user "Alice" has created folder "simple-folder/simple-empty-folder" in the server And user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions in the server When the public uses the webUI to access the last public link created by user "Alice" in a new session And the user opens folder "simple-empty-folder" using the webUI And the user uploads file "new-lorem.txt" using the webUI Then file "new-lorem.txt" should be listed on the webUI And as "Alice" file "simple-folder/simple-empty-folder/new-lorem.txt" should exist in the server Scenario: creating a public link with "Editor" role makes it possible to upload a folder even with password set Given user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions and password "#Passw0rd" in the server When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session And the user uploads folder "PARENT" using the webUI Then folder "PARENT" should be listed on the webUI And folder "CHILD" should be listed in the folder "PARENT" on the webUI And file "child.txt" should be listed in the folder "CHILD" on the webUI And as "Alice" file "simple-folder/PARENT/CHILD/child.txt" should exist in the server Scenario: creating a public link with "Editor" role makes it possible to upload a folder inside a sub-directory even with password set Given user "Alice" has created folder "simple-folder/simple-empty-folder" in the server And user "Alice" has shared folder "simple-folder" with link with "read, update, create, delete" permissions and password "#Passw0rd" in the server When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session And the user opens folder "simple-empty-folder" using the webUI And the user uploads folder "PARENT" using the webUI Then folder "PARENT" should be listed on the webUI And folder "CHILD" should be listed in the folder "PARENT" on the webUI And file "child.txt" should be listed in the folder "CHILD" on the webUI And as "Alice" file "simple-folder/simple-empty-folder/PARENT/CHILD/child.txt" should exist in the server @issue-ocis-723 Scenario: creating a public link with "Viewer" role makes it impossible to create files via the link even with password set Given user "Alice" has shared folder "simple-folder" with link with "read" permissions and password "#Passw0rd" in the server When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session Then the create button should not be visible on the webUI Scenario: creating a public link with "Uploader" role makes it possible to upload a file through files-drop page Given user "Alice" has shared folder "simple-folder" with link with "create" permissions in the server When the public uses the webUI to access the last public link created by user "Alice" in a new session And the public uploads file "new-lorem.txt" in files-drop page Then the following files should be listed on the files-drop page: | new-lorem.txt | And as "Alice" file "simple-folder/new-lorem.txt" should exist in the server Scenario: creating a public link with "Uploader" role makes it possible to upload multiple files via files-drop page Given user "Alice" has shared folder "simple-folder" with link with "create" permissions in the server When the public uses the webUI to access the last public link created by user "Alice" in a new session And the public uploads file "'single'quotes.txt" in files-drop page And the public uploads file "new-lorem.txt" in files-drop page Then the following files should be listed on the files-drop page: | new-lorem.txt | And as "Alice" the content of "simple-folder/'single'quotes.txt" in the server should be the same as the content of local file "'single'quotes.txt" And as "Alice" the content of "simple-folder/new-lorem.txt" in the server should be the same as the content of local file "new-lorem.txt" @issue-ocis-723 Scenario: creating a public link with "Uploader" role makes it possible to create files through files-drop page even with password set Given user "Alice" has shared folder "simple-folder" with link with "create" permissions and password "#Passw0rd" in the server When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session And the public uploads file "'single'quotes.txt" in files-drop page Then the following files should be listed on the files-drop page: | 'single'quotes.txt | And as "Alice" the content of "simple-folder/'single'quotes.txt" in the server should be the same as the content of local file "'single'quotes.txt" @issue-ocis-723 Scenario: creating a public link with "Uploader" role makes it possible to upload multiple files via files-drop page even with password set Given user "Alice" has shared folder "simple-folder" with link with "create" permissions and password "#Passw0rd" in the server When the public uses the webUI to access the last public link created by user "Alice" with password "#Passw0rd" in a new session And the public uploads file "'single'quotes.txt" in files-drop page And the public uploads file "new-lorem.txt" in files-drop page Then the following files should be listed on the files-drop page: | new-lorem.txt | And as "Alice" the content of "simple-folder/'single'quotes.txt" in the server should be the same as the content of local file "'single'quotes.txt" And as "Alice" the content of "simple-folder/new-lorem.txt" in the server should be the same as the content of local file "new-lorem.txt"
owncloud/web/tests/acceptance/features/webUISharingPublicDifferentRoles/shareByPublicLinkDifferentRoles.feature/0
{ "file_path": "owncloud/web/tests/acceptance/features/webUISharingPublicDifferentRoles/shareByPublicLinkDifferentRoles.feature", "repo_id": "owncloud", "token_count": 6126 }
855
const _ = require('lodash') /** * Deep diff between two object, using lodash * For more details check this link https://gist.github.com/Yimiprod/7ee176597fef230d1451 * @param {Object} object Object compared * @param {Object} base Object to compare with * @return {Object} Return a new object who represent the diff */ exports.difference = function (object, base) { function changes(object, base) { return _.transform(object, function (result, value, key) { if (!_.isEqual(value, base[key])) { result[key] = _.isObject(value) && _.isObject(base[key]) ? changes(value, base[key]) : value } }) } return changes(object, base) }
owncloud/web/tests/acceptance/helpers/objects.js/0
{ "file_path": "owncloud/web/tests/acceptance/helpers/objects.js", "repo_id": "owncloud", "token_count": 239 }
856
module.exports = { commands: { /** * @enum {string} * @readonly */ FileAction: Object.freeze({ acceptShare: 'acceptShare', download: 'download', declineShare: 'declineShare', delete: 'delete', favorite: 'favorite', unmarkFavorite: 'unmarkFavorite', restore: 'restore', rename: 'rename', move: 'move', copy: 'copy', preview: 'preview', textEditor: 'textEditor' }), /** * Action button selector * * @param {string} action * @returns {string} */ getActionSelector: function (action) { const actionsAccordionSelector = this.elements.actionsAccordion.selector const actionSelector = this.elements[action + 'ButtonInAccordion'].selector return `${actionsAccordionSelector}${actionSelector}` }, /** * perform one of the main file actions * * @param {string} action delete|share|rename|download * @throws Error * @returns {*} */ performFileAction: async function (action) { this.initAjaxCounters() const fileActionBtnSelectorXpath = this.getActionSelector(action) await this.click('xpath', fileActionBtnSelectorXpath) return await this.waitForAjaxCallsToStartAndFinish() }, /** * returns the disabled state of given action * * @param {string} action * @returns {Promise<boolean>} */ getActionDisabledAttr: async function (action) { let disabledState const btnSelector = this.getActionSelector(action) await this.api.element('xpath', btnSelector, (result) => { // action is disabled when not visible in dropdown menu disabledState = result.status === -1 }) return disabledState }, /** * deletes resource using fileActions 'delete' button * @returns {Promise<*>} */ delete: async function () { await this.performFileAction(this.FileAction.delete) return this }, /** * @param {string} toName * @param {boolean} expectToSucceed * @return {*} */ rename: async function (toName, expectToSucceed = true, fromContextMenu = false) { if (!fromContextMenu) { await this.performFileAction(this.FileAction.rename) } await this.useXpath() .waitForElementVisible('@dialog') .waitForAnimationToFinish() // wait for transition on the modal to finish .clearValue('@dialogInput') .setValue('@dialogInput', toName) .useCss() const timeout = expectToSucceed ? this.api.globals.waitForConditionTimeout : this.api.globals.waitForNegativeConditionTimeout await this.click( { selector: '@dialogConfirmBtnEnabled', suppressNotFoundErrors: !expectToSucceed }, timeout ) if (expectToSucceed) { await this.waitForElementNotPresent('@dialog') } return this }, /** * mark as favorite resource using fileActions 'favorite' button * @returns {Promise<*>} */ favorite: async function () { return await this.performFileAction(this.FileAction.favorite) }, /** * unmark as favorite resource using fileActions 'favorite' button * @returns {Promise<*>} */ unmarkFavorite: async function () { return await this.performFileAction(this.FileAction.unmarkFavorite) }, /** * @return {Promise<module.exports.commands>} */ restore: async function () { return await this.performFileAction(this.FileAction.restore) }, /** * @return {Promise<module.exports.commands>} */ download: async function () { return await this.performFileAction(this.FileAction.download) }, /** * @return {Promise<module.exports.commands>} */ deleteResourceImmediately: async function () { await this.performFileAction(this.FileAction.delete) await this.api.page.FilesPageElement.filesList().confirmDeletion() return this }, /** * Trigger the move of a resource via its file action */ move: async function () { return await this.performFileAction(this.FileAction.move) }, /** * Trigger the copy of a resource via its file action */ copy: async function () { return await this.performFileAction(this.FileAction.copy) }, /** * Trigger accepting a share */ acceptShare: function () { return this.performFileAction(this.FileAction.acceptShare) }, /** * Trigger declining a share */ declineShare: function () { return this.performFileAction(this.FileAction.declineShare) }, /** * Open a resource in the preview via its file action */ preview: function () { return this.performFileAction(this.FileAction.preview) }, /** * Open a resource in the text editor via its file action */ textEditor: function () { return this.performFileAction(this.FileAction.textEditor) } }, elements: { sharingSideBar: { selector: '#oc-files-sharing-sidebar' }, actionsAccordion: { selector: '//ul[@id="oc-files-actions-sidebar"]/li', locateStrategy: 'xpath' }, // covers oc-files-actions-delete-permanent-trigger and oc-files-actions-delete-trigger deleteButtonInAccordion: { selector: '//button[contains(@class, "oc-files-actions-delete-")]', locateStrategy: 'xpath' }, downloadButtonInAccordion: { selector: '//button[contains(@class, "oc-files-actions-download-file-trigger")]', locateStrategy: 'xpath' }, favoriteButtonInAccordion: { selector: '//button[normalize-space()="Add to favorites"]', locateStrategy: 'xpath' }, unmarkFavoriteButtonInAccordion: { selector: '//button[normalize-space()="Remove from favorites"]', locateStrategy: 'xpath' }, restoreButtonInAccordion: { selector: '//button[contains(@class, "oc-files-actions-restore-trigger")]', locateStrategy: 'xpath' }, renameButtonInAccordion: { selector: '//button[contains(@class, "oc-files-actions-rename-trigger")]', locateStrategy: 'xpath' }, // TODO: Merge with selectors in personalPage dialog: { selector: '.oc-modal' }, dialogConfirmBtnEnabled: { selector: '.oc-modal-body-actions-confirm:enabled' }, dialogInput: { selector: '.oc-modal-body-input .oc-text-input' }, moveButtonInAccordion: { selector: '//button[contains(@class, "oc-files-actions-move-trigger")]', locateStrategy: 'xpath' }, copyButtonInAccordion: { selector: '//button[contains(@class, "oc-files-actions-copy-trigger")]', locateStrategy: 'xpath' }, acceptShareButtonInAccordion: { selector: '//button[contains(@class, "oc-files-actions-enable-sync-trigger")]', locateStrategy: 'xpath' }, declineShareButtonInAccordion: { selector: '//button[contains(@class, "oc-files-actions-disable-sync-trigger")]', locateStrategy: 'xpath' }, previewButtonInAccordion: { selector: '//button[normalize-space()="Preview"]', locateStrategy: 'xpath' }, textEditorButtonInAccordion: { selector: '//button[normalize-space()="Open in Text Editor"]', locateStrategy: 'xpath' } } }
owncloud/web/tests/acceptance/pageObjects/FilesPageElement/fileActionsMenu.js/0
{ "file_path": "owncloud/web/tests/acceptance/pageObjects/FilesPageElement/fileActionsMenu.js", "repo_id": "owncloud", "token_count": 2997 }
857
module.exports = { commands: { getUserProfileAvatar: async function () { let userInfo await this.waitForElementVisible('@userProfileAvatar').api.element( '@userProfileAvatar', (result) => { this.api.elementIdText(result.value.ELEMENT, (text) => { userInfo = text.value }) } ) return userInfo }, browseToManageAccount: function () { return this.waitForElementVisible('@manageAccount').click('@manageAccount') } }, elements: { userProfileAvatar: { selector: '.oc-topbar-personal-avatar' }, manageAccount: { selector: '#oc-topbar-account-manage' } } }
owncloud/web/tests/acceptance/pageObjects/profilePage.js/0
{ "file_path": "owncloud/web/tests/acceptance/pageObjects/profilePage.js", "repo_id": "owncloud", "token_count": 303 }
858
const { client } = require('nightwatch-api') const { Given, Then, When } = require('@cucumber/cucumber') const loginHelper = require('../helpers/loginHelper') const assert = require('assert') Given(/^the user has browsed to the login page$/, () => { return client.page.loginPage().navigate() }) When('the user clicks the authenticate button', () => client.page.loginPage().authenticate()) When( 'the user logs in with username {string} and password {string} using the webUI', (username, password) => { if (client.globals.openid_login) { return client.page.ocisLoginPage().login(username, password) } return client.page.ownCloudLoginPage().login(username, password) } ) When( 'the user tries to log in with username {string} and password {string} using the webUI', (username, password) => { if (client.globals.openid_login) { return client.page.ocisLoginPage().login(username, password, false) } return client.page.ownCloudLoginPage().login(username, password, false) } ) When('user {string} logs in using the webUI', (username) => loginHelper.loginAsUser(username)) When('user {string} fills in the login form using the webUI', (username) => loginHelper.fillInAndSubmitLogin(username) ) Then('the files table should not be empty', () => { return ( client.page.FilesPageElement.filesList() // even when the loading indicator is gone the table might not be rendered yet .waitForElementVisible('@fileRow') ) }) Then( 'the warning {string} should be displayed on the login page', async function (expectedMessage) { let actualMessage if (client.globals.openid_login) { actualMessage = await client.page.ocisLoginPage().getLoginErrorMessage() } else { actualMessage = await client.page.ownCloudLoginPage().getLoginErrorMessage() } return assert.strictEqual( actualMessage, expectedMessage, `Error message miss-match, Expected: '${expectedMessage}', Found: '${actualMessage}'` ) } ) Then('the user should be on page with the url containing {string}', function (urlContent) { return client.assert.urlContains(urlContent) }) // combined step Given('user {string} has logged in using the webUI', (user) => { return loginHelper.loginAsUser(user) }) When('the user logs out of the webUI', () => { return loginHelper.logout() }) When('the user re-logs in as {string} using the webUI', (user) => { return loginHelper.reLoginAsUser(user) }) Then('the user profile should be visible on the webUI', function () { return client.page.webPage().waitForElementVisible('@userMenuButton') }) When('the user opens the user profile', function () { return client.page.webPage().browseToUserProfile() }) Then('username {string} should be visible on the webUI', async function (username) { const profileUserName = await client.page.profilePage().getUserProfileName() assert.strictEqual(profileUserName, username) }) When('the user browses to manage the account', function () { return client.page.profilePage().browseToManageAccount() }) Then('the accounts page should be visible on the webUI', async function () { const isPageVisible = await client.page.accountPage().isPageVisible() return assert.ok(isPageVisible) }) Then('the user should be redirected to the login page', function () { return client.page.loginPage().waitForPage() }) Then('the user should be redirected to the user disabled page', function () { return client.page.userDisabledPage().waitTillLoaded() }) Then('the user should be redirected to the IdP login page', function () { return client.page.ocisLoginPage().waitForPage() }) Then('the user should be redirected to the login error page', function () { return client.page.loginErrorPage().waitTillLoaded() }) When('the user exits the login error page', function () { return client.page.loginErrorPage().exit() }) Then('the user should be redirected to the owncloud login page', function () { return client.page.ownCloudLoginPage().waitTillLoaded() })
owncloud/web/tests/acceptance/stepDefinitions/loginContext.js/0
{ "file_path": "owncloud/web/tests/acceptance/stepDefinitions/loginContext.js", "repo_id": "owncloud", "token_count": 1239 }
859
Feature: Kindergarten can use web to organize a day As a kindergarten operator named Alice I want to manage all file related operations by using ownCloud WEB So that i'm sure all parents are informed and have the latest information in a easy and secure way Background: Given "Admin" creates following users using API | id | | Alice | | Brian | | Carol | And "Admin" creates following group using API | id | | sales | | security | And "Admin" adds user to the group using API | user | group | | Brian | sales | Scenario: Alice can share this weeks meal plan with all parents When "Alice" logs in And "Alice" opens the "files" app And "Alice" navigates to the personal space page And "Alice" creates the following resources | resource | type | | groups/Kindergarten Koalas/meal plan | folder | | groups/Pre-Schools Pirates/meal plan | folder | | groups/Teddy Bear Daycare/meal plan | folder | And "Alice" uploads the following resources | resource | to | | PARENT/parent.txt | groups/Kindergarten Koalas/meal plan | | lorem.txt | groups/Kindergarten Koalas/meal plan | | lorem-big.txt | groups/Kindergarten Koalas/meal plan | | data.zip | groups/Pre-Schools Pirates/meal plan | | lorem.txt | groups/Pre-Schools Pirates/meal plan | | lorem-big.txt | groups/Pre-Schools Pirates/meal plan | | data.zip | groups/Teddy Bear Daycare/meal plan | | lorem.txt | groups/Teddy Bear Daycare/meal plan | | lorem-big.txt | groups/Teddy Bear Daycare/meal plan | # Implementation of sharing with different roles is currently broken # since we switched to bulk creating of shares with a single dropdown And "Alice" shares the following resources using the sidebar panel | resource | recipient | type | role | resourceType | | groups/Pre-Schools Pirates/meal plan | Brian | user | Can edit | folder | | groups/Pre-Schools Pirates/meal plan | Carol | user | Can edit | folder | | groups/Pre-Schools Pirates/meal plan/lorem-big.txt | sales | group | Can view | file | | groups/Pre-Schools Pirates/meal plan/lorem-big.txt | Carol | user | Can view | file | | groups/Kindergarten Koalas/meal plan | sales | group | Can view | folder | | groups/Kindergarten Koalas/meal plan | security | group | Can edit | folder | | groups/Kindergarten Koalas/meal plan/lorem.txt | sales | group | Can view | file | | groups/Kindergarten Koalas/meal plan/lorem.txt | security | group | Can view | file | | groups/Teddy Bear Daycare/meal plan | Brian | user | Can edit | folder | | groups/Teddy Bear Daycare/meal plan | Carol | user | Can edit | folder | | groups/Teddy Bear Daycare/meal plan/data.zip | Brian | user | Can edit | file | | groups/Teddy Bear Daycare/meal plan/data.zip | Carol | user | Can edit | file | # update share And "Alice" updates following sharee role | resource | recipient | type | role | resourceType | | groups/Pre-Schools Pirates/meal plan | Carol | user | Can view | folder | | groups/Pre-Schools Pirates/meal plan/lorem-big.txt | sales | group | Can edit | file | | groups/Kindergarten Koalas/meal plan | sales | group | Can edit | folder | | groups/Teddy Bear Daycare/meal plan/data.zip | Carol | user | Can edit | file | # Then what do we check for to be confident that the above things done by Alice have worked? When "Brian" logs in And "Brian" opens the "files" app And "Brian" navigates to the shared with me page And "Brian" downloads the following resources using the sidebar panel | resource | from | type | | data.zip | meal plan | file | # Then what do we check for to be confident that the above things done by Brian have worked? # Then the downloaded zip should contain... ? When "Carol" logs in And "Carol" opens the "files" app And "Carol" navigates to the shared with me page And "Carol" downloads the following resources using the sidebar panel | resource | from | type | | data.zip | meal plan | file | | lorem.txt | meal plan | file | | lorem-big.txt | meal plan | file | | meal plan | | folder | # Then what do we check for to be confident that the above things done by Carol have worked? # Then the downloaded files should have content "abc..." And "Carol" logs out When "Brian" downloads the following resources using the sidebar panel | resource | from | type | | lorem.txt | meal plan | file | | lorem-big.txt | meal plan | file | | meal plan | | folder | # Then what do we check for to be confident that the above things done by Brian have worked? # Then the downloaded files should have content "abc..." And "Brian" logs out And "Alice" downloads the following resources using the sidebar panel | resource | from | type | | parent.txt | groups/Kindergarten Koalas/meal plan | file | | lorem.txt | groups/Kindergarten Koalas/meal plan | file | | lorem-big.txt | groups/Kindergarten Koalas/meal plan | file | | data.zip | groups/Pre-Schools Pirates/meal plan | file | | lorem.txt | groups/Pre-Schools Pirates/meal plan | file | | lorem-big.txt | groups/Pre-Schools Pirates/meal plan | file | | data.zip | groups/Teddy Bear Daycare/meal plan | file | | lorem.txt | groups/Teddy Bear Daycare/meal plan | file | | lorem-big.txt | groups/Teddy Bear Daycare/meal plan | file | | meal plan | groups/Kindergarten Koalas | folder | | meal plan | groups/Pre-Schools Pirates | folder | | meal plan | groups/Teddy Bear Daycare | folder | | Kindergarten Koalas | groups | folder | | Pre-Schools Pirates | groups | folder | | Teddy Bear Daycare | groups | folder | | groups | | folder | And "Alice" deletes the following resources using the batch action | resource | from | | lorem.txt | groups/Kindergarten Koalas/meal plan | | lorem-big.txt | groups/Kindergarten Koalas/meal plan | | data.zip | groups/Pre-Schools Pirates/meal plan | | lorem.txt | groups/Pre-Schools Pirates/meal plan | | lorem-big.txt | groups/Pre-Schools Pirates/meal plan | | data.zip | groups/Teddy Bear Daycare/meal plan | | lorem.txt | groups/Teddy Bear Daycare/meal plan | | lorem-big.txt | groups/Teddy Bear Daycare/meal plan | | Kindergarten Koalas | groups | | Pre-Schools Pirates | groups | | Teddy Bear Daycare | groups | # Then what do we check for to be confident that the above things done by Alice have worked? # Then the downloaded files should have content "abc..." And "Alice" logs out
owncloud/web/tests/e2e/cucumber/features/journeys/kindergarten.feature/0
{ "file_path": "owncloud/web/tests/e2e/cucumber/features/journeys/kindergarten.feature", "repo_id": "owncloud", "token_count": 3514 }
860