Skip to content

Commit 55f8b56

Browse files
committed
feat(sidebar): provide public API to register a sidebar tab
This replaces the legacy `OCA.Files.Sidebar`. It also allows to define the order of the tab to prevent diffent order depending on the localized name like with the legacy tabs. Signed-off-by: Ferdinand Thiessen <opensource@fthiessen.de>
1 parent 287421e commit 55f8b56

7 files changed

Lines changed: 322 additions & 3 deletions

File tree

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

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/navigation/view.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,8 @@ interface ViewData {
9797
loadChildViews?: (view: View) => Promise<void>
9898
}
9999

100+
export type IView = ViewData
101+
100102
export class View implements ViewData {
101103

102104
private _view: ViewData

lib/sidebar/index.ts

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
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 type SidebarComponent = HTMLElement & ISidebarContext
36+
37+
/**
38+
* Implementation of a custom sidebar tab within the files app.
39+
*/
40+
export interface ISidebarTab {
41+
/**
42+
* Unique id of the sidebar tab.
43+
* This has to conform to the HTML id attribute specification.
44+
*/
45+
id: string
46+
47+
/**
48+
* The localized name of the sidebar tab.
49+
*/
50+
displayName: string
51+
52+
/**
53+
* The icon, as SVG, of the sidebar tab.
54+
*/
55+
iconSvg: string
56+
57+
/**
58+
* The order of this tab.
59+
* Use a low number to make this tab ordered in front.
60+
*/
61+
order: number
62+
63+
/**
64+
* Name of the web component as used to register it.
65+
* The web component must already be defined with `CustomElementRegistry.define()`.
66+
*
67+
* To avoid name clashes the name has to start with your appid (e.g. `your_app`).
68+
* So in addition with the web component naming rules a good name would be `your_app-files-sidebar-tab`.
69+
*/
70+
component: string
71+
72+
/**
73+
* Callback to check if the sidebar tab should be shown for the selected node.
74+
*
75+
* @param context - The current context of the files app
76+
*/
77+
enabled: (context: ISidebarContext) => boolean
78+
79+
/**
80+
* Called by the files app if this tab has become the active tab or was deactivated.
81+
*
82+
* @param active - The new active state of this tab
83+
*/
84+
setActive: (active: boolean) => Promise<void>
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.component || typeof tab.component !== 'string') {
130+
throw new Error('Sidebar tabs need to have the component name set')
131+
}
132+
133+
if (!tab.component.match(/^[a-z][a-z0-9-_]+$/) || !tab.component.includes('-')) {
134+
throw new Error('Sidebar tabs component 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.iconSvg !== 'string' || !isSvg(tab.iconSvg)) {
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+
if (typeof tab.setActive !== 'function') {
154+
throw new Error('Sidebar tabs need to have a "setActive" method')
155+
}
156+
}

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[]

package-lock.json

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
"@nextcloud/vite-config": "^2.5.2",
7474
"@types/node": "^25.0.0",
7575
"@vitest/coverage-istanbul": "^4.0.15",
76+
"css.escape": "^1.5.1",
7677
"fast-xml-parser": "^5.3.2",
7778
"jsdom": "^27.3.0",
7879
"tslib": "^2.8.1",

0 commit comments

Comments
 (0)