aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/static/talktree.js
blob: e55653e24f9924db8a57dea452c3aaebd820d9f3 (plain)
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
// talktree.js — Conversation tree editor with unified condition & action
// editors powered by intereditor.js. Tree navigation, messages, and options
// (text / goto) stay here; condition and action editing delegates to
// intereditor via talk-scoped contexts that target talk.nodes[key]... paths.

(function() {
  'use strict';

  // ---- Path helpers ----

  function talkRoot() { return window._talkData && window._talkData.talk; }
  function talkNodes() { var r = talkRoot(); return r && r.nodes; }
  function talkSync() { if (typeof window.onTalkTreeChange === 'function') window.onTalkTreeChange(window._talkData); }

  function talkGet(path) {
    var parts = path.split('.'), obj = talkRoot();
    for (var i = 0; i < parts.length; i++) {
      if (obj == null) return undefined;
      var k = parts[i];
      obj = /^\d+$/.test(k) ? obj[parseInt(k, 10)] : obj[k];
    }
    return obj;
  }

  function talkSet(path, value) {
    var parts = path.split('.'), root = talkRoot();
    for (var i = 0; i < parts.length - 1; i++) {
      var k = parts[i];
      if (/^\d+$/.test(k)) {
        var idx = parseInt(k, 10);
        if (root[idx] == null) root[idx] = /^\d+$/.test(parts[i + 1]) ? [] : {};
        root = root[idx];
      } else {
        if (root[k] == null) root[k] = /^\d+$/.test(parts[i + 1]) ? [] : {};
        root = root[k];
      }
    }
    var lk = parts[parts.length - 1];
    if (/^\d+$/.test(lk)) { root[parseInt(lk, 10)] = value; }
    else { root[lk] = value; }
  }

  function talkDel(path) {
    var parts = path.split('.'), root = talkRoot();
    for (var i = 0; i < parts.length - 1; i++) {
      if (root == null) return;
      var k = parts[i];
      root = /^\d+$/.test(k) ? root[parseInt(k, 10)] : root[k];
    }
    if (!root) return;
    var lk = parts[parts.length - 1];
    if (/^\d+$/.test(lk)) { root.splice(parseInt(lk, 10), 1); }
    else { delete root[lk]; }
  }

  // ---- Talk scopes for intereditor.js ----
  // Each scope targets a specific condition or action object inside the talk
  // tree and handles re-render + talkSync on every mutation.

  // ---- Talk scopes for intereditor.js ----
  // Each scope targets a specific condition or action object inside the talk
  // tree and handles re-render + talkSync on every mutation.

  var _talkScopeSeq = 0;

  function talkCondScope(nodeKey, optIdx) {
    var token = 'tk' + (++_talkScopeSeq);
    return ie_registerScope({
      getCond: function() {
        var t = talkTarget(nodeKey, optIdx);
        return t && t.condition || null;
      },
      setCond: function(c) {
        var t = talkTarget(nodeKey, optIdx);
        if (!t) return;
        if (c) t.condition = c; else delete t.condition;
      },
      onChange: function() {
        talkSync();
        renderTalkTree(window._talkData);
      }
    }, token);
  }

  function talkActionScope(nodeKey, optIdx) {
    var token = 'tk' + (++_talkScopeSeq);
    return ie_registerScope({
      getStep: function() {
        var t = talkTarget(nodeKey, optIdx);
        return t && t.action || {};
      },
      setStep: function(s) {
        var t = talkTarget(nodeKey, optIdx);
        if (!t) return;
        if (s && Object.keys(s).length > 0) t.action = s; else delete t.action;
      },
      onChange: function() {
        talkSync();
        renderTalkTree(window._talkData);
      }
    }, token);
  }

  function talkTarget(nodeKey, optIdx) {
    var node = talkNodes() && talkNodes()[nodeKey];
    if (!node) return null;
    if (optIdx !== null) {
      if (!node.options || !node.options[optIdx]) return null;
      return node.options[optIdx];
    }
    return node;
  }

  // ---- Render a single action step for a talk node or option ----

  function talkRenderActionStep(nodeKey, optIdx) {
    var t = talkTarget(nodeKey, optIdx);
    var step = (t && t.action) || {};
    var scopeToken = talkActionScope(nodeKey, optIdx);
    var h = '<div class="ie-act-root" data-ie-scope="' + escAttr(scopeToken) + '">';
    h += ie_renderMessages(step, '', 0, 0, '');
    h += ie_renderAct(step, '', 0, 0, '');
    h += '<div class="ie-act-addbar">' + ie_renderStepAddbar(step, '', 0, 0, '') + '</div>';
    h += '</div>';
    return h;
  }

  // ---- talk cond/act add/remove helpers (called from onclick data-action) ----

  function talkAddNodeCond(nodeKey) {
    var node = talkNodes() && talkNodes()[nodeKey];
    if (!node || (node.condition && typeof node.condition === 'object')) return;
    node.condition = {all_of: []};
    renderTalkTree(window._talkData);
    talkSync();
  }

  function talkRemoveNodeCond(nodeKey) {
    var node = talkNodes() && talkNodes()[nodeKey];
    if (!node) return;
    delete node.condition;
    renderTalkTree(window._talkData);
    talkSync();
  }

  function talkAddNodeAct(nodeKey) {
    var node = talkNodes() && talkNodes()[nodeKey];
    if (!node || (node.action && typeof node.action === 'object')) return;
    node.action = {};
    renderTalkTree(window._talkData);
    talkSync();
  }

  function talkRemoveNodeAct(nodeKey) {
    var node = talkNodes() && talkNodes()[nodeKey];
    if (!node) return;
    delete node.action;
    renderTalkTree(window._talkData);
    talkSync();
  }

  function talkAddOptionCond(nodeKey, optIdx) {
    var t = talkTarget(nodeKey, optIdx);
    if (!t || (t.condition && typeof t.condition === 'object')) return;
    t.condition = {all_of: []};
    renderTalkTree(window._talkData);
    talkSync();
  }

  function talkRemoveOptionCond(nodeKey, optIdx) {
    var t = talkTarget(nodeKey, optIdx);
    if (!t) return;
    delete t.condition;
    renderTalkTree(window._talkData);
    talkSync();
  }

  function talkAddOptionAct(nodeKey, optIdx) {
    var t = talkTarget(nodeKey, optIdx);
    if (!t || (t.action && typeof t.action === 'object')) return;
    t.action = {};
    renderTalkTree(window._talkData);
    talkSync();
  }

  function talkRemoveOptionAct(nodeKey, optIdx) {
    var t = talkTarget(nodeKey, optIdx);
    if (!t) return;
    delete t.action;
    renderTalkTree(window._talkData);
    talkSync();
  }

  // ---- Event delegation ----

  function talkEvent(e) {
    var el = e.target;
    var path = el.getAttribute('data-tp');
    if (!path) return;

    var tag = el.tagName;
    var type = el.type;

    if (tag === 'INPUT' || tag === 'TEXTAREA') {
      var val;
      if (type === 'checkbox') { val = el.checked; }
      else if (type === 'number') { var n = parseFloat(el.value); val = isNaN(n) ? 0 : n; }
      else { val = el.value; }
      talkSyncPath(path, val);
      if (path.endsWith('.goto') && e.type === 'change') renderTalkTree(window._talkData);
    } else if (tag === 'SELECT') {
      talkSyncPath(path, el.value);
    }
  }

  function talkSyncPath(path, val) {
    talkSet(path, val);
    talkSync();
  }

  function talkHandleClick(e) {
    var el = e.target;
    var action = el.getAttribute('data-action');
    if (!action) return;

    var nodeKey = el.getAttribute('data-nk');
    var optIdx = el.getAttribute('data-oi');

    switch (action) {
      case 'delete-node':
        deleteNode(nodeKey);
        break;
      case 'add-option':
        addOption(nodeKey);
        break;
      case 'delete-option':
        deleteOption(nodeKey, parseInt(optIdx, 10));
        break;
      case 'add-node':
        addNode();
        break;
      case 'add-message':
        addMessageLine(nodeKey);
        break;
      case 'delete-message':
        deleteMessageLine(nodeKey, parseInt(optIdx, 10));
        break;
      case 'add-node-cond':
        talkAddNodeCond(nodeKey);
        break;
      case 'remove-node-cond':
        talkRemoveNodeCond(nodeKey);
        break;
      case 'add-node-act':
        talkAddNodeAct(nodeKey);
        break;
      case 'remove-node-act':
        talkRemoveNodeAct(nodeKey);
        break;
      case 'add-opt-cond':
        talkAddOptionCond(nodeKey, parseInt(optIdx, 10));
        break;
      case 'remove-opt-cond':
        talkRemoveOptionCond(nodeKey, parseInt(optIdx, 10));
        break;
      case 'add-opt-act':
        talkAddOptionAct(nodeKey, parseInt(optIdx, 10));
        break;
      case 'remove-opt-act':
        talkRemoveOptionAct(nodeKey, parseInt(optIdx, 10));
        break;
    }
  }

  // ---- Render entry point ----

  window.renderTalkTree = function(data) {
    var container = document.getElementById('talktree');
    if (!container) return;
    // Purge old talk scopes before re-rendering (new ones will be registered).
    if (window._ieScopes) {
      Object.keys(window._ieScopes).forEach(function(k) {
        if (k.indexOf('tk') === 0) delete window._ieScopes[k];
      });
    }
    _talkScopeSeq = 0;
    window._talkData = data;
    window._talkOpenNodes = window._talkOpenNodes || new Set();
    window._talkOpenNodes.add('start');
    if (!data || !data.talk || !data.talk.nodes) {
      container.innerHTML = '<p style="color:#888">No conversation tree defined.</p>';
      return;
    }
    var nodes = data.talk.nodes;
    var visited = {};
    var html = '<div class="talk-tree" id="talkTreeRoot">';
    html += '<datalist id="talkNodeKeys">';
    Object.keys(nodes).forEach(function(k) { html += '<option value="' + escAttr(k) + '">'; });
    html += '</datalist>';
    html += renderTreeNodes(nodes, 'start', visited);

    var allKeys = Object.keys(nodes);
    var orphanKeys = [];
    for (var i = 0; i < allKeys.length; i++) {
      if (!visited[allKeys[i]]) orphanKeys.push(allKeys[i]);
    }
    if (orphanKeys.length > 0) {
      html += '<div class="talk-orphans">';
      html += '<div class="talk-orphans-label">Unreferenced Nodes</div>';
      html += '<div class="talk-orphans-hint">These nodes are not reachable from start. Add a goto to them from another node\'s option.</div>';
      for (var j = 0; j < orphanKeys.length; j++) {
        html += renderOrphanNode(orphanKeys[j], nodes[orphanKeys[j]], nodes);
      }
      html += '</div>';
    }

    html += renderAddNodeRow();
    html += '</div>';
    container.innerHTML = html;
    if (typeof ced_setupSearchFields === 'function') {
      setTimeout(function() { ced_setupSearchFields(); }, 10);
    }
  };

  // ---- Add/Delete Node ----

  function renderAddNodeRow() {
    return '<div class="talk-add-node-row">' +
      '<input class="talk-input talk-input-sm" id="talkNewNodeKey" placeholder="New node key (unique name)">' +
      '<button class="talk-add-btn" data-action="add-node">Add Node</button>' +
      '</div>';
  }

  function addNode() {
    var input = document.getElementById('talkNewNodeKey');
    if (!input) return;
    var key = input.value.trim();
    if (!key) return;
    if (talkNodes()[key]) { notify('Node "' + key + '" already exists.', 'error'); return; }
    talkNodes()[key] = { messages: [], options: [] };
    input.value = '';
    renderTalkTree(window._talkData);
    talkSync();
  }

  function deleteNode(nodeKey) {
    if (nodeKey === 'start') { notify('Cannot delete the start node.', 'error'); return; }
    var nodes = talkNodes();
    if (!nodes || !nodes[nodeKey]) return;
    delete nodes[nodeKey];
    Object.keys(nodes).forEach(function(k) {
      var n = nodes[k];
      if (n.goto === nodeKey) delete n.goto;
      if (n.options) {
        n.options.forEach(function(opt) { if (opt.goto === nodeKey) opt.goto = ''; });
      }
    });
    renderTalkTree(window._talkData);
    talkSync();
  }

  // ---- Orphan node ----

  function renderOrphanNode(key, node, nodes) {
    var h = '<div class="talk-node">';
    h += '<div class="talk-node-header" onclick="if(!event.target.closest(\'[data-action]\'))talkToggleNode(\'' + escAttr(key) + '\',this.parentElement.parentElement)">';
    h += '<span class="talk-node-arrow"></span>';
    h += '<span class="talk-node-key">' + esc(key) + '</span>';
    h += '<span class="talk-node-preview">' + esc((getNodePreview(node) || '').substring(0, 60)) + '</span>';
    h += '<span class="talk-node-spacer"></span>';
    h += '<button class="talk-node-btn talk-node-del" data-action="delete-node" data-nk="' + escAttr(key) + '">Remove</button>';
    h += '</div>';
    h += '<div class="talk-node-body">';
    h += renderNodeBody(key, node, nodes);
    h += '</div>';
    h += '</div>';
    return h;
  }

  // ---- Recursive tree render ----

  function renderTreeNodes(nodes, rootKey, seen, indent) {
    indent = indent || 0;
    var node = nodes[rootKey];
    if (!node) return '';
    if (seen[rootKey]) {
      return '<div class="talk-node ref"><span class="talk-node-key">' + esc(rootKey) + '</span> <a href="javascript:void(0)" onclick="document.getElementById(\'node-' + escAttr(rootKey) + '\').scrollIntoView({behavior:\'smooth\',block:\'center\'});return false" style="color:inherit;text-decoration:underline">(see above)</a></div>';
    }
    seen[rootKey] = true;

    var previewText = getNodePreview(node);
    var isOpen = window._talkOpenNodes.has(rootKey);

    var html = '<div class="talk-node' + (isOpen ? ' open' : '') + '" id="node-' + escAttr(rootKey) + '">';

    html += '<div class="talk-node-header" onclick="if(!event.target.closest(\'[data-action]\'))talkToggleNode(\'' + escAttr(rootKey) + '\',this.parentElement)">';
    html += '<span class="talk-node-arrow"></span>';
    html += '<span class="talk-node-key">' + esc(rootKey) + '</span>';
    html += '<span class="talk-node-preview">' + esc((previewText || '').substring(0, 60)) + '</span>';
    html += '<span class="talk-node-spacer"></span>';
    html += '<button class="talk-node-btn talk-node-del" data-action="delete-node" data-nk="' + escAttr(rootKey) + '">Remove</button>';
    html += '</div>';

    html += '<div class="talk-node-body">';
    html += renderNodeBody(rootKey, node, nodes);
    html += '</div>';

    var childKeys = [];
    if (node.goto && nodes[node.goto]) childKeys.push(node.goto);
    if (node.options) {
      node.options.forEach(function(opt) {
        if (opt.goto && nodes[opt.goto] && childKeys.indexOf(opt.goto) < 0) childKeys.push(opt.goto);
      });
    }
    if (childKeys.length > 0) {
      html += '<div class="talk-children">';
      childKeys.forEach(function(k) { html += renderTreeNodes(nodes, k, seen, indent + 1); });
      html += '</div>';
    }

    html += '</div>';
    return html;
  }

  function getNodePreview(node) {
    if (node.messages && node.messages.length) return node.messages[0];
    return '';
  }

  // ---- Node body: condition, messages, options, action via intereditor ----

  window._talkOpenNodes = window._talkOpenNodes || new Set();

  function renderNodeBody(nodeKey, node, nodes) {
    var hasCond = !!(node.condition && typeof node.condition === 'object');
    var hasAct = !!(node.action && typeof node.action === 'object' && !Array.isArray(node.action));
    var hasOpts = node.options && node.options.length > 0;

    var html = '';

    // Node condition (via intereditor)
    if (hasCond) {
      html += '<div class="talk-cond-card cond">';
      html += '<div class="talk-cond-card-header">' +
        'Condition (for this node)' +
        '<button class="talk-section-remove" data-action="remove-node-cond" data-nk="' + escAttr(nodeKey) + '">Remove</button>' +
        '</div>';
      html += '<div class="talk-cond-card-body">';
      html += ie_renderCond(node.condition, '', 0, '', '', {scopeToken: talkCondScope(nodeKey, null), alwaysOuterAddbar: true});
      html += '</div>';
      html += '</div>';
    } else {
      html += '<button class="talk-add-cond-btn" data-action="add-node-cond" data-nk="' + escAttr(nodeKey) + '">+ Add Condition</button>';
    }

    // Node messages (unchanged)
    html += renderMessagesSection(nodeKey, node);

    // Node options
    html += renderOptionsSection(nodeKey, node);

    html += '<div class="talk-cond-card-sep"></div>';

    // Node action (via intereditor)
    if (hasAct) {
      html += '<div class="talk-cond-card act" style="margin-top:4px">';
      html += '<div class="talk-cond-card-header">' +
        'Action (at the start of this node)' +
        '<button class="talk-section-remove" data-action="remove-node-act" data-nk="' + escAttr(nodeKey) + '">Remove</button></div>';
      html += '<div class="talk-cond-card-body">';
      html += talkRenderActionStep(nodeKey, null);
      html += '</div>';
      html += '</div>';
    } else {
      html += '<button class="talk-add-act-btn" style="margin-top:4px" data-action="add-node-act" data-nk="' + escAttr(nodeKey) + '">+ Add Action</button>';
    }

    // Goto fallback
    if (hasCond) {
      html += '<div class="talk-cond-card-sep"></div>';
      html += renderGotoFallback(nodeKey, node, 'If condition fails, go to');
    } else if (!hasOpts) {
      html += renderGotoFallback(nodeKey, node, 'Auto-advance to');
    }

    return html;
  }

  // ---- Goto fallback ----

  function renderGotoFallback(nodeKey, node, label) {
    label = label || 'Auto-advance to';
    return '<div class="talk-goto-fallback">' +
      '<span class="talk-prop-label">' + esc(label) + '</span>' +
      '<input class="talk-input talk-input-sm search-input" data-tp="nodes.' + escAttr(nodeKey) + '.goto" list="talkNodeKeys" value="' + escAttr(node.goto || '') + '" placeholder="Fallback node...">' +
      '</div>';
  }

  // ---- Messages section ----

  function renderMessagesSection(nodeKey, node) {
    var msgs = node.messages || [];
    var html = '<div class="talk-section">';
    html += '<div class="talk-section-header"><span class="talk-prop-label">Messages</span></div>';
    msgs.forEach(function(line, i) {
      html += '<div class="talk-seq-line">' +
        '<span class="talk-opt-arrow">&#10132;</span>' +
        '<input class="talk-input" data-tp="nodes.' + escAttr(nodeKey) + '.messages.' + i + '" value="' + escAttr(line) + '" placeholder="Message line...">' +
        '<button class="talk-seq-del" data-action="delete-message" data-nk="' + escAttr(nodeKey) + '" data-oi="' + i + '">x</button>' +
        '</div>';
    });
    html += '<div class="talk-seq-add-row">' +
      '<span class="talk-opt-arrow">&#10132;</span>' +
      '<input class="talk-input" id="talkMsgAdd_' + escAttr(nodeKey) + '" placeholder="Add message line...">' +
      '<button class="talk-add-btn" data-action="add-message" data-nk="' + escAttr(nodeKey) + '">Add</button>' +
      '</div>';
    html += '</div>';
    return html;
  }

  // ---- Options section ----

  function renderOptionsSection(nodeKey, node) {
    var options = node.options || [];
    var html = '<div class="talk-options">';
    html += '<span class="talk-options-label">Options</span>';

    if (options.length > 0) {
      options.forEach(function(opt, idx) {
        html += '<div class="talk-opt-edit-row">';
        html += '<span class="talk-seq-num">' + (idx + 1) + '</span>';
        html += '<input class="talk-input talk-opt-text" data-tp="nodes.' + escAttr(nodeKey) + '.options.' + idx + '.text" value="' + escAttr(opt.text || '') + '" placeholder="Option text...">';
        html += '<input class="talk-input talk-opt-goto search-input" data-tp="nodes.' + escAttr(nodeKey) + '.options.' + idx + '.goto" list="talkNodeKeys" value="' + escAttr(opt.goto || '') + '" placeholder="Goto...">';

        html += '<div class="talk-opt-edit-actions">';
        if (opt.condition && typeof opt.condition === 'object' && !Array.isArray(opt.condition)) {
          html += '<span class="talk-opt-tag talk-opt-tag-cond">cond</span>';
        } else {
          html += '<button class="talk-add-cond-btn" style="margin:0;margin-bottom:0" data-action="add-opt-cond" data-nk="' + escAttr(nodeKey) + '" data-oi="' + idx + '" title="Add condition">cond</button>';
        }
        if (opt.action) {
          html += '<span class="talk-opt-tag talk-opt-tag-act">act</span>';
        } else {
          html += '<button class="talk-add-act-btn" style="margin:0;margin-bottom:0" data-action="add-opt-act" data-nk="' + escAttr(nodeKey) + '" data-oi="' + idx + '" title="Add action">act</button>';
        }
        html += '</div>';

        html += '<button class="talk-opt-del" data-action="delete-option" data-nk="' + escAttr(nodeKey) + '" data-oi="' + idx + '" title="Delete option">x</button>';
        html += '</div>';

        // Option condition detail
        if (opt.condition && typeof opt.condition === 'object' && !Array.isArray(opt.condition)) {
          html += '<div class="talk-opt-detail" style="display:block;margin-left:18px">';
          html += '<div class="talk-cond-card cond" style="margin-top:2px">';
          html += '<div class="talk-cond-card-header">Condition (for this option to show up)' +
            '<button class="talk-section-remove" data-action="remove-opt-cond" data-nk="' + escAttr(nodeKey) + '" data-oi="' + idx + '">Remove</button></div>';
          html += '<div class="talk-cond-card-body">';
          html += ie_renderCond(opt.condition, '', 0, '', '', {scopeToken: talkCondScope(nodeKey, idx), alwaysOuterAddbar: true});
          html += '</div>';
          html += '</div>';
          html += '</div>';
        }

        // Option action detail
        if (opt.action) {
          html += '<div class="talk-opt-detail" style="display:block;margin-left:18px">';
          html += '<div class="talk-cond-card act" style="margin-top:2px">';
          html += '<div class="talk-cond-card-header">' +
            'Action (when this option is chosen)' +
            '<button class="talk-section-remove" data-action="remove-opt-act" data-nk="' + escAttr(nodeKey) + '" data-oi="' + idx + '">Remove</button></div>';
          html += '<div class="talk-cond-card-body">';
          html += talkRenderActionStep(nodeKey, idx);
          html += '</div>';
          html += '</div>';
          html += '</div>';
        }
      });
    } else {
      html += '<div class="talk-option-empty">none</div>';
    }

    html += '<div class="talk-add-opt-row">' +
      '<span class="talk-seq-num" style="color:#555">' + (options.length + 1) + '</span>' +
      '<input class="talk-input talk-opt-text" id="talkOptText_' + escAttr(nodeKey) + '" placeholder="Option text...">' +
      '<input class="talk-input talk-opt-goto search-input" id="talkOptGoto_' + escAttr(nodeKey) + '" list="talkNodeKeys" placeholder="Goto...">' +
      '<span class="talk-opt-gap"></span>' +
      '<button class="talk-add-btn" data-action="add-option" data-nk="' + escAttr(nodeKey) + '">Add</button>' +
      '</div>';

    html += '</div>';
    return html;
  }

  window.talkToggleNode = function(nodeKey, nodeEl) {
    var open = nodeEl.classList.toggle('open');
    if (open) {
      window._talkOpenNodes.add(nodeKey);
    } else {
      window._talkOpenNodes.delete(nodeKey);
    }
  };

  // ---- Add/Delete Option ----

  function addOption(nodeKey) {
    var textInput = document.getElementById('talkOptText_' + nodeKey);
    var gotoInput = document.getElementById('talkOptGoto_' + nodeKey);
    var text = textInput ? textInput.value.trim() : '';
    var dest = gotoInput ? gotoInput.value.trim() : '';
    var node = talkNodes()[nodeKey];
    if (!node) return;
    if (!node.options) node.options = [];
    node.options.push({ text: text, goto: dest });
    if (textInput) textInput.value = '';
    if (gotoInput) gotoInput.value = '';
    renderTalkTree(window._talkData);
    talkSync();
  }

  function deleteOption(nodeKey, idx) {
    var node = talkNodes()[nodeKey];
    if (!node || !node.options || idx < 0 || idx >= node.options.length) return;
    node.options.splice(idx, 1);
    renderTalkTree(window._talkData);
    talkSync();
  }

  // ---- Add/Delete Sequence Line ----

  function addMessageLine(nodeKey) {
    var input = document.getElementById('talkMsgAdd_' + nodeKey);
    var text = input ? input.value.trim() : '';
    var node = talkNodes()[nodeKey];
    if (!node) return;
    if (!node.messages) node.messages = [];
    node.messages.push(text);
    renderTalkTree(window._talkData);
    talkSync();
  }

  function deleteMessageLine(nodeKey, idx) {
    var node = talkNodes()[nodeKey];
    if (!node || !node.messages) return;
    node.messages.splice(idx, 1);
    if (node.messages.length === 0) delete node.messages;
    renderTalkTree(window._talkData);
    talkSync();
  }

  // ---- Global event listeners ----

  document.addEventListener('input', function(e) {
    var el = e.target;
    if (!el.closest || !el.closest('#talktree')) return;
    if (!el.getAttribute('data-tp')) return;
    talkEvent(e);
  });

  document.addEventListener('change', function(e) {
    var el = e.target;
    if (!el.closest || !el.closest('#talktree')) return;
    talkEvent(e);
  });

  document.addEventListener('click', function(e) {
    var el = e.target;
    if (!el.closest || !el.closest('#talktree')) return;
    talkHandleClick(e);
  });

  document.addEventListener('keydown', function(e) {
    if (e.key !== 'Enter') return;
    var el = e.target;
    if (!el.closest || !el.closest('#talktree')) return;

    if (el.id === 'talkNewNodeKey') {
      e.preventDefault();
      addNode();
      return;
    }

    if (el.id && (el.id.startsWith('talkOptText_') || el.id.startsWith('talkOptGoto_'))) {
      e.preventDefault();
      var nodeKey = el.id.replace('talkOptText_', '').replace('talkOptGoto_', '');
      addOption(nodeKey);
      return;
    }

    if (el.id && el.id.startsWith('talkMsgAdd_')) {
      e.preventDefault();
      var nk = el.id.replace('talkMsgAdd_', '');
      addMessageLine(nk);
      return;
    }
  });

})();