Skip to content

Commit 8d29505

Browse files
committed
feat(vite): hot-swap a dependency's components under vite dev
A dependency compiles to a factory over the app, so Solid's refresh pass finds no component to swap, and the entry's watch on every module of its program reloads the page on any edit. The front end now wraps the factory with the runtime's new hot entry, which re-runs a new version against the same app with its module-level calls answered from the first run, and its hotUpdate leaves the entry out when no other module compiles differently and the text outside the components' bodies is unchanged.
1 parent 6a15093 commit 8d29505

9 files changed

Lines changed: 297 additions & 12 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@
2929
- `props` in a component declared without props (`component C()`) is `UNBOUND` (RG-4b); it read `undefined`.
3030
- `guide/async.md`: "One store over the server"; the `GUESS_WHILE_LOADING` advice says what holds when a selection
3131
changes while a guess is out (05 DV-22).
32+
- Under `vite dev`, an edit inside a dependency's components re-renders them in place instead of reloading the page:
33+
the module's top-level sources and every other component's state are kept. An edit to the module's top level or to
34+
an entry still reloads. The runtime's new `@reactivescript/runtime/hot` entry does the swap; it needs a
35+
`@solidjs/vite-plugin` with the front end's `hotUpdate` hook.
3236

3337
## 0.3.1
3438

‎compiler/README.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,14 @@ What happens to a `.rx` module in Vite:
8888
The app mounts a program with `createApp` from `@reactivescript/runtime`
8989
(`../runtime`, CP-4a), as the examples do.
9090

91-
Not yet: hot updates of `.rx` modules are untested; server rendering in Vite
92-
needs a request-scoped app for server functions to run in.
91+
Hot updates: with a Solid plugin that has the front end's `hotUpdate` hook,
92+
an edit inside a dependency's components (markup, logic, `<style>`) swaps
93+
them in place through `@reactivescript/runtime/hot`, keeping the module's
94+
sources and every other component's state. An edit to a module's top level,
95+
or to an entry, reloads the page.
96+
97+
Not yet: server rendering in Vite needs a request-scoped app for server
98+
functions to run in.
9399

94100
### Releasing
95101

‎compiler/src/app.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ pub fn app(entry: &str, target: Target, module_name: &str, spa: bool) -> Value {
4949
let path = &out.paths[name];
5050
let text = read_disk(path).unwrap_or_default();
5151
let l = lower_view(module, path, target, module_name, Some((path, &text))).map_err(|e| json!({ "error": e }))?;
52-
modules.insert(path.clone(), json!({ "code": l.code, "map": l.map, "css": out.module_css[name] }));
52+
modules.insert(path.clone(), json!({ "code": l.code, "map": l.map, "css": out.module_css[name], "hot": out.module_hot.get(name).map(|(c, top)| json!({ "components": c, "top": top })) }));
5353
}
5454
Ok(json!({ "entry": set.entry, "css": out.css, "modules": modules }))
5555
})()

‎compiler/src/emit.rs‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,9 @@ pub struct Compiled {
187187
pub css: String,
188188
/// CSS-4: each module's own stylesheet, by its output name
189189
pub module_css: IndexMap<String, String>,
190+
/// a dependency's exported components and a fingerprint of the rest of its text, by output name: a dev server swaps the
191+
/// components when the fingerprint holds
192+
pub module_hot: IndexMap<String, (Vec<String>, String)>,
190193
}
191194

192195
/// 09 MO-1: one ES module per `.rx` module. A dependency's module is a factory over the app (`__rt.module` runs it once per
@@ -205,6 +208,7 @@ pub fn compile_linked(set: &ModuleSet, extra: &[Vec<Stmt>], by_source: bool) ->
205208
let mut files = IndexMap::new();
206209
let mut paths = IndexMap::new();
207210
let mut module_css = IndexMap::new();
211+
let mut module_hot = IndexMap::new();
208212
for path in &set.order {
209213
let p = &set.programs[path];
210214
let css0 = g.css.len();
@@ -239,13 +243,57 @@ pub fn compile_linked(set: &ModuleSet, extra: &[Vec<Stmt>], by_source: bool) ->
239243
body.append(&mut g.top);
240244
let mut fbody = vec![konst("__B", dot(id("__rt"), "B"))];
241245
fbody.append(&mut inner);
246+
if let Some(shape) = hot_shape(p, set.sources.get(path).map(String::as_str).unwrap_or("")) {
247+
module_hot.insert(g.out(path), shape);
248+
}
242249
body.push(S::ExportDefault(Func { name: Some("module".into()), params: vec![P::Id("__rt".into())], directives: vec![], body: fbody, is_async: false, generator: false }));
243250
}
244251
module_css.insert(g.out(path), g.css[css0..].join("\n"));
245252
files.insert(g.out(path), body);
246253
paths.insert(g.out(path), path.clone());
247254
}
248-
Ok(Compiled { files, paths, entry: g.out(&set.entry), css: g.css.join("\n"), module_css })
255+
Ok(Compiled { files, paths, entry: g.out(&set.entry), css: g.css.join("\n"), module_css, module_hot })
256+
}
257+
258+
/// A dependency's exported components, and a hash of its text outside their bodies (each component's header stays in it);
259+
/// `None` when that text names a JS import or calls an `.rx` one, which a replay would call again outside its record.
260+
fn hot_shape(p: &Program, text: &str) -> Option<(Vec<String>, String)> {
261+
use std::hash::{Hash, Hasher};
262+
let names = |js: bool| -> Vec<String> {
263+
p.decls.iter().filter_map(|d| match d { Decl::Import { resolved, names, .. } if resolved.is_none() == js => Some(names), _ => None }).flatten().map(|n| regex::escape(&n.alias)).collect()
264+
};
265+
let (js, rx) = (names(true), names(false));
266+
let mut alts = vec![];
267+
if !js.is_empty() {
268+
alts.push(format!(r"\b(?:{})\b", js.join("|")));
269+
}
270+
if !rx.is_empty() {
271+
alts.push(format!(r"\b(?:{})\s*\(", rx.join("|")));
272+
}
273+
let word = (!alts.is_empty()).then(|| regex::Regex::new(&alts.join("|")).ok()).flatten();
274+
let mut h = std::collections::hash_map::DefaultHasher::new();
275+
let mut components = vec![];
276+
for d in &p.decls {
277+
let span = d.span();
278+
let (start, end) = (span.start as usize, span.end as usize);
279+
let own = text.get(start..end).unwrap_or("");
280+
match d {
281+
Decl::Component { name, props, props_type, exported, is_default, .. } => {
282+
(name, props, props_type, exported, is_default).hash(&mut h);
283+
if *exported {
284+
components.push(name.clone());
285+
}
286+
}
287+
Decl::Import { .. } => own.hash(&mut h),
288+
_ => {
289+
if word.as_ref().is_some_and(|w| w.is_match(own)) {
290+
return None;
291+
}
292+
own.hash(&mut h);
293+
}
294+
}
295+
}
296+
Some((components, format!("{:016x}", h.finish())))
249297
}
250298

251299
struct Gen<'p> {

‎compiler/test/vite.mjs‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ function project(name, entry) {
5353
return dir;
5454
}
5555
const config = (dir, entry) => ({
56-
root: dir, configFile: false, logLevel: "warn", clearScreen: false,
56+
// a cache per project: the default, under the nearest package.json, would serve one run's runtime to the next
57+
root: dir, cacheDir: path.join(dir, ".vite"), configFile: false, logLevel: "warn", clearScreen: false,
5758
plugins: [solid()],
5859
server: { fs: { allow: [repo, path.dirname(deps), path.resolve(repo, "../solid-next"), pluginDir] } },
5960
build: { outDir: "dist", sourcemap: true, emptyOutDir: true },
@@ -145,6 +146,69 @@ if (!filter || "styles".includes(filter)) { // CSS-4 under the dev server: a d
145146
});
146147
await server.close();
147148
}
149+
if (!filter || "hot".includes(filter)) { // a dependency's component edit swaps in place; a top-level or entry edit reloads
150+
const dir = project("hot-dev", "hot/main.rx");
151+
mkdirSync(path.join(dir, "src/hot"));
152+
const main = path.join(dir, "src/hot/main.rx"), panel = path.join(dir, "src/hot/panel.rx");
153+
writeFileSync(main, `import { Panel } from "./panel.rx"\nimport { Other } from "./other.rx"\nimport { Tick } from "./tick.rx"\n\nexport default component Main() {\n <main><Panel /><Other /><Tick /></main>\n}\n`);
154+
writeFileSync(path.join(dir, "src/hot/other.rx"), `export component Other() {\n source n := 0\n <button class="other" onClick={() => { n := n + 1 }}>other {n}</button>\n}\n`);
155+
// a top level that calls into JS: a replay would call it again, so its module always reloads
156+
const tick = path.join(dir, "src/hot/tick.rx");
157+
writeFileSync(path.join(dir, "src/hot/clock.mjs"), `export const now = () => "one";\n`);
158+
writeFileSync(tick, `import pure { now } from "./clock"\n\nfirst = now()\n\nexport component Tick() {\n <p class="tick">{first}</p>\n}\n`);
159+
const lib = path.join(dir, "src/hot/lib.mjs");
160+
writeFileSync(lib, `export const word = () => "one";\n`);
161+
const source = ({ top = "", label = "total", color = "rgb(0, 0, 255)", step = 1 } = {}) =>
162+
`import pure { word } from "./lib"\n\n${top}source total := 0\n\nexport component Panel() {\n said = word()\n <style>\n .panel { color: ${color} }\n </style>\n <button class="panel" onClick={() => { total := total + ${step} }}>${label} {total}</button>\n <p class="said">{said}</p>\n}\n`;
163+
writeFileSync(panel, source());
164+
const server = await vite.createServer(config(dir, "hot/main.rx")); await server.listen(0);
165+
await drive("hot (dev)", server.resolvedUrls.local[0], async page => {
166+
const seen = async () => ({
167+
panel: (await page.textContent(".panel").catch(() => "")).trim(), other: (await page.textContent(".other").catch(() => "")).trim(),
168+
color: await page.$eval(".panel", e => getComputedStyle(e).color).catch(() => ""), kept: await page.evaluate(() => window.__kept === 1).catch(() => false),
169+
said: (await page.textContent(".said").catch(() => "")).trim(),
170+
});
171+
const until = async (what, want) => {
172+
let got;
173+
for (let i = 0; i < 50; i++) { got = await seen(); if (Object.entries(want).every(([k, v]) => got[k] === v)) return; await page.waitForTimeout(100); }
174+
throw new Error(`${what}: ${JSON.stringify(got)}, not ${JSON.stringify(want)}`);
175+
};
176+
for (let i = 0; i < 3; i++) await page.click(".panel");
177+
for (let i = 0; i < 2; i++) await page.click(".other");
178+
await page.evaluate(() => { window.__kept = 1; });
179+
await until("before the edits", { panel: "total 3", other: "other 2" });
180+
// the module-level source and the other module's component state survive; the page is not reloaded
181+
writeFileSync(panel, source({ label: "sum" }));
182+
await until("after a markup edit", { panel: "sum 3", other: "other 2", kept: true });
183+
writeFileSync(panel, source({ label: "sum", color: "rgb(255, 0, 0)" }));
184+
await until("after a <style> edit", { color: "rgb(255, 0, 0)", panel: "sum 3", other: "other 2", kept: true });
185+
writeFileSync(panel, source({ label: "plus", color: "rgb(255, 0, 0)", step: 10 }));
186+
await until("after a logic edit", { panel: "plus 3", kept: true });
187+
await page.click(".panel"); await until("the new handler", { panel: "plus 13", other: "other 2", kept: true });
188+
// a JS module the dependency imports changed: what its top level read from it may be stale, so the page reloads
189+
writeFileSync(lib, `export const word = () => "two";\n`);
190+
await until("after an import's edit", { said: "two", panel: "plus 0", kept: false });
191+
await page.evaluate(() => { window.__kept = 1; }); await page.click(".other");
192+
writeFileSync(tick, readFileSync(tick, "utf8").replace('class="tick"', 'class="tick edited"'));
193+
await until("after an edit to a module whose top level calls JS", { other: "other 0", kept: false });
194+
await page.evaluate(() => { window.__kept = 1; });
195+
// the module's top level changed: a reload, with the module's new state
196+
writeFileSync(panel, source({ top: "base = 1\n", label: "plus", color: "rgb(255, 0, 0)" }));
197+
await until("after a top-level edit", { panel: "plus 0", other: "other 0", kept: false });
198+
await page.evaluate(() => { window.__kept = 1; }); await page.click(".other");
199+
writeFileSync(main, readFileSync(main, "utf8").replace("<main>", `<main class="edited">`));
200+
await until("after an entry edit", { other: "other 0", kept: false });
201+
if (!await page.$("main.edited")) throw new Error("the entry's edit did not reach the page");
202+
// a dependency that stops compiling, then compiles again, swaps as before
203+
writeFileSync(panel, source({ label: "plus" }) + "\nexport bad = missingName\n"); await page.waitForTimeout(800);
204+
writeFileSync(panel, source({ label: "back" }));
205+
await until("after the fix", { panel: "back 0" });
206+
await page.evaluate(() => { window.__kept = 1; }); await page.click(".panel");
207+
writeFileSync(panel, source({ label: "again" }));
208+
await until("after an edit that follows a failed compile", { panel: "again 1", kept: true });
209+
});
210+
await server.close();
211+
}
148212
if (!filter || "cold".includes(filter)) { // a dependency asked for before its entry, as Vitest's `fsModuleCache` leaves it
149213
const { default: rx } = await import(pathToFileURL(path.join(pkg, "vite.mjs")).href);
150214
const root = project("cold", "shop/main.rx"), catalog = path.join(root, "src/shop/catalog.rx");

‎compiler/vite.mjs‎

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// changes. The crate's output imports its dependencies as `./x.rx?rx-dep`, and a dependency is served from the build
1414
// of a program that contains it. A module several programs share is one module: its instance is keyed by its factory
1515
// (11 CP-4b `module`), not by its place in a program.
16+
import { createHash } from "node:crypto";
1617
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
1718
import { createRequire } from "node:module";
1819
import path from "node:path";
@@ -58,6 +59,31 @@ function entriesOf(file, root) {
5859
return [...seen].sort().sort((a, b) => top(b) - top(a));
5960
}
6061

62+
/** A dependency's factory, wrapped for hot updates (the runtime's `hot` entry); lines are only added after the module's. */
63+
function hotFooter(code, hot) {
64+
// the code's own hash: a version re-run for an import's change, with its own code unchanged, reloads
65+
const meta = { ...hot, code: createHash("sha1").update(code).digest("hex").slice(0, 16) };
66+
const wrapped = code.replace(/^export default function module\(__rt\)/m, "function module(__rt)");
67+
if (wrapped === code) return code;
68+
return `${wrapped}
69+
import { hotModule as __rxHotModule } from "@reactivescript/runtime/hot";
70+
const __rxHot = __rxHotModule(import.meta.hot, module, ${JSON.stringify(meta)});
71+
export default __rxHot.factory;
72+
if (import.meta.hot) import.meta.hot.accept(__rxHot.accept);
73+
`;
74+
}
75+
76+
const hasHotRuntime = new Map();
77+
/** Whether the project's `@reactivescript/runtime` has the `hot` entry the footer imports (0.3.1 and older do not). */
78+
function hotRuntime(root) {
79+
if (!hasHotRuntime.has(root)) {
80+
let ok = true;
81+
try { createRequire(path.join(root, "package.json")).resolve("@reactivescript/runtime/hot"); } catch { ok = false; }
82+
hasHotRuntime.set(root, ok);
83+
}
84+
return hasHotRuntime.get(root);
85+
}
86+
6187
/** @returns {import("@solidjs/vite-plugin").Frontend} */
6288
export default function rx() {
6389
const builds = new Map(); // entry\0target\0moduleName\0spa → { entry, target, moduleName, spa, out, stamps }
@@ -69,10 +95,13 @@ export default function rx() {
6995
const out = JSON.parse(app(entry, target, moduleName, spa));
7096
if (out.modules) out.modules = Object.fromEntries(Object.entries(out.modules).map(([p, m]) => [path.resolve(p), m]));
7197
const files = out.modules ? Object.keys(out.modules) : out.diagnostics ? [...new Set([entry, ...out.diagnostics.map(d => d.file)])] : [entry];
98+
if (out.modules) for (const f of files) if (f !== path.resolve(entry)) dependencies.add(f);
7299
const b = { entry, target, moduleName, spa, out, stamps: new Map(files.map(f => [f, mtime(f)])) };
73100
builds.set(key, b);
74101
return b;
75102
}
103+
const restyling = new Set(); // dependencies whose stylesheet the plugin is about to ask for, after hotUpdate
104+
const dependencies = new Set(); // every file a program built so far held as a dependency, kept when its program fails
76105
const built = (file, target, moduleName, spa) =>
77106
[...builds.values()].filter(b => b.target === target && b.moduleName === moduleName && b.spa === spa && b.out.modules?.[file]);
78107
/** A dependency: from a build of a program that has it, rebuilt if that program changed. */
@@ -91,20 +120,39 @@ export default function rx() {
91120
throw new Error(`${file} is imported as an .rx dependency, but no program under ${root} contains it`);
92121
}
93122
return {
94-
compile(_source, { id, moduleId, root, solid, addWatchFile }) {
123+
// A dependency hot-swaps (rt-hot.ts) when no other module of any program that holds it compiles differently and its
124+
// text outside its components' bodies is unchanged; then the entry, which watches every module of its program, is left
125+
// out of the update, so the page keeps its state. Otherwise Vite's list stands, and the entry reloads the page.
126+
hotUpdate({ file, modules }) {
127+
file = path.resolve(file);
128+
// the plugin compiles the changed file next, by its path alone, for its stylesheet
129+
if (dependencies.has(file)) restyling.add(file);
130+
const holding = [...builds.values()].filter(b => b.out.modules?.[file]);
131+
if (!holding.length) return;
132+
for (const b of holding) {
133+
const before = b.out, after = build(b.entry, b.target, b.moduleName, b.spa).out;
134+
const was = before.modules[file].hot, now = after.modules?.[file]?.hot;
135+
if (!was || !now || was.top !== now.top || was.components.join() !== now.components.join()) return;
136+
const paths = new Set([...Object.keys(before.modules), ...Object.keys(after.modules)]);
137+
for (const p of paths) if (p !== file && before.modules[p]?.code !== after.modules[p]?.code) return;
138+
}
139+
return modules.filter(m => isDep(m.id ?? m.url ?? ""));
140+
},
141+
compile(_source, { id, moduleId, root, solid, addWatchFile, hot }) {
95142
const file = path.resolve(id);
96143
const target = solid.generate === "ssr" ? "ssr" : solid.generate === "universal" ? "universal" : "dom";
97144
const moduleName = solid.moduleName ?? "@solidjs/web";
98145
// 08 CN-3d: a client-only build (no SSR, nothing hydrates) has nothing to show on a first load nothing holds
99146
const spa = target === "dom" && solid.hydratable === false;
100-
const dep = isDep(moduleId);
101-
const { out } = dep ? containing(file, target, moduleName, spa, path.resolve(root ?? process.cwd())) : build(file, target, moduleName, spa);
147+
const dep = isDep(moduleId) || restyling.delete(file);
148+
const projectRoot = path.resolve(root ?? process.cwd());
149+
const { out } = dep ? containing(file, target, moduleName, spa, projectRoot) : build(file, target, moduleName, spa);
102150
if (out.diagnostics) throw new Error(report(out.diagnostics));
103151
if (out.error) throw new Error(out.error);
104152
const m = out.modules[file];
105153
for (const p of Object.keys(out.modules)) if (p !== file) addWatchFile(p);
106154
// CSS-4: each module links its own stylesheet, so a module several programs share links it once
107-
return { code: tagDeps(m.code), map: m.map, css: m.css ?? "" };
155+
return { code: dep && hot && m.hot && hotRuntime(projectRoot) ? hotFooter(tagDeps(m.code), m.hot) : tagDeps(m.code), map: m.map, css: m.css ?? "" };
108156
},
109157
};
110158
}

0 commit comments

Comments
 (0)