-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathnomini.js
More file actions
387 lines (316 loc) · 12.6 KB
/
Copy pathnomini.js
File metadata and controls
387 lines (316 loc) · 12.6 KB
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Nomini v0.3.1
// Inspired by aidenybai/dababy
// Copyright (c) 2025 nonnorm
// Licensed under the MIT License.
(() => {
// Utility functions
const dispatch = (el, name, opts) => {
opts = { bubbles: true, detail: {}, ...opts };
el.dispatchEvent(new CustomEvent(name, opts));
};
const evalExpression = (expression, data, thisArg) => {
if (/^{.*}$/s.test(expression)) {
expression = expression.slice(1, -1);
}
try {
return new Function(
"__data",
`with(__data) {return {${expression}}}`,
).call(thisArg, data);
} catch (err) {
console.error("[Nomini] failed to parse obj:", expression, "\n", err);
return {};
}
};
const queryAttr = (el, selector) => {
const elMatch = el.matches(selector) ? [el] : [];
return [...elMatch, ...el.querySelectorAll(selector)].filter(
(val) => !val.closest("[nm-ignore]"),
);
};
const getClosestProxy = (el) =>
el.closest("[nm-data]")?.nmProxy || helpers();
const runTracked = (fn) => {
currentBind = fn;
currentBind();
currentBind = null;
};
const runWithEl = (el, fn) => {
currentEl = el;
fn();
currentEl = null;
};
// Important reactivity stuff
let currentBind = null;
let currentEl = null;
// Helpers that are included with every data object
const helpers = () => ({
// --- BEGIN ref
$refs: {},
// --- END ref
// --- BEGIN fetch
_nmFetching: false,
_nmAbort: new AbortController(),
$get(url, data) {
this.$fetch(url, "GET", data);
},
$post(url, data) {
this.$fetch(url, "POST", data);
},
$fetch(url, method, data) {
const el = currentEl;
this._nmAbort.abort();
this._nmAbort = new AbortController();
this._nmFetching = true;
const opts = {
headers: { "nm-request": true },
method,
signal: this._nmAbort.signal,
};
data = { ...this.$nmData(), ...this.$dataset(), ...data };
const encodedData = new URLSearchParams(data);
if (/GET|DELETE/.test(method))
url += (url.includes("?") ? "&" : "?") + encodedData;
else opts.body = encodedData;
fetch(url, opts)
.then(async (res) => {
if (!res.ok) {
throw new Error(`${res.statusText}: ${await res.text()}`);
}
const stream = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = "";
let timeout;
while (true) {
const { done, value } = await stream.read();
if (done) break;
buf += value;
clearTimeout(timeout);
timeout = setTimeout(() => {
swap(buf);
buf = "";
}, 20);
}
})
.catch((err) => dispatch(el, "fetcherr", { detail: { err, url } }))
.finally(() => this._nmFetching = false);
},
$nmData() {
const isPrimitive = (x) => x !== Object(x);
return Object.entries(this).reduce((acc, [k, v]) => {
if (!/^[a-z]+$/i.test(k)) return acc;
if (typeof v === "function") v = v();
if (isPrimitive(v) || (Array.isArray(v) && v.every(isPrimitive)))
acc[k] = v;
return acc;
}, {});
},
// --- END fetch
$dataset() {
let datasets = {};
let el = currentEl;
while (el) {
datasets = { ...el.dataset, ...datasets };
if (el.hasAttribute("nm-data")) break;
el = el.parentElement;
}
return datasets;
},
$watch: runTracked,
$dispatch(evt, detail, opts) {
dispatch(currentEl, evt, { detail, ...opts });
},
$debounce(fn, ms, abortable = true) {
const el = currentEl;
const signal = this._nmAbort.signal;
clearTimeout(el.nmTimer);
el.nmTimer = setTimeout(() => {
if (!(abortable && signal.aborted)) runWithEl(el, fn)
}, ms);
},
// --- BEGIN helpers
$persist(prop, key) {
key = key || `_nmProp-${prop}`;
const stored = localStorage[key];
if (stored) this[prop] = JSON.parse(stored);
runTracked(() => {
localStorage[key] = JSON.stringify(this[prop]);
});
},
// --- END helpers
});
// --- BEGIN fetch
const swap = (text) => {
const template = document.createElement("template");
template.innerHTML = text;
for (const fragment of [...template.content.children]) {
if (!fragment.id) {
console.warn("[Nomini] Fragment is missing an id: ", fragment);
continue;
}
const strategy = fragment.getAttribute("nm-swap") || "outer";
const target = document.getElementById(fragment.id);
if (!target) {
console.warn("[Nomini] Swap target not found: #", fragment.id);
continue;
}
queryAttr(target, "[nm-bind]").forEach(
(el) => dispatch(el, "destroy", { bubbles: false })
);
// --- BEGIN morph
cssMorph(fragment);
// --- END morph
if (strategy === "inner") {
target.replaceChildren(...fragment.childNodes);
init(target);
} else if (strategy === "outer") {
target.replaceWith(fragment);
init(fragment);
} else if (/(before|after|prepend|append)/.test(strategy)) {
const kids = [...fragment.childNodes];
target[strategy](...kids);
kids.forEach((n) => n.nodeType === 1 && init(n));
} else console.error("[Nomini] Invalid swap strategy: ", strategy);
}
};
// --- END fetch
// --- BEGIN morph
const cssMorph = (fragment) => {
const attributesToSettle = ["style", "class", "height", "width"];
const idSet = queryAttr(fragment, "[id]");
idSet.forEach((newEl) => {
const oldEl = document.getElementById(newEl.id);
if (oldEl && oldEl.tagName === newEl.tagName) {
const newElCopy = newEl.cloneNode();
const morph = (src) =>
attributesToSettle.forEach((attr) => {
const attrVal = src.getAttribute(attr);
if (attrVal) newEl.setAttribute(attr, attrVal);
else newEl.removeAttribute(attr);
});
morph(oldEl);
requestAnimationFrame(() => morph(newElCopy));
}
});
};
// --- END morph
const init = (baseEl) => {
// --- BEGIN template
queryAttr(baseEl, "[nm-use]").forEach((useEl) => {
const id = useEl.getAttribute("nm-use");
const template = document.getElementById(id);
if (template) {
const templateFrag = template.content.cloneNode(true);
const slot = templateFrag.querySelector("slot:not([name])");
if (slot) slot.replaceWith(...useEl.childNodes);
useEl.replaceChildren(templateFrag);
} else console.error("[Nomini] No template with id: #", id);
});
// --- END template
// --- BEGIN data
queryAttr(baseEl, "[nm-data]").forEach((dataEl) => {
const rawData = {
...evalExpression(dataEl.getAttribute("nm-data"), {}, dataEl),
...helpers(),
};
const trackedDeps = {};
const proxyData = new Proxy(rawData, {
get(obj, prop) {
if (currentBind) (trackedDeps[prop] ||= new Set()).add(currentBind);
return obj[prop];
},
set(obj, prop, val) {
obj[prop] = val;
const deps = trackedDeps[prop];
if (deps) {
// Required to prevent infinite loops (this took 3 hours to debug!)
const thisBind = currentBind;
currentBind = null;
deps.forEach((fn) => fn());
currentBind = thisBind;
}
return true;
},
});
dataEl.nmProxy = proxyData;
});
// --- END data
// --- BEGIN ref
queryAttr(baseEl, "[nm-ref]").forEach((el) => {
const proxyData = getClosestProxy(el);
const refName = el.getAttribute("nm-ref");
proxyData.$refs[refName] = el;
});
// --- END ref
// --- BEGIN form
queryAttr(baseEl, "[nm-form]").forEach((el) => {
const proxyData = getClosestProxy(el);
queryAttr(el, "[name]").forEach((inputEl) => {
const inputType = inputEl.type;
const setVal = () => {
let res;
if (inputType === "checkbox")
res = inputEl.checked;
else if (inputType === "radio" && inputEl.checked)
res = inputEl.value;
else if (inputType === "file")
res = inputEl.files;
else if (/number|range/.test(inputType))
res = +inputEl.value;
else res = inputEl.value;
proxyData[inputEl.name] = res;
};
setVal();
inputEl.addEventListener("input", setVal);
inputEl.addEventListener("change", setVal);
});
queryAttr(el, "button, input[type='submit']").forEach((submitEl) => {
runTracked(() => submitEl.disabled = proxyData._nmFetching);
});
});
// --- END form
// --- BEGIN bind
queryAttr(baseEl, "[nm-bind]").forEach((bindEl) => {
const proxyData = getClosestProxy(bindEl);
const props = evalExpression(
bindEl.getAttribute("nm-bind"),
proxyData,
bindEl,
);
Object.entries(props).forEach(([key, val]) => {
if (key.startsWith("on")) {
// --- BEGIN events
const [eventName, ...mods] = key.slice(2).split(".");
const debounceMod = mods.find((val) => val.startsWith("debounce"));
const delay = +debounceMod?.slice(8);
const listener = (e) => runWithEl(bindEl, () => {
if (mods.includes("prevent")) e.preventDefault();
if (mods.includes("stop")) e.stopPropagation();
if (delay) proxyData.$debounce(() => val(e), delay);
else val(e);
});
(mods.includes("window") ? window : bindEl).addEventListener(eventName, listener, {
once: mods.includes("once"),
});
return;
// --- END events
// If special event handling isn't enabled just do a normal event listener
bindEl.addEventListener(key.slice(2), () => runWithEl(bindEl, val));
} else {
const [main, sub] = key.split(".");
runWithEl(bindEl,
() => runTracked(async () => {
const resolvedVal = await val();
if (sub) {
if (main === "class") bindEl.classList.toggle(sub, resolvedVal);
else bindEl[main][sub] = resolvedVal;
} else bindEl[main] = resolvedVal;
})
);
}
});
dispatch(bindEl, "init", { bubbles: false });
});
// --- END bind
};
document.addEventListener("DOMContentLoaded", () => init(document.body));
})();