feat(editor): functional autoformat when type is specified

This commit is contained in:
Elian Doran 2025-03-14 22:47:42 +02:00
parent 83a4804c2c
commit 4967883f1d
3 changed files with 28 additions and 12 deletions

View File

@ -1,6 +1,17 @@
import Plugin from "@ckeditor/ckeditor5-core/src/plugin";
import Autoformat from "@ckeditor/ckeditor5-autoformat/src/autoformat";
import blockAutoformatEditing from "@ckeditor/ckeditor5-autoformat/src/blockautoformatediting";
import { AdmonitionType, admonitionTypes } from "./admonitioncommand";
function tryParseAdmonitionType(match: RegExpMatchArray) {
if (match.length !== 2) {
return;
}
if ((admonitionTypes as readonly string[]).includes(match[1])) {
return match[1] as AdmonitionType;
}
}
export default class AdmonitionAutoformat extends Plugin {
static get requires() {
@ -13,8 +24,13 @@ export default class AdmonitionAutoformat extends Plugin {
}
const instance = (this as any);
blockAutoformatEditing(this.editor, instance, /^\!\!\[*\! (.+) $/, (match) => {
console.log("Got match ", match);
blockAutoformatEditing(this.editor, instance, /^\!\!\[*\! (.+) $/, ({ match }) => {
const type = tryParseAdmonitionType(match);
if (!type) {
return;
}
this.editor.execute("admonition", { forceValue: type });
});
}
}

View File

@ -17,8 +17,8 @@ import type { DocumentFragment, Element, Position, Range, Schema, Writer } from
* @extends module:core/command~Command
*/
// TODO: Change me.
type AdmonitionType = string;
export const admonitionTypes = [ "note", "tip", "important", "caution", "warning" ] as const;
export type AdmonitionType = typeof admonitionTypes[number];
interface ExecuteOpts {
/**
@ -118,7 +118,7 @@ export default class AdmonitionCommand extends Command {
// In the current implementation, the admonition must be an immediate parent of a block element.
const firstQuote = findQuote( firstBlock );
if (firstQuote?.is("element")) {
return firstQuote.getAttribute("type") as string;
return firstQuote.getAttribute("type") as AdmonitionType;
}
return false;

View File

@ -13,26 +13,26 @@ import { addListToDropdown, createDropdown, ListDropdownButtonDefinition, SplitB
import '../theme/blockquote.css';
import admonitionIcon from '../theme/icons/admonition.svg';
import { Collection } from '@ckeditor/ckeditor5-utils';
import AdmonitionCommand from './admonitioncommand';
import AdmonitionCommand, { AdmonitionType } from './admonitioncommand';
interface AdmonitionDefinition {
title: string;
}
export const ADMONITION_TYPES: Record<string, AdmonitionDefinition> = {
"note": {
export const ADMONITION_TYPES: Record<AdmonitionType, AdmonitionDefinition> = {
note: {
title: "Note"
},
"tip": {
tip: {
title: "Tip"
},
"important": {
important: {
title: "Important"
},
"caution": {
caution: {
title: "Caution"
},
"warning": {
warning: {
title: "Warning"
}
};