-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
feat(editor): add format button to codeblock toolbar #9076
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
giuxtaposition
wants to merge
26
commits into
TriliumNext:main
Choose a base branch
from
giuxtaposition:feat/add-format-codeblock-button
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 23 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
108d8bc
feat(editor): add format button to codeblock toolbar
giuxtaposition 0c6482a
refactor(editor): add formatter registry to support multiple formatte…
giuxtaposition aa09d0c
feat(editor): make PrettierParserConfig plugins type stricter
giuxtaposition fb49152
fix(editor): remove unnecessary trim in extract code text
giuxtaposition 24af153
fix(editor): use vi.waitFor instead of setTimeout in format codeblock…
giuxtaposition ad5ca36
fix(editor): remove XML from supported languages for prettier as it i…
giuxtaposition 1b638fd
fix(editor): gemini suggestion adding double join
giuxtaposition d64c6b3
fix(editor): fix swapped parameter order in onNotificationWarning cal…
giuxtaposition 20fa962
feat(editor): show notification toast when code formatting fails
giuxtaposition 09fd1bd
test(editor): fix format codeblock tests not actually running when ru…
giuxtaposition 64f921a
Merge branch 'main' into feat/add-format-codeblock-button
eliandoran f111468
Merge branch 'main' into feat/add-format-codeblock-button
giuxtaposition 1dcb400
test(ckeditor5): fix templates translation test
giuxtaposition 16fe432
refactor(ckeditor5): move actual code formatting logic in the client …
giuxtaposition e5d7245
Merge branch 'main' into feat/add-format-codeblock-button
giuxtaposition 2a81162
refactor(ckeditor5): move code formatting execution to client
giuxtaposition ced8142
fix(ckeditor5): strip trailing newline from formatted output to preve…
giuxtaposition 93a5536
fix(ckeditor5): add re-entrance guard to prevent concurrent format op…
giuxtaposition d9a2ab5
refactor(ckeditor5): extract CodeFormatterConfig type and remove redu…
giuxtaposition f369f16
fix(editor): simplify onNotificationWarning to not rely on empty-stri…
giuxtaposition 48fb69e
test(editor): add FormatterRegistry.format() tests and remove duplica…
giuxtaposition 6d49adc
refactor(editor): simplify PrettierFormatter error handling and use p…
giuxtaposition 813c7a5
docs: add section about format code block
giuxtaposition 0db3bb2
Merge branch 'main' into feat/add-format-codeblock-button
giuxtaposition 6cb611d
Merge branch 'main' into feat/add-format-codeblock-button
giuxtaposition 5c7f502
Merge remote-tracking branch 'origin/main' into feat/add-format-codeb…
giuxtaposition File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,277 @@ | ||
| import { type CodeFormatter, FormatterRegistry } from "./code_formatter.js"; | ||
| import { beforeEach, describe, expect, it } from "vitest"; | ||
|
|
||
| function makeFormatter( | ||
| name: string, | ||
| supportedLanguages: string[], | ||
| ): CodeFormatter { | ||
| return { | ||
| name, | ||
| canFormat(language: string): boolean { | ||
| return supportedLanguages.includes(language); | ||
| }, | ||
| async format(code: string, _language: string): Promise<string> { | ||
| return `[${name}] ${code}`; | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| function makeNeverFormatter(name = "NeverFormatter"): CodeFormatter { | ||
| return makeFormatter(name, []); | ||
| } | ||
|
|
||
| describe("FormatterRegistry", () => { | ||
| let registry: FormatterRegistry; | ||
|
|
||
| beforeEach(() => { | ||
| registry = new FormatterRegistry(); | ||
| }); | ||
|
|
||
| describe("initial state", () => { | ||
| it("should have no formatters registered", () => { | ||
| expect(registry.isLanguageSupported("javascript")).toBe(false); | ||
| }); | ||
|
|
||
| it("should return undefined for getFormatterForLanguage when empty", () => { | ||
| expect( | ||
| registry.getFormatterForLanguage("typescript"), | ||
| ).toBeUndefined(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("isLanguageSupported", () => { | ||
| it("should return false for an unknown language when formatters are registered", () => { | ||
| registry.register(makeFormatter("A", ["javascript"])); | ||
|
|
||
| expect(registry.isLanguageSupported("python")).toBe(false); | ||
| }); | ||
|
|
||
| it("should return true for a language handled by a registered formatter", () => { | ||
| registry.register(makeFormatter("A", ["javascript"])); | ||
|
|
||
| expect(registry.isLanguageSupported("javascript")).toBe(true); | ||
| }); | ||
|
|
||
| it("should return true when only one of many formatters handles the language", () => { | ||
| registry.register(makeFormatter("A", ["css"])); | ||
| registry.register(makeFormatter("B", ["html"])); | ||
|
|
||
| expect(registry.isLanguageSupported("html")).toBe(true); | ||
| }); | ||
|
|
||
| it("should return false when all registered formatters reject the language", () => { | ||
| registry.register(makeNeverFormatter("X")); | ||
| registry.register(makeNeverFormatter("Y")); | ||
|
|
||
| expect(registry.isLanguageSupported("rust")).toBe(false); | ||
| }); | ||
| }); | ||
|
|
||
| describe("getFormatterForLanguage", () => { | ||
| it("should return undefined for an unregistered language", () => { | ||
| registry.register(makeFormatter("A", ["javascript"])); | ||
|
|
||
| expect(registry.getFormatterForLanguage("rust")).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("should return the matching formatter for a registered language", () => { | ||
| const formatter = makeFormatter("Prettier", ["typescript"]); | ||
| registry.register(formatter); | ||
|
|
||
| expect(registry.getFormatterForLanguage("typescript")).toBe( | ||
| formatter, | ||
| ); | ||
| }); | ||
|
|
||
| it("should return the first matching formatter when multiple formatters support the language", () => { | ||
| const first = makeFormatter("First", ["javascript"]); | ||
| const second = makeFormatter("Second", ["javascript"]); | ||
| registry.register(first); | ||
| registry.register(second); | ||
|
|
||
| expect(registry.getFormatterForLanguage("javascript")).toBe(first); | ||
| }); | ||
|
|
||
| it("should return the correct formatter when languages do not overlap", () => { | ||
| const cssFormatter = makeFormatter("CSS", ["css"]); | ||
| const jsFormatter = makeFormatter("JS", ["javascript"]); | ||
| registry.register(cssFormatter); | ||
| registry.register(jsFormatter); | ||
|
|
||
| expect(registry.getFormatterForLanguage("css")).toBe(cssFormatter); | ||
| expect(registry.getFormatterForLanguage("javascript")).toBe( | ||
| jsFormatter, | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe("register", () => { | ||
| it("should allow registering a single formatter", () => { | ||
| registry.register(makeFormatter("A", ["json"])); | ||
|
|
||
| expect(registry.isLanguageSupported("json")).toBe(true); | ||
| }); | ||
|
|
||
| it("should allow registering multiple formatters independently", () => { | ||
| registry.register(makeFormatter("A", ["json"])); | ||
| registry.register(makeFormatter("B", ["yaml"])); | ||
|
|
||
| expect(registry.isLanguageSupported("json")).toBe(true); | ||
| expect(registry.isLanguageSupported("yaml")).toBe(true); | ||
| }); | ||
|
|
||
| it("should give priority to the first registered formatter when both handle the same language", () => { | ||
| const first = makeFormatter("First", ["scss"]); | ||
| const second = makeFormatter("Second", ["scss"]); | ||
| registry.register(first); | ||
| registry.register(second); | ||
|
|
||
| const resolved = registry.getFormatterForLanguage("scss"); | ||
|
|
||
| expect(resolved?.name).toBe("First"); | ||
| }); | ||
|
|
||
| it("should skip non-matching formatters and reach the one that matches", () => { | ||
| const noMatch = makeNeverFormatter("NoMatch"); | ||
| const match = makeFormatter("Match", ["graphql"]); | ||
| registry.register(noMatch); | ||
| registry.register(match); | ||
|
|
||
| expect(registry.getFormatterForLanguage("graphql")).toBe(match); | ||
| }); | ||
| }); | ||
|
|
||
| describe("format", () => { | ||
| it("should delegate to the matching formatter", async () => { | ||
| registry.register(makeFormatter("F", ["javascript"])); | ||
|
|
||
| const result = await registry.format("x", "javascript"); | ||
|
|
||
| expect(result).toBe("[F] x"); | ||
| }); | ||
|
|
||
| it("should delegate to the first matching formatter when multiple match", async () => { | ||
| registry.register(makeFormatter("First", ["javascript"])); | ||
| registry.register(makeFormatter("Second", ["javascript"])); | ||
|
|
||
| const result = await registry.format("x", "javascript"); | ||
|
|
||
| expect(result).toBe("[First] x"); | ||
| }); | ||
|
|
||
| it("should reject with an error for an unsupported language", async () => { | ||
| await expect(registry.format("x", "rust")).rejects.toThrow( | ||
| "No formatter available for language: rust", | ||
| ); | ||
| }); | ||
|
|
||
| it("should reject with an error when registry is empty", async () => { | ||
| await expect(registry.format("x", "javascript")).rejects.toThrow( | ||
| "No formatter available for language: javascript", | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe("canFormat delegation", () => { | ||
| it("should delegate canFormat to each registered formatter in order", () => { | ||
| const callLog: string[] = []; | ||
|
|
||
| const trackingFormatter = ( | ||
| name: string, | ||
| languages: string[], | ||
| ): CodeFormatter => ({ | ||
| name, | ||
| canFormat(language: string): boolean { | ||
| callLog.push(name); | ||
| return languages.includes(language); | ||
| }, | ||
| async format(code: string): Promise<string> { | ||
| return code; | ||
| }, | ||
| }); | ||
|
|
||
| const formatterA = trackingFormatter("A", []); | ||
| const formatterB = trackingFormatter("B", ["markdown"]); | ||
| registry.register(formatterA); | ||
| registry.register(formatterB); | ||
|
|
||
| registry.getFormatterForLanguage("markdown"); | ||
|
|
||
| expect(callLog).toEqual(["A", "B"]); | ||
| }); | ||
|
|
||
| it("should stop delegation at the first formatter that handles the language", () => { | ||
| const callLog: string[] = []; | ||
|
|
||
| const trackingFormatter = ( | ||
| name: string, | ||
| languages: string[], | ||
| ): CodeFormatter => ({ | ||
| name, | ||
| canFormat(language: string): boolean { | ||
| callLog.push(name); | ||
| return languages.includes(language); | ||
| }, | ||
| async format(code: string): Promise<string> { | ||
| return code; | ||
| }, | ||
| }); | ||
|
|
||
| const formatterA = trackingFormatter("A", ["html"]); | ||
| const formatterB = trackingFormatter("B", ["html"]); | ||
| registry.register(formatterA); | ||
| registry.register(formatterB); | ||
|
|
||
| registry.getFormatterForLanguage("html"); | ||
|
|
||
| // Array.prototype.find stops at the first truthy result, so B | ||
| // should never be consulted. | ||
| expect(callLog).toEqual(["A"]); | ||
| }); | ||
| }); | ||
|
|
||
| describe("CodeFormatter interface contract", () => { | ||
| it("should expose a readonly name property", () => { | ||
| const formatter = makeFormatter("TestFormatter", ["javascript"]); | ||
|
|
||
| expect(formatter.name).toBe("TestFormatter"); | ||
| }); | ||
|
|
||
| it("canFormat should return true for a supported language", () => { | ||
| const formatter = makeFormatter("F", ["css", "scss"]); | ||
|
|
||
| expect(formatter.canFormat("css")).toBe(true); | ||
| expect(formatter.canFormat("scss")).toBe(true); | ||
| }); | ||
|
|
||
| it("canFormat should return false for an unsupported language", () => { | ||
| const formatter = makeFormatter("F", ["css"]); | ||
|
|
||
| expect(formatter.canFormat("rust")).toBe(false); | ||
| }); | ||
|
|
||
| it("format should return a promise that resolves to a string", async () => { | ||
| const formatter = makeFormatter("F", ["javascript"]); | ||
|
|
||
| const result = await formatter.format("const x = 1", "javascript"); | ||
|
|
||
| expect(typeof result).toBe("string"); | ||
| }); | ||
|
|
||
| it("format should resolve with the formatted output", async () => { | ||
| const formatter = makeFormatter("F", ["javascript"]); | ||
|
|
||
| const result = await formatter.format("const x = 1", "javascript"); | ||
|
|
||
| expect(result).toBe("[F] const x = 1"); | ||
| }); | ||
|
|
||
| it("format should preserve empty string input", async () => { | ||
| const formatter = makeFormatter("F", ["javascript"]); | ||
|
|
||
| const result = await formatter.format("", "javascript"); | ||
|
|
||
| expect(result).toBe("[F] "); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| export interface CodeFormatter { | ||
| readonly name: string; | ||
| canFormat(language: string): boolean; | ||
| format(code: string, language: string): Promise<string>; | ||
| } | ||
|
|
||
| export class FormatterRegistry { | ||
| private readonly formatters: CodeFormatter[] = []; | ||
|
|
||
| register(formatter: CodeFormatter): void { | ||
| this.formatters.push(formatter); | ||
| } | ||
|
|
||
| getFormatterForLanguage(language: string): CodeFormatter | undefined { | ||
| return this.formatters.find((f) => f.canFormat(language)); | ||
| } | ||
|
|
||
| isLanguageSupported(language: string): boolean { | ||
| return this.formatters.some((f) => f.canFormat(language)); | ||
| } | ||
|
|
||
| format(code: string, language: string): Promise<string> { | ||
| const formatter = this.getFormatterForLanguage(language); | ||
| if (!formatter) { | ||
| return Promise.reject(new Error(`No formatter available for language: ${language}`)); | ||
| } | ||
| return formatter.format(code, language); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import type { CodeFormatter } from "./code_formatter.js"; | ||
| import type { Plugin } from "prettier"; | ||
|
|
||
| interface PrettierParserConfig { | ||
| parser: string; | ||
| plugins: () => Promise<(string | URL | Plugin)[]>; | ||
| } | ||
|
|
||
| const babelPlugins = () => | ||
| Promise.all([ | ||
| import("prettier/plugins/babel"), | ||
| import("prettier/plugins/estree"), | ||
| ]); | ||
|
|
||
| const typescriptPlugins = () => | ||
| Promise.all([ | ||
| import("prettier/plugins/typescript"), | ||
| import("prettier/plugins/estree"), | ||
| ]); | ||
|
|
||
| const postcssPlugins = () => | ||
| import("prettier/plugins/postcss").then((m) => [m]); | ||
|
giuxtaposition marked this conversation as resolved.
|
||
|
|
||
| const LANGUAGE_MAP: Record<string, PrettierParserConfig> = { | ||
| "application-javascript-env-frontend": { parser: "babel", plugins: babelPlugins }, | ||
| "application-javascript-env-backend": { parser: "babel", plugins: babelPlugins }, | ||
| "text-jsx": { parser: "babel", plugins: babelPlugins }, | ||
| "application-typescript": { parser: "typescript", plugins: typescriptPlugins }, | ||
| "text-typescript-jsx": { parser: "typescript", plugins: typescriptPlugins }, | ||
| "application-json": { parser: "json", plugins: babelPlugins }, | ||
| "text-css": { parser: "css", plugins: postcssPlugins }, | ||
| "text-x-less": { parser: "less", plugins: postcssPlugins }, | ||
| "text-x-scss": { parser: "scss", plugins: postcssPlugins }, | ||
| "text-html": { | ||
| parser: "html", | ||
| plugins: () => import("prettier/plugins/html").then((m) => [m]), | ||
|
giuxtaposition marked this conversation as resolved.
|
||
| }, | ||
| "text-x-yaml": { | ||
| parser: "yaml", | ||
| plugins: () => import("prettier/plugins/yaml").then((m) => [m]), | ||
| }, | ||
| "text-x-markdown": { | ||
| parser: "markdown", | ||
| plugins: () => import("prettier/plugins/markdown").then((m) => [m]), | ||
| }, | ||
| }; | ||
|
|
||
| export class PrettierFormatter implements CodeFormatter { | ||
| readonly name = "Prettier"; | ||
|
|
||
| canFormat(language: string): boolean { | ||
| return language in LANGUAGE_MAP; | ||
| } | ||
|
|
||
| async format(code: string, language: string): Promise<string> { | ||
| const config = LANGUAGE_MAP[language]; | ||
| if (!config) { | ||
| throw new Error( | ||
| `PrettierFormatter: no parser config for language "${language}"`, | ||
| ); | ||
| } | ||
|
|
||
| const [prettier, plugins] = await Promise.all([ | ||
| import("prettier/standalone"), | ||
| config.plugins(), | ||
| ]); | ||
|
|
||
| try { | ||
| return await prettier.format(code, { | ||
| parser: config.parser, | ||
| plugins, | ||
| tabWidth: 4, | ||
| printWidth: 120, | ||
| }); | ||
| } catch (err) { | ||
| const msg = err instanceof Error ? err.message : String(err); | ||
| throw new Error(`Prettier: ${msg}`); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.