diff --git a/src/components/ExtendedTextarea.svelte b/src/components/ExtendedTextarea.svelte index c159a1bce..a5ed0e80f 100644 --- a/src/components/ExtendedTextarea.svelte +++ b/src/components/ExtendedTextarea.svelte @@ -11,7 +11,7 @@ import { hints } from "@app/lib/hints"; import { invoke } from "@app/lib/invoke"; - import { matchesCombo } from "@app/lib/shortcuts.svelte"; + import { matchesShortcut } from "@app/lib/shortcuts.svelte"; import * as utils from "@app/lib/utils"; import Button from "@app/components/Button.svelte"; @@ -437,7 +437,7 @@ class:inline onkeydown={event => { if (!preview) return; - if (matchesCombo(event, "Mod+Enter")) { + if (matchesShortcut(event, "submit")) { event.preventDefault(); void submit({ comment: body, embeds }); } diff --git a/src/components/TextInput.svelte b/src/components/TextInput.svelte index 67dfca077..222d4c385 100644 --- a/src/components/TextInput.svelte +++ b/src/components/TextInput.svelte @@ -4,7 +4,7 @@ import { onMount } from "svelte"; - import { matchesCombo } from "@app/lib/shortcuts.svelte"; + import { matchesShortcut } from "@app/lib/shortcuts.svelte"; interface Props { autofocus?: boolean; @@ -80,7 +80,7 @@ } function handleKeydown(event: KeyboardEvent) { - if (matchesCombo(event, "Mod+Enter") && onModifierSubmit) { + if (matchesShortcut(event, "submit") && onModifierSubmit) { event.preventDefault(); onModifierSubmit(); return; diff --git a/src/components/Textarea.svelte b/src/components/Textarea.svelte index 5e1db39e1..a337dac42 100644 --- a/src/components/Textarea.svelte +++ b/src/components/Textarea.svelte @@ -6,7 +6,13 @@ import { onMount, tick } from "svelte"; - import { matchesCombo } from "@app/lib/shortcuts.svelte"; + import type { MarkdownFormat, TextEdit } from "@app/lib/markdownFormat"; + import { + applyMarkdownFormat, + applyTextEdit, + pasteLinkEdit, + } from "@app/lib/markdownFormat"; + import { matchesShortcut } from "@app/lib/shortcuts.svelte"; interface Props { draggingOver?: boolean; @@ -109,13 +115,69 @@ }); }); + const formats: MarkdownFormat[] = ["bold", "italic", "code", "link"]; + + // `insertText` keeps the edit on the native undo stack; assigning is a fallback. + function applyEdit(element: HTMLTextAreaElement, edit: TextEdit) { + element.setSelectionRange(edit.from, edit.to); + const applied = edit.text + ? document.execCommand("insertText", false, edit.text) + : document.execCommand("delete"); + if (!applied) { + value = applyTextEdit(element.value, edit); + } + + selectionStart = edit.selectionStart; + selectionEnd = edit.selectionEnd; + void tick().then(() => + element.setSelectionRange(edit.selectionStart, edit.selectionEnd), + ); + } + + function handlePaste( + event: ClipboardEvent & { + currentTarget: EventTarget & HTMLTextAreaElement; + }, + ) { + void onpaste?.(event); + if (event.defaultPrevented) { + return; + } + + const element = event.currentTarget; + const edit = pasteLinkEdit( + element.value, + element.selectionStart, + element.selectionEnd, + event.clipboardData?.getData("text/plain") ?? "", + ); + if (edit) { + event.preventDefault(); + applyEdit(element, edit); + } + } + function handleKeydown(event: KeyboardEvent) { - if (matchesCombo(event, "Mod+Enter")) { + if (matchesShortcut(event, "submit")) { void submit(); } if (event.key === "Escape") { textareaElement?.blur(); } + + const format = formats.find(f => matchesShortcut(event, f)); + if (format && textareaElement) { + event.preventDefault(); + applyEdit( + textareaElement, + applyMarkdownFormat( + format, + textareaElement.value, + textareaElement.selectionStart, + textareaElement.selectionEnd, + ), + ); + } } @@ -198,7 +260,7 @@ ? "scroll" : undefined} {placeholder} - {onpaste} + onpaste={handlePaste} {oninput} {onkeypress} onfocus={() => (focussed = true)} diff --git a/src/lib/markdownFormat.ts b/src/lib/markdownFormat.ts new file mode 100644 index 000000000..d614b9df9 --- /dev/null +++ b/src/lib/markdownFormat.ts @@ -0,0 +1,187 @@ +import { safeHttpUrl } from "@app/lib/utils"; + +export type MarkdownFormat = "bold" | "italic" | "code" | "link"; + +export interface TextEdit { + from: number; + to: number; + text: string; + selectionStart: number; + selectionEnd: number; +} + +const markers: Record<"bold" | "italic" | "code", string> = { + bold: "**", + italic: "_", + code: "`", +}; + +const fence = "```"; + +function linkUrl(text: string): string | undefined { + const candidate = text.trim(); + if (candidate === "" || /\s/.test(candidate)) { + return undefined; + } + return safeHttpUrl(candidate) ? candidate : undefined; +} + +export function applyTextEdit(value: string, edit: TextEdit): string { + return value + .substring(0, edit.from) + .concat(edit.text, value.substring(edit.to)); +} + +function toggleWrap( + value: string, + start: number, + end: number, + marker: string, +): TextEdit { + const width = marker.length; + const selected = value.substring(start, end); + + if ( + selected.length >= width * 2 && + selected.startsWith(marker) && + selected.endsWith(marker) + ) { + const inner = selected.substring(width, selected.length - width); + return { + from: start, + to: end, + text: inner, + selectionStart: start, + selectionEnd: start + inner.length, + }; + } + + if ( + start >= width && + value.substring(start - width, start) === marker && + value.substring(end, end + width) === marker + ) { + return { + from: start - width, + to: end + width, + text: selected, + selectionStart: start - width, + selectionEnd: end - width, + }; + } + + return { + from: start, + to: end, + text: marker.concat(selected, marker), + selectionStart: start + width, + selectionEnd: end + width, + }; +} + +function toggleCode(value: string, start: number, end: number): TextEdit { + const selected = value.substring(start, end); + if (!selected.includes("\n")) { + return toggleWrap(value, start, end, markers.code); + } + + const opening = `${fence}\n`; + const closing = `\n${fence}`; + + if (selected.startsWith(opening) && selected.endsWith(closing)) { + const inner = selected.substring( + opening.length, + selected.length - closing.length, + ); + return { + from: start, + to: end, + text: inner, + selectionStart: start, + selectionEnd: start + inner.length, + }; + } + + if ( + start >= opening.length && + value.substring(start - opening.length, start) === opening && + value.substring(end, end + closing.length) === closing + ) { + return { + from: start - opening.length, + to: end + closing.length, + text: selected, + selectionStart: start - opening.length, + selectionEnd: end - opening.length, + }; + } + + // Fences must start on their own line. + const before = start > 0 && value[start - 1] !== "\n" ? "\n" : ""; + const after = end < value.length && value[end] !== "\n" ? "\n" : ""; + const selectionStart = start + before.length + opening.length; + + return { + from: start, + to: end, + text: before.concat(opening, selected, closing, after), + selectionStart, + selectionEnd: selectionStart + selected.length, + }; +} + +function insertLink(value: string, start: number, end: number): TextEdit { + const selected = value.substring(start, end); + const url = linkUrl(selected); + const text = url ? `[](${url})` : `[${selected}]()`; + const caret = url ? start + 1 : start + text.length - 1; + + return { + from: start, + to: end, + text, + selectionStart: caret, + selectionEnd: caret, + }; +} + +export function applyMarkdownFormat( + format: MarkdownFormat, + value: string, + start: number, + end: number, +): TextEdit { + switch (format) { + case "bold": + return toggleWrap(value, start, end, markers.bold); + case "italic": + return toggleWrap(value, start, end, markers.italic); + case "code": + return toggleCode(value, start, end); + case "link": + return insertLink(value, start, end); + } +} + +export function pasteLinkEdit( + value: string, + start: number, + end: number, + pasted: string, +): TextEdit | undefined { + const url = linkUrl(pasted); + if (start === end || !url) { + return undefined; + } + + const text = `[${value.substring(start, end)}](${url})`; + const caret = start + text.length; + + return { + from: start, + to: end, + text, + selectionStart: caret, + selectionEnd: caret, + }; +} diff --git a/src/lib/shortcuts.svelte.ts b/src/lib/shortcuts.svelte.ts index eb682602c..f90cceeb8 100644 --- a/src/lib/shortcuts.svelte.ts +++ b/src/lib/shortcuts.svelte.ts @@ -70,7 +70,41 @@ export const shortcuts = { }, decreaseFontSize: { combos: ["Mod+-"], description: "Decrease font size" }, resetFontSize: { combos: ["Mod+0"], description: "Reset font size" }, - closeModal: { combos: ["Escape"], description: "Close modal" }, + closeModal: { + combos: ["Escape"], + description: "Close modal", + note: "In a modal", + }, + submit: { + combos: ["Mod+Enter"], + description: "Submit", + note: "In a comment or description", + }, + bold: { + combos: ["Mod+B"], + description: "Bold", + note: "In a comment or description", + }, + italic: { + combos: ["Mod+I"], + description: "Italic", + note: "In a comment or description", + }, + code: { + combos: ["Mod+E"], + description: "Code", + note: "In a comment or description", + }, + link: { + combos: ["Mod+K"], + description: "Link", + note: "In a comment or description", + }, + pasteLink: { + combos: ["Mod+V"], + description: "Paste a URL over selected text to link it", + note: "In a comment or description", + }, } satisfies Record; export type ShortcutId = keyof typeof shortcuts; @@ -150,6 +184,10 @@ export function matchesCombo(event: KeyboardEvent, combo: Combo): boolean { ); } +export function matchesShortcut(event: KeyboardEvent, id: ShortcutId): boolean { + return (shortcuts[id].combos as Combo[]).some(c => matchesCombo(event, c)); +} + const keyLabels: Record = { ArrowLeft: "←", ArrowRight: "→", diff --git a/src/modals/KeyboardShortcuts.svelte b/src/modals/KeyboardShortcuts.svelte index 0fe8b0eb5..debee34a2 100644 --- a/src/modals/KeyboardShortcuts.svelte +++ b/src/modals/KeyboardShortcuts.svelte @@ -9,11 +9,24 @@ description: s.description, note: "note" in s ? s.note : undefined, })); + + const globalRows = rows.filter(row => !row.note); + const notes = rows + .map(row => row.note) + .filter( + (note, index, all): note is string => + note !== undefined && all.indexOf(note) === index, + ); + const contextGroups = notes.map(note => ({ + note, + rows: rows.filter(row => row.note === note), + })); +{#snippet shortcutRow(row: (typeof rows)[number])} +
+ {#each row.keys as key, index (key)} + {#if index > 0} + + + {/if} + {key} + {/each} +
+ {row.description} +{/snippet} + -
- {#each rows as row, index (index)} -
- {#each row.keys as key, index (key)} - {#if index > 0} - + - {/if} - {key} +
+
+ {#each globalRows as row, index (index)} + {@render shortcutRow(row)} + {/each} +
+
+ {#each contextGroups as group (group.note)} + {group.note} + {#each group.rows as row, index (index)} + {@render shortcutRow(row)} {/each} -
- - {row.description} - {#if row.note} - {row.note} - {/if} - - {/each} + {/each} +
diff --git a/tests/unit/markdownFormat.test.ts b/tests/unit/markdownFormat.test.ts new file mode 100644 index 000000000..9ceaa1782 --- /dev/null +++ b/tests/unit/markdownFormat.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, test } from "vitest"; + +import type { MarkdownFormat } from "@app/lib/markdownFormat"; +import { + applyMarkdownFormat, + applyTextEdit, + pasteLinkEdit, +} from "@app/lib/markdownFormat"; + +// Pipes mark the selection in both the input and the output. +function format(input: string, kind: MarkdownFormat): string { + const start = input.indexOf("|"); + const end = input.indexOf("|", start + 1) - 1; + const value = input.replaceAll("|", ""); + const edit = applyMarkdownFormat(kind, value, start, end); + const result = applyTextEdit(value, edit); + + return result + .substring(0, edit.selectionStart) + .concat( + "|", + result.substring(edit.selectionStart, edit.selectionEnd), + "|", + result.substring(edit.selectionEnd), + ); +} + +describe("bold", () => { + test.each([ + ["a |word| here", "a **|word|** here"], + ["a ||word", "a **||**word"], + ["a **|word|** here", "a |word| here"], + ["a |**word**| here", "a |word| here"], + ["a **||** here", "a || here"], + ])("%p => %p", (input, expected) => { + expect(format(input, "bold")).toBe(expected); + }); +}); + +describe("italic", () => { + test.each([ + ["a |word| here", "a _|word|_ here"], + ["a _|word|_ here", "a |word| here"], + ["a |_word_| here", "a |word| here"], + ["**|word|**", "**_|word|_**"], + ])("%p => %p", (input, expected) => { + expect(format(input, "italic")).toBe(expected); + }); +}); + +describe("code", () => { + test.each([ + ["a |word| here", "a `|word|` here"], + ["a `|word|` here", "a |word| here"], + ["|one\ntwo|", "```\n|one\ntwo|\n```"], + ["```\n|one\ntwo|\n```", "|one\ntwo|"], + ["a |one\ntwo| b", "a \n```\n|one\ntwo|\n```\n b"], + ["a\n|one\ntwo|\nb", "a\n```\n|one\ntwo|\n```\nb"], + ])("%p => %p", (input, expected) => { + expect(format(input, "code")).toBe(expected); + }); +}); + +describe("link", () => { + test.each([ + ["see |docs| now", "see [docs](||) now"], + ["see || now", "see [](||) now"], + ["see |https://radicle.xyz| now", "see [||](https://radicle.xyz) now"], + ])("%p => %p", (input, expected) => { + expect(format(input, "link")).toBe(expected); + }); +}); + +describe("pasteLinkEdit", () => { + test("wraps the selection and leaves the caret after the link", () => { + const value = "Read the docs here"; + const edit = pasteLinkEdit(value, 9, 13, "https://radicle.xyz"); + + expect(edit && applyTextEdit(value, edit)).toBe( + "Read the [docs](https://radicle.xyz) here", + ); + expect(edit?.selectionStart).toBe(36); + expect(edit?.selectionEnd).toBe(36); + }); + + test("falls through without a selection", () => { + expect(pasteLinkEdit("docs", 2, 2, "https://radicle.xyz")).toBeUndefined(); + }); + + test.each([ + ["https://example.com", "https://example.com"], + ["http://example.com/a?b=1#c", "http://example.com/a?b=1#c"], + [" https://example.com/path ", "https://example.com/path"], + [ + "https://app.radicle.xyz/nodes/iris.radicle.xyz/rad:z4D5U/issues/7bdaa5a", + "https://app.radicle.xyz/nodes/iris.radicle.xyz/rad:z4D5U/issues/7bdaa5a", + ], + ])("links %p", (pasted, url) => { + expect(pasteLinkEdit("docs", 0, 4, pasted)?.text).toBe(`[docs](${url})`); + }); + + test.each([ + "javascript:alert(1)", + "data:text/html,", + "file:///etc/passwd", + "rad:z4D5UCArafTzTQpDZNQRuqswh3ury", + "https://example.com and more", + "https://example.com\nhttps://example.org", + "just some words", + " ", + "", + ])("falls through for %p", pasted => { + expect(pasteLinkEdit("docs", 0, 4, pasted)).toBeUndefined(); + }); +});