/**
* SetContent.ts
*
* Released under LGPL License.
* Copyright (c) 1999-2018 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
import { Editor } from 'tinymce/core/api/Editor';
import Node from 'tinymce/core/api/html/Node';
import Tools from 'tinymce/core/api/util/Tools';
import Serializer from 'tinymce/core/api/html/Serializer';
import * as FilterNode from '../html/FilterNode';
import { Option, Fun } from '@ephox/katamari';
import Settings from 'tinymce/core/api/Settings';
import EditorFocus from 'tinymce/core/focus/EditorFocus';
import CaretFinder from 'tinymce/core/caret/CaretFinder';
import NodeType from 'tinymce/core/dom/NodeType';
import { Element } from '@ephox/sugar';
import { isWsPreserveElement } from 'tinymce/core/dom/ElementType';
import { HTMLElement } from '@ephox/dom-globals';
const defaultFormat = 'html';
type Content = string | Node;
export interface SetContentArgs {
format?: string;
set?: boolean;
content?: string;
no_events?: boolean;
}
const isTreeNode = (content: any): content is Node => content instanceof Node;
const moveSelection = (editor: Editor) => {
if (EditorFocus.hasFocus(editor)) {
CaretFinder.firstPositionIn(editor.getBody()).each((pos) => {
const node = pos.getNode();
const caretPos = NodeType.isTable(node) ? CaretFinder.firstPositionIn(node).getOr(pos) : pos;
editor.selection.setRng(caretPos.toRange());
});
}
};
const setEditorHtml = (editor: Editor, html: string) => {
editor.dom.setHTML(editor.getBody(), html);
moveSelection(editor);
};
const setContentString = (editor: Editor, body: HTMLElement, content: string, args: SetContentArgs): string => {
let forcedRootBlockName, padd;
// Padd empty content in Gecko and Safari. Commands will otherwise fail on the content
// It will also be impossible to place the caret in the editor unless there is a BR element present
if (content.length === 0 || /^\s+$/.test(content)) {
padd = '
';
// Todo: There is a lot more root elements that need special padding
// so separate this and add all of them at some point.
if (body.nodeName === 'TABLE') {
content = '