Skip to content

Commit 0286c52

Browse files
authored
Merge pull request #1419 from nextcloud-libraries/feat/sidebar-api-web-components
feat(sidebar): provide public API to register a sidebar tab with web components
2 parents 7cc0468 + 81ddd92 commit 0286c52

8 files changed

Lines changed: 359 additions & 3 deletions

File tree

.eslintrc.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
{
22
"extends": [
33
"@nextcloud/eslint-config/typescript"
4+
],
5+
"overrides": [
6+
{
7+
"files": ["**.spec.*"],
8+
"rules": {
9+
"no-console": "off"
10+
}
11+
}
412
]
513
}
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
/**
2+
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
3+
* SPDX-License-Identifier: AGPL-3.0-or-later
4+
*/
5+
6+
import type { IFolder, INode, IView } from '../../lib/index.ts'
7+
8+
import { beforeEach, describe, expect, it, Mock, vi } from 'vitest'
9+
import { getSidebarTabs, ISidebarTab, registerSidebarTab } from '../../lib/sidebar'
10+
// missing in JSDom but supported by every browser!
11+
import 'css.escape'
12+
13+
class SidebarTabMock extends HTMLElement {
14+
15+
node?: INode
16+
folder?: IFolder
17+
view?: IView
18+
19+
public setActive(active: boolean) {
20+
console.log('setActive', active)
21+
}
22+
23+
}
24+
25+
describe('Sidebar tabs', () => {
26+
let getCustomElementsSpy: Mock
27+
28+
beforeEach(() => {
29+
vi.restoreAllMocks()
30+
getCustomElementsSpy = vi.spyOn(window.customElements, 'get')
31+
.mockImplementation(() => SidebarTabMock)
32+
delete window._nc_files_sidebar_tabs
33+
})
34+
35+
it('can register a tab', () => {
36+
const tab = getExampleTab()
37+
38+
registerSidebarTab(tab)
39+
expect(window._nc_files_sidebar_tabs).toBeInstanceOf(Map)
40+
expect(window._nc_files_sidebar_tabs!.has(tab.id)).toBe(true)
41+
expect(window._nc_files_sidebar_tabs!.get(tab.id)).toBe(tab)
42+
})
43+
44+
it('can fetch empty list of sidebar tabs', () => {
45+
expect(getSidebarTabs()).toBeInstanceOf(Array)
46+
expect(getSidebarTabs()).toHaveLength(0)
47+
})
48+
49+
it('can fetch list of sidebar tabs', () => {
50+
registerSidebarTab(getExampleTab())
51+
registerSidebarTab({ ...getExampleTab(), id: 'another-example' })
52+
53+
expect(getSidebarTabs()).toBeInstanceOf(Array)
54+
expect(getSidebarTabs()).toHaveLength(2)
55+
})
56+
57+
it('only registeres same id once', () => {
58+
const consoleSpy = vi.spyOn(console, 'warn')
59+
consoleSpy.mockImplementationOnce(() => {})
60+
61+
registerSidebarTab(getExampleTab())
62+
registerSidebarTab(getExampleTab())
63+
expect(consoleSpy).toHaveBeenCalledOnce()
64+
expect(getSidebarTabs()).toHaveLength(1)
65+
})
66+
67+
describe('Tab validation', () => {
68+
it('fails with an invalid parameter', () => {
69+
expect(
70+
// @ts-expect-error mocking for testing
71+
() => registerSidebarTab(getExampleTab),
72+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tab is not an object]')
73+
})
74+
75+
it('fails with missing id', () => {
76+
expect(
77+
// @ts-expect-error mocking for testing
78+
() => registerSidebarTab({ ...getExampleTab(), id: undefined }),
79+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs need to have an id conforming to the HTML id attribute specifications]')
80+
})
81+
82+
it('fails with non conforming id', () => {
83+
expect(
84+
() => registerSidebarTab({ ...getExampleTab(), id: 'this is invalid' }),
85+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs need to have an id conforming to the HTML id attribute specifications]')
86+
})
87+
88+
it('fails with missing tagName name', () => {
89+
expect(
90+
// @ts-expect-error mocking for testing
91+
() => registerSidebarTab({ ...getExampleTab(), tagName: undefined }),
92+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs need to have the tagName name set]')
93+
})
94+
95+
it('fails with invalid tagName name', () => {
96+
expect(() => registerSidebarTab({ ...getExampleTab(), tagName: 'MyAppSidebarTab' }))
97+
.toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs tagName name is invalid]')
98+
})
99+
100+
it('fails with non registered element', () => {
101+
getCustomElementsSpy.mockImplementationOnce(() => undefined)
102+
expect(() => registerSidebarTab(getExampleTab())).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tab element not registered]')
103+
})
104+
105+
it('fails with invalid custom element', () => {
106+
getCustomElementsSpy.mockImplementationOnce(() => HTMLElement)
107+
expect(() => registerSidebarTab(getExampleTab())).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tab elements must have the `setActive` method]')
108+
})
109+
110+
it('fails with missing name', () => {
111+
expect(
112+
// @ts-expect-error mocking for testing
113+
() => registerSidebarTab({ ...getExampleTab(), displayName: undefined }),
114+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs need to have a name set]')
115+
})
116+
117+
it('fails with invalid name', () => {
118+
expect(
119+
// @ts-expect-error mocking for testing
120+
() => registerSidebarTab({ ...getExampleTab(), displayName: 1234 }),
121+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs need to have a name set]')
122+
})
123+
124+
it('fails with missing icon', () => {
125+
expect(
126+
// @ts-expect-error mocking for testing
127+
() => registerSidebarTab({ ...getExampleTab(), iconSvgInline: undefined }),
128+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs need to have an valid SVG icon]')
129+
})
130+
131+
it('fails with invalid SVG icon', () => {
132+
expect(
133+
() => registerSidebarTab({ ...getExampleTab(), iconSvgInline: 'icon-group' }),
134+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs need to have an valid SVG icon]')
135+
})
136+
137+
it('fails with missing order', () => {
138+
expect(
139+
// @ts-expect-error mocking for testing
140+
() => registerSidebarTab({ ...getExampleTab(), order: undefined }),
141+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs need to have a numeric order set]')
142+
})
143+
144+
it('fails with invalid order', () => {
145+
expect(
146+
// @ts-expect-error mocking for testing
147+
() => registerSidebarTab({ ...getExampleTab(), order: '3' }),
148+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs need to have a numeric order set]')
149+
})
150+
151+
it('fails with missing "enabled" method', () => {
152+
expect(
153+
// @ts-expect-error mocking for testing
154+
() => registerSidebarTab({ ...getExampleTab(), enabled: undefined }),
155+
).toThrowErrorMatchingInlineSnapshot('[Error: Sidebar tabs need to have an "enabled" method]')
156+
})
157+
})
158+
})
159+
160+
/**
161+
* Get a very basic mock of a sidebar tab
162+
*/
163+
function getExampleTab(): ISidebarTab {
164+
return {
165+
id: 'example-tab',
166+
displayName: 'Example',
167+
tagName: 'example_app-files-sidebar-tab',
168+
enabled: vi.fn(),
169+
iconSvgInline: '<svg><circle r="45" cx="50" cy="50" fill="red" /></svg>',
170+
order: 0,
171+
}
172+
}

__tests__/view.spec.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,9 @@ describe('View creation', () => {
182182
})
183183
})
184184

185+
/**
186+
* Creates a mock View and its associated Folder for testing purposes.
187+
*/
185188
export function mockView() {
186189
const folder = new Folder({
187190
source: 'https://example.org/dav/files/admin/',

lib/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@ export * from './navigation/index.ts'
1212
export * from './newMenu/index.ts'
1313
export * from './node/index.ts'
1414
export * from './permissions.ts'
15+
export * from './sidebar/index.ts'
1516
export * from './utils/index.ts'

lib/sidebar/index.ts

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
/*
2+
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
3+
* SPDX-License-Identifier: AGPL-3.0-or-later
4+
*/
5+
6+
import type { IView } from '../navigation/view.ts'
7+
import type { IFolder, INode } from '../node/index.ts'
8+
9+
import isSvg from 'is-svg'
10+
import logger from '../utils/logger.ts'
11+
12+
export interface ISidebarContext {
13+
/**
14+
* The active node in the sidebar
15+
*/
16+
node: INode
17+
18+
/**
19+
* The current open folder in the files app
20+
*/
21+
folder: IFolder
22+
23+
/**
24+
* The currently active view
25+
*/
26+
view: IView
27+
}
28+
29+
/**
30+
* This component describes the custom web component that should be registered for a sidebar tab.
31+
*
32+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Web_components
33+
* @see https://vuejs.org/guide/extras/web-components#building-custom-elements-with-vue
34+
*/
35+
export interface SidebarComponent extends HTMLElement, ISidebarContext {
36+
/**
37+
* This method is called by the files app if the sidebar tab state changes.
38+
*
39+
* @param active - The new active state
40+
*/
41+
setActive(active: boolean): Promise<void>
42+
}
43+
44+
/**
45+
* Implementation of a custom sidebar tab within the files app.
46+
*/
47+
export interface ISidebarTab {
48+
/**
49+
* Unique id of the sidebar tab.
50+
* This has to conform to the HTML id attribute specification.
51+
*/
52+
id: string
53+
54+
/**
55+
* The localized name of the sidebar tab.
56+
*/
57+
displayName: string
58+
59+
/**
60+
* The icon, as SVG, of the sidebar tab.
61+
*/
62+
iconSvgInline: string
63+
64+
/**
65+
* The order of this tab.
66+
* Use a low number to make this tab ordered in front.
67+
*/
68+
order: number
69+
70+
/**
71+
* The tag name of the web component.
72+
* The web component must already be registered under that tag name with `CustomElementRegistry.define()`.
73+
*
74+
* To avoid name clashes the name has to start with your appid (e.g. `your_app`).
75+
* So in addition with the web component naming rules a good name would be `your_app-files-sidebar-tab`.
76+
*/
77+
tagName: string
78+
79+
/**
80+
* Callback to check if the sidebar tab should be shown for the selected node.
81+
*
82+
* @param context - The current context of the files app
83+
*/
84+
enabled: (context: ISidebarContext) => boolean
85+
}
86+
87+
/**
88+
* Register a new sidebar tab for the files app.
89+
*
90+
* @param tab - The sidebar tab to register
91+
* @throws If the provided tab is not a valid sidebar tab and thus cannot be registered.
92+
*/
93+
export function registerSidebarTab(tab: ISidebarTab): void {
94+
validateSidebarTab(tab)
95+
96+
window._nc_files_sidebar_tabs ??= new Map<string, ISidebarTab>()
97+
if (window._nc_files_sidebar_tabs.has(tab.id)) {
98+
logger.warn(`Sidebar tab with id "${tab.id}" already registered. Skipping.`)
99+
return
100+
}
101+
window._nc_files_sidebar_tabs.set(tab.id, tab)
102+
logger.debug(`New sidebar tab with id "${tab.id}" registered.`)
103+
}
104+
105+
/**
106+
* Get all currently registered sidebar tabs.
107+
*/
108+
export function getSidebarTabs(): ISidebarTab[] {
109+
if (window._nc_files_sidebar_tabs) {
110+
return [...window._nc_files_sidebar_tabs.values()]
111+
}
112+
return []
113+
}
114+
115+
/**
116+
* Check if a given sidebar tab objects implements all necessary fields.
117+
*
118+
* @param tab - The sidebar tab to validate
119+
*/
120+
function validateSidebarTab(tab: ISidebarTab): void {
121+
if (typeof tab !== 'object') {
122+
throw new Error('Sidebar tab is not an object')
123+
}
124+
125+
if (!tab.id || (typeof tab.id !== 'string') || tab.id !== CSS.escape(tab.id)) {
126+
throw new Error('Sidebar tabs need to have an id conforming to the HTML id attribute specifications')
127+
}
128+
129+
if (!tab.tagName || typeof tab.tagName !== 'string') {
130+
throw new Error('Sidebar tabs need to have the tagName name set')
131+
}
132+
133+
if (!tab.tagName.match(/^[a-z][a-z0-9-_]+$/)) {
134+
throw new Error('Sidebar tabs tagName name is invalid')
135+
}
136+
137+
if (!tab.displayName || typeof tab.displayName !== 'string') {
138+
throw new Error('Sidebar tabs need to have a name set')
139+
}
140+
141+
if (typeof tab.iconSvgInline !== 'string' || !isSvg(tab.iconSvgInline)) {
142+
throw new Error('Sidebar tabs need to have an valid SVG icon')
143+
}
144+
145+
if (typeof tab.order !== 'number') {
146+
throw new Error('Sidebar tabs need to have a numeric order set')
147+
}
148+
149+
if (typeof tab.enabled !== 'function') {
150+
throw new Error('Sidebar tabs need to have an "enabled" method')
151+
}
152+
153+
// now check the custom element constructor
154+
const tagConstructor = window.customElements.get(tab.tagName)
155+
if (!tagConstructor) {
156+
throw new Error('Sidebar tab element not registered')
157+
}
158+
159+
if (!('setActive' in tagConstructor.prototype)) {
160+
// we cannot check properties like `node` or `view` because those are not necessarily defined in the prototype.
161+
throw new Error('Sidebar tab elements must have the `setActive` method')
162+
}
163+
}

lib/window.d.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,8 @@ import type {
1313
NewMenu,
1414
} from './index.ts'
1515

16-
import type {
17-
DavProperty,
18-
} from './dav/index.ts'
16+
import type { DavProperty } from './dav/index.ts'
17+
import type { ISidebarTab } from './sidebar/index.ts'
1918

2019
export {}
2120

@@ -30,6 +29,7 @@ declare global {
3029
_nc_newfilemenu?: NewMenu
3130
_nc_navigation?: Navigation
3231
_nc_filelist_filters?: Map<string, IFileListFilter>
32+
_nc_files_sidebar_tabs?: Map<string, ISidebarTab>
3333

3434
_oc_config?: {
3535
forbidden_filenames_characters: string[]

0 commit comments

Comments
 (0)