Move source of truth into wrapper

This commit is contained in:
Caleb Braaten 2025-04-23 15:52:25 -07:00
parent 80fb1813cf
commit 0222d25a07

View File

@ -7,6 +7,11 @@ class EditorJSWrapper {
private holder: HTMLDivElement | null = null; private holder: HTMLDivElement | null = null;
private onChange!: (data: OutputData) => void; private onChange!: (data: OutputData) => void;
private static instance: EditorJSWrapper | null = null; private static instance: EditorJSWrapper | null = null;
private currentData: OutputData = {
time: Date.now(),
blocks: [],
version: '2.28.2'
};
constructor(onChange: (data: OutputData) => void) { constructor(onChange: (data: OutputData) => void) {
if (EditorJSWrapper.instance) { if (EditorJSWrapper.instance) {
@ -29,13 +34,9 @@ class EditorJSWrapper {
this.editor = new EditorJS({ this.editor = new EditorJS({
holder: holder, holder: holder,
placeholder: 'Start writing...', placeholder: 'Start writing...',
data: this.currentData,
onChange: async () => { onChange: async () => {
try { await this.syncState();
const content = await this.editor!.save();
this.onChange(content);
} catch (err) {
console.error('Error saving editor content:', err);
}
} }
}); });
} catch (error) { } catch (error) {
@ -43,13 +44,22 @@ class EditorJSWrapper {
} }
} }
private async syncState() {
if (!this.editor) return;
try {
this.currentData = await this.editor.save();
this.onChange(this.currentData);
} catch (err) {
console.error('Error syncing state:', err);
}
}
async addBlock(text: string) { async addBlock(text: string) {
if (!this.editor) return; if (!this.editor) return;
try { try {
await this.editor.blocks.insert('paragraph', { text }); await this.editor.blocks.insert('paragraph', { text });
const updatedData = await this.editor.save(); await this.syncState();
this.onChange(updatedData);
} catch (err) { } catch (err) {
console.error('Error adding block:', err); console.error('Error adding block:', err);
} }
@ -59,14 +69,19 @@ class EditorJSWrapper {
if (!this.editor) return; if (!this.editor) return;
try { try {
await this.editor.clear(); await this.editor.clear();
this.currentData = {
time: Date.now(),
blocks: [],
version: '2.28.2'
};
this.onChange(this.currentData);
} catch (err) { } catch (err) {
console.error('Error clearing editor:', err); console.error('Error clearing editor:', err);
} }
} }
async getData(): Promise<OutputData> { async getData(): Promise<OutputData> {
if (!this.editor) throw new Error('Editor not initialized'); return this.currentData;
return this.editor.save();
} }
async destroy() { async destroy() {
@ -75,6 +90,11 @@ class EditorJSWrapper {
await this.editor.destroy(); await this.editor.destroy();
this.editor = null; this.editor = null;
this.holder = null; this.holder = null;
this.currentData = {
time: Date.now(),
blocks: [],
version: '2.28.2'
};
EditorJSWrapper.instance = null; EditorJSWrapper.instance = null;
} }
} catch (error: unknown) { } catch (error: unknown) {