lightview 1.8.1-b → 1.8.2

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.
Files changed (126) hide show
  1. package/README.md +15 -16
  2. package/docs/CNAME +1 -0
  3. package/docs/api.html +674 -0
  4. package/docs/blank.html +10 -0
  5. package/docs/comparedto.html +89 -0
  6. package/docs/components/chart-repl.html +69 -0
  7. package/{components/chart → docs/components}/chart.html +2 -2
  8. package/{components → docs/components}/components.js +3 -3
  9. package/docs/components/contents.html +17 -0
  10. package/docs/components/gantt-repl.html +61 -0
  11. package/{components/gantt → docs/components}/gantt.html +3 -3
  12. package/docs/components/gauge-repl.html +66 -0
  13. package/{components/gauge → docs/components}/gauge.html +2 -2
  14. package/docs/components/orgchart-repl.html +64 -0
  15. package/{components/orgchart → docs/components}/orgchart.html +2 -2
  16. package/docs/components/repl-as-src.html +17 -0
  17. package/docs/components/repl-repl.html +95 -0
  18. package/docs/components/repl.html +527 -0
  19. package/docs/components/timeline-repl.html +72 -0
  20. package/{components/timeline → docs/components}/timeline.html +2 -2
  21. package/docs/components.html +14 -0
  22. package/docs/css/highlightjs.min.css +9 -0
  23. package/docs/css/tutorial.css +35 -0
  24. package/docs/examples/anchor.html +11 -0
  25. package/{examples → docs/examples}/chart.html +2 -2
  26. package/{examples → docs/examples}/counter.html +1 -1
  27. package/{examples → docs/examples}/counter.test.mjs +0 -0
  28. package/{examples → docs/examples}/counter2.html +1 -1
  29. package/{examples → docs/examples}/directives.html +1 -1
  30. package/{examples → docs/examples}/foreign.html +1 -1
  31. package/{examples → docs/examples}/forgeinform.html +1 -1
  32. package/{examples → docs/examples}/form.html +1 -1
  33. package/{examples → docs/examples}/gauge.html +2 -2
  34. package/{examples → docs/examples}/invalid-template-literals.html +1 -1
  35. package/{examples → docs/examples}/medium/remote.html +1 -1
  36. package/{examples → docs/examples}/message.html +0 -0
  37. package/{examples → docs/examples}/nested.html +1 -1
  38. package/{examples → docs/examples}/object-bound-form.html +0 -0
  39. package/{examples → docs/examples}/remote-server.js +0 -0
  40. package/{examples → docs/examples}/remote.html +2 -2
  41. package/{examples → docs/examples}/remote.json +0 -0
  42. package/{examples → docs/examples}/scratch.html +1 -1
  43. package/docs/examples/sensors/index.html +44 -0
  44. package/{examples → docs/examples}/sensors/sensor-server.js +0 -0
  45. package/{examples → docs/examples}/shared.html +0 -0
  46. package/{examples → docs/examples}/template.html +1 -1
  47. package/{examples → docs/examples}/timeline.html +2 -2
  48. package/docs/examples/todo.html +40 -0
  49. package/docs/examples/top.html +10 -0
  50. package/{examples → docs/examples}/types.html +1 -1
  51. package/{examples → docs/examples}/xor.html +1 -1
  52. package/docs/examples.html +25 -0
  53. package/docs/index.html +44 -0
  54. package/docs/javascript/codejar.min.js +8 -0
  55. package/docs/javascript/highlightjs.min.js +1173 -0
  56. package/docs/javascript/isomorphic-git.js +9 -0
  57. package/docs/javascript/json5.min.js +1 -0
  58. package/docs/javascript/lightning-fs.js +1 -0
  59. package/docs/javascript/lightview.js +1285 -0
  60. package/docs/javascript/marked.min.js +6 -0
  61. package/docs/javascript/peerjs.min.js +70 -0
  62. package/docs/javascript/turndown.js +973 -0
  63. package/docs/javascript/types.js +606 -0
  64. package/docs/javascript/utils.js +45 -0
  65. package/docs/lightview.html +63 -0
  66. package/docs/old_index.html +965 -0
  67. package/docs/old_index.md +1132 -0
  68. package/docs/slidein.html +51 -0
  69. package/docs/tutorial/0-getting-started.html +67 -0
  70. package/docs/tutorial/1-intro-to-variables.html +103 -0
  71. package/docs/tutorial/10-template-components.html +80 -0
  72. package/docs/tutorial/11-linked-components.html +76 -0
  73. package/docs/tutorial/12-imported-components.html +67 -0
  74. package/docs/tutorial/13-input-binding.html +94 -0
  75. package/docs/tutorial/14-automatic-variable-creation.html +74 -0
  76. package/docs/tutorial/15-form-binding.html +110 -0
  77. package/docs/tutorial/16-if-directive.html +60 -0
  78. package/docs/tutorial/17-loop-directives.html +83 -0
  79. package/docs/tutorial/18-sanitizing-and-escaping-input.html +79 -0
  80. package/docs/tutorial/2-imported-and-exported-variables.html +80 -0
  81. package/docs/tutorial/3-data-types.html +89 -0
  82. package/docs/tutorial/4-extended-data-types.html +83 -0
  83. package/docs/tutorial/5-extended-functional-types.html +96 -0
  84. package/docs/tutorial/5.1-extended-functional-types.html +79 -0
  85. package/docs/tutorial/5.2-extended-functional-types.html +70 -0
  86. package/docs/tutorial/6-conventional-javascript.html +75 -0
  87. package/docs/tutorial/7-monitoring-with-observers.html +107 -0
  88. package/docs/tutorial/8-event-listeners.html +65 -0
  89. package/docs/tutorial/9-intro-to-components.html +91 -0
  90. package/docs/tutorial/contents.html +32 -0
  91. package/docs/tutorial/my-component.html +29 -0
  92. package/docs/tutorial/remote-value.json +4 -0
  93. package/docs/websiterepl.html +46 -0
  94. package/lightview.js +430 -340
  95. package/lightview.min.js +1 -0
  96. package/lightview_good.js +1267 -0
  97. package/lightview_optimized.js +1274 -0
  98. package/package.json +1 -1
  99. package/repl_hold.html +320 -0
  100. package/test/basic.html +15 -4
  101. package/test/basic.test.mjs +1 -1
  102. package/test/extended.html +1 -1
  103. package/types.js +109 -36
  104. package/components/chart/example.html +0 -32
  105. package/components/chart.html +0 -83
  106. package/components/gantt/example.html +0 -22
  107. package/components/gauge/example.html +0 -28
  108. package/components/gauge.html +0 -60
  109. package/components/orgchart/example.html +0 -25
  110. package/components/repl/code-editor.html +0 -64
  111. package/components/repl/editor.html +0 -37
  112. package/components/repl/editorjs-inline-tool/index.js +0 -3
  113. package/components/repl/editorjs-inline-tool/inline-tools.js +0 -28
  114. package/components/repl/editorjs-inline-tool/tool.js +0 -175
  115. package/components/repl/repl-with-wysiwyg.html +0 -355
  116. package/components/repl/repl.html +0 -345
  117. package/components/repl/sup.js +0 -44
  118. package/components/repl/wysiwyg-repl.html +0 -258
  119. package/components/timeline/example.html +0 -33
  120. package/components/timeline.html +0 -81
  121. package/examples/anchor.html +0 -11
  122. package/examples/sensors/index.html +0 -30
  123. package/examples/todo.html +0 -38
  124. package/examples/top.html +0 -10
  125. package/sites/client.html +0 -48
  126. package/sites/index.html +0 -247
@@ -0,0 +1,1274 @@
1
+ /*
2
+ MIT License
3
+
4
+ Copyright (c) 2022 AnyWhichWay, LLC - Lightview Small, simple, powerful UI creation ...
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ */
24
+
25
+ // <script src="https://000686818.codepen.website/lightview.js?as=x-body"></script>
26
+ /*
27
+ self.variables({name:"string"})
28
+ imported(x) => exported(x) => reactive(x) => remote(x,{path:".
29
+ */
30
+
31
+ var currentComponent = window.currentComponent = null;
32
+ if(document.body) currentComponent = window.currentComponent = document.currentComponent = document.body;
33
+ var Lightview = window.Lightview = { };
34
+
35
+ var {observe} = (() => {
36
+ let CURRENTOBSERVER;
37
+ const parser = new DOMParser();
38
+
39
+ const templateSanitizer = (string) => {
40
+ return string.replace(/function\s+/g, "")
41
+ .replace(/function\(/g, "")
42
+ .replace(/=\s*>/g, "")
43
+ .replace(/(while|do|for|alert)\s*\(/g, "")
44
+ .replace(/console\.[a-zA-Z$]+\s*\(/g, "");
45
+ }
46
+ Lightview.sanitizeTemplate = templateSanitizer;
47
+
48
+ const escaper = document.createElement('textarea');
49
+ function escapeHTML(html) {
50
+ escaper.textContent = html;
51
+ return escaper.innerHTML;
52
+ }
53
+ Lightview.escapeHTML = escapeHTML;
54
+
55
+ const isArrowFunction = (f) => typeof(f)==="function" && (f+"").match(/\(*.*\)*\s*=>/g);
56
+
57
+ const getTemplateVariableName = (template) => {
58
+ if(template && /^\$\{[a-zA-z_0-9.]*\}$/g.test(template)) return template.substring(2, template.length - 1);
59
+ }
60
+
61
+ const walk = (target,path,depth=path.length-1,create) => {
62
+ for(let i=0;i<=depth;i++) {
63
+ target = (target[path[i]]==null && create ? target[path[i]] = (typeof(create)==="function" ? Object.create(create.prototype) : {}) : target[path[i]]);
64
+ if(target===undefined) return;
65
+ }
66
+ return target;
67
+ }
68
+
69
+ const addListener = (node, eventName, callback, self) => {
70
+ node.addEventListener(eventName, (event) => {
71
+ // todo shopuld self be currentComponent or component
72
+ if(self) Object.defineProperty(event,"self",{value:self});
73
+ callback(event);
74
+ });
75
+ }
76
+
77
+ // imports a component based on an anchor and replace content of a target node with an instance of the component
78
+ const anchorHandler = async (event) => {
79
+ event.preventDefault();
80
+ const target = event.target;
81
+ if (target === event.currentTarget) {
82
+ const {as} = await importLink(target),
83
+ targets = querySelectorAll(document, target.getAttribute("target"));
84
+ targets.forEach((target) => {
85
+ while (target.lastChild) target.lastChild.remove();
86
+ target.appendChild(document.createElement(as))
87
+ })
88
+ }
89
+ }
90
+ const getNameFromPath = (path) => {
91
+ const file = path.split("/").pop(),
92
+ name = file.split(".")[0],
93
+ parts = name.split("-");
94
+ if (name.includes("-") && parts[0].length>=1) return name;
95
+ return "l-" + name;
96
+ }
97
+ const observe = (f, thisArg, argsList = []) => {
98
+ const observer = (...args) => {
99
+ if(observer.cancelled) return;
100
+ CURRENTOBSERVER = observer;
101
+ try {
102
+ f.call(thisArg || this, ...argsList, ...args);
103
+ } catch (e) {
104
+
105
+ }
106
+ CURRENTOBSERVER = null;
107
+ }
108
+ observer.cancel = () => observer.cancelled = true;
109
+ observer();
110
+ return observer;
111
+ }
112
+ const coerce = (value, toType) => {
113
+ if (["null","undefined"].includes(value + "") || toType==="any") return value;
114
+ const type = typeof (value);
115
+ if (type === toType) return value;
116
+ if (toType === "number") {
117
+ value = value + "";
118
+ if(value==="NaN") return NaN;
119
+ const result = parseFloat(value);
120
+ if(isNaN(result)) throw new TypeError(`Unable to coerce '${value}' to 'number'`)
121
+ return result;
122
+ }
123
+ if (toType === "boolean") {
124
+ if ([1,"on", "checked", "selected","true"].includes(value)) return true;
125
+ if (value == null || value === "") return false;
126
+ /*try {
127
+ const parsed = JSON.parse(value + "");
128
+ if (typeof (parsed) === "boolean") return parsed;
129
+ return [1, "on", "checked", "selected"].includes(parsed);
130
+ } catch (e) {
131
+ throw new TypeError(`Unable to coerce ${value} to 'boolean'`);
132
+ }*/
133
+ }
134
+ if (toType === "string") return value + "";
135
+ const isfunction = typeof (toType) === "function";
136
+ if ((toType === "object" || isfunction)) {
137
+ if (type === "object" && isfunction && value instanceof toType) return value;
138
+ if (type === "string") {
139
+ value = value.trim();
140
+ try {
141
+ if (isfunction) {
142
+ const instance = toType === Date ? new Date() : Object.create(toType.prototype);
143
+ if (instance instanceof Array) {
144
+ let parsed = tryParse(value.startsWith("[") ? value : `[${value}]`);
145
+ if (!Array.isArray(parsed)) {
146
+ if (value.includes(",")) parsed = value.split(",");
147
+ else {
148
+ parsed = tryParse(`["${value}"]`);
149
+ if (!Array.isArray(parsed) || parsed[0] !== value && parsed.length !== 1) parsed = null;
150
+ }
151
+ }
152
+ if (!Array.isArray(parsed)) {
153
+ throw new TypeError(`Expected Array for parsed data ${parsed}:${typeof(parsed)}`)
154
+ }
155
+ instance.push(...parsed);
156
+ } else if (instance instanceof Date) {
157
+ instance.setTime(Date.parse(value));
158
+ } else {
159
+ Object.assign(instance, JSON.parse(value));
160
+ }
161
+ return instance;
162
+ }
163
+ return JSON.parse(value);
164
+ } catch (e) {
165
+ throw new TypeError(`Unable to coerce '${value}:${type}' to '${isfunction ? toType.name : type}'`);
166
+ }
167
+ }
168
+ }
169
+ throw new TypeError(`Unable to coerce '${value}:${type}' to '${toType}'`)
170
+ }
171
+ const Reactor = (data) => {
172
+ if (data && typeof (data) === "object") {
173
+ if (data.__isReactor__) return data;
174
+ const childReactors = [],
175
+ dependents = {},
176
+ proxy = new Proxy(data, {
177
+ get(target, property) {
178
+ if (property === "__isReactor__") return true;
179
+ //if(property=== "__dependents__") return dependents;
180
+ //if(property=== "__reactorProxyTarget__") return data;
181
+ if (target instanceof Array) {
182
+ if (property === "toJSON") return function toJSON() { return [...target]; }
183
+ if (property === "toString") return function toString() { return JSON.stringify([...target]); }
184
+ }
185
+ if(target instanceof Date) {
186
+ const value = data[property];
187
+ if(typeof(value)==="function") return value.bind(data);
188
+ }
189
+ let value = target[property];
190
+ const type = typeof (value);
191
+ if (CURRENTOBSERVER && typeof (property) !== "symbol" && type !== "function") {
192
+ const observers = dependents[property] ||= new Set();
193
+ observers.add(CURRENTOBSERVER)
194
+ }
195
+ if(value===undefined) return;
196
+ if ((value && type !== "object") || typeof (property) === "symbol" || childReactors.includes(value)) {
197
+ // Dates and Promises must be bound to work with proxies
198
+ if (type === "function" && ([Date].includes(value) || property==="then")) value = value.bind(target)
199
+ return value;
200
+ }
201
+ if (value && type === "object") {
202
+ value = Reactor(value);
203
+ childReactors.push(value);
204
+ target[property] = value;
205
+ }
206
+ // target[property] = value;
207
+ return value;
208
+ },
209
+ async set(target, property, value) {
210
+ if(target instanceof Promise) {
211
+ console.warn(`Setting ${property} = ${value} on a Promise in Reactor`);
212
+ }
213
+ const type = typeof (value);
214
+ if(value && type==="object" && value instanceof Promise) value = await value;
215
+ if (target[property] !== value) {
216
+ if (value && type === "object") {
217
+ value = Reactor(value);
218
+ childReactors.push(value);
219
+ }
220
+ target[property] = value;
221
+ [...dependents[property] || []].forEach((f) => { // handle dependent observers
222
+ if (f.cancelled) dependents[property].delete(f);
223
+ else f();
224
+ })
225
+ }
226
+ return true;
227
+ }
228
+ });
229
+ return proxy;
230
+ }
231
+ return data;
232
+ }
233
+
234
+ const createVarsProxy = (vars, component, constructor) => {
235
+ return new Proxy(vars, {
236
+ get(target, property) {
237
+ if(property==="self") return component;
238
+ if(target instanceof Date) return Reflect.get(target,property);
239
+ let {value,get} = target[property] || {};
240
+ if(get) return target[property].value = get.call(target[property]);
241
+ if (typeof (value) === "function") return value.bind(target);
242
+ return value;
243
+ },
244
+ set(target, property, newValue) {
245
+ const event = {variableName: property, value: newValue};
246
+ if (target[property] === undefined) {
247
+ target[property] = {type: "any", value: newValue}; // should we allow this, do first to prevent loops
248
+ target.postEvent.value("change", event);
249
+ if (event.defaultPrevented) delete target[property].value;
250
+ return true;
251
+ }
252
+ const variable = target[property],
253
+ {value, shared, exported, constant, reactive, remote} = variable;
254
+ let type = variable.type;
255
+ if (constant) {
256
+ const error = new TypeError(`${property}:${type} is a constant`);
257
+ if(Lightview.renderErrors) {
258
+ variable.value = error.toString();
259
+ return true;
260
+ }
261
+ throw error;
262
+ }
263
+ if(newValue!=null || type.required) newValue = type.validate ? type.validate(newValue,target[property]) : coerce(newValue,type);
264
+ const newtype = typeof (newValue),
265
+ typetype = typeof (type);
266
+ if ((newValue == null && !type.required) ||
267
+ type === "any" ||
268
+ (newtype === type && typetype==="string") ||
269
+ (typetype === "function" && !type.validate && (newValue && newtype === "object" && newValue instanceof type) || variable.validityState?.valid)) {
270
+ if (value !== newValue) {
271
+ event.oldValue = value;
272
+ if(target[property].__isReactor__) target[property] = newValue;
273
+ else target[property].value = reactive ? Reactor(newValue) : newValue; // do first to prevent loops
274
+ target.postEvent.value("change", event);
275
+ if (event.defaultPrevented) target[property].value = value; // set value back
276
+ else if(remote && ((variable.reactive && variable?.remote?.config.put!==false) || remote.put)) remote.handleRemote({variable,config: variable?.remote?.config},true);
277
+ else if(variable.set) variable.set(newValue);
278
+ }
279
+ return true;
280
+ }
281
+ if (typetype === "function" && newValue && newtype === "object") {
282
+ const error = new TypeError(`Can't assign instance of '${newValue.constructor.name}' to variable '${property}:${type.name.replace("bound ", "")}'`)
283
+ if(Lightview.renderErrors) {
284
+ variable.value = error.toString();
285
+ return true;
286
+ }
287
+ throw error;
288
+ }
289
+ const error = new TypeError(`Can't assign '${typeof (newValue)} ${newtype === "string" ? '"' + newValue + '"' : newValue}' to variable '${property}:${typetype === "function" ? type.name.replace("bound ", "") : type} ${type.required ? "required" : ""}'`)
290
+ if(Lightview.renderErrors) {
291
+ variable.value = error.toString();
292
+ return true;
293
+ }
294
+ throw error;
295
+ },
296
+ keys() {
297
+ return [...Object.keys(vars)];
298
+ }
299
+ });
300
+ }
301
+ // this is a DOM observer, not an observer of the observer programming paradigm
302
+ const createObserver = (domNode, framed) => {
303
+ const mobserver = new MutationObserver((mutations) => {
304
+ mutations.forEach((mutation) => {
305
+ const target = mutation.target;
306
+ if (mutation.type === "attributes") {
307
+ //if (framed) debugger;
308
+ const name = mutation.attributeName,
309
+ value = target.getAttribute(name);
310
+ if (framed && name === "message" && target instanceof IFrameElement) {
311
+ //if (value) console.log("message", value);
312
+ target.removeAttribute(name);
313
+ target.dispatchEvent(new CustomEvent("message", {detail: JSON.parse(value)}))
314
+ }
315
+ if (target.observedAttributes && target.observedAttributes.includes(name) && value !== mutation.oldValue) {
316
+ target.setVariableValue(name, value);
317
+ }
318
+ } else if (mutation.type === "childList") {
319
+ for (const target of mutation.removedNodes) {
320
+ if (target.disconnectedCallback) target.disconnectedCallback();
321
+ }
322
+ for (const target of mutation.addedNodes) {
323
+ if (target.connectedCallback) target.connectedCallback();
324
+ }
325
+ } else if(mutation.type === "characterData") {
326
+ if(target.characterDataMutationCallback) target.characterDataMutationCallback(target,mutation.oldValue,target.textContent);
327
+ }
328
+ });
329
+ });
330
+ mobserver.observe(domNode, {subtree: true, childList: true});
331
+ return mobserver;
332
+ }
333
+ const querySelectorAll = (node, selector) => {
334
+ const nodes = [...node.querySelectorAll(selector)],
335
+ nodeIterator = document.createNodeIterator(node, Node.ELEMENT_NODE);
336
+ let currentNode;
337
+ while (currentNode = nodeIterator.nextNode()) {
338
+ if (currentNode.shadowRoot) nodes.push(...querySelectorAll(currentNode.shadowRoot, selector));
339
+ }
340
+ return nodes;
341
+ }
342
+ const getNodes = (root,href,nodes=new Set()) => {
343
+ //const nodes = new Set();
344
+ if (root.shadowRoot) {
345
+ nodes.add(root);
346
+ getNodes(root.shadowRoot,href,nodes);//.forEach((node) => nodes.add(node))
347
+ } else {
348
+ for (const node of root.childNodes) {
349
+ if (node.nodeType === Node.TEXT_NODE && node.nodeValue?.includes("${")) {
350
+ node.template ||= node.nodeValue;
351
+ nodes.add(node);
352
+ } else if (node.nodeType === Node.ELEMENT_NODE) {
353
+ let skip;
354
+ //[...node.attributes].forEach((attr) => {
355
+ for(const attr of node.attributes) {
356
+ if (attr.value.includes("${")) {
357
+ attr.template ||= attr.value;
358
+ nodes.add(node);
359
+ } else if (attr.name.includes(":") || attr.name.startsWith("l-")) {
360
+ skip = attr.name.includes("l-for:");
361
+ nodes.add(node)
362
+ }
363
+ }
364
+ //})
365
+ if (node.getAttribute("type") === "radio") nodes.add(node);
366
+ if (!skip && !node.shadowRoot) getNodes(node,href,nodes);//.forEach((node) => nodes.add(node));
367
+ }
368
+ }
369
+ }
370
+ return nodes;
371
+ }
372
+
373
+ // populate a string literal template and turn objects into strings
374
+ const populateTemplate = (strings,...values) => {
375
+ values = values.map((value) => {
376
+ const type = typeof(value);
377
+ try {
378
+ if(value && type==="object") return JSON.stringify(value);
379
+ return value;
380
+ } catch(e) {
381
+ return e.toString();
382
+ }
383
+ });
384
+ return strings.reduce((result,string,index) => index < values.length ? result += string + values[index] : result + string,"");
385
+ }
386
+
387
+ const resolveNodeOrText = (node, component, safe,extras=node.extras||{},skipNodeUpdate) => {
388
+ const type = typeof (node),
389
+ template = type === "string" ? node.trim() : node.template;
390
+ extras.populateTemplate = populateTemplate;
391
+ if (template) {
392
+ const name = getTemplateVariableName(template);
393
+ try {
394
+ const parts = name ? name.split(".") : null;
395
+ let value;
396
+ value = (parts
397
+ ? (value = walk(extras,parts)) || (value = walk(component.varsProxy,parts)) || (value == null ? component[name] : value)
398
+ : Function("context", "extras", "with(context) { with(extras) { return populateTemplate`" + (safe ? template : Lightview.sanitizeTemplate(template)) + "` } }")(component.varsProxy,extras));
399
+ //let value = Function("context", "with(context) { return `" + Lightview.sanitizeTemplate(template) + "` }")(component.varsProxy);
400
+ if(typeof(value)==="function") return value.bind(component);
401
+ value = (name || node.nodeType === Node.TEXT_NODE || safe ? value : Lightview.escapeHTML(value));
402
+ if (type === "string") return value==="undefined" ? undefined : value;
403
+ node.rawValue = value;
404
+ if(!skipNodeUpdate) {
405
+ //requestAnimationFrame(() => {
406
+ if(name) {
407
+ node.nodeValue = value==null ? "" : typeof(value)==="string" ? value : JSON.stringify(value);
408
+ } else {
409
+ node.nodeValue = value == "null" || value == "undefined" ? "" : value;
410
+ }
411
+ //})
412
+ }
413
+ return value;
414
+ } catch (e) {
415
+ //console.warn(e);
416
+ if (!e.message.includes("defined")) {
417
+ if(Lightview.renderErrors) return e.message;
418
+ throw e;
419
+ } // actually looking for undefined or not defined, but different browsers spell or quote differently
420
+ return undefined;
421
+ }
422
+ }
423
+ return node?.nodeValue;
424
+ }
425
+ const inputTypeToType = (inputType) => {
426
+ if (!inputType) return "any"
427
+ if (["text", "tel", "email", "url", "search", "radio", "color", "password"].includes(inputType)) return "string";
428
+ if (["number", "range"].includes(inputType)) return "number";
429
+ if (["datetime"].includes(inputType)) return Date;
430
+ if (["checkbox"].includes(inputType)) return "boolean";
431
+ return "any";
432
+ }
433
+ const enableAnchors = (node) => {
434
+ for(const anode of node.querySelectorAll('a[href$=".html"][target^="#"]')) {
435
+ anode.removeEventListener("click", anchorHandler);
436
+ addListener(anode, "click", anchorHandler);
437
+ }
438
+ }
439
+ Lightview.enableAnchors = enableAnchors;
440
+
441
+ const bound = new WeakSet();
442
+ const bindInput = (input, variableName, component, value, object) => {
443
+ if (bound.has(input)) return;
444
+ bound.add(input);
445
+ const inputtype = input.tagName === "SELECT" || input.tagName === "TEXTAREA" ? "text" : input.getAttribute("type"),
446
+ nameparts = variableName.split(".");
447
+ let type = input.tagName === "SELECT" && input.hasAttribute("multiple") ? Array : inputTypeToType(inputtype);
448
+ const variable = walk(component.vars,nameparts) || {type};
449
+ if(type==="any") type = variable?.type.type || variable?.type;
450
+ if(inputtype==="checkbox" && value==null) value = input.checked;
451
+ if(value==null) {
452
+ const avalue = input.getAttribute("value");
453
+ if(avalue) value = avalue;
454
+ }
455
+ if(object && nameparts.length>1) {
456
+ const [root,...path] = nameparts;
457
+ object = walk(object,path,path.length-2,true);
458
+ const key = path[path.length-1];
459
+ object[key] = coerce(value,type);
460
+ } else {
461
+ const existing = component.vars[variableName];
462
+ if(existing) {
463
+ existingtype = existing?.type.type || existing?.type;
464
+ if(existingtype!==type) throw new TypeError(`Attempt to bind <${input.tagName} name="${variableName}" type="${type}"> to variable ${variableName}:${existing.type}`)
465
+ existing.reactive = true;
466
+ } else if(Lightview.createInputVariables) {
467
+ component.variables({[variableName]: type},{reactive,set:value});
468
+ } else {
469
+ throw new TypeError(`Attempt to bind undefined variable ${variableName} to <${input.tagName} type="${type}>`)
470
+ }
471
+ if(inputtype!=="radio") {
472
+ if(typeof(value)==="string" && value.includes("${")) input.setAttribute("value","");
473
+ else component.setVariableValue(variableName, coerce(value,type));
474
+ }
475
+ }
476
+ let eventname = "change";
477
+ if(input.tagName==="FORM") {
478
+ eventname = "submit"
479
+ } else if (input.tagName !== "SELECT" && (!inputtype || input.tagName === "TEXTAREA" || ["text", "number", "tel", "email", "url", "search", "password"].includes(inputtype))) {
480
+ eventname = "input";
481
+ }
482
+ const listener = (event) => {
483
+ if (event) event.stopImmediatePropagation();
484
+ let value = input.value;
485
+ if (inputtype === "checkbox") {
486
+ value = input.checked
487
+ } else if (input.tagName === "SELECT" && input.hasAttribute("multiple")) {
488
+ value = [...input.querySelectorAll("option")]
489
+ .filter((option) => option.selected || resolveNodeOrText(option.attributes.value || option.innerText, component) === value)
490
+ .map((option) => option.getAttribute("value") || option.innerText);
491
+ }
492
+ if(object) {
493
+ const [root,...path] = nameparts;
494
+ object = walk(object,nameparts,path.length-2,true);
495
+ } else {
496
+ object = walk(component.varsProxy,nameparts,nameparts.length-2,true);
497
+ }
498
+ const key = nameparts[nameparts.length-1];
499
+ object[key] = coerce(value,type);
500
+ };
501
+ addListener(input, eventname, listener,component);
502
+ }
503
+ const tryParse = (value) => {
504
+ try {
505
+ return JSON.parse(value);
506
+ } catch (e) {
507
+ return value;
508
+ }
509
+ }
510
+ const observed = () => {
511
+ return {
512
+ init({variable, component}) {
513
+ const name = variable.name;
514
+ variable.value = component.hasAttribute(name) ? coerce(component.getAttribute(name), variable.type) : variable.value;
515
+ variable.observed = true;
516
+ component.observedAttributes.add(name);
517
+ }
518
+ }
519
+ }
520
+ const reactive = () => {
521
+ return {
522
+ init({variable, component}) {
523
+ variable.reactive = true;
524
+ component.vars[variable.name] = Reactor(variable);
525
+ }
526
+ }
527
+ }
528
+ const shared = () => {
529
+ return {
530
+ init({variable, component}) {
531
+ variable.shared = true;
532
+ variable.set = function(newValue) {
533
+ if(component.vars[this.name]?.shared) component.siblings.forEach((instance) => instance.setVariableValue(this.name, newValue));
534
+ }
535
+ }
536
+ }
537
+ }
538
+ const exported = () => {
539
+ return {
540
+ init({variable, component}) {
541
+ const name = variable.name;
542
+ variable.exported = true;
543
+ variable.set = (newValue) => {
544
+ if(variable.exported) {
545
+ if(newValue==null) {
546
+ removeComponentAttribute(component, name);
547
+ } else {
548
+ const type = typeof(newValue);
549
+ // note, using isArray below will not always work for proxied items, so using instanceOf
550
+ newValue = type === "string" ? newValue : (type==="object" && newValue instanceof Array) ? JSON.stringify([...newValue]) : JSON.stringify(newValue);
551
+ setComponentAttribute(component, name, newValue);
552
+ }
553
+ }
554
+ }
555
+ variable.set(variable.value);
556
+ }
557
+ }
558
+ }
559
+ const imported = () => {
560
+ return {
561
+ init({variable, component}) {
562
+ const name = variable.name.toLowerCase();
563
+ let value = component.hasAttribute(name) ? component.getAttribute(name) : null;
564
+ if((variable.type==="boolean" || variable.type.type==="boolean") && value==="") value = true;
565
+ variable.imported = true;
566
+ variable.value = value!=null ? coerce(value, variable.type) : variable.value;
567
+ }
568
+ }
569
+ }
570
+
571
+ let reserved = {
572
+ observed: {
573
+ constant: true,
574
+ value: observed
575
+ },
576
+ reactive: {
577
+ constant: true,
578
+ value: reactive
579
+ },
580
+ shared: {
581
+ constant: true,
582
+ value: shared
583
+ },
584
+ exported: {
585
+ constant: true,
586
+ value: exported
587
+ },
588
+ imported: {
589
+ constant: true,
590
+ value: imported
591
+ }
592
+ };
593
+ // patches relative references to use the passed in href as base
594
+ const patchElementURIs = (node,tagName,attributeName,href) => { // attributeName will always be href or src
595
+ if(node) {
596
+ for(const child of node.querySelectorAll(tagName)) {
597
+ let value = child.getAttribute(attributeName);
598
+ if (value) child.setAttribute(attributeName, new URL(value, href).href);
599
+ }
600
+ }
601
+ };
602
+ // forces re-evaluation of scripts and links
603
+ const forceLoadElement = (node) => {
604
+ if((node.getAttribute("src")||"").includes("/lightview.js")) return;
605
+ const el = document.createElement(node.tagName.toLowerCase());
606
+ for(const attr of node.attributes) { el.setAttribute(attr.name,attr.value); }
607
+ el.innerHTML = node.innerHTML;
608
+ node.after(el);
609
+ node.remove();
610
+ };
611
+ const createClass = (domElementNode, {observer, framed, href= window.location.href.replace("blob:",""), mount}) => {
612
+ const instances = new Set(),
613
+ observedAttributes = [];
614
+ let dom;
615
+ observedAttributes.add = function(name) { observedAttributes.includes(name) || observedAttributes.push(name); }
616
+ const cls = class CustomElement extends HTMLElement {
617
+ static get instances() {
618
+ return instances;
619
+ }
620
+ static setTemplateNode(node) {
621
+ dom = node.tagName === "TEMPLATE"
622
+ ? document.createElement("div")
623
+ : node.cloneNode(true);
624
+ if(node.tagName === "TEMPLATE") {
625
+ dom.innerHTML = node.innerHTML;
626
+ for(const attr of node.attributes) { dom.setAttribute(attr.name,attr.value) }
627
+ }
628
+ patchElementURIs(dom.head,"link","href",href);
629
+ patchElementURIs(dom.head,"script","src",href);
630
+ patchElementURIs(dom.body||dom,"link","href",href);
631
+ patchElementURIs(dom.body||dom,"script","src",href);
632
+ dom.mount = node.mount || node.body?.mount;
633
+ }
634
+ constructor() {
635
+ super();
636
+ this.componentBaseURI = href;
637
+ currentComponent = window.currentComponent = document.currentComponent = this;
638
+ instances.add(this);
639
+ const shadow = this.attachShadow({mode: "open"}),
640
+ eventlisteners = {};
641
+ this.vars = {
642
+ ...reserved,
643
+ observe: {
644
+ value: (...args) => observe(...args),
645
+ type: "function",
646
+ constant: true
647
+ },
648
+ addEventListener: {
649
+ value: (eventName, listener) => {
650
+ const listeners = eventlisteners[eventName] ||= new Set();
651
+ listeners.forEach((f) => {
652
+ if (listener + "" === f + "") listeners.delete(f);
653
+ })
654
+ eventlisteners[eventName].add(listener);
655
+ },
656
+ type: "function",
657
+ constant: true
658
+ },
659
+ postEvent: {
660
+ value: (eventName, event = {}) => {
661
+ //event = {...event}
662
+ event.type = eventName;
663
+ event.target = currentComponent;
664
+ eventlisteners[eventName]?.forEach((f) => f(event));
665
+ },
666
+ type: "function",
667
+ constant: true
668
+ },
669
+ self: {value: currentComponent, type: CustomElement, constant: true}
670
+ };
671
+ this.varsProxy = createVarsProxy(this.vars, this, CustomElement);
672
+ if (framed || CustomElement.lightviewFramed) this.variables({message: Object}, {exported});
673
+ ["getElementById", "querySelector"] //, "querySelectorAll"
674
+ .forEach((fname) => {
675
+ const f = this[fname];
676
+ Object.defineProperty(this, fname, {
677
+ configurable: true,
678
+ writable: true,
679
+ value: (...args) => { return (f ? f.call(this,...args) : null) || this.shadowRoot[fname](...args) }
680
+ })
681
+ });
682
+ ["querySelectorAll"]
683
+ .forEach((fname) => {
684
+ const f = this[fname];
685
+ Object.defineProperty(this, fname, {
686
+ configurable: true,
687
+ writable: true,
688
+ value: (...args) => { return [...f.call(this,...args),...this.shadowRoot[fname](...args)] }
689
+ })
690
+ });
691
+ [...dom.head?.childNodes||[]].forEach((child) => {
692
+ const clone = child.cloneNode(true);
693
+ document.head.appendChild(clone);
694
+ if(["LINK","SCRIPT"].includes(clone.tagName)) forceLoadElement(clone);
695
+ });
696
+ const body = dom.body || dom;
697
+ for(const child of body.childNodes) {
698
+ if(child.tagName && customElements.get(child.tagName.toLowerCase())) {
699
+ const node = document.createElement(child.tagName);
700
+ for(const attr of child.attributes) { node.setAttribute(attr.name,attr.value); }
701
+ //currentComponent = window.currentComponent = document.currentComponent = node;
702
+ shadow.appendChild(node);
703
+ } else {
704
+ const clone = child.cloneNode(true);
705
+ shadow.appendChild(clone);
706
+ if(["LINK","SCRIPT"].includes(clone.tagName)) forceLoadElement(clone);
707
+ }
708
+ };
709
+ //forceLoadElements(shadow,"link");
710
+ //forceLoadElements(shadow,"script");
711
+ //importStyleSheets(shadow,this);
712
+ enableAnchors(shadow);
713
+ }
714
+
715
+ get siblings() {
716
+ return [...CustomElement.instances].filter((sibling) => sibling != this);
717
+ }
718
+
719
+ adoptedCallback() {
720
+ if (this.hasOwnProperty("adoptedCallback")) this.adoptedCallback();
721
+ }
722
+
723
+ disconnectedCallback() {
724
+ instances.delete(this);
725
+ }
726
+
727
+ connectedCallback() {
728
+ const node = dom.body || dom;
729
+ for(const attr of node.attributes) {
730
+ if(!this.hasAttribute(attr.name)) this.setAttribute(attr.name,attr.value);
731
+ }
732
+ if(dom.mount||mount) {
733
+ const script = document.createElement("script");
734
+ window.currentComponent = document.currentComponent = this;
735
+ script.innerHTML = `with(document.currentComponent.varsProxy) {
736
+ ${typeof(lightviewDebug)!=="undefined" && lightviewDebug===true ? "debugger;" : ""}
737
+ const component = document.currentComponent;
738
+ (async () => { await (${dom.mount||mount}).call(self,self);
739
+ requestAnimationFrame(() => component.compile()); })();
740
+ };`;
741
+ this.appendChild(script);
742
+ script.remove();
743
+ for(const child of this.querySelectorAll('link[rel="stylesheet"][export]')) {
744
+ child.remove();
745
+ this.appendChild(child);
746
+ };
747
+ window.currentComponent = document.currentComponent = null;
748
+ }
749
+ }
750
+ compile() {
751
+ // Promise.all(promises).then(() => {
752
+ const ctx = this,
753
+ shadow = this.shadowRoot;
754
+ const nodes = getNodes(ctx,href),
755
+ processNodes = (nodes,{object,rootName,extras}={}) => {
756
+ nodes.forEach((node) => {
757
+ node.extras = extras;
758
+ if (node.nodeType === Node.TEXT_NODE && node.template.includes("${")) {
759
+ observe(() => resolveNodeOrText(node, this,true,node.extras));
760
+ if(node.parentElement?.tagName==="TEXTAREA") {
761
+ const name = getTemplateVariableName(node.template);
762
+ if (name) {
763
+ const nameparts = name.split(".");
764
+ if(node.extras && node.extras[nameparts[0]]) {
765
+ object = node.extras[nameparts[0]];
766
+ }
767
+ if(!this.vars[nameparts[0]] || this.vars[nameparts[0]].reactive || object) {
768
+ bindInput(node.parentElement, name, this, resolveNodeOrText(node.template, this,true,node.extras), object);
769
+ }
770
+ }
771
+ }
772
+ } else if (node.nodeType === Node.ELEMENT_NODE) {
773
+ // resolve the value before all else;
774
+ const attr = node.attributes.value,
775
+ template = attr?.template;
776
+ if (attr && template) {
777
+ //let value = resolveNodeOrText(attr, this),
778
+ // ;
779
+ const eltype = node.attributes.type ? resolveNodeOrText(node.attributes.type, ctx, false,node.extras) : null,
780
+ aname = node.getAttribute("name"),
781
+ template = attr.template || (rootName && aname ? `\${${rootName}.${name}}` : null);
782
+ if (template) {
783
+ const name = getTemplateVariableName(template);
784
+ if (name) {
785
+ const nameparts = name.split(".");
786
+ if(node.extras && node.extras[nameparts[0]]) {
787
+ object = node.extras[nameparts[0]];
788
+ }
789
+ if(!this.vars[nameparts[0]] || this.vars[nameparts[0]].reactive || object) {
790
+ bindInput(node, name, this, resolveNodeOrText(attr, this,false,node.extras), object);
791
+ }
792
+ }
793
+ if(eltype==="checkbox" || eltype==="radio" || node.tagName==="SELECT") {
794
+ observe(() => {
795
+ const value = resolveNodeOrText(template, ctx, false, node.extras);
796
+ if (value !== undefined) {
797
+ if (eltype === "checkbox") {
798
+ if (coerce(value, "boolean") === true) {
799
+ node.setAttribute("checked", "");
800
+ //node.checked = true; // do we need to do this and set attribute
801
+ } else {
802
+ node.removeAttribute("checked");
803
+ //node.checked = false;
804
+ }
805
+ } else if (node.tagName === "SELECT") {
806
+ const values = node.hasAttribute("multiple") ? coerce(value, Array) : [value];
807
+ for(const option of node.querySelectorAll("option")) {
808
+ if (option.hasAttribute("value")) {
809
+ if (values.includes(resolveNodeOrText(option.attributes.value, ctx, false, node.extras))) {
810
+ option.setAttribute("selected", "");
811
+ //option.selected = true;
812
+ }
813
+ } else if (values.includes(resolveNodeOrText(option.innerText, ctx, false, node.extras))) {
814
+ option.setAttribute("selected", "");
815
+ //option.selected = true;
816
+ }
817
+ }
818
+ } else if (eltype !== "radio") {
819
+ //attr.value = typeof(value)==="string" ? value : JSON.stringify(value);
820
+ let avalue = typeof (value) === "string" ? value : value.toString ? value.toString() : JSON.stringify(value);
821
+ if (avalue.startsWith('"')) avalue = avalue.substring(1);
822
+ if (avalue.endsWith('"')) avalue = avalue.substring(0, avalue.length - 1);
823
+ attr.value = avalue;
824
+ }
825
+ }
826
+ });
827
+ }
828
+ }
829
+ }
830
+ for(const attr of node.attributes) {
831
+ if (attr.name === "value" && attr.template) return;
832
+ const {name, value} = attr,
833
+ vname = node.attributes.name?.value;
834
+ if(value.includes("${")) attr.template = value;
835
+ if (name === "type" && value=="radio" && vname) {
836
+ bindInput(node, vname, this, undefined, object);
837
+ observe(() => {
838
+ const varvalue = Function("context", "with(context) { return `${" + vname + "}` }")(ctx.varsProxy);
839
+ if (node.attributes.value.value == varvalue) {
840
+ node.setAttribute("checked", "");
841
+ node.checked = true;
842
+ } else {
843
+ node.removeAttribute("checked");
844
+ node.checked = false;
845
+ }
846
+ });
847
+ }
848
+
849
+ const [type, ...params] = name.split(":");
850
+ if (type === "") { // name is :something
851
+ observe(() => {
852
+ const value = attr.value;
853
+ if (params[0]) {
854
+ if (value === "true") node.setAttribute(params[0], "")
855
+ else node.removeAttribute(params[0]);
856
+ } else {
857
+ const elvalue = node.attributes.value ? resolveNodeOrText(node.attributes.value, ctx,false,node.extras) : null,
858
+ eltype = node.attributes.type ? resolveNodeOrText(node.attributes.type, ctx,false,node.extras) : null;
859
+ if (eltype === "checkbox" || node.tagName === "OPTION") {
860
+ if (elvalue === true) node.setAttribute("checked", "")
861
+ else node.removeAttribute("checked");
862
+ }
863
+ }
864
+ })
865
+ } else if (type === "l-on") {
866
+ let listener;
867
+ //setTimeout(() => {
868
+ observe(() => {
869
+ const value = resolveNodeOrText(attr, this,true,node.extras,true);
870
+ if (listener) node.removeEventListener(params[0], listener);
871
+ listener = null;
872
+ if(typeof(value)==="function") {
873
+ listener = value;
874
+ } else {
875
+ try {
876
+ listener = Function("return " + value)();
877
+ } catch(e) {
878
+
879
+ }
880
+ }
881
+ if(listener) addListener(node, params[0], listener,ctx);
882
+ })
883
+ // })
884
+ } else if (type === "l-if") {
885
+ observe(() => {
886
+ const value = resolveNodeOrText(attr, this,true,node.extras);
887
+ node.style.setProperty("display", value == true || value === "true" ? "revert" : "none");
888
+ })
889
+ } else if (type === "l-for") {
890
+ node.template ||= node.innerHTML;
891
+ node.clone ||= node.cloneNode(true);
892
+ const [what = "each", vname = "item", index = "index", array = "array", after = false] = params;
893
+ observe(() => {
894
+ const value = resolveNodeOrText(attr, this,false,node.extras,true),
895
+ coerced = coerce(value, what === "each" ? Array : "object"),
896
+ target = what === "each" ? coerced : Object[what](coerced);
897
+ let length = target.length * node.children.length;
898
+ if (!window.lightviewDebug) {
899
+ if (after) node.style.setProperty("display", "none")
900
+ else if (length===0) while(node.lastElementChild) node.lastElementChild.remove();
901
+ else while (node.lastElementChild && length--) node.lastElementChild.remove();
902
+ }
903
+ length = target.length * node.children.length;
904
+ //requestAnimationFrame( () => {
905
+ target.forEach((item,i,target) => {
906
+ const clone = node.clone.cloneNode(true),
907
+ extras = node.extras = {
908
+ [vname]: item,
909
+ [index]: i,
910
+ [array]: target
911
+ };
912
+ processNodes(getNodes(clone,href),{extras});
913
+ [...clone.childNodes].forEach((child,j) => {
914
+ const position = i + j;
915
+ if (after) node.parentElement.insertBefore(child, node);
916
+ else if(position<length) node.replaceChild(child,node.children[position])
917
+ else node.appendChild(child);
918
+ });
919
+ });
920
+ //});
921
+ })
922
+ } else if(attr.template) {
923
+ observe(() => {
924
+ resolveNodeOrText(attr, this,false,node.extras);
925
+ })
926
+ }
927
+ }
928
+ }
929
+ })
930
+ };
931
+ nodes.forEach((node) => {
932
+ if(node.tagName==="FORM") {
933
+ const value = node.getAttribute("value"),
934
+ name = getTemplateVariableName(value);
935
+ if(name) {
936
+ const childnodes = [...nodes].filter((childnode) => node!==childnode && node.contains(childnode));
937
+ childnodes.forEach((node) => nodes.delete(node));
938
+ const variable = ctx.vars[name] ||= {type: "object", reactive:true, value: Reactor({})};
939
+ if(variable.type !== "object" || !variable.reactive || !variable.value || typeof(variable.value)!=="object") {
940
+ throw new TypeError(`Can't bind form ${node.getAttribute("id")} to non-object variable ${name}`);
941
+ }
942
+ processNodes(childnodes,{object:variable.value,rootName:name});
943
+ }
944
+ }
945
+ })
946
+ processNodes(nodes);
947
+ shadow.normalize();
948
+ observer ||= createObserver(ctx, framed);
949
+ observer.observe(ctx, {attributeOldValue: true, subtree:true, characterData:true, characterDataOldValue:true});
950
+ if(this.hasAttribute("l-unhide")) this.removeAttribute("hidden");
951
+ //ctx.vars.postEvent.value("connected");
952
+ this.dispatchEvent(new Event("mounted"));
953
+ // })
954
+ }
955
+ adoptedCallback(callback) {
956
+ this.dispatchEvent(new Event("adopted"));
957
+ }
958
+ disconnectedCallback() {
959
+ this.dispatchEvent(new Event("disconnected"));
960
+ }
961
+ get observedAttributes() {
962
+ return CustomElement.observedAttributes;
963
+ }
964
+ static get observedAttributes() {
965
+ return observedAttributes;
966
+ }
967
+
968
+ getVariableNames() {
969
+ return Object.keys(this.vars)
970
+ .filter(name => !(name in reserved) && !["self", "addEventListener", "postEvent","observe"].includes(name))
971
+ }
972
+
973
+ getVariableData() {
974
+ return this.getVariableNames().reduce((data,name) => {
975
+ data[name] = this.getVariableValue(name);
976
+ return data;
977
+ },{})
978
+ }
979
+
980
+ getVariable(name) {
981
+ return this.vars[name] ? {...this.vars[name]} : undefined;
982
+ }
983
+
984
+ setVariableValue(variableName, value, {coerceTo = typeof (value)} = {}) {
985
+ if (!this.isConnected) {
986
+ instances.delete(this);
987
+ return false;
988
+ }
989
+ let {type} = this.vars[variableName] || {};
990
+ if (type) {
991
+ if (this.varsProxy[variableName] !== value) {
992
+ const variable = this.vars[variableName];
993
+ if (variable.shared) {
994
+ value = type.validate ? type.validate(value,variable) : coerce(value,coerceTo);
995
+ const event = {
996
+ variableName: variableName,
997
+ value: value,
998
+ oldValue: variable.value
999
+ };
1000
+ variable.value = value;
1001
+ this.vars.postEvent.value("change", event);
1002
+ if (event.defaultPrevented) variable.value = value;
1003
+ } else {
1004
+ this.varsProxy[variableName] = value;
1005
+ }
1006
+ }
1007
+ return true;
1008
+ }
1009
+ this.vars[variableName] = {name, type: coerceTo, value: coerce(value, coerceTo)};
1010
+ return false;
1011
+ }
1012
+
1013
+ getVariableValue(variableName) {
1014
+ return this.vars[variableName]?.value;
1015
+ }
1016
+
1017
+ variables(variables, {remote, constant, set,...rest} = {}) { // options = {observed,reactive,shared,exported,imported}
1018
+ const options = {remote, constant, ...rest};
1019
+ if (variables !== undefined) {
1020
+ Object.entries(variables)
1021
+ .forEach(([key, type]) => {
1022
+ if(isArrowFunction(type)) type = type();
1023
+ const variable = this.vars[key] ||= {name: key, type};
1024
+ if(set!==undefined && constant!==undefined) throw new TypeError(`${key} has the constant value ${constant} and can't be set to ${set}`);
1025
+ variable.value = set;
1026
+ if(constant!==undefined) {
1027
+ if(remote || rest.imported) throw new TypeError(`${key} can't be a constant and also remote or imported`)
1028
+ variable.constant = true;
1029
+ variable.value = constant;
1030
+ }
1031
+ if (remote) {
1032
+ if(typeof(remote)==="function") remote = remote(`./${key}`);
1033
+ variable.remote = remote;
1034
+ remote.handleRemote({variable, config:remote.config,component:this});
1035
+ }
1036
+ // todo: handle custom functional types, remote should actually be handled this way
1037
+ Object.entries(rest).forEach(([type,f]) => {
1038
+ const functionalType = variable[type] = typeof(f)==="function" ? f() : f;
1039
+ if(functionalType.init) functionalType.init({variable,options,component:this});
1040
+ if((rest.get!==undefined || rest.set!==undefined) && constant!==undefined) throw new TypeError(`${key} has the constant value ${constant} and can't have a getter or setter`);
1041
+ variable.set != functionalType.set;
1042
+ variable.get != functionalType.get;
1043
+ });
1044
+ if(type.validate && variable.value!==undefined) type.validate(variable.value,variable);
1045
+ });
1046
+ }
1047
+ return Object.entries(this.vars)
1048
+ .reduce((result, [key, variable]) => {
1049
+ result[key] = {...variable};
1050
+ return result;
1051
+ }, {});
1052
+ }
1053
+ }
1054
+ cls.setTemplateNode(domElementNode);
1055
+ return cls;
1056
+ }
1057
+
1058
+ const createComponent = (name, node, {framed, observer, href, mount} = {}) => {
1059
+ let ctor = customElements.get(name);
1060
+ if (ctor) {
1061
+ if (framed && !ctor.lightviewFramed) ctor.lightviewFramed = true;
1062
+ else console.warn(new Error(`${name} is already a CustomElement. Not redefining`));
1063
+ return ctor;
1064
+ }
1065
+ ctor = createClass(node, {observer, framed, href, mount});
1066
+ customElements.define(name, ctor);
1067
+ Lightview.customElements.set(name, ctor);
1068
+ return ctor;
1069
+ }
1070
+ Lightview.customElements = new Map();
1071
+ Lightview.createComponent = createComponent;
1072
+ const importLink = async (link, observer) => {
1073
+ const url = (new URL(link.getAttribute("href"),document.baseURI)),
1074
+ as = link.getAttribute("as") || getNameFromPath(url.pathname);
1075
+ if (url.origin !== window.location.origin && !link.getAttribute("crossorigin")) {
1076
+ throw new URIError(`importLink:HTML imports must be from same domain: ${url.hostname}!=${location.hostname} unless 'crossorigin' attribute is set.`)
1077
+ }
1078
+ if (!customElements.get(as)) {
1079
+ const html = await (await fetch(url.href)).text(),
1080
+ dom = parser.parseFromString(html, "text/html"),
1081
+ unhide = !!dom.head.querySelector('meta[name="l-unhide"]');
1082
+ for (const childlink of [...dom.head.querySelectorAll('link[href]')]) {
1083
+ childlink.setAttribute("href", new URL(childlink.getAttribute("href"), url.href).href);
1084
+ if (link.hasAttribute("crossorigin")) childlink.setAttribute("crossorigin", link.getAttribute("crossorigin"))
1085
+ if(childlink.getAttribute("href").endsWith(".html") && childlink.getAttribute("rel")==="module") await importLink(childlink, observer);
1086
+ }
1087
+ currentComponent = window.currentComponent = document.currentComponent = dom.body;
1088
+ currentComponent.componentBaseURI = url.href;
1089
+ const lvscript = dom.getElementById("lightview");
1090
+ if(lvscript) {
1091
+ const script = document.createElement("script");
1092
+ script.innerHTML = lvscript.innerHTML;
1093
+ document.body.appendChild(script);
1094
+ script.remove();
1095
+ }
1096
+ currentComponent = window.currentComponent = document.currentComponent = null;
1097
+ createComponent(as, dom, {observer,href:url.href});
1098
+ if (unhide) dom.body.removeAttribute("hidden");
1099
+ }
1100
+ return {as};
1101
+ }
1102
+ const importLinks = async () => {
1103
+ const observer = createObserver(document.body);
1104
+ for (const link of [...document.querySelectorAll(`link[href$=".html"][rel=module]`)]) {
1105
+ await importLink(link, observer);
1106
+ }
1107
+ }
1108
+ const bodyAsComponent = ({as = "x-body", unhide, framed} = {}) => {
1109
+ createComponent(as, document.body, {framed});
1110
+ const component = document.createElement(as);
1111
+ document.body.parentElement.replaceChild(component, document.body);
1112
+ Object.defineProperty(document, "body", {
1113
+ enumerable: true, configurable: true, get() {
1114
+ return component;
1115
+ }
1116
+ });
1117
+ if (unhide) component.removeAttribute("hidden");
1118
+ }
1119
+ Lightview.bodyAsComponent = bodyAsComponent;
1120
+ const postMessage = (data, target = window.parent) => {
1121
+ if (postMessage.enabled) {
1122
+ if (target instanceof HTMLIFrameElement) {
1123
+ data = {...data, href: document.baseURI};
1124
+ target.contentWindow.postMessage(JSON.stringify(data), "*");
1125
+ } else {
1126
+ data = {...data, iframeId: document.lightviewId, href: document.baseURI};
1127
+ target.postMessage(JSON.stringify(data), "*");
1128
+ }
1129
+ }
1130
+ }
1131
+ const setComponentAttribute = (node, name, value) => {
1132
+ if (node.getAttribute(name) !== value) node.setAttribute(name, value);
1133
+ postMessage({type: "setAttribute", argsList: [name, value]});
1134
+ }
1135
+ const removeComponentAttribute = (node, name, value) => {
1136
+ node.removeAttribute(name);
1137
+ postMessage({type: "removeAttribute", argsList: [name]});
1138
+ }
1139
+ const getNodePath = (node, path = []) => {
1140
+ path.unshift(node);
1141
+ if (node.parentNode && node.parentNode !== node.parentNode) getNodePath(node.parentNode, path);
1142
+ return path;
1143
+ }
1144
+ const onresize = (node, callback) => {
1145
+ const resizeObserver = new ResizeObserver(() => callback());
1146
+ resizeObserver.observe(node);
1147
+ };
1148
+
1149
+ const url = new URL(document.currentScript.getAttribute("src"), document.baseURI);
1150
+ let domContentLoadedEvent;
1151
+ if (!domContentLoadedEvent) addListener(window, "DOMContentLoaded", (event) => domContentLoadedEvent = event);
1152
+ let OBSERVER;
1153
+ const loader = async (whenFramed) => {
1154
+ await importLinks();
1155
+ const unhide = !!document.querySelector('meta[name="l-unhide"]'),
1156
+ isolated = !!document.querySelector('meta[name="l-isolate"]'),
1157
+ enableFrames = !!document.querySelector('meta[name="l-enableFrames"]');
1158
+ if (whenFramed) {
1159
+ whenFramed({unhide, isolated, enableFrames, framed: true});
1160
+ if (!isolated) {
1161
+ postMessage.enabled = true;
1162
+ addListener(window, "message", ({data}) => {
1163
+ const {type, argsList} = JSON.parse(data);
1164
+ if (type === "framed") {
1165
+ const resize = () => {
1166
+ const {width, height} = document.body.getBoundingClientRect();
1167
+ postMessage({type: "setAttribute", argsList: ["width", width]})
1168
+ postMessage({type: "setAttribute", argsList: ["height", height + 20]});
1169
+ }
1170
+ resize();
1171
+ onresize(document.body, () => resize());
1172
+ return
1173
+ }
1174
+ if (["setAttribute","removeAttribute"].includes(type)) {
1175
+ let [name, value] = [...argsList];
1176
+ const variable = document.body.vars[name];
1177
+ if(type==="removeAttribute") value = undefined;
1178
+ if (variable && variable.imported) document.body.setVariableValue(name, value);
1179
+ }
1180
+ });
1181
+ const url = new URL(document.baseURI);
1182
+ document.lightviewId = url.searchParams.get("id");
1183
+ postMessage({type: "DOMContentLoaded"})
1184
+ }
1185
+ } else if (url.searchParams.has("as")) {
1186
+ bodyAsComponent({as: url.searchParams.get("as"), unhide});
1187
+ }
1188
+ if (enableFrames) {
1189
+ postMessage.enabled = true;
1190
+ addListener(window, "message", (message) => {
1191
+ const {type, iframeId, argsList, href} = JSON.parse(message.data),
1192
+ iframe = document.getElementById(iframeId);
1193
+ if (iframe) {
1194
+ if (type === "DOMContentLoaded") {
1195
+ postMessage({type: "framed", href: document.baseURI}, iframe);
1196
+ Object.defineProperty(domContentLoadedEvent, "currentTarget", {
1197
+ enumerable: false,
1198
+ configurable: true,
1199
+ value: iframe
1200
+ });
1201
+ domContentLoadedEvent.href = href;
1202
+ domContentLoadedEvent.srcElement = iframe;
1203
+ domContentLoadedEvent.bubbles = false;
1204
+ domContentLoadedEvent.path = getNodePath(iframe);
1205
+ Object.defineProperty(domContentLoadedEvent, "timeStamp", {
1206
+ enumerable: false,
1207
+ configurable: true,
1208
+ value: performance.now()
1209
+ })
1210
+ iframe.dispatchEvent(domContentLoadedEvent);
1211
+ return;
1212
+ }
1213
+ if (type === "setAttribute") {
1214
+ const [name, value] = [...argsList];
1215
+ if (iframe.getAttribute(name) !== value + "") iframe.setAttribute(name, value);
1216
+ return;
1217
+ }
1218
+ if (type === "removeAttribute") {
1219
+ iframe.removeAttribute(...argsList);
1220
+ return;
1221
+ }
1222
+ }
1223
+ console.warn("iframe posted a message without providing an id", message);
1224
+ });
1225
+ if (!OBSERVER) {
1226
+ const mutationCallback = (mutationsList) => {
1227
+ const console = document.getElementById("console");
1228
+ for (const {target, attributeName, oldValue} of mutationsList) {
1229
+ const value = target.getAttribute(attributeName);
1230
+ if (!["height", "width", "message"].includes(attributeName)) {
1231
+ if (!value) postMessage({type: "removeAttribute", argsList: [attributeName]}, iframe)
1232
+ else if (value !== oldValue) {
1233
+ postMessage({
1234
+ type: "setAttribute",
1235
+ argsList: [attributeName, value]
1236
+ }, iframe)
1237
+ }
1238
+ }
1239
+ if (attributeName === "message") {
1240
+ if (value) {
1241
+ target.removeAttribute("message");
1242
+ target.dispatchEvent(new CustomEvent("message", {target, detail: JSON.parse(value)}))
1243
+ }
1244
+ } else {
1245
+ target.dispatchEvent(new CustomEvent("attribute.changed", {
1246
+ target,
1247
+ detail: {attributeName, value, oldValue}
1248
+ }))
1249
+ }
1250
+ }
1251
+ };
1252
+ const observer = OBSERVER = new MutationObserver(mutationCallback);
1253
+ // iframe = document.getElementById("myframe");
1254
+ [...document.body.querySelectorAll("iframe")].forEach((iframe) => {
1255
+ observer.observe(iframe, {attributes: true, attributeOldValue: true});
1256
+ });
1257
+ }
1258
+ }
1259
+ }
1260
+ const whenFramed = (callback, {isolated} = {}) => {
1261
+ // loads for framed content
1262
+ addListener(document, "DOMContentLoaded", (event) => loader(callback));
1263
+ }
1264
+ Lightview.whenFramed = whenFramed;
1265
+ Lightview.loader = loader;
1266
+ //debugger;
1267
+ if (window.location === window.parent.location || !(window.parent instanceof Window) || window.parent !== window) {
1268
+ // loads for unframed content
1269
+ // CodePen mucks with window.parent
1270
+ addListener(document, "DOMContentLoaded", () => loader())
1271
+ }
1272
+
1273
+ return {observe}
1274
+ })();