Skip to content
Open
Show file tree
Hide file tree
Changes from 10 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
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CKTextEditor, ClassicEditor, EditorWatchdog, PopupEditor, TemplateDefinition,type WatchdogConfig } from "@triliumnext/ckeditor5";
import { CKTextEditor, ClassicEditor, EditorWatchdog, PopupEditor, TemplateDefinition, type EventInfo, type NotificationShowEventData, type WatchdogConfig } from "@triliumnext/ckeditor5";
import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
import { HTMLProps, RefObject, useEffect, useImperativeHandle, useRef, useState } from "preact/compat";

Expand All @@ -25,7 +25,7 @@ interface CKEditorWithWatchdogProps extends Pick<HTMLProps<HTMLDivElement>, "cla
isClassicEditor?: boolean;
watchdogRef: RefObject<EditorWatchdog>;
watchdogConfig?: WatchdogConfig;
onNotificationWarning?: (evt: any, data: any) => void;
onNotificationWarning?: (evt: EventInfo, data: NotificationShowEventData) => void;
onWatchdogStateChange?: (watchdog: EditorWatchdog) => void;
onChange: () => void;
/** Called upon whenever a new CKEditor instance is initialized, whether it's the first initialization, after a crash or after a config change that requires it (e.g. content language). */
Expand Down
10 changes: 5 additions & 5 deletions apps/client/src/widgets/type_widgets/text/EditableText.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import "./EditableText.css";

import { CKTextEditor, EditorWatchdog, TemplateDefinition } from "@triliumnext/ckeditor5";
import { CKTextEditor, EditorWatchdog, TemplateDefinition, type EventInfo, type NotificationShowEventData } from "@triliumnext/ckeditor5";
import { deferred } from "@triliumnext/commons";
import { RefObject } from "preact";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
Expand Down Expand Up @@ -333,13 +333,13 @@ function useWatchdogCrashHandling() {
return onWatchdogStateChange;
}

function onNotificationWarning(data, evt) {
function onNotificationWarning(evt: EventInfo, data: NotificationShowEventData) {
const title = data.title;
const message = data.message.message;
const message = data.message;

if (title && message) {
toast.showErrorTitleAndMessage(data.title, data.message.message);
} else if (title) {
toast.showErrorTitleAndMessage(title, message);
} else if (title || message) {
toast.showError(title || message);
}

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
"docs:preview": "pnpm http-server site -p 9000",
"edit-docs:edit-demo": "pnpm run --filter edit-docs edit-demo",
"test:all": "pnpm test:parallel && pnpm test:sequential",
"test:parallel": "pnpm --filter=!server --filter=!ckeditor5-mermaid --filter=!ckeditor5-math --parallel test",
"test:sequential": "pnpm --filter=server --filter=ckeditor5-mermaid --filter=ckeditor5-math --sequential test",
"test:parallel": "pnpm --filter=!server --filter=!ckeditor5-mermaid --filter=!ckeditor5-math --filter=!@triliumnext/ckeditor5 --parallel test",
"test:sequential": "pnpm --filter=server --filter=ckeditor5-mermaid --filter=ckeditor5-math --filter=@triliumnext/ckeditor5 --sequential test",
"typecheck": "tsc --build",
"dev:format-check": "eslint -c eslint.format.config.mjs .",
"dev:format-fix": "eslint -c eslint.format.config.mjs . --fix",
Expand Down
6 changes: 5 additions & 1 deletion packages/ckeditor5/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"private": true,
"type": "module",
"main": "./src/index.ts",
"scripts": {
"test": "vitest"
},
"dependencies": {
"@triliumnext/commons": "workspace:*",
"@triliumnext/ckeditor5-admonition": "workspace:*",
Expand All @@ -13,7 +16,8 @@
"@triliumnext/ckeditor5-math": "workspace:*",
"@triliumnext/ckeditor5-mermaid": "workspace:*",
"ckeditor5": "47.6.1",
"ckeditor5-premium-features": "47.6.1"
"ckeditor5-premium-features": "47.6.1",
"prettier": "^3.5.3"
},
"devDependencies": {
"@smithy/middleware-retry": "4.4.42",
Expand Down
1 change: 1 addition & 0 deletions packages/ckeditor5/src/icons/format-codeblock.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion packages/ckeditor5/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { BalloonEditor, DecoupledEditor, FindAndReplaceEditing, FindCommand } fr
import "./translation_overrides.js";
export { default as EditorWatchdog } from "./custom_watchdog";
export { loadPremiumPlugins } from "./plugins.js";
export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, WatchdogConfig, WatchdogState } from "ckeditor5";
export type { EditorConfig, EventInfo, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, NotificationShowEventData, WatchdogConfig, WatchdogState } from "ckeditor5";
export type { TemplateDefinition } from "ckeditor5-premium-features";
export { default as buildExtraCommands } from "./extra_slash_commands.js";
export { default as getCkLocale } from "./i18n.js";
Expand Down
52 changes: 37 additions & 15 deletions packages/ckeditor5/src/plugins/code_block_toolbar.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,37 @@
import { BalloonToolbarShowEvent, CodeBlock, Plugin, ViewDocumentFragment, WidgetToolbarRepository, type ViewNode } from "ckeditor5";
import {
CodeBlock,
Plugin,
ViewDocumentFragment,
WidgetToolbarRepository,
type ViewNode,
} from "ckeditor5";
import CodeBlockLanguageDropdown from "./code_block_language_dropdown";
import CopyToClipboardButton from "./copy_to_clipboard_button";
import FormatCodeblockButton from "./format_codeblock/format_codeblock_button";

export default class CodeBlockToolbar extends Plugin {

static get requires() {
return [ WidgetToolbarRepository, CodeBlock, CodeBlockLanguageDropdown, CopyToClipboardButton ] as const;
return [
WidgetToolbarRepository,
CodeBlock,
CodeBlockLanguageDropdown,
CopyToClipboardButton,
FormatCodeblockButton,
] as const;
Comment thread
giuxtaposition marked this conversation as resolved.
}

afterInit() {
const editor = this.editor;
const widgetToolbarRepository = editor.plugins.get(WidgetToolbarRepository);
const widgetToolbarRepository = editor.plugins.get(
WidgetToolbarRepository,
);

widgetToolbarRepository.register("codeblock", {
items: [
"codeBlockDropdown",
"|",
"copyToClipboard"
"copyToClipboard",
"formatCodeblock",
Comment thread
giuxtaposition marked this conversation as resolved.
],
balloonClassName: "ck-toolbar-container codeblock-language-list",
getRelatedElement(selection) {
Expand All @@ -25,7 +40,8 @@ export default class CodeBlockToolbar extends Plugin {
return null;
}

let parent: ViewNode | ViewDocumentFragment | null = selectionPosition.parent;
let parent: ViewNode | ViewDocumentFragment | null =
selectionPosition.parent;
while (parent) {
if (parent.is("element", "pre")) {
return parent;
Expand All @@ -35,20 +51,26 @@ export default class CodeBlockToolbar extends Plugin {
}

return null;
}
},
});

// Hide balloon toolbar when in a code block
if (editor.plugins.has("BalloonToolbar")) {
editor.listenTo(editor.plugins.get('BalloonToolbar'), 'show', (evt) => {
const firstPosition = editor.model.document.selection.getFirstPosition();
const isInCodeBlock = firstPosition?.findAncestor('codeBlock');
editor.listenTo(
editor.plugins.get("BalloonToolbar"),
"show",
(evt) => {
const firstPosition =
editor.model.document.selection.getFirstPosition();
const isInCodeBlock =
firstPosition?.findAncestor("codeBlock");

if (isInCodeBlock) {
evt.stop(); // Prevent the balloon toolbar from showing
}
}, { priority: 'high' });
if (isInCodeBlock) {
evt.stop(); // Prevent the balloon toolbar from showing
}
},
{ priority: "high" },
);
}
}

}
29 changes: 29 additions & 0 deletions packages/ckeditor5/src/plugins/format_codeblock/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 static instance: FormatterRegistry | null = null;
private readonly formatters: CodeFormatter[] = [];

static getInstance(): FormatterRegistry {
if (!FormatterRegistry.instance) {
FormatterRegistry.instance = new FormatterRegistry();
}
return FormatterRegistry.instance;
}

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));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { ButtonView, Notification, Plugin } from "ckeditor5";
import formatIcon from "../../icons/format-codeblock.svg?raw";
import { FormatterRegistry } from "./code_formatter";
import { FormatCodeblockCommand } from "./format_codeblock_command";
import { PrettierFormatter } from "./prettier_formatter";

export default class FormatCodeblockButton extends Plugin {
static get requires() {
return [Notification];
}

public init() {
const editor = this.editor;

const registry = FormatterRegistry.getInstance();
registry.register(new PrettierFormatter());
Comment thread
giuxtaposition marked this conversation as resolved.
Outdated

editor.commands.add(
"formatCodeblock",
new FormatCodeblockCommand(this.editor),
);

const componentFactory = editor.ui.componentFactory;
componentFactory.add("formatCodeblock", (locale) => {
const button = new ButtonView(locale);
const command = editor.commands.get("formatCodeblock")!;

button.set({
tooltip: "Format code block",
icon: formatIcon,
});

button.bind("isEnabled").to(command, "isEnabled");

this.listenTo(button, "execute", () => {
editor.execute("formatCodeblock");
});

return button;
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { Command, ModelElement, Notification } from "ckeditor5";
import { FormatterRegistry } from "./code_formatter";

export class FormatCodeblockCommand extends Command {
declare value: string | false;

override refresh() {
const codeBlockCommand = this.editor.commands.get("codeBlock");
const language = codeBlockCommand?.value;
const registry = FormatterRegistry.getInstance();

if (
typeof language === "string" &&
registry.isLanguageSupported(language)
) {
this.isEnabled = true;
this.value = language;
} else {
this.isEnabled = false;
this.value = false;
}
}

override execute() {
const editor = this.editor;
const model = editor.model;
const selection = model.document.selection;
const notification = editor.plugins.get(Notification);
const t = editor.locale.t;

const language = this.value;
if (!language) {
return;
}

const registry = FormatterRegistry.getInstance();
const formatter = registry.getFormatterForLanguage(language);
if (!formatter) {
return;
}

const codeBlockEl = selection
.getFirstPosition()
?.findAncestor("codeBlock");
if (!codeBlockEl) {
notification.showWarning(
t("Unable to find code block element to format."),
{
namespace: "formatCodeblock",
},
);
return;
}

const codeText = this.extractCodeText(codeBlockEl);

if (!codeText) {
return;
}

formatter
.format(codeText, language)
.then((formatted) => {
if (formatted === codeText) {
return;
}

model.change((writer) => {
const range = writer.createRangeIn(codeBlockEl);
writer.remove(range);
const lines = formatted.split("\n");
for (let i = 0; i < lines.length; i++) {
if (i > 0) {
writer.appendElement("softBreak", codeBlockEl);
}
if (lines[i]) {
writer.appendText(lines[i], codeBlockEl);
}
}
});
})
.catch((err) => {
notification.showWarning(err.message || String(err), {
title: t(
`Failed to format code block with ${formatter.name}`,
),
namespace: "formatCodeblock",
});
});
}

private extractCodeText(codeBlockEl: ModelElement): string {
return Array.from(codeBlockEl.getChildren())
.map((child) => ("data" in child ? child.data : "\n"))
.join("");
}
}
17 changes: 17 additions & 0 deletions packages/ckeditor5/src/plugins/format_codeblock/languages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const LANG_JAVASCRIPT_FRONTEND = "application-javascript-env-frontend";
export const LANG_JAVASCRIPT_BACKEND = "application-javascript-env-backend";
export const LANG_TYPESCRIPT = "application-typescript";
export const LANG_TYPESCRIPT_JSX = "text-typescript-jsx";
export const LANG_JSX = "text-jsx";
export const LANG_JSON = "application-json";
export const LANG_YAML = "text-x-yaml";
export const LANG_GRAPHQL = "text-x-graphql";
export const LANG_HTML = "text-html";
export const LANG_XML = "text-xml";
export const LANG_MARKDOWN = "text-x-markdown";
export const LANG_CSS = "text-css";
export const LANG_LESS = "text-x-less";
export const LANG_SCSS = "text-x-scss";
export const LANG_PYTHON = "text-x-python";
export const LANG_RUST = "text-x-rustsrc";
export const LANG_C = "text-x-csrc";
Loading
Loading