Skip to content

Commit

Permalink
Content Model: Move pending format into editor core (#2188)
Browse files Browse the repository at this point in the history
* Move formatWithContentModel to be a core API

* Content Model: Allow clear cache from formatContentModel

* Content Model: Move pending format into editor core
  • Loading branch information
JiuqingSong authored Nov 7, 2023
1 parent 331b5a3 commit cbba2ce
Show file tree
Hide file tree
Showing 45 changed files with 1,347 additions and 1,143 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
} from '../publicTypes/IContentModelEditor';
import type {
ContentModelDocument,
ContentModelSegmentFormat,
DOMSelection,
DomToModelOption,
ModelToDomOption,
Expand Down Expand Up @@ -113,4 +114,11 @@ export default class ContentModelEditor

core.api.formatContentModel(core, formatter, options);
}

/**
* Get pending format of editor if any, or return null
*/
getPendingFormat(): ContentModelSegmentFormat | null {
return this.getCore().format.pendingFormat?.format ?? null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export const formatContentModel: FormatContentModel = (core, formatter, options)
selection =
core.api.setContentModel(core, model, undefined /*options*/, onNodeCreated) ||
undefined;

handlePendingFormat(core, context, selection);
};

if (context.skipUndoSnapshot) {
Expand Down Expand Up @@ -71,9 +73,13 @@ export const formatContentModel: FormatContentModel = (core, formatter, options)
},
};
core.api.triggerEvent(core, eventData, true /*broadcast*/);
} else if (context.clearModelCache) {
core.cache.cachedModel = undefined;
core.cache.cachedSelection = undefined;
} else {
if (context.clearModelCache) {
core.cache.cachedModel = undefined;
core.cache.cachedSelection = undefined;
}

handlePendingFormat(core, context, core.api.getDOMSelection(core));
}
};

Expand Down Expand Up @@ -152,3 +158,22 @@ function handleImages(core: ContentModelEditorCore, context: FormatWithContentMo
}
}
}

function handlePendingFormat(
core: ContentModelEditorCore,
context: FormatWithContentModelContext,
selection?: DOMSelection | null
) {
const pendingFormat =
context.newPendingFormat == 'preserve'
? core.format.pendingFormat?.format
: context.newPendingFormat;

if (pendingFormat && selection?.type == 'range' && selection.range.collapsed) {
core.format.pendingFormat = {
format: { ...pendingFormat },
posContainer: selection.range.startContainer,
posOffset: selection.range.startOffset,
};
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import applyDefaultFormat from '../../publicApi/format/applyDefaultFormat';
import applyPendingFormat from '../../publicApi/format/applyPendingFormat';
import { canApplyPendingFormat, clearPendingFormat } from '../../modelApi/format/pendingFormat';
import { applyDefaultFormat } from '../../modelApi/format/applyDefaultFormat';
import { applyPendingFormat } from '../../modelApi/format/applyPendingFormat';
import { getObjectKeys } from 'roosterjs-content-model-dom';
import { isCharacterValue } from '../../domUtils/eventUtils';
import { PluginEventType } from 'roosterjs-editor-types';
Expand Down Expand Up @@ -107,7 +106,7 @@ export default class ContentModelFormatPlugin

case PluginEventType.KeyDown:
if (CursorMovingKeys.has(event.rawEvent.key)) {
clearPendingFormat(this.editor);
this.clearPendingFormat();
} else if (
this.hasDefaultFormat &&
(isCharacterValue(event.rawEvent) || event.rawEvent.key == ProcessKey)
Expand All @@ -119,19 +118,45 @@ export default class ContentModelFormatPlugin

case PluginEventType.MouseUp:
case PluginEventType.ContentChanged:
if (!canApplyPendingFormat(this.editor)) {
clearPendingFormat(this.editor);
if (!this.canApplyPendingFormat()) {
this.clearPendingFormat();
}
break;
}
}

private checkAndApplyPendingFormat(data: string | null) {
if (this.editor && data) {
applyPendingFormat(this.editor, data);
clearPendingFormat(this.editor);
if (this.editor && data && this.state.pendingFormat) {
applyPendingFormat(this.editor, data, this.state.pendingFormat.format);
this.clearPendingFormat();
}
}

private clearPendingFormat() {
this.state.pendingFormat = null;
}

/**
* @internal
* Check if this editor can apply pending format
* @param editor The editor to get format from
*/
private canApplyPendingFormat(): boolean {
let result = false;

if (this.state.pendingFormat && this.editor) {
const selection = this.editor.getDOMSelection();
const range =
selection?.type == 'range' && selection.range.collapsed ? selection.range : null;
const { posContainer, posOffset } = this.state.pendingFormat;

if (range && range.startContainer == posContainer && range.startOffset == posOffset) {
result = true;
}
}

return result;
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ function getPluginState(options: ContentModelEditorOptions): ContentModelPluginS
backgroundColor:
format.backgroundColors?.lightModeColor || format.backgroundColor || undefined,
},
pendingFormat: null,
},
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ export { default as setImageBorder } from './publicApi/image/setImageBorder';
export { default as setImageBoxShadow } from './publicApi/image/setImageBoxShadow';
export { default as changeImage } from './publicApi/image/changeImage';
export { default as getFormatState } from './publicApi/format/getFormatState';
export { default as applyPendingFormat } from './publicApi/format/applyPendingFormat';
export { default as clearFormat } from './publicApi/format/clearFormat';
export { default as insertLink } from './publicApi/link/insertLink';
export { default as removeLink } from './publicApi/link/removeLink';
Expand Down Expand Up @@ -130,4 +129,7 @@ export { updateListMetadata } from './domUtils/metadata/updateListMetadata';

export { ContentModelCachePluginState } from './publicTypes/pluginState/ContentModelCachePluginState';
export { ContentModelPluginState } from './publicTypes/pluginState/ContentModelPluginState';
export { ContentModelFormatPluginState } from './publicTypes/pluginState/ContentModelFormatPluginState';
export {
ContentModelFormatPluginState,
PendingFormat,
} from './publicTypes/pluginState/ContentModelFormatPluginState';
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { DeleteResult } from '../../modelApi/edit/utils/DeleteSelectionStep';
import { deleteSelection } from '../../modelApi/edit/deleteSelection';
import { isBlockElement, isNodeOfType, normalizeContentModel } from 'roosterjs-content-model-dom';
import type { ContentModelSegmentFormat } from 'roosterjs-content-model-types';
import type { IContentModelEditor } from '../../publicTypes/IContentModelEditor';

/**
* @internal
* When necessary, set default format as current pending format so it will be applied when Input event is fired
* @param editor The Content Model Editor
* @param defaultFormat The default segment format to apply
*/
export function applyDefaultFormat(
editor: IContentModelEditor,
defaultFormat: ContentModelSegmentFormat
) {
const selection = editor.getDOMSelection();
const range = selection?.type == 'range' ? selection.range : null;
const posContainer = range?.startContainer ?? null;
const posOffset = range?.startOffset ?? null;

if (posContainer) {
let node: Node | null = posContainer;

while (node && editor.contains(node)) {
if (isNodeOfType(node, 'ELEMENT_NODE')) {
if (node.getAttribute?.('style')) {
return;
} else if (isBlockElement(node)) {
break;
}
}

node = node.parentNode;
}
} else {
return;
}

editor.formatContentModel((model, context) => {
const result = deleteSelection(model, [], context);

if (result.deleteResult == DeleteResult.Range) {
normalizeContentModel(model);
editor.addUndoSnapshot();

return true;
} else if (
result.deleteResult == DeleteResult.NotDeleted &&
result.insertPoint &&
posContainer &&
posOffset !== null
) {
const { paragraph, path, marker } = result.insertPoint;
const blocks = path[0].blocks;
const blockCount = blocks.length;
const blockIndex = blocks.indexOf(paragraph);

if (
paragraph.isImplicit &&
paragraph.segments.length == 1 &&
paragraph.segments[0] == marker &&
blockCount > 0 &&
blockIndex == blockCount - 1
) {
// Focus is in the last paragraph which is implicit and there is not other segments.
// This can happen when focus is moved after all other content under current block group.
// We need to check if browser will merge focus into previous paragraph by checking if
// previous block is block. If previous block is paragraph, browser will most likely merge
// the input into previous paragraph, then nothing need to do here. Otherwise we need to
// apply pending format since this input event will start a new real paragraph.
const previousBlock = blocks[blockIndex - 1];

if (previousBlock?.blockType != 'Paragraph') {
context.newPendingFormat = getNewPendingFormat(
editor,
defaultFormat,
marker.format
);
}
} else if (paragraph.segments.every(x => x.segmentType != 'Text')) {
context.newPendingFormat = getNewPendingFormat(
editor,
defaultFormat,
marker.format
);
}
}

// We didn't do any change but just apply default format to pending format, so no need to write back
return false;
});
}

function getNewPendingFormat(
editor: IContentModelEditor,
defaultFormat: ContentModelSegmentFormat,
markerFormat: ContentModelSegmentFormat
): ContentModelSegmentFormat {
return {
...defaultFormat,
...editor.getPendingFormat(),
...markerFormat,
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { iterateSelections } from '../../modelApi/selection/iterateSelections';
import type { ContentModelSegmentFormat } from 'roosterjs-content-model-types';
import type { IContentModelEditor } from '../../publicTypes/IContentModelEditor';
import {
createText,
normalizeContentModel,
setParagraphNotImplicit,
} from 'roosterjs-content-model-dom';

const ANSI_SPACE = '\u0020';
const NON_BREAK_SPACE = '\u00A0';

/**
* @internal
* Apply pending format to the text user just input
* @param editor The editor to get format from
* @param data The text user just input
*/
export function applyPendingFormat(
editor: IContentModelEditor,
data: string,
format: ContentModelSegmentFormat
) {
let isChanged = false;

editor.formatContentModel(
(model, context) => {
iterateSelections(model, (_, __, block, segments) => {
if (
block?.blockType == 'Paragraph' &&
segments?.length == 1 &&
segments[0].segmentType == 'SelectionMarker'
) {
const marker = segments[0];
const index = block.segments.indexOf(marker);
const previousSegment = block.segments[index - 1];

if (previousSegment?.segmentType == 'Text') {
const text = previousSegment.text;
const subStr = text.substr(-data.length, data.length);

// For space, there can be &#32 (space) or &#160 ( ), we treat them as the same
if (subStr == data || (data == ANSI_SPACE && subStr == NON_BREAK_SPACE)) {
marker.format = { ...format };
previousSegment.text = text.substring(0, text.length - data.length);

const newText = createText(
data == ANSI_SPACE ? NON_BREAK_SPACE : data,
{
...previousSegment.format,
...format,
}
);

block.segments.splice(index, 0, newText);
setParagraphNotImplicit(block);
isChanged = true;
}
}
}
return true;
});

if (isChanged) {
normalizeContentModel(model);
context.skipUndoSnapshot = true;
}

return isChanged;
},
{
apiName: 'applyPendingFormat',
}
);
}
Loading

0 comments on commit cbba2ce

Please sign in to comment.