RuneStone 1.0.0
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
declare const __RUNESTONE_VERSION__: string | undefined;
|
||||
|
||||
/** The release version. vite.config.js defines it from RUNESTONE_VERSION or package.json. */
|
||||
export const appVersion: string = typeof __RUNESTONE_VERSION__ === "string" ? __RUNESTONE_VERSION__ : "dev";
|
||||
@@ -0,0 +1,30 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
import IconButton from '$lib/ui/IconButton.svelte';
|
||||
import { state as browserState, request } from './client';
|
||||
import { engine, engineReady } from './engine';
|
||||
let { open }: { open: (profileId: string, url: string) => Promise<void> } = $props();
|
||||
let error = $state('');
|
||||
// The bookmarks live in the engine. A missing engine is not started here.
|
||||
const installed = $derived(engineReady($engine));
|
||||
let loaded = false;
|
||||
$effect(() => {
|
||||
if (!installed) { loaded = false; return; }
|
||||
if (loaded) return;
|
||||
loaded = true;
|
||||
void request('state').catch(reason => error = String(reason));
|
||||
});
|
||||
</script>
|
||||
<div class="bookmarks">
|
||||
{#if !installed}<p class="note">{$t("Install the browser engine to see the browser bookmarks.")}</p>{/if}
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
{#each installed ? $browserState?.bookmarks || [] : [] as item (item.id)}
|
||||
<div class="row"><button class="link" title={item.url} onclick={() => void open(item.profileId, item.url)}><Icon icon="globe" /><span>{item.title}</span></button><IconButton icon="close" label={`Remove ${item.title}`} onclick={() => void request('removeBookmark', { id: item.id })} /></div>
|
||||
{/each}
|
||||
</div>
|
||||
<style>
|
||||
.bookmarks{color:var(--rs-text);font-family:var(--rs-font-ui)}.row{display:flex;align-items:center;padding:0 5px;border-radius:var(--rs-control-radius)}.row:hover{background:var(--rs-hover-bg)}
|
||||
.link{display:flex;align-items:center;gap:8px;flex:1;min-width:0;padding:7px 5px;border:0;border-radius:var(--rs-control-radius);color:inherit;background:transparent;text-align:left;cursor:pointer}
|
||||
span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.link:focus-visible{outline:2px solid var(--rs-focus)}p{padding:8px;font-size:12px}.error{color:var(--rs-error)}.note{margin:0;color:var(--rs-text-dim)}
|
||||
</style>
|
||||
@@ -0,0 +1,340 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { keys } from '$lib/ui/shortcuts';
|
||||
import { onMount, untrack, tick } from 'svelte';
|
||||
import IconButton from '$lib/ui/IconButton.svelte';
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
import { state as browserState, pageErrors, request, frames, pageEvents, type PageMenu, type BrowserFrame } from './client';
|
||||
import type { ActionMenuItem } from '$lib/ui/actionMenu';
|
||||
import { showActionMenu } from '$lib/ui/managedActionMenu';
|
||||
import { WheelQueue } from './inputQueue';
|
||||
import { TabSession, type TabStatus } from './tabSession';
|
||||
import { engine } from './engine';
|
||||
import { AutoScroll } from './autoScroll';
|
||||
import { keepCopiedImage } from '$lib/workspace/copiedImage';
|
||||
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
|
||||
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('Opening browser…') });
|
||||
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
|
||||
const tabId = $derived(status.tabId);
|
||||
const ready = $derived(status.phase === 'ready');
|
||||
const current = $derived($browserState?.tabs.find(tab => tab.id === tabId));
|
||||
const blank = $derived(!current?.url || current.url === 'about:blank');
|
||||
let address = $state(''); let editing = $state(false);
|
||||
let image = $state(''), imageBox = $state({ width: 0, height: 0, x: 0, y: 0, exact: false }); let surface: HTMLDivElement; let addressField: HTMLInputElement;
|
||||
let width = 1000, height = 700, textInput: HTMLTextAreaElement, composing = false;
|
||||
let inputQueue = Promise.resolve();
|
||||
const orderedInput = (command: string, args: Record<string, unknown>) => inputQueue = inputQueue.then(() => send(command, args));
|
||||
function pageFocus(focused: boolean) { void orderedInput('focus', { focused }); }
|
||||
const wheels = new WheelQueue(input => send('input', { input }));
|
||||
let displayedFrame: BrowserFrame | undefined;
|
||||
let closeMenu: (() => void) | undefined;
|
||||
function chooseProfile(event: MouseEvent) {
|
||||
closeMenu?.();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
closeMenu = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: $t('Browser profile'),
|
||||
items: ($browserState?.profiles || []).map(profile => ({ label: profile.name, radio: true,
|
||||
checked: profile.id === current?.profileId, run: () => void openTab(profile.id) })) }).close;
|
||||
}
|
||||
let opening = $state(false), openingError = $state(''), mounted = $state(false);
|
||||
let findOpen = $state(false), findText = $state('');
|
||||
let findField: HTMLInputElement | undefined = $state();
|
||||
let findTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const autoScroll = new AutoScroll();
|
||||
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
|
||||
let scrollFrame = 0, moveFrame = 0, movePending = false;
|
||||
let pendingMove: Record<string, unknown> | undefined;
|
||||
let suppressedRelease = -1, middlePressed = false;
|
||||
const result = $derived(current?.find?.text === findText ? current.find : null);
|
||||
const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`);
|
||||
$effect(() => {
|
||||
void documentKey;
|
||||
untrack(stopScroll);
|
||||
if (ready && findOpen) untrack(() => { if (findText && !current?.loading) search(); });
|
||||
});
|
||||
export async function find() {
|
||||
findOpen = true;
|
||||
await tick(); findField?.focus(); findField?.select();
|
||||
}
|
||||
export function detach() { connection.detach(); }
|
||||
export function action(command: string, args: Record<string, unknown> = {}) { return send(command, args); }
|
||||
function search(next = false, forward = true) {
|
||||
clearTimeout(findTimer);
|
||||
void send('find', { text: findText, next, forward });
|
||||
}
|
||||
function closeFind() { clearTimeout(findTimer); findOpen = false; void send('stopFind'); surface.focus(); }
|
||||
function findKey(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeFind(); }
|
||||
else if (event.key === 'Enter' && event.target === findField) { event.preventDefault(); event.stopPropagation(); search(true, !event.shiftKey); }
|
||||
}
|
||||
$effect(() => { if (!editing && current?.url) address = current.url === 'about:blank' ? '' : current.url; });
|
||||
$effect(() => {
|
||||
const id = tabId;
|
||||
image = '';
|
||||
if (!id) return;
|
||||
frames.set(id, frame => {
|
||||
if (displayedFrame) acknowledgeFrame();
|
||||
if (frame.width > 0 && frame.height > 0 && ['image/png', 'image/jpeg'].includes(frame.mime)) {
|
||||
displayedFrame = frame;
|
||||
if (blank) { image = ''; acknowledgeFrame(); }
|
||||
else {
|
||||
image = `data:${frame.mime};base64,${frame.data}`; imageBox = frameBox(frame);
|
||||
}
|
||||
}
|
||||
});
|
||||
pageEvents.set(id, event => {
|
||||
if (event.event === 'context-menu') showPageMenu(event);
|
||||
else if (event.event === 'open-link' && event.url) void newTab(current?.profileId || 'user', event.url);
|
||||
});
|
||||
return () => { acknowledgeFrame(); frames.delete(id); pageEvents.delete(id); closeMenu?.(); };
|
||||
});
|
||||
/**
|
||||
* Return the CSS box that shows each frame pixel on one screen pixel: the frame size in CSS pixels, and the offset
|
||||
* from the surface edge to the next device pixel edge. A stretched or misaligned frame is resampled and blurs text.
|
||||
* `exact` is true when the frame scale is the display scale. Then the image uses nearest-pixel sampling, because
|
||||
* layout rounds the CSS size to 1/64 pixel and a scale of 0.99998 still blends neighbour pixels.
|
||||
* Chromium uses nearest-pixel sampling only to scale up, so the size rounds up to the next 1/64 pixel.
|
||||
* The image has its own compositor layer. A shared layer can start at a fractional device pixel and blend the frame again.
|
||||
*/
|
||||
function frameBox(frame: BrowserFrame) {
|
||||
const scale = frame.scale || 1, ratio = devicePixelRatio || 1, rect = surface.getBoundingClientRect();
|
||||
const align = (edge: number) => (Math.ceil(edge * ratio - 0.001) - edge * ratio) / ratio;
|
||||
const size = (pixels: number) => Math.ceil(pixels / scale * 64) / 64;
|
||||
return { width: size(frame.width), height: size(frame.height), x: align(rect.left), y: align(rect.top), exact: scale === ratio };
|
||||
}
|
||||
function acknowledgeFrame() {
|
||||
const frame = displayedFrame; displayedFrame = undefined;
|
||||
if (frame) void request('frameAck', { tabId: frame.tabId, frameId: frame.frameId }).catch(() => {});
|
||||
}
|
||||
function showPageMenu(context: PageMenu) {
|
||||
stopScroll(); closeMenu?.();
|
||||
const action = (name: string) => () => { void send('contextAction', { token: context.token, action: name }); };
|
||||
const edit = (name: string) => () => { void orderedInput('edit', { action: name }); };
|
||||
const items: ActionMenuItem[] = [];
|
||||
if (context.linkURL) items.push(
|
||||
{ label: $t('Open link in new tab'), icon: 'file-plus', run: () => void newTab(current?.profileId || 'user', context.linkURL) },
|
||||
{ label: $t('Open link in default browser'), icon: 'external', run: action('openExternal') },
|
||||
{ label: $t('Copy link address'), icon: 'copy', run: action('copyLink') },
|
||||
{ label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true });
|
||||
if (context.hasImageContents) items.push(
|
||||
{ label: $t('Open image in new tab'), icon: 'file-plus', disabled: !context.srcURL, run: () => void newTab(current?.profileId || 'user', context.srcURL) },
|
||||
{ label: $t('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
|
||||
{ label: $t('Copy image'), icon: 'copy', run: () => copyImage(context) },
|
||||
{ label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
|
||||
if (context.isEditable) items.push(
|
||||
{ label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') },
|
||||
{ label: $t('Redo'), icon: 'redo', shortcut: keys('Mod+Shift+Z'), disabled: !context.editFlags.canRedo, run: edit('redo') }, { separator: true },
|
||||
{ label: $t('Cut'), icon: 'cut', shortcut: keys('Mod+X'), disabled: !context.editFlags.canCut, run: edit('cut') });
|
||||
if (context.isEditable || context.selectionText) items.push({ label: $t('Copy'), icon: 'copy', shortcut: keys('Mod+C'), disabled: !context.editFlags.canCopy, run: edit('copy') });
|
||||
if (context.isEditable) items.push(
|
||||
{ label: $t('Paste'), icon: 'paste', shortcut: keys('Mod+V'), disabled: !context.editFlags.canPaste, run: edit('paste') },
|
||||
{ label: $t('Paste as plain text'), icon: 'paste-text', shortcut: keys('Mod+Shift+V'), disabled: !context.editFlags.canPaste, run: edit('pasteAndMatchStyle') },
|
||||
{ label: $t('Select all'), icon: 'task', shortcut: keys('Mod+A'), run: edit('selectAll') }, { separator: true });
|
||||
items.push({ label: $t('Back'), icon: 'arrow-left', disabled: !current?.canBack, run: () => void send('back') },
|
||||
{ label: $t('Forward'), icon: 'arrow-right', disabled: !current?.canForward, run: () => void send('forward') },
|
||||
{ label: $t('Reload'), icon: 'refresh', run: () => void send('reload') },
|
||||
{ label: $t('Find in page'), icon: 'search', shortcut: keys('Mod+F'), run: () => void find() });
|
||||
const rect = surface.getBoundingClientRect();
|
||||
const menu = showActionMenu({ x: rect.left + imageBox.x + context.x, y: rect.top + imageBox.y + context.y,
|
||||
items, label: $t('Browser page actions') });
|
||||
closeMenu = menu.close;
|
||||
}
|
||||
$effect(() => { if (mounted && ready && tabId) untrack(syncSize); });
|
||||
async function send(command: string, args = {}) {
|
||||
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
|
||||
await connection.send(command, args);
|
||||
}
|
||||
// A paste of a copied image uses the bytes that the page loaded. The engine gives them in parts.
|
||||
// A paste can come before the reply, so the copy is known at once by its address.
|
||||
function copyImage(context: PageMenu) {
|
||||
const owner = tabId;
|
||||
const data = (async () => {
|
||||
const reply = await connection.send('contextAction', { token: context.token, action: 'copyImage' }) as { copied?: { token: string; mime: string } } | null | undefined;
|
||||
const copied = reply?.copied;
|
||||
if (!copied) return undefined;
|
||||
let data = '';
|
||||
for (let offset: number | null = 0; offset !== null;) {
|
||||
const part: { data: string; next: number | null } = await request('copiedImage', { tabId: owner, token: copied.token, offset });
|
||||
data += part.data; offset = part.next;
|
||||
}
|
||||
return `data:${copied.mime};base64,${data}`;
|
||||
})().catch(() => undefined);
|
||||
if (context.srcURL) keepCopiedImage(context.srcURL, data);
|
||||
}
|
||||
async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
|
||||
if (opening) return;
|
||||
opening = true;
|
||||
try { openingError = ''; await newTab(profileId); } catch (error) { openingError = `Could not open a browser tab: ${String(error)}`; }
|
||||
finally { opening = false; }
|
||||
}
|
||||
onMount(() => {
|
||||
mounted = true;
|
||||
const offState = browserState.subscribe(value => { if (value) connection.observe(value); });
|
||||
void connection.connect();
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const resize = new ResizeObserver(entries => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(syncSize, 100);
|
||||
});
|
||||
resize.observe(surface);
|
||||
// A move to a monitor with a different display scale changes the pixel ratio but not always the surface size.
|
||||
let pixelRatio: MediaQueryList;
|
||||
const watchPixelRatio = () => { pixelRatio = matchMedia(`(resolution: ${devicePixelRatio}dppx)`); pixelRatio.addEventListener('change', changePixelRatio, { once: true }); };
|
||||
const changePixelRatio = () => { watchPixelRatio(); syncSize(); };
|
||||
watchPixelRatio();
|
||||
return () => { mounted = false; pixelRatio.removeEventListener('change', changePixelRatio); stopScroll(); wheels.close(); closeMenu?.(); cancelAnimationFrame(moveFrame); clearTimeout(timer); clearTimeout(findTimer); resize.disconnect(); offState(); void connection.close(); };
|
||||
});
|
||||
function syncSize() {
|
||||
const rect = surface.getBoundingClientRect();
|
||||
if (!rect.width || !rect.height) { stopScroll(); void send('visible', { visible: false }); return; }
|
||||
width = Math.max(100, Math.min(5120, Math.round(rect.width)));
|
||||
height = Math.max(100, Math.min(3200, Math.round(rect.height)));
|
||||
void send('resize', { width, height, scale: Math.max(1, Math.min(3, devicePixelRatio || 1)) }); void send('visible', { visible: true });
|
||||
}
|
||||
const modifiers = (event: MouseEvent | KeyboardEvent) => [event.shiftKey && 'shift', event.ctrlKey && 'control', event.altKey && 'alt', event.metaKey && 'meta'].filter(Boolean);
|
||||
function stopScroll() { autoScroll.stop(); wheels.clear(); scrollAnchor = null; cancelAnimationFrame(scrollFrame); }
|
||||
function scrollStep(time: number) {
|
||||
if (!autoScroll.anchor || !ready) { stopScroll(); return; }
|
||||
const delta = autoScroll.delta(time);
|
||||
if (delta && (delta.x || delta.y)) {
|
||||
const rect = surface.getBoundingClientRect();
|
||||
if (!rect.width || !rect.height) { stopScroll(); return; }
|
||||
const anchor = autoScroll.anchor;
|
||||
wheels.push({ type: 'mouseWheel', x: Math.min(width - 1, Math.round(anchor.x - imageBox.x)), y: Math.min(height - 1, Math.round(anchor.y - imageBox.y)), deltaX: -delta.x, deltaY: -delta.y });
|
||||
}
|
||||
scrollFrame = requestAnimationFrame(scrollStep);
|
||||
}
|
||||
function flushMove() {
|
||||
moveFrame = 0;
|
||||
if (!pendingMove || movePending) return;
|
||||
const input = pendingMove; pendingMove = undefined; movePending = true;
|
||||
void send('input', { input }).finally(() => {
|
||||
movePending = false;
|
||||
if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove);
|
||||
});
|
||||
}
|
||||
// The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point.
|
||||
function pagePoint(point: { x: number; y: number }) {
|
||||
return { x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))) };
|
||||
}
|
||||
// A middle-click starts scrolling at once. On a link, it stops the scroll and opens the link in a new tab.
|
||||
async function openLinkAt(input: { x: number; y: number }) {
|
||||
const owner = tabId;
|
||||
const found = await request<{ url: string | null }>('linkAt', { tabId: owner, ...input }).catch(() => null);
|
||||
if (!found?.url || owner !== tabId || !autoScroll.anchor) return;
|
||||
stopScroll();
|
||||
if (middlePressed) suppressedRelease = 1;
|
||||
void newTab(current?.profileId || 'user', found.url);
|
||||
}
|
||||
function pointer(event: MouseEvent | WheelEvent, type: string) {
|
||||
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true });
|
||||
const rect = surface.getBoundingClientRect();
|
||||
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };
|
||||
if (event.button === 1) middlePressed = type === 'mouseDown';
|
||||
if (type === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
|
||||
if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; }
|
||||
if (type === 'mouseDown' && event.button === 1 && ready) {
|
||||
pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0;
|
||||
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep);
|
||||
void openLinkAt(pagePoint(point)); return;
|
||||
}
|
||||
if (autoScroll.anchor) {
|
||||
if (type === 'mouseMove') autoScroll.move(point);
|
||||
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
|
||||
if (type === 'mouseWheel') stopScroll(); else return;
|
||||
}
|
||||
const input = { type, ...pagePoint(point),
|
||||
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
|
||||
...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) };
|
||||
if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; }
|
||||
if (type === 'mouseMove') {
|
||||
pendingMove = input;
|
||||
if (!moveFrame && !movePending) moveFrame = requestAnimationFrame(flushMove);
|
||||
} else { pendingMove = undefined; void orderedInput('input', { input }); }
|
||||
}
|
||||
function key(event: KeyboardEvent, type: string) {
|
||||
if (event.isComposing || composing || event.key === 'Process' || event.key === 'Dead') return;
|
||||
if (autoScroll.anchor) { stopScroll(); if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); return; } }
|
||||
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'f') { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') void find(); return; }
|
||||
if (event.key === 'Escape' && findOpen) { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') closeFind(); return; }
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'l') { event.preventDefault(); addressField.focus(); addressField.select(); return; }
|
||||
if ((event.ctrlKey || event.metaKey) && [',', 'w', 't'].includes(event.key.toLowerCase())) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const editActions: Record<string, string> = { a: 'selectAll', c: 'copy', x: 'cut', v: event.shiftKey ? 'pasteAndMatchStyle' : 'paste', z: event.shiftKey ? 'redo' : 'undo', y: 'redo' };
|
||||
if ((event.ctrlKey || event.metaKey) && editActions[event.key.toLowerCase()]) {
|
||||
if (type === 'keyDown') void orderedInput('edit', { action: editActions[event.key.toLowerCase()] });
|
||||
return;
|
||||
}
|
||||
const names: Record<string, string> = { ArrowLeft: 'LEFT', ArrowRight: 'RIGHT', ArrowUp: 'UP', ArrowDown: 'DOWN', Enter: 'ENTER', Backspace: 'BACKSPACE', Escape: 'ESCAPE', Delete: 'DELETE', Tab: 'TAB', Home: 'HOME', End: 'END', PageUp: 'PAGEUP', PageDown: 'PAGEDOWN', ' ': 'SPACE' };
|
||||
void orderedInput('input', { input: { type, keyCode: names[event.key] || event.key, modifiers: modifiers(event) } });
|
||||
if (type === 'keyDown' && [...event.key].length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) void orderedInput('insertText', { text: event.key });
|
||||
}
|
||||
</script>
|
||||
<svelte:window onblur={() => { stopScroll(); pageFocus(false); }} onfocus={() => { if (surface?.contains(document.activeElement)) pageFocus(true); }} />
|
||||
<svelte:document onvisibilitychange={() => { if (document.hidden) { stopScroll(); pageFocus(false); } else if (surface?.contains(document.activeElement)) pageFocus(true); }} />
|
||||
<div class="browser" class:blank data-browser-tab={tabId} data-browser-state={status.phase}>
|
||||
<form class="toolbar" onsubmit={event => { event.preventDefault(); editing = false; void send('navigate', { input: address }); surface.focus(); }}>
|
||||
<IconButton icon="arrow-left" label={$t("Back")} disabled={!ready || !current?.canBack} onclick={() => void send('back')} />
|
||||
<IconButton icon="arrow-right" label={$t("Forward")} disabled={!ready || !current?.canForward} onclick={() => void send('forward')} />
|
||||
<IconButton icon={current?.loading ? 'stop' : 'refresh'} label={current?.loading ? 'Stop loading' : $t('Reload')} disabled={!ready} onclick={() => void send(current?.loading ? 'stop' : 'reload')} />
|
||||
<input bind:this={addressField} bind:value={address} disabled={!ready} onfocus={() => editing = true} onblur={() => editing = false} aria-label={$t("Address or search")} placeholder={$t("Search or enter an address")} spellcheck="false" autocomplete="off">
|
||||
<IconButton icon="bookmark" label={$t("Bookmark this page")} disabled={!ready || !current?.url.startsWith('http')} onclick={() => void send('bookmark')} />
|
||||
<button type="button" class="profile-choice" aria-label={$t("Browser profile")} aria-haspopup="menu" disabled={opening} onclick={chooseProfile}>
|
||||
{$browserState?.profiles.find(profile => profile.id === current?.profileId)?.name ?? $t('Profile')}<Icon icon="chevron-down" />
|
||||
</button>
|
||||
</form>
|
||||
{#if findOpen}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Find controls share the Escape shortcut.) -->
|
||||
<form class="findbar" role="search" aria-label={$t("Find in page")} onkeydown={findKey} onsubmit={event => { event.preventDefault(); search(true); }}>
|
||||
<input bind:this={findField} bind:value={findText} aria-label={$t("Find in page")} placeholder={$t("Find in page")} maxlength="1000" autocomplete="off" spellcheck="false"
|
||||
disabled={!ready} oninput={() => { clearTimeout(findTimer); findTimer = setTimeout(() => search(), 120); }}>
|
||||
<span class="find-count" role="status" aria-live="polite">{!findText ? '' : !result || result.pending ? 'Searching…' : result.matches ? `${result.activeMatch} of ${result.matches}` : 'No matches'}</span>
|
||||
<IconButton icon="up" label={$t("Previous match (Shift+Enter)")} disabled={!ready || !findText} onclick={() => search(true, false)} />
|
||||
<IconButton icon="down" label={$t("Next match (Enter)")} disabled={!ready || !findText} onclick={() => search(true)} />
|
||||
<IconButton icon="close" label={$t("Close find (Escape)")} onclick={closeFind} />
|
||||
</form>
|
||||
{/if}
|
||||
{#if status.phase === 'connecting'}<p class="status" role="status">{$t(status.message)}</p>{/if}
|
||||
{#if ready && status.message}<p class="error" role="alert">{$t(status.message)}</p>{/if}
|
||||
{#if status.phase === 'disconnected'}
|
||||
<div class="error" role="alert"><p>{$t(status.message)}</p><button class="reconnect" onclick={() => void connection.connect()}>{$t("Reconnect")}</button></div>
|
||||
{/if}
|
||||
{#if status.detail}
|
||||
<details class="diagnostics"><summary>{$t("Browser error details")}</summary><dl>
|
||||
<dt>{$t("Operation")}</dt><dd>{status.detail.operation}</dd><dt>{$t("Reason")}</dt><dd>{status.detail.reason}</dd>
|
||||
<dt>{$t("Tab")}</dt><dd>{status.detail.tabId || $t('Not created')}</dd><dt>{$t("Time")}</dt><dd>{status.detail.time}</dd>
|
||||
<dt>{$t("Engine")}</dt><dd>{$engine?.version ?? ''}</dd>
|
||||
</dl></details>
|
||||
{/if}
|
||||
{#if openingError || $pageErrors[tabId]}<p class="error" role="alert">{openingError || $pageErrors[tabId]}</p>{/if}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (This surface forwards native browser input.) -->
|
||||
<div class="surface" class:autoscroll={!!scrollAnchor} bind:this={surface} role="application" aria-label={$t("Web page")} tabindex="0"
|
||||
onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')}
|
||||
onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')}
|
||||
onfocusin={() => pageFocus(true)} onfocusout={event => { if (!surface.contains(event.relatedTarget as Node | null)) pageFocus(false); }}
|
||||
onkeydown={event => key(event, 'keyDown')} onkeyup={event => key(event, 'keyUp')} onblur={stopScroll} onmouseleave={stopScroll} onauxclick={event => event.preventDefault()} oncontextmenu={event => event.preventDefault()}>
|
||||
<textarea class="text-input" bind:this={textInput} aria-label={$t("Web page text input")} autocomplete="off" spellcheck="false"
|
||||
oncompositionstart={() => composing = true}
|
||||
oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }}
|
||||
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
|
||||
onblur={stopScroll}></textarea>
|
||||
{#if image && ready && !blank}<img src={image} class:exact={imageBox.exact} style:width={`${imageBox.width}px`} style:height={`${imageBox.height}px`} style:transform={`translate(${imageBox.x}px, ${imageBox.y}px)`} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
|
||||
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true"><Icon icon="scroll" /></span>{/if}
|
||||
</div>
|
||||
</div>
|
||||
<style>
|
||||
.text-input{position:absolute;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none;padding:0;border:0;}
|
||||
.browser{display:flex;flex-direction:column;width:100%;height:100%;min-height:200px;background:var(--rs-bg);color:var(--rs-text);font-family:var(--rs-font-ui)}
|
||||
.toolbar,.findbar{display:flex;align-items:center;gap:4px;padding:5px 8px;border-bottom:1px solid var(--rs-border);background:var(--rs-bg-elevated)}
|
||||
.toolbar{flex-wrap:wrap}.toolbar input{flex:1 1 120px}.findbar input{max-width:320px}.find-count{font-size:12px;white-space:nowrap;color:var(--rs-text-dim);min-width:66px}
|
||||
input,.profile-choice{min-width:0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;padding:5px 8px}
|
||||
input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-focus)}
|
||||
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
|
||||
.browser.blank,.blank .surface{background:transparent}
|
||||
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:26px;height:26px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);pointer-events:none;box-shadow:0 1px 4px #0006}.scroll-anchor :global(svg){width:20px;height:20px;flex-basis:20px}
|
||||
img{display:block;pointer-events:none;user-select:none;will-change:transform}img.exact{image-rendering:pixelated}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
|
||||
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
|
||||
.reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer}
|
||||
.reconnect:focus-visible,summary:focus-visible{outline:2px solid var(--rs-focus);outline-offset:2px}summary{cursor:pointer}
|
||||
dl{display:grid;grid-template-columns:auto 1fr;gap:4px 12px}dd{margin:0;overflow-wrap:anywhere;user-select:text}
|
||||
</style>
|
||||
@@ -0,0 +1,17 @@
|
||||
<script lang="ts">
|
||||
import type { ComponentProps } from "svelte";
|
||||
import Browser from "./Browser.svelte";
|
||||
import EngineSetup from "./EngineSetup.svelte";
|
||||
import { engine, engineReady } from "./engine";
|
||||
// A browser tab shows the engine setup until the engine can start. Then it opens the page.
|
||||
let props: ComponentProps<typeof Browser> = $props();
|
||||
let browser = $state<ReturnType<typeof Browser>>();
|
||||
export async function find() { await browser?.find(); }
|
||||
export function detach() { browser?.detach(); }
|
||||
export async function action(command: string, args: Record<string, unknown> = {}) { await browser?.action(command, args); }
|
||||
</script>
|
||||
{#if engineReady($engine)}
|
||||
<Browser bind:this={browser} {...props} />
|
||||
{:else}
|
||||
<EngineSetup variant="tab" url={props.initial.url} />
|
||||
{/if}
|
||||
@@ -0,0 +1,78 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { confirm } from "@tauri-apps/plugin-dialog";
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { engine, installEngine, installEngineFile, cancelEngine, removeEngine, megabytes } from "./engine";
|
||||
// `tab` fills a browser tab while the engine is missing. `settings` is the Engine section of Settings → Browser.
|
||||
let { variant, url = "" }: { variant: "tab" | "settings"; url?: string } = $props();
|
||||
let failure = $state("");
|
||||
const status = $derived($engine);
|
||||
const phase = $derived(status?.state ?? "missing");
|
||||
const busy = $derived(phase === "downloading" || phase === "installing");
|
||||
const error = $derived(failure || status?.error || "");
|
||||
const web = $derived(variant === "tab" && /^https?:\/\//i.test(url));
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
failure = "";
|
||||
try { await action(); } catch (reason) { failure = String(reason); }
|
||||
}
|
||||
async function remove() {
|
||||
const accepted = await confirm($t("Remove the browser engine? Open browser tabs close. Your profiles, bookmarks, and history stay."), { title: $t("Remove browser engine"), kind: "warning", okLabel: $t("Remove"), cancelLabel: $t("Cancel") });
|
||||
if (accepted) await run(removeEngine);
|
||||
}
|
||||
</script>
|
||||
<section class="engine {variant}" aria-labelledby={`engine-${variant}`} data-engine-state={phase}>
|
||||
{#if variant === "tab"}<span class="mark"><Icon icon="globe" /></span>{/if}
|
||||
<h3 id={`engine-${variant}`}>{$t("Browser engine")}</h3>
|
||||
{#if phase === "installed"}
|
||||
<p>{$t("Version {version} is installed.", { version: status?.version ?? "" })}</p>
|
||||
{:else if phase === "development"}
|
||||
<p>{$t("This development build uses the engine in src-tauri/browser-engine.")}</p>
|
||||
{:else if phase === "unavailable"}
|
||||
<p>{$t("No browser engine is available for this platform yet.")}</p>
|
||||
{:else if phase === "downloading"}
|
||||
<p role="status">{$t("Downloading the browser engine: {received} of {total}.", { received: megabytes(status?.received ?? 0), total: megabytes(status?.bytes ?? 0) })}</p>
|
||||
<progress max={status?.bytes || 1} value={status?.received ?? 0} aria-label={$t("Download progress")}></progress>
|
||||
{:else if phase === "installing"}
|
||||
<p role="status">{$t("Installing the browser engine…")}</p>
|
||||
<progress aria-label={$t("Installation progress")}></progress>
|
||||
{:else if phase === "update"}
|
||||
<p>{$t("This RuneStone version needs browser engine {version}. The download is {size}.", { version: status?.version ?? "", size: megabytes(status?.bytes ?? 0) })}</p>
|
||||
{:else}
|
||||
<p>{$t("The built-in browser needs its engine. The engine is a separate download of {size}.", { size: megabytes(status?.bytes ?? 0) })}</p>
|
||||
{/if}
|
||||
{#if error && !busy}<p class="error" role="alert"><Icon icon="alert" /><span>{$t("The browser engine could not be installed: {reason}", { reason: error })}</span></p>{/if}
|
||||
<div class="actions">
|
||||
{#if busy}
|
||||
<button type="button" disabled={phase === "installing"} onclick={() => void run(cancelEngine)}><Icon icon="close" />{$t("Cancel")}</button>
|
||||
{:else if phase === "missing" || phase === "update"}
|
||||
<button type="button" class="primary" onclick={() => void run(installEngine)}><Icon icon={error ? "refresh" : "download"} />{error ? $t("Retry") : phase === "update" ? $t("Update the engine") : $t("Download the engine")}</button>
|
||||
<button type="button" onclick={() => void run(installEngineFile)}><Icon icon="folder-open" />{$t("Install from file…")}</button>
|
||||
{:else if phase === "installed" && variant === "settings"}
|
||||
<button type="button" class="danger" onclick={() => void remove()}><Icon icon="trash" />{$t("Remove engine")}</button>
|
||||
{/if}
|
||||
{#if web}<button type="button" onclick={() => void run(() => openUrl(url))}><Icon icon="globe" />{$t("Open in default browser")}</button>{/if}
|
||||
</div>
|
||||
</section>
|
||||
<style>
|
||||
.engine { color: var(--rs-text); font-family: var(--rs-font-ui); }
|
||||
.engine.tab { box-sizing: border-box; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; height: 100%; min-height: 200px; padding: 24px 16px; text-align: center; background: var(--rs-bg); }
|
||||
.engine.settings { padding: var(--rs-settings-row-padding); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
.mark { display: grid; place-items: center; width: 48px; height: 48px; color: var(--rs-accent); }
|
||||
.mark :global(svg) { width: 40px; height: 40px; }
|
||||
h3 { margin: 0 0 4px; font-size: 14px; font-weight: 500; color: var(--rs-text-strong); }
|
||||
.tab h3 { font-size: var(--rs-settings-heading-size); }
|
||||
p { margin: 4px 0; max-width: 60ch; color: var(--rs-text); font-size: var(--rs-settings-description-size); line-height: 1.6; }
|
||||
.error { display: flex; align-items: flex-start; gap: 6px; color: var(--rs-error); text-align: left; }
|
||||
.error :global(svg) { flex: none; width: 16px; height: 16px; margin-top: 2px; }
|
||||
.error span { overflow-wrap: anywhere; }
|
||||
progress { width: min(320px, 100%); height: 8px; accent-color: var(--rs-accent); }
|
||||
.actions { display: flex; flex-wrap: wrap; justify-content: inherit; gap: 8px; margin-top: 8px; }
|
||||
.tab .actions { justify-content: center; }
|
||||
button { display: inline-flex; align-items: center; gap: 7px; min-height: var(--rs-settings-control-height); padding: 4px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; cursor: pointer; }
|
||||
button:hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||
button:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
|
||||
button:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||
button.primary, button.primary:hover { border-color: var(--rs-accent); background: var(--rs-accent); color: var(--rs-on-accent); }
|
||||
button.danger { border-color: var(--rs-error); color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,103 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { onDestroy } from 'svelte';
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
import { showActionMenu } from '$lib/ui/managedActionMenu';
|
||||
import WebData from './WebData.svelte';
|
||||
import EngineSetup from './EngineSetup.svelte';
|
||||
import { state as browserState, request } from './client';
|
||||
import { engine, engineReady } from './engine';
|
||||
let selected = $state('user'), name = $state(''), message = $state('');
|
||||
let search = $state('duckduckgo'), adblock = $state(true), internalLinks = $state(true), rules = $state('');
|
||||
let homepage = $state(''), filterLists = $state(''), ready = $state(false), busy = $state(false);
|
||||
const engines = [{ id: 'duckduckgo', name: 'DuckDuckGo' }, { id: 'google', name: 'Google' }, { id: 'bing', name: 'Bing' }];
|
||||
let closePicker = () => {};
|
||||
onDestroy(() => closePicker());
|
||||
function picker(event: MouseEvent, profile = false) {
|
||||
closePicker();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: profile ? $t('Profile') : $t('Search engine'),
|
||||
parent: anchor.closest('dialog') ?? undefined,
|
||||
items: (profile ? $browserState?.profiles || [] : engines).map(choice => ({ label: choice.name,
|
||||
radio: true, checked: choice.id === (profile ? selected : search),
|
||||
run: () => { if (profile) selected = choice.id; else { search = choice.id; void save(); } } })) }).close;
|
||||
}
|
||||
// The browser settings live in the engine, so they load when the engine can start.
|
||||
const installed = $derived(engineReady($engine));
|
||||
let loading = false;
|
||||
$effect(() => {
|
||||
if (!installed) { ready = false; loading = false; return; }
|
||||
if (loading) return;
|
||||
loading = true;
|
||||
void request('state').then(value => {
|
||||
selected = value.profiles[0].id; search = value.settings.search; adblock = value.settings.adblock;
|
||||
internalLinks = value.settings.linkDestination === 'internal'; rules = value.settings.personalRules;
|
||||
homepage = value.settings.homepage || ''; filterLists = (value.settings.filterLists || []).join('\n'); ready = true;
|
||||
}).catch(error => message = String(error));
|
||||
});
|
||||
async function act(command: string, args: Record<string, unknown>) {
|
||||
try { const next = await request(command, args); message = $t('Changes saved.'); return next; } catch (error) { message = String(error); return null; }
|
||||
}
|
||||
async function create(duplicate: boolean) {
|
||||
if (!name.trim()) { message = $t('Enter a profile name.'); return; }
|
||||
const result = await act(duplicate ? 'duplicateProfile' : 'createProfile', duplicate ? { profileId: selected, name } : { name });
|
||||
if (result) { selected = result.profiles.at(-1)!.id; name = ''; }
|
||||
}
|
||||
// Settings apply at once: a switch or a choice on change, a text field when it loses focus.
|
||||
// A change during a save starts one more save after it.
|
||||
let pending = false;
|
||||
async function save() {
|
||||
if (!ready) return;
|
||||
if (busy) { pending = true; return; }
|
||||
busy = true; message = $t('Saving browser settings…');
|
||||
try {
|
||||
await act('settings', { search, adblock, linkDestination: internalLinks ? 'internal' : 'external', personalRules: rules,
|
||||
homepage, filterLists: filterLists.split(/\r?\n/).map(value => value.trim()).filter(Boolean) });
|
||||
} finally { busy = false; }
|
||||
if (pending) { pending = false; void save(); }
|
||||
}
|
||||
</script>
|
||||
<div class="settings">
|
||||
<h2>{$t("Browser")}</h2><p>{$t("Choose how you browse within RuneStone.")}</p>
|
||||
<EngineSetup variant="settings" />
|
||||
{#if !installed}
|
||||
<p class="note">{$t("The other browser settings show after the engine is installed.")}</p>
|
||||
{:else}
|
||||
<h3>{$t("General")}</h3>
|
||||
<fieldset disabled={!ready} onchange={() => void save()}>
|
||||
<div class="card">
|
||||
<label class="row"><span>{$t("Open web links in RuneStone")}<small>{$t("Turn this off to use your system browser.")}</small></span><input class="rs-switch" type="checkbox" role="switch" aria-label={$t("Open web links in RuneStone")} bind:checked={internalLinks}></label>
|
||||
<label class="row"><span>{$t("Homepage")}<small>{$t("The page to open in each new browser tab. Leave blank for an empty page.")}</small></span><input class="address" type="url" aria-label={$t("Homepage")} placeholder="https://example.com" maxlength="8192" bind:value={homepage}></label>
|
||||
<div class="row"><span>{$t("Search engine")}</span><button type="button" class="picker" aria-label={$t("Search engine")} aria-haspopup="menu" onclick={event => picker(event)}>{engines.find(engine => engine.id === search)?.name ?? 'DuckDuckGo'}<Icon icon="chevron-down" /></button></div>
|
||||
<label class="row"><span>{$t("Block ads and trackers")}<small>{$t("Apply the filter lists and personal rules to all browser tabs.")}</small></span><input class="rs-switch" type="checkbox" role="switch" aria-label={$t("Block ads and trackers")} bind:checked={adblock}></label>
|
||||
<label class="row list-row"><span>{$t("Ad blocking lists")}<small>{$t("One HTTPS filter list URL per line, up to eight lists. New lists download when you leave the field.")}</small></span><textarea aria-label={$t("Ad blocking lists")} rows="4" maxlength="66000" placeholder="https://easylist.to/easylist/easylist.txt" bind:value={filterLists}></textarea></label>
|
||||
</div>
|
||||
<label class="rules">{$t("Personal filter rules")}<small>{$t("Use one rule per line. Block a domain with ||ads.example.com^, allow it with @@||ads.example.com^, or hide an element with example.com##.advertisement. Save to apply the rules.")}</small><textarea rows="4" maxlength="100000" placeholder={'! Block an advertising domain\n||ads.example.com^\n! Hide an element on one site\nexample.com##.advertisement'} bind:value={rules}></textarea></label>
|
||||
</fieldset>
|
||||
<h3>{$t("Profiles")}</h3><p>{$t("New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.")}</p>
|
||||
<div class="card profiles">
|
||||
<div class="profile-choice"><span>{$t("Profile")}</span><button type="button" class="picker" aria-label={$t("Profile")} aria-haspopup="menu" disabled={!ready} onclick={event => picker(event, true)}>{$browserState?.profiles.find(profile => profile.id === selected)?.name ?? $t('Profile')}<Icon icon="chevron-down" /></button></div>
|
||||
<label>{$t("New profile name")}<input bind:value={name} maxlength="60" placeholder={$t("Profile name")}></label>
|
||||
<div class="actions"><button onclick={() => void create(false)}><Icon icon="plus" />{$t("New blank profile")}</button><button onclick={() => void create(true)}><Icon icon="duplicate" />{$t("Duplicate profile")}</button></div>
|
||||
<p class="note">{$t("Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.")}</p>
|
||||
</div>
|
||||
<h3>{$t("Web data")}</h3><p>{$t("Clear data for the selected profile. Its browser tabs will close. Bookmarks remain.")}</p>
|
||||
<div class="actions"><button onclick={() => void act('clearData', { profileId: selected, kind: 'cache' })}>{$t("Clear cache")}</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'cookies' })}>{$t("Clear cookies")}</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'history' })}>{$t("Clear history")}</button></div>
|
||||
<p role="status">{message}</p>
|
||||
{#if ready}<WebData profileId={selected} />{/if}
|
||||
{/if}
|
||||
</div>
|
||||
<style>
|
||||
.settings{color:var(--rs-text);font-family:var(--rs-font-ui)}h2{margin:0;font-size:var(--rs-settings-heading-size);font-weight:500;color:var(--rs-text-strong)}h3{margin:var(--rs-settings-section-gap) 0 var(--rs-settings-gap);font-size:14px;font-weight:500}
|
||||
p{color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.6}.card{padding:0 var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
|
||||
.row{display:flex;justify-content:space-between;align-items:center;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}.row+.row{border-top:1px solid var(--rs-border)}
|
||||
input:not(.rs-switch),textarea,button{border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;box-sizing:border-box;min-height:var(--rs-settings-control-height);padding:4px 8px}
|
||||
button{display:inline-flex;align-items:center;gap:7px;background:var(--rs-bg-elevated);cursor:pointer}button:hover{background:var(--rs-bg-active)}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--rs-focus);outline-offset:1px}
|
||||
.picker{justify-content:space-between;min-width:140px;max-width:100%;overflow-wrap:anywhere;text-align:left}
|
||||
.rules{display:flex;flex-direction:column;gap:7px;margin:16px 0}.profiles{padding-top:16px;padding-bottom:8px}.profiles label,.profile-choice{display:flex;flex-direction:column;gap:7px;margin-bottom:14px}
|
||||
.actions{display:flex;flex-wrap:wrap;gap:8px}.note{margin-bottom:0}
|
||||
fieldset{border:0;margin:0;padding:0;min-width:0}small{display:block;color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.5;margin-top:5px}
|
||||
.row>span{flex:1}.address,.list-row textarea{width:260px;max-width:48%;box-sizing:border-box}.list-row{align-items:flex-start}textarea{resize:vertical}
|
||||
@media(max-width:600px){.row{flex-wrap:wrap}.address,.list-row textarea{width:100%;max-width:100%}}
|
||||
</style>
|
||||
@@ -0,0 +1,67 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { onDestroy } from 'svelte';
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
import { showActionMenu } from '$lib/ui/managedActionMenu';
|
||||
import { request } from './client';
|
||||
let { profileId }: { profileId: string } = $props();
|
||||
type Cookie = { id: string; name: string; domain: string; path: string };
|
||||
type Visit = { id: string; url: string; title: string; at: number };
|
||||
type Data = { profileId: string; cookies: Cookie[]; history: Visit[] };
|
||||
let data = $state<Data | null>(null), error = $state(''), busy = $state(false), query = $state('');
|
||||
let kind = $state<'cookies' | 'history'>('cookies');
|
||||
let closePicker = () => {};
|
||||
onDestroy(() => closePicker());
|
||||
function chooseKind(event: MouseEvent) {
|
||||
closePicker();
|
||||
const anchor = event.currentTarget as HTMLButtonElement, rect = anchor.getBoundingClientRect();
|
||||
closePicker = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: $t('Web data type'),
|
||||
parent: anchor.closest('dialog') ?? undefined,
|
||||
items: (['cookies', 'history'] as const).map(value => ({ label: value === 'cookies' ? $t('Cookies') : $t('History'),
|
||||
radio: true, checked: kind === value, run: () => kind = value })) }).close;
|
||||
}
|
||||
let generation = 0;
|
||||
const cookies = $derived((data?.cookies || []).filter(item => `${item.domain} ${item.name} ${item.path}`.toLowerCase().includes(query.toLowerCase())));
|
||||
const history = $derived((data?.history || []).filter(item => `${item.title} ${item.url}`.toLowerCase().includes(query.toLowerCase())));
|
||||
$effect(() => { const id = profileId; data = null; query = ''; void refresh(id); return () => { generation++; }; });
|
||||
async function refresh(id = profileId) {
|
||||
const ticket = ++generation; busy = true; error = '';
|
||||
try { const next = await request<Data>('webData', { profileId: id }); if (ticket === generation && id === profileId) data = next; }
|
||||
catch (reason) { if (ticket === generation) error = String(reason); }
|
||||
finally { if (ticket === generation) busy = false; }
|
||||
}
|
||||
async function remove(command: string, id: string) {
|
||||
const selected = profileId; const ticket = ++generation; busy = true; error = '';
|
||||
try { await request(command, { profileId: selected, id }); if (ticket === generation && selected === profileId) await refresh(selected); }
|
||||
catch (reason) { if (ticket === generation) error = String(reason); }
|
||||
finally { if (ticket === generation) busy = false; }
|
||||
}
|
||||
</script>
|
||||
<section aria-label={$t("Individual web data")}>
|
||||
<div class="toolbar">
|
||||
<div class="choice"><span>{$t("Show")}</span><button type="button" aria-label={$t("Web data type")} aria-haspopup="menu" onclick={chooseKind}>{kind === 'cookies' ? $t('Cookies') : $t('History')}<Icon icon="chevron-down" /></button></div>
|
||||
<label class="search">{$t("Filter")}<input type="search" aria-label={$t("Filter web data")} bind:value={query} placeholder={$t("Search this profile")}></label>
|
||||
<button disabled={busy} onclick={() => void refresh()}><Icon icon="refresh" />{$t("Refresh")}</button>
|
||||
</div>
|
||||
<p>{$t("Remove individual entries for this profile. Open tabs stay open. Sites can create cookies again.")}</p>
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
{#if busy}<p role="status">{$t("Please wait…")}</p>{/if}
|
||||
<div class="entries" aria-busy={busy}>
|
||||
{#if kind === 'cookies'}
|
||||
{#each cookies as cookie (cookie.id)}<div class="entry"><div><strong>{cookie.name || $t("(unnamed cookie)")}</strong><small>{cookie.domain} · {cookie.path}</small></div><button disabled={busy} aria-label={$t("Remove cookie {name} from {domain} at {path}", { name: cookie.name, domain: cookie.domain, path: cookie.path })} onclick={() => void remove('removeCookie', cookie.id)}><Icon icon="trash" />{$t("Remove")}</button></div>{/each}
|
||||
{#if data && !cookies.length}<p>{$t("No matching cookies.")}</p>{/if}
|
||||
{:else}
|
||||
{#each history as visit (visit.id)}<div class="entry"><div><strong>{visit.title || visit.url}</strong><small>{visit.url}</small><small>{new Date(visit.at).toLocaleString()}</small></div><button disabled={busy} aria-label={$t("Remove history entry {name}", { name: visit.title || visit.url })} onclick={() => void remove('removeHistory', visit.id)}><Icon icon="trash" />{$t("Remove")}</button></div>{/each}
|
||||
{#if data && !history.length}<p>{$t("No matching history.")}</p>{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
<style>
|
||||
section{margin-top:var(--rs-settings-section-gap)}.toolbar{display:flex;align-items:end;gap:var(--rs-settings-gap);flex-wrap:wrap}
|
||||
label,.choice{display:flex;flex-direction:column;gap:4px}.search{flex:1;min-width:150px}input,button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);font:inherit;padding:4px 8px}
|
||||
button{display:inline-flex;align-items:center;justify-content:center;gap:6px;flex:none;cursor:pointer}button:hover{background:var(--rs-bg-active)}button:disabled{opacity:.6;cursor:wait}
|
||||
button:focus-visible,input:focus-visible{outline:2px solid var(--rs-focus);outline-offset:1px}
|
||||
p,small{font-size:var(--rs-settings-description-size);color:var(--rs-text-dim);line-height:1.5}.entries{max-height:320px;overflow:auto;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);padding:0 var(--rs-settings-row-padding)}
|
||||
.entry{display:flex;gap:var(--rs-settings-gap);align-items:center;padding:var(--rs-settings-row-padding) 0}.entry+.entry{border-top:1px solid var(--rs-border)}.entry>div{flex:1;min-width:0;overflow-wrap:anywhere}small{display:block}strong{font-weight:500}[role=alert]{color:var(--rs-error)}
|
||||
@media(max-width:450px){.entry{flex-wrap:wrap}.entry>div{flex-basis:100%}}
|
||||
</style>
|
||||
@@ -0,0 +1,23 @@
|
||||
export type ScrollPoint = { x: number; y: number };
|
||||
|
||||
/** Middle-button scrolling uses wheel input because offscreen Chromium has no native scroll cursor. */
|
||||
export class AutoScroll {
|
||||
anchor: ScrollPoint | null = null;
|
||||
private point: ScrollPoint = { x: 0, y: 0 };
|
||||
private moved = false;
|
||||
private previous = 0;
|
||||
start(point: ScrollPoint) { this.anchor = { ...point }; this.point = { ...point }; this.moved = false; this.previous = 0; }
|
||||
move(point: ScrollPoint) {
|
||||
this.point = point;
|
||||
if (this.anchor && Math.hypot(point.x - this.anchor.x, point.y - this.anchor.y) > 12) this.moved = true;
|
||||
}
|
||||
release() { if (this.moved) this.stop(); }
|
||||
stop() { this.anchor = null; this.previous = 0; }
|
||||
delta(time: number) {
|
||||
const elapsed = this.previous ? Math.min(50, time - this.previous) : 0;
|
||||
this.previous = time;
|
||||
if (!this.anchor) return null;
|
||||
const speed = (distance: number) => Math.sign(distance) * Math.min(3000, Math.max(0, Math.abs(distance) - 12) * 18);
|
||||
return { x: speed(this.point.x - this.anchor.x) * elapsed / 1000, y: speed(this.point.y - this.anchor.y) * elapsed / 1000 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
|
||||
import { writable } from 'svelte/store';
|
||||
import { SnapshotOrder } from './snapshotOrder';
|
||||
|
||||
export type Profile = { id: string; name: string };
|
||||
export type Tab = { id: string; transferToken?: string; profileId: string; title: string; favicon?: string | null; url: string; loading: boolean; blocked: number; canBack: boolean; canForward: boolean; find?: { text: string; matches: number; activeMatch: number; pending: boolean } | null };
|
||||
export type Snapshot = {
|
||||
runtimeId?: string; revision?: number;
|
||||
profiles: Profile[]; tabs: Tab[];
|
||||
bookmarks: { id: string; profileId: string; title: string; url: string }[];
|
||||
settings: { search: string; adblock: boolean; linkDestination: string; personalRules: string; homepage: string; filterLists: string[] };
|
||||
};
|
||||
export const state = writable<Snapshot | null>(null);
|
||||
export const pageErrors = writable<Record<string, string>>({});
|
||||
export type BrowserFrame = { tabId: string; frameId: number; mime: 'image/png' | 'image/jpeg'; data: string; width: number; height: number; scale?: number };
|
||||
export type PageMenu = { event: string; tabId: string; token: string; x: number; y: number; linkURL: string; srcURL: string; hasImageContents: boolean; isEditable: boolean; selectionText: string; editFlags: Record<string, boolean>; url?: string };
|
||||
export const frames = new Map<string, (frame: BrowserFrame) => void>();
|
||||
export const pageEvents = new Map<string, (event: PageMenu) => void>();
|
||||
let snapshots = new SnapshotOrder();
|
||||
let session: string | undefined;
|
||||
function isSnapshot(value: unknown): value is Snapshot {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return Array.isArray(record.profiles) && Array.isArray(record.tabs) && Array.isArray(record.bookmarks) && !!record.settings && typeof record.settings === 'object';
|
||||
}
|
||||
export async function request<T = Snapshot>(command: string, args: Record<string, unknown> = {}): Promise<T> {
|
||||
const result = await invoke<T>('browser_request', { command, args, session });
|
||||
if (isSnapshot(result) && snapshots.accept(result)) state.set(result);
|
||||
return result;
|
||||
}
|
||||
export async function connect(signal: AbortSignal) {
|
||||
session = await invoke<string>('browser_connect');
|
||||
const window = getCurrentWebviewWindow();
|
||||
const offState = await window.listen<PageMenu & { state?: Snapshot; message?: string }>('browser-state', ({ payload }) => {
|
||||
if (signal.aborted) return;
|
||||
if (isSnapshot(payload.state) && snapshots.accept(payload.state)) state.set(payload.state);
|
||||
if (payload.message && payload.tabId) pageErrors.update(errors => ({ ...errors, [payload.tabId!]: payload.message! }));
|
||||
if (payload.tabId) pageEvents.get(payload.tabId)?.(payload);
|
||||
});
|
||||
const offFrame = await window.listen<BrowserFrame>('browser-frame', ({ payload }) => {
|
||||
if (!signal.aborted) frames.get(payload.tabId)?.(payload);
|
||||
if (!frames.has(payload.tabId)) void request('frameAck', { tabId: payload.tabId, frameId: payload.frameId }).catch(() => {});
|
||||
});
|
||||
const stop = async () => { offState(); offFrame(); frames.clear(); pageEvents.clear(); state.set(null); session = undefined; snapshots = new SnapshotOrder(); pageErrors.set({}); await invoke('browser_stop'); };
|
||||
if (signal.aborted) await stop();
|
||||
return stop;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import { writable } from 'svelte/store';
|
||||
import { tr } from '../i18n/index.ts';
|
||||
|
||||
/** The engine states of `browser_engine_status`. See src-tauri/src/browser_engine.rs. */
|
||||
export type EngineStatus = {
|
||||
state: 'installed' | 'missing' | 'update' | 'downloading' | 'installing' | 'unavailable' | 'development';
|
||||
version: string; bytes: number; received: number; error: string | null;
|
||||
};
|
||||
export const engine = writable<EngineStatus | null>(null);
|
||||
/** True when the engine can start: the pinned version is installed, or a development engine is staged. */
|
||||
export const engineReady = (status: EngineStatus | null) => status?.state === 'installed' || status?.state === 'development';
|
||||
const update = (status: EngineStatus) => { engine.set(status); return status; };
|
||||
|
||||
/** Follow the engine status in this window. A failed status request reports the engine as unavailable. */
|
||||
export async function watchEngine(signal: AbortSignal) {
|
||||
const off = await listen<EngineStatus>('browser-engine', ({ payload }) => { if (!signal.aborted) engine.set(payload); });
|
||||
try { update(await invoke<EngineStatus>('browser_engine_status')); }
|
||||
catch (error) { update({ state: 'unavailable', version: '', bytes: 0, received: 0, error: String(error) }); }
|
||||
return () => { off(); engine.set(null); };
|
||||
}
|
||||
export const installEngine = () => invoke<EngineStatus>('browser_engine_install').then(update);
|
||||
export const installEngineFile = () => invoke<EngineStatus>('browser_engine_install_file').then(update);
|
||||
export const cancelEngine = () => invoke<EngineStatus>('browser_engine_cancel').then(update);
|
||||
export const removeEngine = () => invoke<EngineStatus>('browser_engine_remove').then(update);
|
||||
/** A download size in megabytes, such as "161 MB". */
|
||||
export const megabytes = (bytes: number) => tr('{size} MB', { size: Math.max(bytes ? 1 : 0, Math.round(bytes / 1_000_000)) });
|
||||
@@ -0,0 +1,134 @@
|
||||
import { tr } from "../i18n/index.ts";
|
||||
import { keys } from '../ui/shortcuts.ts';
|
||||
import { mount, unmount } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
|
||||
import type { PluginApi, PluginViewOpenOptions } from '$lib/plugins/sdk';
|
||||
import BrowserTab from './BrowserTab.svelte';
|
||||
import Settings from './Settings.svelte';
|
||||
import Bookmarks from './Bookmarks.svelte';
|
||||
import { connect, request, state } from './client';
|
||||
import { engine, engineReady, watchEngine } from './engine';
|
||||
import type { TabStatus } from './tabSession';
|
||||
|
||||
type BrowserControl = { find(): Promise<void>; detach(): void; action(command: string, args?: Record<string, unknown>): Promise<void> };
|
||||
type SavedView = { view: string; profileId?: string; url?: string; runtimeId: string; status?: TabStatus; control?: BrowserControl };
|
||||
|
||||
export async function activate(api: PluginApi) {
|
||||
const offEngine = await watchEngine(api.signal); api.onDispose(offEngine);
|
||||
const dispose = await connect(api.signal); api.onDispose(dispose);
|
||||
const owners = new Map<string, SavedView>();
|
||||
const offMove = await getCurrentWebviewWindow().listen<{ tabId: string }>('browser-tab-moved', ({ payload }) => {
|
||||
const saved = owners.get(payload.tabId);
|
||||
if (!saved) return;
|
||||
saved.control?.detach();
|
||||
api.closeView?.(saved.view);
|
||||
});
|
||||
api.onDispose(offMove);
|
||||
const off = state.subscribe(value => {
|
||||
for (const tab of value?.tabs || []) {
|
||||
const saved = owners.get(tab.id);
|
||||
if (saved) {
|
||||
saved.profileId = tab.profileId; if (tab.url) saved.url = tab.url;
|
||||
api.updateViewTitle?.(saved.view, `${tab.title || 'Browser'} · ${value!.profiles.find(p => p.id === tab.profileId)?.name || 'User'}`.slice(0, 200));
|
||||
api.updateViewIcon?.(saved.view, tab.favicon ?? null);
|
||||
}
|
||||
}
|
||||
});
|
||||
api.onDispose(off);
|
||||
const mounts = new Set<() => Promise<void>>();
|
||||
function retain(instance: ReturnType<typeof mount>) {
|
||||
let result: Promise<void> | undefined;
|
||||
const cleanup = () => result ??= unmount(instance).then(() => { mounts.delete(cleanup); });
|
||||
mounts.add(cleanup); return cleanup;
|
||||
}
|
||||
api.onDispose(async () => { await Promise.all([...mounts].map(cleanup => cleanup())); });
|
||||
async function open(profileId?: string, url?: string, options?: PluginViewOpenOptions, tabId?: string, pinned = false) {
|
||||
const id = `tab-${crypto.randomUUID()}`;
|
||||
const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
|
||||
const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); };
|
||||
// A new tab with the home page of the profile opens in a pane beside this tab.
|
||||
const split = (direction: 'right' | 'down') => {
|
||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||
void open(current?.profileId || saved.profileId, undefined, { split: direction, relativeTo: id });
|
||||
};
|
||||
api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
|
||||
tabDragData: ({ pinned }) => {
|
||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||
if (saved.status?.phase !== 'ready' || !current?.transferToken) return undefined;
|
||||
return JSON.stringify({ tabId: current.id, transferToken: current.transferToken, pinned });
|
||||
},
|
||||
find: () => { api.openView(id); void saved.control?.find(); },
|
||||
tabActions: ({ pinned }) => {
|
||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||
const ready = saved.status?.phase === 'ready';
|
||||
const web = ready && /^https?:\/\//.test(current?.url || '');
|
||||
return [
|
||||
{ separator: true },
|
||||
{ label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
|
||||
{ label: tr("New tab to the right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
|
||||
{ label: tr("New tab below"), icon: 'split-down', disabled: !ready, run: () => split('down') },
|
||||
{ separator: true },
|
||||
{ label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
|
||||
{ label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') },
|
||||
{ label: tr("Bookmark"), icon: 'bookmark', disabled: !web, run: () => run('bookmark') },
|
||||
];
|
||||
}, mount: container => {
|
||||
let runtimeId = '';
|
||||
const instance = mount(BrowserTab, { target: container, props: {
|
||||
initial: { tabId, profileId: saved.profileId, url: saved.url },
|
||||
onSessionChange: value => {
|
||||
saved.status = value;
|
||||
if (value.tabId !== runtimeId || value.phase === 'closed') {
|
||||
owners.delete(runtimeId);
|
||||
runtimeId = value.phase === 'closed' ? '' : value.tabId;
|
||||
if (runtimeId) owners.set(runtimeId, saved);
|
||||
}
|
||||
saved.runtimeId = runtimeId;
|
||||
api.updateViewIcon?.(saved.view, get(state)?.tabs.find(tab => tab.id === runtimeId)?.favicon ?? null);
|
||||
if (value.profileId) saved.profileId = value.profileId;
|
||||
if (value.url) saved.url = value.url;
|
||||
},
|
||||
newTab: (profile: string, url?: string) => open(profile, url),
|
||||
} });
|
||||
tabId = undefined;
|
||||
saved.control = instance;
|
||||
const cleanup = retain(instance);
|
||||
return async () => { await cleanup(); if (saved.control === instance) saved.control = undefined; };
|
||||
} });
|
||||
api.openView(id, options);
|
||||
}
|
||||
api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', icon: 'globe', run: () => open() });
|
||||
api.contribute('browser', {
|
||||
// A new tab shows the engine setup when the engine is missing.
|
||||
newTab: url => open(undefined, url),
|
||||
mountSettings: container => retain(mount(Settings, { target: container })),
|
||||
mountBookmarks: container => retain(mount(Bookmarks, { target: container, props: { open } })),
|
||||
// A web link never starts a download. Without an engine, the link opens in the system browser.
|
||||
open: async url => {
|
||||
if (!engineReady(get(engine))) return false;
|
||||
const value = await request('state');
|
||||
if (value.settings.linkDestination === 'external') return false;
|
||||
await open(undefined, url); return true;
|
||||
},
|
||||
});
|
||||
api.registerTabDrop?.(async data => {
|
||||
const payload = JSON.parse(data);
|
||||
if (!payload || typeof payload.tabId !== 'string' || typeof payload.transferToken !== 'string') throw new Error(tr("Invalid browser tab transfer."));
|
||||
const existing = owners.get(payload.tabId);
|
||||
if (existing) { api.openView(existing.view); return; }
|
||||
const snapshot = await request('adoptTab', { tabId: payload.tabId, transferToken: payload.transferToken });
|
||||
const current = snapshot.tabs.find(tab => tab.id === payload.tabId);
|
||||
if (!current) throw new Error(tr("The browser tab is unavailable."));
|
||||
await open(current.profileId, current.url, undefined, current.id, payload.pinned === true);
|
||||
});
|
||||
const incoming = new URLSearchParams(location.search).get('browserTab');
|
||||
if (incoming) {
|
||||
const snapshot = await request('adoptTab', { tabId: incoming });
|
||||
const current = snapshot.tabs.find(tab => tab.id === incoming);
|
||||
await open(current?.profileId, current?.url, undefined, incoming, new URLSearchParams(location.search).get('browserPinned') === 'true');
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.delete('browserTab'); url.searchParams.delete('browserPinned');
|
||||
history.replaceState(null, '', url.pathname + url.search);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
type Wheel = { type: 'mouseWheel'; x: number; y: number; deltaX: number; deltaY: number; modifiers?: unknown[] };
|
||||
|
||||
/** Keep one pending wheel event while the transport processes the current event. */
|
||||
export class WheelQueue {
|
||||
private pending?: Wheel;
|
||||
private running = false;
|
||||
private closed = false;
|
||||
private send: (input: Wheel) => Promise<unknown>;
|
||||
constructor(send: (input: Wheel) => Promise<unknown>) { this.send = send; }
|
||||
push(input: Wheel) {
|
||||
if (this.closed) return;
|
||||
const previous = this.pending;
|
||||
// A direction change replaces stale motion instead of replaying it later.
|
||||
const add = (old: number, next: number) => Math.sign(old) === Math.sign(next) || !next ? old + next : next;
|
||||
this.pending = { ...input,
|
||||
deltaX: Math.max(-2000, Math.min(2000, previous ? add(previous.deltaX, input.deltaX) : input.deltaX)),
|
||||
deltaY: Math.max(-2000, Math.min(2000, previous ? add(previous.deltaY, input.deltaY) : input.deltaY)) };
|
||||
void this.flush();
|
||||
}
|
||||
clear() { this.pending = undefined; }
|
||||
close() { this.closed = true; this.clear(); }
|
||||
private async flush() {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
try {
|
||||
while (this.pending && !this.closed) {
|
||||
const input = this.pending; this.pending = undefined;
|
||||
await this.send(input);
|
||||
}
|
||||
} finally { this.running = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export class SnapshotOrder {
|
||||
private runtimeId = '';
|
||||
private revision = -1;
|
||||
private retired = new Set<string>();
|
||||
|
||||
accept(value: { runtimeId?: string; revision?: number }): boolean {
|
||||
if (!value.runtimeId || !Number.isSafeInteger(value.revision)) return true;
|
||||
if (this.retired.has(value.runtimeId)) return false;
|
||||
if (value.runtimeId !== this.runtimeId) {
|
||||
if (this.runtimeId) this.retired.add(this.runtimeId);
|
||||
this.runtimeId = value.runtimeId;
|
||||
this.revision = -1;
|
||||
}
|
||||
if (value.revision! <= this.revision) return false;
|
||||
this.revision = value.revision!;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { message, tr } from "../i18n/index.ts";
|
||||
import type { Snapshot } from './client';
|
||||
|
||||
type Transport = (command: string, args?: Record<string, unknown>) => Promise<unknown>;
|
||||
export type TabStatus = {
|
||||
tabId: string; profileId?: string; url?: string;
|
||||
phase: 'connecting' | 'ready' | 'disconnected' | 'closed';
|
||||
message: string;
|
||||
detail?: { operation: string; reason: string; tabId: string; time: string };
|
||||
};
|
||||
const connectionLost = (error: unknown) => /Unknown browser tab|stopped responding|timed out|response did not match|broken pipe|os error (109|232|10053|10054)\b/i.test(String(error));
|
||||
|
||||
export class TabSession {
|
||||
value: TabStatus;
|
||||
private transport: Transport;
|
||||
private changed: (value: TabStatus) => void;
|
||||
private pending?: Promise<void>;
|
||||
private closed = false;
|
||||
private recovered = false;
|
||||
constructor(transport: Transport, initial: { tabId?: string; profileId?: string; url?: string }, changed: (value: TabStatus) => void) {
|
||||
this.transport = transport; this.changed = changed;
|
||||
this.value = { ...initial, tabId: initial.tabId || '', phase: 'connecting', message: 'Opening browser…' };
|
||||
}
|
||||
private update(value: Partial<TabStatus>) {
|
||||
this.value = { ...this.value, ...value }; this.changed(this.value);
|
||||
}
|
||||
observe(snapshot: Snapshot) {
|
||||
const tab = snapshot.tabs.find(tab => tab.id === this.value.tabId);
|
||||
if (tab) {
|
||||
this.value.profileId = tab.profileId;
|
||||
// The first snapshot can arrive before navigation starts.
|
||||
if (tab.url) this.value.url = tab.url;
|
||||
}
|
||||
}
|
||||
private failure(operation: string, error: unknown, tabId = this.value.tabId, phase: 'ready' | 'disconnected' = 'disconnected') {
|
||||
this.update({ phase, message: phase === 'ready' ? message('The browser could not complete this request. Check the error details.') : connectionLost(error)
|
||||
? message('This tab lost its browser connection. Select Reconnect to restore the page.')
|
||||
: message('The browser could not complete this request. Check the details, then select Reconnect.'),
|
||||
detail: { operation, reason: String(error), tabId, time: new Date().toISOString() } });
|
||||
}
|
||||
connect(): Promise<void> {
|
||||
if (this.closed) return Promise.resolve();
|
||||
if (this.pending) return this.pending;
|
||||
this.pending = this.restore().finally(() => { this.pending = undefined; });
|
||||
return this.pending;
|
||||
}
|
||||
private async restore() {
|
||||
this.update({ phase: 'connecting', message: this.value.tabId ? message('Reconnecting browser…') : message('Opening browser…') });
|
||||
let operation = 'state';
|
||||
// The host discards a failed transport before the next request.
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
operation = 'state';
|
||||
const snapshot = await this.transport('state') as Snapshot;
|
||||
if (this.closed) return;
|
||||
if (snapshot.tabs.some(tab => tab.id === this.value.tabId)) {
|
||||
this.observe(snapshot); this.update({ phase: 'ready', message: '' }); return;
|
||||
}
|
||||
const profileId = this.value.profileId || snapshot.profiles[0]?.id;
|
||||
operation = 'newTab';
|
||||
const result = await this.transport('newTab', { profileId, ...(this.value.url ? { url: this.value.url } : {}) }) as { tabId: string };
|
||||
if (this.closed) { await this.transport('closeTab', { tabId: result.tabId }).catch(() => {}); return; }
|
||||
this.update({ tabId: result.tabId, profileId });
|
||||
operation = 'state';
|
||||
const current = await this.transport('state') as Snapshot;
|
||||
if (this.closed) return;
|
||||
if (current.tabs.some(tab => tab.id === result.tabId)) {
|
||||
this.observe(current); this.update({ phase: 'ready', message: '' }); return;
|
||||
}
|
||||
if (attempt === 1) throw new Error(tr("The runtime restarted twice while opening this tab."));
|
||||
} catch (error) {
|
||||
if (this.closed) return;
|
||||
if (attempt === 0 && connectionLost(error)) continue;
|
||||
this.failure(operation, error); return;
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Returns the reply of the engine, or undefined when the request did not complete. */
|
||||
async send(command: string, args: Record<string, unknown> = {}): Promise<unknown> {
|
||||
if (this.closed || this.value.phase !== 'ready') return;
|
||||
const tabId = this.value.tabId;
|
||||
try {
|
||||
const reply = await this.transport(command, { ...args, tabId });
|
||||
if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' });
|
||||
return reply;
|
||||
} catch (error) {
|
||||
// Replies from the previous connection cannot replace the current error.
|
||||
if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return;
|
||||
const lost = connectionLost(error);
|
||||
this.failure(command, error, tabId, lost ? 'disconnected' : 'ready');
|
||||
if (lost && !this.recovered) {
|
||||
this.recovered = true;
|
||||
await this.connect();
|
||||
// Only an explicit address submission is safe to repeat.
|
||||
if (command === 'navigate' && this.value.phase === 'ready') await this.send(command, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
detach() { this.closed = true; this.update({ phase: 'closed' }); }
|
||||
async close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
const tabId = this.value.tabId;
|
||||
this.update({ phase: 'closed' });
|
||||
if (tabId) await this.transport('closeTab', { tabId }).catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Prec, StateEffect, StateField } from "@codemirror/state";
|
||||
import { Decoration, EditorView, keymap, ViewPlugin, WidgetType } from "@codemirror/view";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { completionHub } from "./hub";
|
||||
import type { CompletionHandle, CompletionSnapshot } from "./contracts";
|
||||
class Ghost extends WidgetType {
|
||||
constructor(readonly text: string) { super(); }
|
||||
eq(other: Ghost) { return other.text === this.text; }
|
||||
toDOM() { const span = document.createElement("span"); span.className = "rs-completion-ghost"; span.textContent = this.text; span.setAttribute("aria-hidden", "true"); return span; }
|
||||
}
|
||||
const preview = StateEffect.define<{ text: string; caret: number } | null>();
|
||||
const ghosts = StateField.define({
|
||||
create: () => Decoration.none,
|
||||
update(value, transaction) {
|
||||
if (transaction.docChanged || transaction.selection) value = Decoration.none;
|
||||
for (const effect of transaction.effects) if (effect.is(preview)) value = effect.value
|
||||
? Decoration.set([Decoration.widget({ widget: new Ghost(effect.value.text), side: 1 }).range(effect.value.caret)]) : Decoration.none;
|
||||
return value;
|
||||
},
|
||||
provide: field => EditorView.decorations.from(field),
|
||||
});
|
||||
const handles = new WeakMap<EditorView, CompletionHandle>();
|
||||
type CompletionContext = Pick<CompletionSnapshot, "kind" | "language">;
|
||||
/** Ghost text completion for an editor. The context gives the kind and the language of the current file. */
|
||||
export function completionExtension(documentId: string, context: () => CompletionContext = () => ({ kind: "prose", language: "markdown" })) {
|
||||
return [ghosts, EditorView.baseTheme({ ".rs-completion-ghost": { opacity: "0.65", fontStyle: "italic", pointerEvents: "none" } }),
|
||||
ViewPlugin.fromClass(class {
|
||||
handle: CompletionHandle;
|
||||
disposed = false;
|
||||
sequence = 0;
|
||||
revision = 0;
|
||||
constructor(readonly view: EditorView) {
|
||||
this.handle = completionHub.registerSurface({
|
||||
id: `editor:${documentId}:${crypto.randomUUID()}`,
|
||||
snapshot: () => ({ documentId, revision: this.revision, text: view.state.doc.toString(), caret: view.state.selection.main.head,
|
||||
selectionEnd: view.state.selection.ranges.length > 1 ? -1 : view.state.selection.main.anchor,
|
||||
focused: view.hasFocus, composing: view.composing, readOnly: view.state.readOnly, ...context() }),
|
||||
preview: text => {
|
||||
const sequence = ++this.sequence, caret = view.state.selection.main.head;
|
||||
queueMicrotask(() => { if (!this.disposed && this.sequence === sequence) view.dispatch({ effects: preview.of(text ? { text, caret } : null) }); });
|
||||
},
|
||||
insert: (text, expected) => {
|
||||
if (this.revision !== expected.revision || view.state.selection.main.head !== expected.caret) return false;
|
||||
view.dispatch({ changes: { from: expected.caret, insert: text }, selection: { anchor: expected.caret + text.length }, userEvent: "input.complete", annotations: isolateHistory.of("full") });
|
||||
return true;
|
||||
},
|
||||
});
|
||||
handles.set(view, this.handle);
|
||||
}
|
||||
update(update: import("@codemirror/view").ViewUpdate) {
|
||||
if (update.docChanged) this.revision++;
|
||||
if (update.docChanged || update.selectionSet || update.focusChanged) this.handle.changed();
|
||||
}
|
||||
destroy() { this.disposed = true; this.handle.dispose(); handles.delete(this.view); }
|
||||
}),
|
||||
Prec.high(keymap.of([
|
||||
{ key: "Tab", run: view => !view.composing && !!handles.get(view)?.accept() },
|
||||
{ key: "Escape", run: view => !!handles.get(view)?.dismiss() },
|
||||
{ key: "Mod-Alt-Space", run: view => { handles.get(view)?.request(); return true; } },
|
||||
{ key: "Mod-Alt-ArrowRight", run: view => !!handles.get(view)?.accept(true) },
|
||||
])),
|
||||
EditorView.domEventHandlers({ compositionstart: (_event, view) => { handles.get(view)?.dismiss(); } }),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
// The completion types are part of the public plugin SDK (packages/plugin-sdk/src/completion.ts).
|
||||
export type { CompletionApi, CompletionDispose, CompletionHandle, CompletionProvider, CompletionRequest, CompletionSnapshot, CompletionSurface, CompletionTransportRequest } from "../plugins/sdk.ts";
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { CompletionHandle, CompletionProvider, CompletionSnapshot, CompletionSurface } from "./contracts.ts";
|
||||
|
||||
export function eligible(s: CompletionSnapshot): boolean {
|
||||
if (!s.focused || s.composing || s.sensitive || s.readOnly || s.caret !== s.selectionEnd || s.caret < 0 || s.caret > s.text.length) return false;
|
||||
if (s.kind === "code") return true;
|
||||
const before = s.text.slice(0, s.caret), line = before.slice(before.lastIndexOf("\n") + 1);
|
||||
if (/^\s*\|/.test(line) || /\]\([^)]*$/.test(line) || /<[^>]*$/.test(line)) return false;
|
||||
if ((line.match(/`/g)?.length ?? 0) % 2) return false;
|
||||
if (/^---\r?\n/.test(s.text) && !/^---\r?$/m.test(before.slice(before.indexOf("\n") + 1))) return false;
|
||||
let fence = "";
|
||||
for (const part of before.split("\n")) {
|
||||
const match = /^\s{0,3}(`{3,}|~{3,})/.exec(part);
|
||||
if (match) { if (!fence) fence = match[1]; else if (match[1][0] === fence[0] && match[1].length >= fence.length) fence = ""; }
|
||||
}
|
||||
return !fence;
|
||||
}
|
||||
function same(a: CompletionSnapshot, b: CompletionSnapshot) {
|
||||
return a.documentId === b.documentId && a.revision === b.revision && a.caret === b.caret && a.selectionEnd === b.selectionEnd && eligible(b);
|
||||
}
|
||||
export class CompletionHub {
|
||||
private provider?: CompletionProvider;
|
||||
private surfaces = new Map<string, CompletionHandle>();
|
||||
private cancelActive?: () => void;
|
||||
registerProvider(provider: CompletionProvider): () => void {
|
||||
if (this.provider) throw new Error("Another autocomplete provider is active.");
|
||||
if (!provider.id || typeof provider.complete !== "function") throw new Error("Invalid autocomplete provider.");
|
||||
this.provider = provider;
|
||||
return () => { if (this.provider === provider) { this.provider = undefined; this.invalidate(); } };
|
||||
}
|
||||
invalidate() { for (const handle of this.surfaces.values()) handle.dismiss(); }
|
||||
registerSurface(surface: CompletionSurface): CompletionHandle {
|
||||
if (!surface.id || this.surfaces.has(surface.id)) throw new Error("Duplicate completion field.");
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
let controller: AbortController | undefined;
|
||||
let expected: CompletionSnapshot | undefined;
|
||||
let candidate = "", disposed = false, serial = 0;
|
||||
const dismiss = () => {
|
||||
const visible = !!candidate;
|
||||
serial++; clearTimeout(timer); clearTimeout(timeout); controller?.abort(); controller = undefined;
|
||||
candidate = ""; expected = undefined; surface.preview(null);
|
||||
return visible;
|
||||
};
|
||||
const run = async (manual: boolean) => {
|
||||
if (disposed || !this.provider) return;
|
||||
const snapshot = surface.snapshot(), provider = this.provider;
|
||||
if (!eligible(snapshot) || !snapshot.text.slice(0, snapshot.caret).trim()) return;
|
||||
this.cancelActive?.(); dismiss(); this.cancelActive = dismiss;
|
||||
const version = serial, abort = new AbortController(); controller = abort; expected = snapshot;
|
||||
timeout = setTimeout(() => {
|
||||
if (serial !== version) return;
|
||||
if (candidate && same(snapshot, surface.snapshot())) abort.abort();
|
||||
else dismiss();
|
||||
}, manual ? 10000 : Math.max(300, Math.min(provider.timeoutMs ?? 1000, 5000)));
|
||||
const publish = (text: string) => {
|
||||
if (disposed || serial !== version || abort.signal.aborted || this.provider !== provider || !same(snapshot, surface.snapshot())) return;
|
||||
if (typeof text !== "string" || text.length > 2000 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(text)) return;
|
||||
candidate = text; surface.preview(text || null);
|
||||
};
|
||||
try {
|
||||
const result = await provider.complete({ surfaceId: surface.id, documentId: snapshot.documentId, revision: snapshot.revision,
|
||||
prefix: snapshot.text.slice(Math.max(0, snapshot.caret - 3000), snapshot.caret), suffix: snapshot.text.slice(snapshot.caret, snapshot.caret + 600),
|
||||
kind: snapshot.kind, language: snapshot.language ?? "", manual, signal: abort.signal }, publish);
|
||||
if (result) publish(result);
|
||||
} catch { if (serial === version) dismiss(); }
|
||||
finally { if (serial === version) { clearTimeout(timeout); controller = undefined; } }
|
||||
};
|
||||
const handle: CompletionHandle = {
|
||||
changed: () => {
|
||||
dismiss();
|
||||
if (disposed || !this.provider || !eligible(surface.snapshot())) return;
|
||||
timer = setTimeout(() => { void run(false); }, Math.max(100, Math.min(this.provider.delayMs ?? 200, 1000)));
|
||||
},
|
||||
request: () => { dismiss(); void run(true); },
|
||||
dismiss,
|
||||
accept: (word = false) => {
|
||||
if (!candidate || !expected || !same(expected, surface.snapshot())) { dismiss(); return false; }
|
||||
const text = word ? (candidate.match(/^\s*\S+\s*/u)?.[0] ?? candidate) : candidate;
|
||||
const snapshot = expected;
|
||||
dismiss();
|
||||
return surface.insert(text, snapshot);
|
||||
},
|
||||
dispose: () => { if (disposed) return; disposed = true; dismiss(); this.surfaces.delete(surface.id); if (this.cancelActive === dismiss) this.cancelActive = undefined; },
|
||||
};
|
||||
this.surfaces.set(surface.id, handle);
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
export const completionHub = new CompletionHub();
|
||||
@@ -0,0 +1,47 @@
|
||||
import { completionHub } from "./hub.ts";
|
||||
import type { CompletionApi, CompletionHandle } from "./contracts.ts";
|
||||
|
||||
export const registerCompletionInput: CompletionApi["registerInput"] = (element, options) => {
|
||||
let revision = 0, composing = false;
|
||||
const hint = document.createElement("div");
|
||||
hint.className = "rs-completion-hint";
|
||||
hint.style.cssText = "position:fixed;z-index:10000;pointer-events:none;max-width:40em;padding:6px 10px;border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);border:1px solid currentColor;font:inherit;white-space:pre-wrap";
|
||||
hint.hidden = true;
|
||||
hint.setAttribute("aria-hidden", "true");
|
||||
document.body.append(hint);
|
||||
const handle = completionHub.registerSurface({
|
||||
id: options.id,
|
||||
snapshot: () => ({ documentId: options.id, revision, text: element.value, caret: element.selectionStart ?? 0, selectionEnd: element.selectionEnd ?? 0,
|
||||
focused: document.activeElement === element, composing, readOnly: element.readOnly || element.disabled,
|
||||
sensitive: options.sensitive || element instanceof HTMLInputElement && !["text", "search"].includes(element.type), kind: options.kind ?? "prose" }),
|
||||
preview: text => { hint.hidden = !text; hint.textContent = text ? `${text}\nTab to accept · Escape to dismiss` : ""; const r = element.getBoundingClientRect(); hint.style.left = `${Math.max(0, Math.min(r.left, innerWidth - 350))}px`; hint.style.top = `${Math.min(r.bottom + 4, innerHeight - 100)}px`; },
|
||||
insert: (text, expected) => {
|
||||
if (element.value !== expected.text || element.selectionStart !== expected.caret || element.selectionEnd !== expected.caret) return false;
|
||||
// The native edit command keeps input and textarea undo history intact.
|
||||
element.focus();
|
||||
return document.execCommand("insertText", false, text);
|
||||
},
|
||||
});
|
||||
const changed = () => { revision++; handle.changed(); };
|
||||
const select = () => handle.dismiss();
|
||||
const start = () => { composing = true; handle.dismiss(); };
|
||||
const end = () => { composing = false; changed(); };
|
||||
const key: EventListener = raw => {
|
||||
const event = raw as KeyboardEvent;
|
||||
if (event.isComposing || composing) return;
|
||||
if (event.key === "Tab" && !event.shiftKey && !event.altKey && !event.ctrlKey && handle.accept()) { event.preventDefault(); event.stopPropagation(); }
|
||||
else if (event.key === "Escape" && handle.dismiss()) { event.preventDefault(); event.stopPropagation(); }
|
||||
else if ((event.ctrlKey || event.metaKey) && event.altKey && event.key === " ") { event.preventDefault(); handle.request(); }
|
||||
else if ((event.ctrlKey || event.metaKey) && event.altKey && event.key === "ArrowRight" && handle.accept(true)) event.preventDefault();
|
||||
};
|
||||
element.addEventListener("input", changed); element.addEventListener("keydown", key); element.addEventListener("blur", select);
|
||||
element.addEventListener("pointerdown", select); element.addEventListener("select", select);
|
||||
element.addEventListener("compositionstart", start); element.addEventListener("compositionend", end);
|
||||
const dispose = () => {
|
||||
handle.dispose(); hint.remove();
|
||||
element.removeEventListener("input", changed); element.removeEventListener("keydown", key); element.removeEventListener("blur", select);
|
||||
element.removeEventListener("pointerdown", select); element.removeEventListener("select", select);
|
||||
element.removeEventListener("compositionstart", start); element.removeEventListener("compositionend", end);
|
||||
};
|
||||
return { ...handle, dispose } satisfies CompletionHandle;
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import { EditorState } from '@codemirror/state';
|
||||
import { EditorView, keymap } from '@codemirror/view';
|
||||
import { history, historyKeymap, defaultKeymap } from '@codemirror/commands';
|
||||
import { completionExtension } from './codemirror';
|
||||
import { completionHub } from './hub';
|
||||
import { ExternalSession } from '../plugins/externalSession';
|
||||
const editor = (parent: string, documentId: string) => new EditorView({ parent: document.querySelector(parent)!, state: EditorState.create({ doc: 'The ', selection: { anchor: 4 }, extensions: [history(), keymap.of([...historyKeymap, ...defaultKeymap]), completionExtension(documentId)] }) });
|
||||
const writer = editor('#writer', 'fixture');
|
||||
const source = editor('#source', 'fixture-source');
|
||||
// Plugin browser tests read the source text through `model`.
|
||||
const model = { getValue: () => source.state.doc.toString() };
|
||||
let stopProvider = completionHub.registerProvider({ id: 'fixture', delayMs: 100, complete: async () => 'quiet harbor.' });
|
||||
Object.assign(window, { completionTest: { writer, source, model, completionHub, stopProvider,
|
||||
async plugin(code: string) {
|
||||
stopProvider();
|
||||
const session = new ExternalSession('test.autocomplete', {
|
||||
settings: { read: async () => ({ enabled: true, endpoint: 'http://127.0.0.1:8012' }), write: async () => {} },
|
||||
workspace: { list: async () => [], read: async () => '', write: async () => {} }, assets: { read: async () => new Uint8Array() },
|
||||
completionTransport: async (request, signal, onLine) => {
|
||||
if (request.route === '/v1/models') { onLine('{"data":[{"id":"fixture-model"}]}'); return; }
|
||||
await new Promise(resolve => setTimeout(resolve, 25));
|
||||
if (!signal.aborted) onLine('data: {"choices":[{"delta":{"content":"quiet harbor."}}]}\n');
|
||||
},
|
||||
}, () => {}, () => {});
|
||||
const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));
|
||||
try { await session.start(await import(/* @vite-ignore */ url)); } finally { URL.revokeObjectURL(url); }
|
||||
await session.mount('settings', document.querySelector('#plugin') as HTMLElement);
|
||||
return session;
|
||||
},
|
||||
destroy() { stopProvider(); writer.destroy(); source.destroy(); },
|
||||
} });
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Channel, invoke } from "@tauri-apps/api/core";
|
||||
import type { CompletionApi } from "./contracts.ts";
|
||||
export const completionTransport: NonNullable<CompletionApi["transport"]> = async (request, signal, onLine) => {
|
||||
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
const id = crypto.randomUUID();
|
||||
let parseError: unknown;
|
||||
const channel = new Channel<string>();
|
||||
channel.onmessage = line => {
|
||||
if (signal.aborted || parseError) return;
|
||||
try { onLine(line); } catch (error) { parseError = error; cancel(); }
|
||||
};
|
||||
const cancel = () => { void invoke("completion_cancel", { id }).catch(() => {}); };
|
||||
signal.addEventListener("abort", cancel, { once: true });
|
||||
try { await invoke("completion_request", { id, request, onLine: channel }); if (parseError) throw parseError; }
|
||||
finally { signal.removeEventListener("abort", cancel); }
|
||||
};
|
||||
@@ -0,0 +1,538 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { tableFormulasEnabled } from "$lib/formulas";
|
||||
import { isSpellingTarget } from "./spellingMenu";
|
||||
import { untrack } from "svelte";
|
||||
import { Compartment, EditorState, StateEffect, type Extension } from "@codemirror/state";
|
||||
import { EditorView, drawSelection, keymap, type KeyBinding } from "@codemirror/view";
|
||||
import { defaultKeymap, history, indentLess, indentWithTab, isolateHistory, redo as redoEdit, redoDepth, undo as undoEdit, undoDepth } from "@codemirror/commands";
|
||||
import { foldedRanges, indentUnit, unfoldEffect } from "@codemirror/language";
|
||||
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
|
||||
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
|
||||
import { editorSearch } from "./editorSearch";
|
||||
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
|
||||
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
|
||||
import { linkCandidates } from "$lib/workspace/markdownLinks";
|
||||
import { documentHeadings } from "$lib/workspace/headingLinks";
|
||||
import { editImageSource, imageSource } from "./imageSource";
|
||||
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
|
||||
import { loadImageSize } from "$lib/workspace/imageSizes";
|
||||
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media";
|
||||
import { registerImageDropTarget } from "./workspaceImageDrop";
|
||||
import { workspaceFileLink } from "./workspaceFileLink";
|
||||
import { savedEditor, saveEditor } from "./editorStates";
|
||||
import { registerSelection } from "./selection";
|
||||
import { liveMarkdown, refreshImages } from "./liveMarkdown";
|
||||
import { imageDrops, trackImageDrop, clearImageDrop } from "./imageDrop";
|
||||
import { noteTitle } from "./noteTitle";
|
||||
import { fileTitleVisible } from "./fileTitle";
|
||||
import type { TableContextActions } from "./tableCellActions";
|
||||
import { markdownMenu } from "./markdownMenu";
|
||||
import { codeMenu } from "./codeMenu";
|
||||
import type { DocumentLinkActions } from "./linkMenu";
|
||||
import { tableNavigation } from "./tableNavigation";
|
||||
import { completionExtension } from "$lib/completion/codemirror";
|
||||
import { documentLinkAt, urlAt } from "./documentLinks";
|
||||
import { headingFolding } from "./headingFolding";
|
||||
import { languageFor } from "./languageFor";
|
||||
import { languageSupport } from "./codeLanguages";
|
||||
import { indentListItem, outdentListItem } from "./markdownLists";
|
||||
import { insertIndent, sourceChrome, sourceEditing } from "./sourceView";
|
||||
import { formatKeymap } from "./formatKeys";
|
||||
import "./headingFolding.css";
|
||||
|
||||
type Mode = "write" | "source";
|
||||
type Props = {
|
||||
buffer: OpenBuffer;
|
||||
/** Write shows formatted Markdown. Source shows the text of any file. */
|
||||
mode: Mode;
|
||||
chrome: Chrome;
|
||||
onChange: (value: string, id: string) => void;
|
||||
onRenameTitle?: (id: string, title: string) => Promise<void>;
|
||||
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
||||
onInsertImage?: (file: File, source?: string) => Promise<string | null>;
|
||||
focusLine?: number | null;
|
||||
/** The line and the column of the cursor, from 1. */
|
||||
onSelectionLine?: (line: number, column: number) => void;
|
||||
tableActions?: TableContextActions;
|
||||
linkActions?: DocumentLinkActions;
|
||||
shouldFocusOnMount?: () => boolean;
|
||||
focusTitle?: boolean;
|
||||
onTitleFocused?: () => void;
|
||||
};
|
||||
let { buffer, mode, chrome, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
|
||||
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 lastValue = "";
|
||||
let lineBreak = "\n";
|
||||
let refreshVersion = 0;
|
||||
let menu: { open(x: number, y: number, spellingOffset?: number, linkOffset?: number): void; close(focus?: boolean): void; destroy(): void } | undefined;
|
||||
const urls = new Map<string, string>();
|
||||
const loading = new Map<string, Promise<void>>();
|
||||
const modeConfig = new Compartment(), languageConfig = new Compartment(), title = new Compartment();
|
||||
let languageExtension: Extension = [];
|
||||
let languagePath = "";
|
||||
// The class follows the configuration that the editor shows, not the requested mode.
|
||||
let shown = $state<{ mode: Mode; chrome: Chrome; markdown: boolean } | null>(null);
|
||||
const markdownDocument = $derived(isMarkdownPath(buffer.relPath));
|
||||
const renameTitle = (name: string) => onRenameTitle!(buffer.id, name);
|
||||
const historyKeymap: KeyBinding[] = [
|
||||
{ key: "Mod-z", run: undoEdit, preventDefault: true },
|
||||
{ key: "Mod-y", run: redoEdit, preventDefault: true },
|
||||
{ key: "Mod-Shift-z", run: redoEdit, preventDefault: true },
|
||||
];
|
||||
|
||||
async function loadImages(path: string, value: string) {
|
||||
const previousSize = urls.size;
|
||||
await Promise.all(markdownImages(value).map(async source => {
|
||||
if (urls.has(source)) return;
|
||||
if (loading.has(source)) return loading.get(source);
|
||||
const task = (async () => {
|
||||
if (isRemoteImage(source)) { urls.set(source, source); return; }
|
||||
let decoded = source;
|
||||
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
|
||||
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
|
||||
try {
|
||||
const url = await workspaceReadDataUrl(candidate);
|
||||
await loadImageSize(url);
|
||||
urls.set(source, url);
|
||||
return;
|
||||
} catch { /* Try attachment location. */ }
|
||||
}
|
||||
})();
|
||||
loading.set(source, task);
|
||||
try { await task; } finally { loading.delete(source); }
|
||||
}));
|
||||
return urls.size !== previousSize;
|
||||
}
|
||||
|
||||
// CodeMirror stores one character per line break. Write the line break of the
|
||||
// file only at the buffer boundary, so pasted LF and CRLF text both make lines.
|
||||
function documentSource(state: EditorState) {
|
||||
return state.doc.sliceString(0, undefined, lineBreak);
|
||||
}
|
||||
|
||||
function detectLineBreak(text: string) {
|
||||
const crlf = text.split("\r\n").length - 1;
|
||||
return crlf > text.split("\n").length - 1 - crlf ? "\r\n" : "\n";
|
||||
}
|
||||
|
||||
async function insertImages(event: ClipboardEvent | DragEvent, view: EditorView) {
|
||||
const data = "clipboardData" in event ? event.clipboardData : event.dataTransfer;
|
||||
const files = imageFiles(data);
|
||||
if (!files.length || !onInsertImage || !markdownDocument) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
|
||||
// Read the HTML now. The clipboard data is empty after the paste event.
|
||||
const source = event instanceof ClipboardEvent && files.length === 1 ? pastedImageSource(data?.getData("text/html") ?? "") : undefined;
|
||||
await importImages(view, files, position, undefined, source);
|
||||
}
|
||||
|
||||
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string, source?: string) {
|
||||
const range = position === null ? view.state.selection.main : { from: position, to: position };
|
||||
const id = Symbol(), path = buffer.relPath;
|
||||
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
|
||||
try {
|
||||
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
|
||||
for (const file of files) {
|
||||
if (editor !== view) return;
|
||||
const snippet = await onInsertImage?.(file, source);
|
||||
if (snippet) snippets.push(snippet);
|
||||
}
|
||||
if (editor !== view || !snippets.length) return;
|
||||
await loadImages(path, snippets.join("\n\n"));
|
||||
if (editor !== view) return;
|
||||
const target = view.state.field(imageDrops).get(id);
|
||||
if (!target) return;
|
||||
const insert = imageInsertion(view.state.doc.toString(), target.from, target.to, snippets);
|
||||
view.dispatch({ changes: { ...target, insert }, selection: { anchor: target.from + insert.length }, userEvent: "input.image", annotations: isolateHistory.of("full") });
|
||||
view.focus();
|
||||
} catch (reason) { if (editor === view) error = String(reason); }
|
||||
finally { if (editor === view) view.dispatch({ effects: clearImageDrop.of(id) }); }
|
||||
}
|
||||
|
||||
function writeExtensions(lists: KeyBinding[]): Extension {
|
||||
// A plain copy: the buffer is reactive, and this code must not track its later edits.
|
||||
const current = untrack(() => ({ ...buffer }));
|
||||
return [
|
||||
headingFolding,
|
||||
tableNavigation,
|
||||
keymap.of([...formatKeymap, { key: "Escape", run: view => {
|
||||
if (!view.state.field(imageSource)) return false;
|
||||
view.dispatch({ effects: editImageSource.of(null) }); return true;
|
||||
} }, ...lists, indentWithTab]),
|
||||
EditorView.lineWrapping,
|
||||
liveMarkdown(urls, { ...untrack(() => tableActions), linkActions: () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }) }, {
|
||||
open: image => onOpenLink?.(image.dataset.mdKind === "wiki" ? "wiki" : "md", image.dataset.mdSrc || ""),
|
||||
reveal: async image => {
|
||||
for (const path of linkCandidates(buffer.relPath, image.dataset.mdSrc || "", "md")) {
|
||||
try { await workspaceReadDataUrl(path); await workspaceReveal(path); return; } catch { /* Try the workspace-relative image. */ }
|
||||
}
|
||||
throw new Error($t("Could not find this image in the workspace."));
|
||||
},
|
||||
validate: async source => {
|
||||
if (isRemoteImage(source)) return;
|
||||
for (const path of linkCandidates(buffer.relPath, source, "md")) {
|
||||
try { await workspaceReadDataUrl(path); return; } catch { /* Try the workspace-relative image. */ }
|
||||
}
|
||||
throw new Error($t("Choose an image that exists in the workspace."));
|
||||
},
|
||||
report: message => { error = message; },
|
||||
}),
|
||||
title.of(fileTitle(current.relPath)),
|
||||
EditorView.contentAttributes.of({ role: "textbox", "aria-label": $t("Writing editor"), "aria-multiline": "true", spellcheck: "true" }),
|
||||
];
|
||||
}
|
||||
|
||||
// The file name title, or nothing when the setting hides it.
|
||||
function fileTitle(path: string): Extension {
|
||||
return untrack(() => $fileTitleVisible) ? noteTitle(markdownTitle(path), onRenameTitle ? renameTitle : undefined) : [];
|
||||
}
|
||||
|
||||
function reportCursor(state: EditorState) {
|
||||
const head = state.selection.main.head, line = state.doc.lineAt(head);
|
||||
onSelectionLine?.(line.number, head - line.from + 1);
|
||||
}
|
||||
|
||||
function modeExtensions(next: NonNullable<typeof shown>): Extension {
|
||||
// Tab in a Markdown list item makes a nested item in Write and in Source.
|
||||
const lists: KeyBinding[] = next.markdown ? [{ key: "Tab", run: indentListItem, shift: outdentListItem }] : [];
|
||||
if (next.mode === "write") return writeExtensions(lists);
|
||||
return [
|
||||
sourceEditing,
|
||||
sourceChrome(next.chrome),
|
||||
keymap.of([...lists, { key: "Tab", run: insertIndent, shift: indentLess }]),
|
||||
EditorView.contentAttributes.of({ "aria-label": $t("Editor"), spellcheck: "false" }),
|
||||
];
|
||||
}
|
||||
|
||||
function requested() {
|
||||
return untrack(() => ({ mode, chrome, markdown: markdownDocument }));
|
||||
}
|
||||
|
||||
function configuration(): Extension[] {
|
||||
// A plain copy: the buffer is reactive, and this code must not track its later edits.
|
||||
const current = untrack(() => ({ ...buffer }));
|
||||
shown = requested();
|
||||
return [
|
||||
completionExtension(current.id, () => ({ kind: isMarkdownPath(buffer.relPath) ? "prose" : "code", language: languageFor(buffer.relPath) })),
|
||||
languageConfig.of(languageExtension),
|
||||
modeConfig.of(modeExtensions(shown)),
|
||||
history(), drawSelection(), indentUnit.of(" "), EditorState.tabSize.of(4),
|
||||
EditorView.theme({}, { dark: true }),
|
||||
editorSearch,
|
||||
imageDrops,
|
||||
keymap.of([...searchKeymap, ...historyKeymap, ...defaultKeymap]),
|
||||
EditorView.updateListener.of(update => {
|
||||
if (update.docChanged || update.selectionSet) {
|
||||
menu?.close(false);
|
||||
reportCursor(update.state);
|
||||
}
|
||||
if (!update.docChanged) return;
|
||||
scroll = scroll?.map(update.changes);
|
||||
lastValue = documentSource(update.state);
|
||||
onChange(lastValue, current.id);
|
||||
if (shown?.mode !== "write") return;
|
||||
void loadImages(buffer.relPath, update.state.sliceDoc()).then(changed => {
|
||||
if (changed && editor === update.view) update.view.dispatch({ effects: refreshImages.of() });
|
||||
});
|
||||
}),
|
||||
EditorView.domEventHandlers({
|
||||
contextmenu(event, view) {
|
||||
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
|
||||
event.preventDefault();
|
||||
const position = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
|
||||
const selection = view.state.selection.main;
|
||||
if (position !== null && (selection.empty || position < selection.from || position > selection.to)) view.dispatch({ selection: { anchor: position } });
|
||||
menu?.open(event.clientX, event.clientY, selection.empty && isSpellingTarget(event.target) ? position ?? undefined : undefined, position ?? undefined);
|
||||
return true;
|
||||
},
|
||||
keydown(event, view) {
|
||||
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return false;
|
||||
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
|
||||
event.preventDefault();
|
||||
const coords = view.coordsAtPos(view.state.selection.main.head);
|
||||
if (coords) menu?.open(coords.left, coords.bottom, view.state.selection.main.empty ? view.state.selection.main.head : undefined);
|
||||
return true;
|
||||
},
|
||||
mousedown(event, view) {
|
||||
if (!event.ctrlKey && !event.metaKey) return false;
|
||||
if (event.button !== 0) return false;
|
||||
const link = event.target instanceof Element ? event.target.closest("[data-href], a") : null;
|
||||
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
const source = view.state.doc.toString();
|
||||
const sourceLink = position === null ? undefined : markdownDocument ? documentLinkAt(source, position) : urlAt(source, position);
|
||||
if (!link && !sourceLink) return false;
|
||||
event.preventDefault();
|
||||
onOpenLink?.(sourceLink?.kind ?? (link?.getAttribute("data-kind") === "wiki" ? "wiki" : "md"), sourceLink?.target ?? link?.getAttribute("data-href") ?? link?.getAttribute("href") ?? "");
|
||||
return true;
|
||||
},
|
||||
paste(event, view) {
|
||||
const html = event.clipboardData?.getData("text/html") || "";
|
||||
if (shown?.mode === "write" && /<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 || !markdownDocument || !imageFiles(event.clipboardData).length) return false;
|
||||
void insertImages(event, view); return true;
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
// Start Write in the body so the initial caret does not reveal properties source.
|
||||
// Saved selections and explicit line navigation still restore their positions.
|
||||
function freshState(source: string) {
|
||||
const doc = EditorState.create({ doc: source }).doc;
|
||||
const anchor = untrack(() => mode) === "write" ? documentBodyStart(doc.toString()) : 0;
|
||||
return EditorState.create({ doc, selection: { anchor }, extensions: configuration() });
|
||||
}
|
||||
|
||||
let scroll: ReturnType<EditorView["scrollSnapshot"]> | undefined;
|
||||
|
||||
$effect(() => {
|
||||
const el = host;
|
||||
if (!el) return;
|
||||
let cancelled = false;
|
||||
let releaseSelection: (() => void) | undefined;
|
||||
let releaseDrop: (() => void) | undefined;
|
||||
let releaseScroll: (() => void) | undefined;
|
||||
// A plain copy: the buffer is reactive, and this code must not track its later edits.
|
||||
const current = untrack(() => ({ ...buffer }));
|
||||
void (async () => {
|
||||
lastValue = current.contents;
|
||||
const saved = savedEditor(current.id);
|
||||
const restore = saved?.source === lastValue ? saved : undefined;
|
||||
lineBreak = restore?.lineBreak ?? detectLineBreak(lastValue);
|
||||
if (isMarkdownPath(current.relPath) && untrack(() => mode) === "write") await loadImages(current.relPath, current.contents);
|
||||
languagePath = current.relPath;
|
||||
languageExtension = await languageSupport(current.relPath);
|
||||
if (cancelled) return;
|
||||
// A restored state keeps its history. The new configuration replaces the handlers of the old editor.
|
||||
const state = restore ? restore.state.update({ effects: StateEffect.reconfigure.of(configuration()) }).state : freshState(lastValue);
|
||||
// Restore through CodeMirror's layout pass, once its viewport is measured.
|
||||
const view = new EditorView({ state, parent: el, scrollTo: restore?.scroll });
|
||||
editor = view;
|
||||
reportCursor(view.state);
|
||||
scroll = restore?.scroll ?? view.scrollSnapshot();
|
||||
// Svelte may detach the old tab before effect cleanup runs, at which point
|
||||
// DOM scroll offsets read as zero. Capture while the view is still mounted.
|
||||
const saveScroll = () => { if (view.dom.isConnected) scroll = view.scrollSnapshot(); };
|
||||
view.scrollDOM.addEventListener("scroll", saveScroll);
|
||||
releaseScroll = () => view.scrollDOM.removeEventListener("scroll", saveScroll);
|
||||
if (isMarkdownPath(current.relPath)) releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.posAtCoords(point, false), path); });
|
||||
releaseSelection = registerSelection(current.id, () => view.state.selection.ranges.map(range => view.state.sliceDoc(range.from, range.to)).join("\n"));
|
||||
menu = isMarkdownPath(current.relPath) ? markdownMenu({
|
||||
snapshot() {
|
||||
const { doc, selection } = view.state;
|
||||
return { source: doc.toString(), selection: selection.main, valid: () => editor === view && view.state.doc === doc && view.state.selection.eq(selection) };
|
||||
},
|
||||
apply(edit) { view.dispatch({ changes: { from: edit.from, to: edit.to, insert: edit.insert }, selection: { anchor: edit.anchor, head: edit.head }, userEvent: "input.markdown", annotations: isolateHistory.of("full") }); },
|
||||
select(from, to) { view.dispatch({ selection: { anchor: from, head: to }, scrollIntoView: true }); },
|
||||
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
|
||||
focus() { view.focus(); },
|
||||
undo() { undoEdit(view); },
|
||||
redo() { redoEdit(view); },
|
||||
canUndo() { return undoDepth(view.state) > 0; },
|
||||
canRedo() { return redoDepth(view.state) > 0; },
|
||||
}, untrack(() => tableActions), message => { error = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }))
|
||||
: codeMenu(view, message => { error = message; });
|
||||
if (!untrack(() => focusTitle) && shouldFocusOnMount()) view.focus();
|
||||
})().catch(reason => { if (!cancelled) error = String(reason); });
|
||||
return () => {
|
||||
cancelled = true;
|
||||
refreshVersion++;
|
||||
menu?.destroy();
|
||||
menu = undefined;
|
||||
releaseDrop?.();
|
||||
releaseScroll?.();
|
||||
if (editor && scroll) saveEditor(current.id, { source: documentSource(editor.state), lineBreak, state: editor.state, scroll });
|
||||
editor?.destroy();
|
||||
releaseSelection?.();
|
||||
editor = undefined;
|
||||
};
|
||||
});
|
||||
|
||||
// Write and Source are two configurations of one state, so the switch keeps the history.
|
||||
$effect(() => {
|
||||
const next = { mode, chrome, markdown: markdownDocument };
|
||||
const view = editor;
|
||||
if (!view) return;
|
||||
untrack(() => {
|
||||
if (shown && shown.mode === next.mode && shown.chrome === next.chrome && shown.markdown === next.markdown) return;
|
||||
void (next.mode === "write" ? loadImages(buffer.relPath, view.state.doc.toString()) : Promise.resolve(false)).then(() => {
|
||||
const latest = requested();
|
||||
if (editor !== view || latest.mode !== next.mode || latest.chrome !== next.chrome || latest.markdown !== next.markdown) return;
|
||||
shown = next;
|
||||
view.dispatch({ effects: modeConfig.reconfigure(modeExtensions(next)) });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const path = buffer.relPath;
|
||||
const view = editor;
|
||||
if (!view || path === languagePath) return;
|
||||
languagePath = path;
|
||||
void languageSupport(path).then(extension => {
|
||||
if (editor !== view || languagePath !== path) return;
|
||||
languageExtension = extension;
|
||||
view.dispatch({ effects: languageConfig.reconfigure(extension) });
|
||||
});
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
void $tableFormulasEnabled;
|
||||
editor?.dispatch({ effects: refreshImages.of() });
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const path = buffer.relPath;
|
||||
void $fileTitleVisible;
|
||||
const view = editor;
|
||||
if (view && shown?.mode === "write") view.dispatch({ effects: title.reconfigure(fileTitle(path)) });
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!focusTitle || !editor || shown?.mode !== "write") return;
|
||||
const button = editor.dom.querySelector<HTMLButtonElement>(".note-title-button");
|
||||
// Without the title, a new note starts with the cursor in the text.
|
||||
if (button) button.click();
|
||||
else if (!$fileTitleVisible) editor.focus();
|
||||
else return;
|
||||
onTitleFocused?.();
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const value = buffer.contents;
|
||||
const path = buffer.relPath;
|
||||
const view = editor;
|
||||
if (!view || value === lastValue) return;
|
||||
const version = ++refreshVersion;
|
||||
void (untrack(() => shown?.mode) === "write" ? loadImages(path, value) : Promise.resolve(false)).then(() => {
|
||||
if (version !== refreshVersion || editor !== view || buffer.contents !== value) return;
|
||||
lastValue = value;
|
||||
lineBreak = detectLineBreak(value);
|
||||
// Reloads start fresh history, so undo cannot revive a discarded disk version.
|
||||
const anchor = Math.min(view.state.selection.main.head, value.replace(/\r\n/g, "\n").length);
|
||||
view.setState(freshState(value));
|
||||
view.dispatch({ selection: { anchor } });
|
||||
});
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const line = focusLine;
|
||||
const view = editor;
|
||||
if (!view || line == null) return;
|
||||
untrack(() => {
|
||||
const number = Math.min(view.state.doc.lines, Math.max(1, line));
|
||||
const anchor = view.state.doc.line(number).from;
|
||||
// A heading starts the text to read, so it goes to the top, as in Read. Other lines, such as a search match, stay in the center.
|
||||
const heading = markdownDocument && documentHeadings(view.state.doc.toString()).some(entry => entry.line === number);
|
||||
const effects = [EditorView.scrollIntoView(anchor, heading ? { y: "start", yMargin: 24 } : { y: "center" })];
|
||||
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
|
||||
view.dispatch({ selection: { anchor }, effects });
|
||||
view.focus();
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class={(shown?.mode ?? mode) === "write" ? "live-writer" : "source-editor"} data-chrome={shown?.chrome ?? chrome}
|
||||
bind:this={host} role="application" aria-label={(shown?.mode ?? mode) === "write" ? $t("Markdown writing editor") : $t("Editor")}
|
||||
ondragovercapture={(event) => {
|
||||
if (!onInsertImage || !markdownDocument || !hasFileDrag(event.dataTransfer)) return;
|
||||
event.preventDefault();
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
|
||||
}}
|
||||
ondropcapture={(event) => { if (editor) void insertImages(event, editor); }}
|
||||
></div>
|
||||
{#if error}<p class="editor-notice" role="alert">{error}<button onclick={() => { error = ""; }}>{$t("Dismiss")}</button></p>{/if}
|
||||
|
||||
<style>
|
||||
.editor-notice { position: absolute; bottom: 12px; left: 12px; right: 12px; z-index: 20; margin: 0; padding: 10px 14px; border: 1px solid var(--rs-border); border-radius: 6px; background: var(--rs-bg-elevated); color: var(--rs-text); }
|
||||
.editor-notice button { margin-left: 12px; }
|
||||
.live-writer, .source-editor { position: absolute; inset: 0; }
|
||||
.live-writer :global(.cm-editor), .source-editor :global(.cm-editor) { height: 100%; color: var(--rs-text); background: transparent; }
|
||||
.live-writer :global(.cm-editor.cm-focused), .source-editor :global(.cm-editor.cm-focused) { outline: none; }
|
||||
.live-writer :global(.cm-panels), .source-editor :global(.cm-panels) { background: var(--rs-bg-elevated); color: var(--rs-text); }
|
||||
.live-writer :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .live-writer :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground),
|
||||
.source-editor :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .source-editor :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground) { background: var(--rs-selection); }
|
||||
|
||||
.source-editor :global(.cm-scroller) { font: var(--rs-code-font-weight) var(--rs-code-font-size)/var(--rs-code-line-height) var(--rs-font-mono); }
|
||||
.source-editor :global(.cm-content) { padding: 8px 0 24px; caret-color: var(--rs-accent); }
|
||||
.source-editor[data-chrome="Writing"] :global(.cm-content) { padding: 16px 24px 48px; }
|
||||
.source-editor :global(.cm-cursor) { border-left-color: var(--rs-accent); }
|
||||
.source-editor :global(.cm-gutters) { border: 0; background: transparent; color: var(--rs-text-dim); }
|
||||
.source-editor :global(.cm-lineNumbers .cm-gutterElement) { padding: 0 10px 0 16px; }
|
||||
.source-editor :global(.cm-activeLine) { background: var(--rs-bg-active); }
|
||||
.source-editor :global(.cm-activeLineGutter) { background: transparent; color: var(--rs-text); }
|
||||
.source-editor :global(.cm-foldGutter .cm-gutterElement) { padding: 0 4px; cursor: pointer; }
|
||||
.source-editor :global(.cm-selectionMatch) { background: var(--rs-item-selection-bg); }
|
||||
.source-editor :global(.cm-matchingBracket) { background: var(--rs-item-selection-bg); outline: 1px solid var(--rs-border); }
|
||||
.source-editor :global(.cm-nonmatchingBracket) { color: var(--rs-error); }
|
||||
|
||||
.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-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-cursor) { border-left-color: var(--rs-text-strong); }
|
||||
.live-writer :global(.writer-blank) { font-size: .75em; }
|
||||
.live-writer :global(.writer-strong) { font-weight: 600; color: var(--rs-text-strong); }
|
||||
.live-writer :global(.writer-emphasis) { font-style: italic; }
|
||||
.live-writer :global(.writer-strike), .live-writer :global(.writer-completed) { text-decoration: line-through; color: var(--rs-text-dim); }
|
||||
.live-writer :global(.writer-link) { color: var(--rs-link); text-decoration: underline; text-underline-offset: 3px; }
|
||||
.live-writer :global(.writer-link-source) { color: var(--rs-link); }
|
||||
.live-writer :global(.writer-link-target) { text-decoration: underline; text-underline-offset: 3px; }
|
||||
.live-writer :global(.writer-inline-code), .live-writer :global(.writer-code-source) { font-family: var(--rs-font-mono); font-size: .9em; }
|
||||
.live-writer :global(.writer-inline-code) { background: var(--rs-bg-elevated); border-radius: 3px; }
|
||||
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-code-block-bg); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
|
||||
.live-writer :global(.writer-code-first) { padding-top: 10px; border-top: 1px solid var(--rs-border); border-radius: var(--rs-control-radius) var(--rs-control-radius) 0 0; padding-right: 44px; }
|
||||
.live-writer :global(.writer-code-last) { padding-bottom: 10px; border-bottom: 1px solid var(--rs-border); border-radius: 0 0 var(--rs-control-radius) var(--rs-control-radius); }
|
||||
.live-writer :global(.writer-code-fence) { color: var(--rs-text-dim); }
|
||||
.live-writer :global(.writer-code-copy) { top: 4px; border-radius: var(--rs-control-radius); }
|
||||
.live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.live-writer :global(.writer-highlight) { background: color-mix(in srgb, var(--rs-highlight) 22%, transparent); color: var(--rs-text-strong); }
|
||||
.live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; }
|
||||
.live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); }
|
||||
.live-writer :global(.writer-divider-line) { display: flex; align-items: center; }
|
||||
.live-writer :global(.writer-divider) { display: inline-flex; align-items: center; flex: 1; min-width: 0; height: 1.75em; cursor: text; }
|
||||
.live-writer :global(.writer-divider::after) { content: ""; width: 100%; border-top: 1px solid var(--rs-border); }
|
||||
.live-writer :global(.writer-checkbox) { display: inline-block; position: static; width: 15px; height: 15px; margin: 0 .55em 0 0; vertical-align: -.1em; accent-color: var(--rs-accent); cursor: pointer; }
|
||||
/* Keep child margins inside the measured widget; collapsed margins otherwise
|
||||
shift mouse hit-testing to the next line after a table or other preview. */
|
||||
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; white-space: normal; }
|
||||
.live-writer :global(.writer-preview > :last-child) { margin-bottom: 0; }
|
||||
.live-writer :global(.writer-preview img) { max-width: 100%; }
|
||||
/* The padding holds the drag and add controls. The table adds no extra gap above it. */
|
||||
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 0; padding: 26px; }
|
||||
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 0; }
|
||||
.live-writer :global(.writer-table td), .live-writer :global(.writer-table th) { cursor: text; }
|
||||
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1lh; white-space: pre-wrap; overflow-wrap: break-word; }
|
||||
.live-writer :global(.writer-table p) { margin: 0; }
|
||||
.live-writer :global(.table-add) { position: absolute; display: block; padding: 0; opacity: 0; border: 1px solid var(--rs-border); background: var(--rs-bg-elevated); color: var(--rs-text-dim); cursor: pointer; transition: opacity 100ms; }
|
||||
/* The add controls show, in dim color, while a cell of the table has focus. */
|
||||
.live-writer :global(.writer-table:focus-within .table-add) { opacity: 1; }
|
||||
.live-writer :global(.table-add:hover), .live-writer :global(.table-add:focus-visible) { opacity: 1; color: var(--rs-accent); border-color: var(--rs-accent-deep); outline: none; }
|
||||
.live-writer :global(.table-add-column) { right: 0; top: 26px; bottom: 26px; width: 26px; border-radius: 0 4px 4px 0; }
|
||||
.live-writer :global(.table-add-row) { left: 26px; right: 26px; bottom: 0; height: 26px; border-radius: 0 0 4px 4px; }
|
||||
.live-writer :global(.table-add span) { position: absolute; font: 20px/24px var(--rs-font-ui); width: 24px; height: 24px; text-align: center; pointer-events: none; }
|
||||
.live-writer :global(.table-add-column span) { left: 0; top: var(--table-add-position, 50%); transform: translateY(-50%); }
|
||||
.live-writer :global(.table-add-row span) { top: 0; left: var(--table-add-position, 50%); transform: translateX(-50%); }
|
||||
</style>
|
||||
@@ -0,0 +1,87 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { untrack } from "svelte";
|
||||
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 { 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);
|
||||
let caseSensitive = $state(initialQuery.caseSensitive);
|
||||
let regexp = $state(initialQuery.regexp);
|
||||
let wholeWord = $state(initialQuery.wholeWord);
|
||||
|
||||
export function sync(next: SearchQuery) {
|
||||
if (next.eq(query)) return;
|
||||
query = next;
|
||||
searchText = next.search;
|
||||
replacement = next.replace;
|
||||
caseSensitive = next.caseSensitive;
|
||||
regexp = next.regexp;
|
||||
wholeWord = next.wholeWord;
|
||||
}
|
||||
|
||||
function commit() {
|
||||
query = new SearchQuery({ search: searchText, replace: replacement, caseSensitive, regexp, wholeWord });
|
||||
target.setQuery(query);
|
||||
}
|
||||
|
||||
function keydown(event: KeyboardEvent) {
|
||||
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") target.replace();
|
||||
else target.next(event.shiftKey);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Handle shortcuts from the search controls.) -->
|
||||
<section class="rs-find-bar" aria-label={$t("Find and replace")} onkeydown={keydown}>
|
||||
<div class="rs-find-row">
|
||||
<div class="rs-find-field">
|
||||
<Icon icon="search" />
|
||||
<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={() => 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">
|
||||
<label><input type="checkbox" bind:checked={() => caseSensitive, value => { caseSensitive = value; commit(); }} />{$t("Match case")}</label>
|
||||
<label><input type="checkbox" bind:checked={() => wholeWord, value => { wholeWord = value; commit(); }} />{$t("Whole word")}</label>
|
||||
<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 !target.readOnly}
|
||||
<div class="rs-find-row">
|
||||
<div class="rs-find-field">
|
||||
<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={() => 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}
|
||||
</section>
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { StreamLanguage } from "@codemirror/language";
|
||||
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import { extensionOf } from "../workspace/chrome";
|
||||
import { languageFor } from "./languageFor";
|
||||
import { noteFormats } from "./noteFormats";
|
||||
|
||||
/** The Markdown language of Write and Source, with the RuneStone note formats. */
|
||||
export const noteMarkdown = () => markdown({ base: markdownLanguage, extensions: [noteFormats] });
|
||||
|
||||
// Each language loads when the first file of that language opens.
|
||||
const loaders: Record<string, (extension: string) => Promise<Extension>> = {
|
||||
markdown: async () => noteMarkdown(),
|
||||
javascript: async extension => (await import("@codemirror/lang-javascript")).javascript({ jsx: extension === "jsx" }),
|
||||
typescript: async extension => (await import("@codemirror/lang-javascript")).javascript({ typescript: true, jsx: extension === "tsx" }),
|
||||
python: async () => (await import("@codemirror/lang-python")).python(),
|
||||
json: async () => (await import("@codemirror/lang-json")).json(),
|
||||
css: async () => (await import("@codemirror/lang-css")).css(),
|
||||
scss: async () => (await import("@codemirror/lang-sass")).sass(),
|
||||
html: async () => (await import("@codemirror/lang-html")).html(),
|
||||
rust: async () => (await import("@codemirror/lang-rust")).rust(),
|
||||
shell: async () => StreamLanguage.define((await import("@codemirror/legacy-modes/mode/shell")).shell),
|
||||
yaml: async () => (await import("@codemirror/lang-yaml")).yaml(),
|
||||
ini: async () => StreamLanguage.define((await import("@codemirror/legacy-modes/mode/toml")).toml),
|
||||
xml: async () => (await import("@codemirror/lang-xml")).xml(),
|
||||
};
|
||||
|
||||
/** The syntax support for a file. Plain text gets none. */
|
||||
export async function languageSupport(relPath: string): Promise<Extension> {
|
||||
return await loaders[languageFor(relPath)]?.(extensionOf(relPath)) ?? [];
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { keys } from "../ui/shortcuts";
|
||||
import { EditorSelection } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { redo, redoDepth, undo, undoDepth } from "@codemirror/commands";
|
||||
import { selectSelectionMatches } from "@codemirror/search";
|
||||
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
|
||||
import { clipboardItems, historyItems } from "../ui/menuItems";
|
||||
|
||||
/** Keep source editing commands in the host's shared action menu. */
|
||||
export function codeMenu(view: EditorView, report: (message: string) => void) {
|
||||
let menu: MenuHandle | undefined;
|
||||
const restore = () => view.focus();
|
||||
function close(focus = true) {
|
||||
menu?.close(); menu = undefined;
|
||||
if (focus) restore();
|
||||
}
|
||||
function open(x: number, y: number) {
|
||||
close(false);
|
||||
const state = view.state, main = state.selection.main;
|
||||
const valid = () => view.state.doc === state.doc && view.state.selection.eq(state.selection);
|
||||
const selected = state.sliceDoc(main.from, main.to);
|
||||
const word = main.empty ? state.wordAt(main.head) : main;
|
||||
const replace = (text: string) => {
|
||||
if (!valid()) return;
|
||||
view.dispatch(view.state.replaceSelection(text), { userEvent: "input", scrollIntoView: true });
|
||||
view.focus();
|
||||
};
|
||||
const clipboard = async (kind: "cut" | "copy" | "paste") => {
|
||||
try {
|
||||
if (kind === "paste") replace(await navigator.clipboard.readText());
|
||||
else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); }
|
||||
} catch { report(tr("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste.")); }
|
||||
};
|
||||
const changeAll = () => {
|
||||
if (!valid() || !word) return;
|
||||
if (main.empty) view.dispatch({ selection: EditorSelection.single(word.from, word.to) });
|
||||
selectSelectionMatches(view);
|
||||
};
|
||||
menu = showActionMenu({ x, y, label: tr("Code text actions"), items: [
|
||||
...historyItems({ canUndo: undoDepth(state) > 0, canRedo: redoDepth(state) > 0, undo: () => undo(view), redo: () => redo(view) }),
|
||||
{ label: tr("Change all occurrences"), icon: "select", shortcut: keys("Mod+Shift+L"), disabled: !word || word.empty, run: changeAll },
|
||||
{ separator: true },
|
||||
...clipboardItems({
|
||||
selected: !!selected, cut: () => void clipboard("cut"), copy: () => void clipboard("copy"), paste: () => void clipboard("paste"),
|
||||
selectAll: () => view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }),
|
||||
}),
|
||||
] }, undefined, restore);
|
||||
}
|
||||
return { open, close, destroy() { close(false); } };
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { markdownLanguage } from "@codemirror/lang-markdown";
|
||||
|
||||
export type DocumentLink = { from: number; to: number; targetFrom: number; targetTo: number; kind: "md" | "wiki"; target: string };
|
||||
|
||||
/** Source ranges survive the change from formatted text to editable Markdown. */
|
||||
export function documentLinks(source: string): DocumentLink[] {
|
||||
const links: DocumentLink[] = [];
|
||||
const literal: { from: number; to: number }[] = [];
|
||||
markdownLanguage.parser.parse(source).iterate({ enter(node) {
|
||||
if (["FencedCode", "CodeBlock", "InlineCode", "Image"].includes(node.name)) {
|
||||
literal.push({ from: node.from, to: node.to });
|
||||
return false;
|
||||
}
|
||||
if (node.name !== "Link" && node.name !== "Autolink") return;
|
||||
const url = node.node.getChild("URL");
|
||||
if (!url) return;
|
||||
const target = source.slice(url.from, url.to).replace(/^<|>$/g, "").replace(/\\([\\()])/g, "$1");
|
||||
const angled = source[url.from] === "<";
|
||||
links.push({ from: node.from, to: node.to, targetFrom: url.from + Number(angled), targetTo: url.to - Number(angled), kind: "md", target });
|
||||
return false;
|
||||
} });
|
||||
const occupied = (from: number, to: number) => [...literal, ...links].some(range => from < range.to && to > range.from);
|
||||
for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) {
|
||||
if (occupied(match.index, match.index + match[0].length)) continue;
|
||||
if (source[match.index - 1] === "!") continue;
|
||||
const raw = match[1].split(/\\?\|/)[0], target = raw.trim();
|
||||
const targetFrom = match.index + 2 + raw.length - raw.trimStart().length;
|
||||
links.push({ from: match.index, to: match.index + match[0].length, targetFrom, targetTo: targetFrom + target.length, kind: "wiki", target });
|
||||
}
|
||||
links.push(...plainUrls(source, occupied));
|
||||
return links.sort((a, b) => a.from - b.from);
|
||||
}
|
||||
|
||||
function plainUrls(source: string, occupied: (from: number, to: number) => boolean = () => false) {
|
||||
const links: DocumentLink[] = [];
|
||||
for (const match of source.matchAll(/(?:https?:\/\/|mailto:)[^\s<>]+/g)) {
|
||||
if (occupied(match.index, match.index + match[0].length)) continue;
|
||||
const target = match[0].replace(/[.,;:!?]+$/, "").replace(/\)+$/, suffix => {
|
||||
const open = (match[0].match(/\(/g) || []).length, close = (match[0].match(/\)/g) || []).length;
|
||||
return suffix.slice(0, Math.max(0, suffix.length - Math.max(0, close - open)));
|
||||
});
|
||||
links.push({ from: match.index, to: match.index + target.length, targetFrom: match.index, targetTo: match.index + target.length, kind: "md" as const, target });
|
||||
}
|
||||
return links;
|
||||
}
|
||||
|
||||
export function documentLinkAt(source: string, position: number) {
|
||||
return documentLinks(source).find(link => position >= link.from && position < link.to);
|
||||
}
|
||||
|
||||
/** The plain URL at a position, for files that are not Markdown. */
|
||||
export function urlAt(source: string, position: number) {
|
||||
return plainUrls(source).find(link => position >= link.from && position < link.to);
|
||||
}
|
||||
@@ -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,33 @@
|
||||
import { flushSync, mount, unmount } from "svelte";
|
||||
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";
|
||||
|
||||
/** CodeMirror search for Write and Source, shown in the shared Find panel. */
|
||||
export const editorSearch = search({
|
||||
top: true,
|
||||
createPanel(view) {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = "rs-editor-search";
|
||||
let panel: { sync(query: SearchQuery): void } | undefined;
|
||||
return {
|
||||
dom,
|
||||
top: true,
|
||||
mount() {
|
||||
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();
|
||||
},
|
||||
update() { panel?.sync(getSearchQuery(view.state)); },
|
||||
destroy() { if (panel) void unmount(panel); },
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { EditorState } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
|
||||
/**
|
||||
* The editor of an open document, kept while its tab stays open.
|
||||
* The state holds the undo history, so Write, Source, and a tab change share it.
|
||||
*/
|
||||
export type SavedEditor = {
|
||||
source: string;
|
||||
lineBreak: string;
|
||||
state: EditorState;
|
||||
scroll: ReturnType<EditorView["scrollSnapshot"]>;
|
||||
};
|
||||
|
||||
const saved = new Map<string, SavedEditor>();
|
||||
let retained = new Set<string>();
|
||||
|
||||
export function savedEditor(id: string) {
|
||||
return saved.get(id);
|
||||
}
|
||||
|
||||
export function saveEditor(id: string, editor: SavedEditor) {
|
||||
if (retained.has(id)) saved.set(id, editor);
|
||||
}
|
||||
|
||||
/** Keep the editors of the open tabs only. */
|
||||
export function retainEditorStates(ids: string[]) {
|
||||
retained = new Set(ids);
|
||||
for (const id of saved.keys()) if (!retained.has(id)) saved.delete(id);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// The document settings of the general section. `showFileTitle` shows the file name as a title above a Markdown note
|
||||
// in Write and Read. `keepLineBreaks` keeps each line break of the source in Read.
|
||||
import { writable } from "svelte/store";
|
||||
import { onSettingsChange } from "../settings/store.ts";
|
||||
import { DEFAULT_SETTINGS, readSettings } from "../workspace/settings.ts";
|
||||
|
||||
const visible = writable(DEFAULT_SETTINGS.showFileTitle);
|
||||
/** A store with the current state of the setting. */
|
||||
export const fileTitleVisible = { subscribe: visible.subscribe };
|
||||
|
||||
/** Apply the saved settings now and after each change in any window. Returns a function that stops it. */
|
||||
export function syncFileTitle() {
|
||||
const read = () => {
|
||||
let settings = DEFAULT_SETTINGS;
|
||||
try { settings = readSettings(); } catch { /* The defaults apply. */ }
|
||||
visible.set(settings.showFileTitle);
|
||||
// The `keepLineBreaks` setting: Read shows each source line break (src/lib/layout/reading.css).
|
||||
document.documentElement.toggleAttribute("data-keep-line-breaks", settings.keepLineBreaks);
|
||||
};
|
||||
read();
|
||||
return onSettingsChange("general", read);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
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 };
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
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="${markdown.utils.escapeHtml(tr('Footnote {number}', { 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="${markdown.utils.escapeHtml(tr('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="${markdown.utils.escapeHtml(index ? tr('Back to reference {number}, occurrence {occurrence}', { number: note.number, occurrence: index + 1 }) : tr('Back to reference {number}', { number: note.number }))}" title="${markdown.utils.escapeHtml(tr('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,25 @@
|
||||
// Write formatting shortcuts. Each one makes the same edit as its item in the Format menu.
|
||||
import type { EditorView, KeyBinding } from "@codemirror/view";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { formatText, type InlineFormat, type MarkdownEdit } from "./markdownCommands";
|
||||
import { externalLinkText } from "./linkCommands";
|
||||
|
||||
/** The shortcut of each format, as written combinations for the menu labels. */
|
||||
export const FORMAT_KEYS: Partial<Record<InlineFormat, string>> = { bold: "Mod+B", italic: "Mod+I", strike: "Mod+Shift+X", highlight: "Mod+Shift+H" };
|
||||
export const LINK_KEY = "Mod+K";
|
||||
|
||||
function apply(view: EditorView, edit: MarkdownEdit) {
|
||||
view.dispatch({ changes: { from: edit.from, to: edit.to, insert: edit.insert }, selection: { anchor: edit.anchor, head: edit.head },
|
||||
userEvent: "input.markdown", annotations: isolateHistory.of("full"), scrollIntoView: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
const format = (kind: InlineFormat) => (view: EditorView) => apply(view, formatText(view.state.doc.toString(), view.state.selection.main, kind));
|
||||
|
||||
export const formatKeymap: KeyBinding[] = [
|
||||
{ key: "Mod-b", run: format("bold"), preventDefault: true },
|
||||
{ key: "Mod-i", run: format("italic"), preventDefault: true },
|
||||
{ key: "Mod-Shift-x", run: format("strike"), preventDefault: true },
|
||||
{ key: "Mod-Shift-h", run: format("highlight"), preventDefault: true },
|
||||
{ key: "Mod-k", run: view => apply(view, externalLinkText(view.state.doc.toString(), view.state.selection.main)), preventDefault: true },
|
||||
];
|
||||
@@ -0,0 +1,19 @@
|
||||
.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-hover-bg); }
|
||||
.rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-focus); 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-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-focus); outline-offset: 3px; border-radius: var(--rs-control-radius); }
|
||||
@@ -0,0 +1,143 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
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";
|
||||
import { attachTooltip } from "../ui/tooltip";
|
||||
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
|
||||
|
||||
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 = tr(collapsed ? "Expand {name}" : "Collapse {name}", { name: label || tr("heading") });
|
||||
button.setAttribute("aria-label", title);
|
||||
tooltipCleanups.set(button, attachTooltip(button, () => button.getAttribute("aria-label") || ""));
|
||||
const icon = actionIcon("chevron");
|
||||
button.append(icon);
|
||||
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;
|
||||
}
|
||||
destroy(dom: HTMLElement) { tooltipCleanups.get(dom)?.(); }
|
||||
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 = tr(collapsed.has(item.key) ? "Expand {name}" : "Collapse {name}", { name: item.label });
|
||||
button.setAttribute("aria-expanded", String(!collapsed.has(item.key)));
|
||||
button.setAttribute("aria-label", 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 => { const button = item.heading.querySelector<HTMLElement>(".rs-heading-toggle"); if (button) tooltipCleanups.get(button)?.(); button?.remove(); item.heading.classList.remove("rs-foldable-heading", "rs-heading-collapsed"); });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/* Image frames, image actions, and the image viewer, from imageControls.ts. */
|
||||
.md-image-frame { display: block; position: relative; width: fit-content; max-width: 100%; margin: 1.4em 0; }
|
||||
.md-image-frame.is-selected, .md-image-frame:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: 3px; border-radius: 6px; }
|
||||
.md-image-frame.is-selected .md-image-actions { opacity: 1; }
|
||||
.md-image-frame[data-error]::after { content: attr(data-error); display: block; padding: 8px; color: var(--rs-text); background: var(--rs-bg-elevated); font: 12px/1.5 var(--rs-font-ui); }
|
||||
.writer-image-inline { display: inline-block; vertical-align: middle; max-width: 100%; }
|
||||
.writer-image-inline .md-image-frame { margin: .5em 0; }
|
||||
.image-drop-target { outline: 2px solid var(--rs-accent); outline-offset: -3px; }
|
||||
.reading .md-image-frame img { margin: 0; }
|
||||
.md-image-actions { position: absolute; top: 8px; right: 8px; display: flex; gap: 2px; padding: 3px; border-radius: 6px; background: var(--rs-bg-elevated); box-shadow: 0 2px 8px #0005; opacity: 0; transition: opacity 100ms; }
|
||||
.md-image-frame:hover .md-image-actions, .md-image-frame:focus-within .md-image-actions { opacity: 1; }
|
||||
.image-action { position: relative; display: inline-grid; place-items: center; flex: 0 0 34px; width: 34px; height: 34px; padding: 6px; color: var(--rs-text); border: 0; border-radius: 4px; background: transparent; cursor: pointer; }
|
||||
.image-action:hover, .image-action:focus-visible { background: var(--rs-hover-bg); color: var(--rs-text-strong); }
|
||||
.image-action:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
|
||||
.image-action:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||
.image-lightbox { position: fixed; inset: 0; width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: var(--rs-image-viewer-bg); color: var(--rs-text); }
|
||||
.image-lightbox[open] { display: flex; flex-direction: column; }
|
||||
.image-lightbox::backdrop { background: var(--rs-scrim); }
|
||||
.image-lightbox-toolbar { display: flex; align-items: center; gap: 6px; padding: 8px 16px; background: var(--rs-bg-elevated); z-index: 1; }
|
||||
.image-lightbox-name { margin-right: auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.image-lightbox-scale { min-width: 44px; text-align: center; font-size: 12px; }
|
||||
.image-lightbox-viewport { flex: 1; min-height: 0; overflow: auto; padding: 16px; display: flex; }
|
||||
.image-lightbox-viewport img { display: block; flex-shrink: 0; max-width: 100%; max-height: 100%; object-fit: contain; margin: auto; }
|
||||
.image-lightbox-viewport.is-zoomed { display: block; }
|
||||
.image-lightbox-viewport.is-zoomed img { max-width: none; max-height: none; height: auto; }
|
||||
@@ -0,0 +1,183 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { revealLabel } from '../ui/menuItems.ts';
|
||||
import { actionIcon, type ActionIcon } from "../ui/actionIcons";
|
||||
import { attachTooltip } from "../ui/tooltip";
|
||||
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
|
||||
import type { ActionMenuItem } from "../ui/actionMenu";
|
||||
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
|
||||
import { imageSize, rememberImageSize } from "../workspace/imageSizes";
|
||||
|
||||
export type ImageActions = {
|
||||
edit?: () => void;
|
||||
done?: () => void;
|
||||
editing?: boolean;
|
||||
select?: () => void;
|
||||
remove?: () => void;
|
||||
markdown?: () => string;
|
||||
swap?: (image: HTMLImageElement) => Promise<void>;
|
||||
open?: (image: HTMLImageElement) => void;
|
||||
reveal?: (image: HTMLImageElement) => Promise<void>;
|
||||
report?: (message: string) => void;
|
||||
};
|
||||
|
||||
async function copyImage(image: HTMLImageElement) {
|
||||
const png = (async () => {
|
||||
await image.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = image.naturalWidth; canvas.height = image.naturalHeight;
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) throw new Error(tr("Image clipboard is unavailable."));
|
||||
context.drawImage(image, 0, 0);
|
||||
return await new Promise<Blob>((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Could not copy image.")), "image/png"));
|
||||
})();
|
||||
await navigator.clipboard.write([new ClipboardItem({ "image/png": png })]);
|
||||
}
|
||||
|
||||
function button(label: string, icon: ActionIcon, action: () => void) {
|
||||
const control = document.createElement("button");
|
||||
control.type = "button";
|
||||
control.className = "image-action";
|
||||
control.setAttribute("aria-label", label);
|
||||
tooltipCleanups.set(control, attachTooltip(control, () => label));
|
||||
control.append(actionIcon(icon));
|
||||
control.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); action(); });
|
||||
return control;
|
||||
}
|
||||
|
||||
function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
|
||||
const dialog = document.createElement("dialog");
|
||||
dialog.className = "image-lightbox";
|
||||
dialog.setAttribute("aria-label", tr("Image zoom"));
|
||||
const header = document.createElement("div");
|
||||
header.className = "image-lightbox-toolbar";
|
||||
const name = document.createElement("span");
|
||||
name.className = "image-lightbox-name";
|
||||
name.textContent = original.dataset.mdSrc || original.alt || tr("Image");
|
||||
const viewport = document.createElement("div");
|
||||
viewport.className = "image-lightbox-viewport";
|
||||
const image = original.cloneNode() as HTMLImageElement;
|
||||
image.removeAttribute("loading");
|
||||
image.removeAttribute("width");
|
||||
image.removeAttribute("height");
|
||||
image.draggable = false;
|
||||
let scale = 0;
|
||||
const status = document.createElement("span");
|
||||
status.className = "image-lightbox-scale";
|
||||
status.setAttribute("aria-live", "polite");
|
||||
function resize(next: number) {
|
||||
scale = next;
|
||||
image.style.width = scale ? `${image.naturalWidth * scale}px` : "";
|
||||
viewport.classList.toggle("is-zoomed", scale > 0);
|
||||
status.textContent = scale ? `${Math.round(scale * 100)}%` : tr("Fit");
|
||||
zoomOut.disabled = scale === 0;
|
||||
zoomIn.disabled = scale >= 4;
|
||||
}
|
||||
const zoomOut = button(tr("Zoom out"), "zoom-out", () => resize(scale <= .5 ? 0 : scale / 2));
|
||||
const zoomIn = button(tr("Zoom in"), "zoom-in", () => resize(scale ? Math.min(4, scale * 2) : 1));
|
||||
const fit = button(tr("Fit image"), "select", () => resize(0));
|
||||
const close = button(tr("Close image"), "close", () => dialog.close());
|
||||
header.append(name, zoomOut, status, zoomIn, fit, close);
|
||||
viewport.append(image);
|
||||
dialog.append(header, viewport);
|
||||
dialog.addEventListener("click", event => { if (event.target === dialog || event.target === viewport) dialog.close(); });
|
||||
// Escape and focus trapping are provided by the native modal dialog.
|
||||
dialog.addEventListener("close", () => { [zoomOut, zoomIn, fit, close].forEach(button => tooltipCleanups.get(button)?.()); dialog.remove(); if (trigger.isConnected) trigger.focus(); }, { once: true });
|
||||
image.addEventListener("load", () => resize(scale));
|
||||
document.body.append(dialog);
|
||||
dialog.showModal();
|
||||
resize(0);
|
||||
close.focus();
|
||||
return () => { if (dialog.isConnected) dialog.close(); };
|
||||
}
|
||||
|
||||
export function imageControls(root: HTMLElement, actions: ImageActions = {}, measure?: () => void): () => void {
|
||||
const cleanup: (() => void)[] = [];
|
||||
for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) {
|
||||
if (image.closest(".md-image-frame")) continue;
|
||||
// A remote image gives its size when it loads. The next view of this image keeps its space from the start.
|
||||
const remember = () => rememberImageSize(image.src, image.naturalWidth, image.naturalHeight);
|
||||
image.addEventListener("load", remember);
|
||||
cleanup.push(() => image.removeEventListener("load", remember));
|
||||
const known = !image.getAttribute("width") && imageSize(image.src);
|
||||
if (known) { image.width = known.width; image.height = known.height; }
|
||||
const frame = document.createElement("span");
|
||||
frame.className = "md-image-frame";
|
||||
frame.contentEditable = "false";
|
||||
frame.tabIndex = 0;
|
||||
frame.setAttribute("role", "group");
|
||||
frame.setAttribute("aria-label", tr("Image: {name}", { name: image.alt || image.dataset.mdSrc || tr("Image") }));
|
||||
image.replaceWith(frame);
|
||||
frame.append(image);
|
||||
image.draggable = false;
|
||||
const toolbar = document.createElement("span");
|
||||
toolbar.className = "md-image-actions";
|
||||
let closeZoom: (() => void) | undefined;
|
||||
const zoom = button(tr("Zoom in"), "zoom-in", () => { closeZoom = zoomImage(image, zoom); });
|
||||
cleanup.push(() => closeZoom?.());
|
||||
toolbar.append(zoom);
|
||||
if (actions.edit) toolbar.append(button(actions.editing ? tr("Hide image source") : tr("Edit image source"), "code", actions.editing && actions.done ? actions.done : actions.edit));
|
||||
frame.append(toolbar);
|
||||
cleanup.push(() => toolbar.querySelectorAll<HTMLButtonElement>("button").forEach(button => tooltipCleanups.get(button)?.()));
|
||||
let menu: MenuHandle | undefined;
|
||||
let openingMenu = false;
|
||||
const restore = () => { if (frame.isConnected) frame.focus({ preventScroll: true }); };
|
||||
function closeMenu(focus = true) { menu?.close(); menu = undefined; if (focus) restore(); }
|
||||
async function run(action: () => void | Promise<void>) {
|
||||
closeMenu(false);
|
||||
try { await action(); } catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (actions.report) actions.report(message);
|
||||
else { frame.dataset.error = message; frame.setAttribute("aria-description", message); }
|
||||
}
|
||||
}
|
||||
function select() {
|
||||
actions.select?.();
|
||||
frame.classList.add("is-selected");
|
||||
frame.focus({ preventScroll: true });
|
||||
}
|
||||
function openMenu(x: number, y: number) {
|
||||
closeMenu(false); select();
|
||||
const items: ActionMenuItem[] = [
|
||||
{ label: tr("Copy image"), icon: "copy", run: () => void run(() => copyImage(image)) },
|
||||
...(actions.markdown ? [{ label: tr("Copy Markdown"), icon: "code" as const, run: () => void run(() => navigator.clipboard.writeText(actions.markdown!())) }] : []),
|
||||
...(actions.swap ? [{ label: tr("Swap image…"), icon: "swap" as const, run: () => void run(() => actions.swap!(image)) }] : []),
|
||||
...(actions.remove ? [{ label: tr("Remove image"), icon: "trash" as const, run: () => void run(actions.remove!) }] : []),
|
||||
{ separator: true },
|
||||
{ label: tr("Zoom in"), icon: "zoom-in", run: () => { closeMenu(false); closeZoom = zoomImage(image, zoom); } },
|
||||
...(actions.edit ? [{ label: tr("Edit image source"), icon: "code" as const, run: () => void run(actions.edit!) }] : []),
|
||||
...(actions.open ? [{ label: tr("Open in new tab"), icon: "external" as const, run: () => void run(() => actions.open!(image)) }] : []),
|
||||
{ label: tr("Copy path"), icon: "link", run: () => void run(() => navigator.clipboard.writeText(image.dataset.mdSrc || "")) },
|
||||
...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: tr(revealLabel()), icon: "folder" as const, run: () => void run(() => actions.reveal!(image)) }] : []),
|
||||
];
|
||||
openingMenu = true;
|
||||
try { menu = showActionMenu({ x, y, items, label: tr("Image actions") }, undefined, restore); }
|
||||
finally { openingMenu = false; }
|
||||
}
|
||||
frame.addEventListener("mousedown", event => { if (!(event.target as Element).closest("button")) { event.preventDefault(); event.stopPropagation(); select(); } });
|
||||
frame.addEventListener("contextmenu", event => { event.preventDefault(); event.stopPropagation(); openMenu(event.clientX, event.clientY); });
|
||||
frame.addEventListener("keydown", event => {
|
||||
if (event.target !== frame) return;
|
||||
if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) {
|
||||
event.preventDefault(); event.stopPropagation(); const rect = frame.getBoundingClientRect(); openMenu(rect.left + 16, rect.top + 16);
|
||||
} else if ((event.key === "Delete" || event.key === "Backspace") && actions.remove) {
|
||||
event.preventDefault(); event.stopPropagation(); actions.remove();
|
||||
} else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c") {
|
||||
event.preventDefault(); event.stopPropagation(); void run(() => copyImage(image));
|
||||
} else if (event.key === "Enter" || event.key === " ") { event.preventDefault(); select(); }
|
||||
});
|
||||
const outside = (event: Event) => {
|
||||
if (openingMenu) return;
|
||||
if (event.target instanceof Node && !frame.contains(event.target) && !menu?.element.contains(event.target)) { closeMenu(false); frame.classList.remove("is-selected"); }
|
||||
};
|
||||
// The shared menu closes itself. This handler also clears the image selection.
|
||||
document.addEventListener("mousedown", outside, true);
|
||||
document.addEventListener("focusin", outside, true);
|
||||
cleanup.push(() => { closeMenu(false); document.removeEventListener("mousedown", outside, true); document.removeEventListener("focusin", outside, true); });
|
||||
if (measure) {
|
||||
image.addEventListener("load", measure);
|
||||
image.addEventListener("error", measure);
|
||||
cleanup.push(() => { image.removeEventListener("load", measure); image.removeEventListener("error", measure); });
|
||||
}
|
||||
}
|
||||
return () => cleanup.forEach(dispose => dispose());
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { StateEffect, StateField } from "@codemirror/state";
|
||||
|
||||
export const trackImageDrop = StateEffect.define<{ id: symbol; from: number; to: number }>();
|
||||
export const clearImageDrop = StateEffect.define<symbol>();
|
||||
export const imageDrops = StateField.define<Map<symbol, { from: number; to: number }>>({
|
||||
create: () => new Map(),
|
||||
update(value, transaction) {
|
||||
const next = new Map([...value].map(([id, range]) => [id, {
|
||||
from: transaction.changes.mapPos(range.from, 1),
|
||||
to: transaction.changes.mapPos(range.to, 1),
|
||||
}]));
|
||||
for (const effect of transaction.effects) {
|
||||
if (effect.is(trackImageDrop)) next.set(effect.value.id, effect.value);
|
||||
if (effect.is(clearImageDrop)) next.delete(effect.value);
|
||||
}
|
||||
return next;
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { EditorView, WidgetType } from "@codemirror/view";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { imageControls, type ImageActions } from "./imageControls";
|
||||
import { editImageSource } from "./imageSource";
|
||||
import { requestText } from "../workspace/dialogs.svelte";
|
||||
import { isRemoteImage } from "../workspace/media";
|
||||
import { estimatedImageHeight } from "../workspace/imageSizes";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
|
||||
export type ImageContext = {
|
||||
open?: (image: HTMLImageElement) => void;
|
||||
reveal?: (image: HTMLImageElement) => Promise<void>;
|
||||
validate?: (source: string) => Promise<void>;
|
||||
report?: (message: string) => void;
|
||||
};
|
||||
const cleanups = new WeakMap<HTMLElement, () => void>();
|
||||
|
||||
export class ImagePreview extends WidgetType {
|
||||
constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); }
|
||||
eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; }
|
||||
get estimatedHeight() { return estimatedImageHeight(this.html); }
|
||||
toDOM(view: EditorView) {
|
||||
const dom = document.createElement(this.block ? "div" : "span");
|
||||
dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`;
|
||||
dom.innerHTML = this.html;
|
||||
const range = () => {
|
||||
const position = view.posAtDOM(dom);
|
||||
const from = this.editing ? position - this.source.length : position;
|
||||
return { from, to: from + this.source.length };
|
||||
};
|
||||
const replace = (insert: string) => {
|
||||
if (!dom.isConnected) return;
|
||||
const target = range();
|
||||
view.dispatch({ changes: { ...target, insert }, selection: { anchor: target.from + insert.length }, effects: editImageSource.of(null), annotations: isolateHistory.of("full"), userEvent: "input.image" });
|
||||
view.focus();
|
||||
};
|
||||
const actions: ImageActions = {
|
||||
editing: this.editing,
|
||||
select: () => { const { from, to } = range(); view.dispatch({ selection: { anchor: from, head: to } }); },
|
||||
edit: () => {
|
||||
const target = range();
|
||||
view.dispatch({ effects: [editImageSource.of(target), EditorView.scrollIntoView(target.from, { y: "nearest" })], selection: { anchor: target.from, head: target.to } });
|
||||
view.focus();
|
||||
},
|
||||
done: () => { view.dispatch({ effects: editImageSource.of(null) }); view.focus(); },
|
||||
remove: () => replace(""),
|
||||
markdown: () => this.source,
|
||||
open: this.context.open,
|
||||
reveal: this.context.reveal,
|
||||
report: this.context.report,
|
||||
swap: async image => {
|
||||
const before = view.state.doc;
|
||||
const path = (await requestText(tr("Image path relative to this note, or https URL"), image.dataset.mdSrc || ""))?.trim();
|
||||
if (!path || !dom.isConnected || view.state.doc !== before) return;
|
||||
if (!isRemoteImage(path) && /^[a-z][a-z\d+.-]*:/i.test(path)) throw new Error(tr("Choose a workspace image path or an http/https URL."));
|
||||
await this.context.validate?.(path);
|
||||
if (!dom.isConnected || view.state.doc !== before) return;
|
||||
const target = path.replace(/[<>\s]/g, char => encodeURIComponent(char));
|
||||
const alt = image.alt.replace(/[\\\[\]]/g, "\\$&");
|
||||
replace(``);
|
||||
},
|
||||
};
|
||||
cleanups.set(dom, imageControls(dom, actions, () => { if (dom.isConnected) view.requestMeasure(); }));
|
||||
// A missing attachment must still offer a way to repair its hidden source.
|
||||
if (!dom.querySelector("img")) {
|
||||
const edit = document.createElement("button");
|
||||
edit.type = "button"; edit.className = "image-action";
|
||||
const label = this.editing ? tr("Hide image source") : tr("Edit image source");
|
||||
edit.setAttribute("aria-label", label); edit.dataset.editorTooltip = label;
|
||||
edit.append(actionIcon("code"));
|
||||
edit.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); (this.editing ? actions.done : actions.edit)?.(); });
|
||||
dom.append(edit);
|
||||
}
|
||||
return dom;
|
||||
}
|
||||
destroy(dom: HTMLElement) { cleanups.get(dom)?.(); }
|
||||
ignoreEvent() { return true; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { StateEffect, StateField } from "@codemirror/state";
|
||||
import { markdownLanguage } from "@codemirror/lang-markdown";
|
||||
|
||||
export type ImageRange = { from: number; to: number };
|
||||
export function imageSourceRanges(source: string): ImageRange[] {
|
||||
const ranges: ImageRange[] = [];
|
||||
// Image controls must also work beyond CodeMirror's partially parsed viewport.
|
||||
markdownLanguage.parser.parse(source).iterate({ enter(node) {
|
||||
if (node.name === "Image") { ranges.push({ from: node.from, to: node.to }); return false; }
|
||||
} });
|
||||
return ranges;
|
||||
}
|
||||
export const editImageSource = StateEffect.define<ImageRange | null>();
|
||||
export const imageSource = StateField.define<ImageRange | null>({
|
||||
create: () => null,
|
||||
update(value, transaction) {
|
||||
if (value) value = { from: transaction.changes.mapPos(value.from, -1), to: transaction.changes.mapPos(value.to, 1) };
|
||||
for (const effect of transaction.effects) if (effect.is(editImageSource)) value = effect.value;
|
||||
if (value && transaction.selection && !transaction.selection.ranges.some(range => range.from <= value.to && range.to >= value.from)) return null;
|
||||
return value;
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
const LANGUAGES: Record<string, string> = {
|
||||
md: "markdown",
|
||||
markdown: "markdown",
|
||||
mdown: "markdown",
|
||||
txt: "plaintext",
|
||||
py: "python",
|
||||
js: "javascript",
|
||||
mjs: "javascript",
|
||||
cjs: "javascript",
|
||||
ts: "typescript",
|
||||
tsx: "typescript",
|
||||
jsx: "javascript",
|
||||
json: "json",
|
||||
css: "css",
|
||||
scss: "scss",
|
||||
html: "html",
|
||||
htm: "html",
|
||||
rs: "rust",
|
||||
sh: "shell",
|
||||
bash: "shell",
|
||||
yml: "yaml",
|
||||
yaml: "yaml",
|
||||
toml: "ini",
|
||||
xml: "xml",
|
||||
svg: "xml",
|
||||
};
|
||||
|
||||
function fileExt(relPath: string): string {
|
||||
const base = relPath.split("/").pop() ?? relPath;
|
||||
const dot = base.lastIndexOf(".");
|
||||
if (dot <= 0) {
|
||||
return "";
|
||||
}
|
||||
return base.slice(dot + 1).toLowerCase();
|
||||
}
|
||||
|
||||
export function languageFor(relPath: string): string {
|
||||
return LANGUAGES[fileExt(relPath)] ?? "plaintext";
|
||||
}
|
||||
@@ -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 : ""}]]`);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import type { ActionMenuItem } from "../ui/actionMenu";
|
||||
|
||||
export type MenuLink = { kind: "md" | "wiki"; target: string };
|
||||
export type DocumentLinkActions = {
|
||||
open?: (link: MenuLink) => void | Promise<void>;
|
||||
browser?: (target: string) => void | Promise<void>;
|
||||
defaultBrowser?: (target: string) => void | Promise<void>;
|
||||
workspaceItems?: (link: MenuLink) => ActionMenuItem[];
|
||||
};
|
||||
|
||||
export function linkMenuItems(link: MenuLink, actions: DocumentLinkActions, close: () => void, report: (message: string) => void, edit?: () => void): ActionMenuItem[] {
|
||||
const run = (action: () => void | Promise<void>) => () => {
|
||||
close();
|
||||
void Promise.resolve().then(action).catch(error => report(error instanceof Error ? error.message : String(error)));
|
||||
};
|
||||
const external = /^(https?:\/\/|mailto:)/i.test(link.target);
|
||||
const items: ActionMenuItem[] = external ? [
|
||||
...(actions.browser && /^https?:\/\//i.test(link.target) ? [{ label: tr("Open link in app browser"), icon: "globe" as const, run: run(() => actions.browser!(link.target)) }] : []),
|
||||
...(actions.defaultBrowser ? [{ label: tr("Open link in default browser"), icon: "external" as const, run: run(() => actions.defaultBrowser!(link.target)) }] : []),
|
||||
] : [];
|
||||
if (!items.length && actions.open) items.push({ label: external ? tr("Open link") : tr("Open in new tab"), icon: external ? "external" : "file-plus", run: run(() => actions.open!(link)) });
|
||||
if (!external && actions.workspaceItems) {
|
||||
const wrap = (item: ActionMenuItem): ActionMenuItem => "separator" in item ? item : { ...item, run: item.run ? run(item.run) : undefined, children: item.children?.map(wrap) };
|
||||
const workspaceItems = actions.workspaceItems(link).filter(item => !edit || "separator" in item || ![tr("Rename…"), tr("Move file to…"), tr("Open in default app")].includes(item.label));
|
||||
items.push(...workspaceItems.map(wrap));
|
||||
}
|
||||
items.push({ label: external ? tr("Copy URL") : tr("Copy link target"), icon: "link", run: run(() => navigator.clipboard.writeText(link.target)) });
|
||||
if (edit) items.push({ label: tr("Edit link"), icon: "rename", run: () => { close(); edit(); } });
|
||||
return items;
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { isMac } from "../ui/shortcuts";
|
||||
|
||||
/** The tooltip of a link in Write. A click with Ctrl, or Cmd on macOS, opens the link. */
|
||||
const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" });
|
||||
import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
|
||||
import { renderMarkdownSections } from "../workspace/noteHtml";
|
||||
import { renderDiagrams } from "../workspace/diagrams";
|
||||
import { tableControls, tableEditors } from "./tableControls";
|
||||
import { parseMarkdownTable } from "./markdownTable";
|
||||
import type { TableContextActions } from "./tableCellActions";
|
||||
import { imageControls } from "./imageControls";
|
||||
import { ImagePreview, type ImageContext } from "./imagePreview";
|
||||
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
import { attachTooltip } from "../ui/tooltip";
|
||||
import { documentLinks } from "./documentLinks";
|
||||
import { listLabels } from "./markdownLists";
|
||||
|
||||
import { activeTableFormulas } from "../formulas/index.ts";
|
||||
|
||||
const previewFormulas = new WeakMap<HTMLElement, unknown>();
|
||||
const previewHtml = new WeakMap<HTMLElement, string>();
|
||||
export const refreshImages = StateEffect.define<void>();
|
||||
const imageCleanups = new WeakMap<HTMLElement, () => void>();
|
||||
|
||||
/**
|
||||
* CodeMirror reads the line height of the document from the first short line that holds only plain text.
|
||||
* A different height makes it estimate all heights again, and the view then jumps to other text.
|
||||
* A mark span keeps a line with a different height out of that reading.
|
||||
*/
|
||||
const otherLineHeight = Decoration.mark({ class: "writer-line-text" });
|
||||
|
||||
// A resize observer records the height of a preview without a CodeMirror measure request.
|
||||
// A request from toDOM restarts the layout loop of CodeMirror, and a loop that restarts too often does not restore the scroll position.
|
||||
const previewHeights = new WeakMap<Element, { value: number }>();
|
||||
let previewSizes: ResizeObserver | undefined;
|
||||
function watchPreviewHeight(dom: HTMLElement, height: { value: number }) {
|
||||
previewSizes ??= new ResizeObserver(entries => {
|
||||
for (const { target } of entries) {
|
||||
const holder = previewHeights.get(target);
|
||||
if (holder && target.isConnected) holder.value = (target as HTMLElement).offsetHeight;
|
||||
}
|
||||
});
|
||||
const known = previewHeights.get(dom);
|
||||
if (known && known !== height) height.value = known.value;
|
||||
previewHeights.set(dom, height);
|
||||
previewSizes.observe(dom);
|
||||
}
|
||||
|
||||
const linkTooltips = ViewPlugin.define(view => {
|
||||
const attached = new Map<HTMLElement, () => void>();
|
||||
const refresh = () => {
|
||||
for (const [node, dispose] of attached) if (!view.dom.contains(node)) { dispose(); attached.delete(node); }
|
||||
for (const node of view.dom.querySelectorAll<HTMLElement>("[data-editor-tooltip]")) {
|
||||
if (!attached.has(node)) attached.set(node, attachTooltip(node, () => node.dataset.editorTooltip || ""));
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(refresh);
|
||||
observer.observe(view.dom, { childList: true, subtree: true });
|
||||
refresh();
|
||||
return { destroy() { observer.disconnect(); attached.forEach(dispose => dispose()); } };
|
||||
});
|
||||
|
||||
class CodeCopy extends WidgetType {
|
||||
constructor(readonly code: string) { super(); }
|
||||
eq(other: CodeCopy) { return this.code === other.code; }
|
||||
toDOM() {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "rs-fence-copy writer-code-copy";
|
||||
button.setAttribute("aria-label", tr("Copy code"));
|
||||
button.dataset.editorTooltip = tr("Copy code");
|
||||
button.append(actionIcon("copy"));
|
||||
button.onmousedown = event => event.preventDefault();
|
||||
button.onclick = async event => {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
try {
|
||||
await navigator.clipboard.writeText(this.code);
|
||||
button.dataset.copied = "true";
|
||||
button.dataset.editorTooltip = tr("Copied");
|
||||
button.setAttribute("aria-label", tr("Code copied"));
|
||||
} catch {
|
||||
button.dataset.editorTooltip = tr("Could not copy code");
|
||||
button.setAttribute("aria-label", tr("Could not copy code"));
|
||||
}
|
||||
};
|
||||
return button;
|
||||
}
|
||||
ignoreEvent() { return true; }
|
||||
}
|
||||
|
||||
class Divider extends WidgetType {
|
||||
eq(other: Divider) { return other instanceof Divider; }
|
||||
toDOM(view: EditorView) {
|
||||
const dom = document.createElement("span");
|
||||
dom.className = "writer-divider";
|
||||
dom.setAttribute("role", "separator");
|
||||
dom.addEventListener("mousedown", event => {
|
||||
if (event.button !== 0 || event.shiftKey) return;
|
||||
event.preventDefault();
|
||||
view.dispatch({ selection: { anchor: view.posAtDOM(dom) }, scrollIntoView: true });
|
||||
view.focus();
|
||||
});
|
||||
return dom;
|
||||
}
|
||||
ignoreEvent() { return false; }
|
||||
}
|
||||
|
||||
class Checkbox extends WidgetType {
|
||||
constructor(readonly checked: boolean) { super(); }
|
||||
eq(other: Checkbox) { return this.checked === other.checked; }
|
||||
toDOM(view: EditorView) {
|
||||
const box = document.createElement("input");
|
||||
box.type = "checkbox";
|
||||
box.checked = this.checked;
|
||||
box.className = "writer-checkbox";
|
||||
box.setAttribute("aria-label", this.checked ? tr("Mark task incomplete") : tr("Mark task complete"));
|
||||
box.addEventListener("mousedown", event => event.preventDefault());
|
||||
box.addEventListener("click", event => {
|
||||
event.stopPropagation();
|
||||
const line = view.state.doc.lineAt(view.posAtDOM(box));
|
||||
const match = /^(\s*[-+*]\s+\[)([ xX])(\])/.exec(line.text);
|
||||
if (!match) return;
|
||||
const from = line.from + match[1].length;
|
||||
view.dispatch({ changes: { from, to: from + 1, insert: this.checked ? " " : "x" }, userEvent: "input" });
|
||||
});
|
||||
return box;
|
||||
}
|
||||
ignoreEvent() { return true; }
|
||||
}
|
||||
|
||||
class ListLabel extends WidgetType {
|
||||
constructor(readonly label: string) { super(); }
|
||||
eq(other: ListLabel) { return other.label === this.label; }
|
||||
toDOM() {
|
||||
const span = document.createElement("span");
|
||||
span.className = "writer-list-label";
|
||||
span.textContent = this.label;
|
||||
return span;
|
||||
}
|
||||
ignoreEvent() { return false; }
|
||||
}
|
||||
|
||||
/**
|
||||
* The heights of previews, by their HTML, from a layout outside the editor. CodeMirror draws only the lines near the view.
|
||||
* Without a height, a large table counts as one line until its first draw. The document then grows by thousands of pixels
|
||||
* at one time, the scrollbar moves, and the layout loop of CodeMirror can stop before it restores the scroll position.
|
||||
*/
|
||||
const measuredHeights = new Map<string, { width: number; height: number }>();
|
||||
const maxMeasuredHeights = 1000;
|
||||
|
||||
class Preview extends WidgetType {
|
||||
readonly formulas = activeTableFormulas();
|
||||
readonly estimate: number;
|
||||
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) {
|
||||
super();
|
||||
this.estimate = measuredHeights.get(html)?.height ?? -1;
|
||||
}
|
||||
get estimatedHeight() { return this.height.value >= 0 ? this.height.value : this.estimate; }
|
||||
// A new estimate must reach the height map of CodeMirror. updateDOM keeps the drawn table.
|
||||
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible && other.estimate === this.estimate; }
|
||||
updateDOM(dom: HTMLElement) {
|
||||
const table = tableEditors.get(dom);
|
||||
if (previewFormulas.get(dom) !== this.formulas || (table ? table.source !== this.source : previewHtml.get(dom) !== this.html)) return false;
|
||||
watchPreviewHeight(dom, this.height);
|
||||
return true;
|
||||
}
|
||||
destroy(dom: HTMLElement) { previewSizes?.unobserve(dom); tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
|
||||
toDOM(view: EditorView) {
|
||||
const dom = document.createElement("div");
|
||||
previewFormulas.set(dom, this.formulas);
|
||||
previewHtml.set(dom, this.html);
|
||||
dom.className = "reading writer-preview";
|
||||
dom.innerHTML = this.html;
|
||||
// Widgets handle their own events, so CodeMirror's link handler cannot run.
|
||||
dom.addEventListener("mousedown", event => {
|
||||
if (event.button !== 0 || (!event.ctrlKey && !event.metaKey)) return;
|
||||
const link = event.target instanceof Element ? event.target.closest<HTMLElement>("[data-href], a[href]") : null;
|
||||
if (!link) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void this.actions.linkActions?.().open?.({ kind: link.dataset.kind === "wiki" ? "wiki" : "md", target: link.dataset.href ?? link.getAttribute("href") ?? "" });
|
||||
}, { capture: true });
|
||||
// Cancel native anchor navigation even when an ordinary click reveals source.
|
||||
dom.addEventListener("click", event => {
|
||||
if (event.target instanceof Element && event.target.closest("a[href], [data-href]")) event.preventDefault();
|
||||
}, { capture: true });
|
||||
tableControls(dom, view, this.source, this.actions);
|
||||
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
|
||||
watchPreviewHeight(dom, this.height);
|
||||
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
|
||||
dom.addEventListener("mousedown", event => {
|
||||
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
|
||||
if (event.target instanceof Element && event.target.closest("summary, .md-image-frame")) return;
|
||||
if (event.ctrlKey || event.metaKey) return;
|
||||
event.preventDefault();
|
||||
view.dispatch({ selection: { anchor: view.posAtDOM(dom) }, scrollIntoView: true });
|
||||
view.focus();
|
||||
});
|
||||
requestAnimationFrame(() => {
|
||||
if (dom.isConnected) {
|
||||
void renderDiagrams(dom, () => !dom.isConnected).then(() => view.requestMeasure());
|
||||
view.requestMeasure();
|
||||
}
|
||||
});
|
||||
return dom;
|
||||
}
|
||||
ignoreEvent() { return true; }
|
||||
}
|
||||
|
||||
function textColumnWidth(view: EditorView) {
|
||||
const style = getComputedStyle(view.contentDOM);
|
||||
return view.contentDOM.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
|
||||
}
|
||||
|
||||
/** Measure previews in one layout pass, in a hidden copy of the text column. A copy has the table frame and footer, but not the table controls. */
|
||||
function measurePreviews(view: EditorView, widgets: Preview[], width: number) {
|
||||
const host = document.createElement("div");
|
||||
host.className = view.contentDOM.className;
|
||||
host.setAttribute("aria-hidden", "true");
|
||||
host.style.cssText = "position:absolute;inset:0 0 auto 0;height:0;min-height:0;padding-block:0;overflow:hidden;visibility:hidden;pointer-events:none";
|
||||
const footer = document.createElement("div");
|
||||
footer.className = "table-footer";
|
||||
const tools = activeTableFormulas()?.createFormulaTools(() => {}, () => {});
|
||||
if (tools) footer.append(tools.formulaTools);
|
||||
const copies = widgets.map(widget => {
|
||||
const copy = document.createElement("div");
|
||||
copy.className = "reading writer-preview";
|
||||
copy.innerHTML = widget.html;
|
||||
const scroll = copy.querySelector(".md-table-scroll");
|
||||
if (scroll && parseMarkdownTable(widget.source)) {
|
||||
const frame = document.createElement("div");
|
||||
frame.className = "writer-table";
|
||||
scroll.before(frame);
|
||||
frame.append(scroll);
|
||||
frame.after(footer.cloneNode(true));
|
||||
}
|
||||
host.append(copy);
|
||||
return copy;
|
||||
});
|
||||
view.scrollDOM.append(host);
|
||||
if (measuredHeights.size + widgets.length > maxMeasuredHeights) measuredHeights.clear();
|
||||
copies.forEach((copy, index) => {
|
||||
measuredHeights.set(widgets[index].html, { width, height: copy.offsetHeight });
|
||||
widgets[index].height.value = -1;
|
||||
});
|
||||
host.remove();
|
||||
}
|
||||
|
||||
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
|
||||
const selecting = StateEffect.define<boolean>();
|
||||
const mouseSelecting = StateField.define({
|
||||
create: () => false,
|
||||
update(value, transaction) {
|
||||
if (transaction.docChanged) return false;
|
||||
for (const effect of transaction.effects) if (effect.is(selecting)) value = effect.value;
|
||||
return value;
|
||||
},
|
||||
});
|
||||
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 }));
|
||||
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.
|
||||
if (/^<pre\b/.test(section.html)) continue;
|
||||
// The first rendered section includes leading blank lines. Keep those
|
||||
// editable when the user exits above a table at the start of a note.
|
||||
if (/<table>/.test(section.html)) section.start += /^(?:[ \t]*\r?\n)+/.exec(source.slice(section.start, section.end))?.[0].length ?? 0;
|
||||
const end = section.end - (source.slice(section.start, section.end).match(/\n+$/)?.[0].length || 0);
|
||||
const isTable = /<table>/.test(section.html) && parseMarkdownTable(source.slice(section.start, end));
|
||||
if (end <= section.start) continue;
|
||||
const imageHtml = section.html.match(/<img\b[^>]*>|<span class="missing-image"[^>]*>[\s\S]*?<\/span>/g) || [];
|
||||
const nodes = imageNodes.filter(node => node.from >= section.start && node.to <= end);
|
||||
if (!isTable && imageHtml.length && imageHtml.length === nodes.length && (!/md-callout/.test(section.html) || selected(section.start, end))) {
|
||||
nodes.forEach((node, index) => {
|
||||
const revealed = editing?.from === node.from;
|
||||
const block = state.doc.lineAt(node.from).from === node.from && state.doc.lineAt(node.to).to === node.to;
|
||||
const widget = new ImagePreview(imageHtml[index], source.slice(node.from, node.to), images, revealed, revealed || block);
|
||||
if (revealed) ranges.push(Decoration.widget({ widget, block: true, side: 1 }).range(node.to));
|
||||
else {
|
||||
hiddenBlocks.push(node);
|
||||
ranges.push(Decoration.replace({ widget, block, atomic: true }).range(node.from, node.to));
|
||||
}
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (!isTable && selected(section.start, end)) {
|
||||
// Keep images below the editable source, without duplicating surrounding prose.
|
||||
const images = section.html.match(/<img\b[^>]*>|<span class="missing-image"[^>]*>[\s\S]*?<\/span>/g)?.join("");
|
||||
if (images) ranges.push(Decoration.widget({ widget: new Preview(images, source.slice(section.start, end), actions, true), block: true, side: 1 }).range(end));
|
||||
continue;
|
||||
}
|
||||
hiddenBlocks.push({ from: section.start, to: end });
|
||||
// Keep the table height between edits and the next layout pass. A one-line
|
||||
// estimate can move the scroll anchor below a tall table on a second update.
|
||||
let height: { value: number } | undefined;
|
||||
if (isTable) previous?.between(section.start, end, (from, to, decoration) => {
|
||||
if (from === section.start && to === end && decoration.spec.widget instanceof Preview) height = decoration.spec.widget.height;
|
||||
});
|
||||
ranges.push(Decoration.replace({ widget: new Preview(section.html, source.slice(section.start, end), actions, false, height), block: true, atomic: true }).range(section.start, end));
|
||||
}
|
||||
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
|
||||
for (let number = 1; number <= state.doc.lines; number++) {
|
||||
const line = state.doc.line(number);
|
||||
if (!line.text.trim() && !hidden(line.from, line.to)) {
|
||||
ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
|
||||
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
|
||||
}
|
||||
}
|
||||
const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); };
|
||||
const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
|
||||
const codeRanges: { from: number; to: number }[] = [];
|
||||
syntaxTree(state).iterate({ enter(node) {
|
||||
if (hidden(node.from, node.to)) return false;
|
||||
if (node.name === "FencedCode" || node.name === "CodeBlock") {
|
||||
codeRanges.push({ from: node.from, to: node.to });
|
||||
const first = state.doc.lineAt(node.from), last = state.doc.lineAt(node.to);
|
||||
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);
|
||||
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: 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));
|
||||
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const line = state.doc.lineAt(node.from);
|
||||
// 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 (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
|
||||
}
|
||||
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" && !(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");
|
||||
if (node.name === "InlineCode") mark(node.from, node.to, "writer-inline-code");
|
||||
if (node.name === "NoteHighlight") mark(node.from, node.to, "writer-highlight");
|
||||
if (node.name === "NoteMath") mark(node.from, node.to, "writer-math");
|
||||
if (node.name === "NoteComment") mark(node.from, node.to, "writer-comment");
|
||||
if (["EmphasisMark", "StrikethroughMark", "CodeMark", "NoteFormatMark"].includes(node.name)) replace(node.from, node.to);
|
||||
if (node.name === "Link") {
|
||||
// Wiki links are handled separately, because CommonMark sees their inner
|
||||
// brackets as an incomplete reference link.
|
||||
if (source[node.from - 1] === "[" && source[node.to] === "]") return false;
|
||||
const text = source.slice(node.from, node.to);
|
||||
const match = /^\[([^\]]+)\]\(([^\s)]+)(?:\s+"[^"]*")?\)$/.exec(text);
|
||||
if (!match) return;
|
||||
replace(node.from, node.from + 1);
|
||||
replace(node.from + 1 + match[1].length, node.to);
|
||||
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", "data-editor-tooltip": linkTooltip() } }).range(node.from + 1, node.from + 1 + match[1].length));
|
||||
return false;
|
||||
}
|
||||
} });
|
||||
// Nested ordered markers show letters or Roman numerals. A selection over a marker shows its source.
|
||||
for (const label of listLabels(state)) {
|
||||
if (hidden(label.from, label.to) || state.selection.ranges.some(range => range.from < label.to && range.to > label.from)) continue;
|
||||
ranges.push(Decoration.replace({ widget: new ListLabel(label.label), atomic: true }).range(label.from, label.to));
|
||||
}
|
||||
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;
|
||||
const separator = match[1].indexOf("|");
|
||||
const labelStart = from + 2 + (separator < 0 ? 0 : separator + 1);
|
||||
replace(from, labelStart);
|
||||
replace(to - 2, to);
|
||||
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0], "data-editor-tooltip": linkTooltip() } }).range(labelStart, to - 2));
|
||||
}
|
||||
for (const link of documentLinks(source)) {
|
||||
if (!selected(link.from, link.to) || hidden(link.from, link.to)) continue;
|
||||
mark(link.from, link.to, "writer-link-source");
|
||||
mark(link.targetFrom, link.targetTo, "writer-link-target");
|
||||
}
|
||||
return Decoration.set(ranges, true);
|
||||
}
|
||||
const decorations = StateField.define<DecorationSet>({
|
||||
create: build,
|
||||
update(value, transaction) {
|
||||
// Preserve the rendered geometry until the pointer gesture ends.
|
||||
if (transaction.state.field(mouseSelecting) && !transaction.docChanged) return value;
|
||||
return transaction.docChanged || transaction.selection
|
||||
|| syntaxTree(transaction.startState) !== syntaxTree(transaction.state)
|
||||
|| transaction.effects.some(effect => effect.is(selecting) || 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({
|
||||
filter: (_from, _to, decoration) => decoration.spec.atomic === true,
|
||||
}))],
|
||||
});
|
||||
// Give each preview that is not drawn a height, after the document opens, changes, or gets another width.
|
||||
const previewMeasuring = ViewPlugin.fromClass(class {
|
||||
frame = 0;
|
||||
width = -1;
|
||||
constructor(readonly view: EditorView) { this.schedule(); }
|
||||
update(update: ViewUpdate) {
|
||||
if (update.geometryChanged || update.startState.field(decorations) !== update.state.field(decorations)) this.schedule();
|
||||
}
|
||||
schedule() {
|
||||
this.frame ||= requestAnimationFrame(() => { this.frame = 0; this.measure(); });
|
||||
}
|
||||
measure() {
|
||||
const { view } = this, width = textColumnWidth(view);
|
||||
// The editor has no width while another view or tab covers it.
|
||||
if (width < 50) return;
|
||||
const resized = Math.abs(width - this.width) > 1;
|
||||
this.width = width;
|
||||
const { from: drawnFrom, to: drawnTo } = view.viewport;
|
||||
const widgets: Preview[] = [];
|
||||
view.state.field(decorations).between(0, view.state.doc.length, (from, to, decoration) => {
|
||||
const widget = decoration.spec.widget;
|
||||
if (!(widget instanceof Preview) || (from < drawnTo && to > drawnFrom)) return;
|
||||
if ((resized || widget.height.value < 0) && measuredHeights.get(widget.html)?.width !== width) widgets.push(widget);
|
||||
});
|
||||
if (!widgets.length) return;
|
||||
measurePreviews(view, widgets, width);
|
||||
view.dispatch({ effects: refreshImages.of() });
|
||||
}
|
||||
destroy() { cancelAnimationFrame(this.frame); }
|
||||
});
|
||||
const mousePreview = ViewPlugin.define(view => {
|
||||
const finish = () => {
|
||||
if (!view.state.field(mouseSelecting)) return;
|
||||
const selection = view.state.selection;
|
||||
const ranges = selection.ranges.map(range => {
|
||||
if (range.empty) return range;
|
||||
let from = range.from, to = range.to;
|
||||
// Include hidden syntax at the selected label's exposed boundaries.
|
||||
view.state.field(decorations).between(0, view.state.doc.length, (start, end, decoration) => {
|
||||
if (decoration.spec.atomic !== true || decoration.spec.widget) return;
|
||||
if (range.from >= start && range.from <= end) from = Math.min(from, start);
|
||||
if (range.to >= start && range.to <= end) to = Math.max(to, end);
|
||||
});
|
||||
return EditorSelection.range(range.anchor <= range.head ? from : to, range.anchor <= range.head ? to : from);
|
||||
});
|
||||
view.dispatch({ selection: EditorSelection.create(ranges, selection.mainIndex), effects: selecting.of(false) });
|
||||
};
|
||||
const release = () => queueMicrotask(finish);
|
||||
const start = (event: MouseEvent) => {
|
||||
if (event.button || event.ctrlKey || event.metaKey || !(event.target instanceof Element)
|
||||
|| event.target.closest(".writer-preview, button, input")) return;
|
||||
view.dispatch({ effects: selecting.of(true) });
|
||||
};
|
||||
view.contentDOM.addEventListener("mousedown", start);
|
||||
document.addEventListener("mouseup", release);
|
||||
document.addEventListener("dragend", release);
|
||||
window.addEventListener("blur", finish);
|
||||
return { destroy() {
|
||||
view.contentDOM.removeEventListener("mousedown", start);
|
||||
document.removeEventListener("mouseup", release);
|
||||
document.removeEventListener("dragend", release);
|
||||
window.removeEventListener("blur", finish);
|
||||
} };
|
||||
});
|
||||
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, previewMeasuring, mousePreview, syncBodyFocus,
|
||||
EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing))];
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { plainInlineMarkdown } from "../workspace/noteHtml.ts";
|
||||
|
||||
export type TextSelection = { from: number; to: number };
|
||||
export type MarkdownEdit = TextSelection & { insert: string; anchor: number; head: number };
|
||||
export type InlineFormat = "bold" | "italic" | "strike" | "highlight" | "code" | "math" | "comment" | "clear";
|
||||
export type ParagraphStyle = "bullet" | "number" | "task" | "body" | "quote" | 1 | 2 | 3 | 4 | 5 | 6;
|
||||
export type InsertBlock = "footnote" | "table" | "callout" | "rule" | "code" | "math";
|
||||
|
||||
export function replacement(selection: TextSelection, insert: string, start = 0, end = insert.length): MarkdownEdit {
|
||||
return { ...selection, insert, anchor: selection.from + start, head: selection.from + end };
|
||||
}
|
||||
|
||||
export function formatText(source: string, selection: TextSelection, format: InlineFormat): MarkdownEdit {
|
||||
let { from, to } = selection;
|
||||
const selected = source.slice(from, to);
|
||||
if (format === "clear") {
|
||||
let marker: string | undefined;
|
||||
do {
|
||||
marker = ["**", "__", "~~", "==", "%%", "*", "_", "$", "`"].find(value => source.slice(0, from).endsWith(value) && source.slice(to).startsWith(value));
|
||||
if (marker) { from -= marker.length; to += marker.length; }
|
||||
} while (marker);
|
||||
// The inline serializer uses <br> in tables; retain real newlines in prose.
|
||||
return replacement({ from, to }, plainInlineMarkdown(source.slice(from, to)).replace(/<br>/g, source.includes("\r\n") ? "\r\n" : "\n"));
|
||||
}
|
||||
let marker = { bold: "**", italic: "*", strike: "~~", highlight: "==", code: "`", math: "$", comment: "%%" }[format];
|
||||
// Ignore boundary whitespace so emphasis stays valid Markdown.
|
||||
if (selected.trim()) { from += selected.length - selected.trimStart().length; to -= selected.length - selected.trimEnd().length; }
|
||||
const text = source.slice(from, to);
|
||||
if (format === "code") {
|
||||
const wrapped = /^(`+)([\s\S]+)\1$/.exec(text);
|
||||
if (wrapped && !wrapped[2].startsWith("`") && !wrapped[2].endsWith("`")) return replacement({ from, to }, wrapped[2].replace(/^ (.*) $/s, "$1"));
|
||||
const before = /(`+) ?$/.exec(source.slice(0, from)), after = /^ ?(`+)/.exec(source.slice(to));
|
||||
if (before && after && before[1] === after[1]) return replacement({ from: from - before[0].length, to: to + after[0].length }, text);
|
||||
}
|
||||
const isWrapped = text.startsWith(marker) && text.endsWith(marker) && text.length >= marker.length * 2
|
||||
&& !(format === "italic" && text.startsWith("**") && !text.startsWith("***"));
|
||||
if (isWrapped) return replacement({ from, to }, text.slice(marker.length, -marker.length));
|
||||
const before = source.slice(0, from), after = source.slice(to);
|
||||
const surrounds = before.endsWith(marker) && after.startsWith(marker)
|
||||
&& !(format === "italic" && before.endsWith("**") && !before.endsWith("***"));
|
||||
if (surrounds) return replacement({ from: from - marker.length, to: to + marker.length }, text);
|
||||
if (format === "code") marker = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map(match => match[0].length)) + 1);
|
||||
const padding = format === "code" && /^`|`$/.test(text) ? " " : "";
|
||||
return replacement({ from, to }, marker + padding + text + padding + marker, marker.length + padding.length, marker.length + padding.length + text.length);
|
||||
}
|
||||
|
||||
export function paragraphText(source: string, selection: TextSelection, style: ParagraphStyle): MarkdownEdit {
|
||||
const from = selection.from === 0 ? 0 : source.lastIndexOf("\n", selection.from - 1) + 1;
|
||||
// A selection ending at the start of the next line must not format that line.
|
||||
const last = selection.to > selection.from && source[selection.to - 1] === "\n" ? selection.to - 1 : selection.to;
|
||||
const newline = source.indexOf("\n", last);
|
||||
const to = newline < 0 ? source.length : newline > 0 && source[newline - 1] === "\r" ? newline - 1 : newline;
|
||||
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
||||
let number = 0;
|
||||
const insert = source.slice(from, to).split(/\r?\n/).map(line => {
|
||||
if (!line.trim() && from !== to) { number = 0; return line; }
|
||||
const indent = /^[\t ]*/.exec(line)![0];
|
||||
const body = line.slice(indent.length).replace(/^(?:#{1,6}\s+|>\s?|(?:[-+*]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)/, "");
|
||||
const prefix = typeof style === "number" ? "#".repeat(style) + " " : { bullet: "- ", number: `${++number}. `, task: "- [ ] ", quote: "> ", body: "" }[style];
|
||||
return indent + prefix + body;
|
||||
}).join(eol);
|
||||
return replacement({ from, to }, insert, selection.from === selection.to ? insert.length : 0);
|
||||
}
|
||||
|
||||
export function insertBlock(source: string, selection: TextSelection, kind: InsertBlock): MarkdownEdit {
|
||||
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
||||
const text = source.slice(selection.from, selection.to);
|
||||
if (kind === "footnote") {
|
||||
let id = 1;
|
||||
while (source.includes(`[^${id}]`)) id++;
|
||||
const reference = `[^${id}]`, definition = (text || "Footnote text").replace(/\r?\n/g, eol + " ");
|
||||
const tail = source.slice(selection.to);
|
||||
const beforeDefinition = reference + tail;
|
||||
const gap = beforeDefinition.endsWith(eol + eol) ? "" : beforeDefinition.endsWith(eol) ? eol : eol + eol;
|
||||
const insert = beforeDefinition + gap + reference + ": " + definition + eol;
|
||||
const start = beforeDefinition.length + gap.length + reference.length + 2;
|
||||
return replacement({ from: selection.from, to: source.length }, insert, start, start + definition.length);
|
||||
}
|
||||
const fence = "`".repeat(Math.max(2, ...[...text.matchAll(/`+/g)].map(match => match[0].length)) + 1);
|
||||
const content = text || (kind === "code" ? "Code" : kind === "math" ? "equation" : "Callout text");
|
||||
let block = kind === "table" ? "| Column 1 | Column 2 |\n| --- | --- |\n| | |"
|
||||
: kind === "rule" ? "---" : kind === "code" ? `${fence}\n${content}\n${fence}`
|
||||
: kind === "math" ? `$$\n${content}\n$$` : `> [!note]\n> ${content.replace(/\r?\n/g, "\n> ")}`;
|
||||
block = block.replace(/\r?\n/g, eol);
|
||||
// Structural inserts should not delete selected prose.
|
||||
const at = kind === "table" || kind === "rule" ? { from: selection.to, to: selection.to } : selection;
|
||||
const before = source.slice(0, at.from), after = source.slice(at.to);
|
||||
const leading = !before || before.endsWith(eol + eol) ? "" : before.endsWith(eol) ? eol : eol + eol;
|
||||
const trailing = after.startsWith(eol + eol) ? "" : after.startsWith(eol) ? eol : eol + eol;
|
||||
const start = kind === "table" ? block.indexOf("Column 1") : kind === "rule" ? block.length : block.indexOf(eol) + eol.length + (kind === "callout" ? 2 : 0);
|
||||
const length = kind === "table" ? 8 : kind === "rule" ? 0 : content.length;
|
||||
return replacement(at, leading + block + trailing, leading.length + start, leading.length + start + length);
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { countColumn, EditorState, type ChangeSpec, type Line, type Text, type TransactionSpec } from "@codemirror/state";
|
||||
import { ensureSyntaxTree, getIndentUnit, language, syntaxTree } from "@codemirror/language";
|
||||
import type { Command } from "@codemirror/view";
|
||||
|
||||
type Tree = ReturnType<typeof syntaxTree>;
|
||||
type Node = ReturnType<Tree["resolveInner"]>;
|
||||
|
||||
// A list inside a block quote keeps its quote markers at the line start.
|
||||
const QUOTE = /^(?:[ \t]{0,3}>[ \t]?)*/;
|
||||
const ORDERED = /^(\d{1,9})([.)])$/;
|
||||
|
||||
const parsed = (state: EditorState) => ensureSyntaxTree(state, state.doc.length, 200) ?? syntaxTree(state);
|
||||
const quoteLength = (text: string) => QUOTE.exec(text)![0].length;
|
||||
const markOf = (item: Node | null) => item?.name === "ListItem" ? item.getChild("ListMark") : null;
|
||||
const isList = (node: Node | null) => node?.name === "BulletList" || node?.name === "OrderedList";
|
||||
|
||||
function markColumn(state: EditorState, mark: Node) {
|
||||
const line = state.doc.lineAt(mark.from);
|
||||
return countColumn(line.text.slice(quoteLength(line.text), mark.from - line.from), state.tabSize);
|
||||
}
|
||||
|
||||
function contentColumn(state: EditorState, mark: Node) {
|
||||
const line = state.doc.lineAt(mark.from);
|
||||
const rest = line.text.slice(mark.to - line.from);
|
||||
const spaces = /^ */.exec(rest)![0].length;
|
||||
return markColumn(state, mark) + mark.to - mark.from + (spaces === 0 || spaces > 4 || spaces === rest.length ? 1 : spaces);
|
||||
}
|
||||
|
||||
/** The number of leading characters that cover `columns` columns of indentation. */
|
||||
function indentLength(text: string, columns: number, tabSize: number) {
|
||||
let length = 0;
|
||||
for (let column = 0; length < text.length && column < columns && /[ \t]/.test(text[length]); length++) {
|
||||
column += text[length] === "\t" ? tabSize - column % tabSize : 1;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
function itemOnLine(tree: Tree, line: Line) {
|
||||
const start = line.from + /^(?:[ \t]{0,3}>[ \t]?)*[ \t]*/.exec(line.text)![0].length;
|
||||
const node = tree.resolveInner(start, 1);
|
||||
return node.name === "ListMark" && node.from === start ? node.parent : null;
|
||||
}
|
||||
|
||||
/** The list item around a position. Code inside an item keeps its own indentation. */
|
||||
function itemAround(tree: Tree, position: number) {
|
||||
for (const side of [1, -1] as const) {
|
||||
for (let node: Node | null = tree.resolveInner(position, side); node; node = node.parent) {
|
||||
if (node.name === "FencedCode" || node.name === "CodeBlock") return null;
|
||||
if (node.name === "ListItem") return node;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function itemLines(state: EditorState, item: Node) {
|
||||
return { first: state.doc.lineAt(item.from).number, last: state.doc.lineAt(Math.max(item.from, item.to - 1)).number };
|
||||
}
|
||||
|
||||
/** The outermost list items that the selection touches. A nested item moves with its parent. */
|
||||
function selectedItems(state: EditorState, tree: Tree) {
|
||||
const items = new Map<number, Node>();
|
||||
for (const range of state.selection.ranges) {
|
||||
const first = state.doc.lineAt(range.from);
|
||||
let last = state.doc.lineAt(range.to);
|
||||
if (!range.empty && range.to === last.from && last.number > first.number) last = state.doc.line(last.number - 1);
|
||||
for (let number = first.number; number <= last.number; number++) {
|
||||
const item = itemOnLine(tree, state.doc.line(number)) ?? (number === first.number ? itemAround(tree, range.from) : null);
|
||||
if (item) items.set(item.from, item);
|
||||
}
|
||||
}
|
||||
const nested = (item: Node) => {
|
||||
for (let node = item.parent; node; node = node.parent) if (node.name === "ListItem" && items.has(node.from)) return true;
|
||||
return false;
|
||||
};
|
||||
return [...items.values()].filter(item => !nested(item)).sort((a, b) => a.from - b.from);
|
||||
}
|
||||
|
||||
/** Change a marker. Keep its last character when it stays, so a caret after the marker does not move. */
|
||||
function replaceMark(state: EditorState, mark: Node, prefix: string, marker: string): ChangeSpec {
|
||||
const text = state.sliceDoc(mark.from, mark.to);
|
||||
const keep = marker.at(-1) === text.at(-1) ? 1 : 0;
|
||||
return { from: mark.from, to: mark.to - keep, insert: prefix + marker.slice(0, marker.length - keep) };
|
||||
}
|
||||
|
||||
/** Number each item of the ordered lists in a range from the first item of its list. */
|
||||
function renumber(tree: Tree, doc: Text, from: number, to: number) {
|
||||
const changes: ChangeSpec[] = [];
|
||||
tree.iterate({ from, to, enter(node) {
|
||||
if (node.name !== "OrderedList") return;
|
||||
let next: number | undefined;
|
||||
for (let item = node.node.firstChild; item; item = item.nextSibling) {
|
||||
const mark = markOf(item), parts = mark && ORDERED.exec(doc.sliceString(mark.from, mark.to));
|
||||
if (!mark || !parts) continue;
|
||||
next ??= Number(parts[1]);
|
||||
if (Number(parts[1]) !== next) changes.push({ from: mark.from, to: mark.to - 1, insert: String(next) });
|
||||
next++;
|
||||
}
|
||||
} });
|
||||
return changes;
|
||||
}
|
||||
|
||||
function finish(state: EditorState, changes: ChangeSpec[], from: number, to: number): TransactionSpec[] {
|
||||
if (!changes.length) return [];
|
||||
const moved = state.changes(changes);
|
||||
const doc = moved.apply(state.doc);
|
||||
const parser = state.facet(language)?.parser;
|
||||
const numbers = parser ? renumber(parser.parse(doc.toString()), doc, moved.mapPos(from, -1), moved.mapPos(to, 1)) : [];
|
||||
return [{ changes: moved, userEvent: "input.indent", scrollIntoView: true }, { changes: numbers, sequential: true }];
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the selected list items one level deeper, below the previous item.
|
||||
* The moved item starts a new list as `1.`, or joins the nested list of the previous item.
|
||||
* Returns null outside a list, and an empty array when no item can move.
|
||||
*/
|
||||
export function indentListItems(state: EditorState): TransactionSpec[] | null {
|
||||
const tree = parsed(state), items = selectedItems(state, tree);
|
||||
if (!items.length) return null;
|
||||
const changes: ChangeSpec[] = [];
|
||||
let from = state.doc.length, to = 0;
|
||||
for (const item of items) {
|
||||
const previous = item.prevSibling, mark = markOf(item), previousMark = markOf(previous), list = item.parent;
|
||||
if (!previous || !mark || !previousMark || !list) continue;
|
||||
const column = markColumn(state, mark);
|
||||
const nested = isList(previous.lastChild) ? previous.lastChild : null;
|
||||
const nestedMark = markOf(nested?.firstChild ?? null);
|
||||
let pad = nestedMark ? markColumn(state, nestedMark) - column : 0;
|
||||
if (pad <= 0) pad = Math.max(getIndentUnit(state), contentColumn(state, previousMark) - markColumn(state, previousMark));
|
||||
const style = nested?.name === list.name && nestedMark ? state.sliceDoc(nestedMark.from, nestedMark.to) : state.sliceDoc(mark.from, mark.to);
|
||||
changes.push(replaceMark(state, mark, " ".repeat(pad), list.name === "OrderedList" ? `1${style.at(-1)}` : style));
|
||||
const lines = itemLines(state, item);
|
||||
for (let number = lines.first + 1; number <= lines.last; number++) {
|
||||
const line = state.doc.line(number), start = quoteLength(line.text);
|
||||
if (line.text.slice(start).trim()) changes.push({ from: line.from + start, insert: " ".repeat(pad) });
|
||||
}
|
||||
from = Math.min(from, list.from); to = Math.max(to, list.to);
|
||||
}
|
||||
return finish(state, changes, from, to);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the selected nested list items one level up, after their parent item.
|
||||
* The moved item takes the marker style of the outer list. Later items of its old list become its children.
|
||||
* Returns null outside a list, and an empty array when no item can move.
|
||||
*/
|
||||
export function outdentListItems(state: EditorState): TransactionSpec[] | null {
|
||||
const tree = parsed(state), items = selectedItems(state, tree);
|
||||
if (!items.length) return null;
|
||||
const selected = new Set(items.map(item => item.from));
|
||||
const changes: ChangeSpec[] = [];
|
||||
let from = state.doc.length, to = 0;
|
||||
for (const item of items) {
|
||||
const mark = markOf(item), list = item.parent, parent = list?.parent ?? null, parentMark = markOf(parent), outer = parent?.parent;
|
||||
if (!mark || !list || !parent || !parentMark || !outer) continue;
|
||||
const remove = markColumn(state, mark) - markColumn(state, parentMark);
|
||||
if (remove <= 0) continue;
|
||||
const lines = itemLines(state, item);
|
||||
for (let number = lines.first; number <= lines.last; number++) {
|
||||
const line = state.doc.line(number), start = line.from + quoteLength(line.text);
|
||||
const length = indentLength(state.sliceDoc(start, number === lines.first ? mark.from : line.to), remove, state.tabSize);
|
||||
if (length) changes.push({ from: start, to: start + length });
|
||||
}
|
||||
const text = state.sliceDoc(mark.from, mark.to), parentText = state.sliceDoc(parentMark.from, parentMark.to);
|
||||
const ordered = outer.name === "OrderedList";
|
||||
if (outer.name !== list.name || (ordered ? text.at(-1) !== parentText.at(-1) : text !== parentText)) {
|
||||
changes.push(replaceMark(state, mark, "", ordered ? `${Number(parentText.slice(0, -1)) + 1}${parentText.at(-1)}` : parentText));
|
||||
}
|
||||
// The next item of the old list becomes the first child of the moved item.
|
||||
const next = item.nextSibling, nextMark = markOf(next);
|
||||
if (list.name === "OrderedList" && next && nextMark && !selected.has(next.from)) {
|
||||
changes.push({ from: nextMark.from, to: nextMark.to - 1, insert: "1" });
|
||||
}
|
||||
from = Math.min(from, outer.from); to = Math.max(to, outer.to);
|
||||
}
|
||||
return finish(state, changes, from, to);
|
||||
}
|
||||
|
||||
function listCommand(move: (state: EditorState) => TransactionSpec[] | null): Command {
|
||||
return view => {
|
||||
const specs = move(view.state);
|
||||
if (!specs) return false;
|
||||
if (specs.length) view.dispatch(...specs);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
/** Tab in a list item makes it a nested item. */
|
||||
export const indentListItem = listCommand(indentListItems);
|
||||
/** Shift+Tab in a nested list item moves it one level up. */
|
||||
export const outdentListItem = listCommand(outdentListItems);
|
||||
|
||||
function alphabetic(number: number) {
|
||||
let label = "";
|
||||
for (let rest = number; rest > 0; rest = Math.floor((rest - 1) / 26)) label = String.fromCharCode(97 + (rest - 1) % 26) + label;
|
||||
return label;
|
||||
}
|
||||
|
||||
function roman(number: number) {
|
||||
const numerals: [number, string][] = [[1000, "m"], [900, "cm"], [500, "d"], [400, "cd"], [100, "c"], [90, "xc"], [50, "l"], [40, "xl"], [10, "x"], [9, "ix"], [5, "v"], [4, "iv"], [1, "i"]];
|
||||
let label = "", rest = number;
|
||||
for (const [value, numeral] of numerals) for (; rest >= value; rest -= value) label += numeral;
|
||||
return label;
|
||||
}
|
||||
|
||||
/**
|
||||
* The label of an ordered list item. Level 1 uses decimal numbers, level 2 letters, and level 3 Roman numerals.
|
||||
* Deeper levels repeat the sequence. Numbers that a style cannot show stay decimal, as in CSS.
|
||||
*/
|
||||
export function orderedLabel(level: number, number: number) {
|
||||
const style = (level - 1) % 3;
|
||||
if (style === 1 && number > 0) return alphabetic(number);
|
||||
if (style === 2 && number > 0 && number < 4000) return roman(number);
|
||||
return String(number);
|
||||
}
|
||||
|
||||
function orderedLevel(node: Node | null) {
|
||||
let level = 0;
|
||||
for (; node; node = node.parent) if (node.name === "OrderedList") level++;
|
||||
return level;
|
||||
}
|
||||
|
||||
export type ListLabel = { from: number; to: number; label: string };
|
||||
|
||||
/**
|
||||
* Labels for the markers of nested ordered lists. The Markdown source keeps its numbers.
|
||||
* An item gets the start number of its list plus its position, as a Markdown renderer counts.
|
||||
*/
|
||||
export function listLabels(state: EditorState): ListLabel[] {
|
||||
const labels: ListLabel[] = [];
|
||||
syntaxTree(state).iterate({ enter(node) {
|
||||
if (node.name === "OrderedList") {
|
||||
const level = orderedLevel(node.node);
|
||||
let start: number | undefined, index = 0;
|
||||
for (let item = node.node.firstChild; item; item = item.nextSibling) {
|
||||
const mark = markOf(item), parts = mark && ORDERED.exec(state.sliceDoc(mark.from, mark.to));
|
||||
if (!mark || !parts) continue;
|
||||
start ??= Number(parts[1]);
|
||||
if (level > 1) labels.push({ from: mark.from, to: mark.to, label: orderedLabel(level, start + index) + parts[2] });
|
||||
index++;
|
||||
}
|
||||
}
|
||||
// An empty item cannot start a list inside a paragraph, so the parser reads it as text.
|
||||
// Label it as the nested item that it becomes when the user types its text.
|
||||
const item = node.node.parent;
|
||||
if (node.name !== "Paragraph" || item?.name !== "ListItem") return;
|
||||
const itemMark = markOf(item)!, level = orderedLevel(item) + 1;
|
||||
if (level < 2) return;
|
||||
const first = state.doc.lineAt(node.from).number, last = state.doc.lineAt(node.to).number;
|
||||
for (let number = first + 1; number <= last; number++) {
|
||||
const line = state.doc.line(number);
|
||||
const match = /^(\s*)(\d{1,9})([.)])\s*$/.exec(line.text.slice(quoteLength(line.text)));
|
||||
if (!match) continue;
|
||||
const from = line.from + quoteLength(line.text) + match[1].length;
|
||||
if (countColumn(line.text.slice(quoteLength(line.text), from - line.from), state.tabSize) < contentColumn(state, itemMark)) continue;
|
||||
labels.push({ from, to: from + match[2].length + 1, label: orderedLabel(level, Number(match[2])) + match[3] });
|
||||
}
|
||||
} });
|
||||
return labels;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { tr } from "../i18n/index.ts";
|
||||
import type { ActionMenuItem } from "../ui/actionMenu";
|
||||
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
|
||||
import { clipboardItems, historyItems, searchItem } from "../ui/menuItems";
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { wordAt } from "./spellingWord";
|
||||
import { pickLinkDocument } from "./documentPicker";
|
||||
import { externalLinkText, workspaceLinkText } from "./linkCommands";
|
||||
import { documentLinkAt } from "./documentLinks";
|
||||
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
|
||||
import { htmlToMarkdown } from "../workspace/htmlToMarkdown";
|
||||
import { cellFormats, type TableContextActions } from "./tableCellActions";
|
||||
import { FORMAT_KEYS, LINK_KEY } from "./formatKeys";
|
||||
import { keys } from "../ui/shortcuts";
|
||||
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;
|
||||
select: (from: number, to: number) => void;
|
||||
undo?: () => void;
|
||||
redo?: () => void;
|
||||
canUndo?: () => boolean;
|
||||
canRedo?: () => boolean;
|
||||
};
|
||||
|
||||
// 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, linkActions: () => DocumentLinkActions = () => ({})) {
|
||||
let menu: MenuHandle | undefined, destroyed = false;
|
||||
const pending = new AbortController();
|
||||
const restore = () => { if (!destroyed) editor.focus(); };
|
||||
function close(focus = true) {
|
||||
menu?.close(); menu = undefined;
|
||||
if (focus) restore();
|
||||
}
|
||||
const show = (x: number, y: number, items: ActionMenuItem[]) => menu = showActionMenu({ x, y, items, label: tr("Markdown text actions") }, undefined, restore);
|
||||
|
||||
function open(x: number, y: number, spellingOffset?: number, linkOffset?: number) {
|
||||
close(false);
|
||||
const snapshot = editor.snapshot(), { source, selection } = snapshot;
|
||||
const text = source.slice(selection.from, selection.to);
|
||||
const selectedLink = documentLinkAt(source, linkOffset ?? selection.from);
|
||||
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) {
|
||||
if (external) { apply(externalLinkText(source, selection)); return; }
|
||||
void request(async () => {
|
||||
const target = await pickLinkDocument(pending.signal);
|
||||
if (!target || !valid()) return;
|
||||
apply(workspaceLinkText(source, selection, target));
|
||||
});
|
||||
}
|
||||
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(tr("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[] = [
|
||||
...(selectedLink ? [...linkMenuItems(selectedLink, linkActions(), () => close(false), report, () => {
|
||||
if (!valid()) return;
|
||||
editor.select(selectedLink.targetFrom, selectedLink.targetTo); editor.focus();
|
||||
}), { separator: true as const }] : []),
|
||||
...(editor.undo ? historyItems({ canUndo: !!editor.canUndo?.(), canRedo: !!editor.canRedo?.(), undo: () => editor.undo?.(), redo: () => editor.redo?.() }) : []),
|
||||
{ label: tr("Add link"), icon: "link", run: () => link(false) },
|
||||
{ label: tr("Add external link"), icon: "external", shortcut: keys(LINK_KEY), run: () => link(true) },
|
||||
{ separator: true },
|
||||
searchItem(text, actions.onSearch),
|
||||
{ label: tr("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: tr("Format"), icon: "format", children: cellFormats.flatMap(([label, kind]) => [
|
||||
...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []),
|
||||
{ label: tr(label), icon: kind, ...(FORMAT_KEYS[kind] ? { shortcut: keys(FORMAT_KEYS[kind]) } : {}), disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) },
|
||||
]) },
|
||||
{ label: tr("Paragraph"), icon: "paragraph", children: [
|
||||
paragraph(tr("Bullet list"), "bullet", "bullet"), paragraph(tr("Numbered list"), "number", "number"), paragraph(tr("Task list"), "task", "task"),
|
||||
{ separator: true },
|
||||
...([1, 2, 3, 4, 5, 6] as const).map(level => paragraph(tr("Heading {level}", { level }), level, "heading")),
|
||||
paragraph(tr("Body"), "body", "paragraph"), { separator: true }, paragraph(tr("Quote"), "quote", "quote"),
|
||||
] },
|
||||
{ label: tr("Insert"), icon: "insert", children: [
|
||||
insert(tr("Footnote"), "footnote", "footnote"), insert(tr("Table"), "table", "table"), insert(tr("Callout"), "callout", "quote"), insert(tr("Horizontal rule"), "rule", "rule"),
|
||||
{ separator: true }, insert(tr("Code block"), "code", "code"), insert(tr("Math block"), "math", "math"),
|
||||
] },
|
||||
{ separator: true },
|
||||
...clipboardItems({
|
||||
selected: !!text, cut: () => clipboard("cut"), copy: () => clipboard("copy"), paste: () => clipboard("paste"),
|
||||
pastePlain: () => clipboard("plain"), selectAll: () => editor.selectAll(),
|
||||
}),
|
||||
];
|
||||
const opened = show(x, y, items);
|
||||
const word = spellingOffset === undefined ? null : wordAt(source, spellingOffset);
|
||||
if (word && isTauri()) {
|
||||
const languages = [...new Set([document.documentElement.lang, ...navigator.languages].filter(Boolean))];
|
||||
void invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages }).then(result => {
|
||||
if (!result.misspelled || menu !== opened || !opened.open || !valid()) return;
|
||||
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => apply(replacement(word, value)) }));
|
||||
if (!suggestions.length) suggestions.push({ label: tr("No spelling suggestions"), disabled: true });
|
||||
suggestions.push({ label: tr("Add to dictionary"), icon: "book", run: () => {
|
||||
close();
|
||||
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report(tr("Could not add the word to the dictionary.")));
|
||||
} });
|
||||
const focusedLabel = opened.element.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
|
||||
opened.close();
|
||||
const next = show(x, y, [...suggestions, { separator: true }, ...items]);
|
||||
if (focusedLabel) [...next.element.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
|
||||
}).catch(() => { /* Editing actions remain available without spelling suggestions. */ });
|
||||
}
|
||||
}
|
||||
return { open, close, destroy() { destroyed = true; pending.abort(); close(false); } };
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
export type TableCell = { text: string; from: number; to: number };
|
||||
export type TableRow = { from: number; to: number; indent: string; cells: TableCell[] };
|
||||
export type MarkdownTable = { rows: TableRow[]; columns: number; eol: string; end: number };
|
||||
|
||||
export function hasTableDelimiter(line: string): boolean {
|
||||
return /(^|[^\\])(?:\\\\)*\|/.test(line);
|
||||
}
|
||||
|
||||
function row(text: string, from: number): TableRow {
|
||||
const pipes: number[] = [];
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
if (text[index] !== "|") continue;
|
||||
let slashes = 0;
|
||||
for (let before = index - 1; before >= 0 && text[before] === "\\"; before--) slashes++;
|
||||
if (slashes % 2 === 0) pipes.push(index);
|
||||
}
|
||||
const start = text.search(/\S/);
|
||||
const end = text.trimEnd().length;
|
||||
const left = pipes[0] === start ? pipes.shift()! + 1 : 0;
|
||||
const right = pipes.at(-1) === end - 1 ? pipes.pop()! : text.length;
|
||||
const boundaries = [left - 1, ...pipes, right];
|
||||
const cells = boundaries.slice(0, -1).map((boundary, index) => {
|
||||
const rawFrom = boundary + 1, rawTo = boundaries[index + 1];
|
||||
const raw = text.slice(rawFrom, rawTo);
|
||||
const leading = raw.length - raw.trimStart().length;
|
||||
const cellFrom = from + rawFrom + leading;
|
||||
return { text: raw.trim(), from: cellFrom, to: Math.max(cellFrom, from + rawTo - (raw.length - raw.trimEnd().length)) };
|
||||
});
|
||||
return { from, to: from + text.length, indent: /^\s*/.exec(text)![0], cells };
|
||||
}
|
||||
|
||||
export function parseMarkdownTable(source: string): MarkdownTable | null {
|
||||
const rows: TableRow[] = [];
|
||||
let offset = 0;
|
||||
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
||||
for (const line of source.split(eol)) {
|
||||
if (!line.trim() || (rows.length >= 2 && !hasTableDelimiter(line))) break;
|
||||
rows.push(row(line, offset));
|
||||
offset += line.length + eol.length;
|
||||
}
|
||||
if (rows.length < 2 || !source.slice(rows[0].from, rows[0].to).includes("|")) return null;
|
||||
const columns = rows[0].cells.length;
|
||||
if (rows[1].cells.length !== columns || !rows[1].cells.every(cell => /^:?-+:?$/.test(cell.text))) return null;
|
||||
return { rows, columns, eol, end: rows.at(-1)!.to };
|
||||
}
|
||||
|
||||
export function appendTableColumn(source: string): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table) return source;
|
||||
const body = table.rows.map((row, index) => {
|
||||
const cells = row.cells.map(cell => cell.text);
|
||||
while (cells.length < table.columns) cells.push("");
|
||||
cells.splice(table.columns, 0, index === 1 ? "---" : "");
|
||||
return `${row.indent}| ${cells.join(" | ")} |`;
|
||||
}).join(table.eol);
|
||||
return body + source.slice(table.end);
|
||||
}
|
||||
|
||||
export function appendTableRow(source: string): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table) return source;
|
||||
const row = `${table.rows[0].indent}| ${Array.from({ length: table.columns }, () => "").join(" | ")} |`;
|
||||
return source.slice(0, table.end) + table.eol + row + source.slice(table.end);
|
||||
}
|
||||
|
||||
// Change only the selected cell: padding, alignment, and every other row stay intact.
|
||||
export function replaceTableCell(source: string, rowIndex: number, column: number, text: string): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table || rowIndex === 1 || column < 0 || column >= table.columns || /[\r\n]/.test(text)) return source;
|
||||
const row = table.rows[rowIndex];
|
||||
if (!row) return source;
|
||||
const cell = row.cells[column];
|
||||
if (cell) return source.slice(0, cell.from) + text + source.slice(cell.to);
|
||||
const cells = row.cells.map(cell => cell.text);
|
||||
while (cells.length <= column) cells.push("");
|
||||
cells[column] = text;
|
||||
return source.slice(0, row.from) + `${row.indent}| ${cells.join(" | ")} |` + source.slice(row.to);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { markdown } from "@codemirror/lang-markdown";
|
||||
import { inlineMathEnd } from "../workspace/inlineMath.ts";
|
||||
|
||||
export const noteFormats: NonNullable<NonNullable<Parameters<typeof markdown>[0]>["extensions"]> = {
|
||||
defineNodes: ["NoteHighlight", "NoteMath", "NoteComment", "NoteFormatMark"],
|
||||
parseInline: [{ name: "NoteFormats", before: "Emphasis", parse(context, next, position) {
|
||||
const marker = next === 61 ? "==" : next === 37 ? "%%" : next === 36 ? "$" : "";
|
||||
if (!marker || context.slice(position, position + marker.length) !== marker) return -1;
|
||||
let end = position + marker.length;
|
||||
if (marker === "$") {
|
||||
if (context.char(position - 1) === 36) return -1;
|
||||
const offset = inlineMathEnd(context.slice(position, context.end));
|
||||
if (offset < 0) return -1;
|
||||
end = position + offset;
|
||||
} else {
|
||||
for (; end < context.end; end++) {
|
||||
if (context.char(end) === 92) { end++; continue; }
|
||||
if (context.slice(end, end + marker.length) === marker) break;
|
||||
}
|
||||
if (end >= context.end || end === position + marker.length) return -1;
|
||||
}
|
||||
const kind = marker === "==" ? "NoteHighlight" : marker === "$" ? "NoteMath" : "NoteComment";
|
||||
const children = marker === "==" ? context.parser.parseInline(context.slice(position + marker.length, end), position + marker.length) : [];
|
||||
return context.addElement(context.elt(kind, position, end + marker.length, [
|
||||
context.elt("NoteFormatMark", position, position + marker.length), ...children,
|
||||
context.elt("NoteFormatMark", end, end + marker.length),
|
||||
]));
|
||||
} }],
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
/* The note title of Write, from noteTitle.ts. */
|
||||
.note-title-button { position: relative; display: inline-flex; align-items: center; gap: 12px; max-width: 100%; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; text-align: left; overflow-wrap: anywhere; cursor: text; }
|
||||
.note-title-button .action-icon { opacity: .45; }
|
||||
.note-title-button:hover .action-icon, .note-title-button:focus-visible .action-icon { opacity: 1; color: var(--rs-accent); }
|
||||
.note-title-button:focus-visible { outline: 1px solid var(--rs-focus); outline-offset: 4px; border-radius: 3px; }
|
||||
.note-title-input { box-sizing: border-box; width: 100%; min-width: 0; padding: 0; border: 0; border-radius: 2px; outline: 1px solid var(--rs-accent); outline-offset: 4px; background: transparent; color: inherit; font: inherit; }
|
||||
.note-title-input[aria-invalid] { outline-color: var(--rs-error); }
|
||||
.note-title-error { margin: -.8em 0 1em; color: var(--rs-error); font: 13px/1.5 var(--rs-font-ui); }
|
||||
.note-title-button[hidden], .note-title-input[hidden], .note-title-error[hidden] { display: none; }
|
||||
@@ -0,0 +1,97 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
|
||||
type RenameTitle = (title: string) => Promise<void>;
|
||||
|
||||
class NoteTitle extends WidgetType {
|
||||
constructor(readonly title: string, readonly rename?: RenameTitle) { super(); }
|
||||
eq(other: NoteTitle) { return this.title === other.title && this.rename === other.rename; }
|
||||
toDOM(view: EditorView) {
|
||||
// Contain heading margins so CodeMirror measures the full block height.
|
||||
const block = document.createElement("div");
|
||||
block.style.display = "flow-root";
|
||||
const heading = document.createElement("h1");
|
||||
heading.className = "document-title";
|
||||
heading.textContent = this.title;
|
||||
block.append(heading);
|
||||
if (!this.rename) return block;
|
||||
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "note-title-button";
|
||||
button.setAttribute("aria-label", tr("Rename note"));
|
||||
button.append(document.createTextNode(this.title), actionIcon("rename"));
|
||||
button.dataset.editorTooltip = tr("Rename note");
|
||||
heading.replaceChildren(button);
|
||||
|
||||
const input = document.createElement("input");
|
||||
input.className = "note-title-input";
|
||||
input.setAttribute("aria-label", tr("Note filename"));
|
||||
input.autocomplete = "off";
|
||||
input.spellcheck = false;
|
||||
input.hidden = true;
|
||||
heading.append(input);
|
||||
const message = document.createElement("p");
|
||||
message.className = "note-title-error";
|
||||
message.setAttribute("role", "alert");
|
||||
message.hidden = true;
|
||||
block.append(message);
|
||||
let editing = false, pending = false;
|
||||
const finish = () => {
|
||||
editing = false;
|
||||
input.hidden = true;
|
||||
button.hidden = false;
|
||||
message.hidden = true;
|
||||
input.removeAttribute("aria-invalid");
|
||||
view.requestMeasure();
|
||||
};
|
||||
const commit = async (focusEditor: boolean) => {
|
||||
if (!editing || pending) return;
|
||||
pending = true;
|
||||
input.readOnly = true;
|
||||
input.setAttribute("aria-busy", "true");
|
||||
try {
|
||||
await this.rename!(input.value);
|
||||
finish();
|
||||
if (focusEditor && view.dom.isConnected && (document.activeElement === input || document.activeElement === document.body)) view.focus();
|
||||
} catch (reason) {
|
||||
if (!block.isConnected) return;
|
||||
input.setAttribute("aria-invalid", "true");
|
||||
message.textContent = reason instanceof Error ? reason.message : String(reason);
|
||||
message.hidden = false;
|
||||
view.requestMeasure();
|
||||
} finally {
|
||||
pending = false;
|
||||
input.readOnly = false;
|
||||
input.removeAttribute("aria-busy");
|
||||
}
|
||||
};
|
||||
button.onclick = () => {
|
||||
editing = true;
|
||||
input.value = this.title;
|
||||
button.hidden = true;
|
||||
input.hidden = false;
|
||||
input.focus();
|
||||
input.select();
|
||||
view.requestMeasure();
|
||||
};
|
||||
input.onblur = () => { void commit(false); };
|
||||
input.onkeydown = event => {
|
||||
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;
|
||||
}
|
||||
ignoreEvent() { return true; }
|
||||
}
|
||||
|
||||
// Filename editing stays outside the Markdown and its undo history.
|
||||
export function noteTitle(title: string, rename?: RenameTitle) {
|
||||
return EditorView.decorations.of(Decoration.set([
|
||||
Decoration.widget({ widget: new NoteTitle(title, rename), block: true, side: -1 }).range(0),
|
||||
]));
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { keys } from "../ui/shortcuts";
|
||||
import type { ActionMenuItem } from "../ui/actionMenu";
|
||||
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
|
||||
import { clipboardItems, searchItem } from "../ui/menuItems";
|
||||
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
|
||||
|
||||
/** Preserve the DOM range while the shared menu owns keyboard focus. */
|
||||
export function readingMenu(host: HTMLElement, actions: DocumentLinkActions, search: ((text: string) => void) | undefined, report: (message: string) => void) {
|
||||
let menu: MenuHandle | undefined;
|
||||
let previousFocus: HTMLElement | null = null;
|
||||
let range: Range | undefined;
|
||||
function restore() {
|
||||
(previousFocus?.isConnected ? previousFocus : host).focus({ preventScroll: true });
|
||||
if (range?.startContainer.isConnected && range.endContainer.isConnected) {
|
||||
const selection = window.getSelection(); selection?.removeAllRanges(); selection?.addRange(range);
|
||||
}
|
||||
}
|
||||
function open(event: MouseEvent | KeyboardEvent) {
|
||||
if (event.defaultPrevented || event.target instanceof Element && event.target.closest("input, textarea, [contenteditable=true], .rs-image-frame")) return;
|
||||
const keyboard = event instanceof KeyboardEvent;
|
||||
if (keyboard && event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
|
||||
const selection = window.getSelection();
|
||||
const selected = selection?.rangeCount ? selection.getRangeAt(0) : undefined;
|
||||
range = selected && host.contains(selected.startContainer) && host.contains(selected.endContainer) ? selected.cloneRange() : undefined;
|
||||
const text = range?.toString() ?? "";
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
const anchor = target?.closest("a") ?? (keyboard && selection?.anchorNode ? (selection.anchorNode.parentElement?.closest("a") ?? null) : null);
|
||||
if (!text && !anchor) return;
|
||||
event.preventDefault(); event.stopPropagation(); menu?.close();
|
||||
previousFocus = document.activeElement instanceof HTMLElement && host.contains(document.activeElement) ? document.activeElement : host;
|
||||
const items: ActionMenuItem[] = [];
|
||||
if (text) items.push(
|
||||
...clipboardItems({ selected: true, copy: () => void navigator.clipboard.writeText(text).catch(() => report(tr("Clipboard unavailable. Use {shortcut} to copy.", { shortcut: keys("Mod+C") }))) }),
|
||||
searchItem(text, search),
|
||||
);
|
||||
if (anchor) {
|
||||
if (items.length) items.push({ separator: true });
|
||||
if (anchor.hasAttribute("data-footnote-link")) items.push({ label: tr("Open link"), icon: "link", run: () => (anchor as HTMLElement).click() });
|
||||
else items.push(...linkMenuItems({ kind: anchor.getAttribute("data-kind") === "wiki" ? "wiki" : "md", target: anchor.getAttribute("href") ?? "" }, actions, () => menu?.close(), report));
|
||||
}
|
||||
const rect = keyboard ? (range?.getBoundingClientRect() ?? anchor?.getBoundingClientRect() ?? host.getBoundingClientRect()) : null;
|
||||
menu = showActionMenu({ x: rect?.left ?? (event as MouseEvent).clientX, y: rect?.bottom ?? (event as MouseEvent).clientY, items, label: tr("Reading actions") }, undefined, restore);
|
||||
}
|
||||
host.addEventListener("contextmenu", open);
|
||||
host.addEventListener("keydown", open);
|
||||
return () => {
|
||||
menu?.close();
|
||||
host.removeEventListener("contextmenu", open); host.removeEventListener("keydown", open);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import { documentMatches, type FindTarget } from "./findTarget";
|
||||
|
||||
/** Keys that do not change the text of the find field. These keys keep the selected match. */
|
||||
const keepsMatch = /^(?:Enter|Escape|Tab|Shift|Control|Alt|Meta|CapsLock|ContextMenu|F\d+)$/;
|
||||
|
||||
/** 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;
|
||||
// The window selection also holds the caret of a focused find field. There it reads as collapsed and outside the text.
|
||||
function matchSelected() {
|
||||
const selection = window.getSelection();
|
||||
return !!selection && !selection.isCollapsed && root.contains(selection.anchorNode);
|
||||
}
|
||||
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; if (matchSelected()) window.getSelection()?.removeAllRanges(); },
|
||||
// A selected match takes the caret from the find field, and the browser then drops typed keys. Put the caret back first.
|
||||
// The field cannot report its old caret at this time, so the caret goes to the end of the text.
|
||||
keydown(event) {
|
||||
const field = event.target;
|
||||
const copy = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c";
|
||||
if (field instanceof HTMLInputElement && field.type === "text" && !copy && !keepsMatch.test(event.key) && matchSelected()) field.setSelectionRange(field.value.length, field.value.length);
|
||||
return false;
|
||||
},
|
||||
next, selectAll() {}, replace() {},
|
||||
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Readers retain editor selection when toolbar buttons take focus.
|
||||
const readers = new Map<string, () => string>();
|
||||
export function registerSelection(id: string, read: () => string): () => void {
|
||||
readers.set(id, read);
|
||||
return () => { if (readers.get(id) === read) readers.delete(id); };
|
||||
}
|
||||
export function selectedEditorText(id?: string): string {
|
||||
return id ? readers.get(id)?.() ?? "" : "";
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { countColumn, EditorSelection, EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView, highlightActiveLine, highlightActiveLineGutter, keymap, lineNumbers, type Command } from "@codemirror/view";
|
||||
import { bracketMatching, foldGutter, foldKeymap, getIndentUnit, HighlightStyle, indentOnInput, syntaxHighlighting } from "@codemirror/language";
|
||||
import { closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete";
|
||||
import { highlightSelectionMatches } from "@codemirror/search";
|
||||
import { indentMore } from "@codemirror/commands";
|
||||
import { tags } from "@lezer/highlight";
|
||||
import { chromeLayout } from "../workspace/chrome";
|
||||
import type { Chrome } from "../workspace/types";
|
||||
|
||||
const syntax = (role: string, fallback: string) => `var(--rs-syntax-${role}, ${fallback})`;
|
||||
|
||||
/** Syntax colors come from the theme tokens, so a theme change needs no editor update. */
|
||||
const sourceHighlight = HighlightStyle.define([
|
||||
{ tag: [tags.keyword, tags.modifier, tags.operatorKeyword, tags.controlKeyword, tags.definitionKeyword, tags.moduleKeyword, tags.tagName], color: syntax("keyword", "var(--rs-accent)") },
|
||||
{ tag: tags.heading, color: syntax("heading", "var(--rs-accent)"), fontWeight: "600" },
|
||||
{ tag: [tags.string, tags.special(tags.string), tags.regexp, tags.attributeValue, tags.url, tags.monospace], color: syntax("string", "var(--rs-ok)") },
|
||||
{ tag: [tags.number, tags.bool, tags.null, tags.atom, tags.unit], color: syntax("number", "var(--rs-special)") },
|
||||
{ tag: tags.comment, color: syntax("comment", "var(--rs-text-dim)") },
|
||||
{ tag: [tags.typeName, tags.className, tags.namespace], color: syntax("type", "var(--rs-accent-2)") },
|
||||
{ tag: [tags.function(tags.variableName), tags.function(tags.propertyName), tags.macroName], color: syntax("function", "var(--rs-accent-2)") },
|
||||
{ tag: [tags.propertyName, tags.attributeName], color: syntax("property", "var(--rs-accent-2)") },
|
||||
{ tag: [tags.standard(tags.variableName), tags.self, tags.special(tags.variableName)], color: syntax("constant", "var(--rs-text-dim)") },
|
||||
{ tag: tags.variableName, color: syntax("variable", "var(--rs-text)") },
|
||||
{ tag: [tags.punctuation, tags.operator, tags.meta, tags.processingInstruction], color: syntax("punctuation", "var(--rs-text-dim)") },
|
||||
{ tag: tags.emphasis, fontStyle: "italic" },
|
||||
{ tag: tags.strong, fontWeight: "600" },
|
||||
{ tag: tags.strikethrough, textDecoration: "line-through" },
|
||||
{ tag: tags.link, color: "var(--rs-link)", textDecoration: "underline" },
|
||||
{ tag: tags.invalid, color: "var(--rs-error)" },
|
||||
]);
|
||||
|
||||
/** Tab inserts spaces to the next indent stop at each caret. With a selection, it indents the lines. */
|
||||
export const insertIndent: Command = view => {
|
||||
const { state } = view;
|
||||
if (state.selection.ranges.some(range => !range.empty)) return indentMore(view);
|
||||
const unit = getIndentUnit(state);
|
||||
view.dispatch(state.changeByRange(range => {
|
||||
const line = state.doc.lineAt(range.head);
|
||||
const insert = " ".repeat(unit - countColumn(line.text.slice(0, range.head - line.from), state.tabSize) % unit);
|
||||
return { changes: { from: range.head, insert }, range: EditorSelection.cursor(range.head + insert.length) };
|
||||
}), { scrollIntoView: true, userEvent: "input.indent" });
|
||||
return true;
|
||||
};
|
||||
|
||||
/** Code editing support for Source: syntax colors, brackets, several carets, and matches of the selection. */
|
||||
export const sourceEditing: Extension = [
|
||||
syntaxHighlighting(sourceHighlight), bracketMatching(), closeBrackets(), indentOnInput(), highlightSelectionMatches(),
|
||||
EditorState.allowMultipleSelections.of(true),
|
||||
keymap.of(closeBracketsKeymap),
|
||||
];
|
||||
|
||||
export function sourceChrome(chrome: Chrome): Extension {
|
||||
const layout = chromeLayout(chrome);
|
||||
return [
|
||||
layout.wrap ? EditorView.lineWrapping : [],
|
||||
layout.gutters ? [lineNumbers(), foldGutter(), highlightActiveLineGutter(), keymap.of(foldKeymap)] : [],
|
||||
layout.activeLine ? highlightActiveLine() : [],
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { tr } from "../i18n/index.ts";
|
||||
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 {
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
if (target instanceof HTMLTextAreaElement || (target instanceof HTMLInputElement && ["text", "search"].includes(target.type))) {
|
||||
return target.spellcheck && !target.disabled && !target.readOnly;
|
||||
}
|
||||
const editable = target.closest<HTMLElement>('[contenteditable="true"][spellcheck="true"]');
|
||||
return !!editable && target.isContentEditable
|
||||
&& !target.closest('a, code, pre, button, [data-href], [spellcheck="false"], .writer-inline-code, .writer-code-source, .writer-code-line');
|
||||
}
|
||||
|
||||
export function useSpellingMenu(event: MouseEvent, selectionEmpty: boolean): boolean {
|
||||
return selectionEmpty && isSpellingTarget(event.target);
|
||||
}
|
||||
|
||||
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[]; fallback_spelling?: boolean };
|
||||
const icons: Record<string, ActionIcon> = {
|
||||
undo: "undo", redo: "redo",
|
||||
cut: "cut", copy: "copy", paste: "paste", pasteAndMatchStyle: "paste-text",
|
||||
selectAll: "select", addToDictionary: "book", spellCheck: "book", spellingAndGrammar: "book",
|
||||
};
|
||||
|
||||
function nativeLabel(label: string): string {
|
||||
// Windows uses ampersands for access keys and doubles literal ampersands.
|
||||
return label.replace(/&&|&/g, value => value === "&&" ? "&" : "");
|
||||
}
|
||||
|
||||
export function spellingItems(items: NativeSpellingItem[], select: (id: number) => void): ActionMenuItem[] {
|
||||
return items.map(item => item.kind === 3 ? { separator: true } : {
|
||||
label: nativeLabel(item.label), icon: icons[item.name], shortcut: item.shortcut || undefined,
|
||||
disabled: !item.enabled, checked: item.kind === 1 || item.kind === 2 ? item.checked : undefined,
|
||||
radio: item.kind === 2,
|
||||
children: item.kind === 4 ? spellingItems(item.children, select) : undefined,
|
||||
run: () => select(item.id),
|
||||
});
|
||||
}
|
||||
|
||||
/** Mount once per app window. Other platforms keep their native spelling menu. */
|
||||
export function mountSpellingMenu(): () => void {
|
||||
if (!isTauri()) return () => {};
|
||||
let disposed = false, unlisten: (() => void) | 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;
|
||||
const { request, root, target } = active;
|
||||
active = undefined;
|
||||
root.remove();
|
||||
if (restoreFocus && target.isConnected) target.focus({ preventScroll: true });
|
||||
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, word: spellingWord(target, event.clientX, event.clientY) };
|
||||
};
|
||||
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);
|
||||
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, word } = context;
|
||||
const requestRevision = ++revision;
|
||||
let items = spellingItems(payload.items, id => finish(id, true));
|
||||
const parent = target.closest<HTMLDialogElement>("dialog[open]") ?? document.body;
|
||||
const show = () => {
|
||||
const previous = active?.request === payload.request ? active.root : undefined;
|
||||
const focusedLabel = previous?.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
|
||||
previous?.remove();
|
||||
const root = actionMenu(x, y, items, () => finish(null, true), tr("Spelling actions"), parent);
|
||||
active = { request: payload.request, root, target };
|
||||
if (focusedLabel) [...root.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
|
||||
};
|
||||
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));
|
||||
show();
|
||||
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: tr("No spelling suggestions"), disabled: true });
|
||||
if (result.misspelled) suggestions.push({ label: tr("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: tr("Spelling suggestions unavailable"), disabled: true }, { separator: true }, ...items];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (disposed || requestRevision !== revision || (payload.fallback_spelling && active?.request !== payload.request) || !target.isConnected || (payload.fallback_spelling && word && !word.valid())) {
|
||||
void invoke("spelling_menu_select", { request: payload.request, command: null });
|
||||
return;
|
||||
}
|
||||
show();
|
||||
}).then(async stop => {
|
||||
if (disposed) { stop(); return; }
|
||||
unlisten = stop;
|
||||
await invoke("spelling_menu_install");
|
||||
if (disposed) await invoke("spelling_menu_uninstall");
|
||||
}).catch(error => console.warn("Native spelling menu remains active", error));
|
||||
return () => {
|
||||
disposed = true;
|
||||
finish(); unlisten?.();
|
||||
void invoke("spelling_menu_uninstall").catch(() => {});
|
||||
window.removeEventListener("contextmenu", remember);
|
||||
window.removeEventListener("pointerdown", outside);
|
||||
window.removeEventListener("resize", cancel);
|
||||
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);
|
||||
} };
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { message, tr } from '../i18n/index.ts';
|
||||
import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core";
|
||||
import { requestText } from "../workspace/dialogs.svelte";
|
||||
import { extractedCellMarkdown } from "./tableCellMarkdown";
|
||||
import type { ActionMenuItem } from "../ui/actionMenu";
|
||||
import { clipboardItems, searchItem } from "../ui/menuItems";
|
||||
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
|
||||
import { documentLinkAt } from "./documentLinks";
|
||||
|
||||
export type TableContextActions = {
|
||||
linkActions?: () => DocumentLinkActions;
|
||||
onSearch?: (text: string) => void;
|
||||
onExtract?: (markdown: string, label: string, valid: () => boolean) => Promise<string | null>;
|
||||
};
|
||||
|
||||
export const cellFormats = [
|
||||
[message("Bold"), "bold"], [message("Italic"), "italic"], [message("Strikethrough"), "strike"], [message("Highlight"), "highlight"],
|
||||
[message("Code"), "code"], [message("Math"), "math"], [message("Comment"), "comment"], [message("Clear formatting"), "clear"],
|
||||
] as const;
|
||||
|
||||
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void, editSource: (range: { from: number; to: number }) => void): ActionMenuItem[] {
|
||||
const selection = editor.state.selection, doc = editor.state.doc;
|
||||
const sourceEditing = editor.view.dom.parentElement?.classList.contains("is-source-editing");
|
||||
const text = doc.textBetween(selection.from, selection.to, "\n");
|
||||
const valid = () => !editor.isDestroyed && editor.state.doc === doc && editor.state.selection.eq(selection);
|
||||
function run(command: () => void) { if (!valid()) return; close(); transaction(() => { editor.view.focus(); command(); }); }
|
||||
async function request(command: () => Promise<void>) {
|
||||
pending(true); close();
|
||||
try { await command(); } catch (error) { report(error instanceof Error ? error.message : String(error)); }
|
||||
finally { pending(false); if (!editor.isDestroyed) editor.view.focus(); }
|
||||
}
|
||||
function link(external: boolean) {
|
||||
void request(async () => {
|
||||
const target = await requestText(external ? tr("External link URL") : tr("Link to note (name or workspace path)"), external ? "https://" : text);
|
||||
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("Invalid URL");
|
||||
} catch { report(tr("Enter a valid http, https, or mailto link.")); return; }
|
||||
}
|
||||
if (!external && /[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report(tr("Enter a note name or path without brackets or pipes.")); return; }
|
||||
run(() => {
|
||||
const attrs = { href: target, "data-kind": external ? "md" : "wiki" };
|
||||
if (selection.empty) editor.commands.insertContent({ type: "text", text: target, marks: [{ type: "link", attrs }] });
|
||||
else editor.commands.setMark("link", attrs);
|
||||
});
|
||||
});
|
||||
}
|
||||
const at = doc.resolve(selection.from);
|
||||
const mark = [...at.marks(), ...(at.nodeAfter?.marks || [])].find(mark => mark.type.name === "link");
|
||||
const linkRange = mark && getMarkRange(doc.resolve(selection.from), mark.type, mark.attrs);
|
||||
const sourceLink = sourceEditing ? documentLinkAt(doc.textContent, selection.from - 1)
|
||||
|| documentLinkAt(doc.textContent, selection.from - 2) : undefined;
|
||||
const selectedLink = sourceLink || (mark && linkRange ? { kind: mark.attrs["data-kind"] === "wiki" ? "wiki" as const : "md" as const, target: String(mark.attrs.href) } : undefined);
|
||||
function editLink() {
|
||||
if (!selectedLink) return;
|
||||
if (!valid()) return;
|
||||
close();
|
||||
if (sourceLink) {
|
||||
editor.commands.setTextSelection({ from: sourceLink.targetFrom + 1, to: sourceLink.targetTo + 1 });
|
||||
editor.view.focus();
|
||||
} else if (linkRange) editSource(linkRange);
|
||||
}
|
||||
async function clipboard(action: "cut" | "copy" | "paste" | "plain") {
|
||||
await request(async () => {
|
||||
try {
|
||||
if (action === "copy" || action === "cut") {
|
||||
await navigator.clipboard.writeText(text);
|
||||
if (action === "cut") run(() => { editor.commands.deleteSelection(); });
|
||||
} else {
|
||||
let html = "", value = "";
|
||||
if (!sourceEditing && action === "paste" && navigator.clipboard.read) {
|
||||
try {
|
||||
const data = await navigator.clipboard.read();
|
||||
const rich = data.find(item => item.types.includes("text/html"));
|
||||
if (rich) html = await (await rich.getType("text/html")).text();
|
||||
const plain = data.find(item => item.types.includes("text/plain"));
|
||||
if (plain) value = await (await plain.getType("text/plain")).text();
|
||||
} catch { /* Text clipboard is also supported on older WebViews. */ }
|
||||
}
|
||||
if (!html && !value) value = await navigator.clipboard.readText();
|
||||
if (!html && !value) return;
|
||||
run(() => {
|
||||
if (html) editor.commands.insertContent(html);
|
||||
else {
|
||||
const nodes: JSONContent[] = [];
|
||||
value.replace(/\r\n?/g, "\n").split("\n").forEach((line, i) => { if (i) nodes.push({ type: "hardBreak" }); if (line) nodes.push({ type: "text", text: line, marks: [] }); });
|
||||
editor.commands.insertContent(nodes);
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch { report(tr("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste.")); }
|
||||
});
|
||||
}
|
||||
const items: ActionMenuItem[] = [
|
||||
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
|
||||
{ label: tr("Add link"), icon: "link", run: () => link(false) },
|
||||
{ label: tr("Add external link"), icon: "external", run: () => link(true) },
|
||||
{ separator: true },
|
||||
searchItem(text, actions.onSearch && (value => { close(); actions.onSearch?.(value); })),
|
||||
{ label: tr("Extract current selection…"), icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
|
||||
const selected = doc.slice(selection.from, selection.to).content.toJSON() as JSONContent[] | null;
|
||||
const markdown = extractedCellMarkdown(selected || []);
|
||||
const target = await actions.onExtract?.(markdown, text, valid);
|
||||
if (target) run(() => { editor.commands.insertContent({ type: "text", text: text.replace(/\s+/g, " ").trim(), marks: [{ type: "link", attrs: { href: target, "data-kind": "wiki" } }] }); });
|
||||
}) },
|
||||
{ label: tr("Format"), icon: "format", children: cellFormats.map(([label, kind]) => ({ label: tr(label), icon: kind, disabled: selection.empty, run: () => run(() => {
|
||||
if (kind === "clear") editor.commands.unsetAllMarks(); else editor.commands.toggleMark(kind);
|
||||
}) })) },
|
||||
{ label: tr("Paragraph"), icon: "paragraph", disabled: true, title: tr("Markdown table cells contain inline text") },
|
||||
{ label: tr("Insert"), icon: "insert", disabled: true, title: tr("Use the Row and Column menus to change the table") },
|
||||
{ separator: true },
|
||||
...clipboardItems({
|
||||
selected: !selection.empty, cut: () => void clipboard("cut"), copy: () => void clipboard("copy"), paste: () => void clipboard("paste"),
|
||||
pastePlain: () => void clipboard("plain"), selectAll: () => { close(); editor.commands.selectAll(); editor.view.focus(); },
|
||||
}),
|
||||
];
|
||||
return sourceEditing ? [
|
||||
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
|
||||
...items.slice(items.findIndex(item => "label" in item && item.label === tr("Cut"))),
|
||||
] : items;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { JSONContent } from "@tiptap/core";
|
||||
// Preserve formula source even when calculation is disabled.
|
||||
const isTableFormula = (text: string) => /^=(?!=)/.test(text.trim());
|
||||
|
||||
// Extract inline content into a note without confusing literal <br> in code
|
||||
// with actual cell hard breaks.
|
||||
export function extractedCellMarkdown(nodes: JSONContent[]): string {
|
||||
return nodes.map(node => {
|
||||
if (node.type === "hardBreak") return "\n";
|
||||
if (node.type === "paragraph") return extractedCellMarkdown(node.content || []);
|
||||
return tableCellMarkdown(node);
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function literal(text: string): string {
|
||||
return text.replace(/&/g, "&").replace(/[\\`*_[\]~<>!|=$%]/g, char => `\\${char}`).replace(/\r?\n/g, "<br>");
|
||||
}
|
||||
|
||||
function wrap(text: string, marker: string): string {
|
||||
const [, before, body, after] = /^(\s*)([\s\S]*?)(\s*)$/.exec(text)!;
|
||||
return body ? `${before}${marker}${body}${marker}${after}` : text;
|
||||
}
|
||||
|
||||
// A cell is inline Markdown. Paragraphs from pasted text become safe table breaks.
|
||||
export function tableCellMarkdown(node: JSONContent): string {
|
||||
// Keep plain formula input as readable source. Formatted/code/escaped text
|
||||
// still follows ordinary Markdown serialization and remains literal.
|
||||
if (node.type === "doc" && node.content?.length === 1 && node.content[0].type === "paragraph") {
|
||||
const children = node.content[0].content || [];
|
||||
const text = children.map(child => child.text || "").join("");
|
||||
if (children.every(child => child.type === "text" && !child.marks?.length) && (isTableFormula(text) || /^\s*\\=(?!=)/.test(text))) return text.replace(/\|/g, "\\|");
|
||||
}
|
||||
if (node.type === "hardBreak") return "<br>";
|
||||
if (node.type === "image") {
|
||||
const source = String(node.attrs?.["data-md-src"] || node.attrs?.src || "");
|
||||
const alt = String(node.attrs?.alt || "");
|
||||
return node.attrs?.["data-md-kind"] === "wiki"
|
||||
? `![[${literal(source)}${alt && alt !== source ? `\\|${literal(alt)}` : ""}]]`
|
||||
: `.replace(/>/g, "%3E")}>)`;
|
||||
}
|
||||
let text = node.text === undefined
|
||||
? (node.content || []).map(tableCellMarkdown).join(node.type === "doc" ? "<br>" : "")
|
||||
: literal(node.text);
|
||||
for (const mark of node.marks || []) {
|
||||
if (mark.type === "code") {
|
||||
const raw = node.text || "";
|
||||
const fence = "`".repeat(Math.max(0, ...[...raw.matchAll(/`+/g)].map(match => match[0].length)) + 1);
|
||||
const padding = /^`|`$|^ .* $/.test(raw) ? " " : "";
|
||||
text = `${fence}${padding}${raw.replace(/\|/g, "\\|")}${padding}${fence}`;
|
||||
}
|
||||
if (mark.type === "bold") text = wrap(text, "**");
|
||||
if (mark.type === "italic") text = wrap(text, "*");
|
||||
if (mark.type === "strike") text = wrap(text, "~~");
|
||||
if (mark.type === "highlight") text = wrap(text, "==");
|
||||
if (mark.type === "math" || mark.type === "comment") text = wrap((node.text || "").replace(/\|/g, "\\|"), mark.type === "math" ? "$" : "%%");
|
||||
if (mark.type === "link") {
|
||||
const href = String(mark.attrs?.href || "");
|
||||
text = mark.attrs?.["data-kind"] === "wiki"
|
||||
? `[[${literal(href)}\\|${text}]]`
|
||||
: `[${text}](<${href.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>${mark.attrs?.title ? ` "${String(mark.attrs.title).replace(/"/g, """)}"` : ""})`;
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/* Table editing in Write: cell editors, cell selection, and row and column drag. */
|
||||
.table-edit-help { font: inherit; color: var(--rs-text-dim); }
|
||||
.reading .ProseMirror {
|
||||
outline: none;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.reading .ProseMirror:focus,
|
||||
.reading .ProseMirror:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
.writer-table :is(th, td):is(.is-editing, .is-cell-selected) {
|
||||
background: var(--rs-item-selection-bg);
|
||||
box-shadow:
|
||||
inset 0 var(--cell-selection-top, 0px) 0 var(--rs-item-selection-border),
|
||||
inset 0 calc(-1 * var(--cell-selection-bottom, 0px)) 0 var(--rs-item-selection-border),
|
||||
inset var(--cell-selection-left, 0px) 0 0 var(--rs-item-selection-border),
|
||||
inset calc(-1 * var(--cell-selection-right, 0px)) 0 0 var(--rs-item-selection-border);
|
||||
outline: none;
|
||||
}
|
||||
.writer-table .is-editing {
|
||||
--cell-selection-top: var(--rs-item-selection-width);
|
||||
--cell-selection-bottom: var(--rs-item-selection-width);
|
||||
--cell-selection-left: var(--rs-item-selection-width);
|
||||
--cell-selection-right: var(--rs-item-selection-width);
|
||||
}
|
||||
.writer-table [data-selection-edges~="top"] { --cell-selection-top: var(--rs-item-selection-width); }
|
||||
.writer-table [data-selection-edges~="bottom"] { --cell-selection-bottom: var(--rs-item-selection-width); }
|
||||
.writer-table [data-selection-edges~="left"] { --cell-selection-left: var(--rs-item-selection-width); }
|
||||
.writer-table [data-selection-edges~="right"] { --cell-selection-right: var(--rs-item-selection-width); }
|
||||
.writer-table.has-cell-selection { outline: none; }
|
||||
.writer-table.has-cell-selection .md-table-scroll { user-select: none; }
|
||||
.table-drag-layer { position: absolute; inset: 0; overflow: clip; pointer-events: none; }
|
||||
.table-drag-handle { position: absolute; display: flex; align-items: center; justify-content: center; padding: 0; border: 0; border-radius: 4px; color: var(--rs-text-dim); background: transparent; cursor: grab; touch-action: none; opacity: 0; pointer-events: auto; transition: opacity 100ms; }
|
||||
.table-drag-handle[hidden], .table-drop-indicator[hidden] { display: none; }
|
||||
.table-drag-handle .action-icon { width: 18px; height: 18px; pointer-events: none; }
|
||||
.table-drag-column .action-icon { transform: rotate(90deg); }
|
||||
.table-drag-handle:hover, .table-drag-handle:focus-visible:not([data-pointer-focus]) { opacity: 1; color: var(--rs-text); background: var(--rs-hover-bg); outline: 2px solid var(--rs-accent); outline-offset: -2px; z-index: 2; }
|
||||
.writer-table.is-table-dragging, .writer-table.is-table-dragging * { cursor: grabbing !important; user-select: none; }
|
||||
.writer-table.is-table-dragging .table-drag-handle::after { display: none; }
|
||||
.table-drop-indicator { position: absolute; z-index: 3; border-radius: 2px; background: var(--rs-accent); pointer-events: none; }
|
||||
.table-drag-preview { position: fixed; top: 0; left: 0; z-index: 1100; margin: 0; padding: 0; max-width: calc(100vw - 24px); border: 1px solid var(--rs-accent); border-radius: 6px; background: var(--rs-bg-elevated); color: var(--rs-text); box-shadow: 0 8px 28px #0006; opacity: .92; pointer-events: none; user-select: none; will-change: transform; animation: table-drag-lift 100ms ease-out; }
|
||||
.table-drag-preview.is-invalid-drop { opacity: .6; }
|
||||
.table-drag-preview-label { padding: 5px 10px; border-bottom: 1px solid var(--rs-border); color: var(--rs-accent); font: 12px/1.4 var(--rs-font-ui); }
|
||||
.table-drag-preview-content { max-height: min(260px, 35vh); overflow: hidden; border-radius: 0 0 6px 6px; }
|
||||
.table-drag-preview table { width: 100%; table-layout: fixed; margin: 0; }
|
||||
.table-drag-preview :is(th, td) { min-width: 0; max-width: none; padding: 7px 10px; overflow-wrap: anywhere; }
|
||||
.table-drag-preview p { margin: 0; }
|
||||
@keyframes table-drag-lift { from { opacity: 0; } to { opacity: .92; } }
|
||||
@media (prefers-reduced-motion: reduce) { .table-drag-handle { transition: none; } .table-drag-preview { animation: none; } }
|
||||
.table-add .action-icon { width: 20px; height: 20px; margin: 2px; }
|
||||
.writer-table .md-inline-comment { display: inline; color: var(--rs-text-dim); background: var(--rs-bg-active); }
|
||||
@@ -0,0 +1,467 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { Editor, Extension, Mark, getMarkRange } from "@tiptap/core";
|
||||
import { Plugin } from "@tiptap/pm/state";
|
||||
import { Decoration, DecorationSet } from "@tiptap/pm/view";
|
||||
import Highlight from "@tiptap/extension-highlight";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import Link from "@tiptap/extension-link";
|
||||
import Image from "@tiptap/extension-image";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { isolateHistory, redo, undo } from "@codemirror/commands";
|
||||
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable";
|
||||
import { tableCellMarkdown } from "./tableCellMarkdown";
|
||||
import { tableSelectionControls } from "./tableSelectionControls";
|
||||
import { tableDragControls } from "./tableDragControls";
|
||||
import type { TableContextActions } from "./tableCellActions";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
import { activeTableFormulas } from "../formulas/index.ts";
|
||||
import { attachTooltip } from "../ui/tooltip";
|
||||
import { documentLinks } from "./documentLinks";
|
||||
import { tableLinkLabelPosition } from "./tableLinkSource";
|
||||
import { renderMarkdownHtml } from "../workspace/noteHtml";
|
||||
|
||||
const cellFormats = ["math", "comment"].map(name => Mark.create({
|
||||
name,
|
||||
parseHTML: () => [{ tag: `span[data-cell-format="${name}"]` }],
|
||||
renderHTML: () => ["span", { "data-cell-format": name, class: `md-inline-${name}` }, 0],
|
||||
}));
|
||||
|
||||
const CellLink = Link.extend({
|
||||
addAttributes() { return { ...this.parent?.(), "data-kind": { default: "md" } }; },
|
||||
});
|
||||
const CellImage = Image.extend({
|
||||
addAttributes() { return { ...this.parent?.(), "data-md-src": { default: null }, "data-md-kind": { default: "md" } }; },
|
||||
parseHTML() { return [...(this.parent?.() || []), { tag: "span.missing-image[data-md-src]" }]; },
|
||||
renderHTML({ HTMLAttributes }) {
|
||||
return HTMLAttributes.src
|
||||
? ["img", HTMLAttributes]
|
||||
: ["span", { ...HTMLAttributes, class: "missing-image" }, `Image unavailable: ${HTMLAttributes.alt || HTMLAttributes["data-md-src"] || ""}`];
|
||||
},
|
||||
});
|
||||
|
||||
export const tableEditors = new WeakMap<HTMLElement, { source: string; enter: (forward: boolean, x?: number) => void; destroy: () => void }>();
|
||||
|
||||
export function tableControls(root: HTMLElement, view: EditorView, initialSource: string, actions: TableContextActions = {}) {
|
||||
const formulas = activeTableFormulas();
|
||||
const scroll = root.querySelector<HTMLElement>(".md-table-scroll");
|
||||
const table = scroll?.querySelector("table");
|
||||
if (!scroll || !table || !parseMarkdownTable(initialSource)) return;
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.className = "writer-table";
|
||||
scroll.before(wrapper);
|
||||
wrapper.append(scroll);
|
||||
let editor: Editor | undefined;
|
||||
let active: HTMLTableCellElement | undefined;
|
||||
let sourceEditing = false;
|
||||
let sourceImages = new Map<string, string>();
|
||||
let firstEdit = true;
|
||||
let selectionControls: ReturnType<typeof tableSelectionControls> | undefined;
|
||||
let dragControls: ReturnType<typeof tableDragControls> | undefined;
|
||||
const tooltipCleanup: (() => void)[] = [];
|
||||
const controller = { source: initialSource, enter, destroy: () => { tooltipCleanup.forEach(dispose => dispose()); dragControls?.destroy(); selectionControls?.destroy(); editor?.destroy(); editor = undefined; } };
|
||||
tableEditors.set(root, controller);
|
||||
|
||||
function enter(forward: boolean, x?: number) {
|
||||
const row = table!.rows[forward ? 0 : table!.rows.length - 1];
|
||||
const cells = [...row.cells];
|
||||
let cell = cells[forward ? 0 : cells.length - 1];
|
||||
if (x !== undefined) {
|
||||
const distance = (candidate: HTMLTableCellElement) => {
|
||||
const rect = candidate.getBoundingClientRect();
|
||||
return Math.max(rect.left - x, x - rect.right, 0);
|
||||
};
|
||||
cell = cells.reduce((nearest, candidate) => distance(candidate) < distance(nearest) ? candidate : nearest);
|
||||
}
|
||||
activate(cell);
|
||||
const current = editor!;
|
||||
let position = forward ? 1 : current.state.doc.content.size - 1;
|
||||
if (x !== undefined) {
|
||||
const edge = current.view.coordsAtPos(position);
|
||||
position = current.view.posAtCoords({ left: x, top: (edge.top + edge.bottom) / 2 })?.pos ?? position;
|
||||
}
|
||||
current.commands.setTextSelection(position);
|
||||
current.view.focus();
|
||||
cell.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
}
|
||||
|
||||
function refreshFormulas() {
|
||||
const parsed = parseMarkdownTable(controller.source);
|
||||
if (!parsed || !formulas) return;
|
||||
const grid = parsed.rows.filter((_, index) => index !== 1).map(row => Array.from({ length: parsed.columns }, (_, c) => row.cells[c]?.text || ""));
|
||||
const results = formulas.evaluateTableFormulas(grid);
|
||||
for (const row of table!.rows) for (const cell of row.cells) {
|
||||
const result = results[row.rowIndex]?.[cell.cellIndex];
|
||||
const address = formulas.cellAddress(row.rowIndex, cell.cellIndex);
|
||||
// Only a formula cell has a hover hint. The footer shows the address of each cell, so no hint covers the next cell.
|
||||
if (result?.formula) cell.dataset.cellHint = `${address} · ${result.formula}`;
|
||||
else delete cell.dataset.cellHint;
|
||||
cell.removeAttribute("title");
|
||||
if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result);
|
||||
if (cell === active) {
|
||||
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : tr(" · Type = to calculate")}`;
|
||||
formulaHint.textContent = result?.error ? formulas.formulaErrorText(result.error) : "";
|
||||
formulaHint.hidden = !formulaHint.textContent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function change(insert: string, structural = false) {
|
||||
const source = controller.source;
|
||||
const from = view.posAtDOM(root);
|
||||
if (view.state.doc.sliceString(from, from + source.length) !== source || insert === source) return;
|
||||
// Keep the same DOM/editor on typing, including composition and text selection.
|
||||
if (!structural) controller.source = insert;
|
||||
let start = 0, oldEnd = source.length, newEnd = insert.length;
|
||||
while (start < oldEnd && start < newEnd && source[start] === insert[start]) start++;
|
||||
while (oldEnd > start && newEnd > start && source[oldEnd - 1] === insert[newEnd - 1]) { oldEnd--; newEnd--; }
|
||||
view.dispatch({
|
||||
changes: { from: from + start, to: from + oldEnd, insert: insert.slice(start, newEnd) },
|
||||
userEvent: structural ? "input" : editor?.view.composing ? "input.type.compose" : "input.type.table",
|
||||
annotations: structural ? isolateHistory.of("full") : firstEdit ? isolateHistory.of("before") : [],
|
||||
});
|
||||
firstEdit = false;
|
||||
if (!structural) refreshFormulas();
|
||||
view.requestMeasure();
|
||||
}
|
||||
|
||||
function finish() {
|
||||
if (!editor || !active) return;
|
||||
const cell = active;
|
||||
let html = editor.getHTML();
|
||||
if (sourceEditing) {
|
||||
const rendered = document.createElement("div");
|
||||
rendered.innerHTML = renderMarkdownHtml(controller.source, sourceImages);
|
||||
html = rendered.querySelector("table")?.rows[(cell.parentElement as HTMLTableRowElement).rowIndex]?.cells[cell.cellIndex]?.innerHTML ?? html;
|
||||
}
|
||||
sourceEditing = false;
|
||||
editor.destroy(); editor = undefined; active = undefined;
|
||||
cell.innerHTML = html;
|
||||
cell.classList.remove("is-editing", "is-source-editing");
|
||||
refreshFormulas();
|
||||
formulaStatus.textContent = tr("Type = in a cell to calculate");
|
||||
formulaHint.hidden = true;
|
||||
view.requestMeasure();
|
||||
if (!firstEdit) view.dispatch({ annotations: isolateHistory.of("after") });
|
||||
}
|
||||
|
||||
function leave(after: boolean) {
|
||||
const from = view.posAtDOM(root), to = from + controller.source.length;
|
||||
finish();
|
||||
let anchor = after ? Math.min(view.state.doc.length, to + 1) : Math.max(0, from - 1);
|
||||
if (after && to + 1 >= view.state.doc.length) {
|
||||
view.dispatch({ changes: { from: view.state.doc.length, insert: to === view.state.doc.length ? "\n\n" : "\n" }, userEvent: "input" });
|
||||
anchor = to + 2;
|
||||
} else if (after && view.state.doc.sliceString(to, to + 2) === "\n\n") {
|
||||
// Leave the separator blank so typing below cannot become another row.
|
||||
anchor = to + 2;
|
||||
} else if (!after && from === 0) {
|
||||
view.dispatch({ changes: { from: 0, insert: "\n\n" }, userEvent: "input" });
|
||||
anchor = 0;
|
||||
}
|
||||
view.dispatch({ selection: { anchor }, scrollIntoView: true });
|
||||
view.focus();
|
||||
}
|
||||
|
||||
function activate(cell: HTMLTableCellElement) {
|
||||
if (active === cell) return;
|
||||
finish();
|
||||
active = cell;
|
||||
firstEdit = true;
|
||||
const row = (cell.parentElement as HTMLTableRowElement).rowIndex;
|
||||
const column = cell.cellIndex;
|
||||
const sourceRow = row === 0 ? 0 : row + 1;
|
||||
const originalCell = parseMarkdownTable(controller.source)?.rows[sourceRow]?.cells[column];
|
||||
// The nested editor owns browser focus, but the outer editor also needs to
|
||||
// leave its previous active line so its Markdown markers render again.
|
||||
view.dispatch({ selection: { anchor: view.posAtDOM(root) + (originalCell?.from ?? 0) }, userEvent: "select.table" });
|
||||
let contentFrom = originalCell?.from, contentTo = originalCell?.to;
|
||||
const formula = originalCell && (/^=(?!=)/.test(originalCell.text.trim()) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined;
|
||||
const html = cell.innerHTML;
|
||||
formulaStatus.textContent = formulas ? `${formulas.cellAddress(row, column)}${tr(" · Type = to calculate")}` : "";
|
||||
cell.innerHTML = "";
|
||||
cell.classList.add("is-editing");
|
||||
editor = new Editor({
|
||||
element: cell,
|
||||
extensions: [
|
||||
Extension.create({
|
||||
name: "cellLinkSource",
|
||||
addProseMirrorPlugins: () => [new Plugin({ props: { decorations(state) {
|
||||
if (!sourceEditing) return null;
|
||||
const decorations: Decoration[] = [];
|
||||
state.doc.descendants((node, position) => {
|
||||
if (!node.isTextblock) return;
|
||||
for (const link of documentLinks(node.textBetween(0, node.content.size, "\n", "\n"))) {
|
||||
decorations.push(Decoration.inline(position + link.from + 1, position + link.to + 1, { class: "writer-link-source", "data-href": link.target, "data-kind": link.kind }));
|
||||
if (link.targetTo > link.targetFrom) decorations.push(Decoration.inline(position + link.targetFrom + 1, position + link.targetTo + 1, { class: "writer-link-target" }));
|
||||
}
|
||||
return false;
|
||||
});
|
||||
return DecorationSet.create(state.doc, decorations);
|
||||
} } })],
|
||||
}),
|
||||
StarterKit.configure({ blockquote: false, bulletList: false, orderedList: false, listItem: false, listKeymap: false, codeBlock: false, heading: false, horizontalRule: false, link: false, underline: false, undoRedo: false, trailingNode: false, gapcursor: false, dropcursor: false }),
|
||||
CellLink.configure({ openOnClick: false, autolink: false }),
|
||||
CellImage.configure({ inline: true, allowBase64: true }),
|
||||
Highlight, ...cellFormats,
|
||||
],
|
||||
content: formula ? { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: formula }] }] } : html,
|
||||
enableInputRules: false,
|
||||
enablePasteRules: false,
|
||||
editorProps: {
|
||||
attributes: { class: "writer-cell-editor", role: "textbox", "aria-label": cell.getAttribute("aria-label")!, "aria-multiline": "true", spellcheck: "true" },
|
||||
handleKeyDown(_editorView, event) {
|
||||
if (event.isComposing) return false;
|
||||
if (sourceEditing && (event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) {
|
||||
event.preventDefault(); event.stopPropagation(); return true;
|
||||
}
|
||||
if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
|
||||
// The nested editor owns cursor movement, including word movement
|
||||
// and selections. Never let an arrow reach the prose editor.
|
||||
event.stopPropagation();
|
||||
// Native cursor movement can precede ProseMirror's selectionchange
|
||||
// observer (especially during key repeat). Test the visible caret.
|
||||
const native = document.getSelection();
|
||||
const readNative = (scroll = false) => {
|
||||
if (!native?.anchorNode || !native.focusNode || !_editorView.dom.contains(native.anchorNode) || !_editorView.dom.contains(native.focusNode)) return;
|
||||
const anchor = _editorView.posAtDOM(native.anchorNode, native.anchorOffset);
|
||||
const head = _editorView.posAtDOM(native.focusNode, native.focusOffset);
|
||||
if (anchor === _editorView.state.selection.anchor && head === _editorView.state.selection.head) return;
|
||||
const chain = editor!.chain().setTextSelection({ from: anchor, to: head });
|
||||
(scroll ? chain.scrollIntoView() : chain).run();
|
||||
};
|
||||
readNative();
|
||||
// ProseMirror reads a native move on the next selectionchange. Its
|
||||
// delayed focus check can run first and restore the old selection,
|
||||
// so the move is lost under load. Move the DOM selection here and
|
||||
// read the result at once. Other shortcuts stay with the browser.
|
||||
const mac = navigator.platform.includes("Mac");
|
||||
const vertical = event.key === "ArrowUp" || event.key === "ArrowDown";
|
||||
const word = mac ? event.altKey : event.ctrlKey;
|
||||
const moveNative = () => {
|
||||
if (!native || event.metaKey || (mac ? event.ctrlKey : event.altKey) || (vertical && word)) return false;
|
||||
native.modify(
|
||||
event.shiftKey ? "extend" : "move",
|
||||
vertical ? (event.key === "ArrowUp" ? "backward" : "forward") : event.key === "ArrowLeft" ? "left" : "right",
|
||||
vertical ? "line" : word ? "word" : "character",
|
||||
);
|
||||
readNative(true);
|
||||
return true;
|
||||
};
|
||||
if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey || !_editorView.state.selection.empty) return moveNative();
|
||||
const direction = event.key === "ArrowLeft" ? "left" : event.key === "ArrowRight" ? "right" : event.key === "ArrowUp" ? "up" : "down";
|
||||
const horizontal = direction === "left" || direction === "right";
|
||||
const backwards = direction === "left" || direction === "up";
|
||||
const { $head } = _editorView.state.selection;
|
||||
// Pasted rich text can have several paragraphs within one cell.
|
||||
if ($head.depth && (backwards ? $head.before(1) > 0 : $head.after(1) < _editorView.state.doc.content.size)) return moveNative();
|
||||
if (!_editorView.endOfTextblock(direction)) return moveNative();
|
||||
event.preventDefault();
|
||||
const cells = [...table!.querySelectorAll<HTMLTableCellElement>("th, td")];
|
||||
const next = horizontal
|
||||
? cells[cells.indexOf(cell) + (backwards ? -1 : 1)]
|
||||
: table!.rows[row + (backwards ? -1 : 1)]?.cells[column];
|
||||
// Once there are no more cells in this direction, return to prose.
|
||||
if (!next) { leave(!backwards); return true; }
|
||||
const caret = _editorView.coordsAtPos(_editorView.state.selection.head);
|
||||
activate(next);
|
||||
const current = editor!;
|
||||
let position = backwards ? current.state.doc.content.size - 1 : 1;
|
||||
if (!horizontal) {
|
||||
// Enter the closest position on the first/last visual line, even
|
||||
// when either cell wraps or contains a hard break.
|
||||
const edge = current.view.coordsAtPos(position);
|
||||
position = current.view.posAtCoords({ left: caret.left, top: (edge.top + edge.bottom) / 2 })?.pos ?? position;
|
||||
}
|
||||
current.commands.setTextSelection(position);
|
||||
current.view.focus();
|
||||
next.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
return true;
|
||||
}
|
||||
// Keep formatting shortcuts in the cell. The Writer around the table also binds Ctrl+B.
|
||||
if ((event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) event.stopPropagation();
|
||||
if ((event.ctrlKey || event.metaKey) && (event.key === "Home" || event.key === "End")) {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const position = event.key === "Home" ? 1 : editor!.state.doc.content.size - 1;
|
||||
editor?.commands.setTextSelection(event.shiftKey ? { from: editor.state.selection.anchor, to: position } : position);
|
||||
return true;
|
||||
}
|
||||
if ((event.ctrlKey || event.metaKey) && ["z", "y"].includes(event.key.toLowerCase())) {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const from = view.posAtDOM(root);
|
||||
(event.key.toLowerCase() === "y" || event.shiftKey ? redo : undo)(view);
|
||||
requestAnimationFrame(() => {
|
||||
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
|
||||
(updated?.querySelector("table")?.rows[row]?.cells[column])?.focus();
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (event.key === "Escape" && sourceEditing) { event.preventDefault(); finish(); wrapper.focus(); return true; }
|
||||
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if (event.shiftKey) editor?.commands.setHardBreak();
|
||||
else if (event.ctrlKey || event.metaKey) leave(true);
|
||||
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") {
|
||||
event.preventDefault();
|
||||
const cells = [...table!.querySelectorAll<HTMLTableCellElement>("th, td")];
|
||||
const next = cells[cells.indexOf(cell) + (event.shiftKey ? -1 : 1)];
|
||||
if (next) { activate(next); editor?.commands.setTextSelection(1); editor?.view.focus(); }
|
||||
else if (event.shiftKey) leave(false);
|
||||
else add("row", true);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
onUpdate({ editor: current }) {
|
||||
const text = sourceEditing
|
||||
? current.getText({ blockSeparator: "<br>" }).replace(/\r?\n/g, "<br>").replace(/\|/g, (_pipe, offset, value) => {
|
||||
let slashes = 0;
|
||||
for (let before = offset - 1; before >= 0 && value[before] === "\\"; before--) slashes++;
|
||||
return slashes % 2 ? "|" : "\\|";
|
||||
})
|
||||
: tableCellMarkdown(current.getJSON());
|
||||
const source = controller.source;
|
||||
// Track the full edited range, including typed spaces. Re-parsing the
|
||||
// trimmed cell on each key would gradually turn those spaces into padding.
|
||||
const insert = contentFrom === undefined || contentTo === undefined
|
||||
? replaceTableCell(source, sourceRow, column, text)
|
||||
: source.slice(0, contentFrom) + text + source.slice(contentTo);
|
||||
contentFrom ??= parseMarkdownTable(insert)?.rows[sourceRow]?.cells[column]?.from;
|
||||
if (contentFrom !== undefined) contentTo = contentFrom + text.length;
|
||||
change(insert);
|
||||
},
|
||||
onSelectionUpdate({ editor: current }) {
|
||||
// Read the final mouse/keyboard selection after activation sets its
|
||||
// temporary caret. Menus and range selections keep their own focus.
|
||||
requestAnimationFrame(() => {
|
||||
if (current !== editor || current.isDestroyed || sourceEditing || !current.isFocused || current.view.composing) return;
|
||||
const { selection } = current.state;
|
||||
if (!selection.empty) return;
|
||||
const mark = selection.$from.marks().find(mark => mark.type.name === "link");
|
||||
const range = mark && getMarkRange(selection.$from, mark.type, mark.attrs);
|
||||
if (range) editSource(range, selection.from - range.from);
|
||||
});
|
||||
},
|
||||
onBlur() {
|
||||
// A toolbar click, another cell, or the prose editor can now take focus.
|
||||
queueMicrotask(() => { if (active === cell && !cell.contains(document.activeElement) && !selectionControls?.keepEditing()) finish(); });
|
||||
},
|
||||
});
|
||||
editor.commands.setTextSelection(editor.state.doc.content.size - 1); editor.view.focus();
|
||||
refreshFormulas();
|
||||
view.requestMeasure();
|
||||
}
|
||||
|
||||
function editSource(range: { from: number; to: number }, labelOffset?: number) {
|
||||
if (!editor || !active) return;
|
||||
const row = (active.parentElement as HTMLTableRowElement).rowIndex;
|
||||
const cell = parseMarkdownTable(controller.source)?.rows[row === 0 ? 0 : row + 1]?.cells[active.cellIndex];
|
||||
if (!cell) return;
|
||||
const preceding = new Set<number>();
|
||||
editor.state.doc.descendants((node, position) => {
|
||||
const mark = node.marks.find(mark => mark.type.name === "link");
|
||||
if (mark && position < range.from) {
|
||||
const found = getMarkRange(editor!.state.doc.resolve(position), mark.type, mark.attrs);
|
||||
if (found && found.from < range.from) preceding.add(found.from);
|
||||
}
|
||||
});
|
||||
const link = documentLinks(cell.text)[preceding.size];
|
||||
if (!link) return;
|
||||
sourceImages = new Map([...root.querySelectorAll<HTMLImageElement>("img[data-md-src]")].map(image => [image.dataset.mdSrc!, image.src]));
|
||||
sourceEditing = true;
|
||||
active.classList.add("is-source-editing");
|
||||
editor.commands.setContent({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: cell.text }] }] }, { emitUpdate: false });
|
||||
editor.commands.setTextSelection(labelOffset === undefined
|
||||
? { from: link.targetFrom + 1, to: link.targetTo + 1 }
|
||||
: tableLinkLabelPosition(cell.text, link, labelOffset) + 1);
|
||||
editor.view.focus();
|
||||
view.requestMeasure();
|
||||
}
|
||||
|
||||
function add(kind: "row" | "column", focusNew = false, column = 0) {
|
||||
const from = view.posAtDOM(root);
|
||||
finish();
|
||||
const current = controller.source;
|
||||
change(kind === "column" ? appendTableColumn(current) : appendTableRow(current), true);
|
||||
view.focus();
|
||||
requestAnimationFrame(() => {
|
||||
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
|
||||
if (!updated) return;
|
||||
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;
|
||||
} else updated.querySelector(".table-add-row")?.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
view.requestMeasure();
|
||||
});
|
||||
}
|
||||
|
||||
const help = document.createElement("div");
|
||||
help.className = "table-edit-help";
|
||||
help.hidden = true;
|
||||
const footer = document.createElement("div");
|
||||
footer.className = "table-footer";
|
||||
const tools = formulas?.createFormulaTools(finish, () => view.requestMeasure());
|
||||
const formulaStatus = tools?.formulaStatus ?? document.createElement("span");
|
||||
const formulaHint = tools?.formulaHint ?? document.createElement("div");
|
||||
footer.append(help);
|
||||
if (tools) footer.append(tools.formulaTools, formulaHint);
|
||||
wrapper.after(footer);
|
||||
for (const kind of ["column", "row"] as const) {
|
||||
const button = document.createElement("button");
|
||||
const label = kind === "column" ? tr("Add column to the right") : tr("Add row below");
|
||||
button.type = "button";
|
||||
button.className = `table-add table-add-${kind}`;
|
||||
tooltipCleanup.push(attachTooltip(button, () => label));
|
||||
button.setAttribute("aria-label", label);
|
||||
const plus = document.createElement("span");
|
||||
plus.append(actionIcon("plus"));
|
||||
plus.setAttribute("aria-hidden", "true");
|
||||
button.append(plus);
|
||||
button.addEventListener("mousedown", event => { event.preventDefault(); event.stopPropagation(); });
|
||||
button.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); add(kind); });
|
||||
button.addEventListener("pointermove", event => {
|
||||
const rect = button.getBoundingClientRect();
|
||||
button.style.setProperty("--table-add-position", `${kind === "column" ? Math.max(12, Math.min(rect.height - 12, event.clientY - rect.top)) : Math.max(12, Math.min(rect.width - 12, event.clientX - rect.left))}px`);
|
||||
});
|
||||
wrapper.append(button);
|
||||
}
|
||||
for (const row of table.rows) for (const cell of row.cells) {
|
||||
cell.tabIndex = 0;
|
||||
cell.setAttribute("aria-label", (formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : "") + tr("Row {row}, column {column}", { row: row.rowIndex + 1, column: cell.cellIndex + 1 }));
|
||||
cell.addEventListener("focus", () => activate(cell));
|
||||
}
|
||||
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate, editSource }, actions);
|
||||
dragControls = tableDragControls(root, wrapper, table, scroll, view, () => controller.source, selectionControls.select, change);
|
||||
table.addEventListener("mousedown", event => {
|
||||
if (event.button !== 0) return;
|
||||
if (event.ctrlKey || event.metaKey || !(event.target instanceof Element)) return;
|
||||
const cell = event.target.closest<HTMLTableCellElement>("td, th");
|
||||
if (!cell) return;
|
||||
event.stopPropagation();
|
||||
if (active !== cell) {
|
||||
event.preventDefault(); activate(cell);
|
||||
const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY });
|
||||
if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); }
|
||||
} else if (event.detail === 1 && editor && !editor.view.composing && editor.view.dom.contains(event.target)) {
|
||||
// ProseMirror reads a native click on the next selectionchange. Its
|
||||
// delayed focus check can run first and restore the old selection, so
|
||||
// the click is lost under load. Set the clicked position here. The
|
||||
// browser then places the same caret, and a drag starts from it.
|
||||
const hit = editor.view.posAtCoords({ left: event.clientX, top: event.clientY });
|
||||
if (hit) editor.commands.setTextSelection(hit.pos);
|
||||
}
|
||||
});
|
||||
refreshFormulas();
|
||||
for (const row of table.rows) for (const cell of row.cells) {
|
||||
tooltipCleanup.push(attachTooltip(cell, () => cell.dataset.cellHint || ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
import { moveTableAxis, type TableAxis } from "./tableStructure";
|
||||
import type { CellRange } from "./tableSelection";
|
||||
import { attachTooltip } from "../ui/tooltip";
|
||||
|
||||
const controls = new WeakMap<HTMLTableElement, (axis: TableAxis, index: number, keyboard: boolean) => void>();
|
||||
|
||||
export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, scroll: HTMLElement, view: EditorView, source: () => string, select: (range: CellRange) => void, change: (text: string, structural: boolean) => void) {
|
||||
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
|
||||
const handles: { axis: TableAxis; index: number; button: HTMLButtonElement }[] = [];
|
||||
const tooltipCleanup: (() => void)[] = [];
|
||||
const layer = document.createElement("div");
|
||||
layer.className = "table-drag-layer";
|
||||
wrapper.append(layer);
|
||||
const indicator = document.createElement("div");
|
||||
indicator.className = "table-drop-indicator";
|
||||
indicator.hidden = true;
|
||||
layer.append(indicator);
|
||||
let preview: HTMLElement | undefined, previewLabel: HTMLElement | undefined;
|
||||
let drag: { axis: TableAxis; index: number; pointer: number; x: number; y: number; startX: number; startY: number; active: boolean; to?: number; before: string } | undefined;
|
||||
let frame = 0, layoutFrame = 0;
|
||||
|
||||
function selectAxis(axis: TableAxis, index: number) {
|
||||
select(axis === "row"
|
||||
? { anchor: { row: index, column: 0 }, head: { row: index, column: table.rows[0].cells.length - 1 } }
|
||||
: { anchor: { row: 0, column: index }, head: { row: table.rows.length - 1, column: index } });
|
||||
}
|
||||
function focusAxis(axis: TableAxis, index: number, keyboard = true) {
|
||||
selectAxis(axis, index);
|
||||
const button = handles.find(handle => handle.axis === axis && handle.index === index)?.button;
|
||||
button?.toggleAttribute("data-pointer-focus", !keyboard);
|
||||
button?.focus({ preventScroll: true });
|
||||
}
|
||||
controls.set(table, focusAxis);
|
||||
|
||||
function commit(axis: TableAxis, index: number, to: number, keyboard = true) {
|
||||
const before = source(), after = moveTableAxis(before, axis, index, to);
|
||||
if (before === after) return;
|
||||
const from = view.posAtDOM(root), left = scroll.scrollLeft;
|
||||
change(after, true);
|
||||
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
|
||||
const next = updated?.querySelector("table");
|
||||
const viewport = updated?.querySelector<HTMLElement>(".md-table-scroll");
|
||||
if (viewport) viewport.scrollLeft = left;
|
||||
if (next) controls.get(next)?.(axis, to, keyboard);
|
||||
}
|
||||
|
||||
function layout() {
|
||||
layoutFrame = 0;
|
||||
const origin = wrapper.getBoundingClientRect(), viewport = scroll.getBoundingClientRect();
|
||||
for (const { axis, index, button } of handles) {
|
||||
const rect = (axis === "row" ? table.rows[index] : table.rows[0].cells[index]).getBoundingClientRect();
|
||||
const left = Math.max(viewport.left, rect.left), right = Math.min(viewport.right, rect.right);
|
||||
button.hidden = axis === "column" && right <= left;
|
||||
Object.assign(button.style, axis === "row"
|
||||
? { left: `${viewport.left - origin.left - 26}px`, top: `${rect.top - origin.top}px`, width: "26px", height: `${rect.height}px` }
|
||||
: { left: `${left - origin.left}px`, top: `${viewport.top - origin.top - 26}px`, width: `${Math.max(0, right - left)}px`, height: "26px" });
|
||||
button.style.setProperty("--table-tooltip-left", `${axis === "row" ? 26 : viewport.left - left}px`);
|
||||
button.style.setProperty("--table-tooltip-width", `${Math.min(260, viewport.width)}px`);
|
||||
}
|
||||
}
|
||||
function scheduleLayout() { if (!layoutFrame) layoutFrame = requestAnimationFrame(layout); }
|
||||
|
||||
function createPreview() {
|
||||
if (!drag) return;
|
||||
preview = document.createElement("div");
|
||||
preview.className = `reading table-drag-preview table-drag-preview-${drag.axis}`;
|
||||
preview.setAttribute("aria-hidden", "true");
|
||||
preview.inert = true;
|
||||
previewLabel = document.createElement("div");
|
||||
previewLabel.className = "table-drag-preview-label";
|
||||
preview.append(previewLabel);
|
||||
const content = document.createElement("div");
|
||||
content.className = "table-drag-preview-content";
|
||||
const copy = document.createElement("table");
|
||||
const rows = drag.axis === "row" ? [table.rows[drag.index]] : [...table.rows];
|
||||
const width = drag.axis === "row" ? table.getBoundingClientRect().width : table.rows[0].cells[drag.index].getBoundingClientRect().width;
|
||||
preview.style.width = `${Math.min(width, drag.axis === "row" ? 560 : 280, window.innerWidth - 24)}px`;
|
||||
copy.style.font = getComputedStyle(table).font;
|
||||
for (const row of rows) {
|
||||
const clonedRow = document.createElement("tr");
|
||||
const cells = drag.axis === "row" ? [...row.cells] : [row.cells[drag.index]];
|
||||
for (const cell of cells) {
|
||||
const clonedCell = cell.cloneNode(true) as HTMLTableCellElement;
|
||||
// A visual snapshot must not duplicate focusable controls, document IDs,
|
||||
// or selection styling from the real cells.
|
||||
for (const element of [clonedCell, ...clonedCell.querySelectorAll("*")]) {
|
||||
for (const attribute of ["id", "tabindex", "contenteditable", "aria-selected", "aria-label", "data-selection-edges", "title"]) element.removeAttribute(attribute);
|
||||
element.classList.remove("is-cell-selected", "is-editing");
|
||||
}
|
||||
clonedCell.style.width = `${cell.getBoundingClientRect().width / width * 100}%`;
|
||||
clonedRow.append(clonedCell);
|
||||
}
|
||||
copy.append(clonedRow);
|
||||
}
|
||||
content.append(copy); preview.append(content); document.body.append(preview);
|
||||
updatePreview();
|
||||
}
|
||||
|
||||
function updatePreview() {
|
||||
if (!preview || !previewLabel || !drag) return;
|
||||
const valid = drag.to !== undefined;
|
||||
preview.classList.toggle("is-invalid-drop", !valid);
|
||||
previewLabel.textContent = `${drag.axis === "row" ? tr("Row") : tr("Column")} ${drag.index + 1}${valid ? ` → ${drag.to! + 1}` : tr(" · Release to cancel")}`;
|
||||
const rect = preview.getBoundingClientRect();
|
||||
const x = Math.max(8, Math.min(drag.x + 16, window.innerWidth - rect.width - 8));
|
||||
const y = Math.max(8, Math.min(drag.y + 16, window.innerHeight - rect.height - 8));
|
||||
preview.style.transform = `translate3d(${x}px, ${y}px, 0)`;
|
||||
}
|
||||
|
||||
function updateTarget() {
|
||||
if (!drag?.active) return;
|
||||
const { axis, x, y, index } = drag;
|
||||
const viewport = scroll.getBoundingClientRect(), origin = wrapper.getBoundingClientRect();
|
||||
drag.to = undefined;
|
||||
indicator.hidden = true;
|
||||
if (x < viewport.left - 32 || x > viewport.right + 32 || y < viewport.top - 32 || y > viewport.bottom + 32) return;
|
||||
const items = axis === "row" ? [...table.rows].slice(1) : [...table.rows[0].cells];
|
||||
if (!items.length) return;
|
||||
const coordinate = axis === "row" ? y : x;
|
||||
let boundary = items.findIndex(item => {
|
||||
const rect = item.getBoundingClientRect();
|
||||
return coordinate < (axis === "row" ? (rect.top + rect.bottom) / 2 : (rect.left + rect.right) / 2);
|
||||
});
|
||||
if (boundary < 0) boundary = items.length;
|
||||
const insertion = boundary + (axis === "row" ? 1 : 0);
|
||||
drag.to = insertion > index ? insertion - 1 : insertion;
|
||||
if (drag.to === index) return;
|
||||
const edge = (items[boundary] || items[items.length - 1]).getBoundingClientRect();
|
||||
const position = axis === "row" ? (boundary === items.length ? edge.bottom : edge.top) : (boundary === items.length ? edge.right : edge.left);
|
||||
if (axis === "column" && (position < viewport.left || position > viewport.right)) return;
|
||||
indicator.hidden = false;
|
||||
Object.assign(indicator.style, axis === "row"
|
||||
? { left: `${viewport.left - origin.left}px`, top: `${position - origin.top - 2}px`, width: `${viewport.width}px`, height: "4px" }
|
||||
: { left: `${position - origin.left - 2}px`, top: `${viewport.top - origin.top}px`, width: "4px", height: `${table.getBoundingClientRect().height}px` });
|
||||
}
|
||||
function tick() {
|
||||
if (!drag?.active) return;
|
||||
const viewport = scroll.getBoundingClientRect(), editor = view.scrollDOM.getBoundingClientRect();
|
||||
const speed = (coordinate: number, start: number, end: number) => coordinate < start + 36 ? -Math.min(18, (start + 36 - coordinate) / 3) : coordinate > end - 36 ? Math.min(18, (coordinate - end + 36) / 3) : 0;
|
||||
if (drag.x >= viewport.left - 32 && drag.x <= viewport.right + 32) {
|
||||
if (drag.axis === "column") scroll.scrollLeft += speed(drag.x, viewport.left, viewport.right);
|
||||
// Stop at the table's ends so an edge drag cannot scroll its own drop
|
||||
// target out from under the pointer after the last row becomes visible.
|
||||
const vertical = speed(drag.y, editor.top, editor.bottom);
|
||||
view.scrollDOM.scrollTop += vertical > 0
|
||||
? Math.min(vertical, Math.max(0, viewport.bottom - editor.bottom + 36))
|
||||
: Math.max(vertical, Math.min(0, viewport.top - editor.top - 36));
|
||||
}
|
||||
layout(); updateTarget(); updatePreview();
|
||||
frame = requestAnimationFrame(tick);
|
||||
}
|
||||
function cancel() {
|
||||
const previous = drag;
|
||||
drag = undefined;
|
||||
cancelAnimationFrame(frame);
|
||||
indicator.hidden = true;
|
||||
preview?.remove(); preview = undefined; previewLabel = undefined;
|
||||
wrapper.classList.remove("is-table-dragging");
|
||||
if (previous) {
|
||||
const button = handles.find(handle => handle.axis === previous.axis && handle.index === previous.index)?.button;
|
||||
if (button?.hasPointerCapture(previous.pointer)) button.releasePointerCapture(previous.pointer);
|
||||
}
|
||||
}
|
||||
|
||||
for (const axis of ["column", "row"] as const) {
|
||||
const length = axis === "row" ? table.rows.length : table.rows[0].cells.length;
|
||||
for (let index = axis === "row" ? 1 : 0; index < length; index++) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = `table-drag-handle table-drag-${axis}`;
|
||||
button.dataset.index = String(index);
|
||||
const label = tr(axis === "row" ? "Move row {number}" : "Move column {number}", { number: index + 1 });
|
||||
const tooltip = tr("{label} · Drag to reorder · {keys} to move", { label, keys: axis === "row" ? "↑/↓" : "←/→" });
|
||||
button.setAttribute("aria-label", label);
|
||||
tooltipCleanup.push(attachTooltip(button, () => drag ? "" : tooltip));
|
||||
button.append(actionIcon("grip"));
|
||||
layer.append(button);
|
||||
handles.push({ axis, index, button });
|
||||
button.addEventListener("pointerdown", event => {
|
||||
if (event.button !== 0 || drag) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
focusAxis(axis, index, false);
|
||||
drag = { axis, index, pointer: event.pointerId, x: event.clientX, y: event.clientY, startX: event.clientX, startY: event.clientY, active: false, before: source() };
|
||||
button.setPointerCapture(event.pointerId);
|
||||
}, options);
|
||||
button.addEventListener("lostpointercapture", () => { if (drag) cancel(); }, options);
|
||||
button.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); }, options);
|
||||
button.addEventListener("blur", () => button.removeAttribute("data-pointer-focus"), options);
|
||||
button.addEventListener("keydown", event => {
|
||||
button.removeAttribute("data-pointer-focus");
|
||||
const previous = axis === "row" ? "ArrowUp" : "ArrowLeft", next = axis === "row" ? "ArrowDown" : "ArrowRight";
|
||||
if (![previous, next, " ", "Enter"].includes(event.key)) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (drag) return;
|
||||
if (event.key === previous || event.key === next) commit(axis, index, index + (event.key === previous ? -1 : 1));
|
||||
else focusAxis(axis, index);
|
||||
}, options);
|
||||
}
|
||||
}
|
||||
document.addEventListener("pointermove", event => {
|
||||
if (!drag || event.pointerId !== drag.pointer) return;
|
||||
drag.x = event.clientX; drag.y = event.clientY;
|
||||
if (!drag.active && Math.hypot(drag.x - drag.startX, drag.y - drag.startY) >= 5) {
|
||||
drag.active = true; wrapper.classList.add("is-table-dragging"); createPreview(); tick();
|
||||
}
|
||||
if (drag.active) { event.preventDefault(); updateTarget(); updatePreview(); }
|
||||
}, { ...options, passive: false });
|
||||
document.addEventListener("pointerup", event => {
|
||||
if (!drag || event.pointerId !== drag.pointer) return;
|
||||
drag.x = event.clientX; drag.y = event.clientY; updateTarget();
|
||||
const completed = drag;
|
||||
cancel();
|
||||
if (completed.active && completed.to !== undefined && source() === completed.before) commit(completed.axis, completed.index, completed.to, false);
|
||||
}, options);
|
||||
document.addEventListener("pointercancel", cancel, options);
|
||||
document.addEventListener("keydown", event => {
|
||||
if (drag && event.key === "Escape") { event.preventDefault(); event.stopImmediatePropagation(); cancel(); }
|
||||
}, { ...options, capture: true });
|
||||
window.addEventListener("blur", cancel, options);
|
||||
scroll.addEventListener("scroll", scheduleLayout, options);
|
||||
const observer = new ResizeObserver(scheduleLayout);
|
||||
observer.observe(table); observer.observe(scroll);
|
||||
scheduleLayout();
|
||||
return { destroy() { cancel(); tooltipCleanup.forEach(dispose => dispose()); cancelAnimationFrame(layoutFrame); lifecycle.abort(); observer.disconnect(); controls.delete(table); } };
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import type { DocumentLink } from "./documentLinks";
|
||||
|
||||
/** Keep the caret on the clicked label character when Markdown becomes visible. */
|
||||
export function tableLinkLabelPosition(source: string, link: DocumentLink, offset: number): number {
|
||||
let from = link.targetFrom, to = link.targetTo;
|
||||
if (link.kind === "wiki") {
|
||||
const separator = source.indexOf("|", link.from + 2);
|
||||
from = link.from + 2; to = link.to - 2;
|
||||
if (separator >= 0 && separator < to) {
|
||||
if (separator + 1 < to) from = separator + 1;
|
||||
else to = separator - Number(source[separator - 1] === "\\");
|
||||
}
|
||||
} else if (source[link.from] === "[") {
|
||||
from = link.from + 1;
|
||||
markdownLanguage.parser.parse(source).iterate({ enter(node) {
|
||||
if (node.name === "LinkMark" && node.from > from && node.from < link.targetFrom && source[node.from] === "]") to = node.from;
|
||||
} });
|
||||
}
|
||||
const label = source.slice(from, to);
|
||||
const hidden = new Set<number>();
|
||||
const entities = new Map<number, { to: number; length: number }>();
|
||||
if (link.kind === "wiki") {
|
||||
// Wiki labels are literal text. Table parsing removes escaped pipe marks.
|
||||
for (let i = 0; i < label.length - 1; i++) if (label[i] === "\\" && label[i + 1] === "|") hidden.add(i);
|
||||
} else markdownLanguage.parser.parse(label).iterate({ enter(node) {
|
||||
if (["EmphasisMark", "StrikethroughMark", "CodeMark"].includes(node.name)) {
|
||||
for (let i = node.from; i < node.to; i++) hidden.add(i);
|
||||
} else if (node.name === "Escape") hidden.add(node.from);
|
||||
else if (node.name === "Entity") {
|
||||
const text = document.createElement("textarea");
|
||||
text.innerHTML = label.slice(node.from, node.to);
|
||||
entities.set(node.from, { to: node.to, length: text.value.length });
|
||||
}
|
||||
} });
|
||||
let visible = 0;
|
||||
for (let i = 0; i < label.length; i++) {
|
||||
if (hidden.has(i)) continue;
|
||||
if (visible >= offset) return from + i;
|
||||
const entity = entities.get(i);
|
||||
if (entity) { visible += entity.length; i = entity.to - 1; }
|
||||
else visible++;
|
||||
}
|
||||
return to;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Prec } from "@codemirror/state";
|
||||
import { keymap } from "@codemirror/view";
|
||||
import { tableEditors } from "./tableControls";
|
||||
|
||||
// Tables are atomic in the prose editor. Intercept a movement that would cross
|
||||
// one before CodeMirror skips the widget, and hand focus to its cell editor.
|
||||
export const tableNavigation = Prec.high(keymap.of(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].map(key => ({
|
||||
key,
|
||||
run(view) {
|
||||
const selection = view.state.selection.main;
|
||||
if (!view.hasFocus || !selection.empty || view.state.selection.ranges.length !== 1) return false;
|
||||
const forward = key === "ArrowRight" || key === "ArrowDown";
|
||||
const vertical = key === "ArrowUp" || key === "ArrowDown";
|
||||
const next = vertical ? view.moveVertically(selection, forward) : view.moveByChar(selection, forward);
|
||||
const previews = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")];
|
||||
if (!forward) previews.reverse();
|
||||
for (const root of previews) {
|
||||
const table = tableEditors.get(root);
|
||||
if (!table) continue;
|
||||
const from = view.posAtDOM(root), to = from + table.source.length;
|
||||
const crosses = forward
|
||||
? selection.head <= from && next.head >= from
|
||||
: selection.head >= to && next.head <= to;
|
||||
if (!crosses) continue;
|
||||
const goal = selection.goalColumn ?? next.goalColumn;
|
||||
const x = goal === undefined ? view.coordsAtPos(selection.head)?.left : view.contentDOM.getBoundingClientRect().left + goal;
|
||||
table.enter(forward, vertical ? x : undefined);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
}))));
|
||||
@@ -0,0 +1,129 @@
|
||||
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable.ts";
|
||||
import { plainInlineMarkdown } from "../workspace/noteHtml.ts";
|
||||
|
||||
export type CellPoint = { row: number; column: number };
|
||||
export type CellRange = { anchor: CellPoint; head: CellPoint };
|
||||
export type CellFormat = "bold" | "italic" | "strike" | "highlight" | "code" | "math" | "comment" | "clear";
|
||||
|
||||
export function bounds(range: CellRange) {
|
||||
return { top: Math.min(range.anchor.row, range.head.row), bottom: Math.max(range.anchor.row, range.head.row), left: Math.min(range.anchor.column, range.head.column), right: Math.max(range.anchor.column, range.head.column) };
|
||||
}
|
||||
const sourceRow = (row: number) => row === 0 ? 0 : row + 1;
|
||||
|
||||
export function mapTableCells(source: string, range: CellRange, transform: (text: string) => string): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table) return source;
|
||||
const { top, bottom, left, right } = bounds(range);
|
||||
for (let r = Math.max(0, top); r <= Math.min(bottom, table.rows.length - 2); r++) {
|
||||
for (let c = Math.max(0, left); c <= Math.min(right, table.columns - 1); c++) {
|
||||
source = replaceTableCell(source, sourceRow(r), c, transform(table.rows[sourceRow(r)].cells[c]?.text || ""));
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
export function formatTableCells(source: string, range: CellRange, format: CellFormat): string {
|
||||
if (format === "clear") return mapTableCells(source, range, plainInlineMarkdown);
|
||||
const marker = { bold: "**", italic: "*", strike: "~~", highlight: "==", code: "`", math: "$", comment: "%%" }[format];
|
||||
const wrapped = (text: string) => format === "code" ? /^(`+)(?!`)([\s\S]*[^`])\1(?!`)$/.test(text)
|
||||
: text.startsWith(marker) && text.endsWith(marker) && text.length > marker.length * 2 && !(format === "italic" && text.startsWith("**") && !text.startsWith("***"));
|
||||
let allWrapped = true;
|
||||
mapTableCells(source, range, text => { if (text.trim() && !wrapped(text)) allWrapped = false; return text; });
|
||||
return mapTableCells(source, range, text => {
|
||||
if (!text.trim()) return text;
|
||||
if (wrapped(text)) return allWrapped ? (format === "code" ? plainInlineMarkdown(text) : text.slice(marker.length, -marker.length)) : text;
|
||||
if (format === "code") {
|
||||
const fence = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map(m => m[0].length)) + 1);
|
||||
return `${fence} ${text} ${fence}`;
|
||||
}
|
||||
return marker + text + marker;
|
||||
});
|
||||
}
|
||||
|
||||
export function alignTableCells(source: string, range: CellRange, alignment: "left" | "center" | "right"): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table) return source;
|
||||
const { left, right } = bounds(range);
|
||||
const marker = { left: ":---", center: ":---:", right: "---:" }[alignment];
|
||||
for (let c = Math.min(right, table.columns - 1); c >= Math.max(0, left); c--) {
|
||||
const cell = table.rows[1].cells[c];
|
||||
source = source.slice(0, cell.from) + marker + source.slice(cell.to);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
export function copyTableCells(source: string, range: CellRange): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table) return "";
|
||||
const { top, bottom, left, right } = bounds(range);
|
||||
const quote = (value: string) => /[\t\r\n"]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
|
||||
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);
|
||||
if (table) return table.rows.filter((_, i) => i !== 1).map(row => row.cells.map(cell => cell.text));
|
||||
const rows: string[][] = [[]];
|
||||
let cell = "", quoted = false;
|
||||
text = text.replace(/\r\n?/g, "\n").replace(/\n$/, "");
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const char = text[i];
|
||||
if (char === '"' && (quoted || !cell)) {
|
||||
if (quoted && text[i + 1] === '"') { cell += '"'; i++; }
|
||||
else quoted = !quoted;
|
||||
} else if (!quoted && (char === "\t" || char === "\n")) {
|
||||
rows.at(-1)!.push(cell); cell = "";
|
||||
if (char === "\n") rows.push([]);
|
||||
} else cell += char;
|
||||
}
|
||||
rows.at(-1)!.push(cell);
|
||||
return rows.map(row => row.map(value => value.replace(/\n/g, "<br>").replace(/(\\*)\|/g, (match, slashes: string) => slashes.length % 2 ? match : `${slashes}\\|`)));
|
||||
}
|
||||
|
||||
export function pasteTableCells(source: string, range: CellRange, text: string): string {
|
||||
if (!parseMarkdownTable(source)) return source;
|
||||
const cells = clipboardCells(text), { top, bottom, left, right } = bounds(range);
|
||||
if (cells.length === 1 && cells[0].length === 1) return mapTableCells(source, range, () => cells[0][0]);
|
||||
const gridWidth = Math.max(...cells.map(row => row.length));
|
||||
const height = Math.max(bottom - top + 1, cells.length), width = Math.max(right - left + 1, gridWidth);
|
||||
while (parseMarkdownTable(source)!.columns < left + width) source = appendTableColumn(source);
|
||||
while (parseMarkdownTable(source)!.rows.length - 1 < top + height) source = appendTableRow(source);
|
||||
for (let r = 0; r < height; r++) for (let c = 0; c < width; c++) {
|
||||
source = replaceTableCell(source, sourceRow(top + r), left + c, cells[r % cells.length][c % gridWidth] ?? "");
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
// Whole rows/columns are removed structurally; a partial rectangle shifts cells left.
|
||||
export function deleteTableCells(source: string, range: CellRange): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table) return source;
|
||||
const { top, bottom, left, right } = bounds(range);
|
||||
const allRows = top === 0 && bottom >= table.rows.length - 2;
|
||||
const allColumns = left === 0 && right >= table.columns - 1;
|
||||
if (allRows && allColumns) return source.slice(table.end);
|
||||
const rows = table.rows.flatMap((row, i) => {
|
||||
const r = i === 0 ? 0 : i - 1;
|
||||
if (allColumns && i !== 1 && r >= top && r <= bottom) return [];
|
||||
const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, c) => row.cells[c]?.text || "");
|
||||
if (allRows || (i !== 1 && r >= top && r <= bottom)) {
|
||||
cells.splice(left, right - left + 1);
|
||||
if (!allRows) while (cells.length < table.columns) cells.push("");
|
||||
}
|
||||
return [{ ...row, cells }];
|
||||
});
|
||||
// Deleting the header promotes the first remaining body row.
|
||||
if (allColumns && top === 0) [rows[0], rows[1]] = [rows[1], rows[0]];
|
||||
return rows.map(row => `${row.indent}| ${row.cells.join(" | ")} |`).join(table.eol) + source.slice(table.end);
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { tr } from '../i18n/index.ts';
|
||||
import { keys } from "../ui/shortcuts";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { isolateHistory, redo, undo } from "@codemirror/commands";
|
||||
import type { Editor } from "@tiptap/core";
|
||||
import { useSpellingMenu } from "./spellingMenu";
|
||||
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import { clipboardItems } from "../ui/menuItems";
|
||||
import { cellFormats, tableTextItems, type TableContextActions } from "./tableCellActions";
|
||||
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>();
|
||||
|
||||
export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, view: EditorView, source: () => string, finish: () => void, change: (text: string, structural: boolean) => void, rich: { get: () => Editor | undefined; activate: (cell: HTMLTableCellElement) => void; editSource: (range: { from: number; to: number }) => void }, actions: TableContextActions) {
|
||||
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
|
||||
let range: CellRange | undefined, down: CellPoint | undefined, dragging = false;
|
||||
let menu: HTMLElement | undefined;
|
||||
let pending = false;
|
||||
wrapper.tabIndex = -1;
|
||||
wrapper.contentEditable = "false";
|
||||
const point = (cell: HTMLTableCellElement): CellPoint => ({ row: (cell.parentElement as HTMLTableRowElement).rowIndex, column: cell.cellIndex });
|
||||
function cellAt(target: EventTarget | null) {
|
||||
const cell = target instanceof Element ? target.closest<HTMLTableCellElement>("td, th") : null;
|
||||
return cell?.closest("table") === table ? cell : null;
|
||||
}
|
||||
function closeMenu() { menu?.remove(); menu = undefined; }
|
||||
function clear() {
|
||||
range = undefined; closeMenu();
|
||||
wrapper.classList.remove("has-cell-selection");
|
||||
for (const cell of table.querySelectorAll("th, td")) { cell.classList.remove("is-cell-selected"); cell.removeAttribute("aria-selected"); cell.removeAttribute("data-selection-edges"); }
|
||||
}
|
||||
function select(next: CellRange) {
|
||||
finish();
|
||||
const clamp = (p: CellPoint) => ({ row: Math.max(0, Math.min(table.rows.length - 1, p.row)), column: Math.max(0, Math.min(table.rows[0].cells.length - 1, p.column)) });
|
||||
range = { anchor: clamp(next.anchor), head: clamp(next.head) };
|
||||
const { top, bottom, left, right } = bounds(range);
|
||||
wrapper.classList.add("has-cell-selection");
|
||||
for (const row of table.rows) for (const cell of row.cells) {
|
||||
const selected = row.rowIndex >= top && row.rowIndex <= bottom && cell.cellIndex >= left && cell.cellIndex <= right;
|
||||
cell.classList.toggle("is-cell-selected", selected);
|
||||
cell.setAttribute("aria-selected", String(selected));
|
||||
if (selected) cell.setAttribute("data-selection-edges", [
|
||||
row.rowIndex === top && "top", row.rowIndex === bottom && "bottom",
|
||||
cell.cellIndex === left && "left", cell.cellIndex === right && "right",
|
||||
].filter(Boolean).join(" "));
|
||||
else cell.removeAttribute("data-selection-edges");
|
||||
}
|
||||
document.getSelection()?.removeAllRanges();
|
||||
wrapper.focus({ preventScroll: true });
|
||||
}
|
||||
selections.set(table, select);
|
||||
function apply(transform: (text: string, selected: CellRange) => string, restore?: CellRange) {
|
||||
if (!range) return;
|
||||
const selected = range, from = view.posAtDOM(root);
|
||||
closeMenu(); finish();
|
||||
change(transform(source(), selected), true);
|
||||
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
|
||||
const nextTable = updated?.querySelector("table");
|
||||
if (nextTable) selections.get(nextTable)?.(restore || selected);
|
||||
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;
|
||||
const before = source(), selected = range;
|
||||
closeMenu(); wrapper.focus({ preventScroll: true });
|
||||
try {
|
||||
if (action === "paste") {
|
||||
const text = await navigator.clipboard.readText();
|
||||
if (root.isConnected && source() === before && range === selected) apply((value, target) => pasteTableCells(value, target, text));
|
||||
} else {
|
||||
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 {
|
||||
const status = root.querySelector<HTMLElement>(".table-edit-help");
|
||||
if (status) { status.hidden = false; status.setAttribute("role", "status"); status.textContent = tr("Clipboard unavailable here. Use {shortcut}.", { shortcut: keys(`Mod+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}`) }); }
|
||||
}
|
||||
}
|
||||
function showMenu(x: number, y: number, at = range?.head, textEditor?: Editor) {
|
||||
if (!at) return;
|
||||
closeMenu();
|
||||
const cellRange = { anchor: at, head: at };
|
||||
const returnFocus = () => { closeMenu(); if (textEditor && !textEditor.isDestroyed) textEditor.view.focus(); else wrapper.focus(); };
|
||||
function structural(axis: TableAxis, operation: TableOperation) {
|
||||
range ??= cellRange;
|
||||
const index = axis === "row" ? at!.row : at!.column;
|
||||
const next = { ...at! };
|
||||
if (operation === "previous") next[axis]--;
|
||||
if (operation === "next" || operation === "after" || operation === "duplicate") next[axis]++;
|
||||
apply(text => changeTableStructure(text, axis, index, operation), { anchor: next, head: next });
|
||||
}
|
||||
const row = at.row, column = at.column, lastRow = table.rows.length - 1, lastColumn = table.rows[0].cells.length - 1;
|
||||
const sep: ActionMenuItem = { separator: true };
|
||||
const align = (alignment: "left" | "center" | "right") => {
|
||||
range ??= cellRange;
|
||||
apply((text, selected) => alignTableCells(text, selected, alignment));
|
||||
};
|
||||
const alignmentItems: ActionMenuItem[] = [
|
||||
{ label: tr("Align left"), icon: "left", run: () => align("left") },
|
||||
{ label: tr("Align centre"), icon: "center", run: () => align("center") },
|
||||
{ label: tr("Align right"), icon: "right", run: () => align("right") },
|
||||
].map(item => ({ ...item, title: "Alignment applies to the selected Markdown columns" } as ActionMenuItem));
|
||||
const report = (message: string) => {
|
||||
const status = root.querySelector<HTMLElement>(".table-edit-help");
|
||||
if (status) { status.hidden = false; status.setAttribute("role", "status"); status.textContent = message; status.style.visibility = "visible"; }
|
||||
};
|
||||
const items: ActionMenuItem[] = textEditor ? tableTextItems(textEditor, actions, closeMenu, run => {
|
||||
view.dispatch({ annotations: isolateHistory.of("before") }); run(); view.dispatch({ annotations: isolateHistory.of("after") });
|
||||
}, value => { pending = value; }, report, rich.editSource) : [
|
||||
...clipboardItems({ selected: true, cut: () => void clipboard("cut"), copy: () => void clipboard("copy"), paste: () => void clipboard("paste") }),
|
||||
sep,
|
||||
{ label: tr("Format"), icon: "format", children: cellFormats.map(([label, kind]) => ({ label: tr(label), icon: kind, run: () => format(kind) })) },
|
||||
...alignmentItems,
|
||||
sep, { label: tr("Clear cells"), icon: "clear", run: clearCells, title: tr("Clear selected values and keep the cells.") },
|
||||
{ label: tr("Delete cells"), icon: "trash", run: deleteCells, title: tr("Delete or Backspace removes full rows or columns. Other selections shift cells left.") },
|
||||
];
|
||||
if (textEditor) items.push(sep, { label: tr("Select cell"), icon: "select", title: tr("Select this cell, then use Shift+arrow keys to extend the selection"), run: () => { closeMenu(); select(cellRange); } });
|
||||
items.push(sep,
|
||||
{ label: tr("Row"), icon: "row", children: [
|
||||
{ label: tr("Add row above"), icon: "row-before", disabled: row === 0, title: row === 0 ? tr("The first row is the Markdown header") : undefined, run: () => structural("row", "before") },
|
||||
{ label: tr("Add row below"), icon: "row-after", run: () => structural("row", "after") }, sep,
|
||||
{ label: tr("Move row up"), icon: "up", disabled: row <= 1, run: () => structural("row", "previous") },
|
||||
{ label: tr("Move row down"), icon: "down", disabled: row === 0 || row === lastRow, run: () => structural("row", "next") }, sep,
|
||||
{ label: tr("Duplicate row"), icon: "duplicate", run: () => structural("row", "duplicate") },
|
||||
{ label: tr("Delete row"), icon: "trash", run: () => structural("row", "delete") },
|
||||
] },
|
||||
{ label: tr("Column"), icon: "column", children: [
|
||||
{ label: tr("Add column to the left"), icon: "column-before", run: () => structural("column", "before") },
|
||||
{ label: tr("Add column to the right"), icon: "column-after", run: () => structural("column", "after") }, sep,
|
||||
{ label: tr("Move column left"), icon: "move-left", disabled: column === 0, run: () => structural("column", "previous") },
|
||||
{ label: tr("Move column right"), icon: "move-right", disabled: column === lastColumn, run: () => structural("column", "next") }, sep,
|
||||
...alignmentItems, sep,
|
||||
{ label: tr("Duplicate column"), icon: "duplicate", run: () => structural("column", "duplicate") },
|
||||
{ label: tr("Delete column"), icon: "trash", run: () => structural("column", "delete") },
|
||||
] }, sep,
|
||||
{ label: tr("Sort by column (A to Z)"), icon: "sort-asc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column)); } },
|
||||
{ label: tr("Sort by column (Z to A)"), icon: "sort-desc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column, true)); } },
|
||||
);
|
||||
menu = actionMenu(x, y, items, returnFocus);
|
||||
}
|
||||
table.addEventListener("mousedown", event => {
|
||||
const cell = cellAt(event.target);
|
||||
if (cell && event.button === 2) {
|
||||
if (!useSpellingMenu(event, !range && !!rich.get()?.state.selection.empty)) event.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (!cell || event.button !== 0 || event.ctrlKey || event.metaKey) return;
|
||||
closeMenu(); down = point(cell); dragging = false;
|
||||
if (event.shiftKey) {
|
||||
event.preventDefault(); event.stopImmediatePropagation();
|
||||
const active = table.querySelector<HTMLTableCellElement>(".is-editing");
|
||||
select({ anchor: range?.anchor || (active ? point(active) : down), head: down }); dragging = true;
|
||||
} else clear();
|
||||
}, { ...options, capture: true });
|
||||
document.addEventListener("mousemove", event => {
|
||||
if (!down || !(event.buttons & 1)) return;
|
||||
const cell = cellAt(document.elementFromPoint(event.clientX, event.clientY));
|
||||
if (!cell) return;
|
||||
const head = point(cell);
|
||||
if (dragging || head.row !== down.row || head.column !== down.column) {
|
||||
event.preventDefault(); dragging = true;
|
||||
select({ anchor: range?.anchor || down, head });
|
||||
}
|
||||
}, options);
|
||||
document.addEventListener("mouseup", () => { down = undefined; }, options);
|
||||
table.addEventListener("dragstart", event => event.preventDefault(), options);
|
||||
table.addEventListener("focus", event => { if (range && cellAt(event.target)) clear(); }, { ...options, capture: true });
|
||||
table.addEventListener("click", event => { if (dragging) { event.preventDefault(); event.stopPropagation(); dragging = false; } }, { ...options, capture: true });
|
||||
table.addEventListener("contextmenu", event => {
|
||||
const cell = cellAt(event.target); if (!cell) return;
|
||||
if (useSpellingMenu(event, !range && !!rich.get()?.state.selection.empty)) { closeMenu(); return; }
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (cell.classList.contains("is-cell-selected")) showMenu(event.clientX, event.clientY, point(cell));
|
||||
else {
|
||||
clear(); rich.activate(cell);
|
||||
const current = rich.get();
|
||||
// A context click can arrive before the browser's selectionchange event.
|
||||
// Read the visible word selection before moving focus into the menu.
|
||||
const native = document.getSelection();
|
||||
if (current && native && !native.isCollapsed && native.anchorNode && native.focusNode && current.view.dom.contains(native.anchorNode) && current.view.dom.contains(native.focusNode)) {
|
||||
current.commands.setTextSelection({ from: current.view.posAtDOM(native.anchorNode, native.anchorOffset), to: current.view.posAtDOM(native.focusNode, native.focusOffset) });
|
||||
}
|
||||
if (current?.state.selection.empty) {
|
||||
const hit = current.view.posAtCoords({ left: event.clientX, top: event.clientY });
|
||||
if (hit) current.commands.setTextSelection(hit.pos);
|
||||
}
|
||||
showMenu(event.clientX, event.clientY, point(cell), current);
|
||||
}
|
||||
}, options);
|
||||
document.addEventListener("mousedown", event => { if (!wrapper.contains(event.target as Node) && !menu?.contains(event.target as Node)) { clear(); if (!pending) finish(); } }, options);
|
||||
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 (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;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (mod && ["z", "y"].includes(key)) { closeMenu(); (key === "y" || event.shiftKey ? redo : undo)(view); view.focus(); }
|
||||
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") 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 {
|
||||
const head = { ...range.head };
|
||||
if (event.key === "ArrowLeft") head.column--; if (event.key === "ArrowRight") head.column++;
|
||||
if (event.key === "ArrowUp") head.row--; if (event.key === "ArrowDown") head.row++;
|
||||
select({ anchor: event.shiftKey ? range.anchor : head, head });
|
||||
table.rows[range!.head.row].cells[range!.head.column].scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
}
|
||||
}, options);
|
||||
for (const action of ["copy", "cut", "paste"] as const) wrapper.addEventListener(action, event => {
|
||||
if (!range || !event.clipboardData) return;
|
||||
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));
|
||||
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 => {
|
||||
if (range) return;
|
||||
const text = event.clipboardData?.getData("text/plain") || "";
|
||||
const cell = cellAt(event.target);
|
||||
if (!cell || !text.includes("\t")) return;
|
||||
event.preventDefault(); event.stopPropagation(); select({ anchor: point(cell), head: point(cell) });
|
||||
apply((value, selected) => pasteTableCells(value, selected, text));
|
||||
}, { ...options, capture: true });
|
||||
return { select, keepEditing: () => !!menu || pending, destroy: () => { lifecycle.abort(); closeMenu(); selections.delete(table); } };
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { parseMarkdownTable } from "./markdownTable.ts";
|
||||
import { deleteTableCells } from "./tableSelection.ts";
|
||||
import { plainInlineMarkdown } from "../workspace/noteHtml.ts";
|
||||
|
||||
export type TableAxis = "row" | "column";
|
||||
export type TableOperation = "before" | "after" | "previous" | "next" | "duplicate" | "delete";
|
||||
|
||||
// Indices refer to rendered rows (header = 0), or columns. `to` is the
|
||||
// final position, after removing the source item.
|
||||
export function moveTableAxis(source: string, axis: TableAxis, from: number, to: number): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table) return source;
|
||||
const size = axis === "row" ? table.rows.length - 1 : table.columns;
|
||||
const first = axis === "row" ? 1 : 0;
|
||||
if (![from, to].every(index => Number.isInteger(index) && index >= first && index < size) || from === to) return source;
|
||||
function move<T>(items: T[], start: number, end: number) {
|
||||
items.splice(end, 0, items.splice(start, 1)[0]);
|
||||
return items;
|
||||
}
|
||||
const rows = axis === "row"
|
||||
? move(table.rows.map(row => source.slice(row.from, row.to)), from + 1, to + 1)
|
||||
: table.rows.map(row => {
|
||||
const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, i) => row.cells[i]?.text || "");
|
||||
return `${row.indent}| ${move(cells, from, to).join(" | ")} |`;
|
||||
});
|
||||
return rows.join(table.eol) + source.slice(table.end);
|
||||
}
|
||||
|
||||
export function changeTableStructure(source: string, axis: TableAxis, index: number, operation: TableOperation): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table) return source;
|
||||
const size = axis === "row" ? table.rows.length - 1 : table.columns;
|
||||
if (index < 0 || index >= size) return source;
|
||||
if (operation === "delete") return deleteTableCells(source, axis === "row"
|
||||
? { anchor: { row: index, column: 0 }, head: { row: index, column: table.columns - 1 } }
|
||||
: { anchor: { row: 0, column: index }, head: { row: table.rows.length - 2, column: index } });
|
||||
const moving = operation === "previous" || operation === "next";
|
||||
const other = index + (operation === "previous" ? -1 : 1);
|
||||
// The Markdown header stays a header; row movement and sorting affect the body.
|
||||
if (moving && (other < (axis === "row" ? 1 : 0) || other >= size || (axis === "row" && index === 0))) return source;
|
||||
if (axis === "row") {
|
||||
if (index === 0 && operation === "before") return source;
|
||||
const rows = table.rows.map(row => source.slice(row.from, row.to));
|
||||
const at = index === 0 ? 0 : index + 1;
|
||||
if (moving) [rows[at], rows[other + 1]] = [rows[other + 1], rows[at]];
|
||||
else {
|
||||
const value = operation === "duplicate" ? rows[at] : `${table.rows[0].indent}| ${Array(table.columns).fill("").join(" | ")} |`;
|
||||
rows.splice(index === 0 ? 2 : at + (operation === "before" ? 0 : 1), 0, value);
|
||||
}
|
||||
return rows.join(table.eol) + source.slice(table.end);
|
||||
}
|
||||
const rows = table.rows.map((row, r) => {
|
||||
const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, c) => row.cells[c]?.text || "");
|
||||
if (moving) [cells[index], cells[other]] = [cells[other], cells[index]];
|
||||
else cells.splice(index + (operation === "before" ? 0 : 1), 0, operation === "duplicate" ? cells[index] : r === 1 ? "---" : "");
|
||||
return `${row.indent}| ${cells.join(" | ")} |`;
|
||||
});
|
||||
return rows.join(table.eol) + source.slice(table.end);
|
||||
}
|
||||
|
||||
export function sortTableColumn(source: string, column: number, descending = false): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table || column < 0 || column >= table.columns) return source;
|
||||
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
|
||||
const key = (text: string) => plainInlineMarkdown(text).replace(/<br>/g, " ").replace(/\\([\\`*_[\]~<>!|=$%])/g, "$1").trim();
|
||||
const rows = table.rows.slice(2).map(row => ({ row, key: key(row.cells[column]?.text || "") }));
|
||||
rows.sort((a, b) => !a.key ? (b.key ? 1 : 0) : !b.key ? -1 : collator.compare(a.key, b.key) * (descending ? -1 : 1));
|
||||
return [...table.rows.slice(0, 2), ...rows.map(item => item.row)].map(row => source.slice(row.from, row.to)).join(table.eol) + source.slice(table.end);
|
||||
}
|
||||
@@ -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)}`;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
type Point = { x: number; y: number };
|
||||
const targets = new Map<HTMLElement, (path: string, point: Point) => void>();
|
||||
let highlighted: HTMLElement | undefined;
|
||||
export function registerImageDropTarget(element: HTMLElement, drop: (path: string, point: Point) => void) {
|
||||
targets.set(element, drop);
|
||||
return () => { targets.delete(element); element.classList.remove("image-drop-target"); };
|
||||
}
|
||||
function targetAt(path: string, point: Point) {
|
||||
if (!path || path.endsWith("/")) return;
|
||||
const hit = document.elementFromPoint(point.x, point.y);
|
||||
return [...targets].find(([element]) => element.isConnected && hit && element.contains(hit));
|
||||
}
|
||||
export function highlightImageDrop(path?: string, point?: Point): boolean {
|
||||
highlighted?.classList.remove("image-drop-target");
|
||||
highlighted = path && point ? targetAt(path, point)?.[0] : undefined;
|
||||
highlighted?.classList.add("image-drop-target");
|
||||
return !!highlighted;
|
||||
}
|
||||
export function dropWorkspaceImage(path: string, point: Point): boolean {
|
||||
const target = targetAt(path, point);
|
||||
highlightImageDrop();
|
||||
target?.[1](path, point);
|
||||
return !!target;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<!--
|
||||
Settings → Project Management, and the Project Management settings of the board menu. It is in the main bundle and
|
||||
loads no feature code: the priority levels are in the `projectManagement` settings section (`pmSettings.ts`), and
|
||||
the default board is in `.runestone/pm/workspace.json` of the workspace (`pmBoards.ts`). It shows only while
|
||||
Project Management is on. Each change saves at once.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { message, t } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { PRIORITY_LEVELS, onProjectManagementChange, readProjectManagement, writeProjectManagement, type PriorityLevels, type ProjectManagementSettings } from "./pmSettings";
|
||||
import { readBoardCatalog, writeDefaultBoard, type BoardSummary } from "./pmBoards";
|
||||
|
||||
let { compact = false }: { compact?: boolean } = $props();
|
||||
// The errors here are catalog keys without values (pmBoards.ts) or host text. The full `errorText()` of the feature
|
||||
// (pm/ui/text.ts) is not necessary, and this component must load no feature module.
|
||||
const errorText = (reason: unknown) => $t(reason instanceof Error ? reason.message : String(reason));
|
||||
|
||||
const levelNames: Record<PriorityLevels, string> = { 2: message("2 — High and Low"), 3: message("3 — High, Medium, and Low"), 5: message("5 — Highest through Lowest") };
|
||||
let settings = $state<ProjectManagementSettings>(readProjectManagement());
|
||||
let boards = $state<BoardSummary[]>([]);
|
||||
let defaultBoard = $state("");
|
||||
let boardsReady = $state(false);
|
||||
let boardNote = $state("");
|
||||
let saving = $state(false);
|
||||
let notice = $state("");
|
||||
let error = $state("");
|
||||
let closeMenu = () => {};
|
||||
let disposed = false;
|
||||
const active = $derived(boards.filter(board => !board.archived));
|
||||
const boardName = $derived(defaultBoard ? active.find(board => board.id === defaultBoard)?.name ?? $t("Unavailable board (opens All tasks)") : $t("All tasks"));
|
||||
|
||||
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
||||
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
||||
}
|
||||
|
||||
function saveLevels(priorityLevels: PriorityLevels) {
|
||||
error = "";
|
||||
settings = { ...settings, priorityLevels };
|
||||
writeProjectManagement(settings).then(() => { notice = $t("Changes saved."); })
|
||||
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); notice = ""; settings = readProjectManagement(); });
|
||||
}
|
||||
|
||||
async function saveDefault(id: string) {
|
||||
const previous = defaultBoard;
|
||||
error = ""; saving = true; defaultBoard = id;
|
||||
try { await writeDefaultBoard(id || null); if (!disposed) notice = $t("Changes saved."); }
|
||||
catch (reason) { if (!disposed) { defaultBoard = previous; notice = ""; error = errorText(reason); } }
|
||||
finally { saving = false; }
|
||||
}
|
||||
|
||||
async function readBoards() {
|
||||
try {
|
||||
const catalog = await readBoardCatalog();
|
||||
if (disposed) return;
|
||||
boards = catalog.boards;
|
||||
defaultBoard = catalog.defaultBoardId ?? "";
|
||||
boardsReady = true;
|
||||
boardNote = "";
|
||||
} catch (reason) {
|
||||
if (!disposed) boardNote = /no workspace/i.test(String(reason)) ? $t("Open a workspace to choose its default board.") : errorText(reason);
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
void readBoards();
|
||||
return onProjectManagementChange(() => { settings = readProjectManagement(); });
|
||||
});
|
||||
onDestroy(() => { disposed = true; closeMenu(); });
|
||||
</script>
|
||||
|
||||
<div class="pm-settings">
|
||||
{#if !compact}
|
||||
<h2>{$t("Project Management")}</h2>
|
||||
<p class="intro">{$t("The boards of each workspace stay in {folder} in the workspace.", { folder: ".runestone/pm" })}</p>
|
||||
{/if}
|
||||
<div class="card">
|
||||
<div class="setting-row">
|
||||
<div><span class="name" id="pm-priority-label">{$t("Priority levels")}</span><p id="pm-priority-description">{$t("Existing card priorities stay unchanged when you change this setting.")}</p></div>
|
||||
<button class="picker" type="button" aria-label={$t("Priority levels")} aria-describedby="pm-priority-description" aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Priority levels"), PRIORITY_LEVELS.map(levels => ({ label: $t(levelNames[levels]), checked: settings.priorityLevels === levels, run: () => saveLevels(levels) })))}>
|
||||
{$t(levelNames[settings.priorityLevels])}<Icon icon="chevron-down" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><span class="name" id="pm-default-label">{$t("Default board")}</span><p id="pm-default-description">{boardNote || $t("Choose the board that opens in this workspace. Restored tabs keep their board.")}</p></div>
|
||||
<button class="picker" type="button" aria-label={$t("Default board")} aria-describedby="pm-default-description" aria-haspopup="menu" disabled={!boardsReady || saving}
|
||||
onclick={event => picker(event, $t("Default board"), [
|
||||
{ label: $t("All tasks"), checked: !defaultBoard, run: () => void saveDefault("") },
|
||||
...active.map(board => ({ label: board.name, checked: defaultBoard === board.id, run: () => void saveDefault(board.id) })),
|
||||
])}>
|
||||
{boardName}<Icon icon="chevron-down" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<p class="saved" role="status">{notice}</p>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.pm-settings { min-width: 0; }
|
||||
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
||||
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
||||
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
|
||||
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
|
||||
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||
.name { font-weight: 500; color: var(--rs-text); }
|
||||
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
|
||||
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); box-sizing: border-box; max-width: 100%; min-width: 160px; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: left; cursor: pointer; }
|
||||
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
|
||||
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
.picker:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
|
||||
.error { color: var(--rs-error); margin-top: 10px; }
|
||||
</style>
|
||||
@@ -0,0 +1,39 @@
|
||||
<script lang="ts">
|
||||
// The place of the terminal panel in the workbench and in the terminal window. It is in the main bundle.
|
||||
// The first mount loads the Terminal feature (xterm included). An unmount closes the sessions of this panel.
|
||||
import { onMount } from "svelte";
|
||||
import { t } from "$lib/i18n";
|
||||
import { terminalInstance, type TerminalAction, type TerminalMount, type TerminalProps } from "./terminalHost";
|
||||
let props: TerminalProps = $props();
|
||||
let container: HTMLDivElement;
|
||||
let mounted = $state.raw<TerminalMount>();
|
||||
let loading = $state(true);
|
||||
let error = $state("");
|
||||
let ready: Promise<TerminalMount | undefined> = Promise.resolve(undefined);
|
||||
onMount(() => {
|
||||
let disposed = false;
|
||||
ready = terminalInstance().then(instance => {
|
||||
if (disposed) return undefined;
|
||||
mounted = instance.mountDock(container, { ...props });
|
||||
return mounted;
|
||||
}).catch(reason => { if (!disposed) error = String(reason); return undefined; }).finally(() => { loading = false; });
|
||||
return () => {
|
||||
disposed = true;
|
||||
const current = mounted;
|
||||
mounted = undefined;
|
||||
void current?.dispose().catch(reason => console.error("The terminal panel did not close cleanly.", reason));
|
||||
};
|
||||
});
|
||||
$effect(() => { mounted?.update({ ...props }); });
|
||||
/** Run a terminal action. It waits for the first load. */
|
||||
export async function command(action: Exclude<TerminalAction, "toggle">) { await (await ready)?.command(action); }
|
||||
</script>
|
||||
{#if error}<p class="error" role="alert">{$t("The terminal could not start: {error}", { error })}</p>{/if}
|
||||
{#if loading}<p class="loading">{$t("Loading the terminal…")}</p>{/if}
|
||||
<div class="terminal-host" bind:this={container}></div>
|
||||
<style>
|
||||
.terminal-host { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }
|
||||
.error, .loading { margin: 0; padding: 7px 12px; font-size: 12px; }
|
||||
.error { color: var(--rs-error); }
|
||||
.loading { color: var(--rs-text-dim); }
|
||||
</style>
|
||||
@@ -0,0 +1,113 @@
|
||||
<!--
|
||||
Settings → Terminal. It is in the main bundle and loads no feature code, so it does not load xterm.
|
||||
It shows only while Terminal is on. Each change saves at once to the `terminal` section, and open terminals take it.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { FONT_SIZE, SCROLLBACK, onTerminalChange, readTerminal, writeTerminal, type TerminalSettings } from "./terminalSettings";
|
||||
|
||||
type Profile = { id: string; title: string; kind: string };
|
||||
const initial = readTerminal();
|
||||
let settings = $state<TerminalSettings>(initial);
|
||||
let fontSize = $state<number | undefined>(initial.fontSize);
|
||||
let scrollback = $state<number | undefined>(initial.scrollback);
|
||||
let profiles = $state<Profile[]>([]);
|
||||
let profileNote = $state("");
|
||||
let message = $state("");
|
||||
let error = $state("");
|
||||
let closeMenu = () => {};
|
||||
/** The shells that a new terminal can use. The Node.js debug terminal is not a default. */
|
||||
const shells = $derived(profiles.filter(profile => profile.kind !== "node"));
|
||||
const current = $derived(shells.find(profile => profile.id === settings.defaultProfile) ?? shells[0]);
|
||||
|
||||
function read() {
|
||||
settings = readTerminal();
|
||||
fontSize = settings.fontSize;
|
||||
scrollback = settings.scrollback;
|
||||
}
|
||||
function save(next: TerminalSettings) {
|
||||
error = "";
|
||||
settings = next;
|
||||
writeTerminal(next).then(() => { message = tr("Changes saved."); })
|
||||
.catch(() => { error = tr("Could not save these settings. Your previous settings still apply. Try again."); message = ""; });
|
||||
}
|
||||
function changeNumber(value: number | undefined, range: { min: number; max: number }, key: "fontSize" | "scrollback") {
|
||||
if (typeof value !== "number" || !Number.isInteger(value) || value < range.min || value > range.max) {
|
||||
error = tr("Choose a whole number from {min} to {max}.", { min: range.min.toLocaleString(), max: range.max.toLocaleString() });
|
||||
message = "";
|
||||
return;
|
||||
}
|
||||
save({ ...settings, [key]: value });
|
||||
}
|
||||
function profileMenu(event: MouseEvent) {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: tr("Default terminal profile"), parent: anchor.closest("dialog") ?? undefined,
|
||||
items: shells.map(profile => ({ label: profile.title, icon: "code", radio: true, checked: current?.id === profile.id,
|
||||
run: () => save({ ...settings, defaultProfile: profile.id }) })) }).close;
|
||||
}
|
||||
onMount(() => {
|
||||
const stop = onTerminalChange(read);
|
||||
if (!isTauri()) profileNote = tr("The desktop app lists the installed shells.");
|
||||
else invoke<Profile[]>("pty_profiles").then(found => {
|
||||
profiles = found;
|
||||
if (!found.some(profile => profile.kind !== "node")) profileNote = tr("RuneStone found no supported shells on PATH.");
|
||||
}).catch(reason => { profileNote = tr("RuneStone could not list the shells: {error}", { error: String(reason) }); });
|
||||
return stop;
|
||||
});
|
||||
onDestroy(() => closeMenu());
|
||||
</script>
|
||||
|
||||
<div class="terminal-settings">
|
||||
<h2>{$t("Terminal")}</h2>
|
||||
<p class="intro">{$t("Font, scrollback, and cursor apply to open terminals. The default profile applies to new terminals.")}</p>
|
||||
<div class="card">
|
||||
<div class="setting-row">
|
||||
<div><span class="name" id="terminal-profile-label">{$t("Default profile")}</span><p id="terminal-profile-description">{profileNote || $t("The shell of a new terminal.")}</p></div>
|
||||
<button class="picker" type="button" aria-label={$t("Default profile")} aria-describedby="terminal-profile-description" aria-haspopup="menu" disabled={!shells.length} onclick={profileMenu}>
|
||||
{current?.title ?? $t("No shell")}<Icon icon="chevron-down" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="terminal-font-size">{$t("Font size")}</label><p id="terminal-font-description">{$t("From {min} to {max} pixels.", { min: FONT_SIZE.min, max: FONT_SIZE.max })}</p></div>
|
||||
<input id="terminal-font-size" type="number" min={FONT_SIZE.min} max={FONT_SIZE.max} step="1" required aria-describedby="terminal-font-description" bind:value={fontSize} onchange={() => changeNumber(fontSize, FONT_SIZE, "fontSize")} />
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="terminal-scrollback">{$t("Scrollback lines")}</label><p id="terminal-scrollback-description">{$t("The lines that a terminal keeps above the screen, from {min} to {max}.", { min: SCROLLBACK.min.toLocaleString(), max: SCROLLBACK.max.toLocaleString() })}</p></div>
|
||||
<input id="terminal-scrollback" type="number" min={SCROLLBACK.min} max={SCROLLBACK.max} step="100" required aria-describedby="terminal-scrollback-description" bind:value={scrollback} onchange={() => changeNumber(scrollback, SCROLLBACK, "scrollback")} />
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="terminal-cursor-blink">{$t("Blink cursor")}</label><p id="terminal-blink-description">{$t("The cursor blinks in the focused terminal.")}</p></div>
|
||||
<input id="terminal-cursor-blink" class="rs-switch" type="checkbox" role="switch" aria-describedby="terminal-blink-description" checked={settings.cursorBlink} onchange={event => save({ ...settings, cursorBlink: event.currentTarget.checked })} />
|
||||
</div>
|
||||
</div>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<p class="saved" role="status">{message}</p>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.terminal-settings { min-width: 0; }
|
||||
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
||||
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
||||
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
|
||||
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
|
||||
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||
.setting-row label, .name { font-weight: 500; color: var(--rs-text); }
|
||||
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
|
||||
input[type=number], .picker { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
input[type=number] { width: 96px; }
|
||||
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); max-width: 100%; min-width: 160px; text-align: left; cursor: pointer; }
|
||||
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
|
||||
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
:is(.picker, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
|
||||
.error { color: var(--rs-error); margin-top: 10px; }
|
||||
</style>
|
||||
@@ -0,0 +1,295 @@
|
||||
<!--
|
||||
Appearance → Background. The source is a folder (a slideshow), one image, or none. The folder layout and the order
|
||||
are in the `background` settings section. The image and its layout stay in `appearance.newTabBackground`.
|
||||
This component also works in the settings window, where the slideshow does not run. It sends Next to every window.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { onSettingsChange } from "$lib/settings/store";
|
||||
import { featureSwitches } from "$lib/features/state";
|
||||
import { readBoardCatalog } from "../pmBoards";
|
||||
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance";
|
||||
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
|
||||
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
|
||||
import { folderHost, readSavedImage, sendBackgroundCommand } from "./sources";
|
||||
import { imageNames } from "./imageSettings";
|
||||
import ImageEditor from "./ImageEditor.svelte";
|
||||
|
||||
/** The background targets of single boards need a UUID board ID. */
|
||||
const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
let settings = $state<BackgroundSettings>(readBackground());
|
||||
let appearance = $state<Appearance>(readAppearance());
|
||||
let folder = $state<string | null>(null);
|
||||
let folderNote = $state("");
|
||||
let boards = $state<{ id: string; name: string }[]>([]);
|
||||
let boardsNote = $state("");
|
||||
let previewUrl = $state("");
|
||||
let error = $state("");
|
||||
let imageInput: HTMLInputElement;
|
||||
let imageRevision = 0;
|
||||
let boardRevision = 0;
|
||||
let previewKey = "";
|
||||
let closeMenu = () => {};
|
||||
let disposed = false;
|
||||
|
||||
const image = $derived(appearance.newTabBackground);
|
||||
const layout = $derived<BackgroundLayout | null>(settings.source === "folder" ? normalizeLayout(settings) : settings.source === "image" && hasImage(appearance) ? normalizeLayout(image) : null);
|
||||
const sourceLabels = $derived<Record<BackgroundSource, string>>({ folder: $t("Folder"), image: $t("Image"), none: $t("None") });
|
||||
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
|
||||
const sizeLabels = $derived([$t("Fill"), $t("Fit"), $t("Actual size")]);
|
||||
const orderLabels = $derived({ name: $t("File name"), random: $t("Random") });
|
||||
const targets = $derived([
|
||||
{ id: "app", name: $t("The workspace and new tabs") },
|
||||
{ id: "pm-all", name: $t("All Project Management boards") },
|
||||
...boards.map(board => ({ id: `pm-board:${board.id}`, name: $t("Board: {name}", { name: board.name }) })),
|
||||
// Keep saved targets without a current board, so that the user can remove them.
|
||||
...settings.targets.filter(id => id.startsWith("pm-board:") && !boards.some(board => `pm-board:${board.id}` === id))
|
||||
.map(id => ({ id, name: $t("Unavailable board: {id}", { id: id.slice(9) }) })),
|
||||
]);
|
||||
|
||||
const report = (reason: unknown) => { if (!disposed) error = reason instanceof Error ? reason.message : String(reason); };
|
||||
|
||||
function save(next: BackgroundSettings) {
|
||||
settings = next; error = "";
|
||||
writeBackground(next).catch(() => report(tr("Could not save the background settings.")));
|
||||
}
|
||||
|
||||
function saveImageAppearance(next: Appearance) {
|
||||
try {
|
||||
saveAppearance(next).catch(() => report(tr("Could not save appearance settings.")));
|
||||
appearance = readAppearance(); error = ""; return true;
|
||||
} catch { report(tr("Could not save appearance settings.")); return false; }
|
||||
}
|
||||
|
||||
function changeLayout(patch: Partial<BackgroundLayout>) {
|
||||
if (settings.source === "folder") save({ ...settings, ...patch });
|
||||
else if (image) saveImageAppearance({ ...appearance, newTabBackground: { ...image, ...patch } });
|
||||
}
|
||||
|
||||
function changeOverlay(input: HTMLInputElement) {
|
||||
const percent = input.valueAsNumber;
|
||||
if (!Number.isFinite(percent)) return;
|
||||
changeLayout({ overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 });
|
||||
}
|
||||
|
||||
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
||||
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
||||
}
|
||||
|
||||
async function chooseSource(source: BackgroundSource) {
|
||||
error = "";
|
||||
if (source === "folder" && !folder) { await chooseFolder(); return; }
|
||||
if (source === "image" && !hasImage(appearance)) { imageInput.click(); return; }
|
||||
save({ ...settings, source });
|
||||
}
|
||||
|
||||
async function chooseFolder() {
|
||||
try {
|
||||
const chosen = await folderHost.choose(tr("Choose the background folder"));
|
||||
if (!chosen || disposed) return;
|
||||
folder = chosen;
|
||||
save({ ...settings, source: "folder" });
|
||||
await sendBackgroundCommand("reload");
|
||||
void inspectFolder();
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
async function removeFolder() {
|
||||
try {
|
||||
await folderHost.clear();
|
||||
folder = null; folderNote = "";
|
||||
if (settings.source === "folder") save({ ...settings, source: "none" });
|
||||
await sendBackgroundCommand("reload");
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
/** Count the images of the folder, so that the user sees a problem at once. */
|
||||
async function inspectFolder() {
|
||||
if (!folder) { folderNote = ""; return; }
|
||||
try {
|
||||
const count = imageNames(await folderHost.list()).length;
|
||||
if (!disposed) folderNote = count ? tr(count === 1 ? "{count} image." : "{count} images.", { count }) : tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.");
|
||||
} catch (reason) { if (!disposed) folderNote = reason instanceof Error ? reason.message : String(reason); }
|
||||
}
|
||||
|
||||
async function importImage(file?: File) {
|
||||
if (!file) return;
|
||||
const revision = ++imageRevision;
|
||||
try {
|
||||
if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)) throw new Error(tr("Choose a PNG, JPEG, WebP, or GIF image."));
|
||||
const imageId = await saveBackgroundImage(file);
|
||||
if (revision !== imageRevision) { await removeBackgroundImage(imageId); return; }
|
||||
const old = appearance.newTabBackground?.imageId;
|
||||
if (saveImageAppearance({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
|
||||
if (settings.source !== "image") save({ ...settings, source: "image" });
|
||||
if (old) await removeBackgroundImage(old);
|
||||
} else await removeBackgroundImage(imageId);
|
||||
} catch (reason) { if (revision === imageRevision) report(reason); }
|
||||
finally { if (revision === imageRevision) imageInput.value = ""; }
|
||||
}
|
||||
|
||||
async function removeImage() {
|
||||
imageRevision++;
|
||||
const old = appearance.newTabBackground?.imageId;
|
||||
if (saveImageAppearance({ ...appearance, newTabBackground: undefined }) && old) {
|
||||
try { await removeBackgroundImage(old); } catch { report(tr("Could not remove the saved image from storage.")); }
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTarget(id: string, on: boolean) {
|
||||
save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) });
|
||||
}
|
||||
|
||||
/** The active boards of `.runestone/pm/workspace.json`. It needs no Project Management code. */
|
||||
async function discoverBoards(on: boolean) {
|
||||
const revision = ++boardRevision;
|
||||
if (!on) {
|
||||
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const catalog = await readBoardCatalog();
|
||||
if (disposed || revision !== boardRevision) return;
|
||||
boards = catalog.boards.filter(board => !board.archived && boardId.test(board.id)).map(board => ({ id: board.id, name: board.name }));
|
||||
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
|
||||
} catch (reason) {
|
||||
if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(reason) });
|
||||
}
|
||||
}
|
||||
|
||||
/** The preview of the saved image. It uses its own blob URL, so it works in every window. */
|
||||
async function updatePreview() {
|
||||
const saved = settings.source === "image" ? appearance.newTabBackground : undefined;
|
||||
const key = saved && hasImage(appearance) ? saved.imageId ?? `${saved.image?.length}:${saved.image?.slice(-48)}` : "";
|
||||
if (key === previewKey) return;
|
||||
previewKey = key;
|
||||
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
||||
previewUrl = "";
|
||||
if (!key || !saved) return;
|
||||
try {
|
||||
const url = URL.createObjectURL(await readSavedImage(saved));
|
||||
if (disposed || previewKey !== key) { URL.revokeObjectURL(url); return; }
|
||||
previewUrl = url;
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
const overlayShade = $derived(layout ? `linear-gradient(rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}),rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}))` : "none");
|
||||
|
||||
$effect(() => { void settings.source; void appearance.newTabBackground; void updatePreview(); });
|
||||
|
||||
onMount(() => {
|
||||
const read = () => { settings = readBackground(); appearance = readAppearance(); };
|
||||
const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), featureSwitches.subscribe(switches => { void discoverBoards(switches.pm); })];
|
||||
void folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; });
|
||||
return () => stops.forEach(stop => stop());
|
||||
});
|
||||
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
|
||||
</script>
|
||||
|
||||
<div class="background-settings">
|
||||
<div class="card">
|
||||
<div class="setting-row"><span>{$t("Background source")}</span><button class="picker" aria-label={$t("Background source")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Background source"), (["folder", "image", "none"] as const).map(source => ({ label: sourceLabels[source], checked: settings.source === source, run: () => void chooseSource(source) })))}>{sourceLabels[settings.source]}<Icon icon="chevron-down" /></button></div>
|
||||
{#if settings.source === "folder"}
|
||||
<div class="setting-row folder-row"><label for="background-folder">{$t("Image folder")}</label><div class="controls folder-controls">
|
||||
<input id="background-folder" readonly value={folder ?? ""} title={folder ?? ""} placeholder={$t("No folder selected")} />
|
||||
<button onclick={() => void chooseFolder()}><Icon icon="folder-open" />{$t("Choose folder…")}</button>
|
||||
{#if folder}<button onclick={() => void removeFolder()}>{$t("Remove folder")}</button>{/if}
|
||||
</div></div>
|
||||
<div class="setting-row"><label for="background-seconds">{$t("Seconds per image")}</label><input id="background-seconds" type="number" min="1" max="86400" step="1" value={settings.seconds}
|
||||
onchange={event => { if (event.currentTarget.reportValidity()) save({ ...settings, seconds: event.currentTarget.valueAsNumber }); }} /></div>
|
||||
<div class="setting-row"><span>{$t("Image order")}</span><button class="picker" aria-label={$t("Image order")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image order"), (["name", "random"] as const).map(order => ({ label: orderLabels[order], checked: settings.order === order, run: () => save({ ...settings, order }) })))}>{orderLabels[settings.order]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Slideshow")}</span><div class="controls">
|
||||
<button onclick={() => void sendBackgroundCommand("next").catch(report)}><Icon icon="arrow-right" />{$t("Next image")}</button>
|
||||
<button aria-pressed={settings.paused} onclick={() => save({ ...settings, paused: !settings.paused })}>{settings.paused ? $t("Resume slideshow") : $t("Pause slideshow")}</button>
|
||||
</div></div>
|
||||
{:else if settings.source === "image"}
|
||||
<div class="background-preview" role="img" aria-label={$t("Background image preview")}
|
||||
style:background-image={previewUrl ? `${overlayShade}, url("${previewUrl}")` : "none"}
|
||||
style:background-size={layout ? `100% 100%, ${layout.size}` : undefined}
|
||||
style:background-position={layout ? `center, ${layout.position}` : undefined}><span>{$t("Background")}</span></div>
|
||||
<div class="actions">
|
||||
<button onclick={() => imageInput.click()}>{$t("Choose image…")}</button>
|
||||
{#if image}<button onclick={() => void removeImage()}>{$t("Remove image")}</button>{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{#if layout}
|
||||
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image position"), BACKGROUND_POSITIONS.map((value, index) => ({ label: positionLabels[index], checked: layout?.position === value, run: () => changeLayout({ position: value }) })))}>{positionLabels[BACKGROUND_POSITIONS.indexOf(layout.position)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image size"), BACKGROUND_SIZES.map((value, index) => ({ label: sizeLabels[index], checked: layout?.size === value, run: () => changeLayout({ size: value }) })))}>{sizeLabels[BACKGROUND_SIZES.indexOf(layout.size)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="controls overlay-controls">
|
||||
<input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round(layout.overlay * 100)} oninput={event => changeOverlay(event.currentTarget)} />
|
||||
<label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round(layout.overlay * 100)}
|
||||
oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((layout?.overlay ?? 0) * 100)); }} /><span>%</span></label>
|
||||
</div></div>
|
||||
{/if}
|
||||
</div>
|
||||
<input bind:this={imageInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importImage(event.currentTarget.files?.[0])} />
|
||||
{#if settings.source === "folder"}
|
||||
<p>{$t("Add PNG, JPEG, GIF, or WebP images to the folder. Portrait images show in full over a blurred fill.")}</p>
|
||||
{#if folderNote}<p role="status">{folderNote}</p>{/if}
|
||||
{:else if settings.source === "image"}
|
||||
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image stays on this device.")}</p>
|
||||
{:else}
|
||||
<p>{$t("Choose a folder for a slideshow, or one image.")}</p>
|
||||
{/if}
|
||||
{#if layout}<p>{$t("Move the overlay left to lighten the image or right to darken it.")}</p>{/if}
|
||||
{#if settings.source === "folder" && folder}
|
||||
<ImageEditor {settings} />
|
||||
{/if}
|
||||
{#if settings.source !== "none"}
|
||||
<fieldset class="targets">
|
||||
<legend>{$t("Show the background in")}</legend>
|
||||
{#each targets as target (target.id)}
|
||||
<label class="check"><input type="checkbox" checked={settings.targets.includes(target.id)} onchange={event => toggleTarget(target.id, event.currentTarget.checked)} /><span>{target.name}</span></label>
|
||||
{/each}
|
||||
{#if boardsNote}<p>{boardsNote}</p>{/if}
|
||||
</fieldset>
|
||||
{/if}
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.background-settings { display: grid; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.card { padding: 0 var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); min-width: 0; }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; min-width: 0; }
|
||||
.card > * + * { border-top: 1px solid var(--rs-border); }
|
||||
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; max-width: 100%; }
|
||||
.folder-controls { flex: 1 1 320px; justify-content: flex-end; }
|
||||
.folder-controls input { flex: 1 1 160px; min-width: 120px; width: 0; }
|
||||
input:not([type=checkbox]):not([type=range]), button { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
button { display: inline-flex; align-items: center; gap: 6px; background: var(--rs-bg-elevated); cursor: pointer; }
|
||||
button:hover { background: var(--rs-bg-active); }
|
||||
button[aria-pressed="true"] { border-color: var(--rs-accent); }
|
||||
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
.picker { max-width: 100%; background: var(--rs-bg); }
|
||||
input[type=number] { width: 88px; }
|
||||
:is(button, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; }
|
||||
.background-preview { height: 120px; margin-top: var(--rs-settings-row-padding); background-color: var(--rs-bg); background-repeat: no-repeat; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); display: grid; place-items: center; }
|
||||
.background-preview span { padding: 8px 14px; background: var(--rs-bg-elevated); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range] { width: 160px; max-width: 100%; min-width: 0; appearance: none; background: transparent; height: var(--rs-settings-control-height); margin: 0; cursor: pointer; }
|
||||
.overlay-controls input[type=range]::-webkit-slider-runnable-track { height: 6px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; margin-top: -7px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
||||
.overlay-controls input[type=range]::-moz-range-track { height: 4px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range]::-moz-range-thumb { width: 14px; height: 14px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
||||
.overlay-controls input[type=range]:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; border-radius: var(--rs-control-radius); }
|
||||
.overlay-value { display: flex; align-items: center; gap: 4px; }
|
||||
.overlay-value input { width: 64px; }
|
||||
.targets { display: grid; gap: 2px; min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
||||
.targets legend { padding: 0 4px; color: var(--rs-text); }
|
||||
.check { display: flex; align-items: center; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); overflow-wrap: anywhere; }
|
||||
.check input { flex-shrink: 0; accent-color: var(--rs-accent); }
|
||||
[role=alert] { color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,227 @@
|
||||
<!--
|
||||
The appearance of one image of the folder: fit, position, and overlay. It saves the sidecar file of the folder
|
||||
(`.runestone-backgrounds.json`) only when the file did not change since the read. Then every window reads it again.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, untrack } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { BACKGROUND_POSITIONS } from "$lib/theme/appearance";
|
||||
import { normalizeLayout, type BackgroundSettings } from "../backgroundSettings";
|
||||
import { folderHost, sendBackgroundCommand } from "./sources";
|
||||
import { imageAppearance, imageFits, imageNames, parseImageSettings, sidecarName, type ImageAppearance, type ImageSettings } from "./imageSettings";
|
||||
|
||||
let { settings }: { settings: BackgroundSettings } = $props();
|
||||
|
||||
let names = $state<string[]>([]);
|
||||
let selected = $state("");
|
||||
let query = $state("");
|
||||
let pickerOpen = $state(false);
|
||||
let draft = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
||||
let baseline = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
||||
let saved = $state<ImageSettings>({ schema: 1, images: {} });
|
||||
let source: string | null = null;
|
||||
let url = $state("");
|
||||
let portrait = false;
|
||||
let loaded = $state(false);
|
||||
let busy = $state(false);
|
||||
let status = $state({ text: "", error: false });
|
||||
let generation = 0;
|
||||
let closed = false;
|
||||
let closeMenu = () => {};
|
||||
let trigger: HTMLButtonElement | undefined = $state();
|
||||
let search: HTMLInputElement | undefined = $state();
|
||||
const pickerId = $props.id();
|
||||
|
||||
const filtered = $derived(names.filter(name => name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())));
|
||||
const fitLabels = $derived<Record<string, string>>({ cover: $t("Fill"), contain: $t("Fit"), auto: $t("Actual size"), blurred: $t("Full image with blurred fill") });
|
||||
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
|
||||
const changed = $derived(draft.fit !== baseline.fit || draft.position !== baseline.position || draft.overlay !== baseline.overlay);
|
||||
|
||||
const report = (reason: unknown) => { if (!closed) status = { text: reason instanceof Error ? reason.message : String(reason), error: true }; };
|
||||
|
||||
/** The values that differ from the inherited appearance. Only these go to the file. */
|
||||
function changes(): Partial<ImageAppearance> {
|
||||
return {
|
||||
...(draft.fit !== baseline.fit ? { fit: draft.fit } : {}),
|
||||
...(draft.position !== baseline.position ? { position: draft.position } : {}),
|
||||
...(draft.overlay !== baseline.overlay ? { overlay: draft.overlay } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const revision = ++generation;
|
||||
loaded = false; pickerOpen = false; names = [];
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
url = "";
|
||||
try {
|
||||
const [text, list] = await Promise.all([folderHost.readSidecar(), folderHost.list()]);
|
||||
if (closed || revision !== generation) return;
|
||||
saved = parseImageSettings(text); source = text;
|
||||
names = imageNames(list);
|
||||
if (!names.includes(selected)) selected = names[0] ?? "";
|
||||
if (selected) await choose(selected);
|
||||
else status = { text: tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."), error: false };
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
async function choose(name: string) {
|
||||
const revision = ++generation;
|
||||
selected = name; loaded = false;
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
url = "";
|
||||
try {
|
||||
const next = URL.createObjectURL(await folderHost.read(name));
|
||||
try {
|
||||
const image = new Image(); image.src = next; await image.decode();
|
||||
if (closed || revision !== generation) { URL.revokeObjectURL(next); return; }
|
||||
portrait = image.naturalHeight > image.naturalWidth;
|
||||
} catch (error) { URL.revokeObjectURL(next); throw error; }
|
||||
url = next;
|
||||
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
||||
baseline = { ...draft };
|
||||
loaded = true;
|
||||
status = { text: saved.images[name] ? tr("Saved appearance.") : tr("Default appearance."), error: false };
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
/** A change of the folder layout changes the inherited values. Keep the edits of the user. */
|
||||
function inherit() {
|
||||
if (!loaded) return;
|
||||
const next = imageAppearance(normalizeLayout(settings), saved.images[selected], portrait);
|
||||
if (next.fit === baseline.fit && next.position === baseline.position && next.overlay === baseline.overlay) return;
|
||||
const edited = changes();
|
||||
baseline = next;
|
||||
draft = { ...next, ...edited };
|
||||
}
|
||||
|
||||
async function write(reset: boolean) {
|
||||
if (!loaded || busy) return;
|
||||
const edited = changes();
|
||||
if (!reset && !Object.keys(edited).length) return;
|
||||
busy = true;
|
||||
const revision = generation, name = selected;
|
||||
try {
|
||||
const next = structuredClone($state.snapshot(saved)) as ImageSettings;
|
||||
if (reset) delete next.images[name]; else next.images[name] = { ...next.images[name], ...edited };
|
||||
const contents = JSON.stringify(next, null, 2) + "\n";
|
||||
await folderHost.writeSidecar(contents, source);
|
||||
if (closed || revision !== generation) return;
|
||||
source = contents; saved = next;
|
||||
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
||||
baseline = { ...draft };
|
||||
status = { text: reset ? tr("Default appearance restored.") : tr("Image appearance saved."), error: false };
|
||||
await sendBackgroundCommand("reload");
|
||||
} catch (reason) { report(reason); }
|
||||
finally { busy = false; }
|
||||
}
|
||||
|
||||
function menu(event: MouseEvent, field: "fit" | "position") {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
const values: readonly string[] = field === "fit" ? imageFits : BACKGROUND_POSITIONS;
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === "fit" ? $t("Image fit") : $t("Position of this image"), parent: anchor.closest("dialog") ?? undefined,
|
||||
items: values.map((value, index) => ({ label: field === "fit" ? fitLabels[value] : positionLabels[index], radio: true, checked: draft[field] === value,
|
||||
run: () => { draft = { ...draft, [field]: value }; } })) }).close;
|
||||
}
|
||||
|
||||
function overlay(input: HTMLInputElement) {
|
||||
if (input.validity.valid && Number.isFinite(input.valueAsNumber)) draft = { ...draft, overlay: Math.round(Math.max(-100, Math.min(100, input.valueAsNumber))) / 100 };
|
||||
}
|
||||
|
||||
function openPicker() {
|
||||
if (pickerOpen) { pickerOpen = false; return; }
|
||||
query = ""; pickerOpen = true;
|
||||
queueMicrotask(() => search?.focus());
|
||||
}
|
||||
|
||||
function pick(name: string) {
|
||||
pickerOpen = false;
|
||||
void choose(name).then(() => trigger?.focus());
|
||||
}
|
||||
|
||||
function moveFocus(event: KeyboardEvent, list: HTMLElement) {
|
||||
const rows = [...list.querySelectorAll<HTMLButtonElement>("button")];
|
||||
if (!rows.length) return;
|
||||
const index = rows.indexOf(document.activeElement as HTMLButtonElement);
|
||||
const next = event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : index < 0 ? (event.key === "ArrowDown" ? 0 : rows.length - 1) : Math.max(0, Math.min(rows.length - 1, index + (event.key === "ArrowDown" ? 1 : -1)));
|
||||
event.preventDefault();
|
||||
rows[next].focus();
|
||||
}
|
||||
|
||||
$effect(() => { void settings.size; void settings.position; void settings.overlay; untrack(inherit); });
|
||||
void load();
|
||||
onDestroy(() => { closed = true; generation++; closeMenu(); if (url) URL.revokeObjectURL(url); });
|
||||
</script>
|
||||
|
||||
<details class="image-editor">
|
||||
<summary>{$t("Per-image appearance")}</summary>
|
||||
<p>{$t("Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.")}</p>
|
||||
<fieldset disabled={busy}>
|
||||
<div class="row"><span>{$t("Image")}</span>
|
||||
<button bind:this={trigger} class="choice" aria-label={$t("Image to change")} aria-expanded={pickerOpen} aria-controls={pickerId} disabled={!names.length} onclick={openPicker}>
|
||||
<span class="name">{selected || $t("Choose an image")}</span><Icon icon="chevron-down" /></button></div>
|
||||
{#if pickerOpen}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions (Escape closes the picker.) -->
|
||||
<div id={pickerId} class="rs-picker image-picker" onkeydown={event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); pickerOpen = false; trigger?.focus(); } }}>
|
||||
<input bind:this={search} type="search" aria-label={$t("Find an image")} placeholder={$t("Find an image")} bind:value={query}
|
||||
onkeydown={event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") moveFocus(event, event.currentTarget.nextElementSibling as HTMLElement); else if (event.key === "Enter" && filtered[0]) { event.preventDefault(); pick(filtered[0]); } }} />
|
||||
<div class="options" role="listbox" aria-label={$t("Image files")} tabindex="-1"
|
||||
onkeydown={event => { if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) moveFocus(event, event.currentTarget); }}>
|
||||
{#each filtered.slice(0, 100) as name (name)}
|
||||
<button class="rs-picker-row" role="option" tabindex="-1" aria-selected={name === selected} onclick={() => pick(name)}>{name}</button>
|
||||
{/each}
|
||||
</div>
|
||||
<p role="status">{!filtered.length ? $t("No matching images.") : filtered.length > 100 ? $t("{count} matches. Type more of the name to see other images.", { count: filtered.length }) : $t(filtered.length === 1 ? "{count} image." : "{count} images.", { count: filtered.length })}</p>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="preview" role="img" aria-label={selected ? $t("Selected image preview: {name}", { name: selected }) : $t("Selected image preview")}>
|
||||
{#if url}
|
||||
{#if draft.fit === "blurred"}<span class="fill" style:background-image={`url("${url}")`}></span>{/if}
|
||||
<span class="foreground" style:background-image={`url("${url}")`} style:background-size={draft.fit === "blurred" ? "contain" : draft.fit} style:background-position={draft.position}></span>
|
||||
{/if}
|
||||
<span class="shade" style:background={draft.overlay < 0 ? "white" : "black"} style:opacity={String(Math.abs(draft.overlay))}></span>
|
||||
</div>
|
||||
<div class="row"><span>{$t("Fit")}</span><button class="choice" aria-label={$t("Image fit")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "fit")}>{fitLabels[draft.fit]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="row"><span>{$t("Position")}</span><button class="choice" aria-label={$t("Position of this image")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "position")}>{positionLabels[BACKGROUND_POSITIONS.indexOf(draft.position)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="row"><span>{$t("Overlay")}</span><div class="controls">
|
||||
<input type="range" min="-100" max="100" aria-label={$t("Overlay of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} />
|
||||
<input type="number" min="-100" max="100" step="1" required aria-label={$t("Overlay percentage of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} /><span>%</span>
|
||||
</div></div>
|
||||
<div class="controls">
|
||||
<button disabled={!loaded || !changed} onclick={() => void write(false)}><Icon icon="save" />{$t("Save image appearance")}</button>
|
||||
<button disabled={!loaded || !saved.images[selected]} onclick={() => void write(true)}><Icon icon="undo" />{$t("Reset image appearance")}</button>
|
||||
<button onclick={() => void load()}><Icon icon="refresh" />{$t("Reload image settings")}</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
{#if status.text}<p role={status.error ? "alert" : "status"} class:error={status.error}>{status.text}</p>{/if}
|
||||
</details>
|
||||
|
||||
<style>
|
||||
.image-editor { display: grid; gap: var(--rs-settings-gap); min-width: 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
||||
summary { cursor: pointer; min-height: var(--rs-settings-control-height); line-height: var(--rs-settings-control-height); border-radius: var(--rs-control-radius); }
|
||||
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.error { color: var(--rs-error); }
|
||||
fieldset { display: grid; gap: var(--rs-settings-gap); min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: 0; border: 0; }
|
||||
.row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
button:not(.rs-picker-row), input:not([type=range]) { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
button:not(.rs-picker-row) { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
|
||||
button:not(.rs-picker-row):hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||
button:disabled, input:disabled { opacity: .55; cursor: default; }
|
||||
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
:is(button, input, summary):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.choice { max-width: 100%; min-width: 0; }
|
||||
.choice .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
input[type=number] { width: 72px; }
|
||||
input[type=range] { width: 160px; max-width: 100%; accent-color: var(--rs-accent); }
|
||||
.image-picker { display: grid; gap: var(--rs-settings-gap); width: 100%; min-width: 0; position: static; }
|
||||
.image-picker input { width: 100%; min-width: 0; }
|
||||
.options { display: grid; gap: 2px; max-height: 220px; overflow: auto; min-width: 0; }
|
||||
.options button { justify-content: flex-start; text-align: left; overflow-wrap: anywhere; }
|
||||
.preview { position: relative; width: 100%; height: 170px; overflow: hidden; border-radius: var(--rs-control-radius); background-color: var(--rs-bg-active); }
|
||||
.fill, .foreground, .shade { position: absolute; inset: 0; background-repeat: no-repeat; pointer-events: none; }
|
||||
.fill { inset: -24px; filter: blur(18px); background-size: cover; background-position: center; }
|
||||
</style>
|
||||
@@ -0,0 +1,83 @@
|
||||
// The blurred fill of a portrait image. One worker does the decode, the resize, and the filter away from the
|
||||
// input and paint work of the window. It lives as long as the Background instance.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
|
||||
const workerSource = `
|
||||
self.onmessage = async ({ data: { id, url, width, height } }) => {
|
||||
let image;
|
||||
try {
|
||||
const source = await (await fetch(url)).blob();
|
||||
image = await createImageBitmap(source, { resizeWidth: width, resizeHeight: height, resizeQuality: 'high' });
|
||||
const canvas = new OffscreenCanvas(width, height);
|
||||
const context = canvas.getContext('2d');
|
||||
context.filter = 'blur(24px)';
|
||||
context.drawImage(image, -48, -48, width + 96, height + 96);
|
||||
self.postMessage({ id, blob: await canvas.convertToBlob({ type: 'image/png' }) });
|
||||
} catch (error) {
|
||||
self.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
|
||||
} finally { image?.close(); }
|
||||
};`;
|
||||
|
||||
/** The size of the blurred copy. Its long side is at most 1024 pixels. */
|
||||
export function blurSize(width: number, height: number): { width: number; height: number } {
|
||||
const scale = Math.min(1, 1024 / Math.max(width, height, 1));
|
||||
return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
|
||||
}
|
||||
|
||||
export class BlurWorker {
|
||||
private worker?: Worker;
|
||||
private workerUrl?: string;
|
||||
private serial = 0;
|
||||
private pending = new Map<number, { resolve: (blob: Blob) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
|
||||
/** A blob URL of the blurred copy of the image at `url`. The caller releases it. */
|
||||
async blur(url: string, width: number, height: number): Promise<string> {
|
||||
const size = blurSize(width, height);
|
||||
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") return URL.createObjectURL(await this.inWindow(url, size));
|
||||
const worker = this.start();
|
||||
const id = ++this.serial;
|
||||
const blob = await new Promise<Blob>((resolve, reject) => {
|
||||
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(tr("The blurred image took too long to load."))); }, 10000);
|
||||
this.pending.set(id, { resolve, reject, timer });
|
||||
worker.postMessage({ id, url, ...size });
|
||||
});
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
private start(): Worker {
|
||||
if (this.worker) return this.worker;
|
||||
this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" }));
|
||||
const worker = this.worker = new Worker(this.workerUrl);
|
||||
worker.onmessage = ({ data }) => {
|
||||
const request = this.pending.get(data?.id);
|
||||
if (!request) return;
|
||||
this.pending.delete(data.id); clearTimeout(request.timer);
|
||||
if (data.blob instanceof Blob) request.resolve(data.blob);
|
||||
else request.reject(new Error(data.error || tr("Cannot create the blurred image.")));
|
||||
};
|
||||
worker.onerror = () => this.fail(new Error(tr("Cannot create the blurred image.")));
|
||||
return worker;
|
||||
}
|
||||
|
||||
/** A fallback for a window without OffscreenCanvas. */
|
||||
private async inWindow(url: string, size: { width: number; height: number }): Promise<Blob> {
|
||||
const image = new Image(); image.src = url; await image.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = size.width; canvas.height = size.height;
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.filter = "blur(24px)";
|
||||
context.drawImage(image, -48, -48, size.width + 96, size.height + 96);
|
||||
return new Promise<Blob>((resolve, reject) => canvas.toBlob(value => value ? resolve(value) : reject(new Error(tr("Cannot create the blurred image."))), "image/png"));
|
||||
}
|
||||
|
||||
private fail(error: Error) {
|
||||
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
||||
this.pending.clear();
|
||||
// A failed worker starts again at the next request.
|
||||
this.worker?.terminate(); this.worker = undefined;
|
||||
if (this.workerUrl) URL.revokeObjectURL(this.workerUrl);
|
||||
this.workerUrl = undefined;
|
||||
}
|
||||
|
||||
dispose() { this.fail(new Error(tr("This feature is off."))); }
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
// The Background engine: it shows the images of a source as background frames, one after the other.
|
||||
// It comes from the engine of the Background Slideshow plugin, with these changes for the open card
|
||||
// "Lag before image transition": the next image loads and decodes before its fade, the blurred fills of the
|
||||
// last images stay in a cache, and the folder list and the sidecar are read again only after a settings change,
|
||||
// on window focus, or after every 10 images.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { BackgroundFrame } from "../../plugins/backgroundContracts.ts";
|
||||
import type { BackgroundLayout } from "../backgroundSettings.ts";
|
||||
import { imageAppearance, imageNames, parseImageSettings, sequence, type ImageAppearance, type ImageSettings } from "./imageSettings.ts";
|
||||
|
||||
/** The time of the fade from one image to the next. */
|
||||
export const transitionMs = 2000;
|
||||
/** The folder list and the sidecar are read again after this number of images. */
|
||||
export const RESCAN_SLIDES = 10;
|
||||
/** The number of blurred fills that stay in the cache. */
|
||||
export const BLUR_CACHE = 3;
|
||||
/** The shortest wait before a new try after an error. */
|
||||
export const RETRY_MS = 5000;
|
||||
|
||||
/** Where the images come from: the image folder of the host, or the one saved image. */
|
||||
export interface ImageSource {
|
||||
/** A different key means a different folder or image. The engine then starts again. */
|
||||
readonly key: string;
|
||||
/** True for a folder: the images change on a timer, and the sidecar and the portrait default apply. */
|
||||
readonly timed: boolean;
|
||||
/** The image names. */
|
||||
list(): Promise<string[]>;
|
||||
read(name: string): Promise<Blob>;
|
||||
/** The text of the sidecar file, or null. */
|
||||
sidecar(): Promise<string | null>;
|
||||
}
|
||||
|
||||
export interface LoadedImage { url: string; width: number; height: number }
|
||||
|
||||
/** The browser services of the engine. Tests replace them. */
|
||||
export interface Runtime {
|
||||
/** Make a blob URL and decode the image before it shows. */
|
||||
load(blob: Blob): Promise<LoadedImage>;
|
||||
/** Make the blurred fill of a loaded image. The engine releases the URL. */
|
||||
blur(image: LoadedImage): Promise<string>;
|
||||
release(url: string): void;
|
||||
later(callback: () => void, milliseconds: number): unknown;
|
||||
cancel(timer: unknown): void;
|
||||
random(): number;
|
||||
now(): number;
|
||||
}
|
||||
|
||||
export interface Frames { set(target: string, frame: BackgroundFrame | null): void }
|
||||
|
||||
export interface EngineSettings extends BackgroundLayout {
|
||||
seconds: number;
|
||||
order: "name" | "random";
|
||||
paused: boolean;
|
||||
targets: string[];
|
||||
}
|
||||
|
||||
export interface Status { message: string; image: string | null; count: number; error: boolean }
|
||||
|
||||
interface Shown { name: string; key: string; image: LoadedImage; appearance: ImageAppearance; blurred?: string }
|
||||
interface Prepared { name: string; key: string; image: LoadedImage }
|
||||
|
||||
function toFrame(shown: Shown): BackgroundFrame {
|
||||
const frame: BackgroundFrame = { url: shown.image.url, overlay: shown.appearance.overlay, position: shown.appearance.position,
|
||||
size: shown.appearance.fit === "blurred" ? "contain" : shown.appearance.fit };
|
||||
if (shown.blurred) frame.blurredUrl = shown.blurred;
|
||||
return frame;
|
||||
}
|
||||
|
||||
const sameAppearance = (a: ImageAppearance, b: ImageAppearance) => a.fit === b.fit && a.position === b.position && a.overlay === b.overlay;
|
||||
|
||||
export class Slideshow {
|
||||
status: Status = { message: "", image: null, count: 0, error: false };
|
||||
private source: ImageSource | null = null;
|
||||
private settings: EngineSettings | null = null;
|
||||
private revision = 0;
|
||||
private stopped = false;
|
||||
private timer: unknown;
|
||||
/** When the current timer fires, or null without a timer. */
|
||||
private due: number | null = null;
|
||||
private names: string[] | null = null;
|
||||
private imageSettings: ImageSettings = { schema: 1, images: {} };
|
||||
private sidecarError = "";
|
||||
private stale = true;
|
||||
private slides = 0;
|
||||
private shown: Shown | null = null;
|
||||
/** The image that the current frame fades from. */
|
||||
private previous: Shown | null = null;
|
||||
private targets = new Set<string>();
|
||||
/** The blurred fills, oldest first. */
|
||||
private blurs = new Map<string, string>();
|
||||
private prepared: { name: string; work: Promise<Prepared | null>; discarded: boolean } | null = null;
|
||||
/** Changes at each `clear`, so that a late blurred fill of an old image does not enter the cache. */
|
||||
private epoch = 0;
|
||||
private listeners = new Set<() => void>();
|
||||
private frames: Frames;
|
||||
private runtime: Runtime;
|
||||
|
||||
constructor(frames: Frames, runtime: Runtime) { this.frames = frames; this.runtime = runtime; }
|
||||
|
||||
subscribe(listener: () => void) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
|
||||
private notify() { for (const listener of [...this.listeners]) listener(); }
|
||||
|
||||
/** Use a new source or new settings. The current image stays when the source is the same and still has it. */
|
||||
configure(source: ImageSource | null, settings: EngineSettings): Promise<void> {
|
||||
if (this.stopped) return Promise.resolve();
|
||||
if (source?.key !== this.source?.key) {
|
||||
this.clear();
|
||||
this.names = null;
|
||||
}
|
||||
this.source = source;
|
||||
this.settings = { ...settings, targets: [...settings.targets] };
|
||||
this.stale = true;
|
||||
return this.update(false);
|
||||
}
|
||||
|
||||
/** Read the list and the sidecar again before the next image, for example after a window focus. */
|
||||
invalidate() { this.stale = true; }
|
||||
|
||||
/** Read the list and the sidecar again now, and apply them to the current image. */
|
||||
reload = () => { this.stale = true; return this.update(false); };
|
||||
|
||||
/** Show the next image now. */
|
||||
next = () => this.update(true);
|
||||
|
||||
dispose() {
|
||||
if (this.stopped) return;
|
||||
this.stopped = true; this.revision++;
|
||||
this.runtime.cancel(this.timer); this.timer = undefined;
|
||||
this.clear(); this.listeners.clear();
|
||||
}
|
||||
|
||||
private async update(advance: boolean): Promise<void> {
|
||||
if (this.stopped) return;
|
||||
const revision = ++this.revision;
|
||||
const remaining = this.due === null ? null : Math.max(0, this.due - this.runtime.now());
|
||||
this.runtime.cancel(this.timer); this.timer = undefined; this.due = null;
|
||||
const valid = () => !this.stopped && revision === this.revision;
|
||||
const source = this.source, settings = this.settings;
|
||||
try {
|
||||
if (!source || !settings) { this.clear(); this.setStatus(tr("Choose a folder or an image to show a background.")); return; }
|
||||
if (!settings.targets.length) { this.clear(); this.setStatus(tr("Select where to show the background.")); return; }
|
||||
if (this.stale || !this.names) {
|
||||
const [list, sidecar] = await Promise.all([source.list(), source.timed ? source.sidecar() : Promise.resolve(null)]);
|
||||
if (!valid()) return;
|
||||
this.names = source.timed ? imageNames(list) : [...list];
|
||||
try { this.imageSettings = parseImageSettings(sidecar); this.sidecarError = ""; }
|
||||
catch (reason) { this.imageSettings = { schema: 1, images: {} }; this.sidecarError = reason instanceof Error ? reason.message : String(reason); }
|
||||
this.stale = false; this.slides = 0;
|
||||
if (this.prepared && !this.names.includes(this.prepared.name)) this.discardPrepared();
|
||||
}
|
||||
const names = this.names;
|
||||
this.status.count = names.length;
|
||||
if (!names.length) throw new Error(tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."));
|
||||
const shown = this.shown;
|
||||
if (shown && names.includes(shown.name) && (!advance || names.length === 1)) {
|
||||
await this.reapply(shown, settings, valid);
|
||||
if (!valid()) return;
|
||||
this.schedule(remaining ?? settings.seconds * 1000, revision);
|
||||
this.prepare();
|
||||
return;
|
||||
}
|
||||
let failures = 0;
|
||||
const order = sequence(names, shown?.name ?? null, settings.order, this.runtime.random);
|
||||
const candidates = this.prepared && order.includes(this.prepared.name) ? [this.prepared.name, ...order.filter(name => name !== this.prepared!.name)] : order;
|
||||
for (const name of candidates) {
|
||||
let loaded: Prepared | null = null;
|
||||
let next: Shown;
|
||||
try {
|
||||
loaded = await this.load(name);
|
||||
if (!valid()) { if (loaded) this.runtime.release(loaded.image.url); return; }
|
||||
if (!loaded) throw new Error(tr("The image cannot be displayed."));
|
||||
next = { ...loaded, appearance: this.appearanceOf(name, loaded.image, settings) };
|
||||
if (next.appearance.fit === "blurred") {
|
||||
next.blurred = await this.blurOf(loaded);
|
||||
if (!valid()) { this.runtime.release(loaded.image.url); return; }
|
||||
}
|
||||
} catch {
|
||||
if (loaded) this.runtime.release(loaded.image.url);
|
||||
if (!valid()) return;
|
||||
failures++; continue;
|
||||
}
|
||||
this.publish(next, settings, true);
|
||||
const message = failures ? tr("{name}: skipped {count} unreadable images.", { name, count: failures }) : name;
|
||||
this.status = { image: name, count: names.length, error: !!this.sidecarError, message: this.sidecarError ? `${message} ${this.sidecarError}` : message };
|
||||
this.notify();
|
||||
if (++this.slides >= RESCAN_SLIDES) this.stale = true;
|
||||
this.schedule(settings.seconds * 1000, revision);
|
||||
this.prepare();
|
||||
return;
|
||||
}
|
||||
throw new Error(tr("No readable images in this folder. Check the image files."));
|
||||
} catch (error) {
|
||||
if (!valid()) return;
|
||||
this.clear();
|
||||
this.status = { ...this.status, image: null, error: true, message: error instanceof Error ? error.message : String(error) };
|
||||
this.notify();
|
||||
if (source?.timed && settings) this.schedule(Math.max(RETRY_MS, settings.seconds * 1000), revision, true);
|
||||
}
|
||||
}
|
||||
|
||||
private setStatus(message: string) {
|
||||
this.status = { message, image: null, count: 0, error: false };
|
||||
this.notify();
|
||||
}
|
||||
|
||||
private appearanceOf(name: string, image: LoadedImage, settings: EngineSettings): ImageAppearance {
|
||||
if (!this.source?.timed) return { fit: settings.size, position: settings.position, overlay: settings.overlay };
|
||||
return imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
|
||||
}
|
||||
|
||||
/** The image of `name`: the prepared image when it matches, or a new read. */
|
||||
private async load(name: string): Promise<Prepared | null> {
|
||||
const prepared = this.prepared;
|
||||
if (prepared?.name === name) {
|
||||
this.prepared = null;
|
||||
const result = await prepared.work.catch(() => null);
|
||||
if (result) return result;
|
||||
}
|
||||
const source = this.source!;
|
||||
const blob = await source.read(name);
|
||||
const image = await this.runtime.load(blob);
|
||||
return { name, key: `${source.key}\n${name}\n${blob.size}`, image };
|
||||
}
|
||||
|
||||
/** Load and decode the next image of a timed source now, so that its fade starts on time. */
|
||||
private prepare() {
|
||||
const source = this.source, settings = this.settings, names = this.names, shown = this.shown;
|
||||
if (!source?.timed || !settings || settings.paused || !names || names.length < 2 || !shown || this.prepared) return;
|
||||
const name = sequence(names, shown.name, settings.order, this.runtime.random)[0];
|
||||
const entry: { name: string; work: Promise<Prepared | null>; discarded: boolean } = { name, work: Promise.resolve(null), discarded: false };
|
||||
entry.work = (async (): Promise<Prepared | null> => {
|
||||
const blob = await source.read(name);
|
||||
const image = await this.runtime.load(blob);
|
||||
// A prepared image that nobody wants any more goes away at once.
|
||||
if (this.stopped || entry.discarded) { this.runtime.release(image.url); return null; }
|
||||
const result = { name, key: `${source.key}\n${name}\n${blob.size}`, image };
|
||||
const appearance = imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
|
||||
if (appearance.fit === "blurred") await this.blurOf(result).catch(() => undefined);
|
||||
return result;
|
||||
})();
|
||||
entry.work.catch(() => undefined);
|
||||
this.prepared = entry;
|
||||
}
|
||||
|
||||
private discardPrepared() {
|
||||
const prepared = this.prepared;
|
||||
this.prepared = null;
|
||||
if (!prepared) return;
|
||||
prepared.discarded = true;
|
||||
void prepared.work.then(result => { if (result) this.runtime.release(result.image.url); }, () => undefined);
|
||||
}
|
||||
|
||||
/** The blurred fill of an image, from the cache when possible. */
|
||||
private async blurOf(image: Prepared): Promise<string> {
|
||||
const cached = this.blurs.get(image.key);
|
||||
if (cached) { this.blurs.delete(image.key); this.blurs.set(image.key, cached); return cached; }
|
||||
const epoch = this.epoch;
|
||||
const url = await this.runtime.blur(image.image);
|
||||
if (this.stopped || epoch !== this.epoch) { this.runtime.release(url); throw new Error(tr("The background changed.")); }
|
||||
const again = this.blurs.get(image.key);
|
||||
if (again) { this.runtime.release(url); return again; }
|
||||
this.blurs.set(image.key, url);
|
||||
this.trimBlurs(url);
|
||||
return url;
|
||||
}
|
||||
|
||||
/** Release the oldest blurred fills beyond the cache size. Fills that a frame shows stay. */
|
||||
private trimBlurs(keep?: string) {
|
||||
const used = new Set([this.shown?.blurred, this.previous?.blurred, keep]);
|
||||
for (const [key, url] of this.blurs) {
|
||||
if (this.blurs.size <= BLUR_CACHE) break;
|
||||
if (used.has(url)) continue;
|
||||
this.blurs.delete(key); this.runtime.release(url);
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply new settings or new image settings to the image that shows, without a fade. */
|
||||
private async reapply(shown: Shown, settings: EngineSettings, valid: () => boolean) {
|
||||
const appearance = this.appearanceOf(shown.name, shown.image, settings);
|
||||
const sameTargets = settings.targets.length === this.targets.size && settings.targets.every(target => this.targets.has(target));
|
||||
const needsBlur = appearance.fit === "blurred" && !shown.blurred;
|
||||
if (sameTargets && sameAppearance(appearance, shown.appearance) && !needsBlur) return;
|
||||
const next: Shown = { ...shown, appearance, blurred: undefined };
|
||||
if (appearance.fit === "blurred") {
|
||||
next.blurred = await this.blurOf(shown);
|
||||
if (!valid()) return;
|
||||
}
|
||||
this.publish(next, settings, false);
|
||||
this.notify();
|
||||
}
|
||||
|
||||
/** Show `next` on every target. With `fade`, the frame fades from the image that showed before. */
|
||||
private publish(next: Shown, settings: EngineSettings, fade: boolean) {
|
||||
const old = this.shown;
|
||||
const frame = toFrame(next);
|
||||
if (fade && old) { frame.previous = toFrame(old); frame.transitionMs = transitionMs; }
|
||||
try {
|
||||
for (const target of this.targets) if (!settings.targets.includes(target)) this.frames.set(target, null);
|
||||
// Track the new targets before the frames go out, so that a cleanup also clears a partial publish.
|
||||
for (const target of settings.targets) this.targets.add(target);
|
||||
for (const target of settings.targets) this.frames.set(target, frame);
|
||||
} catch (error) {
|
||||
if (next.image !== old?.image) this.runtime.release(next.image.url);
|
||||
throw error;
|
||||
}
|
||||
this.targets = new Set(settings.targets);
|
||||
// Keep the image of the fade until the next frame replaces it.
|
||||
const release = this.previous;
|
||||
if (release && release.image !== next.image && release.image !== old?.image) this.runtime.release(release.image.url);
|
||||
this.previous = fade && old && old.image !== next.image ? old : null;
|
||||
if (!fade && old && old.image !== next.image) this.runtime.release(old.image.url);
|
||||
this.shown = next;
|
||||
this.trimBlurs();
|
||||
}
|
||||
|
||||
/** Remove the frames of every target and release every image. */
|
||||
private clear() {
|
||||
for (const target of this.targets) { try { this.frames.set(target, null); } catch { /* The window can close before the cleanup. */ } }
|
||||
this.targets.clear();
|
||||
const images = new Set([this.shown?.image.url, this.previous?.image.url]);
|
||||
for (const url of images) if (url) this.runtime.release(url);
|
||||
for (const url of this.blurs.values()) this.runtime.release(url);
|
||||
this.blurs.clear();
|
||||
this.epoch++;
|
||||
this.discardPrepared();
|
||||
this.shown = null; this.previous = null;
|
||||
this.status = { ...this.status, image: null };
|
||||
}
|
||||
|
||||
private schedule(milliseconds: number, revision: number, retry = false) {
|
||||
const settings = this.settings;
|
||||
if (this.stopped || this.revision !== revision || !this.source?.timed || !settings) return;
|
||||
if (settings.paused && !retry) return;
|
||||
this.due = this.runtime.now() + milliseconds;
|
||||
this.timer = this.runtime.later(() => { this.timer = undefined; this.due = null; void this.update(true); }, milliseconds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// The per-image settings: the sidecar file `.runestone-backgrounds.json` in the image folder.
|
||||
// The Background Slideshow plugin used the same file, so the settings of each image stay.
|
||||
import { BACKGROUND_POSITIONS } from "../../theme/appearance.ts";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { BackgroundLayout, BackgroundPosition } from "../backgroundSettings.ts";
|
||||
|
||||
export const sidecarName = ".runestone-backgrounds.json";
|
||||
/** `blurred` shows the full image over a blurred copy that fills the view. Portrait images use it by default. */
|
||||
export const imageFits = ["cover", "contain", "auto", "blurred"] as const;
|
||||
export type ImageFit = typeof imageFits[number];
|
||||
export interface ImageAppearance { fit: ImageFit; position: BackgroundPosition; overlay: number }
|
||||
/** Unknown keys of the file and of each image stay when RuneStone saves the file. */
|
||||
export interface ImageSettings { schema: 1; images: Record<string, Partial<ImageAppearance>>; [key: string]: unknown }
|
||||
|
||||
/** Read the sidecar text. `null` (no file) gives empty settings. Invalid settings throw an error. */
|
||||
export function parseImageSettings(source: string | null): ImageSettings {
|
||||
if (source === null) return { schema: 1, images: {} };
|
||||
const value = JSON.parse(source);
|
||||
if (!value || value.schema !== 1 || !value.images || typeof value.images !== "object" || Array.isArray(value.images)) {
|
||||
throw new Error(tr("The image settings file must use schema 1 and an images object."));
|
||||
}
|
||||
for (const [name, raw] of Object.entries(value.images)) {
|
||||
const appearance = raw as Partial<ImageAppearance>;
|
||||
if (!name || /[\\/]/.test(name) || !appearance || typeof appearance !== "object" || Array.isArray(appearance)
|
||||
|| ("fit" in appearance && !imageFits.includes(appearance.fit!))
|
||||
|| ("position" in appearance && !BACKGROUND_POSITIONS.includes(appearance.position!))
|
||||
|| ("overlay" in appearance && (typeof appearance.overlay !== "number" || !Number.isFinite(appearance.overlay) || Math.abs(appearance.overlay) > 1))) {
|
||||
throw new Error(tr("Invalid image settings for {name}.", { name }));
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** The appearance of one image: the folder layout, the portrait default, then the saved values of the image. */
|
||||
export function imageAppearance(layout: BackgroundLayout, override: Partial<ImageAppearance> | undefined, portrait: boolean): ImageAppearance {
|
||||
return { fit: portrait ? "blurred" : layout.size, position: layout.position, overlay: layout.overlay, ...override };
|
||||
}
|
||||
|
||||
/** The supported image names, without duplicates, in natural order. */
|
||||
export function imageNames(names: readonly string[]): string[] {
|
||||
return [...new Set(names.filter(name => !/[\\/]/.test(name) && /\.(png|jpe?g|gif|webp)$/i.test(name)))]
|
||||
.sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }) || a.localeCompare(b, "en"));
|
||||
}
|
||||
|
||||
/** The order of the next images after `current`. A random order puts the current image last. */
|
||||
export function sequence(names: readonly string[], current: string | null, order: "name" | "random", random = Math.random): string[] {
|
||||
if (order === "name") {
|
||||
const index = current === null ? -1 : names.indexOf(current);
|
||||
return [...names.slice(index + 1), ...names.slice(0, index + 1)];
|
||||
}
|
||||
const rest = names.filter(name => name !== current);
|
||||
for (let i = rest.length - 1; i > 0; i--) {
|
||||
const j = Math.min(i, Math.max(0, Math.floor(random() * (i + 1))));
|
||||
[rest[i], rest[j]] = [rest[j], rest[i]];
|
||||
}
|
||||
return current && names.includes(current) ? [...rest, current] : rest;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// The Background feature. `loader.ts` imports this module when a folder or an image is selected (`launch.ts`),
|
||||
// at a palette command, or when Appearance → Background shows its settings.
|
||||
// It shows the images through `backgroundHub`, so the workarea, browser tabs, and Project Management boards get the frames.
|
||||
import { mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { backgroundHub } from "../../plugins/backgrounds.ts";
|
||||
import { readAppearance } from "../../theme/appearance.ts";
|
||||
import { hasImage, normalizeLayout, onBackgroundChange, readBackground, writeBackground } from "../backgroundSettings.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import { BlurWorker } from "./blur.ts";
|
||||
import { Slideshow, type ImageSource } from "./engine.ts";
|
||||
import { browserRuntime, folderHost, folderSource, imageSource, onBackgroundCommand, sendBackgroundCommand } from "./sources.ts";
|
||||
import BackgroundSettings from "./BackgroundSettings.svelte";
|
||||
|
||||
export function start(_context: FeatureContext): FeatureInstance {
|
||||
const owner = Symbol("background");
|
||||
const blur = new BlurWorker();
|
||||
const engine = new Slideshow({ set: (target, frame) => backgroundHub.set(owner, target, frame) }, browserRuntime(blur));
|
||||
/** The host folder for display. `undefined` until the first read. */
|
||||
let folder: string | null | undefined;
|
||||
let generation = 0;
|
||||
let disposed = false;
|
||||
/** The last source and settings. A change of another appearance setting, such as the theme, gives the same value. */
|
||||
let applied = "";
|
||||
|
||||
/** Give the engine the current source and settings. `reread` asks the host for its folder again. */
|
||||
async function apply(reread: boolean) {
|
||||
const run = ++generation;
|
||||
const settings = readBackground();
|
||||
const appearance = readAppearance();
|
||||
let source: ImageSource | null = null;
|
||||
let layout = normalizeLayout(settings);
|
||||
if (settings.source === "folder") {
|
||||
if (reread || folder === undefined) {
|
||||
try { folder = await folderHost.current(); } catch { folder = null; }
|
||||
if (disposed || run !== generation) return;
|
||||
}
|
||||
source = folder ? folderSource(folder) : null;
|
||||
} else if (settings.source === "image" && hasImage(appearance)) {
|
||||
source = imageSource(appearance.newTabBackground!);
|
||||
layout = normalizeLayout(appearance.newTabBackground);
|
||||
}
|
||||
const next = { ...settings, ...layout };
|
||||
const signature = JSON.stringify([source?.key ?? null, next]);
|
||||
if (!reread && signature === applied) return;
|
||||
applied = signature;
|
||||
await engine.configure(source, next);
|
||||
}
|
||||
|
||||
const stopSettings = onBackgroundChange(() => { void apply(false); });
|
||||
const stopCommands = onBackgroundCommand(command => {
|
||||
if (command === "next") void engine.next();
|
||||
else { engine.invalidate(); void apply(true); }
|
||||
});
|
||||
// Another window or program can change the folder. A focus reads the folder, the list, and the sidecar again.
|
||||
const focus = () => { engine.invalidate(); void apply(true); };
|
||||
window.addEventListener("focus", focus);
|
||||
void apply(true);
|
||||
|
||||
return {
|
||||
mount() { throw new Error(tr("This view is unavailable.")); },
|
||||
async run(command) {
|
||||
if (command === "next") await sendBackgroundCommand("next");
|
||||
else if (command === "pause") {
|
||||
const settings = readBackground();
|
||||
await writeBackground({ ...settings, paused: !settings.paused });
|
||||
} else throw new Error(tr("This command is unavailable."));
|
||||
},
|
||||
dispose() {
|
||||
disposed = true; generation++;
|
||||
stopSettings(); stopCommands();
|
||||
window.removeEventListener("focus", focus);
|
||||
engine.dispose();
|
||||
blur.dispose();
|
||||
backgroundHub.removeOwner(owner);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The settings of Appearance → Background. They work also in a window where Background does not run. */
|
||||
export function mountSettings(element: HTMLElement) {
|
||||
const component = mount(BackgroundSettings, { target: element });
|
||||
return () => { void unmount(component); };
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// The image sources of Background, the host folder commands (`src-tauri/src/backgrounds.rs`), the browser runtime of the
|
||||
// engine, and the commands that reach the Background instance of every window.
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { emit, listen } from "@tauri-apps/api/event";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { readBackgroundImage } from "../../theme/backgroundImages.ts";
|
||||
import type { Appearance } from "../../theme/appearance.ts";
|
||||
import type { BlurWorker } from "./blur.ts";
|
||||
import type { ImageSource, LoadedImage, Runtime } from "./engine.ts";
|
||||
|
||||
const types: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
|
||||
const typeOf = (name: string) => types[name.split(".").pop()!.toLowerCase()] ?? "application/octet-stream";
|
||||
|
||||
/** The host commands of the image folder. The host keeps the folder, so no command takes a path. */
|
||||
export const folderHost = {
|
||||
/** Show the folder dialog. Returns the chosen folder for display, or null after Cancel. */
|
||||
choose: (title: string) => invoke<string | null>("background_choose_folder", { title }),
|
||||
/** The current folder for display, or null. */
|
||||
current: () => invoke<string | null>("background_folder"),
|
||||
clear: () => invoke<void>("background_clear_folder"),
|
||||
list: () => invoke<string[]>("background_list"),
|
||||
read: async (name: string): Promise<Blob> => {
|
||||
const bytes = await invoke<ArrayBuffer | Uint8Array | number[]>("background_read", { name });
|
||||
return new Blob([bytes instanceof ArrayBuffer ? bytes : Uint8Array.from(bytes)], { type: typeOf(name) });
|
||||
},
|
||||
readSidecar: () => invoke<string | null>("background_read_sidecar"),
|
||||
writeSidecar: (contents: string, expected: string | null) => invoke<void>("background_write_sidecar", { contents, expected }),
|
||||
};
|
||||
|
||||
/** The images of the host folder. `folder` is the path for display. It makes the key, so another folder starts again. */
|
||||
export function folderSource(folder: string): ImageSource {
|
||||
return { key: `folder:${folder}`, timed: true, list: folderHost.list, read: folderHost.read, sidecar: folderHost.readSidecar };
|
||||
}
|
||||
|
||||
/** The saved image of Appearance, from IndexedDB or from an old data URL. */
|
||||
export async function readSavedImage(background: NonNullable<Appearance["newTabBackground"]>): Promise<Blob> {
|
||||
if (background.imageId) {
|
||||
const blob = await readBackgroundImage(background.imageId);
|
||||
if (!blob) throw new Error(tr("The saved background image is missing. Choose the image again."));
|
||||
return blob;
|
||||
}
|
||||
const image = background.image ?? "";
|
||||
const [header, data] = image.split(",");
|
||||
const bytes = Uint8Array.from(atob(data ?? ""), character => character.charCodeAt(0));
|
||||
return new Blob([bytes], { type: header.slice(5, header.indexOf(";")) });
|
||||
}
|
||||
|
||||
/** A short hash of a data URL, so that another old image gets another key. */
|
||||
function hash(text: string): string {
|
||||
let value = 0x811c9dc5;
|
||||
for (let index = 0; index < text.length; index++) value = Math.imul(value ^ text.charCodeAt(index), 0x01000193);
|
||||
return (value >>> 0).toString(16);
|
||||
}
|
||||
|
||||
/** The one saved image. It has no timer. */
|
||||
export function imageSource(background: NonNullable<Appearance["newTabBackground"]>): ImageSource {
|
||||
const id = background.imageId ?? `data:${background.image?.length ?? 0}:${hash(background.image ?? "")}`;
|
||||
return { key: `image:${id}`, timed: false, list: async () => ["image"], read: () => readSavedImage(background), sidecar: async () => null };
|
||||
}
|
||||
|
||||
/** Make a blob URL and decode the image before it shows, so the fade does not wait for the decode. */
|
||||
export async function loadImage(blob: Blob): Promise<LoadedImage> {
|
||||
const url = URL.createObjectURL(blob);
|
||||
try {
|
||||
const image = new Image();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
image.src = url;
|
||||
await Promise.race([image.decode(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(tr("The image took too long to load."))), 10000); })])
|
||||
.finally(() => clearTimeout(timer));
|
||||
return { url, width: image.naturalWidth, height: image.naturalHeight };
|
||||
} catch (error) { URL.revokeObjectURL(url); throw error; }
|
||||
}
|
||||
|
||||
export function browserRuntime(blur: BlurWorker): Runtime {
|
||||
return {
|
||||
load: loadImage,
|
||||
blur: image => blur.blur(image.url, image.width, image.height),
|
||||
release: url => URL.revokeObjectURL(url),
|
||||
later: (callback, milliseconds) => setTimeout(callback, milliseconds),
|
||||
cancel: timer => clearTimeout(timer as ReturnType<typeof setTimeout>),
|
||||
random: Math.random,
|
||||
now: () => Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
/** `next` shows the next image. `reload` reads the folder, the list, and the sidecar again. */
|
||||
export type BackgroundCommand = "next" | "reload";
|
||||
const EVENT = "background-command";
|
||||
|
||||
/** Send a command to the Background instance of every window, this window too. */
|
||||
export async function sendBackgroundCommand(command: BackgroundCommand): Promise<void> {
|
||||
if (isTauri()) await emit(EVENT, command);
|
||||
else window.dispatchEvent(new CustomEvent(EVENT, { detail: command }));
|
||||
}
|
||||
|
||||
/** Receive the commands of every window. Returns the function that stops it. */
|
||||
export function onBackgroundCommand(listener: (command: BackgroundCommand) => void): () => void {
|
||||
const accept = (value: unknown) => { if (value === "next" || value === "reload") listener(value); };
|
||||
if (!isTauri()) {
|
||||
const handle = (event: Event) => accept((event as CustomEvent).detail);
|
||||
window.addEventListener(EVENT, handle);
|
||||
return () => window.removeEventListener(EVENT, handle);
|
||||
}
|
||||
let stopped = false;
|
||||
let off: (() => void) | undefined;
|
||||
void listen<unknown>(EVENT, event => accept(event.payload)).then(unlisten => { if (stopped) unlisten(); else off = unlisten; }, () => undefined);
|
||||
return () => { stopped = true; off?.(); };
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// The settings of the Background feature: the `background` section of the settings file.
|
||||
// This file is in the main bundle, because the launch rule and the first-start migration need it without the feature code.
|
||||
// The image source keeps its image and its layout in `appearance.newTabBackground`, so an older version still shows it.
|
||||
// The host keeps the image folder itself (`src-tauri/src/backgrounds.rs`). The interface never sends a folder path.
|
||||
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
|
||||
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, type Appearance } from "../theme/appearance.ts";
|
||||
import type { LegacyPlugin } from "./migration.ts";
|
||||
|
||||
export const BACKGROUND_SOURCES = ["folder", "image", "none"] as const;
|
||||
export type BackgroundSource = typeof BACKGROUND_SOURCES[number];
|
||||
export type BackgroundPosition = typeof BACKGROUND_POSITIONS[number];
|
||||
export type BackgroundSize = typeof BACKGROUND_SIZES[number];
|
||||
/** The views that show the background: the workspace, all Project Management boards, or one board. */
|
||||
export const BACKGROUND_TARGET = /^(?:app|pm-all|pm-board:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
||||
|
||||
export interface BackgroundLayout {
|
||||
/** From -1 (white) to 1 (black). */
|
||||
overlay: number;
|
||||
position: BackgroundPosition;
|
||||
size: BackgroundSize;
|
||||
}
|
||||
|
||||
export interface BackgroundSettings extends BackgroundLayout {
|
||||
source: BackgroundSource;
|
||||
/** The time of each image of a folder, from 1 to 86,400 seconds. */
|
||||
seconds: number;
|
||||
order: "name" | "random";
|
||||
/** A paused folder keeps its current image. */
|
||||
paused: boolean;
|
||||
targets: string[];
|
||||
}
|
||||
|
||||
export const DEFAULT_BACKGROUND: Readonly<BackgroundSettings> = Object.freeze({
|
||||
source: "none", seconds: 60, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover",
|
||||
});
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
/** The folder layout fields from any value. Invalid fields take the defaults. */
|
||||
export function normalizeLayout(value: unknown): BackgroundLayout {
|
||||
const raw = record(value);
|
||||
return {
|
||||
overlay: typeof raw.overlay === "number" && Number.isFinite(raw.overlay) ? Math.max(-1, Math.min(1, raw.overlay)) : 0,
|
||||
position: BACKGROUND_POSITIONS.includes(raw.position as BackgroundPosition) ? raw.position as BackgroundPosition : "center",
|
||||
size: BACKGROUND_SIZES.includes(raw.size as BackgroundSize) ? raw.size as BackgroundSize : "cover",
|
||||
};
|
||||
}
|
||||
|
||||
/** Valid settings from any value. Invalid fields take the defaults. */
|
||||
export function normalizeBackground(value: unknown): BackgroundSettings {
|
||||
const raw = record(value);
|
||||
return {
|
||||
source: BACKGROUND_SOURCES.includes(raw.source as BackgroundSource) ? raw.source as BackgroundSource : "none",
|
||||
seconds: typeof raw.seconds === "number" && Number.isFinite(raw.seconds) ? Math.max(1, Math.min(86400, Math.round(raw.seconds))) : 60,
|
||||
order: raw.order === "random" ? "random" : "name",
|
||||
paused: raw.paused === true,
|
||||
targets: Array.isArray(raw.targets)
|
||||
? [...new Set(raw.targets.filter((target): target is string => typeof target === "string" && BACKGROUND_TARGET.test(target)))]
|
||||
: ["app"],
|
||||
...normalizeLayout(raw),
|
||||
};
|
||||
}
|
||||
|
||||
export function readBackground(): BackgroundSettings {
|
||||
return normalizeBackground(readSection("background"));
|
||||
}
|
||||
|
||||
/** Save the settings. Keys of a newer version stay. */
|
||||
export function writeBackground(next: BackgroundSettings): Promise<void> {
|
||||
return writeSection("background", { ...record(readSection("background")), ...normalizeBackground(next) });
|
||||
}
|
||||
|
||||
/** True when the appearance has a saved background image. */
|
||||
export function hasImage(appearance: Appearance = readAppearance()): boolean {
|
||||
return !!(appearance.newTabBackground?.image || appearance.newTabBackground?.imageId);
|
||||
}
|
||||
|
||||
/** True when Background has something to show: a folder, or an image that exists. */
|
||||
export function hasBackgroundSource(settings: BackgroundSettings = readBackground(), appearance: Appearance = readAppearance()): boolean {
|
||||
return settings.source === "folder" || (settings.source === "image" && hasImage(appearance));
|
||||
}
|
||||
|
||||
/** Run `listener` after each change of the background or appearance settings. Returns the function that stops it. */
|
||||
export function onBackgroundChange(listener: () => void): () => void {
|
||||
const stops = [onSettingsChange("background", listener), onSettingsChange("appearance", listener)];
|
||||
return () => stops.forEach(stop => stop());
|
||||
}
|
||||
|
||||
/** The host side of the first-start migration of the `background` section. */
|
||||
export interface BackgroundMigrationHost {
|
||||
/** True when the settings file has no `background` section. */
|
||||
missing(): boolean;
|
||||
/** True when the appearance has a saved background image. */
|
||||
hasImage(): boolean;
|
||||
/** Copy the folder of the old plugin grant to the host. True when the host has a folder after the call. */
|
||||
migrateFolder(): Promise<boolean>;
|
||||
write(value: BackgroundSettings): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the `background` section from the old Background Slideshow plugin and the old background image.
|
||||
* The source is the folder when the plugin was installed, enabled, and on, and its folder migrated.
|
||||
* Otherwise it is the image when one exists. The kept plugin settings give the sequence, the targets, and the layout.
|
||||
*/
|
||||
export async function migrateBackground(legacy: LegacyPlugin | undefined, host: BackgroundMigrationHost): Promise<BackgroundSettings> {
|
||||
const kept = record(legacy?.settings);
|
||||
// Migrate the folder whenever a grant exists, so that a later choice of Folder brings it back.
|
||||
let folder = false;
|
||||
if (typeof kept.grant === "string" && kept.grant) {
|
||||
try { folder = await host.migrateFolder(); } catch (reason) { console.error("RuneStone could not take the old background folder.", reason); }
|
||||
}
|
||||
const slideshow = !!legacy?.installed && legacy.enabled && kept.enabled === true && folder;
|
||||
const copied = Object.fromEntries(["seconds", "order", "targets", "overlay", "position", "size"].filter(key => key in kept).map(key => [key, kept[key]]));
|
||||
const value = normalizeBackground({ ...copied, source: slideshow ? "folder" : host.hasImage() ? "image" : "none", paused: false });
|
||||
await host.write(value);
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// The native features of RuneStone. Each feature has an off switch in Settings → Features.
|
||||
// This file is in the main bundle, so it holds only small static data: names, views, commands, and document types.
|
||||
// The code of a feature loads with a dynamic import at first need (see `loader.ts`), and never while its switch is off.
|
||||
import { message, tr } from "../i18n/index.ts";
|
||||
import type { PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
||||
import { identifyPdf } from "./pdfDocument.ts";
|
||||
|
||||
export type FeatureId = "git" | "background" | "terminal" | "pdf" | "pm";
|
||||
|
||||
/** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */
|
||||
export interface FeatureViewInfo {
|
||||
id: string;
|
||||
/** Returns the title in the current language. */
|
||||
title: () => string;
|
||||
placement: "editor" | "sidebar";
|
||||
icon?: PluginView["icon"];
|
||||
/** Show a navigation button for the view. */
|
||||
navigation?: boolean;
|
||||
/** True when a launch, such as a ribbon button, asks the feature which view to open (`FeatureInstance.launch`). */
|
||||
launch?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A family of editor views whose IDs follow a pattern, for example one tab for each board. The session answers for each
|
||||
* matching ID before the feature module loads, so a tab transfer from another window can restore it.
|
||||
* The feature gives the real title later (`FeatureContext.setViewTitle`).
|
||||
*/
|
||||
export interface FeatureViewPattern {
|
||||
/** Matches the whole view ID. */
|
||||
match: RegExp;
|
||||
/** The title until the feature gives one. */
|
||||
title: () => string;
|
||||
icon?: PluginView["icon"];
|
||||
}
|
||||
|
||||
/** A command of a feature. The command palette lists it. */
|
||||
export interface FeatureCommandInfo {
|
||||
id: string;
|
||||
title: () => string;
|
||||
icon?: PluginCommand["icon"];
|
||||
/** The view that the command opens. Without a view, the command loads the feature and calls `FeatureInstance.run`. */
|
||||
view?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A document type of a feature. The file tree marks the files of the type, and a click opens them in a tab,
|
||||
* without the feature code. The first tab of the type loads the feature and calls `FeatureInstance.mountDocument`.
|
||||
*/
|
||||
export interface FeatureDocumentInfo {
|
||||
id: string;
|
||||
/** Returns the title in the current language. The file tree shows it as the tooltip of the file icon. */
|
||||
title: () => string;
|
||||
icon: NonNullable<PluginDocumentType["icon"]>;
|
||||
/** Lowercase file extensions without the dot. */
|
||||
extensions: readonly string[];
|
||||
/** "binary" when `identify` needs no file contents. */
|
||||
content: "text" | "binary";
|
||||
/** The document ID of a file, or null when the file is not of this type. */
|
||||
identify(path: string, source: string): { id: string } | null;
|
||||
}
|
||||
|
||||
export interface FeatureEntry {
|
||||
id: FeatureId;
|
||||
/** The ID of the old plugin package. Saved tabs and tab transfers keep it as the owner ID. */
|
||||
owner: string;
|
||||
/** Catalog keys for Settings → Features. */
|
||||
name: string;
|
||||
description: string;
|
||||
/** Extra words for the Settings search. */
|
||||
keywords: string;
|
||||
/** The switch for a user who never installed the old package. */
|
||||
defaultOn: boolean;
|
||||
/** True when the first start gives the switch the state of the old package. False when every user gets `defaultOn`. */
|
||||
followsPackage: boolean;
|
||||
views: readonly FeatureViewInfo[];
|
||||
/** Editor views with IDs that follow a pattern. */
|
||||
viewPatterns?: readonly FeatureViewPattern[];
|
||||
commands: readonly FeatureCommandInfo[];
|
||||
documentTypes: readonly FeatureDocumentInfo[];
|
||||
}
|
||||
|
||||
export const FEATURES: readonly FeatureEntry[] = [
|
||||
{
|
||||
id: "git", owner: "runestone.git", name: message("Git"),
|
||||
description: message("Review changes, stage files, commit, and see the commit graph of the workspace repository."),
|
||||
keywords: "git source control commit stage diff graph branch push pull blame",
|
||||
defaultOn: true, followsPackage: true,
|
||||
views: [
|
||||
{ id: "source-control", title: () => tr("Source control"), placement: "sidebar", icon: "git", navigation: true },
|
||||
{ id: "diff", title: () => tr("Git diff"), placement: "editor", icon: "git" },
|
||||
{ id: "graph", title: () => tr("Git graph"), placement: "editor", icon: "git" },
|
||||
],
|
||||
commands: [{ id: "graph", title: () => tr("Show Git graph"), icon: "git", view: "graph" }],
|
||||
documentTypes: [],
|
||||
},
|
||||
{
|
||||
// Background replaces the Background Slideshow plugin and the background image of Appearance. Its settings are in
|
||||
// Appearance → Background. It loads at the start only when a folder or an image is selected (see `launch.ts`).
|
||||
id: "background", owner: "runestone.bg-slideshow", name: message("Background"),
|
||||
description: message("Show a folder of images as a slideshow, or one image, behind the workspace and the boards."),
|
||||
keywords: "background image wallpaper slideshow folder picture photo overlay blur",
|
||||
defaultOn: true, followsPackage: false,
|
||||
views: [],
|
||||
commands: [
|
||||
{ id: "next", title: () => tr("Next background image"), icon: "image" },
|
||||
{ id: "pause", title: () => tr("Pause background"), icon: "pause" },
|
||||
],
|
||||
documentTypes: [],
|
||||
},
|
||||
{
|
||||
// Terminal replaces the Terminal plugin. Its panel is not a view: the workbench and the terminal window show it
|
||||
// (`src/lib/features/TerminalHost.svelte`), and the first use loads the module. Its settings are in Settings → Terminal.
|
||||
id: "terminal", owner: "runestone.terminal", name: message("Terminal"),
|
||||
description: message("Run shells, tasks, and the active file in a panel below the editor or in a separate window."),
|
||||
keywords: "terminal shell console powershell bash cmd command prompt task run pty xterm",
|
||||
defaultOn: true, followsPackage: true,
|
||||
views: [],
|
||||
commands: [],
|
||||
documentTypes: [],
|
||||
},
|
||||
{
|
||||
// PDF Viewer replaces the PDF Viewer plugin. It has no view: its document type opens each PDF file in its own tab.
|
||||
// The file tree marks PDF files without the module. The first PDF tab loads the module and PDF.js.
|
||||
id: "pdf", owner: "runestone.pdf-viewer", name: message("PDF Viewer"),
|
||||
description: message("Read PDF files of the workspace in tabs, with page controls, zoom, rotation, and text selection."),
|
||||
keywords: "pdf document viewer page zoom rotate password pdf.js",
|
||||
defaultOn: true, followsPackage: true,
|
||||
views: [],
|
||||
commands: [],
|
||||
documentTypes: [
|
||||
{ id: "pdf", title: () => tr("PDF document"), icon: "file", extensions: ["pdf"], content: "binary", identify: identifyPdf },
|
||||
],
|
||||
},
|
||||
{
|
||||
// Project Management replaces the Project Management plugin. It reads only `.runestone/pm/` in the workspace, so the
|
||||
// file tree reads no Markdown file for it. Its ribbon button opens `planning`: the default board of the workspace, or
|
||||
// All tasks. Each board has its own tab, `board-<hex of the board ID>`, as in the plugin, so tab transfers between
|
||||
// the plugin and the feature work. Its settings are in Settings → Project Management (`ProjectManagementSettings.svelte`).
|
||||
id: "pm", owner: "runestone.pm", name: message("Project Management"),
|
||||
description: message("Plan work on Kanban boards, in All tasks, and on Gantt and calendar views. The cards stay in the workspace."),
|
||||
keywords: "project management kanban board card task list gantt calendar label priority backlog todo plan",
|
||||
defaultOn: true, followsPackage: true,
|
||||
views: [{ id: "planning", title: () => tr("Project Management"), placement: "editor", icon: "kanban", launch: true }],
|
||||
viewPatterns: [{ match: /^board-(?:[0-9a-f]{2})+$/, title: () => tr("Project Management"), icon: "kanban" }],
|
||||
commands: [],
|
||||
documentTypes: [],
|
||||
},
|
||||
];
|
||||
|
||||
export function featureEntry(id: FeatureId): FeatureEntry {
|
||||
const entry = FEATURES.find(item => item.id === id);
|
||||
if (!entry) throw new Error(`Unknown feature: ${id}`);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/** The feature that uses `owner` as its owner ID, if any. */
|
||||
export function featureOfOwner(owner: string): FeatureEntry | undefined {
|
||||
return FEATURES.find(item => item.owner === owner);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<script lang="ts">
|
||||
import { diffLineKind } from "./model";
|
||||
let { text, error = false, label }: { text: string; error?: boolean; label: string } = $props();
|
||||
const lines = $derived(text.split("\n"));
|
||||
</script>
|
||||
|
||||
<!-- One block element for each line, so that the add and remove fills cover the full width.
|
||||
The diff takes focus, so that a keyboard user can scroll it. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
|
||||
<pre class="diff" class:error tabindex="0" aria-label={label}>{#each lines as line, index (index)}<span class="line {diffLineKind(line)}">{line || " "}</span>{/each}</pre>
|
||||
|
||||
<style>
|
||||
.diff { flex: 1; min-height: 0; margin: 0; padding: 8px; overflow: auto; font: 12px/1.6 var(--rs-font-mono); font-weight: var(--rs-code-font-weight); tab-size: 4; background: var(--rs-image-editor-bg, var(--rs-bg)); border-radius: var(--rs-control-radius); }
|
||||
.diff:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.line { display: block; min-width: max-content; min-height: 1.6em; }
|
||||
.add { background: color-mix(in srgb, var(--rs-ok) 18%, transparent); }
|
||||
.remove { background: color-mix(in srgb, var(--rs-error) 18%, transparent); }
|
||||
.range { color: var(--rs-accent); }
|
||||
.error { color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,39 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import DiffText from "./DiffText.svelte";
|
||||
import type { GitState } from "./state.svelte";
|
||||
|
||||
let { git, openFile }: { git: GitState; openFile: (path: string) => Promise<void> } = $props();
|
||||
let error = $state("");
|
||||
|
||||
const title = $derived(git.selected
|
||||
? git.selected.staged ? $t("{path} · Staged", { path: git.selected.path }) : $t("{path} · Working tree", { path: git.selected.path })
|
||||
: $t("Git diff"));
|
||||
|
||||
async function open() {
|
||||
if (!git.selected) return;
|
||||
error = "";
|
||||
try { await openFile(git.selected.path); }
|
||||
catch (reason) { error = String(reason); }
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="git-diff">
|
||||
<div class="header">
|
||||
<strong>{title}</strong>
|
||||
<button class="text-button" type="button" disabled={!git.selected} onclick={open}>{$t("Open file")}</button>
|
||||
</div>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<DiffText text={git.selected?.text ?? $t("Select a file in Source control to see its diff.")} error={!!git.selected?.error} label={$t("Git diff")} />
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.git-diff { display: flex; flex-direction: column; gap: 10px; height: 100%; padding: 12px; box-sizing: border-box; overflow: hidden; font-size: 13px; }
|
||||
.header { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
strong { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
||||
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
|
||||
.text-button:hover:not(:disabled) { background: var(--rs-hover-bg); }
|
||||
.text-button:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.text-button:disabled { color: var(--rs-text-dim); }
|
||||
.error { margin: 0; color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,244 @@
|
||||
<script lang="ts">
|
||||
import { onMount, tick, untrack } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { attachTooltip } from "$lib/ui/tooltip";
|
||||
import { gitApi } from "$lib/git/service";
|
||||
import type { GitCommitDetails, GitCommitFile, GitGraph } from "$lib/git/contracts";
|
||||
import { graphLayout } from "./model";
|
||||
import DiffText from "./DiffText.svelte";
|
||||
import type { GitState } from "./state.svelte";
|
||||
|
||||
let { git }: { git: GitState } = $props();
|
||||
|
||||
const rowHeight = 30;
|
||||
const x = (lane: number) => 12 + lane * 18;
|
||||
const y = (row: number) => rowHeight / 2 + row * rowHeight;
|
||||
|
||||
let history = $state.raw<GitGraph | null>(null);
|
||||
let graphMessage = $state(tr("Loading history…"));
|
||||
let graphError = $state(false);
|
||||
let refreshing = $state(false);
|
||||
let detail = $state.raw<GitCommitDetails | null>(null);
|
||||
let detailMessage = $state(tr("Select a commit."));
|
||||
let diff = $state<{ text: string; error: boolean } | null>(null);
|
||||
let list: HTMLOListElement | undefined = $state();
|
||||
let disposed = false, generation = 0, selection = 0, fileRequest = 0;
|
||||
|
||||
const layout = $derived(graphLayout(history));
|
||||
|
||||
function tooltip(node: HTMLElement, text: string) {
|
||||
let current = text;
|
||||
const dispose = attachTooltip(node, () => current);
|
||||
return { update(value: string) { current = value; }, destroy: dispose };
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const request = ++generation;
|
||||
refreshing = true;
|
||||
try {
|
||||
const result = await gitApi.graph();
|
||||
if (disposed || request !== generation) return;
|
||||
history = result;
|
||||
graphError = false;
|
||||
graphMessage = result.commits.length ? "" : tr("No commits yet. Create a commit to start the graph.");
|
||||
const kept = result.commits.some(commit => commit.id === git.history.selectedId) ? git.history.selectedId : result.commits[0]?.id ?? null;
|
||||
if (kept) {
|
||||
if (kept !== detail?.id || kept !== git.history.selectedId) void select(kept);
|
||||
} else {
|
||||
git.history.selectedId = null;
|
||||
++selection; ++fileRequest;
|
||||
detail = null; diff = null;
|
||||
detailMessage = tr("No commit is selected.");
|
||||
}
|
||||
} catch (reason) {
|
||||
if (disposed || request !== generation) return;
|
||||
history = null;
|
||||
graphError = true;
|
||||
graphMessage = String(reason);
|
||||
++selection; ++fileRequest;
|
||||
detail = null; diff = null;
|
||||
detailMessage = tr("Select Refresh to try again.");
|
||||
} finally {
|
||||
if (!disposed && request === generation) refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function select(id: string) {
|
||||
git.history.selectedId = id;
|
||||
const request = ++selection;
|
||||
++fileRequest;
|
||||
detailMessage = tr("Loading commit…");
|
||||
try {
|
||||
const result = await gitApi.commitDetails(id);
|
||||
if (disposed || request !== selection) return;
|
||||
detail = result;
|
||||
diff = null;
|
||||
const file = result.files.find(item => item.path === git.history.file) ?? result.files[0];
|
||||
if (file) void selectFile(file, result);
|
||||
} catch (reason) {
|
||||
if (disposed || request !== selection) return;
|
||||
detail = null;
|
||||
detailMessage = String(reason);
|
||||
}
|
||||
}
|
||||
|
||||
async function selectFile(file: GitCommitFile, commit: GitCommitDetails) {
|
||||
git.history.file = file.path;
|
||||
const request = ++fileRequest;
|
||||
diff = { text: tr("Loading diff…"), error: false };
|
||||
try {
|
||||
const text = await gitApi.commitDiff(commit.id, file.path);
|
||||
if (disposed || request !== fileRequest || git.history.selectedId !== commit.id) return;
|
||||
diff = { text: text || tr("No text changes."), error: false };
|
||||
} catch (reason) {
|
||||
if (!disposed && request === fileRequest) diff = { text: String(reason), error: true };
|
||||
}
|
||||
}
|
||||
|
||||
async function keydown(event: KeyboardEvent) {
|
||||
const commits = layout.nodes;
|
||||
const index = commits.findIndex(commit => commit.id === git.history.selectedId);
|
||||
const next = event.key === "ArrowDown" ? Math.min(commits.length - 1, index + 1)
|
||||
: event.key === "ArrowUp" ? Math.max(0, index - 1)
|
||||
: event.key === "Home" ? 0 : event.key === "End" ? commits.length - 1 : -1;
|
||||
if (next < 0 || !commits[next]) return;
|
||||
event.preventDefault();
|
||||
void select(commits[next].id);
|
||||
await tick();
|
||||
list?.querySelector<HTMLButtonElement>(`[data-commit="${commits[next].id}"]`)?.focus();
|
||||
}
|
||||
|
||||
// The graph reads the history again after a commit, push, or pull, and on window focus.
|
||||
$effect(() => {
|
||||
void git.historyVersion;
|
||||
untrack(() => void refresh());
|
||||
});
|
||||
onMount(() => {
|
||||
const focus = () => void refresh();
|
||||
window.addEventListener("focus", focus);
|
||||
return () => { disposed = true; ++generation; ++selection; ++fileRequest; window.removeEventListener("focus", focus); };
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="git-graph" aria-label={$t("Git history")}>
|
||||
<div class="header">
|
||||
<strong>{$t("Commit graph")}</strong>
|
||||
<IconButton icon="refresh" label={$t("Refresh commit graph")} disabled={refreshing} onclick={() => void refresh()} />
|
||||
</div>
|
||||
<p class="hint">{$t("Latest 100 commits. Select a commit to see its files. Dashed lines continue beyond this history.")}</p>
|
||||
<div class="body">
|
||||
<div class="graph" aria-label={$t("Commit graph with branches, authors, and dates")}>
|
||||
{#if graphMessage}
|
||||
<p class:error={graphError}>{graphMessage}</p>
|
||||
{:else}
|
||||
<div class="canvas">
|
||||
<svg width={layout.lanes * 18 + 12} height={layout.nodes.length * rowHeight} aria-hidden="true" class="lines">
|
||||
{#each layout.edges as edge (`${edge.from}:${edge.to}`)}
|
||||
{@const middle = y(edge.row) + rowHeight / 2}
|
||||
<path class="edge" class:boundary={edge.outside} style:color={`var(--git-lane-${edge.color + 1})`}
|
||||
d={`M ${x(edge.lane)} ${y(edge.row)} C ${x(edge.lane)} ${middle} ${x(edge.parentLane)} ${middle} ${x(edge.parentLane)} ${y(edge.row) + rowHeight} L ${x(edge.parentLane)} ${y(edge.endRow)}`} />
|
||||
{/each}
|
||||
{#each layout.nodes as commit (commit.id)}
|
||||
<circle class="node" cx={x(commit.lane)} cy={y(commit.row)} r="4" style:color={`var(--git-lane-${commit.color + 1})`} />
|
||||
{/each}
|
||||
</svg>
|
||||
<ol role="listbox" aria-label={$t("Commits")} bind:this={list} onkeydown={keydown}>
|
||||
{#each layout.nodes as commit (commit.id)}
|
||||
{@const selected = commit.id === git.history.selectedId}
|
||||
<li>
|
||||
<button type="button" role="option" data-commit={commit.id} aria-selected={selected}
|
||||
tabindex={selected || (!git.history.selectedId && commit.row === 0) ? 0 : -1}
|
||||
use:tooltip={`${commit.summary}\n${commit.author} · ${commit.date}\n${commit.id}`}
|
||||
onclick={() => void select(commit.id)}>
|
||||
<span class="description">
|
||||
{#if commit.refs.length}<span class="refs">{commit.refs.join(" · ")}</span>{/if}
|
||||
<span class="summary">{commit.summary}</span>
|
||||
</span>
|
||||
<span class="meta author">{commit.author}</span>
|
||||
<span class="meta date">{commit.date}</span>
|
||||
<span class="meta">{commit.id.slice(0, 7)}</span>
|
||||
<span class="screen-reader">{commit.parents.length ? $t("Parents: {parents}", { parents: commit.parents.join(", ") }) : $t("Root commit")}</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ol>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<section class="details" aria-label={$t("Commit details")}>
|
||||
{#if detail}
|
||||
<div class="detail-meta">
|
||||
<strong>{detail.author}</strong>
|
||||
<time>{detail.date}</time>
|
||||
<code>{detail.id}</code>
|
||||
{#if detail.parents.length > 1}<span class="dim">{$t("Changes against the first parent.")}</span>{/if}
|
||||
</div>
|
||||
<p class="message">{detail.message}</p>
|
||||
<strong>{$t("Changed files: {count}", { count: detail.files.length })}</strong>
|
||||
<div class="files" aria-label={$t("Changed files")}>
|
||||
{#each detail.files as file (file.path)}
|
||||
<button type="button" class="file" aria-pressed={file.path === git.history.file}
|
||||
use:tooltip={file.originalPath ? `${file.originalPath} → ${file.path}` : file.path}
|
||||
onclick={() => void selectFile(file, detail!)}>
|
||||
<span>{file.path}</span><span class="dim">{file.status}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{#if diff}
|
||||
<DiffText text={diff.text} error={diff.error} label={$t("Commit file diff")} />
|
||||
{:else}
|
||||
<p class="dim">{detail.files.length ? $t("Select a file to see its diff.") : $t("This commit contains no file changes.")}</p>
|
||||
{/if}
|
||||
{:else}
|
||||
<p class="dim">{detailMessage}</p>
|
||||
{/if}
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.git-graph { container-type: inline-size; display: flex; flex-direction: column; gap: 6px; height: 100%; padding: 8px; box-sizing: border-box; overflow: hidden; font-size: 13px;
|
||||
--git-lane-1: #007fff; --git-lane-2: #ca7000; --git-lane-3: #f000ff; --git-lane-4: #00a000; --git-lane-5: #aa00ff; --git-lane-6: #ff0033; }
|
||||
.header, .hint { padding: 4px 6px; border-radius: var(--rs-control-radius); background: var(--rs-image-control-bg, var(--rs-bg)); }
|
||||
.header { display: flex; align-items: center; gap: 6px; }
|
||||
.header strong { flex: 1; }
|
||||
.hint { margin: 0; font-size: 11px; color: var(--rs-text-dim); }
|
||||
.body { display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, 32%); flex: 1; min-height: 0; min-width: 0; }
|
||||
.graph { min-height: 0; min-width: 0; padding: 4px; overflow: auto; background: var(--rs-image-editor-bg, var(--rs-bg)); }
|
||||
.graph p { margin: 8px; color: var(--rs-text-dim); }
|
||||
.graph p.error { color: var(--rs-error); }
|
||||
.canvas { display: flex; align-items: flex-start; min-width: 0; }
|
||||
.lines { flex: 0 0 auto; overflow: hidden; }
|
||||
.edge { fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
.boundary { stroke-dasharray: 3 3; }
|
||||
.node { fill: currentColor; stroke: currentColor; stroke-width: 2; }
|
||||
ol { flex: 1; min-width: 0; margin: 0; padding: 0; list-style: none; }
|
||||
li { height: 30px; min-width: 0; }
|
||||
ol button { display: grid; grid-template-columns: minmax(0, 1fr) 95px 78px 54px; align-items: center; gap: 8px; width: 100%; height: 30px; padding: 0 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
|
||||
ol button:hover { background: var(--rs-hover-bg); }
|
||||
ol button[aria-selected="true"], .file[aria-pressed="true"] { background: var(--rs-item-selection-bg); border-color: var(--rs-item-selection-border); }
|
||||
ol button:focus-visible, .file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.description { display: flex; align-items: center; gap: 5px; min-width: 0; }
|
||||
.summary, .refs, .meta { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.summary { flex: 1; }
|
||||
.refs { max-width: 45%; padding: 1px 4px; border-radius: var(--rs-control-radius); background: var(--rs-bg-active); color: var(--rs-accent); font-size: 11px; }
|
||||
.meta, .dim { color: var(--rs-text-dim); font-size: 11px; }
|
||||
.screen-reader { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
|
||||
.details { display: flex; flex-direction: column; gap: 8px; min-height: 0; min-width: 0; padding: 10px; overflow: auto; border-left: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-image-editor-bg, var(--rs-bg)); }
|
||||
.details p { margin: 0; }
|
||||
.detail-meta { display: flex; flex-direction: column; gap: 3px; overflow-wrap: anywhere; }
|
||||
time { color: var(--rs-text-dim); }
|
||||
code { font: 11px var(--rs-font-mono); overflow-wrap: anywhere; }
|
||||
.message { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.files { display: flex; flex-direction: column; flex-shrink: 0; max-height: 180px; overflow: auto; }
|
||||
.file { display: flex; flex-shrink: 0; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 3px 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
|
||||
.file:hover { background: var(--rs-hover-bg); }
|
||||
.file span:first-child { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.details :global(.diff) { min-height: 140px; }
|
||||
@container (max-width: 950px) { ol button { grid-template-columns: minmax(0, 1fr) 54px; } .author, .date { display: none; } }
|
||||
@container (max-width: 650px) {
|
||||
.body { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(140px, 45%) minmax(0, 1fr); }
|
||||
.details { border-left: 0; border-top: 1px solid var(--rs-border); }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,201 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { attachTooltip } from "$lib/ui/tooltip";
|
||||
import { keys } from "$lib/ui/shortcuts";
|
||||
import { gitApi } from "$lib/git/service";
|
||||
import type { GitChange, GitStatus } from "$lib/git/contracts";
|
||||
import { changeLabel, groups, isConflict, pathsFor } from "./model";
|
||||
import type { GitState } from "./state.svelte";
|
||||
|
||||
let { git, showDiff, showGraph, onWorkspaceChange }: {
|
||||
git: GitState;
|
||||
showDiff: (path: string, staged: boolean) => void;
|
||||
showGraph: () => void;
|
||||
onWorkspaceChange: (listener: () => void) => () => void;
|
||||
} = $props();
|
||||
|
||||
let snapshot = $state<GitStatus | null>(null);
|
||||
let busy = $state(false);
|
||||
let refreshing = $state(false);
|
||||
let message = $state("");
|
||||
let notice = $state({ text: tr("Loading repository…"), error: false });
|
||||
let disposed = false;
|
||||
let sequence = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const grouped = $derived(snapshot?.repository ? groups(snapshot.changes) : { staged: [], working: [] });
|
||||
const conflicts = $derived(!!snapshot?.changes.some(isConflict));
|
||||
const canCommit = $derived(!!snapshot?.repository && grouped.staged.length > 0 && !conflicts && message.trim().length > 0);
|
||||
|
||||
function tooltip(node: HTMLElement, text: string) {
|
||||
let current = text;
|
||||
const dispose = attachTooltip(node, () => current);
|
||||
return { update(value: string) { current = value; }, destroy: dispose };
|
||||
}
|
||||
function report(text: string, error = false) { notice = { text, error }; }
|
||||
|
||||
async function refresh(keepNotice = false) {
|
||||
if (disposed || busy) return;
|
||||
const request = ++sequence;
|
||||
refreshing = true;
|
||||
try {
|
||||
const result = await gitApi.status();
|
||||
if (disposed || request !== sequence) return;
|
||||
snapshot = result;
|
||||
if (!result.available) report(tr("Git is not installed. Install Git, then restart RuneStone."));
|
||||
else if (!result.repository) report(tr("Open a Git repository root as your workspace. Create repositories with Git outside RuneStone."));
|
||||
else if (result.changes.some(isConflict)) report(tr("Resolve the conflicts, then stage the files before you commit."));
|
||||
else if (!keepNotice) report(result.changes.length ? "" : tr("No changes. Your working tree is clean."));
|
||||
} catch (reason) {
|
||||
if (!disposed && request === sequence) { snapshot = null; report(String(reason), true); }
|
||||
} finally {
|
||||
if (request === sequence) refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Run one Git action at a time, then read the status again. */
|
||||
async function perform(action: () => Promise<void>, changesHistory = false) {
|
||||
if (busy || disposed) return;
|
||||
busy = true;
|
||||
clearTimeout(timer);
|
||||
++sequence;
|
||||
report("");
|
||||
try {
|
||||
await action();
|
||||
if (changesHistory) git.historyVersion++;
|
||||
} catch (reason) {
|
||||
if (!disposed) report(String(reason), true);
|
||||
} finally {
|
||||
busy = false;
|
||||
if (!disposed) await refresh(true);
|
||||
}
|
||||
}
|
||||
|
||||
function stage(changes: GitChange[], staged: boolean) {
|
||||
void perform(() => staged ? gitApi.unstage(pathsFor(changes)) : gitApi.stage(pathsFor(changes)));
|
||||
}
|
||||
function commit() {
|
||||
if (!canCommit) return;
|
||||
void perform(async () => {
|
||||
await gitApi.commit(message);
|
||||
message = "";
|
||||
report(tr("Commit created."));
|
||||
}, true);
|
||||
}
|
||||
function pull() {
|
||||
void perform(async () => {
|
||||
report(tr("Pull in progress…"));
|
||||
await gitApi.pull();
|
||||
report(tr("Pull complete. The branch is up to date."));
|
||||
}, true);
|
||||
}
|
||||
function push() {
|
||||
void perform(async () => {
|
||||
report(tr("Push in progress…"));
|
||||
await gitApi.push();
|
||||
report(tr("Push complete."));
|
||||
}, true);
|
||||
}
|
||||
function rowLabel(change: GitChange, staged: boolean) {
|
||||
const status = changeLabel(change, staged);
|
||||
return change.originalPath
|
||||
? $t("{path} — {status}, from {original}", { path: change.path, status, original: change.originalPath })
|
||||
: $t("{path} — {status}", { path: change.path, status });
|
||||
}
|
||||
|
||||
// The status refreshes after a workspace change, which includes the `.git` folder, and on window focus.
|
||||
function schedule() {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => void refresh(), 350);
|
||||
}
|
||||
onMount(() => {
|
||||
const off = onWorkspaceChange(schedule);
|
||||
window.addEventListener("focus", schedule);
|
||||
void refresh();
|
||||
return () => {
|
||||
disposed = true;
|
||||
sequence++;
|
||||
clearTimeout(timer);
|
||||
off();
|
||||
window.removeEventListener("focus", schedule);
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="source-control" aria-label={$t("Git source control")} aria-busy={busy}>
|
||||
<div class="header">
|
||||
<span class="branch" use:tooltip={snapshot?.branch ?? $t("Source control")}>{snapshot?.branch ?? $t("Source control")}</span>
|
||||
{#if snapshot?.repository}
|
||||
<IconButton icon="git" label={$t("Show Git graph")} disabled={busy} onclick={showGraph} />
|
||||
<IconButton icon="download" label={$t("Pull from the upstream branch")} disabled={busy} onclick={pull} />
|
||||
<IconButton icon="upload" label={$t("Push to the upstream branch")} disabled={busy} onclick={push} />
|
||||
{/if}
|
||||
<IconButton icon="refresh" label={$t("Refresh source control")} disabled={busy || refreshing} onclick={() => void refresh()} />
|
||||
</div>
|
||||
<p class="notice" class:error={notice.error} role="status" hidden={!notice.text}>{notice.text}</p>
|
||||
{#if snapshot?.repository}
|
||||
<form class="commit" onsubmit={event => { event.preventDefault(); commit(); }}>
|
||||
<textarea rows="3" maxlength="65536" placeholder={$t("Commit message")} aria-label={$t("Commit message")} disabled={busy} bind:value={message}
|
||||
onkeydown={event => { if ((event.ctrlKey || event.metaKey) && event.key === "Enter") { event.preventDefault(); commit(); } }}></textarea>
|
||||
<button class="primary" type="submit" disabled={busy || !canCommit}><Icon icon="check" /><span>{$t("Commit staged")}</span></button>
|
||||
<small>{$t("Only staged files enter the commit. Press {shortcut} to commit.", { shortcut: keys("Mod+Enter") })}</small>
|
||||
</form>
|
||||
<details class="changes" open>
|
||||
<summary>{$t("Changes ({count})", { count: snapshot.changes.length })}</summary>
|
||||
{#each [{ staged: true, changes: grouped.staged }, { staged: false, changes: grouped.working }] as group (group.staged)}
|
||||
{#if group.changes.length}
|
||||
<section class="group">
|
||||
<div class="group-header">
|
||||
<h3>{group.staged ? $t("Staged changes ({count})", { count: group.changes.length }) : $t("Unstaged changes ({count})", { count: group.changes.length })}</h3>
|
||||
<IconButton icon={group.staged ? "minus" : "plus"} label={group.staged ? $t("Unstage all") : $t("Stage all")} disabled={busy} onclick={() => stage(group.changes, group.staged)} />
|
||||
</div>
|
||||
{#each group.changes as change (change.path)}
|
||||
<div class="row">
|
||||
<button class="file" type="button" disabled={busy} aria-label={rowLabel(change, group.staged)} use:tooltip={rowLabel(change, group.staged)} onclick={() => showDiff(change.path, group.staged)}>
|
||||
<Icon icon="text" /><span>{change.path}</span>
|
||||
</button>
|
||||
<span class="status">{changeLabel(change, group.staged)}</span>
|
||||
<IconButton icon={group.staged ? "minus" : "plus"} label={group.staged ? $t("Unstage {path}", { path: change.path }) : $t("Stage {path}", { path: change.path })} disabled={busy} onclick={() => stage([change], group.staged)} />
|
||||
</div>
|
||||
{/each}
|
||||
</section>
|
||||
{/if}
|
||||
{/each}
|
||||
</details>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.source-control { display: flex; flex-direction: column; gap: 8px; height: 100%; min-width: 0; padding: 6px; overflow: auto; box-sizing: border-box; font-size: 13px; }
|
||||
.header { display: flex; align-items: center; gap: 2px; min-width: 0; }
|
||||
.branch { flex: 1; min-width: 0; padding-left: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
|
||||
.notice { margin: 0; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--rs-text-dim); }
|
||||
.notice.error { color: var(--rs-error); }
|
||||
.notice[hidden] { display: none; }
|
||||
.commit { display: flex; flex-direction: column; gap: 5px; flex: 0 0 auto; }
|
||||
textarea { box-sizing: border-box; width: 100%; min-height: 60px; resize: vertical; padding: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
textarea:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
|
||||
.primary { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 28px; padding: 3px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; font-weight: 600; }
|
||||
.primary:hover:not(:disabled) { background: var(--rs-hover-bg); }
|
||||
.primary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.primary:disabled { color: var(--rs-text-dim); }
|
||||
small { color: var(--rs-text-dim); line-height: 1.5; }
|
||||
.changes { min-width: 0; border-top: 1px solid var(--rs-border); }
|
||||
summary { padding: 8px 4px; border-radius: var(--rs-control-radius); cursor: pointer; font-weight: 600; }
|
||||
summary:hover { background: var(--rs-hover-bg); }
|
||||
summary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.group { margin-bottom: 6px; }
|
||||
.group-header { display: flex; align-items: center; gap: 6px; padding-bottom: 4px; }
|
||||
h3 { flex: 1; margin: 0; padding-left: 4px; font: inherit; font-weight: 600; }
|
||||
.row { display: flex; align-items: center; gap: 3px; min-width: 0; }
|
||||
.file { display: flex; flex: 1; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 4px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
|
||||
.file:hover:not(:disabled) { background: var(--rs-hover-bg); }
|
||||
.file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.file:disabled { color: var(--rs-text-dim); }
|
||||
.file span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.status { color: var(--rs-text-dim); font-size: 11px; white-space: nowrap; }
|
||||
@media (max-width: 450px) { .status { display: none; } }
|
||||
</style>
|
||||
@@ -0,0 +1,62 @@
|
||||
// The Git feature. `loader.ts` imports this module at first need: the Source control pane, a Git tab, or the graph command.
|
||||
// It uses the host Git service directly. `src-tauri/src/git.rs` runs the `git` program for the workspace of the window.
|
||||
import { mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { gitApi } from "../../git/service.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import { GitState } from "./state.svelte.ts";
|
||||
import SourceControl from "./SourceControl.svelte";
|
||||
import GitDiff from "./GitDiff.svelte";
|
||||
import GitGraph from "./GitGraph.svelte";
|
||||
|
||||
export function start(context: FeatureContext): FeatureInstance {
|
||||
const state = new GitState();
|
||||
|
||||
async function loadDiff(path: string, staged: boolean) {
|
||||
const sequence = ++state.sequence;
|
||||
state.selected = { path, staged, text: tr("Loading diff…"), error: false };
|
||||
try {
|
||||
const text = await gitApi.diff(path, staged);
|
||||
if (state.disposed || sequence !== state.sequence) return;
|
||||
state.selected = { path, staged, text: text || tr("No text changes."), error: false };
|
||||
} catch (reason) {
|
||||
if (state.disposed || sequence !== state.sequence) return;
|
||||
state.selected = { path, staged, text: String(reason), error: true };
|
||||
}
|
||||
}
|
||||
|
||||
const views: Record<string, (target: HTMLElement) => Record<string, unknown>> = {
|
||||
"source-control": target => mount(SourceControl, { target, props: {
|
||||
git: state,
|
||||
showDiff: (path: string, staged: boolean) => { context.openView("diff"); void loadDiff(path, staged); },
|
||||
showGraph: () => context.openView("graph"),
|
||||
onWorkspaceChange: context.onWorkspaceChange,
|
||||
} }),
|
||||
diff: target => mount(GitDiff, { target, props: { git: state, openFile: context.openFile } }),
|
||||
graph: target => mount(GitGraph, { target, props: { git: state } }),
|
||||
};
|
||||
|
||||
return {
|
||||
mount(view, element) {
|
||||
const create = views[view];
|
||||
if (!create) throw new Error(tr("This view is unavailable."));
|
||||
const component = create(element);
|
||||
return () => unmount(component);
|
||||
},
|
||||
saveTabState(view) {
|
||||
if (view === "diff") return state.selected ? { path: state.selected.path, staged: state.selected.staged } : null;
|
||||
if (view === "graph") return { selectedId: state.history.selectedId, file: state.history.file };
|
||||
return undefined;
|
||||
},
|
||||
async restoreTabState(view, value) {
|
||||
const saved = value && typeof value === "object" ? value as Record<string, unknown> : null;
|
||||
if (!saved) return;
|
||||
if (view === "diff" && typeof saved.path === "string" && typeof saved.staged === "boolean") await loadDiff(saved.path, saved.staged);
|
||||
if (view === "graph") {
|
||||
state.history.selectedId = typeof saved.selectedId === "string" ? saved.selectedId : null;
|
||||
state.history.file = typeof saved.file === "string" ? saved.file : null;
|
||||
}
|
||||
},
|
||||
dispose() { state.disposed = true; state.sequence++; },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Pure Git helpers of the Git feature: change groups, labels, and the lanes of the commit graph.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { GitChange, GitGraph, GitGraphCommit } from "../../git/contracts.ts";
|
||||
|
||||
export function isConflict(change: GitChange): boolean {
|
||||
return change.index === "U" || change.worktree === "U" || ["AA", "DD"].includes(change.index + change.worktree);
|
||||
}
|
||||
|
||||
/** Staged changes and working tree changes. A conflict shows only with the working tree changes. */
|
||||
export function groups(changes: GitChange[]): { staged: GitChange[]; working: GitChange[] } {
|
||||
return {
|
||||
staged: changes.filter(change => !isConflict(change) && ![" ", "?", "!"].includes(change.index)),
|
||||
working: changes.filter(change => isConflict(change) || ![" ", "!"].includes(change.worktree)),
|
||||
};
|
||||
}
|
||||
|
||||
/** The paths to stage or unstage. A rename needs both its old and its new path. */
|
||||
export function pathsFor(changes: GitChange[]): string[] {
|
||||
return [...new Set(changes.flatMap(change => change.originalPath ? [change.originalPath, change.path] : [change.path]))];
|
||||
}
|
||||
|
||||
export function changeLabel(change: GitChange, staged: boolean): string {
|
||||
if (isConflict(change)) return tr("Conflict");
|
||||
const code = staged ? change.index : change.worktree;
|
||||
switch (code) {
|
||||
case "?": return tr("New");
|
||||
case "A": return tr("Added");
|
||||
case "M": return tr("Modified");
|
||||
case "D": return tr("Deleted");
|
||||
case "R": return tr("Renamed");
|
||||
case "C": return tr("Copied");
|
||||
case "T": return tr("Type changed");
|
||||
default: return code;
|
||||
}
|
||||
}
|
||||
|
||||
export type DiffLineKind = "add" | "remove" | "range" | "context";
|
||||
|
||||
export function diffLineKind(line: string): DiffLineKind {
|
||||
if (line.startsWith("+") && !line.startsWith("+++")) return "add";
|
||||
if (line.startsWith("-") && !line.startsWith("---")) return "remove";
|
||||
return line.startsWith("@@") ? "range" : "context";
|
||||
}
|
||||
|
||||
export interface GraphNode extends GitGraphCommit { row: number; lane: number; color: number }
|
||||
export interface GraphEdge { from: string; to: string; row: number; lane: number; parentLane: number; color: number; outside: boolean; endRow: number }
|
||||
|
||||
/** Lanes and colors for the commit graph. The six colors repeat, and lanes that are in use do not share a color. */
|
||||
export function graphLayout(history: GitGraph | null | undefined): { nodes: GraphNode[]; edges: GraphEdge[]; lanes: number } {
|
||||
const commits = history?.commits ?? [];
|
||||
const lanes: (string | null)[] = [];
|
||||
const nodes: GraphNode[] = [];
|
||||
const edges: Omit<GraphEdge, "endRow">[] = [];
|
||||
const colors = new Map<string, number>();
|
||||
let nextColor = 0;
|
||||
const ids = new Set(commits.map(commit => commit.id));
|
||||
const reserve = (id: string, preferredColor?: number) => {
|
||||
let lane = lanes.indexOf(id);
|
||||
if (lane < 0) {
|
||||
lane = lanes.indexOf(null);
|
||||
if (lane < 0) lane = lanes.length;
|
||||
lanes[lane] = id;
|
||||
if (preferredColor === undefined) {
|
||||
const activeColors = new Set(lanes.filter(value => value !== id && value !== null).map(value => colors.get(value!)));
|
||||
preferredColor = nextColor++;
|
||||
for (let offset = 0; offset < 6 && activeColors.has(preferredColor % 6); offset++) preferredColor = nextColor++;
|
||||
}
|
||||
colors.set(id, preferredColor % 6);
|
||||
}
|
||||
return lane;
|
||||
};
|
||||
let width = 1;
|
||||
for (const [row, commit] of commits.entries()) {
|
||||
const lane = reserve(commit.id);
|
||||
const color = colors.get(commit.id)!;
|
||||
nodes.push({ ...commit, row, lane, color });
|
||||
lanes[lane] = null;
|
||||
for (const [index, parent] of commit.parents.entries()) {
|
||||
const parentLane = reserve(parent, index === 0 ? color : undefined);
|
||||
edges.push({ from: commit.id, to: parent, row, lane, parentLane, color: index === 0 ? color : colors.get(parent)!, outside: !ids.has(parent) });
|
||||
}
|
||||
width = Math.max(width, lanes.length, lane + 1);
|
||||
}
|
||||
const rows = new Map(nodes.map(node => [node.id, node.row]));
|
||||
return { nodes, edges: edges.map(edge => ({ ...edge, endRow: rows.get(edge.to) ?? nodes.length })), lanes: width };
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// The shared state of one Git feature instance. The Source control pane, the diff tab, and the graph tab read it.
|
||||
|
||||
export interface DiffSelection {
|
||||
path: string;
|
||||
staged: boolean;
|
||||
text: string;
|
||||
error: boolean;
|
||||
}
|
||||
|
||||
export class GitState {
|
||||
/** The file of the diff tab. */
|
||||
selected = $state<DiffSelection | null>(null);
|
||||
/** The commit and the file of the graph tab. Tab transfers carry them. */
|
||||
history = $state<{ selectedId: string | null; file: string | null }>({ selectedId: null, file: null });
|
||||
/** Grows after each commit, push, or pull, so that the graph reads the history again. */
|
||||
historyVersion = $state(0);
|
||||
/** The diff request that may write `selected`. */
|
||||
sequence = 0;
|
||||
disposed = false;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Launch rules: a feature with a rule starts its instance as soon as the rule wants it, without a view or a command.
|
||||
// A feature without a rule loads at first need. `syncFeatures` in `src/lib/plugins/external.ts` applies the rules.
|
||||
import type { FeatureId } from "./catalog.ts";
|
||||
import { hasBackgroundSource, onBackgroundChange } from "./backgroundSettings.ts";
|
||||
|
||||
export interface LaunchRule {
|
||||
/** True when the feature also runs in browser windows. Other features stay out of them. */
|
||||
browserWindow: boolean;
|
||||
/** True when the rule also starts the feature in the settings window. */
|
||||
settingsWindow: boolean;
|
||||
/** True when the instance must run now. */
|
||||
wanted(): boolean;
|
||||
/** Run `listener` after each change that can change `wanted`. Returns the function that stops it. */
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
export const LAUNCH_RULES: Partial<Record<FeatureId, LaunchRule>> = {
|
||||
// Background starts at the start of a window when a folder or an image is selected, and at once when the user selects one.
|
||||
// The settings window shows the settings only, so the slideshow does not run there.
|
||||
background: { browserWindow: true, settingsWindow: false, wanted: () => hasBackgroundSource(), subscribe: onBackgroundChange },
|
||||
};
|
||||
|
||||
/** True when a feature runs in a window of this kind. */
|
||||
export function runsInWindow(id: FeatureId, window: { browserWindow: boolean }): boolean {
|
||||
return !window.browserWindow || !!LAUNCH_RULES[id]?.browserWindow;
|
||||
}
|
||||
|
||||
/** True when the launch rule of a feature wants its instance now in a window of this kind. */
|
||||
export function launchWanted(id: FeatureId, window: { settingsWindow: boolean }): boolean {
|
||||
const rule = LAUNCH_RULES[id];
|
||||
return !!rule && (!window.settingsWindow || rule.settingsWindow) && rule.wanted();
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Each feature module loads at most one time in each window. The host core never imports a feature module
|
||||
// statically. `pnpm check:features` makes sure of this in the build output.
|
||||
import { writable } from "svelte/store";
|
||||
import type { FeatureId } from "./catalog.ts";
|
||||
import type { FeatureModule } from "./types.ts";
|
||||
|
||||
const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
|
||||
git: () => import("./git/index.ts"),
|
||||
background: () => import("./background/index.ts"),
|
||||
terminal: () => import("./terminal/index.ts"),
|
||||
pdf: () => import("./pdf/index.ts"),
|
||||
pm: () => import("./pm/index.ts"),
|
||||
};
|
||||
|
||||
const modules = new Map<FeatureId, Promise<FeatureModule>>();
|
||||
|
||||
/** The last load error of each feature, for Settings → Features. */
|
||||
export const featureErrors = writable<Partial<Record<FeatureId, string>>>({});
|
||||
|
||||
function setError(id: FeatureId, message: string | undefined) {
|
||||
featureErrors.update(errors => {
|
||||
const next = { ...errors };
|
||||
if (message) next[id] = message; else delete next[id];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
/** Import the module of a feature. After a failure, the next call tries again. */
|
||||
export function loadFeature(id: FeatureId, load: () => Promise<FeatureModule> = imports[id]): Promise<FeatureModule> {
|
||||
let pending = modules.get(id);
|
||||
if (!pending) {
|
||||
pending = load().then(module => { setError(id, undefined); return module; }, reason => {
|
||||
modules.delete(id);
|
||||
setError(id, String(reason));
|
||||
throw reason;
|
||||
});
|
||||
modules.set(id, pending);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** True after the first load started in this window. Tests use it to prove that an off feature never loads. */
|
||||
export function featureRequested(id: FeatureId): boolean {
|
||||
return modules.has(id);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// The first start of a version with a new native feature. The switch takes the state of the old plugin package,
|
||||
// or the default of the feature when the feature does not follow its package (`followsPackage`).
|
||||
// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing.
|
||||
// The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`),
|
||||
// the `terminal` section from the localStorage key of the Terminal plugin (`terminalSettings.ts`), and the
|
||||
// `projectManagement` section and the tab view states from the kept Project Management settings (`pmSettings.ts`).
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { readSection, writeSection } from "../settings/store.ts";
|
||||
import { readAppearance } from "../theme/appearance.ts";
|
||||
import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "./catalog.ts";
|
||||
import { storedSwitches } from "./state.ts";
|
||||
import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts";
|
||||
import { LEGACY_TERMINAL_KEY, migrateTerminal, writeTerminal, type TerminalMigrationHost } from "./terminalSettings.ts";
|
||||
import { migrateProjectManagement, writeProjectManagement, type ProjectManagementMigrationHost } from "./pmSettings.ts";
|
||||
|
||||
/** What the host reports about one old plugin package. */
|
||||
export interface LegacyPlugin {
|
||||
id: string;
|
||||
installed: boolean;
|
||||
enabled: boolean;
|
||||
/** The kept plugin settings, or null. */
|
||||
settings: unknown;
|
||||
}
|
||||
|
||||
/** An installed package gives its enabled state. Without a package, or for a feature that does not follow its package, the default applies. */
|
||||
export function legacySwitch(entry: FeatureEntry, legacy: LegacyPlugin | undefined): boolean {
|
||||
return entry.followsPackage && legacy?.installed ? legacy.enabled : entry.defaultOn;
|
||||
}
|
||||
|
||||
export interface MigrationHost {
|
||||
read: () => unknown;
|
||||
write: (value: unknown) => Promise<void>;
|
||||
legacy: (ids: string[]) => Promise<LegacyPlugin[]>;
|
||||
}
|
||||
|
||||
const desktopHost: MigrationHost = {
|
||||
read: () => readSection("features"),
|
||||
write: value => writeSection("features", value),
|
||||
legacy: ids => invoke<LegacyPlugin[]>("features_legacy", { ids }),
|
||||
};
|
||||
|
||||
const desktopBackground: BackgroundMigrationHost = {
|
||||
missing: () => readSection("background") === undefined,
|
||||
hasImage: () => hasImage(readAppearance()),
|
||||
migrateFolder: async () => !!await invoke<string | null>("background_migrate"),
|
||||
write: writeBackground,
|
||||
};
|
||||
|
||||
const desktopProjectManagement: ProjectManagementMigrationHost = {
|
||||
missing: () => readSection("projectManagement") === undefined,
|
||||
write: writeProjectManagement,
|
||||
get storage() { return localStorage; },
|
||||
};
|
||||
|
||||
const desktopTerminal: TerminalMigrationHost = {
|
||||
missing: () => readSection("terminal") === undefined,
|
||||
legacy: () => localStorage.getItem(LEGACY_TERMINAL_KEY),
|
||||
write: writeTerminal,
|
||||
};
|
||||
|
||||
/**
|
||||
* Give each feature without a stored switch the state of its old package, and make a missing `background`, `terminal`,
|
||||
* or `projectManagement` section.
|
||||
* It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again.
|
||||
* The `terminal` section needs no package report, so it migrates also then.
|
||||
*/
|
||||
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground,
|
||||
terminal: TerminalMigrationHost = desktopTerminal, projectManagement: ProjectManagementMigrationHost = desktopProjectManagement): Promise<FeatureId[]> {
|
||||
try { await migrateTerminal(terminal); }
|
||||
catch (reason) { console.error("RuneStone could not copy the old terminal settings.", reason); }
|
||||
const current = host.read();
|
||||
const stored = storedSwitches(current);
|
||||
const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
|
||||
const backgroundOwner = featureEntry("background").owner;
|
||||
const backgroundMissing = background.missing();
|
||||
const pmOwner = featureEntry("pm").owner;
|
||||
const pmMissing = projectManagement.missing();
|
||||
const owners = [...new Set([...missing.map(entry => entry.owner), ...backgroundMissing ? [backgroundOwner] : [], ...pmMissing ? [pmOwner] : []])];
|
||||
if (!owners.length) return [];
|
||||
let legacy: LegacyPlugin[];
|
||||
try { legacy = await host.legacy(owners); }
|
||||
catch (reason) {
|
||||
console.error("RuneStone could not read the old plugin packages. The feature defaults apply.", reason);
|
||||
return [];
|
||||
}
|
||||
if (missing.length) {
|
||||
const next: Record<string, unknown> = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record<string, unknown> } : {};
|
||||
for (const entry of missing) next[entry.id] = legacySwitch(entry, legacy.find(item => item.id === entry.owner));
|
||||
await host.write(next);
|
||||
}
|
||||
if (backgroundMissing) await migrateBackground(legacy.find(item => item.id === backgroundOwner), background);
|
||||
if (pmMissing) await migrateProjectManagement(legacy.find(item => item.id === pmOwner), projectManagement);
|
||||
return missing.map(entry => entry.id);
|
||||
}
|
||||
|
||||
/** Workbench and Settings windows of the desktop app migrate. Browser windows start no feature, and the browser preview keeps the defaults. */
|
||||
export function migrateFeaturesOnStart(): Promise<unknown> {
|
||||
const browserWindow = new URLSearchParams(location.search).get("browserWindow") === "true";
|
||||
if (!isTauri() || browserWindow) return Promise.resolve();
|
||||
return migrateFeatures().catch(reason => console.error("The feature migration failed.", reason));
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
<script lang="ts">
|
||||
// One PDF tab: the toolbar, the status line, the password form, and all pages in one column that scrolls.
|
||||
// Only the pages near the visible area have a canvas and a text layer. The other pages are empty sheets.
|
||||
// The document and its worker live as long as the tab. `close` releases both.
|
||||
import { flushSync, onMount } from "svelte";
|
||||
import { message, t } from "$lib/i18n";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import type { PluginDocumentContext } from "$lib/plugins/sdk";
|
||||
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
|
||||
import { MAX_ZOOM, MIN_ZOOM, PAGE_GAP, PAGE_MARGIN, RESIZE_SETTLE_MS, ZOOM_STEP, fitZoom, mostVisiblePage, nextRotation, outputScale, pageBoxes, pageNumber, pagesInRange, zoomFromText, zoomLevel, type PageSize } from "./model";
|
||||
|
||||
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
|
||||
|
||||
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
|
||||
/** One page that has a drawing, or waits for one. `key` names the zoom, the rotation, and the pixel ratio. */
|
||||
type Drawing = { key: string; done: boolean; cancel(): void };
|
||||
|
||||
let page = $state(1);
|
||||
let count = $state(0);
|
||||
let zoom = $state(1);
|
||||
let rotation = $state(0);
|
||||
let fit = $state(true);
|
||||
let sizes = $state.raw<PageSize[]>([]);
|
||||
let status = $state<Status>({ key: message("Loading PDF…") });
|
||||
let asking = $state<"needed" | "incorrect" | null>(null);
|
||||
let reloading = $state(false);
|
||||
let failed = $state(false);
|
||||
let scroller: HTMLDivElement;
|
||||
let sheets: HTMLDivElement[] = $state([]);
|
||||
let pageInput: HTMLInputElement;
|
||||
let passwordInput: HTMLInputElement | undefined = $state();
|
||||
|
||||
let disposed = false;
|
||||
let pdf: PDFDocumentProxy | undefined;
|
||||
let opened: OpenPdf | undefined;
|
||||
let answer: ((password: string) => void) | undefined;
|
||||
let generation = 0;
|
||||
const drawings = new Map<number, Drawing>();
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
let loading: Promise<void> = Promise.resolve();
|
||||
let closing: Promise<void> | undefined;
|
||||
// The place in the document: a page and the part of its height above the top of the visible area.
|
||||
let anchor = { index: 0, part: 0 };
|
||||
// The scroll position that the viewer set. A scroll event at this position keeps the page number.
|
||||
let settled = -1;
|
||||
let frame = 0;
|
||||
|
||||
const ready = $derived(count > 0);
|
||||
const boxes = $derived(pageBoxes(sizes, zoom, rotation));
|
||||
const zoomText = $derived(ready ? `${Math.round(zoom * 100)}%` : "—");
|
||||
|
||||
function fail(reason: unknown) {
|
||||
if (disposed) return;
|
||||
failed = true;
|
||||
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
|
||||
}
|
||||
|
||||
const drawingKey = () => `${zoom}:${rotation}:${window.devicePixelRatio}`;
|
||||
|
||||
/** The status line names the current page when its drawing is complete. */
|
||||
function report() {
|
||||
if (disposed || failed || !pdf) return;
|
||||
const drawing = drawings.get(page);
|
||||
status = drawing?.done && drawing.key === drawingKey()
|
||||
? { key: message("Page {page} of {count}"), values: { page, count } }
|
||||
: { key: message("Loading page {page}…"), values: { page } };
|
||||
}
|
||||
|
||||
/** Draw one page. The jobs run one at a time. A cancelled job ends at its next step. */
|
||||
function draw(number: number, key: string) {
|
||||
let cancelled = false;
|
||||
let render: RenderTask | undefined;
|
||||
let text: TextLayer | undefined;
|
||||
const drawing: Drawing = { key, done: false, cancel() { cancelled = true; render?.cancel(); text?.cancel(); } };
|
||||
drawings.set(number, drawing);
|
||||
const source = pdf;
|
||||
queue = queue.then(async () => {
|
||||
if (cancelled || disposed || !source) return;
|
||||
const pdfPage = await source.getPage(number);
|
||||
const sheet = sheets[number - 1];
|
||||
if (cancelled || disposed || !sheet) return;
|
||||
const viewport = pdfPage.getViewport({ scale: zoom, rotation: (pdfPage.rotate + rotation) % 360 });
|
||||
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, Math.floor(viewport.width * scale));
|
||||
canvas.height = Math.max(1, Math.floor(viewport.height * scale));
|
||||
canvas.setAttribute("role", "img");
|
||||
// The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N".
|
||||
canvas.setAttribute("aria-label", $t("PDF page {page}", { page: number }));
|
||||
const layer = document.createElement("div");
|
||||
layer.className = "textLayer";
|
||||
layer.style.setProperty("--total-scale-factor", String(viewport.scale));
|
||||
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
|
||||
await render.promise;
|
||||
if (cancelled || disposed) return;
|
||||
// The old drawing of the page stays until the new one is complete.
|
||||
sheet.replaceChildren(canvas, layer);
|
||||
text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport });
|
||||
await text.render();
|
||||
if (cancelled || disposed) return;
|
||||
drawing.done = true;
|
||||
pdfPage.cleanup();
|
||||
report();
|
||||
}).catch(reason => { if (!cancelled && !disposed) fail(reason); });
|
||||
}
|
||||
|
||||
/** Draw the pages near the visible area, the current page first. Empty the pages that are far from it. */
|
||||
function refresh() {
|
||||
if (!pdf || disposed || scroller.clientWidth === 0) return;
|
||||
const key = drawingKey();
|
||||
const height = scroller.clientHeight;
|
||||
const wanted = pagesInRange(boxes, scroller.scrollTop - height, scroller.scrollTop + 2 * height);
|
||||
for (const [number, drawing] of drawings) {
|
||||
const keep = wanted.includes(number);
|
||||
if (keep && drawing.key === key) continue;
|
||||
drawing.cancel();
|
||||
drawings.delete(number);
|
||||
if (!keep) sheets[number - 1]?.replaceChildren();
|
||||
}
|
||||
for (const number of wanted.sort((a, b) => Math.abs(a - page) - Math.abs(b - page))) if (!drawings.has(number)) draw(number, key);
|
||||
report();
|
||||
}
|
||||
|
||||
/** Put the remembered place at the top of the visible area again, after the page boxes changed. */
|
||||
function restore() {
|
||||
flushSync();
|
||||
const box = boxes[anchor.index];
|
||||
if (!box || scroller.clientWidth === 0) return;
|
||||
scroller.scrollTop = Math.max(0, box.top + anchor.part * box.height);
|
||||
settled = scroller.scrollTop;
|
||||
refresh();
|
||||
}
|
||||
|
||||
function remember() {
|
||||
const box = boxes[page - 1];
|
||||
anchor = { index: page - 1, part: box ? (scroller.scrollTop - box.top) / box.height : 0 };
|
||||
}
|
||||
|
||||
function scrolled() {
|
||||
if (frame) return;
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
if (disposed || !ready || scroller.clientWidth === 0) return;
|
||||
if (scroller.scrollTop !== settled) {
|
||||
settled = -1;
|
||||
page = mostVisiblePage(boxes, scroller.scrollTop, scroller.scrollTop + scroller.clientHeight);
|
||||
remember();
|
||||
}
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
|
||||
/** Show the top of a page. */
|
||||
function go(value: number) {
|
||||
if (!pdf) return;
|
||||
page = pageNumber(value, pdf.numPages);
|
||||
pageInput.value = String(page);
|
||||
// The first page shows with the margin above it. Each other page shows with half of the gap above it.
|
||||
anchor = { index: page - 1, part: -(page === 1 ? PAGE_MARGIN : PAGE_GAP / 2) / (boxes[page - 1]?.height ?? 1) };
|
||||
restore();
|
||||
}
|
||||
|
||||
function applyFit() {
|
||||
if (fit && scroller.clientWidth > 0 && sizes.length) zoom = fitZoom(sizes, rotation, scroller.clientWidth - 2 * PAGE_MARGIN);
|
||||
}
|
||||
|
||||
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); restore(); }
|
||||
|
||||
function typedZoom(input: HTMLInputElement) {
|
||||
const value = zoomFromText(input.value);
|
||||
if (value !== null && Math.round(value * 100) !== Math.round(zoom * 100)) setZoom(value);
|
||||
input.value = zoomText;
|
||||
}
|
||||
|
||||
/** Read the size of each page after the first. Until then, a page has the size of the first page. */
|
||||
async function measure(source: PDFDocumentProxy, current: number) {
|
||||
const next = [...sizes];
|
||||
let changed = false;
|
||||
for (let number = 2; number <= source.numPages; number++) {
|
||||
const { width, height } = (await source.getPage(number)).getViewport({ scale: 1 });
|
||||
if (disposed || current !== generation) return;
|
||||
if (width !== next[number - 1].width || height !== next[number - 1].height) { next[number - 1] = { width, height }; changed = true; }
|
||||
}
|
||||
if (!changed) return;
|
||||
sizes = next;
|
||||
applyFit();
|
||||
restore();
|
||||
}
|
||||
|
||||
async function load() {
|
||||
failed = false;
|
||||
status = { key: message("Loading PDF…") };
|
||||
const bytes = await readBytes(file.path);
|
||||
if (disposed) return;
|
||||
opened = openPdf(bytes, (reason, next) => {
|
||||
if (disposed) return;
|
||||
answer = next;
|
||||
asking = reason;
|
||||
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
|
||||
queueMicrotask(() => passwordInput?.focus());
|
||||
});
|
||||
const source = await opened.promise;
|
||||
if (disposed) return;
|
||||
const current = ++generation;
|
||||
const { width, height } = (await source.getPage(1)).getViewport({ scale: 1 });
|
||||
if (disposed) return;
|
||||
pdf = source;
|
||||
sizes = Array.from({ length: source.numPages }, () => ({ width, height }));
|
||||
count = source.numPages;
|
||||
applyFit();
|
||||
go(page);
|
||||
report();
|
||||
void measure(source, current).catch(reason => { if (current === generation) fail(reason); });
|
||||
}
|
||||
|
||||
async function release() {
|
||||
generation++;
|
||||
for (const drawing of drawings.values()) drawing.cancel();
|
||||
drawings.clear();
|
||||
await queue;
|
||||
const current = opened;
|
||||
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0; sizes = [];
|
||||
await current?.close();
|
||||
}
|
||||
|
||||
async function reload() {
|
||||
if (reloading || disposed) return;
|
||||
reloading = true;
|
||||
try {
|
||||
await loading;
|
||||
await release();
|
||||
if (!disposed) await (loading = load());
|
||||
} catch (reason) { fail(reason); }
|
||||
finally { reloading = false; }
|
||||
}
|
||||
|
||||
function unlock(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
if (!passwordInput || !answer) return;
|
||||
const value = passwordInput.value;
|
||||
passwordInput.value = "";
|
||||
asking = null;
|
||||
status = { key: message("Loading PDF…") };
|
||||
const next = answer;
|
||||
answer = undefined;
|
||||
next(value);
|
||||
}
|
||||
|
||||
/** Ctrl and the wheel change the zoom. The wheel alone scrolls the pages. */
|
||||
function wheel(event: WheelEvent) {
|
||||
if (!(event.ctrlKey || event.metaKey) || !ready || event.deltaY === 0) return;
|
||||
event.preventDefault();
|
||||
setZoom(event.deltaY < 0 ? zoom * 1.1 : zoom / 1.1);
|
||||
}
|
||||
|
||||
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
|
||||
export function close(): Promise<void> {
|
||||
if (closing) return closing;
|
||||
disposed = true;
|
||||
closing = release().then(() => loading).catch(() => {});
|
||||
return closing;
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
loading = load().catch(fail);
|
||||
// Fit-width pages follow the width of the tab. A tab that shows again draws at once. Later sizes wait until the size settles.
|
||||
let width = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const resized = () => { applyFit(); restore(); };
|
||||
const observer = new ResizeObserver(() => {
|
||||
const next = scroller.clientWidth;
|
||||
if (next === width) return;
|
||||
const shown = width === 0;
|
||||
width = next;
|
||||
clearTimeout(timer);
|
||||
if (next === 0) return;
|
||||
if (shown) resized();
|
||||
else timer = setTimeout(resized, RESIZE_SETTLE_MS);
|
||||
});
|
||||
observer.observe(scroller);
|
||||
scroller.addEventListener("wheel", wheel, { passive: false });
|
||||
return () => { observer.disconnect(); clearTimeout(timer); cancelAnimationFrame(frame); scroller.removeEventListener("wheel", wheel); void close(); };
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="pdf-viewer" aria-label={$t("PDF Viewer")}>
|
||||
<div class="toolbar" role="group" aria-label={$t("PDF controls")}>
|
||||
<IconButton icon="up" label={$t("Previous page")} disabled={!ready || page <= 1} onclick={() => go(page - 1)} />
|
||||
<input bind:this={pageInput} class="page" type="number" min="1" max={Math.max(count, 1)} value={page} disabled={!ready}
|
||||
aria-label={$t("Page number")} onchange={event => { if (Number(event.currentTarget.value) !== page) go(Number(event.currentTarget.value)); }}
|
||||
onkeydown={event => { if (event.key === "Enter") go(Number(event.currentTarget.value)); }} />
|
||||
<span class="count">/ {ready ? count : "—"}</span>
|
||||
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
|
||||
<span class="separator" aria-hidden="true"></span>
|
||||
<IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} />
|
||||
<input class="zoom" type="text" inputmode="decimal" value={zoomText} disabled={!ready} aria-label={$t("Zoom percent")}
|
||||
onfocus={event => event.currentTarget.select()} onchange={event => typedZoom(event.currentTarget)}
|
||||
onkeydown={event => { if (event.key === "Enter") typedZoom(event.currentTarget); }} />
|
||||
<IconButton icon="zoom-in" label={$t("Zoom in")} disabled={!ready || zoom >= MAX_ZOOM} onclick={() => setZoom(zoom * ZOOM_STEP)} />
|
||||
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; applyFit(); restore(); }} />
|
||||
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); applyFit(); restore(); }} />
|
||||
<IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
|
||||
</div>
|
||||
<p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p>
|
||||
{#if asking}
|
||||
<form class="password" onsubmit={unlock}>
|
||||
<label>{$t("PDF password")} <input bind:this={passwordInput} type="password" autocomplete="off" /></label>
|
||||
<button class="text-button" type="submit">{$t("Unlock")}</button>
|
||||
</form>
|
||||
{/if}
|
||||
<!-- The page area takes focus, so the keyboard scrolls the pages. The host gives it focus after a tab change by keyboard. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
|
||||
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF pages")} data-tab-focus onscroll={scrolled}>
|
||||
<div class="pages">
|
||||
{#each boxes as box, index (index)}
|
||||
<div bind:this={sheets[index]} class="sheet" data-page={index + 1} style:width={`${box.width}px`} style:height={`${box.height}px`}></div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
|
||||
/* The toolbar, the status line, and the password form are opaque, so a background image never hides them. */
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
|
||||
.page { box-sizing: border-box; width: 64px; height: 28px; margin-left: 4px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: right; }
|
||||
.page:disabled, .zoom:disabled { color: var(--rs-text-dim); }
|
||||
.count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
|
||||
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
|
||||
.zoom { box-sizing: border-box; width: 60px; height: 28px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: center; }
|
||||
.status { margin: 0; padding: 4px 12px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
|
||||
.status.alert { color: var(--rs-error); }
|
||||
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
|
||||
.password input { box-sizing: border-box; height: 28px; margin-left: 4px; padding: 2px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
.text-button:hover { background: var(--rs-bg-active); }
|
||||
/* The padding and the gap match PAGE_MARGIN and PAGE_GAP in model.ts. */
|
||||
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; background: var(--rs-workarea-editor-bg); }
|
||||
.scroll:focus-visible { outline-offset: -2px; }
|
||||
.pages { display: flex; flex-direction: column; align-items: center; gap: 12px; width: max-content; min-width: 100%; }
|
||||
/* A PDF page is paper: white in both themes. */
|
||||
.sheet { position: relative; flex: none; background: white; box-shadow: 0 2px 10px #0003; }
|
||||
.sheet :global(canvas) { display: block; width: 100%; height: 100%; }
|
||||
/* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */
|
||||
.sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0; --min-font-size: 1; --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); }
|
||||
.sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; }
|
||||
.sheet :global(.textLayer > :not(.markedContent)), .sheet :global(.markedContent span:not(.markedContent)) { z-index: 1; --font-height: 0; font-size: calc(var(--text-scale-factor) * var(--font-height)); --scale-x: 1; --rotate: 0deg; transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv)); }
|
||||
.sheet :global(.markedContent) { display: contents; }
|
||||
.sheet :global(.textLayer ::selection) { background: color-mix(in srgb, var(--rs-selection) 65%, transparent); color: transparent; }
|
||||
</style>
|
||||
@@ -0,0 +1,69 @@
|
||||
/// <reference types="vite/client" />
|
||||
// PDF.js for the PDF Viewer feature. The worker, the character maps, the standard fonts, and the WebAssembly image
|
||||
// decoders come from the app (`'self'`) as Vite assets, so a PDF never causes a network request.
|
||||
// Each open document has its own worker. `close` stops it.
|
||||
// The reference to the Vite types serves the unit test type check, which reaches this file through `loader.ts`.
|
||||
import { getDocument, PDFWorker, PasswordResponses, type PDFDocumentLoadingTask, type PDFDocumentProxy } from "pdfjs-dist/build/pdf.min.mjs";
|
||||
import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
|
||||
|
||||
export { TextLayer, type PDFDocumentProxy, type RenderTask } from "pdfjs-dist/build/pdf.min.mjs";
|
||||
|
||||
// `build.assetsInlineLimit` in vite.config.js keeps these files out of the code, so each one is a file of the app.
|
||||
// The JPEG 2000 and JBIG2 decoders are the only WebAssembly files that PDF.js asks for with `useWorkerFetch: false`.
|
||||
// The viewer runs no PDF scripts (quickjs) and uses no ICC color profiles (qcms), as the PDF Viewer plugin did.
|
||||
const assets = import.meta.glob<string>([
|
||||
"/node_modules/pdfjs-dist/cmaps/*.bcmap",
|
||||
"/node_modules/pdfjs-dist/standard_fonts/*.{pfb,ttf}",
|
||||
"/node_modules/pdfjs-dist/wasm/{jbig2,openjpeg}.wasm",
|
||||
], { query: "?url", import: "default", eager: true });
|
||||
|
||||
const folders: Record<string, string> = { cMapUrl: "cmaps", standardFontDataUrl: "standard_fonts", wasmUrl: "wasm" };
|
||||
|
||||
/** The app URL of a PDF.js data file, or undefined for an unknown kind or file. */
|
||||
export function assetUrl(kind: string, filename: string): string | undefined {
|
||||
const folder = folders[kind];
|
||||
if (!folder || !/^[\w.-]+$/.test(filename)) return undefined;
|
||||
return assets[`/node_modules/pdfjs-dist/${folder}/${filename}`];
|
||||
}
|
||||
|
||||
/** PDF.js asks the window for its data files (`useWorkerFetch: false`). This class reads them from the app. */
|
||||
class AppBinaryDataFactory {
|
||||
async fetch({ kind, filename }: { kind: string; filename: string }): Promise<Uint8Array> {
|
||||
const url = assetUrl(kind, filename);
|
||||
if (!url) throw new Error(`PDF.js has no data file ${filename}.`);
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(`PDF.js could not read ${filename}: ${response.status}.`);
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenPdf {
|
||||
/** Resolves with the document after the password, if the file needs one. */
|
||||
promise: Promise<PDFDocumentProxy>;
|
||||
/** Stop the load or release the document, and stop the worker. Later calls return the same promise. */
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the bytes of a PDF in a new worker. PDF.js calls `onPassword` for a protected file, with "incorrect" after a
|
||||
* wrong password. The viewer calls `answer` with the next password.
|
||||
*/
|
||||
export function openPdf(data: Uint8Array, onPassword: (reason: "needed" | "incorrect", answer: (password: string) => void) => void): OpenPdf {
|
||||
const port = new Worker(workerUrl, { type: "module", name: "PDF.js" });
|
||||
const worker = PDFWorker.create({ port });
|
||||
const task: PDFDocumentLoadingTask = getDocument({
|
||||
data, worker, useWorkerFetch: false, BinaryDataFactory: AppBinaryDataFactory,
|
||||
useSystemFonts: false, isImageDecoderSupported: false, enableXfa: false,
|
||||
});
|
||||
task.onPassword = (answer: (password: string) => void, reason: number) => {
|
||||
onPassword(reason === PasswordResponses.INCORRECT_PASSWORD ? "incorrect" : "needed", answer);
|
||||
};
|
||||
let closing: Promise<void> | undefined;
|
||||
return {
|
||||
promise: task.promise,
|
||||
close: () => closing ??= (async () => {
|
||||
try { await task.destroy(); }
|
||||
finally { worker.destroy(); port.terminate(); }
|
||||
})(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// The PDF Viewer feature. `loader.ts` imports this module when the first PDF tab opens. The file tree marks PDF files
|
||||
// before that, through the document type of the catalog (`../pdfDocument.ts`).
|
||||
// Each tab reads its file with `workspace_read_bytes` (64 MiB at most) and has its own PDF.js worker.
|
||||
import { flushSync, mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { workspaceReadBytes } from "../../workspace/api.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import PdfViewer from "./PdfViewer.svelte";
|
||||
|
||||
export function start(_context: FeatureContext): FeatureInstance {
|
||||
const tabs = new Set<() => Promise<void>>();
|
||||
let stopped = false;
|
||||
return {
|
||||
mount() { throw new Error(tr("This view is unavailable.")); },
|
||||
mountDocument(type, element, file) {
|
||||
if (type !== "pdf") throw new Error(tr("This view is unavailable."));
|
||||
if (stopped) throw new Error(tr("This feature is off."));
|
||||
const viewer = mount(PdfViewer, { target: element, props: { file, readBytes: workspaceReadBytes } });
|
||||
flushSync();
|
||||
let closing: Promise<void> | undefined;
|
||||
// Release the document and stop its worker first. Then remove the component.
|
||||
const dispose = () => closing ??= viewer.close().then(() => unmount(viewer)).finally(() => { tabs.delete(dispose); });
|
||||
tabs.add(dispose);
|
||||
return dispose;
|
||||
},
|
||||
/** The host closes the PDF tabs first. Close what is left, so no worker stays. */
|
||||
async dispose() {
|
||||
stopped = true;
|
||||
await Promise.allSettled([...tabs].map(dispose => dispose()));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// The limits of the PDF Viewer: page numbers, zoom, and the size of the page canvas.
|
||||
|
||||
export const MIN_ZOOM = 0.25;
|
||||
export const MAX_ZOOM = 4;
|
||||
/** Each zoom step multiplies or divides the zoom by this factor. */
|
||||
export const ZOOM_STEP = 1.25;
|
||||
/** A redraw after a resize waits until the size did not change for this time. */
|
||||
export const RESIZE_SETTLE_MS = 150;
|
||||
|
||||
/** A whole page number from 1 to `count`. A value that is not a number gives page 1. */
|
||||
export function pageNumber(value: number, count: number): number {
|
||||
return Math.max(1, Math.min(count, Number.isFinite(value) ? Math.trunc(value) : 1));
|
||||
}
|
||||
|
||||
/** A zoom factor from 0.25 to 4. A value that is not a finite number gives 1. */
|
||||
export function zoomLevel(value: number): number {
|
||||
return Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, Number.isFinite(value) ? value : 1));
|
||||
}
|
||||
|
||||
/** The next clockwise rotation in degrees: 0, 90, 180, or 270. */
|
||||
export function nextRotation(rotation: number): number {
|
||||
return (rotation + 90) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pixel scale of the page canvas. It follows the device pixel ratio up to 2, and keeps each side at most
|
||||
* 8192 pixels and the area at most 16 million pixels, so a large page does not use too much memory.
|
||||
*/
|
||||
export function outputScale(width: number, height: number, deviceScale: number): number {
|
||||
return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height)));
|
||||
}
|
||||
|
||||
/** The space around the pages and between two pages, in CSS pixels. `PdfViewer.svelte` uses the same values in its styles. */
|
||||
export const PAGE_MARGIN = 16;
|
||||
export const PAGE_GAP = 12;
|
||||
|
||||
/** The size of a page at zoom 1, with the rotation of the file. */
|
||||
export interface PageSize { width: number; height: number }
|
||||
/** The place of a page in the column of pages, in whole CSS pixels. */
|
||||
export interface PageBox { top: number; width: number; height: number }
|
||||
|
||||
/** The zoom factor for typed text such as "150" or "150 %". Text that is not a number gives null. */
|
||||
export function zoomFromText(text: string): number | null {
|
||||
const value = Number(text.replace("%", "").replace(",", ".").trim());
|
||||
return text.trim() && Number.isFinite(value) && value > 0 ? zoomLevel(value / 100) : null;
|
||||
}
|
||||
|
||||
/** The zoom that fits the widest page in `available` pixels. */
|
||||
export function fitZoom(sizes: readonly PageSize[], rotation: number, available: number): number {
|
||||
const turned = rotation % 180 !== 0;
|
||||
const widest = Math.max(0, ...sizes.map(size => turned ? size.height : size.width));
|
||||
return zoomLevel(widest > 0 ? available / widest : 1);
|
||||
}
|
||||
|
||||
/** One box for each page, from the top of the column to the bottom. */
|
||||
export function pageBoxes(sizes: readonly PageSize[], zoom: number, rotation: number): PageBox[] {
|
||||
const turned = rotation % 180 !== 0;
|
||||
let top = PAGE_MARGIN;
|
||||
return sizes.map(size => {
|
||||
const width = Math.max(1, Math.floor((turned ? size.height : size.width) * zoom));
|
||||
const height = Math.max(1, Math.floor((turned ? size.width : size.height) * zoom));
|
||||
const box = { top, width, height };
|
||||
top += height + PAGE_GAP;
|
||||
return box;
|
||||
});
|
||||
}
|
||||
|
||||
/** The numbers of the pages that touch the range from `from` to `to`. */
|
||||
export function pagesInRange(boxes: readonly PageBox[], from: number, to: number): number[] {
|
||||
const pages: number[] = [];
|
||||
for (let index = 0; index < boxes.length; index++) {
|
||||
if (boxes[index].top >= to) break;
|
||||
if (boxes[index].top + boxes[index].height > from) pages.push(index + 1);
|
||||
}
|
||||
return pages;
|
||||
}
|
||||
|
||||
/** The number of the page that shows the most in the range from `from` to `to`. The first such page wins. */
|
||||
export function mostVisiblePage(boxes: readonly PageBox[], from: number, to: number): number {
|
||||
let page = 1, most = 0;
|
||||
for (let index = 0; index < boxes.length; index++) {
|
||||
const { top, height } = boxes[index];
|
||||
if (top >= to) break;
|
||||
const shown = Math.min(top + height, to) - Math.max(top, from);
|
||||
if (shown > most) { most = shown; page = index + 1; }
|
||||
}
|
||||
return page;
|
||||
}
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
// The minified build of PDF.js has the same exports as the package entry.
|
||||
declare module "pdfjs-dist/build/pdf.min.mjs" {
|
||||
export * from "pdfjs-dist";
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// The document identification of the PDF Viewer feature. It is in the main bundle, because the file tree marks
|
||||
// PDF files before the feature module loads. The document ID is the workspace path, so two files never share a tab.
|
||||
|
||||
/** The document ID of a PDF file: its path with forward slashes. Any letter case of the extension matches. */
|
||||
export function identifyPdf(path: string): { id: string } | null {
|
||||
return /\.pdf$/i.test(path) ? { id: path.replaceAll("\\", "/") } : null;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// The Project Management feature. `loader.ts` imports this module at the first use: the ribbon button, a board tab,
|
||||
// or a tab transfer from another window. The views are `planning` (All tasks) and `board-<hex of the board ID>`.
|
||||
// The storage code (`storage/`) and the domain code (`model/`) use no host module, so the skill helper can bundle them.
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { backgroundHub } from "../../plugins/backgrounds.ts";
|
||||
import { onProjectManagementChange, readProjectManagement, readViewStates, writeProjectManagement, writeViewStates } from "../pmSettings.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import { boardKey, isManagedBoard, readCatalog } from "./storage/catalog.ts";
|
||||
import { findLegacy, hasLegacy, type LegacyContent } from "./storage/legacy.ts";
|
||||
import { isHiddenCard } from "./storage/persistence.ts";
|
||||
import { message } from "./storage/message.ts";
|
||||
import type { BoardReference } from "./storage/board.ts";
|
||||
import { TaskStore } from "./model/store.ts";
|
||||
import { hostMenus } from "./ui/host.ts";
|
||||
import { mountPM, parseViewState, type PMViewState } from "./ui/ui.ts";
|
||||
import { hostWorkspace } from "./workspace.ts";
|
||||
import { boardOfView, boardViewId, PLANNING } from "./views.ts";
|
||||
|
||||
export function start(context: FeatureContext): FeatureInstance {
|
||||
const workspace = hostWorkspace(context.onWorkspaceChange);
|
||||
const preferences = readProjectManagement();
|
||||
const stopPreferences = onProjectManagementChange(() => Object.assign(preferences, readProjectManagement()));
|
||||
const states = new Map<string, PMViewState>(Object.entries(readViewStates()).map(([key, value]) => [key, parseViewState(value)]));
|
||||
const dirty = new Set<string>();
|
||||
let saveTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let disposed = false;
|
||||
const mounted = new Set<() => void>();
|
||||
/** The legacy data of each workspace root. A migration reads it again. */
|
||||
const legacy = new Map<string, Promise<LegacyContent>>();
|
||||
|
||||
const flush = () => {
|
||||
clearTimeout(saveTimer);
|
||||
if (!dirty.size) return;
|
||||
writeViewStates(Object.fromEntries([...dirty].map(key => [key, structuredClone(states.get(key))])));
|
||||
dirty.clear();
|
||||
};
|
||||
const persist = (id: string) => {
|
||||
if (disposed) return;
|
||||
dirty.add(id);
|
||||
clearTimeout(saveTimer);
|
||||
saveTimer = setTimeout(flush, 200);
|
||||
};
|
||||
const root = () => invoke<string | null>("workspace_last_path").catch(() => null);
|
||||
const legacyContent = async (fresh = false) => {
|
||||
const key = await root() ?? "";
|
||||
if (fresh) legacy.delete(key);
|
||||
let pending = legacy.get(key);
|
||||
if (!pending) {
|
||||
pending = findLegacy(workspace, () => { if (disposed) throw new Error(message("Project Management is off.")); });
|
||||
pending.catch(() => legacy.delete(key));
|
||||
legacy.set(key, pending);
|
||||
}
|
||||
return pending;
|
||||
};
|
||||
/** Copy the legacy boards, the root label file, and every legacy task note to `.runestone/pm/`, with backups. */
|
||||
const migrate = async () => {
|
||||
const store = new TaskStore(workspace, undefined, { legacy: true });
|
||||
try {
|
||||
await store.reload();
|
||||
const cards = store.tasks.filter(task => !isHiddenCard(task.path)).map(task => task.id);
|
||||
return await store.migrateStorage(cards);
|
||||
} finally {
|
||||
store.dispose();
|
||||
void legacyContent(true).catch(() => undefined);
|
||||
}
|
||||
};
|
||||
|
||||
const openBoard = async (path: string, from?: string) => {
|
||||
const snapshot = await readCatalog(workspace);
|
||||
const board = isManagedBoard(path) ? snapshot.value.boards.find(item => boardKey(item.value.id) === path) : undefined;
|
||||
if (!board) throw new Error(message("This board is unavailable. Refresh Project Management."));
|
||||
const id = boardViewId(board.value.id);
|
||||
context.setViewTitle(id, board.name);
|
||||
if (from) context.replaceView(from, id); else context.openView(id);
|
||||
};
|
||||
|
||||
function mountView(view: string, element: HTMLElement) {
|
||||
const boardId = view === PLANNING ? null : boardOfView(view);
|
||||
if (view !== PLANNING && !boardId) throw new Error(message("This view is unavailable."));
|
||||
const reference: BoardReference | undefined = boardId ? { id: boardId, path: boardKey(boardId) } : undefined;
|
||||
if (!states.has(view)) states.set(view, {});
|
||||
const store = new TaskStore(workspace, reference, { legacy: false });
|
||||
if (boardId) {
|
||||
void readCatalog(workspace).then(snapshot => {
|
||||
const board = snapshot.value.boards.find(item => item.value.id === boardId);
|
||||
if (board && !disposed) context.setViewTitle(view, board.name);
|
||||
}, () => undefined);
|
||||
}
|
||||
const cleanup = mountPM(element, store, {
|
||||
ui: hostMenus,
|
||||
backgrounds: backgroundHub,
|
||||
state: states.get(view),
|
||||
stateChanged: () => persist(view),
|
||||
preferences,
|
||||
savePreferences: value => writeProjectManagement(value),
|
||||
openBoard: (path, replace) => openBoard(path, replace ? view : undefined),
|
||||
openAll: replace => { if (replace) context.replaceView(view, PLANNING); else context.openView(PLANNING); },
|
||||
boardRenamed: name => { if (boardId) context.setViewTitle(view, name); },
|
||||
boardDeleted: () => { if (boardId) context.closeView(view); },
|
||||
watch: workspace.watch,
|
||||
legacy: { find: legacyContent, has: hasLegacy, migrate },
|
||||
});
|
||||
mounted.add(cleanup);
|
||||
return () => { mounted.delete(cleanup); cleanup(); };
|
||||
}
|
||||
|
||||
return {
|
||||
mount: mountView,
|
||||
async launch(view) {
|
||||
if (view !== PLANNING) { context.openView(view); return; }
|
||||
// The default board of the workspace is in the catalog. A missing, archived, or damaged default opens All tasks.
|
||||
try {
|
||||
const { value } = await readCatalog(workspace);
|
||||
const board = value.boards.find(item => item.value.id === value.defaultBoardId && !item.archived);
|
||||
if (board) { await openBoard(boardKey(board.value.id)); return; }
|
||||
} catch { /* All tasks shows the storage problem. */ }
|
||||
context.openView(PLANNING);
|
||||
},
|
||||
saveTabState: view => structuredClone(states.get(view) ?? {}),
|
||||
restoreTabState(view, value) {
|
||||
if (view !== PLANNING && !boardOfView(view)) throw new Error(message("This view is unavailable."));
|
||||
states.set(view, parseViewState(value));
|
||||
persist(view);
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
flush();
|
||||
stopPreferences();
|
||||
for (const cleanup of [...mounted]) cleanup();
|
||||
mounted.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { defaultBoard, type BoardDocument, type BoardList } from "../storage/board.ts";
|
||||
import type { Task } from "./model.ts";
|
||||
import { message } from "../storage/message.ts";
|
||||
|
||||
export interface TaskColumn {
|
||||
list?: BoardList;
|
||||
tasks: Task[];
|
||||
allowCreate?: boolean;
|
||||
}
|
||||
|
||||
/** Merge equal list names without changing the cards' board placements. */
|
||||
export function allTaskColumns(boards: BoardDocument[], tasks: Task[]): TaskColumn[] {
|
||||
const active = boards.filter(board => !board.archived);
|
||||
const columns = new Map<string, TaskColumn>();
|
||||
const assigned = new Set<string>();
|
||||
const append = (list: BoardList | undefined, members: Task[], allowCreate = false) => {
|
||||
const key = list ? `list:${list.name.trim().toLowerCase()}` : "unlisted";
|
||||
let column = columns.get(key);
|
||||
if (!column) {
|
||||
column = { list: list ? { id: allowCreate ? list.id : key, name: list.name, status: list.status, collapsed: false } : undefined, tasks: [], allowCreate };
|
||||
columns.set(key, column);
|
||||
}
|
||||
const included = new Set(column.tasks.map(task => task.id));
|
||||
for (const task of members) if (!included.has(task.id)) {
|
||||
column.tasks.push(task);
|
||||
included.add(task.id);
|
||||
}
|
||||
};
|
||||
for (const board of active) {
|
||||
const members = tasks.filter(task => Object.hasOwn(task.placements ?? {}, board.id));
|
||||
for (const task of members) assigned.add(task.id);
|
||||
for (const list of board.value.lists)
|
||||
append(list, members.filter(task => task.placements![board.id].listId === list.id));
|
||||
const unlisted = members.filter(task => !board.value.lists.some(list => list.id === task.placements![board.id].listId));
|
||||
if (unlisted.length) append(undefined, unlisted);
|
||||
}
|
||||
const standalone = tasks.filter(task => !assigned.has(task.id));
|
||||
if (standalone.length || !active.length) {
|
||||
for (const list of defaultBoard("all-tasks").lists)
|
||||
append(list, standalone.filter(task => task.status === list.status), true);
|
||||
}
|
||||
return [...columns.values()];
|
||||
}
|
||||
|
||||
export interface TaskBoardGroup {
|
||||
boardIds: string[];
|
||||
name: string;
|
||||
tasks: Task[];
|
||||
}
|
||||
|
||||
/** Keep shared cards once and name every board represented in this column. */
|
||||
export function allTaskGroups(boards: BoardDocument[], column: TaskColumn): TaskBoardGroup[] {
|
||||
const active = boards.filter(board => !board.archived);
|
||||
const groups = new Map<string, TaskBoardGroup>();
|
||||
for (const task of column.tasks) {
|
||||
const owners = active.filter(board => {
|
||||
const placement = task.placements?.[board.id];
|
||||
if (!placement) return false;
|
||||
const list = board.value.lists.find(list => list.id === placement.listId);
|
||||
return column.list
|
||||
? list?.name.trim().toLowerCase() === column.list.name.trim().toLowerCase()
|
||||
: !list;
|
||||
});
|
||||
const boardIds = owners.map(board => board.id);
|
||||
const key = JSON.stringify(boardIds);
|
||||
let group = groups.get(key);
|
||||
if (!group) {
|
||||
group = { boardIds, name: owners.length ? owners.map(board => board.name).join(" · ") : message("No active board"), tasks: [] };
|
||||
groups.set(key, group);
|
||||
}
|
||||
group.tasks.push(task);
|
||||
}
|
||||
return [...groups.values()].sort((a, b) => {
|
||||
const order = (group: TaskBoardGroup) => group.boardIds.length ? active.findIndex(board => board.id === group.boardIds[0]) : active.length;
|
||||
return order(a) - order(b);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export const backgroundPositions = ["center", "top left", "top", "top right", "left", "right", "bottom left", "bottom", "bottom right"] as const;
|
||||
export const backgroundSizes = ["cover", "contain", "auto"] as const;
|
||||
export interface BackgroundAppearance { overlay: number; position: typeof backgroundPositions[number]; size: typeof backgroundSizes[number] }
|
||||
export function parseBackground(value: unknown): BackgroundAppearance {
|
||||
const raw = value as Partial<BackgroundAppearance> | null;
|
||||
return { overlay: typeof raw?.overlay === "number" && Number.isFinite(raw.overlay) ? Math.max(-1, Math.min(1, raw.overlay)) : 0,
|
||||
position: backgroundPositions.includes(raw?.position as any) ? raw!.position! : "center",
|
||||
size: backgroundSizes.includes(raw?.size as any) ? raw!.size! : "cover" };
|
||||
}
|
||||
export function backgroundOverlay(value: number) {
|
||||
const color = value < 0 ? `rgba(255,255,255,${-value})` : `rgba(0,0,0,${value})`;
|
||||
return `linear-gradient(${color}, ${color})`;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export function headingEdit(value: string, selectionStart: number, selectionEnd: number) {
|
||||
const start = selectionStart === 0 ? 0 : value.lastIndexOf("\n", selectionStart - 1) + 1;
|
||||
const last = selectionEnd > selectionStart && value[selectionEnd - 1] === "\n"
|
||||
? selectionEnd - 1 : selectionEnd;
|
||||
const next = value.indexOf("\n", last);
|
||||
const end = next < 0 ? value.length : next;
|
||||
const edits: { start: number; removed: number; added: number }[] = [];
|
||||
let offset = start;
|
||||
const text = value.slice(start, end).split("\n").map(line => {
|
||||
const prefix = /^( {0,3})(#{1,6})(?:[\t ]+|$)/.exec(line);
|
||||
const removed = prefix?.[0].length ?? 0;
|
||||
const replacement = `${prefix?.[1] ?? ""}## `;
|
||||
edits.push({ start: offset, removed, added: replacement.length });
|
||||
offset += line.length + 1;
|
||||
return replacement + line.slice(removed);
|
||||
}).join("\n");
|
||||
const position = (original: number) => {
|
||||
let result = original;
|
||||
for (const edit of edits) {
|
||||
if (original < edit.start) break;
|
||||
result += original < edit.start + edit.removed
|
||||
? edit.added - (original - edit.start) : edit.added - edit.removed;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
return { start, end, text, selectionStart: position(selectionStart), selectionEnd: position(selectionEnd) };
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user