Update the browser, editor, settings, and installer
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
|
||||
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
|
||||
import { registerImageDropTarget } from "./workspaceImageDrop";
|
||||
import { workspaceFileLink } from "./workspaceFileLink";
|
||||
import { editorSession } from "./sessions";
|
||||
import { registerSelection } from "./selection";
|
||||
import { monacoChrome } from "./monacoChrome";
|
||||
@@ -56,7 +57,7 @@
|
||||
if (!range) return true;
|
||||
const [marker] = model.deltaDecorations([], [{ range, options: { stickiness: 1 } }]);
|
||||
try {
|
||||
const snippets: string[] = linkedPath ? [workspaceImageLink(buffer.relPath, linkedPath)] : [];
|
||||
const snippets: string[] = linkedPath ? [workspaceFileLink(buffer.relPath, linkedPath)] : [];
|
||||
for (const file of files) {
|
||||
if (editor !== view) return true;
|
||||
const snippet = await onInsertImage?.(file);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import { useSpellingMenu } from "./spellingMenu";
|
||||
import { spellingWord } from "./spellingWord";
|
||||
import { untrack } from "svelte";
|
||||
import { Compartment, EditorState, EditorSelection, Transaction } from "@codemirror/state";
|
||||
import { EditorView, drawSelection, keymap } from "@codemirror/view";
|
||||
@@ -17,6 +18,7 @@
|
||||
import { markdownImages } from "$lib/workspace/noteHtml";
|
||||
import { isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
|
||||
import { registerImageDropTarget } from "./workspaceImageDrop";
|
||||
import { workspaceFileLink } from "./workspaceFileLink";
|
||||
import { editorSession } from "./sessions";
|
||||
import { registerSelection } from "./selection";
|
||||
import { liveMarkdown, refreshImages } from "./liveMarkdown";
|
||||
@@ -28,6 +30,8 @@
|
||||
import { tableNavigation } from "./tableNavigation";
|
||||
import { completionExtension } from "$lib/completion/codemirror";
|
||||
import { documentLinkAt } from "./documentLinks";
|
||||
import { headingFolding } from "./headingFolding";
|
||||
import "./headingFolding.css";
|
||||
|
||||
type Props = {
|
||||
buffer: OpenBuffer;
|
||||
@@ -125,7 +129,7 @@
|
||||
const id = Symbol(), path = buffer.relPath;
|
||||
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
|
||||
try {
|
||||
const snippets: string[] = linkedPath ? [workspaceImageLink(path, linkedPath)] : [];
|
||||
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
|
||||
for (const file of files) {
|
||||
if (editor !== view) return;
|
||||
const snippet = await onInsertImage?.(file);
|
||||
@@ -168,6 +172,7 @@
|
||||
const extensions = [
|
||||
completionExtension(current.id),
|
||||
markdown({ base: markdownLanguage, extensions: [noteFormats] }),
|
||||
headingFolding,
|
||||
writerHistory.of({
|
||||
undo: () => {
|
||||
clearTimeout(historyTimer);
|
||||
@@ -237,7 +242,7 @@
|
||||
EditorView.domEventHandlers({
|
||||
contextmenu(event, view) {
|
||||
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
|
||||
if (useSpellingMenu(event, view.state.selection.main.empty)) { menu?.close(false); return false; }
|
||||
if (event.target instanceof HTMLElement && spellingWord(event.target.closest<HTMLElement>('[contenteditable="true"]') ?? event.target, event.clientX, event.clientY) && useSpellingMenu(event, view.state.selection.main.empty)) { menu?.close(false); return false; }
|
||||
event.preventDefault();
|
||||
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
const selection = view.state.selection.main;
|
||||
@@ -394,8 +399,9 @@
|
||||
.live-writer :global(.cm-editor.cm-focused) { outline: none; }
|
||||
.live-writer :global(.cm-scroller) { overflow: auto; font: var(--rs-font-weight) var(--rs-prose-size)/var(--rs-prose-line) var(--rs-font-prose); scrollbar-gutter: stable; }
|
||||
.live-writer :global(.cm-content) { max-width: 868px; width: 100%; margin: 0 auto; padding: clamp(24px, 4vw, 56px) clamp(22px, 4vw, 64px) 35vh; caret-color: var(--rs-text-strong); }
|
||||
.live-writer :global(.cm-line) { padding: 0; position: relative; }
|
||||
.live-writer :global(.cm-line) { padding-inline: 0; position: relative; }
|
||||
.live-writer :global(.cm-line:hover)::before { content: ""; position: absolute; left: -14px; top: 2px; bottom: 2px; width: 3px; border-radius: var(--rs-control-radius); background: var(--rs-text-dim); opacity: .5; pointer-events: none; }
|
||||
.live-writer :global(.writer-heading:hover)::before { display: none; }
|
||||
.live-writer :global(.cm-panels) { background: var(--rs-bg-elevated); color: var(--rs-text); }
|
||||
.live-writer :global(.cm-cursor) { border-left-color: var(--rs-text-strong); }
|
||||
.live-writer :global(.cm-selectionBackground), .live-writer :global(.cm-focused .cm-selectionBackground) { background: var(--rs-bg-active); }
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { mount, unmount } from "svelte";
|
||||
import QuickOpen from "../layout/QuickOpen.svelte";
|
||||
|
||||
/** Use the workspace file picker without opening or switching the active note. */
|
||||
export function pickLinkDocument(signal: AbortSignal): Promise<string | null> {
|
||||
if (signal.aborted) return Promise.resolve(null);
|
||||
return new Promise(resolve => {
|
||||
const target = document.createElement("div");
|
||||
document.body.append(target);
|
||||
let component: ReturnType<typeof mount> | undefined;
|
||||
let finished = false;
|
||||
const finish = (path: string | null) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
signal.removeEventListener("abort", cancel);
|
||||
if (component) void unmount(component).finally(() => target.remove());
|
||||
else target.remove();
|
||||
resolve(path);
|
||||
};
|
||||
const cancel = () => finish(null);
|
||||
try {
|
||||
component = mount(QuickOpen, { target, props: {
|
||||
onOpen: entry => finish(entry.rel_path),
|
||||
onClose: cancel,
|
||||
purpose: "Add workspace link",
|
||||
actionLabel: "insert link",
|
||||
} });
|
||||
} catch (error) { target.remove(); throw error; }
|
||||
signal.addEventListener("abort", cancel, { once: true });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type MarkdownIt from "markdown-it";
|
||||
import type { Token } from "markdown-it";
|
||||
type MarkdownParser = InstanceType<typeof MarkdownIt>;
|
||||
|
||||
type Footnote = { label: string; tokens: Token[]; number: number; references: number };
|
||||
export type FootnoteEnvironment = { noteFootnotes?: Map<string, Footnote>; urls?: Map<string, string> };
|
||||
|
||||
export function footnotes(markdown: MarkdownParser) {
|
||||
markdown.block.ruler.before("reference", "note_footnote_definition", (state, start, end, silent) => {
|
||||
if (state.sCount[start] - state.blkIndent >= 4) return false;
|
||||
const line = state.src.slice(state.bMarks[start] + state.tShift[start], state.eMarks[start]);
|
||||
const match = /^\[\^([^\]\s]+)\]:[ \t]*(.*)$/.exec(line);
|
||||
if (!match) return false;
|
||||
if (silent) return true;
|
||||
let next = start + 1;
|
||||
let body = match[2];
|
||||
while (next < end) {
|
||||
const text = state.src.slice(state.bMarks[next], state.eMarks[next]);
|
||||
if (/^(?: {4}|\t)/.test(text)) { body += "\n" + text.replace(/^(?: {4}|\t)/, ""); next++; }
|
||||
else if (!text.trim() && next + 1 < end && /^(?: {4}|\t)/.test(state.src.slice(state.bMarks[next + 1], state.eMarks[next + 1]))) { body += "\n"; next++; }
|
||||
else break;
|
||||
}
|
||||
const env = state.env as FootnoteEnvironment;
|
||||
const definitions = env.noteFootnotes ??= new Map();
|
||||
const tokens: Token[] = [];
|
||||
// Definitions are blocks. Their inline content is parsed after all labels exist.
|
||||
markdown.block.parse(body, markdown, state.env, tokens);
|
||||
if (!definitions.has(match[1])) definitions.set(match[1], { label: match[1], tokens, number: 0, references: 0 });
|
||||
const token = state.push("note_footnote_definition", "", 0);
|
||||
token.map = [start, next];
|
||||
state.line = next;
|
||||
return true;
|
||||
}, { alt: ["paragraph", "reference"] });
|
||||
|
||||
markdown.inline.ruler.before("image", "note_footnote_reference", (state, silent) => {
|
||||
if (state.linkLevel > 0) return false;
|
||||
const match = /^\[\^([^\]\s]+)\]/.exec(state.src.slice(state.pos));
|
||||
const definitions = (state.env as FootnoteEnvironment).noteFootnotes;
|
||||
const note = match && definitions?.get(match[1]);
|
||||
if (!match || !note) return false;
|
||||
if (!silent) {
|
||||
if (!note.number) note.number = Math.max(0, ...[...definitions!.values()].map(value => value.number)) + 1;
|
||||
const token = state.push("note_footnote_reference", "", 0);
|
||||
token.content = match[1];
|
||||
token.meta = { number: note.number, reference: ++note.references };
|
||||
}
|
||||
state.pos += match[0].length;
|
||||
return true;
|
||||
});
|
||||
markdown.core.ruler.after("inline", "note_footnote_content", state => {
|
||||
for (const note of (state.env as FootnoteEnvironment).noteFootnotes?.values() ?? []) {
|
||||
for (const token of note.tokens) {
|
||||
if (token.type === "inline") {
|
||||
token.children = [];
|
||||
markdown.inline.parse(token.content, markdown, state.env, token.children);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
markdown.renderer.rules.note_footnote_definition = () => "";
|
||||
markdown.renderer.rules.note_footnote_reference = (tokens, index) => {
|
||||
const { number, reference } = tokens[index].meta as { number: number; reference: number };
|
||||
return `<sup class="md-footnote-ref"><a href="#rs-fn-${number}" id="rs-fnref-${number}-${reference}" data-footnote-link aria-label="Footnote ${number}">${number}</a></sup>`;
|
||||
};
|
||||
}
|
||||
|
||||
export function renderFootnotes(markdown: MarkdownParser, env: FootnoteEnvironment): string {
|
||||
const notes = [...env.noteFootnotes?.values() ?? []].filter(note => note.number).sort((a, b) => a.number - b.number);
|
||||
if (!notes.length) return "";
|
||||
return '<section class="md-footnotes" aria-label="Footnotes"><ol>' + notes.map(note => {
|
||||
const backlinks = Array.from({ length: note.references }, (_, index) => `<a href="#rs-fnref-${note.number}-${index + 1}" class="md-footnote-back" data-footnote-link aria-label="Back to reference ${note.number}${index ? `, occurrence ${index + 1}` : ""}" title="Back to reference">↩</a>`).join(" ");
|
||||
return `<li id="rs-fn-${note.number}" tabindex="-1">${markdown.renderer.render(note.tokens, markdown.options, env)} ${backlinks}</li>`;
|
||||
}).join("") + "</ol></section>";
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
.rs-foldable-heading { position: relative; }
|
||||
.reading .rs-foldable-heading { padding-inline-start: 4px; }
|
||||
.reading .rs-heading-toggle { inset-inline-start: -24px; }
|
||||
.live-writer .rs-heading-toggle { top: .7em; }
|
||||
.rs-heading-toggle { position: absolute; inset-inline-start: -30px; top: 0; width: 28px; height: 28px; padding: 6px; border: 0; border-radius: var(--rs-control-radius); color: var(--rs-text-dim); background: transparent; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; vertical-align: middle; }
|
||||
.rs-heading-toggle:hover, .rs-heading-toggle:focus-visible { color: var(--rs-text); background: var(--rs-bg-active); }
|
||||
.rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 1px; }
|
||||
.rs-heading-toggle svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.rs-heading-toggle[aria-expanded="true"] svg { transform: rotate(90deg); }
|
||||
.rs-heading-tooltip { display: none; position: absolute; z-index: 5; top: 100%; inset-inline-start: 0; max-width: 240px; width: max-content; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: 12px/1.5 var(--rs-font-ui); white-space: normal; pointer-events: none; }
|
||||
.rs-heading-toggle:hover .rs-heading-tooltip, .rs-heading-toggle:focus-visible .rs-heading-tooltip { display: block; }
|
||||
.rs-heading-collapsed::after { content: " …"; color: var(--rs-text-dim); font-weight: normal; }
|
||||
.live-writer .cm-foldPlaceholder { border: none; background: transparent; color: var(--rs-text-dim); cursor: pointer; padding: 0 .3em; }
|
||||
.reading [hidden] { display: none !important; }
|
||||
.reading .md-footnote-ref, .live-writer .writer-footnote-ref { font-size: .75em; vertical-align: super; line-height: 0; }
|
||||
.live-writer .writer-footnote-definition { color: var(--rs-text-dim); font-size: .85em; }
|
||||
.reading .md-footnotes { margin-top: 2em; padding-top: 1em; border-top: 1px solid var(--rs-border); font-size: .9em; }
|
||||
.reading .md-footnotes li { padding-inline-start: .3em; }
|
||||
.reading .md-footnotes li > p:last-of-type { display: inline; }
|
||||
.reading .md-footnote-back { margin-inline-start: .4em; }
|
||||
.reading .md-footnote-ref a:focus-visible, .reading .md-footnote-back:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 3px; border-radius: var(--rs-control-radius); }
|
||||
@@ -0,0 +1,143 @@
|
||||
import { StateField, type EditorState, type Range } from "@codemirror/state";
|
||||
import { Decoration, EditorView, WidgetType, keymap } from "@codemirror/view";
|
||||
import { codeFolding, foldEffect, foldKeymap, foldedRanges, foldService, syntaxTree, unfoldEffect } from "@codemirror/language";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
|
||||
export type HeadingRange = { start: number; from: number; to: number; level: number; label: string };
|
||||
|
||||
export function headingRanges(state: EditorState): HeadingRange[] {
|
||||
const headings: HeadingRange[] = [];
|
||||
syntaxTree(state).iterate({ enter(node) {
|
||||
if (/^(?:FencedCode|CodeBlock|Blockquote|ListItem)$/.test(node.name)) return false;
|
||||
const match = /^(?:ATX|Setext)Heading([1-6])$/.exec(node.name);
|
||||
if (!match) return;
|
||||
const line = state.doc.lineAt(node.from);
|
||||
headings.push({ start: line.from, from: node.to, to: state.doc.length, level: Number(match[1]), label: line.text.replace(/^\s*#+\s*/, "").replace(/\s+#+\s*$/, "") });
|
||||
return false;
|
||||
} });
|
||||
headings.forEach((heading, index) => {
|
||||
const next = headings.slice(index + 1).find(other => other.level <= heading.level);
|
||||
heading.to = next ? Math.max(heading.from, next.start - 1) : state.doc.length;
|
||||
});
|
||||
return headings.filter(heading => state.sliceDoc(heading.from, heading.to).trim().length > 0);
|
||||
}
|
||||
|
||||
export function headingButton(label: string, collapsed: boolean): HTMLButtonElement {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "rs-heading-toggle";
|
||||
button.setAttribute("aria-expanded", String(!collapsed));
|
||||
const title = `${collapsed ? "Expand" : "Collapse"} ${label || "heading"}`;
|
||||
button.setAttribute("aria-label", title);
|
||||
button.title = title;
|
||||
const icon = actionIcon("chevron");
|
||||
const tooltip = document.createElement("span");
|
||||
tooltip.className = "rs-heading-tooltip";
|
||||
tooltip.textContent = title;
|
||||
button.append(icon, tooltip);
|
||||
return button;
|
||||
}
|
||||
|
||||
class HeadingToggle extends WidgetType {
|
||||
constructor(readonly heading: HeadingRange, readonly collapsed: boolean) { super(); }
|
||||
eq(other: HeadingToggle) { return this.heading.from === other.heading.from && this.heading.to === other.heading.to && this.heading.label === other.heading.label && this.collapsed === other.collapsed; }
|
||||
toDOM(view: EditorView) {
|
||||
const button = headingButton(this.heading.label, this.collapsed);
|
||||
button.dataset.headingStart = String(this.heading.start);
|
||||
button.onmousedown = event => event.preventDefault();
|
||||
button.onclick = event => {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const restoreFocus = document.activeElement === button;
|
||||
const { from, to } = this.heading;
|
||||
const selection = !this.collapsed && view.state.selection.ranges.some(range => range.to > from && range.from <= to) ? { anchor: from } : undefined;
|
||||
view.dispatch({ effects: (this.collapsed ? unfoldEffect : foldEffect).of({ from, to }), selection });
|
||||
if (restoreFocus) view.dom.querySelector<HTMLButtonElement>(`[data-heading-start="${this.heading.start}"]`)?.focus({ preventScroll: true });
|
||||
};
|
||||
return button;
|
||||
}
|
||||
ignoreEvent() { return true; }
|
||||
}
|
||||
|
||||
export const headingFolding = [
|
||||
codeFolding({ placeholderText: "…" }),
|
||||
keymap.of(foldKeymap),
|
||||
foldService.of((state, start) => {
|
||||
const heading = headingRanges(state).find(heading => heading.start === start);
|
||||
return heading ? { from: heading.from, to: heading.to } : null;
|
||||
}),
|
||||
StateField.define({
|
||||
create: decorations,
|
||||
update(value, transaction) {
|
||||
return transaction.docChanged || transaction.effects.some(effect => effect.is(foldEffect) || effect.is(unfoldEffect)) || syntaxTree(transaction.state) !== syntaxTree(transaction.startState)
|
||||
? decorations(transaction.state) : value;
|
||||
},
|
||||
provide: field => EditorView.decorations.from(field),
|
||||
}),
|
||||
];
|
||||
|
||||
function decorations(state: EditorState) {
|
||||
const ranges: Range<Decoration>[] = [];
|
||||
const folds = foldedRanges(state);
|
||||
for (const heading of headingRanges(state)) {
|
||||
let collapsed = false, hidden = false;
|
||||
folds.between(0, state.doc.length, (from, to) => {
|
||||
if (from === heading.from) collapsed = true;
|
||||
if (from < heading.start && to >= heading.start) hidden = true;
|
||||
});
|
||||
if (!hidden) ranges.push(Decoration.widget({ widget: new HeadingToggle(heading, collapsed), side: -1 }).range(heading.start));
|
||||
}
|
||||
return Decoration.set(ranges, true);
|
||||
}
|
||||
|
||||
export function readerHeadingFolding(root: HTMLElement, collapsed: Set<string>) {
|
||||
const elements = [...root.children].filter(element => !element.classList.contains("document-title")) as HTMLElement[];
|
||||
const headings = elements.flatMap((element, index) => {
|
||||
const heading = /^H[1-6]$/.test(element.tagName) ? element : element.querySelector<HTMLElement>(":scope > h1, :scope > h2, :scope > h3, :scope > h4, :scope > h5, :scope > h6");
|
||||
return heading ? [{ element, heading, index, level: Number(heading.tagName.slice(1)), label: heading.textContent || "heading", key: `${index}:${heading.textContent}` }] : [];
|
||||
});
|
||||
function apply() {
|
||||
elements.forEach(element => { element.hidden = false; });
|
||||
headings.forEach(item => {
|
||||
const button = item.heading.querySelector<HTMLButtonElement>(".rs-heading-toggle");
|
||||
if (button) {
|
||||
const label = `${collapsed.has(item.key) ? "Expand" : "Collapse"} ${item.label}`;
|
||||
button.setAttribute("aria-expanded", String(!collapsed.has(item.key)));
|
||||
button.setAttribute("aria-label", label);
|
||||
button.title = label;
|
||||
button.querySelector(".rs-heading-tooltip")!.textContent = label;
|
||||
item.heading.classList.toggle("rs-heading-collapsed", collapsed.has(item.key));
|
||||
}
|
||||
if (!collapsed.has(item.key)) return;
|
||||
const next = headings.find(other => other.index > item.index && other.level <= item.level);
|
||||
for (let index = item.index + 1; index < (next?.index ?? elements.length); index++) elements[index].hidden = true;
|
||||
});
|
||||
}
|
||||
for (const item of headings) {
|
||||
const next = headings.find(other => other.index > item.index && other.level <= item.level);
|
||||
if ((next?.index ?? elements.length) <= item.index + 1) continue;
|
||||
const button = headingButton(item.label, collapsed.has(item.key));
|
||||
button.onclick = event => {
|
||||
event.stopPropagation();
|
||||
if (collapsed.has(item.key)) collapsed.delete(item.key); else collapsed.add(item.key);
|
||||
apply();
|
||||
};
|
||||
item.heading.classList.add("rs-foldable-heading");
|
||||
item.heading.prepend(button);
|
||||
}
|
||||
apply();
|
||||
return {
|
||||
reveal(target: HTMLElement) {
|
||||
const index = elements.findIndex(element => element === target || element.contains(target));
|
||||
if (index < 0) return;
|
||||
for (const item of headings) {
|
||||
const next = headings.find(other => other.index > item.index && other.level <= item.level);
|
||||
if (item.index < index && (next?.index ?? elements.length) > index) collapsed.delete(item.key);
|
||||
}
|
||||
apply();
|
||||
},
|
||||
destroy() {
|
||||
elements.forEach(element => { element.hidden = false; });
|
||||
headings.forEach(item => { item.heading.querySelector(".rs-heading-toggle")?.remove(); item.heading.classList.remove("rs-foldable-heading", "rs-heading-collapsed"); });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { replacement, type TextSelection } from "./markdownCommands.ts";
|
||||
|
||||
export function externalLinkText(source: string, selection: TextSelection) {
|
||||
const label = source.slice(selection.from, selection.to).replace(/[\\[\]]/g, "\\$&").replace(/\r?\n/g, " ");
|
||||
// Select the empty URL when a label exists. Otherwise start in the label.
|
||||
const cursor = label ? label.length + 3 : 1;
|
||||
return replacement(selection, `[${label}]()`, cursor, cursor);
|
||||
}
|
||||
|
||||
export function workspaceLinkText(source: string, selection: TextSelection, path: string) {
|
||||
const label = source.slice(selection.from, selection.to).replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim();
|
||||
// Root paths avoid a same-name note in the current folder. Encode syntax characters.
|
||||
const target = "/" + path.replaceAll("\\", "/").replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
|
||||
return replacement(selection, `[[${target}${label ? "|" + label : ""}]]`);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
|
||||
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
|
||||
import { renderMarkdownSections } from "../workspace/noteHtml";
|
||||
import { renderDiagrams } from "../workspace/diagrams";
|
||||
import { tableControls, tableEditors } from "./tableControls";
|
||||
@@ -139,10 +139,12 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
const active = state.selection.ranges.map(range => ({ from: state.doc.lineAt(range.from).from, to: state.doc.lineAt(range.to).to }));
|
||||
const selected = (from: number, to: number) => active.some(range => range.from <= to && range.to >= from);
|
||||
const hiddenBlocks: { from: number; to: number }[] = [];
|
||||
foldedRanges(state).between(0, state.doc.length, (from, to) => { hiddenBlocks.push({ from, to }); });
|
||||
const source = state.doc.toString();
|
||||
const editing = state.field(imageSource);
|
||||
const imageNodes = imageSourceRanges(source);
|
||||
for (const section of renderMarkdownSections(source, urls)) {
|
||||
if (hiddenBlocks.some(block => block.from <= section.start && block.to >= section.end - 1)) continue;
|
||||
if (!/(?:<pre|<table|<img|md-properties|md-callout|missing-image)/.test(section.html)) continue;
|
||||
// Code remains a real editor surface. A preview swap loses the first drag
|
||||
// and changes block height when focus or the selection moves elsewhere.
|
||||
@@ -199,17 +201,19 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
const fenced = node.name === "FencedCode";
|
||||
const closed = fenced && /^\s*(`{3,}|~{3,})\s*$/.test(last.text) && last.number > first.number;
|
||||
const code = fenced ? source.slice(Math.min(first.to + 1, node.to), closed ? last.from : node.to) : source.slice(node.from, node.to);
|
||||
ranges.push(Decoration.widget({ widget: new CodeCopy(code), side: 1 }).range(first.to));
|
||||
const editingCode = selected(node.from, node.to);
|
||||
if (!editingCode) ranges.push(Decoration.widget({ widget: new CodeCopy(code), side: 1 }).range(first.to));
|
||||
for (let number = first.number; number <= last.number; number++) {
|
||||
const line = state.doc.line(number);
|
||||
ranges.push(Decoration.line({ class: `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
|
||||
ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const line = state.doc.lineAt(node.from);
|
||||
if (/^ATXHeading[1-6]$/.test(node.name)) {
|
||||
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name)) {
|
||||
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
|
||||
}
|
||||
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
|
||||
if (selected(node.from, node.to)) return;
|
||||
if (node.name === "HorizontalRule") {
|
||||
ranges.push(Decoration.line({ class: "writer-divider-line" }).range(line.from));
|
||||
@@ -244,6 +248,12 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed");
|
||||
}
|
||||
} });
|
||||
for (const match of source.matchAll(/\[\^([^\]\s]+)\](:)?/g)) {
|
||||
const from = match.index, to = from + match[0].length;
|
||||
if (hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue;
|
||||
if (source[from - 1] === "\\") continue;
|
||||
mark(from, to, match[2] && state.doc.lineAt(from).from === from ? "writer-footnote-definition" : "writer-footnote-ref");
|
||||
}
|
||||
for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) {
|
||||
const from = match.index, to = from + match[0].length;
|
||||
if (selected(from, to) || hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue;
|
||||
@@ -260,7 +270,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
update(value, transaction) {
|
||||
return transaction.docChanged || transaction.selection
|
||||
|| syntaxTree(transaction.startState) !== syntaxTree(transaction.state)
|
||||
|| transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource))
|
||||
|| transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource) || effect.is(foldEffect) || effect.is(unfoldEffect))
|
||||
? build(transaction.state, value.map(transaction.changes)) : value;
|
||||
},
|
||||
provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field).update({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import { requestText } from "../workspace/dialogs.svelte";
|
||||
import { pickLinkDocument } from "./documentPicker";
|
||||
import { externalLinkText, workspaceLinkText } from "./linkCommands";
|
||||
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";
|
||||
@@ -15,6 +16,7 @@ export type MarkdownMenuEditor = {
|
||||
// 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;
|
||||
const pending = new AbortController();
|
||||
function close(focus = true) {
|
||||
root?.remove(); root = undefined;
|
||||
if (focus && !destroyed) editor.focus();
|
||||
@@ -41,21 +43,11 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
|
||||
finally { if (valid()) editor.focus(); }
|
||||
}
|
||||
function link(external: boolean) {
|
||||
if (external) { apply(externalLinkText(source, selection)); return; }
|
||||
void request(async () => {
|
||||
const target = (await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text))?.trim();
|
||||
const target = await pickLinkDocument(pending.signal);
|
||||
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 : ""}]]`));
|
||||
}
|
||||
apply(workspaceLinkText(source, selection, target));
|
||||
});
|
||||
}
|
||||
function clipboard(kind: "cut" | "copy" | "paste" | "plain") {
|
||||
@@ -114,7 +106,7 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
|
||||
root = actionMenu(x, y, items, close, "Markdown text actions");
|
||||
}
|
||||
return { open, close, destroy() {
|
||||
destroyed = true; close(false);
|
||||
destroyed = true; pending.abort(); close(false);
|
||||
document.removeEventListener("mousedown", outside, true);
|
||||
document.removeEventListener("scroll", scroll, true);
|
||||
window.removeEventListener("resize", resize);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import type { ActionIcon } from "../ui/actionIcons";
|
||||
import { spellingWord } from "./spellingWord";
|
||||
|
||||
/** WebView2 owns spelling suggestions and applies corrections to the original word. */
|
||||
export function isSpellingTarget(target: EventTarget | null): boolean {
|
||||
@@ -22,7 +23,7 @@ export type NativeSpellingItem = {
|
||||
id: number; name: string; label: string; shortcut: string; kind: number;
|
||||
enabled: boolean; checked: boolean; children: NativeSpellingItem[];
|
||||
};
|
||||
type NativeMenu = { request: string; items: NativeSpellingItem[] };
|
||||
type NativeMenu = { request: string; items: NativeSpellingItem[]; fallback_spelling?: boolean };
|
||||
const icons: Record<string, ActionIcon> = {
|
||||
undo: "undo", redo: "redo",
|
||||
cut: "cut", copy: "copy", paste: "paste", pasteAndMatchStyle: "paste-text",
|
||||
@@ -48,7 +49,8 @@ export function spellingItems(items: NativeSpellingItem[], select: (id: number)
|
||||
export function mountSpellingMenu(): () => void {
|
||||
if (!isTauri()) return () => {};
|
||||
let disposed = false, unlisten: (() => void) | undefined;
|
||||
let context: { target: HTMLElement; x: number; y: number } | undefined;
|
||||
let context: { target: HTMLElement; x: number; y: number; word: ReturnType<typeof spellingWord> } | undefined;
|
||||
let revision = 0;
|
||||
let active: { request: string; root: HTMLElement; target: HTMLElement } | undefined;
|
||||
const finish = (command: number | null = null, restoreFocus = false) => {
|
||||
if (!active) return;
|
||||
@@ -59,30 +61,57 @@ export function mountSpellingMenu(): () => void {
|
||||
void invoke("spelling_menu_select", { request, command }).catch(error => console.error("Cannot close the spelling menu", error));
|
||||
};
|
||||
const remember = (event: MouseEvent) => {
|
||||
revision++;
|
||||
finish();
|
||||
if (event.defaultPrevented || !isSpellingTarget(event.target)) { context = undefined; return; }
|
||||
const target = (event.target as HTMLElement).closest<HTMLElement>('[contenteditable="true"], textarea, input')!;
|
||||
const bounds = document.getSelection()?.rangeCount ? document.getSelection()!.getRangeAt(0).getBoundingClientRect() : target.getBoundingClientRect();
|
||||
context = { target, x: event.clientX || bounds.left, y: event.clientY || bounds.bottom };
|
||||
context = { target, x: event.clientX || bounds.left, y: event.clientY || bounds.bottom, word: spellingWord(target, event.clientX, event.clientY) };
|
||||
};
|
||||
const outside = (event: PointerEvent) => { if (active && !active.root.contains(event.target as Node)) finish(); };
|
||||
const scroll = (event: Event) => { if (active && !active.root.contains(event.target as Node)) finish(); };
|
||||
const cancel = () => finish();
|
||||
const outside = (event: PointerEvent) => { if (!active?.root.contains(event.target as Node)) { revision++; finish(); } };
|
||||
const scroll = (event: Event) => { if (!active?.root.contains(event.target as Node)) { revision++; finish(); } };
|
||||
const cancel = () => { revision++; finish(); };
|
||||
window.addEventListener("contextmenu", remember);
|
||||
window.addEventListener("pointerdown", outside);
|
||||
window.addEventListener("resize", cancel);
|
||||
window.addEventListener("blur", cancel);
|
||||
window.addEventListener("pagehide", cancel);
|
||||
document.addEventListener("scroll", scroll, true);
|
||||
void listen<NativeMenu>("spelling-menu", ({ payload }) => {
|
||||
document.addEventListener("input", cancel, true);
|
||||
void listen<NativeMenu>("spelling-menu", async ({ payload }) => {
|
||||
finish();
|
||||
if (disposed || !context?.target.isConnected) {
|
||||
void invoke("spelling_menu_select", { request: payload.request, command: null, fallback: true });
|
||||
return;
|
||||
}
|
||||
const { target, x, y } = context;
|
||||
const { target, x, y, word } = context;
|
||||
const requestRevision = ++revision;
|
||||
let items = spellingItems(payload.items, id => finish(id, true));
|
||||
if (payload.fallback_spelling) {
|
||||
const readable = (entries: NativeSpellingItem[]): NativeSpellingItem[] => entries.filter(item => item.kind === 3 || item.label.trim()).map(item => ({ ...item, children: readable(item.children) }));
|
||||
items = spellingItems(readable(payload.items), id => finish(id, true));
|
||||
if (word) {
|
||||
const languages = [...new Set([target.lang, document.documentElement.lang, ...navigator.languages].filter(Boolean))];
|
||||
try {
|
||||
const result = await invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages });
|
||||
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => { finish(); word.replace(value); } }));
|
||||
if (result.misspelled && !suggestions.length) suggestions.push({ label: "No spelling suggestions", disabled: true });
|
||||
if (result.misspelled) suggestions.push({ label: "Add to dictionary", icon: "book", run: () => {
|
||||
finish(null, true);
|
||||
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(error => console.error("Could not add the word", error));
|
||||
} }, { separator: true });
|
||||
items = [...suggestions, ...items];
|
||||
} catch {
|
||||
items = [{ label: "Spelling suggestions unavailable", disabled: true }, { separator: true }, ...items];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (disposed || requestRevision !== revision || !target.isConnected || (payload.fallback_spelling && word && !word.valid())) {
|
||||
void invoke("spelling_menu_select", { request: payload.request, command: null });
|
||||
return;
|
||||
}
|
||||
const parent = target.closest<HTMLDialogElement>("dialog[open]") ?? document.body;
|
||||
const root = actionMenu(x, y, spellingItems(payload.items, id => finish(id, true)), () => finish(null, true), "Spelling actions", parent);
|
||||
const root = actionMenu(x, y, items, () => finish(null, true), "Spelling actions", parent);
|
||||
active = { request: payload.request, root, target };
|
||||
}).then(async stop => {
|
||||
if (disposed) { stop(); return; }
|
||||
@@ -100,5 +129,6 @@ export function mountSpellingMenu(): () => void {
|
||||
window.removeEventListener("blur", cancel);
|
||||
window.removeEventListener("pagehide", cancel);
|
||||
document.removeEventListener("scroll", scroll, true);
|
||||
document.removeEventListener("input", cancel, true);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
export function wordAt(text: string, offset: number) {
|
||||
for (const match of text.matchAll(/[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*/gu)) {
|
||||
if (match.index <= offset && match.index + match[0].length >= offset) {
|
||||
return { word: match[0], from: match.index, to: match.index + match[0].length };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type WordTarget = { word: string; replace(value: string): void; valid(): boolean };
|
||||
|
||||
export function spellingWord(target: HTMLElement, x: number, y: number): WordTarget | null {
|
||||
const control = target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement;
|
||||
if (control) {
|
||||
const original = target.value;
|
||||
let offset = target.selectionStart ?? 0;
|
||||
// A transparent mirror resolves the pointer position in wrapped and scrolled inputs.
|
||||
if (x || y) {
|
||||
const box = target.getBoundingClientRect(), css = getComputedStyle(target);
|
||||
const mirror = document.createElement("div");
|
||||
for (const key of Array.from(css)) mirror.style.setProperty(key, css.getPropertyValue(key));
|
||||
Object.assign(mirror.style, { position: "fixed", left: `${box.left}px`, top: `${box.top}px`, width: `${box.width}px`, height: `${box.height}px`, margin: "0", opacity: "0", zIndex: "2147483647", pointerEvents: "auto", overflow: "hidden", whiteSpace: target instanceof HTMLInputElement ? "pre" : "pre-wrap", overflowWrap: "break-word" });
|
||||
mirror.textContent = original || " ";
|
||||
(target.closest("dialog[open]") ?? document.body).append(mirror);
|
||||
mirror.scrollTop = target.scrollTop; mirror.scrollLeft = target.scrollLeft;
|
||||
const hit = document.caretRangeFromPoint(x, y);
|
||||
if (hit?.startContainer === mirror.firstChild) offset = hit.startOffset;
|
||||
mirror.remove();
|
||||
}
|
||||
const found = wordAt(original, offset);
|
||||
if (!found) return null;
|
||||
const valid = () => target.isConnected && target.value === original && !target.disabled && !target.readOnly;
|
||||
return { word: found.word, valid, replace(value) {
|
||||
if (!valid()) return;
|
||||
target.focus({ preventScroll: true }); target.setSelectionRange(found.from, found.to);
|
||||
if (!document.execCommand("insertText", false, value)) {
|
||||
target.setRangeText(value, found.from, found.to, "end");
|
||||
target.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertReplacementText", data: value }));
|
||||
}
|
||||
} };
|
||||
}
|
||||
const range = x || y ? document.caretRangeFromPoint(x, y) : document.getSelection()?.rangeCount ? document.getSelection()!.getRangeAt(0).cloneRange() : null;
|
||||
if (!range || range.startContainer.nodeType !== Node.TEXT_NODE || !target.contains(range.startContainer)) return null;
|
||||
const node = range.startContainer, original = node.textContent ?? "";
|
||||
const found = wordAt(original, range.startOffset);
|
||||
if (!found) return null;
|
||||
range.setStart(node, found.from); range.setEnd(node, found.to);
|
||||
const valid = () => node.isConnected && target.isConnected && node.textContent === original;
|
||||
return { word: found.word, valid, replace(value) {
|
||||
if (!valid()) return;
|
||||
target.focus({ preventScroll: true });
|
||||
document.getSelection()?.removeAllRanges(); document.getSelection()?.addRange(range);
|
||||
document.execCommand("insertText", false, value);
|
||||
} };
|
||||
}
|
||||
@@ -59,6 +59,12 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
else view.focus();
|
||||
}
|
||||
const clearCells = () => apply((text, selected) => mapTableCells(text, selected, () => ""));
|
||||
const deleteCells = () => {
|
||||
if (!range) return;
|
||||
const { top, left } = bounds(range);
|
||||
const next = { row: top, column: left };
|
||||
apply(deleteTableCells, { anchor: next, head: next });
|
||||
};
|
||||
const format = (kind: CellFormat) => apply((text, selected) => formatTableCells(text, selected, kind));
|
||||
async function clipboard(action: "copy" | "cut" | "paste") {
|
||||
if (!range) return;
|
||||
@@ -112,9 +118,10 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
sep,
|
||||
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, run: () => format(kind) })) },
|
||||
...alignmentItems,
|
||||
sep, { label: "Clear cells", icon: "clear", run: clearCells },
|
||||
{ label: "Delete cells", icon: "trash", run: () => apply(deleteTableCells), title: "Remove selected rows/columns; otherwise shift cells left" },
|
||||
sep, { label: "Clear cells", icon: "clear", run: clearCells, title: "Clear selected values and keep the cells." },
|
||||
{ label: "Delete cells", icon: "trash", run: deleteCells, title: "Delete or Backspace removes full rows or columns. Other selections shift cells left." },
|
||||
];
|
||||
if (textEditor) items.push(sep, { label: "Select cell", icon: "select", title: "Select this cell, then use Shift+arrow keys to extend the selection", run: () => { closeMenu(); select(cellRange); } });
|
||||
items.push(sep,
|
||||
{ label: "Row", icon: "row", children: [
|
||||
{ label: "Add row above", icon: "row-before", disabled: row === 0, title: row === 0 ? "The first row is the Markdown header" : undefined, run: () => structural("row", "before") },
|
||||
@@ -191,7 +198,16 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
document.addEventListener("scroll", event => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }, { ...options, capture: true });
|
||||
window.addEventListener("resize", closeMenu, options);
|
||||
wrapper.addEventListener("keydown", event => {
|
||||
if (!range) return;
|
||||
if (event.isComposing) return;
|
||||
if (!range) {
|
||||
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
|
||||
const cell = cellAt(event.target);
|
||||
if (!cell) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const rect = cell.getBoundingClientRect();
|
||||
showMenu(rect.left, rect.bottom, point(cell), rich.get());
|
||||
return;
|
||||
}
|
||||
const mod = event.ctrlKey || event.metaKey, key = event.key.toLowerCase();
|
||||
const handled = ["Escape", "Delete", "Backspace", "Enter", "ContextMenu", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key) || (event.shiftKey && event.key === "F10") || (mod && ["b", "i", "z", "y", "a"].includes(key));
|
||||
if (!handled) return;
|
||||
@@ -200,7 +216,7 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
else if (mod && key === "a") select({ anchor: { row: 0, column: 0 }, head: { row: table.rows.length - 1, column: table.rows[0].cells.length - 1 } });
|
||||
else if (mod && ["b", "i"].includes(key)) format(key === "b" ? "bold" : "italic");
|
||||
else if (event.key === "Escape") { clear(); view.focus(); }
|
||||
else if (event.key === "Delete" || event.key === "Backspace") clearCells();
|
||||
else if (event.key === "Delete" || event.key === "Backspace") deleteCells();
|
||||
else if (event.key === "Enter") { const target = table.rows[range.head.row].cells[range.head.column]; clear(); target.focus(); }
|
||||
else if (event.key === "ContextMenu" || event.key === "F10") { const rect = table.rows[range.head.row].cells[range.head.column].getBoundingClientRect(); showMenu(rect.left, rect.bottom); }
|
||||
else {
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { isImagePath, workspaceImageLink } from "../workspace/media.ts";
|
||||
|
||||
export function workspaceFileLink(notePath: string, filePath: string): string {
|
||||
const image = workspaceImageLink(notePath, filePath);
|
||||
if (isImagePath(filePath)) return image;
|
||||
const label = (filePath.replaceAll("\\", "/").split("/").pop() || filePath).replace(/[\\[\]]/g, "\\$&");
|
||||
return `[${label}]${image.slice(3)}`;
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import { isImagePath } from "../workspace/media";
|
||||
|
||||
type Point = { x: number; y: number };
|
||||
const targets = new Map<HTMLElement, (path: string, point: Point) => void>();
|
||||
let highlighted: HTMLElement | undefined;
|
||||
@@ -8,7 +6,7 @@ export function registerImageDropTarget(element: HTMLElement, drop: (path: strin
|
||||
return () => { targets.delete(element); element.classList.remove("image-drop-target"); };
|
||||
}
|
||||
function targetAt(path: string, point: Point) {
|
||||
if (!isImagePath(path)) return;
|
||||
if (!path || path.endsWith("/")) return;
|
||||
const hit = document.elementFromPoint(point.x, point.y);
|
||||
return [...targets].find(([element]) => element.isConnected && hit && element.contains(hit));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user