Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
Expand Up @@ -566,6 +566,17 @@ it.each([
expect(serializeEditorDoc(editor.state.doc).value).toBe(pasted);
});

it("types outside bold inserted by an editor command", async () => {
await using screen = await mountEditor("");
const { editor } = screen;
await act(async () => {
editor.view.focus();
editor.commands.insertContent({ type: "text", text: "DEV", marks: [{ type: "bold" }] });
});
await userEvent.keyboard("!");
expect(serializeEditorDoc(editor.state.doc).value).toBe("**DEV**!");
});

it.each([
["**DEV**", "**DEV**!"],
["*DEV*", "*DEV*!"],
Expand Down
53 changes: 37 additions & 16 deletions apps/web/src/composer-markdown-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import {
type RichTextMark,
} from "~/composer-rich-text";
import { caretTakesMarksBefore, serializeEditorDoc } from "~/composer-rich-text-doc";
import { isPasteTransaction } from "~/composer-undo-grouping";

// Styled text the selection touches becomes source text with the source mark,
// parsed back once the selection leaves. History steps only replay on the shape
Expand Down Expand Up @@ -265,8 +264,10 @@ function mapRange(mapping: Mapping, { from, to }: TextRange): TextRange {
return { from: mapping.map(from, 1), to: mapping.map(to, -1) };
}

type ContinuedStyleSide = "before" | "after" | null;

/** Shows styled text the selection touches as Markdown, returning the source it added. */
function revealStyledText(tr: Transaction, type: MarkType, typed: boolean, takesBefore: boolean) {
function revealStyledText(tr: Transaction, type: MarkType, styleSide: ContinuedStyleSide) {
const { schema } = tr.doc.type;
const selection = tr.selection;
const ranges = collectStyledRanges(tr.doc).filter(
Expand Down Expand Up @@ -299,7 +300,7 @@ function revealStyledText(tr: Transaction, type: MarkType, typed: boolean, takes
const map = (pos: number) => {
let next = pos;
for (const { at, length, closing } of insertions) {
const inside = typed && selection.empty && (closing ? takesBefore : !takesBefore);
const inside = selection.empty && styleSide === (closing ? "before" : "after");
if (at < pos || (at === pos && (selection instanceof NodeSelection || closing !== inside))) {
next += length;
}
Expand All @@ -311,12 +312,15 @@ function revealStyledText(tr: Transaction, type: MarkType, typed: boolean, takes
}

/** Shows styled text the selection touches as Markdown, and parses source it left. */
function normalizeMarkdownSource(state: EditorState, typed: boolean): Transaction | null {
function normalizeMarkdownSource(
state: EditorState,
styleSide: ContinuedStyleSide,
): Transaction | null {
const type = state.schema.marks[MARKDOWN_SOURCE_MARK];
if (!type) return null;
const tr = state.tr;
collapseMarkdownSource(tr, (region) => touches(state.selection, region));
revealStyledText(tr, type, typed, caretTakesMarksBefore(state));
revealStyledText(tr, type, styleSide);
return tr.docChanged ? tr : null;
}

Expand All @@ -335,7 +339,7 @@ function normalizeDetached(state: EditorState, revealed: TextRange[]): Transacti
if (touches(state.selection, region)) kept.push(region);
else collapseRegion(tr, region, type);
}
const added = revealStyledText(tr, type, false, caretTakesMarksBefore(state));
const added = revealStyledText(tr, type, null);
if (!tr.docChanged) return null;
const shown = [...kept.map((region) => mapRange(tr.mapping, region)), ...added];
return tr.setMeta(markdownSourceKey, shown).setMeta("addToHistory", false);
Expand Down Expand Up @@ -439,6 +443,7 @@ type MarkdownSourceState = {
};

const markdownSourceKey = new PluginKey<MarkdownSourceState>("composer-markdown-source");
const textInputKey = new PluginKey("composer-markdown-text-input");

function markdownSourcePlugin(type: MarkType): Plugin<MarkdownSourceState> {
let view: EditorView | null = null;
Expand Down Expand Up @@ -497,23 +502,39 @@ function markdownSourcePlugin(type: MarkType): Plugin<MarkdownSourceState> {
if (!transactions.some((tr) => tr.docChanged || tr.selectionSet)) return null;
const source = markdownSourceKey.getState(state);
if (source?.detached) return normalizeDetached(state, source.revealed);
// A paste is not typing: the caret ends past the pasted text's closing markers.
const tr = normalizeMarkdownSource(
state,
transactions.some((item) => item.docChanged && !isPasteTransaction(item)),
);
const continueStyle =
state.storedMarks !== null ||
transactions.some(
(tr) => tr.getMeta(textInputKey) === true || tr.getMeta("composition") != null,
);
let styleSide: ContinuedStyleSide = null;
if (continueStyle) styleSide = caretTakesMarksBefore(state) ? "before" : "after";
const tr = normalizeMarkdownSource(state, styleSide);
// With nothing to undo, a recorded rewrite would only add a no-op undo.
if (tr && undoDepth(state) === 0) tr.setMeta("addToHistory", false);
return tr;
},
});
}

/** Keeps source `normalizeDetached` revealed out of what undo, redo and edits see. */
const MarkdownSourceHistoryExtension = Extension.create({
name: "composer-markdown-source-history",
// Runs after undo grouping, so a rebased edit keeps the grouping chosen for it.
/** Marks typed text, and keeps source `normalizeDetached` revealed out of undo, redo and edits. */
const MarkdownSourceEditingExtension = Extension.create({
name: "composer-markdown-source-editing",
// Runs after input rules and undo grouping, which must see the original edit.
priority: 1,
addProseMirrorPlugins() {
return [
new Plugin({
key: textInputKey,
props: {
handleTextInput(view, _from, _to, _text, insert) {
view.dispatch(insert().setMeta(textInputKey, true));
return true;
},
},
}),
];
},
dispatchTransaction({ transaction, next }) {
const { editor } = this;
const revealed = markdownSourceKey.getState(editor.state)?.revealed ?? [];
Expand Down Expand Up @@ -587,7 +608,7 @@ export const ComposerMarkdownSourceExtension = TiptapMark.create({
};
},
addExtensions() {
return [MarkdownSourceHistoryExtension];
return [MarkdownSourceEditingExtension];
},
addProseMirrorPlugins() {
return [markdownSourcePlugin(this.type), replayPlugin];
Expand Down
4 changes: 0 additions & 4 deletions apps/web/src/composer-undo-grouping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ export function markAsClipboardEdit(tr: Transaction, event: "paste" | "cut"): Tr
return tr.setMeta(CLIPBOARD_EDIT_META, event);
}

export function isPasteTransaction(tr: Transaction): boolean {
return tr.getMeta("uiEvent") === "paste" || tr.getMeta(CLIPBOARD_EDIT_META) === "paste";
}

/** Start a replacement undo group, keeping the IME edits together and prior typing separate. */
export function markAsCompositionReplace(tr: Transaction): Transaction {
return closeHistory(tr).setMeta(COMPOSITION_REPLACE_META, true);
Expand Down
Loading