feat(editor): functional autoformat when type is not specified

This commit is contained in:
Elian Doran 2025-03-14 22:54:46 +02:00
parent 4967883f1d
commit 2f3106d8cd
3 changed files with 15 additions and 9 deletions

View File

@ -26,11 +26,17 @@ export default class AdmonitionAutoformat extends Plugin {
const instance = (this as any);
blockAutoformatEditing(this.editor, instance, /^\!\!\[*\! (.+) $/, ({ match }) => {
const type = tryParseAdmonitionType(match);
if (!type) {
return;
}
this.editor.execute("admonition", { forceValue: type });
if (type) {
// User has entered the admonition type, so we insert as-is.
this.editor.execute("admonition", { forceValue: type });
} else {
// User has not entered a valid type, assume it's part of the text of the admonition.
this.editor.execute("admonition");
if (match.length > 1) {
this.editor.execute("insertText", { text: (match[1] ?? "") + " " });
}
}
});
}
}

View File

@ -18,6 +18,7 @@ import type { DocumentFragment, Element, Position, Range, Schema, Writer } from
*/
export const admonitionTypes = [ "note", "tip", "important", "caution", "warning" ] as const;
export const defaultAdmonitionType = admonitionTypes[0];
export type AdmonitionType = typeof admonitionTypes[number];
interface ExecuteOpts {

View File

@ -11,7 +11,7 @@ import { Plugin } from 'ckeditor5/src/core.js';
import { Enter, type ViewDocumentEnterEvent } from 'ckeditor5/src/enter.js';
import { Delete, type ViewDocumentDeleteEvent } from 'ckeditor5/src/typing.js';
import AdmonitionCommand from './admonitioncommand.js';
import AdmonitionCommand, { AdmonitionType, admonitionTypes, defaultAdmonitionType } from './admonitioncommand.js';
import { ADMONITION_TYPES } from './admonitionui.js';
/**
@ -56,11 +56,10 @@ export default class AdmonitionEditing extends Plugin {
classes: "admonition",
},
model: (viewElement, { writer }) => {
let type = "note";
const allowedTypes = Object.keys(ADMONITION_TYPES);
let type: AdmonitionType = defaultAdmonitionType;
for (const className of viewElement.getClassNames()) {
if (className !== "admonition" && allowedTypes.includes(className)) {
type = className;
if (className !== "admonition" && (admonitionTypes as readonly string[]).includes(className)) {
type = className as AdmonitionType;
}
}