-
Notifications
You must be signed in to change notification settings - Fork 42
fix: correct toggle logic for partial selection #840
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
makhnatkin
wants to merge
6
commits into
main
Choose a base branch
from
fix/toggle-mark
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b1765cc
fix(marks): apply mark to whole selection when not fully covered
makhnatkin 27f1724
test: cover toggle-mark fix risks + pin markup colorify limitation
makhnatkin 1c203a6
fix: align markdown mark shortcuts with toggle actions
makhnatkin da338b3
refactor: tighten inline toggle behavior
makhnatkin 91576cb
Merge branch 'main' into fix/toggle-mark
makhnatkin feee8f5
fix: restore color toggle semantics
makhnatkin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
236 changes: 236 additions & 0 deletions
236
packages/editor/src/extensions/yfm/Color/Color.action.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,236 @@ | ||
| import type {MarkType} from 'prosemirror-model'; | ||
| import {EditorState, TextSelection} from 'prosemirror-state'; | ||
|
|
||
| import {ExtensionsManager} from '../../../core'; | ||
| import type {ActionSpec} from '../../../core/types/actions'; | ||
| import {BaseSchemaSpecs} from '../../base/specs'; | ||
|
|
||
| import {colorMarkName, colorType} from './ColorSpecs'; | ||
| import {colorAction} from './const'; | ||
|
|
||
| import {Color} from './index'; | ||
|
|
||
| const {schema, rawActions} = new ExtensionsManager({ | ||
| extensions: (builder) => builder.use(BaseSchemaSpecs, {}).use(Color), | ||
| }).build(); | ||
|
|
||
| const action: ActionSpec = rawActions[colorAction]; | ||
| const color: MarkType = colorType(schema); | ||
|
|
||
| // Both isActive and meta are populated by Color extension — narrow the optional | ||
| // signatures once so the tests don't need non-null assertions everywhere. | ||
| const isActive = action.isActive as (state: EditorState) => boolean; | ||
| const meta = action.meta as (state: EditorState) => string | undefined; | ||
|
|
||
| type Segment = string | {text: string; color: string}; | ||
|
|
||
| /** | ||
| * Build an EditorState whose first paragraph contains the given segments. | ||
| * `from` / `to` are 0-based offsets within the paragraph text. | ||
| */ | ||
| function makeState(segments: Segment[], from: number, to: number): EditorState { | ||
| const paragraph = schema.nodes.paragraph; | ||
| const nodes = segments.map((seg) => { | ||
| if (typeof seg === 'string') return schema.text(seg); | ||
| return schema.text(seg.text, [color.create({[colorMarkName]: seg.color})]); | ||
| }); | ||
| const doc = schema.node('doc', null, [paragraph.create(null, nodes)]); | ||
| // PM positions: 0=before doc, 1=start of paragraph content | ||
| const sel = TextSelection.create(doc, from + 1, to + 1); | ||
| return EditorState.create({doc, selection: sel}); | ||
| } | ||
|
|
||
| /** Run the action on `state`, return the resulting state. */ | ||
| function run(state: EditorState, attrs?: {color?: string}): EditorState { | ||
| const ref = {state}; | ||
| action.run( | ||
| ref.state, | ||
| (tr) => { | ||
| ref.state = ref.state.apply(tr); | ||
| }, | ||
| undefined as never, | ||
| attrs, | ||
| ); | ||
| return ref.state; | ||
| } | ||
|
|
||
| /** Collect color-mark values for every text node in the doc, in order. */ | ||
| function colorOfTextNodes(state: EditorState): Array<string | undefined> { | ||
| const colors: Array<string | undefined> = []; | ||
| state.doc.descendants((node) => { | ||
| if (node.isText) { | ||
| const m = color.isInSet(node.marks); | ||
| colors.push(m?.attrs[colorMarkName]); | ||
| } | ||
| return true; | ||
| }); | ||
| return colors; | ||
| } | ||
|
|
||
| /** True if any text node has more than one color mark (sanity for `excludes`). */ | ||
| function hasNestedColorMarks(state: EditorState): boolean { | ||
| let nested = false; | ||
| state.doc.descendants((node) => { | ||
| if (node.isText) { | ||
| const colorMarksOnNode = node.marks.filter((m) => m.type === color); | ||
| if (colorMarksOnNode.length > 1) nested = true; | ||
| } | ||
| return true; | ||
| }); | ||
| return nested; | ||
| } | ||
|
|
||
| function storedColor(state: EditorState): string | undefined { | ||
| const m = state.storedMarks ? color.isInSet(state.storedMarks) : undefined; | ||
| return m?.attrs[colorMarkName]; | ||
| } | ||
|
|
||
| // ─── Risk 4: PM `excludes` default behaviour for parameterised marks ───────── | ||
|
|
||
| describe('Color action — default `excludes` behaviour (risk 4)', () => { | ||
| it('C1: addMark replaces existing color mark over the whole paragraph', () => { | ||
| // "ABC" all blue → run({color: 'red'}) → all red, no blue, no nesting | ||
| const state = makeState([{text: 'ABC', color: 'blue'}], 0, 3); | ||
| const next = run(state, {color: 'red'}); | ||
| expect(colorOfTextNodes(next)).toEqual(['red']); | ||
| expect(hasNestedColorMarks(next)).toBe(false); | ||
| }); | ||
|
|
||
| it('C2: addMark over [blue, plain, blue] makes the whole range red', () => { | ||
| const state = makeState( | ||
| [{text: 'AB', color: 'blue'}, 'CD', {text: 'EF', color: 'blue'}], | ||
| 0, | ||
| 6, | ||
| ); | ||
| const next = run(state, {color: 'red'}); | ||
| // ranges may merge into fewer text nodes; assert every node is red. | ||
| const colors = colorOfTextNodes(next); | ||
| expect(colors.every((c) => c === 'red')).toBe(true); | ||
| expect(hasNestedColorMarks(next)).toBe(false); | ||
| }); | ||
| }); | ||
|
|
||
| // ─── Risk 1: wysiwyg toggle behaviour ──────────────────────────────────────── | ||
|
|
||
| describe('Color action — toggle behaviour (risk 1)', () => { | ||
| it('A1: empty selection, no stored marks → adds a stored color mark', () => { | ||
| const state = makeState(['hello'], 2, 2); | ||
| const next = run(state, {color: 'red'}); | ||
| expect(storedColor(next)).toBe('red'); | ||
| // Document content unchanged. | ||
| expect(next.doc.eq(state.doc)).toBe(true); | ||
| }); | ||
|
|
||
| it('A2: empty selection with same stored color → toggles stored mark off', () => { | ||
| const base = makeState(['hello'], 2, 2); | ||
| const withStored = base.apply( | ||
| base.tr.addStoredMark(color.create({[colorMarkName]: 'red'})), | ||
| ); | ||
| const next = run(withStored, {color: 'red'}); | ||
| expect(storedColor(next)).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('A3: empty selection with different stored color → replaces stored mark', () => { | ||
| const base = makeState(['hello'], 2, 2); | ||
| const withStored = base.apply( | ||
| base.tr.addStoredMark(color.create({[colorMarkName]: 'blue'})), | ||
| ); | ||
| const next = run(withStored, {color: 'red'}); | ||
| expect(storedColor(next)).toBe('red'); | ||
| }); | ||
|
|
||
| it('A4: range fully red + click red → mark removed', () => { | ||
| const state = makeState([{text: 'ABC', color: 'red'}], 0, 3); | ||
| const next = run(state, {color: 'red'}); | ||
| expect(colorOfTextNodes(next).every((c) => c === undefined)).toBe(true); | ||
| }); | ||
|
|
||
| it('A5: range [red, plain] + click red → all red (the headline fix)', () => { | ||
| const state = makeState([{text: 'AB', color: 'red'}, 'CD'], 0, 4); | ||
| const next = run(state, {color: 'red'}); | ||
| expect(colorOfTextNodes(next).every((c) => c === 'red')).toBe(true); | ||
| }); | ||
|
|
||
| it('A6: range fully red + run({color: ""}) → mark removed', () => { | ||
| const state = makeState([{text: 'ABC', color: 'red'}], 0, 3); | ||
| const next = run(state, {color: ''}); | ||
| expect(colorOfTextNodes(next).every((c) => c === undefined)).toBe(true); | ||
| }); | ||
|
|
||
| it('A7: range fully blue + click red → all red, no blue', () => { | ||
| const state = makeState([{text: 'ABC', color: 'blue'}], 0, 3); | ||
| const next = run(state, {color: 'red'}); | ||
| expect(colorOfTextNodes(next).every((c) => c === 'red')).toBe(true); | ||
| }); | ||
|
|
||
| it('A8: range across two paragraphs + mixed coverage → all red', () => { | ||
| const paragraph = schema.nodes.paragraph; | ||
| const doc = schema.node('doc', null, [ | ||
| paragraph.create(null, [ | ||
| schema.text('AB', [color.create({[colorMarkName]: 'red'})]), | ||
| schema.text('CD'), | ||
| ]), | ||
| paragraph.create(null, [ | ||
| schema.text('EF'), | ||
| schema.text('GH', [color.create({[colorMarkName]: 'blue'})]), | ||
| ]), | ||
| ]); | ||
| // Select from inside p1 to inside p2. | ||
| const sel = TextSelection.create(doc, 2, 11); | ||
| const state = EditorState.create({doc, selection: sel}); | ||
| const next = run(state, {color: 'red'}); | ||
|
|
||
| // Walk the resulting doc and assert every text node *inside* the original | ||
| // selection range is red. We accept that text nodes outside the selection | ||
| // keep their original mark. | ||
| let allRedInRange = true; | ||
| next.doc.nodesBetween(2, next.tr.mapping.map(11), (node, pos) => { | ||
| if (!node.isText) return true; | ||
| const c = color.isInSet(node.marks)?.attrs[colorMarkName]; | ||
| // Node entirely inside selection must be red. | ||
| const nodeStart = pos; | ||
| const nodeEnd = pos + node.nodeSize; | ||
| if (nodeStart >= 2 && nodeEnd <= 11 && c !== 'red') allRedInRange = false; | ||
| return true; | ||
| }); | ||
| expect(allRedInRange).toBe(true); | ||
| }); | ||
| }); | ||
|
|
||
| // ─── Risk 2: isActive + meta semantics ─────────────────────────────────────── | ||
|
|
||
| describe('Color action — isActive / meta (risk 2)', () => { | ||
| it('D1: cursor inside red word, no stored marks → isActive is true', () => { | ||
| // "ABC" all red, cursor between A and B. | ||
| const state = makeState([{text: 'ABC', color: 'red'}], 1, 1); | ||
| expect(isActive(state)).toBe(true); | ||
| }); | ||
|
|
||
| it('D2: range fully red → isActive reflects current cursor-style semantics', () => { | ||
| // After PR: isActive reads `storedMarks ?? $to.marks()` — with TextSelection | ||
| // both anchor and head live inside the colored text, so $to.marks() includes | ||
| // the red mark. Pinning the actual return value as a regression guard. | ||
| const state = makeState([{text: 'ABC', color: 'red'}], 0, 3); | ||
| expect(isActive(state)).toBe(true); | ||
| }); | ||
|
|
||
| it('E1: empty selection → run({red}) → meta returns "red" (via storedMarks)', () => { | ||
| const state = makeState(['hello'], 2, 2); | ||
| const next = run(state, {color: 'red'}); | ||
| expect(meta(next)).toBe('red'); | ||
| }); | ||
|
|
||
| it('E2: cursor inside red, no storedMarks → meta returns "red" (via $to)', () => { | ||
| const state = makeState([{text: 'ABC', color: 'red'}], 1, 1); | ||
| expect(meta(state)).toBe('red'); | ||
| }); | ||
|
|
||
| it('E3: after toggle-off (A2) → meta returns undefined', () => { | ||
| const base = makeState(['hello'], 2, 2); | ||
| const withStored = base.apply( | ||
| base.tr.addStoredMark(color.create({[colorMarkName]: 'red'})), | ||
| ); | ||
| const next = run(withStored, {color: 'red'}); | ||
| expect(meta(next)).toBeUndefined(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue (complexity): Consider extracting cursor and range color‑toggling logic into separate helpers and adding a small helper for effective marks to flatten
runand reduce duplication.You can keep the new behaviour but make it easier to reason about by extracting a few small helpers and reducing nesting in
run.1. Split cursor vs range handling
The
runbody is doing both cursor and range logic inline. Pulling these into helpers makesruna simple dispatcher and flattens the nesting:Then
runbecomes:This keeps all current behaviour but makes each branch smaller and single‑purpose.
2. De‑duplicate effective marks access
You currently repeat
state.storedMarks ?? state.selection.$to.marks()(and a variant in the cursor branch). A small helper makes the intent explicit and cuts duplication:Use it in
isActiveandmeta:And in the cursor helper above (
getEffectiveMarks(state, $cursor)).These changes keep the richer selection/cursor semantics while making the flow flatter and reducing cognitive load.