@handylib/kai-code 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1089 @@
1
+ // src/KaiCode.tsx
2
+ import Editor from "@monaco-editor/react";
3
+ import {
4
+ useCallback,
5
+ useEffect,
6
+ useId,
7
+ useMemo,
8
+ useRef,
9
+ useState
10
+ } from "react";
11
+
12
+ // src/fileSystem.ts
13
+ function createMemoryFileSystem(initialFiles = {}) {
14
+ const files = new Map(
15
+ Object.entries(initialFiles).map(([path, contents]) => [
16
+ normalizePath(path),
17
+ contents
18
+ ])
19
+ );
20
+ const directories = /* @__PURE__ */ new Set();
21
+ const listeners = /* @__PURE__ */ new Set();
22
+ const addParentDirectories = (path) => {
23
+ const parts = path.split("/");
24
+ parts.pop();
25
+ let parent = "";
26
+ for (const part of parts) {
27
+ parent = parent ? `${parent}/${part}` : part;
28
+ if (files.has(parent)) {
29
+ throw new Error(`A file blocks this directory path: ${parent}`);
30
+ }
31
+ directories.add(parent);
32
+ }
33
+ };
34
+ for (const path of files.keys()) addParentDirectories(path);
35
+ const notify = () => {
36
+ listeners.forEach((listener) => listener());
37
+ };
38
+ return {
39
+ async readDirectory(directory = "") {
40
+ const base = normalizePath(directory);
41
+ const prefix = base ? `${base}/` : "";
42
+ const entries = /* @__PURE__ */ new Map();
43
+ for (const path of directories) {
44
+ if (!path.startsWith(prefix) || path === base) continue;
45
+ const remainder = path.slice(prefix.length);
46
+ if (remainder.includes("/")) continue;
47
+ entries.set(path, {
48
+ type: "directory",
49
+ name: remainder,
50
+ path
51
+ });
52
+ }
53
+ for (const path of files.keys()) {
54
+ if (!path.startsWith(prefix)) continue;
55
+ const remainder = path.slice(prefix.length);
56
+ const slash = remainder.indexOf("/");
57
+ if (slash === -1) {
58
+ entries.set(path, {
59
+ type: "file",
60
+ name: remainder,
61
+ path
62
+ });
63
+ } else {
64
+ const name = remainder.slice(0, slash);
65
+ const childPath = `${prefix}${name}`;
66
+ entries.set(childPath, {
67
+ type: "directory",
68
+ name,
69
+ path: childPath
70
+ });
71
+ }
72
+ }
73
+ return [...entries.values()].sort((left, right) => {
74
+ if (left.type !== right.type) return left.type === "directory" ? -1 : 1;
75
+ return left.name.localeCompare(right.name);
76
+ });
77
+ },
78
+ async readFile(path) {
79
+ const normalized = normalizePath(path);
80
+ const contents = files.get(normalized);
81
+ if (contents === void 0) {
82
+ throw new Error(`File not found: ${normalized}`);
83
+ }
84
+ return contents;
85
+ },
86
+ async writeFile(path, contents) {
87
+ const normalized = normalizePath(path);
88
+ if (!normalized) throw new Error("File path must not be empty.");
89
+ if (directories.has(normalized)) {
90
+ throw new Error(`A directory already exists at ${normalized}`);
91
+ }
92
+ addParentDirectories(normalized);
93
+ files.set(normalized, contents);
94
+ notify();
95
+ },
96
+ async createFile(path, contents = "") {
97
+ const normalized = normalizePath(path);
98
+ if (!normalized) throw new Error("File path must not be empty.");
99
+ if (files.has(normalized)) {
100
+ throw new Error(`File already exists: ${normalized}`);
101
+ }
102
+ if (directories.has(normalized)) {
103
+ throw new Error(`A directory already exists at ${normalized}`);
104
+ }
105
+ addParentDirectories(normalized);
106
+ files.set(normalized, contents);
107
+ notify();
108
+ },
109
+ async createDirectory(path) {
110
+ const normalized = normalizePath(path);
111
+ if (!normalized) throw new Error("Directory path must not be empty.");
112
+ if (files.has(normalized) || directories.has(normalized)) {
113
+ throw new Error(`Path already exists: ${normalized}`);
114
+ }
115
+ const parts = normalized.split("/");
116
+ let directory = "";
117
+ for (const part of parts) {
118
+ directory = directory ? `${directory}/${part}` : part;
119
+ if (files.has(directory)) {
120
+ throw new Error(`A file blocks this directory path: ${directory}`);
121
+ }
122
+ directories.add(directory);
123
+ }
124
+ notify();
125
+ },
126
+ async deleteFile(path) {
127
+ const normalized = normalizePath(path);
128
+ if (!files.delete(normalized)) {
129
+ throw new Error(`File not found: ${normalized}`);
130
+ }
131
+ notify();
132
+ },
133
+ async deleteDirectory(path) {
134
+ const normalized = normalizePath(path);
135
+ if (!directories.has(normalized)) {
136
+ throw new Error(`Directory not found: ${normalized}`);
137
+ }
138
+ const prefix = `${normalized}/`;
139
+ for (const file of files.keys()) {
140
+ if (file.startsWith(prefix)) files.delete(file);
141
+ }
142
+ for (const directory of directories) {
143
+ if (directory === normalized || directory.startsWith(prefix)) {
144
+ directories.delete(directory);
145
+ }
146
+ }
147
+ notify();
148
+ },
149
+ async renameFile(oldPath, newPath) {
150
+ const oldNormalized = normalizePath(oldPath);
151
+ const newNormalized = normalizePath(newPath);
152
+ const contents = files.get(oldNormalized);
153
+ if (contents === void 0) {
154
+ throw new Error(`File not found: ${oldNormalized}`);
155
+ }
156
+ if (files.has(newNormalized)) {
157
+ throw new Error(`File already exists: ${newNormalized}`);
158
+ }
159
+ if (!newNormalized || directories.has(newNormalized)) {
160
+ throw new Error(`Invalid file path: ${newNormalized}`);
161
+ }
162
+ files.delete(oldNormalized);
163
+ addParentDirectories(newNormalized);
164
+ files.set(newNormalized, contents);
165
+ notify();
166
+ },
167
+ watch(listener) {
168
+ listeners.add(listener);
169
+ return () => listeners.delete(listener);
170
+ }
171
+ };
172
+ }
173
+ function normalizePath(path) {
174
+ return path.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
175
+ }
176
+
177
+ // src/KaiCode.tsx
178
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
179
+ var DEFAULT_FILES = {
180
+ "src/App.tsx": `export function App() {
181
+ return <h1>Hello from KaiCode</h1>;
182
+ }
183
+ `,
184
+ "README.md": "# Welcome to KaiCode\n\nChoose a file to start editing."
185
+ };
186
+ var languageByExtension = {
187
+ c: "c",
188
+ css: "css",
189
+ go: "go",
190
+ htm: "html",
191
+ html: "html",
192
+ js: "javascript",
193
+ json: "json",
194
+ jsx: "javascript",
195
+ md: "markdown",
196
+ mjs: "javascript",
197
+ py: "python",
198
+ rs: "rust",
199
+ scss: "scss",
200
+ sh: "shell",
201
+ sql: "sql",
202
+ svg: "xml",
203
+ ts: "typescript",
204
+ tsx: "typescript",
205
+ txt: "plaintext",
206
+ xml: "xml",
207
+ yaml: "yaml",
208
+ yml: "yaml"
209
+ };
210
+ function getLanguage(path) {
211
+ const extension = path.split(".").pop()?.toLowerCase() ?? "";
212
+ return languageByExtension[extension] ?? "plaintext";
213
+ }
214
+ function getFileGlyph(path) {
215
+ const extension = path.split(".").pop()?.toLowerCase();
216
+ if (extension === "tsx" || extension === "jsx") return "\u25C7";
217
+ if (extension === "ts" || extension === "js") return "\u25C6";
218
+ if (extension === "json") return "{}";
219
+ if (extension === "md") return "M";
220
+ if (extension === "css" || extension === "scss") return "#";
221
+ return "\xB7";
222
+ }
223
+ function errorMessage(error) {
224
+ return error instanceof Error ? error.message : String(error);
225
+ }
226
+ async function readTree(fileSystem, directory = "") {
227
+ const entries = await fileSystem.readDirectory(directory);
228
+ const nodes = await Promise.all(
229
+ entries.map(async (entry) => {
230
+ if (entry.type === "file") return entry;
231
+ return {
232
+ ...entry,
233
+ children: await readTree(fileSystem, entry.path)
234
+ };
235
+ })
236
+ );
237
+ return nodes.sort((left, right) => {
238
+ if (left.type !== right.type) return left.type === "directory" ? -1 : 1;
239
+ return left.name.localeCompare(right.name);
240
+ });
241
+ }
242
+ function firstFile(nodes) {
243
+ for (const node of nodes) {
244
+ if (node.type === "file") return node.path;
245
+ const nested = firstFile(node.children ?? []);
246
+ if (nested) return nested;
247
+ }
248
+ return void 0;
249
+ }
250
+ function directoryPaths(nodes) {
251
+ return nodes.flatMap(
252
+ (node) => node.type === "directory" ? [node.path, ...directoryPaths(node.children ?? [])] : []
253
+ );
254
+ }
255
+ function filesInDirectory(nodes, directoryPath) {
256
+ const directory = findDirectory(nodes, directoryPath);
257
+ return directory ? filePaths(directory.children ?? []) : [];
258
+ }
259
+ function findDirectory(nodes, path) {
260
+ for (const node of nodes) {
261
+ if (node.type !== "directory") continue;
262
+ if (node.path === path) return node;
263
+ const nested = findDirectory(node.children ?? [], path);
264
+ if (nested) return nested;
265
+ }
266
+ return void 0;
267
+ }
268
+ function filePaths(nodes) {
269
+ return nodes.flatMap(
270
+ (node) => node.type === "file" ? [node.path] : filePaths(node.children ?? [])
271
+ );
272
+ }
273
+ function parentDirectory(path) {
274
+ const separator = path.lastIndexOf("/");
275
+ return separator === -1 ? "" : path.slice(0, separator);
276
+ }
277
+ function FileTree({
278
+ nodes,
279
+ activeFile,
280
+ onOpen,
281
+ collapsedFolders,
282
+ onToggleDirectory,
283
+ onContextMenu,
284
+ depth = 0
285
+ }) {
286
+ return /* @__PURE__ */ jsx(Fragment, { children: nodes.map(
287
+ (node) => node.type === "directory" ? /* @__PURE__ */ jsxs(
288
+ "details",
289
+ {
290
+ className: "kai-code__directory",
291
+ open: !collapsedFolders.has(node.path),
292
+ onToggle: (event) => onToggleDirectory(node.path, event.currentTarget.open),
293
+ children: [
294
+ /* @__PURE__ */ jsxs(
295
+ "summary",
296
+ {
297
+ onContextMenu: (event) => onContextMenu(node, event),
298
+ style: { "--tree-depth": depth },
299
+ children: [
300
+ /* @__PURE__ */ jsx("span", { className: "kai-code__chevron", "aria-hidden": "true", children: "\u25B8" }),
301
+ /* @__PURE__ */ jsx("span", { className: "kai-code__folder-icon", "aria-hidden": "true", children: "\u25B0" }),
302
+ node.name
303
+ ]
304
+ }
305
+ ),
306
+ /* @__PURE__ */ jsx(
307
+ FileTree,
308
+ {
309
+ nodes: node.children ?? [],
310
+ activeFile,
311
+ onOpen,
312
+ collapsedFolders,
313
+ onToggleDirectory,
314
+ onContextMenu,
315
+ depth: depth + 1
316
+ }
317
+ )
318
+ ]
319
+ },
320
+ node.path
321
+ ) : /* @__PURE__ */ jsxs(
322
+ "button",
323
+ {
324
+ className: `kai-code__file${activeFile === node.path ? " is-active" : ""}`,
325
+ onClick: () => onOpen(node.path),
326
+ onContextMenu: (event) => onContextMenu(node, event),
327
+ style: { "--tree-depth": depth },
328
+ type: "button",
329
+ children: [
330
+ /* @__PURE__ */ jsx("span", { className: "kai-code__file-icon", "aria-hidden": "true", children: getFileGlyph(node.path) }),
331
+ node.name
332
+ ]
333
+ },
334
+ node.path
335
+ )
336
+ ) });
337
+ }
338
+ function KaiCode({
339
+ fileSystem,
340
+ initialFiles,
341
+ initialActiveFile,
342
+ theme = "vs-dark",
343
+ options,
344
+ height = 640,
345
+ readOnly = false,
346
+ className,
347
+ onFileChange,
348
+ onSave
349
+ }) {
350
+ const [memoryFileSystem] = useState(
351
+ () => createMemoryFileSystem(initialFiles ?? DEFAULT_FILES)
352
+ );
353
+ const fs = fileSystem ?? memoryFileSystem;
354
+ const [tree, setTree] = useState([]);
355
+ const [activeFile, setActiveFile] = useState(null);
356
+ const [openFiles, setOpenFiles] = useState([]);
357
+ const [documents, setDocuments] = useState({});
358
+ const [dirtyFiles, setDirtyFiles] = useState(() => /* @__PURE__ */ new Set());
359
+ const [explorerVisible, setExplorerVisible] = useState(true);
360
+ const [sidebarWidth, setSidebarWidth] = useState(230);
361
+ const [collapsedFolders, setCollapsedFolders] = useState(
362
+ () => /* @__PURE__ */ new Set()
363
+ );
364
+ const [contextMenu, setContextMenu] = useState(null);
365
+ const [creationRequest, setCreationRequest] = useState(null);
366
+ const [creationName, setCreationName] = useState("");
367
+ const [deleteTarget, setDeleteTarget] = useState(null);
368
+ const [loadingTree, setLoadingTree] = useState(true);
369
+ const [loadingDocument, setLoadingDocument] = useState(false);
370
+ const [failedDocument, setFailedDocument] = useState(null);
371
+ const [documentRequest, setDocumentRequest] = useState(0);
372
+ const [error, setError] = useState(null);
373
+ const saveRef = useRef(async () => void 0);
374
+ const activeFileRef = useRef(null);
375
+ const resizeStartRef = useRef(null);
376
+ const createInputId = useId();
377
+ const createTitleId = useId();
378
+ const deleteTitleId = useId();
379
+ const isLight = theme === "light";
380
+ const reloadFiles = useCallback(async () => {
381
+ setLoadingTree(true);
382
+ try {
383
+ const nextTree = await readTree(fs);
384
+ setTree(nextTree);
385
+ setError(null);
386
+ const requested = initialActiveFile ? initialActiveFile : void 0;
387
+ const current = activeFileRef.current;
388
+ const selected = current && findFile(nextTree, current) ? current : requested && findFile(nextTree, requested) ? requested : firstFile(nextTree) ?? null;
389
+ activeFileRef.current = selected;
390
+ setActiveFile(selected);
391
+ if (selected) {
392
+ setOpenFiles(
393
+ (files) => files.includes(selected) ? files : [...files, selected]
394
+ );
395
+ }
396
+ } catch (loadError) {
397
+ setError(`Unable to load files: ${errorMessage(loadError)}`);
398
+ } finally {
399
+ setLoadingTree(false);
400
+ }
401
+ }, [fs, initialActiveFile]);
402
+ useEffect(() => {
403
+ void reloadFiles();
404
+ return fs.watch?.(() => {
405
+ void reloadFiles();
406
+ });
407
+ }, [fs, reloadFiles]);
408
+ useEffect(() => {
409
+ if (!activeFile || documents[activeFile] !== void 0) return;
410
+ let cancelled = false;
411
+ setLoadingDocument(true);
412
+ setFailedDocument(null);
413
+ fs.readFile(activeFile).then((contents) => {
414
+ if (!cancelled) {
415
+ setDocuments((current) => ({ ...current, [activeFile]: contents }));
416
+ setFailedDocument(null);
417
+ setError(null);
418
+ }
419
+ }).catch((readError) => {
420
+ if (!cancelled) {
421
+ setFailedDocument(activeFile);
422
+ setError(`Unable to open ${activeFile}: ${errorMessage(readError)}`);
423
+ }
424
+ }).finally(() => {
425
+ if (!cancelled) setLoadingDocument(false);
426
+ });
427
+ return () => {
428
+ cancelled = true;
429
+ };
430
+ }, [activeFile, documentRequest, documents, fs]);
431
+ const collapseAll = useCallback(() => {
432
+ setCollapsedFolders(new Set(directoryPaths(tree)));
433
+ }, [tree]);
434
+ useEffect(() => {
435
+ let chordTimer;
436
+ let awaitingCollapseChord = false;
437
+ const handleKeyDown = (event) => {
438
+ if (event.key === "Escape") {
439
+ setContextMenu(null);
440
+ setCreationRequest(null);
441
+ setDeleteTarget(null);
442
+ }
443
+ const modifierPressed = event.ctrlKey || event.metaKey;
444
+ if (awaitingCollapseChord) {
445
+ if (["Control", "Meta", "Shift", "Alt"].includes(event.key)) return;
446
+ awaitingCollapseChord = false;
447
+ if (chordTimer) clearTimeout(chordTimer);
448
+ if (modifierPressed && (event.key === "0" || event.code === "Digit0" || event.code === "Numpad0")) {
449
+ event.preventDefault();
450
+ event.stopPropagation();
451
+ collapseAll();
452
+ return;
453
+ }
454
+ }
455
+ if (!modifierPressed || event.shiftKey) return;
456
+ if (event.key.toLowerCase() === "b") {
457
+ event.preventDefault();
458
+ event.stopPropagation();
459
+ setExplorerVisible((visible) => !visible);
460
+ } else if (event.key.toLowerCase() === "k") {
461
+ event.preventDefault();
462
+ event.stopPropagation();
463
+ awaitingCollapseChord = true;
464
+ chordTimer = setTimeout(() => {
465
+ awaitingCollapseChord = false;
466
+ }, 1200);
467
+ }
468
+ };
469
+ window.addEventListener("keydown", handleKeyDown, true);
470
+ return () => {
471
+ window.removeEventListener("keydown", handleKeyDown, true);
472
+ if (chordTimer) clearTimeout(chordTimer);
473
+ };
474
+ }, [collapseAll]);
475
+ const saveFile = useCallback(async () => {
476
+ if (!activeFile || documents[activeFile] === void 0 || readOnly) return;
477
+ const contents = documents[activeFile];
478
+ try {
479
+ await fs.writeFile(activeFile, contents);
480
+ } catch (saveError) {
481
+ setError(`Unable to save ${activeFile}: ${errorMessage(saveError)}`);
482
+ return;
483
+ }
484
+ setDirtyFiles((current) => {
485
+ const next = new Set(current);
486
+ next.delete(activeFile);
487
+ return next;
488
+ });
489
+ setError(null);
490
+ onSave?.(activeFile, contents);
491
+ }, [activeFile, documents, fs, onSave, readOnly]);
492
+ saveRef.current = saveFile;
493
+ const openFile = useCallback((path) => {
494
+ activeFileRef.current = path;
495
+ setActiveFile(path);
496
+ setOpenFiles(
497
+ (current) => current.includes(path) ? current : [...current, path]
498
+ );
499
+ }, []);
500
+ const closeFile = useCallback(
501
+ (path) => {
502
+ if (dirtyFiles.has(path)) {
503
+ setError(`Save changes before closing ${path}.`);
504
+ return;
505
+ }
506
+ const currentIndex = openFiles.indexOf(path);
507
+ const next = openFiles.filter((file) => file !== path);
508
+ setOpenFiles(next);
509
+ if (activeFile === path) {
510
+ const nextActive = next[Math.max(0, currentIndex - 1)] ?? null;
511
+ activeFileRef.current = nextActive;
512
+ setActiveFile(nextActive);
513
+ }
514
+ },
515
+ [activeFile, dirtyFiles, openFiles]
516
+ );
517
+ const changeDocument = useCallback(
518
+ (contents) => {
519
+ if (!activeFile || contents === void 0) return;
520
+ setDocuments((current) => ({ ...current, [activeFile]: contents }));
521
+ setDirtyFiles((current) => new Set(current).add(activeFile));
522
+ onFileChange?.(activeFile, contents);
523
+ },
524
+ [activeFile, onFileChange]
525
+ );
526
+ const beginCreate = useCallback(
527
+ (kind, parentPath) => {
528
+ if (readOnly) return;
529
+ setContextMenu(null);
530
+ setError(null);
531
+ setCreationName("");
532
+ setCreationRequest({ kind, parentPath });
533
+ },
534
+ [readOnly]
535
+ );
536
+ const openContextMenu = useCallback(
537
+ (entry, event) => {
538
+ event.preventDefault();
539
+ event.stopPropagation();
540
+ const canDelete = entry.type === "file" ? fs.deleteFile : fs.deleteDirectory;
541
+ if (readOnly || !fs.createFile && !fs.createDirectory && !canDelete) {
542
+ return;
543
+ }
544
+ setContextMenu({
545
+ entry,
546
+ x: Math.max(4, Math.min(event.clientX, window.innerWidth - 220)),
547
+ y: Math.max(4, Math.min(event.clientY, window.innerHeight - 170))
548
+ });
549
+ },
550
+ [fs, readOnly]
551
+ );
552
+ const toggleDirectory = useCallback((path, expanded) => {
553
+ setCollapsedFolders((current) => {
554
+ const next = new Set(current);
555
+ if (expanded) next.delete(path);
556
+ else next.add(path);
557
+ return next;
558
+ });
559
+ }, []);
560
+ const submitCreation = useCallback(
561
+ async (event) => {
562
+ event.preventDefault();
563
+ if (!creationRequest) return;
564
+ const name = creationName.trim();
565
+ if (!name || name === "." || name === ".." || /[/\\]/.test(name)) {
566
+ setError("Enter a name without path separators.");
567
+ return;
568
+ }
569
+ const path = normalizePath(
570
+ creationRequest.parentPath ? `${creationRequest.parentPath}/${name}` : name
571
+ );
572
+ try {
573
+ if (creationRequest.kind === "file") {
574
+ if (!fs.createFile) {
575
+ throw new Error("File creation is not supported.");
576
+ }
577
+ await fs.createFile(path, "");
578
+ setDocuments((current) => ({ ...current, [path]: "" }));
579
+ } else {
580
+ if (!fs.createDirectory) {
581
+ throw new Error("Folder creation is not supported.");
582
+ }
583
+ await fs.createDirectory(path);
584
+ }
585
+ setCreationRequest(null);
586
+ setError(null);
587
+ await reloadFiles();
588
+ if (creationRequest.kind === "file") openFile(path);
589
+ } catch (createError) {
590
+ setError(`Unable to create ${path}: ${errorMessage(createError)}`);
591
+ }
592
+ },
593
+ [creationName, creationRequest, fs, openFile, reloadFiles]
594
+ );
595
+ const confirmDelete = useCallback(async () => {
596
+ if (!deleteTarget) return;
597
+ const target = deleteTarget;
598
+ try {
599
+ if (target.type === "file") {
600
+ if (!fs.deleteFile) {
601
+ throw new Error("File deletion is not supported.");
602
+ }
603
+ await fs.deleteFile(target.path);
604
+ } else {
605
+ if (!fs.deleteDirectory) {
606
+ throw new Error("Folder deletion is not supported.");
607
+ }
608
+ await fs.deleteDirectory(target.path);
609
+ }
610
+ const affectedFiles = target.type === "file" ? [target.path] : [
611
+ .../* @__PURE__ */ new Set([
612
+ ...filesInDirectory(tree, target.path),
613
+ ...Object.keys(documents).filter(
614
+ (path) => path.startsWith(`${target.path}/`)
615
+ )
616
+ ])
617
+ ];
618
+ const affected = new Set(affectedFiles);
619
+ setOpenFiles((current) => current.filter((path) => !affected.has(path)));
620
+ setDirtyFiles((current) => {
621
+ const next = new Set(current);
622
+ affected.forEach((path) => next.delete(path));
623
+ return next;
624
+ });
625
+ setDocuments((current) => {
626
+ const next = { ...current };
627
+ affected.forEach((path) => delete next[path]);
628
+ return next;
629
+ });
630
+ if (activeFileRef.current && affected.has(activeFileRef.current)) {
631
+ activeFileRef.current = null;
632
+ setActiveFile(null);
633
+ }
634
+ setDeleteTarget(null);
635
+ setContextMenu(null);
636
+ setError(null);
637
+ await reloadFiles();
638
+ } catch (deleteError) {
639
+ setError(`Unable to delete ${target.path}: ${errorMessage(deleteError)}`);
640
+ }
641
+ }, [deleteTarget, documents, fs, reloadFiles, tree]);
642
+ const editorOptions = useMemo(
643
+ () => ({
644
+ automaticLayout: true,
645
+ fontSize: 13,
646
+ fontFamily: 'Consolas, "Courier New", monospace',
647
+ minimap: { enabled: true },
648
+ padding: { top: 12 },
649
+ scrollBeyondLastLine: false,
650
+ smoothScrolling: true,
651
+ tabSize: 2,
652
+ ...options,
653
+ readOnly
654
+ }),
655
+ [options, readOnly]
656
+ );
657
+ const activeLanguage = activeFile ? findFileEntry(tree, activeFile)?.language ?? getLanguage(activeFile) : null;
658
+ return /* @__PURE__ */ jsxs(
659
+ "section",
660
+ {
661
+ className: `kai-code${isLight ? " kai-code--light" : ""}${className ? ` ${className}` : ""}`,
662
+ style: { height },
663
+ "aria-label": "KaiCode editor",
664
+ children: [
665
+ /* @__PURE__ */ jsxs("header", { className: "kai-code__titlebar", children: [
666
+ /* @__PURE__ */ jsx("div", { className: "kai-code__brand-mark", "aria-hidden": "true", children: "K" }),
667
+ /* @__PURE__ */ jsx("span", { className: "kai-code__brand", children: "KaiCode" }),
668
+ /* @__PURE__ */ jsx("span", { className: "kai-code__title-divider" }),
669
+ /* @__PURE__ */ jsx("span", { className: "kai-code__workspace-title", children: "Workspace" }),
670
+ /* @__PURE__ */ jsx("div", { className: "kai-code__title-actions", children: /* @__PURE__ */ jsx(
671
+ "button",
672
+ {
673
+ className: "kai-code__title-button",
674
+ disabled: !activeFile || !dirtyFiles.has(activeFile) || readOnly,
675
+ onClick: () => void saveFile(),
676
+ type: "button",
677
+ children: "Save"
678
+ }
679
+ ) })
680
+ ] }),
681
+ /* @__PURE__ */ jsxs(
682
+ "div",
683
+ {
684
+ className: "kai-code__workbench",
685
+ onClick: () => setContextMenu(null),
686
+ children: [
687
+ /* @__PURE__ */ jsxs("nav", { className: "kai-code__activity-bar", "aria-label": "Workbench", children: [
688
+ /* @__PURE__ */ jsx(
689
+ "button",
690
+ {
691
+ className: `kai-code__activity-button${explorerVisible ? " is-active" : ""}`,
692
+ "aria-label": "Toggle Explorer",
693
+ "aria-expanded": explorerVisible,
694
+ title: "Explorer (Ctrl+B)",
695
+ onClick: () => setExplorerVisible((visible) => !visible),
696
+ type: "button",
697
+ children: /* @__PURE__ */ jsxs("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", children: [
698
+ /* @__PURE__ */ jsx("path", { d: "M3.5 5.5h6l2 2h9v11h-17z" }),
699
+ /* @__PURE__ */ jsx("path", { d: "M3.5 8h17" })
700
+ ] })
701
+ }
702
+ ),
703
+ /* @__PURE__ */ jsx("div", { className: "kai-code__activity-spacer" }),
704
+ /* @__PURE__ */ jsx("span", { className: "kai-code__activity-avatar", "aria-hidden": "true", children: "K" })
705
+ ] }),
706
+ explorerVisible && /* @__PURE__ */ jsxs(Fragment, { children: [
707
+ /* @__PURE__ */ jsxs(
708
+ "aside",
709
+ {
710
+ className: "kai-code__sidebar",
711
+ style: { flexBasis: sidebarWidth },
712
+ children: [
713
+ /* @__PURE__ */ jsxs("div", { className: "kai-code__sidebar-heading", children: [
714
+ /* @__PURE__ */ jsx("span", { children: "EXPLORER" }),
715
+ /* @__PURE__ */ jsxs("div", { className: "kai-code__sidebar-actions", children: [
716
+ fs.createFile && !readOnly && /* @__PURE__ */ jsx(
717
+ "button",
718
+ {
719
+ className: "kai-code__icon-button",
720
+ "aria-label": "New File",
721
+ title: "New File",
722
+ onClick: () => beginCreate("file", ""),
723
+ type: "button",
724
+ children: "+"
725
+ }
726
+ ),
727
+ fs.createDirectory && !readOnly && /* @__PURE__ */ jsx(
728
+ "button",
729
+ {
730
+ className: "kai-code__icon-button",
731
+ "aria-label": "New Folder",
732
+ title: "New Folder",
733
+ onClick: () => beginCreate("directory", ""),
734
+ type: "button",
735
+ children: "\u25B0+"
736
+ }
737
+ ),
738
+ /* @__PURE__ */ jsx(
739
+ "button",
740
+ {
741
+ className: "kai-code__icon-button",
742
+ "aria-label": "Collapse All",
743
+ title: "Collapse All (Ctrl+K Ctrl+0)",
744
+ onClick: collapseAll,
745
+ type: "button",
746
+ children: "\u229F"
747
+ }
748
+ )
749
+ ] })
750
+ ] }),
751
+ /* @__PURE__ */ jsxs("div", { className: "kai-code__workspace-row", children: [
752
+ /* @__PURE__ */ jsx("span", { className: "kai-code__chevron", "aria-hidden": "true", children: "\u25BE" }),
753
+ /* @__PURE__ */ jsx("span", { children: "WORKSPACE" })
754
+ ] }),
755
+ /* @__PURE__ */ jsx("div", { className: "kai-code__file-tree", children: loadingTree && tree.length === 0 ? /* @__PURE__ */ jsx("div", { className: "kai-code__empty", children: "Loading files\u2026" }) : tree.length ? /* @__PURE__ */ jsx(
756
+ FileTree,
757
+ {
758
+ nodes: tree,
759
+ activeFile,
760
+ onOpen: openFile,
761
+ collapsedFolders,
762
+ onToggleDirectory: toggleDirectory,
763
+ onContextMenu: openContextMenu
764
+ }
765
+ ) : /* @__PURE__ */ jsx("div", { className: "kai-code__empty", children: "No files in this workspace" }) })
766
+ ]
767
+ }
768
+ ),
769
+ /* @__PURE__ */ jsx(
770
+ "div",
771
+ {
772
+ className: "kai-code__resizer",
773
+ role: "separator",
774
+ "aria-orientation": "vertical",
775
+ "aria-label": "Resize Explorer",
776
+ "aria-valuenow": sidebarWidth,
777
+ "aria-valuemin": 160,
778
+ "aria-valuemax": 480,
779
+ tabIndex: 0,
780
+ onPointerDown: (event) => {
781
+ event.preventDefault();
782
+ resizeStartRef.current = {
783
+ x: event.clientX,
784
+ width: sidebarWidth
785
+ };
786
+ event.currentTarget.setPointerCapture(event.pointerId);
787
+ },
788
+ onPointerMove: (event) => {
789
+ const start = resizeStartRef.current;
790
+ if (!start) return;
791
+ setSidebarWidth(
792
+ Math.max(
793
+ 160,
794
+ Math.min(
795
+ 480,
796
+ Math.round(start.width + event.clientX - start.x)
797
+ )
798
+ )
799
+ );
800
+ },
801
+ onPointerUp: () => {
802
+ resizeStartRef.current = null;
803
+ },
804
+ onKeyDown: (event) => {
805
+ const direction = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
806
+ if (!direction) return;
807
+ event.preventDefault();
808
+ setSidebarWidth(
809
+ (width) => Math.max(160, Math.min(480, width + direction * 12))
810
+ );
811
+ }
812
+ }
813
+ )
814
+ ] }),
815
+ contextMenu && /* @__PURE__ */ jsxs(
816
+ "div",
817
+ {
818
+ className: "kai-code__context-menu",
819
+ role: "menu",
820
+ "aria-label": "File actions",
821
+ style: { left: contextMenu.x, top: contextMenu.y },
822
+ onClick: (event) => event.stopPropagation(),
823
+ onContextMenu: (event) => event.preventDefault(),
824
+ children: [
825
+ fs.createFile && !readOnly && /* @__PURE__ */ jsx(
826
+ "button",
827
+ {
828
+ role: "menuitem",
829
+ onClick: () => beginCreate(
830
+ "file",
831
+ contextMenu.entry.type === "directory" ? contextMenu.entry.path : parentDirectory(contextMenu.entry.path)
832
+ ),
833
+ type: "button",
834
+ children: "New File"
835
+ }
836
+ ),
837
+ fs.createDirectory && !readOnly && /* @__PURE__ */ jsx(
838
+ "button",
839
+ {
840
+ role: "menuitem",
841
+ onClick: () => beginCreate(
842
+ "directory",
843
+ contextMenu.entry.type === "directory" ? contextMenu.entry.path : parentDirectory(contextMenu.entry.path)
844
+ ),
845
+ type: "button",
846
+ children: "New Folder"
847
+ }
848
+ ),
849
+ (contextMenu.entry.type === "file" && fs.deleteFile || contextMenu.entry.type === "directory" && fs.deleteDirectory) && !readOnly && /* @__PURE__ */ jsxs(Fragment, { children: [
850
+ /* @__PURE__ */ jsx("div", { className: "kai-code__context-divider" }),
851
+ /* @__PURE__ */ jsx(
852
+ "button",
853
+ {
854
+ className: "is-danger",
855
+ role: "menuitem",
856
+ onClick: () => {
857
+ setError(null);
858
+ setDeleteTarget(contextMenu.entry);
859
+ setContextMenu(null);
860
+ },
861
+ type: "button",
862
+ children: "Delete"
863
+ }
864
+ )
865
+ ] })
866
+ ]
867
+ }
868
+ ),
869
+ /* @__PURE__ */ jsxs("main", { className: "kai-code__editor-area", children: [
870
+ /* @__PURE__ */ jsx("div", { className: "kai-code__tabs", role: "tablist", "aria-label": "Open files", children: openFiles.map((path) => {
871
+ const fileName = path.split("/").pop() ?? path;
872
+ return /* @__PURE__ */ jsxs(
873
+ "div",
874
+ {
875
+ className: `kai-code__tab${activeFile === path ? " is-active" : ""}`,
876
+ role: "presentation",
877
+ children: [
878
+ /* @__PURE__ */ jsxs(
879
+ "button",
880
+ {
881
+ className: "kai-code__tab-label",
882
+ onClick: () => openFile(path),
883
+ role: "tab",
884
+ "aria-selected": activeFile === path,
885
+ type: "button",
886
+ children: [
887
+ /* @__PURE__ */ jsx("span", { className: "kai-code__file-icon", "aria-hidden": "true", children: getFileGlyph(path) }),
888
+ fileName,
889
+ dirtyFiles.has(path) && /* @__PURE__ */ jsx("span", { className: "kai-code__dirty-dot", "aria-label": "Unsaved" })
890
+ ]
891
+ }
892
+ ),
893
+ /* @__PURE__ */ jsx(
894
+ "button",
895
+ {
896
+ className: "kai-code__tab-close",
897
+ "aria-label": `Close ${fileName}`,
898
+ onClick: () => closeFile(path),
899
+ type: "button",
900
+ children: "\xD7"
901
+ }
902
+ )
903
+ ]
904
+ },
905
+ path
906
+ );
907
+ }) }),
908
+ activeFile && /* @__PURE__ */ jsx("div", { className: "kai-code__breadcrumbs", children: activeFile.split("/").map((part, index, parts) => /* @__PURE__ */ jsxs("span", { children: [
909
+ index > 0 && /* @__PURE__ */ jsx("span", { className: "kai-code__breadcrumb-separator", children: "\u203A" }),
910
+ part,
911
+ index < parts.length - 1 && " "
912
+ ] }, `${part}-${index}`)) }),
913
+ error && /* @__PURE__ */ jsxs("div", { className: "kai-code__error", role: "alert", children: [
914
+ /* @__PURE__ */ jsx("span", { children: error }),
915
+ /* @__PURE__ */ jsx(
916
+ "button",
917
+ {
918
+ "aria-label": "Dismiss error",
919
+ onClick: () => setError(null),
920
+ type: "button",
921
+ children: "\xD7"
922
+ }
923
+ )
924
+ ] }),
925
+ /* @__PURE__ */ jsx("div", { className: "kai-code__monaco", children: activeFile ? loadingDocument && documents[activeFile] === void 0 ? /* @__PURE__ */ jsxs("div", { className: "kai-code__empty", children: [
926
+ "Opening ",
927
+ activeFile,
928
+ "\u2026"
929
+ ] }) : failedDocument === activeFile ? /* @__PURE__ */ jsxs("div", { className: "kai-code__empty", role: "alert", children: [
930
+ "Could not load this file.",
931
+ " ",
932
+ /* @__PURE__ */ jsx(
933
+ "button",
934
+ {
935
+ className: "kai-code__retry",
936
+ onClick: () => setDocumentRequest((request) => request + 1),
937
+ type: "button",
938
+ children: "Retry"
939
+ }
940
+ )
941
+ ] }) : /* @__PURE__ */ jsx(
942
+ Editor,
943
+ {
944
+ height: "100%",
945
+ language: activeLanguage ?? void 0,
946
+ path: activeFile,
947
+ value: documents[activeFile] ?? "",
948
+ theme,
949
+ options: editorOptions,
950
+ onChange: changeDocument,
951
+ onMount: (instance, monaco) => {
952
+ instance.addCommand(
953
+ monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS,
954
+ () => void saveRef.current()
955
+ );
956
+ }
957
+ },
958
+ activeFile
959
+ ) : /* @__PURE__ */ jsxs("div", { className: "kai-code__welcome", children: [
960
+ /* @__PURE__ */ jsx("div", { className: "kai-code__welcome-mark", children: "K" }),
961
+ /* @__PURE__ */ jsx("h1", { children: "KaiCode" }),
962
+ /* @__PURE__ */ jsx("p", { children: "Select a file from the Explorer to start editing." })
963
+ ] }) })
964
+ ] })
965
+ ]
966
+ }
967
+ ),
968
+ creationRequest && /* @__PURE__ */ jsx(
969
+ "div",
970
+ {
971
+ className: "kai-code__dialog-backdrop",
972
+ onMouseDown: (event) => {
973
+ if (event.target === event.currentTarget) setCreationRequest(null);
974
+ },
975
+ children: /* @__PURE__ */ jsxs(
976
+ "form",
977
+ {
978
+ className: "kai-code__dialog",
979
+ role: "dialog",
980
+ "aria-modal": "true",
981
+ "aria-labelledby": createTitleId,
982
+ onSubmit: (event) => void submitCreation(event),
983
+ children: [
984
+ /* @__PURE__ */ jsxs("h2", { id: createTitleId, children: [
985
+ "New ",
986
+ creationRequest.kind === "file" ? "File" : "Folder"
987
+ ] }),
988
+ /* @__PURE__ */ jsx("p", { children: creationRequest.parentPath || "Workspace root" }),
989
+ /* @__PURE__ */ jsx("label", { htmlFor: createInputId, children: creationRequest.kind === "file" ? "File name" : "Folder name" }),
990
+ /* @__PURE__ */ jsx(
991
+ "input",
992
+ {
993
+ id: createInputId,
994
+ autoFocus: true,
995
+ value: creationName,
996
+ onChange: (event) => setCreationName(event.target.value),
997
+ placeholder: creationRequest.kind === "file" ? "Example.tsx" : "components"
998
+ }
999
+ ),
1000
+ error && /* @__PURE__ */ jsx("p", { className: "kai-code__dialog-error", role: "alert", children: error }),
1001
+ /* @__PURE__ */ jsxs("div", { className: "kai-code__dialog-actions", children: [
1002
+ /* @__PURE__ */ jsx("button", { onClick: () => setCreationRequest(null), type: "button", children: "Cancel" }),
1003
+ /* @__PURE__ */ jsx("button", { className: "is-primary", type: "submit", children: "Create" })
1004
+ ] })
1005
+ ]
1006
+ }
1007
+ )
1008
+ }
1009
+ ),
1010
+ deleteTarget && /* @__PURE__ */ jsx(
1011
+ "div",
1012
+ {
1013
+ className: "kai-code__dialog-backdrop",
1014
+ onMouseDown: (event) => {
1015
+ if (event.target === event.currentTarget) setDeleteTarget(null);
1016
+ },
1017
+ children: /* @__PURE__ */ jsxs(
1018
+ "div",
1019
+ {
1020
+ className: "kai-code__dialog",
1021
+ role: "dialog",
1022
+ "aria-modal": "true",
1023
+ "aria-labelledby": deleteTitleId,
1024
+ children: [
1025
+ /* @__PURE__ */ jsxs("h2", { id: deleteTitleId, children: [
1026
+ "Delete ",
1027
+ deleteTarget.type === "file" ? "file" : "folder",
1028
+ "?"
1029
+ ] }),
1030
+ /* @__PURE__ */ jsxs("p", { children: [
1031
+ /* @__PURE__ */ jsx("strong", { children: deleteTarget.name }),
1032
+ deleteTarget.type === "directory" && " and all of its contents will be permanently deleted."
1033
+ ] }),
1034
+ error && /* @__PURE__ */ jsx("p", { className: "kai-code__dialog-error", role: "alert", children: error }),
1035
+ /* @__PURE__ */ jsxs("div", { className: "kai-code__dialog-actions", children: [
1036
+ /* @__PURE__ */ jsx("button", { onClick: () => setDeleteTarget(null), type: "button", children: "Cancel" }),
1037
+ /* @__PURE__ */ jsx(
1038
+ "button",
1039
+ {
1040
+ className: "is-danger",
1041
+ onClick: () => void confirmDelete(),
1042
+ type: "button",
1043
+ children: "Delete"
1044
+ }
1045
+ )
1046
+ ] })
1047
+ ]
1048
+ }
1049
+ )
1050
+ }
1051
+ ),
1052
+ /* @__PURE__ */ jsxs("footer", { className: "kai-code__statusbar", children: [
1053
+ /* @__PURE__ */ jsxs("div", { className: "kai-code__status-left", children: [
1054
+ /* @__PURE__ */ jsx("span", { className: "kai-code__status-branch", children: "\u2442 main" }),
1055
+ /* @__PURE__ */ jsx("span", { children: error ? "Problems" : "Ready" })
1056
+ ] }),
1057
+ /* @__PURE__ */ jsxs("div", { className: "kai-code__status-right", children: [
1058
+ activeLanguage && /* @__PURE__ */ jsx("span", { children: activeLanguage }),
1059
+ /* @__PURE__ */ jsx("span", { children: "UTF-8" }),
1060
+ /* @__PURE__ */ jsx("span", { children: "LF" }),
1061
+ /* @__PURE__ */ jsx("span", { className: "kai-code__status-kai", children: "KaiCode" })
1062
+ ] })
1063
+ ] })
1064
+ ]
1065
+ }
1066
+ );
1067
+ }
1068
+ function findFile(nodes, path) {
1069
+ return nodes.some(
1070
+ (node) => node.type === "file" && node.path === path || node.type === "directory" && findFile(node.children ?? [], path)
1071
+ );
1072
+ }
1073
+ function findFileEntry(nodes, path) {
1074
+ for (const node of nodes) {
1075
+ if (node.type === "file" && node.path === path) return node;
1076
+ if (node.type === "directory") {
1077
+ const nested = findFileEntry(node.children ?? [], path);
1078
+ if (nested) return nested;
1079
+ }
1080
+ }
1081
+ return void 0;
1082
+ }
1083
+ var KaiCode_default = KaiCode;
1084
+ export {
1085
+ KaiCode,
1086
+ createMemoryFileSystem,
1087
+ KaiCode_default as default,
1088
+ normalizePath
1089
+ };