Skip to content

Commit

Permalink
Merge branch jon-dez/main
Browse files Browse the repository at this point in the history
  • Loading branch information
jon-dez committed Aug 28, 2024
2 parents e3e48e9 + 07ab2ce commit 14fc97a
Show file tree
Hide file tree
Showing 18 changed files with 579 additions and 167 deletions.
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "tldraw",
"name": "Tldraw",
"version": "1.3.0",
"version": "1.4.0",
"minAppVersion": "0.15.0",
"description": "Integrates Tldraw into Obsidian, allowing users to draw and edit content on a virtual whiteboard.",
"author": "Sam Alhaqab",
Expand Down
42 changes: 24 additions & 18 deletions src/components/TldrawApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ import {
defaultShapeUtils,
useActions,
} from "@tldraw/tldraw";
import { TldrawPluginSettings } from "../obsidian/TldrawSettingsTab";
import { useDebouncedCallback } from "use-debounce";
import { SAVE_FILE_COPY_ACTION } from "src/utils/file";
import { OPEN_FILE_ACTION, SAVE_FILE_COPY_ACTION, SAVE_FILE_COPY_IN_VAULT_ACTION } from "src/utils/file";
import { isObsidianThemeDark, safeSecondsToMs } from "src/utils/utils";
import { uiOverrides } from "src/tldraw/ui-overrides";
import { TLDataDocument, TldrawPluginMetaData } from "src/utils/document";
import { createRawTldrawFile } from "src/utils/tldraw-file";
import TldrawPlugin from "src/main";
import { Platform } from "obsidian";

type TldrawAppOptions = {
isReadonly?: boolean,
Expand All @@ -46,34 +47,39 @@ export type SetTldrawFileData = (data: {
}) => void;

export type TldrawAppProps = {
settings: TldrawPluginSettings;
plugin: TldrawPlugin;
initialData: TLDataDocument;
setFileData: SetTldrawFileData;
options: TldrawAppOptions
};

// /~https://github.com/tldraw/tldraw/blob/58890dcfce698802f745253ca42584731d126cc3/apps/examples/src/examples/custom-main-menu/CustomMainMenuExample.tsx
const components: TLComponents = {
const components = (plugin: TldrawPlugin): TLComponents => ({
MainMenu: () => (
<DefaultMainMenu>
<LocalFileMenu />
<LocalFileMenu plugin={plugin} />
<DefaultMainMenuContent />
</DefaultMainMenu>
),
};
});

function LocalFileMenu() {
function LocalFileMenu(props: { plugin: TldrawPlugin }) {
const actions = useActions();

return (
<TldrawUiMenuSubmenu id="file" label="menu.file">
<TldrawUiMenuItem {...actions[SAVE_FILE_COPY_ACTION]} />
{/* <TldrawUiMenuItem {...actions[OPEN_FILE_ACTION]} /> */}
{
Platform.isMobile
? <></>
: <TldrawUiMenuItem {...actions[SAVE_FILE_COPY_ACTION]} />
}
<TldrawUiMenuItem {...actions[SAVE_FILE_COPY_IN_VAULT_ACTION]} />
<TldrawUiMenuItem {...actions[OPEN_FILE_ACTION]} />
</TldrawUiMenuSubmenu>
);
}

const TldrawApp = ({ settings, initialData, setFileData, options: {
const TldrawApp = ({ plugin, initialData, setFileData, options: {
autoFocus = true,
hideUi = false,
inputFocus = false,
Expand All @@ -82,7 +88,7 @@ const TldrawApp = ({ settings, initialData, setFileData, options: {
zoomToBounds = false,
defaultFontOverrides
} }: TldrawAppProps) => {
const saveDelayInMs = safeSecondsToMs(settings.saveFileDelay);
const saveDelayInMs = safeSecondsToMs(plugin.settings.saveFileDelay);

const [{ meta, store },
/**
Expand Down Expand Up @@ -134,7 +140,7 @@ const TldrawApp = ({ settings, initialData, setFileData, options: {
// Obsidian thinks they're swiping down, left, or right so it opens various menus.
// By preventing the event from propagating, we can prevent those actions menus from opening.
onTouchStart={(e) => e.stopPropagation()}
onBlur={!inputFocus ? undefined : () => {
onBlur={!inputFocus ? undefined : () => {
editorRef.current?.selectNone()
editorRef.current?.blur()
}}
Expand All @@ -145,14 +151,14 @@ const TldrawApp = ({ settings, initialData, setFileData, options: {
fonts: defaultFontOverrides
}}
hideUi={hideUi}
overrides={uiOverrides}
overrides={uiOverrides(plugin)}
store={store}
components={components}
components={components(plugin)}
// Set this flag to false when a tldraw document is embed into markdown to prevent it from gaining focus when it is loaded.
autoFocus={autoFocus}
onMount={(editor) => {
editorRef.current = editor;
if(selectNone) {
if (selectNone) {
editor.selectNone();
}

Expand All @@ -163,7 +169,7 @@ const TldrawApp = ({ settings, initialData, setFileData, options: {
snapMode,
focusMode,
toolSelected,
} = settings;
} = plugin.settings;

// NOTE: The API broke when updating Tldraw version and I don't know what to replace it with.
// editor.focus();
Expand Down Expand Up @@ -200,7 +206,7 @@ export const createRootAndRenderTldrawApp = (
node: Element,
initialData: TLDataDocument,
setFileData: SetTldrawFileData,
settings: TldrawPluginSettings,
plugin: TldrawPlugin,
options: TldrawAppOptions = {}
) => {
const root = createRoot(node);
Expand All @@ -209,7 +215,7 @@ export const createRootAndRenderTldrawApp = (
<TldrawApp
setFileData={setFileData}
initialData={initialData}
settings={settings}
plugin={plugin}
options={options}
/>
);
Expand Down
117 changes: 43 additions & 74 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
addIcon,
normalizePath,
moment,
Notice,
} from "obsidian";
import { TldrawView } from "./obsidian/TldrawView";
import {
Expand Down Expand Up @@ -49,6 +50,10 @@ import { pluginBuild } from "./utils/decorators/plugin";
import { markdownPostProcessor } from "./obsidian/plugin/markdown-post-processor";
import { processFontOverrides } from "./obsidian/plugin/settings";
import { createRawTldrawFile } from "./utils/tldraw-file";
import { TLDRAW_FILE_EXTENSION, TLStore } from "@tldraw/tldraw";
import { registerCommands } from "./obsidian/plugin/commands";
import { migrateTldrawFileDataIfNecessary } from "./utils/migrate/tl-data-to-tlstore";
import { pluginMenuLabel } from "./obsidian/menu";

@pluginBuild
export default class TldrawPlugin extends Plugin {
Expand Down Expand Up @@ -118,6 +123,8 @@ export default class TldrawPlugin extends Plugin {

// Change how tldraw files are displayed when reading the document, e.g. when it is embed in another Obsidian document.
this.registerMarkdownPostProcessor((e, c) => markdownPostProcessor(this, e, c))

this.registerExtensions(['tldr'], VIEW_TYPE_TLDRAW_READ_ONLY)
}

onunload() {
Expand Down Expand Up @@ -193,7 +200,30 @@ export default class TldrawPlugin extends Plugin {
// adds a menu item to the file menu (three dots) depending on view mode
this.registerEvent(
this.app.workspace.on("file-menu", (menu, file, source, leaf) => {
if (!leaf || !(file instanceof TFile)) return;
if (!(file instanceof TFile)) return;

if (file.path.endsWith(TLDRAW_FILE_EXTENSION)) {
menu.addItem((item) => pluginMenuLabel(item
.setSection('tldraw')
)).addItem((item) => {
item.setIcon('edit')
.setSection('tldraw')
.setTitle('Edit as new Note')
.onClick(async () => {
const newFile = await this.createUntitledTldrFile({
tlStore: migrateTldrawFileDataIfNecessary(
await this.app.vault.read(file)
)
});
await this.openTldrFile(newFile, 'new-tab', 'tldraw-view')
new Notice(`Created a new file for editing "${newFile.path}"`)
})
})
return;
}

if (!leaf) return;

if (!this.isTldrawFile(file)) return;

const { type } = leaf.getViewState();
Expand Down Expand Up @@ -245,75 +275,7 @@ export default class TldrawPlugin extends Plugin {
);
}

private registerCommands() {
this.addCommand({
id: "toggle-view-mode",
name: "Toggle view mode",
checkCallback: (checking) => {
const file = this.app.workspace.getActiveFile();
if (!file) return false;

const fileIsTldraw = this.isTldrawFile(file);
if (checking) return fileIsTldraw;

const leaf = this.app.workspace.getLeaf(false);
const currentViewMode = this.getLeafFileViewMode(leaf, file);
const oppositeViewMode =
currentViewMode === VIEW_TYPE_MARKDOWN
? VIEW_TYPE_TLDRAW
: VIEW_TYPE_MARKDOWN;
this.updateViewMode(oppositeViewMode, leaf);
},
});

this.addCommand({
id: "new-tldraw-file-current-tab",
name: "Create a new drawing in the current tab",
callback: async () => {
await this.createAndOpenUntitledTldrFile("current-tab");
},
});

this.addCommand({
id: "new-tldraw-file-new-tab",
name: "Create a new drawing in a new tab",
callback: async () => {
await this.createAndOpenUntitledTldrFile("new-tab");
},
});

this.addCommand({
id: "new-tldraw-file-split-tab ",
name: "Create a new drawing in split tab",
callback: async () => {
await this.createAndOpenUntitledTldrFile("split-tab");
},
});

this.addCommand({
id: "new-tldraw-file-new-window",
name: "Create a new drawing in a new window",
callback: async () => {
await this.createAndOpenUntitledTldrFile("new-window");
},
});

this.addCommand({
id: "new-tldraw-file-embed",
name: "Create a new drawing and embed as attachment",
editorCallback: async (editor, ctx) => {
const { file } = ctx;
if (file === null) {
console.log(ctx)
throw new Error('ctx.file was null');
}
const from = editor.getCursor('from');
const to = editor.getCursor('to');
const newFile = await this.createUntitledTldrFile(file);
editor.replaceRange(`![[${newFile.path}]]`, from, to)
},
});
}
private registerCommands = () => registerCommands(this)

public setStatusBarViewModeVisibility(visible: boolean) {
if (visible)
Expand Down Expand Up @@ -415,14 +377,16 @@ export default class TldrawPlugin extends Plugin {
return await this.app.vault.create(fname, data ?? "");
}

public createTldrFile = async (filename: string, foldername?: string) => {
public createTldrFile = async (filename: string, {
foldername, tlStore
}: { foldername?: string, tlStore?: TLStore } = {}) => {
// adds the markdown extension if the filename does not already include it:
filename = filename.endsWith(FILE_EXTENSION)
? filename
: filename + FILE_EXTENSION;

// constructs the markdown content thats a template:
const tlData = getTLDataTemplate(this.manifest.version, createRawTldrawFile(), window.crypto.randomUUID());
const tlData = getTLDataTemplate(this.manifest.version, createRawTldrawFile(tlStore), window.crypto.randomUUID());
const frontmatter = frontmatterTemplate(`${FRONTMATTER_KEY}: true`);
const codeblock = codeBlockTemplate(tlData);
const fileData = tlFileTemplate(frontmatter, codeblock);
Expand All @@ -435,7 +399,9 @@ export default class TldrawPlugin extends Plugin {
* @param attachTo The file that is considered as the "parent" of this new file. If this is not undefined then the new untitled tldr file will be considered as an attachment.
* @returns
*/
public createUntitledTldrFile = async (attachTo?: TFile) => {
public createUntitledTldrFile = async ({
attachTo, tlStore
}: { attachTo?: TFile, tlStore?: TLStore } = {}) => {
const { newFilePrefix, newFileTimeFormat, folder, useAttachmentsFolder } = this.settings;

const date =
Expand All @@ -455,7 +421,10 @@ export default class TldrawPlugin extends Plugin {
? { filename, folder }
: await createAttachmentFilepath(filename, attachTo, this.app.fileManager);

return await this.createTldrFile(res.filename, res.folder);
return await this.createTldrFile(res.filename, {
tlStore,
foldername: res.folder,
});
};

public openTldrFile = async (file: TFile, location: PaneTarget, viewType: ViewType = VIEW_TYPE_TLDRAW) => {
Expand Down
10 changes: 6 additions & 4 deletions src/obsidian/TldrawMixins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ export function TldrawLoadableMixin<T extends abstract new (...args: any[]) => F
override onload(): void {
this.contentEl.addClass("tldraw-view-content");

this.addAction(MARKDOWN_ICON_NAME, "View as markdown", () => {
this.plugin.updateViewMode(VIEW_TYPE_MARKDOWN);
});
this.addAction(MARKDOWN_ICON_NAME, "View as markdown", () => this.viewAsMarkdownClicked());
}

/**
Expand All @@ -55,7 +53,7 @@ export function TldrawLoadableMixin<T extends abstract new (...args: any[]) => F
entryPoint,
tldata,
this.setFileData,
this.plugin.settings,
this.plugin,
this.getTldrawOptions()
);
}
Expand All @@ -76,6 +74,10 @@ export function TldrawLoadableMixin<T extends abstract new (...args: any[]) => F
tldrawContainer, (entryPoint) => this.createReactRoot(entryPoint, tldata)
);
}

protected viewAsMarkdownClicked() {
this.plugin.updateViewMode(VIEW_TYPE_MARKDOWN);
}
}

return _TldrawLoadableMixin;
Expand Down
Loading

0 comments on commit 14fc97a

Please sign in to comment.