Improve editor, plugin updates, and window transfers for 0.1.41
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
<script lang="ts">
|
||||
import FindPanel from "./FindPanel.svelte";
|
||||
import { monacoSearch } from "./monacoSearch";
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import { t } from "$lib/i18n";
|
||||
import { untrack } from "svelte";
|
||||
import { tick, untrack } from "svelte";
|
||||
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
|
||||
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
|
||||
import { registerImageDropTarget } from "./workspaceImageDrop";
|
||||
@@ -34,6 +37,24 @@
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
|
||||
export function focus() { editor?.focus(); }
|
||||
let search = $state.raw<ReturnType<typeof monacoSearch>>();
|
||||
let findOpen = $state(false);
|
||||
let findPanel = $state<FindPanel>();
|
||||
export async function openFind(replace = false) {
|
||||
if (!search || !editor) return;
|
||||
const selection = editor.getSelection();
|
||||
const text = selection && editor.getModel()?.getValueInRange(selection);
|
||||
if (text && !text.includes("\n") && !text.includes("\r")) {
|
||||
search.target.setQuery(new SearchQuery({ ...search.target.query, search: text }));
|
||||
findPanel?.sync(search.target.query);
|
||||
}
|
||||
findOpen = true;
|
||||
search.refresh();
|
||||
await tick();
|
||||
findPanel?.focus(replace);
|
||||
}
|
||||
export function closeFind() { if (findOpen) search?.target.close(); }
|
||||
export function nextMatch(backward = false) { if (findOpen) search?.target.next(backward); else void openFind(); }
|
||||
let ready = $state(0);
|
||||
let applying = false;
|
||||
let loadError = $state<string | null>(null);
|
||||
@@ -125,6 +146,12 @@
|
||||
...monacoChrome(mode),
|
||||
});
|
||||
editor = view;
|
||||
search = monacoSearch(monaco, view, () => { findOpen = false; });
|
||||
for (const [id, label, replace] of [["actions.find", "Find", false], ["editor.action.startFindReplaceAction", "Replace", true]] as const) {
|
||||
listeners.push(view.addAction({ id, label, keybindings: [monaco.KeyMod.CtrlCmd | (replace ? monaco.KeyCode.KeyH : monaco.KeyCode.KeyF)], run: () => openFind(replace) }));
|
||||
}
|
||||
listeners.push(view.addAction({ id: "editor.action.nextMatchFindAction", label: "Next match", keybindings: [monaco.KeyCode.F3], run: () => nextMatch() }));
|
||||
listeners.push(view.addAction({ id: "editor.action.previousMatchFindAction", label: "Previous match", keybindings: [monaco.KeyMod.Shift | monaco.KeyCode.F3], run: () => nextMatch(true) }));
|
||||
const linkPath = `/${encodeURIComponent(untrack(() => buffer.id))}/`;
|
||||
if (markdown) listeners.push(monaco.languages.registerLinkProvider("markdown", {
|
||||
provideLinks(candidate) {
|
||||
@@ -230,6 +257,9 @@
|
||||
menu?.destroy();
|
||||
releaseDrop?.();
|
||||
listeners.forEach(listener => listener.dispose());
|
||||
search?.dispose();
|
||||
search = undefined;
|
||||
findOpen = false;
|
||||
view?.dispose();
|
||||
if (session) releaseEditorSession(session);
|
||||
editor = undefined;
|
||||
@@ -273,6 +303,8 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="source-editor">
|
||||
{#if findOpen && search}<FindPanel bind:this={findPanel} target={search.target} />{/if}
|
||||
<div
|
||||
class="monaco-host"
|
||||
role="application"
|
||||
@@ -291,14 +323,14 @@
|
||||
void takeImages(event, event.clipboardData);
|
||||
}}
|
||||
></div>
|
||||
</div>
|
||||
{#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>{$t("Dismiss")}</button></p>{/if}
|
||||
|
||||
<style>
|
||||
.monaco-host {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.source-editor { position: absolute; inset: 0; display: flex; flex-direction: column; min-width: 0; }
|
||||
.source-editor :global(.rs-find-bar) { flex-shrink: 0; border-bottom: 1px solid var(--rs-border); }
|
||||
.monaco-host { position: relative; flex: 1; min-height: 0; overflow: hidden; }
|
||||
.monaco-host :global(.rs-source-search-match) { background: var(--rs-item-selection-bg); outline: 1px solid var(--rs-accent); }
|
||||
|
||||
.monaco-host :global(.monaco-editor),
|
||||
.monaco-host :global(.overflow-guard) {
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { untrack } from "svelte";
|
||||
import { runScopeHandlers, type EditorView } from "@codemirror/view";
|
||||
import { SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, selectMatches, setSearchQuery } from "@codemirror/search";
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import type { FindTarget } from "./findTarget";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import "$lib/ui/find.css";
|
||||
|
||||
let { view }: { view: EditorView } = $props();
|
||||
const initialQuery = untrack(() => getSearchQuery(view.state));
|
||||
let { target }: { target: FindTarget } = $props();
|
||||
const initialQuery = untrack(() => target.query);
|
||||
let searchInput: HTMLInputElement;
|
||||
let replaceInput = $state<HTMLInputElement>();
|
||||
export function focus(replace = false) { (replace ? replaceInput : searchInput)?.select(); }
|
||||
let query = $state.raw(initialQuery);
|
||||
let searchText = $state(initialQuery.search);
|
||||
let replacement = $state(initialQuery.replace);
|
||||
@@ -28,18 +31,23 @@
|
||||
|
||||
function commit() {
|
||||
query = new SearchQuery({ search: searchText, replace: replacement, caseSensitive, regexp, wholeWord });
|
||||
view.dispatch({ effects: setSearchQuery.of(query) });
|
||||
target.setQuery(query);
|
||||
}
|
||||
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (runScopeHandlers(view, event, "search-panel")) {
|
||||
if (target.keydown?.(event)) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
} else if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
target.close();
|
||||
} else if (event.key === "Enter" && event.target instanceof HTMLInputElement && event.target.type === "text") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
commit();
|
||||
if (event.target.name === "replace") replaceNext(view);
|
||||
else (event.shiftKey ? findPrevious : findNext)(view);
|
||||
if (event.target.name === "replace") target.replace();
|
||||
else target.next(event.shiftKey);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -49,14 +57,14 @@
|
||||
<div class="rs-find-row">
|
||||
<div class="rs-find-field">
|
||||
<Icon icon="search" />
|
||||
<input type="text" name="search" {...{ "main-field": "true" }} aria-label={$t("Find in document")} placeholder={$t("Find in document")}
|
||||
<input bind:this={searchInput} type="text" name="search" autocomplete="off" {...{ "main-field": "true" }} aria-label={$t("Find in document")} placeholder={$t("Find in document")}
|
||||
aria-invalid={searchText !== "" && !query.valid} bind:value={() => searchText, value => { searchText = value; commit(); }} />
|
||||
</div>
|
||||
<div class="rs-find-actions">
|
||||
<IconButton icon="up" label={$t("Previous match (Shift+Enter)")} onclick={() => findPrevious(view)} disabled={!query.valid} />
|
||||
<IconButton icon="down" label={$t("Next match (Enter)")} onclick={() => findNext(view)} disabled={!query.valid} />
|
||||
<button class="rs-find-button" type="button" onclick={() => selectMatches(view)} disabled={!query.valid}>{$t("Select all")}</button>
|
||||
<IconButton icon="close" label={$t("Close find (Escape)")} onclick={() => closeSearchPanel(view)} />
|
||||
<IconButton icon="up" label={$t("Previous match (Shift+Enter)")} onclick={() => target.next(true)} disabled={!query.valid} />
|
||||
<IconButton icon="down" label={$t("Next match (Enter)")} onclick={() => target.next()} disabled={!query.valid} />
|
||||
{#if target.canSelectAll !== false}<button class="rs-find-button" type="button" onclick={() => target.selectAll()} disabled={!query.valid}>{$t("Select all")}</button>{/if}
|
||||
<IconButton icon="close" label={$t("Close find (Escape)")} onclick={() => target.close()} />
|
||||
</div>
|
||||
</div>
|
||||
<div class="rs-find-options">
|
||||
@@ -65,14 +73,14 @@
|
||||
<label><input type="checkbox" bind:checked={() => regexp, value => { regexp = value; commit(); }} />{$t("Regex")}</label>
|
||||
{#if searchText && !query.valid}<span class="rs-find-error" role="status">{$t("Invalid expression")}</span>{/if}
|
||||
</div>
|
||||
{#if !view.state.readOnly}
|
||||
{#if !target.readOnly}
|
||||
<div class="rs-find-row">
|
||||
<div class="rs-find-field">
|
||||
<input type="text" name="replace" aria-label={$t("Replace with")} placeholder={$t("Replace with")} bind:value={() => replacement, value => { replacement = value; commit(); }} />
|
||||
<input bind:this={replaceInput} type="text" name="replace" autocomplete="off" aria-label={$t("Replace with")} placeholder={$t("Replace with")} bind:value={() => replacement, value => { replacement = value; commit(); }} />
|
||||
</div>
|
||||
<div class="rs-find-actions">
|
||||
<button class="rs-find-button" type="button" onclick={() => replaceNext(view)} disabled={!query.valid}>{$t("Replace")}</button>
|
||||
<button class="rs-find-button" type="button" onclick={() => replaceAll(view)} disabled={!query.valid}>{$t("Replace all")}</button>
|
||||
<button class="rs-find-button" type="button" onclick={() => target.replace()} disabled={!query.valid}>{$t("Replace")}</button>
|
||||
<button class="rs-find-button" type="button" onclick={() => target.replace(true)} disabled={!query.valid}>{$t("Replace all")}</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
import { writerHistory, historyKeymap } from "./writerHistory";
|
||||
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import { noteFormats } from "./noteFormats";
|
||||
import { searchKeymap } from "@codemirror/search";
|
||||
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
|
||||
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
|
||||
import { writerSearch } from "./writerSearch";
|
||||
import type { OpenBuffer } from "$lib/workspace/types";
|
||||
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
|
||||
@@ -52,6 +53,13 @@
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor = $state.raw<EditorView>();
|
||||
export function focus() { editor?.focus(); }
|
||||
export function openFind(replace = false) {
|
||||
if (!editor) return;
|
||||
openSearchPanel(editor);
|
||||
editor.dom.querySelector<HTMLInputElement>(replace ? 'input[name="replace"]' : 'input[name="search"]')?.select();
|
||||
}
|
||||
export function closeFind() { if (editor) closeSearchPanel(editor); }
|
||||
export function nextMatch(backward = false) { if (editor) (backward ? findPrevious : findNext)(editor); }
|
||||
let error = $state("");
|
||||
let model: import("monaco-editor").editor.ITextModel | undefined;
|
||||
let ModelSelection: typeof import("monaco-editor").Selection;
|
||||
@@ -272,6 +280,17 @@
|
||||
return true;
|
||||
},
|
||||
paste(event, view) {
|
||||
const html = event.clipboardData?.getData("text/html") || "";
|
||||
if (/<table[\s>]/i.test(html)) {
|
||||
const markdown = htmlToMarkdown(html).replace(/\r\n?/g, "\n").trim();
|
||||
if (markdown) {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const { from, to } = view.state.selection.main;
|
||||
const insert = imageInsertion(view.state.doc.toString(), from, to, [markdown]);
|
||||
view.dispatch({ changes: { from, to, insert }, selection: { anchor: from + insert.length }, userEvent: "input.paste", annotations: isolateHistory.of("full") });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!onInsertImage || !imageFiles(event.clipboardData).length) return false;
|
||||
void insertImages(event, view); return true;
|
||||
},
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
|
||||
/** Commands for the shared document search controls. */
|
||||
export interface FindTarget {
|
||||
query: SearchQuery;
|
||||
readOnly: boolean;
|
||||
canSelectAll?: boolean;
|
||||
setQuery(query: SearchQuery): void;
|
||||
next(backward?: boolean): void;
|
||||
selectAll(): void;
|
||||
replace(all?: boolean): void;
|
||||
close(): void;
|
||||
keydown?(event: KeyboardEvent): boolean;
|
||||
}
|
||||
|
||||
export function documentMatches(source: string, query: SearchQuery) {
|
||||
const state = EditorState.create({ doc: source });
|
||||
const matches: { from: number; to: number }[] = [];
|
||||
if (query.valid) {
|
||||
const cursor = query.getCursor(state);
|
||||
for (let match = cursor.next(); !match.done; match = cursor.next()) matches.push(match.value);
|
||||
}
|
||||
return { state, matches };
|
||||
}
|
||||
|
||||
export function replacementText(source: string, from: number, query: SearchQuery) {
|
||||
const replacement = query.literal ? query.replace : query.replace.replace(/\\([nrt\\])/g, (_, char: string) => ({ n: "\n", r: "\r", t: "\t", "\\": "\\" })[char]!);
|
||||
if (!query.regexp) return replacement;
|
||||
const expression = new RegExp(query.search, "gmu" + (query.caseSensitive ? "" : "i"));
|
||||
expression.lastIndex = from;
|
||||
const match = expression.exec(source);
|
||||
return replacement.replace(/\$([$&]|\d+)/g, (token, index: string) => {
|
||||
if (index === "$") return "$";
|
||||
if (index === "&") return match?.[0] ?? "";
|
||||
for (let length = index.length; length > 0; length--) {
|
||||
const number = Number(index.slice(0, length));
|
||||
if (match && number > 0 && number < match.length) return (match[number] ?? "") + index.slice(length);
|
||||
}
|
||||
return token;
|
||||
});
|
||||
}
|
||||
@@ -145,6 +145,24 @@ class Preview extends WidgetType {
|
||||
}
|
||||
|
||||
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
|
||||
const focusBody = StateEffect.define<boolean>();
|
||||
const bodyFocused = StateField.define({
|
||||
create: () => false,
|
||||
update(value, transaction) {
|
||||
for (const effect of transaction.effects) if (effect.is(focusBody)) value = effect.value;
|
||||
return value;
|
||||
},
|
||||
});
|
||||
const syncBodyFocus = ViewPlugin.define(view => {
|
||||
// A restored editor can already own focus before its focus observer starts.
|
||||
const sync = () => queueMicrotask(() => {
|
||||
if (view.dom.isConnected && view.state.field(bodyFocused, false) !== undefined && view.state.field(bodyFocused) !== view.hasFocus) {
|
||||
view.dispatch({ effects: focusBody.of(view.hasFocus) });
|
||||
}
|
||||
});
|
||||
sync();
|
||||
return { update: sync };
|
||||
});
|
||||
function build(state: EditorState, previous?: DecorationSet): DecorationSet {
|
||||
const ranges: Range<Decoration>[] = [];
|
||||
const active = state.selection.ranges.map(range => ({ from: state.doc.lineAt(range.from).from, to: state.doc.lineAt(range.to).to }));
|
||||
@@ -221,17 +239,32 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
return false;
|
||||
}
|
||||
const line = state.doc.lineAt(node.from);
|
||||
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name)) {
|
||||
// A list starts with one hyphen. Do not enlarge the preceding paragraph
|
||||
// while the user enters that marker. Keep the Markdown source unchanged.
|
||||
const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
|
||||
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) {
|
||||
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 (node.name === "TaskMarker") {
|
||||
const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text);
|
||||
if (!match) return;
|
||||
const markerFrom = line.from + match[1].length;
|
||||
// ArrowLeft and Home reach the replacement's start, before the list bullet.
|
||||
// Keep the trailing space outside the edit range so task text stays rendered.
|
||||
const editingMarker = state.field(bodyFocused) && state.selection.ranges.some(range => range.from <= node.to && range.to >= markerFrom);
|
||||
if (editingMarker) return;
|
||||
ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x"), atomic: true }).range(markerFrom, line.from + match[0].length));
|
||||
if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed");
|
||||
return;
|
||||
}
|
||||
if (selected(node.from, node.to)) return;
|
||||
if (node.name === "HorizontalRule") {
|
||||
ranges.push(Decoration.line({ class: "writer-divider-line" }).range(line.from));
|
||||
ranges.push(Decoration.replace({ widget: new Divider(), atomic: true }).range(node.from, node.to));
|
||||
return false;
|
||||
}
|
||||
if (node.name === "HeaderMark") replace(node.from, Math.min(line.to, node.to + 1));
|
||||
if (node.name === "HeaderMark" && !(source.slice(node.from, node.to) === "-" && node.node.parent?.name === "SetextHeading2")) replace(node.from, Math.min(line.to, node.to + 1));
|
||||
if (node.name === "StrongEmphasis") mark(node.from, node.to, "writer-strong");
|
||||
if (node.name === "Emphasis") mark(node.from, node.to, "writer-emphasis");
|
||||
if (node.name === "Strikethrough") mark(node.from, node.to, "writer-strike");
|
||||
@@ -252,12 +285,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", "data-editor-tooltip": "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
|
||||
return false;
|
||||
}
|
||||
if (node.name === "TaskMarker") {
|
||||
const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text);
|
||||
if (!match) return;
|
||||
ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x"), atomic: true }).range(line.from + match[1].length, line.from + match[0].length));
|
||||
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;
|
||||
@@ -281,12 +308,12 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
}
|
||||
return Decoration.set(ranges, true);
|
||||
}
|
||||
return [imageSource, linkTooltips, StateField.define<DecorationSet>({
|
||||
return [imageSource, linkTooltips, bodyFocused, syncBodyFocus, EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing)), StateField.define<DecorationSet>({
|
||||
create: build,
|
||||
update(value, transaction) {
|
||||
return transaction.docChanged || transaction.selection
|
||||
|| syntaxTree(transaction.startState) !== syntaxTree(transaction.state)
|
||||
|| transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource) || effect.is(foldEffect) || effect.is(unfoldEffect))
|
||||
|| transaction.effects.some(effect => effect.is(focusBody) || 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({
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import type * as Monaco from "monaco-editor";
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import { documentMatches, replacementText, type FindTarget } from "./findTarget";
|
||||
|
||||
export function monacoSearch(monaco: typeof Monaco, view: Monaco.editor.IStandaloneCodeEditor, close: () => void) {
|
||||
const decorations = view.createDecorationsCollection();
|
||||
let active = false;
|
||||
let query = new SearchQuery({ search: "" });
|
||||
function snapshot() {
|
||||
const model = view.getModel()!;
|
||||
const { state, matches } = documentMatches(model.getValue(), query);
|
||||
function range(match: { from: number; to: number }) {
|
||||
const from = state.doc.lineAt(match.from), to = state.doc.lineAt(match.to);
|
||||
return new monaco.Range(from.number, match.from - from.from + 1, to.number, match.to - to.from + 1);
|
||||
}
|
||||
return { model, state, matches, range };
|
||||
}
|
||||
function refresh() {
|
||||
active = true;
|
||||
const { matches, range } = snapshot();
|
||||
decorations.set(matches.map(match => ({ range: range(match), options: { inlineClassName: "rs-source-search-match" } })));
|
||||
}
|
||||
function next(backward = false) {
|
||||
const { matches, range } = snapshot();
|
||||
if (!matches.length) return;
|
||||
const selection = view.getSelection();
|
||||
const ranges = matches.map(range);
|
||||
const current = ranges.findIndex(match => selection?.equalsRange(match));
|
||||
let index: number;
|
||||
if (current >= 0) index = (current + (backward ? -1 : 1) + ranges.length) % ranges.length;
|
||||
else if (backward) {
|
||||
index = ranges.findLastIndex(match => !selection || monaco.Position.compare(match.getEndPosition(), selection.getStartPosition()) <= 0);
|
||||
if (index < 0) index = ranges.length - 1;
|
||||
} else {
|
||||
index = ranges.findIndex(match => !selection || monaco.Position.compare(match.getStartPosition(), selection.getEndPosition()) >= 0);
|
||||
if (index < 0) index = 0;
|
||||
}
|
||||
view.setSelection(ranges[index]);
|
||||
view.revealRangeInCenterIfOutsideViewport(ranges[index]);
|
||||
}
|
||||
const target: FindTarget = {
|
||||
get query() { return query; }, readOnly: false,
|
||||
setQuery(value) { query = value; refresh(); },
|
||||
next,
|
||||
selectAll() {
|
||||
const { matches, range } = snapshot();
|
||||
if (!matches.length) return;
|
||||
view.setSelections(matches.map(match => { const value = range(match); return new monaco.Selection(value.startLineNumber, value.startColumn, value.endLineNumber, value.endColumn); }));
|
||||
view.focus();
|
||||
},
|
||||
replace(all = false) {
|
||||
const { state, matches, range } = snapshot();
|
||||
const selection = view.getSelection();
|
||||
const selected = all ? matches : matches.filter(match => selection?.equalsRange(range(match))).slice(0, 1);
|
||||
if (!selected.length) { if (!all) next(); return; }
|
||||
const edits = selected.map(match => ({ range: range(match), text: replacementText(state.doc.toString(), match.from, query) }));
|
||||
const last = selected[selected.length - 1];
|
||||
const inserted = edits[edits.length - 1].text;
|
||||
const end = state.update({ changes: selected.map((match, index) => ({ ...match, insert: edits[index].text })) }).state;
|
||||
const offset = all ? 0 : last.from + inserted.length;
|
||||
const line = end.doc.lineAt(Math.min(offset, end.doc.length));
|
||||
view.pushUndoStop();
|
||||
view.executeEdits("document-find", edits, [new monaco.Selection(line.number, offset - line.from + 1, line.number, offset - line.from + 1)]);
|
||||
view.pushUndoStop();
|
||||
if (!all) next();
|
||||
},
|
||||
close() { active = false; decorations.clear(); close(); view.focus(); },
|
||||
};
|
||||
const changed = view.onDidChangeModelContent(() => { if (active) refresh(); });
|
||||
return { target, refresh, dispose() { changed.dispose(); decorations.clear(); } };
|
||||
}
|
||||
@@ -81,6 +81,7 @@ class NoteTitle extends WidgetType {
|
||||
event.stopPropagation();
|
||||
if (event.isComposing) return;
|
||||
if (event.key === "Enter") { event.preventDefault(); void commit(true); }
|
||||
if (event.key === "Tab" && !event.shiftKey) { event.preventDefault(); void commit(true); }
|
||||
if (event.key === "Escape" && !pending) { event.preventDefault(); finish(); button.focus(); }
|
||||
};
|
||||
return block;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import { documentMatches, type FindTarget } from "./findTarget";
|
||||
|
||||
/** Search the visible reading text without changing its Markdown or rendered nodes. */
|
||||
export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget {
|
||||
let query = new SearchQuery({ search: "" });
|
||||
let current = -1;
|
||||
function ranges() {
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||||
const nodes: { node: Text; from: number; to: number }[] = [];
|
||||
let source = "", block: Element | null = null;
|
||||
while (walker.nextNode()) {
|
||||
const node = walker.currentNode as Text, parent = node.parentElement;
|
||||
if (!parent || parent.closest(options.includeButtons ? "[hidden], [aria-hidden=true], script, style" : "button, [hidden], script, style") || !parent.getClientRects().length) continue;
|
||||
const nextBlock = parent.closest("p, h1, h2, h3, h4, h5, h6, li, td, th, pre, button, div, section");
|
||||
if (nodes.length && nextBlock !== block) source += "\n";
|
||||
block = nextBlock;
|
||||
nodes.push({ node, from: source.length, to: source.length + node.length });
|
||||
source += node.data;
|
||||
}
|
||||
return documentMatches(source, query).matches.flatMap(match => {
|
||||
const start = nodes.find(node => node.to > match.from || node.from === match.from);
|
||||
const end = nodes.find(node => node.to >= match.to);
|
||||
if (!start || !end) return [];
|
||||
const range = document.createRange();
|
||||
range.setStart(start.node, Math.max(0, match.from - start.from));
|
||||
range.setEnd(end.node, Math.max(0, match.to - end.from));
|
||||
return [range];
|
||||
});
|
||||
}
|
||||
function next(backward = false) {
|
||||
const matches = ranges();
|
||||
if (!matches.length) { current = -1; return; }
|
||||
current = current < 0 ? (backward ? matches.length - 1 : 0) : (current + (backward ? -1 : 1) + matches.length) % matches.length;
|
||||
const range = matches[current];
|
||||
const selection = window.getSelection();
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
range.startContainer.parentElement?.scrollIntoView({ block: "center" });
|
||||
}
|
||||
return {
|
||||
get query() { return query; }, readOnly: true, canSelectAll: false,
|
||||
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; window.getSelection()?.removeAllRanges(); },
|
||||
next, selectAll() {}, replace() {},
|
||||
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
|
||||
};
|
||||
}
|
||||
@@ -277,9 +277,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if (sourceEditing || /^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
|
||||
if (event.shiftKey) editor?.commands.setHardBreak();
|
||||
else if (event.ctrlKey || event.metaKey) leave(true);
|
||||
else editor?.commands.setHardBreak();
|
||||
else {
|
||||
const next = table!.rows[row + 1]?.cells[column];
|
||||
if (next) { activate(next); editor?.commands.setTextSelection(1); editor?.view.focus(); }
|
||||
else add("row", true, column);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (event.key === "Tab") {
|
||||
@@ -360,7 +364,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
view.requestMeasure();
|
||||
}
|
||||
|
||||
function add(kind: "row" | "column", focusNew = false) {
|
||||
function add(kind: "row" | "column", focusNew = false, column = 0) {
|
||||
const from = view.posAtDOM(root);
|
||||
finish();
|
||||
const current = controller.source;
|
||||
@@ -369,7 +373,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
requestAnimationFrame(() => {
|
||||
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
|
||||
if (!updated) return;
|
||||
if (focusNew) updated.querySelector<HTMLTableCellElement>("tbody tr:last-child td")?.focus();
|
||||
if (focusNew) updated.querySelector<HTMLTableRowElement>("tbody tr:last-child")?.cells[column]?.focus();
|
||||
if (kind === "column") {
|
||||
const viewport = updated.querySelector<HTMLElement>(".md-table-scroll")!;
|
||||
viewport.scrollLeft = viewport.scrollWidth;
|
||||
|
||||
@@ -60,6 +60,16 @@ export function copyTableCells(source: string, range: CellRange): string {
|
||||
return Array.from({ length: bottom - top + 1 }, (_, r) => Array.from({ length: right - left + 1 }, (_, c) => quote(table.rows[sourceRow(top + r)]?.cells[left + c]?.text || "")).join("\t")).join("\n");
|
||||
}
|
||||
|
||||
export function copyTableMarkdown(source: string, range: CellRange): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table) return "";
|
||||
const { top, bottom, left, right } = bounds(range);
|
||||
const rows = Array.from({ length: bottom - top + 1 }, (_, r) =>
|
||||
`| ${Array.from({ length: right - left + 1 }, (_, c) => table.rows[sourceRow(top + r)]?.cells[left + c]?.text || "").join(" | ")} |`);
|
||||
rows.splice(1, 0, `| ${Array.from({ length: right - left + 1 }, () => "---").join(" | ")} |`);
|
||||
return rows.join("\n");
|
||||
}
|
||||
|
||||
// Parse quoted spreadsheet TSV, including embedded tabs/newlines, or a Markdown table.
|
||||
export function clipboardCells(text: string): string[][] {
|
||||
const table = parseMarkdownTable(text);
|
||||
|
||||
@@ -7,7 +7,8 @@ import { useSpellingMenu } from "./spellingMenu";
|
||||
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import { cellFormats, tableTextItems, type TableContextActions } from "./tableCellActions";
|
||||
import { alignTableCells, bounds, copyTableCells, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells, type CellFormat, type CellPoint, type CellRange } from "./tableSelection";
|
||||
import { alignTableCells, bounds, copyTableCells, copyTableMarkdown, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells, type CellFormat, type CellPoint, type CellRange } from "./tableSelection";
|
||||
import { renderMarkdownHtml } from "../workspace/noteHtml";
|
||||
|
||||
const selections = new WeakMap<Element, (range: CellRange) => void>();
|
||||
|
||||
@@ -76,7 +77,12 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
const text = await navigator.clipboard.readText();
|
||||
if (root.isConnected && source() === before && range === selected) apply((value, target) => pasteTableCells(value, target, text));
|
||||
} else {
|
||||
await navigator.clipboard.writeText(copyTableCells(before, selected));
|
||||
if (navigator.clipboard.write && typeof ClipboardItem !== "undefined") {
|
||||
await navigator.clipboard.write([new ClipboardItem({
|
||||
"text/plain": new Blob([copyTableCells(before, selected)], { type: "text/plain" }),
|
||||
"text/html": new Blob([renderMarkdownHtml(copyTableMarkdown(before, selected), new Map())], { type: "text/html" }),
|
||||
})]);
|
||||
} else await navigator.clipboard.writeText(copyTableMarkdown(before, selected));
|
||||
if (action === "cut" && root.isConnected && source() === before && range === selected) clearCells();
|
||||
}
|
||||
} catch {
|
||||
@@ -233,7 +239,11 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
if (action === "paste" && !event.clipboardData.types.includes("text/plain")) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (action === "paste") apply((text, selected) => pasteTableCells(text, selected, event.clipboardData!.getData("text/plain")));
|
||||
else { event.clipboardData.setData("text/plain", copyTableCells(source(), range)); if (action === "cut") clearCells(); }
|
||||
else {
|
||||
event.clipboardData.setData("text/plain", copyTableCells(source(), range));
|
||||
event.clipboardData.setData("text/html", renderMarkdownHtml(copyTableMarkdown(source(), range), new Map()));
|
||||
if (action === "cut") clearCells();
|
||||
}
|
||||
}, { ...options, capture: true });
|
||||
// Spreadsheet data pasted while editing one cell becomes a grid operation.
|
||||
wrapper.addEventListener("paste", event => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { flushSync, mount, unmount } from "svelte";
|
||||
import { getSearchQuery, search, type SearchQuery } from "@codemirror/search";
|
||||
import { runScopeHandlers } from "@codemirror/view";
|
||||
import { closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, search, selectMatches, setSearchQuery, type SearchQuery } from "@codemirror/search";
|
||||
import FindPanel from "./FindPanel.svelte";
|
||||
|
||||
export const writerSearch = search({
|
||||
@@ -12,7 +13,15 @@ export const writerSearch = search({
|
||||
dom,
|
||||
top: true,
|
||||
mount() {
|
||||
panel = mount(FindPanel, { target: dom, props: { view } });
|
||||
panel = mount(FindPanel, { target: dom, props: { target: {
|
||||
query: getSearchQuery(view.state), readOnly: view.state.readOnly,
|
||||
setQuery(query) { view.dispatch({ effects: setSearchQuery.of(query) }); },
|
||||
next(backward) { (backward ? findPrevious : findNext)(view); },
|
||||
selectAll() { selectMatches(view); },
|
||||
replace(all) { (all ? replaceAll : replaceNext)(view); },
|
||||
close() { closeSearchPanel(view); view.focus(); },
|
||||
keydown(event) { return runScopeHandlers(view, event, "search-panel"); },
|
||||
} } });
|
||||
flushSync();
|
||||
dom.querySelector<HTMLInputElement>("[main-field]")?.select();
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user