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