Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/code notes: fix some issues
Adorian Doran67c21fc5c482
diff --git a/apps/client/src/widgets/type_widgets/code/Code.spec.tsx b/apps/client/src/widgets/type_widgets/code/Code.spec.tsxindex 54bc8afd1f..41d7157160 100644--- a/apps/client/src/widgets/type_widgets/code/Code.spec.tsx+++ b/apps/client/src/widgets/type_widgets/code/Code.spec.tsx@@ -78,8 +78,14 @@ describe("EditableCode", () => {});it("publishes its editor while it is displayed for the note of its context", async () => {- const setContextData = vi.fn();- const noteContext = { noteId: noteA.noteId, setContextData } as unknown as NoteContext;+ const contextData = new Map<string, unknown>();+ const setContextData = vi.fn((key: string, value: unknown) => contextData.set(key, value));+ const noteContext = {+ noteId: noteA.noteId,+ setContextData,+ getContextData: (key: string) => contextData.get(key),+ clearContextData: (key: string) => contextData.delete(key)+ } as unknown as NoteContext;let editor: VanillaCodeMirror | null = null;const showIn = (isVisible: boolean) => (<ParentComponent.Provider value={parent}>@@ -108,6 +114,18 @@ describe("EditableCode", () => {await act(async () => { if (container) render(showIn(false), container); });await act(async () => { if (container) render(showIn(true), container); });expect(getPublished()).toEqual([ editor ]);+ expect(contextData.get("codeEditor")).toBe(editor);++ // Hidden, as by the attachments view of the same note.+ await act(async () => { if (container) render(showIn(false), container); });+ expect(contextData.has("codeEditor")).toBe(false);++ // Hidden after another type widget has published its own editor.+ await act(async () => { if (container) render(showIn(true), container); });+ const replacement = {};+ contextData.set("codeEditor", replacement);+ await act(async () => { if (container) render(showIn(false), container); });+ expect(contextData.get("codeEditor")).toBe(replacement);});});diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsxindex 56f4ea894e..f41d648ecb 100644--- a/apps/client/src/widgets/type_widgets/code/Code.tsx+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx@@ -294,7 +294,7 @@ export function CodeEditor({/*** Publishes `editor` as the `codeEditor` context data while the type widget is displayed for the* note of `noteContext`. A note switch clears the context data, and a displayed widget publishes- * it again.+ * it again. A hidden widget clears it, unless another widget has published its editor since.*/function usePublishedEditor(noteContext: NoteContext | undefined,@@ -305,6 +305,11 @@ function usePublishedEditor(useEffect(() => {if (!noteContext || !editor || !isVisible || noteContext.noteId !== note.noteId) return;noteContext.setContextData("codeEditor", editor);+ return () => {+ if (noteContext.getContextData("codeEditor") === editor) {+ noteContext.clearContextData("codeEditor");+ }+ };}, [ noteContext, note.noteId, isVisible, editor ]);}diff --git a/packages/codemirror/src/text_tools.spec.ts b/packages/codemirror/src/text_tools.spec.tsindex c71be47345..8fc22bdbc3 100644--- a/packages/codemirror/src/text_tools.spec.ts+++ b/packages/codemirror/src/text_tools.spec.ts@@ -66,6 +66,20 @@ describe("runLineOperation", () => {expect(shuffled.marked).toBe("[b\nc\nd\na]");});+ it("keeps the direction of each range", () => {+ const target = createTarget("c\nb\na\n\nz\ny");+ target.dispatch(target.state.update({+ selection: EditorSelection.create([+ EditorSelection.range(5, 0), EditorSelection.range(7, 10)+ ])+ }));+ runLineOperation(target, "sortAscending");+ expect(target.state.sliceDoc()).toBe("a\nb\nc\n\ny\nz");+ expect(target.state.selection.ranges).toMatchObject([+ { anchor: 5, head: 0 }, { anchor: 7, head: 10 }+ ]);+ });+it("removes the line break of a block that has no line left", () => {expect(run("a\n[\n ]\nb", "removeBlankLines")).toBe("a\n|b");expect(run("a\n[\n ]", "removeBlankLines")).toBe("a|");@@ -131,6 +145,7 @@ describe("runTextTransform", () => {expect(transform("[FIRST\nSECOND]", "sentenceCase")).toBe("[First\nSecond]");expect(transform("the lord [OF THE] rings", "titleCase")).toBe("the lord [of the] rings");expect(transform("the lord of the [rings]", "titleCase")).toBe("the lord of the [Rings]");+ expect(transform("Ο[Σ] x", "lowerCase", "el")).toBe("Ο[ς] x");});it("uses the locale", () => {diff --git a/packages/codemirror/src/text_tools.ts b/packages/codemirror/src/text_tools.tsindex 2eddc0b69b..e2ee3c756e 100644--- a/packages/codemirror/src/text_tools.ts+++ b/packages/codemirror/src/text_tools.ts@@ -20,8 +20,8 @@ export function hasSelectedText(state: EditorState) {/*** Applies `operation` to the whole lines that the selection touches, in one undo step, and selects- * the changed lines. Each range of the selection changes its own lines. Returns `false` when- * nothing is selected or the editor is read-only.+ * the changed lines in the direction of each range. Each range of the selection changes its own+ * lines. Returns `false` when nothing is selected or the editor is read-only.*/export function runLineOperation(target: TextToolTarget,@@ -43,8 +43,11 @@ export function runLineOperation(return true;}- const ranges = blocks.map((block) =>- EditorSelection.range(changes.mapPos(block.from, -1), changes.mapPos(block.to, 1)));+ const ranges = blocks.map((block) => {+ const from = changes.mapPos(block.from, -1);+ const to = changes.mapPos(block.to, 1);+ return block.isBackward ? EditorSelection.range(to, from) : EditorSelection.range(from, to);+ });target.dispatch(state.update({changes,selection: EditorSelection.create(ranges, mainIndex),@@ -99,6 +102,8 @@ export function runTextTransform(interface LineBlock {from: number;to: number;+ /** Whether the first range in the block has its head before its anchor. */+ isBackward: boolean;}/** The text tools change the document as one undo step, which later typing does not join. */@@ -131,7 +136,7 @@ function getLineBlocks(state: EditorState) {if (previous && first.from <= previous.to) {previous.to = Math.max(previous.to, last.to);} else {- blocks.push({ from: first.from, to: last.to });+ blocks.push({ from: first.from, to: last.to, isBackward: range.head < range.anchor });}if (index === selection.mainIndex) {mainIndex = blocks.length - 1;diff --git a/packages/commons/src/lib/text_transforms.spec.ts b/packages/commons/src/lib/text_transforms.spec.tsindex 3824387d92..1e4c605995 100644--- a/packages/commons/src/lib/text_transforms.spec.ts+++ b/packages/commons/src/lib/text_transforms.spec.ts@@ -147,6 +147,13 @@ describe("transformText", () => {expect(titleCase("the lo", "en", { after: "rd of" })).toBe("The Lo");});+ it("lowercases a capital sigma by the end of its word in the whole line", () => {+ expect(transformText("Σ", "lowerCase", { locale: "el", before: "Ο" })).toBe("ς");+ expect(transformText("ΟΣ", "lowerCase", { locale: "el", after: "Α" })).toBe("οσ");+ expect(sentenceCase("Σ", "el", { before: "Ο" })).toBe("ς");+ expect(titleCase("ΟΣ", "el", { after: "Α" })).toBe("Οσ");+ });+it("removes the accents and marks of Latin, Greek and Cyrillic letters", () => {expect(removeDiacritics("Ștefan Țară façade Łódź Ærø")).toBe("Stefan Tara facade Lodz Æro");expect(removeDiacritics("Tiếng Việt, Đà Nẵng")).toBe("Tieng Viet, Da Nang");diff --git a/packages/commons/src/lib/text_transforms.ts b/packages/commons/src/lib/text_transforms.tsindex cc060b3333..21348c3cbd 100644--- a/packages/commons/src/lib/text_transforms.ts+++ b/packages/commons/src/lib/text_transforms.ts@@ -89,8 +89,11 @@ export function transformText(switch (transform) {case "upperCase":return text.toLocaleUpperCase(locale);- case "lowerCase":- return text.toLocaleLowerCase(locale);+ case "lowerCase": {+ const { before = "", after = "" } = options;+ const start = before.length;+ return toLowerCase(before + text + after, start, start + text.length, locale);+ }case "sentenceCase":return changeWordCase(text, locale, options, (word) => word.isSentenceStart);case "titleCase": {@@ -131,6 +134,10 @@ const MINOR_WORDS = new Map(Object.entries({ro: "a al ale cu de din în la o ori pe sau și un"}).map(([ language, words ]) => [ language, new Set(words.split(" ")) ]));+// A capital sigma at the end of a word, by the Final_Sigma condition of Unicode. Sticky, to test+// one position of a line.+const FINAL_SIGMA = /(?<=\p{Cased}\p{Case_Ignorable}*)Σ(?!\p{Case_Ignorable}*\p{Cased})/uy;+/** The lowercase letters whose capital is not their uppercase: Latin digraphs such as "dž". */const TITLE_CASE_LETTERS = new Map([ [ "dž", "Dž" ], [ "lj", "Lj" ], [ "nj", "Nj" ], [ "dz", "Dz" ] ]);// Georgian Mkhedruli letters, whose uppercase (Mtavruli) is only for text in all caps.@@ -193,10 +200,9 @@ function changeWordCase(const from = Math.max(word.start, start);const to = Math.min(word.end, end);- const part = line.slice(from, to);+ const part = toLowerCase(line, from, to, locale);const isCapitalized = from === word.start && isCapital(word, words[index + 1]);- result += line.slice(position, from)- + (isCapitalized ? capitalize(part, locale) : part.toLocaleLowerCase(locale));+ result += line.slice(position, from) + (isCapitalized ? capitalize(part, locale) : part);position = to;}return result + line.slice(position, end);@@ -219,17 +225,30 @@ function findWords(line: string): Word[] {return words;}-/** Lowercases `word` and gives it a capital first letter. */+/**+ * Lowercases the text of `line` from `from` to `to`. A capital sigma takes its form from the whole+ * line, so it becomes "ς" only at the end of a word.+ */+function toLowerCase(line: string, from: number, to: number, locale: string) {+ return line.slice(from, to)+ .replace(/Σ/g, (_, offset: number) => isFinalSigma(line, from + offset) ? "ς" : "σ")+ .toLocaleLowerCase(locale);+}++function isFinalSigma(line: string, index: number) {+ FINAL_SIGMA.lastIndex = index;+ return FINAL_SIGMA.test(line);+}++/** Gives the lowercase `word` a capital first letter. */function capitalize(word: string, locale: string) {- // Lowercased as a whole, so that a Greek sigma at the end of the word becomes "ς".- const lower = word.toLocaleLowerCase(locale);// Dutch writes the digraph "ij" as one letter: "IJsselmeer".- if (languageOf(locale) === "nl" && lower.startsWith("ij")) {- return `IJ${lower.slice(2)}`;+ if (languageOf(locale) === "nl" && word.startsWith("ij")) {+ return `IJ${word.slice(2)}`;}- const [ first ] = lower;- return toCapitalLetter(first, locale) + lower.slice(first.length);+ const [ first ] = word;+ return toCapitalLetter(first, locale) + word.slice(first.length);}function toCapitalLetter(letter: string, locale: string) {