@hamur/devtools 0.0.0-stage → 0.0.2

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 (134) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +24 -2
  3. package/dist/src/client.js +780 -0
  4. package/dist/src/index.js +1711 -0
  5. package/dist/types/src/apps/locator.d.ts +3 -0
  6. package/dist/types/src/bridge.d.ts +8 -0
  7. package/dist/types/src/client.d.ts +3 -0
  8. package/dist/types/src/dev/analyze.d.ts +31 -0
  9. package/dist/types/src/dev/assets.d.ts +33 -0
  10. package/dist/types/src/dev/authz.d.ts +49 -0
  11. package/dist/types/src/dev/bundle.d.ts +22 -0
  12. package/dist/types/src/dev/config.d.ts +24 -0
  13. package/dist/types/src/dev/handler.d.ts +20 -0
  14. package/dist/types/src/dev/modules.d.ts +28 -0
  15. package/dist/types/src/dev/overview.d.ts +20 -0
  16. package/dist/types/src/dev/processes.d.ts +4 -0
  17. package/dist/types/src/dev/server-routes.d.ts +7 -0
  18. package/dist/types/src/dev/tasks.d.ts +26 -0
  19. package/dist/types/src/dev/timeline.d.ts +20 -0
  20. package/dist/types/src/dev/virtual.d.ts +9 -0
  21. package/dist/types/src/icons.d.ts +24 -0
  22. package/dist/types/src/index.d.ts +8 -0
  23. package/dist/types/src/locator.d.ts +17 -0
  24. package/dist/types/src/mask.d.ts +8 -0
  25. package/dist/types/src/module.d.ts +27 -0
  26. package/dist/types/src/open-in-editor.d.ts +4 -0
  27. package/dist/types/src/options.d.ts +14 -0
  28. package/dist/types/src/panel/document.d.ts +16 -0
  29. package/dist/types/src/panel/groups.d.ts +14 -0
  30. package/dist/types/src/panel/index.d.ts +1 -0
  31. package/dist/types/src/panel/settings.d.ts +69 -0
  32. package/dist/types/src/panel/style.d.ts +1 -0
  33. package/dist/types/src/panel/ui.d.ts +34 -0
  34. package/dist/types/src/server/authz.d.ts +30 -0
  35. package/dist/types/src/server/index.d.ts +3 -0
  36. package/dist/types/src/server/routes.d.ts +6 -0
  37. package/dist/types/src/server/storage.d.ts +56 -0
  38. package/dist/types/src/source-link.d.ts +2 -0
  39. package/dist/types/src/tabs/analyze-model.d.ts +31 -0
  40. package/dist/types/src/tabs/analyze.d.ts +2 -0
  41. package/dist/types/src/tabs/assets.d.ts +11 -0
  42. package/dist/types/src/tabs/audit-model.d.ts +42 -0
  43. package/dist/types/src/tabs/audit.d.ts +2 -0
  44. package/dist/types/src/tabs/authz-model.d.ts +11 -0
  45. package/dist/types/src/tabs/authz.d.ts +2 -0
  46. package/dist/types/src/tabs/config.d.ts +8 -0
  47. package/dist/types/src/tabs/inspect.d.ts +7 -0
  48. package/dist/types/src/tabs/modules.d.ts +4 -0
  49. package/dist/types/src/tabs/overview.d.ts +2 -0
  50. package/dist/types/src/tabs/pages.d.ts +2 -0
  51. package/dist/types/src/tabs/payload.d.ts +6 -0
  52. package/dist/types/src/tabs/plugins-model.d.ts +15 -0
  53. package/dist/types/src/tabs/plugins.d.ts +2 -0
  54. package/dist/types/src/tabs/seo-model.d.ts +36 -0
  55. package/dist/types/src/tabs/seo.d.ts +2 -0
  56. package/dist/types/src/tabs/server-routes.d.ts +2 -0
  57. package/dist/types/src/tabs/storage.d.ts +13 -0
  58. package/dist/types/src/tabs/tasks-model.d.ts +16 -0
  59. package/dist/types/src/tabs/tasks.d.ts +2 -0
  60. package/dist/types/src/tabs/terminals-model.d.ts +53 -0
  61. package/dist/types/src/tabs/terminals.d.ts +2 -0
  62. package/dist/types/src/tabs/timeline-model.d.ts +58 -0
  63. package/dist/types/src/tabs/timeline.d.ts +2 -0
  64. package/dist/types/src/tester.d.ts +43 -0
  65. package/dist/types/src/toolbar/element.d.ts +28 -0
  66. package/dist/types/src/toolbar/shortcut.d.ts +14 -0
  67. package/dist/types/src/toolbar/style.d.ts +3 -0
  68. package/dist/types/src/view-context.d.ts +13 -0
  69. package/package.json +34 -4
  70. package/src/apps/locator.ts +131 -0
  71. package/src/bridge.ts +172 -0
  72. package/src/client.ts +10 -0
  73. package/src/dev/analyze.ts +128 -0
  74. package/src/dev/assets.ts +208 -0
  75. package/src/dev/authz.ts +162 -0
  76. package/src/dev/bundle.ts +91 -0
  77. package/src/dev/config.ts +132 -0
  78. package/src/dev/handler.ts +161 -0
  79. package/src/dev/modules.ts +60 -0
  80. package/src/dev/overview.ts +57 -0
  81. package/src/dev/processes.ts +34 -0
  82. package/src/dev/server-routes.ts +14 -0
  83. package/src/dev/tasks.ts +93 -0
  84. package/src/dev/timeline.ts +43 -0
  85. package/src/dev/virtual.ts +40 -0
  86. package/src/env.d.ts +21 -0
  87. package/src/icons.ts +48 -0
  88. package/src/index.ts +12 -0
  89. package/src/locator.ts +31 -0
  90. package/src/mask.ts +16 -0
  91. package/src/module.ts +352 -0
  92. package/src/open-in-editor.ts +18 -0
  93. package/src/options.ts +36 -0
  94. package/src/panel/document.ts +60 -0
  95. package/src/panel/groups.ts +41 -0
  96. package/src/panel/index.ts +429 -0
  97. package/src/panel/settings.ts +224 -0
  98. package/src/panel/style.ts +321 -0
  99. package/src/panel/ui.ts +52 -0
  100. package/src/server/authz.ts +110 -0
  101. package/src/server/index.ts +25 -0
  102. package/src/server/routes.ts +51 -0
  103. package/src/server/storage.ts +251 -0
  104. package/src/source-link.ts +29 -0
  105. package/src/tabs/analyze-model.ts +97 -0
  106. package/src/tabs/analyze.ts +217 -0
  107. package/src/tabs/assets.ts +375 -0
  108. package/src/tabs/audit-model.ts +216 -0
  109. package/src/tabs/audit.ts +223 -0
  110. package/src/tabs/authz-model.ts +28 -0
  111. package/src/tabs/authz.ts +337 -0
  112. package/src/tabs/config.ts +250 -0
  113. package/src/tabs/inspect.ts +101 -0
  114. package/src/tabs/modules.ts +58 -0
  115. package/src/tabs/overview.ts +104 -0
  116. package/src/tabs/pages.ts +188 -0
  117. package/src/tabs/payload.ts +224 -0
  118. package/src/tabs/plugins-model.ts +44 -0
  119. package/src/tabs/plugins.ts +95 -0
  120. package/src/tabs/seo-model.ts +140 -0
  121. package/src/tabs/seo.ts +162 -0
  122. package/src/tabs/server-routes.ts +469 -0
  123. package/src/tabs/storage.ts +313 -0
  124. package/src/tabs/tasks-model.ts +59 -0
  125. package/src/tabs/tasks.ts +287 -0
  126. package/src/tabs/terminals-model.ts +127 -0
  127. package/src/tabs/terminals.ts +294 -0
  128. package/src/tabs/timeline-model.ts +200 -0
  129. package/src/tabs/timeline.ts +260 -0
  130. package/src/tester.ts +158 -0
  131. package/src/toolbar/element.ts +428 -0
  132. package/src/toolbar/shortcut.ts +56 -0
  133. package/src/toolbar/style.ts +94 -0
  134. package/src/view-context.ts +93 -0
@@ -0,0 +1,428 @@
1
+ import type { DevtoolsApp, DevtoolsPage } from "hamur/app"
2
+ import { DEVTOOLS_HOOK } from "hamur/adapter/dev"
3
+ import { serveBridge } from "../bridge.ts"
4
+ import {
5
+ clampRect,
6
+ isDocked,
7
+ pillPosition,
8
+ readSettings,
9
+ readView,
10
+ resizeRect,
11
+ SETTINGS_KEY,
12
+ writeSettings,
13
+ writeView,
14
+ type Edge,
15
+ type PanelRect,
16
+ type Placement,
17
+ } from "../panel/settings.ts"
18
+ import { startView, viewContext } from "../view-context.ts"
19
+ import { isTyping, matchesShortcut, parseShortcut } from "./shortcut.ts"
20
+ import { HAMUR_ICON, TOOLBAR_CSS } from "./style.ts"
21
+
22
+ export const TOOLBAR_TAG = "hamur-devtools"
23
+
24
+ export interface ToolbarApp {
25
+ name: string
26
+ title: string
27
+ icon: string
28
+ load: () => Promise<{ default: DevtoolsApp }>
29
+ }
30
+
31
+ export interface ToolbarConfig {
32
+ baseURL: string
33
+ shortcut: string | false
34
+ placement: Placement
35
+ apps: ToolbarApp[]
36
+ }
37
+
38
+ export interface ToolbarControl {
39
+ open(tab?: string): void
40
+ close(): void
41
+ /** The frame as a rectangle in px, whether docked or floating. */
42
+ rect(): PanelRect
43
+ /** Puts the frame at `rect` (kept inside the viewport); `commit` keeps it in the settings. */
44
+ place(rect: PanelRect, commit: boolean): void
45
+ dock(): void
46
+ }
47
+
48
+ type PageHook = DevtoolsPage & { toolbar?: ToolbarControl }
49
+
50
+ const MIN_HEIGHT = 120
51
+ const DRAG_THRESHOLD = 4
52
+
53
+ const GRIPS: Array<[Edge, string]> = [
54
+ ["n", "-top-1 left-0 right-0 h-2 cursor-ns-resize"],
55
+ ["s", "-bottom-1 left-0 right-0 h-2 cursor-ns-resize"],
56
+ ["w", "-left-1 top-0 bottom-0 w-2 cursor-ew-resize"],
57
+ ["e", "-right-1 top-0 bottom-0 w-2 cursor-ew-resize"],
58
+ ["nw", "-top-1 -left-1 size-3 cursor-nwse-resize"],
59
+ ["ne", "-top-1 -right-1 size-3 cursor-nesw-resize"],
60
+ ["sw", "-bottom-1 -left-1 size-3 cursor-nesw-resize"],
61
+ ["se", "-bottom-1 -right-1 size-3 cursor-nwse-resize"],
62
+ ]
63
+
64
+ const viewport = () => ({ width: window.innerWidth, height: window.innerHeight })
65
+
66
+ const clampHeight = (height: number): number =>
67
+ Math.round(Math.max(MIN_HEIGHT, Math.min(height, window.innerHeight - 48)))
68
+
69
+ const PILL =
70
+ "fixed flex items-center gap-0.5 h-10 px-1 rounded-xl bg-raised shadow-pop text-fg text-sm font-sans whitespace-nowrap"
71
+ const BUTTON =
72
+ "inline-flex items-center justify-center gap-1 min-w-8 h-8 px-1.5 rounded-lg bg-transparent cursor-pointer hover:bg-hover hover:text-fg focus-visible:outline-accent"
73
+
74
+ /** Where the pill sits: a `bottom-*` placement moves above the panel while it is open. */
75
+ function placementClasses(placement: Placement, open: boolean): string {
76
+ const [edge, side] = placement.split("-") as ["top" | "bottom", "left" | "right" | "center"]
77
+ const vertical = edge === "top" ? "top-3" : open ? "bottom-[calc(var(--panel-height)+12px)]" : "bottom-3"
78
+ return `${vertical} ${side === "left" ? "left-3" : side === "right" ? "right-3" : "left-1/2 -translate-x-1/2"}`
79
+ }
80
+
81
+ /** Everything the toolbar draws lives in its shadow root, so the app's DOM outside the element is unchanged. */
82
+ class DevtoolsToolbar extends HTMLElement {
83
+ static config: ToolbarConfig
84
+ #root: HTMLDivElement
85
+ #pill: HTMLDivElement
86
+ #button: HTMLButtonElement
87
+ #panel: HTMLDivElement
88
+ #frame: HTMLIFrameElement | undefined
89
+ #live: PanelRect | undefined
90
+
91
+ constructor() {
92
+ super()
93
+ const shadow = this.attachShadow({ mode: "open" })
94
+ shadow.innerHTML = `<style>${TOOLBAR_CSS}</style><div data-root><div data-panel class="fixed bg-app shadow-panel" hidden></div><div data-pill class="${PILL}"><button type="button" data-hamur class="${BUTTON} text-fg aria-expanded:bg-active aria-expanded:text-accent" title="Hamur devtools" aria-label="Hamur devtools" aria-expanded="false">${HAMUR_ICON}</button><span data-badge class="inline-flex items-center h-8 px-1.5 text-fg-2 text-sm whitespace-nowrap" hidden></span></div></div>`
95
+ this.#root = shadow.querySelector("[data-root]")!
96
+ this.#pill = shadow.querySelector("[data-pill]")!
97
+ this.#button = shadow.querySelector("[data-hamur]")!
98
+ this.#panel = shadow.querySelector("[data-panel]")!
99
+ this.#button.addEventListener("click", () => this.toggle())
100
+ this.#showBadge(shadow.querySelector("[data-badge]")!)
101
+ for (const [edge, classes] of GRIPS) {
102
+ const grip = document.createElement("div")
103
+ grip.className = `absolute touch-none ${classes}`
104
+ grip.dataset.grip = edge
105
+ this.#panel.append(grip)
106
+ this.#resizable(grip, edge)
107
+ }
108
+ this.#draggable(this.#pill)
109
+ for (const app of DevtoolsToolbar.config.apps) this.#addApp(app)
110
+ this.apply()
111
+ }
112
+
113
+ /** The render-mode badge text of the core, `<route name> · <mode>`, which the page hook keeps current. */
114
+ #showBadge(badge: HTMLElement): void {
115
+ const page = (window as unknown as Record<string, PageHook | undefined>)[DEVTOOLS_HOOK]
116
+ const show = (text: string) => {
117
+ badge.textContent = text
118
+ badge.hidden = text === ""
119
+ }
120
+ show(page?.badge() ?? "")
121
+ page?.on("badge", (text) => show(String(text)))
122
+ }
123
+
124
+ /** A button per devtools app; a click starts it on its canvas, the next one tears it down. */
125
+ #addApp(app: ToolbarApp): void {
126
+ const button = document.createElement("button")
127
+ button.type = "button"
128
+ button.className = `${BUTTON} text-fg-2 aria-pressed:bg-active aria-pressed:text-accent data-[failed]:text-red`
129
+ button.title = app.title
130
+ button.ariaLabel = app.title
131
+ button.ariaPressed = "false"
132
+ button.dataset.app = app.name
133
+ const icon = document.createElement("span")
134
+ icon.className = "inline-flex"
135
+ if (app.icon.trimStart().startsWith("<svg")) icon.innerHTML = app.icon
136
+ else icon.textContent = app.icon
137
+ const badge = document.createElement("span")
138
+ badge.className = "inline-flex items-center h-4 px-1.5 rounded bg-accent/10 text-accent text-2xs font-medium"
139
+ badge.dataset.badge = ""
140
+ badge.hidden = true
141
+ button.append(icon, badge)
142
+ this.#pill.append(button)
143
+ const canvas = document.createElement("div")
144
+ canvas.className = "fixed inset-0 pointer-events-none"
145
+ canvas.dataset.app = app.name
146
+ this.#root.append(canvas)
147
+ const setBadge = (text: string | undefined) => {
148
+ badge.hidden = text === undefined
149
+ badge.textContent = text ?? ""
150
+ }
151
+ let running: Promise<(() => void) | undefined> | undefined
152
+ button.addEventListener("click", () => {
153
+ if (running) {
154
+ const stopping = running
155
+ running = undefined
156
+ button.ariaPressed = "false"
157
+ void stopping.then((stop) => {
158
+ stop?.()
159
+ setBadge(undefined)
160
+ canvas.replaceChildren()
161
+ canvas.style.pointerEvents = ""
162
+ })
163
+ return
164
+ }
165
+ button.ariaPressed = "true"
166
+ delete button.dataset.failed
167
+ const page = (window as unknown as Record<string, PageHook | undefined>)[DEVTOOLS_HOOK]
168
+ const run: Promise<(() => void) | undefined> = startView(
169
+ app.load,
170
+ canvas,
171
+ viewContext(DevtoolsToolbar.config.baseURL, page, setBadge),
172
+ ).catch((error: unknown) => {
173
+ if (running === run) {
174
+ button.dataset.failed = ""
175
+ button.ariaPressed = "false"
176
+ running = undefined
177
+ }
178
+ console.error(
179
+ `[hamur] devtools app ${JSON.stringify(app.name)} failed: ${error instanceof Error ? error.message : String(error)}`,
180
+ )
181
+ return undefined
182
+ })
183
+ running = run
184
+ })
185
+ }
186
+
187
+ get isOpen(): boolean {
188
+ return !this.#panel.hidden
189
+ }
190
+
191
+ /** Reads the settings again: the panel writes them from its own document. */
192
+ apply(): void {
193
+ const settings = readSettings()
194
+ this.#pill.dataset.placement = settings.placement ?? DevtoolsToolbar.config.placement
195
+ this.#layout()
196
+ }
197
+
198
+ /** The frame's rectangle in px: docked at the bottom edge with the kept height, or the kept rectangle inside the viewport. */
199
+ rect(): PanelRect {
200
+ const settings = readSettings()
201
+ if (this.#live) return this.#live
202
+ if (isDocked(settings.panel)) {
203
+ const height = clampHeight(settings.height)
204
+ return { x: 0, y: window.innerHeight - height, width: window.innerWidth, height }
205
+ }
206
+ return clampRect(settings.panel, viewport())
207
+ }
208
+
209
+ #layout(): void {
210
+ const settings = readSettings()
211
+ const style = this.#panel.style
212
+ if (isDocked(settings.panel) && !this.#live) {
213
+ const height = clampHeight(settings.height)
214
+ this.#root.style.setProperty("--panel-height", `${height}px`)
215
+ style.setProperty("left", "0")
216
+ style.setProperty("top", "auto")
217
+ style.setProperty("bottom", "0")
218
+ style.setProperty("width", "100%")
219
+ style.setProperty("height", `${height}px`)
220
+ } else {
221
+ const rect = this.rect()
222
+ style.setProperty("left", `${rect.x}px`)
223
+ style.setProperty("top", `${rect.y}px`)
224
+ style.setProperty("bottom", "auto")
225
+ style.setProperty("width", `${rect.width}px`)
226
+ style.setProperty("height", `${rect.height}px`)
227
+ }
228
+ this.#place()
229
+ }
230
+
231
+ place(rect: PanelRect, commit: boolean): void {
232
+ const next = clampRect(rect, viewport())
233
+ if (commit) {
234
+ this.#live = undefined
235
+ writeSettings({ ...readSettings(), panel: next })
236
+ } else this.#live = next
237
+ this.#layout()
238
+ }
239
+
240
+ dock(): void {
241
+ this.#live = undefined
242
+ writeSettings({ ...readSettings(), panel: { dock: "bottom" } })
243
+ this.#layout()
244
+ }
245
+
246
+ #place(): void {
247
+ const settings = readSettings()
248
+ if (settings.pill) {
249
+ this.#pill.className = PILL
250
+ const box = this.#pill.getBoundingClientRect()
251
+ const { left, top } = pillPosition(settings.pill, box, viewport())
252
+ this.#pill.style.setProperty("left", `${left}px`)
253
+ this.#pill.style.setProperty("top", `${top}px`)
254
+ return
255
+ }
256
+ this.#pill.style.removeProperty("left")
257
+ this.#pill.style.removeProperty("top")
258
+ this.#pill.className = `${PILL} ${placementClasses(this.#pill.dataset.placement as Placement, this.isOpen && isDocked(settings.panel) && !this.#live)}`
259
+ }
260
+
261
+ open(tab?: string): void {
262
+ const view = readView()
263
+ const shown = tab ?? (this.#frame ? undefined : view.tab)
264
+ const src = `${DevtoolsToolbar.config.baseURL}_hamur/devtools/${shown ? `#/${shown}` : ""}`
265
+ const kept = shown ?? view.tab
266
+ writeView(kept === undefined ? { open: true } : { open: true, tab: kept })
267
+ if (!this.#frame) {
268
+ this.#frame = document.createElement("iframe")
269
+ this.#frame.title = "Hamur devtools"
270
+ this.#frame.className = "block w-full h-full border-0"
271
+ this.#frame.src = src
272
+ this.#panel.append(this.#frame)
273
+ } else if (tab) this.#frame.contentWindow?.location.replace(src)
274
+ this.#panel.hidden = false
275
+ this.#button.setAttribute("aria-expanded", "true")
276
+ this.#layout()
277
+ }
278
+
279
+ close(): void {
280
+ writeView({ ...readView(), open: false })
281
+ this.#panel.hidden = true
282
+ this.#button.setAttribute("aria-expanded", "false")
283
+ this.#layout()
284
+ }
285
+
286
+ toggle(): void {
287
+ if (this.isOpen) this.close()
288
+ else this.open()
289
+ }
290
+
291
+ #resizable(grip: HTMLElement, edge: Edge): void {
292
+ grip.addEventListener("pointerdown", (down) => {
293
+ if (down.button !== 0) return
294
+ grip.setPointerCapture(down.pointerId)
295
+ this.#frame?.classList.add("pointer-events-none")
296
+ const docked = isDocked(readSettings().panel)
297
+ const start = this.rect()
298
+ const dockedHeight = (event: PointerEvent) => clampHeight(start.height - (event.clientY - down.clientY))
299
+ const move = (event: PointerEvent) => {
300
+ if (docked && edge === "n") {
301
+ const height = dockedHeight(event)
302
+ this.#root.style.setProperty("--panel-height", `${height}px`)
303
+ this.#panel.style.setProperty("height", `${height}px`)
304
+ this.#place()
305
+ } else
306
+ this.place(
307
+ resizeRect(start, edge, event.clientX - down.clientX, event.clientY - down.clientY, viewport()),
308
+ false,
309
+ )
310
+ }
311
+ const up = (event: PointerEvent) => {
312
+ grip.removeEventListener("pointermove", move)
313
+ grip.removeEventListener("pointerup", up)
314
+ this.#frame?.classList.remove("pointer-events-none")
315
+ if (docked && edge === "n") writeSettings({ ...readSettings(), height: dockedHeight(event) })
316
+ else
317
+ this.place(
318
+ resizeRect(start, edge, event.clientX - down.clientX, event.clientY - down.clientY, viewport()),
319
+ true,
320
+ )
321
+ }
322
+ grip.addEventListener("pointermove", move)
323
+ grip.addEventListener("pointerup", up)
324
+ })
325
+ }
326
+
327
+ /** A drag of 4 px or more moves the pill and keeps its place as fractions of the viewport; a shorter one is the click it was. */
328
+ #draggable(pill: HTMLElement): void {
329
+ let moved = false
330
+ pill.addEventListener(
331
+ "click",
332
+ (event) => {
333
+ if (!moved) return
334
+ moved = false
335
+ event.stopPropagation()
336
+ event.preventDefault()
337
+ },
338
+ true,
339
+ )
340
+ pill.addEventListener("pointerdown", (down) => {
341
+ if (down.button !== 0) return
342
+ const box = pill.getBoundingClientRect()
343
+ let dragging = false
344
+ moved = false
345
+ const at = (event: PointerEvent) => {
346
+ const left = Math.max(0, Math.min(box.left + event.clientX - down.clientX, window.innerWidth - box.width))
347
+ const top = Math.max(0, Math.min(box.top + event.clientY - down.clientY, window.innerHeight - box.height))
348
+ return { left, top }
349
+ }
350
+ const move = (event: PointerEvent) => {
351
+ if (!dragging) {
352
+ if (Math.hypot(event.clientX - down.clientX, event.clientY - down.clientY) < DRAG_THRESHOLD) return
353
+ dragging = true
354
+ pill.setPointerCapture(down.pointerId)
355
+ this.#frame?.classList.add("pointer-events-none")
356
+ pill.className = PILL
357
+ }
358
+ const { left, top } = at(event)
359
+ pill.style.setProperty("left", `${left}px`)
360
+ pill.style.setProperty("top", `${top}px`)
361
+ }
362
+ const up = (event: PointerEvent) => {
363
+ window.removeEventListener("pointermove", move)
364
+ window.removeEventListener("pointerup", up)
365
+ window.removeEventListener("pointercancel", up)
366
+ if (!dragging) return
367
+ this.#frame?.classList.remove("pointer-events-none")
368
+ moved = true
369
+ setTimeout(() => (moved = false), 0)
370
+ const { left, top } = at(event)
371
+ writeSettings({ ...readSettings(), pill: { x: left / window.innerWidth, y: top / window.innerHeight } })
372
+ this.#place()
373
+ }
374
+ window.addEventListener("pointermove", move)
375
+ window.addEventListener("pointerup", up)
376
+ window.addEventListener("pointercancel", up)
377
+ })
378
+ }
379
+ }
380
+
381
+ /** Defines `<hamur-devtools>`, appends one to `body` and puts it back when the app replaces the body's children. */
382
+ export function mountToolbar(config: ToolbarConfig): void {
383
+ if (document.querySelector(TOOLBAR_TAG)) return
384
+ DevtoolsToolbar.config = config
385
+ if (!customElements.get(TOOLBAR_TAG)) customElements.define(TOOLBAR_TAG, DevtoolsToolbar)
386
+ const toolbar = document.createElement(TOOLBAR_TAG) as DevtoolsToolbar
387
+ document.body.append(toolbar)
388
+
389
+ const keep = () => {
390
+ if (toolbar.parentNode !== document.body) document.body.append(toolbar)
391
+ bodyObserver.disconnect()
392
+ bodyObserver.observe(document.body, { childList: true })
393
+ }
394
+ const bodyObserver = new MutationObserver(keep)
395
+ bodyObserver.observe(document.body, { childList: true })
396
+ new MutationObserver(keep).observe(document.documentElement, { childList: true })
397
+
398
+ const shortcut = config.shortcut === false ? undefined : parseShortcut(config.shortcut)
399
+ if (shortcut) {
400
+ window.addEventListener(
401
+ "keydown",
402
+ (event) => {
403
+ if (!matchesShortcut(event, shortcut) || isTyping(event)) return
404
+ event.preventDefault()
405
+ toolbar.toggle()
406
+ },
407
+ true,
408
+ )
409
+ }
410
+ window.addEventListener("storage", (event) => {
411
+ if (event.key === SETTINGS_KEY || event.key === null) toolbar.apply()
412
+ })
413
+ window.addEventListener("resize", () => toolbar.apply())
414
+
415
+ const hook = (window as unknown as Record<string, PageHook | undefined>)[DEVTOOLS_HOOK]
416
+ if (hook) {
417
+ hook.toolbar = {
418
+ open: (tab) => toolbar.open(tab),
419
+ close: () => toolbar.close(),
420
+ rect: () => toolbar.rect(),
421
+ place: (rect, commit) => toolbar.place(rect, commit),
422
+ dock: () => toolbar.dock(),
423
+ }
424
+ serveBridge(hook)
425
+ }
426
+ const view = readView()
427
+ if (view.open) toolbar.open(view.tab)
428
+ }
@@ -0,0 +1,56 @@
1
+ export interface Shortcut {
2
+ ctrl: boolean
3
+ alt: boolean
4
+ shift: boolean
5
+ meta: boolean
6
+ /** The `KeyboardEvent.code` of the key: `KeyD`, `Digit1`, `F5`. */
7
+ code: string
8
+ }
9
+
10
+ const MODIFIERS = ["ctrl", "alt", "shift", "meta"] as const
11
+ type Modifier = (typeof MODIFIERS)[number]
12
+
13
+ /** Modifiers each at most once, then one key `a`–`z`, `0`–`9` or `f1`–`f12`; case ignored. */
14
+ export function parseShortcut(text: string): Shortcut | undefined {
15
+ const parts = text
16
+ .toLowerCase()
17
+ .split("+")
18
+ .map((part) => part.trim())
19
+ const key = parts.pop() ?? ""
20
+ const shortcut: Shortcut = { ctrl: false, alt: false, shift: false, meta: false, code: "" }
21
+ for (const part of parts) {
22
+ if (!MODIFIERS.includes(part as Modifier) || shortcut[part as Modifier]) return undefined
23
+ shortcut[part as Modifier] = true
24
+ }
25
+ if (/^[a-z]$/.test(key)) shortcut.code = `Key${key.toUpperCase()}`
26
+ else if (/^[0-9]$/.test(key)) shortcut.code = `Digit${key}`
27
+ else if (/^f(?:[1-9]|1[0-2])$/.test(key)) shortcut.code = key.toUpperCase()
28
+ else return undefined
29
+ return shortcut
30
+ }
31
+
32
+ /** Matched by `code`, so `alt` on macOS, which changes `key`, still matches. */
33
+ export function matchesShortcut(
34
+ event: Pick<KeyboardEvent, "code" | "ctrlKey" | "altKey" | "shiftKey" | "metaKey">,
35
+ shortcut: Shortcut,
36
+ ): boolean {
37
+ return (
38
+ event.code === shortcut.code &&
39
+ event.ctrlKey === shortcut.ctrl &&
40
+ event.altKey === shortcut.alt &&
41
+ event.shiftKey === shortcut.shift &&
42
+ event.metaKey === shortcut.meta
43
+ )
44
+ }
45
+
46
+ /** A keydown in a field the user types into is not a shortcut. */
47
+ export function isTyping(event: Event): boolean {
48
+ const target = event.composedPath()[0]
49
+ if (!(target instanceof HTMLElement)) return false
50
+ return (
51
+ target.isContentEditable ||
52
+ target instanceof HTMLInputElement ||
53
+ target instanceof HTMLTextAreaElement ||
54
+ target instanceof HTMLSelectElement
55
+ )
56
+ }
@@ -0,0 +1,94 @@
1
+ export const HAMUR_ICON =
2
+ '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 16.5c0-5.5 3.6-9.5 8-9.5s8 4 8 9.5z" fill="currentColor" fill-opacity="0.16" stroke="none"></path><path d="M4 16.5c0-5.5 3.6-9.5 8-9.5s8 4 8 9.5M3 16.5h18M9.5 12v1M14.5 12v1"></path></svg>'
3
+
4
+ /** The shadow root's sheet, the panel's tokens and the utilities the toolbar uses, in px since `rem` is the page's. */
5
+ export const TOOLBAR_CSS = String.raw`
6
+ :host {
7
+ all: initial;
8
+ position: fixed;
9
+ z-index: 2147483646;
10
+ --app: #f5f4f2; --raised: #ffffff; --hover: #f6f5f3; --active: #f0efee; --line: #e8e6e5;
11
+ --fg: #222120; --fg-2: #5b5956; --accent: #db5e29; --red: #cf4445;
12
+ --hairline: rgba(255,248,240,0.08);
13
+ color-scheme: light;
14
+ }
15
+ @media (prefers-color-scheme: dark) {
16
+ :host {
17
+ --app: #121110; --raised: #1f1e1d; --hover: #21201f; --active: #252423; --line: #272725;
18
+ --fg: #f8f6f4; --fg-2: #a3a09d; --accent: #ff8a4a; --red: #eb635e;
19
+ color-scheme: dark;
20
+ }
21
+ }
22
+ *, ::before, ::after { box-sizing: border-box; }
23
+ svg { overflow: visible; flex: none; }
24
+ [hidden] { display: none !important; }
25
+ button { all: unset; box-sizing: border-box; }
26
+ .fixed { position: fixed; }
27
+ .absolute { position: absolute; }
28
+ .inset-0 { inset: 0; }
29
+ .left-0 { left: 0; }
30
+ .right-0 { right: 0; }
31
+ .bottom-0 { bottom: 0; }
32
+ .-top-1 { top: -4px; }
33
+ .top-0 { top: 0; }
34
+ .-bottom-1 { bottom: -4px; }
35
+ .-left-1 { left: -4px; }
36
+ .-right-1 { right: -4px; }
37
+ .top-3 { top: 12px; }
38
+ .bottom-3 { bottom: 12px; }
39
+ .left-3 { left: 12px; }
40
+ .right-3 { right: 12px; }
41
+ .left-1\/2 { left: 50%; }
42
+ .-translate-x-1\/2 { transform: translateX(-50%); }
43
+ .bottom-\[calc\(var\(--panel-height\)\+12px\)\] { bottom: calc(var(--panel-height) + 12px); }
44
+ .flex { display: flex; }
45
+ .inline-flex { display: inline-flex; }
46
+ .block { display: block; }
47
+ .items-center { align-items: center; }
48
+ .justify-center { justify-content: center; }
49
+ .gap-0\.5 { gap: 2px; }
50
+ .gap-1 { gap: 4px; }
51
+ .h-2 { height: 8px; }
52
+ .w-2 { width: 8px; }
53
+ .size-3 { width: 12px; height: 12px; }
54
+ .h-4 { height: 16px; }
55
+ .h-8 { height: 32px; }
56
+ .h-10 { height: 40px; }
57
+ .h-full { height: 100%; }
58
+ .h-\[var\(--panel-height\)\] { height: var(--panel-height); }
59
+ .w-full { width: 100%; }
60
+ .min-w-8 { min-width: 32px; }
61
+ .px-1 { padding-left: 4px; padding-right: 4px; }
62
+ .px-1\.5 { padding-left: 6px; padding-right: 6px; }
63
+ .rounded { border-radius: 4px; }
64
+ .rounded-lg { border-radius: 8px; }
65
+ .rounded-xl { border-radius: 12px; }
66
+ .border-0 { border: 0; }
67
+ .bg-app { background: var(--app); }
68
+ .bg-raised { background: var(--raised); }
69
+ .bg-transparent { background: transparent; }
70
+ .bg-accent\/10 { background: color-mix(in srgb, var(--accent) 10%, transparent); }
71
+ .text-fg { color: var(--fg); }
72
+ .text-fg-2 { color: var(--fg-2); }
73
+ .text-accent { color: var(--accent); }
74
+ .font-sans { font-family: Inter, system-ui, sans-serif; }
75
+ .text-sm { font-size: 13px; line-height: 1; }
76
+ .text-2xs { font-size: 11px; line-height: 1; }
77
+ .font-medium { font-weight: 500; }
78
+ .whitespace-nowrap { white-space: nowrap; }
79
+ .cursor-pointer { cursor: pointer; }
80
+ .cursor-ns-resize { cursor: ns-resize; }
81
+ .cursor-ew-resize { cursor: ew-resize; }
82
+ .cursor-nwse-resize { cursor: nwse-resize; }
83
+ .cursor-nesw-resize { cursor: nesw-resize; }
84
+ .touch-none { touch-action: none; }
85
+ .pointer-events-none { pointer-events: none; }
86
+ .shadow-pop { box-shadow: 0 0 0 1px var(--hairline), inset 0 1px 0 rgba(255,255,255,0.04), 0 16px 40px -12px rgba(0,0,0,0.55); }
87
+ .shadow-panel { box-shadow: 0 -1px 0 var(--line), 0 -12px 32px -16px rgba(0,0,0,0.5); }
88
+ .hover\:bg-hover:hover { background: var(--hover); }
89
+ .hover\:text-fg:hover { color: var(--fg); }
90
+ .aria-expanded\:bg-active[aria-expanded="true"], .aria-pressed\:bg-active[aria-pressed="true"] { background: var(--active); }
91
+ .aria-expanded\:text-accent[aria-expanded="true"], .aria-pressed\:text-accent[aria-pressed="true"] { color: var(--accent); }
92
+ .data-\[failed\]\:text-red[data-failed] { color: var(--red); }
93
+ .focus-visible\:outline-accent:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
94
+ `
@@ -0,0 +1,93 @@
1
+ import type { DevtoolsApp, DevtoolsAppContext, DevtoolsPage } from "hamur/app"
2
+
3
+ type Listener = (data: unknown) => void
4
+
5
+ const listeners = new Map<string, Set<Listener>>()
6
+ let socket: WebSocket | undefined
7
+
8
+ /** One devtools socket per document, opened on the first listener and reopened 1 s after it closes. */
9
+ function connect(): void {
10
+ socket = new WebSocket(
11
+ `${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/_hamur/reload?devtools=1`,
12
+ )
13
+ socket.onmessage = (event) => {
14
+ let message: { type?: unknown; event?: unknown; data?: unknown } | undefined
15
+ try {
16
+ message = JSON.parse(String(event.data))
17
+ } catch {
18
+ return
19
+ }
20
+ if (message?.type !== "custom" || typeof message.event !== "string") return
21
+ for (const listener of listeners.get(message.event) ?? []) listener(message.data)
22
+ }
23
+ socket.onclose = () => setTimeout(connect, 1000)
24
+ }
25
+
26
+ /** Calls `fn` with the data of each devtools push named `event`; returns the function that stops it. */
27
+ export function onDevtoolsEvent(event: string, fn: Listener): () => void {
28
+ const set = listeners.get(event) ?? new Set()
29
+ listeners.set(event, set)
30
+ set.add(fn)
31
+ if (!socket) connect()
32
+ return () => void set.delete(fn)
33
+ }
34
+
35
+ /** `POST <baseURL>_hamur/devtools/api/rpc/<name>` with the args as JSON. */
36
+ export async function callDevtoolsRpc<R>(baseURL: string, name: string, args?: unknown): Promise<R> {
37
+ const response = await fetch(`${baseURL}_hamur/devtools/api/rpc/${encodeURIComponent(name)}`, {
38
+ method: "POST",
39
+ headers: { "content-type": "application/json" },
40
+ ...(args === undefined ? {} : { body: JSON.stringify(args) }),
41
+ })
42
+ const answer = (await response.json().catch(() => ({}))) as { result?: R; error?: string }
43
+ if (!response.ok) throw new Error(answer.error ?? `devtools RPC ${name} answered ${response.status}`)
44
+ return answer.result as R
45
+ }
46
+
47
+ /** The `ctx` a tab's or an app's `init` gets. */
48
+ export function viewContext(
49
+ baseURL: string,
50
+ page: DevtoolsPage | undefined,
51
+ setBadge: (text: string | undefined) => void,
52
+ ): DevtoolsAppContext {
53
+ return { rpc: (name, args) => callDevtoolsRpc(baseURL, name, args), on: onDevtoolsEvent, page, setBadge }
54
+ }
55
+
56
+ /** Runs a view's `init` and gives back its teardown; a failed load or `init` stops its listeners, and after either `on` and `setBadge` do nothing. */
57
+ export async function startView(
58
+ load: () => Promise<{ default: DevtoolsApp }>,
59
+ canvas: HTMLElement,
60
+ ctx: DevtoolsAppContext,
61
+ ): Promise<() => void> {
62
+ const offs: Array<() => void> = []
63
+ let stopped = false
64
+ const stopListeners = () => {
65
+ stopped = true
66
+ for (const off of offs.splice(0)) off()
67
+ }
68
+ const tracked: DevtoolsAppContext = {
69
+ ...ctx,
70
+ on(event, fn) {
71
+ if (stopped) return () => {}
72
+ const off = ctx.on(event, fn)
73
+ offs.push(off)
74
+ return off
75
+ },
76
+ setBadge(text) {
77
+ if (!stopped) ctx.setBadge(text)
78
+ },
79
+ }
80
+ let teardown: unknown
81
+ try {
82
+ const { default: view } = await load()
83
+ teardown = await view.init(canvas, tracked)
84
+ } catch (error) {
85
+ stopListeners()
86
+ throw error
87
+ }
88
+ return () => {
89
+ if (stopped) return
90
+ stopListeners()
91
+ if (typeof teardown === "function") teardown()
92
+ }
93
+ }