287 lines
8.5 KiB
Svelte
287 lines
8.5 KiB
Svelte
<script lang="ts">
|
|
import { t } from "$lib/i18n";
|
|
import { untrack } from "svelte";
|
|
import type { OpenBuffer } from "$lib/workspace/types";
|
|
import { workspaceReadDataUrl } from "$lib/workspace/api";
|
|
import { markdownBlocks } from "$lib/workspace/markdownBlocks";
|
|
import { findMarkdownImages, isRemoteImage, resolveImageRel } from "$lib/workspace/media";
|
|
import { renderMarkdownHtml } from "$lib/workspace/noteHtml";
|
|
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
|
|
import ContextMenu from "$lib/layout/ContextMenu.svelte";
|
|
import type { MenuItem } from "$lib/layout/menuTypes";
|
|
import { writerContextItems } from "./writerMenu";
|
|
import { useSpellingMenu } from "./spellingMenu";
|
|
|
|
type Props = {
|
|
buffer: OpenBuffer;
|
|
onChange: (value: string) => void;
|
|
onInsertImage?: (file: File) => Promise<string | null>;
|
|
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
|
};
|
|
|
|
type OpenMenu = { x: number; y: number; items: MenuItem[] } | null;
|
|
|
|
let { buffer, onChange, onInsertImage, onOpenLink }: Props = $props();
|
|
|
|
let host: HTMLDivElement | undefined = $state();
|
|
let editor: import("@tiptap/core").Editor | undefined;
|
|
let ready = $state(0);
|
|
let applying = false;
|
|
let skipUpdate = true;
|
|
let menu = $state<OpenMenu>(null);
|
|
|
|
function imageFiles(data: DataTransfer | null): File[] {
|
|
if (!data) {
|
|
return [];
|
|
}
|
|
return [...data.files].filter((file) => file.type.startsWith("image/"));
|
|
}
|
|
|
|
async function loadUrls(noteRel: string, contents: string): Promise<Map<string, string>> {
|
|
const urls = new Map<string, string>();
|
|
for (const block of markdownBlocks(contents)) {
|
|
if (block.type !== "text") {
|
|
continue;
|
|
}
|
|
for (const image of findMarkdownImages(block.line)) {
|
|
if (urls.has(image.src)) {
|
|
continue;
|
|
}
|
|
if (isRemoteImage(image.src)) {
|
|
urls.set(image.src, image.src.trim());
|
|
continue;
|
|
}
|
|
const primary = resolveImageRel(noteRel, image.src);
|
|
const base = image.src.replaceAll("\\", "/").split("/").pop() ?? image.src;
|
|
try {
|
|
urls.set(image.src, await workspaceReadDataUrl(primary));
|
|
} catch {
|
|
try {
|
|
urls.set(image.src, await workspaceReadDataUrl(base));
|
|
} catch {
|
|
urls.set(image.src, "");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return urls;
|
|
}
|
|
|
|
$effect(() => {
|
|
const el = host;
|
|
if (!el) {
|
|
return;
|
|
}
|
|
let cancelled = false;
|
|
void Promise.all([
|
|
import("@tiptap/core"),
|
|
import("@tiptap/starter-kit"),
|
|
import("@tiptap/extension-image"),
|
|
import("@tiptap/extension-link"),
|
|
import("@tiptap/extension-table"),
|
|
import("@tiptap/extension-superscript"),
|
|
import("@tiptap/extension-subscript"),
|
|
import("@tiptap/extension-task-list"),
|
|
import("@tiptap/extension-task-item"),
|
|
import("@tiptap/extension-highlight"),
|
|
import("./headingMarks"),
|
|
import("./writerMarks"),
|
|
]).then(async ([core, starter, imageMod, linkMod, tableMod, supMod, subMod, taskListMod, taskItemMod, highlightMod, marks, extra]) => {
|
|
if (cancelled || !el.isConnected) {
|
|
return;
|
|
}
|
|
const path = untrack(() => buffer.relPath);
|
|
const value = untrack(() => buffer.contents ?? "");
|
|
const urls = await loadUrls(path, value);
|
|
if (cancelled) {
|
|
return;
|
|
}
|
|
applying = true;
|
|
const html = renderMarkdownHtml(value, urls) || "<p></p>";
|
|
const Image = imageMod.default.extend({
|
|
addAttributes() {
|
|
return {
|
|
...this.parent?.(),
|
|
"data-md-src": { default: null },
|
|
"data-md-kind": { default: "md" },
|
|
};
|
|
},
|
|
});
|
|
const Link = linkMod.default.extend({
|
|
addAttributes() {
|
|
return {
|
|
...this.parent?.(),
|
|
"data-kind": { default: "md" },
|
|
class: { default: null },
|
|
};
|
|
},
|
|
});
|
|
const view = new core.Editor({
|
|
element: el,
|
|
extensions: [
|
|
starter.default.configure({ heading: { levels: [1, 2, 3, 4, 5, 6] } }),
|
|
Image.configure({ inline: false, allowBase64: true }),
|
|
Link.configure({ openOnClick: false, autolink: false }),
|
|
tableMod.TableKit.configure({ table: { resizable: false } }),
|
|
supMod.default,
|
|
subMod.default,
|
|
taskListMod.default,
|
|
taskItemMod.default.configure({ nested: false }),
|
|
highlightMod.default.configure({ multicolor: false }),
|
|
extra.MathMark,
|
|
extra.CommentMark,
|
|
marks.HeadingMarks,
|
|
],
|
|
content: html,
|
|
editorProps: {
|
|
attributes: { class: "reading writer-doc", spellcheck: "true" },
|
|
handleDOMEvents: {
|
|
contextmenu: (pmView, event) => {
|
|
if (useSpellingMenu(event, pmView.state.selection.empty)) { menu = null; return false; }
|
|
event.preventDefault();
|
|
if (!editor) {
|
|
return true;
|
|
}
|
|
const hit = pmView.posAtCoords({ left: event.clientX, top: event.clientY });
|
|
if (hit) {
|
|
const { from, to } = editor.state.selection;
|
|
if (from === to || hit.pos < from || hit.pos > to) {
|
|
editor.chain().setTextSelection(hit.pos).run();
|
|
}
|
|
}
|
|
menu = {
|
|
x: event.clientX,
|
|
y: event.clientY,
|
|
items: writerContextItems(editor),
|
|
};
|
|
return true;
|
|
},
|
|
},
|
|
handleClick: (_view, _pos, event) => {
|
|
const node = event.target instanceof Element ? event.target.closest("a") : null;
|
|
if (!node) {
|
|
return false;
|
|
}
|
|
const href = node.getAttribute("href") ?? "";
|
|
const kind = node.getAttribute("data-kind");
|
|
if (kind === "wiki") {
|
|
event.preventDefault();
|
|
onOpenLink?.("wiki", href);
|
|
return true;
|
|
}
|
|
if (kind === "md" && !/^https?:\/\//i.test(href)) {
|
|
event.preventDefault();
|
|
onOpenLink?.("md", href);
|
|
return true;
|
|
}
|
|
return false;
|
|
},
|
|
},
|
|
onCreate: () => {
|
|
applying = false;
|
|
queueMicrotask(() => {
|
|
skipUpdate = false;
|
|
});
|
|
},
|
|
onUpdate: ({ editor: current }) => {
|
|
if (applying || skipUpdate) {
|
|
return;
|
|
}
|
|
onChange(htmlToMarkdown(current.getHTML()));
|
|
},
|
|
});
|
|
editor = view;
|
|
ready += 1;
|
|
view.commands.focus("end");
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
editor?.destroy();
|
|
editor = undefined;
|
|
};
|
|
});
|
|
|
|
$effect(() => {
|
|
void ready;
|
|
const contents = buffer.contents;
|
|
const view = editor;
|
|
if (!view) {
|
|
return;
|
|
}
|
|
if (view.isFocused) {
|
|
return;
|
|
}
|
|
const current = htmlToMarkdown(view.getHTML());
|
|
if (contents === current) {
|
|
return;
|
|
}
|
|
applying = true;
|
|
void loadUrls(buffer.relPath, contents).then((urls) => {
|
|
if (editor !== view) {
|
|
return;
|
|
}
|
|
view.commands.setContent(renderMarkdownHtml(contents, urls) || "<p></p>");
|
|
applying = false;
|
|
});
|
|
});
|
|
</script>
|
|
|
|
<div
|
|
class="writer-host"
|
|
role="application"
|
|
aria-label={$t("Writer")}
|
|
bind:this={host}
|
|
ondragover={(event) => {
|
|
if (imageFiles(event.dataTransfer).length > 0) {
|
|
event.preventDefault();
|
|
}
|
|
}}
|
|
ondrop={(event) => {
|
|
const files = imageFiles(event.dataTransfer);
|
|
if (files.length === 0 || !onInsertImage) {
|
|
return;
|
|
}
|
|
event.preventDefault();
|
|
void (async () => {
|
|
for (const file of files) {
|
|
const snippet = await onInsertImage(file);
|
|
const rel = snippet ? /\(([^)]+)\)/.exec(snippet)?.[1] : null;
|
|
if (!rel || !editor) {
|
|
continue;
|
|
}
|
|
try {
|
|
const src = await workspaceReadDataUrl(rel);
|
|
editor.commands.insertContent(
|
|
`<img src="${src}" alt="${file.name}" data-md-src="${rel}" data-md-kind="md" />`,
|
|
);
|
|
} catch {
|
|
editor.commands.insertContent(snippet);
|
|
}
|
|
}
|
|
})();
|
|
}}
|
|
></div>
|
|
|
|
{#if menu}
|
|
<ContextMenu
|
|
x={menu.x}
|
|
y={menu.y}
|
|
items={menu.items}
|
|
onClose={() => (menu = null)}
|
|
/>
|
|
{/if}
|
|
|
|
<style>
|
|
.writer-host {
|
|
position: absolute;
|
|
inset: 0;
|
|
overflow: hidden;
|
|
}
|
|
|
|
.writer-host :global(.tiptap),
|
|
.writer-host :global(.ProseMirror) {
|
|
height: 100%;
|
|
overflow: auto;
|
|
}
|
|
</style>
|