@sigil-dev/grimoire 0.9.25 → 0.9.26

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/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "module": "index.ts",
12
12
  "type": "module",
13
13
  "private": false,
14
- "version": "0.9.25",
14
+ "version": "0.9.26",
15
15
  "exports": {
16
16
  ".": "./index.ts",
17
17
  "./server": "./server.ts",
@@ -35,8 +35,8 @@
35
35
  "test": "bun test"
36
36
  },
37
37
  "dependencies": {
38
- "@sigil-dev/compiler": "0.9.25",
39
- "@sigil-dev/runtime": "0.9.25",
38
+ "@sigil-dev/compiler": "0.9.26",
39
+ "@sigil-dev/runtime": "0.9.26",
40
40
  "vite": "^8.0.16"
41
41
  },
42
42
  "peerDependencies": {
@@ -115,9 +115,14 @@ export async function hmrRerender(): Promise<void> {
115
115
  });
116
116
  popHydrationNodes();
117
117
  const preserved = capturePreservedScroll();
118
+ // swapping the root can shrink the document for a moment, and the browser
119
+ // clamps scrollY to the shorter height; put the page back where it was
120
+ const y = window.scrollY;
118
121
  document.getElementById("grimoire-root")?.replaceChildren(rootNode);
119
122
  flush();
120
123
  restorePreservedScroll(preserved);
124
+ window.scrollTo(0, y);
125
+ requestAnimationFrame(() => window.scrollTo(0, y));
121
126
  }
122
127
 
123
128
  /**
@@ -554,6 +559,9 @@ export async function navigate(
554
559
  }
555
560
  onNavigateCb?.(seen);
556
561
  saveScrollPosition();
562
+ // read before the loading placeholder below collapses the page and the
563
+ // browser clamps scrollY; a same-path refetch restores this value
564
+ const startY = window.scrollY;
557
565
 
558
566
  // load the loading immediately
559
567
  const destPattern = findPattern(url.pathname);
@@ -690,8 +698,13 @@ export async function navigate(
690
698
  return;
691
699
  }
692
700
  // fresh navigation starts at the top; a same-path replace
693
- // (invalidate/refetch) keeps the current scroll
694
- if (!isRefetch) scrollToTop();
701
+ // (invalidate/refetch) keeps the scroll it started with
702
+ if (!isRefetch) {
703
+ scrollToTop();
704
+ return;
705
+ }
706
+ window.scrollTo(0, startY);
707
+ requestAnimationFrame(() => window.scrollTo(0, startY));
695
708
  };
696
709
 
697
710
  // View transitions: animate the swap when the browser supports it and the
@@ -1,202 +1,229 @@
1
- export const HMR_CLIENT_SOURCE = `
2
- (function() {
3
- let version = 0;
4
-
5
- const moduleUrl = (entry) =>
6
- '/__grimoire__/m/' + entry.modUrl + '?v=' + entry.version;
7
-
8
- /**
9
- * Apply one server batch. Route and layout modules are re-imported at
10
- * their new versions; the module the browser fetches carries version
11
- * stamps on its own imports, so an edited component two levels down comes
12
- * back fresh instead of out of the module cache.
13
- */
14
- async function applyBatch(payloads) {
15
- const css = [];
16
- const routes = [];
17
- const layouts = [];
18
- let invalidate = false;
19
-
20
- for (const p of payloads) {
21
- if (p.kind === 'reload') { location.reload(); return; }
22
- if (p.kind === 'css') css.push(p);
23
- if (p.kind === 'routes') routes.push(...p.entries);
24
- if (p.kind === 'layouts') layouts.push(...p.entries);
25
- if (p.kind === 'invalidate') invalidate = true;
26
- }
27
-
28
- for (const p of css) applyCss(p.hash, p.text);
29
-
30
- const hmr = window.__grimoire_hmr__;
31
- if (!hmr) { location.reload(); return; }
32
-
33
- const current = window.__grimoire_current_pattern__;
34
- captureSignals();
35
- try {
36
- // layouts wrap every page: always needed, so import eagerly
37
- for (const entry of layouts) {
38
- const mod = await import(moduleUrl(entry));
39
- if (!mod.default) throw new Error('layout ' + entry.path + ' has no default export');
40
- hmr.setLayout(entry.path, mod.default);
41
- }
42
-
43
- let touchesCurrent = layouts.length > 0;
44
- for (const entry of routes) {
45
- if (entry.pattern === current) {
46
- const mod = await import(moduleUrl(entry));
47
- if (!mod.default) throw new Error('route ' + entry.pattern + ' has no default export');
48
- hmr.setRoute(entry.pattern, mod.default);
49
- touchesCurrent = true;
50
- } else {
51
- // not on screen — re-register lazily so the next
52
- // navigation picks up the new version
53
- const url = moduleUrl(entry);
54
- hmr.setRoute(entry.pattern, { __lazy: () => import(url) });
55
- }
56
- }
57
-
58
- // a changed load()/action means the rendered data is stale too:
59
- // refetch instead of re-rendering against the old payload
60
- if (invalidate) await refetchCurrent();
61
- else if (touchesCurrent) await hmr.rerender();
62
- } catch (e) {
63
- console.error('[sigil hmr] swap failed, reloading:', e);
64
- location.reload();
65
- } finally {
66
- clearCapture();
67
- }
68
- }
69
-
70
- async function refetchCurrent() {
71
- if (window.__grimoire_navigate__) {
72
- await window.__grimoire_navigate__(location.pathname, true);
73
- } else {
74
- location.reload();
75
- }
76
- }
77
-
78
- function applyCss(hash, text) {
79
- let el = document.getElementById('sigil-' + hash);
80
- if (!el) {
81
- el = document.createElement('style');
82
- el.id = 'sigil-' + hash;
83
- document.head.appendChild(el);
84
- }
85
- el.textContent = text;
86
- }
87
-
88
- const __hmrRegistry__ = new Map(); // key -> signal getter fn
89
-
90
- window.__hmrAdopt__ = function(key, initial) {
91
- if (!window.__hmrCapture__) return initial;
92
- if (!window.__hmrCapture__.has(key)) return initial;
93
- const stored = window.__hmrCapture__.get(key);
94
- // shape guard — only adopt if same type and array-ness
95
- if (typeof stored !== typeof initial) return initial;
96
- if (Array.isArray(stored) !== Array.isArray(initial)) return initial;
97
- return stored;
98
- };
99
-
100
- window.__hmrRegister__ = function(key, signal) {
101
- __hmrRegistry__.set(key, signal);
102
- };
103
-
104
- function captureSignals() {
105
- window.__hmrCapture__ = new Map();
106
- for (const [key, signal] of __hmrRegistry__) {
107
- try { window.__hmrCapture__.set(key, signal()); } catch {}
108
- }
109
- }
110
-
111
- function clearCapture() {
112
- window.__hmrCapture__ = null;
113
- }
114
-
115
- function connect() {
116
- const ws = new WebSocket(
117
- (location.protocol === 'https:' ? 'wss' : 'ws') +
118
- '://' + location.host + '/__grimoire__/hmr'
119
- );
120
-
121
- ws.onopen = () => {
122
- console.log('[sigil hmr] connected');
123
- document.getElementById('__grimoire_overlay__')?.remove();
124
- };
125
-
126
- ws.onmessage = async (ev) => {
127
- const msg = JSON.parse(ev.data);
128
- if (msg.type === 'error') { showOverlay(msg.message, msg.loc); return; }
129
- if (msg.v !== undefined && msg.v <= version) return;
130
- if (msg.v !== undefined) version = msg.v;
131
-
132
- if (msg.type === 'batch') {
133
- document.getElementById('__grimoire_overlay__')?.remove();
134
- await applyBatch(msg.payloads);
135
- }
136
- };
137
-
138
- ws.onclose = () => {
139
- console.log('[sigil hmr] disconnected, reconnecting...');
140
- const retry = setInterval(async () => {
141
- try {
142
- await fetch('/', { method: 'HEAD' });
143
- clearInterval(retry);
144
- location.reload();
145
- } catch {}
146
- }, 300);
147
- };
148
- }
149
-
150
- function stripAnsi(str) {
151
- return str.replace(/\u001b[[0-9;]*m/g, '');
152
- }
153
-
154
- function unescapeHtml(str) {
155
- let result = str;
156
- // run twice to handle double-escaped entities
157
- for (let i = 0; i < 2; i++) {
158
- result = result
159
- .replace(/&amp;/g, '&')
160
- .replace(/&lt;/g, '<')
161
- .replace(/&gt;/g, '>')
162
- .replace(/&quot;/g, '"')
163
- .replace(/&#39;/g, "'");
164
- }
165
- return result;
166
- }
167
-
168
- function showOverlay(message, loc) {
169
- document.getElementById('__grimoire_overlay__')?.remove();
170
- const clean = unescapeHtml(stripAnsi(message));
171
- const d = document.createElement('div');
172
- d.id = '__grimoire_overlay__';
173
- d.style.cssText = [
174
- 'position:fixed;inset:0;z-index:99999',
175
- 'background:rgba(15,15,20,.94)',
176
- 'color:#ff8a8a',
177
- 'font:13px/1.6 monospace',
178
- 'padding:40px',
179
- 'overflow:auto',
180
- 'white-space:pre-wrap',
181
- ].join(';');
182
-
183
- d.textContent = '[sigil] compile error\\n\\n' + clean;
184
-
185
- if (loc) {
186
- const link = document.createElement('a');
187
- link.href = '/__grimoire__/open?file=' + encodeURIComponent(loc.file) +
188
- '&line=' + loc.line + '&col=' + loc.col;
189
- link.style.cssText = 'color:#88aaff;text-decoration:underline;cursor:pointer;display:block;margin:8px 0 16px';
190
- link.textContent = loc.file + ':' + loc.line + ':' + loc.col;
191
- link.onclick = (e) => { e.preventDefault(); fetch(link.href); };
192
- d.appendChild(link);
193
- }
194
-
195
- d.title = 'Click anywhere to dismiss';
196
- d.onclick = (ev) => { if (ev.target === d) d.remove(); };
197
- document.body.appendChild(d);
198
- }
199
-
200
- connect();
201
- })();
202
- `;
1
+ export const HMR_CLIENT_SOURCE = `
2
+ (function() {
3
+ let version = 0;
4
+
5
+ // The router turns off the browser's scroll restoration, so a full reload
6
+ // would land at the top. Stash the offset and put it back after the reload.
7
+ const SCROLL_KEY = '__sigil_hmr_scroll__';
8
+
9
+ function reload() {
10
+ try {
11
+ sessionStorage.setItem(SCROLL_KEY, JSON.stringify({
12
+ path: location.pathname + location.search,
13
+ y: window.scrollY,
14
+ }));
15
+ } catch {}
16
+ location.reload();
17
+ }
18
+
19
+ (function restoreScroll() {
20
+ let saved = null;
21
+ try {
22
+ saved = JSON.parse(sessionStorage.getItem(SCROLL_KEY) || 'null');
23
+ sessionStorage.removeItem(SCROLL_KEY);
24
+ } catch {}
25
+ if (!saved || saved.path !== location.pathname + location.search) return;
26
+ const apply = () => window.scrollTo(0, saved.y);
27
+ apply();
28
+ requestAnimationFrame(apply);
29
+ window.addEventListener('load', apply, { once: true });
30
+ })();
31
+
32
+ const moduleUrl = (entry) =>
33
+ '/__grimoire__/m/' + entry.modUrl + '?v=' + entry.version;
34
+
35
+ /**
36
+ * Apply one server batch. Route and layout modules are re-imported at
37
+ * their new versions; the module the browser fetches carries version
38
+ * stamps on its own imports, so an edited component two levels down comes
39
+ * back fresh instead of out of the module cache.
40
+ */
41
+ async function applyBatch(payloads) {
42
+ const css = [];
43
+ const routes = [];
44
+ const layouts = [];
45
+ let invalidate = false;
46
+
47
+ for (const p of payloads) {
48
+ if (p.kind === 'reload') { reload(); return; }
49
+ if (p.kind === 'css') css.push(p);
50
+ if (p.kind === 'routes') routes.push(...p.entries);
51
+ if (p.kind === 'layouts') layouts.push(...p.entries);
52
+ if (p.kind === 'invalidate') invalidate = true;
53
+ }
54
+
55
+ for (const p of css) applyCss(p.hash, p.text);
56
+
57
+ const hmr = window.__grimoire_hmr__;
58
+ if (!hmr) { reload(); return; }
59
+
60
+ const current = window.__grimoire_current_pattern__;
61
+ captureSignals();
62
+ try {
63
+ // layouts wrap every page: always needed, so import eagerly
64
+ for (const entry of layouts) {
65
+ const mod = await import(moduleUrl(entry));
66
+ if (!mod.default) throw new Error('layout ' + entry.path + ' has no default export');
67
+ hmr.setLayout(entry.path, mod.default);
68
+ }
69
+
70
+ let touchesCurrent = layouts.length > 0;
71
+ for (const entry of routes) {
72
+ if (entry.pattern === current) {
73
+ const mod = await import(moduleUrl(entry));
74
+ if (!mod.default) throw new Error('route ' + entry.pattern + ' has no default export');
75
+ hmr.setRoute(entry.pattern, mod.default);
76
+ touchesCurrent = true;
77
+ } else {
78
+ // not on screen — re-register lazily so the next
79
+ // navigation picks up the new version
80
+ const url = moduleUrl(entry);
81
+ hmr.setRoute(entry.pattern, { __lazy: () => import(url) });
82
+ }
83
+ }
84
+
85
+ // a changed load()/action means the rendered data is stale too:
86
+ // refetch instead of re-rendering against the old payload
87
+ if (invalidate) await refetchCurrent();
88
+ else if (touchesCurrent) await hmr.rerender();
89
+ } catch (e) {
90
+ console.error('[sigil hmr] swap failed, reloading:', e);
91
+ reload();
92
+ } finally {
93
+ clearCapture();
94
+ }
95
+ }
96
+
97
+ async function refetchCurrent() {
98
+ if (window.__grimoire_navigate__) {
99
+ await window.__grimoire_navigate__(location.pathname, true);
100
+ } else {
101
+ reload();
102
+ }
103
+ }
104
+
105
+ function applyCss(hash, text) {
106
+ let el = document.getElementById('sigil-' + hash);
107
+ if (!el) {
108
+ el = document.createElement('style');
109
+ el.id = 'sigil-' + hash;
110
+ document.head.appendChild(el);
111
+ }
112
+ el.textContent = text;
113
+ }
114
+
115
+ const __hmrRegistry__ = new Map(); // key -> signal getter fn
116
+
117
+ window.__hmrAdopt__ = function(key, initial) {
118
+ if (!window.__hmrCapture__) return initial;
119
+ if (!window.__hmrCapture__.has(key)) return initial;
120
+ const stored = window.__hmrCapture__.get(key);
121
+ // shape guard — only adopt if same type and array-ness
122
+ if (typeof stored !== typeof initial) return initial;
123
+ if (Array.isArray(stored) !== Array.isArray(initial)) return initial;
124
+ return stored;
125
+ };
126
+
127
+ window.__hmrRegister__ = function(key, signal) {
128
+ __hmrRegistry__.set(key, signal);
129
+ };
130
+
131
+ function captureSignals() {
132
+ window.__hmrCapture__ = new Map();
133
+ for (const [key, signal] of __hmrRegistry__) {
134
+ try { window.__hmrCapture__.set(key, signal()); } catch {}
135
+ }
136
+ }
137
+
138
+ function clearCapture() {
139
+ window.__hmrCapture__ = null;
140
+ }
141
+
142
+ function connect() {
143
+ const ws = new WebSocket(
144
+ (location.protocol === 'https:' ? 'wss' : 'ws') +
145
+ '://' + location.host + '/__grimoire__/hmr'
146
+ );
147
+
148
+ ws.onopen = () => {
149
+ console.log('[sigil hmr] connected');
150
+ document.getElementById('__grimoire_overlay__')?.remove();
151
+ };
152
+
153
+ ws.onmessage = async (ev) => {
154
+ const msg = JSON.parse(ev.data);
155
+ if (msg.type === 'error') { showOverlay(msg.message, msg.loc); return; }
156
+ if (msg.v !== undefined && msg.v <= version) return;
157
+ if (msg.v !== undefined) version = msg.v;
158
+
159
+ if (msg.type === 'batch') {
160
+ document.getElementById('__grimoire_overlay__')?.remove();
161
+ await applyBatch(msg.payloads);
162
+ }
163
+ };
164
+
165
+ ws.onclose = () => {
166
+ console.log('[sigil hmr] disconnected, reconnecting...');
167
+ const retry = setInterval(async () => {
168
+ try {
169
+ await fetch('/', { method: 'HEAD' });
170
+ clearInterval(retry);
171
+ reload();
172
+ } catch {}
173
+ }, 300);
174
+ };
175
+ }
176
+
177
+ function stripAnsi(str) {
178
+ return str.replace(/\u001b[[0-9;]*m/g, '');
179
+ }
180
+
181
+ function unescapeHtml(str) {
182
+ let result = str;
183
+ // run twice to handle double-escaped entities
184
+ for (let i = 0; i < 2; i++) {
185
+ result = result
186
+ .replace(/&amp;/g, '&')
187
+ .replace(/&lt;/g, '<')
188
+ .replace(/&gt;/g, '>')
189
+ .replace(/&quot;/g, '"')
190
+ .replace(/&#39;/g, "'");
191
+ }
192
+ return result;
193
+ }
194
+
195
+ function showOverlay(message, loc) {
196
+ document.getElementById('__grimoire_overlay__')?.remove();
197
+ const clean = unescapeHtml(stripAnsi(message));
198
+ const d = document.createElement('div');
199
+ d.id = '__grimoire_overlay__';
200
+ d.style.cssText = [
201
+ 'position:fixed;inset:0;z-index:99999',
202
+ 'background:rgba(15,15,20,.94)',
203
+ 'color:#ff8a8a',
204
+ 'font:13px/1.6 monospace',
205
+ 'padding:40px',
206
+ 'overflow:auto',
207
+ 'white-space:pre-wrap',
208
+ ].join(';');
209
+
210
+ d.textContent = '[sigil] compile error\\n\\n' + clean;
211
+
212
+ if (loc) {
213
+ const link = document.createElement('a');
214
+ link.href = '/__grimoire__/open?file=' + encodeURIComponent(loc.file) +
215
+ '&line=' + loc.line + '&col=' + loc.col;
216
+ link.style.cssText = 'color:#88aaff;text-decoration:underline;cursor:pointer;display:block;margin:8px 0 16px';
217
+ link.textContent = loc.file + ':' + loc.line + ':' + loc.col;
218
+ link.onclick = (e) => { e.preventDefault(); fetch(link.href); };
219
+ d.appendChild(link);
220
+ }
221
+
222
+ d.title = 'Click anywhere to dismiss';
223
+ d.onclick = (ev) => { if (ev.target === d) d.remove(); };
224
+ document.body.appendChild(d);
225
+ }
226
+
227
+ connect();
228
+ })();
229
+ `;