atoms-element v5.0.0
git clone https://git.pyrossh.dev/atoms-element
A simple web component library for defining your custom elements. It works on both client and server.
25308a9
— Peter John
2026-08-07T14:14:05+05:30
use lit
Generated files not shown: package-lock.json
- examples/e2e.spec.js +14 -7
- examples/pages/index.js +13 -14
- examples/server.js +11 -4
- index.d.ts +9 -0
- index.js +61 -283
- index.test.js +6 -6
- index.test.js.snapshot +10 -10
- package.json +2 -0
examples/e2e.spec.js
CHANGED
|
@@ -5,6 +5,7 @@ import { test, before, after } from 'node:test';
|
|
|
5
5
|
import assert from 'node:assert/strict';
|
|
6
6
|
import { spawn } from 'node:child_process';
|
|
7
7
|
import { chromium } from 'playwright';
|
|
8
|
+
import { createElement, getElement, html } from '../index.js';
|
|
8
9
|
|
|
9
10
|
const PORT = 3987;
|
|
10
11
|
const BASE_URL = `http://localhost:${PORT}/`;
|
|
@@ -67,15 +68,21 @@ test('no console/page errors were thrown', () => {
|
|
|
67
68
|
assert.deepStrictEqual(pageErrors, []);
|
|
68
69
|
});
|
|
69
70
|
|
|
70
|
-
test('
|
|
71
|
+
test('hydration reuses the exact SSR DOM node, so focus survives it naturally', async () => {
|
|
72
|
+
// Server-render the fixture the same way examples/server.js does, so the
|
|
73
|
+
// markup handed to the browser has real lit hydration markers rather than
|
|
74
|
+
// hand-typed HTML — hydrate() only works against genuine SSR structure.
|
|
75
|
+
const Comp = () => html`<div class="wrap"><button>-</button><button>+</button></div>`;
|
|
76
|
+
createElement({ url: '/focus-test-element.js' }, Comp);
|
|
77
|
+
const ssrMarkup = new (getElement('focus-test-element'))().render();
|
|
78
|
+
|
|
71
|
-
const result = await page.evaluate(async () => {
|
|
79
|
+
const result = await page.evaluate(async (markup) => {
|
|
72
80
|
const { createElement, html } = await import('/index.js');
|
|
73
81
|
const Comp = () => html`<div class="wrap"><button>-</button><button>+</button></div>`;
|
|
74
82
|
createElement({ url: '/focus-test-element.js' }, Comp);
|
|
75
83
|
|
|
76
84
|
const el = document.createElement('focus-test-element');
|
|
77
|
-
|
|
85
|
+
el.innerHTML = markup;
|
|
78
|
-
el.innerHTML = '<div class="wrap"><button>-</button><button>+</button></div>';
|
|
79
86
|
document.body.appendChild(el);
|
|
80
87
|
|
|
81
88
|
const originalPlus = el.querySelectorAll('button')[1];
|
|
@@ -90,9 +97,9 @@ test('preserves focus across the first hydration render, without reusing the old
|
|
|
90
97
|
const sameNode = originalPlus === newPlus;
|
|
91
98
|
el.remove();
|
|
92
99
|
return { focusedBefore, focusedAfter, sameNode };
|
|
93
|
-
});
|
|
100
|
+
}, ssrMarkup);
|
|
94
101
|
|
|
95
102
|
assert.strictEqual(result.focusedBefore, true, 'button should be focused before the hydration render runs');
|
|
96
|
-
assert.strictEqual(result.sameNode,
|
|
103
|
+
assert.strictEqual(result.sameNode, true, 'hydration should attach to the existing SSR node, not recreate it');
|
|
97
|
-
assert.strictEqual(result.focusedAfter, true, 'focus should
|
|
104
|
+
assert.strictEqual(result.focusedAfter, true, 'focus should remain on the same node through hydration');
|
|
98
105
|
});
|
examples/pages/index.js
CHANGED
|
@@ -1,26 +1,25 @@
|
|
|
1
|
-
import { createPage, css,
|
|
1
|
+
import { createPage, css, staticHtml, unsafeHTML } from '../../index.js';
|
|
2
2
|
import '../elements/app-counter.js';
|
|
3
3
|
import '../elements/app-total.js';
|
|
4
4
|
|
|
5
5
|
const head = ({ config }) => {
|
|
6
|
+
const styleTag = `<style>${css`
|
|
7
|
+
.page {
|
|
8
|
+
display: flex;
|
|
9
|
+
flex: 1;
|
|
10
|
+
flex-direction: column;
|
|
11
|
+
align-items: center;
|
|
12
|
+
justify-content: center;
|
|
13
|
+
}
|
|
14
|
+
`}</style>`;
|
|
6
|
-
return
|
|
15
|
+
return staticHtml`
|
|
7
16
|
<title>${config.title}</title>
|
|
8
|
-
<style>
|
|
9
|
-
${css`
|
|
10
|
-
.page {
|
|
11
|
-
display: flex;
|
|
12
|
-
flex: 1;
|
|
13
|
-
flex-direction: column;
|
|
14
|
-
align-items: center;
|
|
15
|
-
justify-content: center;
|
|
16
|
-
}
|
|
17
|
-
`}
|
|
18
|
-
|
|
17
|
+
${unsafeHTML(styleTag)}
|
|
19
18
|
`;
|
|
20
19
|
};
|
|
21
20
|
|
|
22
21
|
const body = () => {
|
|
23
|
-
return
|
|
22
|
+
return staticHtml`
|
|
24
23
|
<div class="page">
|
|
25
24
|
<app-counter name="1" meta="{'start': 5}"></app-counter>
|
|
26
25
|
<app-counter name="2" meta="{'start': 7}"></app-counter>
|
examples/server.js
CHANGED
|
@@ -18,15 +18,22 @@ elements.forEach((el) => {
|
|
|
18
18
|
srcMap['/elements/' + el] = `${__dirname}/elements/${el}`;
|
|
19
19
|
});
|
|
20
20
|
|
|
21
|
-
// lit-html and mutative are real npm dependencies (not
|
|
21
|
+
// lit-html, @lit-labs/ssr-client and mutative are real npm dependencies (not
|
|
22
|
-
// browser needs an import map for
|
|
22
|
+
// vendored), so the browser needs an import map for every bare specifier
|
|
23
|
-
//
|
|
23
|
+
// reachable from index.js — including ones used by their own internal files,
|
|
24
|
+
// since the import map is global to the page, not scoped per-package the way
|
|
25
|
+
// Node's node_modules resolution is. The packages' files are served as-is;
|
|
24
|
-
// relative, so no other wiring is needed.
|
|
26
|
+
// their own internal imports are all relative, so no other wiring is needed.
|
|
25
27
|
const importMap = {
|
|
26
28
|
imports: {
|
|
27
29
|
'lit-html': '/node_modules/lit-html/lit-html.js',
|
|
30
|
+
'lit-html/is-server.js': '/node_modules/lit-html/is-server.js',
|
|
31
|
+
'lit-html/directive.js': '/node_modules/lit-html/directive.js',
|
|
28
32
|
'lit-html/directive-helpers.js': '/node_modules/lit-html/directive-helpers.js',
|
|
33
|
+
'lit-html/private-ssr-support.js': '/node_modules/lit-html/private-ssr-support.js',
|
|
29
34
|
'lit-html/directives/unsafe-html.js': '/node_modules/lit-html/directives/unsafe-html.js',
|
|
35
|
+
'@lit-labs/ssr-client': '/node_modules/@lit-labs/ssr-client/index.js',
|
|
36
|
+
'@lit-labs/ssr/lib/server-template.js': '/node_modules/@lit-labs/ssr/lib/server-template.js',
|
|
30
37
|
mutative: '/node_modules/mutative/dist/mutative.esm.mjs',
|
|
31
38
|
},
|
|
32
39
|
};
|
index.d.ts
CHANGED
|
@@ -60,3 +60,12 @@ export function createElement(meta: any, renderFn: any): any
|
|
|
60
60
|
export function css(strings: TemplateStringsArray, ...values: any[]): string;
|
|
61
61
|
export type Handler = (props: any) => string;
|
|
62
62
|
export function createPage(props: { head: Handler, body: Handler}): (props: { props: any, headScript: string, bodyScript: string }) => string;
|
|
63
|
+
// staticHtml is for createPage's head/body only: unlike html, its output is never
|
|
64
|
+
// hydrated, so it can bind values inside <title>/<textarea>/<script>/<style>,
|
|
65
|
+
// where lit's hydration marker comments can't be inserted. Don't use it for a
|
|
66
|
+
// component's own render function.
|
|
67
|
+
export function staticHtml(strings: TemplateStringsArray, ...values: any[]): any;
|
|
68
|
+
// Wraps an object/array value passed as a dynamic attribute binding
|
|
69
|
+
// (e.g. meta=${jsonAttr(data)}) so it round-trips through this library's
|
|
70
|
+
// attribute-parsing convention instead of being stringified as [object Object].
|
|
71
|
+
export function jsonAttr(value: any): unknown;
|
index.js
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
1
|
import { html, render as litRender } from 'lit-html';
|
|
2
|
-
import { isTemplateResult } from 'lit-html/directive-helpers.js';
|
|
3
|
-
import { unsafeHTML
|
|
2
|
+
import { unsafeHTML } from 'lit-html/directives/unsafe-html.js';
|
|
3
|
+
import { directive, Directive } from 'lit-html/directive.js';
|
|
4
|
+
import { hydrate as litHydrate } from '@lit-labs/ssr-client';
|
|
5
|
+
// A template tagged with staticHtml is never hydrated, so unlike html it can bind
|
|
6
|
+
// values inside raw-text elements (<title>, <textarea>, <script>, <style>) where
|
|
7
|
+
// lit's marker comments can't be inserted. Real components nested inside (via
|
|
8
|
+
// their own tag, e.g. <app-counter>) are unaffected and still hydrate normally —
|
|
9
|
+
// use it for createPage's head/body, never for a component's own render function.
|
|
10
|
+
import { html as staticHtml } from '@lit-labs/ssr/lib/server-template.js';
|
|
4
11
|
import { create } from 'mutative';
|
|
5
12
|
|
|
6
13
|
const isBrowser = typeof window !== 'undefined';
|
|
7
|
-
export { html, isBrowser };
|
|
14
|
+
export { html, isBrowser, unsafeHTML, staticHtml };
|
|
15
|
+
|
|
16
|
+
// @lit-labs/ssr pulls in Node-only dependencies (module resolution, fetch
|
|
17
|
+
// polyfills), so it can only ever be imported on the server. This project's
|
|
18
|
+
// index.js is loaded directly in the browser too (no bundler), so the import
|
|
19
|
+
// is conditional and dynamic — in the browser this line never executes.
|
|
20
|
+
const ssr = isBrowser ? null : await import('@lit-labs/ssr');
|
|
8
21
|
|
|
9
|
-
const lastAttributeNameRegex =
|
|
10
|
-
/([ \x09\x0a\x0c\x0d])([^\0-\x1F\x7F-\x9F "'>=/]+)([ \x09\x0a\x0c\x0d]*=[ \x09\x0a\x0c\x0d]*(?:[^ \x09\x0a\x0c\x0d"'`<>=]*|"[^"]*|'[^']*))$/;
|
|
11
|
-
const tagRE = /<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g;
|
|
12
|
-
const whitespaceRE = /^\s*$/;
|
|
13
22
|
const attrRE = /\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;
|
|
14
23
|
const voidElements = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr'];
|
|
15
24
|
const STRIP_COMMENTS = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/gm;
|
|
@@ -77,223 +86,55 @@ const parseTag = (tag) => {
|
|
|
77
86
|
|
|
78
87
|
return res;
|
|
79
88
|
};
|
|
80
|
-
const parseHtml = (html) => {
|
|
81
|
-
const result = [];
|
|
82
|
-
const arr = [];
|
|
83
|
-
let current;
|
|
84
|
-
let level = -1;
|
|
85
|
-
|
|
86
|
-
// handle text at top level
|
|
87
|
-
if (html.indexOf('<') !== 0) {
|
|
88
|
-
var end = html.indexOf('<');
|
|
89
|
-
result.push({
|
|
90
|
-
type: 'text',
|
|
91
|
-
content: end === -1 ? html : html.substring(0, end),
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
html.replace(tagRE, function (tag, index) {
|
|
96
|
-
const isOpen = tag.charAt(1) !== '/';
|
|
97
|
-
const isComment = tag.startsWith('<!--');
|
|
98
|
-
const start = index + tag.length;
|
|
99
|
-
const nextChar = html.charAt(start);
|
|
100
|
-
let parent;
|
|
101
|
-
|
|
102
|
-
if (isComment) {
|
|
103
|
-
const comment = parseTag(tag);
|
|
104
|
-
|
|
105
|
-
// if we're at root, push new base node
|
|
106
|
-
if (level < 0) {
|
|
107
|
-
result.push(comment);
|
|
108
|
-
return result;
|
|
109
|
-
}
|
|
110
|
-
parent = arr[level];
|
|
111
|
-
parent.children.push(comment);
|
|
112
|
-
return result;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
if (isOpen) {
|
|
116
|
-
level++;
|
|
117
|
-
|
|
118
|
-
current = parseTag(tag);
|
|
119
|
-
|
|
120
|
-
if (!current.voidElement && nextChar && nextChar !== '<') {
|
|
121
|
-
current.children.push({
|
|
122
|
-
type: 'text',
|
|
123
|
-
content: html.slice(start, html.indexOf('<', start)),
|
|
124
|
-
});
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// if we're at root, push new base node
|
|
128
|
-
if (level === 0) {
|
|
129
|
-
result.push(current);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
parent = arr[level - 1];
|
|
133
|
-
|
|
134
|
-
if (parent) {
|
|
135
|
-
parent.children.push(current);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
arr[level] = current;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
if (!isOpen || current.voidElement) {
|
|
142
|
-
if (level > -1 && (current.voidElement || current.name === tag.slice(2, -1))) {
|
|
143
|
-
level--;
|
|
144
|
-
// move current up a level to match the end tag
|
|
145
|
-
current = level === -1 ? result : arr[level];
|
|
146
|
-
}
|
|
147
|
-
if (nextChar !== '<' && nextChar) {
|
|
148
|
-
// trailing text node
|
|
149
|
-
// if we're at the root, push a base text node. otherwise add as
|
|
150
|
-
// a child to the current node.
|
|
151
|
-
parent = level === -1 ? result : arr[level].children;
|
|
152
|
-
|
|
153
|
-
// calculate correct end of the content slice in case there's
|
|
154
|
-
// no tag after the text node.
|
|
155
|
-
const end = html.indexOf('<', start);
|
|
156
|
-
let content = html.slice(start, end === -1 ? undefined : end);
|
|
157
|
-
// if a node is nothing but whitespace, collapse it as the spec states:
|
|
158
|
-
// https://www.w3.org/TR/html4/struct/text.html#h-9.1
|
|
159
|
-
if (whitespaceRE.test(content)) {
|
|
160
|
-
content = ' ';
|
|
161
|
-
}
|
|
162
|
-
// don't add whitespace-only text nodes if they would be trailing text nodes
|
|
163
|
-
// or if they would be leading whitespace-only text nodes:
|
|
164
|
-
// * end > -1 indicates this is not a trailing text node
|
|
165
|
-
// * leading node is when level is -1 and parent has length 0
|
|
166
|
-
|
|
89
|
+
const parseAttrValue = (value) => (value && value.startsWith('{') ? JSON.parse(value.replace(/'/g, '"')) : value);
|
|
167
|
-
parent.push({
|
|
168
|
-
type: 'text',
|
|
169
|
-
content: content,
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
return result;
|
|
177
|
-
};
|
|
178
|
-
|
|
179
|
-
const stringifyAttrs = (attrs) => {
|
|
180
|
-
const buff = [];
|
|
181
|
-
for (let key in attrs) {
|
|
182
|
-
buff.push(key + '="' + attrs[key] + '"');
|
|
183
|
-
}
|
|
184
|
-
if (!buff.length) {
|
|
185
|
-
return '';
|
|
186
|
-
}
|
|
187
|
-
return ' ' + buff.join(' ');
|
|
188
|
-
};
|
|
189
90
|
|
|
190
|
-
|
|
91
|
+
class JsonAttrDirective extends Directive {
|
|
191
|
-
switch (doc.type) {
|
|
192
|
-
case 'text':
|
|
193
|
-
return buff + doc.content;
|
|
194
|
-
case 'tag':
|
|
195
|
-
buff += '<' + doc.name + (doc.attrs ? stringifyAttrs(doc.attrs) : '') + (doc.voidElement ? '/>' : '>');
|
|
196
|
-
|
|
92
|
+
render(value) {
|
|
197
|
-
return buff;
|
|
198
|
-
}
|
|
199
|
-
return buff + doc.children.reduce(stringifyHtml, '') + '</' + doc.name + '>';
|
|
200
|
-
case 'comment':
|
|
201
|
-
|
|
93
|
+
return JSON.stringify(value).replace(/"/g, `'`);
|
|
202
|
-
return buff;
|
|
203
94
|
}
|
|
204
|
-
};
|
|
205
|
-
|
|
206
|
-
const hydrate = (node) => {
|
|
207
|
-
const Clazz = getElement(node.name);
|
|
208
|
-
if (Clazz) {
|
|
209
|
-
const newAttrs = {};
|
|
210
|
-
Object.keys(node.attrs).forEach((key) => {
|
|
211
|
-
const newValue = node.attrs[key];
|
|
212
|
-
newAttrs[key] = newValue && newValue.startsWith(`{`) ? JSON.parse(newValue.replace(/'/g, `"`)) : newValue;
|
|
213
|
-
});
|
|
214
|
-
const instance = new Clazz(newAttrs);
|
|
215
|
-
const res = instance.render();
|
|
216
|
-
node.children = parseHtml(res);
|
|
217
|
-
|
|
95
|
+
}
|
|
96
|
+
// Wrap object values passed as a dynamic attribute binding to a custom element
|
|
97
|
+
// (e.g. meta=${jsonAttr(data)}) so they serialize the same way this library's
|
|
98
|
+
// attribute-parsing convention (parseAttrValue) expects to read them back.
|
|
99
|
+
export const jsonAttr = directive(JsonAttrDirective);
|
|
100
|
+
|
|
101
|
+
const collectSSR = (iterable) => {
|
|
218
|
-
|
|
102
|
+
let out = '';
|
|
219
|
-
|
|
103
|
+
for (const chunk of iterable) {
|
|
220
|
-
|
|
104
|
+
if (typeof chunk !== 'string') {
|
|
105
|
+
throw new Error('Async values are not supported in server-rendered templates');
|
|
221
106
|
}
|
|
107
|
+
out += chunk;
|
|
222
108
|
}
|
|
109
|
+
return out;
|
|
223
110
|
};
|
|
224
111
|
|
|
112
|
+
// @lit-labs/ssr renders a single template to a string with lit's hydration
|
|
113
|
+
// marker comments embedded, but has no concept of this library's own custom
|
|
114
|
+
// elements (its automatic custom-element expansion requires Shadow DOM, which
|
|
115
|
+
// this library deliberately doesn't use). So each registered tag found in that
|
|
116
|
+
// output is expanded here by rendering its own component and splicing the
|
|
117
|
+
// result between its open/close tags — never by re-parsing the already
|
|
118
|
+
// marked-up string, which would risk corrupting lit's marker comments.
|
|
225
|
-
const
|
|
119
|
+
const expandCustomElements = (htmlString) => {
|
|
226
|
-
let buffer = text;
|
|
227
|
-
const
|
|
120
|
+
const tagNames = Object.keys(registry);
|
|
228
|
-
if (
|
|
121
|
+
if (!tagNames.length) {
|
|
229
|
-
|
|
122
|
+
return htmlString;
|
|
230
123
|
}
|
|
124
|
+
const re = new RegExp(`<(${tagNames.join('|')})(?=[\\s>])([^>]*)>\\s*</\\1>`, 'g');
|
|
125
|
+
return htmlString.replace(re, (match, tagName, attrsPortion) => {
|
|
126
|
+
const { attrs } = parseTag(`<${tagName}${attrsPortion}>`);
|
|
231
|
-
|
|
127
|
+
Object.keys(attrs).forEach((key) => {
|
|
128
|
+
attrs[key] = parseAttrValue(attrs[key]);
|
|
129
|
+
});
|
|
130
|
+
const RenderElementClass = registry[tagName];
|
|
131
|
+
const instance = new RenderElementClass(attrs);
|
|
232
|
-
|
|
132
|
+
const innerHtml = instance.render();
|
|
233
|
-
|
|
133
|
+
return `<${tagName}${attrsPortion}>${innerHtml}</${tagName}>`;
|
|
234
|
-
}
|
|
134
|
+
});
|
|
235
|
-
return buffer;
|
|
236
135
|
};
|
|
237
136
|
|
|
238
|
-
const escapeAttribute = (s) => s.replace(/&/g, '&').replace(/"/g, '"');
|
|
239
|
-
const escapeText = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
240
|
-
const UNSAFE_HTML = Symbol('unsafeHtml');
|
|
241
|
-
|
|
242
|
-
export const renderHtml = isBrowser
|
|
243
|
-
? litRender
|
|
244
|
-
: (template) => {
|
|
245
|
-
let js = '';
|
|
246
|
-
template.strings.forEach((text, i) => {
|
|
247
|
-
const value = template.values[i];
|
|
248
|
-
const type = typeof value;
|
|
249
|
-
let attrName, suffix;
|
|
250
|
-
const matchName = lastAttributeNameRegex.exec(text);
|
|
251
|
-
if (matchName) {
|
|
252
|
-
attrName = matchName[2];
|
|
253
|
-
suffix = matchName[3];
|
|
254
|
-
}
|
|
255
|
-
if (value != null && type === 'object' && value[UNSAFE_HTML]) {
|
|
256
|
-
js += wrapAttribute(attrName, suffix, text, value.value);
|
|
257
|
-
} else if (value === null || !(type === 'object' || type === 'function' || type === 'undefined')) {
|
|
258
|
-
const str = type !== 'string' ? String(value) : value;
|
|
259
|
-
js += wrapAttribute(attrName, suffix, text, attrName ? escapeAttribute(str) : escapeText(str));
|
|
260
|
-
|
|
137
|
+
export const renderHtml = isBrowser ? litRender : (template) => expandCustomElements(collectSSR(ssr.render(template, {})));
|
|
261
|
-
js += text;
|
|
262
|
-
value.forEach((v) => {
|
|
263
|
-
js += renderHtml(v);
|
|
264
|
-
});
|
|
265
|
-
} else if (type === 'object') {
|
|
266
|
-
// TemplateResult
|
|
267
|
-
if (isTemplateResult(value)) {
|
|
268
|
-
js += text;
|
|
269
|
-
js += renderHtml(value);
|
|
270
|
-
} else {
|
|
271
|
-
js += wrapAttribute(attrName, suffix, text, JSON.stringify(value).replace(/"/g, `'`));
|
|
272
|
-
}
|
|
273
|
-
} else if (type == 'function') {
|
|
274
|
-
if (attrName) {
|
|
275
|
-
js += text.replace(' ' + attrName + '=', '');
|
|
276
|
-
} else {
|
|
277
|
-
// js += text;
|
|
278
|
-
// js += value();
|
|
279
|
-
}
|
|
280
|
-
} else if (type !== 'undefined') {
|
|
281
|
-
js += text;
|
|
282
|
-
js += value.toString();
|
|
283
|
-
} else {
|
|
284
|
-
js += text;
|
|
285
|
-
// console.log('value', value);
|
|
286
|
-
}
|
|
287
|
-
});
|
|
288
|
-
const nodes = parseHtml(js);
|
|
289
|
-
for (const node of nodes) {
|
|
290
|
-
hydrate(node);
|
|
291
|
-
}
|
|
292
|
-
const html = nodes.reduce((acc, node) => {
|
|
293
|
-
return acc + stringifyHtml('', node);
|
|
294
|
-
}, '');
|
|
295
|
-
return html;
|
|
296
|
-
};
|
|
297
138
|
|
|
298
139
|
const hyphenate = (s) => s.replace(/[A-Z]|^ms/g, '-$&').toLowerCase();
|
|
299
140
|
|
|
@@ -436,8 +277,6 @@ const pageStyles = {
|
|
|
436
277
|
},
|
|
437
278
|
};
|
|
438
279
|
|
|
439
|
-
export const unsafeHTML = isBrowser ? litUnsafeHTML : (value) => ({ [UNSAFE_HTML]: true, value });
|
|
440
|
-
|
|
441
280
|
const fifo = (q) => q.shift();
|
|
442
281
|
const filo = (q) => q.pop();
|
|
443
282
|
const microtask = (flush) => () => queueMicrotask(flush);
|
|
@@ -524,62 +363,6 @@ export const useEffect = (fn, deps) => {
|
|
|
524
363
|
}
|
|
525
364
|
};
|
|
526
365
|
|
|
527
|
-
// Walks/matches by element position only, since lit-html injects its own comment
|
|
528
|
-
// marker nodes (part boundaries, per-binding markers) that don't exist in the
|
|
529
|
-
// server-rendered markup and would otherwise throw off a childNodes-based index.
|
|
530
|
-
const getNodePath = (root, node) => {
|
|
531
|
-
const path = [];
|
|
532
|
-
let current = node;
|
|
533
|
-
while (current && current !== root) {
|
|
534
|
-
const parent = current.parentElement;
|
|
535
|
-
if (!parent) {
|
|
536
|
-
return null;
|
|
537
|
-
}
|
|
538
|
-
path.unshift(Array.prototype.indexOf.call(parent.children, current));
|
|
539
|
-
current = parent;
|
|
540
|
-
}
|
|
541
|
-
return current === root ? path : null;
|
|
542
|
-
};
|
|
543
|
-
|
|
544
|
-
const getNodeAtPath = (root, path) => {
|
|
545
|
-
let current = root;
|
|
546
|
-
for (const index of path) {
|
|
547
|
-
current = current && current.children[index];
|
|
548
|
-
}
|
|
549
|
-
return current || null;
|
|
550
|
-
};
|
|
551
|
-
|
|
552
|
-
const captureFocusState = (root) => {
|
|
553
|
-
const active = document.activeElement;
|
|
554
|
-
if (!active || !root.contains(active)) {
|
|
555
|
-
return null;
|
|
556
|
-
}
|
|
557
|
-
const path = getNodePath(root, active);
|
|
558
|
-
if (!path) {
|
|
559
|
-
return null;
|
|
560
|
-
}
|
|
561
|
-
const state = { path, tagName: active.tagName };
|
|
562
|
-
if (typeof active.selectionStart === 'number') {
|
|
563
|
-
state.selectionStart = active.selectionStart;
|
|
564
|
-
state.selectionEnd = active.selectionEnd;
|
|
565
|
-
}
|
|
566
|
-
return state;
|
|
567
|
-
};
|
|
568
|
-
|
|
569
|
-
const restoreFocusState = (root, state) => {
|
|
570
|
-
if (!state) {
|
|
571
|
-
return;
|
|
572
|
-
}
|
|
573
|
-
const next = getNodeAtPath(root, state.path);
|
|
574
|
-
if (!next || next.tagName !== state.tagName || typeof next.focus !== 'function') {
|
|
575
|
-
return;
|
|
576
|
-
}
|
|
577
|
-
next.focus();
|
|
578
|
-
if (state.selectionStart != null && typeof next.setSelectionRange === 'function') {
|
|
579
|
-
next.setSelectionRange(state.selectionStart, state.selectionEnd);
|
|
580
|
-
}
|
|
581
|
-
};
|
|
582
|
-
|
|
583
366
|
const registry = {};
|
|
584
367
|
const injectedStyleTags = new Set();
|
|
585
368
|
export const getElement = (name) => registry[name];
|
|
@@ -628,7 +411,7 @@ export const createElement = (meta, renderFn) => {
|
|
|
628
411
|
}
|
|
629
412
|
|
|
630
413
|
attributeChangedCallback(key, oldValue, newValue) {
|
|
631
|
-
this.attrs[key] =
|
|
414
|
+
this.attrs[key] = parseAttrValue(newValue);
|
|
632
415
|
if (this._connected) {
|
|
633
416
|
this.update();
|
|
634
417
|
}
|
|
@@ -699,16 +482,11 @@ export const createElement = (meta, renderFn) => {
|
|
|
699
482
|
document.getElementById('global').textContent += styles;
|
|
700
483
|
}
|
|
701
484
|
if (!this._hydrated) {
|
|
702
|
-
// lit-html's render() appends into the container rather than replacing its
|
|
703
|
-
//
|
|
485
|
+
// The server-rendered light-DOM markup already contains lit's hydration
|
|
704
|
-
// the first client-side render
|
|
486
|
+
// marker comments (via @lit-labs/ssr), so the first client-side render
|
|
705
|
-
// Discarding it drops focus/selection state on whatever was focused inside,
|
|
706
|
-
//
|
|
487
|
+
// attaches to that existing DOM instead of discarding and rebuilding it.
|
|
707
488
|
this._hydrated = true;
|
|
708
|
-
const focusState = captureFocusState(this);
|
|
709
|
-
this.textContent = '';
|
|
710
|
-
|
|
489
|
+
litHydrate(template, this);
|
|
711
|
-
restoreFocusState(this, focusState);
|
|
712
490
|
} else {
|
|
713
491
|
renderHtml(template, this);
|
|
714
492
|
}
|
index.test.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { test } from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
|
-
import { getElement, createElement, createPage, createReducer, html, renderHtml, unsafeHTML, css, useReducer, useEffect } from './index.js';
|
|
3
|
+
import { getElement, createElement, createPage, createReducer, html, staticHtml, renderHtml, unsafeHTML, css, useReducer, useEffect, jsonAttr } from './index.js';
|
|
4
4
|
|
|
5
5
|
test('css tagged template', (t) => {
|
|
6
6
|
const color = 'magenta';
|
|
@@ -39,7 +39,7 @@ test('renderHtml', (t) => {
|
|
|
39
39
|
const highlight = 'high';
|
|
40
40
|
const template = html`
|
|
41
41
|
<div>
|
|
42
|
-
<app-counter name="123" class="abc ${highlight}" age=${age} details1=${data} items=${items}></app-counter>
|
|
42
|
+
<app-counter name="123" class="abc ${highlight}" age=${age} details1=${jsonAttr(data)} items=${jsonAttr(items)}></app-counter>
|
|
43
43
|
</div>
|
|
44
44
|
`;
|
|
45
45
|
const res = renderHtml(template);
|
|
@@ -63,7 +63,7 @@ test('render attributes within quotes', (t) => {
|
|
|
63
63
|
const classes = 'high';
|
|
64
64
|
const template = html`
|
|
65
65
|
<div>
|
|
66
|
-
<app-counter name="123" class=${classes} age="${age}" details1="${data}" items="${items}"></app-counter>
|
|
66
|
+
<app-counter name="123" class=${classes} age="${age}" details1="${jsonAttr(data)}" items="${jsonAttr(items)}"></app-counter>
|
|
67
67
|
</div>
|
|
68
68
|
`;
|
|
69
69
|
const res = renderHtml(template);
|
|
@@ -98,7 +98,7 @@ test('render multi template', (t) => {
|
|
|
98
98
|
<div>
|
|
99
99
|
${[1, 2].map(
|
|
100
100
|
(v) => html`
|
|
101
|
-
<app-item meta="${{ index: v }}" @click=${() => {}} .handleClick=${() => {}}>
|
|
101
|
+
<app-item meta="${jsonAttr({ index: v })}" @click=${() => {}} .handleClick=${() => {}}>
|
|
102
102
|
<button @click=${() => {}}>+</button>
|
|
103
103
|
</app-item>
|
|
104
104
|
`,
|
|
@@ -233,7 +233,7 @@ test('createPage', (t) => {
|
|
|
233
233
|
return `${langPart}`;
|
|
234
234
|
};
|
|
235
235
|
const head = ({ config }) => {
|
|
236
|
-
return
|
|
236
|
+
return staticHtml`
|
|
237
237
|
<title>${config.title}</title>
|
|
238
238
|
<meta name="title" content=${config.title} />
|
|
239
239
|
<meta name="description" content=${config.title} />
|
|
@@ -241,7 +241,7 @@ test('createPage', (t) => {
|
|
|
241
241
|
};
|
|
242
242
|
|
|
243
243
|
const body = ({ config }) => {
|
|
244
|
-
return
|
|
244
|
+
return staticHtml`
|
|
245
245
|
<div>
|
|
246
246
|
<app-header></app-header>
|
|
247
247
|
<main class="flex flex-1 flex-col mt-20 items-center">
|
index.test.js.snapshot
CHANGED
|
@@ -3,15 +3,15 @@ exports[`createElement styles are scoped and injected via SSR 1`] = `
|
|
|
3
3
|
`;
|
|
4
4
|
|
|
5
5
|
exports[`createElement with attrs and hooks 1`] = `
|
|
6
|
-
"\\n <div>\\n <div>\\n <span>perPage: 5</span>
|
|
6
|
+
"<!--lit-part z5rbBgZAlEw=-->\\n <div>\\n <div>\\n <span>perPage: <!--lit-part-->5<!--/lit-part--></span>\\n </div>\\n </div>\\n <span>Count: <!--lit-part-->3<!--/lit-part--></span>\\n </div>\\n <!--lit-node 6--><button >Set</button>\\n </div>\\n <!--/lit-part-->"
|
|
7
7
|
`;
|
|
8
8
|
|
|
9
9
|
exports[`createElement without attrs 1`] = `
|
|
10
|
-
" <div></div>"
|
|
10
|
+
"<!--lit-part Wd91oPYJke0=--> <div></div> <!--/lit-part-->"
|
|
11
11
|
`;
|
|
12
12
|
|
|
13
13
|
exports[`createPage 1`] = `
|
|
14
|
-
"\\n <!DOCTYPE html>\\n <html lang=\\"en\\">\\n <head>\\n <meta charset=\\"utf-8\\" />\\n <meta http-equiv=\\"x-ua-compatible\\" content=\\"ie=edge\\" />\\n <meta http-equiv=\\"Content-Type\\" content=\\"text/html; charset=utf-8\\">\\n <meta name=\\"viewport\\" content=\\"width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=5.0, shrink-to-fit=no\\">\\n <link rel=\\"sitemap\\" type=\\"application/xml\\" href=\\"/sitemap.xml\\" />\\n <link rel=\\"icon\\" type=\\"image/png\\" href=\\"/assets/icon.png\\" />\\n \\n <title>123</title>
|
|
14
|
+
"\\n <!DOCTYPE html>\\n <html lang=\\"en\\">\\n <head>\\n <meta charset=\\"utf-8\\" />\\n <meta http-equiv=\\"x-ua-compatible\\" content=\\"ie=edge\\" />\\n <meta http-equiv=\\"Content-Type\\" content=\\"text/html; charset=utf-8\\">\\n <meta name=\\"viewport\\" content=\\"width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=5.0, shrink-to-fit=no\\">\\n <link rel=\\"sitemap\\" type=\\"application/xml\\" href=\\"/sitemap.xml\\" />\\n <link rel=\\"icon\\" type=\\"image/png\\" href=\\"/assets/icon.png\\" />\\n \\n <title>123</title>\\n <meta name=\\"title\\" content=\\"123\\" />\\n <meta name=\\"description\\" content=\\"123\\" />\\n \\n <style id=\\"global\\">\\n *, ::before, ::after {\\n\\n box-sizing: border-box;\\n border-width: 0;\\n border-style: solid;\\n border-color: #e5e7eb;\\n\\n}\\nhr {\\n\\n height: 0;\\n color: inherit;\\n border-top-width: 1px;\\n\\n}\\nabbr[title] {\\n\\n -webkit-text-decoration: underline dotted;\\n text-decoration: underline dotted;\\n\\n}\\nb, strong {\\n\\n font-weight: bolder;\\n\\n}\\ncode, kbd, samp, pre {\\n\\n font-family: ui-monospace, SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;\\n font-size: 1em;\\n\\n}\\nsmall {\\n\\n font-size: 80%;\\n\\n}\\nsub, sup {\\n\\n font-size: 75%;\\n line-height: 0;\\n position: relative;\\n vertical-align: baseline;\\n\\n}\\nsub {\\n\\n bottom: -0.25em;\\n\\n}\\nsup {\\n\\n top: -0.5em;\\n\\n}\\ntable {\\n\\n text-indent: 0;\\n border-color: inherit;\\n border-collapse: collapse;\\n\\n}\\nbutton, input, optgroup, select, textarea {\\n\\n font-size: 100%;\\n margin: 0;\\n padding: 0;\\n line-height: inherit;\\n color: inherit;\\n\\n}\\nbutton, select {\\n\\n\\n}\\nbutton, [type='button'], [type='reset'], [type='submit'] {\\n\\n\\n}\\n::-moz-focus-inner {\\n\\n border-style: none;\\n padding: 0;\\n\\n}\\n:-moz-focusring {\\n\\n outline: 1px dotted ButtonText;\\n\\n}\\n:-moz-ui-invalid {\\n\\n box-shadow: none;\\n\\n}\\nlegend {\\n\\n padding: 0;\\n\\n}\\nprogress {\\n\\n vertical-align: baseline;\\n\\n}\\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\\n\\n height: auto;\\n\\n}\\n[type='search'] {\\n\\n -webkit-appearance: textfield;\\n outline-offset: -2px;\\n\\n}\\n::-webkit-search-decoration {\\n\\n -webkit-appearance: none;\\n\\n}\\n::-webkit-file-upload-button {\\n\\n -webkit-appearance: button;\\n font: inherit;\\n\\n}\\nsummary {\\n\\n display: list-item;\\n\\n}\\nblockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre {\\n\\n margin: 0;\\n\\n}\\nbutton {\\n\\n background-image: none;\\n\\n outline: 1px dotted, 5px auto -webkit-focus-ring-color;\\n\\n}\\nfieldset {\\n\\n margin: 0;\\n padding: 0;\\n\\n}\\nol, ul {\\n\\n list-style: none;\\n margin: 0;\\n padding: 0;\\n\\n}\\nimg {\\n\\n border-style: solid;\\n\\n}\\ntextarea {\\n\\n resize: vertical;\\n\\n}\\ninput::-moz-placeholder, textarea::-moz-placeholder {\\n\\n opacity: 1;\\n color: #9ca3af;\\n\\n}\\ninput:-ms-input-placeholder, textarea:-ms-input-placeholder {\\n\\n opacity: 1;\\n color: #9ca3af;\\n\\n}\\ninput::placeholder, textarea::placeholder {\\n\\n opacity: 1;\\n color: #9ca3af;\\n\\n}\\nbutton, [role='button'] {\\n\\n cursor: pointer;\\n\\n}\\nh1, h2, h3, h4, h5, h6 {\\n\\n font-size: inherit;\\n font-weight: inherit;\\n\\n}\\na {\\n\\n color: inherit;\\n text-decoration: inherit;\\n\\n}\\npre, code, kbd, samp {\\n\\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;\\n\\n}\\nimg, svg, video, canvas, audio, iframe, embed, object {\\n\\n display: block;\\n vertical-align: middle;\\n\\n}\\nimg, video {\\n\\n max-width: 100%;\\n height: auto;\\n\\n}\\nhtml {\\n\\n -moz-tab-size: 4;\\n -o-tab-size: 4;\\n tab-size: 4;\\n line-height: 1.5;\\n -webkit-text-size-adjust: 100%;\\n font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';\\n width: 100%;\\n height: 100%;\\n\\n}\\nbody {\\n\\n margin: 0px;\\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;\\n line-height: 1.4;\\n background-color: white;\\n width: 100%;\\n height: 100%;\\n display: flex;\\n flex-direction: column;\\n flex: 1 1 0%;\\n min-width: 320px;\\n min-height: 100vh;\\n font-weight: 400;\\n color: rgba(44, 62, 80, 1);\\n direction: ltr;\\n font-synthesis: none;\\n text-rendering: optimizeLegibility;\\n\\n}\\n\\n \\n </style>\\n <script type=\\"module\\"><script>\\n </head>\\n <body>\\n \\n <div>\\n <app-header></app-header>\\n <main class=\\"flex flex-1 flex-col mt-20 items-center\\">\\n <h1 class=\\"text-5xl\\">123</h1>\\n </main>\\n </div>\\n \\n <script>\\n window.props = {\\"config\\":{\\"title\\":\\"123\\"}};\\n </script>\\n <script type=\\"module\\"><script>\\n </body>\\n </html>\\n "
|
|
15
15
|
`;
|
|
16
16
|
|
|
17
17
|
exports[`css tagged template 1`] = `
|
|
@@ -19,29 +19,29 @@ exports[`css tagged template 1`] = `
|
|
|
19
19
|
`;
|
|
20
20
|
|
|
21
21
|
exports[`render attribute keys 1`] = `
|
|
22
|
-
"\\n <div>\\n <app-counter name=\\"123\\" perPage=\\"1\\"></app-counter>
|
|
22
|
+
"<!--lit-part Jm3yLdRDsSk=-->\\n <div>\\n <app-counter name=\\"123\\" perPage=\\"1\\"></app-counter>\\n </div>\\n <!--/lit-part-->"
|
|
23
23
|
`;
|
|
24
24
|
|
|
25
25
|
exports[`render attributes within quotes 1`] = `
|
|
26
|
-
"\\n <div>\\n <app-counter name=\\"123\\" class=\\"high\\" age=\\"1\\" details1=\\"{
|
|
26
|
+
"<!--lit-part NYzZmKc0ApY=-->\\n <div>\\n <!--lit-node 1--><app-counter name=\\"123\\" class=\\"high\\" age=\\"1\\" details1=\\"{'name':'123','address':{'street':'1'}}\\" items=\\"[1,2,3]\\"></app-counter>\\n </div>\\n <!--/lit-part-->"
|
|
27
27
|
`;
|
|
28
28
|
|
|
29
29
|
exports[`render multi template 1`] = `
|
|
30
|
-
"\\n <div>\\n \\n <app-item meta=\\"{
|
|
30
|
+
"<!--lit-part xbA0QwrFuvM=-->\\n <div>\\n <!--lit-part--><!--lit-part iq0TqtY/tw4=-->\\n <!--lit-node 0--><app-item meta=\\"{'index':1}\\" >\\n <!--lit-node 1--><button >+</button>\\n </app-item>\\n <!--/lit-part--><!--lit-part iq0TqtY/tw4=-->\\n <!--lit-node 0--><app-item meta=\\"{'index':2}\\" >\\n <!--lit-node 1--><button >+</button>\\n </app-item>\\n <!--/lit-part--><!--/lit-part-->\\n </div>\\n <!--/lit-part-->"
|
|
31
31
|
`;
|
|
32
32
|
|
|
33
33
|
exports[`render single template 1`] = `
|
|
34
|
-
" <div>NoCountry false</div>"
|
|
34
|
+
"<!--lit-part Wd91oPYJke0=--> <div><!--lit-part 8PHODPkg0Ao=-->NoCountry <!--lit-part-->false<!--/lit-part--><?><!--/lit-part--></div> <!--/lit-part-->"
|
|
35
35
|
`;
|
|
36
36
|
|
|
37
37
|
exports[`render unsafeHTML 1`] = `
|
|
38
|
-
" <div><div><p class=\\"123\\">this is unsafe</p></div></div>"
|
|
38
|
+
"<!--lit-part Wd91oPYJke0=--> <div><!--lit-part MbydkCRGgUo=--><div><p class=\\"123\\">this is unsafe</p></div><!--/lit-part--></div> <!--/lit-part-->"
|
|
39
39
|
`;
|
|
40
40
|
|
|
41
41
|
exports[`renderHtml 1`] = `
|
|
42
|
-
"\\n <div>\\n <app-counter name=\\"123\\" class=\\"abc high\\" age=\\"1\\" details1=\\"{
|
|
42
|
+
"<!--lit-part 4yM259EK+Bs=-->\\n <div>\\n <!--lit-node 1--><app-counter name=\\"123\\" class=\\"abc high\\" age=\\"1\\" details1=\\"{'name':'123','address':{'street':'1'}}\\" items=\\"[1,2,3]\\"></app-counter>\\n </div>\\n <!--/lit-part-->"
|
|
43
43
|
`;
|
|
44
44
|
|
|
45
45
|
exports[`renderHtml escapes text and attribute values 1`] = `
|
|
46
|
-
"<div class=\\"a" onmouseover="alert(1)\\"><script>alert(1)</script></div>"
|
|
46
|
+
"<!--lit-part PkF/hiJU4II=--><!--lit-node 0--><div class=\\"a" onmouseover="alert(1)\\"><!--lit-part--><script>alert(1)</script><!--/lit-part--></div><!--/lit-part-->"
|
|
47
47
|
`;
|
package.json
CHANGED
|
@@ -39,6 +39,8 @@
|
|
|
39
39
|
"trailingComma": "all"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
+
"@lit-labs/ssr": "^4.1.0",
|
|
43
|
+
"@lit-labs/ssr-client": "^1.1.8",
|
|
42
44
|
"lit-html": "^3.3.3",
|
|
43
45
|
"mutative": "^1.3.0"
|
|
44
46
|
}
|