Initial RuneStone project
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import { requestText } from "../workspace/dialogs.svelte";
|
||||
import { htmlToMarkdown } from "../workspace/htmlToMarkdown";
|
||||
import { cellFormats, type TableContextActions } from "./tableCellActions";
|
||||
import { formatText, insertBlock, paragraphText, replacement, type MarkdownEdit, type TextSelection, type ParagraphStyle, type InsertBlock } from "./markdownCommands";
|
||||
|
||||
export type MarkdownMenuEditor = {
|
||||
snapshot: () => { source: string; selection: TextSelection; valid: () => boolean };
|
||||
apply: (edit: MarkdownEdit) => void;
|
||||
selectAll: () => void;
|
||||
focus: () => void;
|
||||
};
|
||||
|
||||
// A shared controller keeps menus, async selection guards, and clipboard behavior
|
||||
// identical in the writing editor and the source editor.
|
||||
export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void) {
|
||||
let root: HTMLElement | undefined, destroyed = false;
|
||||
function close(focus = true) {
|
||||
root?.remove(); root = undefined;
|
||||
if (focus && !destroyed) editor.focus();
|
||||
}
|
||||
const outside = (event: MouseEvent) => { if (root && !root.contains(event.target as Node)) close(false); };
|
||||
const scroll = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
|
||||
const resize = () => close(false);
|
||||
document.addEventListener("mousedown", outside, true);
|
||||
document.addEventListener("scroll", scroll, true);
|
||||
window.addEventListener("resize", resize);
|
||||
|
||||
function open(x: number, y: number) {
|
||||
close(false);
|
||||
const snapshot = editor.snapshot(), { source, selection } = snapshot;
|
||||
const text = source.slice(selection.from, selection.to);
|
||||
const valid = () => !destroyed && snapshot.valid();
|
||||
function apply(edit: MarkdownEdit) {
|
||||
if (!valid()) return;
|
||||
close(); editor.apply(edit); editor.focus();
|
||||
}
|
||||
async function request(run: () => Promise<void>) {
|
||||
close(false);
|
||||
try { await run(); } catch (error) { if (!destroyed) report(error instanceof Error ? error.message : String(error)); }
|
||||
finally { if (valid()) editor.focus(); }
|
||||
}
|
||||
function link(external: boolean) {
|
||||
void request(async () => {
|
||||
const target = (await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text))?.trim();
|
||||
if (!target || !valid()) return;
|
||||
if (external) {
|
||||
try {
|
||||
const url = new URL(target);
|
||||
if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error();
|
||||
} catch { report("Enter a valid http, https, or mailto link."); return; }
|
||||
const label = (text || target).replace(/[\\[\]]/g, "\\$&").replace(/\r?\n/g, " ");
|
||||
apply(replacement(selection, `[${label}](${target.replace(/[()<>]/g, char => encodeURIComponent(char).replace("(", "%28").replace(")", "%29"))})`));
|
||||
} else {
|
||||
if (/[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report("Enter a note name or path without brackets or pipes."); return; }
|
||||
const label = text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim();
|
||||
apply(replacement(selection, `[[${target}${label && label !== target ? "|" + label : ""}]]`));
|
||||
}
|
||||
});
|
||||
}
|
||||
function clipboard(kind: "cut" | "copy" | "paste" | "plain") {
|
||||
void request(async () => {
|
||||
try {
|
||||
if (kind === "cut" || kind === "copy") {
|
||||
await navigator.clipboard.writeText(text);
|
||||
if (kind === "cut") apply(replacement(selection, ""));
|
||||
} else {
|
||||
let value = "";
|
||||
if (kind === "paste" && navigator.clipboard.read) {
|
||||
try {
|
||||
const data = await navigator.clipboard.read();
|
||||
const rich = data.find(item => item.types.includes("text/html"));
|
||||
if (rich) value = htmlToMarkdown(await (await rich.getType("text/html")).text());
|
||||
} catch { /* Fall back to the text clipboard on older WebViews. */ }
|
||||
}
|
||||
if (!value) value = await navigator.clipboard.readText();
|
||||
if (value) apply(replacement(selection, value.replace(/\r?\n/g, source.includes("\r\n") ? "\r\n" : "\n")));
|
||||
}
|
||||
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
|
||||
});
|
||||
}
|
||||
const paragraph = (label: string, style: ParagraphStyle, icon: "bullet" | "number" | "task" | "heading" | "paragraph" | "quote"): ActionMenuItem => ({ label, icon, run: () => apply(paragraphText(source, selection, style)) });
|
||||
const insert = (label: string, kind: InsertBlock, icon: "footnote" | "table" | "quote" | "rule" | "code" | "math"): ActionMenuItem => ({ label, icon, run: () => apply(insertBlock(source, selection, kind)) });
|
||||
const items: ActionMenuItem[] = [
|
||||
{ label: "Add link", icon: "link", run: () => link(false) },
|
||||
{ label: "Add external link", icon: "external", run: () => link(true) },
|
||||
{ separator: true },
|
||||
{ label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
|
||||
{ label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
|
||||
const target = await actions.onExtract?.(text, text, valid);
|
||||
if (target) apply(replacement(selection, `[[${target}|${text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim()}]]`));
|
||||
}) },
|
||||
{ label: "Format", icon: "format", children: cellFormats.flatMap(([label, kind]) => [
|
||||
...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []),
|
||||
{ label, icon: kind, disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) },
|
||||
]) },
|
||||
{ label: "Paragraph", icon: "paragraph", children: [
|
||||
paragraph("Bullet list", "bullet", "bullet"), paragraph("Numbered list", "number", "number"), paragraph("Task list", "task", "task"),
|
||||
{ separator: true },
|
||||
...([1, 2, 3, 4, 5, 6] as const).map(level => paragraph(`Heading ${level}`, level, "heading")),
|
||||
paragraph("Body", "body", "paragraph"), { separator: true }, paragraph("Quote", "quote", "quote"),
|
||||
] },
|
||||
{ label: "Insert", icon: "insert", children: [
|
||||
insert("Footnote", "footnote", "footnote"), insert("Table", "table", "table"), insert("Callout", "callout", "quote"), insert("Horizontal rule", "rule", "rule"),
|
||||
{ separator: true }, insert("Code block", "code", "code"), insert("Math block", "math", "math"),
|
||||
] },
|
||||
{ separator: true },
|
||||
{ label: "Cut", icon: "cut", disabled: !text, run: () => clipboard("cut") },
|
||||
{ label: "Copy", icon: "copy", disabled: !text, run: () => clipboard("copy") },
|
||||
{ label: "Paste", icon: "paste", run: () => clipboard("paste") },
|
||||
{ label: "Paste as plain text", icon: "paste-text", run: () => clipboard("plain") },
|
||||
{ label: "Select all", icon: "select", run: () => { close(); editor.selectAll(); } },
|
||||
];
|
||||
root = actionMenu(x, y, items, close, "Markdown text actions");
|
||||
}
|
||||
return { open, close, destroy() {
|
||||
destroyed = true; close(false);
|
||||
document.removeEventListener("mousedown", outside, true);
|
||||
document.removeEventListener("scroll", scroll, true);
|
||||
window.removeEventListener("resize", resize);
|
||||
} };
|
||||
}
|
||||
Reference in New Issue
Block a user