Skip to content

Commit

Permalink
Fix #2575 Entity delimiter cursor moving (#2581)
Browse files Browse the repository at this point in the history
* Preserve reverted selection info in Content Model

* Entity delimiter cursor moving (#2575)

* improve

* Add test

* add test
  • Loading branch information
JiuqingSong authored Apr 24, 2024
1 parent e3cc9e8 commit b69795f
Show file tree
Hide file tree
Showing 11 changed files with 1,468 additions and 90 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,12 @@ export function formatSegmentWithContentModel(

if (isCollapsedSelection) {
const para = segmentAndParagraphs[0][1];
const path = segmentAndParagraphs[0][2];

segmentAndParagraphs = adjustWordSelection(
model,
segmentAndParagraphs[0][0]
).map(x => [x, para]);
).map(x => [x, para, path]);

if (segmentAndParagraphs.length > 1) {
isCollapsedSelection = false;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import {
getAllEntityWrappers,
isBlockEntityContainer,
isEntityElement,
isNodeOfType,
parseEntityFormat,
reuseCachedElement,
} from 'roosterjs-content-model-dom';
import type { Snapshot, EditorCore, KnownEntityItem } from 'roosterjs-content-model-types';

const BlockEntityContainer = '_E_EBlockEntityContainer';

/**
* @internal
*/
Expand Down Expand Up @@ -85,10 +84,6 @@ function tryGetEntityElement(
return result;
}

function isBlockEntityContainer(node: HTMLElement) {
return node.classList.contains(BlockEntityContainer);
}

function tryGetEntityFromContainer(
element: HTMLElement,
entityMap: Record<string, KnownEntityItem>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import {
getSelectedSegmentsAndParagraphs,
isBlockEntityContainer,
isEntityDelimiter,
isNodeOfType,
} from 'roosterjs-content-model-dom';
import type {
ContentModelBlockGroup,
ContentModelEntity,
ContentModelParagraph,
ContentModelSegment,
IEditor,
} from 'roosterjs-content-model-types';

/**
* @internal
*/
export function adjustSelectionAroundEntity(
editor: IEditor,
key: 'ArrowLeft' | 'ArrowRight',
shiftKey: boolean
) {
const selection = editor.isDisposed() ? null : editor.getDOMSelection();

if (!selection || selection.type != 'range') {
return;
}

const { range, isReverted } = selection;
const anchorNode = isReverted ? range.startContainer : range.endContainer;
const offset = isReverted ? range.startOffset : range.endOffset;
const delimiter = isNodeOfType(anchorNode, 'ELEMENT_NODE')
? anchorNode
: anchorNode.parentElement;
const isRtl =
delimiter &&
editor.getDocument().defaultView?.getComputedStyle(delimiter).direction == 'rtl';
const movingBefore = (key == 'ArrowLeft') != !!isRtl;

if (
delimiter &&
((isEntityDelimiter(delimiter, !movingBefore) &&
((movingBefore && offset == 0) || (!movingBefore && offset == 1))) ||
isBlockEntityContainer(delimiter))
) {
editor.formatContentModel(model => {
const allSel = getSelectedSegmentsAndParagraphs(
model,
false /*includingFormatHolder*/,
true /*includingEntity*/
);
const sel = allSel[isReverted ? 0 : allSel.length - 1];
const index = sel?.[1]?.segments.indexOf(sel[0]) ?? -1;

if (sel && sel[1] && index >= 0) {
const [segment, paragraph, path] = sel;
const isShrinking = shiftKey && !range.collapsed && movingBefore != !!isReverted;
const entitySegment = isShrinking
? segment
: paragraph.segments[movingBefore ? index - 1 : index + 1];

const pairedDelimiter = findPairedDelimiter(
entitySegment,
path,
paragraph,
movingBefore
);

if (pairedDelimiter) {
const newRange = getNewRange(
range,
isShrinking,
movingBefore,
pairedDelimiter,
shiftKey
);

editor.setDOMSelection({
type: 'range',
range: newRange,
isReverted: newRange.collapsed ? false : isReverted,
});
}
}

return false;
});
}
}

function getNewRange(
originalRange: Range,
isShrinking: boolean,
movingBefore: boolean,
pairedDelimiter: HTMLElement,
shiftKey: boolean
) {
const newRange = originalRange.cloneRange();

if (isShrinking) {
if (movingBefore) {
newRange.setEndBefore(pairedDelimiter);
} else {
newRange.setStartAfter(pairedDelimiter);
}
} else {
if (movingBefore) {
newRange.setStartBefore(pairedDelimiter);
} else {
newRange.setEndAfter(pairedDelimiter);
}
if (!shiftKey) {
if (movingBefore) {
newRange.setEndBefore(pairedDelimiter);
} else {
newRange.setStartAfter(pairedDelimiter);
}
}
}

return newRange;
}

function findPairedDelimiter(
entitySegment: ContentModelSegment,
path: ContentModelBlockGroup[],
paragraph: ContentModelParagraph,
movingBefore: boolean
) {
let entity: ContentModelEntity | null = null;

if (entitySegment?.segmentType == 'Entity') {
// Inline entity
entity = entitySegment;
} else {
// Block entity
const blocks = path[0].blocks;
const paraIndex = blocks.indexOf(paragraph);
const entityBlock =
paraIndex >= 0 ? blocks[movingBefore ? paraIndex - 1 : paraIndex + 1] : null;

if (entityBlock?.blockType == 'Entity') {
entity = entityBlock;
}
}

const pairedDelimiter = entity
? movingBefore
? entity.wrapper.previousElementSibling
: entity.wrapper.nextElementSibling
: null;

return isNodeOfType(pairedDelimiter, 'ELEMENT_NODE') &&
isEntityDelimiter(pairedDelimiter, movingBefore)
? pairedDelimiter
: null;
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { adjustSelectionAroundEntity } from './adjustSelectionAroundEntity';
import { normalizePos } from '../selection/normalizePos';
import {
addDelimiters,
Expand All @@ -11,6 +12,7 @@ import {
findClosestEntityWrapper,
iterateSelections,
isCharacterValue,
findClosestBlockEntityContainer,
} from 'roosterjs-content-model-dom';
import type {
CompositionEndEvent,
Expand All @@ -29,8 +31,6 @@ const DelimiterSelector = '.' + DelimiterAfter + ',.' + DelimiterBefore;
const ZeroWidthSpace = '\u200B';
const EntityInfoName = '_Entity';
const InlineEntitySelector = 'span.' + EntityInfoName;
const BlockEntityContainer = '_E_EBlockEntityContainer';
const BlockEntityContainerSelector = '.' + BlockEntityContainer;

/**
* @internal exported only for unit test
Expand Down Expand Up @@ -195,56 +195,97 @@ export function handleCompositionEndEvent(editor: IEditor, event: CompositionEnd
export function handleDelimiterKeyDownEvent(editor: IEditor, event: KeyDownEvent) {
const selection = editor.getDOMSelection();

const { rawEvent } = event;
if (!selection || selection.type != 'range') {
return;
}
const isEnter = rawEvent.key === 'Enter';
const helper = editor.getDOMHelper();
if (selection.range.collapsed && (isCharacterValue(rawEvent) || isEnter)) {
const helper = editor.getDOMHelper();
const node = getFocusedElement(selection);
if (node && isEntityDelimiter(node) && helper.isNodeInEditor(node)) {
const blockEntityContainer = node.closest(BlockEntityContainerSelector);
if (blockEntityContainer && helper.isNodeInEditor(blockEntityContainer)) {
const isAfter = node.classList.contains(DelimiterAfter);

if (isAfter) {
selection.range.setStartAfter(blockEntityContainer);
} else {
selection.range.setStartBefore(blockEntityContainer);
}
selection.range.collapse(true /* toStart */);

if (isEnter) {
event.rawEvent.preventDefault();
}
const rawEvent = event.rawEvent;
const range = selection.range;
const key = rawEvent.key;

editor.formatContentModel(handleKeyDownInBlockDelimiter, {
selectionOverride: {
type: 'range',
isReverted: false,
range: selection.range,
},
});
switch (key) {
case 'Enter':
if (range.collapsed) {
handleInputOnDelimiter(editor, range, getFocusedElement(selection), rawEvent);
} else {
if (isEnter) {
event.rawEvent.preventDefault();
editor.formatContentModel(handleEnterInlineEntity);
} else {
editor.takeSnapshot();
editor
.getDocument()
.defaultView?.requestAnimationFrame(() =>
preventTypeInDelimiter(node, editor)
);
const helper = editor.getDOMHelper();
const entity = findClosestEntityWrapper(range.startContainer, helper);

if (
entity &&
isNodeOfType(entity, 'ELEMENT_NODE') &&
helper.isNodeInEditor(entity)
) {
triggerEntityEventOnEnter(editor, entity, rawEvent);
}
}
}
} else if (isEnter) {
const entity = findClosestEntityWrapper(selection.range.startContainer, helper);
if (entity && isNodeOfType(entity, 'ELEMENT_NODE') && helper.isNodeInEditor(entity)) {
triggerEntityEventOnEnter(editor, entity, rawEvent);
break;

case 'ArrowLeft':
case 'ArrowRight':
if (!rawEvent.altKey && !rawEvent.ctrlKey && !rawEvent.metaKey) {
// Handle in async so focus is already moved, this makes us easier to check if we should adjust the selection
editor.getDocument().defaultView?.requestAnimationFrame(() => {
adjustSelectionAroundEntity(editor, key, rawEvent.shiftKey);
});
}
break;

default:
if (isCharacterValue(rawEvent) && range.collapsed) {
handleInputOnDelimiter(editor, range, getFocusedElement(selection), rawEvent);
}

break;
}
}

function handleInputOnDelimiter(
editor: IEditor,
range: Range,
focusedNode: HTMLElement | null,
rawEvent: KeyboardEvent
) {
const helper = editor.getDOMHelper();

if (focusedNode && isEntityDelimiter(focusedNode) && helper.isNodeInEditor(focusedNode)) {
const blockEntityContainer = findClosestBlockEntityContainer(focusedNode, helper);
const isEnter = rawEvent.key === 'Enter';

if (blockEntityContainer && helper.isNodeInEditor(blockEntityContainer)) {
const isAfter = focusedNode.classList.contains(DelimiterAfter);

if (isAfter) {
range.setStartAfter(blockEntityContainer);
} else {
range.setStartBefore(blockEntityContainer);
}

range.collapse(true /* toStart */);

if (isEnter) {
rawEvent.preventDefault();
}

editor.formatContentModel(handleKeyDownInBlockDelimiter, {
selectionOverride: {
type: 'range',
isReverted: false,
range,
},
});
} else {
if (isEnter) {
rawEvent.preventDefault();
editor.formatContentModel(handleEnterInlineEntity);
} else {
editor.takeSnapshot();
editor
.getDocument()
.defaultView?.requestAnimationFrame(() =>
preventTypeInDelimiter(focusedNode, editor)
);
}
}
}
}
Expand Down
Loading

0 comments on commit b69795f

Please sign in to comment.