-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdotpipe.js
More file actions
7670 lines (6812 loc) · 281 KB
/
dotpipe.js
File metadata and controls
7670 lines (6812 loc) · 281 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* dotPipe.js – Dynamic Web Components & Attribute Framework
*
* USAGE INSTRUCTIONS:
*
* All custom tags MUST include a unique 'id' attribute.
* Most attributes/classes can be combined for powerful UI behaviors.
* Inline macros can be used via the 'inline' attribute for dynamic, per-element logic.
* See below for supported elements, attributes, and inline macro usage.
*
* ──────────────────────────────────────────────────────────────
* CUSTOM TAGS
*
* <pipe> AJAX loader & DOM initializer. Triggers on DOMContentLoaded.
* <cart> Shopping cart UI; supports <item> children.
* <item> Product item, used inside <cart>.
* <dyn> Auto event tag; triggers pipes() on click.
* <search> Search/filter content or tables by IDs.
* <csv> Display CSV data as table, list, or cards.
* <tabs> Tabbed navigation; define tabs and sources.
* <login> Login and registration forms; supports AJAX.
* <checkout> Checkout flow with validation and summary.
* <carousel> Content/image slider, supports auto/timed movement.
* <columns> Multi-column responsive layout.
* <timed> Auto-refresh content at intervals.
* <refresh> Manual/auto refresh for element targets.
* <order-confirmation> Order confirmation details display.
* <lnk> Clickable link; supports AJAX/source loading.
*
* ──────────────────────────────────────────────────────────────
* UNIVERSAL ATTRIBUTES
*
* id REQUIRED for all custom tags. Must be unique.
* inline Optional inline macro string to define dynamic logic per element.
* Supports operators: |, |!, |$, |$id:varName, nop:varName, |@id.prop:varName, |#varName:id.prop, |%funcName:[args]
* ajax Fetch remote resource (HTML, JSON, etc.) for tag.
* insert Target ID to render AJAX response.
* query Key-value pairs for AJAX requests, e.g. "key:value&"
* callback JS function called after completion.
* callback-class CSS class grouping for callback parameters.
* modal Load JSON file(s) into target(s) for templates or modals.
* file Filename to download (with class="download").
* directory Path for file download (must end with slash).
* set Set attribute value: "target-id:attr:value".
* get Get attribute value: "source-id:attr:target-id".
* delete Remove attribute: "target-id:attr".
* x-toggle Toggle classes on elements: "id:class;id2:class2".
* tool-tip Tooltip text and options: "text;id;class;duration;zIndex".
* modal-tip Load tooltip from JSON: "filename.json;duration;zIndex".
* copy Copy element content to clipboard by ID.
* remove Remove elements by IDs: "id1;id2".
* display Show/hide elements by IDs: "id1;id2".
* headers Custom HTTP headers for AJAX, e.g. "header:value&header2:value2".
* form-class Class grouping for form elements in AJAX forms.
* action-class Class group for triggering/listening elements.
* event Supported events: "click;mouseover;..." (works with mouse/pipe classes).
* options <select> tag only; defines options: "key:value;key2:value2".
* sources For carousel/card tags; semicolon-delimited file list.
* style Inline CSS for the tag/component.
* tab <tabs> only; defines tabs: "TabName:TabId:Source;..."
* login-page <login> only; login AJAX handler/page.
* registration-page <login> only; registration AJAX handler/page.
* css-page <login> only; external stylesheet for auth UI.
* validate <checkout> only; enables validation mode (debug).
* pages <columns> only; semicolon-delimited sources for columns.
* count <columns> only; number of columns.
* percents <columns> only; comma-separated column percent widths.
* height, width <columns> only; set column layout size.
* delay For <timed>, <carousel>; refresh/slide interval (ms).
* interval Number of steps for file-order/carousel.
* file-order Iterates AJAX over files: "file1;file2;file3".
* file-index Index for file-order.
* mode HTTP method: "POST" or "GET".
* turn Element rotation/activation: "elem1;elem2".
* turn-index Current index for turn.
* boxes Request/set number of carousel boxes.
* sort For <csv>; column and direction, e.g. "Name:csv-asc".
* page-size For <csv>; items per page.
* lazy-load For <csv>; enable/disable lazy loading (default true).
*
* ──────────────────────────────────────────────────────────────
* Core Syntax
* |verb:param1:param2 → call a verb with parameters
* !varName → resolve a pipeline variable
* &varName:value → assign a pipeline variable
* |$id.prop:value → set a DOM property/attribute
*
* Shells (scoped pipelines)
* |+targetId:shellName → start a new shell, scoped to element with id=targetId
* - shell variables are isolated until closed
* - shellName is a label for managing
* |-shellName → close shell, merge variables back into parent, discard shell
*
* Example:
* |+crazyStrawOutput:timer1
* |&n:testing
* |log:!n
* |-timer1
*
* Variable Handling
* &x:123 → define variable x = "123"
* log:!x → logs "123" in console
* !x.prop → deep resolve object property (if object/JSON)
*
* Example:
* |&user:John
* |log:!user
*
* DOM Binding
* |$id.innerHTML:!var → set innerHTML of element #id
* |$id.value:42 → set form input value
*
* Example:
* |&msg:Hello
* |$status.innerHTML:!msg
*
* Standard Verbs
* log:x → console.log the parameter(s)
* modala:url:targetId → fetch JSON and render into DOM via modala()
* exc:this → send the current clicked element into the pipeline
* exc:someVar → send variable into the pipeline
* nop:x → no-op, passes value through
*
* AJAX & Modala
* <tag ajax="file.json:targetId" class="modala"> → load JSON via modala()
* Or inline:
* |modala:./inline/data.json:crazyStrawOutput
*
* Example Pipeline
* <div id="crazyStrawOutput"></div>
*
* <button inline="
* |+crazyStrawOutput:timer1
* |modala:./inline/data.json:crazyStrawOutput
* |&n:testing
* |log:!n
* |$crazyStrawOutput.innerHTML:!n
* |-timer1
* ">Run Modala</button>
*
* -------------------------------------------------------
* |call: Function Invoker
* -------------------------------------------------------
* Usage:
* |call:fnName:param1:param2:...
*
* Behavior:
* - Looks up a function by name in global scope (window).
* - Resolves each param:
* - "this" → the current clicked/triggered element
* - "!varName" → value from dpVars
* - any other string → literal
* - Calls fnName(...resolvedParams)
*
* Examples:
* |call:highlight:this
* → highlight(elem) with the clicked element.
*
* |&n:42 |call:processValue:!n
* → stores 42 in dpVars.n, then calls processValue(42).
*
* |call:saveData:crazyStrawOutput:Done!
* → saveData("crazyStrawOutput", "Done!")
*
* Notes:
* - Functions must be globally accessible (on window).
* - Works with loose functions, modules (if exported globally),
* or inline <script> functions.
* - This allows extending dotPipe with ANY custom JS logic.
* ============================================================
* EXAMPLES
*
* <!-- Basic variable and DOM injection -->
* <div id="example" inline="
* |&greeting:Hello World
* |$outputDiv:!greeting
* "></div>
* <div id="outputDiv"></div>
* <button id="run">Show Greeting</button>
* <script>
* dotPipe.register();
* document.getElementById('run').addEventListener('click', () => {
* dotPipe.runInline('example');
* });
* </script>
*
* <!-- Function call with variable reference -->
* <div id="example2" inline="
* |&greeting:Hello World
* |%shout:[!greeting]
* "></div>
* <script>
* function shout(text) { alert(text.toUpperCase()); }
* dotPipe.register();
* document.getElementById('example2').addEventListener('click', () => {
* dotPipe.runInline('example2');
* });
* </script>
*
* <!-- Read and update element properties -->
* <input id="input1" value="initial">
* <div id="display"></div>
* <div id="example3" inline="
* |#currentValue:input1.value
* |$display:!currentValue
* "></div>
* <script>
* dotPipe.register();
* document.getElementById('example3').addEventListener('click', () => {
* dotPipe.runInline('example3');
* });
* </script>
*
* <!-- Store current value for later reuse -->
* <div id="example4" inline="
* |&greeting:Hello World
* |nop:latest
* |$outputDiv:!latest
* "></div>
* <div id="outputDiv"></div>
* <script>
* dotPipe.register();
* document.getElementById('example4').addEventListener('click', () => {
* dotPipe.runInline('example4');
* });
* </script>
*
* ──────────────────────────────────────────────────────────────
* SYSTEM FLOW:
*
* 1. dotPipe.register(selector) scans for elements with 'inline' attributes.
* 2. Each element gets a dpVars object for variable storage.
* 3. Inline macros are executed manually with dotPipe.runInline(id).
* 4. Inline operators allow:
* - Variable storage and referencing
* - Function calls with arguments
* - DOM insertion or property manipulation
* - Value reading and storage
* 5. Async/await supported for AJAX or custom async functions.
* 6. No recursion occurs; macros only execute when triggered.
*
* ──────────────────────────────────────────────────────────────
* BEST PRACTICES:
*
* - Use unique IDs for all elements involved in inline macros.
* - Chain multiple operators using '|' in inline attribute.
* - Update dpVars at runtime as needed; macros only fire when runInline() is called.
* - Use !varName inside %funcName:[...] to reference current runtime values.
* - For DOM manipulation:
* - Use |$id:!varName for innerHTML
* - Use |@id.prop:!varName for element properties
* - For property reads: |#varName:id.prop
* - For temporary storage: |nop:varName
* ──────────────────────────────────────────────────────────────
* SUPPORT CLASSES
*
* download Enables file download behavior.
* redirect Follows AJAX URL after response.
* plain-text Renders response as plain text.
* plain-html Renders response as HTML.
* json Renders response as JSON.
* strict-json Returns only JSON to page; errors otherwise.
* tree-view Renders tree structure from JSON.
* incrIndex Increment file-order index (carousel, etc.).
* decrIndex Decrement file-order index.
* modala-multi-first Multi-ajax; insert at start, remove last if limit.
* modala-multi-last Multi-ajax; insert at end, remove first if limit.
* clear-node Clears content of specified nodes.
* time-active Activates timers for auto-refresh/timed elements.
* time-inactive Deactivates timers for auto-refresh/timed elements.
* disabled Disables the tag from interaction.
* multiple Multi-select form box.
* action-class Marks tags to be triggered/listened for actions.
* mouse Enables tooltip and event-driven interactions.
* mouse-insert Event-driven insertions for mouse events.
* carousel-step-right Moves carousel one step right.
* carousel-step-left Moves carousel one step left.
* carousel-slide-right Auto-slide carousel to right.
* carousel-slide-left Auto-slide carousel to left.
*
* ──────────────────────────────────────────────────────────────
* SPECIAL KEY/VALUE PAIRS (for modala templates)
*
* br Insert line breaks ("br": "count").
* js Load external JS file(s).
* css Load external CSS file(s).
* modala Load modala JSON file(s).
* tree-view Load tree structure from JSON.
*
* ──────────────────────────────────────────────────────────────
* QUICK USAGE EXAMPLES:
*
* <!-- AJAX load into target -->
* <pipe id="product-list" ajax="products.json" insert="product-container"></pipe>
*
* <!-- Shopping cart with items -->
* <cart id="main-cart">
* <item id="widget-1" name="Widget" price="9.99"></item>
* <item id="gadget-2" name="Gadget" price="14.99"></item>
* </cart>
*
* <!-- Inline macros -->
* <div id="fa" inline="ajax:/api/new:GET|!nop:newData|$resultsDiv:newData"></div>
* <div id="fb" inline="ajax:/api/list:GET|!nop:list|%processData:[#list,@outputDiv.innerText]|@outputDiv.innerText:list"></div>
*
* <!-- Carousel slider -->
* <carousel id="image-carousel" sources="img1.jpg;img2.jpg;img3.jpg" delay="3000" boxes="1"></carousel>
*
* <!-- Form with AJAX login -->
* <login id="auth-login" login-page="login.php" registration-page="register.php" css-page="auth.css"></login>
*
* ──────────────────────────────────────────────────────────────
* SYSTEM FLOW:
* - On DOMContentLoaded, dotPipe processes all supported custom tags.
* - pipes() manages all custom tag logic, triggers AJAX, updates DOM, runs callbacks, and executes inline macros.
* - Inline macros are parsed via regex, support all pipe operators, and store variables per element in dpVars.
* - navigate() performs AJAX requests and inserts responses.
* - modala() loads and renders JSON templates for modals and complex UIs.
*
* (c) dotPipe.js – https://github.com/dotpipe/dotPipe
*/
class DotPipeBinder {
constructor() {
this.controllers = {};
}
register(name, controller) {
this.controllers[name] = controller;
}
bindElement(el) {
const controllerName = el.getAttribute("bind");
if (controllerName && this.controllers[controllerName]) {
const controller = this.controllers[controllerName];
if (typeof controller.init === "function") {
controller.init(el);
}
// Auto-bind methods like onAdd, onRemove, onCheckout
Object.keys(controller).forEach(key => {
if (key.startsWith("on")) {
const eventName = key.slice(2).toLowerCase();
el.addEventListener(eventName, e => controller[key](el, e));
}
});
}
}
init(root = document) {
root.querySelectorAll("[bind]").forEach(el => this.bindElement(el));
}
// NEW: Observe DOM changes (e.g. after AJAX injection)
observe() {
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.nodeType === 1) {
// If the new node itself has a bind attribute
if (node.hasAttribute && node.hasAttribute("bind")) {
this.bindElement(node);
}
// Or if it contains children with bind attributes
this.init(node);
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
}
}
// Tutorial helper utilities (exposed on window) moved from demo HTML
window.showAlert = function(message) {
alert(message);
};
window.updateOutput = function(outputId, content) {
const elem = document.getElementById(outputId);
if (elem) elem.innerHTML = content;
};
window.highlightElement = function(elementId) {
const elem = document.getElementById(elementId);
if (elem) {
const prev = elem.style.background;
elem.style.background = '#ffff00';
setTimeout(() => { elem.style.background = prev; }, 2000);
}
};
window.processData = function(data) {
try { console.log('Processing data:', data); return JSON.stringify(data, null, 2); }
catch (e) { return String(data); }
};
window.clearOutput = function(outputId) {
const elem = document.getElementById(outputId);
if (elem) elem.innerHTML = '<em>Output cleared. Ready for next demo...</em>';
};
// Simple in-memory storage for demo usage
window.demoVars = window.demoVars || {};
window.storeValue = function(key, value) { window.demoVars[key] = value; console.log(`Stored ${key} = ${value}`); };
window.retrieveValue = function(key) { return window.demoVars[key] || 'undefined'; };
document.addEventListener("DOMContentLoaded", function () {
try {
if (document.body != null && JSON.parse(document.body.textContent)) {
const irc = JSON.parse(document.body.textContent);
document.body.textContent = "";
modala(irc, document.body);
document.body.style.display = "block";
}
}
catch (e) {
console.error('Failed to parse body JSON:', e);
}
domContentLoad();
addPipe(document.body);
var binder = new DotPipeBinder();
binder.init();
binder.observe();
generateNonce().then(nonce => {
const script_tags = document.getElementsByTagName("script");
const style_tags = document.getElementsByTagName("style");
Array.from(script_tags).forEach(function (elem) {
elem.nonce = nonce;
});
Array.from(style_tags).forEach(function (elem) {
elem.nonce = nonce;
});
PAGE_NONCE = nonce
var meta = document.createElement("meta");
meta.content = `default-src 'self'; script-src 'self' 'nonce-${PAGE_NONCE}'; style-src 'self' 'unsafe-inline' 'unsafe-hashes'; img-src 'self' data: https: http:; connect-src https: http: 'self'; child-src 'none'; object-src 'none'`;
meta.httpEquiv = "Content-Security-Policy";
document.head.appendChild(meta);
});
// Automatically register all inline elements
// dotPipe.register();
// Optionally, auto-bind clicks or other events if desired
for (const key in dotPipe.matrix) {
const entry = dotPipe.matrix[key];
const el = entry.element;
// Auto-click binding if element has inline and is clickable
if (el.tagName === 'BUTTON' || el.hasAttribute('data-auto-click')) {
el.addEventListener('click', () => dotPipe.runInline(key));
}
// Optionally, you can parse a 'data-event' attribute for any event
const events = el.getAttribute('data-event');
if (events) {
events.split(';').forEach(ev => {
el.addEventListener(ev.trim(), () => dotPipe.runInline(key));
});
}
}
});
// Macro resolver: #id.member or .class.member
function resolveMacro(expr) {
if (!expr || typeof expr !== "string") return expr;
// Only process if starts with # or .
if (!(expr.startsWith("#") || expr.startsWith("."))) return expr;
let parts = expr.split(".");
let base = parts[0]; // "#id" or ".class"
let member = parts.slice(1).join("."); // optional member chain
let elems = [];
if (base.startsWith("#")) {
let id = base.slice(1);
let el = document.getElementById(id);
if (el) elems.push(el);
} else if (base.startsWith(".")) {
let cls = base.slice(1);
elems = Array.from(document.getElementsByClassName(cls));
}
if (!member) return elems.length === 1 ? elems[0] : elems;
// If member is present, return values or functions
return elems.map(el => {
if (member in el) {
return (typeof el[member] === "function") ? el[member].bind(el) : el[member];
}
return null;
});
}
const dotPipe = {
matrix: {},
vars: {},
// ======================
// Register inline macros
// ======================
register: function (selector = '[inline]') {
const elements = document.querySelectorAll(selector);
elements.forEach(el => {
const key = el.id || el.getAttribute('inline') || Symbol();
this.matrix[key] = {
element: el,
tag: el,
inlineMacro: el.getAttribute('inline'),
dpVars: {}, // plain storage; no auto-run
shells: {}
};
});
},
// ======================
// Shell Management
// ======================
runShellOpen: function (targetId, shellName, entry) {
if (!entry.shells) entry.shells = {};
entry.shells[shellName] = {
targetId,
dpVars: {},
matrix: [],
buffer: [],
element: document.getElementById(targetId) || entry.element,
segments: []
};
console.log(`[dotPipe] Opened shell "${shellName}" on target "${targetId}"`);
return entry.shells[shellName];
},
runShellClose: function (shellName, entry) {
if (entry.shells && entry.shells[shellName]) {
console.log(`[dotPipe] Closed shell "${shellName}"`);
delete entry.shells[shellName];
return true;
} else {
console.warn(`[dotPipe] Tried to close unknown shell: "${shellName}"`);
return false;
}
},
// ======================
// Inline Macro Runner
// ======================
runInline: async function (key) {
const entry = this.matrix[key];
if (!entry || !entry.inlineMacro) return;
this.currentElem = entry.element;
let currentValue = null;
let currentShell = null;
const segments = entry.inlineMacro.split('|').filter(s => s.trim() !== '');
for (let i = 0; i < segments.length; i++) {
let seg = segments[i].trim();
// Replace only single backslash-escaped ! (not double-backslash) with a placeholder
const EXCL_PLACEHOLDER = '__DOTPIPE_EXCL__';
seg = seg.replace(/(^|[^\\])\\!(?!\\)/g, (m, p1) => p1 + EXCL_PLACEHOLDER);
// Restore double-backslash-escaped ! to single backslash + !
seg = seg.replace(/\\\\!/g, '\\!');
let m;
// ===============================
// ATTRIBUTE BINDING
// Supports: #id[attr]:value
// .class[][attr]:value
// ===============================
if (m = /^([#\.]?[a-zA-Z0-9_\-]+)(\[\s*([a-zA-Z0-9_\-]+)\s*\])\s*:(.+)$/.exec(seg)) {
const selector = m[1]; // "#id" or ".class" or "id"
const attrName = m[3]; // attribute inside the [attr]
let rawValue = m[4]; // literal or !var
const s = currentShell || entry;
// Restore literal exclamation marks
rawValue = rawValue.replace(/__DOTPIPE_EXCL__/g, '!');
// Resolve !var (only if it starts with ! and not a literal)
// Interpolate all !var occurrences in the string (not preceded by a backslash)
if (typeof rawValue === 'string') {
rawValue = rawValue.replace(/(^|[^\\])!([a-zA-Z_][a-zA-Z0-9_]*)/g, (m, pre, v) => {
let val = s.dpVars[v];
if (val === undefined || val === null) val = '';
return pre + val;
});
// Restore literal exclamation marks
rawValue = rawValue.replace(/__DOTPIPE_EXCL__/g, '!');
} else {
rawValue = dotPipe.parseValue(rawValue);
}
// Get elements — re-use your selector logic
let elems = [];
if (selector.startsWith('#')) {
const el = document.getElementById(selector.slice(1));
if (el) elems = [el];
} else if (selector.startsWith('.')) {
elems = Array.from(document.getElementsByClassName(selector.slice(1)));
} else {
const el = document.getElementById(selector);
if (el) elems = [el];
}
elems.forEach(el => {
if (rawValue === null || rawValue === undefined) {
el.removeAttribute(attrName);
} else {
el.setAttribute(attrName, rawValue);
}
});
currentValue = rawValue;
continue;
}
// Operator property / text setter supporting [indexExpr]
if (m = /^([#\.\$]?[\w\-]+)(?:\[(.*?)\])?\.(text|style|[a-zA-Z\-]+)\:(.+)$/.exec(seg)) {
const selector = m[1]; // e.g. ".item" or "#id" or "$id" or "bareId"
const indexExpr = m[2] || ""; // e.g. "0", "1,3", "1:4:2", ""
const propOrKind = m[3]; // "text" or "style" or "color" etc.
let rawValue = m[4]; // could be "!var" or literal
const s = currentShell || entry;
// Restore literal exclamation marks
rawValue = rawValue.replace(/__DOTPIPE_EXCL__/g, '!');
// resolve variable references like !var (only if not a literal)
if (typeof rawValue === 'string') {
rawValue = rawValue.replace(/(^|[^\\])!([a-zA-Z_][a-zA-Z0-9_]*)/g, (m, pre, v) => {
let val = s.dpVars[v];
if (val === undefined || val === null) val = '';
return pre + val;
});
rawValue = rawValue.replace(/__DOTPIPE_EXCL__/g, '!');
} else {
rawValue = dotPipe.parseValue(rawValue);
}
// get matching elements (handles class slices)
const elems = dotPipe.getElementsForSelector(selector, indexExpr);
if (!elems || elems.length === 0) {
// nothing to apply to; warn optionally
// console.warn("[dotPipe] operator: selector matched no elements:", selector, indexExpr);
currentValue = undefined;
continue;
}
// apply to all matched elements
elems.forEach(el => {
if (propOrKind === 'text') {
el.innerHTML = (rawValue === undefined || rawValue === null) ? '' : String(rawValue);
} else if (propOrKind === 'style') {
// expected usage: "#id.style:color:red" but here we captured only "style" as prop; handle "style:prop:val" pattern elsewhere.
// if using "#id.styleProp:value" user should send "#id.styleProp:value" - here treat 'style' as setting innerText
el.innerHTML = (rawValue === undefined || rawValue === null) ? '' : String(rawValue);
} else {
// treat propOrKind as CSS/property
try {
el.style[propOrKind] = rawValue;
} catch (e) {
// if property not a style, set attribute/property fallback
try { el[propOrKind] = rawValue; } catch (e2) { el.setAttribute(propOrKind, rawValue); }
}
}
});
currentValue = rawValue;
continue;
}
// --- Start shell: |+targetId:shellName
if (m = /^\+\s*([a-zA-Z0-9_\-]+):([a-zA-Z0-9_]+)/.exec(seg)) {
const targetId = m[1];
const shellName = m[2];
entry.shells = entry.shells || {};
if (!entry.shells[shellName]) {
entry.shells[shellName] = {
dpVars: {},
matrix: [],
element: document.getElementById(targetId) || entry.element,
segments: segments.slice(i + 1)
};
}
currentShell = entry.shells[shellName];
await this.runShell(currentShell);
currentShell = null;
break;
}
// --- Close shell: |-shellName
if (m = /^\-\s*([a-zA-Z0-9_]+)/.exec(seg)) {
const shellName = m[1];
if (entry.shells && entry.shells[shellName]) {
Object.assign(entry.dpVars, entry.shells[shellName].dpVars);
delete entry.shells[shellName];
currentShell = null;
}
continue;
}
// --- Property read: |#var:id.prop
if (m = /^#([a-zA-Z0-9_]+):([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)$/.exec(seg)) {
const varName = m[1];
const elemId = m[2];
const prop = m[3];
const el = document.getElementById(elemId);
let value = undefined;
if (el && prop in el) {
value = el[prop];
}
(currentShell || entry).dpVars[varName] = value;
currentValue = value;
continue;
}
// --- Literal assignment: |&var:value (supports !var?default)
if (m = /^\&([a-zA-Z0-9_]+):(.+)$/.exec(seg)) {
const varName = m[1];
let value = m[2];
const s = currentShell || entry;
const initMatch = /^!(\w+)?(.+)$/.exec(value);
if (initMatch) {
const existingVar = initMatch[1];
const defaultVal = initMatch[2];
if (s.dpVars[existingVar] === undefined) {
s.dpVars[existingVar] = dotPipe.parseValue(defaultVal);
}
currentValue = s.dpVars[existingVar];
} else {
s.dpVars[varName] = dotPipe.parseValue(value);
currentValue = s.dpVars[varName];
}
continue;
}
// ==========================
// Operator property setter
// ==========================
if (m = /^([#\.\$]?[\w\-]+)\.([a-zA-Z\-]+):(.+)$/.exec(seg)) {
let selector = m[1];
let prop = m[2];
let value = m[3];
const s = currentShell || entry;
// Restore literal exclamation marks
value = value.replace(/__DOTPIPE_EXCL__/g, '!');
// resolve variables such as !hp or !color (only if not a literal)
if (typeof value === 'string') {
value = value.replace(/(^|[^\\])!([a-zA-Z_][a-zA-Z0-9_]*)/g, (m, pre, v) => {
let val = s.dpVars[v];
if (val === undefined || val === null) val = '';
return pre + val;
});
value = value.replace(/__DOTPIPE_EXCL__/g, '!');
} else {
value = dotPipe.parseValue(value);
}
const el = dotPipe.resolveElement(selector);
if (!el) {
console.warn("[dotPipe] selector not found:", selector);
continue;
}
el.style[prop] = value;
currentValue = value;
continue;
}
// --- nop:varName stores currentValue
if (m = /^nop:([a-zA-Z0-9_]+)$/.exec(seg)) {
(currentShell || entry).dpVars[m[1]] = currentValue;
continue;
}
// --- Set element content: $id or $id:!var
if (m = /^\$([a-zA-Z0-9_-]+)(?::(.+))?$/.exec(seg)) {
const targetEl = document.getElementById(m[1]);
if (targetEl) {
let value;
if (!m[2]) {
value = currentValue;
} else {
// Improved: Replace !varName even if followed by punctuation or /number
value = m[2].split(' ').map(word => {
if (word.startsWith('!')) {
// Extract variable name (letters, numbers, underscores)
const match = /^!([a-zA-Z_][a-zA-Z0-9_]*)(.*)$/.exec(word);
if (match) {
const varName = match[1];
const suffix = match[2] || '';
let v = (currentShell || entry).dpVars[varName];
if (v === undefined || v === null) v = '';
return v + suffix;
} else {
return word;
}
} else {
return word;
}
}).join(' ');
}
// Restore literal exclamation marks
if (typeof value === 'string') value = value.replace(/__DOTPIPE_EXCL__/g, '!');
if (typeof value === "boolean") value = value ? "ON" : "OFF";
targetEl.innerHTML = value;
}
continue;
}
// --- Verbs ---
if (m = /^([a-zA-Z0-9_+\-]+):?(.*)$/.exec(seg)) {
const verb = m[1];
const params = m[2] ? m[2].split(':').map(p => p.trim()) : [];
const resolvedParams = params.map(p => {
if (p.startsWith('!')) return (currentShell || entry).dpVars[p.slice(1)];
return p;
});
if (typeof this.verbs[verb] === 'function') {
const result = await this.verbs[verb](...resolvedParams, currentShell || entry);
currentValue = result;
} else {
console.warn("Unknown verb:", verb);
}
continue;
}
}
},
// returns array of elements given selector and optional indexExpr
getElementsForSelector: function (selector, indexExpr) {
// selector may be '#id', '$id', '.class' or bare id
if (!selector) return [];
// normalize $ to #
if (selector[0] === '$') selector = '#' + selector.slice(1);
// ID selector -> single element in array
if (selector[0] === '#') {
const el = document.getElementById(selector.slice(1));
return el ? [el] : [];
}
// class selector -> collection
let elems = [];
if (selector[0] === '.') {
elems = Array.from(document.getElementsByClassName(selector.slice(1)));
} else {
// bare id fallback
const el = document.getElementById(selector);
if (el) elems = [el];
}
if (!indexExpr || indexExpr === '') return elems;
// indexExpr handling: "x,y", "start:end:step", "N" or negative indices or empty -> all
if (indexExpr.includes(',')) {
const indices = indexExpr.split(',').map(s => parseInt(s.trim(), 10)).filter(n => !isNaN(n));
const out = [];
indices.forEach(idx => {
if (idx < 0) idx = elems.length + idx;
if (idx >= 0 && idx < elems.length) out.push(elems[idx]);
});
return out;
}
if (indexExpr.includes(':')) {
const parts = indexExpr.split(':').map(s => s.trim());
let start = parts[0] === '' ? 0 : parseInt(parts[0], 10);
let endPart = parts[1];
let step = parts[2] ? parseInt(parts[2], 10) : 1;
if (isNaN(start)) start = 0;
if (!endPart) {
endPart = elems.length;
}
let end = parseInt(endPart, 10);
if (isNaN(end)) end = elems.length;
if (start < 0) start = elems.length + start;
if (end < 0) end = elems.length + end;
start = Math.max(0, start);
end = Math.min(elems.length, end);
const out = [];
for (let i = start; i < end; i += step) {
out.push(elems[i]);
}
return out;
}
// single index
let idx = parseInt(indexExpr, 10);
if (isNaN(idx)) return elems;
if (idx < 0) idx = elems.length + idx;
return (idx >= 0 && idx < elems.length) ? [elems[idx]] : [];
},
// ======================
// Run shell segments
// ======================
runShell: async function (shell) {
if (!shell || !shell.segments) return;
let currentValue = null;
for (let seg of shell.segments) {
seg = seg.trim();
let m;
// &var:value inside shell
if (m = /^\&([a-zA-Z0-9_]+):(.+)$/.exec(seg)) {
const varName = m[1];
let value = m[2];
const initMatch = /^!(\w+)\?(.+)$/.exec(value);
if (initMatch) {
const existingVar = initMatch[1];
const defaultVal = initMatch[2];
if (shell.dpVars[existingVar] === undefined) {
shell.dpVars[existingVar] = dotPipe.parseValue(defaultVal);
}
currentValue = shell.dpVars[existingVar];
} else {
shell.dpVars[varName] = dotPipe.parseValue(value);
currentValue = shell.dpVars[varName];
}
continue;
}
// nop
if (m = /^nop:([a-zA-Z0-9_]+)$/.exec(seg)) {
shell.dpVars[m[1]] = currentValue;
continue;
}
// $id or $id:!var or $id:Hello !user !score
if (m = /^\$([a-zA-Z0-9_-]+)(?::(.+))?$/.exec(seg)) {
const targetEl = document.getElementById(m[1]);
if (targetEl) {
let value;
if (!m[2]) {
value = currentValue;
} else {
// Improved: Replace !varName even if followed by punctuation or /number
value = m[2].split(' ').map(word => {
if (word.startsWith('!')) {
const match = /^!([a-zA-Z_][a-zA-Z0-9_]*)(.*)$/.exec(word);
if (match) {
const varName = match[1];
const suffix = match[2] || '';
let v = shell.dpVars[varName];
if (v === undefined || v === null) v = '';
return v + suffix;
} else {
return word;
}
} else {
return word;
}
}).join(' ');
}
if (typeof value === "boolean") value = value ? "ON" : "OFF";
targetEl.innerHTML = value;
}
continue;
}
// verbs
if (m = /^([a-zA-Z0-9_+\-]+):?(.*)$/.exec(seg)) {
const verb = m[1];
const params = m[2] ? m[2].split(':').map(p => p.trim()) : [];
const resolvedParams = params.map(p => {
if (p.startsWith('!')) return shell.dpVars[p.slice(1)];
return p;
});
if (typeof dotPipe.verbs[verb] === 'function') {
currentValue = await dotPipe.verbs[verb](...resolvedParams, shell);
}
continue;
}
}
},
// ======================
// Helpers
// ======================
parseValue: function (val) {