-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
1459 lines (1290 loc) · 54.4 KB
/
app.js
File metadata and controls
1459 lines (1290 loc) · 54.4 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
// === LuminTree-Intel — Novel Creation Studio (Web App) ===
// Fixed 6-category tree for structured novel development
// Storage: localStorage | Voice: Web Speech API (direct, no extension injection)
const treeEl = document.getElementById("tree");
const treeView = document.getElementById("tree-view");
const settingsEl = document.getElementById("settings");
const chatArea = document.getElementById("chat-area");
const chatSnippet = document.getElementById("chat-snippet");
const chatBreadcrumb = document.getElementById("chat-breadcrumb");
const statusEl = document.getElementById("settings-status");
// --- Fixed Category Definitions ---
const CATEGORIES = [
{ id: "core-concept", title: "📖 Core Concept & Story Positioning", icon: "📖", placeholder: "Genre, theme, logline, target audience, core conflict..." },
{ id: "worldview", title: "🌍 Worldview Setting", icon: "🌍", placeholder: "World rules, geography, magic systems, technology, history, factions..." },
{ id: "plot-framework", title: "📐 Plot Framework", icon: "📐", placeholder: "Story arcs, turning points, act structure, subplot threads..." },
{ id: "character-library", title: "👤 Character Profile Library", icon: "👤", placeholder: "Character bios, motivations, relationships, voice notes, OOC boundaries..." },
{ id: "chapter-structure", title: "📑 Chapter Structure", icon: "📑", placeholder: "Governs chapter organization. Each child node links to a chapter in the right panel. Use to plan: how chapters end/begin, non-linear timeline, scene transitions, POV shifts, pacing across chapters..." },
{ id: "writing-materials", title: "🗂 Writing Material Library", icon: "🗂", placeholder: "Reference snippets, inspiration, research notes, style references..." }
];
// --- AI System Prompts per Category (novel creation agent) ---
const CATEGORY_PROMPTS = {
"core-concept": "You are a novel development AI assistant. The user is working on the core concept and story positioning of their novel. Help them refine their genre, theme, logline, target audience, and central conflict. Be specific and actionable. Challenge weak premises. Suggest ways to sharpen the hook.",
"worldview": "You are a worldbuilding AI assistant for novel creation. Help the user develop consistent, immersive world settings — geography, rules, magic/technology systems, history, cultures, factions. Flag internal contradictions. Suggest details that deepen verisimilitude.",
"plot-framework": "You are a plot architecture AI assistant. Help the user design story arcs, turning points, act structures, and subplot threads. Identify pacing issues, missing stakes, or logical gaps. Reference proven narrative structures (3-act, Save the Cat, Kishotenketsu, etc.) when relevant.",
"character-library": "You are a character development AI assistant focused on OOC (out-of-character) prevention. Help the user build deep character profiles — motivations, backstory, speech patterns, relationships, internal contradictions. Flag when proposed actions would break established character logic. Suggest character-consistent alternatives.",
"chapter-structure": "You are a chapter planning AI assistant. Help the user organize chapters, scene breakdowns, POV assignments, and pacing. Ensure each chapter has clear purpose and forward momentum. Flag chapters that lack conflict or character development.",
"writing-materials": "You are a writing research AI assistant. Help the user organize reference materials, inspiration snippets, style notes, and research findings. Suggest how collected materials connect to their story elements. Help categorize and tag materials for easy retrieval."
};
// --- Data ---
let nodes = [];
let activeNodeId = null;
let targetParentId = null;
function genId() { return Date.now().toString(36) + Math.random().toString(36).slice(2, 6); }
function truncate(text, len = 50) {
return text.length > len ? text.slice(0, len) + "…" : text;
}
function formatTime(iso) {
const d = new Date(iso);
const pad = n => String(n).padStart(2, "0");
return `${pad(d.getMonth()+1)}/${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
function findNode(id, list = nodes) {
for (const n of list) {
if (n.id === id) return n;
const found = findNode(id, n.children);
if (found) return found;
}
return null;
}
function getNodeCategory(node) {
if (node.categoryId) return node.categoryId;
let current = node;
while (current.parentId) {
current = findNode(current.parentId);
if (!current) break;
}
return current ? current.categoryId : null;
}
function getAncestors(id) {
const path = [];
let node = findNode(id);
while (node) {
path.unshift(node);
node = node.parentId ? findNode(node.parentId) : null;
}
return path;
}
function ensureCategories() {
for (const cat of CATEGORIES) {
const exists = nodes.find(n => n.categoryId === cat.id && !n.parentId);
if (!exists) {
nodes.push({
id: cat.id, parentId: null, categoryId: cat.id,
title: cat.title, fullText: cat.placeholder,
timestamp: new Date().toISOString(),
children: [], chatHistory: [], isCategory: true
});
}
}
}
function addNode(text, parentId = null) {
const finalParent = parentId || targetParentId || "writing-materials";
const node = {
id: genId(), parentId: finalParent, categoryId: null,
title: truncate(text), fullText: text,
timestamp: new Date().toISOString(),
children: [], chatHistory: []
};
const parent = findNode(finalParent);
if (parent) parent.children.push(node);
// If adding under chapter-structure, also create a linked chapter in right panel
if (getNodeCategory(node) === "chapter-structure" && !node.isCategory) {
node.chapterId = node.id; // link: tree node id = chapter id
const ch = { id: node.id, title: node.title, content: "" };
chapters.push(ch);
saveChapters();
}
saveTree();
renderTree();
renderChapters();
generateTitle(node);
return node;
}
async function generateTitle(node) {
const cfg = getConfig();
if (!cfg.url || !cfg.key) return;
const catId = getNodeCategory(node);
const catContext = catId ? CATEGORIES.find(c => c.id === catId)?.title : "novel writing";
try {
const res = await fetch(cfg.url, {
method: "POST",
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${cfg.key}` },
body: JSON.stringify({
model: cfg.model || "gpt-4o-mini",
messages: [
{ role: "system", content: `Generate a concise one-line title (max 8 words) for this novel writing note in the "${catContext}" category. Return ONLY the title, nothing else.` },
{ role: "user", content: node.fullText }
]
})
});
if (!res.ok) return;
const data = await res.json();
const title = data.choices?.[0]?.message?.content?.trim();
if (title) {
node.title = title.replace(/^["']|["']$/g, "");
// Sync title to linked chapter if exists
if (node.chapterId) {
const ch = chapters.find(c => c.id === node.chapterId);
if (ch) { ch.title = node.title; saveChapters(); }
}
saveTree();
renderTree();
renderChapters();
}
} catch {}
}
function removeNode(id, list = nodes) {
for (let i = 0; i < list.length; i++) {
if (list[i].id === id) {
if (list[i].isCategory) return false;
// Remove linked chapter if exists
if (list[i].chapterId) {
const ci = chapters.findIndex(c => c.id === list[i].chapterId);
if (ci !== -1) { chapters.splice(ci, 1); saveChapters(); }
if (activeChapterId === list[i].chapterId) activeChapterId = null;
}
list.splice(i, 1); saveTree(); renderTree(); renderChapters(); return true;
}
if (removeNode(id, list[i].children)) return true;
}
return false;
}
// Move a node to become a child of a new parent (for drag-and-drop rearranging)
function moveNodeToParent(nodeId, newParentId) {
const node = findNode(nodeId);
const newParent = findNode(newParentId);
if (!node || !newParent || node.isCategory) return;
// Prevent dropping onto self or own descendant
let check = newParent;
while (check) {
if (check.id === nodeId) return;
check = check.parentId ? findNode(check.parentId) : null;
}
// Detach from old parent
const oldParent = findNode(node.parentId);
if (!oldParent) return;
const idx = oldParent.children.indexOf(node);
if (idx === -1) return;
oldParent.children.splice(idx, 1);
// Attach to new parent
node.parentId = newParentId;
newParent.children.push(node);
saveTree();
renderTree();
}
// --- Persistence (localStorage) ---
function saveTree() {
try { localStorage.setItem("lumintree_tree", JSON.stringify(nodes)); } catch {}
}
function loadTree() {
try { nodes = JSON.parse(localStorage.getItem("lumintree_tree")) || []; } catch { nodes = []; }
ensureCategories();
renderTree();
}
// --- Tree rendering ---
function collectNodes(node, out = []) {
out.push(node);
for (const c of node.children) collectNodes(c, out);
return out;
}
function renderTree() {
treeEl.innerHTML = "";
const indicator = document.getElementById("pin-indicator");
if (indicator) indicator.remove();
if (targetParentId) {
const node = findNode(targetParentId);
if (node) {
const bar = document.createElement("div");
bar.id = "pin-indicator";
bar.className = "pin-indicator";
bar.innerHTML = `📌 Next node → child of "<b>${truncate(node.title, 30)}</b>" <button id="unpin-btn">✕ Unpin</button>`;
treeEl.before(bar);
document.getElementById("unpin-btn").addEventListener("click", () => {
targetParentId = null;
renderTree();
});
}
}
for (const cat of CATEGORIES) {
const root = nodes.find(n => n.categoryId === cat.id && !n.parentId);
if (root) treeEl.appendChild(renderNodeEl(root, 0));
}
exportBtn.classList.remove("hidden");
previewBtn.classList.remove("hidden");
jsonExportBtn.classList.remove("hidden");
}
function renderNodeEl(node, depth) {
const wrap = document.createElement("div");
wrap.className = "tree-node";
wrap.style.paddingLeft = (depth * 16) + "px";
const row = document.createElement("div");
row.className = "tree-row"
+ (node.id === targetParentId ? " pinned" : "")
+ (node.isCategory ? " category-root" : "");
// Drag-and-drop for rearranging parent-child relationships
if (!node.isCategory) {
row.draggable = true;
row.addEventListener("dragstart", (e) => {
e.stopPropagation();
e.dataTransfer.setData("text/plain", node.id);
e.dataTransfer.effectAllowed = "move";
row.classList.add("dragging");
});
row.addEventListener("dragend", () => { row.classList.remove("dragging"); });
}
// All nodes (including categories) can be drop targets
row.addEventListener("dragover", (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = "move";
row.classList.add("drag-over");
});
row.addEventListener("dragleave", () => { row.classList.remove("drag-over"); });
row.addEventListener("drop", (e) => {
e.preventDefault();
e.stopPropagation();
row.classList.remove("drag-over");
const draggedId = e.dataTransfer.getData("text/plain");
if (draggedId && draggedId !== node.id) {
moveNodeToParent(draggedId, node.id);
}
});
const toggle = document.createElement("span");
toggle.className = "tree-toggle";
if (node.children.length > 0) {
toggle.textContent = "▼";
toggle.addEventListener("click", (e) => {
e.stopPropagation();
const childContainer = wrap.querySelector(".tree-children");
if (childContainer) {
const collapsed = childContainer.classList.toggle("hidden");
toggle.textContent = collapsed ? "▶" : "▼";
}
});
} else {
toggle.textContent = node.isCategory ? "▶" : "•";
}
const label = document.createElement("span");
label.className = "tree-label";
label.textContent = (node.chapterId ? "🔗 " : "") + node.title;
label.title = node.chapterId ? `Linked to chapter panel — click to edit structure notes` : node.fullText;
label.addEventListener("click", () => openChat(node.id));
const ts = document.createElement("span");
ts.className = "tree-time";
ts.textContent = node.isCategory ? "" : formatTime(node.timestamp);
const jsonDl = document.createElement("button");
jsonDl.className = "tree-export";
jsonDl.textContent = "💾";
jsonDl.title = "Export this branch (JSON)";
jsonDl.addEventListener("click", (e) => { e.stopPropagation(); exportBranchJson(node); });
const pin = document.createElement("button");
pin.className = "tree-pin";
pin.textContent = node.id === targetParentId ? "📌" : "🔗";
pin.title = node.id === targetParentId ? "Unpin" : "Pin as parent for next node";
pin.addEventListener("click", (e) => {
e.stopPropagation();
targetParentId = targetParentId === node.id ? null : node.id;
renderTree();
});
// Add child button
const addChild = document.createElement("button");
addChild.className = "tree-add";
addChild.textContent = "+";
addChild.title = "Add child node";
addChild.addEventListener("click", (e) => {
e.stopPropagation();
const title = prompt("Enter node title:");
if (title && title.trim()) addNode(title.trim(), node.id);
});
const del = document.createElement("button");
del.className = "tree-del";
del.textContent = "✕";
del.title = "Delete node";
if (!node.isCategory) {
del.addEventListener("click", (e) => { e.stopPropagation(); removeNode(node.id); });
} else {
del.style.display = "none";
}
row.appendChild(toggle);
row.appendChild(label);
row.appendChild(ts);
row.appendChild(jsonDl);
row.appendChild(addChild);
row.appendChild(pin);
row.appendChild(del);
// Import JSON button for chapter-structure category
if (node.isCategory && node.categoryId === "chapter-structure") {
const impBtn = document.createElement("button");
impBtn.className = "tree-add";
impBtn.textContent = "📂";
impBtn.title = "Import chapters (JSON, TXT, MD)";
impBtn.addEventListener("click", (e) => {
e.stopPropagation();
const input = document.createElement("input");
input.type = "file"; input.accept = ".json,.txt,.md"; input.style.display = "none";
input.addEventListener("change", () => {
if (input.files[0]) importChaptersJson(input.files[0]);
});
document.body.appendChild(input);
input.click();
input.remove();
});
row.appendChild(impBtn);
}
wrap.appendChild(row);
if (node.children.length > 0) {
const childContainer = document.createElement("div");
childContainer.className = "tree-children";
node.children.forEach(c => childContainer.appendChild(renderNodeEl(c, depth + 1)));
wrap.appendChild(childContainer);
}
return wrap;
}
// --- Editor (note-taking for each node) ---
function openChat(nodeId) {
const node = findNode(nodeId);
if (!node) return;
activeNodeId = nodeId;
activeChapterId = null; // deselect chapter
saveTree();
renderChapters();
const ancestors = getAncestors(nodeId);
chatBreadcrumb.textContent = ancestors.map(n => truncate(n.title, 20)).join(" → ");
chatSnippet.textContent = node.isCategory ? node.fullText : node.title;
// Load node content into editor
const editor = document.getElementById("node-editor");
editor.value = node.fullText || "";
// Show editor in middle panel, reset to editor tab
document.getElementById("middle-empty").classList.add("hidden");
chatArea.classList.remove("hidden");
document.getElementById("preview-area").classList.add("hidden");
switchMiddleTab("editor");
// Load node AI history
loadNodeAiHistory(node);
editor.focus();
}
// Save handled by unified editor-save listener below (supports both tree nodes and chapters)
// --- Settings (localStorage) ---
function getConfig() {
try { return JSON.parse(localStorage.getItem("lumintree_api")) || {}; } catch { return {}; }
}
function saveConfig(cfg) {
localStorage.setItem("lumintree_api", JSON.stringify(cfg));
}
document.getElementById("settings-btn").addEventListener("click", () => settingsEl.classList.toggle("hidden"));
const PRESETS = {
dashscope: { url: "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions", model: "qwen-plus" },
openai: { url: "https://api.openai.com/v1/chat/completions", model: "gpt-4o-mini" }
};
document.getElementById("api-preset").addEventListener("change", (e) => {
const p = PRESETS[e.target.value];
if (p) { document.getElementById("api-url").value = p.url; document.getElementById("api-model").value = p.model; }
});
// Load saved settings into form
const savedCfg = getConfig();
document.getElementById("api-url").value = savedCfg.url || "";
document.getElementById("api-key").value = savedCfg.key || "";
document.getElementById("api-model").value = savedCfg.model || "";
document.getElementById("save-settings").addEventListener("click", () => {
saveConfig({
url: document.getElementById("api-url").value.trim(),
key: document.getElementById("api-key").value.trim(),
model: document.getElementById("api-model").value.trim()
});
statusEl.textContent = "✓ Saved";
setTimeout(() => (statusEl.textContent = ""), 2000);
});
// --- Export (declarations must be before loadTree) ---
const exportBtn = document.getElementById("export-btn");
const previewBtn = document.getElementById("preview-btn");
const jsonExportBtn = document.getElementById("json-export-btn");
// --- Init ---
loadTree();
exportBtn.addEventListener("click", exportMarkdown);
previewBtn.addEventListener("click", () => showPreview(nodes));
document.getElementById("preview-back").addEventListener("click", () => {
document.getElementById("preview-area").classList.add("hidden");
if (activeNodeId) {
chatArea.classList.remove("hidden");
} else {
document.getElementById("middle-empty").classList.remove("hidden");
}
});
jsonExportBtn.addEventListener("click", exportAllJson);
const jsonImportFile = document.getElementById("json-import-file");
document.getElementById("json-import-btn").addEventListener("click", () => jsonImportFile.click());
// Clear All — wipe all tree nodes and chapters for fresh import
document.getElementById("clear-all-btn").addEventListener("click", () => {
if (!confirm("⚠️ Clear ALL data? This will remove all tree nodes, chapters, and AI chat history.\n\nYou can re-import from a JSON file afterward.")) return;
nodes = [];
chapters = [];
activeNodeId = null;
activeChapterId = null;
ensureCategories();
saveTree();
saveChapters();
renderTree();
renderChapters();
// Reset middle panel
document.getElementById("middle-empty").classList.remove("hidden");
chatArea.classList.add("hidden");
document.getElementById("preview-area").classList.add("hidden");
// Reset AI Writer
document.getElementById("ai-messages").innerHTML = "";
document.getElementById("ai-chapter-label").textContent = "No chapter selected";
});
jsonImportFile.addEventListener("change", (e) => {
if (e.target.files[0]) { importJson(e.target.files[0]); e.target.value = ""; }
});
// === Smart Import — AI-powered JSON transformation ===
const smartImportFile = document.getElementById("smart-import-file");
document.getElementById("smart-import-btn").addEventListener("click", () => smartImportFile.click());
smartImportFile.addEventListener("change", (e) => {
if (e.target.files[0]) { smartImport(e.target.files[0]); e.target.value = ""; }
});
async function smartImport(file) {
const cfg = getConfig();
if (!cfg.url || !cfg.key) { alert("Configure your API settings first (⚙️ button)."); return; }
const text = await file.text();
// Step 1: Try direct JSON parse
let rawJson = null;
try { rawJson = JSON.parse(text); } catch {}
// Step 2: Try to extract JSON from text (e.g. markdown code fences)
if (!rawJson) {
const jsonMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/i) || text.match(/(\{[\s\S]*\})/);
if (jsonMatch) {
try { rawJson = JSON.parse(jsonMatch[1].trim()); } catch {}
}
}
// Whatever we have (JSON object or raw text), send to AI for transformation
const userContent = rawJson ? JSON.stringify(rawJson, null, 2) : text;
const catSchema = CATEGORIES.map(c => ` "${c.id}": { title: "${c.title}", children: [ { title: "...", fullText: "..." }, ... ] }`).join(",\n");
const systemPrompt = `You are a data transformation assistant for a novel writing tool. The user will provide input that contains novel/story configuration data. The input may be:
- A well-structured JSON object
- A JSON with different structure or naming than expected
- Plain text, markdown, or any unstructured format describing a novel
Your job: extract ALL relevant content and transform it into the EXACT target JSON format below. Map each piece of content to the correct category by meaning, not by name. If a field doesn't fit any category, put it in "writing-materials".
Target format (output ONLY valid JSON, no markdown, no explanation):
{
"nodes": [
${catSchema}
],
"chapters": [
{ "id": "unique_id", "title": "Chapter Title", "content": "chapter text..." }
]
}
Rules:
- Each node in "nodes" must have: categoryId (matching the id above), isCategory: true, title, fullText (empty string if none), children (array of child nodes)
- Each child node must have: id (generate unique), parentId (the category id), title, fullText (the content), children: [], timestamp (ISO string)
- Map content intelligently: world/setting → "worldview", characters → "character-library", plot/story arcs → "plot-framework", concept/theme/genre → "core-concept", chapter plans → "chapter-structure", style/references/materials → "writing-materials"
- If the input has chapter content, include it in "chapters" array
- Preserve ALL content from the input — do not drop anything
- Output ONLY the JSON object, nothing else`;
const userMsg = userContent;
// Show progress
const btn = document.getElementById("smart-import-btn");
const origText = btn.textContent;
btn.textContent = "⏳ AI processing...";
btn.disabled = true;
try {
const res = await fetch(cfg.url, {
method: "POST",
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${cfg.key}` },
body: JSON.stringify({
model: cfg.model || "gpt-4o-mini",
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userMsg }
],
temperature: 0.1
})
});
if (!res.ok) throw new Error(`API error: ${res.status}`);
const data = await res.json();
let reply = data.choices?.[0]?.message?.content || "";
// Strip markdown code fences if present
reply = reply.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "").trim();
const transformed = JSON.parse(reply);
// Robustly merge transformed data into existing categories
const importNodes = transformed.nodes || (Array.isArray(transformed) ? transformed : []);
for (const imp of importNodes) {
// Find which category this belongs to
const catId = imp.categoryId || imp.id;
const existing = nodes.find(n => n.categoryId === catId && n.isCategory);
if (existing && imp.children && imp.children.length > 0) {
// Ensure each child has required fields
for (const child of imp.children) {
child.id = child.id || genId();
child.parentId = existing.id;
child.children = child.children || [];
child.timestamp = child.timestamp || new Date().toISOString();
child.fullText = child.fullText || "";
// Auto-link chapter-structure children to chapters panel
if (catId === "chapter-structure") {
child.chapterId = child.chapterId || child.id;
if (!chapters.find(c => c.id === child.chapterId)) {
chapters.push({ id: child.chapterId, title: child.title, content: "" });
}
}
}
existing.children.push(...imp.children);
}
}
if (transformed.chapters && Array.isArray(transformed.chapters)) {
for (const ch of transformed.chapters) {
ch.id = ch.id || genId();
ch.content = ch.content || "";
if (!chapters.find(c => c.id === ch.id)) chapters.push(ch);
}
saveChapters();
}
ensureCategories();
saveTree();
renderTree();
renderChapters();
alert("✅ Smart Import complete! Data has been mapped to the correct categories.");
} catch (err) {
alert("Smart Import failed: " + err.message);
} finally {
btn.textContent = origText;
btn.disabled = false;
}
}
mermaid.initialize({ startOnLoad: false, theme: "default" });
async function showPreview(rootNodes) {
const md = buildExportMd(rootNodes);
const previewArea = document.getElementById("preview-area");
const previewContent = document.getElementById("preview-content");
let mermaidCode = "";
const mdWithoutMermaid = md.replace(/```mermaid\n([\s\S]*?)```/g, (_, code) => {
mermaidCode = code;
return "%%MERMAID%%";
});
let html = renderContent(mdWithoutMermaid);
if (mermaidCode) {
try {
const { svg } = await mermaid.render("mermaid-preview", mermaidCode);
html = html.replace("%%MERMAID%%", `<div class="mermaid-chart">${svg}</div>`);
} catch {
html = html.replace("%%MERMAID%%", `<pre>${mermaidCode}</pre>`);
}
}
previewContent.innerHTML = html;
document.getElementById("middle-empty").classList.add("hidden");
chatArea.classList.add("hidden");
previewArea.classList.remove("hidden");
}
function exportMarkdown() {
if (nodes.length === 0) return;
const date = new Date().toISOString().slice(0, 10);
downloadFile(`lumintree-export-${date}.md`, buildExportMd(nodes));
}
function exportBranch(node) {
const date = new Date().toISOString().slice(0, 10);
downloadFile(`lumintree-${node.id}-${date}.md`, buildExportMd([node]));
}
function exportBranchJson(node) {
const date = new Date().toISOString().slice(0, 10);
const blob = new Blob([JSON.stringify([node], null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = `lumintree-${node.id}-${date}.json`; a.click();
URL.revokeObjectURL(url);
}
function exportAllJson() {
const date = new Date().toISOString().slice(0, 10);
const data = { nodes, chapters };
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = `lumintree-export-${date}.json`; a.click();
URL.revokeObjectURL(url);
}
function importJson(file) {
const reader = new FileReader();
reader.onload = () => {
try {
let imported = JSON.parse(reader.result);
// Support new format { nodes, chapters } and legacy array format
let importedNodes, importedChapters;
if (Array.isArray(imported)) {
importedNodes = imported; importedChapters = null;
} else if (imported && Array.isArray(imported.nodes)) {
importedNodes = imported.nodes; importedChapters = imported.chapters || null;
} else { throw new Error("Invalid format"); }
for (const imp of importedNodes) {
if (imp.isCategory && imp.categoryId) {
const existing = nodes.find(n => n.categoryId === imp.categoryId && n.isCategory);
if (existing) {
// Auto-link chapter-structure children to chapters panel
if (imp.categoryId === "chapter-structure") {
for (const child of (imp.children || [])) {
child.chapterId = child.chapterId || child.id;
if (child.chapterId && !chapters.find(c => c.id === child.chapterId)) {
chapters.push({ id: child.chapterId, title: child.title || "Untitled", content: "" });
}
}
}
existing.children.push(...(imp.children || [])); continue;
}
}
nodes.push(imp);
}
if (importedChapters) {
for (const ch of importedChapters) {
if (!chapters.find(c => c.id === ch.id)) chapters.push(ch);
}
}
saveChapters();
ensureCategories();
saveTree();
renderTree();
renderChapters();
} catch (e) {
alert("Import failed: " + e.message);
}
};
reader.readAsText(file);
}
// Import chapters into chapter-structure and chapters panel (any format)
async function importChaptersJson(file) {
const text = await file.text();
// Try to parse as JSON directly
let parsed = null;
try { parsed = JSON.parse(text); } catch {}
// Try to extract JSON from text
if (!parsed) {
const m = text.match(/```(?:json)?\s*([\s\S]*?)```/i) || text.match(/(\[[\s\S]*\])/);
if (m) { try { parsed = JSON.parse(m[1].trim()); } catch {} }
}
let chList;
if (parsed) {
chList = Array.isArray(parsed) ? parsed : (parsed.chapters || []);
} else {
// Send raw text to AI to extract chapters
const cfg = getConfig();
if (!cfg.url || !cfg.key) { alert("Not valid JSON and no API configured for AI extraction."); return; }
const btn = document.querySelector('[title*="Import chapters"]');
if (btn) { btn.textContent = "⏳"; btn.disabled = true; }
try {
const res = await fetch(cfg.url, {
method: "POST",
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${cfg.key}` },
body: JSON.stringify({
model: cfg.model || "gpt-4o-mini",
messages: [
{ role: "system", content: `Extract chapter information from the user's input. Output ONLY a valid JSON array of chapters, no markdown, no explanation. Each chapter: { "title": "...", "content": "...", "notes": "..." }. Preserve ALL content.` },
{ role: "user", content: text }
], temperature: 0.1
})
});
if (!res.ok) throw new Error(`API error: ${res.status}`);
const data = await res.json();
let reply = (data.choices?.[0]?.message?.content || "").replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "").trim();
chList = JSON.parse(reply);
if (!Array.isArray(chList)) chList = chList.chapters || [];
} catch (e) {
alert("Chapter import failed: " + e.message); return;
} finally {
if (btn) { btn.textContent = "📂"; btn.disabled = false; }
}
}
const csRoot = findNode("chapter-structure");
for (const ch of chList) {
const id = ch.id || genId();
const title = ch.title || "Untitled Chapter";
const content = ch.content || "";
if (!chapters.find(c => c.id === id)) {
chapters.push({ id, title, content });
}
if (csRoot && !csRoot.children.find(c => c.chapterId === id)) {
csRoot.children.push({
id, parentId: "chapter-structure", categoryId: null,
title, fullText: ch.notes || ch.structure || "",
timestamp: new Date().toISOString(),
children: [], chatHistory: [], chapterId: id
});
}
}
saveChapters(); saveTree(); renderTree(); renderChapters();
alert(`✅ Imported ${chList.length} chapter(s).`);
}
function buildExportMd(rootNodes) {
const date = new Date().toISOString().slice(0, 10);
let md = `# LuminTree-Intel — Novel Project Export (${date})\n\n`;
md += "```mermaid\nflowchart TD\n";
const allNodes = [];
flattenNodes(rootNodes, allNodes);
allNodes.forEach(n => {
const label = escapeMermaid(n.title);
const time = n.isCategory ? "" : formatTime(n.timestamp);
md += ` ${n.id}["${label}${time ? '<br/><i>' + time + '</i>' : ''}"]\n`;
});
allNodes.forEach(n => {
n.children.forEach(c => { md += ` ${n.id} --> ${c.id}\n`; });
});
md += "```\n\n---\n\n";
md += "## Novel Structure\n\n";
rootNodes.forEach(n => { md += renderNodeMd(n, 2); });
return md;
}
function flattenNodes(list, out) {
list.forEach(n => { out.push(n); flattenNodes(n.children, out); });
}
function renderNodeMd(node, headingLevel) {
const h = "#".repeat(Math.min(headingLevel, 6));
let md = `${h} ${node.title}\n`;
if (!node.isCategory) {
md += `> ${node.fullText.replace(/\n/g, "\n> ")}\n`;
md += `> *${formatTime(node.timestamp)}*\n\n`;
} else {
md += "\n";
}
if (node.chatHistory && node.chatHistory.length > 0) {
node.chatHistory.forEach(m => {
if (m.role === "user") md += `**Q:** ${m.content} *(${formatTime(m.timestamp)})*\n\n`;
else md += `**A:** ${m.content}\n\n`;
});
}
node.children.forEach(c => { md += renderNodeMd(c, headingLevel + 1); });
return md;
}
function escapeMermaid(text) {
return text.replace(/"/g, "'").replace(/[[\](){}]/g, " ").replace(/\n/g, " ");
}
function downloadFile(filename, content) {
const blob = new Blob([content], { type: "text/markdown" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = filename; a.click();
URL.revokeObjectURL(url);
}
// === Chapter Organization Panel ===
// Chapters are linked to tree nodes under "chapter-structure" category.
// - Left tree node (chapter-structure child): planning notes — how chapters connect, transitions, non-linear timeline
// - Right panel chapter: actual chapter content/writing
// Creating/deleting/renaming from either side syncs to the other.
function removeLinkedTreeNode(chapterId) {
const csRoot = findNode("chapter-structure");
if (!csRoot) return;
const idx = csRoot.children.findIndex(n => n.chapterId === chapterId);
if (idx !== -1) { csRoot.children.splice(idx, 1); saveTree(); }
}
let chapters = [];
let activeChapterId = null;
function loadChapters() {
try { chapters = JSON.parse(localStorage.getItem("lumintree_chapters")) || []; } catch { chapters = []; }
renderChapters();
}
function saveChapters() {
try { localStorage.setItem("lumintree_chapters", JSON.stringify(chapters)); } catch {}
}
function renderChapters() {
const list = document.getElementById("chapter-list");
const empty = document.getElementById("chapter-empty");
list.innerHTML = "";
if (chapters.length === 0) { empty.classList.remove("hidden"); return; }
empty.classList.add("hidden");
chapters.forEach((ch, i) => {
const item = document.createElement("div");
item.className = "chapter-item" + (ch.id === activeChapterId ? " active" : "");
const num = document.createElement("span");
num.className = "chapter-number";
num.textContent = `${i + 1}.`;
const title = document.createElement("span");
title.className = "chapter-title";
title.textContent = ch.title;
title.addEventListener("click", () => openChapterInEditor(ch.id));
const edit = document.createElement("button");
edit.className = "chapter-edit";
edit.textContent = "✏️";
edit.title = "Rename";
edit.addEventListener("click", (e) => {
e.stopPropagation();
const newTitle = prompt("Rename chapter:", ch.title);
if (newTitle && newTitle.trim()) {
ch.title = newTitle.trim();
// Sync title to linked tree node
const linked = findNode(ch.id);
if (linked && linked.chapterId === ch.id) { linked.title = ch.title; saveTree(); }
saveChapters(); renderTree(); renderChapters();
}
});
const del = document.createElement("button");
del.className = "chapter-del";
del.textContent = "✕";
del.addEventListener("click", (e) => {
e.stopPropagation();
if (confirm(`Delete "${ch.title}"?`)) {
chapters.splice(i, 1);
if (activeChapterId === ch.id) activeChapterId = null;
// Remove linked tree node
removeLinkedTreeNode(ch.id);
saveChapters(); renderTree(); renderChapters();
}
});
item.appendChild(num);
item.appendChild(title);
item.appendChild(edit);
item.appendChild(del);
list.appendChild(item);
});
}
function openChapterInEditor(chId) {
const ch = chapters.find(c => c.id === chId);
if (!ch) return;
activeChapterId = chId;
activeNodeId = null; // deselect tree node
chatBreadcrumb.textContent = `📚 ${ch.title}`;
chatSnippet.textContent = ch.title;
const editor = document.getElementById("node-editor");
editor.value = ch.content || "";
document.getElementById("middle-empty").classList.add("hidden");
chatArea.classList.remove("hidden");
document.getElementById("preview-area").classList.add("hidden");
switchMiddleTab("editor");
// Load chapter's node AI history
loadNodeAiHistory(ch);
editor.focus();
renderChapters();
}
document.getElementById("add-chapter-btn").addEventListener("click", () => {
const title = prompt("Chapter title:", `Chapter ${chapters.length + 1}`);
if (title && title.trim()) {
const t = title.trim();
const id = genId();
// Create chapter
chapters.push({ id, title: t, content: "" });
saveChapters();
// Create linked tree node under chapter-structure
const csRoot = findNode("chapter-structure");
if (csRoot) {
csRoot.children.push({
id, parentId: "chapter-structure", categoryId: null,
title: t, fullText: "",
timestamp: new Date().toISOString(),
children: [], chatHistory: [], chapterId: id
});
saveTree();
}
renderTree(); renderChapters();
}
});
// Patch editor save to handle both tree nodes and chapters
document.getElementById("editor-save").addEventListener("click", () => {
const editor = document.getElementById("node-editor");
if (activeChapterId) {
const ch = chapters.find(c => c.id === activeChapterId);
if (ch) { ch.content = editor.value; saveChapters(); }
} else if (activeNodeId) {