Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 49 additions & 12 deletions apps/obsidian/src/components/TldrawView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import { TLStore } from "tldraw";
import React from "react";
import DiscourseGraphPlugin from "~/index";
import { processInitialData, TLData } from "~/utils/tldraw";
import { ObsidianTLAssetStore } from "~/utils/assetStore";

export class TldrawView extends TextFileView {
plugin: DiscourseGraphPlugin;
private reactRoot?: Root;
private store?: TLStore;
private store: TLStore | null = null;
private assetStore: ObsidianTLAssetStore | null = null;
private onUnloadCallbacks: (() => void)[] = [];

constructor(leaf: WorkspaceLeaf, plugin: DiscourseGraphPlugin) {
Expand All @@ -31,7 +33,7 @@ export class TldrawView extends TextFileView {
return this.data;
}

setViewData(data: string, clear: boolean): void {
setViewData(data: string, _clear: boolean): void {
this.data = data;
}

Expand Down Expand Up @@ -66,17 +68,28 @@ export class TldrawView extends TextFileView {

const fileData = await this.app.vault.read(file);

const store = this.createStore(fileData);
const assetStore = new ObsidianTLAssetStore(
`tldraw-${encodeURIComponent(file.path)}`,
{
app: this.app,
file,
},
);
const store = this.createStore(fileData, assetStore);

if (!store) {
console.warn("No tldraw data found in file");
return;
}

this.setStore(store);
this.assetStore = assetStore;
await this.setStore(store);
}

private createStore(fileData: string): TLStore | undefined {
private createStore(
fileData: string,
assetStore: ObsidianTLAssetStore,
): TLStore | undefined {
try {
const match = fileData.match(
/```json !!!_START_OF_TLDRAW_DG_DATA__DO_NOT_CHANGE_THIS_PHRASE_!!!([\s\S]*?)!!!_END_OF_TLDRAW_DG_DATA__DO_NOT_CHANGE_THIS_PHRASE_!!!\n```/,
Expand All @@ -93,7 +106,7 @@ export class TldrawView extends TextFileView {
return;
}

const { store } = processInitialData(data);
const { store } = processInitialData(data, assetStore);

return store;
} catch (e) {
Expand All @@ -102,23 +115,36 @@ export class TldrawView extends TextFileView {
}
}

private assertInitialized(): void {
if (!this.file) throw new Error("TldrawView not initialized: missing file");
if (!this.assetStore)
throw new Error("TldrawView not initialized: missing assetStore");
if (!this.store)
throw new Error("TldrawView not initialized: missing store");
}

private createReactRoot(entryPoint: Element, store: TLStore) {
const root = createRoot(entryPoint);
if (!this.file) return;
if (!this.file) throw new Error("TldrawView not initialized: missing file");
if (!this.assetStore)
throw new Error("TldrawView not initialized: missing assetStore");
if (!this.store)
throw new Error("TldrawView not initialized: missing store");

root.render(
<React.StrictMode>
<TldrawPreviewComponent
store={store}
plugin={this.plugin}
file={this.file}
assetStore={this.assetStore}
/>
</React.StrictMode>,
);
return root;
}

protected setStore(store: TLStore) {
protected async setStore(store: TLStore) {
if (this.store) {
try {
this.store.dispose();
Expand All @@ -129,11 +155,11 @@ export class TldrawView extends TextFileView {

this.store = store;
if (this.tldrawContainer) {
this.refreshView();
await this.refreshView();
}
}

private refreshView() {
private async refreshView() {
if (!this.store) return;

if (this.reactRoot) {
Expand All @@ -151,6 +177,7 @@ export class TldrawView extends TextFileView {
const container = this.tldrawContainer;
if (container) {
this.reactRoot = this.createReactRoot(container, this.store);
await new Promise((resolve) => setTimeout(resolve, 0)); // Wait for React to render
}
}

Expand All @@ -163,6 +190,11 @@ export class TldrawView extends TextFileView {
this.onUnloadCallbacks = [];
callbacks.forEach((cb) => cb());

if (this.assetStore) {
this.assetStore.dispose();
this.assetStore = null;
}

return super.onUnloadFile(file);
}

Expand All @@ -187,7 +219,12 @@ export class TldrawView extends TextFileView {
} catch (e) {
console.error("Failed to dispose store", e);
}
this.store = undefined;
this.store = null;
}

if (this.assetStore) {
this.assetStore.dispose();
this.assetStore = null;
}
}
}
}
21 changes: 7 additions & 14 deletions apps/obsidian/src/components/TldrawViewComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,24 @@ import {
TLDATA_DELIMITER_START,
} from "~/constants";
import { TFile } from "obsidian";
import { ObsidianTLAssetStore } from "~/utils/assetStore";

interface TldrawPreviewProps {
store: TLStore;
plugin: DiscourseGraphPlugin;
file: TFile;
assetStore: ObsidianTLAssetStore;
}

export const TldrawPreviewComponent = ({
store,
plugin,
file,
assetStore,
}: TldrawPreviewProps) => {
const containerRef = useRef<HTMLDivElement>(null);
const [currentStore, setCurrentStore] = useState<TLStore>(store);
const [isReady, setIsReady] = useState(false);
const editorRef = useRef<Editor | null>(null);
const saveTimeoutRef = useRef<NodeJS.Timeout>();
const lastSavedDataRef = useRef<string>("");

Expand Down Expand Up @@ -90,11 +92,11 @@ export const TldrawPreviewComponent = ({
);
if (match?.[1]) {
const data = JSON.parse(match[1]) as TLData;
const { store: newStore } = processInitialData(data);
const { store: newStore } = processInitialData(data, assetStore);
setCurrentStore(newStore);
}
}
}, [file, plugin, currentStore]);
}, [file, plugin, currentStore, assetStore]);

useEffect(() => {
const unsubscribe = currentStore.listen(
Expand All @@ -118,24 +120,15 @@ export const TldrawPreviewComponent = ({
};
}, [currentStore, saveChanges]);

const handleMount = useCallback((editor: Editor) => {
editorRef.current = editor;
editor.setCurrentTool("select");
}, []);

return (
<div
ref={containerRef}
className="tldraw__editor relative flex h-full w-full flex-1 overflow-hidden"
onTouchStart={(e) => e.stopPropagation()}
>
<div ref={containerRef} className="tldraw__editor relative h-full">
{isReady ? (
<ErrorBoundary
fallback={({ error }) => (
<div>Error in Tldraw component: {JSON.stringify(error)}</div>
)}
>
<Tldraw store={currentStore} onMount={handleMount} autoFocus={true} />
<Tldraw store={currentStore} autoFocus={true} initialState="select" />
</ErrorBoundary>
) : (
<div>Loading Tldraw...</div>
Expand Down
Loading