-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
254 lines (227 loc) · 9.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/* (c) 2023 - by Markus Walther, MIT License.
*
* sig-html is a micro framework for web apps based on plain or computed signals + lit-html template notation.
*
* Supported lit-html notation (cf. https://lit.dev):
*
* <div attribute="${1}" .property="${2}" ?booleanAttribute="${false}" @event="${e => alert(e)}">${5}</div>
*
* Known restrictions:
* - Signals are the only mechanism provided for reactivity
* - any literal variables must span the entire attribute value or text content in which it occurs, i.e. no 'some ${...} other text or template variable' is allowed (for now)
* - no HTML validation or sanitizing whatsoever
* - no careful memory or performance optimizations (yet)
*/
// constants
let SUBSCRIBE = "subscribe";
let TEXTCONTENT = "textContent";
let ATTRIBUTE = "Attribute";
let GET = "get";
let SET = "set";
let REMOVE = "remove";
let GETATTRIBUTE = GET + ATTRIBUTE;
let GETATTRIBUTENAMES = GETATTRIBUTE + "Names";
let APPENDCHILD = "appendChild";
let DEFAULT_EFFECT = (domNode, value) => (domNode[TEXTCONTENT] = value); // set the text content of an assumed Text node to a value
let DEFAULT_REACTION = identity => identity; // the identity value transform
let LIT_HTML_SPECIALS = ".?@";
// module globals
let plugs2Values = {};
let plugCounter = 0;
let parser = new DOMParser();
let d = document;
// helper functions
let parse = htmlText => {
return parser.parseFromString(htmlText, "text/html"); // returns document tree corresponding to <html><head></head><body>child nodes</body></html>
};
let extractNodes = dom => dom?.all[2].childNodes; // extract the <html>, then the <body>, then the children under it
let isText = domNode => domNode.nodeType === 3; // is it a Text node?
let isFunction = f => typeof f === "function";
// determine an attribute's type; returns a pair of [sanitizedAttribute, indexOfSpecialCharacterOrZero]
// Note: missing/undefined attribute initialized to 'impossible' string "\0" with which search for special character will fail with -1 index
let attributeType = (attribute = "\0") => {
let firstCharacter = attribute[0];
// lit-html-style prefixed attribute?
let litHTMLSpecialIndex = LIT_HTML_SPECIALS.indexOf(firstCharacter) + 1;
return [
litHTMLSpecialIndex ? /* yes, strip first character */ attribute.slice(1) : /* no, return as-is */ attribute,
litHTMLSpecialIndex
];
};
let deriveEffect =
([attribute, litHTMLSpecialIndex]) =>
// given a DOM node and a value:
(domNode, value) =>
[
/* a Text node or a plain, undecorated attribute */
() =>
isText(domNode)
? DEFAULT_EFFECT(domNode, value) // effect: set text content to value
: domNode[SET + ATTRIBUTE](attribute, value), // effect: set attribute to value
/* a .property */
() => (domNode[attribute] = value), // effect: set property to value
/* a ?Boolean attribute */
() => domNode[(value ? SET : REMOVE) + ATTRIBUTE](attribute, ""), // effect: add or remove Boolean attribute
/* an @event handler */
() => {
let { listener, options } = isFunction(value) ? { listener: value, options: false } : value;
domNode.addEventListener(attribute, listener, options);
} // effect: attach event listener for event named in value
][litHTMLSpecialIndex]();
let handleEffect = (attribute, domNode, value) => {
// try to get initial value from attribute value
if (value === undefined && GETATTRIBUTE in domNode) {
value = domNode[GETATTRIBUTE](attribute);
}
// determine attribute type according to lit-html's notational conventions
let type = attributeType(attribute);
// is it a lit-html-annotated attribute?
if (type[1]) {
// yes, remove it (it will replaced by the effect it induces on the DOM node)
domNode[REMOVE + ATTRIBUTE](attribute);
}
// is the value indicative of a filled string-template variable a.k.a. 'plug'?
if (value in plugs2Values) {
// yes, get its associated real value
value = plugs2Values[value];
}
// return the tuple of [effect, value], with side effects of handling any signal values
return [deriveEffect(type), handleSignal(domNode, value, attribute)];
};
let isSignal = signal => signal instanceof Signal;
let handleSignal = (domNode, value, attribute) => {
// value represents a straightforward signal?
if (isSignal(value)) {
// yes, subscribe DOM node and get initial value of the signal
value = value[SUBSCRIBE](domNode, attribute);
// value represents a computed signal?
} else if (Array.isArray(value) && isSignal(value[0])) {
// get its effect
let effect = value[1];
// install effect for DOM node
let reaction = effect(domNode, attribute);
// compute initial value as reaction to initial signal value
value = reaction(value);
}
// return the - possibly signal-transformed - value
return value;
};
let handleVariables = domNode => {
// Text node?
if (isText(domNode)) {
// yes, try to see whether it contains a plug
let value = plugs2Values[domNode[TEXTCONTENT]];
// it does?
if (value != undefined) {
// yes, see if it is a signal, too
let parent = domNode.parentNode;
let signal = isSignal(value) && value;
value = handleSignal(domNode, value);
// and - for text - assign its initial text content
if (/string|number|boolean/.test(typeof value)) DEFAULT_EFFECT(domNode, value);
else if (parent && signal && "value" in signal && value instanceof Node) {
// for signals containing a piece of DOM...
// remove text node
domNode[REMOVE]();
// set its initial DOM content on the parent of the text node
parent[APPENDCHILD](value);
// and update the signal to point to the parent, so later render(signal,...) works as expected
signal.value = parent;
}
}
}
// HTMLElement node?
if (!isFunction(domNode[GETATTRIBUTENAMES])) return; // no (also exit for Text nodes)
// yes, loop through its attributes:
for (let attribute of domNode[GETATTRIBUTENAMES]()) {
// getting the appropriate effect and initial value for each
let [effect, value] = handleEffect(attribute, domNode);
// and executing that effect initially once
effect(domNode, value);
}
};
// API
// replace the string-template variables with unique 'plug' strings s.t. the resulting fully instantiated string can be DOM-parsed.
// Along the way, remember the association of plugs with their corresponding variable values
export let html = (fragments, ...values) => {
let n = fragments.length;
let m = values.length;
// otherwise initialize a result strings array (we need to copy, because fragments originating from tagged string template literals are read-only,
// i.e. can not be re-assigned in-place)
let strings = [];
// for all string fragments, in order:
for (let i = 0, plug; i < n; i++) {
// calculate unique string-valued variable filler a.k.a. 'plug' that's unlikely to be confused with a real attribute value or text content
plug = i < m ? `_${++plugCounter}${Math.random() * 1e18}_` : "";
// the fragment with right-adjacent variable is replaced by the fragment with right-adjacent 'plug'
strings[i] = fragments[i] + plug;
// and we remember the association between 'plug' and original variable value
plugs2Values[plug] = values[i];
}
return strings.join("");
};
// render plugged string-template HTML under a root node
export let render = (rootNode, pluggedHTML = "", domTree) => {
let aSignal = isSignal(rootNode);
domTree = domTree ?? aSignal ? rootNode.value : d.createDocumentFragment();
// extract a list of child nodes from parsed, string-template-variables-plugged HTML text
let domHTML = extractNodes(parse(pluggedHTML));
// create a corresponding DOM tree, reparenting the child nodes under a new document fragment
for (let domNode of domHTML) {
domTree[APPENDCHILD](domNode);
}
// walk the entire DOM tree under the document fragment...
for (let treeWalker = d.createTreeWalker(domTree, 5); treeWalker.nextNode(); ) {
// ... handling its string template variables-turned-unique-plugs
handleVariables(treeWalker.currentNode);
}
// finally, append the DOM tree under the root node provided
return aSignal ? domTree : rootNode ? rootNode[APPENDCHILD](domTree) : domTree;
};
// provide plain and computed signals
export class Signal {
// private instance variables
#value;
#subscribers;
#effects;
constructor(initialValue) {
this.#value = initialValue;
this.#subscribers = new Set();
this.#effects = new WeakMap();
}
subscribe(domNode, attribute, reaction = DEFAULT_REACTION) {
this.#subscribers.add(domNode);
if (isSignal(domNode)) return;
let effect = deriveEffect(attributeType(attribute));
let effects = this.#effects.get(domNode) || new Set();
effects.add((newValue, node) => effect(node, reaction(newValue)));
this.#effects[SET](domNode, effects);
return this.#value;
}
get value() {
return this.#value;
}
set value(newValue) {
this.#value = newValue;
for (let domNode of this.#subscribers) {
if (isSignal(domNode)) {
domNode.value = undefined;
continue;
}
for (let effect of this.#effects[GET](domNode)) {
effect(newValue, domNode);
}
}
}
// define a derived signal, which applies a value transform a.k.a. reaction whenever a signal value changes
computed(reaction, when = []) {
when.forEach(signal => signal[SUBSCRIBE](this));
return [
this,
(domNode, attribute) => {
this[SUBSCRIBE](domNode, attribute, reaction);
return reaction;
}
];
}
}