@noy4/docserve 0.3.1 → 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.
- package/bin.mjs +2 -2
- package/dist/widget/index.js +11155 -0
- package/package.json +24 -3
- package/src/node/adapter.mjs +67 -0
- package/src/node/assets.mjs +36 -0
- package/src/node/dates.mjs +73 -0
- package/src/node/docs-info.mjs +39 -0
- package/src/node/files.mjs +43 -0
- package/src/node/gallery.mjs +33 -0
- package/src/node/inject.mjs +43 -0
- package/src/node/meta.mjs +137 -0
- package/src/node/routes.mjs +105 -0
- package/src/node/scan.mjs +87 -0
- package/src/node/serve-static.mjs +158 -0
- package/src/node/server.mjs +69 -0
- package/src/node/watch.mjs +119 -0
- package/src/plugins/copy/client.js +72 -0
- package/src/plugins/copy/copy.css +21 -0
- package/src/plugins/home/client.js +24 -0
- package/src/plugins/sidebar/client.js +105 -0
- package/src/plugins/sidebar/grouping.js +108 -0
- package/src/plugins/sidebar/icons.js +25 -0
- package/src/plugins/sidebar/model.ts +91 -0
- package/src/plugins/sidebar/resize-model.ts +47 -0
- package/src/plugins/sidebar/sidebar.css +663 -0
- package/src/plugins/sidebar/tree-model.ts +23 -0
- package/src/plugins/sidebar/tree.ts +69 -0
- package/src/plugins/sidebar/ui/PageList.tsx +153 -0
- package/src/plugins/sidebar/ui/RadioMenu.tsx +201 -0
- package/src/plugins/sidebar/ui/Sidebar.tsx +95 -0
- package/src/plugins/sidebar/ui/SidebarHeader.tsx +87 -0
- package/src/plugins/sidebar/ui/TreeList.tsx +121 -0
- package/src/plugins/sidebar/ui/preview-model.ts +134 -0
- package/src/plugins/sidebar/ui/useModel.ts +25 -0
- package/src/shared/types.d.ts +193 -0
- package/src/widget/commands.js +214 -0
- package/src/widget/docks.js +127 -0
- package/src/widget/host.js +187 -0
- package/src/widget/index.js +14 -0
- package/src/widget/lib/disposables.js +44 -0
- package/src/widget/lib/dom.js +106 -0
- package/src/widget/lib/events.js +65 -0
- package/src/widget/lib/persisted-signal.js +40 -0
- package/src/widget/lib/storage.js +70 -0
- package/src/widget/live.js +86 -0
- package/src/widget/pages.js +65 -0
- package/src/widget/palette.css +162 -0
- package/src/widget/palette.js +259 -0
- package/src/widget/placement.js +204 -0
- package/src/widget/plugins.js +39 -0
- package/src/widget/rpc.js +32 -0
- package/src/widget/styles.js +31 -0
- package/src/widget/ui.js +50 -0
- package/src/widget/widget.css +193 -0
- package/server/files.mjs +0 -233
- package/server/index.mjs +0 -189
- package/server/inject.html +0 -88
- package/server/inject.mjs +0 -28
- package/server/watch.mjs +0 -104
- /package/{server → src/node}/state.mjs +0 -0
- /package/{server → src/node}/websocket.mjs +0 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// The docks registry: one pill that every plugin registers items on. An item
|
|
2
|
+
// either runs a command or is a link.
|
|
3
|
+
import { formatKey } from "./commands.js"
|
|
4
|
+
import { el } from "./lib/dom.js"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Build the dock and mount it into the shadow root.
|
|
8
|
+
* @param {object} options
|
|
9
|
+
* @param {ShadowRoot} options.root
|
|
10
|
+
* @param {() => DocserveContext} options.getContext Resolved when an item is clicked.
|
|
11
|
+
* @returns {DocksContext}
|
|
12
|
+
*/
|
|
13
|
+
export function createDocks({ root, getContext }) {
|
|
14
|
+
/** @type {DockItem[]} */
|
|
15
|
+
const items = []
|
|
16
|
+
const element = el("div", { class: "docserve-dock", role: "toolbar", "aria-label": "docserve" })
|
|
17
|
+
/** @type {Map<string, DocksItemHandle>} */
|
|
18
|
+
const handles = new Map()
|
|
19
|
+
|
|
20
|
+
root.append(element)
|
|
21
|
+
render()
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
element,
|
|
25
|
+
register,
|
|
26
|
+
remove,
|
|
27
|
+
items() {
|
|
28
|
+
return [...items]
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {DockItem} item
|
|
34
|
+
* @returns {DocksItemHandle}
|
|
35
|
+
*/
|
|
36
|
+
function register(item) {
|
|
37
|
+
if (typeof item?.id !== "string" || !item.id) throw new TypeError("docks.register expects an item with an id")
|
|
38
|
+
if (handles.has(item.id)) throw new Error(`dock item already added: ${item.id}`)
|
|
39
|
+
if (!item.command === !item.href) throw new TypeError(`dock item ${item.id} needs exactly one of command or href`)
|
|
40
|
+
|
|
41
|
+
const handle = {
|
|
42
|
+
/** @type {HTMLElement | null} */
|
|
43
|
+
element: null,
|
|
44
|
+
update() {
|
|
45
|
+
syncDockItem(handle.element, item)
|
|
46
|
+
},
|
|
47
|
+
dispose() {
|
|
48
|
+
remove(item.id)
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
handles.set(item.id, handle)
|
|
52
|
+
items.push(item)
|
|
53
|
+
render()
|
|
54
|
+
return handle
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @param {string} id
|
|
59
|
+
*/
|
|
60
|
+
function remove(id) {
|
|
61
|
+
const index = items.findIndex((item) => item.id === id)
|
|
62
|
+
if (index === -1) return
|
|
63
|
+
items.splice(index, 1)
|
|
64
|
+
handles.delete(id)
|
|
65
|
+
render()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function render() {
|
|
69
|
+
element.replaceChildren()
|
|
70
|
+
let previousCategory
|
|
71
|
+
let first = true
|
|
72
|
+
|
|
73
|
+
for (const item of sorted()) {
|
|
74
|
+
if (!first && item.category != null && previousCategory != null && item.category !== previousCategory)
|
|
75
|
+
element.append(el("span", { class: "docserve-dock__divider", "aria-hidden": "true" }))
|
|
76
|
+
first = false
|
|
77
|
+
previousCategory = item.category
|
|
78
|
+
|
|
79
|
+
const node = createDockItem(item, getContext())
|
|
80
|
+
const handle = handles.get(item.id)
|
|
81
|
+
if (handle) handle.element = node
|
|
82
|
+
element.append(node)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function sorted() {
|
|
87
|
+
return [...items].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Build one dock item: a command button, or a link when `href` is set.
|
|
93
|
+
* @param {DockItem} item
|
|
94
|
+
* @param {DocserveContext} ctx
|
|
95
|
+
* @returns {HTMLElement}
|
|
96
|
+
*/
|
|
97
|
+
function createDockItem(item, ctx) {
|
|
98
|
+
const keys = item.command ? ctx.commands.list().find((command) => command.id === item.command)?.keys ?? [] : []
|
|
99
|
+
const props = {
|
|
100
|
+
class: "docserve-dock__button",
|
|
101
|
+
title: keys.length ? `${item.title} (${keys.map(formatKey).join(" / ")})` : item.title,
|
|
102
|
+
"aria-label": item.title,
|
|
103
|
+
"data-action": item.id,
|
|
104
|
+
html: item.icon ?? "",
|
|
105
|
+
}
|
|
106
|
+
const node = item.href
|
|
107
|
+
? el("a", { ...props, href: item.href })
|
|
108
|
+
: el("button", { ...props, type: "button" })
|
|
109
|
+
|
|
110
|
+
syncDockItem(node, item)
|
|
111
|
+
if (!item.href) {
|
|
112
|
+
node.addEventListener("click", () => {
|
|
113
|
+
ctx.commands.run(/** @type {string} */ (item.command)).catch((error) => console.error(`[docserve] dock command failed: ${item.command}`, error))
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
return node
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Reflect `isActive` onto `aria-pressed`.
|
|
121
|
+
* @param {HTMLElement | null} node
|
|
122
|
+
* @param {DockItem} item
|
|
123
|
+
*/
|
|
124
|
+
function syncDockItem(node, item) {
|
|
125
|
+
if (!node || !item.isActive) return
|
|
126
|
+
node.setAttribute("aria-pressed", String(Boolean(item.isActive())))
|
|
127
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Widget host
|
|
2
|
+
import { createCommands } from "./commands.js"
|
|
3
|
+
import { createDocks } from "./docks.js"
|
|
4
|
+
import { el } from "./lib/dom.js"
|
|
5
|
+
import { createEventEmitter } from "./lib/events.js"
|
|
6
|
+
import { connectLive } from "./live.js"
|
|
7
|
+
import { createPages } from "./pages.js"
|
|
8
|
+
import { createPalette } from "./palette.js"
|
|
9
|
+
import { createPlacement } from "./placement.js"
|
|
10
|
+
import { createPlugins } from "./plugins.js"
|
|
11
|
+
import { createRpc } from "./rpc.js"
|
|
12
|
+
import { reloadStyles, settled } from "./styles.js"
|
|
13
|
+
import { createUi } from "./ui.js"
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Create the widget without mounting it.
|
|
17
|
+
* @returns {{ ctx: DocserveContext, start: () => DocserveContext, stop: () => void, use: (plugin: DocservePlugin) => DocserveContext }}
|
|
18
|
+
*/
|
|
19
|
+
export function createHost() {
|
|
20
|
+
const script = injectedScript()
|
|
21
|
+
const page = resolvePage(script)
|
|
22
|
+
const docs = resolveDocs(script)
|
|
23
|
+
|
|
24
|
+
// element
|
|
25
|
+
const { host, root, status, reveal } = mount()
|
|
26
|
+
|
|
27
|
+
// lifecycle state
|
|
28
|
+
/** @type {ReturnType<typeof connectLive> | null} */
|
|
29
|
+
let live = null
|
|
30
|
+
let mounted = false
|
|
31
|
+
|
|
32
|
+
// transport
|
|
33
|
+
const rpc = createRpc()
|
|
34
|
+
const pages = createPages({ rpc })
|
|
35
|
+
const events = createEventEmitter()
|
|
36
|
+
|
|
37
|
+
// context is filled below, services resolve it when called
|
|
38
|
+
const getContext = () => ctx
|
|
39
|
+
|
|
40
|
+
// commands
|
|
41
|
+
const commands = createCommands({ getContext })
|
|
42
|
+
|
|
43
|
+
// interface
|
|
44
|
+
const ui = createUi({ root, status })
|
|
45
|
+
const docks = createDocks({ root, getContext })
|
|
46
|
+
const placement = createPlacement({ host, handle: docks.element })
|
|
47
|
+
const palette = createPalette({
|
|
48
|
+
root,
|
|
49
|
+
ui,
|
|
50
|
+
commands: commands.api,
|
|
51
|
+
subscribe: commands.onChange,
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
// plugins
|
|
55
|
+
const { use, dispose } = createPlugins(getContext)
|
|
56
|
+
|
|
57
|
+
// context
|
|
58
|
+
/** @type {DocserveContext} */
|
|
59
|
+
const ctx = {
|
|
60
|
+
page,
|
|
61
|
+
docs,
|
|
62
|
+
rpc,
|
|
63
|
+
docks,
|
|
64
|
+
commands: commands.api,
|
|
65
|
+
ui,
|
|
66
|
+
events,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return { ctx, start, stop, use }
|
|
70
|
+
|
|
71
|
+
// ---
|
|
72
|
+
|
|
73
|
+
function start() {
|
|
74
|
+
if (mounted) return ctx
|
|
75
|
+
mounted = true
|
|
76
|
+
|
|
77
|
+
document.documentElement.toggleAttribute("data-docserve-widget", true)
|
|
78
|
+
document.body.append(host)
|
|
79
|
+
reveal()
|
|
80
|
+
events.emit("host:started")
|
|
81
|
+
|
|
82
|
+
live = connectLive({
|
|
83
|
+
onOpen() {
|
|
84
|
+
pages.invalidate()
|
|
85
|
+
events.emit("live:connected")
|
|
86
|
+
},
|
|
87
|
+
onMessage: onLiveMessage,
|
|
88
|
+
})
|
|
89
|
+
return ctx
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function stop() {
|
|
93
|
+
live?.close()
|
|
94
|
+
live = null
|
|
95
|
+
if (mounted) {
|
|
96
|
+
// reverse order
|
|
97
|
+
placement.destroy()
|
|
98
|
+
palette.destroy()
|
|
99
|
+
commands.destroy()
|
|
100
|
+
document.documentElement.toggleAttribute("data-docserve-widget", false)
|
|
101
|
+
host.toggleAttribute("data-ready", false)
|
|
102
|
+
host.remove()
|
|
103
|
+
mounted = false
|
|
104
|
+
}
|
|
105
|
+
dispose()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* @param {LiveMessage} message
|
|
110
|
+
*/
|
|
111
|
+
function onLiveMessage(message) {
|
|
112
|
+
switch (message.type) {
|
|
113
|
+
case "css":
|
|
114
|
+
reloadStyles([document, root])
|
|
115
|
+
return
|
|
116
|
+
case "change":
|
|
117
|
+
onContentChange(message)
|
|
118
|
+
return
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* @param {ChangeMessage} message
|
|
124
|
+
*/
|
|
125
|
+
function onContentChange(message) {
|
|
126
|
+
if (message.contentSetChanged || message.pages.length)
|
|
127
|
+
pages.invalidate()
|
|
128
|
+
events.emit("pages:changed", message)
|
|
129
|
+
|
|
130
|
+
// only reload when this page or the gallery template changed
|
|
131
|
+
if (message.pages.includes(page) || message.templateChanged)
|
|
132
|
+
location.reload()
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Inline `<style>` in the shadow root: keeps the host out of the layout and
|
|
137
|
+
// hidden until `reveal()` sets `data-ready`. The rules after it are only a
|
|
138
|
+
// fallback for a stylesheet that never loads.
|
|
139
|
+
const CRITICAL_CSS = [
|
|
140
|
+
":host{display:none;position:fixed;right:16px;bottom:16px;z-index:2147483647;margin:0;padding:0;line-height:0}",
|
|
141
|
+
":host([data-ready]){display:block}",
|
|
142
|
+
".docserve-dock{display:flex;align-items:center}",
|
|
143
|
+
".docserve-dock__button{display:grid;place-items:center;width:30px;height:30px;padding:0;border:0;background:none;color:inherit}",
|
|
144
|
+
".docserve-dock__status{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}",
|
|
145
|
+
].join("")
|
|
146
|
+
|
|
147
|
+
/** Shadow host, its root, the live region and the reveal hook. */
|
|
148
|
+
function mount() {
|
|
149
|
+
const host = el("div", { id: "docserve-dock-host", "data-docserve-widget": "" })
|
|
150
|
+
const root = host.attachShadow({ mode: "open" })
|
|
151
|
+
root.append(el("style", { text: CRITICAL_CSS }))
|
|
152
|
+
const status = el("span", { class: "docserve-dock__status", role: "status", "aria-live": "polite" })
|
|
153
|
+
root.append(status)
|
|
154
|
+
return { host, root, status, reveal }
|
|
155
|
+
|
|
156
|
+
// Show the widget only once its stylesheets are applied, so nothing appears
|
|
157
|
+
// unstyled. The timeout covers a stylesheet that never settles.
|
|
158
|
+
function reveal() {
|
|
159
|
+
const done = () => host.toggleAttribute("data-ready", true)
|
|
160
|
+
const links = [...root.querySelectorAll('link[rel~="stylesheet"]')]
|
|
161
|
+
Promise.all(links.map(settled)).then(done)
|
|
162
|
+
setTimeout(done, 500)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The injected module script, when the page was served by docserve. */
|
|
167
|
+
function injectedScript() {
|
|
168
|
+
return /** @type {HTMLScriptElement | null} */ (
|
|
169
|
+
document.querySelector('script[src="/__docserve/widget/index.js"]')
|
|
170
|
+
)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** docs-relative path of the page being viewed */
|
|
174
|
+
function resolvePage(script) {
|
|
175
|
+
const page = script?.getAttribute("data-page")
|
|
176
|
+
if (page) return page
|
|
177
|
+
return location.pathname.replace(/^\//, "")
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Served folder identity from `data-docs-*`; undefined outside docserve. */
|
|
181
|
+
function resolveDocs(script) {
|
|
182
|
+
const name = script?.getAttribute("data-docs-name") || ""
|
|
183
|
+
const path = script?.getAttribute("data-docs-path") || ""
|
|
184
|
+
if (!name && !path) return undefined
|
|
185
|
+
const hue = Number(script?.getAttribute("data-docs-hue"))
|
|
186
|
+
return { name: name || path, path: path || name, hue: Number.isFinite(hue) ? hue : 0 }
|
|
187
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Widget entry: register the built-in plugins, then start.
|
|
2
|
+
import { copyPlugin } from "../plugins/copy/client.js"
|
|
3
|
+
import { homePlugin } from "../plugins/home/client.js"
|
|
4
|
+
import { sidebarPlugin } from "../plugins/sidebar/client.js"
|
|
5
|
+
import { createHost } from "./host.js"
|
|
6
|
+
|
|
7
|
+
const PLUGINS = [sidebarPlugin, homePlugin, copyPlugin]
|
|
8
|
+
|
|
9
|
+
// The server skips iframe previews; this guard covers pages served some other way.
|
|
10
|
+
if (window.self === window.top && !document.getElementById("docserve-dock-host")) {
|
|
11
|
+
const widget = createHost()
|
|
12
|
+
for (const plugin of PLUGINS) widget.use(plugin())
|
|
13
|
+
widget.start()
|
|
14
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Collect teardown callbacks so a setup can close everything in one place.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @typedef {object} Disposables
|
|
5
|
+
* @property {(dispose: () => void) => void} add Run immediately when already disposed.
|
|
6
|
+
* @property {() => void} dispose Idempotent; newest callback first.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @returns {Disposables}
|
|
11
|
+
*/
|
|
12
|
+
export function createDisposables() {
|
|
13
|
+
/** @type {(() => void)[]} */
|
|
14
|
+
const callbacks = []
|
|
15
|
+
let done = false
|
|
16
|
+
|
|
17
|
+
return {
|
|
18
|
+
add(dispose) {
|
|
19
|
+
if (typeof dispose !== "function") throw new TypeError("disposables.add expects a function")
|
|
20
|
+
if (done) {
|
|
21
|
+
safeRun(dispose)
|
|
22
|
+
return
|
|
23
|
+
}
|
|
24
|
+
callbacks.push(dispose)
|
|
25
|
+
},
|
|
26
|
+
dispose() {
|
|
27
|
+
if (done) return
|
|
28
|
+
done = true
|
|
29
|
+
for (let i = callbacks.length - 1; i >= 0; i--) safeRun(callbacks[i])
|
|
30
|
+
callbacks.length = 0
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {() => void} dispose
|
|
37
|
+
*/
|
|
38
|
+
function safeRun(dispose) {
|
|
39
|
+
try {
|
|
40
|
+
dispose()
|
|
41
|
+
} catch (err) {
|
|
42
|
+
console.error(err)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// DOM helpers
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Create an element. `class`, `text`, `html` and object `style` are special;
|
|
5
|
+
* `on*` keys attach listeners; anything else becomes an attribute.
|
|
6
|
+
* @param {string} tag
|
|
7
|
+
* @param {Record<string, any>} [props]
|
|
8
|
+
* @param {Node | string | null | false | (Node | string | null | false)[]} [children]
|
|
9
|
+
* @returns {HTMLElement}
|
|
10
|
+
*/
|
|
11
|
+
export function el(tag, props = {}, children = []) {
|
|
12
|
+
const node = document.createElement(tag)
|
|
13
|
+
for (const [key, value] of Object.entries(props)) {
|
|
14
|
+
if (value == null || value === false) continue
|
|
15
|
+
if (key === "class") node.className = value
|
|
16
|
+
else if (key === "text") node.textContent = value
|
|
17
|
+
else if (key === "html") node.innerHTML = value
|
|
18
|
+
else if (key === "style" && typeof value === "object") Object.assign(node.style, value)
|
|
19
|
+
else if (key.startsWith("on") && typeof value === "function")
|
|
20
|
+
node.addEventListener(key.slice(2).toLowerCase(), value)
|
|
21
|
+
else node.setAttribute(key, value === true ? "" : String(value))
|
|
22
|
+
}
|
|
23
|
+
for (const child of Array.isArray(children) ? children : [children]) {
|
|
24
|
+
if (child == null || child === false) continue
|
|
25
|
+
node.append(child)
|
|
26
|
+
}
|
|
27
|
+
return /** @type {HTMLElement} */ (node)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Mark inline SVG as decorative and optionally add a class.
|
|
32
|
+
* @param {string} svg `<svg …>…</svg>` markup.
|
|
33
|
+
* @param {string} [name]
|
|
34
|
+
* @returns {string}
|
|
35
|
+
*/
|
|
36
|
+
export function iconSvg(svg, name = "") {
|
|
37
|
+
const cls = name ? ` class="${name}"` : ""
|
|
38
|
+
return svg.replace("<svg ", `<svg aria-hidden="true"${cls} `)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Unix seconds or a parseable date → `YYYY/MM/DD`, or `""` when invalid.
|
|
43
|
+
* @param {number | string} value
|
|
44
|
+
* @returns {string}
|
|
45
|
+
*/
|
|
46
|
+
export function displayDate(value) {
|
|
47
|
+
const date = new Date(typeof value === "number" ? value * 1000 : value)
|
|
48
|
+
if (Number.isNaN(date.getTime())) return ""
|
|
49
|
+
const y = date.getFullYear()
|
|
50
|
+
const m = String(date.getMonth() + 1).padStart(2, "0")
|
|
51
|
+
const d = String(date.getDate()).padStart(2, "0")
|
|
52
|
+
return `${y}/${m}/${d}`
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Docs-relative path → root-absolute URL, encoding each segment.
|
|
57
|
+
* @param {string} path e.g. `guides/intro.html`
|
|
58
|
+
* @returns {string}
|
|
59
|
+
*/
|
|
60
|
+
export function pageUrl(path) {
|
|
61
|
+
return `/${path.split("/").map(encodeURIComponent).join("/")}`
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Decode a URL, falling back to the input when it is malformed.
|
|
66
|
+
* @param {string} url
|
|
67
|
+
* @returns {string}
|
|
68
|
+
*/
|
|
69
|
+
export function decoded(url) {
|
|
70
|
+
try {
|
|
71
|
+
return decodeURIComponent(url)
|
|
72
|
+
} catch {
|
|
73
|
+
return url
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* True when the event target takes text input, so shortcuts must stay out.
|
|
79
|
+
* @param {EventTarget | null} target
|
|
80
|
+
* @returns {boolean}
|
|
81
|
+
*/
|
|
82
|
+
export function isTyping(target) {
|
|
83
|
+
if (!(target instanceof HTMLElement)) return false
|
|
84
|
+
return target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Copy text to the clipboard, falling back to a hidden textarea.
|
|
89
|
+
* @param {string} text
|
|
90
|
+
* @returns {Promise<void>}
|
|
91
|
+
*/
|
|
92
|
+
export async function writeClipboard(text) {
|
|
93
|
+
if (navigator.clipboard?.writeText) {
|
|
94
|
+
await navigator.clipboard.writeText(text)
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
const area = /** @type {HTMLTextAreaElement} */ (el("textarea", { readonly: "" }))
|
|
98
|
+
area.style.position = "fixed"
|
|
99
|
+
area.style.top = "-9999px"
|
|
100
|
+
area.value = text
|
|
101
|
+
document.body.append(area)
|
|
102
|
+
area.select()
|
|
103
|
+
const ok = document.execCommand("copy")
|
|
104
|
+
area.remove()
|
|
105
|
+
if (!ok) throw new Error("copy failed")
|
|
106
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Generic event emitter, ported from devframe's `utils/events.ts`.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @template {EventsMap} [Events=EventsMap]
|
|
5
|
+
* @returns {EventEmitter<Events>}
|
|
6
|
+
*/
|
|
7
|
+
export function createEventEmitter() {
|
|
8
|
+
/** @type {EventEmitter<Events>['_listeners']} */
|
|
9
|
+
const _listeners = {}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {keyof Events} event
|
|
13
|
+
* @param {...any} args
|
|
14
|
+
*/
|
|
15
|
+
function emit(event, ...args) {
|
|
16
|
+
const callbacks = _listeners[event] || []
|
|
17
|
+
for (let i = 0, length = callbacks.length; i < length; i++) {
|
|
18
|
+
const callback = callbacks[i]
|
|
19
|
+
if (callback)
|
|
20
|
+
callback(...args)
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {keyof Events} event
|
|
26
|
+
* @param {...any} args
|
|
27
|
+
*/
|
|
28
|
+
function emitOnce(event, ...args) {
|
|
29
|
+
emit(event, ...args)
|
|
30
|
+
delete _listeners[event]
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {keyof Events} event
|
|
35
|
+
* @param {(...args: any[]) => void} cb
|
|
36
|
+
* @returns {EventUnsubscribe}
|
|
37
|
+
*/
|
|
38
|
+
function on(event, cb) {
|
|
39
|
+
;(_listeners[event] ||= []).push(/** @type {Events[keyof Events]} */ (cb))
|
|
40
|
+
return () => {
|
|
41
|
+
_listeners[event] = /** @type {any} */ (_listeners[event]?.filter(i => cb !== i))
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param {keyof Events} event
|
|
47
|
+
* @param {(...args: any[]) => void} cb
|
|
48
|
+
* @returns {EventUnsubscribe}
|
|
49
|
+
*/
|
|
50
|
+
function once(event, cb) {
|
|
51
|
+
const unsubscribe = on(event, (...args) => {
|
|
52
|
+
unsubscribe()
|
|
53
|
+
return cb(...args)
|
|
54
|
+
})
|
|
55
|
+
return unsubscribe
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
_listeners,
|
|
60
|
+
emit,
|
|
61
|
+
emitOnce,
|
|
62
|
+
on,
|
|
63
|
+
once,
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Signal backed by localStorage: read once on creation, written on change.
|
|
2
|
+
import { signal } from "@preact/signals-react"
|
|
3
|
+
import { persisted as persistedStore } from "./storage.js"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @template T
|
|
7
|
+
* @param {string} key
|
|
8
|
+
* @param {T} [initial] Used when the key is absent or cannot be parsed.
|
|
9
|
+
* @param {object} [options]
|
|
10
|
+
* @param {(raw: string) => T} [options.parse]
|
|
11
|
+
* @param {(value: T) => string} [options.serialize]
|
|
12
|
+
* @returns {import("@preact/signals-react").Signal<T>}
|
|
13
|
+
*/
|
|
14
|
+
export function persisted(key, initial, options = {}) {
|
|
15
|
+
const store = persistedStore(key, initial, options)
|
|
16
|
+
const value = signal(store.value)
|
|
17
|
+
|
|
18
|
+
// `subscribe` runs once immediately; skip that write so construction alone
|
|
19
|
+
// does not create the key.
|
|
20
|
+
let first = true
|
|
21
|
+
value.subscribe((next) => {
|
|
22
|
+
if (first) {
|
|
23
|
+
first = false
|
|
24
|
+
return
|
|
25
|
+
}
|
|
26
|
+
store.value = next
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
return value
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Boolean variant of `persisted`.
|
|
34
|
+
* @param {string} key
|
|
35
|
+
* @param {boolean} [initial]
|
|
36
|
+
* @returns {import("@preact/signals-react").Signal<boolean>}
|
|
37
|
+
*/
|
|
38
|
+
export function persistedBool(key, initial = false) {
|
|
39
|
+
return persisted(key, initial, { parse: (raw) => raw === "true" })
|
|
40
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// localStorage-backed values.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @template T
|
|
5
|
+
* @typedef {object} Persisted
|
|
6
|
+
* @property {T} value
|
|
7
|
+
* @property {() => void} clear
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @template T
|
|
12
|
+
* @param {string} key
|
|
13
|
+
* @param {T} [initial] Returned when the key is absent or cannot be parsed.
|
|
14
|
+
* Object values (arrays included) default to JSON parse/serialize; primitives
|
|
15
|
+
* default to plain strings.
|
|
16
|
+
* @param {object} [options]
|
|
17
|
+
* @param {(raw: string) => T} [options.parse]
|
|
18
|
+
* @param {(value: T) => string} [options.serialize]
|
|
19
|
+
* @returns {Persisted<T>}
|
|
20
|
+
*/
|
|
21
|
+
export function persisted(key, initial = /** @type {any} */ (null), options = {}) {
|
|
22
|
+
// Object initial values are stored as JSON; primitives as plain strings.
|
|
23
|
+
const json = initial !== null && typeof initial === "object"
|
|
24
|
+
const {
|
|
25
|
+
parse = json ? (raw) => JSON.parse(raw) : (raw) => /** @type {any} */(raw),
|
|
26
|
+
serialize = json ? (value) => JSON.stringify(value) : (value) => String(value),
|
|
27
|
+
} = options
|
|
28
|
+
|
|
29
|
+
function read() {
|
|
30
|
+
try {
|
|
31
|
+
const raw = localStorage.getItem(key)
|
|
32
|
+
return raw == null ? initial : parse(raw)
|
|
33
|
+
} catch {
|
|
34
|
+
return initial
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function write(value) {
|
|
39
|
+
try {
|
|
40
|
+
localStorage.setItem(key, serialize(value))
|
|
41
|
+
} catch { }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
get value() {
|
|
46
|
+
return read()
|
|
47
|
+
},
|
|
48
|
+
set value(next) {
|
|
49
|
+
write(next)
|
|
50
|
+
},
|
|
51
|
+
clear() {
|
|
52
|
+
try {
|
|
53
|
+
localStorage.removeItem(key)
|
|
54
|
+
} catch { }
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Boolean variant: stores `"true"` / `"false"`.
|
|
61
|
+
* @param {string} key
|
|
62
|
+
* @param {boolean} [initial]
|
|
63
|
+
* @returns {Persisted<boolean>}
|
|
64
|
+
*/
|
|
65
|
+
export function persistedFlag(key, initial = false) {
|
|
66
|
+
return persisted(key, initial, {
|
|
67
|
+
parse: (raw) => raw === "true",
|
|
68
|
+
serialize: (value) => String(value),
|
|
69
|
+
})
|
|
70
|
+
}
|