feat(notes): rich text, med Apple Notes' egne stilarter
Man skriver nu i formateret tekst frem for i Markdown-kildekode. Titel, Overskrift, Underrubrik, Brødtekst, Monotype, Blokcitat, punkt- og talliste, plus fed, kursiv, understreget og gennemstreget — samme ordforråd som Apple Notes, for det er det, en, der kommer derfra, allerede kan. Filen under er stadig Markdown. Det er ikke et kompromis, nogen skal leve med i stilhed: det er grunden til, at eksporten er til at stole på — filen, en note bliver til, er den fil, den allerede var. Understregning er den ene undtagelse; den findes ikke i noget Markdown-dialekt og gemmes som <u>, som enhver læser sender uændret igennem. Det er bedre end at fjerne en stilart, kilden har. contenteditable med execCommand. Den er forældet og også det eneste, alle browsere er enige om; at skrive en markeringsmodel fra bunden er ugers arbejde og en ny slags fejl netop dér, hvor tabt tekst er utilgiveligt. Tre ting, prøverne fandt, som alle ville have kostet tekst: Værktøjslinjen stjal markeringen, når man klikkede — knapperne tager ikke fokus længere. Browseren skrev <span style="font-weight: normal"> for en ophævet fed, hvilket en oversætter, der læser tags, taber; der bedes nu om tags, og styles læses alligevel, fordi det ikke honoreres alle steder. Og markeringen med Shift+Home tog hele dokumentet, ikke linjen. Favoritter er stjernen på hver note. Noteoversigten har fået luft mod venstre kant, og Gem og Slet er knapper frem for bare ord. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
5757f06e7a
commit
1b02eecdab
+46
-36
@@ -1955,48 +1955,58 @@ test('en note kan skrives, findes igen, og peger på det den nævner', async ({
|
||||
expect(trouble).toEqual([]);
|
||||
});
|
||||
|
||||
test('noteeditoren viser formatering, og lagene flugter', async ({ page }) => {
|
||||
test('noteeditoren er rich text, og teksten overlever turen til Markdown og tilbage', async ({
|
||||
page
|
||||
}) => {
|
||||
const trouble = watchForTrouble(page);
|
||||
await page.goto('/noter');
|
||||
|
||||
await page.getByRole('button', { name: 'Ny note' }).click();
|
||||
const body = page.getByLabel('Notens tekst');
|
||||
await body.fill(
|
||||
'# Overskrift\n\nDette er **fed** og *kursiv* og `kode`.\n\nHandler om #Firma og [[En anden note]].\n- et punkt\n> et citat'
|
||||
);
|
||||
const page_ = page.getByRole('textbox', { name: 'Notens tekst' });
|
||||
await page_.click();
|
||||
|
||||
// The marks are still there — this is a mirror, not a renderer — but they are
|
||||
// drawn as what they mean.
|
||||
const mirror = page.locator('.mirror');
|
||||
await expect(mirror.locator('.bold')).toHaveText('**fed**');
|
||||
await expect(mirror.locator('.italic')).toHaveText('*kursiv*');
|
||||
await expect(mirror.locator('.code')).toHaveText('`kode`');
|
||||
await expect(mirror.locator('.tag')).toHaveText('#Firma');
|
||||
await expect(mirror.locator('.wikilink')).toHaveText('[[En anden note]]');
|
||||
await expect(mirror.locator('.h1')).toContainText('Overskrift');
|
||||
// Typed and formatted the way somebody would: pick a style, write, pick another.
|
||||
await page.getByRole('button', { name: 'Formatér' }).click();
|
||||
await page.getByRole('menuitem', { name: 'Titel' }).click();
|
||||
await page.keyboard.type('Møde med Anders');
|
||||
await page.keyboard.press('Enter');
|
||||
|
||||
// The whole risk of the technique: two layers that must line up character for
|
||||
// character. If they drift, the formatting slides away from the text as the
|
||||
// note grows, and it is unusable — so this measures rather than trusts.
|
||||
const drift = await page.evaluate(() => {
|
||||
const ta = document.querySelector('.paper textarea');
|
||||
const mi = document.querySelector('.paper .mirror');
|
||||
const a = getComputedStyle(ta), b = getComputedStyle(mi);
|
||||
return {
|
||||
font: a.fontSize === b.fontSize && a.fontFamily === b.fontFamily,
|
||||
line: a.lineHeight === b.lineHeight,
|
||||
wrap: a.whiteSpace === b.whiteSpace,
|
||||
padding: a.paddingTop === b.paddingTop && a.paddingLeft === b.paddingLeft,
|
||||
// And the rendered height, which is what actually proves it: the same text
|
||||
// laid out twice has to take the same room.
|
||||
heights: Math.abs(ta.scrollHeight - mi.scrollHeight)
|
||||
};
|
||||
});
|
||||
expect(drift.font, 'skrifttypen er ikke ens').toBe(true);
|
||||
expect(drift.line, 'linjehøjden er ikke ens').toBe(true);
|
||||
expect(drift.wrap, 'ombrydningen er ikke ens').toBe(true);
|
||||
expect(drift.padding, 'polstringen er ikke ens').toBe(true);
|
||||
expect(drift.heights, 'lagene fylder ikke det samme').toBeLessThanOrEqual(2);
|
||||
await page.getByRole('button', { name: 'Formatér' }).click();
|
||||
await page.getByRole('menuitem', { name: 'Brødtekst' }).click();
|
||||
await page.keyboard.type('Han vil gerne have kaffe hver uge.');
|
||||
|
||||
// The styles are real elements, not asterisks on screen. This is the whole of
|
||||
// "it should feel like Apple Notes".
|
||||
await expect(page_.locator('h1')).toHaveText('Møde med Anders');
|
||||
await expect(page_.locator('p').filter({ hasText: 'kaffe' })).toBeVisible();
|
||||
|
||||
// Bold through the toolbar, on a selection made with the keyboard. Not
|
||||
// Shift+Home — in a contenteditable that is the start of the document, so it
|
||||
// took the heading with it and the button toggled bold off instead of on. Not a
|
||||
// double-click either: it leaves the selection empty here.
|
||||
for (let i = 0; i < 5; i++) await page.keyboard.press('Shift+ArrowLeft');
|
||||
await page.getByRole('button', { name: 'Fed' }).click();
|
||||
// Either tag: the browser's own bold is <b>, the converter writes <strong>, and
|
||||
// both are read as bold on the way back. Asserting one of them would be
|
||||
// asserting which browser this is.
|
||||
await expect(page_.locator('b, strong')).toBeVisible();
|
||||
|
||||
// And the round trip, which is the thing that can quietly ruin a note: what is
|
||||
// stored is Markdown, and reopening it has to give back the same document. A
|
||||
// converter that disagrees with itself reshapes a note a little on every save.
|
||||
await page_.blur();
|
||||
await page.reload();
|
||||
await page.getByRole('button', { name: /Møde med Anders/ }).click();
|
||||
|
||||
const back = page.getByRole('textbox', { name: 'Notens tekst' });
|
||||
await expect(back.locator('h1')).toHaveText('Møde med Anders');
|
||||
await expect(back.locator('b, strong')).toBeVisible();
|
||||
await expect(back).toContainText('kaffe hver uge');
|
||||
// No stray Markdown on screen: if the marks are showing, the conversion failed
|
||||
// in the direction nobody notices until a note looks wrong.
|
||||
await expect(back).not.toContainText('**');
|
||||
await expect(back).not.toContainText('# ');
|
||||
|
||||
expect(trouble).toEqual([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
<script>
|
||||
/**
|
||||
* The note itself.
|
||||
*
|
||||
* Rich text, not Markdown source: somebody who writes in Apple Notes presses
|
||||
* ⌘B and expects the word to go bold, not to grow asterisks. The file underneath
|
||||
* is still Markdown — see $lib/richtext.js for the seam — so nothing about the
|
||||
* export changes.
|
||||
*
|
||||
* contenteditable with execCommand. It is deprecated and it is also the only
|
||||
* thing every browser agrees on; writing a selection model from scratch is weeks
|
||||
* of work and a new class of bug in the one place where losing text is
|
||||
* unforgivable. When the replacement (the EditContext API) is everywhere, this
|
||||
* is the file to change.
|
||||
*/
|
||||
import { markdownToHtml, htmlToMarkdown } from '$lib/richtext.js';
|
||||
import { t } from '$lib/i18n.svelte.js';
|
||||
|
||||
let { note, onchange, onsave } = $props();
|
||||
|
||||
let editor;
|
||||
let stylesOpen = $state(false);
|
||||
// Which marks are on where the caret is, so the toolbar shows state rather than
|
||||
// only offering actions.
|
||||
let active = $state({});
|
||||
|
||||
// Loaded when the note changes, never while it is being typed in: writing to
|
||||
// innerHTML puts the caret back at the start, which mid-sentence is unusable.
|
||||
let loadedId = $state(null);
|
||||
$effect(() => {
|
||||
if (!editor || !note || note.id === loadedId) return;
|
||||
editor.innerHTML = markdownToHtml(note.body) || '<p><br></p>';
|
||||
loadedId = note.id;
|
||||
active = {};
|
||||
});
|
||||
|
||||
const STYLES = [
|
||||
{ key: 'title', tag: 'h1', label: 'notes.styleTitle' },
|
||||
{ key: 'heading', tag: 'h2', label: 'notes.styleHeading' },
|
||||
{ key: 'subheading', tag: 'h3', label: 'notes.styleSubheading' },
|
||||
{ key: 'body', tag: 'p', label: 'notes.styleBody' },
|
||||
{ key: 'mono', tag: 'pre', label: 'notes.styleMono' },
|
||||
{ key: 'quote', tag: 'blockquote', label: 'notes.styleQuote' }
|
||||
];
|
||||
|
||||
function apply(command, value) {
|
||||
editor?.focus();
|
||||
// Tags, not inline styles. Left to itself the browser writes
|
||||
// <span style="font-weight: normal"> for an un-bold, which is invisible to a
|
||||
// converter that reads tags — so the change is lost on the way to Markdown
|
||||
// and comes back bold. Asking for tags keeps the document in a shape that
|
||||
// can be written down.
|
||||
try {
|
||||
document.execCommand('styleWithCSS', false, false);
|
||||
} catch {
|
||||
// Not everywhere. The formats below still work; some of them just produce
|
||||
// spans, which is why the converter reads styles as well as tags.
|
||||
}
|
||||
document.execCommand(command, false, value);
|
||||
readState();
|
||||
changed();
|
||||
}
|
||||
|
||||
function setStyle(style) {
|
||||
stylesOpen = false;
|
||||
if (style.key === 'bullet') return apply('insertUnorderedList');
|
||||
if (style.key === 'numbered') return apply('insertOrderedList');
|
||||
apply('formatBlock', style.tag);
|
||||
}
|
||||
|
||||
/** What the caret is standing in, for the toolbar's pressed states. */
|
||||
function readState() {
|
||||
if (!editor) return;
|
||||
try {
|
||||
active = {
|
||||
bold: document.queryCommandState('bold'),
|
||||
italic: document.queryCommandState('italic'),
|
||||
underline: document.queryCommandState('underline'),
|
||||
strike: document.queryCommandState('strikeThrough'),
|
||||
bullet: document.queryCommandState('insertUnorderedList'),
|
||||
numbered: document.queryCommandState('insertOrderedList')
|
||||
};
|
||||
} catch {
|
||||
// Some browsers throw on queryCommandState with no selection. The toolbar
|
||||
// showing nothing is a smaller problem than the editor throwing.
|
||||
active = {};
|
||||
}
|
||||
}
|
||||
|
||||
function changed() {
|
||||
if (!editor) return;
|
||||
onchange?.(htmlToMarkdown(editor));
|
||||
}
|
||||
|
||||
function onkeydown(event) {
|
||||
// The shortcuts people already have in their fingers. execCommand handles
|
||||
// bold and italic itself; underline and strikethrough are claimed here so
|
||||
// they behave the same way.
|
||||
if (!(event.metaKey || event.ctrlKey)) return;
|
||||
const key = event.key.toLowerCase();
|
||||
if (key === 'u') {
|
||||
event.preventDefault();
|
||||
apply('underline');
|
||||
} else if (key === 'x' && event.shiftKey) {
|
||||
event.preventDefault();
|
||||
apply('strikeThrough');
|
||||
}
|
||||
}
|
||||
|
||||
// Pasted text arrives as whatever the source was — a web page brings its fonts,
|
||||
// its colours and its layout with it. Only the words are wanted.
|
||||
function onpaste(event) {
|
||||
event.preventDefault();
|
||||
const text = event.clipboardData?.getData('text/plain') ?? '';
|
||||
document.execCommand('insertText', false, text);
|
||||
changed();
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="wrap">
|
||||
<!-- Nothing in here may take focus. A click that moves focus out of the editor
|
||||
collapses the selection first, so the format lands on nothing — the button
|
||||
appears to do nothing at all, which is how it read the first time. -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="toolbar" onmousedown={(e) => e.preventDefault()}>
|
||||
<div class="styles">
|
||||
<button
|
||||
class="aa"
|
||||
onclick={() => (stylesOpen = !stylesOpen)}
|
||||
aria-expanded={stylesOpen}
|
||||
aria-label={t('notes.format')}
|
||||
title={t('notes.format')}>Aa</button
|
||||
>
|
||||
{#if stylesOpen}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="menu" role="menu">
|
||||
{#each STYLES as style}
|
||||
<button class={style.key} role="menuitem" onclick={() => setStyle(style)}>
|
||||
{t(style.label)}
|
||||
</button>
|
||||
{/each}
|
||||
<hr />
|
||||
<button
|
||||
class:on={active.bullet}
|
||||
role="menuitem"
|
||||
onclick={() => setStyle({ key: 'bullet' })}>• {t('notes.styleBullet')}</button
|
||||
>
|
||||
<button
|
||||
class:on={active.numbered}
|
||||
role="menuitem"
|
||||
onclick={() => setStyle({ key: 'numbered' })}>1. {t('notes.styleNumbered')}</button
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<span class="sep" aria-hidden="true"></span>
|
||||
|
||||
<button class:on={active.bold} onclick={() => apply('bold')} title="⌘B" aria-label={t('notes.bold')}>
|
||||
<strong>B</strong>
|
||||
</button>
|
||||
<button class:on={active.italic} onclick={() => apply('italic')} title="⌘I" aria-label={t('notes.italic')}>
|
||||
<em>I</em>
|
||||
</button>
|
||||
<button class:on={active.underline} onclick={() => apply('underline')} title="⌘U" aria-label={t('notes.underline')}>
|
||||
<u>U</u>
|
||||
</button>
|
||||
<button class:on={active.strike} onclick={() => apply('strikeThrough')} aria-label={t('notes.strike')}>
|
||||
<s>S</s>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
|
||||
<div
|
||||
class="page"
|
||||
bind:this={editor}
|
||||
contenteditable="true"
|
||||
role="textbox"
|
||||
aria-multiline="true"
|
||||
aria-label={t('notes.body')}
|
||||
spellcheck="true"
|
||||
oninput={changed}
|
||||
onblur={onsave}
|
||||
onkeyup={readState}
|
||||
onmouseup={readState}
|
||||
{onkeydown}
|
||||
{onpaste}
|
||||
></div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s1);
|
||||
padding: 0 0 var(--s2);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.toolbar button {
|
||||
min-width: 28px;
|
||||
height: 28px;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--ink-muted);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.toolbar button:hover {
|
||||
background: var(--surface);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.toolbar button.on {
|
||||
background: var(--surface-raised);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.sep {
|
||||
width: 1px;
|
||||
height: 18px;
|
||||
background: var(--line);
|
||||
margin: 0 var(--s1);
|
||||
}
|
||||
|
||||
.styles {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.aa {
|
||||
font-weight: 560;
|
||||
}
|
||||
|
||||
.menu {
|
||||
position: absolute;
|
||||
top: calc(100% + var(--s1));
|
||||
left: 0;
|
||||
z-index: 20;
|
||||
min-width: 210px;
|
||||
padding: var(--s1);
|
||||
background: var(--surface-raised);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 8px 24px rgb(0 0 0 / 0.25);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.menu button {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
padding: var(--s1) var(--s2);
|
||||
height: auto;
|
||||
min-height: 30px;
|
||||
}
|
||||
|
||||
.menu hr {
|
||||
border: 0;
|
||||
border-top: 1px solid var(--line);
|
||||
margin: var(--s1) 0;
|
||||
}
|
||||
|
||||
/* The menu shows each style in the style it applies, the way Apple Notes does.
|
||||
Reading the word "Overskrift" set as one is faster than reading a label. */
|
||||
.menu .title {
|
||||
font-size: 1.35rem;
|
||||
font-weight: 700;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.menu .heading {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 640;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.menu .subheading {
|
||||
font-weight: 620;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.menu .mono {
|
||||
font-family: var(--mono, ui-monospace, monospace);
|
||||
}
|
||||
|
||||
.menu .quote {
|
||||
border-left: 2px solid var(--line-strong);
|
||||
padding-left: var(--s2);
|
||||
color: var(--ink-muted);
|
||||
}
|
||||
|
||||
.page {
|
||||
flex: 1;
|
||||
min-height: 50vh;
|
||||
padding: var(--s3) 0;
|
||||
outline: none;
|
||||
line-height: 1.55;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* The document styles. These are the whole of "it should look like Apple Notes":
|
||||
a title that is a title, and body text that is comfortable to read for a page
|
||||
at a time. */
|
||||
.page :global(h1) {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
margin: 0 0 var(--s2);
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.page :global(h2) {
|
||||
font-size: 1.2rem;
|
||||
font-weight: 640;
|
||||
margin: var(--s3) 0 var(--s1);
|
||||
}
|
||||
|
||||
.page :global(h3) {
|
||||
font-size: 1rem;
|
||||
font-weight: 620;
|
||||
margin: var(--s3) 0 var(--s1);
|
||||
}
|
||||
|
||||
.page :global(p) {
|
||||
margin: 0 0 var(--s2);
|
||||
}
|
||||
|
||||
.page :global(ul),
|
||||
.page :global(ol) {
|
||||
margin: 0 0 var(--s2);
|
||||
padding-left: var(--s4);
|
||||
}
|
||||
|
||||
.page :global(li) {
|
||||
margin-bottom: var(--s1);
|
||||
}
|
||||
|
||||
.page :global(blockquote) {
|
||||
margin: 0 0 var(--s2);
|
||||
padding-left: var(--s3);
|
||||
border-left: 2px solid var(--line-strong);
|
||||
color: var(--ink-muted);
|
||||
}
|
||||
|
||||
.page :global(pre) {
|
||||
margin: 0 0 var(--s2);
|
||||
font-family: var(--mono, ui-monospace, monospace);
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.page :global(code) {
|
||||
font-family: var(--mono, ui-monospace, monospace);
|
||||
color: var(--accent);
|
||||
}
|
||||
</style>
|
||||
@@ -16,6 +16,22 @@
|
||||
*/
|
||||
export const da = {
|
||||
// --- the shell ---------------------------------------------------------------
|
||||
'notes.save': 'Gem',
|
||||
'notes.format': 'Formatér',
|
||||
'notes.bold': 'Fed',
|
||||
'notes.italic': 'Kursiv',
|
||||
'notes.underline': 'Understreget',
|
||||
'notes.strike': 'Gennemstreget',
|
||||
'notes.styleTitle': 'Titel',
|
||||
'notes.styleHeading': 'Overskrift',
|
||||
'notes.styleSubheading': 'Underrubrik',
|
||||
'notes.styleBody': 'Brødtekst',
|
||||
'notes.styleMono': 'Monotype',
|
||||
'notes.styleQuote': 'Blokcitat',
|
||||
'notes.styleBullet': 'Punktliste',
|
||||
'notes.styleNumbered': 'Nummereret liste',
|
||||
'notes.favourite': 'Gør til favorit',
|
||||
'notes.unfavourite': 'Fjern som favorit',
|
||||
'notes.title': 'Noter',
|
||||
'notes.new': 'Ny note',
|
||||
'notes.search': 'Søg i noter',
|
||||
|
||||
@@ -12,6 +12,22 @@
|
||||
*/
|
||||
export const en = {
|
||||
// --- the shell ---------------------------------------------------------------
|
||||
'notes.save': 'Save',
|
||||
'notes.format': 'Format',
|
||||
'notes.bold': 'Bold',
|
||||
'notes.italic': 'Italic',
|
||||
'notes.underline': 'Underline',
|
||||
'notes.strike': 'Strikethrough',
|
||||
'notes.styleTitle': 'Title',
|
||||
'notes.styleHeading': 'Heading',
|
||||
'notes.styleSubheading': 'Subheading',
|
||||
'notes.styleBody': 'Body',
|
||||
'notes.styleMono': 'Monospaced',
|
||||
'notes.styleQuote': 'Block quote',
|
||||
'notes.styleBullet': 'Bulleted list',
|
||||
'notes.styleNumbered': 'Numbered list',
|
||||
'notes.favourite': 'Make a favourite',
|
||||
'notes.unfavourite': 'Remove from favourites',
|
||||
'notes.title': 'Notes',
|
||||
'notes.new': 'New note',
|
||||
'notes.search': 'Search notes',
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
/**
|
||||
* Just enough Markdown to see what you are writing.
|
||||
*
|
||||
* Not a renderer: the output is the same text, in the same order, with parts
|
||||
* wrapped so they can be styled. That matters because it sits behind a textarea
|
||||
* and has to line up with it character for character — a renderer that dropped
|
||||
* the `**` or reflowed a list would drift out of alignment on the first bold word.
|
||||
*
|
||||
* So the marks stay, dimmed. Obsidian hides them except in the line the cursor is
|
||||
* in; dimming them always is simpler, does not move text under the cursor as it
|
||||
* travels, and still lets you read a document at a glance. It is a smaller idea
|
||||
* that survives contact with a textarea.
|
||||
*/
|
||||
|
||||
const INLINE = [
|
||||
// Order matters: the longer fence first, or `**bold**` is read as two italics.
|
||||
{ kind: 'code', re: /`([^`\n]+)`/g },
|
||||
{ kind: 'bold', re: /\*\*([^*\n]+)\*\*/g },
|
||||
{ kind: 'italic', re: /\*([^*\n]+)\*/g },
|
||||
{ kind: 'tag', re: /(?:^|(?<=\s))#[\p{L}\p{N}_-]{1,64}/gu },
|
||||
{ kind: 'wikilink', re: /\[\[[^\]\n]{1,200}\]\]/g }
|
||||
];
|
||||
|
||||
/**
|
||||
* segmentsOf splits one line into pieces, each with the kind it should be drawn
|
||||
* as. A piece with no kind is ordinary text.
|
||||
*/
|
||||
function inlineSegments(line) {
|
||||
const marks = [];
|
||||
|
||||
// Each pass reads a copy with the earlier passes' characters blanked out.
|
||||
//
|
||||
// Skipping overlaps after the fact is not enough, and the failure is subtle:
|
||||
// after `**fed**` is claimed as bold, a plain overlap check still lets the
|
||||
// italic pass start at the leftover `*` and run to the next one — swallowing
|
||||
// " og " and leaving the actual italic word unmarked. Blanking means a later
|
||||
// pass cannot see the characters at all.
|
||||
let masked = line;
|
||||
const blank = (start, end) =>
|
||||
(masked = masked.slice(0, start) + '\u0000'.repeat(end - start) + masked.slice(end));
|
||||
|
||||
for (const { kind, re } of INLINE) {
|
||||
re.lastIndex = 0;
|
||||
let m;
|
||||
while ((m = re.exec(masked))) {
|
||||
marks.push({ kind, start: m.index, end: m.index + m[0].length });
|
||||
}
|
||||
for (const mark of marks) blank(mark.start, mark.end);
|
||||
}
|
||||
marks.sort((a, b) => a.start - b.start);
|
||||
|
||||
const out = [];
|
||||
let at = 0;
|
||||
for (const mark of marks) {
|
||||
if (mark.start > at) out.push({ text: line.slice(at, mark.start) });
|
||||
out.push({ text: line.slice(mark.start, mark.end), kind: mark.kind });
|
||||
at = mark.end;
|
||||
}
|
||||
if (at < line.length) out.push({ text: line.slice(at) });
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* linesOf turns a body into lines, each with a block kind and its inline pieces.
|
||||
* Every line is returned, blank ones included, or the mirror would be one line
|
||||
* short of the textarea for every empty line in the note.
|
||||
*/
|
||||
export function linesOf(body) {
|
||||
return body.split('\n').map((line) => {
|
||||
const heading = /^(#{1,6})\s/.exec(line);
|
||||
if (heading) {
|
||||
return { block: `h${heading[1].length}`, parts: inlineSegments(line) };
|
||||
}
|
||||
if (/^\s*[-*+]\s/.test(line)) return { block: 'list', parts: inlineSegments(line) };
|
||||
if (/^\s*\d+\.\s/.test(line)) return { block: 'list', parts: inlineSegments(line) };
|
||||
if (/^\s*>\s?/.test(line)) return { block: 'quote', parts: inlineSegments(line) };
|
||||
return { block: 'p', parts: inlineSegments(line) };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* Between what you see and what is stored.
|
||||
*
|
||||
* The editor is rich text; the note on disk is Markdown. That is not a compromise
|
||||
* anybody has to live with silently — it is the reason the export is trustworthy:
|
||||
* the file a note becomes is the file it already was. So these two functions are
|
||||
* the seam, and they have to agree with each other exactly, or a note changes
|
||||
* shape a little every time it is opened and saved.
|
||||
*
|
||||
* The set of styles is deliberately small and matches what Apple Notes offers,
|
||||
* because that is the vocabulary somebody coming from there already has:
|
||||
*
|
||||
* Titel → #
|
||||
* Overskrift → ##
|
||||
* Underrubrik → ###
|
||||
* Brødtekst → nothing
|
||||
* Monotype → four spaces
|
||||
* Punktliste → -
|
||||
* Nummereret → 1.
|
||||
* Blokcitat → >
|
||||
*
|
||||
* Bold, italic and strikethrough have Markdown of their own. Underline does not —
|
||||
* there is no such thing in any Markdown dialect — so it is stored as inline HTML,
|
||||
* which every Markdown reader passes through untouched. It is the one place where
|
||||
* the file is not pure Markdown, and it is that rather than dropping a style the
|
||||
* source program has.
|
||||
*/
|
||||
|
||||
const BLOCKS = [
|
||||
{ style: 'title', tag: 'h1', prefix: '# ' },
|
||||
{ style: 'heading', tag: 'h2', prefix: '## ' },
|
||||
{ style: 'subheading', tag: 'h3', prefix: '### ' },
|
||||
{ style: 'quote', tag: 'blockquote', prefix: '> ' },
|
||||
{ style: 'mono', tag: 'pre', prefix: ' ' }
|
||||
];
|
||||
|
||||
const escapeHtml = (s) =>
|
||||
s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
/** Inline marks, innermost first so a bold word inside italics survives both. */
|
||||
function inlineToHtml(text) {
|
||||
return escapeHtml(text)
|
||||
.replace(/<u>(.+?)<\/u>/g, '<u>$1</u>')
|
||||
.replace(/`([^`]+)`/g, '<code>$1</code>')
|
||||
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||
.replace(/~~(.+?)~~/g, '<s>$1</s>')
|
||||
.replace(/(^|[^*])\*([^*]+)\*/g, '$1<em>$2</em>');
|
||||
}
|
||||
|
||||
/**
|
||||
* markdownToHtml renders a note for the editor.
|
||||
*
|
||||
* Every line becomes exactly one block. Markdown would normally join consecutive
|
||||
* lines into one paragraph; here it must not, because the person typed a line and
|
||||
* expects to get it back — an editor that silently reflows what somebody wrote is
|
||||
* an editor they stop trusting.
|
||||
*/
|
||||
export function markdownToHtml(markdown) {
|
||||
const lines = (markdown ?? '').split('\n');
|
||||
const out = [];
|
||||
let list = null;
|
||||
|
||||
const closeList = () => {
|
||||
if (list) {
|
||||
out.push(`</${list}>`);
|
||||
list = null;
|
||||
}
|
||||
};
|
||||
|
||||
for (const line of lines) {
|
||||
const bullet = /^[-*+]\s+(.*)$/.exec(line);
|
||||
const numbered = /^\d+\.\s+(.*)$/.exec(line);
|
||||
|
||||
if (bullet || numbered) {
|
||||
const want = bullet ? 'ul' : 'ol';
|
||||
if (list !== want) {
|
||||
closeList();
|
||||
out.push(`<${want}>`);
|
||||
list = want;
|
||||
}
|
||||
out.push(`<li>${inlineToHtml((bullet ?? numbered)[1])}</li>`);
|
||||
continue;
|
||||
}
|
||||
closeList();
|
||||
|
||||
const block = BLOCKS.find((b) =>
|
||||
b.prefix === ' ' ? line.startsWith(' ') : line.startsWith(b.prefix)
|
||||
);
|
||||
if (block) {
|
||||
out.push(`<${block.tag}>${inlineToHtml(line.slice(block.prefix.length))}</${block.tag}>`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// An empty line is still a line. Without the break the browser collapses the
|
||||
// block to nothing and the caret has nowhere to stand.
|
||||
out.push(`<p>${line.trim() === '' ? '<br>' : inlineToHtml(line)}</p>`);
|
||||
}
|
||||
closeList();
|
||||
return out.join('');
|
||||
}
|
||||
|
||||
/** The inline marks, read back off the DOM. */
|
||||
function inlineToMarkdown(node) {
|
||||
if (node.nodeType === Node.TEXT_NODE) return node.textContent;
|
||||
if (node.nodeType !== Node.ELEMENT_NODE) return '';
|
||||
|
||||
const inner = [...node.childNodes].map(inlineToMarkdown).join('');
|
||||
switch (node.tagName) {
|
||||
case 'STRONG':
|
||||
case 'B':
|
||||
return inner ? `**${inner}**` : '';
|
||||
case 'EM':
|
||||
case 'I':
|
||||
return inner ? `*${inner}*` : '';
|
||||
case 'S':
|
||||
case 'STRIKE':
|
||||
case 'DEL':
|
||||
return inner ? `~~${inner}~~` : '';
|
||||
case 'U':
|
||||
return inner ? `<u>${inner}</u>` : '';
|
||||
case 'CODE':
|
||||
return inner ? `\`${inner}\`` : '';
|
||||
case 'SPAN': {
|
||||
// The browser's own way of saying bold or italic when it is writing styles
|
||||
// rather than tags. Read as well as tags, because `styleWithCSS` is not
|
||||
// honoured everywhere and a note must not lose a format on the way out.
|
||||
const style = node.getAttribute('style') ?? '';
|
||||
if (/font-weight:\s*(bold|[6-9]00)/.test(style)) return inner ? `**${inner}**` : '';
|
||||
if (/font-style:\s*italic/.test(style)) return inner ? `*${inner}*` : '';
|
||||
if (/text-decoration[^;]*line-through/.test(style)) return inner ? `~~${inner}~~` : '';
|
||||
if (/text-decoration[^;]*underline/.test(style)) return inner ? `<u>${inner}</u>` : '';
|
||||
return inner;
|
||||
}
|
||||
case 'BR':
|
||||
return '';
|
||||
default:
|
||||
return inner;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* htmlToMarkdown reads the editor back.
|
||||
*
|
||||
* Written against the DOM rather than against a string of HTML, because that is
|
||||
* what contenteditable actually produces — and what it produces is not tidy. The
|
||||
* browser will nest, split and re-wrap as somebody types, and a regular expression
|
||||
* over that is a guess.
|
||||
*/
|
||||
export function htmlToMarkdown(root) {
|
||||
const lines = [];
|
||||
|
||||
const walk = (node) => {
|
||||
for (const child of node.childNodes) {
|
||||
if (child.nodeType === Node.TEXT_NODE) {
|
||||
if (child.textContent.trim()) lines.push(child.textContent);
|
||||
continue;
|
||||
}
|
||||
if (child.nodeType !== Node.ELEMENT_NODE) continue;
|
||||
|
||||
switch (child.tagName) {
|
||||
case 'UL':
|
||||
case 'OL': {
|
||||
let n = 1;
|
||||
for (const li of child.children) {
|
||||
const text = inlineToMarkdown(li).trim();
|
||||
lines.push(child.tagName === 'UL' ? `- ${text}` : `${n++}. ${text}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'DIV':
|
||||
// The browser's own container when nothing else applies. Read through
|
||||
// it rather than treating it as a block, or every paste adds a level.
|
||||
if ([...child.children].some((c) => /^(P|H[1-3]|UL|OL|PRE|BLOCKQUOTE|DIV)$/.test(c.tagName))) {
|
||||
walk(child);
|
||||
} else {
|
||||
lines.push(inlineToMarkdown(child));
|
||||
}
|
||||
break;
|
||||
default: {
|
||||
const block = BLOCKS.find((b) => b.tag === child.tagName.toLowerCase());
|
||||
const text = inlineToMarkdown(child);
|
||||
lines.push(block ? block.prefix + text : text);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
walk(root);
|
||||
// Trailing blank lines are what an editor accumulates from people pressing
|
||||
// return at the end; they are not content and they grow every time.
|
||||
while (lines.length && lines[lines.length - 1].trim() === '') lines.pop();
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
import { api, humanMessage } from '$lib/api.js';
|
||||
import { app } from '$lib/stores.svelte.js';
|
||||
import { t } from '$lib/i18n.svelte.js';
|
||||
import { linesOf } from '$lib/markdown.js';
|
||||
import NoteEditor from '$lib/components/NoteEditor.svelte';
|
||||
|
||||
let notes = $state([]);
|
||||
let selected = $state(null);
|
||||
@@ -89,6 +89,25 @@
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Favourites are the pinned ones. The list already puts them first, so marking
|
||||
* one is the same act as saying "keep this where I can see it" — one idea, not
|
||||
* two that have to be explained apart.
|
||||
*/
|
||||
async function favourite(note) {
|
||||
const pinned = !note.pinned;
|
||||
// Moved before the answer comes back: a star that waits for a round trip
|
||||
// feels broken on a slow connection, and the cost of being wrong is a star.
|
||||
notes = notes.map((n) => (n.id === note.id ? { ...n, pinned } : n));
|
||||
try {
|
||||
await api.updateNote(note.id, { pinned });
|
||||
await load(query);
|
||||
} catch (e) {
|
||||
notes = notes.map((n) => (n.id === note.id ? { ...n, pinned: !pinned } : n));
|
||||
app.toast(humanMessage(e));
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(note) {
|
||||
if (!confirm(t('notes.deleteNote', { name: note.title || t('notes.untitled') }))) return;
|
||||
try {
|
||||
@@ -103,11 +122,7 @@
|
||||
// What the note points at, for the panel under the editor.
|
||||
let links = $derived(selected?.links ?? []);
|
||||
|
||||
// The styled twin of what is in the textarea. Recomputed on every keystroke,
|
||||
// which sounds expensive and is not: it is a split and a handful of regexes
|
||||
// over a page of text, and it runs in the same frame as the character that
|
||||
// caused it.
|
||||
let lines = $derived(linesOf(draft));
|
||||
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{t('notes.title')} · verdande</title></svelte:head>
|
||||
@@ -135,10 +150,22 @@
|
||||
<ul>
|
||||
{#each notes as note (note.id)}
|
||||
<li>
|
||||
<div class="rowline">
|
||||
<button class="row" class:on={selected?.id === note.id} onclick={() => open(note)}>
|
||||
<strong>{note.title || t('notes.untitled')}</strong>
|
||||
<span class="preview">{note.body.slice(0, 80)}</span>
|
||||
</button>
|
||||
<button
|
||||
class="star"
|
||||
class:on={note.pinned}
|
||||
onclick={() => favourite(note)}
|
||||
aria-pressed={note.pinned}
|
||||
aria-label={note.pinned ? t('notes.unfavourite') : t('notes.favourite')}
|
||||
title={note.pinned ? t('notes.unfavourite') : t('notes.favourite')}
|
||||
>
|
||||
{note.pinned ? '★' : '☆'}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
@@ -147,33 +174,14 @@
|
||||
|
||||
<section class="editor">
|
||||
{#if selected}
|
||||
<!-- The mirror sits behind the textarea and must match it exactly: same font,
|
||||
same size, same padding, same wrapping. Any difference shows up as
|
||||
formatting that drifts away from the text as the note grows.
|
||||
|
||||
A contenteditable would let the text be styled directly and would also
|
||||
break undo, autocorrect and IME input — a bad trade in the one place in
|
||||
this program where somebody writes for half an hour at a stretch. -->
|
||||
<div class="paper">
|
||||
<div class="mirror" aria-hidden="true">
|
||||
{#each lines as line}
|
||||
<div class={line.block}>
|
||||
{#each line.parts as part}
|
||||
{#if part.kind}<span class={part.kind}>{part.text}</span>{:else}{part.text}{/if}
|
||||
{/each}{#if !line.parts.length} {/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
bind:value={draft}
|
||||
oninput={typed}
|
||||
onblur={save}
|
||||
spellcheck="true"
|
||||
aria-label={t('notes.body')}
|
||||
placeholder={t('notes.placeholder')}
|
||||
></textarea>
|
||||
</div>
|
||||
<NoteEditor
|
||||
note={selected}
|
||||
onchange={(body) => {
|
||||
draft = body;
|
||||
typed();
|
||||
}}
|
||||
onsave={save}
|
||||
/>
|
||||
|
||||
<footer>
|
||||
<span class="hint">{saving ? t('notes.saving') : t('notes.saved')}</span>
|
||||
@@ -184,7 +192,10 @@
|
||||
{/each}
|
||||
</span>
|
||||
{/if}
|
||||
<button class="remove" onclick={() => remove(selected)}>{t('notes.delete')}</button>
|
||||
<div class="actions">
|
||||
<button class="button" onclick={save}>{t('notes.save')}</button>
|
||||
<button class="button danger" onclick={() => remove(selected)}>{t('notes.delete')}</button>
|
||||
</div>
|
||||
</footer>
|
||||
{:else}
|
||||
<p class="empty">{t('notes.pickOne')}</p>
|
||||
@@ -194,8 +205,10 @@
|
||||
|
||||
<style>
|
||||
.notes {
|
||||
/* Air above the heading, so it does not sit against the top bar. */
|
||||
padding-top: var(--s3);
|
||||
/* Air on all sides. The heading, the search box and the list all sat flush
|
||||
against the sidebar's rule, which reads as a rendering fault rather than
|
||||
as a layout. */
|
||||
padding: var(--s3) 0 0 var(--s4);
|
||||
display: grid;
|
||||
grid-template-columns: minmax(220px, 300px) 1fr;
|
||||
gap: var(--s4);
|
||||
@@ -245,9 +258,34 @@
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.rowline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s1);
|
||||
}
|
||||
|
||||
.star {
|
||||
flex: none;
|
||||
width: 24px;
|
||||
color: var(--ink-faint);
|
||||
opacity: 0;
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.rowline:hover .star,
|
||||
.star.on,
|
||||
.star:focus-visible {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.star.on {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.row {
|
||||
display: block;
|
||||
width: 100%;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
padding: var(--s2);
|
||||
border-radius: var(--radius);
|
||||
@@ -398,15 +436,35 @@
|
||||
font-family: var(--mono, ui-monospace, monospace);
|
||||
}
|
||||
|
||||
.remove {
|
||||
/* Real buttons. They were bare words, which on a Mac reads as a web page rather
|
||||
than as something you can press. */
|
||||
.actions {
|
||||
margin-left: auto;
|
||||
color: var(--ink-faint);
|
||||
display: flex;
|
||||
gap: var(--s2);
|
||||
}
|
||||
|
||||
.remove:hover {
|
||||
.button {
|
||||
border: 1px solid var(--line-strong);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--s1) var(--s3);
|
||||
background: var(--surface);
|
||||
color: var(--ink);
|
||||
font-size: var(--text-xs);
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
background: var(--surface-raised);
|
||||
}
|
||||
|
||||
.button.danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.button.danger:hover {
|
||||
border-color: var(--danger);
|
||||
}
|
||||
|
||||
.empty,
|
||||
.hint {
|
||||
color: var(--ink-faint);
|
||||
|
||||
Reference in New Issue
Block a user