From be0a0f4e40137c9bed8251c0a0045714a71ff2f3 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 9 Jun 2024 21:19:37 -0400 Subject: [PATCH] fix: Unexpected behavior when changing color of existing highlight --- shared/editor/commands/toggleMark.ts | 35 ++++++++++++++++++++++++++++ shared/editor/marks/Mark.ts | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 shared/editor/commands/toggleMark.ts diff --git a/shared/editor/commands/toggleMark.ts b/shared/editor/commands/toggleMark.ts new file mode 100644 index 000000000..cfc1b5d72 --- /dev/null +++ b/shared/editor/commands/toggleMark.ts @@ -0,0 +1,35 @@ +import { toggleMark as pmToggleMark } from "prosemirror-commands"; +import { MarkType } from "prosemirror-model"; +import { Command } from "prosemirror-state"; +import { Primitive } from "utility-types"; +import { chainTransactions } from "../lib/chainTransactions"; +import { isMarkActive } from "../queries/isMarkActive"; + +/** + * Toggles a mark on the current selection, if the mark is already with + * matching attributes it will remove the mark instead, if the mark is active + * but with different attributes it will update the mark with the new attributes. + * + * @param type - The mark type to toggle. + * @param attrs - The attributes to apply to the mark. + * @returns A prosemirror command. + */ +export function toggleMark( + type: MarkType, + attrs: Record | undefined +): Command { + return (state, dispatch) => { + if (isMarkActive(type, attrs)(state)) { + return pmToggleMark(type)(state, dispatch); + } + + if (isMarkActive(type)(state)) { + return chainTransactions(pmToggleMark(type), pmToggleMark(type, attrs))( + state, + dispatch + ); + } + + return pmToggleMark(type, attrs)(state, dispatch); + }; +} diff --git a/shared/editor/marks/Mark.ts b/shared/editor/marks/Mark.ts index 69ad5dc27..34da95a0b 100644 --- a/shared/editor/marks/Mark.ts +++ b/shared/editor/marks/Mark.ts @@ -1,4 +1,3 @@ -import { toggleMark } from "prosemirror-commands"; import { InputRule } from "prosemirror-inputrules"; import { ParseSpec } from "prosemirror-markdown"; import { @@ -8,6 +7,7 @@ import { Schema, } from "prosemirror-model"; import { Command } from "prosemirror-state"; +import { toggleMark } from "../commands/toggleMark"; import Extension, { CommandFactory } from "../lib/Extension"; import { MarkdownSerializerState } from "../lib/markdown/serializer";