/
setBackgroundColor.ts
44 lines (39 loc) · 1.6 KB
/
setBackgroundColor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { createSelectionMarker, setSelection } from 'roosterjs-content-model-dom';
import { formatSegmentWithContentModel } from '../utils/formatSegmentWithContentModel';
import type { ContentModelParagraph, IEditor } from 'roosterjs-content-model-types';
/**
* Set background color
* @param editor The editor to operate on
* @param backgroundColor The color to set. Pass null to remove existing color.
*/
export function setBackgroundColor(editor: IEditor, backgroundColor: string | null) {
editor.focus();
let lastParagraph: ContentModelParagraph | null = null;
let lastSegmentIndex: number = -1;
formatSegmentWithContentModel(
editor,
'setBackgroundColor',
(format, _, segment, paragraph) => {
if (backgroundColor === null) {
delete format.backgroundColor;
} else {
format.backgroundColor = backgroundColor;
}
if (segment && paragraph && segment.segmentType != 'SelectionMarker') {
lastParagraph = paragraph;
lastSegmentIndex = lastParagraph.segments.indexOf(segment);
}
},
undefined /*segmentHasStyleCallback*/,
undefined /*includingFormatHolder*/,
model => {
if (lastParagraph && lastSegmentIndex >= 0) {
const marker = createSelectionMarker(
lastParagraph.segments[lastSegmentIndex]?.format
);
lastParagraph.segments.splice(lastSegmentIndex + 1, 0, marker);
setSelection(model, marker, marker);
}
}
);
}