UNPKG

1.57 kBJavaScriptView Raw
1/**
2 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4 */
5/**
6 * @module paste-from-office/filters/removemsattributes
7 */
8import { UpcastWriter } from 'ckeditor5/src/engine.js';
9/**
10 * Cleanup MS attributes like styles, attributes and elements.
11 *
12 * @param documentFragment element `data.content` obtained from clipboard.
13 */
14export default function removeMSAttributes(documentFragment) {
15 const elementsToUnwrap = [];
16 const writer = new UpcastWriter(documentFragment.document);
17 for (const { item } of writer.createRangeIn(documentFragment)) {
18 if (!item.is('element')) {
19 continue;
20 }
21 for (const className of item.getClassNames()) {
22 if (/\bmso/gi.exec(className)) {
23 writer.removeClass(className, item);
24 }
25 }
26 for (const styleName of item.getStyleNames()) {
27 if (/\bmso/gi.exec(styleName)) {
28 writer.removeStyle(styleName, item);
29 }
30 }
31 if (item.is('element', 'w:sdt') ||
32 item.is('element', 'w:sdtpr') && item.isEmpty ||
33 item.is('element', 'o:p') && item.isEmpty) {
34 elementsToUnwrap.push(item);
35 }
36 }
37 for (const item of elementsToUnwrap) {
38 const itemParent = item.parent;
39 const childIndex = itemParent.getChildIndex(item);
40 writer.insertChild(childIndex, item.getChildren(), itemParent);
41 writer.remove(item);
42 }
43}