From e0fa25f8bc1b54dbed000d8549b15c944d0702b7 Mon Sep 17 00:00:00 2001
From: Ved Thakar <111605341+Vedthakar@users.noreply.github.com>
Date: Wed, 21 Oct 2026 17:30:23 -0400
Subject: [PATCH] [lexical-extension][lexical-playground] Bug Fix: Select a
horizontal rule when clicking the empty space above or below it
A click in the gap above or below a horizontal rule (its margins) lands
on the parent element, so the CLICK_COMMAND handler, which only checked
for the
itself, ignored it. Where the browser then puts the caret
differs between Chromium and Firefox, so the handler now hit tests the
click against each child rule's box extended by its margins and selects
the nearest one, matching the arrow keys. Shift-click still extends the
range, and a click below a rule that is the last block still inserts a
paragraph.
Selecting the rule from the click handler builds on #8967 by @LeSingh1.
Signed-off-by: Ved Thakar <111605341+Vedthakar@users.noreply.github.com>
Co-authored-by: Ved Thakar <111605341+Vedthakar@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5
---
.../src/HorizontalRuleExtension.ts | 61 ++++++++
.../__tests__/e2e/HorizontalRule.spec.mjs | 147 +++++++++++++++++-
2 files changed, 204 insertions(+), 4 deletions(-)
diff --git a/packages/lexical-extension/src/HorizontalRuleExtension.ts b/packages/lexical-extension/src/HorizontalRuleExtension.ts
index b170c8d1b4a3..6d4faf5b1742 100644
--- a/packages/lexical-extension/src/HorizontalRuleExtension.ts
+++ b/packages/lexical-extension/src/HorizontalRuleExtension.ts
@@ -13,6 +13,7 @@ import {
$getDocument,
$getNodeFromDOMNode,
$getSelection,
+ $isElementNode,
$isNodeSelection,
$isRangeSelection,
$setSelection,
@@ -28,6 +29,7 @@ import {
type EditorConfig,
isDOMNode,
type LexicalCommand,
+ type LexicalEditor,
type LexicalNode,
mergeRegister,
type NodeKey,
@@ -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 `
`, 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)
+ ? $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();
+ 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.
@@ -186,6 +237,16 @@ export const HorizontalRuleExtension = defineExtension({
return true;
}
}
+ // A shift-click in the gap extends the selection as usual.
+ const ruleAtClick = event.shiftKey
+ ? null
+ : $getHorizontalRuleAtClick(editor, event);
+ if (ruleAtClick !== null) {
+ const nodeSelection = $createNodeSelection();
+ nodeSelection.add(ruleAtClick.getKey());
+ $setSelection(nodeSelection);
+ return true;
+ }
return false;
},
COMMAND_PRIORITY_LOW,
diff --git a/packages/lexical-playground/__tests__/e2e/HorizontalRule.spec.mjs b/packages/lexical-playground/__tests__/e2e/HorizontalRule.spec.mjs
index d1fd332cff67..2747dfbf1fe9 100644
--- a/packages/lexical-playground/__tests__/e2e/HorizontalRule.spec.mjs
+++ b/packages/lexical-playground/__tests__/e2e/HorizontalRule.spec.mjs
@@ -775,6 +775,132 @@ 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.
+ await expect
+ .poll(() =>
+ getPageOrFrame(page).evaluate(() => {
+ const sel = window.lexicalEditor.getEditorState()._selection;
+ return sel !== null && 'anchor' in sel && !sel.isCollapsed();
+ }),
+ )
+ .toBe(true);
+ });
+
+ 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,
}) => {
@@ -818,11 +944,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;
}
@@ -833,10 +961,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 ({