Skip to content
Open
Show file tree
Hide file tree
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 Mar 16, 2026
0c6482a
refactor(editor): add formatter registry to support multiple formatte…
giuxtaposition Mar 16, 2026
aa09d0c
feat(editor): make PrettierParserConfig plugins type stricter
giuxtaposition Mar 16, 2026
fb49152
fix(editor): remove unnecessary trim in extract code text
giuxtaposition Mar 16, 2026
24af153
fix(editor): use vi.waitFor instead of setTimeout in format codeblock…
giuxtaposition Mar 16, 2026
ad5ca36
fix(editor): remove XML from supported languages for prettier as it i…
giuxtaposition Mar 16, 2026
1b638fd
fix(editor): gemini suggestion adding double join
giuxtaposition Mar 16, 2026
d64c6b3
fix(editor): fix swapped parameter order in onNotificationWarning cal…
giuxtaposition Mar 16, 2026
20fa962
feat(editor): show notification toast when code formatting fails
giuxtaposition Mar 16, 2026
09fd1bd
test(editor): fix format codeblock tests not actually running when ru…
giuxtaposition Mar 16, 2026
64f921a
Merge branch 'main' into feat/add-format-codeblock-button
eliandoran Mar 19, 2026
f111468
Merge branch 'main' into feat/add-format-codeblock-button
giuxtaposition Mar 20, 2026
1dcb400
test(ckeditor5): fix templates translation test
giuxtaposition Mar 20, 2026
16fe432
refactor(ckeditor5): move actual code formatting logic in the client …
giuxtaposition Mar 20, 2026
e5d7245
Merge branch 'main' into feat/add-format-codeblock-button
giuxtaposition Mar 20, 2026
2a81162
refactor(ckeditor5): move code formatting execution to client
giuxtaposition Mar 20, 2026
ced8142
fix(ckeditor5): strip trailing newline from formatted output to preve…
giuxtaposition Mar 20, 2026
93a5536
fix(ckeditor5): add re-entrance guard to prevent concurrent format op…
giuxtaposition Mar 20, 2026
d9a2ab5
refactor(ckeditor5): extract CodeFormatterConfig type and remove redu…
giuxtaposition Mar 20, 2026
f369f16
fix(editor): simplify onNotificationWarning to not rely on empty-stri…
giuxtaposition Mar 20, 2026
48fb69e
test(editor): add FormatterRegistry.format() tests and remove duplica…
giuxtaposition Mar 20, 2026
6d49adc
refactor(editor): simplify PrettierFormatter error handling and use p…
giuxtaposition Mar 20, 2026
813c7a5
docs: add section about format code block
giuxtaposition Mar 20, 2026
0db3bb2
Merge branch 'main' into feat/add-format-codeblock-button
giuxtaposition Mar 21, 2026
6cb611d
Merge branch 'main' into feat/add-format-codeblock-button
giuxtaposition Mar 23, 2026
5c7f502
Merge remote-tracking branch 'origin/main' into feat/add-format-codeb…
giuxtaposition Apr 9, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
"rrule": "2.8.1",
"svg-pan-zoom": "3.6.2",
"tabulator-tables": "6.4.0",
"prettier": "^3.5.3",
"vanilla-js-wheel-zoom": "9.0.4"
},
"devDependencies": {
Expand Down
277 changes: 277 additions & 0 deletions apps/client/src/services/code_formatter.spec.ts
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] ");
});
});
});
29 changes: 29 additions & 0 deletions apps/client/src/services/code_formatter.ts
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);
}
}
80 changes: 80 additions & 0 deletions apps/client/src/services/prettier_formatter.ts
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"),
]);
Comment thread
giuxtaposition marked this conversation as resolved.

const typescriptPlugins = () =>
Promise.all([
import("prettier/plugins/typescript"),
import("prettier/plugins/estree"),
]);

const postcssPlugins = () =>
import("prettier/plugins/postcss").then((m) => [m]);
Comment thread
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]),
Comment thread
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}`);
}
}
}
Loading
Loading