Elffuss BraidHub

kikocis/continue public

3ff29c567dd0 · 1.6 KiBRawPermalink
1type DocumentNode = ParagraphNode | ListNode;
2
3abstract class Node {
4 abstract render(): string;
5}
6
7class ParagraphNode extends Node {
8 constructor(public text: string) {
9 super();
10 }
11
12 render(): string {
13 return `<p>${this.text}</p>`;
14 }
15}
16
17class ListNode extends Node {
18 constructor(public items: string[]) {
19 super();
20 }
21
22 render(): string {
23 return `<ul>${this.items.map((item) => `<li>${item}</li>`).join("")}</ul>`;
24 }
25}
26
27interface Command {
28 execute(): void;
29 undo(): void;
30}
31
32interface Observer {
33 update(doc: DocumentEditor): void;
34}
35
36class DocumentEditor {
37 private nodes: DocumentNode[] = [];
38 private undoStack: Command[] = [];
39 private redoStack: Command[] = [];
40 private observers: Observer[] = [];
41
42 addNode(node: DocumentNode) {
43 this.nodes.push(node);
44 this.notify();
45 }
46
47 executeCommand(command: Command) {
48 command.execute();
49 this.undoStack.push(command);
50 this.redoStack = [];
51 this.notify();
52 }
53
54 undo() {
55 const cmd = this.undoStack.pop();
56 if (cmd) {
57 cmd.undo();
58 this.redoStack.push(cmd);
59 this.notify();
60 }
61 }
62
63 redo() {
64 const cmd = this.redoStack.pop();
65 if (cmd) {
66 cmd.execute();
67 this.undoStack.push(cmd);
68 this.notify();
69 }
70 }
71
72 getContent(): string {
73 return this.nodes.map((n) => n.render()).join("\n");
74 }
75
76 getNodes(): DocumentNode[] {
77 return this.nodes;
78 }
79
80 setNodes(nodes: DocumentNode[]) {
81 this.nodes = nodes;
82 }
83
84 subscribe(observer: Observer) {
85 this.observers.push(observer);
86 }
87
88 private notify() {
89 this.observers.forEach((o) => o.update(this));
90 }
91}