@charmland/gem 0.1.0 → 0.2.0

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.
@@ -6,5 +6,5 @@ import "@charmland/gem/theme.js";
6
6
  import type { BootFlags } from "@charmland/gem-compiler/types";
7
7
  import type { ElmApp } from "./runtime.js";
8
8
  export declare function boot(flags: BootFlags, node?: HTMLElement): ElmApp;
9
- export { connectPorts, installTabs } from "./runtime.js";
9
+ export { connectPorts, installLightbox, installTabs } from "./runtime.js";
10
10
  export type { ElmApp, ElmProgram } from "./runtime.js";
@@ -11,4 +11,4 @@ export function boot(flags, node) {
11
11
  }
12
12
  return start(Elm.Gem.Main, flags, node);
13
13
  }
14
- export { connectPorts, installTabs } from "./runtime.js";
14
+ export { connectPorts, installLightbox, installTabs } from "./runtime.js";
@@ -0,0 +1,8 @@
1
+ /** The image lightbox: Elm renders the image, this floats it into an overlay. */
2
+ export interface Lightbox {
3
+ close(): void;
4
+ destroy(): void;
5
+ }
6
+ /** Idempotent; re-run by the mutation observer and on image load. */
7
+ export declare function upgradeImages(root?: ParentNode): void;
8
+ export declare function installLightbox(): Lightbox;
@@ -0,0 +1,282 @@
1
+ /** The image lightbox: Elm renders the image, this floats it into an overlay. */
2
+ const IMAGE = ".md-image";
3
+ const TINY = 48;
4
+ // The backdrop fade in `gem.scss` matches it.
5
+ const DURATION = 300;
6
+ const EASE = "cubic-bezier(0.4, 0, 0.2, 1)";
7
+ const WIDTH_RATIO = 0.94;
8
+ const HEIGHT_RATIO = 0.9;
9
+ const MAX_WIDTH = 1600;
10
+ // Matches the media query in `gem.scss`.
11
+ const NARROW = 768;
12
+ const NO_SHADOW = "0 0 0 rgba(0, 0, 0, 0)";
13
+ function expandable(node) {
14
+ if (!(node instanceof HTMLImageElement) ||
15
+ !node.matches(IMAGE) ||
16
+ node.closest("a") ||
17
+ node.hasAttribute("data-no-zoom")) {
18
+ return false;
19
+ }
20
+ return !(node.complete &&
21
+ node.naturalHeight > 0 &&
22
+ node.naturalHeight < TINY);
23
+ }
24
+ /** Idempotent; re-run by the mutation observer and on image load. */
25
+ export function upgradeImages(root = document) {
26
+ root.querySelectorAll(IMAGE).forEach((node) => {
27
+ if (expandable(node)) {
28
+ node.setAttribute("tabindex", "0");
29
+ node.setAttribute("role", "button");
30
+ }
31
+ else if (node.hasAttribute("role")) {
32
+ node.removeAttribute("tabindex");
33
+ node.removeAttribute("role");
34
+ }
35
+ });
36
+ }
37
+ function previewSize(source) {
38
+ const naturalWidth = source.naturalWidth || source.width || 1;
39
+ const naturalHeight = source.naturalHeight || source.height || 1;
40
+ const narrow = window.innerWidth <= NARROW;
41
+ const maxWidth = narrow
42
+ ? window.innerWidth
43
+ : Math.min(window.innerWidth * WIDTH_RATIO, MAX_WIDTH);
44
+ const maxHeight = window.innerHeight * (narrow ? 1 : HEIGHT_RATIO);
45
+ const scale = Math.min(maxWidth / naturalWidth, maxHeight / naturalHeight);
46
+ return { width: naturalWidth * scale, height: naturalHeight * scale };
47
+ }
48
+ function flight(from, to) {
49
+ const dx = from.left + from.width / 2 - (to.left + to.width / 2);
50
+ const dy = from.top + from.height / 2 - (to.top + to.height / 2);
51
+ const scale = to.width > 0 ? from.width / to.width : 1;
52
+ return `translate(${dx}px, ${dy}px) scale(${scale})`;
53
+ }
54
+ function skin(el) {
55
+ const style = getComputedStyle(el);
56
+ return { borderRadius: style.borderRadius, boxShadow: style.boxShadow };
57
+ }
58
+ function reducedMotion() {
59
+ return (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true);
60
+ }
61
+ /** Reserves the scrollbar's width, so nothing reflows behind the layer. */
62
+ function lockPage() {
63
+ const doc = document.documentElement;
64
+ const gap = Math.max(0, window.innerWidth - doc.clientWidth);
65
+ doc.style.setProperty("--gem-lightbox-gap", `${gap}px`);
66
+ doc.classList.add("gem-lightbox-open");
67
+ }
68
+ function unlockPage() {
69
+ const doc = document.documentElement;
70
+ doc.classList.remove("gem-lightbox-open");
71
+ doc.style.removeProperty("--gem-lightbox-gap");
72
+ }
73
+ function build() {
74
+ const root = document.createElement("div");
75
+ root.className = "gem-lightbox";
76
+ root.setAttribute("role", "dialog");
77
+ root.setAttribute("aria-modal", "true");
78
+ root.setAttribute("aria-label", "Image preview");
79
+ root.tabIndex = -1;
80
+ root.hidden = true;
81
+ const image = document.createElement("img");
82
+ image.className = "gem-lightbox-image";
83
+ image.alt = "";
84
+ root.append(image);
85
+ // Sibling of `body`: Elm diffs `<body>`'s children.
86
+ document.documentElement.append(root);
87
+ return { root, image };
88
+ }
89
+ export function installLightbox() {
90
+ if (typeof document === "undefined") {
91
+ return { close: () => { }, destroy: () => { } };
92
+ }
93
+ let overlay = null;
94
+ let shown = false;
95
+ // Stays painted: the copy starts and lands on it, so no gap can show.
96
+ let lifted = null;
97
+ let restored = null;
98
+ // A close landing after a reopen is then a no-op.
99
+ let generation = 0;
100
+ let motion = null;
101
+ function stop() {
102
+ if (!motion)
103
+ return;
104
+ motion.onfinish = null;
105
+ motion.oncancel = null;
106
+ motion.cancel();
107
+ motion = null;
108
+ }
109
+ function ensure() {
110
+ if (!overlay || !overlay.root.isConnected)
111
+ overlay = build();
112
+ return overlay;
113
+ }
114
+ function finish(box) {
115
+ box.root.hidden = true;
116
+ box.root.classList.remove("open");
117
+ box.image.removeAttribute("src");
118
+ box.image.style.removeProperty("width");
119
+ box.image.style.removeProperty("height");
120
+ unlockPage();
121
+ shown = false;
122
+ lifted = null;
123
+ stop();
124
+ if (restored?.isConnected)
125
+ restored.focus();
126
+ restored = null;
127
+ }
128
+ function close() {
129
+ if (!shown || !overlay)
130
+ return;
131
+ shown = false;
132
+ stop();
133
+ const box = overlay;
134
+ const source = lifted;
135
+ const mine = generation;
136
+ const land = () => {
137
+ if (mine === generation)
138
+ finish(box);
139
+ };
140
+ box.root.classList.remove("open");
141
+ const target = box.image.getBoundingClientRect();
142
+ if (source?.isConnected &&
143
+ !reducedMotion() &&
144
+ typeof box.image.animate === "function") {
145
+ // `forwards` holds the landing transform until `finish` hides the layer.
146
+ motion = box.image.animate([
147
+ { transform: "none", ...skin(box.image) },
148
+ {
149
+ transform: flight(fromRect(source), target),
150
+ ...skin(source),
151
+ boxShadow: NO_SHADOW,
152
+ },
153
+ ], { duration: DURATION, easing: EASE, fill: "forwards" });
154
+ motion.onfinish = land;
155
+ motion.oncancel = land;
156
+ }
157
+ else {
158
+ land();
159
+ }
160
+ }
161
+ function show(source) {
162
+ const box = ensure();
163
+ generation += 1;
164
+ stop();
165
+ const from = fromRect(source);
166
+ const size = previewSize(source);
167
+ box.image.src = source.currentSrc || source.src;
168
+ box.image.alt = source.alt;
169
+ box.image.style.width = `${size.width}px`;
170
+ box.image.style.height = `${size.height}px`;
171
+ box.root.hidden = false;
172
+ // A transition needs a before-change style; this was `display: none`.
173
+ void box.root.offsetWidth;
174
+ box.root.classList.add("open");
175
+ lockPage();
176
+ lifted = source;
177
+ restored =
178
+ document.activeElement instanceof HTMLElement
179
+ ? document.activeElement
180
+ : null;
181
+ box.root.focus();
182
+ shown = true;
183
+ if (reducedMotion() || typeof box.image.animate !== "function")
184
+ return;
185
+ // `backwards` holds it on the page rect until the first frame.
186
+ motion = box.image.animate([
187
+ {
188
+ transform: flight(from, box.image.getBoundingClientRect()),
189
+ ...skin(source),
190
+ boxShadow: NO_SHADOW,
191
+ },
192
+ { transform: "none", ...skin(box.image) },
193
+ ], { duration: DURATION, easing: EASE, fill: "backwards" });
194
+ }
195
+ function fromRect(source) {
196
+ const rect = source.getBoundingClientRect();
197
+ return {
198
+ width: rect.width,
199
+ height: rect.height,
200
+ left: rect.left,
201
+ top: rect.top,
202
+ };
203
+ }
204
+ const onClick = (event) => {
205
+ const target = event.target;
206
+ if (!(target instanceof Element))
207
+ return;
208
+ const overLayer = shown && overlay?.root.contains(target) === true;
209
+ if (overLayer) {
210
+ event.preventDefault();
211
+ close();
212
+ return;
213
+ }
214
+ const image = target.closest(IMAGE);
215
+ if (!expandable(image))
216
+ return;
217
+ event.preventDefault();
218
+ show(image);
219
+ };
220
+ const onActivate = (event) => {
221
+ if (event.key !== "Enter" && event.key !== " ")
222
+ return;
223
+ const target = event.target;
224
+ if (!(target instanceof Element) || !expandable(target))
225
+ return;
226
+ event.preventDefault();
227
+ show(target);
228
+ };
229
+ const onKey = (event) => {
230
+ if (!shown)
231
+ return;
232
+ if (event.key === "Escape") {
233
+ event.preventDefault();
234
+ close();
235
+ return;
236
+ }
237
+ if (event.key === "Tab") {
238
+ event.preventDefault();
239
+ overlay?.root.focus();
240
+ }
241
+ };
242
+ const onPopState = () => close();
243
+ const onLoad = (event) => {
244
+ if (event.target instanceof HTMLImageElement)
245
+ upgradeImages(document);
246
+ };
247
+ document.addEventListener("click", onClick);
248
+ document.addEventListener("keydown", onActivate);
249
+ document.addEventListener("keydown", onKey);
250
+ document.addEventListener("load", onLoad, true);
251
+ window.addEventListener("popstate", onPopState);
252
+ let scheduled = false;
253
+ const observer = new MutationObserver(() => {
254
+ if (scheduled)
255
+ return;
256
+ scheduled = true;
257
+ requestAnimationFrame(() => {
258
+ scheduled = false;
259
+ upgradeImages(document);
260
+ });
261
+ });
262
+ observer.observe(document.body, { childList: true, subtree: true });
263
+ upgradeImages(document);
264
+ ensure();
265
+ return {
266
+ close,
267
+ destroy() {
268
+ document.removeEventListener("click", onClick);
269
+ document.removeEventListener("keydown", onActivate);
270
+ document.removeEventListener("keydown", onKey);
271
+ document.removeEventListener("load", onLoad, true);
272
+ window.removeEventListener("popstate", onPopState);
273
+ observer.disconnect();
274
+ stop();
275
+ unlockPage();
276
+ overlay?.root.remove();
277
+ overlay = null;
278
+ lifted = null;
279
+ shown = false;
280
+ },
281
+ };
282
+ }
@@ -51,19 +51,19 @@ export function connectMeta(app) {
51
51
  }
52
52
  export function connectScroll(app) {
53
53
  const port = app.ports?.onScroll;
54
- if (!port)
55
- return;
56
- let queued = false;
57
- const send = () => {
58
- if (queued)
59
- return;
60
- queued = true;
61
- requestAnimationFrame(() => {
62
- queued = false;
63
- port.send(window.scrollY);
64
- });
65
- };
66
- window.addEventListener("scroll", send, { passive: true });
54
+ if (port) {
55
+ let queued = false;
56
+ const send = () => {
57
+ if (queued)
58
+ return;
59
+ queued = true;
60
+ requestAnimationFrame(() => {
61
+ queued = false;
62
+ port.send(window.scrollY);
63
+ });
64
+ };
65
+ window.addEventListener("scroll", send, { passive: true });
66
+ }
67
67
  }
68
68
  function writeClipboard(text) {
69
69
  if (navigator.clipboard && window.isSecureContext) {
@@ -1,5 +1,10 @@
1
1
  /**
2
- * Delegated anchor handling for prerendered pages. Elm only attaches its own
3
- * interceptor to nodes it created, so the HTML from the build needs this.
2
+ * Anchor handling for every same-origin link. Elm installs its own click
3
+ * listener on each anchor it renders, and the build's HTML has none, so this
4
+ * capture-phase listener owns both: it is the only place that decides whether
5
+ * a click stays in the app. Known page routes push state and dispatch
6
+ * `popstate`; anything else keeps the browser's default navigation, so a link
7
+ * to `llms.txt`, a `.md` twin or a `public/` asset reaches the server.
4
8
  */
5
- export declare function installLinkInterception(): () => void;
9
+ import type { BootFlags } from "@charmland/gem-compiler/types";
10
+ export declare function installLinkInterception(flags: BootFlags): () => void;
@@ -1,16 +1,27 @@
1
1
  /**
2
- * Delegated anchor handling for prerendered pages. Elm only attaches its own
3
- * interceptor to nodes it created, so the HTML from the build needs this.
2
+ * Anchor handling for every same-origin link. Elm installs its own click
3
+ * listener on each anchor it renders, and the build's HTML has none, so this
4
+ * capture-phase listener owns both: it is the only place that decides whether
5
+ * a click stays in the app. Known page routes push state and dispatch
6
+ * `popstate`; anything else keeps the browser's default navigation, so a link
7
+ * to `llms.txt`, a `.md` twin or a `public/` asset reaches the server.
4
8
  */
5
- export function installLinkInterception() {
9
+ export function installLinkInterception(flags) {
6
10
  if (typeof document === "undefined")
7
11
  return () => { };
12
+ // Compare like with like: the routes the build wrote, mounted and without a
13
+ // trailing slash, against the request path in the same form.
14
+ const base = flags.base || "/";
15
+ const mount = base === "/" ? "" : base.replace(/\/$/, "");
16
+ const normal = (path) => (path === "/" ? "/" : path.replace(/\/+$/, "") || "/");
17
+ const routes = new Set(flags.pages.map((page) => normal(mount + page.route)));
18
+ const isRoute = (pathname) => routes.has(normal(pathname));
8
19
  const handler = (event) => {
9
20
  if (event.defaultPrevented)
10
21
  return;
11
22
  if (event.button !== 0)
12
23
  return;
13
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
24
+ if (event.metaKey || event.ctrlKey || event.shiftKey)
14
25
  return;
15
26
  const target = event.target;
16
27
  const anchor = target instanceof Element ? target.closest("a") : null;
@@ -26,10 +37,27 @@ export function installLinkInterception() {
26
37
  const url = new URL(anchor.href, window.location.href);
27
38
  if (url.origin !== window.location.origin)
28
39
  return;
40
+ // This listener owns the click, so Elm's per-anchor handler must not also
41
+ // run; stopping here leaves the default action (or the push below) intact.
42
+ event.stopPropagation();
43
+ // Alt-click is the browser's download gesture.
44
+ if (event.altKey)
45
+ return;
46
+ if (!isRoute(url.pathname))
47
+ return;
29
48
  event.preventDefault();
30
49
  window.history.pushState({}, "", url.pathname + url.search + url.hash);
31
50
  window.dispatchEvent(new PopStateEvent("popstate"));
51
+ // A click starts a new page: at its section, or at the top. History
52
+ // navigation is left to the browser, which restores the position.
53
+ if (url.hash) {
54
+ const id = decodeURIComponent(url.hash.slice(1));
55
+ requestAnimationFrame(() => document.getElementById(id)?.scrollIntoView());
56
+ }
57
+ else {
58
+ window.scrollTo(0, 0);
59
+ }
32
60
  };
33
- document.addEventListener("click", handler);
34
- return () => document.removeEventListener("click", handler);
61
+ document.addEventListener("click", handler, true);
62
+ return () => document.removeEventListener("click", handler, true);
35
63
  }
@@ -9,4 +9,6 @@ export interface ElmProgram<App extends ElmApp = ElmApp> {
9
9
  export type { ElmApp, MetaFlags } from "./ports.js";
10
10
  export { connectPorts } from "./ports.js";
11
11
  export { installTabs } from "./tabs.js";
12
+ export { installLightbox, upgradeImages } from "./lightbox.js";
13
+ export type { Lightbox } from "./lightbox.js";
12
14
  export declare function start<App extends ElmApp>(program: ElmProgram<App>, flags: BootFlags, node?: HTMLElement): App;
@@ -1,9 +1,11 @@
1
1
  import { connectColorScheme, prepareColorScheme, watchSystem } from "./color-scheme.js";
2
+ import { installLightbox } from "./lightbox.js";
2
3
  import { connectExternal, connectMeta, connectPorts, connectScroll } from "./ports.js";
3
4
  import { installLinkInterception } from "./router.js";
4
5
  import { installTabs, observeTabs } from "./tabs.js";
5
6
  export { connectPorts } from "./ports.js";
6
7
  export { installTabs } from "./tabs.js";
8
+ export { installLightbox, upgradeImages } from "./lightbox.js";
7
9
  export function start(program, flags, node) {
8
10
  const app = program.init({
9
11
  flags: prepareColorScheme(flags),
@@ -15,8 +17,9 @@ export function start(program, flags, node) {
15
17
  connectMeta(app);
16
18
  connectScroll(app);
17
19
  watchSystem();
18
- installLinkInterception();
20
+ installLinkInterception(flags);
19
21
  installTabs();
20
22
  observeTabs();
23
+ installLightbox();
21
24
  return app;
22
25
  }