@noy4/docserve 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/bin.mjs +2 -2
  2. package/dist/widget/index.js +11155 -0
  3. package/package.json +24 -3
  4. package/src/node/adapter.mjs +67 -0
  5. package/src/node/assets.mjs +36 -0
  6. package/src/node/dates.mjs +73 -0
  7. package/src/node/docs-info.mjs +39 -0
  8. package/src/node/files.mjs +43 -0
  9. package/src/node/gallery.mjs +33 -0
  10. package/src/node/inject.mjs +43 -0
  11. package/src/node/meta.mjs +137 -0
  12. package/src/node/routes.mjs +105 -0
  13. package/src/node/scan.mjs +87 -0
  14. package/src/node/serve-static.mjs +158 -0
  15. package/src/node/server.mjs +69 -0
  16. package/src/node/watch.mjs +119 -0
  17. package/src/plugins/copy/client.js +72 -0
  18. package/src/plugins/copy/copy.css +21 -0
  19. package/src/plugins/home/client.js +24 -0
  20. package/src/plugins/sidebar/client.js +105 -0
  21. package/src/plugins/sidebar/grouping.js +108 -0
  22. package/src/plugins/sidebar/icons.js +25 -0
  23. package/src/plugins/sidebar/model.ts +91 -0
  24. package/src/plugins/sidebar/resize-model.ts +47 -0
  25. package/src/plugins/sidebar/sidebar.css +663 -0
  26. package/src/plugins/sidebar/tree-model.ts +23 -0
  27. package/src/plugins/sidebar/tree.ts +69 -0
  28. package/src/plugins/sidebar/ui/PageList.tsx +153 -0
  29. package/src/plugins/sidebar/ui/RadioMenu.tsx +201 -0
  30. package/src/plugins/sidebar/ui/Sidebar.tsx +95 -0
  31. package/src/plugins/sidebar/ui/SidebarHeader.tsx +87 -0
  32. package/src/plugins/sidebar/ui/TreeList.tsx +121 -0
  33. package/src/plugins/sidebar/ui/preview-model.ts +134 -0
  34. package/src/plugins/sidebar/ui/useModel.ts +25 -0
  35. package/src/shared/types.d.ts +193 -0
  36. package/src/widget/commands.js +214 -0
  37. package/src/widget/docks.js +127 -0
  38. package/src/widget/host.js +187 -0
  39. package/src/widget/index.js +14 -0
  40. package/src/widget/lib/disposables.js +44 -0
  41. package/src/widget/lib/dom.js +106 -0
  42. package/src/widget/lib/events.js +65 -0
  43. package/src/widget/lib/persisted-signal.js +40 -0
  44. package/src/widget/lib/storage.js +70 -0
  45. package/src/widget/live.js +86 -0
  46. package/src/widget/pages.js +65 -0
  47. package/src/widget/palette.css +162 -0
  48. package/src/widget/palette.js +259 -0
  49. package/src/widget/placement.js +204 -0
  50. package/src/widget/plugins.js +39 -0
  51. package/src/widget/rpc.js +32 -0
  52. package/src/widget/styles.js +31 -0
  53. package/src/widget/ui.js +50 -0
  54. package/src/widget/widget.css +193 -0
  55. package/server/files.mjs +0 -261
  56. package/server/index.mjs +0 -198
  57. package/server/inject.html +0 -88
  58. package/server/inject.mjs +0 -28
  59. package/server/watch.mjs +0 -104
  60. /package/{server → src/node}/state.mjs +0 -0
  61. /package/{server → src/node}/websocket.mjs +0 -0
@@ -0,0 +1,87 @@
1
+ // Document discovery and the path guards every other node module shares.
2
+ import { realpathSync } from "node:fs"
3
+ import { readdir } from "node:fs/promises"
4
+ import { isAbsolute, join, relative, sep } from "node:path"
5
+
6
+ // Walk docsDir recursively and collect .html files; only the root index.html is
7
+ // excluded from the gallery.
8
+ const MAX_DEPTH = 3
9
+
10
+ /**
11
+ * @param {string} docsDir
12
+ * @returns {Promise<string[]>} absolute paths
13
+ */
14
+ export async function listHtmlFiles(docsDir) {
15
+ /** @type {string[]} */
16
+ const out = []
17
+ await walk(docsDir, docsDir, 0)
18
+ return out
19
+
20
+ /**
21
+ * @param {string} dir
22
+ * @param {string} root
23
+ * @param {number} depth
24
+ */
25
+ async function walk(dir, root, depth) {
26
+ if (depth > MAX_DEPTH) return
27
+ let entries
28
+ try {
29
+ entries = await readdir(dir, { withFileTypes: true })
30
+ } catch {
31
+ return
32
+ }
33
+ for (const entry of entries) {
34
+ const full = join(dir, entry.name)
35
+ if (shouldIgnore(entry.name)) continue
36
+ if (entry.isDirectory()) {
37
+ await walk(full, root, depth + 1)
38
+ } else if (entry.name.endsWith(".html") && !(dir === root && entry.name === "index.html")) {
39
+ out.push(full)
40
+ }
41
+ }
42
+ }
43
+ }
44
+
45
+ /**
46
+ * @param {string} base
47
+ * @param {string} path
48
+ * @returns {boolean}
49
+ */
50
+ export function isWithin(base, path) {
51
+ const rel = relative(base, path)
52
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
53
+ }
54
+
55
+ /**
56
+ * @param {string} base
57
+ * @param {string} path
58
+ * @returns {string}
59
+ */
60
+ export function normalizedRelative(base, path) {
61
+ return relative(base, path).split(sep).join("/")
62
+ }
63
+
64
+ /**
65
+ * @param {string} relPath
66
+ * @returns {boolean}
67
+ */
68
+ export function shouldIgnore(relPath) {
69
+ return relPath
70
+ .split(/[/\\]/)
71
+ .filter(Boolean)
72
+ .some((part) => part.startsWith(".") || part === "node_modules")
73
+ }
74
+
75
+ // On macOS /var is a symlink to /private/var; canonicalize to real paths so
76
+ // lookups match git output.
77
+ /**
78
+ * @param {string} p
79
+ * @returns {string}
80
+ */
81
+ export function realpath(p) {
82
+ try {
83
+ return realpathSync(p)
84
+ } catch {
85
+ return p
86
+ }
87
+ }
@@ -0,0 +1,158 @@
1
+ // Static file serving shared by the docs root, the widget tree and the plugin
2
+ // tree: one containment check, one MIME table, streaming bodies.
3
+ //
4
+ // Path flow: decode once → resolve inside root → canonical (realpath) check →
5
+ // directory index → 301 for a directory without its trailing slash.
6
+ import { createReadStream } from "node:fs"
7
+ import { readFile, realpath, stat } from "node:fs/promises"
8
+ import { extname, resolve, sep } from "node:path"
9
+ import { Readable } from "node:stream"
10
+ import { isWithin, normalizedRelative } from "./scan.mjs"
11
+
12
+ export const MIME = {
13
+ ".html": "text/html",
14
+ ".htm": "text/html",
15
+ ".js": "text/javascript",
16
+ ".mjs": "text/javascript",
17
+ ".css": "text/css",
18
+ ".json": "application/json",
19
+ ".txt": "text/plain",
20
+ ".md": "text/markdown",
21
+ ".xml": "application/xml",
22
+ ".png": "image/png",
23
+ ".jpg": "image/jpeg",
24
+ ".jpeg": "image/jpeg",
25
+ ".gif": "image/gif",
26
+ ".svg": "image/svg+xml",
27
+ ".webp": "image/webp",
28
+ ".ico": "image/x-icon",
29
+ ".pdf": "application/pdf",
30
+ ".woff": "font/woff",
31
+ ".woff2": "font/woff2",
32
+ ".mp4": "video/mp4",
33
+ ".webm": "video/webm",
34
+ }
35
+
36
+ /**
37
+ * @param {string} path
38
+ * @returns {string}
39
+ */
40
+ export function contentTypeFor(path) {
41
+ const type = MIME[extname(path).toLowerCase()] || "application/octet-stream"
42
+ return type === "text/html" ? "text/html; charset=utf-8" : type
43
+ }
44
+
45
+ /**
46
+ * @typedef {object} StaticHandlerOptions
47
+ * @property {string} root Directory files are served from.
48
+ * @property {string[]} [indexNames] Directory index candidates.
49
+ * @property {Record<string, string>} [headers] Extra response headers.
50
+ * @property {(body: string, relative: string) => string} [transform] HTML rewrite.
51
+ */
52
+
53
+ /**
54
+ * Returns a handler that maps a Request to a Response, or null on a miss so a
55
+ * router can fall through to its own 404.
56
+ * @param {StaticHandlerOptions} options
57
+ * @returns {(request: Request) => Promise<Response | null>}
58
+ */
59
+ export function createStaticHandler({ root: rootDir, indexNames = ["index.html"], headers = {}, transform }) {
60
+ const root = resolve(rootDir)
61
+ const realRoot = realpath(root).catch(() => root)
62
+
63
+ return async function serve(request) {
64
+ const method = request.method || "GET"
65
+ if (method !== "GET" && method !== "HEAD") return plain("Method Not Allowed", 405)
66
+
67
+ const url = new URL(request.url)
68
+ let pathname
69
+ try {
70
+ pathname = decodeURIComponent(url.pathname)
71
+ } catch {
72
+ return plain("Bad Request", 400)
73
+ }
74
+ if (pathname.includes("\0")) return plain("Bad Request", 400)
75
+
76
+ const abs = resolve(root, pathname.replace(/^\/+/, ""))
77
+ if (!isWithin(root, abs)) return plain("Forbidden", 403)
78
+
79
+ const real = await realRoot
80
+ const hasSlash = pathname.endsWith("/")
81
+ let file = await statFile(abs, real)
82
+
83
+ if (!file) {
84
+ const isDir = await isDirectory(abs)
85
+ // /sub → /sub/ so relative links in index.html resolve; /sub/ serves it.
86
+ if (isDir && !hasSlash) return redirect(url)
87
+ if (isDir || hasSlash) {
88
+ for (const name of indexNames) {
89
+ file = await statFile(resolve(abs, name), real)
90
+ if (file) break
91
+ }
92
+ }
93
+ if (!file) return null
94
+ }
95
+
96
+ const responseHeaders = new Headers(headers)
97
+ responseHeaders.set("content-type", contentTypeFor(file.abs))
98
+ responseHeaders.set("content-length", String(file.size))
99
+ responseHeaders.set("last-modified", file.mtime.toUTCString())
100
+ if (method === "HEAD") return new Response(null, { status: 200, headers: responseHeaders })
101
+
102
+ const type = responseHeaders.get("content-type") || ""
103
+ if (transform && type.startsWith("text/html")) {
104
+ const html = transform(await readFile(file.abs, "utf8"), normalizedRelative(root, file.abs))
105
+ responseHeaders.set("content-length", String(Buffer.byteLength(html)))
106
+ return new Response(html, { status: 200, headers: responseHeaders })
107
+ }
108
+
109
+ return new Response(Readable.toWeb(createReadStream(file.abs)), { status: 200, headers: responseHeaders })
110
+ }
111
+ }
112
+
113
+ /**
114
+ * @param {string} abs
115
+ * @param {string} realRoot
116
+ * @returns {Promise<{ abs: string, size: number, mtime: Date } | null>}
117
+ */
118
+ async function statFile(abs, realRoot) {
119
+ try {
120
+ const s = await stat(abs)
121
+ if (!s.isFile()) return null
122
+ const real = await realpath(abs)
123
+ if (real !== realRoot && !real.startsWith(realRoot + sep)) return null
124
+ return { abs, size: s.size, mtime: s.mtime }
125
+ } catch {
126
+ return null
127
+ }
128
+ }
129
+
130
+ /**
131
+ * @param {string} abs
132
+ * @returns {Promise<boolean>}
133
+ */
134
+ async function isDirectory(abs) {
135
+ try {
136
+ return (await stat(abs)).isDirectory()
137
+ } catch {
138
+ return false
139
+ }
140
+ }
141
+
142
+ /**
143
+ * @param {URL} url
144
+ * @returns {Response}
145
+ */
146
+ function redirect(url) {
147
+ const location = new URL(`${url.pathname}/${url.search}`, url)
148
+ return new Response(null, { status: 301, headers: { location: location.href } })
149
+ }
150
+
151
+ /**
152
+ * @param {string} body
153
+ * @param {number} status
154
+ * @returns {Response}
155
+ */
156
+ function plain(body, status) {
157
+ return new Response(body, { status, headers: { "content-type": "text/plain; charset=utf-8" } })
158
+ }
@@ -0,0 +1,69 @@
1
+ // Server lifecycle: bind with port fallback, wire the watcher and socket, and
2
+ // write the state file the CLI and desktop app read.
3
+ //
4
+ // ┌──────────────────────────────────────────────────────────┐
5
+ // │ runServer() │
6
+ // │ ├─ createServer ──▶ adapter(createHandler()) │
7
+ // │ ├─ WebSocketServer("/__reload") ◀─ FileWatcher │
8
+ // │ └─ listen ──▶ watcher.start() + writeState() │
9
+ // └──────────────────────────────────────────────────────────┘
10
+ import { exec } from "node:child_process"
11
+ import { createServer } from "node:http"
12
+ import { createNodeServerAdapter } from "./adapter.mjs"
13
+ import { INDEX_TEMPLATE } from "./gallery.mjs"
14
+ import { createHandler } from "./routes.mjs"
15
+ import { clearState, writeState } from "./state.mjs"
16
+ import { FileWatcher } from "./watch.mjs"
17
+ import { WebSocketServer } from "./websocket.mjs"
18
+ import { WS_PATH } from "./inject.mjs"
19
+
20
+ const MAX_PORT_TRIES = 20 // on conflict, try the next port up to 20 times
21
+
22
+ /**
23
+ * @param {{ docsDir: string, port: number, open?: boolean }} options
24
+ */
25
+ export async function runServer({ docsDir, port: initialPort, open = false }) {
26
+ const wss = new WebSocketServer({ path: WS_PATH })
27
+ const fileWatcher = new FileWatcher({ wss, docsDir, templatePath: INDEX_TEMPLATE })
28
+ let port = initialPort
29
+ let closed = false
30
+
31
+ const server = createServer(createNodeServerAdapter(createHandler({ docsDir })))
32
+ wss.attach(server)
33
+
34
+ const close = () => {
35
+ if (closed) return
36
+ closed = true
37
+ process.off("SIGINT", onSignal)
38
+ process.off("SIGTERM", onSignal)
39
+ fileWatcher.close()
40
+ wss.close()
41
+ clearState()
42
+ server.closeAllConnections()
43
+ if (server.listening) server.close()
44
+ }
45
+ const onSignal = () => {
46
+ close()
47
+ process.exit(0)
48
+ }
49
+ process.on("SIGINT", onSignal)
50
+ process.on("SIGTERM", onSignal)
51
+
52
+ server.on("error", (/** @type {NodeJS.ErrnoException} */ err) => {
53
+ if (err.code === "EADDRINUSE" && port < initialPort + MAX_PORT_TRIES) {
54
+ port += 1
55
+ server.listen(port, "127.0.0.1")
56
+ } else {
57
+ console.error(err)
58
+ process.exit(1)
59
+ }
60
+ })
61
+ server.listen(port, "127.0.0.1", async () => {
62
+ await fileWatcher.start()
63
+ const state = { pid: process.pid, port, url: `http://localhost:${port}/`, docsDir }
64
+ writeState(state)
65
+ console.log(state.url)
66
+ if (open && process.platform === "darwin") exec(`open ${state.url}`)
67
+ })
68
+ return { server, wss, fileWatcher, close }
69
+ }
@@ -0,0 +1,119 @@
1
+ // Watches docsDir for *.html / *.css and the gallery template, broadcasting
2
+ // debounced reload batches. The gallery set is every *.html except index.html;
3
+ // only additions/removals flip contentSetChanged.
4
+ import { existsSync, watch } from "node:fs"
5
+ import { basename, dirname, resolve } from "node:path"
6
+ import { isWithin, listHtmlFiles, normalizedRelative, shouldIgnore } from "./scan.mjs"
7
+
8
+ const DEBOUNCE_MS = 50
9
+
10
+ export class FileWatcher {
11
+ constructor(options = {}) {
12
+ this.wss = options.wss
13
+ this.docsDir = options.docsDir
14
+ this.templatePath = options.templatePath
15
+ this.debounceMs = options.debounceMs ?? DEBOUNCE_MS
16
+ this.knownFiles = new Set()
17
+ this.queue = Promise.resolve()
18
+ this.watchers = []
19
+ this.pending = { pages: new Set(), css: new Set(), template: false }
20
+
21
+ // html/css/template edits in one burst flush together
22
+ this.queueFlush = debounce(() => {
23
+ const { pages, css, template } = this.pending
24
+ this.pending = { pages: new Set(), css: new Set(), template: false }
25
+ if (pages.size || template) {
26
+ this.enqueue(() => this.broadcastChanges({ pages: [...pages], template }))
27
+ }
28
+ if (css.size)
29
+ this.enqueue(() => this.broadcastCss([...css]))
30
+ }, this.debounceMs)
31
+ }
32
+
33
+ enqueue(task) {
34
+ this.queue = this.queue.then(task)
35
+ .catch((error) => console.error(error))
36
+ }
37
+
38
+ async start() {
39
+ try {
40
+ this.knownFiles = new Set(
41
+ (await listHtmlFiles(this.docsDir)).map((p) => normalizedRelative(this.docsDir, p)),
42
+ )
43
+ } catch {
44
+ this.knownFiles = new Set()
45
+ }
46
+
47
+ this.watchers.push(
48
+ watch(this.docsDir, { recursive: true }, (event, filename) => {
49
+ if (!filename || shouldIgnore(filename)) return
50
+ const full = resolve(this.docsDir, filename)
51
+ if (!isWithin(this.docsDir, full)) return
52
+ const rel = normalizedRelative(this.docsDir, full)
53
+
54
+ if (filename.endsWith(".html")) {
55
+ this.pending.pages.add(rel)
56
+ this.queueFlush()
57
+ } else if (filename.endsWith(".css")) {
58
+ this.pending.css.add(rel)
59
+ this.queueFlush()
60
+ }
61
+ }).on("error", () => { }),
62
+ )
63
+
64
+ if (this.templatePath) {
65
+ // Watch the directory
66
+ const templateName = basename(this.templatePath)
67
+ this.watchers.push(
68
+ watch(dirname(this.templatePath), (event, filename) => {
69
+ if (filename === templateName) {
70
+ this.pending.template = true
71
+ this.queueFlush()
72
+ }
73
+ }).on("error", () => { }),
74
+ )
75
+ }
76
+ }
77
+
78
+ async broadcastChanges({ pages, template }) {
79
+ this.wss.broadcast({
80
+ type: "change",
81
+ pages,
82
+ contentSetChanged: syncKnownFiles(this.knownFiles, this.docsDir, pages),
83
+ templateChanged: template,
84
+ })
85
+ }
86
+
87
+ // Refresh linked stylesheets in place.
88
+ broadcastCss(files) {
89
+ this.wss.broadcast({ type: "css", files })
90
+ }
91
+
92
+ close() {
93
+ this.watchers.forEach((w) => w.close())
94
+ }
95
+ }
96
+
97
+ // True when pages were added to or removed from the gallery.
98
+ function syncKnownFiles(knownFiles, docsDir, pages) {
99
+ let changed = false
100
+ for (const rel of pages) {
101
+ if (basename(rel) === "index.html") continue // not a gallery card
102
+ const exists = existsSync(resolve(docsDir, rel))
103
+ const wasKnown = knownFiles.has(rel)
104
+ if (exists === wasKnown) continue
105
+ if (exists) knownFiles.add(rel)
106
+ else knownFiles.delete(rel)
107
+ changed = true
108
+ }
109
+ return changed
110
+ }
111
+
112
+ // Trailing-edge debounce.
113
+ function debounce(fn, ms) {
114
+ let timer = null
115
+ return () => {
116
+ clearTimeout(timer)
117
+ timer = setTimeout(fn, ms)
118
+ }
119
+ }
@@ -0,0 +1,72 @@
1
+ // Dock action: copy the current page's absolute path.
2
+ import ICON_CHECK_RAW from "~icons/lucide/check?raw&width=18&height=18"
3
+ import ICON_COPY_RAW from "~icons/lucide/copy?raw&width=18&height=18"
4
+ import { iconSvg, writeClipboard } from "../../widget/lib/dom.js"
5
+
6
+ const ICON_COPY = iconSvg(ICON_COPY_RAW, "docserve-icon-copy")
7
+ const ICON_CHECK = iconSvg(ICON_CHECK_RAW, "docserve-icon-check")
8
+
9
+ /**
10
+ * @returns {DocservePlugin}
11
+ */
12
+ export function copyPlugin() {
13
+ return {
14
+ id: "copy",
15
+ setup(ctx) {
16
+ /** @type {ReturnType<typeof setTimeout> | null} */
17
+ let resetTimer = null
18
+
19
+ ctx.ui.style("/__docserve/plugins/copy/copy.css")
20
+
21
+ const offCopy = ctx.commands.register({
22
+ id: "plugin:copy:path",
23
+ title: "Copy file path",
24
+ description: "Absolute path of this page",
25
+ category: "Actions",
26
+ icon: ICON_COPY,
27
+ keys: ["c"],
28
+ run: copyPath,
29
+ })
30
+
31
+ const dock = ctx.docks.register({
32
+ id: "copy",
33
+ title: "Copy file path",
34
+ icon: ICON_COPY + ICON_CHECK,
35
+ category: "actions",
36
+ command: "plugin:copy:path",
37
+ })
38
+
39
+ return () => {
40
+ offCopy()
41
+ if (resetTimer) clearTimeout(resetTimer)
42
+ dock.dispose()
43
+ }
44
+
45
+ async function copyPath() {
46
+ const file = /** @type {DocPage | null} */ (await ctx.rpc.call("docserve:pages:resolve", ctx.page))
47
+ const text = file?.filePath ?? location.href
48
+ try {
49
+ await writeClipboard(text)
50
+ flash("copied")
51
+ ctx.ui.announce("File path copied")
52
+ } catch {
53
+ ctx.ui.announce("Copy failed")
54
+ }
55
+ }
56
+
57
+ /**
58
+ * @param {"copied" | ""} state
59
+ */
60
+ function flash(state) {
61
+ const element = dock.element
62
+ if (!element) return
63
+ element.dataset.state = state
64
+ if (resetTimer) clearTimeout(resetTimer)
65
+ resetTimer = setTimeout(() => {
66
+ element.dataset.state = ""
67
+ resetTimer = null
68
+ }, 1200)
69
+ }
70
+ },
71
+ }
72
+ }
@@ -0,0 +1,21 @@
1
+ .docserve-dock__button .docserve-icon-check {
2
+ display: none;
3
+ }
4
+
5
+ .docserve-dock__button[data-state="copied"] {
6
+ color: #16a34a;
7
+ }
8
+
9
+ .docserve-dock__button[data-state="copied"] .docserve-icon-copy {
10
+ display: none;
11
+ }
12
+
13
+ .docserve-dock__button[data-state="copied"] .docserve-icon-check {
14
+ display: block;
15
+ }
16
+
17
+ @media (prefers-color-scheme: dark) {
18
+ .docserve-dock__button[data-state="copied"] {
19
+ color: #4ade80;
20
+ }
21
+ }
@@ -0,0 +1,24 @@
1
+ // Dock link back to the gallery.
2
+ import { iconSvg } from "../../widget/lib/dom.js"
3
+ import ICON_HOME_RAW from "~icons/lucide/house?raw&width=18&height=18"
4
+
5
+ const ICON_HOME = iconSvg(ICON_HOME_RAW)
6
+
7
+ /**
8
+ * @returns {DocservePlugin}
9
+ */
10
+ export function homePlugin() {
11
+ return {
12
+ id: "home",
13
+ setup(ctx) {
14
+ const dock = ctx.docks.register({
15
+ id: "home",
16
+ title: "Back to gallery",
17
+ icon: ICON_HOME,
18
+ href: "/",
19
+ category: "actions",
20
+ })
21
+ return () => dock.dispose()
22
+ },
23
+ }
24
+ }
@@ -0,0 +1,105 @@
1
+ // Dock toggle plus a left panel that lists every page, as rows or preview cards.
2
+ import { createElement } from "react"
3
+ import { createRoot } from "react-dom/client"
4
+ import { createDisposables } from "../../widget/lib/disposables.js"
5
+ import { ICON_CALENDAR, ICON_GRID, ICON_SIDEBAR } from "./icons.js"
6
+ import { SidebarModel } from "./model.js"
7
+ import { Sidebar } from "./ui/Sidebar.js"
8
+
9
+ /**
10
+ * @returns {DocservePlugin}
11
+ */
12
+ export function sidebarPlugin() {
13
+ return {
14
+ id: "sidebar",
15
+ setup(ctx) {
16
+ // state
17
+ const model = SidebarModel.fromContext(ctx)
18
+ // styles
19
+ ctx.ui.style("/__docserve/plugins/sidebar/sidebar.css")
20
+ // cleanup
21
+ const cleanup = createDisposables()
22
+
23
+ // mount
24
+ const host = ctx.ui.mountPoint()
25
+ const root = createRoot(host)
26
+ cleanup.add(() => {
27
+ root.unmount()
28
+ host.remove()
29
+ })
30
+ root.render(createElement(Sidebar, { model }))
31
+
32
+ // commands
33
+ registerCommands(ctx, model, cleanup)
34
+
35
+ // dock
36
+ const dock = ctx.docks.register({
37
+ id: "sidebar",
38
+ title: "Toggle sidebar",
39
+ icon: ICON_SIDEBAR,
40
+ category: "main",
41
+ command: "plugin:sidebar:toggle",
42
+ isActive: () => model.open.value,
43
+ })
44
+ cleanup.add(() => dock.dispose())
45
+ cleanup.add(model.open.subscribe(() => dock.update()))
46
+
47
+ // events
48
+ cleanup.add(ctx.events.on("pages:changed", (change) => {
49
+ if (change.pages.length || change.contentSetChanged)
50
+ model.load({ force: true })
51
+ }))
52
+ cleanup.add(ctx.events.on("live:connected", () => model.load({ force: true })))
53
+
54
+ model.load()
55
+
56
+ return cleanup.dispose
57
+ },
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Register every sidebar command; each one is unregistered by `cleanup`.
63
+ * @param {DocserveContext} ctx
64
+ * @param {SidebarModel} model
65
+ * @param {import("../../widget/lib/disposables.js").Disposables} cleanup
66
+ */
67
+ function registerCommands(ctx, model, cleanup) {
68
+ cleanup.add(ctx.commands.register({
69
+ id: "plugin:sidebar:toggle",
70
+ title: "Toggle sidebar",
71
+ category: "View",
72
+ icon: ICON_SIDEBAR,
73
+ keys: ["[", "Alt+B"],
74
+ run: () => model.setOpen(!model.open.value),
75
+ }))
76
+
77
+ cleanup.add(ctx.commands.register({
78
+ id: "plugin:sidebar:close",
79
+ title: "Close sidebar",
80
+ keys: ["Escape"],
81
+ showInPalette: false,
82
+ when: () => model.open.value,
83
+ run: () => model.setOpen(false),
84
+ }))
85
+
86
+ cleanup.add(ctx.commands.register({
87
+ id: "plugin:sidebar:view",
88
+ title: "Toggle sidebar view",
89
+ category: "View",
90
+ icon: ICON_GRID,
91
+ keys: ["v"],
92
+ when: () => model.open.value,
93
+ run: () => model.toggleView(),
94
+ }))
95
+
96
+ cleanup.add(ctx.commands.register({
97
+ id: "plugin:sidebar:grouping",
98
+ title: "Cycle sidebar grouping",
99
+ category: "View",
100
+ icon: ICON_CALENDAR,
101
+ keys: ["m"],
102
+ when: () => model.open.value && model.view.value !== "tree",
103
+ run: () => model.toggleGrouping(),
104
+ }))
105
+ }