Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/hr-gap-click-selects-rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@lexical/extension': patch
---

[fix] A click in the empty space above or below a horizontal rule selects the rule

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: CONTRIBUTING.md ("Changesets") asks a fix that changes editing behavior to add a Verify: paragraph, so it lists under Behavior changes. Clicks between two adjacent rules no longer leave a caret between them, which is worth flagging:

Suggested change
[fix] A click in the empty space above or below a horizontal rule selects the rule
[fix] A click in the empty space above or below a horizontal rule selects the rule
Verify: clicks in the space above or below a horizontal rule, including between two adjacent rules, now select the rule instead of placing a caret; check tests that click beside a rule.

66 changes: 66 additions & 0 deletions packages/lexical-extension/src/HorizontalRuleExtension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
$getDocument,
$getNodeFromDOMNode,
$getSelection,
$isElementNode,
$isNodeSelection,
$isRangeSelection,
$setSelection,
Expand All @@ -28,6 +29,7 @@ import {
type EditorConfig,
isDOMNode,
type LexicalCommand,
type LexicalEditor,
type LexicalNode,
mergeRegister,
type NodeKey,
Expand Down Expand Up @@ -134,6 +136,55 @@ function $toggleNodeSelection(
}
}

/**
* A click in the empty space above or below a horizontal rule (its margins)
* lands on the parent element rather than the `<hr>`, and where the browser
* then puts the caret differs: before the rule, after it, or at the start of
* the next block. Hit test the click against the rules' own geometry instead,
* so the gap on either side selects the rule, as the arrow keys do. Between
* two rules whose margins overlap, the nearer rule wins.
*/
function $getHorizontalRuleAtClick(
editor: LexicalEditor,
event: MouseEvent,
): null | HorizontalRuleNode {
const parent = isDOMNode(event.target)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: AGENTS.md's realm-safety table asks for getComposedEventTarget(event) instead of event.target (lint can't enforce it). It works today because the click listener is on the root inside the same shadow tree, so this is a consistency nit, same as the existing branch at line 233.

? $getNodeFromDOMNode(event.target)
: null;
if (!$isElementNode(parent)) {
return null;
}
const {clientX, clientY} = event;
let nearest: null | HorizontalRuleNode = null;
let nearestDistance = Infinity;
for (const child of parent.getChildren()) {
if (!$isHorizontalRuleNode(child)) {
continue;
}
const dom = editor.getElementByKey(child.getKey());
const view = dom && dom.ownerDocument.defaultView;
if (!dom || !view) {
continue;
}
const rect = dom.getBoundingClientRect();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: a rule that isn't laid out has an all-zero rect, so a click at (0, 0) passes the bounds check. A user can't click there, but jsdom reports every rect as zero and element.click() sends (0, 0): with this extension, rootElement.click() in a jsdom test now selects the first rule instead of keeping the caret. Skipping empty rects avoids that:

Suggested change
const rect = dom.getBoundingClientRect();
const rect = dom.getBoundingClientRect();
if (rect.width === 0 && rect.height === 0) {
// Not laid out (display: none, or jsdom): nothing to click beside.
continue;
}

const style = view.getComputedStyle(dom);
if (
clientX < rect.left - parseFloat(style.marginLeft) ||
clientX > rect.right + parseFloat(style.marginRight) ||
clientY < rect.top - parseFloat(style.marginTop) ||
clientY > rect.bottom + parseFloat(style.marginBottom)
) {
continue;
}
const distance = Math.max(rect.top - clientY, clientY - rect.bottom, 0);
if (distance < nearestDistance) {
nearest = child;
nearestDistance = distance;
}
}
return nearest;
}

/**
* An extension for HorizontalRuleNode that provides an implementation that
* works without any React dependency.
Expand Down Expand Up @@ -186,6 +237,21 @@ export const HorizontalRuleExtension = defineExtension({
return true;
}
}
// A shift-click in the gap extends the selection as usual, and a
// drag released there keeps the range it selected: the browser
// fires its click on the common ancestor, at the release point.
const selection = $getSelection();
const ruleAtClick =
event.shiftKey ||
($isRangeSelection(selection) && !selection.isCollapsed())
? null
: $getHorizontalRuleAtClick(editor, event);
Comment on lines +243 to +248

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, worth a device check: core cancels the mousedown only for taps on a decorator, because a NodeSelection leaves no DOM caret and iOS then scrolls to the top of the editor when the keyboard opens (#9112, see the comments above onMouseDownIOS and in onClick in packages/lexical/src/LexicalEvents.ts). A tap in the gap targets the parent element, so it focuses the editor and places a caret, and this branch then swaps it for a NodeSelection. If a gap tap on iOS makes the page jump in a long document, limiting the hit test to mouse clicks would keep taps on the caret they placed.

if (ruleAtClick !== null) {
const nodeSelection = $createNodeSelection();
nodeSelection.add(ruleAtClick.getKey());
$setSelection(nodeSelection);
return true;
}
return false;
},
COMMAND_PRIORITY_LOW,
Expand Down
178 changes: 174 additions & 4 deletions packages/lexical-playground/__tests__/e2e/HorizontalRule.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,163 @@ test.describe('HorizontalRule', () => {
expect(isNodeSel).toBe(true);
});

test.describe('Clicking the empty space beside a horizontal rule (#7758)', () => {
const getSelectionState = page =>
getPageOrFrame(page).evaluate(() => {
const state = window.lexicalEditor.getEditorState();
const sel = state._selection;
if (sel === null) {
return null;
}
if ('anchor' in sel) {
return {anchorType: sel.anchor.type, type: 'range'};
}
return {
type: 'node',
types: Array.from(sel._nodes).map(key =>
state._nodeMap.get(key).getType(),
),
};
});

// The middle of the gap between the rule and the block above or below
// it, or of the rule's bottom margin when nothing follows it.
const getGapPoint = (page, side) =>
getPageOrFrame(page).evaluate(gapSide => {
const hr = document.querySelector('[contenteditable="true"] hr');
const rect = hr.getBoundingClientRect();
const sibling =
gapSide === 'above'
? hr.previousElementSibling
: hr.nextElementSibling;
let y;
if (gapSide === 'above') {
y = (sibling.getBoundingClientRect().bottom + rect.top) / 2;
} else if (sibling !== null) {
y = (rect.bottom + sibling.getBoundingClientRect().top) / 2;
} else {
y = rect.bottom + parseFloat(getComputedStyle(hr).marginBottom) / 2;
}
return {x: Math.round(rect.left + rect.width / 2), y: Math.round(y)};
}, side);

const expectRuleSelected = async page => {
await expect
.poll(() => getSelectionState(page))
.toEqual({type: 'node', types: ['horizontalrule']});
await expect(getPageOrFrame(page).locator('hr')).toHaveClass(
/PlaygroundEditorTheme__hrSelected/,
);
};

test.beforeEach(async ({page}) => {
await focusEditor(page);
await page.keyboard.type('Above');
await selectFromInsertDropdown(page, '.horizontal-rule');
await waitForSelector(page, 'hr');
await page.keyboard.type('Below');
});

test('Clicking the gap above the rule selects it', async ({page}) => {
await click(page, 'p:has-text("Below")');
const {x, y} = await getGapPoint(page, 'above');
await page.mouse.click(x, y);
await expectRuleSelected(page);
});

test('Clicking the gap below the rule selects it', async ({page}) => {
await click(page, 'p:has-text("Above")');
const {x, y} = await getGapPoint(page, 'below');
await page.mouse.click(x, y);
await expectRuleSelected(page);
});

test('Clicking text next to the rule places a caret', async ({page}) => {
await click(page, 'p:has-text("Above")');
await expect
.poll(() => getSelectionState(page))
.toEqual({anchorType: 'text', type: 'range'});
await expect(getPageOrFrame(page).locator('hr')).not.toHaveClass(
/PlaygroundEditorTheme__hrSelected/,
);
});

test('Shift-clicking the gap extends the range selection', async ({
page,
}) => {
await click(page, 'p:has-text("Above")');
const {x, y} = await getGapPoint(page, 'below');
await page.keyboard.down('Shift');
await page.mouse.click(x, y);
await page.keyboard.up('Shift');
// The range now spans the rule instead of being replaced by a
// NodeSelection of it.
Comment on lines +867 to +868

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: the assertion below now checks only for a non-collapsed range (in Firefox the range ends before the rule), so this comment no longer matches it:

Suggested change
// The range now spans the rule instead of being replaced by a
// NodeSelection of it.
// The range is kept instead of being replaced by a NodeSelection of
// the rule (Firefox ends it before the rule, Chromium after it).

await expect
.poll(() =>
getPageOrFrame(page).evaluate(() => {
const sel = window.lexicalEditor.getEditorState()._selection;
return sel !== null && 'anchor' in sel && !sel.isCollapsed();
}),
)
.toBe(true);
Comment thread
rootnode-bot[bot] marked this conversation as resolved.
Resolved
});

test('A drag released in the gap keeps the dragged selection', async ({
page,
}) => {
const start = await getPageOrFrame(page).evaluate(() => {
const rect = document
.querySelector('[contenteditable="true"] p')
.getBoundingClientRect();
return {x: rect.left + 1, y: rect.top + rect.height / 2};
});
const {x, y} = await getGapPoint(page, 'above');
await page.mouse.move(start.x, start.y);
await page.mouse.down();
await page.mouse.move(x, y, {steps: 5});
await page.mouse.up();
// The dragged range survives, instead of being replaced by a
// NodeSelection of the rule.
await expect
.poll(() =>
getPageOrFrame(page).evaluate(() => {
const sel = window.lexicalEditor.getEditorState()._selection;
return (
sel !== null &&
'anchor' in sel &&
sel.anchor.type === 'text' &&
!sel.isCollapsed()
);
}),
)
.toBe(true);
});
Comment thread
rootnode-bot[bot] marked this conversation as resolved.
Resolved

test('Clicking below a rule that is the last block inserts a paragraph', async ({
page,
}) => {
await getPageOrFrame(page).evaluate(() => {
const editor = window.lexicalEditor;
editor.update(
() => {
const root = editor.getEditorState()._nodeMap.get('root');
root.getLastChild().remove();
root.getFirstChild().selectEnd();
},
{discrete: true},
);
});
const {x, y} = await getGapPoint(page, 'below');
await page.mouse.click(x, y);
await expect(
getPageOrFrame(page).locator('[contenteditable="true"] hr + p'),
).toHaveCount(1);
await expect
.poll(() => getSelectionState(page))
.toEqual({anchorType: 'element', type: 'range'});
});
});

test('Clicking between consecutive block decorators creates selection (#6775)', async ({
page,
}) => {
Expand Down Expand Up @@ -818,11 +975,13 @@ test.describe('HorizontalRule', () => {
await page.mouse.click(clickPos.x, clickPos.y);

// Without the fix, Firefox leaves selection as null (rangeCount === 0).
// The fix computes the correct child offset from click coordinates.
// The fix computes the correct child offset from click coordinates. A
// click in the rules' margins now selects the nearer rule (#7758).
await expect
.poll(() =>
getPageOrFrame(page).evaluate(() => {
const sel = window.lexicalEditor.getEditorState()._selection;
const state = window.lexicalEditor.getEditorState();
const sel = state._selection;
if (sel === null) {
return null;
}
Expand All @@ -833,10 +992,21 @@ test.describe('HorizontalRule', () => {
type: 'range',
};
}
return {type: 'node'};
return {
type: 'node',
types: Array.from(sel._nodes).map(key =>
state._nodeMap.get(key).getType(),
),
};
}),
)
.toEqual({anchorKey: 'root', anchorType: 'element', type: 'range'});
.toEqual({type: 'node', types: ['horizontalrule']});

// Selecting a rule still lets the user add a paragraph between them.
await page.keyboard.press('Enter');
await expect(
getPageOrFrame(page).locator('[contenteditable="true"] hr + p + hr'),
).toHaveCount(1);
});

test('ArrowDown from block cursor between shadow root and decorator selects the decorator', async ({
Expand Down
Loading