htmx-router 1.0.15 → 1.0.16

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/event-source.d.ts CHANGED
@@ -14,6 +14,7 @@ export declare class EventSource {
14
14
  static OPEN: number;
15
15
  static CLOSED: number;
16
16
  constructor(request: Request, keepAlive?: number);
17
+ isAborted(): boolean;
17
18
  private sendBytes;
18
19
  private sendText;
19
20
  private keepAlive;
package/event-source.js CHANGED
@@ -42,7 +42,7 @@ export class EventSource {
42
42
  this.createdAt = Date.now();
43
43
  this.#updatedAt = 0;
44
44
  // immediate prepare for abortion
45
- const cancel = () => { this.close(); };
45
+ const cancel = () => { this.close(); request.signal.removeEventListener("abort", cancel); };
46
46
  request.signal.addEventListener('abort', cancel);
47
47
  this.#signal = request.signal;
48
48
  const start = (c) => { this.#controller = c; this.#state = EventSource.OPEN; };
@@ -51,12 +51,13 @@ export class EventSource {
51
51
  this.#timer = setInterval(() => this.keepAlive(), keepAlive);
52
52
  register.add(this);
53
53
  }
54
+ isAborted() { return this.#signal.aborted; }
54
55
  sendBytes(chunk, active) {
55
56
  if (this.#state === EventSource.CLOSED) {
56
57
  const err = new Error(`Warn: Attempted to send data on closed stream for: ${this.url}`);
57
58
  console.warn(err);
58
59
  }
59
- if (this.#signal.aborted) {
60
+ if (this.isAborted()) {
60
61
  this.close();
61
62
  return false;
62
63
  }
@@ -70,12 +70,12 @@ function BuildServerManifest(type, imported) {
70
70
  out += `from "${imp.href}";\n`;
71
71
  }
72
72
  out += `\nimport { Style } from "htmx-router/css";\n`
73
- + `const island = new Style("i", ".this{display:contents;}\\n").name;\n\n`
73
+ + `const island = new Style("hx", ".this{display:contents;}\\n").name;\n\n`
74
74
  + "type FirstArg<T> = T extends (arg: infer U, ...args: any[]) => any ? U : never;\n"
75
75
  + "function mount(name: string, json: string, ssr?: JSX.Element) {\n"
76
76
  + "\treturn (<div className={island}>\n"
77
77
  + `\t\t{ssr}\n`
78
- + `\t\t${SafeScript(type, "`Router.mountParentWith('${name}', ${json})`")}\n`
78
+ + `\t\t${SafeScript(type, "`Router._mount('${name}', ${json})`")}\n`
79
79
  + "\t</div>);\n"
80
80
  + "}\n"
81
81
  + "function Stringify(data: any) {\n"
@@ -111,17 +111,11 @@ function BuildClientManifest(type, imports) {
111
111
  for (const imported of imports) {
112
112
  if (Array.isArray(imported.mapping)) {
113
113
  for (const map of imported.mapping) {
114
- out += `\t${map.name}: async (element: HTMLElement, props: any) => {\n`
115
- + `\t\tconst C = (await import("${imported.href}")).${map.original};\n`
116
- + bind.mount
117
- + `\n\t},\n`;
114
+ out += BuildClientMounter(map.name, map.original, imported.href, bind.mount);
118
115
  }
119
116
  }
120
117
  else {
121
- out += `\t${imported.mapping.name}: async (element: HTMLElement, props: any) => {\n`
122
- + `\t\tconst C = (await import("${imported.href}")).default;\n`
123
- + bind.mount
124
- + `\n\t},\n`;
118
+ out += BuildClientMounter(imported.mapping.name, "default", imported.href, bind.mount);
125
119
  }
126
120
  }
127
121
  out += "}\nexport default client;\n"
@@ -130,12 +124,19 @@ function BuildClientManifest(type, imports) {
130
124
  out += cleanup;
131
125
  return out;
132
126
  }
127
+ function BuildClientMounter(output, input, href, mounter) {
128
+ return `\t${output}: async (element: HTMLElement, props: any, hydrate: boolean) => {\n`
129
+ + `\t\tconst C = (await import("${href}")).${input};\n`
130
+ + mounter
131
+ + `\n\t},\n`;
132
+ }
133
133
  const binding = {
134
134
  react: {
135
- mount: '\t\tconst d = await import("react-dom/client");\n'
136
- + '\t\tconst r = d.createRoot(element);\n'
137
- + '\t\tr.render(<C {...props} />);\n'
138
- + '\t\tmounted.set(element, r);',
135
+ mount: `const d = await import("react-dom/client");
136
+ const c = <C {...props} />;
137
+ const r = hydrate ? d.hydrateRoot(element, c) : d.createRoot(element);
138
+ if (!hydrate) r.render(<C {...props} />);
139
+ mounted.set(element, r);\n`,
139
140
  unmount: `
140
141
  import type { Root } from "react-dom/client";
141
142
  const mounted = new Map<HTMLElement, Root>();
@@ -174,7 +175,7 @@ function CleanNode(node: Node) {
174
175
  if (node instanceof HTMLElement) {
175
176
  const root = mounted.get(node);
176
177
  if (root) {
177
- console.info("unmounting", node);
178
+ if (window.Router?.verbose) console.info("unmounting", node);
178
179
  Unmount(node, root);
179
180
  }
180
181
  }
package/internal/mount.js CHANGED
@@ -25,6 +25,23 @@ function ClientMounter() {
25
25
  return localStorage.getItem("theme");
26
26
  }
27
27
  };
28
+ /**
29
+ * based on https://gist.github.com/hyamamoto/fd435505d29ebfa3d9716fd2be8d42f0,
30
+ * derived from Java's string hashcode implementation
31
+ */
32
+ function HashString(s) {
33
+ let h = 0;
34
+ for (let i = 0; i < s.length; i++)
35
+ h = Math.imul(31, h) + s.charCodeAt(i) | 0;
36
+ return h;
37
+ }
38
+ const mountKey = "htmx-router-cache";
39
+ function GetElementCache(elm) {
40
+ return elm[mountKey] || null;
41
+ }
42
+ function SetElementCache(elm, cache) {
43
+ elm[mountKey] = cache;
44
+ }
28
45
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
29
46
  theme.infer();
30
47
  theme.apply();
@@ -33,21 +50,33 @@ function ClientMounter() {
33
50
  const global = window;
34
51
  const mountRequests = new Array();
35
52
  function RequestMount(funcName, json) {
36
- const elm = document.currentScript.parentElement;
37
- if (elm.hasAttribute("mounted"))
38
- return;
53
+ const scope = document.currentScript;
54
+ let elm = scope.previousElementSibling;
55
+ if (!elm) {
56
+ const parent = scope.parentElement;
57
+ if (!parent)
58
+ throw new Error("Mounting script does not exist within <div>");
59
+ elm = document.createElement("div");
60
+ elm.style.display = "contents";
61
+ parent.prepend(elm);
62
+ }
39
63
  if (!document.body.contains(elm))
40
64
  return;
41
65
  mountRequests.push([funcName, elm, json]);
42
66
  }
43
67
  function Mount([funcName, element, json]) {
44
- console.info("hydrating", funcName, "into", element);
45
68
  const func = global.CLIENT[funcName];
46
69
  if (!func)
47
70
  throw new Error(`Component ${funcName} is missing from client manifest`);
48
- func(element, json);
49
- element.setAttribute("component", funcName);
50
- element.setAttribute("mounted", "yes");
71
+ const cache = GetElementCache(element);
72
+ const data = JSON.stringify(json);
73
+ const hash = HashString(data);
74
+ const hydrate = !!cache && cache.component === funcName
75
+ && cache.hash === hash && cache.data == data;
76
+ if (config.verbose)
77
+ console.info(hydrate ? "hydrating" : "mounting", funcName, "into", element);
78
+ func(element, json, hydrate);
79
+ SetElementCache(element, { component: funcName, data, hash });
51
80
  }
52
81
  function MountAll() {
53
82
  if (!global.CLIENT)
@@ -89,15 +118,18 @@ function ClientMounter() {
89
118
  document.addEventListener("DOMContentLoaded", MountAll);
90
119
  document.addEventListener("htmx:load", MountAll);
91
120
  }
92
- return {
121
+ const config = {
122
+ _mount: RequestMount,
93
123
  mountParentWith: RequestMount,
94
124
  mount: {
95
125
  freeze: Freeze,
96
126
  unfreeze: Unfreeze,
97
127
  step: MountStep
98
128
  },
99
- theme
129
+ theme,
130
+ verbose: window.location.hostname === "localhost"
100
131
  };
132
+ return config;
101
133
  }
102
134
  ;
103
135
  const script = "window.Router = (function () {"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "htmx-router",
3
- "version": "1.0.15",
3
+ "version": "1.0.16",
4
4
  "description": "A lightweight SSR framework with server+client islands",
5
5
  "keywords": [
6
6
  "htmx",