\xA0
').append(targetClone); newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild); newRange.setEndAfter(targetClone); } else { $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp); newRange.setStart($realSelectionContainer[0].firstChild, 1); newRange.setEnd($realSelectionContainer[0].lastChild, 0); } $realSelectionContainer.css({ top: dom2.getPos(node, editor.getBody()).y }); $realSelectionContainer[0].focus(); var sel = selection.getSel(); sel.removeAllRanges(); sel.addRange(newRange); return newRange; }; var selectElement = function(elm) { var targetClone = elm.cloneNode(true); var e2 = editor.fire("ObjectSelected", { target: elm, targetClone }); if (e2.isDefaultPrevented()) { return null; } var range3 = setupOffscreenSelection(elm, e2.targetClone, targetClone); var nodeElm = SugarElement.fromDom(elm); each$k(descendants(SugarElement.fromDom(editor.getBody()), "*[data-mce-selected]"), function(elm2) { if (!eq2(nodeElm, elm2)) { remove$6(elm2, elementSelectionAttr); } }); if (!dom2.getAttrib(elm, elementSelectionAttr)) { elm.setAttribute(elementSelectionAttr, "1"); } selectedElement = elm; hideFakeCaret(); return range3; }; var setElementSelection = function(range3, forward) { if (!range3) { return null; } if (range3.collapsed) { if (!isRangeInCaretContainer(range3)) { var dir2 = forward ? 1 : -1; var caretPosition = getNormalizedRangeEndPoint(dir2, rootNode, range3); var beforeNode = caretPosition.getNode(!forward); if (isFakeCaretTarget(beforeNode)) { return showCaret2(dir2, beforeNode, forward ? !caretPosition.isAtEnd() : false, false); } var afterNode = caretPosition.getNode(forward); if (isFakeCaretTarget(afterNode)) { return showCaret2(dir2, afterNode, forward ? false : !caretPosition.isAtEnd(), false); } } return null; } var startContainer = range3.startContainer; var startOffset = range3.startOffset; var endOffset = range3.endOffset; if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) { startContainer = startContainer.parentNode; startOffset = dom2.nodeIndex(startContainer); startContainer = startContainer.parentNode; } if (startContainer.nodeType !== 1) { return null; } if (endOffset === startOffset + 1 && startContainer === range3.endContainer) { var node = startContainer.childNodes[startOffset]; if (isFakeSelectionTargetElement(node)) { return selectElement(node); } } return null; }; var removeElementSelection = function() { if (selectedElement) { selectedElement.removeAttribute(elementSelectionAttr); } descendant(SugarElement.fromDom(editor.getBody()), "#" + realSelectionId).each(remove$7); selectedElement = null; }; var destroy4 = function() { fakeCaret.destroy(); selectedElement = null; }; var hideFakeCaret = function() { fakeCaret.hide(); }; if (Env.ceFalse && !isRtc(editor)) { registerEvents2(); } return { showCaret: showCaret2, showBlockCaretContainer: showBlockCaretContainer2, hideFakeCaret, destroy: destroy4 }; }; var Quirks = function(editor) { var each3 = Tools.each; var BACKSPACE = VK.BACKSPACE, DELETE2 = VK.DELETE, dom2 = editor.dom, selection = editor.selection, parser = editor.parser; var isGecko = Env.gecko, isIE2 = Env.ie, isWebKit = Env.webkit; var mceInternalUrlPrefix = "data:text/mce-internal,"; var mceInternalDataType = isIE2 ? "Text" : "URL"; var setEditorCommandState2 = function(cmd, state) { try { editor.getDoc().execCommand(cmd, false, state); } catch (ex) { } }; var isDefaultPrevented = function(e2) { return e2.isDefaultPrevented(); }; var setMceInternalContent = function(e2) { var selectionHtml, internalContent; if (e2.dataTransfer) { if (editor.selection.isCollapsed() && e2.target.tagName === "IMG") { selection.select(e2.target); } selectionHtml = editor.selection.getContent(); if (selectionHtml.length > 0) { internalContent = mceInternalUrlPrefix + escape(editor.id) + "," + escape(selectionHtml); e2.dataTransfer.setData(mceInternalDataType, internalContent); } } }; var getMceInternalContent = function(e2) { var internalContent; if (e2.dataTransfer) { internalContent = e2.dataTransfer.getData(mceInternalDataType); if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) { internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(","); return { id: unescape(internalContent[0]), html: unescape(internalContent[1]) }; } } return null; }; var insertClipboardContents = function(content, internal) { if (editor.queryCommandSupported("mceInsertClipboardContent")) { editor.execCommand("mceInsertClipboardContent", false, { content, internal }); } else { editor.execCommand("mceInsertContent", false, content); } }; var emptyEditorWhenDeleting = function() { var serializeRng = function(rng) { var body = dom2.create("body"); var contents = rng.cloneContents(); body.appendChild(contents); return selection.serializer.serialize(body, { format: "html" }); }; var allContentsSelected = function(rng) { var selection2 = serializeRng(rng); var allRng = dom2.createRng(); allRng.selectNode(editor.getBody()); var allSelection = serializeRng(allRng); return selection2 === allSelection; }; editor.on("keydown", function(e2) { var keyCode = e2.keyCode; var isCollapsed, body; if (!isDefaultPrevented(e2) && (keyCode === DELETE2 || keyCode === BACKSPACE)) { isCollapsed = editor.selection.isCollapsed(); body = editor.getBody(); if (isCollapsed && !dom2.isEmpty(body)) { return; } if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { return; } e2.preventDefault(); editor.setContent(""); if (body.firstChild && dom2.isBlock(body.firstChild)) { editor.selection.setCursorLocation(body.firstChild, 0); } else { editor.selection.setCursorLocation(body, 0); } editor.nodeChanged(); } }); }; var selectAll = function() { editor.shortcuts.add("meta+a", null, "SelectAll"); }; var documentElementEditingFocus = function() { if (!editor.inline) { dom2.bind(editor.getDoc(), "mousedown mouseup", function(e2) { var rng; if (e2.target === editor.getDoc().documentElement) { rng = selection.getRng(); editor.getBody().focus(); if (e2.type === "mousedown") { if (isCaretContainer$2(rng.startContainer)) { return; } selection.placeCaretAt(e2.clientX, e2.clientY); } else { selection.setRng(rng); } } }); } }; var removeHrOnBackspace = function() { editor.on("keydown", function(e2) { if (!isDefaultPrevented(e2) && e2.keyCode === BACKSPACE) { if (!editor.getBody().getElementsByTagName("hr").length) { return; } if (selection.isCollapsed() && selection.getRng().startOffset === 0) { var node = selection.getNode(); var previousSibling = node.previousSibling; if (node.nodeName === "HR") { dom2.remove(node); e2.preventDefault(); return; } if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") { dom2.remove(previousSibling); e2.preventDefault(); } } } }); }; var focusBody2 = function() { if (!Range.prototype.getClientRects) { editor.on("mousedown", function(e2) { if (!isDefaultPrevented(e2) && e2.target.nodeName === "HTML") { var body_1 = editor.getBody(); body_1.blur(); Delay.setEditorTimeout(editor, function() { body_1.focus(); }); } }); } }; var selectControlElements = function() { editor.on("click", function(e2) { var target = e2.target; if (/^(IMG|HR)$/.test(target.nodeName) && dom2.getContentEditableParent(target) !== "false") { e2.preventDefault(); editor.selection.select(target); editor.nodeChanged(); } if (target.nodeName === "A" && dom2.hasClass(target, "mce-item-anchor")) { e2.preventDefault(); selection.select(target); } }); }; var removeStylesWhenDeletingAcrossBlockElements = function() { var getAttributeApplyFunction = function() { var template = dom2.getAttribs(selection.getStart().cloneNode(false)); return function() { var target = selection.getStart(); if (target !== editor.getBody()) { dom2.setAttrib(target, "style", null); each3(template, function(attr) { target.setAttributeNode(attr.cloneNode(true)); }); } }; }; var isSelectionAcrossElements = function() { return !selection.isCollapsed() && dom2.getParent(selection.getStart(), dom2.isBlock) !== dom2.getParent(selection.getEnd(), dom2.isBlock); }; editor.on("keypress", function(e2) { var applyAttributes2; if (!isDefaultPrevented(e2) && (e2.keyCode === 8 || e2.keyCode === 46) && isSelectionAcrossElements()) { applyAttributes2 = getAttributeApplyFunction(); editor.getDoc().execCommand("delete", false, null); applyAttributes2(); e2.preventDefault(); return false; } }); dom2.bind(editor.getDoc(), "cut", function(e2) { var applyAttributes2; if (!isDefaultPrevented(e2) && isSelectionAcrossElements()) { applyAttributes2 = getAttributeApplyFunction(); Delay.setEditorTimeout(editor, function() { applyAttributes2(); }); } }); }; var disableBackspaceIntoATable = function() { editor.on("keydown", function(e2) { if (!isDefaultPrevented(e2) && e2.keyCode === BACKSPACE) { if (selection.isCollapsed() && selection.getRng().startOffset === 0) { var previousSibling = selection.getNode().previousSibling; if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { e2.preventDefault(); return false; } } } }); }; var removeBlockQuoteOnBackSpace = function() { editor.on("keydown", function(e2) { var rng, parent3; if (isDefaultPrevented(e2) || e2.keyCode !== VK.BACKSPACE) { return; } rng = selection.getRng(); var container = rng.startContainer; var offset4 = rng.startOffset; var root2 = dom2.getRoot(); parent3 = container; if (!rng.collapsed || offset4 !== 0) { return; } while (parent3 && parent3.parentNode && parent3.parentNode.firstChild === parent3 && parent3.parentNode !== root2) { parent3 = parent3.parentNode; } if (parent3.tagName === "BLOCKQUOTE") { editor.formatter.toggle("blockquote", null, parent3); rng = dom2.createRng(); rng.setStart(container, 0); rng.setEnd(container, 0); selection.setRng(rng); } }); }; var setGeckoEditingOptions = function() { var setOpts = function() { setEditorCommandState2("StyleWithCSS", false); setEditorCommandState2("enableInlineTableEditing", false); if (!getObjectResizing(editor)) { setEditorCommandState2("enableObjectResizing", false); } }; if (!isReadOnly$1(editor)) { editor.on("BeforeExecCommand mousedown", setOpts); } }; var addBrAfterLastLinks = function() { var fixLinks = function() { each3(dom2.select("a"), function(node) { var parentNode = node.parentNode; var root2 = dom2.getRoot(); if (parentNode.lastChild === node) { while (parentNode && !dom2.isBlock(parentNode)) { if (parentNode.parentNode.lastChild !== parentNode || parentNode === root2) { return; } parentNode = parentNode.parentNode; } dom2.add(parentNode, "br", { "data-mce-bogus": 1 }); } }); }; editor.on("SetContent ExecCommand", function(e2) { if (e2.type === "setcontent" || e2.command === "mceInsertLink") { fixLinks(); } }); }; var setDefaultBlockType = function() { if (getForcedRootBlock(editor)) { editor.on("init", function() { setEditorCommandState2("DefaultParagraphSeparator", getForcedRootBlock(editor)); }); } }; var normalizeSelection2 = function() { editor.on("keyup focusin mouseup", function(e2) { if (!VK.modifierPressed(e2)) { selection.normalize(); } }, true); }; var showBrokenImageIcon = function() { editor.contentStyles.push("img:-moz-broken {-moz-force-broken-image-icon:1;min-width:24px;min-height:24px}"); }; var restoreFocusOnKeyDown = function() { if (!editor.inline) { editor.on("keydown", function() { if (document.activeElement === document.body) { editor.getWin().focus(); } }); } }; var bodyHeight = function() { if (!editor.inline) { editor.contentStyles.push("body {min-height: 150px}"); editor.on("click", function(e2) { var rng; if (e2.target.nodeName === "HTML") { if (Env.ie > 11) { editor.getBody().focus(); return; } rng = editor.selection.getRng(); editor.getBody().focus(); editor.selection.setRng(rng); editor.selection.normalize(); editor.nodeChanged(); } }); } }; var blockCmdArrowNavigation = function() { if (Env.mac) { editor.on("keydown", function(e2) { if (VK.metaKeyPressed(e2) && !e2.shiftKey && (e2.keyCode === 37 || e2.keyCode === 39)) { e2.preventDefault(); var selection_1 = editor.selection.getSel(); selection_1.modify("move", e2.keyCode === 37 ? "backward" : "forward", "lineboundary"); } }); } }; var disableAutoUrlDetect = function() { setEditorCommandState2("AutoUrlDetect", false); }; var tapLinksAndImages = function() { editor.on("click", function(e2) { var elm = e2.target; do { if (elm.tagName === "A") { e2.preventDefault(); return; } } while (elm = elm.parentNode); }); editor.contentStyles.push(".mce-content-body {-webkit-touch-callout: none}"); }; var blockFormSubmitInsideEditor = function() { editor.on("init", function() { editor.dom.bind(editor.getBody(), "submit", function(e2) { e2.preventDefault(); }); }); }; var removeAppleInterchangeBrs = function() { parser.addNodeFilter("br", function(nodes2) { var i2 = nodes2.length; while (i2--) { if (nodes2[i2].attr("class") === "Apple-interchange-newline") { nodes2[i2].remove(); } } }); }; var ieInternalDragAndDrop = function() { editor.on("dragstart", function(e2) { setMceInternalContent(e2); }); editor.on("drop", function(e2) { if (!isDefaultPrevented(e2)) { var internalContent = getMceInternalContent(e2); if (internalContent && internalContent.id !== editor.id) { e2.preventDefault(); var rng = fromPoint(e2.x, e2.y, editor.getDoc()); selection.setRng(rng); insertClipboardContents(internalContent.html, true); } } }); }; var refreshContentEditable = noop2; var isHidden2 = function() { if (!isGecko || editor.removed) { return false; } var sel = editor.selection.getSel(); return !sel || !sel.rangeCount || sel.rangeCount === 0; }; var setupRtc = function() { if (isWebKit) { documentElementEditingFocus(); selectControlElements(); blockFormSubmitInsideEditor(); selectAll(); if (Env.iOS) { restoreFocusOnKeyDown(); bodyHeight(); tapLinksAndImages(); } } if (isGecko) { focusBody2(); setGeckoEditingOptions(); showBrokenImageIcon(); blockCmdArrowNavigation(); } }; var setup124 = function() { removeBlockQuoteOnBackSpace(); emptyEditorWhenDeleting(); if (!Env.windowsPhone) { normalizeSelection2(); } if (isWebKit) { documentElementEditingFocus(); selectControlElements(); setDefaultBlockType(); blockFormSubmitInsideEditor(); disableBackspaceIntoATable(); removeAppleInterchangeBrs(); if (Env.iOS) { restoreFocusOnKeyDown(); bodyHeight(); tapLinksAndImages(); } else { selectAll(); } } if (Env.ie >= 11) { bodyHeight(); disableBackspaceIntoATable(); } if (Env.ie) { selectAll(); disableAutoUrlDetect(); ieInternalDragAndDrop(); } if (isGecko) { removeHrOnBackspace(); focusBody2(); removeStylesWhenDeletingAcrossBlockElements(); setGeckoEditingOptions(); addBrAfterLastLinks(); showBrokenImageIcon(); blockCmdArrowNavigation(); disableBackspaceIntoATable(); } }; if (isRtc(editor)) { setupRtc(); } else { setup124(); } return { refreshContentEditable, isHidden: isHidden2 }; }; var DOM$6 = DOMUtils.DOM; var appendStyle = function(editor, text) { var body = SugarElement.fromDom(editor.getBody()); var container = getStyleContainer(getRootNode(body)); var style = SugarElement.fromTag("style"); set$12(style, "type", "text/css"); append$1(style, SugarElement.fromText(text)); append$1(container, style); editor.on("remove", function() { remove$7(style); }); }; var getRootName = function(editor) { return editor.inline ? editor.getElement().nodeName.toLowerCase() : void 0; }; var removeUndefined = function(obj) { return filter$3(obj, function(v2) { return isUndefined2(v2) === false; }); }; var mkSchemaSettings = function(editor) { var settings = editor.settings; return removeUndefined({ block_elements: settings.block_elements, boolean_attributes: settings.boolean_attributes, custom_elements: settings.custom_elements, extended_valid_elements: settings.extended_valid_elements, invalid_elements: settings.invalid_elements, invalid_styles: settings.invalid_styles, move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements, non_empty_elements: settings.non_empty_elements, schema: settings.schema, self_closing_elements: settings.self_closing_elements, short_ended_elements: settings.short_ended_elements, special: settings.special, text_block_elements: settings.text_block_elements, text_inline_elements: settings.text_inline_elements, valid_children: settings.valid_children, valid_classes: settings.valid_classes, valid_elements: settings.valid_elements, valid_styles: settings.valid_styles, verify_html: settings.verify_html, whitespace_elements: settings.whitespace_elements, padd_empty_block_inline_children: settings.format_empty_lines }); }; var mkParserSettings = function(editor) { var settings = editor.settings; var blobCache = editor.editorUpload.blobCache; return removeUndefined({ allow_conditional_comments: settings.allow_conditional_comments, allow_html_data_urls: settings.allow_html_data_urls, allow_svg_data_urls: settings.allow_svg_data_urls, allow_html_in_named_anchor: settings.allow_html_in_named_anchor, allow_script_urls: settings.allow_script_urls, allow_unsafe_link_target: settings.allow_unsafe_link_target, convert_fonts_to_spans: settings.convert_fonts_to_spans, fix_list_elements: settings.fix_list_elements, font_size_legacy_values: settings.font_size_legacy_values, forced_root_block: settings.forced_root_block, forced_root_block_attrs: settings.forced_root_block_attrs, padd_empty_with_br: settings.padd_empty_with_br, preserve_cdata: settings.preserve_cdata, remove_trailing_brs: settings.remove_trailing_brs, inline_styles: settings.inline_styles, root_name: getRootName(editor), validate: true, blob_cache: blobCache, document: editor.getDoc(), images_dataimg_filter: settings.images_dataimg_filter }); }; var mkSerializerSettings = function(editor) { var settings = editor.settings; return __assign(__assign(__assign({}, mkParserSettings(editor)), mkSchemaSettings(editor)), removeUndefined({ url_converter: settings.url_converter, url_converter_scope: settings.url_converter_scope, element_format: settings.element_format, entities: settings.entities, entity_encoding: settings.entity_encoding, indent: settings.indent, indent_after: settings.indent_after, indent_before: settings.indent_before })); }; var createParser = function(editor) { var parser = DomParser(mkParserSettings(editor), editor.schema); parser.addAttributeFilter("src,href,style,tabindex", function(nodes2, name2) { var i2 = nodes2.length, node, value25; var dom2 = editor.dom; var internalName = "data-mce-" + name2; while (i2--) { node = nodes2[i2]; value25 = node.attr(name2); if (value25 && !node.attr(internalName)) { if (value25.indexOf("data:") === 0 || value25.indexOf("blob:") === 0) { continue; } if (name2 === "style") { value25 = dom2.serializeStyle(dom2.parseStyle(value25), node.name); if (!value25.length) { value25 = null; } node.attr(internalName, value25); node.attr(name2, value25); } else if (name2 === "tabindex") { node.attr(internalName, value25); node.attr(name2, null); } else { node.attr(internalName, editor.convertURL(value25, name2, node.name)); } } } }); parser.addNodeFilter("script", function(nodes2) { var i2 = nodes2.length; while (i2--) { var node = nodes2[i2]; var type3 = node.attr("type") || "no/type"; if (type3.indexOf("mce-") !== 0) { node.attr("type", "mce-" + type3); } } }); if (editor.settings.preserve_cdata) { parser.addNodeFilter("#cdata", function(nodes2) { var i2 = nodes2.length; while (i2--) { var node = nodes2[i2]; node.type = 8; node.name = "#comment"; node.value = "[CDATA[" + editor.dom.encode(node.value) + "]]"; } }); } parser.addNodeFilter("p,h1,h2,h3,h4,h5,h6,div", function(nodes2) { var i2 = nodes2.length; var nonEmptyElements = editor.schema.getNonEmptyElements(); while (i2--) { var node = nodes2[i2]; if (node.isEmpty(nonEmptyElements) && node.getAll("br").length === 0) { node.append(new AstNode("br", 1)).shortEnded = true; } } }); return parser; }; var autoFocus = function(editor) { if (editor.settings.auto_focus) { Delay.setEditorTimeout(editor, function() { var focusEditor2; if (editor.settings.auto_focus === true) { focusEditor2 = editor; } else { focusEditor2 = editor.editorManager.get(editor.settings.auto_focus); } if (!focusEditor2.destroyed) { focusEditor2.focus(); } }, 100); } }; var moveSelectionToFirstCaretPosition = function(editor) { var root2 = editor.dom.getRoot(); if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root2)) { firstPositionIn(root2).each(function(pos) { var node = pos.getNode(); var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos; if (Env.browser.isIE()) { storeNative(editor, caretPos.toRange()); } else { editor.selection.setRng(caretPos.toRange()); } }); } }; var initEditor = function(editor) { editor.bindPendingEventDelegates(); editor.initialized = true; fireInit(editor); editor.focus(true); moveSelectionToFirstCaretPosition(editor); editor.nodeChanged({ initial: true }); editor.execCallback("init_instance_callback", editor); autoFocus(editor); }; var getStyleSheetLoader$1 = function(editor) { return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader; }; var makeStylesheetLoadingPromises = function(editor, css2, framedFonts) { var promises = [new promiseObj(function(resolve2, reject) { return getStyleSheetLoader$1(editor).loadAll(css2, resolve2, reject); })]; if (editor.inline) { return promises; } else { return promises.concat([new promiseObj(function(resolve2, reject) { return editor.ui.styleSheetLoader.loadAll(framedFonts, resolve2, reject); })]); } }; var loadContentCss = function(editor) { var styleSheetLoader = getStyleSheetLoader$1(editor); var fontCss = getFontCss(editor); var css2 = editor.contentCSS; var removeCss = function() { styleSheetLoader.unloadAll(css2); if (!editor.inline) { editor.ui.styleSheetLoader.unloadAll(fontCss); } }; var loaded2 = function() { if (editor.removed) { removeCss(); } else { editor.on("remove", removeCss); } }; if (editor.contentStyles.length > 0) { var contentCssText_1 = ""; Tools.each(editor.contentStyles, function(style) { contentCssText_1 += style + "\r\n"; }); editor.dom.addStyle(contentCssText_1); } var allStylesheets = promiseObj.all(makeStylesheetLoadingPromises(editor, css2, fontCss)).then(loaded2).catch(loaded2); if (editor.settings.content_style) { appendStyle(editor, editor.settings.content_style); } return allStylesheets; }; var preInit = function(editor) { var settings = editor.settings, doc2 = editor.getDoc(), body = editor.getBody(); firePreInit(editor); if (!settings.browser_spellcheck && !settings.gecko_spellcheck) { doc2.body.spellcheck = false; DOM$6.setAttrib(body, "spellcheck", "false"); } editor.quirks = Quirks(editor); firePostRender(editor); var directionality = getDirectionality(editor); if (directionality !== void 0) { body.dir = directionality; } if (settings.protect) { editor.on("BeforeSetContent", function(e2) { Tools.each(settings.protect, function(pattern2) { e2.content = e2.content.replace(pattern2, function(str) { return ""; }); }); }); } editor.on("SetContent", function() { editor.addVisual(editor.getBody()); }); editor.on("compositionstart compositionend", function(e2) { editor.composing = e2.type === "compositionstart"; }); }; var loadInitialContent = function(editor) { if (!isRtc(editor)) { editor.load({ initial: true, format: "html" }); } editor.startContent = editor.getContent({ format: "raw" }); }; var initEditorWithInitialContent = function(editor) { if (editor.removed !== true) { loadInitialContent(editor); initEditor(editor); } }; var initContentBody = function(editor, skipWrite) { var settings = editor.settings; var targetElm = editor.getElement(); var doc2 = editor.getDoc(); if (!settings.inline) { editor.getElement().style.visibility = editor.orgVisibility; } if (!skipWrite && !editor.inline) { doc2.open(); doc2.write(editor.iframeHTML); doc2.close(); } if (editor.inline) { DOM$6.addClass(targetElm, "mce-content-body"); editor.contentDocument = doc2 = document; editor.contentWindow = window; editor.bodyElement = targetElm; editor.contentAreaContainer = targetElm; } var body = editor.getBody(); body.disabled = true; editor.readonly = !!settings.readonly; if (!editor.readonly) { if (editor.inline && DOM$6.getStyle(body, "position", true) === "static") { body.style.position = "relative"; } body.contentEditable = editor.getParam("content_editable_state", true); } body.disabled = false; editor.editorUpload = EditorUpload(editor); editor.schema = Schema2(mkSchemaSettings(editor)); editor.dom = DOMUtils(doc2, { keep_values: true, url_converter: editor.convertURL, url_converter_scope: editor, hex_colors: settings.force_hex_style_colors, update_styles: true, root_element: editor.inline ? editor.getBody() : null, collect: function() { return editor.inline; }, schema: editor.schema, contentCssCors: shouldUseContentCssCors(editor), referrerPolicy: getReferrerPolicy(editor), onSetAttrib: function(e2) { editor.fire("SetAttrib", e2); } }); editor.parser = createParser(editor); editor.serializer = DomSerializer(mkSerializerSettings(editor), editor); editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor); editor.annotator = Annotator(editor); editor.formatter = Formatter(editor); editor.undoManager = UndoManager(editor); editor._nodeChangeDispatcher = new NodeChange(editor); editor._selectionOverrides = SelectionOverrides(editor); setup$e(editor); setup$3(editor); if (!isRtc(editor)) { setup$2(editor); } var caret = setup$4(editor); setup$f(editor, caret); setup$d(editor); setup$g(editor); var setupRtcThunk = setup$i(editor); preInit(editor); setupRtcThunk.fold(function() { loadContentCss(editor).then(function() { return initEditorWithInitialContent(editor); }); }, function(setupRtc) { editor.setProgressState(true); loadContentCss(editor).then(function() { setupRtc().then(function(_rtcMode) { editor.setProgressState(false); initEditorWithInitialContent(editor); }, function(err) { editor.notificationManager.open({ type: "error", text: String(err) }); initEditorWithInitialContent(editor); }); }); }); }; var DOM$5 = DOMUtils.DOM; var relaxDomain = function(editor, ifr) { if (document.domain !== window.location.hostname && Env.browser.isIE()) { var bodyUuid = uuid2("mce"); editor[bodyUuid] = function() { initContentBody(editor); }; var domainRelaxUrl = 'javascript:(function(){document.open();document.domain="' + document.domain + '";var ed = window.parent.tinymce.get("' + editor.id + '");document.write(ed.iframeHTML);document.close();ed.' + bodyUuid + "(true);})()"; DOM$5.setAttrib(ifr, "src", domainRelaxUrl); return true; } return false; }; var createIframeElement = function(id2, title, height, customAttrs) { var iframe = SugarElement.fromTag("iframe"); setAll$1(iframe, customAttrs); setAll$1(iframe, { id: id2 + "_ifr", frameBorder: "0", allowTransparency: "true", title }); add$12(iframe, "tox-edit-area__iframe"); return iframe; }; var getIframeHtml = function(editor) { var iframeHTML = getDocType(editor) + ""; if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) { iframeHTML += '" + sanitizeHtmlString(providersBackstage.translate(message2)) + "
") }] }] }); }; var pFooter = function(buttons) { return ModalDialog.parts.footer({ dom: { tag: "div", classes: ["tox-dialog__footer"] }, components: buttons }); }; var pFooterGroup = function(startButtons, endButtons) { return [ Container.sketch({ dom: { tag: "div", classes: ["tox-dialog__footer-start"] }, components: startButtons }), Container.sketch({ dom: { tag: "div", classes: ["tox-dialog__footer-end"] }, components: endButtons }) ]; }; var renderDialog$1 = function(spec) { var _a4; var dialogClass = "tox-dialog"; var blockerClass = dialogClass + "-wrap"; var blockerBackdropClass = blockerClass + "__backdrop"; var scrollLockClass = dialogClass + "__disable-scroll"; return ModalDialog.sketch({ lazySink: spec.lazySink, onEscape: function(comp) { spec.onEscape(comp); return Optional.some(true); }, useTabstopAt: function(elem) { return !isPseudoStop(elem); }, dom: { tag: "div", classes: [dialogClass].concat(spec.extraClasses), styles: __assign({ position: "relative" }, spec.extraStyles) }, components: __spreadArray([ spec.header, spec.body ], spec.footer.toArray(), true), parts: { blocker: { dom: fromHtml(''), components: [{ dom: { tag: "div", classes: isTouch ? [ blockerBackdropClass, blockerBackdropClass + "--opaque" ] : [blockerBackdropClass] } }] } }, dragBlockClass: blockerClass, modalBehaviours: derive$1(__spreadArray([ Focusing.config({}), config3("dialog-events", spec.dialogEvents.concat([runOnSource(focusin(), function(comp, _se) { Keying.focusIn(comp); })])), config3("scroll-lock", [ runOnAttached(function() { add$2(body(), scrollLockClass); }), runOnDetached(function() { remove$2(body(), scrollLockClass); }) ]) ], spec.extraBehaviours, true)), eventOrder: __assign((_a4 = {}, _a4[execute$5()] = ["dialog-events"], _a4[attachedToDom()] = [ "scroll-lock", "dialog-events", "alloy.base.behaviour" ], _a4[detachedFromDom()] = [ "alloy.base.behaviour", "dialog-events", "scroll-lock" ], _a4), spec.eventOrder) }); }; var renderClose = function(providersBackstage) { return Button2.sketch({ dom: { tag: "button", classes: [ "tox-button", "tox-button--icon", "tox-button--naked" ], attributes: { "type": "button", "aria-label": providersBackstage.translate("Close"), "title": providersBackstage.translate("Close") } }, components: [render$3("close", { tag: "div", classes: ["tox-icon"] }, providersBackstage.icons)], action: function(comp) { emit2(comp, formCancelEvent); } }); }; var renderTitle2 = function(spec, id2, providersBackstage) { var renderComponents2 = function(data65) { return [text$1(providersBackstage.translate(data65.title))]; }; return { dom: { tag: "div", classes: ["tox-dialog__title"], attributes: __assign({}, id2.map(function(x2) { return { id: x2 }; }).getOr({})) }, components: renderComponents2(spec), behaviours: derive$1([Reflecting.config({ channel: titleChannel, renderComponents: renderComponents2 })]) }; }; var renderDragHandle = function() { return { dom: fromHtml('') }; }; var renderInlineHeader = function(spec, titleId, providersBackstage) { return Container.sketch({ dom: fromHtml(''), components: [ renderTitle2(spec, Optional.some(titleId), providersBackstage), renderDragHandle(), renderClose(providersBackstage) ], containerBehaviours: derive$1([Dragging.config({ mode: "mouse", blockerClass: "blocker", getTarget: function(handle2) { return closest$1(handle2, '[role="dialog"]').getOrDie(); }, snaps: { getSnapPoints: function() { return []; }, leftAttr: "data-drag-left", topAttr: "data-drag-top" } })]) }); }; var renderModalHeader = function(spec, providersBackstage) { var pTitle = ModalDialog.parts.title(renderTitle2(spec, Optional.none(), providersBackstage)); var pHandle = ModalDialog.parts.draghandle(renderDragHandle()); var pClose2 = ModalDialog.parts.close(renderClose(providersBackstage)); var components4 = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose2]); return Container.sketch({ dom: fromHtml(''), components: components4 }); }; var getHeader = function(title, backstage) { return renderModalHeader({ title: backstage.shared.providers.translate(title), draggable: backstage.dialog.isDraggableModal() }, backstage.shared.providers); }; var getBusySpec = function(message2, bs, providers) { return { dom: { tag: "div", classes: ["tox-dialog__busy-spinner"], attributes: { "aria-label": providers.translate(message2) }, styles: { left: "0px", right: "0px", bottom: "0px", top: "0px", position: "absolute" } }, behaviours: bs, components: [{ dom: fromHtml('' + code + ""); editor.selection.select(editor.$("#__new").removeAttr("id")[0]); }, function(n2) { editor.dom.setAttrib(n2, "class", "language-" + language); n2.innerHTML = code; get2(editor).highlightElement(n2); editor.selection.select(n2); }); }); }; var getCurrentCode = function(editor) { var node = getSelectedCodeSample(editor); return node.fold(constant2(""), function(n2) { return n2.textContent; }); }; var getLanguages = function(editor) { var defaultLanguages = [ { text: "HTML/XML", value: "markup" }, { text: "JavaScript", value: "javascript" }, { text: "CSS", value: "css" }, { text: "PHP", value: "php" }, { text: "Ruby", value: "ruby" }, { text: "Python", value: "python" }, { text: "Java", value: "java" }, { text: "C", value: "c" }, { text: "C#", value: "csharp" }, { text: "C++", value: "cpp" } ]; var customLanguages = getLanguages$1(editor); return customLanguages ? customLanguages : defaultLanguages; }; var getCurrentLanguage = function(editor, fallback) { var node = getSelectedCodeSample(editor); return node.fold(function() { return fallback; }, function(n2) { var matches = n2.className.match(/language-(\w+)/); return matches ? matches[1] : fallback; }); }; var open6 = function(editor) { var languages = getLanguages(editor); var defaultLanguage = head(languages).fold(constant2(""), function(l2) { return l2.value; }); var currentLanguage = getCurrentLanguage(editor, defaultLanguage); var currentCode = getCurrentCode(editor); editor.windowManager.open({ title: "Insert/Edit Code Sample", size: "large", body: { type: "panel", items: [ { type: "selectbox", name: "language", label: "Language", items: languages }, { type: "textarea", name: "code", label: "Code view" } ] }, buttons: [ { type: "cancel", name: "cancel", text: "Cancel" }, { type: "submit", name: "save", text: "Save", primary: true } ], initialData: { language: currentLanguage, code: currentCode }, onSubmit: function(api2) { var data65 = api2.getData(); insertCodeSample(editor, data65.language, data65.code); api2.close(); } }); }; var register$1 = function(editor) { editor.addCommand("codesample", function() { var node = editor.selection.getNode(); if (editor.selection.isCollapsed() || isCodeSample(node)) { open6(editor); } else { editor.formatter.toggle("code"); } }); }; var setup123 = function(editor) { var $2 = editor.$; editor.on("PreProcess", function(e2) { $2("pre[contenteditable=false]", e2.node).filter(trimArg(isCodeSample)).each(function(idx, elm) { var $elm = $2(elm), code = elm.textContent; $elm.attr("class", $2.trim($elm.attr("class"))); $elm.removeAttr("contentEditable"); $elm.empty().append($2("
").each(function() {
this.textContent = code;
}));
});
});
editor.on("SetContent", function() {
var unprocessedCodeSamples = $2("pre").filter(trimArg(isCodeSample)).filter(function(idx, elm) {
return elm.contentEditable !== "false";
});
if (unprocessedCodeSamples.length) {
editor.undoManager.transact(function() {
unprocessedCodeSamples.each(function(idx, elm) {
$2(elm).find("br").each(function(idx2, elm2) {
elm2.parentNode.replaceChild(editor.getDoc().createTextNode("\n"), elm2);
});
elm.contentEditable = "false";
elm.innerHTML = editor.dom.encode(elm.textContent);
get2(editor).highlightElement(elm);
elm.className = $2.trim(elm.className);
});
});
}
});
};
var isCodeSampleSelection = function(editor) {
var node = editor.selection.getStart();
return editor.dom.is(node, 'pre[class*="language-"]');
};
var register3 = function(editor) {
var onAction = function() {
return editor.execCommand("codesample");
};
editor.ui.registry.addToggleButton("codesample", {
icon: "code-sample",
tooltip: "Insert/edit code sample",
onAction,
onSetup: function(api2) {
var nodeChangeHandler = function() {
api2.setActive(isCodeSampleSelection(editor));
};
editor.on("NodeChange", nodeChangeHandler);
return function() {
return editor.off("NodeChange", nodeChangeHandler);
};
}
});
editor.ui.registry.addMenuItem("codesample", {
text: "Code sample...",
icon: "code-sample",
onAction
});
};
function Plugin() {
global$2.add("codesample", function(editor) {
setup123(editor);
register3(editor);
register$1(editor);
editor.on("dblclick", function(ev) {
if (isCodeSample(ev.target)) {
open6(editor);
}
});
});
}
Plugin();
})();
(function() {
var typeOf = function(x2) {
var t2 = typeof x2;
if (x2 === null) {
return "null";
} else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
return "array";
} else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
return "string";
} else {
return t2;
}
};
var isType$1 = function(type3) {
return function(value25) {
return typeOf(value25) === type3;
};
};
var isSimpleType = function(type3) {
return function(value25) {
return typeof value25 === type3;
};
};
var eq$2 = function(t2) {
return function(a2) {
return t2 === a2;
};
};
var isString3 = isType$1("string");
var isObject3 = isType$1("object");
var isArray2 = isType$1("array");
var isNull2 = eq$2(null);
var isBoolean2 = isSimpleType("boolean");
var isUndefined2 = eq$2(void 0);
var isNullable = function(a2) {
return a2 === null || a2 === void 0;
};
var isNonNullable = function(a2) {
return !isNullable(a2);
};
var isFunction3 = isSimpleType("function");
var isNumber2 = isSimpleType("number");
var noop2 = function() {
};
var compose = function(fa, fb) {
return function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return fa(fb.apply(null, args));
};
};
var compose1 = function(fbc, fab) {
return function(a2) {
return fbc(fab(a2));
};
};
var constant2 = function(value25) {
return function() {
return value25;
};
};
var identity2 = function(x2) {
return x2;
};
var tripleEquals = function(a2, b2) {
return a2 === b2;
};
function curry(fn) {
var initialArgs = [];
for (var _i = 1; _i < arguments.length; _i++) {
initialArgs[_i - 1] = arguments[_i];
}
return function() {
var restArgs = [];
for (var _i2 = 0; _i2 < arguments.length; _i2++) {
restArgs[_i2] = arguments[_i2];
}
var all3 = initialArgs.concat(restArgs);
return fn.apply(null, all3);
};
}
var not = function(f2) {
return function(t2) {
return !f2(t2);
};
};
var die = function(msg) {
return function() {
throw new Error(msg);
};
};
var never = constant2(false);
var always = constant2(true);
var none$2 = function() {
return NONE;
};
var NONE = function() {
var call2 = function(thunk) {
return thunk();
};
var id2 = identity2;
var me = {
fold: function(n2, _s) {
return n2();
},
isSome: never,
isNone: always,
getOr: id2,
getOrThunk: call2,
getOrDie: function(msg) {
throw new Error(msg || "error: getOrDie called on none.");
},
getOrNull: constant2(null),
getOrUndefined: constant2(void 0),
or: id2,
orThunk: call2,
map: none$2,
each: noop2,
bind: none$2,
exists: never,
forall: always,
filter: function() {
return none$2();
},
toArray: function() {
return [];
},
toString: constant2("none()")
};
return me;
}();
var some2 = function(a2) {
var constant_a = constant2(a2);
var self2 = function() {
return me;
};
var bind5 = function(f2) {
return f2(a2);
};
var me = {
fold: function(n2, s2) {
return s2(a2);
},
isSome: always,
isNone: never,
getOr: constant_a,
getOrThunk: constant_a,
getOrDie: constant_a,
getOrNull: constant_a,
getOrUndefined: constant_a,
or: self2,
orThunk: self2,
map: function(f2) {
return some2(f2(a2));
},
each: function(f2) {
f2(a2);
},
bind: bind5,
exists: bind5,
forall: bind5,
filter: function(f2) {
return f2(a2) ? me : NONE;
},
toArray: function() {
return [a2];
},
toString: function() {
return "some(" + a2 + ")";
}
};
return me;
};
var from$1 = function(value25) {
return value25 === null || value25 === void 0 ? NONE : some2(value25);
};
var Optional = {
some: some2,
none: none$2,
from: from$1
};
var nativeSlice = Array.prototype.slice;
var nativeIndexOf = Array.prototype.indexOf;
var nativePush = Array.prototype.push;
var rawIndexOf = function(ts, t2) {
return nativeIndexOf.call(ts, t2);
};
var contains$2 = function(xs, x2) {
return rawIndexOf(xs, x2) > -1;
};
var exists = function(xs, pred) {
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
if (pred(x2, i2)) {
return true;
}
}
return false;
};
var range$1 = function(num, f2) {
var r3 = [];
for (var i2 = 0; i2 < num; i2++) {
r3.push(f2(i2));
}
return r3;
};
var map$1 = function(xs, f2) {
var len = xs.length;
var r3 = new Array(len);
for (var i2 = 0; i2 < len; i2++) {
var x2 = xs[i2];
r3[i2] = f2(x2, i2);
}
return r3;
};
var each$2 = function(xs, f2) {
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
f2(x2, i2);
}
};
var eachr = function(xs, f2) {
for (var i2 = xs.length - 1; i2 >= 0; i2--) {
var x2 = xs[i2];
f2(x2, i2);
}
};
var partition2 = function(xs, pred) {
var pass = [];
var fail = [];
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
var arr = pred(x2, i2) ? pass : fail;
arr.push(x2);
}
return {
pass,
fail
};
};
var filter$2 = function(xs, pred) {
var r3 = [];
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
if (pred(x2, i2)) {
r3.push(x2);
}
}
return r3;
};
var foldr = function(xs, f2, acc) {
eachr(xs, function(x2, i2) {
acc = f2(acc, x2, i2);
});
return acc;
};
var foldl = function(xs, f2, acc) {
each$2(xs, function(x2, i2) {
acc = f2(acc, x2, i2);
});
return acc;
};
var findUntil = function(xs, pred, until) {
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
if (pred(x2, i2)) {
return Optional.some(x2);
} else if (until(x2, i2)) {
break;
}
}
return Optional.none();
};
var find$12 = function(xs, pred) {
return findUntil(xs, pred, never);
};
var findIndex2 = function(xs, pred) {
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
if (pred(x2, i2)) {
return Optional.some(i2);
}
}
return Optional.none();
};
var flatten$1 = function(xs) {
var r3 = [];
for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
if (!isArray2(xs[i2])) {
throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
}
nativePush.apply(r3, xs[i2]);
}
return r3;
};
var bind$22 = function(xs, f2) {
return flatten$1(map$1(xs, f2));
};
var forall = function(xs, pred) {
for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
var x2 = xs[i2];
if (pred(x2, i2) !== true) {
return false;
}
}
return true;
};
var reverse = function(xs) {
var r3 = nativeSlice.call(xs, 0);
r3.reverse();
return r3;
};
var mapToObject = function(xs, f2) {
var r3 = {};
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
r3[String(x2)] = f2(x2, i2);
}
return r3;
};
var pure = function(x2) {
return [x2];
};
var sort$1 = function(xs, comparator) {
var copy2 = nativeSlice.call(xs, 0);
copy2.sort(comparator);
return copy2;
};
var get$d = function(xs, i2) {
return i2 >= 0 && i2 < xs.length ? Optional.some(xs[i2]) : Optional.none();
};
var head = function(xs) {
return get$d(xs, 0);
};
var last$2 = function(xs) {
return get$d(xs, xs.length - 1);
};
var findMap = function(arr, f2) {
for (var i2 = 0; i2 < arr.length; i2++) {
var r3 = f2(arr[i2], i2);
if (r3.isSome()) {
return r3;
}
}
return Optional.none();
};
var __assign = function() {
__assign = Object.assign || function __assign2(t2) {
for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
s2 = arguments[i2];
for (var p in s2)
if (Object.prototype.hasOwnProperty.call(s2, p))
t2[p] = s2[p];
}
return t2;
};
return __assign.apply(this, arguments);
};
function __spreadArray(to2, from3, pack) {
if (pack || arguments.length === 2)
for (var i2 = 0, l2 = from3.length, ar; i2 < l2; i2++) {
if (ar || !(i2 in from3)) {
if (!ar)
ar = Array.prototype.slice.call(from3, 0, i2);
ar[i2] = from3[i2];
}
}
return to2.concat(ar || Array.prototype.slice.call(from3));
}
var cached2 = function(f2) {
var called = false;
var r3;
return function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!called) {
called = true;
r3 = f2.apply(null, args);
}
return r3;
};
};
var DeviceType = function(os, browser, userAgent, mediaMatch2) {
var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
var isiPhone = os.isiOS() && !isiPad;
var isMobile2 = os.isiOS() || os.isAndroid();
var isTouch = isMobile2 || mediaMatch2("(pointer:coarse)");
var isTablet = isiPad || !isiPhone && isMobile2 && mediaMatch2("(min-device-width:768px)");
var isPhone = isiPhone || isMobile2 && !isTablet;
var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
var isDesktop = !isPhone && !isTablet && !iOSwebview;
return {
isiPad: constant2(isiPad),
isiPhone: constant2(isiPhone),
isTablet: constant2(isTablet),
isPhone: constant2(isPhone),
isTouch: constant2(isTouch),
isAndroid: os.isAndroid,
isiOS: os.isiOS,
isWebView: constant2(iOSwebview),
isDesktop: constant2(isDesktop)
};
};
var firstMatch = function(regexes2, s2) {
for (var i2 = 0; i2 < regexes2.length; i2++) {
var x2 = regexes2[i2];
if (x2.test(s2)) {
return x2;
}
}
return void 0;
};
var find2 = function(regexes2, agent) {
var r3 = firstMatch(regexes2, agent);
if (!r3) {
return {
major: 0,
minor: 0
};
}
var group = function(i2) {
return Number(agent.replace(r3, "$" + i2));
};
return nu$2(group(1), group(2));
};
var detect$6 = function(versionRegexes, agent) {
var cleanedAgent = String(agent).toLowerCase();
if (versionRegexes.length === 0) {
return unknown$2();
}
return find2(versionRegexes, cleanedAgent);
};
var unknown$2 = function() {
return nu$2(0, 0);
};
var nu$2 = function(major, minor) {
return {
major,
minor
};
};
var Version = {
nu: nu$2,
detect: detect$6,
unknown: unknown$2
};
var detectBrowser$1 = function(browsers2, userAgentData) {
return findMap(userAgentData.brands, function(uaBrand) {
var lcBrand = uaBrand.brand.toLowerCase();
return find$12(browsers2, function(browser) {
var _a3;
return lcBrand === ((_a3 = browser.brand) === null || _a3 === void 0 ? void 0 : _a3.toLowerCase());
}).map(function(info3) {
return {
current: info3.name,
version: Version.nu(parseInt(uaBrand.version, 10), 0)
};
});
});
};
var detect$5 = function(candidates, userAgent) {
var agent = String(userAgent).toLowerCase();
return find$12(candidates, function(candidate) {
return candidate.search(agent);
});
};
var detectBrowser = function(browsers2, userAgent) {
return detect$5(browsers2, userAgent).map(function(browser) {
var version = Version.detect(browser.versionRegexes, userAgent);
return {
current: browser.name,
version
};
});
};
var detectOs = function(oses2, userAgent) {
return detect$5(oses2, userAgent).map(function(os) {
var version = Version.detect(os.versionRegexes, userAgent);
return {
current: os.name,
version
};
});
};
var removeFromStart = function(str, numChars) {
return str.substring(numChars);
};
var checkRange = function(str, substr, start) {
return substr === "" || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
};
var removeLeading = function(str, prefix) {
return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
};
var contains$1 = function(str, substr) {
return str.indexOf(substr) !== -1;
};
var startsWith = function(str, prefix) {
return checkRange(str, prefix, 0);
};
var endsWith2 = function(str, suffix) {
return checkRange(str, suffix, str.length - suffix.length);
};
var blank = function(r3) {
return function(s2) {
return s2.replace(r3, "");
};
};
var trim2 = blank(/^\s+|\s+$/g);
var isNotEmpty = function(s2) {
return s2.length > 0;
};
var isEmpty$1 = function(s2) {
return !isNotEmpty(s2);
};
var toFloat2 = function(value25) {
var num = parseFloat(value25);
return isNaN(num) ? Optional.none() : Optional.some(num);
};
var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
var checkContains = function(target) {
return function(uastring) {
return contains$1(uastring, target);
};
};
var browsers = [
{
name: "Edge",
versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
search: function(uastring) {
return contains$1(uastring, "edge/") && contains$1(uastring, "chrome") && contains$1(uastring, "safari") && contains$1(uastring, "applewebkit");
}
},
{
name: "Chrome",
brand: "Chromium",
versionRegexes: [
/.*?chrome\/([0-9]+)\.([0-9]+).*/,
normalVersionRegex
],
search: function(uastring) {
return contains$1(uastring, "chrome") && !contains$1(uastring, "chromeframe");
}
},
{
name: "IE",
versionRegexes: [
/.*?msie\ ?([0-9]+)\.([0-9]+).*/,
/.*?rv:([0-9]+)\.([0-9]+).*/
],
search: function(uastring) {
return contains$1(uastring, "msie") || contains$1(uastring, "trident");
}
},
{
name: "Opera",
versionRegexes: [
normalVersionRegex,
/.*?opera\/([0-9]+)\.([0-9]+).*/
],
search: checkContains("opera")
},
{
name: "Firefox",
versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
search: checkContains("firefox")
},
{
name: "Safari",
versionRegexes: [
normalVersionRegex,
/.*?cpu os ([0-9]+)_([0-9]+).*/
],
search: function(uastring) {
return (contains$1(uastring, "safari") || contains$1(uastring, "mobile/")) && contains$1(uastring, "applewebkit");
}
}
];
var oses = [
{
name: "Windows",
search: checkContains("win"),
versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
},
{
name: "iOS",
search: function(uastring) {
return contains$1(uastring, "iphone") || contains$1(uastring, "ipad");
},
versionRegexes: [
/.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
/.*cpu os ([0-9]+)_([0-9]+).*/,
/.*cpu iphone os ([0-9]+)_([0-9]+).*/
]
},
{
name: "Android",
search: checkContains("android"),
versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
},
{
name: "OSX",
search: checkContains("mac os x"),
versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
},
{
name: "Linux",
search: checkContains("linux"),
versionRegexes: []
},
{
name: "Solaris",
search: checkContains("sunos"),
versionRegexes: []
},
{
name: "FreeBSD",
search: checkContains("freebsd"),
versionRegexes: []
},
{
name: "ChromeOS",
search: checkContains("cros"),
versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
}
];
var PlatformInfo = {
browsers: constant2(browsers),
oses: constant2(oses)
};
var edge = "Edge";
var chrome = "Chrome";
var ie = "IE";
var opera = "Opera";
var firefox = "Firefox";
var safari = "Safari";
var unknown$1 = function() {
return nu$1({
current: void 0,
version: Version.unknown()
});
};
var nu$1 = function(info3) {
var current2 = info3.current;
var version = info3.version;
var isBrowser2 = function(name2) {
return function() {
return current2 === name2;
};
};
return {
current: current2,
version,
isEdge: isBrowser2(edge),
isChrome: isBrowser2(chrome),
isIE: isBrowser2(ie),
isOpera: isBrowser2(opera),
isFirefox: isBrowser2(firefox),
isSafari: isBrowser2(safari)
};
};
var Browser = {
unknown: unknown$1,
nu: nu$1,
edge: constant2(edge),
chrome: constant2(chrome),
ie: constant2(ie),
opera: constant2(opera),
firefox: constant2(firefox),
safari: constant2(safari)
};
var windows = "Windows";
var ios = "iOS";
var android = "Android";
var linux = "Linux";
var osx = "OSX";
var solaris = "Solaris";
var freebsd = "FreeBSD";
var chromeos = "ChromeOS";
var unknown = function() {
return nu({
current: void 0,
version: Version.unknown()
});
};
var nu = function(info3) {
var current2 = info3.current;
var version = info3.version;
var isOS = function(name2) {
return function() {
return current2 === name2;
};
};
return {
current: current2,
version,
isWindows: isOS(windows),
isiOS: isOS(ios),
isAndroid: isOS(android),
isOSX: isOS(osx),
isLinux: isOS(linux),
isSolaris: isOS(solaris),
isFreeBSD: isOS(freebsd),
isChromeOS: isOS(chromeos)
};
};
var OperatingSystem = {
unknown,
nu,
windows: constant2(windows),
ios: constant2(ios),
android: constant2(android),
linux: constant2(linux),
osx: constant2(osx),
solaris: constant2(solaris),
freebsd: constant2(freebsd),
chromeos: constant2(chromeos)
};
var detect$4 = function(userAgent, userAgentDataOpt, mediaMatch2) {
var browsers2 = PlatformInfo.browsers();
var oses2 = PlatformInfo.oses();
var browser = userAgentDataOpt.bind(function(userAgentData) {
return detectBrowser$1(browsers2, userAgentData);
}).orThunk(function() {
return detectBrowser(browsers2, userAgent);
}).fold(Browser.unknown, Browser.nu);
var os = detectOs(oses2, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
var deviceType = DeviceType(os, browser, userAgent, mediaMatch2);
return {
browser,
os,
deviceType
};
};
var PlatformDetection = { detect: detect$4 };
var mediaMatch = function(query) {
return window.matchMedia(query).matches;
};
var platform = cached2(function() {
return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
});
var detect$3 = function() {
return platform();
};
var compareDocumentPosition = function(a2, b2, match5) {
return (a2.compareDocumentPosition(b2) & match5) !== 0;
};
var documentPositionContainedBy = function(a2, b2) {
return compareDocumentPosition(a2, b2, Node.DOCUMENT_POSITION_CONTAINED_BY);
};
var COMMENT = 8;
var DOCUMENT = 9;
var DOCUMENT_FRAGMENT = 11;
var ELEMENT = 1;
var TEXT = 3;
var fromHtml$1 = function(html, scope) {
var doc = scope || document;
var div = doc.createElement("div");
div.innerHTML = html;
if (!div.hasChildNodes() || div.childNodes.length > 1) {
console.error("HTML does not have a single root node", html);
throw new Error("HTML must have a single root node");
}
return fromDom$1(div.childNodes[0]);
};
var fromTag = function(tag, scope) {
var doc = scope || document;
var node = doc.createElement(tag);
return fromDom$1(node);
};
var fromText = function(text, scope) {
var doc = scope || document;
var node = doc.createTextNode(text);
return fromDom$1(node);
};
var fromDom$1 = function(node) {
if (node === null || node === void 0) {
throw new Error("Node cannot be null or undefined");
}
return { dom: node };
};
var fromPoint$1 = function(docElm, x2, y2) {
return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom$1);
};
var SugarElement = {
fromHtml: fromHtml$1,
fromTag,
fromText,
fromDom: fromDom$1,
fromPoint: fromPoint$1
};
var is$2 = function(element, selector2) {
var dom = element.dom;
if (dom.nodeType !== ELEMENT) {
return false;
} else {
var elem = dom;
if (elem.matches !== void 0) {
return elem.matches(selector2);
} else if (elem.msMatchesSelector !== void 0) {
return elem.msMatchesSelector(selector2);
} else if (elem.webkitMatchesSelector !== void 0) {
return elem.webkitMatchesSelector(selector2);
} else if (elem.mozMatchesSelector !== void 0) {
return elem.mozMatchesSelector(selector2);
} else {
throw new Error("Browser lacks native selectors");
}
}
};
var bypassSelector = function(dom) {
return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
};
var all$1 = function(selector2, scope) {
var base2 = scope === void 0 ? document : scope.dom;
return bypassSelector(base2) ? [] : map$1(base2.querySelectorAll(selector2), SugarElement.fromDom);
};
var one = function(selector2, scope) {
var base2 = scope === void 0 ? document : scope.dom;
return bypassSelector(base2) ? Optional.none() : Optional.from(base2.querySelector(selector2)).map(SugarElement.fromDom);
};
var eq$1 = function(e1, e2) {
return e1.dom === e2.dom;
};
var regularContains = function(e1, e2) {
var d1 = e1.dom;
var d2 = e2.dom;
return d1 === d2 ? false : d1.contains(d2);
};
var ieContains = function(e1, e2) {
return documentPositionContainedBy(e1.dom, e2.dom);
};
var contains2 = function(e1, e2) {
return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
};
var is$1 = is$2;
var keys2 = Object.keys;
var hasOwnProperty2 = Object.hasOwnProperty;
var each$12 = function(obj, f2) {
var props2 = keys2(obj);
for (var k2 = 0, len = props2.length; k2 < len; k2++) {
var i2 = props2[k2];
var x2 = obj[i2];
f2(x2, i2);
}
};
var map2 = function(obj, f2) {
return tupleMap(obj, function(x2, i2) {
return {
k: i2,
v: f2(x2, i2)
};
});
};
var tupleMap = function(obj, f2) {
var r3 = {};
each$12(obj, function(x2, i2) {
var tuple3 = f2(x2, i2);
r3[tuple3.k] = tuple3.v;
});
return r3;
};
var objAcc = function(r3) {
return function(x2, i2) {
r3[i2] = x2;
};
};
var internalFilter = function(obj, pred, onTrue, onFalse) {
var r3 = {};
each$12(obj, function(x2, i2) {
(pred(x2, i2) ? onTrue : onFalse)(x2, i2);
});
return r3;
};
var filter$1 = function(obj, pred) {
var t2 = {};
internalFilter(obj, pred, objAcc(t2), noop2);
return t2;
};
var mapToArray2 = function(obj, f2) {
var r3 = [];
each$12(obj, function(value25, name2) {
r3.push(f2(value25, name2));
});
return r3;
};
var values2 = function(obj) {
return mapToArray2(obj, identity2);
};
var size = function(obj) {
return keys2(obj).length;
};
var get$c = function(obj, key3) {
return has$12(obj, key3) ? Optional.from(obj[key3]) : Optional.none();
};
var has$12 = function(obj, key3) {
return hasOwnProperty2.call(obj, key3);
};
var hasNonNullableKey = function(obj, key3) {
return has$12(obj, key3) && obj[key3] !== void 0 && obj[key3] !== null;
};
var isEmpty = function(r3) {
for (var x2 in r3) {
if (hasOwnProperty2.call(r3, x2)) {
return false;
}
}
return true;
};
var validSectionList = [
"tfoot",
"thead",
"tbody",
"colgroup"
];
var isValidSection = function(parentName) {
return contains$2(validSectionList, parentName);
};
var grid = function(rows2, columns3) {
return {
rows: rows2,
columns: columns3
};
};
var address = function(row2, column) {
return {
row: row2,
column
};
};
var detail = function(element, rowspan, colspan) {
return {
element,
rowspan,
colspan
};
};
var detailnew = function(element, rowspan, colspan, isNew) {
return {
element,
rowspan,
colspan,
isNew
};
};
var extended = function(element, rowspan, colspan, row2, column, isLocked) {
return {
element,
rowspan,
colspan,
row: row2,
column,
isLocked
};
};
var rowdetail = function(element, cells2, section2) {
return {
element,
cells: cells2,
section: section2
};
};
var rowdetailnew = function(element, cells2, section2, isNew) {
return {
element,
cells: cells2,
section: section2,
isNew
};
};
var elementnew = function(element, isNew, isLocked) {
return {
element,
isNew,
isLocked
};
};
var rowcells = function(element, cells2, section2, isNew) {
return {
element,
cells: cells2,
section: section2,
isNew
};
};
var bounds = function(startRow, startCol, finishRow, finishCol) {
return {
startRow,
startCol,
finishRow,
finishCol
};
};
var columnext = function(element, colspan, column) {
return {
element,
colspan,
column
};
};
var colgroup = function(element, columns3) {
return {
element,
columns: columns3
};
};
typeof window !== "undefined" ? window : Function("return this;")();
var name = function(element) {
var r3 = element.dom.nodeName;
return r3.toLowerCase();
};
var type$12 = function(element) {
return element.dom.nodeType;
};
var isType = function(t2) {
return function(element) {
return type$12(element) === t2;
};
};
var isComment = function(element) {
return type$12(element) === COMMENT || name(element) === "#comment";
};
var isElement2 = isType(ELEMENT);
var isText = isType(TEXT);
var isDocument = isType(DOCUMENT);
var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
var isTag = function(tag) {
return function(e2) {
return isElement2(e2) && name(e2) === tag;
};
};
var owner = function(element) {
return SugarElement.fromDom(element.dom.ownerDocument);
};
var documentOrOwner = function(dos) {
return isDocument(dos) ? dos : owner(dos);
};
var defaultView = function(element) {
return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
};
var parent2 = function(element) {
return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
};
var parentElement = function(element) {
return Optional.from(element.dom.parentElement).map(SugarElement.fromDom);
};
var parents = function(element, isRoot) {
var stop2 = isFunction3(isRoot) ? isRoot : never;
var dom = element.dom;
var ret = [];
while (dom.parentNode !== null && dom.parentNode !== void 0) {
var rawParent = dom.parentNode;
var p = SugarElement.fromDom(rawParent);
ret.push(p);
if (stop2(p) === true) {
break;
} else {
dom = rawParent;
}
}
return ret;
};
var prevSibling = function(element) {
return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
};
var nextSibling = function(element) {
return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
};
var children$3 = function(element) {
return map$1(element.dom.childNodes, SugarElement.fromDom);
};
var child$3 = function(element, index2) {
var cs = element.dom.childNodes;
return Optional.from(cs[index2]).map(SugarElement.fromDom);
};
var firstChild = function(element) {
return child$3(element, 0);
};
var isShadowRoot = function(dos) {
return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
};
var supported = isFunction3(Element.prototype.attachShadow) && isFunction3(Node.prototype.getRootNode);
var isSupported$1 = constant2(supported);
var getRootNode = supported ? function(e2) {
return SugarElement.fromDom(e2.dom.getRootNode());
} : documentOrOwner;
var getShadowRoot = function(e2) {
var r3 = getRootNode(e2);
return isShadowRoot(r3) ? Optional.some(r3) : Optional.none();
};
var getShadowHost = function(e2) {
return SugarElement.fromDom(e2.dom.host);
};
var getOriginalEventTarget = function(event) {
if (isSupported$1() && isNonNullable(event.target)) {
var el = SugarElement.fromDom(event.target);
if (isElement2(el) && isOpenShadowHost(el)) {
if (event.composed && event.composedPath) {
var composedPath = event.composedPath();
if (composedPath) {
return head(composedPath);
}
}
}
}
return Optional.from(event.target);
};
var isOpenShadowHost = function(element) {
return isNonNullable(element.dom.shadowRoot);
};
var inBody = function(element) {
var dom = isText(element) ? element.dom.parentNode : element.dom;
if (dom === void 0 || dom === null || dom.ownerDocument === null) {
return false;
}
var doc = dom.ownerDocument;
return getShadowRoot(SugarElement.fromDom(dom)).fold(function() {
return doc.body.contains(dom);
}, compose1(inBody, getShadowHost));
};
var body$1 = function() {
return getBody$1(SugarElement.fromDom(document));
};
var getBody$1 = function(doc) {
var b2 = doc.dom.body;
if (b2 === null || b2 === void 0) {
throw new Error("Body is not available yet");
}
return SugarElement.fromDom(b2);
};
var ancestors$4 = function(scope, predicate, isRoot) {
return filter$2(parents(scope, isRoot), predicate);
};
var children$2 = function(scope, predicate) {
return filter$2(children$3(scope), predicate);
};
var descendants$1 = function(scope, predicate) {
var result = [];
each$2(children$3(scope), function(x2) {
if (predicate(x2)) {
result = result.concat([x2]);
}
result = result.concat(descendants$1(x2, predicate));
});
return result;
};
var ancestors$3 = function(scope, selector2, isRoot) {
return ancestors$4(scope, function(e2) {
return is$2(e2, selector2);
}, isRoot);
};
var children$1 = function(scope, selector2) {
return children$2(scope, function(e2) {
return is$2(e2, selector2);
});
};
var descendants = function(scope, selector2) {
return all$1(selector2, scope);
};
function ClosestOrAncestor(is3, ancestor2, scope, a2, isRoot) {
if (is3(scope, a2)) {
return Optional.some(scope);
} else if (isFunction3(isRoot) && isRoot(scope)) {
return Optional.none();
} else {
return ancestor2(scope, a2, isRoot);
}
}
var ancestor$2 = function(scope, predicate, isRoot) {
var element = scope.dom;
var stop2 = isFunction3(isRoot) ? isRoot : never;
while (element.parentNode) {
element = element.parentNode;
var el = SugarElement.fromDom(element);
if (predicate(el)) {
return Optional.some(el);
} else if (stop2(el)) {
break;
}
}
return Optional.none();
};
var closest$2 = function(scope, predicate, isRoot) {
var is3 = function(s2, test) {
return test(s2);
};
return ClosestOrAncestor(is3, ancestor$2, scope, predicate, isRoot);
};
var child$2 = function(scope, predicate) {
var pred = function(node) {
return predicate(SugarElement.fromDom(node));
};
var result = find$12(scope.dom.childNodes, pred);
return result.map(SugarElement.fromDom);
};
var descendant$1 = function(scope, predicate) {
var descend = function(node) {
for (var i2 = 0; i2 < node.childNodes.length; i2++) {
var child_1 = SugarElement.fromDom(node.childNodes[i2]);
if (predicate(child_1)) {
return Optional.some(child_1);
}
var res = descend(node.childNodes[i2]);
if (res.isSome()) {
return res;
}
}
return Optional.none();
};
return descend(scope.dom);
};
var ancestor$1 = function(scope, selector2, isRoot) {
return ancestor$2(scope, function(e2) {
return is$2(e2, selector2);
}, isRoot);
};
var child$1 = function(scope, selector2) {
return child$2(scope, function(e2) {
return is$2(e2, selector2);
});
};
var descendant = function(scope, selector2) {
return one(selector2, scope);
};
var closest$1 = function(scope, selector2, isRoot) {
var is3 = function(element, selector3) {
return is$2(element, selector3);
};
return ClosestOrAncestor(is3, ancestor$1, scope, selector2, isRoot);
};
var rawSet = function(dom, key3, value25) {
if (isString3(value25) || isBoolean2(value25) || isNumber2(value25)) {
dom.setAttribute(key3, value25 + "");
} else {
console.error("Invalid call to Attribute.set. Key ", key3, ":: Value ", value25, ":: Element ", dom);
throw new Error("Attribute value was not simple");
}
};
var set$2 = function(element, key3, value25) {
rawSet(element.dom, key3, value25);
};
var setAll$1 = function(element, attrs) {
var dom = element.dom;
each$12(attrs, function(v2, k2) {
rawSet(dom, k2, v2);
});
};
var setOptions = function(element, attrs) {
each$12(attrs, function(v2, k2) {
v2.fold(function() {
remove$7(element, k2);
}, function(value25) {
rawSet(element.dom, k2, value25);
});
});
};
var get$b = function(element, key3) {
var v2 = element.dom.getAttribute(key3);
return v2 === null ? void 0 : v2;
};
var getOpt = function(element, key3) {
return Optional.from(get$b(element, key3));
};
var remove$7 = function(element, key3) {
element.dom.removeAttribute(key3);
};
var clone$2 = function(element) {
return foldl(element.dom.attributes, function(acc, attr) {
acc[attr.name] = attr.value;
return acc;
}, {});
};
var is2 = function(lhs, rhs, comparator) {
if (comparator === void 0) {
comparator = tripleEquals;
}
return lhs.exists(function(left2) {
return comparator(left2, rhs);
});
};
var cat = function(arr) {
var r3 = [];
var push3 = function(x2) {
r3.push(x2);
};
for (var i2 = 0; i2 < arr.length; i2++) {
arr[i2].each(push3);
}
return r3;
};
var lift2 = function(oa, ob, f2) {
return oa.isSome() && ob.isSome() ? Optional.some(f2(oa.getOrDie(), ob.getOrDie())) : Optional.none();
};
var bindFrom = function(a2, f2) {
return a2 !== void 0 && a2 !== null ? f2(a2) : Optional.none();
};
var flatten2 = function(oot) {
return oot.bind(identity2);
};
var someIf = function(b2, a2) {
return b2 ? Optional.some(a2) : Optional.none();
};
var isSupported = function(dom) {
return dom.style !== void 0 && isFunction3(dom.style.getPropertyValue);
};
var internalSet = function(dom, property2, value25) {
if (!isString3(value25)) {
console.error("Invalid call to CSS.set. Property ", property2, ":: Value ", value25, ":: Element ", dom);
throw new Error("CSS value must be a string: " + value25);
}
if (isSupported(dom)) {
dom.style.setProperty(property2, value25);
}
};
var internalRemove = function(dom, property2) {
if (isSupported(dom)) {
dom.style.removeProperty(property2);
}
};
var set$12 = function(element, property2, value25) {
var dom = element.dom;
internalSet(dom, property2, value25);
};
var setAll = function(element, css3) {
var dom = element.dom;
each$12(css3, function(v2, k2) {
internalSet(dom, k2, v2);
});
};
var get$a = function(element, property2) {
var dom = element.dom;
var styles2 = window.getComputedStyle(dom);
var r3 = styles2.getPropertyValue(property2);
return r3 === "" && !inBody(element) ? getUnsafeProperty(dom, property2) : r3;
};
var getUnsafeProperty = function(dom, property2) {
return isSupported(dom) ? dom.style.getPropertyValue(property2) : "";
};
var getRaw$2 = function(element, property2) {
var dom = element.dom;
var raw = getUnsafeProperty(dom, property2);
return Optional.from(raw).filter(function(r3) {
return r3.length > 0;
});
};
var remove$6 = function(element, property2) {
var dom = element.dom;
internalRemove(dom, property2);
if (is2(getOpt(element, "style").map(trim2), "")) {
remove$7(element, "style");
}
};
var copy$2 = function(source2, target) {
var sourceDom = source2.dom;
var targetDom = target.dom;
if (isSupported(sourceDom) && isSupported(targetDom)) {
targetDom.style.cssText = sourceDom.style.cssText;
}
};
var getAttrValue = function(cell2, name2, fallback2) {
if (fallback2 === void 0) {
fallback2 = 0;
}
return getOpt(cell2, name2).map(function(value25) {
return parseInt(value25, 10);
}).getOr(fallback2);
};
var getSpan = function(cell2, type3) {
return getAttrValue(cell2, type3, 1);
};
var hasColspan = function(cellOrCol) {
if (isTag("col")(cellOrCol)) {
return getAttrValue(cellOrCol, "span", 1) > 1;
} else {
return getSpan(cellOrCol, "colspan") > 1;
}
};
var hasRowspan = function(cell2) {
return getSpan(cell2, "rowspan") > 1;
};
var getCssValue = function(element, property2) {
return parseInt(get$a(element, property2), 10);
};
var minWidth = constant2(10);
var minHeight = constant2(10);
var firstLayer = function(scope, selector2) {
return filterFirstLayer(scope, selector2, always);
};
var filterFirstLayer = function(scope, selector2, predicate) {
return bind$22(children$3(scope), function(x2) {
if (is$2(x2, selector2)) {
return predicate(x2) ? [x2] : [];
} else {
return filterFirstLayer(x2, selector2, predicate);
}
});
};
var lookup = function(tags, element, isRoot) {
if (isRoot === void 0) {
isRoot = never;
}
if (isRoot(element)) {
return Optional.none();
}
if (contains$2(tags, name(element))) {
return Optional.some(element);
}
var isRootOrUpperTable = function(elm) {
return is$2(elm, "table") || isRoot(elm);
};
return ancestor$1(element, tags.join(","), isRootOrUpperTable);
};
var cell = function(element, isRoot) {
return lookup([
"td",
"th"
], element, isRoot);
};
var cells$1 = function(ancestor2) {
return firstLayer(ancestor2, "th,td");
};
var columns$1 = function(ancestor2) {
if (is$2(ancestor2, "colgroup")) {
return children$1(ancestor2, "col");
} else {
return bind$22(columnGroups(ancestor2), function(columnGroup) {
return children$1(columnGroup, "col");
});
}
};
var table2 = function(element, isRoot) {
return closest$1(element, "table", isRoot);
};
var rows$1 = function(ancestor2) {
return firstLayer(ancestor2, "tr");
};
var columnGroups = function(ancestor2) {
return table2(ancestor2).fold(constant2([]), function(table3) {
return children$1(table3, "colgroup");
});
};
var fromRowsOrColGroups = function(elems, getSection) {
return map$1(elems, function(row2) {
if (name(row2) === "colgroup") {
var cells2 = map$1(columns$1(row2), function(column) {
var colspan = getAttrValue(column, "span", 1);
return detail(column, 1, colspan);
});
return rowdetail(row2, cells2, "colgroup");
} else {
var cells2 = map$1(cells$1(row2), function(cell2) {
var rowspan = getAttrValue(cell2, "rowspan", 1);
var colspan = getAttrValue(cell2, "colspan", 1);
return detail(cell2, rowspan, colspan);
});
return rowdetail(row2, cells2, getSection(row2));
}
});
};
var getParentSection = function(group) {
return parent2(group).map(function(parent3) {
var parentName = name(parent3);
return isValidSection(parentName) ? parentName : "tbody";
}).getOr("tbody");
};
var fromTable$1 = function(table3) {
var rows2 = rows$1(table3);
var columnGroups$1 = columnGroups(table3);
var elems = __spreadArray(__spreadArray([], columnGroups$1, true), rows2, true);
return fromRowsOrColGroups(elems, getParentSection);
};
var fromPastedRows = function(elems, section2) {
return fromRowsOrColGroups(elems, function() {
return section2;
});
};
var addCells = function(gridRow, index2, cells2) {
var existingCells = gridRow.cells;
var before2 = existingCells.slice(0, index2);
var after2 = existingCells.slice(index2);
var newCells = before2.concat(cells2).concat(after2);
return setCells(gridRow, newCells);
};
var addCell = function(gridRow, index2, cell2) {
return addCells(gridRow, index2, [cell2]);
};
var mutateCell = function(gridRow, index2, cell2) {
var cells2 = gridRow.cells;
cells2[index2] = cell2;
};
var setCells = function(gridRow, cells2) {
return rowcells(gridRow.element, cells2, gridRow.section, gridRow.isNew);
};
var mapCells = function(gridRow, f2) {
var cells2 = gridRow.cells;
var r3 = map$1(cells2, f2);
return rowcells(gridRow.element, r3, gridRow.section, gridRow.isNew);
};
var getCell = function(gridRow, index2) {
return gridRow.cells[index2];
};
var getCellElement = function(gridRow, index2) {
return getCell(gridRow, index2).element;
};
var cellLength = function(gridRow) {
return gridRow.cells.length;
};
var extractGridDetails = function(grid2) {
var result = partition2(grid2, function(row2) {
return row2.section === "colgroup";
});
return {
rows: result.fail,
cols: result.pass
};
};
var clone$12 = function(gridRow, cloneRow2, cloneCell) {
var newCells = map$1(gridRow.cells, cloneCell);
return rowcells(cloneRow2(gridRow.element), newCells, gridRow.section, true);
};
var LOCKED_COL_ATTR = "data-snooker-locked-cols";
var getLockedColumnsFromTable = function(table3) {
return getOpt(table3, LOCKED_COL_ATTR).bind(function(lockedColStr) {
return Optional.from(lockedColStr.match(/\d+/g));
}).map(function(lockedCols) {
return mapToObject(lockedCols, always);
});
};
var getLockedColumnsFromGrid = function(grid2) {
var locked = foldl(extractGridDetails(grid2).rows, function(acc, row2) {
each$2(row2.cells, function(cell2, idx) {
if (cell2.isLocked) {
acc[idx] = true;
}
});
return acc;
}, {});
var lockedArr = mapToArray2(locked, function(_val, key3) {
return parseInt(key3, 10);
});
return sort$1(lockedArr);
};
var key2 = function(row2, column) {
return row2 + "," + column;
};
var getAt = function(warehouse, row2, column) {
return Optional.from(warehouse.access[key2(row2, column)]);
};
var findItem = function(warehouse, item, comparator) {
var filtered = filterItems(warehouse, function(detail2) {
return comparator(item, detail2.element);
});
return filtered.length > 0 ? Optional.some(filtered[0]) : Optional.none();
};
var filterItems = function(warehouse, predicate) {
var all3 = bind$22(warehouse.all, function(r3) {
return r3.cells;
});
return filter$2(all3, predicate);
};
var generateColumns = function(rowData) {
var columnsGroup = {};
var index2 = 0;
each$2(rowData.cells, function(column) {
var colspan = column.colspan;
range$1(colspan, function(columnIndex) {
var colIndex = index2 + columnIndex;
columnsGroup[colIndex] = columnext(column.element, colspan, colIndex);
});
index2 += colspan;
});
return columnsGroup;
};
var generate$12 = function(list) {
var access = {};
var cells2 = [];
var tableOpt = head(list).map(function(rowData) {
return rowData.element;
}).bind(table2);
var lockedColumns = tableOpt.bind(getLockedColumnsFromTable).getOr({});
var maxRows = 0;
var maxColumns = 0;
var rowCount = 0;
var _a3 = partition2(list, function(rowData) {
return rowData.section === "colgroup";
}), colgroupRows = _a3.pass, rows2 = _a3.fail;
each$2(rows2, function(rowData) {
var currentRow = [];
each$2(rowData.cells, function(rowCell) {
var start = 0;
while (access[key2(rowCount, start)] !== void 0) {
start++;
}
var isLocked = hasNonNullableKey(lockedColumns, start.toString());
var current2 = extended(rowCell.element, rowCell.rowspan, rowCell.colspan, rowCount, start, isLocked);
for (var occupiedColumnPosition = 0; occupiedColumnPosition < rowCell.colspan; occupiedColumnPosition++) {
for (var occupiedRowPosition = 0; occupiedRowPosition < rowCell.rowspan; occupiedRowPosition++) {
var rowPosition = rowCount + occupiedRowPosition;
var columnPosition = start + occupiedColumnPosition;
var newpos = key2(rowPosition, columnPosition);
access[newpos] = current2;
maxColumns = Math.max(maxColumns, columnPosition + 1);
}
}
currentRow.push(current2);
});
maxRows++;
cells2.push(rowdetail(rowData.element, currentRow, rowData.section));
rowCount++;
});
var _b2 = last$2(colgroupRows).map(function(rowData) {
var columns4 = generateColumns(rowData);
var colgroup$1 = colgroup(rowData.element, values2(columns4));
return {
colgroups: [colgroup$1],
columns: columns4
};
}).getOrThunk(function() {
return {
colgroups: [],
columns: {}
};
}), columns3 = _b2.columns, colgroups = _b2.colgroups;
var grid$1 = grid(maxRows, maxColumns);
return {
grid: grid$1,
access,
all: cells2,
columns: columns3,
colgroups
};
};
var fromTable = function(table3) {
var list = fromTable$1(table3);
return generate$12(list);
};
var justCells = function(warehouse) {
return bind$22(warehouse.all, function(w2) {
return w2.cells;
});
};
var justColumns = function(warehouse) {
return values2(warehouse.columns);
};
var hasColumns = function(warehouse) {
return keys2(warehouse.columns).length > 0;
};
var getColumnAt = function(warehouse, columnIndex) {
return Optional.from(warehouse.columns[columnIndex]);
};
var Warehouse = {
fromTable,
generate: generate$12,
getAt,
findItem,
filterItems,
justCells,
justColumns,
hasColumns,
getColumnAt
};
var inSelection = function(bounds2, detail2) {
var leftEdge = detail2.column;
var rightEdge = detail2.column + detail2.colspan - 1;
var topEdge = detail2.row;
var bottomEdge = detail2.row + detail2.rowspan - 1;
return leftEdge <= bounds2.finishCol && rightEdge >= bounds2.startCol && (topEdge <= bounds2.finishRow && bottomEdge >= bounds2.startRow);
};
var isWithin = function(bounds2, detail2) {
return detail2.column >= bounds2.startCol && detail2.column + detail2.colspan - 1 <= bounds2.finishCol && detail2.row >= bounds2.startRow && detail2.row + detail2.rowspan - 1 <= bounds2.finishRow;
};
var isRectangular = function(warehouse, bounds2) {
var isRect = true;
var detailIsWithin = curry(isWithin, bounds2);
for (var i2 = bounds2.startRow; i2 <= bounds2.finishRow; i2++) {
for (var j2 = bounds2.startCol; j2 <= bounds2.finishCol; j2++) {
isRect = isRect && Warehouse.getAt(warehouse, i2, j2).exists(detailIsWithin);
}
}
return isRect ? Optional.some(bounds2) : Optional.none();
};
var getBounds = function(detailA, detailB) {
return bounds(Math.min(detailA.row, detailB.row), Math.min(detailA.column, detailB.column), Math.max(detailA.row + detailA.rowspan - 1, detailB.row + detailB.rowspan - 1), Math.max(detailA.column + detailA.colspan - 1, detailB.column + detailB.colspan - 1));
};
var getAnyBox = function(warehouse, startCell, finishCell) {
var startCoords = Warehouse.findItem(warehouse, startCell, eq$1);
var finishCoords = Warehouse.findItem(warehouse, finishCell, eq$1);
return startCoords.bind(function(sc) {
return finishCoords.map(function(fc) {
return getBounds(sc, fc);
});
});
};
var getBox$1 = function(warehouse, startCell, finishCell) {
return getAnyBox(warehouse, startCell, finishCell).bind(function(bounds2) {
return isRectangular(warehouse, bounds2);
});
};
var moveBy$1 = function(warehouse, cell2, row2, column) {
return Warehouse.findItem(warehouse, cell2, eq$1).bind(function(detail2) {
var startRow = row2 > 0 ? detail2.row + detail2.rowspan - 1 : detail2.row;
var startCol = column > 0 ? detail2.column + detail2.colspan - 1 : detail2.column;
var dest = Warehouse.getAt(warehouse, startRow + row2, startCol + column);
return dest.map(function(d2) {
return d2.element;
});
});
};
var intercepts$1 = function(warehouse, start, finish) {
return getAnyBox(warehouse, start, finish).map(function(bounds2) {
var inside = Warehouse.filterItems(warehouse, curry(inSelection, bounds2));
return map$1(inside, function(detail2) {
return detail2.element;
});
});
};
var parentCell = function(warehouse, innerCell) {
var isContainedBy = function(c1, c2) {
return contains2(c2, c1);
};
return Warehouse.findItem(warehouse, innerCell, isContainedBy).map(function(detail2) {
return detail2.element;
});
};
var moveBy = function(cell2, deltaRow, deltaColumn) {
return table2(cell2).bind(function(table3) {
var warehouse = getWarehouse(table3);
return moveBy$1(warehouse, cell2, deltaRow, deltaColumn);
});
};
var intercepts = function(table3, first2, last3) {
var warehouse = getWarehouse(table3);
return intercepts$1(warehouse, first2, last3);
};
var nestedIntercepts = function(table3, first2, firstTable, last3, lastTable) {
var warehouse = getWarehouse(table3);
var optStartCell = eq$1(table3, firstTable) ? Optional.some(first2) : parentCell(warehouse, first2);
var optLastCell = eq$1(table3, lastTable) ? Optional.some(last3) : parentCell(warehouse, last3);
return optStartCell.bind(function(startCell) {
return optLastCell.bind(function(lastCell) {
return intercepts$1(warehouse, startCell, lastCell);
});
});
};
var getBox = function(table3, first2, last3) {
var warehouse = getWarehouse(table3);
return getBox$1(warehouse, first2, last3);
};
var getWarehouse = Warehouse.fromTable;
var before$4 = function(marker, element) {
var parent$1 = parent2(marker);
parent$1.each(function(v2) {
v2.dom.insertBefore(element.dom, marker.dom);
});
};
var after$5 = function(marker, element) {
var sibling = nextSibling(marker);
sibling.fold(function() {
var parent$1 = parent2(marker);
parent$1.each(function(v2) {
append$1(v2, element);
});
}, function(v2) {
before$4(v2, element);
});
};
var prepend = function(parent3, element) {
var firstChild$1 = firstChild(parent3);
firstChild$1.fold(function() {
append$1(parent3, element);
}, function(v2) {
parent3.dom.insertBefore(element.dom, v2.dom);
});
};
var append$1 = function(parent3, element) {
parent3.dom.appendChild(element.dom);
};
var appendAt = function(parent3, element, index2) {
child$3(parent3, index2).fold(function() {
append$1(parent3, element);
}, function(v2) {
before$4(v2, element);
});
};
var wrap = function(element, wrapper) {
before$4(element, wrapper);
append$1(wrapper, element);
};
var before$3 = function(marker, elements) {
each$2(elements, function(x2) {
before$4(marker, x2);
});
};
var after$4 = function(marker, elements) {
each$2(elements, function(x2, i2) {
var e2 = i2 === 0 ? marker : elements[i2 - 1];
after$5(e2, x2);
});
};
var append = function(parent3, elements) {
each$2(elements, function(x2) {
append$1(parent3, x2);
});
};
var empty2 = function(element) {
element.dom.textContent = "";
each$2(children$3(element), function(rogue) {
remove$5(rogue);
});
};
var remove$5 = function(element) {
var dom = element.dom;
if (dom.parentNode !== null) {
dom.parentNode.removeChild(dom);
}
};
var unwrap = function(wrapper) {
var children2 = children$3(wrapper);
if (children2.length > 0) {
before$3(wrapper, children2);
}
remove$5(wrapper);
};
var NodeValue = function(is3, name2) {
var get3 = function(element) {
if (!is3(element)) {
throw new Error("Can only get " + name2 + " value of a " + name2 + " node");
}
return getOption3(element).getOr("");
};
var getOption3 = function(element) {
return is3(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
};
var set3 = function(element, value25) {
if (!is3(element)) {
throw new Error("Can only set raw " + name2 + " value of a " + name2 + " node");
}
element.dom.nodeValue = value25;
};
return {
get: get3,
getOption: getOption3,
set: set3
};
};
var api$2 = NodeValue(isText, "text");
var get$9 = function(element) {
return api$2.get(element);
};
var getOption2 = function(element) {
return api$2.getOption(element);
};
var set2 = function(element, value25) {
return api$2.set(element, value25);
};
var TagBoundaries = [
"body",
"p",
"div",
"article",
"aside",
"figcaption",
"figure",
"footer",
"header",
"nav",
"section",
"ol",
"ul",
"li",
"table",
"thead",
"tbody",
"tfoot",
"caption",
"tr",
"td",
"th",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"blockquote",
"pre",
"address"
];
function DomUniverse() {
var clone5 = function(element) {
return SugarElement.fromDom(element.dom.cloneNode(false));
};
var document2 = function(element) {
return documentOrOwner(element).dom;
};
var isBoundary = function(element) {
if (!isElement2(element)) {
return false;
}
if (name(element) === "body") {
return true;
}
return contains$2(TagBoundaries, name(element));
};
var isEmptyTag2 = function(element) {
if (!isElement2(element)) {
return false;
}
return contains$2([
"br",
"img",
"hr",
"input"
], name(element));
};
var isNonEditable = function(element) {
return isElement2(element) && get$b(element, "contenteditable") === "false";
};
var comparePosition = function(element, other) {
return element.dom.compareDocumentPosition(other.dom);
};
var copyAttributesTo = function(source2, destination) {
var as2 = clone$2(source2);
setAll$1(destination, as2);
};
var isSpecial = function(element) {
var tag = name(element);
return contains$2([
"script",
"noscript",
"iframe",
"noframes",
"noembed",
"title",
"style",
"textarea",
"xmp"
], tag);
};
var getLanguage = function(element) {
return isElement2(element) ? getOpt(element, "lang") : Optional.none();
};
return {
up: constant2({
selector: ancestor$1,
closest: closest$1,
predicate: ancestor$2,
all: parents
}),
down: constant2({
selector: descendants,
predicate: descendants$1
}),
styles: constant2({
get: get$a,
getRaw: getRaw$2,
set: set$12,
remove: remove$6
}),
attrs: constant2({
get: get$b,
set: set$2,
remove: remove$7,
copyTo: copyAttributesTo
}),
insert: constant2({
before: before$4,
after: after$5,
afterAll: after$4,
append: append$1,
appendAll: append,
prepend,
wrap
}),
remove: constant2({
unwrap,
remove: remove$5
}),
create: constant2({
nu: SugarElement.fromTag,
clone: clone5,
text: SugarElement.fromText
}),
query: constant2({
comparePosition,
prevSibling,
nextSibling
}),
property: constant2({
children: children$3,
name,
parent: parent2,
document: document2,
isText,
isComment,
isElement: isElement2,
isSpecial,
getLanguage,
getText: get$9,
setText: set2,
isBoundary,
isEmptyTag: isEmptyTag2,
isNonEditable
}),
eq: eq$1,
is: is$1
};
}
var all2 = function(universe2, look, elements, f2) {
var head2 = elements[0];
var tail = elements.slice(1);
return f2(universe2, look, head2, tail);
};
var oneAll = function(universe2, look, elements) {
return elements.length > 0 ? all2(universe2, look, elements, unsafeOne) : Optional.none();
};
var unsafeOne = function(universe2, look, head2, tail) {
var start = look(universe2, head2);
return foldr(tail, function(b2, a2) {
var current2 = look(universe2, a2);
return commonElement(universe2, b2, current2);
}, start);
};
var commonElement = function(universe2, start, end) {
return start.bind(function(s2) {
return end.filter(curry(universe2.eq, s2));
});
};
var eq2 = function(universe2, item) {
return curry(universe2.eq, item);
};
var ancestors$2 = function(universe2, start, end, isRoot) {
if (isRoot === void 0) {
isRoot = never;
}
var ps1 = [start].concat(universe2.up().all(start));
var ps2 = [end].concat(universe2.up().all(end));
var prune2 = function(path2) {
var index2 = findIndex2(path2, isRoot);
return index2.fold(function() {
return path2;
}, function(ind) {
return path2.slice(0, ind + 1);
});
};
var pruned1 = prune2(ps1);
var pruned2 = prune2(ps2);
var shared = find$12(pruned1, function(x2) {
return exists(pruned2, eq2(universe2, x2));
});
return {
firstpath: pruned1,
secondpath: pruned2,
shared
};
};
var sharedOne$1 = oneAll;
var ancestors$1 = ancestors$2;
var universe$3 = DomUniverse();
var sharedOne = function(look, elements) {
return sharedOne$1(universe$3, function(_universe, element) {
return look(element);
}, elements);
};
var ancestors = function(start, finish, isRoot) {
return ancestors$1(universe$3, start, finish, isRoot);
};
var lookupTable = function(container) {
return ancestor$1(container, "table");
};
var identify = function(start, finish, isRoot) {
var getIsRoot2 = function(rootTable) {
return function(element) {
return isRoot !== void 0 && isRoot(element) || eq$1(element, rootTable);
};
};
if (eq$1(start, finish)) {
return Optional.some({
boxes: Optional.some([start]),
start,
finish
});
} else {
return lookupTable(start).bind(function(startTable) {
return lookupTable(finish).bind(function(finishTable) {
if (eq$1(startTable, finishTable)) {
return Optional.some({
boxes: intercepts(startTable, start, finish),
start,
finish
});
} else if (contains2(startTable, finishTable)) {
var ancestorCells = ancestors$3(finish, "td,th", getIsRoot2(startTable));
var finishCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : finish;
return Optional.some({
boxes: nestedIntercepts(startTable, start, startTable, finish, finishTable),
start,
finish: finishCell
});
} else if (contains2(finishTable, startTable)) {
var ancestorCells = ancestors$3(start, "td,th", getIsRoot2(finishTable));
var startCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : start;
return Optional.some({
boxes: nestedIntercepts(finishTable, start, startTable, finish, finishTable),
start,
finish: startCell
});
} else {
return ancestors(start, finish).shared.bind(function(lca) {
return closest$1(lca, "table", isRoot).bind(function(lcaTable) {
var finishAncestorCells = ancestors$3(finish, "td,th", getIsRoot2(lcaTable));
var finishCell2 = finishAncestorCells.length > 0 ? finishAncestorCells[finishAncestorCells.length - 1] : finish;
var startAncestorCells = ancestors$3(start, "td,th", getIsRoot2(lcaTable));
var startCell2 = startAncestorCells.length > 0 ? startAncestorCells[startAncestorCells.length - 1] : start;
return Optional.some({
boxes: nestedIntercepts(lcaTable, start, startTable, finish, finishTable),
start: startCell2,
finish: finishCell2
});
});
});
}
});
});
}
};
var retrieve$1 = function(container, selector2) {
var sels = descendants(container, selector2);
return sels.length > 0 ? Optional.some(sels) : Optional.none();
};
var getLast = function(boxes, lastSelectedSelector) {
return find$12(boxes, function(box) {
return is$2(box, lastSelectedSelector);
});
};
var getEdges = function(container, firstSelectedSelector, lastSelectedSelector) {
return descendant(container, firstSelectedSelector).bind(function(first2) {
return descendant(container, lastSelectedSelector).bind(function(last3) {
return sharedOne(lookupTable, [
first2,
last3
]).map(function(table3) {
return {
first: first2,
last: last3,
table: table3
};
});
});
});
};
var expandTo = function(finish, firstSelectedSelector) {
return ancestor$1(finish, "table").bind(function(table3) {
return descendant(table3, firstSelectedSelector).bind(function(start) {
return identify(start, finish).bind(function(identified) {
return identified.boxes.map(function(boxes) {
return {
boxes,
start: identified.start,
finish: identified.finish
};
});
});
});
});
};
var shiftSelection = function(boxes, deltaRow, deltaColumn, firstSelectedSelector, lastSelectedSelector) {
return getLast(boxes, lastSelectedSelector).bind(function(last3) {
return moveBy(last3, deltaRow, deltaColumn).bind(function(finish) {
return expandTo(finish, firstSelectedSelector);
});
});
};
var retrieve = function(container, selector2) {
return retrieve$1(container, selector2);
};
var retrieveBox = function(container, firstSelectedSelector, lastSelectedSelector) {
return getEdges(container, firstSelectedSelector, lastSelectedSelector).bind(function(edges) {
var isRoot = function(ancestor2) {
return eq$1(container, ancestor2);
};
var sectionSelector = "thead,tfoot,tbody,table";
var firstAncestor = ancestor$1(edges.first, sectionSelector, isRoot);
var lastAncestor = ancestor$1(edges.last, sectionSelector, isRoot);
return firstAncestor.bind(function(fA) {
return lastAncestor.bind(function(lA) {
return eq$1(fA, lA) ? getBox(edges.table, edges.first, edges.last) : Optional.none();
});
});
});
};
var generate2 = function(cases) {
if (!isArray2(cases)) {
throw new Error("cases must be an array");
}
if (cases.length === 0) {
throw new Error("there must be at least one case");
}
var constructors = [];
var adt2 = {};
each$2(cases, function(acase, count2) {
var keys$12 = keys2(acase);
if (keys$12.length !== 1) {
throw new Error("one and only one name per case");
}
var key3 = keys$12[0];
var value25 = acase[key3];
if (adt2[key3] !== void 0) {
throw new Error("duplicate key detected:" + key3);
} else if (key3 === "cata") {
throw new Error("cannot have a case named cata (sorry)");
} else if (!isArray2(value25)) {
throw new Error("case arguments must be an array");
}
constructors.push(key3);
adt2[key3] = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var argLength = args.length;
if (argLength !== value25.length) {
throw new Error("Wrong number of arguments to case " + key3 + ". Expected " + value25.length + " (" + value25 + "), got " + argLength);
}
var match5 = function(branches) {
var branchKeys = keys2(branches);
if (constructors.length !== branchKeys.length) {
throw new Error("Wrong number of arguments to match. Expected: " + constructors.join(",") + "\nActual: " + branchKeys.join(","));
}
var allReqd = forall(constructors, function(reqKey) {
return contains$2(branchKeys, reqKey);
});
if (!allReqd) {
throw new Error("Not all branches were specified when using match. Specified: " + branchKeys.join(", ") + "\nRequired: " + constructors.join(", "));
}
return branches[key3].apply(null, args);
};
return {
fold: function() {
var foldArgs = [];
for (var _i2 = 0; _i2 < arguments.length; _i2++) {
foldArgs[_i2] = arguments[_i2];
}
if (foldArgs.length !== cases.length) {
throw new Error("Wrong number of arguments to fold. Expected " + cases.length + ", got " + foldArgs.length);
}
var target = foldArgs[count2];
return target.apply(null, args);
},
match: match5,
log: function(label) {
console.log(label, {
constructors,
constructor: key3,
params: args
});
}
};
};
});
return adt2;
};
var Adt = { generate: generate2 };
var type2 = Adt.generate([
{ none: [] },
{ multiple: ["elements"] },
{ single: ["element"] }
]);
var cata$2 = function(subject, onNone, onMultiple, onSingle) {
return subject.fold(onNone, onMultiple, onSingle);
};
var none$1 = type2.none;
var multiple = type2.multiple;
var single = type2.single;
var Selections = function(lazyRoot, getStart2, selectedSelector) {
var get3 = function() {
return retrieve(lazyRoot(), selectedSelector).fold(function() {
return getStart2().fold(none$1, single);
}, function(cells2) {
return multiple(cells2);
});
};
return { get: get3 };
};
var global$3 = tinymce.util.Tools.resolve("tinymce.PluginManager");
var clone4 = function(original, isDeep) {
return SugarElement.fromDom(original.dom.cloneNode(isDeep));
};
var shallow = function(original) {
return clone4(original, false);
};
var deep = function(original) {
return clone4(original, true);
};
var shallowAs = function(original, tag) {
var nu2 = SugarElement.fromTag(tag);
var attributes2 = clone$2(original);
setAll$1(nu2, attributes2);
return nu2;
};
var copy$1 = function(original, tag) {
var nu2 = shallowAs(original, tag);
var cloneChildren = children$3(deep(original));
append(nu2, cloneChildren);
return nu2;
};
var mutate$1 = function(original, tag) {
var nu2 = shallowAs(original, tag);
before$4(original, nu2);
var children2 = children$3(original);
append(nu2, children2);
remove$5(original);
return nu2;
};
var Dimension = function(name2, getOffset2) {
var set3 = function(element, h2) {
if (!isNumber2(h2) && !h2.match(/^[0-9]+$/)) {
throw new Error(name2 + ".set accepts only positive integer values. Value was " + h2);
}
var dom = element.dom;
if (isSupported(dom)) {
dom.style[name2] = h2 + "px";
}
};
var get3 = function(element) {
var r3 = getOffset2(element);
if (r3 <= 0 || r3 === null) {
var css3 = get$a(element, name2);
return parseFloat(css3) || 0;
}
return r3;
};
var getOuter2 = get3;
var aggregate = function(element, properties) {
return foldl(properties, function(acc, property2) {
var val = get$a(element, property2);
var value25 = val === void 0 ? 0 : parseInt(val, 10);
return isNaN(value25) ? acc : acc + value25;
}, 0);
};
var max4 = function(element, value25, properties) {
var cumulativeInclusions = aggregate(element, properties);
var absoluteMax = value25 > cumulativeInclusions ? value25 - cumulativeInclusions : 0;
return absoluteMax;
};
return {
set: set3,
get: get3,
getOuter: getOuter2,
aggregate,
max: max4
};
};
var needManualCalc = function() {
var browser = detect$3().browser;
return browser.isIE() || browser.isEdge();
};
var toNumber3 = function(px, fallback2) {
return toFloat2(px).getOr(fallback2);
};
var getProp = function(element, name2, fallback2) {
return toNumber3(get$a(element, name2), fallback2);
};
var getBoxSizing = function(element) {
return get$a(element, "box-sizing");
};
var calcContentBoxSize = function(element, size2, upper, lower) {
var paddingUpper = getProp(element, "padding-" + upper, 0);
var paddingLower = getProp(element, "padding-" + lower, 0);
var borderUpper = getProp(element, "border-" + upper + "-width", 0);
var borderLower = getProp(element, "border-" + lower + "-width", 0);
return size2 - paddingUpper - paddingLower - borderUpper - borderLower;
};
var getCalculatedHeight = function(element, boxSizing) {
var dom = element.dom;
var height2 = dom.getBoundingClientRect().height || dom.offsetHeight;
return boxSizing === "border-box" ? height2 : calcContentBoxSize(element, height2, "top", "bottom");
};
var getCalculatedWidth = function(element, boxSizing) {
var dom = element.dom;
var width2 = dom.getBoundingClientRect().width || dom.offsetWidth;
return boxSizing === "border-box" ? width2 : calcContentBoxSize(element, width2, "left", "right");
};
var getHeight$1 = function(element) {
return needManualCalc() ? getCalculatedHeight(element, getBoxSizing(element)) : getProp(element, "height", element.dom.offsetHeight);
};
var getWidth = function(element) {
return needManualCalc() ? getCalculatedWidth(element, getBoxSizing(element)) : getProp(element, "width", element.dom.offsetWidth);
};
var getInnerWidth = function(element) {
return getCalculatedWidth(element, "content-box");
};
var api$12 = Dimension("width", function(element) {
return element.dom.offsetWidth;
});
var get$8 = function(element) {
return api$12.get(element);
};
var getOuter$2 = function(element) {
return api$12.getOuter(element);
};
var getInner = getInnerWidth;
var getRuntime$1 = getWidth;
var columns2 = function(warehouse, isValidCell) {
if (isValidCell === void 0) {
isValidCell = always;
}
var grid2 = warehouse.grid;
var cols = range$1(grid2.columns, identity2);
var rowsArr = range$1(grid2.rows, identity2);
return map$1(cols, function(col2) {
var getBlock = function() {
return bind$22(rowsArr, function(r3) {
return Warehouse.getAt(warehouse, r3, col2).filter(function(detail2) {
return detail2.column === col2;
}).toArray();
});
};
var isValid4 = function(detail2) {
return detail2.colspan === 1 && isValidCell(detail2.element);
};
var getFallback = function() {
return Warehouse.getAt(warehouse, 0, col2);
};
return decide(getBlock, isValid4, getFallback);
});
};
var decide = function(getBlock, isValid4, getFallback) {
var inBlock = getBlock();
var validInBlock = find$12(inBlock, isValid4);
var detailOption = validInBlock.orThunk(function() {
return Optional.from(inBlock[0]).orThunk(getFallback);
});
return detailOption.map(function(detail2) {
return detail2.element;
});
};
var rows = function(warehouse) {
var grid2 = warehouse.grid;
var rowsArr = range$1(grid2.rows, identity2);
var cols = range$1(grid2.columns, identity2);
return map$1(rowsArr, function(row2) {
var getBlock = function() {
return bind$22(cols, function(c2) {
return Warehouse.getAt(warehouse, row2, c2).filter(function(detail2) {
return detail2.row === row2;
}).fold(constant2([]), function(detail2) {
return [detail2];
});
});
};
var isSingle = function(detail2) {
return detail2.rowspan === 1;
};
var getFallback = function() {
return Warehouse.getAt(warehouse, row2, 0);
};
return decide(getBlock, isSingle, getFallback);
});
};
var deduce = function(xs, index2) {
if (index2 < 0 || index2 >= xs.length - 1) {
return Optional.none();
}
var current2 = xs[index2].fold(function() {
var rest = reverse(xs.slice(0, index2));
return findMap(rest, function(a2, i2) {
return a2.map(function(aa) {
return {
value: aa,
delta: i2 + 1
};
});
});
}, function(c2) {
return Optional.some({
value: c2,
delta: 0
});
});
var next3 = xs[index2 + 1].fold(function() {
var rest = xs.slice(index2 + 1);
return findMap(rest, function(a2, i2) {
return a2.map(function(aa) {
return {
value: aa,
delta: i2 + 1
};
});
});
}, function(n2) {
return Optional.some({
value: n2,
delta: 1
});
});
return current2.bind(function(c2) {
return next3.map(function(n2) {
var extras = n2.delta + c2.delta;
return Math.abs(n2.value - c2.value) / extras;
});
});
};
var onDirection = function(isLtr, isRtl) {
return function(element) {
return getDirection(element) === "rtl" ? isRtl : isLtr;
};
};
var getDirection = function(element) {
return get$a(element, "direction") === "rtl" ? "rtl" : "ltr";
};
var api2 = Dimension("height", function(element) {
var dom = element.dom;
return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
});
var get$7 = function(element) {
return api2.get(element);
};
var getOuter$1 = function(element) {
return api2.getOuter(element);
};
var getRuntime = getHeight$1;
var r2 = function(left2, top) {
var translate2 = function(x2, y2) {
return r2(left2 + x2, top + y2);
};
return {
left: left2,
top,
translate: translate2
};
};
var SugarPosition = r2;
var boxPosition = function(dom) {
var box = dom.getBoundingClientRect();
return SugarPosition(box.left, box.top);
};
var firstDefinedOrZero = function(a2, b2) {
if (a2 !== void 0) {
return a2;
} else {
return b2 !== void 0 ? b2 : 0;
}
};
var absolute = function(element) {
var doc = element.dom.ownerDocument;
var body2 = doc.body;
var win = doc.defaultView;
var html = doc.documentElement;
if (body2 === element.dom) {
return SugarPosition(body2.offsetLeft, body2.offsetTop);
}
var scrollTop2 = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
var scrollLeft2 = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
var clientTop = firstDefinedOrZero(html.clientTop, body2.clientTop);
var clientLeft = firstDefinedOrZero(html.clientLeft, body2.clientLeft);
return viewport(element).translate(scrollLeft2 - clientLeft, scrollTop2 - clientTop);
};
var viewport = function(element) {
var dom = element.dom;
var doc = dom.ownerDocument;
var body2 = doc.body;
if (body2 === dom) {
return SugarPosition(body2.offsetLeft, body2.offsetTop);
}
if (!inBody(element)) {
return SugarPosition(0, 0);
}
return boxPosition(dom);
};
var rowInfo = function(row2, y2) {
return {
row: row2,
y: y2
};
};
var colInfo = function(col2, x2) {
return {
col: col2,
x: x2
};
};
var rtlEdge = function(cell2) {
var pos = absolute(cell2);
return pos.left + getOuter$2(cell2);
};
var ltrEdge = function(cell2) {
return absolute(cell2).left;
};
var getLeftEdge = function(index2, cell2) {
return colInfo(index2, ltrEdge(cell2));
};
var getRightEdge = function(index2, cell2) {
return colInfo(index2, rtlEdge(cell2));
};
var getTop$1 = function(cell2) {
return absolute(cell2).top;
};
var getTopEdge = function(index2, cell2) {
return rowInfo(index2, getTop$1(cell2));
};
var getBottomEdge = function(index2, cell2) {
return rowInfo(index2, getTop$1(cell2) + getOuter$1(cell2));
};
var findPositions = function(getInnerEdge, getOuterEdge, array3) {
if (array3.length === 0) {
return [];
}
var lines = map$1(array3.slice(1), function(cellOption, index2) {
return cellOption.map(function(cell2) {
return getInnerEdge(index2, cell2);
});
});
var lastLine = array3[array3.length - 1].map(function(cell2) {
return getOuterEdge(array3.length - 1, cell2);
});
return lines.concat([lastLine]);
};
var negate = function(step) {
return -step;
};
var height = {
delta: identity2,
positions: function(optElements) {
return findPositions(getTopEdge, getBottomEdge, optElements);
},
edge: getTop$1
};
var ltr$1 = {
delta: identity2,
edge: ltrEdge,
positions: function(optElements) {
return findPositions(getLeftEdge, getRightEdge, optElements);
}
};
var rtl$1 = {
delta: negate,
edge: rtlEdge,
positions: function(optElements) {
return findPositions(getRightEdge, getLeftEdge, optElements);
}
};
var detect$2 = onDirection(ltr$1, rtl$1);
var width = {
delta: function(amount, table3) {
return detect$2(table3).delta(amount, table3);
},
positions: function(cols, table3) {
return detect$2(table3).positions(cols, table3);
},
edge: function(cell2) {
return detect$2(cell2).edge(cell2);
}
};
var units = {
unsupportedLength: [
"em",
"ex",
"cap",
"ch",
"ic",
"rem",
"lh",
"rlh",
"vw",
"vh",
"vi",
"vb",
"vmin",
"vmax",
"cm",
"mm",
"Q",
"in",
"pc",
"pt",
"px"
],
fixed: [
"px",
"pt"
],
relative: ["%"],
empty: [""]
};
var pattern2 = function() {
var decimalDigits = "[0-9]+";
var signedInteger = "[+-]?" + decimalDigits;
var exponentPart = "[eE]" + signedInteger;
var dot = "\\.";
var opt = function(input) {
return "(?:" + input + ")?";
};
var unsignedDecimalLiteral = [
"Infinity",
decimalDigits + dot + opt(decimalDigits) + opt(exponentPart),
dot + decimalDigits + opt(exponentPart),
decimalDigits + opt(exponentPart)
].join("|");
var float2 = "[+-]?(?:" + unsignedDecimalLiteral + ")";
return new RegExp("^(" + float2 + ")(.*)$");
}();
var isUnit = function(unit, accepted) {
return exists(accepted, function(acc) {
return exists(units[acc], function(check) {
return unit === check;
});
});
};
var parse2 = function(input, accepted) {
var match5 = Optional.from(pattern2.exec(input));
return match5.bind(function(array3) {
var value25 = Number(array3[1]);
var unitRaw = array3[2];
if (isUnit(unitRaw, accepted)) {
return Optional.some({
value: value25,
unit: unitRaw
});
} else {
return Optional.none();
}
});
};
var rPercentageBasedSizeRegex = /(\d+(\.\d+)?)%/;
var rPixelBasedSizeRegex = /(\d+(\.\d+)?)px|em/;
var isCol$2 = isTag("col");
var getPercentSize = function(elm, outerGetter, innerGetter) {
var relativeParent = parentElement(elm).getOrThunk(function() {
return getBody$1(owner(elm));
});
return outerGetter(elm) / innerGetter(relativeParent) * 100;
};
var setPixelWidth = function(cell2, amount) {
set$12(cell2, "width", amount + "px");
};
var setPercentageWidth = function(cell2, amount) {
set$12(cell2, "width", amount + "%");
};
var setHeight = function(cell2, amount) {
set$12(cell2, "height", amount + "px");
};
var getHeightValue = function(cell2) {
return getRuntime(cell2) + "px";
};
var convert = function(cell2, number3, getter, setter) {
var newSize = table2(cell2).map(function(table3) {
var total3 = getter(table3);
return Math.floor(number3 / 100 * total3);
}).getOr(number3);
setter(cell2, newSize);
return newSize;
};
var normalizePixelSize = function(value25, cell2, getter, setter) {
var number3 = parseFloat(value25);
return endsWith2(value25, "%") && name(cell2) !== "table" ? convert(cell2, number3, getter, setter) : number3;
};
var getTotalHeight = function(cell2) {
var value25 = getHeightValue(cell2);
if (!value25) {
return get$7(cell2);
}
return normalizePixelSize(value25, cell2, get$7, setHeight);
};
var get$6 = function(cell2, type3, f2) {
var v2 = f2(cell2);
var span = getSpan(cell2, type3);
return v2 / span;
};
var getRaw$1 = function(element, prop) {
return getRaw$2(element, prop).orThunk(function() {
return getOpt(element, prop).map(function(val) {
return val + "px";
});
});
};
var getRawWidth$1 = function(element) {
return getRaw$1(element, "width");
};
var getRawHeight = function(element) {
return getRaw$1(element, "height");
};
var getPercentageWidth = function(cell2) {
return getPercentSize(cell2, get$8, getInner);
};
var getPixelWidth$1 = function(cell2) {
return isCol$2(cell2) ? get$8(cell2) : getRuntime$1(cell2);
};
var getHeight = function(cell2) {
return get$6(cell2, "rowspan", getTotalHeight);
};
var getGenericWidth = function(cell2) {
var width2 = getRawWidth$1(cell2);
return width2.bind(function(w2) {
return parse2(w2, [
"fixed",
"relative",
"empty"
]);
});
};
var setGenericWidth = function(cell2, amount, unit) {
set$12(cell2, "width", amount + unit);
};
var getPixelTableWidth = function(table3) {
return get$8(table3) + "px";
};
var getPercentTableWidth = function(table3) {
return getPercentSize(table3, get$8, getInner) + "%";
};
var isPercentSizing$1 = function(table3) {
return getRawWidth$1(table3).exists(function(size2) {
return rPercentageBasedSizeRegex.test(size2);
});
};
var isPixelSizing$1 = function(table3) {
return getRawWidth$1(table3).exists(function(size2) {
return rPixelBasedSizeRegex.test(size2);
});
};
var isNoneSizing$1 = function(table3) {
return getRawWidth$1(table3).isNone();
};
var percentageBasedSizeRegex = constant2(rPercentageBasedSizeRegex);
var isCol$1 = isTag("col");
var getRawW = function(cell2) {
return getRawWidth$1(cell2).getOrThunk(function() {
return getPixelWidth$1(cell2) + "px";
});
};
var getRawH = function(cell2) {
return getRawHeight(cell2).getOrThunk(function() {
return getHeight(cell2) + "px";
});
};
var justCols = function(warehouse) {
return map$1(Warehouse.justColumns(warehouse), function(column) {
return Optional.from(column.element);
});
};
var isValidColumn = function(cell2) {
var browser = detect$3().browser;
var supportsColWidths = browser.isChrome() || browser.isFirefox();
return isCol$1(cell2) ? supportsColWidths : true;
};
var getDimension = function(cellOpt, index2, backups, filter2, getter, fallback2) {
return cellOpt.filter(filter2).fold(function() {
return fallback2(deduce(backups, index2));
}, function(cell2) {
return getter(cell2);
});
};
var getWidthFrom = function(warehouse, table3, getWidth2, fallback2) {
var columnCells = columns2(warehouse);
var columns$12 = Warehouse.hasColumns(warehouse) ? justCols(warehouse) : columnCells;
var backups = [Optional.some(width.edge(table3))].concat(map$1(width.positions(columnCells, table3), function(pos) {
return pos.map(function(p) {
return p.x;
});
}));
var colFilter = not(hasColspan);
return map$1(columns$12, function(cellOption, c2) {
return getDimension(cellOption, c2, backups, colFilter, function(column) {
if (isValidColumn(column)) {
return getWidth2(column);
} else {
var cell2 = bindFrom(columnCells[c2], identity2);
return getDimension(cell2, c2, backups, colFilter, function(cell3) {
return fallback2(Optional.some(get$8(cell3)));
}, fallback2);
}
}, fallback2);
});
};
var getDeduced = function(deduced) {
return deduced.map(function(d2) {
return d2 + "px";
}).getOr("");
};
var getRawWidths = function(warehouse, table3) {
return getWidthFrom(warehouse, table3, getRawW, getDeduced);
};
var getPercentageWidths = function(warehouse, table3, tableSize) {
return getWidthFrom(warehouse, table3, getPercentageWidth, function(deduced) {
return deduced.fold(function() {
return tableSize.minCellWidth();
}, function(cellWidth) {
return cellWidth / tableSize.pixelWidth() * 100;
});
});
};
var getPixelWidths = function(warehouse, table3, tableSize) {
return getWidthFrom(warehouse, table3, getPixelWidth$1, function(deduced) {
return deduced.getOrThunk(tableSize.minCellWidth);
});
};
var getHeightFrom = function(warehouse, table3, direction, getHeight2, fallback2) {
var rows$12 = rows(warehouse);
var backups = [Optional.some(direction.edge(table3))].concat(map$1(direction.positions(rows$12, table3), function(pos) {
return pos.map(function(p) {
return p.y;
});
}));
return map$1(rows$12, function(cellOption, c2) {
return getDimension(cellOption, c2, backups, not(hasRowspan), getHeight2, fallback2);
});
};
var getPixelHeights = function(warehouse, table3, direction) {
return getHeightFrom(warehouse, table3, direction, getHeight, function(deduced) {
return deduced.getOrThunk(minHeight);
});
};
var getRawHeights = function(warehouse, table3, direction) {
return getHeightFrom(warehouse, table3, direction, getRawH, getDeduced);
};
var widthLookup = function(table3, getter) {
return function() {
if (inBody(table3)) {
return getter(table3);
} else {
return parseFloat(getRaw$2(table3, "width").getOr("0"));
}
};
};
var noneSize = function(table3) {
var getWidth2 = widthLookup(table3, get$8);
var zero2 = constant2(0);
var getWidths = function(warehouse, tableSize) {
return getPixelWidths(warehouse, table3, tableSize);
};
return {
width: getWidth2,
pixelWidth: getWidth2,
getWidths,
getCellDelta: zero2,
singleColumnWidth: constant2([0]),
minCellWidth: zero2,
setElementWidth: noop2,
adjustTableWidth: noop2,
isRelative: true,
label: "none"
};
};
var percentageSize = function(table3) {
var getFloatWidth = widthLookup(table3, function(elem) {
return parseFloat(getPercentTableWidth(elem));
});
var getWidth2 = widthLookup(table3, get$8);
var getCellDelta = function(delta) {
return delta / getWidth2() * 100;
};
var singleColumnWidth = function(w2, _delta) {
return [100 - w2];
};
var minCellWidth = function() {
return minWidth() / getWidth2() * 100;
};
var adjustTableWidth = function(delta) {
var currentWidth = getFloatWidth();
var change = delta / 100 * currentWidth;
var newWidth = currentWidth + change;
setPercentageWidth(table3, newWidth);
};
var getWidths = function(warehouse, tableSize) {
return getPercentageWidths(warehouse, table3, tableSize);
};
return {
width: getFloatWidth,
pixelWidth: getWidth2,
getWidths,
getCellDelta,
singleColumnWidth,
minCellWidth,
setElementWidth: setPercentageWidth,
adjustTableWidth,
isRelative: true,
label: "percent"
};
};
var pixelSize = function(table3) {
var getWidth2 = widthLookup(table3, get$8);
var getCellDelta = identity2;
var singleColumnWidth = function(w2, delta) {
var newNext = Math.max(minWidth(), w2 + delta);
return [newNext - w2];
};
var adjustTableWidth = function(delta) {
var newWidth = getWidth2() + delta;
setPixelWidth(table3, newWidth);
};
var getWidths = function(warehouse, tableSize) {
return getPixelWidths(warehouse, table3, tableSize);
};
return {
width: getWidth2,
pixelWidth: getWidth2,
getWidths,
getCellDelta,
singleColumnWidth,
minCellWidth: minWidth,
setElementWidth: setPixelWidth,
adjustTableWidth,
isRelative: false,
label: "pixel"
};
};
var chooseSize = function(element, width2) {
var percentMatch = percentageBasedSizeRegex().exec(width2);
if (percentMatch !== null) {
return percentageSize(element);
} else {
return pixelSize(element);
}
};
var getTableSize = function(table3) {
var width2 = getRawWidth$1(table3);
return width2.fold(function() {
return noneSize(table3);
}, function(w2) {
return chooseSize(table3, w2);
});
};
var TableSize = {
getTableSize,
pixelSize,
percentageSize,
noneSize
};
var statsStruct = function(minRow, minCol, maxRow, maxCol, allCells, selectedCells) {
return {
minRow,
minCol,
maxRow,
maxCol,
allCells,
selectedCells
};
};
var findSelectedStats = function(house, isSelected) {
var totalColumns = house.grid.columns;
var totalRows = house.grid.rows;
var minRow = totalRows;
var minCol = totalColumns;
var maxRow = 0;
var maxCol = 0;
var allCells = [];
var selectedCells = [];
each$12(house.access, function(detail2) {
allCells.push(detail2);
if (isSelected(detail2)) {
selectedCells.push(detail2);
var startRow = detail2.row;
var endRow = startRow + detail2.rowspan - 1;
var startCol = detail2.column;
var endCol = startCol + detail2.colspan - 1;
if (startRow < minRow) {
minRow = startRow;
} else if (endRow > maxRow) {
maxRow = endRow;
}
if (startCol < minCol) {
minCol = startCol;
} else if (endCol > maxCol) {
maxCol = endCol;
}
}
});
return statsStruct(minRow, minCol, maxRow, maxCol, allCells, selectedCells);
};
var makeCell = function(list, seenSelected, rowIndex) {
var row2 = list[rowIndex].element;
var td = SugarElement.fromTag("td");
append$1(td, SugarElement.fromTag("br"));
var f2 = seenSelected ? append$1 : prepend;
f2(row2, td);
};
var fillInGaps = function(list, house, stats, isSelected) {
var totalColumns = house.grid.columns;
var totalRows = house.grid.rows;
for (var i2 = 0; i2 < totalRows; i2++) {
var seenSelected = false;
for (var j2 = 0; j2 < totalColumns; j2++) {
if (!(i2 < stats.minRow || i2 > stats.maxRow || j2 < stats.minCol || j2 > stats.maxCol)) {
var needCell = Warehouse.getAt(house, i2, j2).filter(isSelected).isNone();
if (needCell) {
makeCell(list, seenSelected, i2);
} else {
seenSelected = true;
}
}
}
}
};
var clean = function(replica, stats, house, widthDelta) {
each$12(house.columns, function(col2) {
if (col2.column < stats.minCol || col2.column > stats.maxCol) {
remove$5(col2.element);
}
});
var emptyRows = filter$2(firstLayer(replica, "tr"), function(row2) {
return row2.dom.childElementCount === 0;
});
each$2(emptyRows, remove$5);
if (stats.minCol === stats.maxCol || stats.minRow === stats.maxRow) {
each$2(firstLayer(replica, "th,td"), function(cell2) {
remove$7(cell2, "rowspan");
remove$7(cell2, "colspan");
});
}
remove$7(replica, LOCKED_COL_ATTR);
remove$7(replica, "data-snooker-col-series");
var tableSize = TableSize.getTableSize(replica);
tableSize.adjustTableWidth(widthDelta);
};
var getTableWidthDelta = function(table3, warehouse, tableSize, stats) {
if (stats.minCol === 0 && warehouse.grid.columns === stats.maxCol + 1) {
return 0;
}
var colWidths = getPixelWidths(warehouse, table3, tableSize);
var allColsWidth = foldl(colWidths, function(acc, width2) {
return acc + width2;
}, 0);
var selectedColsWidth = foldl(colWidths.slice(stats.minCol, stats.maxCol + 1), function(acc, width2) {
return acc + width2;
}, 0);
var newWidth = selectedColsWidth / allColsWidth * tableSize.pixelWidth();
var delta = newWidth - tableSize.pixelWidth();
return tableSize.getCellDelta(delta);
};
var extract$1 = function(table3, selectedSelector) {
var isSelected = function(detail2) {
return is$2(detail2.element, selectedSelector);
};
var replica = deep(table3);
var list = fromTable$1(replica);
var tableSize = TableSize.getTableSize(table3);
var replicaHouse = Warehouse.generate(list);
var replicaStats = findSelectedStats(replicaHouse, isSelected);
var selector2 = "th:not(" + selectedSelector + "),td:not(" + selectedSelector + ")";
var unselectedCells = filterFirstLayer(replica, "th,td", function(cell2) {
return is$2(cell2, selector2);
});
each$2(unselectedCells, remove$5);
fillInGaps(list, replicaHouse, replicaStats, isSelected);
var house = Warehouse.fromTable(table3);
var widthDelta = getTableWidthDelta(table3, house, tableSize, replicaStats);
clean(replica, replicaStats, replicaHouse, widthDelta);
return replica;
};
var nbsp = "\xA0";
var getEnd = function(element) {
return name(element) === "img" ? 1 : getOption2(element).fold(function() {
return children$3(element).length;
}, function(v2) {
return v2.length;
});
};
var isTextNodeWithCursorPosition = function(el) {
return getOption2(el).filter(function(text) {
return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
}).isSome();
};
var elementsWithCursorPosition = [
"img",
"br"
];
var isCursorPosition = function(elem) {
var hasCursorPosition = isTextNodeWithCursorPosition(elem);
return hasCursorPosition || contains$2(elementsWithCursorPosition, name(elem));
};
var first = function(element) {
return descendant$1(element, isCursorPosition);
};
var last$1 = function(element) {
return descendantRtl(element, isCursorPosition);
};
var descendantRtl = function(scope, predicate) {
var descend = function(element) {
var children2 = children$3(element);
for (var i2 = children2.length - 1; i2 >= 0; i2--) {
var child2 = children2[i2];
if (predicate(child2)) {
return Optional.some(child2);
}
var res = descend(child2);
if (res.isSome()) {
return res;
}
}
return Optional.none();
};
return descend(scope);
};
var transferableAttributes = {
scope: [
"row",
"col"
]
};
var createCell = function(doc) {
return function() {
var td = SugarElement.fromTag("td", doc.dom);
append$1(td, SugarElement.fromTag("br", doc.dom));
return td;
};
};
var createCol = function(doc) {
return function() {
return SugarElement.fromTag("col", doc.dom);
};
};
var createColgroup = function(doc) {
return function() {
return SugarElement.fromTag("colgroup", doc.dom);
};
};
var createRow$1 = function(doc) {
return function() {
return SugarElement.fromTag("tr", doc.dom);
};
};
var replace$1 = function(cell2, tag, attrs) {
var replica = copy$1(cell2, tag);
each$12(attrs, function(v2, k2) {
if (v2 === null) {
remove$7(replica, k2);
} else {
set$2(replica, k2, v2);
}
});
return replica;
};
var pasteReplace = function(cell2) {
return cell2;
};
var cloneFormats = function(oldCell, newCell, formats2) {
var first$1 = first(oldCell);
return first$1.map(function(firstText) {
var formatSelector = formats2.join(",");
var parents2 = ancestors$3(firstText, formatSelector, function(element) {
return eq$1(element, oldCell);
});
return foldr(parents2, function(last3, parent3) {
var clonedFormat = shallow(parent3);
remove$7(clonedFormat, "contenteditable");
append$1(last3, clonedFormat);
return clonedFormat;
}, newCell);
}).getOr(newCell);
};
var cloneAppropriateAttributes = function(original, clone5) {
each$12(transferableAttributes, function(validAttributes, attributeName) {
return getOpt(original, attributeName).filter(function(attribute) {
return contains$2(validAttributes, attribute);
}).each(function(attribute) {
return set$2(clone5, attributeName, attribute);
});
});
};
var cellOperations = function(mutate2, doc, formatsToClone) {
var cloneCss = function(prev3, clone5) {
copy$2(prev3.element, clone5);
remove$6(clone5, "height");
if (prev3.colspan !== 1) {
remove$6(clone5, "width");
}
};
var newCell = function(prev3) {
var td = SugarElement.fromTag(name(prev3.element), doc.dom);
var formats2 = formatsToClone.getOr([
"strong",
"em",
"b",
"i",
"span",
"font",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"p",
"div"
]);
var lastNode = formats2.length > 0 ? cloneFormats(prev3.element, td, formats2) : td;
append$1(lastNode, SugarElement.fromTag("br"));
cloneCss(prev3, td);
cloneAppropriateAttributes(prev3.element, td);
mutate2(prev3.element, td);
return td;
};
var newCol = function(prev3) {
var col2 = SugarElement.fromTag(name(prev3.element), doc.dom);
cloneCss(prev3, col2);
mutate2(prev3.element, col2);
return col2;
};
return {
col: newCol,
colgroup: createColgroup(doc),
row: createRow$1(doc),
cell: newCell,
replace: replace$1,
colGap: createCol(doc),
gap: createCell(doc)
};
};
var paste$1 = function(doc) {
return {
col: createCol(doc),
colgroup: createColgroup(doc),
row: createRow$1(doc),
cell: createCell(doc),
replace: pasteReplace,
colGap: createCol(doc),
gap: createCell(doc)
};
};
var fromHtml = function(html, scope) {
var doc = scope || document;
var div = doc.createElement("div");
div.innerHTML = html;
return children$3(SugarElement.fromDom(div));
};
var fromDom = function(nodes2) {
return map$1(nodes2, SugarElement.fromDom);
};
var getNodeName = function(elm) {
return elm.nodeName.toLowerCase();
};
var getBody2 = function(editor) {
return SugarElement.fromDom(editor.getBody());
};
var getPixelWidth = function(elm) {
return elm.getBoundingClientRect().width;
};
var getPixelHeight = function(elm) {
return elm.getBoundingClientRect().height;
};
var getIsRoot = function(editor) {
return function(element) {
return eq$1(element, getBody2(editor));
};
};
var removePxSuffix = function(size2) {
return size2 ? size2.replace(/px$/, "") : "";
};
var addPxSuffix = function(size2) {
return /^\d+(\.\d+)?$/.test(size2) ? size2 + "px" : size2;
};
var removeDataStyle = function(table3) {
remove$7(table3, "data-mce-style");
var removeStyleAttribute = function(element) {
return remove$7(element, "data-mce-style");
};
each$2(cells$1(table3), removeStyleAttribute);
each$2(columns$1(table3), removeStyleAttribute);
each$2(rows$1(table3), removeStyleAttribute);
};
var getRawWidth = function(editor, elm) {
var raw = editor.dom.getStyle(elm, "width") || editor.dom.getAttrib(elm, "width");
return Optional.from(raw).filter(isNotEmpty);
};
var isPercentage$1 = function(value25) {
return /^(\d+(\.\d+)?)%$/.test(value25);
};
var isPixel = function(value25) {
return /^(\d+(\.\d+)?)px$/.test(value25);
};
var getSelectionStart = function(editor) {
return SugarElement.fromDom(editor.selection.getStart());
};
var getSelectionEnd = function(editor) {
return SugarElement.fromDom(editor.selection.getEnd());
};
var selection = function(selections) {
return cata$2(selections.get(), constant2([]), identity2, pure);
};
var unmergable = function(selections) {
var hasSpan = function(elem, type3) {
return getOpt(elem, type3).exists(function(span) {
return parseInt(span, 10) > 1;
});
};
var hasRowOrColSpan = function(elem) {
return hasSpan(elem, "rowspan") || hasSpan(elem, "colspan");
};
var candidates = selection(selections);
return candidates.length > 0 && forall(candidates, hasRowOrColSpan) ? Optional.some(candidates) : Optional.none();
};
var mergable = function(table3, selections, ephemera2) {
return cata$2(selections.get(), Optional.none, function(cells2) {
if (cells2.length <= 1) {
return Optional.none();
} else {
return retrieveBox(table3, ephemera2.firstSelectedSelector, ephemera2.lastSelectedSelector).map(function(bounds2) {
return {
bounds: bounds2,
cells: cells2
};
});
}
}, Optional.none);
};
var strSelected = "data-mce-selected";
var strSelectedSelector = "td[" + strSelected + "],th[" + strSelected + "]";
var strAttributeSelector = "[" + strSelected + "]";
var strFirstSelected = "data-mce-first-selected";
var strFirstSelectedSelector = "td[" + strFirstSelected + "],th[" + strFirstSelected + "]";
var strLastSelected = "data-mce-last-selected";
var strLastSelectedSelector = "td[" + strLastSelected + "],th[" + strLastSelected + "]";
var attributeSelector = strAttributeSelector;
var ephemera = {
selected: strSelected,
selectedSelector: strSelectedSelector,
firstSelected: strFirstSelected,
firstSelectedSelector: strFirstSelectedSelector,
lastSelected: strLastSelected,
lastSelectedSelector: strLastSelectedSelector
};
var noMenu = function(cell2) {
return {
element: cell2,
mergable: Optional.none(),
unmergable: Optional.none(),
selection: [cell2]
};
};
var forMenu = function(selections, table3, cell2) {
return {
element: cell2,
mergable: mergable(table3, selections, ephemera),
unmergable: unmergable(selections),
selection: selection(selections)
};
};
var paste = function(element, clipboard, generators) {
return {
element,
clipboard,
generators
};
};
var pasteRows = function(selections, cell2, clipboard, generators) {
return {
selection: selection(selections),
clipboard,
generators
};
};
var getSelectionCellFallback = function(element) {
return table2(element).bind(function(table3) {
return retrieve(table3, ephemera.firstSelectedSelector);
}).fold(constant2(element), function(cells2) {
return cells2[0];
});
};
var getSelectionFromSelector = function(selector2) {
return function(initCell, isRoot) {
var cellName = name(initCell);
var cell2 = cellName === "col" || cellName === "colgroup" ? getSelectionCellFallback(initCell) : initCell;
return closest$1(cell2, selector2, isRoot);
};
};
var getSelectionCellOrCaption = getSelectionFromSelector("th,td,caption");
var getSelectionCell = getSelectionFromSelector("th,td");
var getCellsFromSelection = function(selections) {
return selection(selections);
};
var getRowsFromSelection = function(selected, selector2) {
var cellOpt = getSelectionCell(selected);
var rowsOpt = cellOpt.bind(function(cell2) {
return table2(cell2);
}).map(function(table3) {
return rows$1(table3);
});
return lift2(cellOpt, rowsOpt, function(cell2, rows2) {
return filter$2(rows2, function(row2) {
return exists(fromDom(row2.dom.cells), function(rowCell) {
return get$b(rowCell, selector2) === "1" || eq$1(rowCell, cell2);
});
});
}).getOr([]);
};
var extractSelected = function(cells2) {
return table2(cells2[0]).map(function(table3) {
var replica = extract$1(table3, attributeSelector);
removeDataStyle(replica);
return [replica];
});
};
var serializeElements = function(editor, elements) {
return map$1(elements, function(elm) {
return editor.selection.serializer.serialize(elm.dom, {});
}).join("");
};
var getTextContent = function(elements) {
return map$1(elements, function(element) {
return element.dom.innerText;
}).join("");
};
var registerEvents = function(editor, selections, actions) {
editor.on("BeforeGetContent", function(e2) {
var multiCellContext = function(cells2) {
e2.preventDefault();
extractSelected(cells2).each(function(elements) {
e2.content = e2.format === "text" ? getTextContent(elements) : serializeElements(editor, elements);
});
};
if (e2.selection === true) {
cata$2(selections.get(), noop2, multiCellContext, noop2);
}
});
editor.on("BeforeSetContent", function(e2) {
if (e2.selection === true && e2.paste === true) {
var selectedCells = getCellsFromSelection(selections);
head(selectedCells).each(function(cell2) {
table2(cell2).each(function(table3) {
var elements = filter$2(fromHtml(e2.content), function(content) {
return name(content) !== "meta";
});
var isTable = isTag("table");
if (elements.length === 1 && isTable(elements[0])) {
e2.preventDefault();
var doc = SugarElement.fromDom(editor.getDoc());
var generators = paste$1(doc);
var targets = paste(cell2, elements[0], generators);
actions.pasteCells(table3, targets).each(function() {
editor.focus();
});
}
});
});
}
});
};
var adt$7 = Adt.generate([
{ none: [] },
{ only: ["index"] },
{
left: [
"index",
"next"
]
},
{
middle: [
"prev",
"index",
"next"
]
},
{
right: [
"prev",
"index"
]
}
]);
var ColumnContext = __assign({}, adt$7);
var neighbours = function(input, index2) {
if (input.length === 0) {
return ColumnContext.none();
}
if (input.length === 1) {
return ColumnContext.only(0);
}
if (index2 === 0) {
return ColumnContext.left(0, 1);
}
if (index2 === input.length - 1) {
return ColumnContext.right(index2 - 1, index2);
}
if (index2 > 0 && index2 < input.length - 1) {
return ColumnContext.middle(index2 - 1, index2, index2 + 1);
}
return ColumnContext.none();
};
var determine = function(input, column, step, tableSize, resize2) {
var result = input.slice(0);
var context2 = neighbours(input, column);
var onNone = constant2(map$1(result, constant2(0)));
var onOnly = function(index2) {
return tableSize.singleColumnWidth(result[index2], step);
};
var onLeft = function(index2, next3) {
return resize2.calcLeftEdgeDeltas(result, index2, next3, step, tableSize.minCellWidth(), tableSize.isRelative);
};
var onMiddle = function(prev3, index2, next3) {
return resize2.calcMiddleDeltas(result, prev3, index2, next3, step, tableSize.minCellWidth(), tableSize.isRelative);
};
var onRight = function(prev3, index2) {
return resize2.calcRightEdgeDeltas(result, prev3, index2, step, tableSize.minCellWidth(), tableSize.isRelative);
};
return context2.fold(onNone, onOnly, onLeft, onMiddle, onRight);
};
var total2 = function(start, end, measures) {
var r3 = 0;
for (var i2 = start; i2 < end; i2++) {
r3 += measures[i2] !== void 0 ? measures[i2] : 0;
}
return r3;
};
var recalculateWidthForCells = function(warehouse, widths) {
var all3 = Warehouse.justCells(warehouse);
return map$1(all3, function(cell2) {
var width2 = total2(cell2.column, cell2.column + cell2.colspan, widths);
return {
element: cell2.element,
width: width2,
colspan: cell2.colspan
};
});
};
var recalculateWidthForColumns = function(warehouse, widths) {
var groups = Warehouse.justColumns(warehouse);
return map$1(groups, function(column, index2) {
return {
element: column.element,
width: widths[index2],
colspan: column.colspan
};
});
};
var recalculateHeightForCells = function(warehouse, heights) {
var all3 = Warehouse.justCells(warehouse);
return map$1(all3, function(cell2) {
var height2 = total2(cell2.row, cell2.row + cell2.rowspan, heights);
return {
element: cell2.element,
height: height2,
rowspan: cell2.rowspan
};
});
};
var matchRowHeight = function(warehouse, heights) {
return map$1(warehouse.all, function(row2, i2) {
return {
element: row2.element,
height: heights[i2]
};
});
};
var sumUp = function(newSize) {
return foldr(newSize, function(b2, a2) {
return b2 + a2;
}, 0);
};
var recalculate = function(warehouse, widths) {
if (Warehouse.hasColumns(warehouse)) {
return recalculateWidthForColumns(warehouse, widths);
} else {
return recalculateWidthForCells(warehouse, widths);
}
};
var recalculateAndApply = function(warehouse, widths, tableSize) {
var newSizes = recalculate(warehouse, widths);
each$2(newSizes, function(cell2) {
tableSize.setElementWidth(cell2.element, cell2.width);
});
};
var adjustWidth = function(table3, delta, index2, resizing, tableSize) {
var warehouse = Warehouse.fromTable(table3);
var step = tableSize.getCellDelta(delta);
var widths = tableSize.getWidths(warehouse, tableSize);
var isLastColumn = index2 === warehouse.grid.columns - 1;
var clampedStep = resizing.clampTableDelta(widths, index2, step, tableSize.minCellWidth(), isLastColumn);
var deltas = determine(widths, index2, clampedStep, tableSize, resizing);
var newWidths = map$1(deltas, function(dx, i2) {
return dx + widths[i2];
});
recalculateAndApply(warehouse, newWidths, tableSize);
resizing.resizeTable(tableSize.adjustTableWidth, clampedStep, isLastColumn);
};
var adjustHeight = function(table3, delta, index2, direction) {
var warehouse = Warehouse.fromTable(table3);
var heights = getPixelHeights(warehouse, table3, direction);
var newHeights = map$1(heights, function(dy, i2) {
return index2 === i2 ? Math.max(delta + dy, minHeight()) : dy;
});
var newCellSizes = recalculateHeightForCells(warehouse, newHeights);
var newRowSizes = matchRowHeight(warehouse, newHeights);
each$2(newRowSizes, function(row2) {
setHeight(row2.element, row2.height);
});
each$2(newCellSizes, function(cell2) {
setHeight(cell2.element, cell2.height);
});
var total3 = sumUp(newHeights);
setHeight(table3, total3);
};
var adjustAndRedistributeWidths$1 = function(_table, list, details, tableSize, resizeBehaviour) {
var warehouse = Warehouse.generate(list);
var sizes = tableSize.getWidths(warehouse, tableSize);
var tablePixelWidth = tableSize.pixelWidth();
var _a3 = resizeBehaviour.calcRedestributedWidths(sizes, tablePixelWidth, details.pixelDelta, tableSize.isRelative), newSizes = _a3.newSizes, delta = _a3.delta;
recalculateAndApply(warehouse, newSizes, tableSize);
tableSize.adjustTableWidth(delta);
};
var adjustWidthTo = function(_table, list, _info, tableSize) {
var warehouse = Warehouse.generate(list);
var widths = tableSize.getWidths(warehouse, tableSize);
recalculateAndApply(warehouse, widths, tableSize);
};
var zero = function(array3) {
return map$1(array3, constant2(0));
};
var surround = function(sizes, startIndex, endIndex, results, f2) {
return f2(sizes.slice(0, startIndex)).concat(results).concat(f2(sizes.slice(endIndex)));
};
var clampDeltaHelper = function(predicate) {
return function(sizes, index2, delta, minCellSize) {
if (!predicate(delta)) {
return delta;
} else {
var newSize = Math.max(minCellSize, sizes[index2] - Math.abs(delta));
var diff2 = Math.abs(newSize - sizes[index2]);
return delta >= 0 ? diff2 : -diff2;
}
};
};
var clampNegativeDelta = clampDeltaHelper(function(delta) {
return delta < 0;
});
var clampDelta = clampDeltaHelper(always);
var resizeTable = function() {
var calcFixedDeltas = function(sizes, index2, next3, delta, minCellSize) {
var clampedDelta = clampNegativeDelta(sizes, index2, delta, minCellSize);
return surround(sizes, index2, next3 + 1, [
clampedDelta,
0
], zero);
};
var calcRelativeDeltas = function(sizes, index2, delta, minCellSize) {
var ratio = (100 + delta) / 100;
var newThis = Math.max(minCellSize, (sizes[index2] + delta) / ratio);
return map$1(sizes, function(size2, idx) {
var newSize = idx === index2 ? newThis : size2 / ratio;
return newSize - size2;
});
};
var calcLeftEdgeDeltas = function(sizes, index2, next3, delta, minCellSize, isRelative) {
if (isRelative) {
return calcRelativeDeltas(sizes, index2, delta, minCellSize);
} else {
return calcFixedDeltas(sizes, index2, next3, delta, minCellSize);
}
};
var calcMiddleDeltas = function(sizes, _prev, index2, next3, delta, minCellSize, isRelative) {
return calcLeftEdgeDeltas(sizes, index2, next3, delta, minCellSize, isRelative);
};
var resizeTable2 = function(resizer, delta) {
return resizer(delta);
};
var calcRightEdgeDeltas = function(sizes, _prev, index2, delta, minCellSize, isRelative) {
if (isRelative) {
return calcRelativeDeltas(sizes, index2, delta, minCellSize);
} else {
var clampedDelta = clampNegativeDelta(sizes, index2, delta, minCellSize);
return zero(sizes.slice(0, index2)).concat([clampedDelta]);
}
};
var calcRedestributedWidths = function(sizes, totalWidth, pixelDelta, isRelative) {
if (isRelative) {
var tableWidth = totalWidth + pixelDelta;
var ratio_1 = tableWidth / totalWidth;
var newSizes = map$1(sizes, function(size2) {
return size2 / ratio_1;
});
return {
delta: ratio_1 * 100 - 100,
newSizes
};
} else {
return {
delta: pixelDelta,
newSizes: sizes
};
}
};
return {
resizeTable: resizeTable2,
clampTableDelta: clampNegativeDelta,
calcLeftEdgeDeltas,
calcMiddleDeltas,
calcRightEdgeDeltas,
calcRedestributedWidths
};
};
var preserveTable = function() {
var calcLeftEdgeDeltas = function(sizes, index2, next3, delta, minCellSize) {
var idx = delta >= 0 ? next3 : index2;
var clampedDelta = clampDelta(sizes, idx, delta, minCellSize);
return surround(sizes, index2, next3 + 1, [
clampedDelta,
-clampedDelta
], zero);
};
var calcMiddleDeltas = function(sizes, _prev, index2, next3, delta, minCellSize) {
return calcLeftEdgeDeltas(sizes, index2, next3, delta, minCellSize);
};
var resizeTable2 = function(resizer, delta, isLastColumn) {
if (isLastColumn) {
resizer(delta);
}
};
var calcRightEdgeDeltas = function(sizes, _prev, _index, delta, _minCellSize, isRelative) {
if (isRelative) {
return zero(sizes);
} else {
var diff2 = delta / sizes.length;
return map$1(sizes, constant2(diff2));
}
};
var clampTableDelta = function(sizes, index2, delta, minCellSize, isLastColumn) {
if (isLastColumn) {
if (delta >= 0) {
return delta;
} else {
var maxDelta = foldl(sizes, function(a2, b2) {
return a2 + b2 - minCellSize;
}, 0);
return Math.max(-maxDelta, delta);
}
} else {
return clampNegativeDelta(sizes, index2, delta, minCellSize);
}
};
var calcRedestributedWidths = function(sizes, _totalWidth, _pixelDelta, _isRelative) {
return {
delta: 0,
newSizes: sizes
};
};
return {
resizeTable: resizeTable2,
clampTableDelta,
calcLeftEdgeDeltas,
calcMiddleDeltas,
calcRightEdgeDeltas,
calcRedestributedWidths
};
};
var only = function(element, isResizable2) {
var parent3 = Optional.from(element.dom.documentElement).map(SugarElement.fromDom).getOr(element);
return {
parent: constant2(parent3),
view: constant2(element),
origin: constant2(SugarPosition(0, 0)),
isResizable: isResizable2
};
};
var detached = function(editable, chrome2, isResizable2) {
var origin = function() {
return absolute(chrome2);
};
return {
parent: constant2(chrome2),
view: constant2(editable),
origin,
isResizable: isResizable2
};
};
var body = function(editable, chrome2, isResizable2) {
return {
parent: constant2(chrome2),
view: constant2(editable),
origin: constant2(SugarPosition(0, 0)),
isResizable: isResizable2
};
};
var ResizeWire = {
only,
detached,
body
};
var adt$6 = Adt.generate([
{ invalid: ["raw"] },
{ pixels: ["value"] },
{ percent: ["value"] }
]);
var validateFor = function(suffix, type3, value25) {
var rawAmount = value25.substring(0, value25.length - suffix.length);
var amount = parseFloat(rawAmount);
return rawAmount === amount.toString() ? type3(amount) : adt$6.invalid(value25);
};
var from2 = function(value25) {
if (endsWith2(value25, "%")) {
return validateFor("%", adt$6.percent, value25);
}
if (endsWith2(value25, "px")) {
return validateFor("px", adt$6.pixels, value25);
}
return adt$6.invalid(value25);
};
var Size = __assign(__assign({}, adt$6), { from: from2 });
var redistributeToPercent = function(widths, totalWidth) {
return map$1(widths, function(w2) {
var colType = Size.from(w2);
return colType.fold(function() {
return w2;
}, function(px) {
var ratio = px / totalWidth * 100;
return ratio + "%";
}, function(pc) {
return pc + "%";
});
});
};
var redistributeToPx = function(widths, totalWidth, newTotalWidth) {
var scale = newTotalWidth / totalWidth;
return map$1(widths, function(w2) {
var colType = Size.from(w2);
return colType.fold(function() {
return w2;
}, function(px) {
return px * scale + "px";
}, function(pc) {
return pc / 100 * newTotalWidth + "px";
});
});
};
var redistributeEmpty = function(newWidthType, columns3) {
var f2 = newWidthType.fold(function() {
return constant2("");
}, function(pixels) {
var num = pixels / columns3;
return constant2(num + "px");
}, function() {
var num = 100 / columns3;
return constant2(num + "%");
});
return range$1(columns3, f2);
};
var redistributeValues = function(newWidthType, widths, totalWidth) {
return newWidthType.fold(function() {
return widths;
}, function(px) {
return redistributeToPx(widths, totalWidth, px);
}, function(_pc) {
return redistributeToPercent(widths, totalWidth);
});
};
var redistribute$1 = function(widths, totalWidth, newWidth) {
var newType = Size.from(newWidth);
var floats = forall(widths, function(s2) {
return s2 === "0px";
}) ? redistributeEmpty(newType, widths.length) : redistributeValues(newType, widths, totalWidth);
return normalize2(floats);
};
var sum = function(values3, fallback2) {
if (values3.length === 0) {
return fallback2;
}
return foldr(values3, function(rest, v2) {
return Size.from(v2).fold(constant2(0), identity2, identity2) + rest;
}, 0);
};
var roundDown = function(num, unit) {
var floored = Math.floor(num);
return {
value: floored + unit,
remainder: num - floored
};
};
var add$3 = function(value25, amount) {
return Size.from(value25).fold(constant2(value25), function(px) {
return px + amount + "px";
}, function(pc) {
return pc + amount + "%";
});
};
var normalize2 = function(values3) {
if (values3.length === 0) {
return values3;
}
var scan3 = foldr(values3, function(rest, value25) {
var info3 = Size.from(value25).fold(function() {
return {
value: value25,
remainder: 0
};
}, function(num) {
return roundDown(num, "px");
}, function(num) {
return {
value: num + "%",
remainder: 0
};
});
return {
output: [info3.value].concat(rest.output),
remainder: rest.remainder + info3.remainder
};
}, {
output: [],
remainder: 0
});
var r3 = scan3.output;
return r3.slice(0, r3.length - 1).concat([add$3(r3[r3.length - 1], Math.round(scan3.remainder))]);
};
var validate3 = Size.from;
var redistributeToW = function(newWidths, cells2, unit) {
each$2(cells2, function(cell2) {
var widths = newWidths.slice(cell2.column, cell2.colspan + cell2.column);
var w2 = sum(widths, minWidth());
set$12(cell2.element, "width", w2 + unit);
});
};
var redistributeToColumns = function(newWidths, columns3, unit) {
each$2(columns3, function(column, index2) {
var width2 = sum([newWidths[index2]], minWidth());
set$12(column.element, "width", width2 + unit);
});
};
var redistributeToH = function(newHeights, rows2, cells2, unit) {
each$2(cells2, function(cell2) {
var heights = newHeights.slice(cell2.row, cell2.rowspan + cell2.row);
var h2 = sum(heights, minHeight());
set$12(cell2.element, "height", h2 + unit);
});
each$2(rows2, function(row2, i2) {
set$12(row2.element, "height", newHeights[i2]);
});
};
var getUnit = function(newSize) {
return validate3(newSize).fold(constant2("px"), constant2("px"), constant2("%"));
};
var redistribute = function(table3, optWidth, optHeight) {
var warehouse = Warehouse.fromTable(table3);
var rows2 = warehouse.all;
var cells2 = Warehouse.justCells(warehouse);
var columns3 = Warehouse.justColumns(warehouse);
optWidth.each(function(newWidth) {
var widthUnit2 = getUnit(newWidth);
var totalWidth = get$8(table3);
var oldWidths = getRawWidths(warehouse, table3);
var nuWidths = redistribute$1(oldWidths, totalWidth, newWidth);
if (Warehouse.hasColumns(warehouse)) {
redistributeToColumns(nuWidths, columns3, widthUnit2);
} else {
redistributeToW(nuWidths, cells2, widthUnit2);
}
set$12(table3, "width", newWidth);
});
optHeight.each(function(newHeight) {
var hUnit = getUnit(newHeight);
var totalHeight = get$7(table3);
var oldHeights = getRawHeights(warehouse, table3, height);
var nuHeights = redistribute$1(oldHeights, totalHeight, newHeight);
redistributeToH(nuHeights, rows2, cells2, hUnit);
set$12(table3, "height", newHeight);
});
};
var isPercentSizing = isPercentSizing$1;
var isPixelSizing = isPixelSizing$1;
var isNoneSizing = isNoneSizing$1;
var getGridSize = function(table3) {
var warehouse = Warehouse.fromTable(table3);
return warehouse.grid;
};
var Event2 = function(fields2) {
var handlers = [];
var bind5 = function(handler7) {
if (handler7 === void 0) {
throw new Error("Event bind error: undefined handler");
}
handlers.push(handler7);
};
var unbind2 = function(handler7) {
handlers = filter$2(handlers, function(h2) {
return h2 !== handler7;
});
};
var trigger2 = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var event = {};
each$2(fields2, function(name2, i2) {
event[name2] = args[i2];
});
each$2(handlers, function(handler7) {
handler7(event);
});
};
return {
bind: bind5,
unbind: unbind2,
trigger: trigger2
};
};
var create$4 = function(typeDefs) {
var registry = map2(typeDefs, function(event) {
return {
bind: event.bind,
unbind: event.unbind
};
});
var trigger2 = map2(typeDefs, function(event) {
return event.trigger;
});
return {
registry,
trigger: trigger2
};
};
var last2 = function(fn, rate) {
var timer = null;
var cancel2 = function() {
if (!isNull2(timer)) {
clearTimeout(timer);
timer = null;
}
};
var throttle2 = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
cancel2();
timer = setTimeout(function() {
timer = null;
fn.apply(null, args);
}, rate);
};
return {
cancel: cancel2,
throttle: throttle2
};
};
var sort = function(arr) {
return arr.slice(0).sort();
};
var reqMessage = function(required2, keys3) {
throw new Error("All required keys (" + sort(required2).join(", ") + ") were not specified. Specified keys were: " + sort(keys3).join(", ") + ".");
};
var unsuppMessage = function(unsupported) {
throw new Error("Unsupported keys for object: " + sort(unsupported).join(", "));
};
var validateStrArr = function(label, array3) {
if (!isArray2(array3)) {
throw new Error("The " + label + " fields must be an array. Was: " + array3 + ".");
}
each$2(array3, function(a2) {
if (!isString3(a2)) {
throw new Error("The value " + a2 + " in the " + label + " fields was not a string.");
}
});
};
var invalidTypeMessage = function(incorrect, type3) {
throw new Error("All values need to be of type: " + type3 + ". Keys (" + sort(incorrect).join(", ") + ") were not.");
};
var checkDupes = function(everything) {
var sorted = sort(everything);
var dupe = find$12(sorted, function(s2, i2) {
return i2 < sorted.length - 1 && s2 === sorted[i2 + 1];
});
dupe.each(function(d2) {
throw new Error("The field: " + d2 + " occurs more than once in the combined fields: [" + sorted.join(", ") + "].");
});
};
var base = function(handleUnsupported, required2) {
return baseWith(handleUnsupported, required2, {
validate: isFunction3,
label: "function"
});
};
var baseWith = function(handleUnsupported, required2, pred) {
if (required2.length === 0) {
throw new Error("You must specify at least one required field.");
}
validateStrArr("required", required2);
checkDupes(required2);
return function(obj) {
var keys$12 = keys2(obj);
var allReqd = forall(required2, function(req) {
return contains$2(keys$12, req);
});
if (!allReqd) {
reqMessage(required2, keys$12);
}
handleUnsupported(required2, keys$12);
var invalidKeys = filter$2(required2, function(key3) {
return !pred.validate(obj[key3], key3);
});
if (invalidKeys.length > 0) {
invalidTypeMessage(invalidKeys, pred.label);
}
return obj;
};
};
var handleExact = function(required2, keys3) {
var unsupported = filter$2(keys3, function(key3) {
return !contains$2(required2, key3);
});
if (unsupported.length > 0) {
unsuppMessage(unsupported);
}
};
var exactly = function(required2) {
return base(handleExact, required2);
};
var DragMode = exactly([
"compare",
"extract",
"mutate",
"sink"
]);
var DragSink = exactly([
"element",
"start",
"stop",
"destroy"
]);
var DragApi = exactly([
"forceDrop",
"drop",
"move",
"delayDrop"
]);
var InDrag = function() {
var previous = Optional.none();
var reset2 = function() {
previous = Optional.none();
};
var update2 = function(mode3, nu2) {
var result = previous.map(function(old) {
return mode3.compare(old, nu2);
});
previous = Optional.some(nu2);
return result;
};
var onEvent = function(event, mode3) {
var dataOption = mode3.extract(event);
dataOption.each(function(data65) {
var offset4 = update2(mode3, data65);
offset4.each(function(d2) {
events.trigger.move(d2);
});
});
};
var events = create$4({ move: Event2(["info"]) });
return {
onEvent,
reset: reset2,
events: events.registry
};
};
var NoDrag = function() {
var events = create$4({ move: Event2(["info"]) });
return {
onEvent: noop2,
reset: noop2,
events: events.registry
};
};
var Movement = function() {
var noDragState = NoDrag();
var inDragState = InDrag();
var dragState = noDragState;
var on3 = function() {
dragState.reset();
dragState = inDragState;
};
var off2 = function() {
dragState.reset();
dragState = noDragState;
};
var onEvent = function(event, mode3) {
dragState.onEvent(event, mode3);
};
var isOn3 = function() {
return dragState === inDragState;
};
return {
on: on3,
off: off2,
isOn: isOn3,
onEvent,
events: inDragState.events
};
};
var setup123 = function(mutation, mode3, settings) {
var active = false;
var events = create$4({
start: Event2([]),
stop: Event2([])
});
var movement = Movement();
var drop = function() {
sink2.stop();
if (movement.isOn()) {
movement.off();
events.trigger.stop();
}
};
var throttledDrop = last2(drop, 200);
var go3 = function(parent3) {
sink2.start(parent3);
movement.on();
events.trigger.start();
};
var mousemove = function(event) {
throttledDrop.cancel();
movement.onEvent(event, mode3);
};
movement.events.move.bind(function(event) {
mode3.mutate(mutation, event.info);
});
var on3 = function() {
active = true;
};
var off2 = function() {
active = false;
};
var runIfActive = function(f2) {
return function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (active) {
f2.apply(null, args);
}
};
};
var sink2 = mode3.sink(DragApi({
forceDrop: drop,
drop: runIfActive(drop),
move: runIfActive(mousemove),
delayDrop: runIfActive(throttledDrop.throttle)
}), settings);
var destroy4 = function() {
sink2.destroy();
};
return {
element: sink2.element,
go: go3,
on: on3,
off: off2,
destroy: destroy4,
events: events.registry
};
};
var mkEvent = function(target, x2, y2, stop2, prevent, kill, raw) {
return {
target,
x: x2,
y: y2,
stop: stop2,
prevent,
kill,
raw
};
};
var fromRawEvent$1 = function(rawEvent) {
var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
var stop2 = function() {
return rawEvent.stopPropagation();
};
var prevent = function() {
return rawEvent.preventDefault();
};
var kill = compose(prevent, stop2);
return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop2, prevent, kill, rawEvent);
};
var handle$2 = function(filter2, handler7) {
return function(rawEvent) {
if (filter2(rawEvent)) {
handler7(fromRawEvent$1(rawEvent));
}
};
};
var binder = function(element, event, filter2, handler7, useCapture) {
var wrapped = handle$2(filter2, handler7);
element.dom.addEventListener(event, wrapped, useCapture);
return { unbind: curry(unbind, element, event, wrapped, useCapture) };
};
var bind$12 = function(element, event, filter2, handler7) {
return binder(element, event, filter2, handler7, false);
};
var unbind = function(element, event, handler7, useCapture) {
element.dom.removeEventListener(event, handler7, useCapture);
};
var filter = always;
var bind4 = function(element, event, handler7) {
return bind$12(element, event, filter, handler7);
};
var fromRawEvent = fromRawEvent$1;
var read = function(element, attr) {
var value25 = get$b(element, attr);
return value25 === void 0 || value25 === "" ? [] : value25.split(" ");
};
var add$2 = function(element, attr, id2) {
var old = read(element, attr);
var nu2 = old.concat([id2]);
set$2(element, attr, nu2.join(" "));
return true;
};
var remove$4 = function(element, attr, id2) {
var nu2 = filter$2(read(element, attr), function(v2) {
return v2 !== id2;
});
if (nu2.length > 0) {
set$2(element, attr, nu2.join(" "));
} else {
remove$7(element, attr);
}
return false;
};
var supports = function(element) {
return element.dom.classList !== void 0;
};
var get$5 = function(element) {
return read(element, "class");
};
var add$12 = function(element, clazz) {
return add$2(element, "class", clazz);
};
var remove$3 = function(element, clazz) {
return remove$4(element, "class", clazz);
};
var add3 = function(element, clazz) {
if (supports(element)) {
element.dom.classList.add(clazz);
} else {
add$12(element, clazz);
}
};
var cleanClass = function(element) {
var classList = supports(element) ? element.dom.classList : get$5(element);
if (classList.length === 0) {
remove$7(element, "class");
}
};
var remove$2 = function(element, clazz) {
if (supports(element)) {
var classList = element.dom.classList;
classList.remove(clazz);
} else {
remove$3(element, clazz);
}
cleanClass(element);
};
var has2 = function(element, clazz) {
return supports(element) && element.dom.classList.contains(clazz);
};
var css2 = function(namespace) {
var dashNamespace = namespace.replace(/\./g, "-");
var resolve2 = function(str) {
return dashNamespace + "-" + str;
};
return { resolve: resolve2 };
};
var styles$1 = css2("ephox-dragster");
var resolve$1 = styles$1.resolve;
var Blocker = function(options2) {
var settings = __assign({ layerClass: resolve$1("blocker") }, options2);
var div = SugarElement.fromTag("div");
set$2(div, "role", "presentation");
setAll(div, {
position: "fixed",
left: "0px",
top: "0px",
width: "100%",
height: "100%"
});
add3(div, resolve$1("blocker"));
add3(div, settings.layerClass);
var element = constant2(div);
var destroy4 = function() {
remove$5(div);
};
return {
element,
destroy: destroy4
};
};
var compare2 = function(old, nu2) {
return SugarPosition(nu2.left - old.left, nu2.top - old.top);
};
var extract = function(event) {
return Optional.some(SugarPosition(event.x, event.y));
};
var mutate = function(mutation, info3) {
mutation.mutate(info3.left, info3.top);
};
var sink = function(dragApi, settings) {
var blocker = Blocker(settings);
var mdown = bind4(blocker.element(), "mousedown", dragApi.forceDrop);
var mup = bind4(blocker.element(), "mouseup", dragApi.drop);
var mmove = bind4(blocker.element(), "mousemove", dragApi.move);
var mout = bind4(blocker.element(), "mouseout", dragApi.delayDrop);
var destroy4 = function() {
blocker.destroy();
mup.unbind();
mmove.unbind();
mout.unbind();
mdown.unbind();
};
var start = function(parent3) {
append$1(parent3, blocker.element());
};
var stop2 = function() {
remove$5(blocker.element());
};
return DragSink({
element: blocker.element,
start,
stop: stop2,
destroy: destroy4
});
};
var MouseDrag = DragMode({
compare: compare2,
extract,
sink,
mutate
});
var transform$1 = function(mutation, settings) {
if (settings === void 0) {
settings = {};
}
var mode3 = settings.mode !== void 0 ? settings.mode : MouseDrag;
return setup123(mutation, mode3, settings);
};
var closest = function(target) {
return closest$1(target, "[contenteditable]");
};
var isEditable$1 = function(element, assumeEditable) {
if (assumeEditable === void 0) {
assumeEditable = false;
}
if (!detect$3().browser.isIE() && inBody(element)) {
return element.dom.isContentEditable;
} else {
return closest(element).fold(constant2(assumeEditable), function(editable) {
return getRaw(editable) === "true";
});
}
};
var getRaw = function(element) {
return element.dom.contentEditable;
};
var styles = css2("ephox-snooker");
var resolve = styles.resolve;
var Mutation = function() {
var events = create$4({
drag: Event2([
"xDelta",
"yDelta"
])
});
var mutate2 = function(x2, y2) {
events.trigger.drag(x2, y2);
};
return {
mutate: mutate2,
events: events.registry
};
};
var BarMutation = function() {
var events = create$4({
drag: Event2([
"xDelta",
"yDelta",
"target"
])
});
var target = Optional.none();
var delegate = Mutation();
delegate.events.drag.bind(function(event) {
target.each(function(t2) {
events.trigger.drag(event.xDelta, event.yDelta, t2);
});
});
var assign2 = function(t2) {
target = Optional.some(t2);
};
var get3 = function() {
return target;
};
return {
assign: assign2,
get: get3,
mutate: delegate.mutate,
events: events.registry
};
};
var col = function(column, x2, y2, w2, h2) {
var bar = SugarElement.fromTag("div");
setAll(bar, {
position: "absolute",
left: x2 - w2 / 2 + "px",
top: y2 + "px",
height: h2 + "px",
width: w2 + "px"
});
setAll$1(bar, {
"data-column": column,
"role": "presentation"
});
return bar;
};
var row = function(r3, x2, y2, w2, h2) {
var bar = SugarElement.fromTag("div");
setAll(bar, {
position: "absolute",
left: x2 + "px",
top: y2 - h2 / 2 + "px",
height: h2 + "px",
width: w2 + "px"
});
setAll$1(bar, {
"data-row": r3,
"role": "presentation"
});
return bar;
};
var resizeBar = resolve("resizer-bar");
var resizeRowBar = resolve("resizer-rows");
var resizeColBar = resolve("resizer-cols");
var BAR_THICKNESS = 7;
var resizableRows = function(warehouse, isResizable2) {
return bind$22(warehouse.all, function(row2, i2) {
return isResizable2(row2.element) ? [i2] : [];
});
};
var resizableColumns = function(warehouse, isResizable2) {
var resizableCols = [];
range$1(warehouse.grid.columns, function(index2) {
var colElmOpt = Warehouse.getColumnAt(warehouse, index2).map(function(col2) {
return col2.element;
});
if (colElmOpt.forall(isResizable2)) {
resizableCols.push(index2);
}
});
return filter$2(resizableCols, function(colIndex) {
var columnCells = Warehouse.filterItems(warehouse, function(cell2) {
return cell2.column === colIndex;
});
return forall(columnCells, function(cell2) {
return isResizable2(cell2.element);
});
});
};
var destroy3 = function(wire) {
var previous = descendants(wire.parent(), "." + resizeBar);
each$2(previous, remove$5);
};
var drawBar = function(wire, positions, create2) {
var origin = wire.origin();
each$2(positions, function(cpOption) {
cpOption.each(function(cp) {
var bar = create2(origin, cp);
add3(bar, resizeBar);
append$1(wire.parent(), bar);
});
});
};
var refreshCol = function(wire, colPositions, position2, tableHeight) {
drawBar(wire, colPositions, function(origin, cp) {
var colBar = col(cp.col, cp.x - origin.left, position2.top - origin.top, BAR_THICKNESS, tableHeight);
add3(colBar, resizeColBar);
return colBar;
});
};
var refreshRow = function(wire, rowPositions, position2, tableWidth) {
drawBar(wire, rowPositions, function(origin, cp) {
var rowBar = row(cp.row, position2.left - origin.left, cp.y - origin.top, tableWidth, BAR_THICKNESS);
add3(rowBar, resizeRowBar);
return rowBar;
});
};
var refreshGrid = function(warhouse, wire, table3, rows2, cols) {
var position2 = absolute(table3);
var isResizable2 = wire.isResizable;
var rowPositions = rows2.length > 0 ? height.positions(rows2, table3) : [];
var resizableRowBars = rowPositions.length > 0 ? resizableRows(warhouse, isResizable2) : [];
var resizableRowPositions = filter$2(rowPositions, function(_pos, i2) {
return exists(resizableRowBars, function(barIndex) {
return i2 === barIndex;
});
});
refreshRow(wire, resizableRowPositions, position2, getOuter$2(table3));
var colPositions = cols.length > 0 ? width.positions(cols, table3) : [];
var resizableColBars = colPositions.length > 0 ? resizableColumns(warhouse, isResizable2) : [];
var resizableColPositions = filter$2(colPositions, function(_pos, i2) {
return exists(resizableColBars, function(barIndex) {
return i2 === barIndex;
});
});
refreshCol(wire, resizableColPositions, position2, getOuter$1(table3));
};
var refresh = function(wire, table3) {
destroy3(wire);
if (wire.isResizable(table3)) {
var warehouse = Warehouse.fromTable(table3);
var rows$12 = rows(warehouse);
var cols = columns2(warehouse);
refreshGrid(warehouse, wire, table3, rows$12, cols);
}
};
var each2 = function(wire, f2) {
var bars = descendants(wire.parent(), "." + resizeBar);
each$2(bars, f2);
};
var hide = function(wire) {
each2(wire, function(bar) {
set$12(bar, "display", "none");
});
};
var show = function(wire) {
each2(wire, function(bar) {
set$12(bar, "display", "block");
});
};
var isRowBar = function(element) {
return has2(element, resizeRowBar);
};
var isColBar = function(element) {
return has2(element, resizeColBar);
};
var resizeBarDragging = resolve("resizer-bar-dragging");
var BarManager = function(wire) {
var mutation = BarMutation();
var resizing = transform$1(mutation, {});
var hoverTable = Optional.none();
var getResizer = function(element, type3) {
return Optional.from(get$b(element, type3));
};
mutation.events.drag.bind(function(event) {
getResizer(event.target, "data-row").each(function(_dataRow) {
var currentRow = getCssValue(event.target, "top");
set$12(event.target, "top", currentRow + event.yDelta + "px");
});
getResizer(event.target, "data-column").each(function(_dataCol) {
var currentCol = getCssValue(event.target, "left");
set$12(event.target, "left", currentCol + event.xDelta + "px");
});
});
var getDelta = function(target, dir) {
var newX = getCssValue(target, dir);
var oldX = getAttrValue(target, "data-initial-" + dir, 0);
return newX - oldX;
};
resizing.events.stop.bind(function() {
mutation.get().each(function(target) {
hoverTable.each(function(table3) {
getResizer(target, "data-row").each(function(row2) {
var delta = getDelta(target, "top");
remove$7(target, "data-initial-top");
events.trigger.adjustHeight(table3, delta, parseInt(row2, 10));
});
getResizer(target, "data-column").each(function(column) {
var delta = getDelta(target, "left");
remove$7(target, "data-initial-left");
events.trigger.adjustWidth(table3, delta, parseInt(column, 10));
});
refresh(wire, table3);
});
});
});
var handler7 = function(target, dir) {
events.trigger.startAdjust();
mutation.assign(target);
set$2(target, "data-initial-" + dir, getCssValue(target, dir));
add3(target, resizeBarDragging);
set$12(target, "opacity", "0.2");
resizing.go(wire.parent());
};
var mousedown = bind4(wire.parent(), "mousedown", function(event) {
if (isRowBar(event.target)) {
handler7(event.target, "top");
}
if (isColBar(event.target)) {
handler7(event.target, "left");
}
});
var isRoot = function(e2) {
return eq$1(e2, wire.view());
};
var findClosestEditableTable = function(target) {
return closest$1(target, "table", isRoot).filter(isEditable$1);
};
var mouseover = bind4(wire.view(), "mouseover", function(event) {
findClosestEditableTable(event.target).fold(function() {
if (inBody(event.target)) {
destroy3(wire);
}
}, function(table3) {
hoverTable = Optional.some(table3);
refresh(wire, table3);
});
});
var destroy$1 = function() {
mousedown.unbind();
mouseover.unbind();
resizing.destroy();
destroy3(wire);
};
var refresh$1 = function(tbl) {
refresh(wire, tbl);
};
var events = create$4({
adjustHeight: Event2([
"table",
"delta",
"row"
]),
adjustWidth: Event2([
"table",
"delta",
"column"
]),
startAdjust: Event2([])
});
return {
destroy: destroy$1,
refresh: refresh$1,
on: resizing.on,
off: resizing.off,
hideBars: curry(hide, wire),
showBars: curry(show, wire),
events: events.registry
};
};
var create$3 = function(wire, resizing, lazySizing) {
var hdirection = height;
var vdirection = width;
var manager = BarManager(wire);
var events = create$4({
beforeResize: Event2([
"table",
"type"
]),
afterResize: Event2([
"table",
"type"
]),
startDrag: Event2([])
});
manager.events.adjustHeight.bind(function(event) {
var table3 = event.table;
events.trigger.beforeResize(table3, "row");
var delta = hdirection.delta(event.delta, table3);
adjustHeight(table3, delta, event.row, hdirection);
events.trigger.afterResize(table3, "row");
});
manager.events.startAdjust.bind(function(_event) {
events.trigger.startDrag();
});
manager.events.adjustWidth.bind(function(event) {
var table3 = event.table;
events.trigger.beforeResize(table3, "col");
var delta = vdirection.delta(event.delta, table3);
var tableSize = lazySizing(table3);
adjustWidth(table3, delta, event.column, resizing, tableSize);
events.trigger.afterResize(table3, "col");
});
return {
on: manager.on,
off: manager.off,
hideBars: manager.hideBars,
showBars: manager.showBars,
destroy: manager.destroy,
events: events.registry
};
};
var TableResize = { create: create$3 };
var fireNewRow = function(editor, row2) {
return editor.fire("newrow", { node: row2 });
};
var fireNewCell = function(editor, cell2) {
return editor.fire("newcell", { node: cell2 });
};
var fireObjectResizeStart = function(editor, target, width2, height2, origin) {
editor.fire("ObjectResizeStart", {
target,
width: width2,
height: height2,
origin
});
};
var fireObjectResized = function(editor, target, width2, height2, origin) {
editor.fire("ObjectResized", {
target,
width: width2,
height: height2,
origin
});
};
var fireTableSelectionChange = function(editor, cells2, start, finish, otherCells) {
editor.fire("TableSelectionChange", {
cells: cells2,
start,
finish,
otherCells
});
};
var fireTableSelectionClear = function(editor) {
editor.fire("TableSelectionClear");
};
var fireTableModified = function(editor, table3, data65) {
editor.fire("TableModified", __assign(__assign({}, data65), { table: table3 }));
};
var styleModified = {
structure: false,
style: true
};
var structureModified = {
structure: true,
style: false
};
var styleAndStructureModified = {
structure: true,
style: true
};
var defaultTableToolbar = "tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol";
var defaultStyles = {
"border-collapse": "collapse",
"width": "100%"
};
var defaultCellBorderWidths = range$1(5, function(i2) {
var size2 = i2 + 1 + "px";
return {
title: size2,
value: size2
};
});
var defaultCellBorderStyles = map$1([
"Solid",
"Dotted",
"Dashed",
"Double",
"Groove",
"Ridge",
"Inset",
"Outset",
"None",
"Hidden"
], function(type3) {
return {
title: type3,
value: type3.toLowerCase()
};
});
var determineDefaultStyles = function(editor) {
var _a3;
if (isPixelsForced(editor)) {
var dom = editor.dom;
var parentBlock = (_a3 = dom.getParent(editor.selection.getStart(), dom.isBlock)) !== null && _a3 !== void 0 ? _a3 : editor.getBody();
var contentWidth = getInner(SugarElement.fromDom(parentBlock));
return __assign(__assign({}, defaultStyles), { width: contentWidth + "px" });
} else if (isResponsiveForced(editor)) {
return filter$1(defaultStyles, function(_value, key3) {
return key3 !== "width";
});
} else {
return defaultStyles;
}
};
var defaultAttributes = { border: "1" };
var defaultColumnResizingBehaviour = "preservetable";
var getTableSizingMode = function(editor) {
return editor.getParam("table_sizing_mode", "auto");
};
var getTableResponseWidth = function(editor) {
return editor.getParam("table_responsive_width");
};
var getTableBorderWidths = function(editor) {
return editor.getParam("table_border_widths", defaultCellBorderWidths, "array");
};
var getTableBorderStyles = function(editor) {
return editor.getParam("table_border_styles", defaultCellBorderStyles, "array");
};
var getDefaultAttributes = function(editor) {
return editor.getParam("table_default_attributes", defaultAttributes, "object");
};
var getDefaultStyles = function(editor) {
return editor.getParam("table_default_styles", determineDefaultStyles(editor), "object");
};
var hasTableResizeBars = function(editor) {
return editor.getParam("table_resize_bars", true, "boolean");
};
var hasTabNavigation = function(editor) {
return editor.getParam("table_tab_navigation", true, "boolean");
};
var hasAdvancedCellTab = function(editor) {
return editor.getParam("table_cell_advtab", true, "boolean");
};
var hasAdvancedRowTab = function(editor) {
return editor.getParam("table_row_advtab", true, "boolean");
};
var hasAdvancedTableTab = function(editor) {
return editor.getParam("table_advtab", true, "boolean");
};
var hasAppearanceOptions = function(editor) {
return editor.getParam("table_appearance_options", true, "boolean");
};
var hasTableGrid = function(editor) {
return editor.getParam("table_grid", true, "boolean");
};
var shouldStyleWithCss = function(editor) {
return editor.getParam("table_style_by_css", false, "boolean");
};
var getCellClassList = function(editor) {
return editor.getParam("table_cell_class_list", [], "array");
};
var getRowClassList = function(editor) {
return editor.getParam("table_row_class_list", [], "array");
};
var getTableClassList = function(editor) {
return editor.getParam("table_class_list", [], "array");
};
var isPercentagesForced = function(editor) {
return getTableSizingMode(editor) === "relative" || getTableResponseWidth(editor) === true;
};
var isPixelsForced = function(editor) {
return getTableSizingMode(editor) === "fixed" || getTableResponseWidth(editor) === false;
};
var isResponsiveForced = function(editor) {
return getTableSizingMode(editor) === "responsive";
};
var getToolbar = function(editor) {
return editor.getParam("table_toolbar", defaultTableToolbar);
};
var useColumnGroup = function(editor) {
return editor.getParam("table_use_colgroups", false, "boolean");
};
var getTableHeaderType = function(editor) {
var defaultValue = "section";
var value25 = editor.getParam("table_header_type", defaultValue, "string");
var validValues = [
"section",
"cells",
"sectionCells",
"auto"
];
if (!contains$2(validValues, value25)) {
return defaultValue;
} else {
return value25;
}
};
var getColumnResizingBehaviour = function(editor) {
var validModes = [
"preservetable",
"resizetable"
];
var givenMode = editor.getParam("table_column_resizing", defaultColumnResizingBehaviour, "string");
return find$12(validModes, function(mode3) {
return mode3 === givenMode;
}).getOr(defaultColumnResizingBehaviour);
};
var isPreserveTableColumnResizing = function(editor) {
return getColumnResizingBehaviour(editor) === "preservetable";
};
var isResizeTableColumnResizing = function(editor) {
return getColumnResizingBehaviour(editor) === "resizetable";
};
var getCloneElements = function(editor) {
var cloneElements = editor.getParam("table_clone_elements");
if (isString3(cloneElements)) {
return Optional.some(cloneElements.split(/[ ,]/));
} else if (Array.isArray(cloneElements)) {
return Optional.some(cloneElements);
} else {
return Optional.none();
}
};
var hasObjectResizing = function(editor) {
var objectResizing = editor.getParam("object_resizing", true);
return isString3(objectResizing) ? objectResizing === "table" : objectResizing;
};
var getTableBackgroundColorMap = function(editor) {
return editor.getParam("table_background_color_map", [], "array");
};
var getTableBorderColorMap = function(editor) {
return editor.getParam("table_border_color_map", [], "array");
};
var get$4 = function(editor, table3) {
if (isPercentagesForced(editor)) {
return TableSize.percentageSize(table3);
} else if (isPixelsForced(editor)) {
return TableSize.pixelSize(table3);
} else {
return TableSize.getTableSize(table3);
}
};
var cleanupLegacyAttributes = function(element) {
remove$7(element, "width");
};
var convertToPercentSize = function(table3) {
var newWidth = getPercentTableWidth(table3);
redistribute(table3, Optional.some(newWidth), Optional.none());
cleanupLegacyAttributes(table3);
};
var convertToPixelSize = function(table3) {
var newWidth = getPixelTableWidth(table3);
redistribute(table3, Optional.some(newWidth), Optional.none());
cleanupLegacyAttributes(table3);
};
var convertToNoneSize = function(table3) {
remove$6(table3, "width");
var columns3 = columns$1(table3);
var rowElements = columns3.length > 0 ? columns3 : cells$1(table3);
each$2(rowElements, function(cell2) {
remove$6(cell2, "width");
cleanupLegacyAttributes(cell2);
});
cleanupLegacyAttributes(table3);
};
var enforcePercentage = convertToPercentSize;
var enforcePixels = convertToPixelSize;
var enforceNone = convertToNoneSize;
var syncPixels = function(table3) {
var warehouse = Warehouse.fromTable(table3);
if (!Warehouse.hasColumns(warehouse)) {
each$2(cells$1(table3), function(cell2) {
var computedWidth = get$a(cell2, "width");
set$12(cell2, "width", computedWidth);
remove$7(cell2, "width");
});
}
};
var createContainer2 = function() {
var container = SugarElement.fromTag("div");
setAll(container, {
position: "static",
height: "0",
width: "0",
padding: "0",
margin: "0",
border: "0"
});
append$1(body$1(), container);
return container;
};
var get$3 = function(editor, isResizable2) {
return editor.inline ? ResizeWire.body(getBody2(editor), createContainer2(), isResizable2) : ResizeWire.only(SugarElement.fromDom(editor.getDoc()), isResizable2);
};
var remove$1 = function(editor, wire) {
if (editor.inline) {
remove$5(wire.parent());
}
};
var barResizerPrefix = "bar-";
var isResizable = function(elm) {
return get$b(elm, "data-mce-resize") !== "false";
};
var getResizeHandler = function(editor) {
var selectionRng = Optional.none();
var resize2 = Optional.none();
var wire = Optional.none();
var startW;
var startRawW;
var isTable = function(elm) {
return elm.nodeName === "TABLE";
};
var lazyResize = function() {
return resize2;
};
var lazyWire = function() {
return wire.getOr(ResizeWire.only(SugarElement.fromDom(editor.getBody()), isResizable));
};
var lazySizing = function(table3) {
return get$4(editor, table3);
};
var lazyResizingBehaviour = function() {
return isPreserveTableColumnResizing(editor) ? preserveTable() : resizeTable();
};
var getNumColumns = function(table3) {
return getGridSize(table3).columns;
};
var afterCornerResize = function(table3, origin, width2) {
var isRightEdgeResize = endsWith2(origin, "e");
if (startRawW === "") {
enforcePercentage(table3);
}
if (width2 !== startW && startRawW !== "") {
set$12(table3, "width", startRawW);
var resizing = lazyResizingBehaviour();
var tableSize = lazySizing(table3);
var col2 = isPreserveTableColumnResizing(editor) || isRightEdgeResize ? getNumColumns(table3) - 1 : 0;
adjustWidth(table3, width2 - startW, col2, resizing, tableSize);
} else if (isPercentage$1(startRawW)) {
var percentW = parseFloat(startRawW.replace("%", ""));
var targetPercentW = width2 * percentW / startW;
set$12(table3, "width", targetPercentW + "%");
}
if (isPixel(startRawW)) {
syncPixels(table3);
}
};
var destroy4 = function() {
resize2.each(function(sz) {
sz.destroy();
});
wire.each(function(w2) {
remove$1(editor, w2);
});
};
editor.on("init", function() {
var rawWire = get$3(editor, isResizable);
wire = Optional.some(rawWire);
if (hasObjectResizing(editor) && hasTableResizeBars(editor)) {
var resizing = lazyResizingBehaviour();
var sz = TableResize.create(rawWire, resizing, lazySizing);
sz.on();
sz.events.startDrag.bind(function(_event) {
selectionRng = Optional.some(editor.selection.getRng());
});
sz.events.beforeResize.bind(function(event) {
var rawTable = event.table.dom;
fireObjectResizeStart(editor, rawTable, getPixelWidth(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
});
sz.events.afterResize.bind(function(event) {
var table3 = event.table;
var rawTable = table3.dom;
removeDataStyle(table3);
selectionRng.each(function(rng) {
editor.selection.setRng(rng);
editor.focus();
});
fireObjectResized(editor, rawTable, getPixelWidth(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
editor.undoManager.add();
});
resize2 = Optional.some(sz);
}
});
editor.on("ObjectResizeStart", function(e2) {
var targetElm = e2.target;
if (isTable(targetElm)) {
var table3 = SugarElement.fromDom(targetElm);
each$2(editor.dom.select(".mce-clonedresizable"), function(clone5) {
editor.dom.addClass(clone5, "mce-" + getColumnResizingBehaviour(editor) + "-columns");
});
if (!isPixelSizing(table3) && isPixelsForced(editor)) {
enforcePixels(table3);
} else if (!isPercentSizing(table3) && isPercentagesForced(editor)) {
enforcePercentage(table3);
}
if (isNoneSizing(table3) && startsWith(e2.origin, barResizerPrefix)) {
enforcePercentage(table3);
}
startW = e2.width;
startRawW = isResponsiveForced(editor) ? "" : getRawWidth(editor, targetElm).getOr("");
}
});
editor.on("ObjectResized", function(e2) {
var targetElm = e2.target;
if (isTable(targetElm)) {
var table3 = SugarElement.fromDom(targetElm);
var origin_1 = e2.origin;
if (startsWith(origin_1, "corner-")) {
afterCornerResize(table3, origin_1, e2.width);
}
removeDataStyle(table3);
fireTableModified(editor, table3.dom, styleModified);
}
});
editor.on("SwitchMode", function() {
lazyResize().each(function(resize3) {
if (editor.mode.isReadOnly()) {
resize3.hideBars();
} else {
resize3.showBars();
}
});
});
return {
lazyResize,
lazyWire,
destroy: destroy4
};
};
var point = function(element, offset4) {
return {
element,
offset: offset4
};
};
var scan$1 = function(universe2, element, direction) {
if (universe2.property().isText(element) && universe2.property().getText(element).trim().length === 0 || universe2.property().isComment(element)) {
return direction(element).bind(function(elem) {
return scan$1(universe2, elem, direction).orThunk(function() {
return Optional.some(elem);
});
});
} else {
return Optional.none();
}
};
var toEnd = function(universe2, element) {
if (universe2.property().isText(element)) {
return universe2.property().getText(element).length;
}
var children2 = universe2.property().children(element);
return children2.length;
};
var freefallRtl$2 = function(universe2, element) {
var candidate = scan$1(universe2, element, universe2.query().prevSibling).getOr(element);
if (universe2.property().isText(candidate)) {
return point(candidate, toEnd(universe2, candidate));
}
var children2 = universe2.property().children(candidate);
return children2.length > 0 ? freefallRtl$2(universe2, children2[children2.length - 1]) : point(candidate, toEnd(universe2, candidate));
};
var freefallRtl$1 = freefallRtl$2;
var universe$2 = DomUniverse();
var freefallRtl = function(element) {
return freefallRtl$1(universe$2, element);
};
var halve = function(main, other) {
var colspan = getSpan(main, "colspan");
if (colspan === 1) {
var width2 = getGenericWidth(main);
width2.each(function(w2) {
var newWidth = w2.value / 2;
setGenericWidth(main, newWidth, w2.unit);
setGenericWidth(other, newWidth, w2.unit);
});
}
};
var isHeaderCell = isTag("th");
var isHeaderCells = function(cells2) {
return forall(cells2, function(cell2) {
return isHeaderCell(cell2.element);
});
};
var getRowHeaderType = function(isHeaderRow, isHeaderCells2) {
if (isHeaderRow && isHeaderCells2) {
return "sectionCells";
} else if (isHeaderRow) {
return "section";
} else {
return "cells";
}
};
var getRowType$1 = function(row2) {
var isHeaderRow = row2.section === "thead";
var isHeaderCells2 = is2(findCommonCellType(row2.cells), "th");
if (isHeaderRow || isHeaderCells2) {
return {
type: "header",
subType: getRowHeaderType(isHeaderRow, isHeaderCells2)
};
} else if (row2.section === "tfoot") {
return { type: "footer" };
} else {
return { type: "body" };
}
};
var findCommonCellType = function(cells2) {
var headerCells = filter$2(cells2, function(cell2) {
return isHeaderCell(cell2.element);
});
if (headerCells.length === 0) {
return Optional.some("td");
} else if (headerCells.length === cells2.length) {
return Optional.some("th");
} else {
return Optional.none();
}
};
var findCommonRowType = function(rows2) {
var rowTypes = map$1(rows2, function(row2) {
return getRowType$1(row2).type;
});
var hasHeader = contains$2(rowTypes, "header");
var hasFooter = contains$2(rowTypes, "footer");
if (!hasHeader && !hasFooter) {
return Optional.some("body");
} else {
var hasBody = contains$2(rowTypes, "body");
if (hasHeader && !hasBody && !hasFooter) {
return Optional.some("header");
} else if (!hasHeader && !hasBody && hasFooter) {
return Optional.some("footer");
} else {
return Optional.none();
}
}
};
var findTableRowHeaderType = function(warehouse) {
return findMap(warehouse.all, function(row2) {
var rowType = getRowType$1(row2);
return rowType.type === "header" ? Optional.from(rowType.subType) : Optional.none();
});
};
var transformCell = function(cell2, comparator, substitution) {
return elementnew(substitution(cell2.element, comparator), true, cell2.isLocked);
};
var transformRow = function(row2, section2) {
return row2.section !== section2 ? rowcells(row2.element, row2.cells, section2, row2.isNew) : row2;
};
var section = function() {
return {
transformRow,
transformCell: function(cell2, comparator, substitution) {
var newCell = substitution(cell2.element, comparator);
var fixedCell = name(newCell) !== "td" ? mutate$1(newCell, "td") : newCell;
return elementnew(fixedCell, cell2.isNew, cell2.isLocked);
}
};
};
var sectionCells = function() {
return {
transformRow,
transformCell
};
};
var cells = function() {
return {
transformRow: function(row2, section2) {
var newSection = section2 === "thead" ? "tbody" : section2;
return transformRow(row2, newSection);
},
transformCell
};
};
var fallback = function() {
return {
transformRow: identity2,
transformCell
};
};
var getTableSectionType = function(table3, fallback2) {
var warehouse = Warehouse.fromTable(table3);
var type3 = findTableRowHeaderType(warehouse).getOr(fallback2);
switch (type3) {
case "section":
return section();
case "sectionCells":
return sectionCells();
case "cells":
return cells();
}
};
var TableSection = {
getTableSectionType,
section,
sectionCells,
cells,
fallback
};
var setIfNot = function(element, property2, value25, ignore) {
if (value25 === ignore) {
remove$7(element, property2);
} else {
set$2(element, property2, value25);
}
};
var insert$1 = function(table3, selector2, element) {
last$2(children$1(table3, selector2)).fold(function() {
return prepend(table3, element);
}, function(child2) {
return after$5(child2, element);
});
};
var generateSection = function(table3, sectionName) {
var section2 = child$1(table3, sectionName).getOrThunk(function() {
var newSection = SugarElement.fromTag(sectionName, owner(table3).dom);
if (sectionName === "thead") {
insert$1(table3, "caption,colgroup", newSection);
} else if (sectionName === "colgroup") {
insert$1(table3, "caption", newSection);
} else {
append$1(table3, newSection);
}
return newSection;
});
empty2(section2);
return section2;
};
var render$1 = function(table3, grid2) {
var newRows = [];
var newCells = [];
var syncRows = function(gridSection) {
return map$1(gridSection, function(row2) {
if (row2.isNew) {
newRows.push(row2.element);
}
var tr = row2.element;
empty2(tr);
each$2(row2.cells, function(cell2) {
if (cell2.isNew) {
newCells.push(cell2.element);
}
setIfNot(cell2.element, "colspan", cell2.colspan, 1);
setIfNot(cell2.element, "rowspan", cell2.rowspan, 1);
append$1(tr, cell2.element);
});
return tr;
});
};
var syncColGroup = function(gridSection) {
return bind$22(gridSection, function(colGroup) {
return map$1(colGroup.cells, function(col2) {
setIfNot(col2.element, "span", col2.colspan, 1);
return col2.element;
});
});
};
var renderSection = function(gridSection, sectionName) {
var section2 = generateSection(table3, sectionName);
var sync2 = sectionName === "colgroup" ? syncColGroup : syncRows;
var sectionElems = sync2(gridSection);
append(section2, sectionElems);
};
var removeSection = function(sectionName) {
child$1(table3, sectionName).each(remove$5);
};
var renderOrRemoveSection = function(gridSection, sectionName) {
if (gridSection.length > 0) {
renderSection(gridSection, sectionName);
} else {
removeSection(sectionName);
}
};
var headSection = [];
var bodySection = [];
var footSection = [];
var columnGroupsSection = [];
each$2(grid2, function(row2) {
switch (row2.section) {
case "thead":
headSection.push(row2);
break;
case "tbody":
bodySection.push(row2);
break;
case "tfoot":
footSection.push(row2);
break;
case "colgroup":
columnGroupsSection.push(row2);
break;
}
});
renderOrRemoveSection(columnGroupsSection, "colgroup");
renderOrRemoveSection(headSection, "thead");
renderOrRemoveSection(bodySection, "tbody");
renderOrRemoveSection(footSection, "tfoot");
return {
newRows,
newCells
};
};
var copy = function(grid2) {
return map$1(grid2, function(row2) {
var tr = shallow(row2.element);
each$2(row2.cells, function(cell2) {
var clonedCell = deep(cell2.element);
setIfNot(clonedCell, "colspan", cell2.colspan, 1);
setIfNot(clonedCell, "rowspan", cell2.rowspan, 1);
append$1(tr, clonedCell);
});
return tr;
});
};
var getColumn2 = function(grid2, index2) {
return map$1(grid2, function(row2) {
return getCell(row2, index2);
});
};
var getRow = function(grid2, index2) {
return grid2[index2];
};
var findDiff = function(xs, comp) {
if (xs.length === 0) {
return 0;
}
var first2 = xs[0];
var index2 = findIndex2(xs, function(x2) {
return !comp(first2.element, x2.element);
});
return index2.getOr(xs.length);
};
var subgrid = function(grid2, row2, column, comparator) {
var gridRow = getRow(grid2, row2);
var isColRow = gridRow.section === "colgroup";
var colspan = findDiff(gridRow.cells.slice(column), comparator);
var rowspan = isColRow ? 1 : findDiff(getColumn2(grid2.slice(row2), column), comparator);
return {
colspan,
rowspan
};
};
var toDetails = function(grid2, comparator) {
var seen = map$1(grid2, function(row2) {
return map$1(row2.cells, never);
});
var updateSeen = function(rowIndex, columnIndex, rowspan, colspan) {
for (var row2 = rowIndex; row2 < rowIndex + rowspan; row2++) {
for (var column = columnIndex; column < columnIndex + colspan; column++) {
seen[row2][column] = true;
}
}
};
return map$1(grid2, function(row2, rowIndex) {
var details = bind$22(row2.cells, function(cell2, columnIndex) {
if (seen[rowIndex][columnIndex] === false) {
var result = subgrid(grid2, rowIndex, columnIndex, comparator);
updateSeen(rowIndex, columnIndex, result.rowspan, result.colspan);
return [detailnew(cell2.element, result.rowspan, result.colspan, cell2.isNew)];
} else {
return [];
}
});
return rowdetailnew(row2.element, details, row2.section, row2.isNew);
});
};
var toGrid = function(warehouse, generators, isNew) {
var grid2 = [];
each$2(warehouse.colgroups, function(colgroup2) {
var colgroupCols = [];
for (var columnIndex2 = 0; columnIndex2 < warehouse.grid.columns; columnIndex2++) {
var element2 = Warehouse.getColumnAt(warehouse, columnIndex2).map(function(column) {
return elementnew(column.element, isNew, false);
}).getOrThunk(function() {
return elementnew(generators.colGap(), true, false);
});
colgroupCols.push(element2);
}
grid2.push(rowcells(colgroup2.element, colgroupCols, "colgroup", isNew));
});
for (var rowIndex = 0; rowIndex < warehouse.grid.rows; rowIndex++) {
var rowCells = [];
for (var columnIndex = 0; columnIndex < warehouse.grid.columns; columnIndex++) {
var element = Warehouse.getAt(warehouse, rowIndex, columnIndex).map(function(item) {
return elementnew(item.element, isNew, item.isLocked);
}).getOrThunk(function() {
return elementnew(generators.gap(), true, false);
});
rowCells.push(element);
}
var rowDetail = warehouse.all[rowIndex];
var row2 = rowcells(rowDetail.element, rowCells, rowDetail.section, isNew);
grid2.push(row2);
}
return grid2;
};
var fromWarehouse = function(warehouse, generators) {
return toGrid(warehouse, generators, false);
};
var toDetailList = function(grid2) {
return toDetails(grid2, eq$1);
};
var findInWarehouse = function(warehouse, element) {
return findMap(warehouse.all, function(r3) {
return find$12(r3.cells, function(e2) {
return eq$1(element, e2.element);
});
});
};
var extractCells = function(warehouse, target, predicate) {
var details = map$1(target.selection, function(cell$1) {
return cell(cell$1).bind(function(lc) {
return findInWarehouse(warehouse, lc);
}).filter(predicate);
});
var cells2 = cat(details);
return someIf(cells2.length > 0, cells2);
};
var run = function(operation, extract2, adjustment, postAction, genWrappers) {
return function(wire, table3, target, generators, behaviours) {
var warehouse = Warehouse.fromTable(table3);
var tableSection = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.section).getOrThunk(TableSection.fallback);
var output = extract2(warehouse, target).map(function(info3) {
var model = fromWarehouse(warehouse, generators);
var result = operation(model, info3, eq$1, genWrappers(generators), tableSection);
var lockedColumns = getLockedColumnsFromGrid(result.grid);
var grid2 = toDetailList(result.grid);
return {
info: info3,
grid: grid2,
cursor: result.cursor,
lockedColumns
};
});
return output.bind(function(out) {
var newElements = render$1(table3, out.grid);
var tableSizing = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.sizing).getOrThunk(function() {
return TableSize.getTableSize(table3);
});
var resizing = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.resize).getOrThunk(preserveTable);
adjustment(table3, out.grid, out.info, {
sizing: tableSizing,
resize: resizing,
section: tableSection
});
postAction(table3);
refresh(wire, table3);
remove$7(table3, LOCKED_COL_ATTR);
if (out.lockedColumns.length > 0) {
set$2(table3, LOCKED_COL_ATTR, out.lockedColumns.join(","));
}
return Optional.some({
cursor: out.cursor,
newRows: newElements.newRows,
newCells: newElements.newCells
});
});
};
};
var onPaste = function(warehouse, target) {
return cell(target.element).bind(function(cell2) {
return findInWarehouse(warehouse, cell2).map(function(details) {
var value25 = __assign(__assign({}, details), {
generators: target.generators,
clipboard: target.clipboard
});
return value25;
});
});
};
var onPasteByEditor = function(warehouse, target) {
return extractCells(warehouse, target, always).map(function(cells2) {
return {
cells: cells2,
generators: target.generators,
clipboard: target.clipboard
};
});
};
var onMergable = function(_warehouse, target) {
return target.mergable;
};
var onUnmergable = function(_warehouse, target) {
return target.unmergable;
};
var onCells = function(warehouse, target) {
return extractCells(warehouse, target, always);
};
var onUnlockedCells = function(warehouse, target) {
return extractCells(warehouse, target, function(detail2) {
return !detail2.isLocked;
});
};
var isUnlockedTableCell = function(warehouse, cell2) {
return findInWarehouse(warehouse, cell2).exists(function(detail2) {
return !detail2.isLocked;
});
};
var allUnlocked = function(warehouse, cells2) {
return forall(cells2, function(cell2) {
return isUnlockedTableCell(warehouse, cell2);
});
};
var onUnlockedMergable = function(warehouse, target) {
return onMergable(warehouse, target).filter(function(mergeable) {
return allUnlocked(warehouse, mergeable.cells);
});
};
var onUnlockedUnmergable = function(warehouse, target) {
return onUnmergable(warehouse, target).filter(function(cells2) {
return allUnlocked(warehouse, cells2);
});
};
var merge$22 = function(grid2, bounds2, comparator, substitution) {
var rows2 = extractGridDetails(grid2).rows;
if (rows2.length === 0) {
return grid2;
}
for (var i2 = bounds2.startRow; i2 <= bounds2.finishRow; i2++) {
for (var j2 = bounds2.startCol; j2 <= bounds2.finishCol; j2++) {
var row2 = rows2[i2];
var isLocked = getCell(row2, j2).isLocked;
mutateCell(row2, j2, elementnew(substitution(), false, isLocked));
}
}
return grid2;
};
var unmerge = function(grid2, target, comparator, substitution) {
var rows2 = extractGridDetails(grid2).rows;
var first2 = true;
for (var i2 = 0; i2 < rows2.length; i2++) {
for (var j2 = 0; j2 < cellLength(rows2[0]); j2++) {
var row2 = rows2[i2];
var currentCell = getCell(row2, j2);
var currentCellElm = currentCell.element;
var isToReplace = comparator(currentCellElm, target);
if (isToReplace === true && first2 === false) {
mutateCell(row2, j2, elementnew(substitution(), true, currentCell.isLocked));
} else if (isToReplace === true) {
first2 = false;
}
}
}
return grid2;
};
var uniqueCells = function(row2, comparator) {
return foldl(row2, function(rest, cell2) {
return exists(rest, function(currentCell) {
return comparator(currentCell.element, cell2.element);
}) ? rest : rest.concat([cell2]);
}, []);
};
var splitCols = function(grid2, index2, comparator, substitution) {
if (index2 > 0 && index2 < grid2[0].cells.length) {
each$2(grid2, function(row2) {
var prevCell = row2.cells[index2 - 1];
var current2 = row2.cells[index2];
var isToReplace = comparator(current2.element, prevCell.element);
if (isToReplace) {
mutateCell(row2, index2, elementnew(substitution(), true, current2.isLocked));
}
});
}
return grid2;
};
var splitRows = function(grid2, index2, comparator, substitution) {
var rows2 = extractGridDetails(grid2).rows;
if (index2 > 0 && index2 < rows2.length) {
var rowPrevCells = rows2[index2 - 1].cells;
var cells2 = uniqueCells(rowPrevCells, comparator);
each$2(cells2, function(cell2) {
var replacement = Optional.none();
for (var i2 = index2; i2 < rows2.length; i2++) {
var _loop_1 = function(j3) {
var row2 = rows2[i2];
var current2 = getCell(row2, j3);
var isToReplace = comparator(current2.element, cell2.element);
if (isToReplace) {
if (replacement.isNone()) {
replacement = Optional.some(substitution());
}
replacement.each(function(sub) {
mutateCell(row2, j3, elementnew(sub, true, current2.isLocked));
});
}
};
for (var j2 = 0; j2 < cellLength(rows2[0]); j2++) {
_loop_1(j2);
}
}
});
}
return grid2;
};
var value$1 = function(o2) {
var or = function(_opt) {
return value$1(o2);
};
var orThunk = function(_f) {
return value$1(o2);
};
var map3 = function(f2) {
return value$1(f2(o2));
};
var mapError = function(_f) {
return value$1(o2);
};
var each3 = function(f2) {
f2(o2);
};
var bind5 = function(f2) {
return f2(o2);
};
var fold = function(_2, onValue) {
return onValue(o2);
};
var exists2 = function(f2) {
return f2(o2);
};
var forall2 = function(f2) {
return f2(o2);
};
var toOptional = function() {
return Optional.some(o2);
};
return {
isValue: always,
isError: never,
getOr: constant2(o2),
getOrThunk: constant2(o2),
getOrDie: constant2(o2),
or,
orThunk,
fold,
map: map3,
mapError,
each: each3,
bind: bind5,
exists: exists2,
forall: forall2,
toOptional
};
};
var error3 = function(message2) {
var getOrThunk = function(f2) {
return f2();
};
var getOrDie = function() {
return die(String(message2))();
};
var or = identity2;
var orThunk = function(f2) {
return f2();
};
var map3 = function(_f) {
return error3(message2);
};
var mapError = function(f2) {
return error3(f2(message2));
};
var bind5 = function(_f) {
return error3(message2);
};
var fold = function(onError2, _2) {
return onError2(message2);
};
return {
isValue: never,
isError: always,
getOr: identity2,
getOrThunk,
getOrDie,
or,
orThunk,
fold,
map: map3,
mapError,
each: noop2,
bind: bind5,
exists: never,
forall: always,
toOptional: Optional.none
};
};
var fromOption = function(opt, err) {
return opt.fold(function() {
return error3(err);
}, value$1);
};
var Result = {
value: value$1,
error: error3,
fromOption
};
var measure = function(startAddress, gridA, gridB) {
if (startAddress.row >= gridA.length || startAddress.column > cellLength(gridA[0])) {
return Result.error("invalid start address out of table bounds, row: " + startAddress.row + ", column: " + startAddress.column);
}
var rowRemainder = gridA.slice(startAddress.row);
var colRemainder = rowRemainder[0].cells.slice(startAddress.column);
var colRequired = cellLength(gridB[0]);
var rowRequired = gridB.length;
return Result.value({
rowDelta: rowRemainder.length - rowRequired,
colDelta: colRemainder.length - colRequired
});
};
var measureWidth = function(gridA, gridB) {
var colLengthA = cellLength(gridA[0]);
var colLengthB = cellLength(gridB[0]);
return {
rowDelta: 0,
colDelta: colLengthA - colLengthB
};
};
var measureHeight = function(gridA, gridB) {
var rowLengthA = gridA.length;
var rowLengthB = gridB.length;
return {
rowDelta: rowLengthA - rowLengthB,
colDelta: 0
};
};
var generateElements = function(amount, row2, generators, isLocked) {
var generator = row2.section === "colgroup" ? generators.col : generators.cell;
return range$1(amount, function(idx) {
return elementnew(generator(), true, isLocked(idx));
});
};
var rowFill = function(grid2, amount, generators, lockedColumns) {
var exampleRow = grid2[grid2.length - 1];
return grid2.concat(range$1(amount, function() {
var generator = exampleRow.section === "colgroup" ? generators.colgroup : generators.row;
var row2 = clone$12(exampleRow, generator, identity2);
var elements = generateElements(row2.cells.length, row2, generators, function(idx) {
return has$12(lockedColumns, idx.toString());
});
return setCells(row2, elements);
}));
};
var colFill = function(grid2, amount, generators, startIndex) {
return map$1(grid2, function(row2) {
var newChildren = generateElements(amount, row2, generators, never);
return addCells(row2, startIndex, newChildren);
});
};
var lockedColFill = function(grid2, generators, lockedColumns) {
return map$1(grid2, function(row2) {
return foldl(lockedColumns, function(acc, colNum) {
var newChild = generateElements(1, row2, generators, always)[0];
return addCell(acc, colNum, newChild);
}, row2);
});
};
var tailor = function(gridA, delta, generators) {
var fillCols = delta.colDelta < 0 ? colFill : identity2;
var fillRows = delta.rowDelta < 0 ? rowFill : identity2;
var lockedColumns = getLockedColumnsFromGrid(gridA);
var gridWidth = cellLength(gridA[0]);
var isLastColLocked = exists(lockedColumns, function(locked) {
return locked === gridWidth - 1;
});
var modifiedCols = fillCols(gridA, Math.abs(delta.colDelta), generators, isLastColLocked ? gridWidth - 1 : gridWidth);
var newLockedColumns = getLockedColumnsFromGrid(modifiedCols);
return fillRows(modifiedCols, Math.abs(delta.rowDelta), generators, mapToObject(newLockedColumns, always));
};
var isSpanning = function(grid2, row2, col2, comparator) {
var candidate = getCell(grid2[row2], col2);
var matching = curry(comparator, candidate.element);
var currentRow = grid2[row2];
return grid2.length > 1 && cellLength(currentRow) > 1 && (col2 > 0 && matching(getCellElement(currentRow, col2 - 1)) || col2 < currentRow.cells.length - 1 && matching(getCellElement(currentRow, col2 + 1)) || row2 > 0 && matching(getCellElement(grid2[row2 - 1], col2)) || row2 < grid2.length - 1 && matching(getCellElement(grid2[row2 + 1], col2)));
};
var mergeTables = function(startAddress, gridA, gridB, generator, comparator, lockedColumns) {
var startRow = startAddress.row;
var startCol = startAddress.column;
var mergeHeight = gridB.length;
var mergeWidth = cellLength(gridB[0]);
var endRow = startRow + mergeHeight;
var endCol = startCol + mergeWidth + lockedColumns.length;
var lockedColumnObj = mapToObject(lockedColumns, always);
for (var r3 = startRow; r3 < endRow; r3++) {
var skippedCol = 0;
for (var c2 = startCol; c2 < endCol; c2++) {
if (lockedColumnObj[c2]) {
skippedCol++;
continue;
}
if (isSpanning(gridA, r3, c2, comparator)) {
unmerge(gridA, getCellElement(gridA[r3], c2), comparator, generator.cell);
}
var gridBColIndex = c2 - startCol - skippedCol;
var newCell = getCell(gridB[r3 - startRow], gridBColIndex);
var newCellElm = newCell.element;
var replacement = generator.replace(newCellElm);
mutateCell(gridA[r3], c2, elementnew(replacement, true, newCell.isLocked));
}
}
return gridA;
};
var getValidStartAddress = function(currentStartAddress, grid2, lockedColumns) {
var gridColLength = cellLength(grid2[0]);
var adjustedRowAddress = extractGridDetails(grid2).cols.length + currentStartAddress.row;
var possibleColAddresses = range$1(gridColLength - currentStartAddress.column, function(num) {
return num + currentStartAddress.column;
});
var validColAddress = find$12(possibleColAddresses, function(num) {
return forall(lockedColumns, function(col2) {
return col2 !== num;
});
}).getOr(gridColLength - 1);
return {
row: adjustedRowAddress,
column: validColAddress
};
};
var getLockedColumnsWithinBounds = function(startAddress, grid2, lockedColumns) {
return filter$2(lockedColumns, function(colNum) {
return colNum >= startAddress.column && colNum <= cellLength(grid2[0]) + startAddress.column;
});
};
var merge$12 = function(startAddress, gridA, gridB, generator, comparator) {
var lockedColumns = getLockedColumnsFromGrid(gridA);
var validStartAddress = getValidStartAddress(startAddress, gridA, lockedColumns);
var gridBRows = extractGridDetails(gridB).rows;
var lockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridBRows, lockedColumns);
var result = measure(validStartAddress, gridA, gridBRows);
return result.map(function(diff2) {
var delta = __assign(__assign({}, diff2), { colDelta: diff2.colDelta - lockedColumnsWithinBounds.length });
var fittedGrid = tailor(gridA, delta, generator);
var newLockedColumns = getLockedColumnsFromGrid(fittedGrid);
var newLockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridBRows, newLockedColumns);
return mergeTables(validStartAddress, fittedGrid, gridBRows, generator, comparator, newLockedColumnsWithinBounds);
});
};
var insertCols = function(index2, gridA, gridB, generator, comparator) {
splitCols(gridA, index2, comparator, generator.cell);
var delta = measureHeight(gridB, gridA);
var fittedNewGrid = tailor(gridB, delta, generator);
var secondDelta = measureHeight(gridA, fittedNewGrid);
var fittedOldGrid = tailor(gridA, secondDelta, generator);
return map$1(fittedOldGrid, function(gridRow, i2) {
return addCells(gridRow, index2, fittedNewGrid[i2].cells);
});
};
var insertRows = function(index2, gridA, gridB, generator, comparator) {
splitRows(gridA, index2, comparator, generator.cell);
var locked = getLockedColumnsFromGrid(gridA);
var diff2 = measureWidth(gridA, gridB);
var delta = __assign(__assign({}, diff2), { colDelta: diff2.colDelta - locked.length });
var fittedOldGrid = tailor(gridA, delta, generator);
var _a3 = extractGridDetails(fittedOldGrid), oldCols = _a3.cols, oldRows = _a3.rows;
var newLocked = getLockedColumnsFromGrid(fittedOldGrid);
var secondDiff = measureWidth(gridB, gridA);
var secondDelta = __assign(__assign({}, secondDiff), { colDelta: secondDiff.colDelta + newLocked.length });
var fittedGridB = lockedColFill(gridB, generator, newLocked);
var fittedNewGrid = tailor(fittedGridB, secondDelta, generator);
return oldCols.concat(oldRows.slice(0, index2)).concat(fittedNewGrid).concat(oldRows.slice(index2, oldRows.length));
};
var cloneRow = function(row2, cloneCell, comparator, substitution) {
return clone$12(row2, function(elem) {
return substitution(elem, comparator);
}, cloneCell);
};
var insertRowAt = function(grid2, index2, example, comparator, substitution) {
var _a3 = extractGridDetails(grid2), rows2 = _a3.rows, cols = _a3.cols;
var before2 = rows2.slice(0, index2);
var after2 = rows2.slice(index2);
var newRow = cloneRow(rows2[example], function(ex, c2) {
var withinSpan = index2 > 0 && index2 < rows2.length && comparator(getCellElement(rows2[index2 - 1], c2), getCellElement(rows2[index2], c2));
var ret = withinSpan ? getCell(rows2[index2], c2) : elementnew(substitution(ex.element, comparator), true, ex.isLocked);
return ret;
}, comparator, substitution);
return cols.concat(before2).concat([newRow]).concat(after2);
};
var getElementFor = function(row2, column, section2, withinSpan, example, comparator, substitution) {
if (section2 === "colgroup" || !withinSpan) {
var cell2 = getCell(row2, example);
return elementnew(substitution(cell2.element, comparator), true, false);
} else {
return getCell(row2, column);
}
};
var insertColumnAt = function(grid2, index2, example, comparator, substitution) {
return map$1(grid2, function(row2) {
var withinSpan = index2 > 0 && index2 < cellLength(row2) && comparator(getCellElement(row2, index2 - 1), getCellElement(row2, index2));
var sub = getElementFor(row2, index2, row2.section, withinSpan, example, comparator, substitution);
return addCell(row2, index2, sub);
});
};
var deleteColumnsAt = function(grid2, columns3) {
return bind$22(grid2, function(row2) {
var existingCells = row2.cells;
var cells2 = foldr(columns3, function(acc, column) {
return column >= 0 && column < acc.length ? acc.slice(0, column).concat(acc.slice(column + 1)) : acc;
}, existingCells);
return cells2.length > 0 ? [rowcells(row2.element, cells2, row2.section, row2.isNew)] : [];
});
};
var deleteRowsAt = function(grid2, start, finish) {
var _a3 = extractGridDetails(grid2), rows2 = _a3.rows, cols = _a3.cols;
return cols.concat(rows2.slice(0, start)).concat(rows2.slice(finish + 1));
};
var notInStartRow = function(grid2, rowIndex, colIndex, comparator) {
return getCellElement(grid2[rowIndex], colIndex) !== void 0 && (rowIndex > 0 && comparator(getCellElement(grid2[rowIndex - 1], colIndex), getCellElement(grid2[rowIndex], colIndex)));
};
var notInStartColumn = function(row2, index2, comparator) {
return index2 > 0 && comparator(getCellElement(row2, index2 - 1), getCellElement(row2, index2));
};
var isDuplicatedCell = function(grid2, rowIndex, colIndex, comparator) {
return notInStartRow(grid2, rowIndex, colIndex, comparator) || notInStartColumn(grid2[rowIndex], colIndex, comparator);
};
var rowReplacerPredicate = function(targetRow, columnHeaders) {
var entireTableIsHeader = forall(columnHeaders, identity2) && isHeaderCells(targetRow.cells);
return entireTableIsHeader ? always : function(cell2, _rowIndex, colIndex) {
var type3 = name(cell2.element);
return !(type3 === "th" && columnHeaders[colIndex]);
};
};
var columnReplacePredicate = function(targetColumn, rowHeaders) {
var entireTableIsHeader = forall(rowHeaders, identity2) && isHeaderCells(targetColumn);
return entireTableIsHeader ? always : function(cell2, rowIndex, _colIndex) {
var type3 = name(cell2.element);
return !(type3 === "th" && rowHeaders[rowIndex]);
};
};
var determineScope = function(applyScope, element, newScope, isInHeader) {
var hasSpan = function(scope) {
return scope === "row" ? hasRowspan(element) : hasColspan(element);
};
var getScope = function(scope) {
return hasSpan(scope) ? scope + "group" : scope;
};
if (applyScope) {
return isHeaderCell(element) ? getScope(newScope) : null;
} else if (isInHeader && isHeaderCell(element)) {
var oppositeScope = newScope === "row" ? "col" : "row";
return getScope(oppositeScope);
} else {
return null;
}
};
var rowScopeGenerator = function(applyScope, columnHeaders) {
return function(cell2, rowIndex, columnIndex) {
return Optional.some(determineScope(applyScope, cell2.element, "col", columnHeaders[columnIndex]));
};
};
var columnScopeGenerator = function(applyScope, rowHeaders) {
return function(cell2, rowIndex) {
return Optional.some(determineScope(applyScope, cell2.element, "row", rowHeaders[rowIndex]));
};
};
var replace2 = function(cell2, comparator, substitute) {
return elementnew(substitute(cell2.element, comparator), true, cell2.isLocked);
};
var replaceIn = function(grid2, targets, comparator, substitute, replacer, genScope, shouldReplace) {
var isTarget = function(cell2) {
return exists(targets, function(target) {
return comparator(cell2.element, target.element);
});
};
return map$1(grid2, function(row2, rowIndex) {
return mapCells(row2, function(cell2, colIndex) {
if (isTarget(cell2)) {
var newCell_1 = shouldReplace(cell2, rowIndex, colIndex) ? replacer(cell2, comparator, substitute) : cell2;
genScope(newCell_1, rowIndex, colIndex).each(function(scope) {
setOptions(newCell_1.element, { scope: Optional.from(scope) });
});
return newCell_1;
} else {
return cell2;
}
});
});
};
var getColumnCells = function(rows2, columnIndex, comparator) {
return bind$22(rows2, function(row2, i2) {
return isDuplicatedCell(rows2, i2, columnIndex, comparator) ? [] : [getCell(row2, columnIndex)];
});
};
var getRowCells = function(rows2, rowIndex, comparator) {
var targetRow = rows2[rowIndex];
return bind$22(targetRow.cells, function(item, i2) {
return isDuplicatedCell(rows2, rowIndex, i2, comparator) ? [] : [item];
});
};
var replaceColumns = function(grid2, indexes, applyScope, comparator, substitution) {
var rows2 = extractGridDetails(grid2).rows;
var targets = bind$22(indexes, function(index2) {
return getColumnCells(rows2, index2, comparator);
});
var rowHeaders = map$1(grid2, function(row2) {
return isHeaderCells(row2.cells);
});
var shouldReplaceCell = columnReplacePredicate(targets, rowHeaders);
var scopeGenerator = columnScopeGenerator(applyScope, rowHeaders);
return replaceIn(grid2, targets, comparator, substitution, replace2, scopeGenerator, shouldReplaceCell);
};
var replaceRows = function(grid2, indexes, section2, applyScope, comparator, substitution, tableSection) {
var _a3 = extractGridDetails(grid2), cols = _a3.cols, rows2 = _a3.rows;
var targetRow = rows2[indexes[0]];
var targets = bind$22(indexes, function(index2) {
return getRowCells(rows2, index2, comparator);
});
var columnHeaders = map$1(targetRow.cells, function(_cell, index2) {
return isHeaderCells(getColumnCells(rows2, index2, comparator));
});
var newRows = __spreadArray([], rows2, true);
each$2(indexes, function(index2) {
newRows[index2] = tableSection.transformRow(rows2[index2], section2);
});
var newGrid = cols.concat(newRows);
var shouldReplaceCell = rowReplacerPredicate(targetRow, columnHeaders);
var scopeGenerator = rowScopeGenerator(applyScope, columnHeaders);
return replaceIn(newGrid, targets, comparator, substitution, tableSection.transformCell, scopeGenerator, shouldReplaceCell);
};
var replaceCells = function(grid2, details, comparator, substitution) {
var rows2 = extractGridDetails(grid2).rows;
var targetCells = map$1(details, function(detail2) {
return getCell(rows2[detail2.row], detail2.column);
});
return replaceIn(grid2, targetCells, comparator, substitution, replace2, Optional.none, always);
};
var uniqueColumns = function(details) {
var uniqueCheck = function(rest, detail2) {
var columnExists = exists(rest, function(currentDetail) {
return currentDetail.column === detail2.column;
});
return columnExists ? rest : rest.concat([detail2]);
};
return foldl(details, uniqueCheck, []).sort(function(detailA, detailB) {
return detailA.column - detailB.column;
});
};
var isCol = isTag("col");
var isColgroup = isTag("colgroup");
var isRow$1 = function(element) {
return name(element) === "tr" || isColgroup(element);
};
var elementToData = function(element) {
var colspan = getAttrValue(element, "colspan", 1);
var rowspan = getAttrValue(element, "rowspan", 1);
return {
element,
colspan,
rowspan
};
};
var modification = function(generators, toData) {
if (toData === void 0) {
toData = elementToData;
}
var nuCell = function(data65) {
return isCol(data65.element) ? generators.col(data65) : generators.cell(data65);
};
var nuRow = function(data65) {
return isColgroup(data65.element) ? generators.colgroup(data65) : generators.row(data65);
};
var add4 = function(element) {
if (isRow$1(element)) {
return nuRow({ element });
} else {
var replacement = nuCell(toData(element));
recent = Optional.some({
item: element,
replacement
});
return replacement;
}
};
var recent = Optional.none();
var getOrInit = function(element, comparator) {
return recent.fold(function() {
return add4(element);
}, function(p) {
return comparator(element, p.item) ? p.replacement : add4(element);
});
};
return { getOrInit };
};
var transform2 = function(tag) {
return function(generators) {
var list = [];
var find3 = function(element, comparator) {
return find$12(list, function(x2) {
return comparator(x2.item, element);
});
};
var makeNew = function(element) {
var attrs = tag === "td" ? { scope: null } : {};
var cell2 = generators.replace(element, tag, attrs);
list.push({
item: element,
sub: cell2
});
return cell2;
};
var replaceOrInit = function(element, comparator) {
if (isRow$1(element) || isCol(element)) {
return element;
} else {
return find3(element, comparator).fold(function() {
return makeNew(element);
}, function(p) {
return comparator(element, p.item) ? p.sub : makeNew(element);
});
}
};
return { replaceOrInit };
};
};
var getScopeAttribute = function(cell2) {
return getOpt(cell2, "scope").map(function(attribute) {
return attribute.substr(0, 3);
});
};
var merging = function(generators) {
var unmerge2 = function(cell2) {
var scope = getScopeAttribute(cell2);
scope.each(function(attribute) {
return set$2(cell2, "scope", attribute);
});
return function() {
var raw = generators.cell({
element: cell2,
colspan: 1,
rowspan: 1
});
remove$6(raw, "width");
remove$6(cell2, "width");
scope.each(function(attribute) {
return set$2(raw, "scope", attribute);
});
return raw;
};
};
var merge5 = function(cells2) {
var getScopeProperty = function() {
var stringAttributes2 = cat(map$1(cells2, getScopeAttribute));
if (stringAttributes2.length === 0) {
return Optional.none();
} else {
var baseScope_1 = stringAttributes2[0];
var scopes_1 = [
"row",
"col"
];
var isMixed = exists(stringAttributes2, function(attribute) {
return attribute !== baseScope_1 && contains$2(scopes_1, attribute);
});
return isMixed ? Optional.none() : Optional.from(baseScope_1);
}
};
remove$6(cells2[0], "width");
getScopeProperty().fold(function() {
return remove$7(cells2[0], "scope");
}, function(attribute) {
return set$2(cells2[0], "scope", attribute + "group");
});
return constant2(cells2[0]);
};
return {
unmerge: unmerge2,
merge: merge5
};
};
var Generators = {
modification,
transform: transform2,
merging
};
var blockList = [
"body",
"p",
"div",
"article",
"aside",
"figcaption",
"figure",
"footer",
"header",
"nav",
"section",
"ol",
"ul",
"table",
"thead",
"tfoot",
"tbody",
"caption",
"tr",
"td",
"th",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"blockquote",
"pre",
"address"
];
var isList$1 = function(universe2, item) {
var tagName = universe2.property().name(item);
return contains$2([
"ol",
"ul"
], tagName);
};
var isBlock$1 = function(universe2, item) {
var tagName = universe2.property().name(item);
return contains$2(blockList, tagName);
};
var isEmptyTag$1 = function(universe2, item) {
return contains$2([
"br",
"img",
"hr",
"input"
], universe2.property().name(item));
};
var universe$1 = DomUniverse();
var isBlock = function(element) {
return isBlock$1(universe$1, element);
};
var isList = function(element) {
return isList$1(universe$1, element);
};
var isEmptyTag = function(element) {
return isEmptyTag$1(universe$1, element);
};
var merge4 = function(cells2) {
var isBr2 = function(el) {
return name(el) === "br";
};
var advancedBr = function(children2) {
return forall(children2, function(c2) {
return isBr2(c2) || isText(c2) && get$9(c2).trim().length === 0;
});
};
var isListItem = function(el) {
return name(el) === "li" || ancestor$2(el, isList).isSome();
};
var siblingIsBlock = function(el) {
return nextSibling(el).map(function(rightSibling) {
if (isBlock(rightSibling)) {
return true;
}
if (isEmptyTag(rightSibling)) {
return name(rightSibling) === "img" ? false : true;
}
return false;
}).getOr(false);
};
var markCell = function(cell2) {
return last$1(cell2).bind(function(rightEdge) {
var rightSiblingIsBlock = siblingIsBlock(rightEdge);
return parent2(rightEdge).map(function(parent3) {
return rightSiblingIsBlock === true || isListItem(parent3) || isBr2(rightEdge) || isBlock(parent3) && !eq$1(cell2, parent3) ? [] : [SugarElement.fromTag("br")];
});
}).getOr([]);
};
var markContent = function() {
var content = bind$22(cells2, function(cell2) {
var children2 = children$3(cell2);
return advancedBr(children2) ? [] : children2.concat(markCell(cell2));
});
return content.length === 0 ? [SugarElement.fromTag("br")] : content;
};
var contents = markContent();
empty2(cells2[0]);
append(cells2[0], contents);
};
var isEditable = function(elem) {
return isEditable$1(elem, true);
};
var prune = function(table3) {
var cells2 = cells$1(table3);
if (cells2.length === 0) {
remove$5(table3);
}
};
var outcome = function(grid2, cursor) {
return {
grid: grid2,
cursor
};
};
var findEditableCursorPosition = function(rows2) {
return findMap(rows2, function(row2) {
return findMap(row2.cells, function(cell2) {
var elem = cell2.element;
return someIf(isEditable(elem), elem);
});
});
};
var elementFromGrid = function(grid2, row2, column) {
var _a3, _b2;
var rows2 = extractGridDetails(grid2).rows;
return Optional.from((_b2 = (_a3 = rows2[row2]) === null || _a3 === void 0 ? void 0 : _a3.cells[column]) === null || _b2 === void 0 ? void 0 : _b2.element).filter(isEditable).orThunk(function() {
return findEditableCursorPosition(rows2);
});
};
var bundle = function(grid2, row2, column) {
var cursorElement = elementFromGrid(grid2, row2, column);
return outcome(grid2, cursorElement);
};
var uniqueRows = function(details) {
var rowCompilation = function(rest, detail2) {
var rowExists = exists(rest, function(currentDetail) {
return currentDetail.row === detail2.row;
});
return rowExists ? rest : rest.concat([detail2]);
};
return foldl(details, rowCompilation, []).sort(function(detailA, detailB) {
return detailA.row - detailB.row;
});
};
var opInsertRowsBefore = function(grid2, details, comparator, genWrappers) {
var targetIndex = details[0].row;
var rows2 = uniqueRows(details);
var newGrid = foldr(rows2, function(acc, row2) {
var newG = insertRowAt(acc.grid, targetIndex, row2.row + acc.delta, comparator, genWrappers.getOrInit);
return {
grid: newG,
delta: acc.delta + 1
};
}, {
grid: grid2,
delta: 0
}).grid;
return bundle(newGrid, targetIndex, details[0].column);
};
var opInsertRowsAfter = function(grid2, details, comparator, genWrappers) {
var rows2 = uniqueRows(details);
var target = rows2[rows2.length - 1];
var targetIndex = target.row + target.rowspan;
var newGrid = foldr(rows2, function(newG, row2) {
return insertRowAt(newG, targetIndex, row2.row, comparator, genWrappers.getOrInit);
}, grid2);
return bundle(newGrid, targetIndex, details[0].column);
};
var opInsertColumnsBefore = function(grid2, extractDetail, comparator, genWrappers) {
var details = extractDetail.details;
var columns3 = uniqueColumns(details);
var targetIndex = columns3[0].column;
var newGrid = foldr(columns3, function(acc, col2) {
var newG = insertColumnAt(acc.grid, targetIndex, col2.column + acc.delta, comparator, genWrappers.getOrInit);
return {
grid: newG,
delta: acc.delta + 1
};
}, {
grid: grid2,
delta: 0
}).grid;
return bundle(newGrid, details[0].row, targetIndex);
};
var opInsertColumnsAfter = function(grid2, extractDetail, comparator, genWrappers) {
var details = extractDetail.details;
var target = details[details.length - 1];
var targetIndex = target.column + target.colspan;
var columns3 = uniqueColumns(details);
var newGrid = foldr(columns3, function(newG, col2) {
return insertColumnAt(newG, targetIndex, col2.column, comparator, genWrappers.getOrInit);
}, grid2);
return bundle(newGrid, details[0].row, targetIndex);
};
var opMakeColumnsHeader = function(initialGrid, details, comparator, genWrappers) {
var columns3 = uniqueColumns(details);
var columnIndexes = map$1(columns3, function(detail2) {
return detail2.column;
});
var newGrid = replaceColumns(initialGrid, columnIndexes, true, comparator, genWrappers.replaceOrInit);
return bundle(newGrid, details[0].row, details[0].column);
};
var opMakeCellsHeader = function(initialGrid, details, comparator, genWrappers) {
var newGrid = replaceCells(initialGrid, details, comparator, genWrappers.replaceOrInit);
return bundle(newGrid, details[0].row, details[0].column);
};
var opUnmakeColumnsHeader = function(initialGrid, details, comparator, genWrappers) {
var columns3 = uniqueColumns(details);
var columnIndexes = map$1(columns3, function(detail2) {
return detail2.column;
});
var newGrid = replaceColumns(initialGrid, columnIndexes, false, comparator, genWrappers.replaceOrInit);
return bundle(newGrid, details[0].row, details[0].column);
};
var opUnmakeCellsHeader = function(initialGrid, details, comparator, genWrappers) {
var newGrid = replaceCells(initialGrid, details, comparator, genWrappers.replaceOrInit);
return bundle(newGrid, details[0].row, details[0].column);
};
var makeRowsSection = function(section2, applyScope) {
return function(initialGrid, details, comparator, genWrappers, tableSection) {
var rows2 = uniqueRows(details);
var rowIndexes = map$1(rows2, function(detail2) {
return detail2.row;
});
var newGrid = replaceRows(initialGrid, rowIndexes, section2, applyScope, comparator, genWrappers.replaceOrInit, tableSection);
return bundle(newGrid, details[0].row, details[0].column);
};
};
var opMakeRowsHeader = makeRowsSection("thead", true);
var opMakeRowsBody = makeRowsSection("tbody", false);
var opMakeRowsFooter = makeRowsSection("tfoot", false);
var opEraseColumns = function(grid2, extractDetail, _comparator, _genWrappers) {
var columns3 = uniqueColumns(extractDetail.details);
var newGrid = deleteColumnsAt(grid2, map$1(columns3, function(column) {
return column.column;
}));
var maxColIndex = newGrid.length > 0 ? newGrid[0].cells.length - 1 : 0;
return bundle(newGrid, columns3[0].row, Math.min(columns3[0].column, maxColIndex));
};
var opEraseRows = function(grid2, details, _comparator, _genWrappers) {
var rows2 = uniqueRows(details);
var newGrid = deleteRowsAt(grid2, rows2[0].row, rows2[rows2.length - 1].row);
var maxRowIndex = newGrid.length > 0 ? newGrid.length - 1 : 0;
return bundle(newGrid, Math.min(details[0].row, maxRowIndex), details[0].column);
};
var opMergeCells = function(grid2, mergable2, comparator, genWrappers) {
var cells2 = mergable2.cells;
merge4(cells2);
var newGrid = merge$22(grid2, mergable2.bounds, comparator, genWrappers.merge(cells2));
return outcome(newGrid, Optional.from(cells2[0]));
};
var opUnmergeCells = function(grid2, unmergable2, comparator, genWrappers) {
var unmerge$1 = function(b2, cell2) {
return unmerge(b2, cell2, comparator, genWrappers.unmerge(cell2));
};
var newGrid = foldr(unmergable2, unmerge$1, grid2);
return outcome(newGrid, Optional.from(unmergable2[0]));
};
var opPasteCells = function(grid2, pasteDetails, comparator, _genWrappers) {
var gridify = function(table3, generators) {
var wh = Warehouse.fromTable(table3);
return toGrid(wh, generators, true);
};
var gridB = gridify(pasteDetails.clipboard, pasteDetails.generators);
var startAddress = address(pasteDetails.row, pasteDetails.column);
var mergedGrid = merge$12(startAddress, grid2, gridB, pasteDetails.generators, comparator);
return mergedGrid.fold(function() {
return outcome(grid2, Optional.some(pasteDetails.element));
}, function(newGrid) {
return bundle(newGrid, pasteDetails.row, pasteDetails.column);
});
};
var gridifyRows = function(rows2, generators, context2) {
var pasteDetails = fromPastedRows(rows2, context2.section);
var wh = Warehouse.generate(pasteDetails);
return toGrid(wh, generators, true);
};
var opPasteColsBefore = function(grid2, pasteDetails, comparator, _genWrappers) {
var rows2 = extractGridDetails(grid2).rows;
var index2 = pasteDetails.cells[0].column;
var context2 = rows2[pasteDetails.cells[0].row];
var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context2);
var mergedGrid = insertCols(index2, grid2, gridB, pasteDetails.generators, comparator);
return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
};
var opPasteColsAfter = function(grid2, pasteDetails, comparator, _genWrappers) {
var rows2 = extractGridDetails(grid2).rows;
var index2 = pasteDetails.cells[pasteDetails.cells.length - 1].column + pasteDetails.cells[pasteDetails.cells.length - 1].colspan;
var context2 = rows2[pasteDetails.cells[0].row];
var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context2);
var mergedGrid = insertCols(index2, grid2, gridB, pasteDetails.generators, comparator);
return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
};
var opPasteRowsBefore = function(grid2, pasteDetails, comparator, _genWrappers) {
var rows2 = extractGridDetails(grid2).rows;
var index2 = pasteDetails.cells[0].row;
var context2 = rows2[index2];
var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context2);
var mergedGrid = insertRows(index2, grid2, gridB, pasteDetails.generators, comparator);
return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
};
var opPasteRowsAfter = function(grid2, pasteDetails, comparator, _genWrappers) {
var rows2 = extractGridDetails(grid2).rows;
var index2 = pasteDetails.cells[pasteDetails.cells.length - 1].row + pasteDetails.cells[pasteDetails.cells.length - 1].rowspan;
var context2 = rows2[pasteDetails.cells[0].row];
var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context2);
var mergedGrid = insertRows(index2, grid2, gridB, pasteDetails.generators, comparator);
return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
};
var opGetColumnsType = function(table3, target) {
var house = Warehouse.fromTable(table3);
var details = onCells(house, target);
return details.bind(function(selectedCells) {
var lastSelectedCell = selectedCells[selectedCells.length - 1];
var minColRange = selectedCells[0].column;
var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
var selectedColumnCells = flatten$1(map$1(house.all, function(row2) {
return filter$2(row2.cells, function(cell2) {
return cell2.column >= minColRange && cell2.column < maxColRange;
});
}));
return findCommonCellType(selectedColumnCells);
}).getOr("");
};
var opGetCellsType = function(table3, target) {
var house = Warehouse.fromTable(table3);
var details = onCells(house, target);
return details.bind(findCommonCellType).getOr("");
};
var opGetRowsType = function(table3, target) {
var house = Warehouse.fromTable(table3);
var details = onCells(house, target);
return details.bind(function(selectedCells) {
var lastSelectedCell = selectedCells[selectedCells.length - 1];
var minRowRange = selectedCells[0].row;
var maxRowRange = lastSelectedCell.row + lastSelectedCell.rowspan;
var selectedRows = house.all.slice(minRowRange, maxRowRange);
return findCommonRowType(selectedRows);
}).getOr("");
};
var resize = function(table3, list, details, behaviours) {
return adjustWidthTo(table3, list, details, behaviours.sizing);
};
var adjustAndRedistributeWidths = function(table3, list, details, behaviours) {
return adjustAndRedistributeWidths$1(table3, list, details, behaviours.sizing, behaviours.resize);
};
var firstColumnIsLocked = function(_warehouse, details) {
return exists(details, function(detail2) {
return detail2.column === 0 && detail2.isLocked;
});
};
var lastColumnIsLocked = function(warehouse, details) {
return exists(details, function(detail2) {
return detail2.column + detail2.colspan >= warehouse.grid.columns && detail2.isLocked;
});
};
var getColumnsWidth = function(warehouse, details) {
var columns$12 = columns2(warehouse);
var uniqueCols = uniqueColumns(details);
return foldl(uniqueCols, function(acc, detail2) {
var column = columns$12[detail2.column];
var colWidth = column.map(getOuter$2).getOr(0);
return acc + colWidth;
}, 0);
};
var insertColumnsExtractor = function(before2) {
return function(warehouse, target) {
return onCells(warehouse, target).filter(function(details) {
var checkLocked = before2 ? firstColumnIsLocked : lastColumnIsLocked;
return !checkLocked(warehouse, details);
}).map(function(details) {
return {
details,
pixelDelta: getColumnsWidth(warehouse, details)
};
});
};
};
var eraseColumnsExtractor = function(warehouse, target) {
return onUnlockedCells(warehouse, target).map(function(details) {
return {
details,
pixelDelta: -getColumnsWidth(warehouse, details)
};
});
};
var pasteColumnsExtractor = function(before2) {
return function(warehouse, target) {
return onPasteByEditor(warehouse, target).filter(function(details) {
var checkLocked = before2 ? firstColumnIsLocked : lastColumnIsLocked;
return !checkLocked(warehouse, details.cells);
});
};
};
var headerCellGenerator = Generators.transform("th");
var bodyCellGenerator = Generators.transform("td");
var insertRowsBefore = run(opInsertRowsBefore, onCells, noop2, noop2, Generators.modification);
var insertRowsAfter = run(opInsertRowsAfter, onCells, noop2, noop2, Generators.modification);
var insertColumnsBefore = run(opInsertColumnsBefore, insertColumnsExtractor(true), adjustAndRedistributeWidths, noop2, Generators.modification);
var insertColumnsAfter = run(opInsertColumnsAfter, insertColumnsExtractor(false), adjustAndRedistributeWidths, noop2, Generators.modification);
var eraseColumns = run(opEraseColumns, eraseColumnsExtractor, adjustAndRedistributeWidths, prune, Generators.modification);
var eraseRows = run(opEraseRows, onCells, noop2, prune, Generators.modification);
var makeColumnsHeader = run(opMakeColumnsHeader, onUnlockedCells, noop2, noop2, headerCellGenerator);
var unmakeColumnsHeader = run(opUnmakeColumnsHeader, onUnlockedCells, noop2, noop2, bodyCellGenerator);
var makeRowsHeader = run(opMakeRowsHeader, onUnlockedCells, noop2, noop2, headerCellGenerator);
var makeRowsBody = run(opMakeRowsBody, onUnlockedCells, noop2, noop2, bodyCellGenerator);
var makeRowsFooter = run(opMakeRowsFooter, onUnlockedCells, noop2, noop2, bodyCellGenerator);
var makeCellsHeader = run(opMakeCellsHeader, onUnlockedCells, noop2, noop2, headerCellGenerator);
var unmakeCellsHeader = run(opUnmakeCellsHeader, onUnlockedCells, noop2, noop2, bodyCellGenerator);
var mergeCells = run(opMergeCells, onUnlockedMergable, resize, noop2, Generators.merging);
var unmergeCells = run(opUnmergeCells, onUnlockedUnmergable, resize, noop2, Generators.merging);
var pasteCells = run(opPasteCells, onPaste, resize, noop2, Generators.modification);
var pasteColsBefore = run(opPasteColsBefore, pasteColumnsExtractor(true), noop2, noop2, Generators.modification);
var pasteColsAfter = run(opPasteColsAfter, pasteColumnsExtractor(false), noop2, noop2, Generators.modification);
var pasteRowsBefore = run(opPasteRowsBefore, onPasteByEditor, noop2, noop2, Generators.modification);
var pasteRowsAfter = run(opPasteRowsAfter, onPasteByEditor, noop2, noop2, Generators.modification);
var getColumnsType = opGetColumnsType;
var getCellsType = opGetCellsType;
var getRowsType = opGetRowsType;
var TableActions = function(editor, cellSelection, lazyWire) {
var isTableBody = function(editor2) {
return name(getBody2(editor2)) === "table";
};
var lastRowGuard = function(table3) {
return isTableBody(editor) === false || getGridSize(table3).rows > 1;
};
var lastColumnGuard = function(table3) {
return isTableBody(editor) === false || getGridSize(table3).columns > 1;
};
var cloneFormats2 = getCloneElements(editor);
var colMutationOp = isResizeTableColumnResizing(editor) ? noop2 : halve;
var getTableSectionType2 = function(table3) {
switch (getTableHeaderType(editor)) {
case "section":
return TableSection.section();
case "sectionCells":
return TableSection.sectionCells();
case "cells":
return TableSection.cells();
default:
return TableSection.getTableSectionType(table3, "section");
}
};
var setSelectionFromAction = function(table3, result) {
return result.cursor.fold(function() {
var cells2 = cells$1(table3);
return head(cells2).filter(inBody).map(function(firstCell) {
cellSelection.clear(table3);
var rng = editor.dom.createRng();
rng.selectNode(firstCell.dom);
editor.selection.setRng(rng);
set$2(firstCell, "data-mce-selected", "1");
return rng;
});
}, function(cell2) {
var des = freefallRtl(cell2);
var rng = editor.dom.createRng();
rng.setStart(des.element.dom, des.offset);
rng.setEnd(des.element.dom, des.offset);
editor.selection.setRng(rng);
cellSelection.clear(table3);
return Optional.some(rng);
});
};
var execute = function(operation, guard, mutate2, lazyWire2, effect) {
return function(table3, target, noEvents) {
if (noEvents === void 0) {
noEvents = false;
}
removeDataStyle(table3);
var wire = lazyWire2();
var doc = SugarElement.fromDom(editor.getDoc());
var generators = cellOperations(mutate2, doc, cloneFormats2);
var behaviours = {
sizing: get$4(editor, table3),
resize: isResizeTableColumnResizing(editor) ? resizeTable() : preserveTable(),
section: getTableSectionType2(table3)
};
return guard(table3) ? operation(wire, table3, target, generators, behaviours).bind(function(result) {
each$2(result.newRows, function(row2) {
fireNewRow(editor, row2.dom);
});
each$2(result.newCells, function(cell2) {
fireNewCell(editor, cell2.dom);
});
var range3 = setSelectionFromAction(table3, result);
if (inBody(table3)) {
removeDataStyle(table3);
if (!noEvents) {
fireTableModified(editor, table3.dom, effect);
}
}
return range3.map(function(rng) {
return {
rng,
effect
};
});
}) : Optional.none();
};
};
var deleteRow = execute(eraseRows, lastRowGuard, noop2, lazyWire, structureModified);
var deleteColumn = execute(eraseColumns, lastColumnGuard, noop2, lazyWire, structureModified);
var insertRowsBefore$1 = execute(insertRowsBefore, always, noop2, lazyWire, structureModified);
var insertRowsAfter$1 = execute(insertRowsAfter, always, noop2, lazyWire, structureModified);
var insertColumnsBefore$1 = execute(insertColumnsBefore, always, colMutationOp, lazyWire, structureModified);
var insertColumnsAfter$1 = execute(insertColumnsAfter, always, colMutationOp, lazyWire, structureModified);
var mergeCells$1 = execute(mergeCells, always, noop2, lazyWire, structureModified);
var unmergeCells$1 = execute(unmergeCells, always, noop2, lazyWire, structureModified);
var pasteColsBefore$1 = execute(pasteColsBefore, always, noop2, lazyWire, structureModified);
var pasteColsAfter$1 = execute(pasteColsAfter, always, noop2, lazyWire, structureModified);
var pasteRowsBefore$1 = execute(pasteRowsBefore, always, noop2, lazyWire, structureModified);
var pasteRowsAfter$1 = execute(pasteRowsAfter, always, noop2, lazyWire, structureModified);
var pasteCells$1 = execute(pasteCells, always, noop2, lazyWire, styleAndStructureModified);
var makeCellsHeader$1 = execute(makeCellsHeader, always, noop2, lazyWire, structureModified);
var unmakeCellsHeader$1 = execute(unmakeCellsHeader, always, noop2, lazyWire, structureModified);
var makeColumnsHeader$1 = execute(makeColumnsHeader, always, noop2, lazyWire, structureModified);
var unmakeColumnsHeader$1 = execute(unmakeColumnsHeader, always, noop2, lazyWire, structureModified);
var makeRowsHeader$1 = execute(makeRowsHeader, always, noop2, lazyWire, structureModified);
var makeRowsBody$1 = execute(makeRowsBody, always, noop2, lazyWire, structureModified);
var makeRowsFooter$1 = execute(makeRowsFooter, always, noop2, lazyWire, structureModified);
var getTableCellType = getCellsType;
var getTableColType = getColumnsType;
var getTableRowType = getRowsType;
return {
deleteRow,
deleteColumn,
insertRowsBefore: insertRowsBefore$1,
insertRowsAfter: insertRowsAfter$1,
insertColumnsBefore: insertColumnsBefore$1,
insertColumnsAfter: insertColumnsAfter$1,
mergeCells: mergeCells$1,
unmergeCells: unmergeCells$1,
pasteColsBefore: pasteColsBefore$1,
pasteColsAfter: pasteColsAfter$1,
pasteRowsBefore: pasteRowsBefore$1,
pasteRowsAfter: pasteRowsAfter$1,
pasteCells: pasteCells$1,
makeCellsHeader: makeCellsHeader$1,
unmakeCellsHeader: unmakeCellsHeader$1,
makeColumnsHeader: makeColumnsHeader$1,
unmakeColumnsHeader: unmakeColumnsHeader$1,
makeRowsHeader: makeRowsHeader$1,
makeRowsBody: makeRowsBody$1,
makeRowsFooter: makeRowsFooter$1,
getTableRowType,
getTableCellType,
getTableColType
};
};
var DefaultRenderOptions = {
styles: {
"border-collapse": "collapse",
"width": "100%"
},
attributes: { border: "1" },
colGroups: false
};
var tableHeaderCell = function() {
return SugarElement.fromTag("th");
};
var tableCell = function() {
return SugarElement.fromTag("td");
};
var tableColumn = function() {
return SugarElement.fromTag("col");
};
var createRow = function(columns3, rowHeaders, columnHeaders, rowIndex) {
var tr = SugarElement.fromTag("tr");
for (var j2 = 0; j2 < columns3; j2++) {
var td = rowIndex < rowHeaders || j2 < columnHeaders ? tableHeaderCell() : tableCell();
if (j2 < columnHeaders) {
set$2(td, "scope", "row");
}
if (rowIndex < rowHeaders) {
set$2(td, "scope", "col");
}
append$1(td, SugarElement.fromTag("br"));
append$1(tr, td);
}
return tr;
};
var createGroupRow = function(columns3) {
var columnGroup = SugarElement.fromTag("colgroup");
range$1(columns3, function() {
return append$1(columnGroup, tableColumn());
});
return columnGroup;
};
var createRows = function(rows2, columns3, rowHeaders, columnHeaders) {
return range$1(rows2, function(r3) {
return createRow(columns3, rowHeaders, columnHeaders, r3);
});
};
var render123 = function(rows2, columns3, rowHeaders, columnHeaders, headerType, renderOpts) {
if (renderOpts === void 0) {
renderOpts = DefaultRenderOptions;
}
var table3 = SugarElement.fromTag("table");
var rowHeadersGoInThead = headerType !== "cells";
setAll(table3, renderOpts.styles);
setAll$1(table3, renderOpts.attributes);
if (renderOpts.colGroups) {
append$1(table3, createGroupRow(columns3));
}
var actualRowHeaders = Math.min(rows2, rowHeaders);
if (rowHeadersGoInThead && rowHeaders > 0) {
var thead = SugarElement.fromTag("thead");
append$1(table3, thead);
var theadRowHeaders = headerType === "sectionCells" ? actualRowHeaders : 0;
var theadRows = createRows(rowHeaders, columns3, theadRowHeaders, columnHeaders);
append(thead, theadRows);
}
var tbody = SugarElement.fromTag("tbody");
append$1(table3, tbody);
var numRows = rowHeadersGoInThead ? rows2 - actualRowHeaders : rows2;
var numRowHeaders = rowHeadersGoInThead ? 0 : rowHeaders;
var tbodyRows = createRows(numRows, columns3, numRowHeaders, columnHeaders);
append(tbody, tbodyRows);
return table3;
};
var get$22 = function(element) {
return element.dom.innerHTML;
};
var getOuter = function(element) {
var container = SugarElement.fromTag("div");
var clone5 = SugarElement.fromDom(element.dom.cloneNode(true));
append$1(container, clone5);
return get$22(container);
};
var placeCaretInCell = function(editor, cell2) {
editor.selection.select(cell2.dom, true);
editor.selection.collapse(true);
};
var selectFirstCellInTable = function(editor, tableElm) {
descendant(tableElm, "td,th").each(curry(placeCaretInCell, editor));
};
var fireEvents2 = function(editor, table3) {
each$2(descendants(table3, "tr"), function(row2) {
fireNewRow(editor, row2.dom);
each$2(descendants(row2, "th,td"), function(cell2) {
fireNewCell(editor, cell2.dom);
});
});
};
var isPercentage2 = function(width2) {
return isString3(width2) && width2.indexOf("%") !== -1;
};
var insert = function(editor, columns3, rows2, colHeaders, rowHeaders) {
var defaultStyles2 = getDefaultStyles(editor);
var options2 = {
styles: defaultStyles2,
attributes: getDefaultAttributes(editor),
colGroups: useColumnGroup(editor)
};
editor.undoManager.ignore(function() {
var table3 = render123(rows2, columns3, rowHeaders, colHeaders, getTableHeaderType(editor), options2);
set$2(table3, "data-mce-id", "__mce");
var html = getOuter(table3);
editor.insertContent(html);
editor.addVisual();
});
return descendant(getBody2(editor), 'table[data-mce-id="__mce"]').map(function(table3) {
if (isPixelsForced(editor)) {
enforcePixels(table3);
} else if (isResponsiveForced(editor)) {
enforceNone(table3);
} else if (isPercentagesForced(editor) || isPercentage2(defaultStyles2.width)) {
enforcePercentage(table3);
}
removeDataStyle(table3);
remove$7(table3, "data-mce-id");
fireEvents2(editor, table3);
selectFirstCellInTable(editor, table3);
return table3.dom;
}).getOr(null);
};
var insertTableWithDataValidation = function(editor, rows2, columns3, options2, errorMsg) {
if (options2 === void 0) {
options2 = {};
}
var checkInput = function(val) {
return isNumber2(val) && val > 0;
};
if (checkInput(rows2) && checkInput(columns3)) {
var headerRows = options2.headerRows || 0;
var headerColumns = options2.headerColumns || 0;
return insert(editor, columns3, rows2, headerColumns, headerRows);
} else {
console.error(errorMsg);
return null;
}
};
var getClipboardElements = function(getClipboard) {
return function() {
return getClipboard().fold(function() {
return [];
}, function(elems) {
return map$1(elems, function(e2) {
return e2.dom;
});
});
};
};
var setClipboardElements = function(setClipboard) {
return function(elems) {
var elmsOpt = elems.length > 0 ? Optional.some(fromDom(elems)) : Optional.none();
setClipboard(elmsOpt);
};
};
var insertTable = function(editor) {
return function(columns3, rows2, options2) {
if (options2 === void 0) {
options2 = {};
}
var table3 = insertTableWithDataValidation(editor, rows2, columns3, options2, "Invalid values for insertTable - rows and columns values are required to insert a table.");
editor.undoManager.add();
return table3;
};
};
var getApi = function(editor, clipboard, resizeHandler2, selectionTargets) {
return {
insertTable: insertTable(editor),
setClipboardRows: setClipboardElements(clipboard.setRows),
getClipboardRows: getClipboardElements(clipboard.getRows),
setClipboardCols: setClipboardElements(clipboard.setColumns),
getClipboardCols: getClipboardElements(clipboard.getColumns),
resizeHandler: resizeHandler2,
selectionTargets
};
};
var constrainSpan = function(element, property2, value25) {
var currentColspan = getAttrValue(element, property2, 1);
if (value25 === 1 || currentColspan <= 1) {
remove$7(element, property2);
} else {
set$2(element, property2, Math.min(value25, currentColspan));
}
};
var generateColGroup = function(house, minColRange, maxColRange) {
if (Warehouse.hasColumns(house)) {
var colsToCopy = filter$2(Warehouse.justColumns(house), function(col2) {
return col2.column >= minColRange && col2.column < maxColRange;
});
var copiedCols = map$1(colsToCopy, function(c2) {
var clonedCol = deep(c2.element);
constrainSpan(clonedCol, "span", maxColRange - minColRange);
return clonedCol;
});
var fakeColgroup = SugarElement.fromTag("colgroup");
append(fakeColgroup, copiedCols);
return [fakeColgroup];
} else {
return [];
}
};
var generateRows = function(house, minColRange, maxColRange) {
return map$1(house.all, function(row2) {
var cellsToCopy = filter$2(row2.cells, function(cell2) {
return cell2.column >= minColRange && cell2.column < maxColRange;
});
var copiedCells = map$1(cellsToCopy, function(cell2) {
var clonedCell = deep(cell2.element);
constrainSpan(clonedCell, "colspan", maxColRange - minColRange);
return clonedCell;
});
var fakeTR = SugarElement.fromTag("tr");
append(fakeTR, copiedCells);
return fakeTR;
});
};
var copyCols = function(table3, target) {
var house = Warehouse.fromTable(table3);
var details = onUnlockedCells(house, target);
return details.map(function(selectedCells) {
var lastSelectedCell = selectedCells[selectedCells.length - 1];
var minColRange = selectedCells[0].column;
var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
var fakeColGroups = generateColGroup(house, minColRange, maxColRange);
var fakeRows = generateRows(house, minColRange, maxColRange);
return __spreadArray(__spreadArray([], fakeColGroups, true), fakeRows, true);
});
};
var copyRows = function(table3, target, generators) {
var warehouse = Warehouse.fromTable(table3);
var details = onCells(warehouse, target);
return details.bind(function(selectedCells) {
var grid2 = toGrid(warehouse, generators, false);
var rows2 = extractGridDetails(grid2).rows;
var slicedGrid = rows2.slice(selectedCells[0].row, selectedCells[selectedCells.length - 1].row + selectedCells[selectedCells.length - 1].rowspan);
var filteredGrid = bind$22(slicedGrid, function(row2) {
var newCells = filter$2(row2.cells, function(cell2) {
return !cell2.isLocked;
});
return newCells.length > 0 ? [__assign(__assign({}, row2), { cells: newCells })] : [];
});
var slicedDetails = toDetailList(filteredGrid);
return someIf(slicedDetails.length > 0, slicedDetails);
}).map(function(slicedDetails) {
return copy(slicedDetails);
});
};
var global$2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
var getTDTHOverallStyle = function(dom, elm, name2) {
var cells2 = dom.select("td,th", elm);
var firstChildStyle;
var checkChildren = function(firstChildStyle2, elms) {
for (var i2 = 0; i2 < elms.length; i2++) {
var currentStyle = dom.getStyle(elms[i2], name2);
if (typeof firstChildStyle2 === "undefined") {
firstChildStyle2 = currentStyle;
}
if (firstChildStyle2 !== currentStyle) {
return "";
}
}
return firstChildStyle2;
};
return checkChildren(firstChildStyle, cells2);
};
var applyAlign = function(editor, elm, name2) {
if (name2) {
editor.formatter.apply("align" + name2, {}, elm);
}
};
var applyVAlign = function(editor, elm, name2) {
if (name2) {
editor.formatter.apply("valign" + name2, {}, elm);
}
};
var unApplyAlign = function(editor, elm) {
global$2.each("left center right".split(" "), function(name2) {
editor.formatter.remove("align" + name2, {}, elm);
});
};
var unApplyVAlign = function(editor, elm) {
global$2.each("top middle bottom".split(" "), function(name2) {
editor.formatter.remove("valign" + name2, {}, elm);
});
};
var verticalAlignValues = [
{
text: "None",
value: ""
},
{
text: "Top",
value: "top"
},
{
text: "Middle",
value: "middle"
},
{
text: "Bottom",
value: "bottom"
}
];
var hexColour = function(value25) {
return { value: value25 };
};
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
var isHexString = function(hex2) {
return shorthandRegex.test(hex2) || longformRegex.test(hex2);
};
var normalizeHex = function(hex2) {
return removeLeading(hex2, "#").toUpperCase();
};
var fromString$1 = function(hex2) {
return isHexString(hex2) ? Optional.some({ value: normalizeHex(hex2) }) : Optional.none();
};
var toHex2 = function(component) {
var hex2 = component.toString(16);
return (hex2.length === 1 ? "0" + hex2 : hex2).toUpperCase();
};
var fromRgba = function(rgbaColour2) {
var value25 = toHex2(rgbaColour2.red) + toHex2(rgbaColour2.green) + toHex2(rgbaColour2.blue);
return hexColour(value25);
};
var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
var rgbaColour = function(red, green, blue, alpha) {
return {
red,
green,
blue,
alpha
};
};
var fromStringValues = function(red, green, blue, alpha) {
var r3 = parseInt(red, 10);
var g2 = parseInt(green, 10);
var b2 = parseInt(blue, 10);
var a2 = parseFloat(alpha);
return rgbaColour(r3, g2, b2, a2);
};
var fromString = function(rgbaString) {
if (rgbaString === "transparent") {
return Optional.some(rgbaColour(0, 0, 0, 0));
}
var rgbMatch = rgbRegex.exec(rgbaString);
if (rgbMatch !== null) {
return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], "1"));
}
var rgbaMatch = rgbaRegex.exec(rgbaString);
if (rgbaMatch !== null) {
return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
}
return Optional.none();
};
var anyToHex = function(color) {
return fromString$1(color).orThunk(function() {
return fromString(color).map(fromRgba);
}).getOrThunk(function() {
var canvas = document.createElement("canvas");
canvas.height = 1;
canvas.width = 1;
var canvasContext = canvas.getContext("2d");
canvasContext.clearRect(0, 0, canvas.width, canvas.height);
canvasContext.fillStyle = "#FFFFFF";
canvasContext.fillStyle = color;
canvasContext.fillRect(0, 0, 1, 1);
var rgba = canvasContext.getImageData(0, 0, 1, 1).data;
var r3 = rgba[0];
var g2 = rgba[1];
var b2 = rgba[2];
var a2 = rgba[3];
return fromRgba(rgbaColour(r3, g2, b2, a2));
});
};
var Cell3 = function(initial) {
var value25 = initial;
var get3 = function() {
return value25;
};
var set3 = function(v2) {
value25 = v2;
};
return {
get: get3,
set: set3
};
};
var singleton = function(doRevoke) {
var subject = Cell3(Optional.none());
var revoke = function() {
return subject.get().each(doRevoke);
};
var clear3 = function() {
revoke();
subject.set(Optional.none());
};
var isSet2 = function() {
return subject.get().isSome();
};
var get3 = function() {
return subject.get();
};
var set3 = function(s2) {
revoke();
subject.set(Optional.some(s2));
};
return {
clear: clear3,
isSet: isSet2,
get: get3,
set: set3
};
};
var unbindable = function() {
return singleton(function(s2) {
return s2.unbind();
});
};
var value24 = function() {
var subject = singleton(noop2);
var on3 = function(f2) {
return subject.get().each(f2);
};
return __assign(__assign({}, subject), { on: on3 });
};
var onSetupToggle = function(editor, selections, formatName, formatValue2) {
return function(api3) {
var boundCallback = unbindable();
var isNone = isEmpty$1(formatValue2);
var init = function() {
var selectedCells = getCellsFromSelection(selections);
var checkNode = function(cell2) {
return editor.formatter.match(formatName, { value: formatValue2 }, cell2.dom, isNone);
};
if (isNone) {
api3.setActive(!exists(selectedCells, checkNode));
boundCallback.set(editor.formatter.formatChanged(formatName, function(match5) {
return api3.setActive(!match5);
}, true));
} else {
api3.setActive(forall(selectedCells, checkNode));
boundCallback.set(editor.formatter.formatChanged(formatName, api3.setActive, false, { value: formatValue2 }));
}
};
editor.initialized ? init() : editor.on("init", init);
return boundCallback.clear;
};
};
var isListGroup = function(item) {
return hasNonNullableKey(item, "menu");
};
var buildListItems = function(items) {
return map$1(items, function(item) {
var text = item.text || item.title;
if (isListGroup(item)) {
return {
text,
items: buildListItems(item.menu)
};
} else {
return {
text,
value: item.value
};
}
});
};
var buildMenuItems = function(editor, selections, items, format3, onAction) {
return map$1(items, function(item) {
var text = item.text || item.title;
if (isListGroup(item)) {
return {
type: "nestedmenuitem",
text,
getSubmenuItems: function() {
return buildMenuItems(editor, selections, item.menu, format3, onAction);
}
};
} else {
return {
text,
type: "togglemenuitem",
onAction: function() {
return onAction(item.value);
},
onSetup: onSetupToggle(editor, selections, format3, item.value)
};
}
});
};
var applyTableCellStyle = function(editor, style) {
return function(value25) {
var _a3;
editor.execCommand("mceTableApplyCellStyle", false, (_a3 = {}, _a3[style] = value25, _a3));
};
};
var filterNoneItem = function(list) {
return bind$22(list, function(item) {
if (isListGroup(item)) {
return [__assign(__assign({}, item), { menu: filterNoneItem(item.menu) })];
} else {
return isNotEmpty(item.value) ? [item] : [];
}
});
};
var generateMenuItemsCallback = function(editor, selections, items, format3, onAction) {
return function(callback2) {
return callback2(buildMenuItems(editor, selections, items, format3, onAction));
};
};
var buildColorMenu = function(editor, colorList, style) {
var colorMap = map$1(colorList, function(entry) {
return {
text: entry.title,
value: "#" + anyToHex(entry.value).value,
type: "choiceitem"
};
});
return [{
type: "fancymenuitem",
fancytype: "colorswatch",
initData: {
colors: colorMap.length > 0 ? colorMap : void 0,
allowCustomColors: false
},
onAction: function(data65) {
var _a3;
var value25 = data65.value === "remove" ? "" : data65.value;
editor.execCommand("mceTableApplyCellStyle", false, (_a3 = {}, _a3[style] = value25, _a3));
}
}];
};
var changeRowHeader = function(editor) {
return function() {
var currentType = editor.queryCommandValue("mceTableRowType");
var newType = currentType === "header" ? "body" : "header";
editor.execCommand("mceTableRowType", false, { type: newType });
};
};
var changeColumnHeader = function(editor) {
return function() {
var currentType = editor.queryCommandValue("mceTableColType");
var newType = currentType === "th" ? "td" : "th";
editor.execCommand("mceTableColType", false, { type: newType });
};
};
var getClassList$1 = function(editor) {
var classes3 = buildListItems(getCellClassList(editor));
if (classes3.length > 0) {
return Optional.some({
name: "class",
type: "listbox",
label: "Class",
items: classes3
});
}
return Optional.none();
};
var children = [
{
name: "width",
type: "input",
label: "Width"
},
{
name: "height",
type: "input",
label: "Height"
},
{
name: "celltype",
type: "listbox",
label: "Cell type",
items: [
{
text: "Cell",
value: "td"
},
{
text: "Header cell",
value: "th"
}
]
},
{
name: "scope",
type: "listbox",
label: "Scope",
items: [
{
text: "None",
value: ""
},
{
text: "Row",
value: "row"
},
{
text: "Column",
value: "col"
},
{
text: "Row group",
value: "rowgroup"
},
{
text: "Column group",
value: "colgroup"
}
]
},
{
name: "halign",
type: "listbox",
label: "Horizontal align",
items: [
{
text: "None",
value: ""
},
{
text: "Left",
value: "left"
},
{
text: "Center",
value: "center"
},
{
text: "Right",
value: "right"
}
]
},
{
name: "valign",
type: "listbox",
label: "Vertical align",
items: verticalAlignValues
}
];
var getItems$2 = function(editor) {
return children.concat(getClassList$1(editor).toArray());
};
var getAdvancedTab = function(editor, dialogName) {
var emptyBorderStyle = [{
text: "Select...",
value: ""
}];
var advTabItems = [
{
name: "borderstyle",
type: "listbox",
label: "Border style",
items: emptyBorderStyle.concat(buildListItems(getTableBorderStyles(editor)))
},
{
name: "bordercolor",
type: "colorinput",
label: "Border color"
},
{
name: "backgroundcolor",
type: "colorinput",
label: "Background color"
}
];
var borderWidth = {
name: "borderwidth",
type: "input",
label: "Border width"
};
var items = dialogName === "cell" ? [borderWidth].concat(advTabItems) : advTabItems;
return {
title: "Advanced",
name: "advanced",
items
};
};
var modifiers = function(testTruthy) {
return function(editor, node) {
var dom = editor.dom;
var setAttrib = function(attr, value25) {
if (!testTruthy || value25) {
dom.setAttrib(node, attr, value25);
}
};
var setStyle2 = function(prop, value25) {
if (!testTruthy || value25) {
dom.setStyle(node, prop, value25);
}
};
var setFormat = function(formatName, value25) {
if (!testTruthy || value25) {
if (value25 === "") {
editor.formatter.remove(formatName, { value: null }, node, true);
} else {
editor.formatter.apply(formatName, { value: value25 }, node);
}
}
};
return {
setAttrib,
setStyle: setStyle2,
setFormat
};
};
};
var DomModifier = {
normal: modifiers(false),
ifTruthy: modifiers(true)
};
var rgbToHex2 = function(dom) {
return function(value25) {
return startsWith(value25, "rgb") ? dom.toHex(value25) : value25;
};
};
var extractAdvancedStyles = function(dom, elm) {
var element = SugarElement.fromDom(elm);
return {
borderwidth: getRaw$2(element, "border-width").getOr(""),
borderstyle: getRaw$2(element, "border-style").getOr(""),
bordercolor: getRaw$2(element, "border-color").map(rgbToHex2(dom)).getOr(""),
backgroundcolor: getRaw$2(element, "background-color").map(rgbToHex2(dom)).getOr("")
};
};
var getSharedValues = function(data65) {
var baseData = data65[0];
var comparisonData = data65.slice(1);
each$2(comparisonData, function(items) {
each$2(keys2(baseData), function(key3) {
each$12(items, function(itemValue, itemKey) {
var comparisonValue = baseData[key3];
if (comparisonValue !== "" && key3 === itemKey) {
if (comparisonValue !== itemValue) {
baseData[key3] = "";
}
}
});
});
});
return baseData;
};
var getAlignment = function(formats2, formatName, editor, elm) {
return find$12(formats2, function(name2) {
return !isUndefined2(editor.formatter.matchNode(elm, formatName + name2));
}).getOr("");
};
var getHAlignment = curry(getAlignment, [
"left",
"center",
"right"
], "align");
var getVAlignment = curry(getAlignment, [
"top",
"middle",
"bottom"
], "valign");
var extractDataFromSettings = function(editor, hasAdvTableTab) {
var style = getDefaultStyles(editor);
var attrs = getDefaultAttributes(editor);
var extractAdvancedStyleData = function(dom) {
return {
borderstyle: get$c(style, "border-style").getOr(""),
bordercolor: rgbToHex2(dom)(get$c(style, "border-color").getOr("")),
backgroundcolor: rgbToHex2(dom)(get$c(style, "background-color").getOr(""))
};
};
var defaultData = {
height: "",
width: "100%",
cellspacing: "",
cellpadding: "",
caption: false,
class: "",
align: "",
border: ""
};
var getBorder = function() {
var borderWidth = style["border-width"];
if (shouldStyleWithCss(editor) && borderWidth) {
return { border: borderWidth };
}
return get$c(attrs, "border").fold(function() {
return {};
}, function(border) {
return { border };
});
};
var advStyle = hasAdvTableTab ? extractAdvancedStyleData(editor.dom) : {};
var getCellPaddingCellSpacing = function() {
var spacing = get$c(style, "border-spacing").or(get$c(attrs, "cellspacing")).fold(function() {
return {};
}, function(cellspacing) {
return { cellspacing };
});
var padding = get$c(style, "border-padding").or(get$c(attrs, "cellpadding")).fold(function() {
return {};
}, function(cellpadding) {
return { cellpadding };
});
return __assign(__assign({}, spacing), padding);
};
var data65 = __assign(__assign(__assign(__assign(__assign(__assign({}, defaultData), style), attrs), advStyle), getBorder()), getCellPaddingCellSpacing());
return data65;
};
var getRowType = function(elm) {
return table2(SugarElement.fromDom(elm)).map(function(table3) {
var target = { selection: fromDom(elm.cells) };
return getRowsType(table3, target);
}).getOr("");
};
var extractDataFromTableElement = function(editor, elm, hasAdvTableTab) {
var getBorder = function(dom2, elm2) {
var optBorderWidth = getRaw$2(SugarElement.fromDom(elm2), "border-width");
if (shouldStyleWithCss(editor) && optBorderWidth.isSome()) {
return optBorderWidth.getOr("");
}
return dom2.getAttrib(elm2, "border") || getTDTHOverallStyle(editor.dom, elm2, "border-width") || getTDTHOverallStyle(editor.dom, elm2, "border");
};
var dom = editor.dom;
var cellspacing = shouldStyleWithCss(editor) ? dom.getStyle(elm, "border-spacing") || dom.getAttrib(elm, "cellspacing") : dom.getAttrib(elm, "cellspacing") || dom.getStyle(elm, "border-spacing");
var cellpadding = shouldStyleWithCss(editor) ? getTDTHOverallStyle(dom, elm, "padding") || dom.getAttrib(elm, "cellpadding") : dom.getAttrib(elm, "cellpadding") || getTDTHOverallStyle(dom, elm, "padding");
return __assign({
width: dom.getStyle(elm, "width") || dom.getAttrib(elm, "width"),
height: dom.getStyle(elm, "height") || dom.getAttrib(elm, "height"),
cellspacing,
cellpadding,
border: getBorder(dom, elm),
caption: !!dom.select("caption", elm)[0],
class: dom.getAttrib(elm, "class", ""),
align: getHAlignment(editor, elm)
}, hasAdvTableTab ? extractAdvancedStyles(dom, elm) : {});
};
var extractDataFromRowElement = function(editor, elm, hasAdvancedRowTab2) {
var dom = editor.dom;
return __assign({
height: dom.getStyle(elm, "height") || dom.getAttrib(elm, "height"),
class: dom.getAttrib(elm, "class", ""),
type: getRowType(elm),
align: getHAlignment(editor, elm)
}, hasAdvancedRowTab2 ? extractAdvancedStyles(dom, elm) : {});
};
var extractDataFromCellElement = function(editor, cell2, hasAdvancedCellTab2, column) {
var dom = editor.dom;
var colElm = column.getOr(cell2);
var getStyle3 = function(element, style) {
return dom.getStyle(element, style) || dom.getAttrib(element, style);
};
return __assign({
width: getStyle3(colElm, "width"),
height: getStyle3(cell2, "height"),
scope: dom.getAttrib(cell2, "scope"),
celltype: getNodeName(cell2),
class: dom.getAttrib(cell2, "class", ""),
halign: getHAlignment(editor, cell2),
valign: getVAlignment(editor, cell2)
}, hasAdvancedCellTab2 ? extractAdvancedStyles(dom, cell2) : {});
};
var getSelectedCells = function(table3, cells2) {
var warehouse = Warehouse.fromTable(table3);
var allCells = Warehouse.justCells(warehouse);
var filtered = filter$2(allCells, function(cellA) {
return exists(cells2, function(cellB) {
return eq$1(cellA.element, cellB);
});
});
return map$1(filtered, function(cell2) {
return {
element: cell2.element.dom,
column: Warehouse.getColumnAt(warehouse, cell2.column).map(function(col2) {
return col2.element.dom;
})
};
});
};
var updateSimpleProps$1 = function(modifier, colModifier, data65) {
modifier.setAttrib("scope", data65.scope);
modifier.setAttrib("class", data65.class);
modifier.setStyle("height", addPxSuffix(data65.height));
colModifier.setStyle("width", addPxSuffix(data65.width));
};
var updateAdvancedProps$1 = function(modifier, data65) {
modifier.setFormat("tablecellbackgroundcolor", data65.backgroundcolor);
modifier.setFormat("tablecellbordercolor", data65.bordercolor);
modifier.setFormat("tablecellborderstyle", data65.borderstyle);
modifier.setFormat("tablecellborderwidth", addPxSuffix(data65.borderwidth));
};
var applyStyleData$1 = function(editor, cells2, data65) {
var isSingleCell = cells2.length === 1;
each$2(cells2, function(item) {
var cellElm = item.element;
var modifier = isSingleCell ? DomModifier.normal(editor, cellElm) : DomModifier.ifTruthy(editor, cellElm);
var colModifier = item.column.map(function(col2) {
return isSingleCell ? DomModifier.normal(editor, col2) : DomModifier.ifTruthy(editor, col2);
}).getOr(modifier);
updateSimpleProps$1(modifier, colModifier, data65);
if (hasAdvancedCellTab(editor)) {
updateAdvancedProps$1(modifier, data65);
}
if (isSingleCell) {
unApplyAlign(editor, cellElm);
unApplyVAlign(editor, cellElm);
}
if (data65.halign) {
applyAlign(editor, cellElm, data65.halign);
}
if (data65.valign) {
applyVAlign(editor, cellElm, data65.valign);
}
});
};
var applyStructureData$1 = function(editor, data65) {
editor.execCommand("mceTableCellType", false, {
type: data65.celltype,
no_events: true
});
};
var applyCellData = function(editor, cells2, oldData, data65) {
var modifiedData = filter$1(data65, function(value25, key3) {
return oldData[key3] !== value25;
});
if (size(modifiedData) > 0 && cells2.length >= 1) {
table2(cells2[0]).each(function(table3) {
var selectedCells = getSelectedCells(table3, cells2);
var styleModified2 = size(filter$1(modifiedData, function(_value, key3) {
return key3 !== "scope" && key3 !== "celltype";
})) > 0;
var structureModified2 = has$12(modifiedData, "celltype");
if (styleModified2 || has$12(modifiedData, "scope")) {
applyStyleData$1(editor, selectedCells, data65);
}
if (structureModified2) {
applyStructureData$1(editor, data65);
}
fireTableModified(editor, table3.dom, {
structure: structureModified2,
style: styleModified2
});
});
}
};
var onSubmitCellForm = function(editor, cells2, oldData, api3) {
var data65 = api3.getData();
api3.close();
editor.undoManager.transact(function() {
applyCellData(editor, cells2, oldData, data65);
editor.focus();
});
};
var getData = function(editor, cells2) {
var cellsData = table2(cells2[0]).map(function(table3) {
return map$1(getSelectedCells(table3, cells2), function(item) {
return extractDataFromCellElement(editor, item.element, hasAdvancedCellTab(editor), item.column);
});
});
return getSharedValues(cellsData.getOrDie());
};
var open$2 = function(editor, selections) {
var cells2 = getCellsFromSelection(selections);
if (cells2.length === 0) {
return;
}
var data65 = getData(editor, cells2);
var dialogTabPanel = {
type: "tabpanel",
tabs: [
{
title: "General",
name: "general",
items: getItems$2(editor)
},
getAdvancedTab(editor, "cell")
]
};
var dialogPanel = {
type: "panel",
items: [{
type: "grid",
columns: 2,
items: getItems$2(editor)
}]
};
editor.windowManager.open({
title: "Cell Properties",
size: "normal",
body: hasAdvancedCellTab(editor) ? dialogTabPanel : dialogPanel,
buttons: [
{
type: "cancel",
name: "cancel",
text: "Cancel"
},
{
type: "submit",
name: "save",
text: "Save",
primary: true
}
],
initialData: data65,
onSubmit: curry(onSubmitCellForm, editor, cells2, data65)
});
};
var getClassList = function(editor) {
var classes3 = buildListItems(getRowClassList(editor));
if (classes3.length > 0) {
return Optional.some({
name: "class",
type: "listbox",
label: "Class",
items: classes3
});
}
return Optional.none();
};
var formChildren = [
{
type: "listbox",
name: "type",
label: "Row type",
items: [
{
text: "Header",
value: "header"
},
{
text: "Body",
value: "body"
},
{
text: "Footer",
value: "footer"
}
]
},
{
type: "listbox",
name: "align",
label: "Alignment",
items: [
{
text: "None",
value: ""
},
{
text: "Left",
value: "left"
},
{
text: "Center",
value: "center"
},
{
text: "Right",
value: "right"
}
]
},
{
label: "Height",
name: "height",
type: "input"
}
];
var getItems$1 = function(editor) {
return formChildren.concat(getClassList(editor).toArray());
};
var updateSimpleProps = function(modifier, data65) {
modifier.setAttrib("class", data65.class);
modifier.setStyle("height", addPxSuffix(data65.height));
};
var updateAdvancedProps = function(modifier, data65) {
modifier.setStyle("background-color", data65.backgroundcolor);
modifier.setStyle("border-color", data65.bordercolor);
modifier.setStyle("border-style", data65.borderstyle);
};
var applyStyleData = function(editor, rows2, data65, oldData) {
var isSingleRow = rows2.length === 1;
each$2(rows2, function(rowElm) {
var modifier = isSingleRow ? DomModifier.normal(editor, rowElm) : DomModifier.ifTruthy(editor, rowElm);
updateSimpleProps(modifier, data65);
if (hasAdvancedRowTab(editor)) {
updateAdvancedProps(modifier, data65);
}
if (data65.align !== oldData.align) {
unApplyAlign(editor, rowElm);
applyAlign(editor, rowElm, data65.align);
}
});
};
var applyStructureData = function(editor, data65) {
editor.execCommand("mceTableRowType", false, {
type: data65.type,
no_events: true
});
};
var applyRowData = function(editor, rows2, oldData, data65) {
var modifiedData = filter$1(data65, function(value25, key3) {
return oldData[key3] !== value25;
});
if (size(modifiedData) > 0) {
var typeModified_1 = has$12(modifiedData, "type");
var styleModified_1 = typeModified_1 ? size(modifiedData) > 1 : true;
if (styleModified_1) {
applyStyleData(editor, rows2, data65, oldData);
}
if (typeModified_1) {
applyStructureData(editor, data65);
}
table2(SugarElement.fromDom(rows2[0])).each(function(table3) {
return fireTableModified(editor, table3.dom, {
structure: typeModified_1,
style: styleModified_1
});
});
}
};
var onSubmitRowForm = function(editor, rows2, oldData, api3) {
var data65 = api3.getData();
api3.close();
editor.undoManager.transact(function() {
applyRowData(editor, rows2, oldData, data65);
editor.focus();
});
};
var open$1 = function(editor) {
var rows2 = getRowsFromSelection(getSelectionStart(editor), ephemera.selected);
if (rows2.length === 0) {
return;
}
var rowsData = map$1(rows2, function(rowElm) {
return extractDataFromRowElement(editor, rowElm.dom, hasAdvancedRowTab(editor));
});
var data65 = getSharedValues(rowsData);
var dialogTabPanel = {
type: "tabpanel",
tabs: [
{
title: "General",
name: "general",
items: getItems$1(editor)
},
getAdvancedTab(editor, "row")
]
};
var dialogPanel = {
type: "panel",
items: [{
type: "grid",
columns: 2,
items: getItems$1(editor)
}]
};
editor.windowManager.open({
title: "Row Properties",
size: "normal",
body: hasAdvancedRowTab(editor) ? dialogTabPanel : dialogPanel,
buttons: [
{
type: "cancel",
name: "cancel",
text: "Cancel"
},
{
type: "submit",
name: "save",
text: "Save",
primary: true
}
],
initialData: data65,
onSubmit: curry(onSubmitRowForm, editor, map$1(rows2, function(r3) {
return r3.dom;
}), data65)
});
};
var getItems = function(editor, classes3, insertNewTable) {
var rowColCountItems = !insertNewTable ? [] : [
{
type: "input",
name: "cols",
label: "Cols",
inputMode: "numeric"
},
{
type: "input",
name: "rows",
label: "Rows",
inputMode: "numeric"
}
];
var alwaysItems = [
{
type: "input",
name: "width",
label: "Width"
},
{
type: "input",
name: "height",
label: "Height"
}
];
var appearanceItems = hasAppearanceOptions(editor) ? [
{
type: "input",
name: "cellspacing",
label: "Cell spacing",
inputMode: "numeric"
},
{
type: "input",
name: "cellpadding",
label: "Cell padding",
inputMode: "numeric"
},
{
type: "input",
name: "border",
label: "Border width"
},
{
type: "label",
label: "Caption",
items: [{
type: "checkbox",
name: "caption",
label: "Show caption"
}]
}
] : [];
var alignmentItem = [{
type: "listbox",
name: "align",
label: "Alignment",
items: [
{
text: "None",
value: ""
},
{
text: "Left",
value: "left"
},
{
text: "Center",
value: "center"
},
{
text: "Right",
value: "right"
}
]
}];
var classListItem = classes3.length > 0 ? [{
type: "listbox",
name: "class",
label: "Class",
items: classes3
}] : [];
return rowColCountItems.concat(alwaysItems).concat(appearanceItems).concat(alignmentItem).concat(classListItem);
};
var styleTDTH = function(dom, elm, name2, value25) {
if (elm.tagName === "TD" || elm.tagName === "TH") {
if (isString3(name2)) {
dom.setStyle(elm, name2, value25);
} else {
dom.setStyle(elm, name2);
}
} else {
if (elm.children) {
for (var i2 = 0; i2 < elm.children.length; i2++) {
styleTDTH(dom, elm.children[i2], name2, value25);
}
}
}
};
var applyDataToElement = function(editor, tableElm, data65) {
var dom = editor.dom;
var attrs = {};
var styles2 = {};
attrs.class = data65.class;
styles2.height = addPxSuffix(data65.height);
if (dom.getAttrib(tableElm, "width") && !shouldStyleWithCss(editor)) {
attrs.width = removePxSuffix(data65.width);
} else {
styles2.width = addPxSuffix(data65.width);
}
if (shouldStyleWithCss(editor)) {
styles2["border-width"] = addPxSuffix(data65.border);
styles2["border-spacing"] = addPxSuffix(data65.cellspacing);
} else {
attrs.border = data65.border;
attrs.cellpadding = data65.cellpadding;
attrs.cellspacing = data65.cellspacing;
}
if (shouldStyleWithCss(editor) && tableElm.children) {
for (var i2 = 0; i2 < tableElm.children.length; i2++) {
styleTDTH(dom, tableElm.children[i2], {
"border-width": addPxSuffix(data65.border),
"padding": addPxSuffix(data65.cellpadding)
});
if (hasAdvancedTableTab(editor)) {
styleTDTH(dom, tableElm.children[i2], { "border-color": data65.bordercolor });
}
}
}
if (hasAdvancedTableTab(editor)) {
styles2["background-color"] = data65.backgroundcolor;
styles2["border-color"] = data65.bordercolor;
styles2["border-style"] = data65.borderstyle;
}
attrs.style = dom.serializeStyle(__assign(__assign({}, getDefaultStyles(editor)), styles2));
dom.setAttribs(tableElm, __assign(__assign({}, getDefaultAttributes(editor)), attrs));
};
var onSubmitTableForm = function(editor, tableElm, oldData, api3) {
var dom = editor.dom;
var data65 = api3.getData();
var modifiedData = filter$1(data65, function(value25, key3) {
return oldData[key3] !== value25;
});
api3.close();
if (data65.class === "") {
delete data65.class;
}
editor.undoManager.transact(function() {
if (!tableElm) {
var cols = parseInt(data65.cols, 10) || 1;
var rows2 = parseInt(data65.rows, 10) || 1;
tableElm = insert(editor, cols, rows2, 0, 0);
}
if (size(modifiedData) > 0) {
applyDataToElement(editor, tableElm, data65);
var captionElm = dom.select("caption", tableElm)[0];
if (captionElm && !data65.caption || !captionElm && data65.caption) {
editor.execCommand("mceTableToggleCaption");
}
if (data65.align === "") {
unApplyAlign(editor, tableElm);
} else {
applyAlign(editor, tableElm, data65.align);
}
}
editor.focus();
editor.addVisual();
if (size(modifiedData) > 0) {
var captionModified = has$12(modifiedData, "caption");
var styleModified2 = captionModified ? size(modifiedData) > 1 : true;
fireTableModified(editor, tableElm, {
structure: captionModified,
style: styleModified2
});
}
});
};
var open6 = function(editor, insertNewTable) {
var dom = editor.dom;
var tableElm;
var data65 = extractDataFromSettings(editor, hasAdvancedTableTab(editor));
if (insertNewTable === false) {
tableElm = dom.getParent(editor.selection.getStart(), "table", editor.getBody());
if (tableElm) {
data65 = extractDataFromTableElement(editor, tableElm, hasAdvancedTableTab(editor));
} else {
if (hasAdvancedTableTab(editor)) {
data65.borderstyle = "";
data65.bordercolor = "";
data65.backgroundcolor = "";
}
}
} else {
data65.cols = "1";
data65.rows = "1";
if (hasAdvancedTableTab(editor)) {
data65.borderstyle = "";
data65.bordercolor = "";
data65.backgroundcolor = "";
}
}
var classes3 = buildListItems(getTableClassList(editor));
if (classes3.length > 0) {
if (data65.class) {
data65.class = data65.class.replace(/\s*mce\-item\-table\s*/g, "");
}
}
var generalPanel = {
type: "grid",
columns: 2,
items: getItems(editor, classes3, insertNewTable)
};
var nonAdvancedForm = function() {
return {
type: "panel",
items: [generalPanel]
};
};
var advancedForm = function() {
return {
type: "tabpanel",
tabs: [
{
title: "General",
name: "general",
items: [generalPanel]
},
getAdvancedTab(editor, "table")
]
};
};
var dialogBody = hasAdvancedTableTab(editor) ? advancedForm() : nonAdvancedForm();
editor.windowManager.open({
title: "Table Properties",
size: "normal",
body: dialogBody,
onSubmit: curry(onSubmitTableForm, editor, tableElm, data65),
buttons: [
{
type: "cancel",
name: "cancel",
text: "Cancel"
},
{
type: "submit",
name: "save",
text: "Save",
primary: true
}
],
initialData: data65
});
};
var getSelectionStartCellOrCaption = function(editor) {
return getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
};
var getSelectionStartCell = function(editor) {
return getSelectionCell(getSelectionStart(editor), getIsRoot(editor));
};
var registerCommands = function(editor, actions, cellSelection, selections, clipboard) {
var isRoot = getIsRoot(editor);
var eraseTable = function() {
return getSelectionStartCellOrCaption(editor).each(function(cellOrCaption) {
table2(cellOrCaption, isRoot).filter(not(isRoot)).each(function(table3) {
var cursor = SugarElement.fromText("");
after$5(table3, cursor);
remove$5(table3);
if (editor.dom.isEmpty(editor.getBody())) {
editor.setContent("");
editor.selection.setCursorLocation();
} else {
var rng = editor.dom.createRng();
rng.setStart(cursor.dom, 0);
rng.setEnd(cursor.dom, 0);
editor.selection.setRng(rng);
editor.nodeChanged();
}
});
});
};
var setSizingMode = function(sizing) {
return getSelectionStartCellOrCaption(editor).each(function(cellOrCaption) {
var isForcedSizing = isResponsiveForced(editor) || isPixelsForced(editor) || isPercentagesForced(editor);
if (!isForcedSizing) {
table2(cellOrCaption, isRoot).each(function(table3) {
if (sizing === "relative" && !isPercentSizing(table3)) {
enforcePercentage(table3);
} else if (sizing === "fixed" && !isPixelSizing(table3)) {
enforcePixels(table3);
} else if (sizing === "responsive" && !isNoneSizing(table3)) {
enforceNone(table3);
}
removeDataStyle(table3);
fireTableModified(editor, table3.dom, structureModified);
});
}
});
};
var getTableFromCell = function(cell2) {
return table2(cell2, isRoot);
};
var performActionOnSelection = function(action) {
return getSelectionStartCell(editor).bind(function(cell2) {
return getTableFromCell(cell2).map(function(table3) {
return action(table3, cell2);
});
});
};
var toggleTableClass = function(_ui, clazz) {
performActionOnSelection(function(table3) {
editor.formatter.toggle("tableclass", { value: clazz }, table3.dom);
fireTableModified(editor, table3.dom, styleModified);
});
};
var toggleTableCellClass = function(_ui, clazz) {
performActionOnSelection(function(table3) {
var selectedCells = getCellsFromSelection(selections);
var allHaveClass = forall(selectedCells, function(cell2) {
return editor.formatter.match("tablecellclass", { value: clazz }, cell2.dom);
});
var formatterAction = allHaveClass ? editor.formatter.remove : editor.formatter.apply;
each$2(selectedCells, function(cell2) {
return formatterAction("tablecellclass", { value: clazz }, cell2.dom);
});
fireTableModified(editor, table3.dom, styleModified);
});
};
var toggleCaption = function() {
getSelectionStartCellOrCaption(editor).each(function(cellOrCaption) {
table2(cellOrCaption, isRoot).each(function(table3) {
child$1(table3, "caption").fold(function() {
var caption = SugarElement.fromTag("caption");
append$1(caption, SugarElement.fromText("Caption"));
appendAt(table3, caption, 0);
editor.selection.setCursorLocation(caption.dom, 0);
}, function(caption) {
if (isTag("caption")(cellOrCaption)) {
one("td", table3).each(function(td) {
return editor.selection.setCursorLocation(td.dom, 0);
});
}
remove$5(caption);
});
fireTableModified(editor, table3.dom, structureModified);
});
});
};
var postExecute = function(_data) {
editor.focus();
};
var actOnSelection = function(execute, noEvents) {
if (noEvents === void 0) {
noEvents = false;
}
return performActionOnSelection(function(table3, startCell) {
var targets = forMenu(selections, table3, startCell);
execute(table3, targets, noEvents).each(postExecute);
});
};
var copyRowSelection = function() {
return performActionOnSelection(function(table3, startCell) {
var targets = forMenu(selections, table3, startCell);
var generators = cellOperations(noop2, SugarElement.fromDom(editor.getDoc()), Optional.none());
return copyRows(table3, targets, generators);
});
};
var copyColSelection = function() {
return performActionOnSelection(function(table3, startCell) {
var targets = forMenu(selections, table3, startCell);
return copyCols(table3, targets);
});
};
var pasteOnSelection = function(execute, getRows2) {
return getRows2().each(function(rows2) {
var clonedRows = map$1(rows2, function(row2) {
return deep(row2);
});
performActionOnSelection(function(table3, startCell) {
var generators = paste$1(SugarElement.fromDom(editor.getDoc()));
var targets = pasteRows(selections, startCell, clonedRows, generators);
execute(table3, targets).each(postExecute);
});
});
};
var actOnType = function(getAction) {
return function(_ui, args) {
return get$c(args, "type").each(function(type3) {
actOnSelection(getAction(type3), args.no_events);
});
};
};
each$12({
mceTableSplitCells: function() {
return actOnSelection(actions.unmergeCells);
},
mceTableMergeCells: function() {
return actOnSelection(actions.mergeCells);
},
mceTableInsertRowBefore: function() {
return actOnSelection(actions.insertRowsBefore);
},
mceTableInsertRowAfter: function() {
return actOnSelection(actions.insertRowsAfter);
},
mceTableInsertColBefore: function() {
return actOnSelection(actions.insertColumnsBefore);
},
mceTableInsertColAfter: function() {
return actOnSelection(actions.insertColumnsAfter);
},
mceTableDeleteCol: function() {
return actOnSelection(actions.deleteColumn);
},
mceTableDeleteRow: function() {
return actOnSelection(actions.deleteRow);
},
mceTableCutCol: function() {
return copyColSelection().each(function(selection2) {
clipboard.setColumns(selection2);
actOnSelection(actions.deleteColumn);
});
},
mceTableCutRow: function() {
return copyRowSelection().each(function(selection2) {
clipboard.setRows(selection2);
actOnSelection(actions.deleteRow);
});
},
mceTableCopyCol: function() {
return copyColSelection().each(function(selection2) {
return clipboard.setColumns(selection2);
});
},
mceTableCopyRow: function() {
return copyRowSelection().each(function(selection2) {
return clipboard.setRows(selection2);
});
},
mceTablePasteColBefore: function() {
return pasteOnSelection(actions.pasteColsBefore, clipboard.getColumns);
},
mceTablePasteColAfter: function() {
return pasteOnSelection(actions.pasteColsAfter, clipboard.getColumns);
},
mceTablePasteRowBefore: function() {
return pasteOnSelection(actions.pasteRowsBefore, clipboard.getRows);
},
mceTablePasteRowAfter: function() {
return pasteOnSelection(actions.pasteRowsAfter, clipboard.getRows);
},
mceTableDelete: eraseTable,
mceTableCellToggleClass: toggleTableCellClass,
mceTableToggleClass: toggleTableClass,
mceTableToggleCaption: toggleCaption,
mceTableSizingMode: function(_ui, sizing) {
return setSizingMode(sizing);
},
mceTableCellType: actOnType(function(type3) {
return type3 === "th" ? actions.makeCellsHeader : actions.unmakeCellsHeader;
}),
mceTableColType: actOnType(function(type3) {
return type3 === "th" ? actions.makeColumnsHeader : actions.unmakeColumnsHeader;
}),
mceTableRowType: actOnType(function(type3) {
switch (type3) {
case "header":
return actions.makeRowsHeader;
case "footer":
return actions.makeRowsFooter;
default:
return actions.makeRowsBody;
}
})
}, function(func, name2) {
return editor.addCommand(name2, func);
});
each$12({
mceTableProps: curry(open6, editor, false),
mceTableRowProps: curry(open$1, editor),
mceTableCellProps: curry(open$2, editor, selections)
}, function(func, name2) {
return editor.addCommand(name2, function() {
return func();
});
});
editor.addCommand("mceInsertTable", function(_ui, args) {
if (isObject3(args) && keys2(args).length > 0) {
insertTableWithDataValidation(editor, args.rows, args.columns, args.options, "Invalid values for mceInsertTable - rows and columns values are required to insert a table.");
} else {
open6(editor, true);
}
});
editor.addCommand("mceTableApplyCellStyle", function(_ui, args) {
var getFormatName = function(style) {
return "tablecell" + style.toLowerCase().replace("-", "");
};
if (!isObject3(args)) {
return;
}
var cells2 = getCellsFromSelection(selections);
if (cells2.length === 0) {
return;
}
var validArgs = filter$1(args, function(value25, style) {
return editor.formatter.has(getFormatName(style)) && isString3(value25);
});
if (isEmpty(validArgs)) {
return;
}
each$12(validArgs, function(value25, style) {
each$2(cells2, function(cell2) {
DomModifier.normal(editor, cell2.dom).setFormat(getFormatName(style), value25);
});
});
getTableFromCell(cells2[0]).each(function(table3) {
return fireTableModified(editor, table3.dom, styleModified);
});
});
};
var registerQueryCommands = function(editor, actions, selections) {
var isRoot = getIsRoot(editor);
var lookupOnSelection = function(action) {
return getSelectionCell(getSelectionStart(editor)).bind(function(cell2) {
return table2(cell2, isRoot).map(function(table3) {
var targets = forMenu(selections, table3, cell2);
return action(table3, targets);
});
}).getOr("");
};
each$12({
mceTableRowType: function() {
return lookupOnSelection(actions.getTableRowType);
},
mceTableCellType: function() {
return lookupOnSelection(actions.getTableCellType);
},
mceTableColType: function() {
return lookupOnSelection(actions.getTableColType);
}
}, function(func, name2) {
return editor.addQueryValueHandler(name2, func);
});
};
var Clipboard = function() {
var rows2 = value24();
var cols = value24();
return {
getRows: rows2.get,
setRows: function(r3) {
r3.fold(rows2.clear, rows2.set);
cols.clear();
},
clearRows: rows2.clear,
getColumns: cols.get,
setColumns: function(c2) {
c2.fold(cols.clear, cols.set);
rows2.clear();
},
clearColumns: cols.clear
};
};
var genericBase = {
remove_similar: true,
inherit: false
};
var cellBase = __assign({ selector: "td,th" }, genericBase);
var cellFormats = {
tablecellbackgroundcolor: __assign({ styles: { backgroundColor: "%value" } }, cellBase),
tablecellverticalalign: __assign({ styles: { "vertical-align": "%value" } }, cellBase),
tablecellbordercolor: __assign({ styles: { borderColor: "%value" } }, cellBase),
tablecellclass: __assign({ classes: ["%value"] }, cellBase),
tableclass: __assign({
selector: "table",
classes: ["%value"]
}, genericBase),
tablecellborderstyle: __assign({ styles: { borderStyle: "%value" } }, cellBase),
tablecellborderwidth: __assign({ styles: { borderWidth: "%value" } }, cellBase)
};
var registerFormats = function(editor) {
editor.formatter.register(cellFormats);
};
var adt$5 = Adt.generate([
{ none: ["current"] },
{ first: ["current"] },
{
middle: [
"current",
"target"
]
},
{ last: ["current"] }
]);
var none = function(current2) {
if (current2 === void 0) {
current2 = void 0;
}
return adt$5.none(current2);
};
var CellLocation = __assign(__assign({}, adt$5), { none });
var walk = function(all3, current2, index2, direction, isEligible) {
if (isEligible === void 0) {
isEligible = always;
}
var forwards = direction === 1;
if (!forwards && index2 <= 0) {
return CellLocation.first(all3[0]);
} else if (forwards && index2 >= all3.length - 1) {
return CellLocation.last(all3[all3.length - 1]);
} else {
var newIndex = index2 + direction;
var elem = all3[newIndex];
return isEligible(elem) ? CellLocation.middle(current2, elem) : walk(all3, current2, newIndex, direction, isEligible);
}
};
var detect$1 = function(current2, isRoot) {
return table2(current2, isRoot).bind(function(table3) {
var all3 = cells$1(table3);
var index2 = findIndex2(all3, function(x2) {
return eq$1(current2, x2);
});
return index2.map(function(index3) {
return {
index: index3,
all: all3
};
});
});
};
var next2 = function(current2, isEligible, isRoot) {
var detection = detect$1(current2, isRoot);
return detection.fold(function() {
return CellLocation.none(current2);
}, function(info3) {
return walk(info3.all, current2, info3.index, 1, isEligible);
});
};
var prev2 = function(current2, isEligible, isRoot) {
var detection = detect$1(current2, isRoot);
return detection.fold(function() {
return CellLocation.none();
}, function(info3) {
return walk(info3.all, current2, info3.index, -1, isEligible);
});
};
var create$2 = function(start, soffset, finish, foffset) {
return {
start,
soffset,
finish,
foffset
};
};
var SimRange = { create: create$2 };
var adt$4 = Adt.generate([
{ before: ["element"] },
{
on: [
"element",
"offset"
]
},
{ after: ["element"] }
]);
var cata$1 = function(subject, onBefore, onOn, onAfter) {
return subject.fold(onBefore, onOn, onAfter);
};
var getStart$1 = function(situ) {
return situ.fold(identity2, identity2, identity2);
};
var before$2 = adt$4.before;
var on2 = adt$4.on;
var after$3 = adt$4.after;
var Situ = {
before: before$2,
on: on2,
after: after$3,
cata: cata$1,
getStart: getStart$1
};
var adt$3 = Adt.generate([
{ domRange: ["rng"] },
{
relative: [
"startSitu",
"finishSitu"
]
},
{
exact: [
"start",
"soffset",
"finish",
"foffset"
]
}
]);
var exactFromRange = function(simRange) {
return adt$3.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
};
var getStart = function(selection2) {
return selection2.match({
domRange: function(rng) {
return SugarElement.fromDom(rng.startContainer);
},
relative: function(startSitu, _finishSitu) {
return Situ.getStart(startSitu);
},
exact: function(start, _soffset, _finish, _foffset) {
return start;
}
});
};
var domRange = adt$3.domRange;
var relative = adt$3.relative;
var exact = adt$3.exact;
var getWin = function(selection2) {
var start = getStart(selection2);
return defaultView(start);
};
var range2 = SimRange.create;
var SimSelection = {
domRange,
relative,
exact,
exactFromRange,
getWin,
range: range2
};
var selectNode = function(win, element) {
var rng = win.document.createRange();
rng.selectNode(element.dom);
return rng;
};
var selectNodeContents = function(win, element) {
var rng = win.document.createRange();
selectNodeContentsUsing(rng, element);
return rng;
};
var selectNodeContentsUsing = function(rng, element) {
return rng.selectNodeContents(element.dom);
};
var setStart = function(rng, situ) {
situ.fold(function(e2) {
rng.setStartBefore(e2.dom);
}, function(e2, o2) {
rng.setStart(e2.dom, o2);
}, function(e2) {
rng.setStartAfter(e2.dom);
});
};
var setFinish = function(rng, situ) {
situ.fold(function(e2) {
rng.setEndBefore(e2.dom);
}, function(e2, o2) {
rng.setEnd(e2.dom, o2);
}, function(e2) {
rng.setEndAfter(e2.dom);
});
};
var relativeToNative = function(win, startSitu, finishSitu) {
var range3 = win.document.createRange();
setStart(range3, startSitu);
setFinish(range3, finishSitu);
return range3;
};
var exactToNative = function(win, start, soffset, finish, foffset) {
var rng = win.document.createRange();
rng.setStart(start.dom, soffset);
rng.setEnd(finish.dom, foffset);
return rng;
};
var toRect = function(rect) {
return {
left: rect.left,
top: rect.top,
right: rect.right,
bottom: rect.bottom,
width: rect.width,
height: rect.height
};
};
var getFirstRect$1 = function(rng) {
var rects = rng.getClientRects();
var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
};
var adt$2 = Adt.generate([
{
ltr: [
"start",
"soffset",
"finish",
"foffset"
]
},
{
rtl: [
"start",
"soffset",
"finish",
"foffset"
]
}
]);
var fromRange = function(win, type3, range3) {
return type3(SugarElement.fromDom(range3.startContainer), range3.startOffset, SugarElement.fromDom(range3.endContainer), range3.endOffset);
};
var getRanges = function(win, selection2) {
return selection2.match({
domRange: function(rng) {
return {
ltr: constant2(rng),
rtl: Optional.none
};
},
relative: function(startSitu, finishSitu) {
return {
ltr: cached2(function() {
return relativeToNative(win, startSitu, finishSitu);
}),
rtl: cached2(function() {
return Optional.some(relativeToNative(win, finishSitu, startSitu));
})
};
},
exact: function(start, soffset, finish, foffset) {
return {
ltr: cached2(function() {
return exactToNative(win, start, soffset, finish, foffset);
}),
rtl: cached2(function() {
return Optional.some(exactToNative(win, finish, foffset, start, soffset));
})
};
}
});
};
var doDiagnose = function(win, ranges) {
var rng = ranges.ltr();
if (rng.collapsed) {
var reversed = ranges.rtl().filter(function(rev) {
return rev.collapsed === false;
});
return reversed.map(function(rev) {
return adt$2.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
}).getOrThunk(function() {
return fromRange(win, adt$2.ltr, rng);
});
} else {
return fromRange(win, adt$2.ltr, rng);
}
};
var diagnose = function(win, selection2) {
var ranges = getRanges(win, selection2);
return doDiagnose(win, ranges);
};
var asLtrRange = function(win, selection2) {
var diagnosis = diagnose(win, selection2);
return diagnosis.match({
ltr: function(start, soffset, finish, foffset) {
var rng = win.document.createRange();
rng.setStart(start.dom, soffset);
rng.setEnd(finish.dom, foffset);
return rng;
},
rtl: function(start, soffset, finish, foffset) {
var rng = win.document.createRange();
rng.setStart(finish.dom, foffset);
rng.setEnd(start.dom, soffset);
return rng;
}
});
};
adt$2.ltr;
adt$2.rtl;
var searchForPoint = function(rectForOffset, x2, y2, maxX, length) {
if (length === 0) {
return 0;
} else if (x2 === maxX) {
return length - 1;
}
var xDelta = maxX;
for (var i2 = 1; i2 < length; i2++) {
var rect = rectForOffset(i2);
var curDeltaX = Math.abs(x2 - rect.left);
if (y2 <= rect.bottom) {
if (y2 < rect.top || curDeltaX > xDelta) {
return i2 - 1;
} else {
xDelta = curDeltaX;
}
}
}
return 0;
};
var inRect = function(rect, x2, y2) {
return x2 >= rect.left && x2 <= rect.right && y2 >= rect.top && y2 <= rect.bottom;
};
var locateOffset = function(doc, textnode, x2, y2, rect) {
var rangeForOffset = function(o2) {
var r3 = doc.dom.createRange();
r3.setStart(textnode.dom, o2);
r3.collapse(true);
return r3;
};
var rectForOffset = function(o2) {
var r3 = rangeForOffset(o2);
return r3.getBoundingClientRect();
};
var length = get$9(textnode).length;
var offset4 = searchForPoint(rectForOffset, x2, y2, rect.right, length);
return rangeForOffset(offset4);
};
var locate$1 = function(doc, node, x2, y2) {
var r3 = doc.dom.createRange();
r3.selectNode(node.dom);
var rects = r3.getClientRects();
var foundRect = findMap(rects, function(rect) {
return inRect(rect, x2, y2) ? Optional.some(rect) : Optional.none();
});
return foundRect.map(function(rect) {
return locateOffset(doc, node, x2, y2, rect);
});
};
var searchInChildren = function(doc, node, x2, y2) {
var r3 = doc.dom.createRange();
var nodes2 = children$3(node);
return findMap(nodes2, function(n2) {
r3.selectNode(n2.dom);
return inRect(r3.getBoundingClientRect(), x2, y2) ? locateNode(doc, n2, x2, y2) : Optional.none();
});
};
var locateNode = function(doc, node, x2, y2) {
return isText(node) ? locate$1(doc, node, x2, y2) : searchInChildren(doc, node, x2, y2);
};
var locate = function(doc, node, x2, y2) {
var r3 = doc.dom.createRange();
r3.selectNode(node.dom);
var rect = r3.getBoundingClientRect();
var boundedX = Math.max(rect.left, Math.min(rect.right, x2));
var boundedY = Math.max(rect.top, Math.min(rect.bottom, y2));
return locateNode(doc, node, boundedX, boundedY);
};
var COLLAPSE_TO_LEFT = true;
var COLLAPSE_TO_RIGHT = false;
var getCollapseDirection = function(rect, x2) {
return x2 - rect.left < rect.right - x2 ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
};
var createCollapsedNode = function(doc, target, collapseDirection) {
var r3 = doc.dom.createRange();
r3.selectNode(target.dom);
r3.collapse(collapseDirection);
return r3;
};
var locateInElement = function(doc, node, x2) {
var cursorRange = doc.dom.createRange();
cursorRange.selectNode(node.dom);
var rect = cursorRange.getBoundingClientRect();
var collapseDirection = getCollapseDirection(rect, x2);
var f2 = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1;
return f2(node).map(function(target) {
return createCollapsedNode(doc, target, collapseDirection);
});
};
var locateInEmpty = function(doc, node, x2) {
var rect = node.dom.getBoundingClientRect();
var collapseDirection = getCollapseDirection(rect, x2);
return Optional.some(createCollapsedNode(doc, node, collapseDirection));
};
var search = function(doc, node, x2) {
var f2 = children$3(node).length === 0 ? locateInEmpty : locateInElement;
return f2(doc, node, x2);
};
var caretPositionFromPoint = function(doc, x2, y2) {
var _a3, _b2;
return Optional.from((_b2 = (_a3 = doc.dom).caretPositionFromPoint) === null || _b2 === void 0 ? void 0 : _b2.call(_a3, x2, y2)).bind(function(pos) {
if (pos.offsetNode === null) {
return Optional.none();
}
var r3 = doc.dom.createRange();
r3.setStart(pos.offsetNode, pos.offset);
r3.collapse();
return Optional.some(r3);
});
};
var caretRangeFromPoint = function(doc, x2, y2) {
var _a3, _b2;
return Optional.from((_b2 = (_a3 = doc.dom).caretRangeFromPoint) === null || _b2 === void 0 ? void 0 : _b2.call(_a3, x2, y2));
};
var searchTextNodes = function(doc, node, x2, y2) {
var r3 = doc.dom.createRange();
r3.selectNode(node.dom);
var rect = r3.getBoundingClientRect();
var boundedX = Math.max(rect.left, Math.min(rect.right, x2));
var boundedY = Math.max(rect.top, Math.min(rect.bottom, y2));
return locate(doc, node, boundedX, boundedY);
};
var searchFromPoint = function(doc, x2, y2) {
return SugarElement.fromPoint(doc, x2, y2).bind(function(elem) {
var fallback2 = function() {
return search(doc, elem, x2);
};
return children$3(elem).length === 0 ? fallback2() : searchTextNodes(doc, elem, x2, y2).orThunk(fallback2);
});
};
var availableSearch = function() {
if (document.caretPositionFromPoint) {
return caretPositionFromPoint;
} else if (document.caretRangeFromPoint) {
return caretRangeFromPoint;
} else {
return searchFromPoint;
}
}();
var fromPoint = function(win, x2, y2) {
var doc = SugarElement.fromDom(win.document);
return availableSearch(doc, x2, y2).map(function(rng) {
return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
});
};
var beforeSpecial = function(element, offset4) {
var name$1 = name(element);
if (name$1 === "input") {
return Situ.after(element);
} else if (!contains$2([
"br",
"img"
], name$1)) {
return Situ.on(element, offset4);
} else {
return offset4 === 0 ? Situ.before(element) : Situ.after(element);
}
};
var preprocessRelative = function(startSitu, finishSitu) {
var start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
var finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
return SimSelection.relative(start, finish);
};
var preprocessExact = function(start, soffset, finish, foffset) {
var startSitu = beforeSpecial(start, soffset);
var finishSitu = beforeSpecial(finish, foffset);
return SimSelection.relative(startSitu, finishSitu);
};
var preprocess = function(selection2) {
return selection2.match({
domRange: function(rng) {
var start = SugarElement.fromDom(rng.startContainer);
var finish = SugarElement.fromDom(rng.endContainer);
return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
},
relative: preprocessRelative,
exact: preprocessExact
});
};
var makeRange = function(start, soffset, finish, foffset) {
var doc = owner(start);
var rng = doc.dom.createRange();
rng.setStart(start.dom, soffset);
rng.setEnd(finish.dom, foffset);
return rng;
};
var after$2 = function(start, soffset, finish, foffset) {
var r3 = makeRange(start, soffset, finish, foffset);
var same = eq$1(start, finish) && soffset === foffset;
return r3.collapsed && !same;
};
var getNativeSelection = function(win) {
return Optional.from(win.getSelection());
};
var doSetNativeRange = function(win, rng) {
getNativeSelection(win).each(function(selection2) {
selection2.removeAllRanges();
selection2.addRange(rng);
});
};
var doSetRange = function(win, start, soffset, finish, foffset) {
var rng = exactToNative(win, start, soffset, finish, foffset);
doSetNativeRange(win, rng);
};
var setLegacyRtlRange = function(win, selection2, start, soffset, finish, foffset) {
selection2.collapse(start.dom, soffset);
selection2.extend(finish.dom, foffset);
};
var setRangeFromRelative = function(win, relative2) {
return diagnose(win, relative2).match({
ltr: function(start, soffset, finish, foffset) {
doSetRange(win, start, soffset, finish, foffset);
},
rtl: function(start, soffset, finish, foffset) {
getNativeSelection(win).each(function(selection2) {
if (selection2.setBaseAndExtent) {
selection2.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
} else if (selection2.extend) {
try {
setLegacyRtlRange(win, selection2, start, soffset, finish, foffset);
} catch (e2) {
doSetRange(win, finish, foffset, start, soffset);
}
} else {
doSetRange(win, finish, foffset, start, soffset);
}
});
}
});
};
var setExact = function(win, start, soffset, finish, foffset) {
var relative2 = preprocessExact(start, soffset, finish, foffset);
setRangeFromRelative(win, relative2);
};
var setRelative = function(win, startSitu, finishSitu) {
var relative2 = preprocessRelative(startSitu, finishSitu);
setRangeFromRelative(win, relative2);
};
var toNative = function(selection2) {
var win = SimSelection.getWin(selection2).dom;
var getDomRange = function(start, soffset, finish, foffset) {
return exactToNative(win, start, soffset, finish, foffset);
};
var filtered = preprocess(selection2);
return diagnose(win, filtered).match({
ltr: getDomRange,
rtl: getDomRange
});
};
var readRange = function(selection2) {
if (selection2.rangeCount > 0) {
var firstRng = selection2.getRangeAt(0);
var lastRng = selection2.getRangeAt(selection2.rangeCount - 1);
return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
} else {
return Optional.none();
}
};
var doGetExact = function(selection2) {
if (selection2.anchorNode === null || selection2.focusNode === null) {
return readRange(selection2);
} else {
var anchor = SugarElement.fromDom(selection2.anchorNode);
var focus_1 = SugarElement.fromDom(selection2.focusNode);
return after$2(anchor, selection2.anchorOffset, focus_1, selection2.focusOffset) ? Optional.some(SimRange.create(anchor, selection2.anchorOffset, focus_1, selection2.focusOffset)) : readRange(selection2);
}
};
var setToElement = function(win, element, selectNodeContents$1) {
if (selectNodeContents$1 === void 0) {
selectNodeContents$1 = true;
}
var rngGetter = selectNodeContents$1 ? selectNodeContents : selectNode;
var rng = rngGetter(win, element);
doSetNativeRange(win, rng);
};
var getExact = function(win) {
return getNativeSelection(win).filter(function(sel) {
return sel.rangeCount > 0;
}).bind(doGetExact);
};
var get$12 = function(win) {
return getExact(win).map(function(range3) {
return SimSelection.exact(range3.start, range3.soffset, range3.finish, range3.foffset);
});
};
var getFirstRect = function(win, selection2) {
var rng = asLtrRange(win, selection2);
return getFirstRect$1(rng);
};
var getAtPoint = function(win, x2, y2) {
return fromPoint(win, x2, y2);
};
var clear2 = function(win) {
getNativeSelection(win).each(function(selection2) {
return selection2.removeAllRanges();
});
};
var global$12 = tinymce.util.Tools.resolve("tinymce.util.VK");
var forward = function(editor, isRoot, cell2) {
return go$1(editor, isRoot, next2(cell2, isEditable$1));
};
var backward = function(editor, isRoot, cell2) {
return go$1(editor, isRoot, prev2(cell2, isEditable$1));
};
var getCellFirstCursorPosition = function(editor, cell2) {
var selection2 = SimSelection.exact(cell2, 0, cell2, 0);
return toNative(selection2);
};
var go$1 = function(editor, isRoot, cell2) {
return cell2.fold(Optional.none, Optional.none, function(current2, next3) {
return first(next3).map(function(cell3) {
return getCellFirstCursorPosition(editor, cell3);
});
}, function(current2) {
editor.execCommand("mceTableInsertRowAfter");
return forward(editor, isRoot, current2);
});
};
var rootElements = [
"table",
"li",
"dl"
];
var handle$1 = function(event, editor, cellSelection) {
if (event.keyCode === global$12.TAB) {
var body_1 = getBody2(editor);
var isRoot_1 = function(element) {
var name$1 = name(element);
return eq$1(element, body_1) || contains$2(rootElements, name$1);
};
var rng = editor.selection.getRng();
var container = SugarElement.fromDom(event.shiftKey ? rng.startContainer : rng.endContainer);
cell(container, isRoot_1).each(function(cell2) {
event.preventDefault();
table2(cell2, isRoot_1).each(cellSelection.clear);
editor.selection.collapse(event.shiftKey);
var navigation = event.shiftKey ? backward : forward;
var rng2 = navigation(editor, isRoot_1, cell2);
rng2.each(function(range3) {
editor.selection.setRng(range3);
});
});
}
};
var create$1 = function(selection2, kill) {
return {
selection: selection2,
kill
};
};
var Response = { create: create$1 };
var create = function(start, soffset, finish, foffset) {
return {
start: Situ.on(start, soffset),
finish: Situ.on(finish, foffset)
};
};
var Situs = { create };
var convertToRange = function(win, selection2) {
var rng = asLtrRange(win, selection2);
return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
};
var makeSitus = Situs.create;
var sync = function(container, isRoot, start, soffset, finish, foffset, selectRange) {
if (!(eq$1(start, finish) && soffset === foffset)) {
return closest$1(start, "td,th", isRoot).bind(function(s2) {
return closest$1(finish, "td,th", isRoot).bind(function(f2) {
return detect(container, isRoot, s2, f2, selectRange);
});
});
} else {
return Optional.none();
}
};
var detect = function(container, isRoot, start, finish, selectRange) {
if (!eq$1(start, finish)) {
return identify(start, finish, isRoot).bind(function(cellSel) {
var boxes = cellSel.boxes.getOr([]);
if (boxes.length > 1) {
selectRange(container, boxes, cellSel.start, cellSel.finish);
return Optional.some(Response.create(Optional.some(makeSitus(start, 0, start, getEnd(start))), true));
} else {
return Optional.none();
}
});
} else {
return Optional.none();
}
};
var update = function(rows2, columns3, container, selected, annotations) {
var updateSelection = function(newSels) {
annotations.clearBeforeUpdate(container);
annotations.selectRange(container, newSels.boxes, newSels.start, newSels.finish);
return newSels.boxes;
};
return shiftSelection(selected, rows2, columns3, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(updateSelection);
};
var traverse = function(item, mode3) {
return {
item,
mode: mode3
};
};
var backtrack = function(universe2, item, _direction, transition) {
if (transition === void 0) {
transition = sidestep;
}
return universe2.property().parent(item).map(function(p) {
return traverse(p, transition);
});
};
var sidestep = function(universe2, item, direction, transition) {
if (transition === void 0) {
transition = advance;
}
return direction.sibling(universe2, item).map(function(p) {
return traverse(p, transition);
});
};
var advance = function(universe2, item, direction, transition) {
if (transition === void 0) {
transition = advance;
}
var children2 = universe2.property().children(item);
var result = direction.first(children2);
return result.map(function(r3) {
return traverse(r3, transition);
});
};
var successors = [
{
current: backtrack,
next: sidestep,
fallback: Optional.none()
},
{
current: sidestep,
next: advance,
fallback: Optional.some(backtrack)
},
{
current: advance,
next: advance,
fallback: Optional.some(sidestep)
}
];
var go2 = function(universe2, item, mode3, direction, rules2) {
if (rules2 === void 0) {
rules2 = successors;
}
var ruleOpt = find$12(rules2, function(succ) {
return succ.current === mode3;
});
return ruleOpt.bind(function(rule) {
return rule.current(universe2, item, direction, rule.next).orThunk(function() {
return rule.fallback.bind(function(fb) {
return go2(universe2, item, fb, direction);
});
});
});
};
var left$1 = function() {
var sibling = function(universe2, item) {
return universe2.query().prevSibling(item);
};
var first2 = function(children2) {
return children2.length > 0 ? Optional.some(children2[children2.length - 1]) : Optional.none();
};
return {
sibling,
first: first2
};
};
var right$1 = function() {
var sibling = function(universe2, item) {
return universe2.query().nextSibling(item);
};
var first2 = function(children2) {
return children2.length > 0 ? Optional.some(children2[0]) : Optional.none();
};
return {
sibling,
first: first2
};
};
var Walkers = {
left: left$1,
right: right$1
};
var hone = function(universe2, item, predicate, mode3, direction, isRoot) {
var next3 = go2(universe2, item, mode3, direction);
return next3.bind(function(n2) {
if (isRoot(n2.item)) {
return Optional.none();
} else {
return predicate(n2.item) ? Optional.some(n2.item) : hone(universe2, n2.item, predicate, n2.mode, direction, isRoot);
}
});
};
var left = function(universe2, item, predicate, isRoot) {
return hone(universe2, item, predicate, sidestep, Walkers.left(), isRoot);
};
var right = function(universe2, item, predicate, isRoot) {
return hone(universe2, item, predicate, sidestep, Walkers.right(), isRoot);
};
var isLeaf = function(universe2) {
return function(element) {
return universe2.property().children(element).length === 0;
};
};
var before$1 = function(universe2, item, isRoot) {
return seekLeft$1(universe2, item, isLeaf(universe2), isRoot);
};
var after$1 = function(universe2, item, isRoot) {
return seekRight$1(universe2, item, isLeaf(universe2), isRoot);
};
var seekLeft$1 = left;
var seekRight$1 = right;
var universe = DomUniverse();
var before = function(element, isRoot) {
return before$1(universe, element, isRoot);
};
var after = function(element, isRoot) {
return after$1(universe, element, isRoot);
};
var seekLeft = function(element, predicate, isRoot) {
return seekLeft$1(universe, element, predicate, isRoot);
};
var seekRight = function(element, predicate, isRoot) {
return seekRight$1(universe, element, predicate, isRoot);
};
var ancestor = function(scope, predicate, isRoot) {
return ancestor$2(scope, predicate, isRoot).isSome();
};
var adt$1 = Adt.generate([
{ none: ["message"] },
{ success: [] },
{ failedUp: ["cell"] },
{ failedDown: ["cell"] }
]);
var isOverlapping = function(bridge, before2, after2) {
var beforeBounds = bridge.getRect(before2);
var afterBounds = bridge.getRect(after2);
return afterBounds.right > beforeBounds.left && afterBounds.left < beforeBounds.right;
};
var isRow = function(elem) {
return closest$1(elem, "tr");
};
var verify = function(bridge, before2, beforeOffset, after2, afterOffset, failure, isRoot) {
return closest$1(after2, "td,th", isRoot).bind(function(afterCell) {
return closest$1(before2, "td,th", isRoot).map(function(beforeCell) {
if (!eq$1(afterCell, beforeCell)) {
return sharedOne(isRow, [
afterCell,
beforeCell
]).fold(function() {
return isOverlapping(bridge, beforeCell, afterCell) ? adt$1.success() : failure(beforeCell);
}, function(_sharedRow) {
return failure(beforeCell);
});
} else {
return eq$1(after2, afterCell) && getEnd(afterCell) === afterOffset ? failure(beforeCell) : adt$1.none("in same cell");
}
});
}).getOr(adt$1.none("default"));
};
var cata = function(subject, onNone, onSuccess2, onFailedUp, onFailedDown) {
return subject.fold(onNone, onSuccess2, onFailedUp, onFailedDown);
};
var BeforeAfter = __assign(__assign({}, adt$1), {
verify,
cata
});
var inParent = function(parent3, children2, element, index2) {
return {
parent: parent3,
children: children2,
element,
index: index2
};
};
var indexInParent = function(element) {
return parent2(element).bind(function(parent3) {
var children2 = children$3(parent3);
return indexOf2(children2, element).map(function(index2) {
return inParent(parent3, children2, element, index2);
});
});
};
var indexOf2 = function(elements, element) {
return findIndex2(elements, curry(eq$1, element));
};
var isBr = function(elem) {
return name(elem) === "br";
};
var gatherer = function(cand, gather, isRoot) {
return gather(cand, isRoot).bind(function(target) {
return isText(target) && get$9(target).trim().length === 0 ? gatherer(target, gather, isRoot) : Optional.some(target);
});
};
var handleBr = function(isRoot, element, direction) {
return direction.traverse(element).orThunk(function() {
return gatherer(element, direction.gather, isRoot);
}).map(direction.relative);
};
var findBr = function(element, offset4) {
return child$3(element, offset4).filter(isBr).orThunk(function() {
return child$3(element, offset4 - 1).filter(isBr);
});
};
var handleParent = function(isRoot, element, offset4, direction) {
return findBr(element, offset4).bind(function(br) {
return direction.traverse(br).fold(function() {
return gatherer(br, direction.gather, isRoot).map(direction.relative);
}, function(adjacent) {
return indexInParent(adjacent).map(function(info3) {
return Situ.on(info3.parent, info3.index);
});
});
});
};
var tryBr = function(isRoot, element, offset4, direction) {
var target = isBr(element) ? handleBr(isRoot, element, direction) : handleParent(isRoot, element, offset4, direction);
return target.map(function(tgt) {
return {
start: tgt,
finish: tgt
};
});
};
var process2 = function(analysis) {
return BeforeAfter.cata(analysis, function(_message) {
return Optional.none();
}, function() {
return Optional.none();
}, function(cell2) {
return Optional.some(point(cell2, 0));
}, function(cell2) {
return Optional.some(point(cell2, getEnd(cell2)));
});
};
var moveDown = function(caret, amount) {
return {
left: caret.left,
top: caret.top + amount,
right: caret.right,
bottom: caret.bottom + amount
};
};
var moveUp = function(caret, amount) {
return {
left: caret.left,
top: caret.top - amount,
right: caret.right,
bottom: caret.bottom - amount
};
};
var translate = function(caret, xDelta, yDelta) {
return {
left: caret.left + xDelta,
top: caret.top + yDelta,
right: caret.right + xDelta,
bottom: caret.bottom + yDelta
};
};
var getTop2 = function(caret) {
return caret.top;
};
var getBottom = function(caret) {
return caret.bottom;
};
var getPartialBox = function(bridge, element, offset4) {
if (offset4 >= 0 && offset4 < getEnd(element)) {
return bridge.getRangedRect(element, offset4, element, offset4 + 1);
} else if (offset4 > 0) {
return bridge.getRangedRect(element, offset4 - 1, element, offset4);
}
return Optional.none();
};
var toCaret = function(rect) {
return {
left: rect.left,
top: rect.top,
right: rect.right,
bottom: rect.bottom
};
};
var getElemBox = function(bridge, element) {
return Optional.some(bridge.getRect(element));
};
var getBoxAt = function(bridge, element, offset4) {
if (isElement2(element)) {
return getElemBox(bridge, element).map(toCaret);
} else if (isText(element)) {
return getPartialBox(bridge, element, offset4).map(toCaret);
} else {
return Optional.none();
}
};
var getEntireBox = function(bridge, element) {
if (isElement2(element)) {
return getElemBox(bridge, element).map(toCaret);
} else if (isText(element)) {
return bridge.getRangedRect(element, 0, element, getEnd(element)).map(toCaret);
} else {
return Optional.none();
}
};
var JUMP_SIZE = 5;
var NUM_RETRIES = 100;
var adt = Adt.generate([
{ none: [] },
{ retry: ["caret"] }
]);
var isOutside = function(caret, box) {
return caret.left < box.left || Math.abs(box.right - caret.left) < 1 || caret.left > box.right;
};
var inOutsideBlock = function(bridge, element, caret) {
return closest$2(element, isBlock).fold(never, function(cell2) {
return getEntireBox(bridge, cell2).exists(function(box) {
return isOutside(caret, box);
});
});
};
var adjustDown = function(bridge, element, guessBox, original, caret) {
var lowerCaret = moveDown(caret, JUMP_SIZE);
if (Math.abs(guessBox.bottom - original.bottom) < 1) {
return adt.retry(lowerCaret);
} else if (guessBox.top > caret.bottom) {
return adt.retry(lowerCaret);
} else if (guessBox.top === caret.bottom) {
return adt.retry(moveDown(caret, 1));
} else {
return inOutsideBlock(bridge, element, caret) ? adt.retry(translate(lowerCaret, JUMP_SIZE, 0)) : adt.none();
}
};
var adjustUp = function(bridge, element, guessBox, original, caret) {
var higherCaret = moveUp(caret, JUMP_SIZE);
if (Math.abs(guessBox.top - original.top) < 1) {
return adt.retry(higherCaret);
} else if (guessBox.bottom < caret.top) {
return adt.retry(higherCaret);
} else if (guessBox.bottom === caret.top) {
return adt.retry(moveUp(caret, 1));
} else {
return inOutsideBlock(bridge, element, caret) ? adt.retry(translate(higherCaret, JUMP_SIZE, 0)) : adt.none();
}
};
var upMovement = {
point: getTop2,
adjuster: adjustUp,
move: moveUp,
gather: before
};
var downMovement = {
point: getBottom,
adjuster: adjustDown,
move: moveDown,
gather: after
};
var isAtTable = function(bridge, x2, y2) {
return bridge.elementFromPoint(x2, y2).filter(function(elm) {
return name(elm) === "table";
}).isSome();
};
var adjustForTable = function(bridge, movement, original, caret, numRetries) {
return adjustTil(bridge, movement, original, movement.move(caret, JUMP_SIZE), numRetries);
};
var adjustTil = function(bridge, movement, original, caret, numRetries) {
if (numRetries === 0) {
return Optional.some(caret);
}
if (isAtTable(bridge, caret.left, movement.point(caret))) {
return adjustForTable(bridge, movement, original, caret, numRetries - 1);
}
return bridge.situsFromPoint(caret.left, movement.point(caret)).bind(function(guess) {
return guess.start.fold(Optional.none, function(element) {
return getEntireBox(bridge, element).bind(function(guessBox) {
return movement.adjuster(bridge, element, guessBox, original, caret).fold(Optional.none, function(newCaret) {
return adjustTil(bridge, movement, original, newCaret, numRetries - 1);
});
}).orThunk(function() {
return Optional.some(caret);
});
}, Optional.none);
});
};
var ieTryDown = function(bridge, caret) {
return bridge.situsFromPoint(caret.left, caret.bottom + JUMP_SIZE);
};
var ieTryUp = function(bridge, caret) {
return bridge.situsFromPoint(caret.left, caret.top - JUMP_SIZE);
};
var checkScroll = function(movement, adjusted, bridge) {
if (movement.point(adjusted) > bridge.getInnerHeight()) {
return Optional.some(movement.point(adjusted) - bridge.getInnerHeight());
} else if (movement.point(adjusted) < 0) {
return Optional.some(-movement.point(adjusted));
} else {
return Optional.none();
}
};
var retry = function(movement, bridge, caret) {
var moved = movement.move(caret, JUMP_SIZE);
var adjusted = adjustTil(bridge, movement, caret, moved, NUM_RETRIES).getOr(moved);
return checkScroll(movement, adjusted, bridge).fold(function() {
return bridge.situsFromPoint(adjusted.left, movement.point(adjusted));
}, function(delta) {
bridge.scrollBy(0, delta);
return bridge.situsFromPoint(adjusted.left, movement.point(adjusted) - delta);
});
};
var Retries = {
tryUp: curry(retry, upMovement),
tryDown: curry(retry, downMovement),
ieTryUp,
ieTryDown,
getJumpSize: constant2(JUMP_SIZE)
};
var MAX_RETRIES = 20;
var findSpot = function(bridge, isRoot, direction) {
return bridge.getSelection().bind(function(sel) {
return tryBr(isRoot, sel.finish, sel.foffset, direction).fold(function() {
return Optional.some(point(sel.finish, sel.foffset));
}, function(brNeighbour) {
var range3 = bridge.fromSitus(brNeighbour);
var analysis = BeforeAfter.verify(bridge, sel.finish, sel.foffset, range3.finish, range3.foffset, direction.failure, isRoot);
return process2(analysis);
});
});
};
var scan2 = function(bridge, isRoot, element, offset4, direction, numRetries) {
if (numRetries === 0) {
return Optional.none();
}
return tryCursor(bridge, isRoot, element, offset4, direction).bind(function(situs) {
var range3 = bridge.fromSitus(situs);
var analysis = BeforeAfter.verify(bridge, element, offset4, range3.finish, range3.foffset, direction.failure, isRoot);
return BeforeAfter.cata(analysis, function() {
return Optional.none();
}, function() {
return Optional.some(situs);
}, function(cell2) {
if (eq$1(element, cell2) && offset4 === 0) {
return tryAgain(bridge, element, offset4, moveUp, direction);
} else {
return scan2(bridge, isRoot, cell2, 0, direction, numRetries - 1);
}
}, function(cell2) {
if (eq$1(element, cell2) && offset4 === getEnd(cell2)) {
return tryAgain(bridge, element, offset4, moveDown, direction);
} else {
return scan2(bridge, isRoot, cell2, getEnd(cell2), direction, numRetries - 1);
}
});
});
};
var tryAgain = function(bridge, element, offset4, move2, direction) {
return getBoxAt(bridge, element, offset4).bind(function(box) {
return tryAt(bridge, direction, move2(box, Retries.getJumpSize()));
});
};
var tryAt = function(bridge, direction, box) {
var browser = detect$3().browser;
if (browser.isChrome() || browser.isSafari() || browser.isFirefox() || browser.isEdge()) {
return direction.otherRetry(bridge, box);
} else if (browser.isIE()) {
return direction.ieRetry(bridge, box);
} else {
return Optional.none();
}
};
var tryCursor = function(bridge, isRoot, element, offset4, direction) {
return getBoxAt(bridge, element, offset4).bind(function(box) {
return tryAt(bridge, direction, box);
});
};
var handle = function(bridge, isRoot, direction) {
return findSpot(bridge, isRoot, direction).bind(function(spot) {
return scan2(bridge, isRoot, spot.element, spot.offset, direction, MAX_RETRIES).map(bridge.fromSitus);
});
};
var inSameTable = function(elem, table3) {
return ancestor(elem, function(e2) {
return parent2(e2).exists(function(p) {
return eq$1(p, table3);
});
});
};
var simulate = function(bridge, isRoot, direction, initial, anchor) {
return closest$1(initial, "td,th", isRoot).bind(function(start) {
return closest$1(start, "table", isRoot).bind(function(table3) {
if (!inSameTable(anchor, table3)) {
return Optional.none();
}
return handle(bridge, isRoot, direction).bind(function(range3) {
return closest$1(range3.finish, "td,th", isRoot).map(function(finish) {
return {
start,
finish,
range: range3
};
});
});
});
});
};
var navigate = function(bridge, isRoot, direction, initial, anchor, precheck) {
if (detect$3().browser.isIE()) {
return Optional.none();
} else {
return precheck(initial, isRoot).orThunk(function() {
return simulate(bridge, isRoot, direction, initial, anchor).map(function(info3) {
var range3 = info3.range;
return Response.create(Optional.some(makeSitus(range3.start, range3.soffset, range3.finish, range3.foffset)), true);
});
});
}
};
var firstUpCheck = function(initial, isRoot) {
return closest$1(initial, "tr", isRoot).bind(function(startRow) {
return closest$1(startRow, "table", isRoot).bind(function(table3) {
var rows2 = descendants(table3, "tr");
if (eq$1(startRow, rows2[0])) {
return seekLeft(table3, function(element) {
return last$1(element).isSome();
}, isRoot).map(function(last3) {
var lastOffset = getEnd(last3);
return Response.create(Optional.some(makeSitus(last3, lastOffset, last3, lastOffset)), true);
});
} else {
return Optional.none();
}
});
});
};
var lastDownCheck = function(initial, isRoot) {
return closest$1(initial, "tr", isRoot).bind(function(startRow) {
return closest$1(startRow, "table", isRoot).bind(function(table3) {
var rows2 = descendants(table3, "tr");
if (eq$1(startRow, rows2[rows2.length - 1])) {
return seekRight(table3, function(element) {
return first(element).isSome();
}, isRoot).map(function(first2) {
return Response.create(Optional.some(makeSitus(first2, 0, first2, 0)), true);
});
} else {
return Optional.none();
}
});
});
};
var select2 = function(bridge, container, isRoot, direction, initial, anchor, selectRange) {
return simulate(bridge, isRoot, direction, initial, anchor).bind(function(info3) {
return detect(container, isRoot, info3.start, info3.finish, selectRange);
});
};
var findCell = function(target, isRoot) {
return closest$1(target, "td,th", isRoot);
};
var MouseSelection = function(bridge, container, isRoot, annotations) {
var cursor = value24();
var clearstate = cursor.clear;
var applySelection = function(event) {
cursor.on(function(start) {
annotations.clearBeforeUpdate(container);
findCell(event.target, isRoot).each(function(finish) {
identify(start, finish, isRoot).each(function(cellSel) {
var boxes = cellSel.boxes.getOr([]);
if (boxes.length === 1) {
var singleCell = boxes[0];
var isNonEditableCell = getRaw(singleCell) === "false";
var isCellClosestContentEditable = is2(closest(event.target), singleCell, eq$1);
if (isNonEditableCell && isCellClosestContentEditable) {
annotations.selectRange(container, boxes, singleCell, singleCell);
bridge.selectContents(singleCell);
}
} else if (boxes.length > 1) {
annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
bridge.selectContents(finish);
}
});
});
});
};
var mousedown = function(event) {
annotations.clear(container);
findCell(event.target, isRoot).each(cursor.set);
};
var mouseover = function(event) {
applySelection(event);
};
var mouseup = function(event) {
applySelection(event);
clearstate();
};
return {
clearstate,
mousedown,
mouseover,
mouseup
};
};
var down2 = {
traverse: nextSibling,
gather: after,
relative: Situ.before,
otherRetry: Retries.tryDown,
ieRetry: Retries.ieTryDown,
failure: BeforeAfter.failedDown
};
var up2 = {
traverse: prevSibling,
gather: before,
relative: Situ.before,
otherRetry: Retries.tryUp,
ieRetry: Retries.ieTryUp,
failure: BeforeAfter.failedUp
};
var isKey2 = function(key3) {
return function(keycode) {
return keycode === key3;
};
};
var isUp = isKey2(38);
var isDown = isKey2(40);
var isNavigation = function(keycode) {
return keycode >= 37 && keycode <= 40;
};
var ltr = {
isBackward: isKey2(37),
isForward: isKey2(39)
};
var rtl = {
isBackward: isKey2(39),
isForward: isKey2(37)
};
var get2 = function(_DOC) {
var doc = _DOC !== void 0 ? _DOC.dom : document;
var x2 = doc.body.scrollLeft || doc.documentElement.scrollLeft;
var y2 = doc.body.scrollTop || doc.documentElement.scrollTop;
return SugarPosition(x2, y2);
};
var by = function(x2, y2, _DOC) {
var doc = _DOC !== void 0 ? _DOC.dom : document;
var win = doc.defaultView;
if (win) {
win.scrollBy(x2, y2);
}
};
var WindowBridge = function(win) {
var elementFromPoint = function(x2, y2) {
return SugarElement.fromPoint(SugarElement.fromDom(win.document), x2, y2);
};
var getRect = function(element) {
return element.dom.getBoundingClientRect();
};
var getRangedRect = function(start, soffset, finish, foffset) {
var sel = SimSelection.exact(start, soffset, finish, foffset);
return getFirstRect(win, sel);
};
var getSelection = function() {
return get$12(win).map(function(exactAdt) {
return convertToRange(win, exactAdt);
});
};
var fromSitus = function(situs) {
var relative2 = SimSelection.relative(situs.start, situs.finish);
return convertToRange(win, relative2);
};
var situsFromPoint = function(x2, y2) {
return getAtPoint(win, x2, y2).map(function(exact2) {
return Situs.create(exact2.start, exact2.soffset, exact2.finish, exact2.foffset);
});
};
var clearSelection4 = function() {
clear2(win);
};
var collapseSelection = function(toStart) {
if (toStart === void 0) {
toStart = false;
}
get$12(win).each(function(sel) {
return sel.fold(function(rng) {
return rng.collapse(toStart);
}, function(startSitu, finishSitu) {
var situ = toStart ? startSitu : finishSitu;
setRelative(win, situ, situ);
}, function(start, soffset, finish, foffset) {
var node = toStart ? start : finish;
var offset4 = toStart ? soffset : foffset;
setExact(win, node, offset4, node, offset4);
});
});
};
var selectNode2 = function(element) {
setToElement(win, element, false);
};
var selectContents = function(element) {
setToElement(win, element);
};
var setSelection = function(sel) {
setExact(win, sel.start, sel.soffset, sel.finish, sel.foffset);
};
var setRelativeSelection = function(start, finish) {
setRelative(win, start, finish);
};
var getInnerHeight = function() {
return win.innerHeight;
};
var getScrollY = function() {
var pos = get2(SugarElement.fromDom(win.document));
return pos.top;
};
var scrollBy = function(x2, y2) {
by(x2, y2, SugarElement.fromDom(win.document));
};
return {
elementFromPoint,
getRect,
getRangedRect,
getSelection,
fromSitus,
situsFromPoint,
clearSelection: clearSelection4,
collapseSelection,
setSelection,
setRelativeSelection,
selectNode: selectNode2,
selectContents,
getInnerHeight,
getScrollY,
scrollBy
};
};
var rc = function(rows2, cols) {
return {
rows: rows2,
cols
};
};
var mouse = function(win, container, isRoot, annotations) {
var bridge = WindowBridge(win);
var handlers = MouseSelection(bridge, container, isRoot, annotations);
return {
clearstate: handlers.clearstate,
mousedown: handlers.mousedown,
mouseover: handlers.mouseover,
mouseup: handlers.mouseup
};
};
var keyboard = function(win, container, isRoot, annotations) {
var bridge = WindowBridge(win);
var clearToNavigate = function() {
annotations.clear(container);
return Optional.none();
};
var keydown = function(event, start, soffset, finish, foffset, direction) {
var realEvent = event.raw;
var keycode = realEvent.which;
var shiftKey = realEvent.shiftKey === true;
var handler7 = retrieve$1(container, annotations.selectedSelector).fold(function() {
if (isNavigation(keycode) && !shiftKey) {
annotations.clearBeforeUpdate(container);
}
if (isDown(keycode) && shiftKey) {
return curry(select2, bridge, container, isRoot, down2, finish, start, annotations.selectRange);
} else if (isUp(keycode) && shiftKey) {
return curry(select2, bridge, container, isRoot, up2, finish, start, annotations.selectRange);
} else if (isDown(keycode)) {
return curry(navigate, bridge, isRoot, down2, finish, start, lastDownCheck);
} else if (isUp(keycode)) {
return curry(navigate, bridge, isRoot, up2, finish, start, firstUpCheck);
} else {
return Optional.none;
}
}, function(selected) {
var update$1 = function(attempts) {
return function() {
var navigation = findMap(attempts, function(delta) {
return update(delta.rows, delta.cols, container, selected, annotations);
});
return navigation.fold(function() {
return getEdges(container, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(function(edges) {
var relative2 = isDown(keycode) || direction.isForward(keycode) ? Situ.after : Situ.before;
bridge.setRelativeSelection(Situ.on(edges.first, 0), relative2(edges.table));
annotations.clear(container);
return Response.create(Optional.none(), true);
});
}, function(_2) {
return Optional.some(Response.create(Optional.none(), true));
});
};
};
if (isDown(keycode) && shiftKey) {
return update$1([rc(1, 0)]);
} else if (isUp(keycode) && shiftKey) {
return update$1([rc(-1, 0)]);
} else if (direction.isBackward(keycode) && shiftKey) {
return update$1([
rc(0, -1),
rc(-1, 0)
]);
} else if (direction.isForward(keycode) && shiftKey) {
return update$1([
rc(0, 1),
rc(1, 0)
]);
} else if (isNavigation(keycode) && !shiftKey) {
return clearToNavigate;
} else {
return Optional.none;
}
});
return handler7();
};
var keyup = function(event, start, soffset, finish, foffset) {
return retrieve$1(container, annotations.selectedSelector).fold(function() {
var realEvent = event.raw;
var keycode = realEvent.which;
var shiftKey = realEvent.shiftKey === true;
if (!shiftKey) {
return Optional.none();
}
if (isNavigation(keycode)) {
return sync(container, isRoot, start, soffset, finish, foffset, annotations.selectRange);
} else {
return Optional.none();
}
}, Optional.none);
};
return {
keydown,
keyup
};
};
var external = function(win, container, isRoot, annotations) {
var bridge = WindowBridge(win);
return function(start, finish) {
annotations.clearBeforeUpdate(container);
identify(start, finish, isRoot).each(function(cellSel) {
var boxes = cellSel.boxes.getOr([]);
annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
bridge.selectContents(finish);
bridge.collapseSelection();
});
};
};
var remove3 = function(element, classes3) {
each$2(classes3, function(x2) {
remove$2(element, x2);
});
};
var addClass2 = function(clazz) {
return function(element) {
add3(element, clazz);
};
};
var removeClasses = function(classes3) {
return function(element) {
remove3(element, classes3);
};
};
var byClass = function(ephemera2) {
var addSelectionClass = addClass2(ephemera2.selected);
var removeSelectionClasses = removeClasses([
ephemera2.selected,
ephemera2.lastSelected,
ephemera2.firstSelected
]);
var clear3 = function(container) {
var sels = descendants(container, ephemera2.selectedSelector);
each$2(sels, removeSelectionClasses);
};
var selectRange = function(container, cells2, start, finish) {
clear3(container);
each$2(cells2, addSelectionClass);
add3(start, ephemera2.firstSelected);
add3(finish, ephemera2.lastSelected);
};
return {
clearBeforeUpdate: clear3,
clear: clear3,
selectRange,
selectedSelector: ephemera2.selectedSelector,
firstSelectedSelector: ephemera2.firstSelectedSelector,
lastSelectedSelector: ephemera2.lastSelectedSelector
};
};
var byAttr = function(ephemera2, onSelection, onClear4) {
var removeSelectionAttributes = function(element) {
remove$7(element, ephemera2.selected);
remove$7(element, ephemera2.firstSelected);
remove$7(element, ephemera2.lastSelected);
};
var addSelectionAttribute = function(element) {
set$2(element, ephemera2.selected, "1");
};
var clear3 = function(container) {
clearBeforeUpdate(container);
onClear4();
};
var clearBeforeUpdate = function(container) {
var sels = descendants(container, ephemera2.selectedSelector + "," + ephemera2.firstSelectedSelector + "," + ephemera2.lastSelectedSelector);
each$2(sels, removeSelectionAttributes);
};
var selectRange = function(container, cells2, start, finish) {
clear3(container);
each$2(cells2, addSelectionAttribute);
set$2(start, ephemera2.firstSelected, "1");
set$2(finish, ephemera2.lastSelected, "1");
onSelection(cells2, start, finish);
};
return {
clearBeforeUpdate,
clear: clear3,
selectRange,
selectedSelector: ephemera2.selectedSelector,
firstSelectedSelector: ephemera2.firstSelectedSelector,
lastSelectedSelector: ephemera2.lastSelectedSelector
};
};
var SelectionAnnotation = {
byClass,
byAttr
};
var getUpOrLeftCells = function(grid2, selectedCells) {
var upGrid = grid2.slice(0, selectedCells[selectedCells.length - 1].row + 1);
var upDetails = toDetailList(upGrid);
return bind$22(upDetails, function(detail2) {
var slicedCells = detail2.cells.slice(0, selectedCells[selectedCells.length - 1].column + 1);
return map$1(slicedCells, function(cell2) {
return cell2.element;
});
});
};
var getDownOrRightCells = function(grid2, selectedCells) {
var downGrid = grid2.slice(selectedCells[0].row + selectedCells[0].rowspan - 1, grid2.length);
var downDetails = toDetailList(downGrid);
return bind$22(downDetails, function(detail2) {
var slicedCells = detail2.cells.slice(selectedCells[0].column + selectedCells[0].colspan - 1, detail2.cells.length);
return map$1(slicedCells, function(cell2) {
return cell2.element;
});
});
};
var getOtherCells = function(table3, target, generators) {
var warehouse = Warehouse.fromTable(table3);
var details = onCells(warehouse, target);
return details.map(function(selectedCells) {
var grid2 = toGrid(warehouse, generators, false);
var upOrLeftCells = getUpOrLeftCells(grid2, selectedCells);
var downOrRightCells = getDownOrRightCells(grid2, selectedCells);
return {
upOrLeftCells,
downOrRightCells
};
});
};
var global2 = tinymce.util.Tools.resolve("tinymce.Env");
var hasInternalTarget = function(e2) {
return has2(SugarElement.fromDom(e2.target), "ephox-snooker-resizer-bar") === false;
};
function CellSelection(editor, lazyResize, selectionTargets) {
var onSelection = function(cells2, start, finish) {
selectionTargets.targets().each(function(targets) {
var tableOpt = table2(start);
tableOpt.each(function(table3) {
var cloneFormats2 = getCloneElements(editor);
var generators = cellOperations(noop2, SugarElement.fromDom(editor.getDoc()), cloneFormats2);
var otherCells = getOtherCells(table3, targets, generators);
fireTableSelectionChange(editor, cells2, start, finish, otherCells);
});
});
};
var onClear4 = function() {
return fireTableSelectionClear(editor);
};
var annotations = SelectionAnnotation.byAttr(ephemera, onSelection, onClear4);
editor.on("init", function(_e) {
var win = editor.getWin();
var body2 = getBody2(editor);
var isRoot = getIsRoot(editor);
var syncSelection = function() {
var sel = editor.selection;
var start = SugarElement.fromDom(sel.getStart());
var end = SugarElement.fromDom(sel.getEnd());
var shared = sharedOne(table2, [
start,
end
]);
shared.fold(function() {
return annotations.clear(body2);
}, noop2);
};
var mouseHandlers = mouse(win, body2, isRoot, annotations);
var keyHandlers = keyboard(win, body2, isRoot, annotations);
var external$1 = external(win, body2, isRoot, annotations);
var hasShiftKey = function(event) {
return event.raw.shiftKey === true;
};
editor.on("TableSelectorChange", function(e2) {
return external$1(e2.start, e2.finish);
});
var handleResponse = function(event, response) {
if (!hasShiftKey(event)) {
return;
}
if (response.kill) {
event.kill();
}
response.selection.each(function(ns) {
var relative2 = SimSelection.relative(ns.start, ns.finish);
var rng = asLtrRange(win, relative2);
editor.selection.setRng(rng);
});
};
var keyup = function(event) {
var wrappedEvent = fromRawEvent(event);
if (wrappedEvent.raw.shiftKey && isNavigation(wrappedEvent.raw.which)) {
var rng = editor.selection.getRng();
var start = SugarElement.fromDom(rng.startContainer);
var end = SugarElement.fromDom(rng.endContainer);
keyHandlers.keyup(wrappedEvent, start, rng.startOffset, end, rng.endOffset).each(function(response) {
handleResponse(wrappedEvent, response);
});
}
};
var keydown = function(event) {
var wrappedEvent = fromRawEvent(event);
lazyResize().each(function(resize2) {
return resize2.hideBars();
});
var rng = editor.selection.getRng();
var start = SugarElement.fromDom(rng.startContainer);
var end = SugarElement.fromDom(rng.endContainer);
var direction = onDirection(ltr, rtl)(SugarElement.fromDom(editor.selection.getStart()));
keyHandlers.keydown(wrappedEvent, start, rng.startOffset, end, rng.endOffset, direction).each(function(response) {
handleResponse(wrappedEvent, response);
});
lazyResize().each(function(resize2) {
return resize2.showBars();
});
};
var isLeftMouse = function(raw) {
return raw.button === 0;
};
var isLeftButtonPressed = function(raw) {
if (raw.buttons === void 0) {
return true;
}
if (global2.browser.isEdge() && raw.buttons === 0) {
return true;
}
return (raw.buttons & 1) !== 0;
};
var dragStart = function(_e2) {
mouseHandlers.clearstate();
};
var mouseDown = function(e2) {
if (isLeftMouse(e2) && hasInternalTarget(e2)) {
mouseHandlers.mousedown(fromRawEvent(e2));
}
};
var mouseOver = function(e2) {
if (isLeftButtonPressed(e2) && hasInternalTarget(e2)) {
mouseHandlers.mouseover(fromRawEvent(e2));
}
};
var mouseUp = function(e2) {
if (isLeftMouse(e2) && hasInternalTarget(e2)) {
mouseHandlers.mouseup(fromRawEvent(e2));
}
};
var getDoubleTap = function() {
var lastTarget = Cell3(SugarElement.fromDom(body2));
var lastTimeStamp = Cell3(0);
var touchEnd = function(t2) {
var target = SugarElement.fromDom(t2.target);
if (name(target) === "td" || name(target) === "th") {
var lT = lastTarget.get();
var lTS = lastTimeStamp.get();
if (eq$1(lT, target) && t2.timeStamp - lTS < 300) {
t2.preventDefault();
external$1(target, target);
}
}
lastTarget.set(target);
lastTimeStamp.set(t2.timeStamp);
};
return { touchEnd };
};
var doubleTap = getDoubleTap();
editor.on("dragstart", dragStart);
editor.on("mousedown", mouseDown);
editor.on("mouseover", mouseOver);
editor.on("mouseup", mouseUp);
editor.on("touchend", doubleTap.touchEnd);
editor.on("keyup", keyup);
editor.on("keydown", keydown);
editor.on("NodeChange", syncSelection);
});
return { clear: annotations.clear };
}
var child = function(scope, selector2) {
return child$1(scope, selector2).isSome();
};
var getSelectionTargets = function(editor, selections) {
var targets = Cell3(Optional.none());
var changeHandlers = Cell3([]);
var selectionDetails = Optional.none();
var isCaption = isTag("caption");
var isDisabledForSelection = function(key3) {
return selectionDetails.forall(function(details) {
return !details[key3];
});
};
var getStart2 = function() {
return getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
};
var getEnd2 = function() {
return getSelectionCellOrCaption(getSelectionEnd(editor), getIsRoot(editor));
};
var findTargets = function() {
return getStart2().bind(function(startCellOrCaption) {
return flatten2(lift2(table2(startCellOrCaption), getEnd2().bind(table2), function(startTable, endTable) {
if (eq$1(startTable, endTable)) {
if (isCaption(startCellOrCaption)) {
return Optional.some(noMenu(startCellOrCaption));
} else {
return Optional.some(forMenu(selections, startTable, startCellOrCaption));
}
}
return Optional.none();
}));
});
};
var getExtractedDetails = function(targets2) {
var tableOpt = table2(targets2.element);
return tableOpt.map(function(table3) {
var warehouse = Warehouse.fromTable(table3);
var selectedCells = onCells(warehouse, targets2).getOr([]);
var locked = foldl(selectedCells, function(acc, cell2) {
if (cell2.isLocked) {
acc.onAny = true;
if (cell2.column === 0) {
acc.onFirst = true;
} else if (cell2.column + cell2.colspan >= warehouse.grid.columns) {
acc.onLast = true;
}
}
return acc;
}, {
onAny: false,
onFirst: false,
onLast: false
});
return {
mergeable: onUnlockedMergable(warehouse, targets2).isSome(),
unmergeable: onUnlockedUnmergable(warehouse, targets2).isSome(),
locked
};
});
};
var resetTargets = function() {
targets.set(cached2(findTargets)());
selectionDetails = targets.get().bind(getExtractedDetails);
each$2(changeHandlers.get(), function(handler7) {
return handler7();
});
};
var setupHandler = function(handler7) {
handler7();
changeHandlers.set(changeHandlers.get().concat([handler7]));
return function() {
changeHandlers.set(filter$2(changeHandlers.get(), function(h2) {
return h2 !== handler7;
}));
};
};
var onSetup = function(api3, isDisabled2) {
return setupHandler(function() {
return targets.get().fold(function() {
api3.setDisabled(true);
}, function(targets2) {
api3.setDisabled(isDisabled2(targets2));
});
});
};
var onSetupWithToggle = function(api3, isDisabled2, isActive) {
return setupHandler(function() {
return targets.get().fold(function() {
api3.setDisabled(true);
api3.setActive(false);
}, function(targets2) {
api3.setDisabled(isDisabled2(targets2));
api3.setActive(isActive(targets2));
});
});
};
var isDisabledFromLocked = function(lockedDisable) {
return selectionDetails.exists(function(details) {
return details.locked[lockedDisable];
});
};
var onSetupTable = function(api3) {
return onSetup(api3, function(_2) {
return false;
});
};
var onSetupCellOrRow = function(api3) {
return onSetup(api3, function(targets2) {
return isCaption(targets2.element);
});
};
var onSetupColumn = function(lockedDisable) {
return function(api3) {
return onSetup(api3, function(targets2) {
return isCaption(targets2.element) || isDisabledFromLocked(lockedDisable);
});
};
};
var onSetupPasteable = function(getClipboardData) {
return function(api3) {
return onSetup(api3, function(targets2) {
return isCaption(targets2.element) || getClipboardData().isNone();
});
};
};
var onSetupPasteableColumn = function(getClipboardData, lockedDisable) {
return function(api3) {
return onSetup(api3, function(targets2) {
return isCaption(targets2.element) || getClipboardData().isNone() || isDisabledFromLocked(lockedDisable);
});
};
};
var onSetupMergeable = function(api3) {
return onSetup(api3, function(_targets) {
return isDisabledForSelection("mergeable");
});
};
var onSetupUnmergeable = function(api3) {
return onSetup(api3, function(_targets) {
return isDisabledForSelection("unmergeable");
});
};
var onSetupTableWithCaption = function(api3) {
return onSetupWithToggle(api3, never, function(targets2) {
var tableOpt = table2(targets2.element, getIsRoot(editor));
return tableOpt.exists(function(table3) {
return child(table3, "caption");
});
});
};
var onSetupTableHeaders = function(command, headerType) {
return function(api3) {
return onSetupWithToggle(api3, function(targets2) {
return isCaption(targets2.element);
}, function() {
return editor.queryCommandValue(command) === headerType;
});
};
};
var onSetupTableRowHeaders = onSetupTableHeaders("mceTableRowType", "header");
var onSetupTableColumnHeaders = onSetupTableHeaders("mceTableColType", "th");
editor.on("NodeChange ExecCommand TableSelectorChange", resetTargets);
return {
onSetupTable,
onSetupCellOrRow,
onSetupColumn,
onSetupPasteable,
onSetupPasteableColumn,
onSetupMergeable,
onSetupUnmergeable,
resetTargets,
onSetupTableWithCaption,
onSetupTableRowHeaders,
onSetupTableColumnHeaders,
targets: targets.get
};
};
var addButtons = function(editor, selections, selectionTargets, clipboard) {
editor.ui.registry.addMenuButton("table", {
tooltip: "Table",
icon: "table",
fetch: function(callback2) {
return callback2("inserttable | cell row column | advtablesort | tableprops deletetable");
}
});
var cmd = function(command) {
return function() {
return editor.execCommand(command);
};
};
editor.ui.registry.addButton("tableprops", {
tooltip: "Table properties",
onAction: cmd("mceTableProps"),
icon: "table",
onSetup: selectionTargets.onSetupTable
});
editor.ui.registry.addButton("tabledelete", {
tooltip: "Delete table",
onAction: cmd("mceTableDelete"),
icon: "table-delete-table",
onSetup: selectionTargets.onSetupTable
});
editor.ui.registry.addButton("tablecellprops", {
tooltip: "Cell properties",
onAction: cmd("mceTableCellProps"),
icon: "table-cell-properties",
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton("tablemergecells", {
tooltip: "Merge cells",
onAction: cmd("mceTableMergeCells"),
icon: "table-merge-cells",
onSetup: selectionTargets.onSetupMergeable
});
editor.ui.registry.addButton("tablesplitcells", {
tooltip: "Split cell",
onAction: cmd("mceTableSplitCells"),
icon: "table-split-cells",
onSetup: selectionTargets.onSetupUnmergeable
});
editor.ui.registry.addButton("tableinsertrowbefore", {
tooltip: "Insert row before",
onAction: cmd("mceTableInsertRowBefore"),
icon: "table-insert-row-above",
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton("tableinsertrowafter", {
tooltip: "Insert row after",
onAction: cmd("mceTableInsertRowAfter"),
icon: "table-insert-row-after",
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton("tabledeleterow", {
tooltip: "Delete row",
onAction: cmd("mceTableDeleteRow"),
icon: "table-delete-row",
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton("tablerowprops", {
tooltip: "Row properties",
onAction: cmd("mceTableRowProps"),
icon: "table-row-properties",
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton("tableinsertcolbefore", {
tooltip: "Insert column before",
onAction: cmd("mceTableInsertColBefore"),
icon: "table-insert-column-before",
onSetup: selectionTargets.onSetupColumn("onFirst")
});
editor.ui.registry.addButton("tableinsertcolafter", {
tooltip: "Insert column after",
onAction: cmd("mceTableInsertColAfter"),
icon: "table-insert-column-after",
onSetup: selectionTargets.onSetupColumn("onLast")
});
editor.ui.registry.addButton("tabledeletecol", {
tooltip: "Delete column",
onAction: cmd("mceTableDeleteCol"),
icon: "table-delete-column",
onSetup: selectionTargets.onSetupColumn("onAny")
});
editor.ui.registry.addButton("tablecutrow", {
tooltip: "Cut row",
icon: "cut-row",
onAction: cmd("mceTableCutRow"),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton("tablecopyrow", {
tooltip: "Copy row",
icon: "duplicate-row",
onAction: cmd("mceTableCopyRow"),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addButton("tablepasterowbefore", {
tooltip: "Paste row before",
icon: "paste-row-before",
onAction: cmd("mceTablePasteRowBefore"),
onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
});
editor.ui.registry.addButton("tablepasterowafter", {
tooltip: "Paste row after",
icon: "paste-row-after",
onAction: cmd("mceTablePasteRowAfter"),
onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
});
editor.ui.registry.addButton("tablecutcol", {
tooltip: "Cut column",
icon: "cut-column",
onAction: cmd("mceTableCutCol"),
onSetup: selectionTargets.onSetupColumn("onAny")
});
editor.ui.registry.addButton("tablecopycol", {
tooltip: "Copy column",
icon: "duplicate-column",
onAction: cmd("mceTableCopyCol"),
onSetup: selectionTargets.onSetupColumn("onAny")
});
editor.ui.registry.addButton("tablepastecolbefore", {
tooltip: "Paste column before",
icon: "paste-column-before",
onAction: cmd("mceTablePasteColBefore"),
onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, "onFirst")
});
editor.ui.registry.addButton("tablepastecolafter", {
tooltip: "Paste column after",
icon: "paste-column-after",
onAction: cmd("mceTablePasteColAfter"),
onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, "onLast")
});
editor.ui.registry.addButton("tableinsertdialog", {
tooltip: "Insert table",
onAction: cmd("mceInsertTable"),
icon: "table"
});
var tableClassList = filterNoneItem(getTableClassList(editor));
if (tableClassList.length !== 0) {
editor.ui.registry.addMenuButton("tableclass", {
icon: "table-classes",
tooltip: "Table styles",
fetch: generateMenuItemsCallback(editor, selections, tableClassList, "tableclass", function(value25) {
return editor.execCommand("mceTableToggleClass", false, value25);
}),
onSetup: selectionTargets.onSetupTable
});
}
var tableCellClassList = filterNoneItem(getCellClassList(editor));
if (tableCellClassList.length !== 0) {
editor.ui.registry.addMenuButton("tablecellclass", {
icon: "table-cell-classes",
tooltip: "Cell styles",
fetch: generateMenuItemsCallback(editor, selections, tableCellClassList, "tablecellclass", function(value25) {
return editor.execCommand("mceTableCellToggleClass", false, value25);
}),
onSetup: selectionTargets.onSetupCellOrRow
});
}
editor.ui.registry.addMenuButton("tablecellvalign", {
icon: "vertical-align",
tooltip: "Vertical align",
fetch: generateMenuItemsCallback(editor, selections, verticalAlignValues, "tablecellverticalalign", applyTableCellStyle(editor, "vertical-align")),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuButton("tablecellborderwidth", {
icon: "border-width",
tooltip: "Border width",
fetch: generateMenuItemsCallback(editor, selections, getTableBorderWidths(editor), "tablecellborderwidth", applyTableCellStyle(editor, "border-width")),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuButton("tablecellborderstyle", {
icon: "border-style",
tooltip: "Border style",
fetch: generateMenuItemsCallback(editor, selections, getTableBorderStyles(editor), "tablecellborderstyle", applyTableCellStyle(editor, "border-style")),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addToggleButton("tablecaption", {
tooltip: "Table caption",
onAction: cmd("mceTableToggleCaption"),
icon: "table-caption",
onSetup: selectionTargets.onSetupTableWithCaption
});
editor.ui.registry.addMenuButton("tablecellbackgroundcolor", {
icon: "cell-background-color",
tooltip: "Background color",
fetch: function(callback2) {
return callback2(buildColorMenu(editor, getTableBackgroundColorMap(editor), "background-color"));
},
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuButton("tablecellbordercolor", {
icon: "cell-border-color",
tooltip: "Border color",
fetch: function(callback2) {
return callback2(buildColorMenu(editor, getTableBorderColorMap(editor), "border-color"));
},
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addToggleButton("tablerowheader", {
tooltip: "Row header",
icon: "table-top-header",
onAction: changeRowHeader(editor),
onSetup: selectionTargets.onSetupTableRowHeaders
});
editor.ui.registry.addToggleButton("tablecolheader", {
tooltip: "Column header",
icon: "table-left-header",
onAction: changeColumnHeader(editor),
onSetup: selectionTargets.onSetupTableColumnHeaders
});
};
var addToolbars = function(editor) {
var isTable = function(table3) {
return editor.dom.is(table3, "table") && editor.getBody().contains(table3);
};
var toolbar2 = getToolbar(editor);
if (toolbar2.length > 0) {
editor.ui.registry.addContextToolbar("table", {
predicate: isTable,
items: toolbar2,
scope: "node",
position: "node"
});
}
};
var addMenuItems = function(editor, selections, selectionTargets, clipboard) {
var cmd = function(command) {
return function() {
return editor.execCommand(command);
};
};
var insertTableAction = function(data65) {
editor.execCommand("mceInsertTable", false, {
rows: data65.numRows,
columns: data65.numColumns
});
};
var tableProperties = {
text: "Table properties",
onSetup: selectionTargets.onSetupTable,
onAction: cmd("mceTableProps")
};
var deleteTable = {
text: "Delete table",
icon: "table-delete-table",
onSetup: selectionTargets.onSetupTable,
onAction: cmd("mceTableDelete")
};
editor.ui.registry.addMenuItem("tableinsertrowbefore", {
text: "Insert row before",
icon: "table-insert-row-above",
onAction: cmd("mceTableInsertRowBefore"),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem("tableinsertrowafter", {
text: "Insert row after",
icon: "table-insert-row-after",
onAction: cmd("mceTableInsertRowAfter"),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem("tabledeleterow", {
text: "Delete row",
icon: "table-delete-row",
onAction: cmd("mceTableDeleteRow"),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem("tablerowprops", {
text: "Row properties",
icon: "table-row-properties",
onAction: cmd("mceTableRowProps"),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem("tablecutrow", {
text: "Cut row",
icon: "cut-row",
onAction: cmd("mceTableCutRow"),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem("tablecopyrow", {
text: "Copy row",
icon: "duplicate-row",
onAction: cmd("mceTableCopyRow"),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem("tablepasterowbefore", {
text: "Paste row before",
icon: "paste-row-before",
onAction: cmd("mceTablePasteRowBefore"),
onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
});
editor.ui.registry.addMenuItem("tablepasterowafter", {
text: "Paste row after",
icon: "paste-row-after",
onAction: cmd("mceTablePasteRowAfter"),
onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
});
var row2 = {
type: "nestedmenuitem",
text: "Row",
getSubmenuItems: constant2("tableinsertrowbefore tableinsertrowafter tabledeleterow tablerowprops | tablecutrow tablecopyrow tablepasterowbefore tablepasterowafter")
};
editor.ui.registry.addMenuItem("tableinsertcolumnbefore", {
text: "Insert column before",
icon: "table-insert-column-before",
onAction: cmd("mceTableInsertColBefore"),
onSetup: selectionTargets.onSetupColumn("onFirst")
});
editor.ui.registry.addMenuItem("tableinsertcolumnafter", {
text: "Insert column after",
icon: "table-insert-column-after",
onAction: cmd("mceTableInsertColAfter"),
onSetup: selectionTargets.onSetupColumn("onLast")
});
editor.ui.registry.addMenuItem("tabledeletecolumn", {
text: "Delete column",
icon: "table-delete-column",
onAction: cmd("mceTableDeleteCol"),
onSetup: selectionTargets.onSetupColumn("onAny")
});
editor.ui.registry.addMenuItem("tablecutcolumn", {
text: "Cut column",
icon: "cut-column",
onAction: cmd("mceTableCutCol"),
onSetup: selectionTargets.onSetupColumn("onAny")
});
editor.ui.registry.addMenuItem("tablecopycolumn", {
text: "Copy column",
icon: "duplicate-column",
onAction: cmd("mceTableCopyCol"),
onSetup: selectionTargets.onSetupColumn("onAny")
});
editor.ui.registry.addMenuItem("tablepastecolumnbefore", {
text: "Paste column before",
icon: "paste-column-before",
onAction: cmd("mceTablePasteColBefore"),
onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, "onFirst")
});
editor.ui.registry.addMenuItem("tablepastecolumnafter", {
text: "Paste column after",
icon: "paste-column-after",
onAction: cmd("mceTablePasteColAfter"),
onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, "onLast")
});
var column = {
type: "nestedmenuitem",
text: "Column",
getSubmenuItems: constant2("tableinsertcolumnbefore tableinsertcolumnafter tabledeletecolumn | tablecutcolumn tablecopycolumn tablepastecolumnbefore tablepastecolumnafter")
};
editor.ui.registry.addMenuItem("tablecellprops", {
text: "Cell properties",
icon: "table-cell-properties",
onAction: cmd("mceTableCellProps"),
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addMenuItem("tablemergecells", {
text: "Merge cells",
icon: "table-merge-cells",
onAction: cmd("mceTableMergeCells"),
onSetup: selectionTargets.onSetupMergeable
});
editor.ui.registry.addMenuItem("tablesplitcells", {
text: "Split cell",
icon: "table-split-cells",
onAction: cmd("mceTableSplitCells"),
onSetup: selectionTargets.onSetupUnmergeable
});
var cell2 = {
type: "nestedmenuitem",
text: "Cell",
getSubmenuItems: constant2("tablecellprops tablemergecells tablesplitcells")
};
if (hasTableGrid(editor) === false) {
editor.ui.registry.addMenuItem("inserttable", {
text: "Table",
icon: "table",
onAction: cmd("mceInsertTable")
});
} else {
editor.ui.registry.addNestedMenuItem("inserttable", {
text: "Table",
icon: "table",
getSubmenuItems: function() {
return [{
type: "fancymenuitem",
fancytype: "inserttable",
onAction: insertTableAction
}];
}
});
}
editor.ui.registry.addMenuItem("inserttabledialog", {
text: "Insert table",
icon: "table",
onAction: cmd("mceInsertTable")
});
editor.ui.registry.addMenuItem("tableprops", tableProperties);
editor.ui.registry.addMenuItem("deletetable", deleteTable);
editor.ui.registry.addNestedMenuItem("row", row2);
editor.ui.registry.addNestedMenuItem("column", column);
editor.ui.registry.addNestedMenuItem("cell", cell2);
editor.ui.registry.addContextMenu("table", {
update: function() {
selectionTargets.resetTargets();
return selectionTargets.targets().fold(constant2(""), function(targets) {
if (name(targets.element) === "caption") {
return "tableprops deletetable";
} else {
return "cell row column | advtablesort | tableprops deletetable";
}
});
}
});
var tableClassList = filterNoneItem(getTableClassList(editor));
if (tableClassList.length !== 0) {
editor.ui.registry.addNestedMenuItem("tableclass", {
icon: "table-classes",
text: "Table styles",
getSubmenuItems: function() {
return buildMenuItems(editor, selections, tableClassList, "tableclass", function(value25) {
return editor.execCommand("mceTableToggleClass", false, value25);
});
},
onSetup: selectionTargets.onSetupTable
});
}
var tableCellClassList = filterNoneItem(getCellClassList(editor));
if (tableCellClassList.length !== 0) {
editor.ui.registry.addNestedMenuItem("tablecellclass", {
icon: "table-cell-classes",
text: "Cell styles",
getSubmenuItems: function() {
return buildMenuItems(editor, selections, tableCellClassList, "tablecellclass", function(value25) {
return editor.execCommand("mceTableCellToggleClass", false, value25);
});
},
onSetup: selectionTargets.onSetupCellOrRow
});
}
editor.ui.registry.addNestedMenuItem("tablecellvalign", {
icon: "vertical-align",
text: "Vertical align",
getSubmenuItems: function() {
return buildMenuItems(editor, selections, verticalAlignValues, "tablecellverticalalign", applyTableCellStyle(editor, "vertical-align"));
},
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addNestedMenuItem("tablecellborderwidth", {
icon: "border-width",
text: "Border width",
getSubmenuItems: function() {
return buildMenuItems(editor, selections, getTableBorderWidths(editor), "tablecellborderwidth", applyTableCellStyle(editor, "border-width"));
},
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addNestedMenuItem("tablecellborderstyle", {
icon: "border-style",
text: "Border style",
getSubmenuItems: function() {
return buildMenuItems(editor, selections, getTableBorderStyles(editor), "tablecellborderstyle", applyTableCellStyle(editor, "border-style"));
},
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addToggleMenuItem("tablecaption", {
icon: "table-caption",
text: "Table caption",
onAction: cmd("mceTableToggleCaption"),
onSetup: selectionTargets.onSetupTableWithCaption
});
editor.ui.registry.addNestedMenuItem("tablecellbackgroundcolor", {
icon: "cell-background-color",
text: "Background color",
getSubmenuItems: function() {
return buildColorMenu(editor, getTableBackgroundColorMap(editor), "background-color");
},
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addNestedMenuItem("tablecellbordercolor", {
icon: "cell-border-color",
text: "Border color",
getSubmenuItems: function() {
return buildColorMenu(editor, getTableBorderColorMap(editor), "border-color");
},
onSetup: selectionTargets.onSetupCellOrRow
});
editor.ui.registry.addToggleMenuItem("tablerowheader", {
text: "Row header",
icon: "table-top-header",
onAction: changeRowHeader(editor),
onSetup: selectionTargets.onSetupTableRowHeaders
});
editor.ui.registry.addToggleMenuItem("tablecolheader", {
text: "Column header",
icon: "table-left-header",
onAction: changeColumnHeader(editor),
onSetup: selectionTargets.onSetupTableColumnHeaders
});
};
var Plugin = function(editor) {
var selections = Selections(function() {
return getBody2(editor);
}, function() {
return getSelectionCell(getSelectionStart(editor), getIsRoot(editor));
}, ephemera.selectedSelector);
var selectionTargets = getSelectionTargets(editor, selections);
var resizeHandler2 = getResizeHandler(editor);
var cellSelection = CellSelection(editor, resizeHandler2.lazyResize, selectionTargets);
var actions = TableActions(editor, cellSelection, resizeHandler2.lazyWire);
var clipboard = Clipboard();
registerCommands(editor, actions, cellSelection, selections, clipboard);
registerQueryCommands(editor, actions, selections);
registerEvents(editor, selections, actions);
addMenuItems(editor, selections, selectionTargets, clipboard);
addButtons(editor, selections, selectionTargets, clipboard);
addToolbars(editor);
editor.on("PreInit", function() {
editor.serializer.addTempAttr(ephemera.firstSelected);
editor.serializer.addTempAttr(ephemera.lastSelected);
registerFormats(editor);
});
if (hasTabNavigation(editor)) {
editor.on("keydown", function(e2) {
handle$1(e2, editor, cellSelection);
});
}
editor.on("remove", function() {
resizeHandler2.destroy();
});
return getApi(editor, clipboard, resizeHandler2, selectionTargets);
};
function Plugin$1() {
global$3.add("table", Plugin);
}
Plugin$1();
})();
(function() {
var global$2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
var fireInsertCustomChar = function(editor, chr) {
return editor.fire("insertCustomChar", { chr });
};
var insertChar = function(editor, chr) {
var evtChr = fireInsertCustomChar(editor, chr).chr;
editor.execCommand("mceInsertContent", false, evtChr);
};
var typeOf = function(x2) {
var t2 = typeof x2;
if (x2 === null) {
return "null";
} else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
return "array";
} else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
return "string";
} else {
return t2;
}
};
var isType = function(type2) {
return function(value24) {
return typeOf(value24) === type2;
};
};
var eq2 = function(t2) {
return function(a2) {
return t2 === a2;
};
};
var isArray$12 = isType("array");
var isNull2 = eq2(null);
var noop2 = function() {
};
var constant2 = function(value24) {
return function() {
return value24;
};
};
var identity2 = function(x2) {
return x2;
};
var never = constant2(false);
var always = constant2(true);
var none = function() {
return NONE;
};
var NONE = function() {
var call2 = function(thunk) {
return thunk();
};
var id2 = identity2;
var me = {
fold: function(n2, _s) {
return n2();
},
isSome: never,
isNone: always,
getOr: id2,
getOrThunk: call2,
getOrDie: function(msg) {
throw new Error(msg || "error: getOrDie called on none.");
},
getOrNull: constant2(null),
getOrUndefined: constant2(void 0),
or: id2,
orThunk: call2,
map: none,
each: noop2,
bind: none,
exists: never,
forall: always,
filter: function() {
return none();
},
toArray: function() {
return [];
},
toString: constant2("none()")
};
return me;
}();
var some2 = function(a2) {
var constant_a = constant2(a2);
var self2 = function() {
return me;
};
var bind5 = function(f2) {
return f2(a2);
};
var me = {
fold: function(n2, s2) {
return s2(a2);
},
isSome: always,
isNone: never,
getOr: constant_a,
getOrThunk: constant_a,
getOrDie: constant_a,
getOrNull: constant_a,
getOrUndefined: constant_a,
or: self2,
orThunk: self2,
map: function(f2) {
return some2(f2(a2));
},
each: function(f2) {
f2(a2);
},
bind: bind5,
exists: bind5,
forall: bind5,
filter: function(f2) {
return f2(a2) ? me : NONE;
},
toArray: function() {
return [a2];
},
toString: function() {
return "some(" + a2 + ")";
}
};
return me;
};
var from2 = function(value24) {
return value24 === null || value24 === void 0 ? NONE : some2(value24);
};
var Optional = {
some: some2,
none,
from: from2
};
var nativePush = Array.prototype.push;
var map2 = function(xs, f2) {
var len = xs.length;
var r2 = new Array(len);
for (var i2 = 0; i2 < len; i2++) {
var x2 = xs[i2];
r2[i2] = f2(x2, i2);
}
return r2;
};
var each2 = function(xs, f2) {
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
f2(x2, i2);
}
};
var findUntil = function(xs, pred, until) {
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
if (pred(x2, i2)) {
return Optional.some(x2);
} else if (until(x2, i2)) {
break;
}
}
return Optional.none();
};
var find2 = function(xs, pred) {
return findUntil(xs, pred, never);
};
var flatten2 = function(xs) {
var r2 = [];
for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
if (!isArray$12(xs[i2])) {
throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
}
nativePush.apply(r2, xs[i2]);
}
return r2;
};
var bind4 = function(xs, f2) {
return flatten2(map2(xs, f2));
};
var global$12 = tinymce.util.Tools.resolve("tinymce.util.Tools");
var getCharMap$1 = function(editor) {
return editor.getParam("charmap");
};
var getCharMapAppend = function(editor) {
return editor.getParam("charmap_append");
};
var isArray2 = global$12.isArray;
var UserDefined = "User Defined";
var getDefaultCharMap = function() {
return [
{
name: "Currency",
characters: [
[
36,
"dollar sign"
],
[
162,
"cent sign"
],
[
8364,
"euro sign"
],
[
163,
"pound sign"
],
[
165,
"yen sign"
],
[
164,
"currency sign"
],
[
8352,
"euro-currency sign"
],
[
8353,
"colon sign"
],
[
8354,
"cruzeiro sign"
],
[
8355,
"french franc sign"
],
[
8356,
"lira sign"
],
[
8357,
"mill sign"
],
[
8358,
"naira sign"
],
[
8359,
"peseta sign"
],
[
8360,
"rupee sign"
],
[
8361,
"won sign"
],
[
8362,
"new sheqel sign"
],
[
8363,
"dong sign"
],
[
8365,
"kip sign"
],
[
8366,
"tugrik sign"
],
[
8367,
"drachma sign"
],
[
8368,
"german penny symbol"
],
[
8369,
"peso sign"
],
[
8370,
"guarani sign"
],
[
8371,
"austral sign"
],
[
8372,
"hryvnia sign"
],
[
8373,
"cedi sign"
],
[
8374,
"livre tournois sign"
],
[
8375,
"spesmilo sign"
],
[
8376,
"tenge sign"
],
[
8377,
"indian rupee sign"
],
[
8378,
"turkish lira sign"
],
[
8379,
"nordic mark sign"
],
[
8380,
"manat sign"
],
[
8381,
"ruble sign"
],
[
20870,
"yen character"
],
[
20803,
"yuan character"
],
[
22291,
"yuan character, in hong kong and taiwan"
],
[
22278,
"yen/yuan character variant one"
]
]
},
{
name: "Text",
characters: [
[
169,
"copyright sign"
],
[
174,
"registered sign"
],
[
8482,
"trade mark sign"
],
[
8240,
"per mille sign"
],
[
181,
"micro sign"
],
[
183,
"middle dot"
],
[
8226,
"bullet"
],
[
8230,
"three dot leader"
],
[
8242,
"minutes / feet"
],
[
8243,
"seconds / inches"
],
[
167,
"section sign"
],
[
182,
"paragraph sign"
],
[
223,
"sharp s / ess-zed"
]
]
},
{
name: "Quotations",
characters: [
[
8249,
"single left-pointing angle quotation mark"
],
[
8250,
"single right-pointing angle quotation mark"
],
[
171,
"left pointing guillemet"
],
[
187,
"right pointing guillemet"
],
[
8216,
"left single quotation mark"
],
[
8217,
"right single quotation mark"
],
[
8220,
"left double quotation mark"
],
[
8221,
"right double quotation mark"
],
[
8218,
"single low-9 quotation mark"
],
[
8222,
"double low-9 quotation mark"
],
[
60,
"less-than sign"
],
[
62,
"greater-than sign"
],
[
8804,
"less-than or equal to"
],
[
8805,
"greater-than or equal to"
],
[
8211,
"en dash"
],
[
8212,
"em dash"
],
[
175,
"macron"
],
[
8254,
"overline"
],
[
164,
"currency sign"
],
[
166,
"broken bar"
],
[
168,
"diaeresis"
],
[
161,
"inverted exclamation mark"
],
[
191,
"turned question mark"
],
[
710,
"circumflex accent"
],
[
732,
"small tilde"
],
[
176,
"degree sign"
],
[
8722,
"minus sign"
],
[
177,
"plus-minus sign"
],
[
247,
"division sign"
],
[
8260,
"fraction slash"
],
[
215,
"multiplication sign"
],
[
185,
"superscript one"
],
[
178,
"superscript two"
],
[
179,
"superscript three"
],
[
188,
"fraction one quarter"
],
[
189,
"fraction one half"
],
[
190,
"fraction three quarters"
]
]
},
{
name: "Mathematical",
characters: [
[
402,
"function / florin"
],
[
8747,
"integral"
],
[
8721,
"n-ary sumation"
],
[
8734,
"infinity"
],
[
8730,
"square root"
],
[
8764,
"similar to"
],
[
8773,
"approximately equal to"
],
[
8776,
"almost equal to"
],
[
8800,
"not equal to"
],
[
8801,
"identical to"
],
[
8712,
"element of"
],
[
8713,
"not an element of"
],
[
8715,
"contains as member"
],
[
8719,
"n-ary product"
],
[
8743,
"logical and"
],
[
8744,
"logical or"
],
[
172,
"not sign"
],
[
8745,
"intersection"
],
[
8746,
"union"
],
[
8706,
"partial differential"
],
[
8704,
"for all"
],
[
8707,
"there exists"
],
[
8709,
"diameter"
],
[
8711,
"backward difference"
],
[
8727,
"asterisk operator"
],
[
8733,
"proportional to"
],
[
8736,
"angle"
]
]
},
{
name: "Extended Latin",
characters: [
[
192,
"A - grave"
],
[
193,
"A - acute"
],
[
194,
"A - circumflex"
],
[
195,
"A - tilde"
],
[
196,
"A - diaeresis"
],
[
197,
"A - ring above"
],
[
256,
"A - macron"
],
[
198,
"ligature AE"
],
[
199,
"C - cedilla"
],
[
200,
"E - grave"
],
[
201,
"E - acute"
],
[
202,
"E - circumflex"
],
[
203,
"E - diaeresis"
],
[
274,
"E - macron"
],
[
204,
"I - grave"
],
[
205,
"I - acute"
],
[
206,
"I - circumflex"
],
[
207,
"I - diaeresis"
],
[
298,
"I - macron"
],
[
208,
"ETH"
],
[
209,
"N - tilde"
],
[
210,
"O - grave"
],
[
211,
"O - acute"
],
[
212,
"O - circumflex"
],
[
213,
"O - tilde"
],
[
214,
"O - diaeresis"
],
[
216,
"O - slash"
],
[
332,
"O - macron"
],
[
338,
"ligature OE"
],
[
352,
"S - caron"
],
[
217,
"U - grave"
],
[
218,
"U - acute"
],
[
219,
"U - circumflex"
],
[
220,
"U - diaeresis"
],
[
362,
"U - macron"
],
[
221,
"Y - acute"
],
[
376,
"Y - diaeresis"
],
[
562,
"Y - macron"
],
[
222,
"THORN"
],
[
224,
"a - grave"
],
[
225,
"a - acute"
],
[
226,
"a - circumflex"
],
[
227,
"a - tilde"
],
[
228,
"a - diaeresis"
],
[
229,
"a - ring above"
],
[
257,
"a - macron"
],
[
230,
"ligature ae"
],
[
231,
"c - cedilla"
],
[
232,
"e - grave"
],
[
233,
"e - acute"
],
[
234,
"e - circumflex"
],
[
235,
"e - diaeresis"
],
[
275,
"e - macron"
],
[
236,
"i - grave"
],
[
237,
"i - acute"
],
[
238,
"i - circumflex"
],
[
239,
"i - diaeresis"
],
[
299,
"i - macron"
],
[
240,
"eth"
],
[
241,
"n - tilde"
],
[
242,
"o - grave"
],
[
243,
"o - acute"
],
[
244,
"o - circumflex"
],
[
245,
"o - tilde"
],
[
246,
"o - diaeresis"
],
[
248,
"o slash"
],
[
333,
"o macron"
],
[
339,
"ligature oe"
],
[
353,
"s - caron"
],
[
249,
"u - grave"
],
[
250,
"u - acute"
],
[
251,
"u - circumflex"
],
[
252,
"u - diaeresis"
],
[
363,
"u - macron"
],
[
253,
"y - acute"
],
[
254,
"thorn"
],
[
255,
"y - diaeresis"
],
[
563,
"y - macron"
],
[
913,
"Alpha"
],
[
914,
"Beta"
],
[
915,
"Gamma"
],
[
916,
"Delta"
],
[
917,
"Epsilon"
],
[
918,
"Zeta"
],
[
919,
"Eta"
],
[
920,
"Theta"
],
[
921,
"Iota"
],
[
922,
"Kappa"
],
[
923,
"Lambda"
],
[
924,
"Mu"
],
[
925,
"Nu"
],
[
926,
"Xi"
],
[
927,
"Omicron"
],
[
928,
"Pi"
],
[
929,
"Rho"
],
[
931,
"Sigma"
],
[
932,
"Tau"
],
[
933,
"Upsilon"
],
[
934,
"Phi"
],
[
935,
"Chi"
],
[
936,
"Psi"
],
[
937,
"Omega"
],
[
945,
"alpha"
],
[
946,
"beta"
],
[
947,
"gamma"
],
[
948,
"delta"
],
[
949,
"epsilon"
],
[
950,
"zeta"
],
[
951,
"eta"
],
[
952,
"theta"
],
[
953,
"iota"
],
[
954,
"kappa"
],
[
955,
"lambda"
],
[
956,
"mu"
],
[
957,
"nu"
],
[
958,
"xi"
],
[
959,
"omicron"
],
[
960,
"pi"
],
[
961,
"rho"
],
[
962,
"final sigma"
],
[
963,
"sigma"
],
[
964,
"tau"
],
[
965,
"upsilon"
],
[
966,
"phi"
],
[
967,
"chi"
],
[
968,
"psi"
],
[
969,
"omega"
]
]
},
{
name: "Symbols",
characters: [
[
8501,
"alef symbol"
],
[
982,
"pi symbol"
],
[
8476,
"real part symbol"
],
[
978,
"upsilon - hook symbol"
],
[
8472,
"Weierstrass p"
],
[
8465,
"imaginary part"
]
]
},
{
name: "Arrows",
characters: [
[
8592,
"leftwards arrow"
],
[
8593,
"upwards arrow"
],
[
8594,
"rightwards arrow"
],
[
8595,
"downwards arrow"
],
[
8596,
"left right arrow"
],
[
8629,
"carriage return"
],
[
8656,
"leftwards double arrow"
],
[
8657,
"upwards double arrow"
],
[
8658,
"rightwards double arrow"
],
[
8659,
"downwards double arrow"
],
[
8660,
"left right double arrow"
],
[
8756,
"therefore"
],
[
8834,
"subset of"
],
[
8835,
"superset of"
],
[
8836,
"not a subset of"
],
[
8838,
"subset of or equal to"
],
[
8839,
"superset of or equal to"
],
[
8853,
"circled plus"
],
[
8855,
"circled times"
],
[
8869,
"perpendicular"
],
[
8901,
"dot operator"
],
[
8968,
"left ceiling"
],
[
8969,
"right ceiling"
],
[
8970,
"left floor"
],
[
8971,
"right floor"
],
[
9001,
"left-pointing angle bracket"
],
[
9002,
"right-pointing angle bracket"
],
[
9674,
"lozenge"
],
[
9824,
"black spade suit"
],
[
9827,
"black club suit"
],
[
9829,
"black heart suit"
],
[
9830,
"black diamond suit"
],
[
8194,
"en space"
],
[
8195,
"em space"
],
[
8201,
"thin space"
],
[
8204,
"zero width non-joiner"
],
[
8205,
"zero width joiner"
],
[
8206,
"left-to-right mark"
],
[
8207,
"right-to-left mark"
]
]
}
];
};
var charmapFilter = function(charmap) {
return global$12.grep(charmap, function(item) {
return isArray2(item) && item.length === 2;
});
};
var getCharsFromSetting = function(settingValue) {
if (isArray2(settingValue)) {
return charmapFilter(settingValue);
}
if (typeof settingValue === "function") {
return settingValue();
}
return [];
};
var extendCharMap = function(editor, charmap) {
var userCharMap = getCharMap$1(editor);
if (userCharMap) {
charmap = [{
name: UserDefined,
characters: getCharsFromSetting(userCharMap)
}];
}
var userCharMapAppend = getCharMapAppend(editor);
if (userCharMapAppend) {
var userDefinedGroup = global$12.grep(charmap, function(cg) {
return cg.name === UserDefined;
});
if (userDefinedGroup.length) {
userDefinedGroup[0].characters = [].concat(userDefinedGroup[0].characters).concat(getCharsFromSetting(userCharMapAppend));
return charmap;
}
return charmap.concat({
name: UserDefined,
characters: getCharsFromSetting(userCharMapAppend)
});
}
return charmap;
};
var getCharMap = function(editor) {
var groups = extendCharMap(editor, getDefaultCharMap());
return groups.length > 1 ? [{
name: "All",
characters: bind4(groups, function(g2) {
return g2.characters;
})
}].concat(groups) : groups;
};
var get2 = function(editor) {
var getCharMap$12 = function() {
return getCharMap(editor);
};
var insertChar$1 = function(chr) {
insertChar(editor, chr);
};
return {
getCharMap: getCharMap$12,
insertChar: insertChar$1
};
};
var Cell3 = function(initial) {
var value24 = initial;
var get3 = function() {
return value24;
};
var set2 = function(v2) {
value24 = v2;
};
return {
get: get3,
set: set2
};
};
var last2 = function(fn, rate) {
var timer = null;
var cancel2 = function() {
if (!isNull2(timer)) {
clearTimeout(timer);
timer = null;
}
};
var throttle2 = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
cancel2();
timer = setTimeout(function() {
timer = null;
fn.apply(null, args);
}, rate);
};
return {
cancel: cancel2,
throttle: throttle2
};
};
var nativeFromCodePoint = String.fromCodePoint;
var contains2 = function(str, substr) {
return str.indexOf(substr) !== -1;
};
var fromCodePoint = function() {
var codePoints = [];
for (var _i = 0; _i < arguments.length; _i++) {
codePoints[_i] = arguments[_i];
}
if (nativeFromCodePoint) {
return nativeFromCodePoint.apply(void 0, codePoints);
} else {
var codeUnits = [];
var codeLen = 0;
var result = "";
for (var index2 = 0, len = codePoints.length; index2 !== len; ++index2) {
var codePoint = +codePoints[index2];
if (!(codePoint < 1114111 && codePoint >>> 0 === codePoint)) {
throw RangeError("Invalid code point: " + codePoint);
}
if (codePoint <= 65535) {
codeLen = codeUnits.push(codePoint);
} else {
codePoint -= 65536;
codeLen = codeUnits.push((codePoint >> 10) + 55296, codePoint % 1024 + 56320);
}
if (codeLen >= 16383) {
result += String.fromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result + String.fromCharCode.apply(null, codeUnits);
}
};
var charMatches = function(charCode, name, lowerCasePattern) {
if (contains2(fromCodePoint(charCode).toLowerCase(), lowerCasePattern)) {
return true;
} else {
return contains2(name.toLowerCase(), lowerCasePattern) || contains2(name.toLowerCase().replace(/\s+/g, ""), lowerCasePattern);
}
};
var scan2 = function(group, pattern2) {
var matches = [];
var lowerCasePattern = pattern2.toLowerCase();
each2(group.characters, function(g2) {
if (charMatches(g2[0], g2[1], lowerCasePattern)) {
matches.push(g2);
}
});
return map2(matches, function(m2) {
return {
text: m2[1],
value: fromCodePoint(m2[0]),
icon: fromCodePoint(m2[0])
};
});
};
var patternName = "pattern";
var open6 = function(editor, charMap) {
var makeGroupItems = function() {
return [
{
label: "Search",
type: "input",
name: patternName
},
{
type: "collection",
name: "results"
}
];
};
var makeTabs = function() {
return map2(charMap, function(charGroup) {
return {
title: charGroup.name,
name: charGroup.name,
items: makeGroupItems()
};
});
};
var makePanel = function() {
return {
type: "panel",
items: makeGroupItems()
};
};
var makeTabPanel = function() {
return {
type: "tabpanel",
tabs: makeTabs()
};
};
var currentTab = charMap.length === 1 ? Cell3(UserDefined) : Cell3("All");
var scanAndSet = function(dialogApi2, pattern2) {
find2(charMap, function(group) {
return group.name === currentTab.get();
}).each(function(f2) {
var items = scan2(f2, pattern2);
dialogApi2.setData({ results: items });
});
};
var SEARCH_DELAY = 40;
var updateFilter = last2(function(dialogApi2) {
var pattern2 = dialogApi2.getData().pattern;
scanAndSet(dialogApi2, pattern2);
}, SEARCH_DELAY);
var body = charMap.length === 1 ? makePanel() : makeTabPanel();
var initialData = {
pattern: "",
results: scan2(charMap[0], "")
};
var bridgeSpec = {
title: "Special Character",
size: "normal",
body,
buttons: [{
type: "cancel",
name: "close",
text: "Close",
primary: true
}],
initialData,
onAction: function(api2, details) {
if (details.name === "results") {
insertChar(editor, details.value);
api2.close();
}
},
onTabChange: function(dialogApi2, details) {
currentTab.set(details.newTabName);
updateFilter.throttle(dialogApi2);
},
onChange: function(dialogApi2, changeData) {
if (changeData.name === patternName) {
updateFilter.throttle(dialogApi2);
}
}
};
var dialogApi = editor.windowManager.open(bridgeSpec);
dialogApi.focus(patternName);
};
var register$1 = function(editor, charMap) {
editor.addCommand("mceShowCharmap", function() {
open6(editor, charMap);
});
};
var global2 = tinymce.util.Tools.resolve("tinymce.util.Promise");
var init = function(editor, all2) {
editor.ui.registry.addAutocompleter("charmap", {
ch: ":",
columns: "auto",
minChars: 2,
fetch: function(pattern2, _maxResults) {
return new global2(function(resolve, _reject) {
resolve(scan2(all2, pattern2));
});
},
onAction: function(autocompleteApi, rng, value24) {
editor.selection.setRng(rng);
editor.insertContent(value24);
autocompleteApi.hide();
}
});
};
var register3 = function(editor) {
editor.ui.registry.addButton("charmap", {
icon: "insert-character",
tooltip: "Special character",
onAction: function() {
return editor.execCommand("mceShowCharmap");
}
});
editor.ui.registry.addMenuItem("charmap", {
icon: "insert-character",
text: "Special character...",
onAction: function() {
return editor.execCommand("mceShowCharmap");
}
});
};
function Plugin() {
global$2.add("charmap", function(editor) {
var charMap = getCharMap(editor);
register$1(editor, charMap);
register3(editor);
init(editor, charMap[0]);
return get2(editor);
});
}
Plugin();
})();
(function() {
var global2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
var typeOf = function(x2) {
var t2 = typeof x2;
if (x2 === null) {
return "null";
} else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
return "array";
} else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
return "string";
} else {
return t2;
}
};
var isType$1 = function(type3) {
return function(value24) {
return typeOf(value24) === type3;
};
};
var isSimpleType = function(type3) {
return function(value24) {
return typeof value24 === type3;
};
};
var isString3 = isType$1("string");
var isBoolean2 = isSimpleType("boolean");
var isNullable = function(a2) {
return a2 === null || a2 === void 0;
};
var isNonNullable = function(a2) {
return !isNullable(a2);
};
var isFunction3 = isSimpleType("function");
var isNumber2 = isSimpleType("number");
var noop2 = function() {
};
var compose1 = function(fbc, fab) {
return function(a2) {
return fbc(fab(a2));
};
};
var constant2 = function(value24) {
return function() {
return value24;
};
};
var identity2 = function(x2) {
return x2;
};
var never = constant2(false);
var always = constant2(true);
var none = function() {
return NONE;
};
var NONE = function() {
var call2 = function(thunk) {
return thunk();
};
var id2 = identity2;
var me = {
fold: function(n2, _s) {
return n2();
},
isSome: never,
isNone: always,
getOr: id2,
getOrThunk: call2,
getOrDie: function(msg) {
throw new Error(msg || "error: getOrDie called on none.");
},
getOrNull: constant2(null),
getOrUndefined: constant2(void 0),
or: id2,
orThunk: call2,
map: none,
each: noop2,
bind: none,
exists: never,
forall: always,
filter: function() {
return none();
},
toArray: function() {
return [];
},
toString: constant2("none()")
};
return me;
}();
var some2 = function(a2) {
var constant_a = constant2(a2);
var self2 = function() {
return me;
};
var bind4 = function(f2) {
return f2(a2);
};
var me = {
fold: function(n2, s2) {
return s2(a2);
},
isSome: always,
isNone: never,
getOr: constant_a,
getOrThunk: constant_a,
getOrDie: constant_a,
getOrNull: constant_a,
getOrUndefined: constant_a,
or: self2,
orThunk: self2,
map: function(f2) {
return some2(f2(a2));
},
each: function(f2) {
f2(a2);
},
bind: bind4,
exists: bind4,
forall: bind4,
filter: function(f2) {
return f2(a2) ? me : NONE;
},
toArray: function() {
return [a2];
},
toString: function() {
return "some(" + a2 + ")";
}
};
return me;
};
var from2 = function(value24) {
return value24 === null || value24 === void 0 ? NONE : some2(value24);
};
var Optional = {
some: some2,
none,
from: from2
};
var map2 = function(xs, f2) {
var len = xs.length;
var r2 = new Array(len);
for (var i2 = 0; i2 < len; i2++) {
var x2 = xs[i2];
r2[i2] = f2(x2, i2);
}
return r2;
};
var each2 = function(xs, f2) {
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
f2(x2, i2);
}
};
var filter = function(xs, pred) {
var r2 = [];
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
if (pred(x2, i2)) {
r2.push(x2);
}
}
return r2;
};
var DOCUMENT = 9;
var DOCUMENT_FRAGMENT = 11;
var ELEMENT = 1;
var TEXT = 3;
var fromHtml = function(html, scope) {
var doc = scope || document;
var div = doc.createElement("div");
div.innerHTML = html;
if (!div.hasChildNodes() || div.childNodes.length > 1) {
console.error("HTML does not have a single root node", html);
throw new Error("HTML must have a single root node");
}
return fromDom(div.childNodes[0]);
};
var fromTag = function(tag, scope) {
var doc = scope || document;
var node = doc.createElement(tag);
return fromDom(node);
};
var fromText = function(text, scope) {
var doc = scope || document;
var node = doc.createTextNode(text);
return fromDom(node);
};
var fromDom = function(node) {
if (node === null || node === void 0) {
throw new Error("Node cannot be null or undefined");
}
return { dom: node };
};
var fromPoint = function(docElm, x2, y2) {
return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom);
};
var SugarElement = {
fromHtml,
fromTag,
fromText,
fromDom,
fromPoint
};
var is2 = function(element, selector2) {
var dom = element.dom;
if (dom.nodeType !== ELEMENT) {
return false;
} else {
var elem = dom;
if (elem.matches !== void 0) {
return elem.matches(selector2);
} else if (elem.msMatchesSelector !== void 0) {
return elem.msMatchesSelector(selector2);
} else if (elem.webkitMatchesSelector !== void 0) {
return elem.webkitMatchesSelector(selector2);
} else if (elem.mozMatchesSelector !== void 0) {
return elem.mozMatchesSelector(selector2);
} else {
throw new Error("Browser lacks native selectors");
}
}
};
typeof window !== "undefined" ? window : Function("return this;")();
var name = function(element) {
var r2 = element.dom.nodeName;
return r2.toLowerCase();
};
var type2 = function(element) {
return element.dom.nodeType;
};
var isType = function(t2) {
return function(element) {
return type2(element) === t2;
};
};
var isElement2 = isType(ELEMENT);
var isText = isType(TEXT);
var isDocument = isType(DOCUMENT);
var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
var isTag = function(tag) {
return function(e2) {
return isElement2(e2) && name(e2) === tag;
};
};
var owner = function(element) {
return SugarElement.fromDom(element.dom.ownerDocument);
};
var documentOrOwner = function(dos) {
return isDocument(dos) ? dos : owner(dos);
};
var parent2 = function(element) {
return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
};
var children$2 = function(element) {
return map2(element.dom.childNodes, SugarElement.fromDom);
};
var rawSet = function(dom, key2, value24) {
if (isString3(value24) || isBoolean2(value24) || isNumber2(value24)) {
dom.setAttribute(key2, value24 + "");
} else {
console.error("Invalid call to Attribute.set. Key ", key2, ":: Value ", value24, ":: Element ", dom);
throw new Error("Attribute value was not simple");
}
};
var set2 = function(element, key2, value24) {
rawSet(element.dom, key2, value24);
};
var remove3 = function(element, key2) {
element.dom.removeAttribute(key2);
};
var isShadowRoot = function(dos) {
return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
};
var supported = isFunction3(Element.prototype.attachShadow) && isFunction3(Node.prototype.getRootNode);
var getRootNode = supported ? function(e2) {
return SugarElement.fromDom(e2.dom.getRootNode());
} : documentOrOwner;
var getShadowRoot = function(e2) {
var r2 = getRootNode(e2);
return isShadowRoot(r2) ? Optional.some(r2) : Optional.none();
};
var getShadowHost = function(e2) {
return SugarElement.fromDom(e2.dom.host);
};
var inBody = function(element) {
var dom = isText(element) ? element.dom.parentNode : element.dom;
if (dom === void 0 || dom === null || dom.ownerDocument === null) {
return false;
}
var doc = dom.ownerDocument;
return getShadowRoot(SugarElement.fromDom(dom)).fold(function() {
return doc.body.contains(dom);
}, compose1(inBody, getShadowHost));
};
var ancestor$1 = function(scope, predicate, isRoot) {
var element = scope.dom;
var stop2 = isFunction3(isRoot) ? isRoot : never;
while (element.parentNode) {
element = element.parentNode;
var el = SugarElement.fromDom(element);
if (predicate(el)) {
return Optional.some(el);
} else if (stop2(el)) {
break;
}
}
return Optional.none();
};
var ancestor = function(scope, selector2, isRoot) {
return ancestor$1(scope, function(e2) {
return is2(e2, selector2);
}, isRoot);
};
var isSupported = function(dom) {
return dom.style !== void 0 && isFunction3(dom.style.getPropertyValue);
};
var get2 = function(element, property2) {
var dom = element.dom;
var styles = window.getComputedStyle(dom);
var r2 = styles.getPropertyValue(property2);
return r2 === "" && !inBody(element) ? getUnsafeProperty(dom, property2) : r2;
};
var getUnsafeProperty = function(dom, property2) {
return isSupported(dom) ? dom.style.getPropertyValue(property2) : "";
};
var getDirection = function(element) {
return get2(element, "direction") === "rtl" ? "rtl" : "ltr";
};
var children$1 = function(scope, predicate) {
return filter(children$2(scope), predicate);
};
var children = function(scope, selector2) {
return children$1(scope, function(e2) {
return is2(e2, selector2);
});
};
var getParentElement = function(element) {
return parent2(element).filter(isElement2);
};
var getNormalizedBlock = function(element, isListItem2) {
var normalizedElement = isListItem2 ? ancestor(element, "ol,ul") : Optional.some(element);
return normalizedElement.getOr(element);
};
var isListItem = isTag("li");
var setDir = function(editor, dir) {
var selectedBlocks = editor.selection.getSelectedBlocks();
if (selectedBlocks.length > 0) {
each2(selectedBlocks, function(block) {
var blockElement = SugarElement.fromDom(block);
var isBlockElementListItem = isListItem(blockElement);
var normalizedBlock = getNormalizedBlock(blockElement, isBlockElementListItem);
var normalizedBlockParent = getParentElement(normalizedBlock);
normalizedBlockParent.each(function(parent3) {
var parentDirection = getDirection(parent3);
if (parentDirection !== dir) {
set2(normalizedBlock, "dir", dir);
} else if (getDirection(normalizedBlock) !== dir) {
remove3(normalizedBlock, "dir");
}
if (isBlockElementListItem) {
var listItems = children(normalizedBlock, "li[dir]");
each2(listItems, function(listItem) {
return remove3(listItem, "dir");
});
}
});
});
editor.nodeChanged();
}
};
var register$1 = function(editor) {
editor.addCommand("mceDirectionLTR", function() {
setDir(editor, "ltr");
});
editor.addCommand("mceDirectionRTL", function() {
setDir(editor, "rtl");
});
};
var getNodeChangeHandler = function(editor, dir) {
return function(api2) {
var nodeChangeHandler = function(e2) {
var element = SugarElement.fromDom(e2.element);
api2.setActive(getDirection(element) === dir);
};
editor.on("NodeChange", nodeChangeHandler);
return function() {
return editor.off("NodeChange", nodeChangeHandler);
};
};
};
var register3 = function(editor) {
editor.ui.registry.addToggleButton("ltr", {
tooltip: "Left to right",
icon: "ltr",
onAction: function() {
return editor.execCommand("mceDirectionLTR");
},
onSetup: getNodeChangeHandler(editor, "ltr")
});
editor.ui.registry.addToggleButton("rtl", {
tooltip: "Right to left",
icon: "rtl",
onAction: function() {
return editor.execCommand("mceDirectionRTL");
},
onSetup: getNodeChangeHandler(editor, "rtl")
});
};
function Plugin() {
global2.add("directionality", function(editor) {
register$1(editor);
register3(editor);
});
}
Plugin();
})();
(function() {
var Cell3 = function(initial) {
var value25 = initial;
var get3 = function() {
return value25;
};
var set3 = function(v2) {
value25 = v2;
};
return {
get: get3,
set: set3
};
};
var global$3 = tinymce.util.Tools.resolve("tinymce.PluginManager");
var get$5 = function(fullscreenState) {
return {
isFullscreen: function() {
return fullscreenState.get() !== null;
}
};
};
var typeOf = function(x2) {
var t2 = typeof x2;
if (x2 === null) {
return "null";
} else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
return "array";
} else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
return "string";
} else {
return t2;
}
};
var isType$1 = function(type3) {
return function(value25) {
return typeOf(value25) === type3;
};
};
var isSimpleType = function(type3) {
return function(value25) {
return typeof value25 === type3;
};
};
var isString3 = isType$1("string");
var isArray2 = isType$1("array");
var isBoolean2 = isSimpleType("boolean");
var isNullable = function(a2) {
return a2 === null || a2 === void 0;
};
var isNonNullable = function(a2) {
return !isNullable(a2);
};
var isFunction3 = isSimpleType("function");
var isNumber2 = isSimpleType("number");
var noop2 = function() {
};
var compose = function(fa, fb) {
return function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return fa(fb.apply(null, args));
};
};
var compose1 = function(fbc, fab) {
return function(a2) {
return fbc(fab(a2));
};
};
var constant2 = function(value25) {
return function() {
return value25;
};
};
var identity2 = function(x2) {
return x2;
};
function curry(fn) {
var initialArgs = [];
for (var _i = 1; _i < arguments.length; _i++) {
initialArgs[_i - 1] = arguments[_i];
}
return function() {
var restArgs = [];
for (var _i2 = 0; _i2 < arguments.length; _i2++) {
restArgs[_i2] = arguments[_i2];
}
var all3 = initialArgs.concat(restArgs);
return fn.apply(null, all3);
};
}
var never = constant2(false);
var always = constant2(true);
var none = function() {
return NONE;
};
var NONE = function() {
var call2 = function(thunk) {
return thunk();
};
var id2 = identity2;
var me = {
fold: function(n2, _s) {
return n2();
},
isSome: never,
isNone: always,
getOr: id2,
getOrThunk: call2,
getOrDie: function(msg) {
throw new Error(msg || "error: getOrDie called on none.");
},
getOrNull: constant2(null),
getOrUndefined: constant2(void 0),
or: id2,
orThunk: call2,
map: none,
each: noop2,
bind: none,
exists: never,
forall: always,
filter: function() {
return none();
},
toArray: function() {
return [];
},
toString: constant2("none()")
};
return me;
}();
var some2 = function(a2) {
var constant_a = constant2(a2);
var self2 = function() {
return me;
};
var bind5 = function(f2) {
return f2(a2);
};
var me = {
fold: function(n2, s2) {
return s2(a2);
},
isSome: always,
isNone: never,
getOr: constant_a,
getOrThunk: constant_a,
getOrDie: constant_a,
getOrNull: constant_a,
getOrUndefined: constant_a,
or: self2,
orThunk: self2,
map: function(f2) {
return some2(f2(a2));
},
each: function(f2) {
f2(a2);
},
bind: bind5,
exists: bind5,
forall: bind5,
filter: function(f2) {
return f2(a2) ? me : NONE;
},
toArray: function() {
return [a2];
},
toString: function() {
return "some(" + a2 + ")";
}
};
return me;
};
var from2 = function(value25) {
return value25 === null || value25 === void 0 ? NONE : some2(value25);
};
var Optional = {
some: some2,
none,
from: from2
};
var __assign = function() {
__assign = Object.assign || function __assign2(t2) {
for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
s2 = arguments[i2];
for (var p in s2)
if (Object.prototype.hasOwnProperty.call(s2, p))
t2[p] = s2[p];
}
return t2;
};
return __assign.apply(this, arguments);
};
var singleton = function(doRevoke) {
var subject = Cell3(Optional.none());
var revoke = function() {
return subject.get().each(doRevoke);
};
var clear2 = function() {
revoke();
subject.set(Optional.none());
};
var isSet2 = function() {
return subject.get().isSome();
};
var get3 = function() {
return subject.get();
};
var set3 = function(s2) {
revoke();
subject.set(Optional.some(s2));
};
return {
clear: clear2,
isSet: isSet2,
get: get3,
set: set3
};
};
var unbindable = function() {
return singleton(function(s2) {
return s2.unbind();
});
};
var value24 = function() {
var subject = singleton(noop2);
var on2 = function(f2) {
return subject.get().each(f2);
};
return __assign(__assign({}, subject), { on: on2 });
};
var nativePush = Array.prototype.push;
var map2 = function(xs, f2) {
var len = xs.length;
var r3 = new Array(len);
for (var i2 = 0; i2 < len; i2++) {
var x2 = xs[i2];
r3[i2] = f2(x2, i2);
}
return r3;
};
var each$12 = function(xs, f2) {
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
f2(x2, i2);
}
};
var filter$1 = function(xs, pred) {
var r3 = [];
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
if (pred(x2, i2)) {
r3.push(x2);
}
}
return r3;
};
var findUntil = function(xs, pred, until) {
for (var i2 = 0, len = xs.length; i2 < len; i2++) {
var x2 = xs[i2];
if (pred(x2, i2)) {
return Optional.some(x2);
} else if (until(x2, i2)) {
break;
}
}
return Optional.none();
};
var find$12 = function(xs, pred) {
return findUntil(xs, pred, never);
};
var flatten2 = function(xs) {
var r3 = [];
for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
if (!isArray2(xs[i2])) {
throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
}
nativePush.apply(r3, xs[i2]);
}
return r3;
};
var bind$32 = function(xs, f2) {
return flatten2(map2(xs, f2));
};
var get$4 = function(xs, i2) {
return i2 >= 0 && i2 < xs.length ? Optional.some(xs[i2]) : Optional.none();
};
var head = function(xs) {
return get$4(xs, 0);
};
var findMap = function(arr, f2) {
for (var i2 = 0; i2 < arr.length; i2++) {
var r3 = f2(arr[i2], i2);
if (r3.isSome()) {
return r3;
}
}
return Optional.none();
};
var keys2 = Object.keys;
var each2 = function(obj, f2) {
var props2 = keys2(obj);
for (var k2 = 0, len = props2.length; k2 < len; k2++) {
var i2 = props2[k2];
var x2 = obj[i2];
f2(x2, i2);
}
};
var contains2 = function(str, substr) {
return str.indexOf(substr) !== -1;
};
var isSupported$1 = function(dom) {
return dom.style !== void 0 && isFunction3(dom.style.getPropertyValue);
};
var fromHtml = function(html, scope) {
var doc = scope || document;
var div = doc.createElement("div");
div.innerHTML = html;
if (!div.hasChildNodes() || div.childNodes.length > 1) {
console.error("HTML does not have a single root node", html);
throw new Error("HTML must have a single root node");
}
return fromDom(div.childNodes[0]);
};
var fromTag = function(tag, scope) {
var doc = scope || document;
var node = doc.createElement(tag);
return fromDom(node);
};
var fromText = function(text, scope) {
var doc = scope || document;
var node = doc.createTextNode(text);
return fromDom(node);
};
var fromDom = function(node) {
if (node === null || node === void 0) {
throw new Error("Node cannot be null or undefined");
}
return { dom: node };
};
var fromPoint = function(docElm, x2, y2) {
return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom);
};
var SugarElement = {
fromHtml,
fromTag,
fromText,
fromDom,
fromPoint
};
typeof window !== "undefined" ? window : Function("return this;")();
var DOCUMENT = 9;
var DOCUMENT_FRAGMENT = 11;
var ELEMENT = 1;
var TEXT = 3;
var type2 = function(element) {
return element.dom.nodeType;
};
var isType = function(t2) {
return function(element) {
return type2(element) === t2;
};
};
var isElement2 = isType(ELEMENT);
var isText = isType(TEXT);
var isDocument = isType(DOCUMENT);
var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
var cached2 = function(f2) {
var called = false;
var r3;
return function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!called) {
called = true;
r3 = f2.apply(null, args);
}
return r3;
};
};
var DeviceType = function(os, browser, userAgent, mediaMatch2) {
var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
var isiPhone = os.isiOS() && !isiPad;
var isMobile2 = os.isiOS() || os.isAndroid();
var isTouch = isMobile2 || mediaMatch2("(pointer:coarse)");
var isTablet = isiPad || !isiPhone && isMobile2 && mediaMatch2("(min-device-width:768px)");
var isPhone = isiPhone || isMobile2 && !isTablet;
var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
var isDesktop = !isPhone && !isTablet && !iOSwebview;
return {
isiPad: constant2(isiPad),
isiPhone: constant2(isiPhone),
isTablet: constant2(isTablet),
isPhone: constant2(isPhone),
isTouch: constant2(isTouch),
isAndroid: os.isAndroid,
isiOS: os.isiOS,
isWebView: constant2(iOSwebview),
isDesktop: constant2(isDesktop)
};
};
var firstMatch = function(regexes2, s2) {
for (var i2 = 0; i2 < regexes2.length; i2++) {
var x2 = regexes2[i2];
if (x2.test(s2)) {
return x2;
}
}
return void 0;
};
var find2 = function(regexes2, agent) {
var r3 = firstMatch(regexes2, agent);
if (!r3) {
return {
major: 0,
minor: 0
};
}
var group = function(i2) {
return Number(agent.replace(r3, "$" + i2));
};
return nu$2(group(1), group(2));
};
var detect$3 = function(versionRegexes, agent) {
var cleanedAgent = String(agent).toLowerCase();
if (versionRegexes.length === 0) {
return unknown$2();
}
return find2(versionRegexes, cleanedAgent);
};
var unknown$2 = function() {
return nu$2(0, 0);
};
var nu$2 = function(major, minor) {
return {
major,
minor
};
};
var Version = {
nu: nu$2,
detect: detect$3,
unknown: unknown$2
};
var detectBrowser$1 = function(browsers2, userAgentData) {
return findMap(userAgentData.brands, function(uaBrand) {
var lcBrand = uaBrand.brand.toLowerCase();
return find$12(browsers2, function(browser) {
var _a3;
return lcBrand === ((_a3 = browser.brand) === null || _a3 === void 0 ? void 0 : _a3.toLowerCase());
}).map(function(info3) {
return {
current: info3.name,
version: Version.nu(parseInt(uaBrand.version, 10), 0)
};
});
});
};
var detect$2 = function(candidates, userAgent) {
var agent = String(userAgent).toLowerCase();
return find$12(candidates, function(candidate) {
return candidate.search(agent);
});
};
var detectBrowser = function(browsers2, userAgent) {
return detect$2(browsers2, userAgent).map(function(browser) {
var version = Version.detect(browser.versionRegexes, userAgent);
return {
current: browser.name,
version
};
});
};
var detectOs = function(oses2, userAgent) {
return detect$2(oses2, userAgent).map(function(os) {
var version = Version.detect(os.versionRegexes, userAgent);
return {
current: os.name,
version
};
});
};
var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
var checkContains = function(target) {
return function(uastring) {
return contains2(uastring, target);
};
};
var browsers = [
{
name: "Edge",
versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
search: function(uastring) {
return contains2(uastring, "edge/") && contains2(uastring, "chrome") && contains2(uastring, "safari") && contains2(uastring, "applewebkit");
}
},
{
name: "Chrome",
brand: "Chromium",
versionRegexes: [
/.*?chrome\/([0-9]+)\.([0-9]+).*/,
normalVersionRegex
],
search: function(uastring) {
return contains2(uastring, "chrome") && !contains2(uastring, "chromeframe");
}
},
{
name: "IE",
versionRegexes: [
/.*?msie\ ?([0-9]+)\.([0-9]+).*/,
/.*?rv:([0-9]+)\.([0-9]+).*/
],
search: function(uastring) {
return contains2(uastring, "msie") || contains2(uastring, "trident");
}
},
{
name: "Opera",
versionRegexes: [
normalVersionRegex,
/.*?opera\/([0-9]+)\.([0-9]+).*/
],
search: checkContains("opera")
},
{
name: "Firefox",
versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
search: checkContains("firefox")
},
{
name: "Safari",
versionRegexes: [
normalVersionRegex,
/.*?cpu os ([0-9]+)_([0-9]+).*/
],
search: function(uastring) {
return (contains2(uastring, "safari") || contains2(uastring, "mobile/")) && contains2(uastring, "applewebkit");
}
}
];
var oses = [
{
name: "Windows",
search: checkContains("win"),
versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
},
{
name: "iOS",
search: function(uastring) {
return contains2(uastring, "iphone") || contains2(uastring, "ipad");
},
versionRegexes: [
/.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
/.*cpu os ([0-9]+)_([0-9]+).*/,
/.*cpu iphone os ([0-9]+)_([0-9]+).*/
]
},
{
name: "Android",
search: checkContains("android"),
versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
},
{
name: "OSX",
search: checkContains("mac os x"),
versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
},
{
name: "Linux",
search: checkContains("linux"),
versionRegexes: []
},
{
name: "Solaris",
search: checkContains("sunos"),
versionRegexes: []
},
{
name: "FreeBSD",
search: checkContains("freebsd"),
versionRegexes: []
},
{
name: "ChromeOS",
search: checkContains("cros"),
versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
}
];
var PlatformInfo = {
browsers: constant2(browsers),
oses: constant2(oses)
};
var edge = "Edge";
var chrome = "Chrome";
var ie = "IE";
var opera = "Opera";
var firefox = "Firefox";
var safari = "Safari";
var unknown$1 = function() {
return nu$1({
current: void 0,
version: Version.unknown()
});
};
var nu$1 = function(info3) {
var current2 = info3.current;
var version = info3.version;
var isBrowser2 = function(name) {
return function() {
return current2 === name;
};
};
return {
current: current2,
version,
isEdge: isBrowser2(edge),
isChrome: isBrowser2(chrome),
isIE: isBrowser2(ie),
isOpera: isBrowser2(opera),
isFirefox: isBrowser2(firefox),
isSafari: isBrowser2(safari)
};
};
var Browser = {
unknown: unknown$1,
nu: nu$1,
edge: constant2(edge),
chrome: constant2(chrome),
ie: constant2(ie),
opera: constant2(opera),
firefox: constant2(firefox),
safari: constant2(safari)
};
var windows = "Windows";
var ios = "iOS";
var android = "Android";
var linux = "Linux";
var osx = "OSX";
var solaris = "Solaris";
var freebsd = "FreeBSD";
var chromeos = "ChromeOS";
var unknown = function() {
return nu({
current: void 0,
version: Version.unknown()
});
};
var nu = function(info3) {
var current2 = info3.current;
var version = info3.version;
var isOS = function(name) {
return function() {
return current2 === name;
};
};
return {
current: current2,
version,
isWindows: isOS(windows),
isiOS: isOS(ios),
isAndroid: isOS(android),
isOSX: isOS(osx),
isLinux: isOS(linux),
isSolaris: isOS(solaris),
isFreeBSD: isOS(freebsd),
isChromeOS: isOS(chromeos)
};
};
var OperatingSystem = {
unknown,
nu,
windows: constant2(windows),
ios: constant2(ios),
android: constant2(android),
linux: constant2(linux),
osx: constant2(osx),
solaris: constant2(solaris),
freebsd: constant2(freebsd),
chromeos: constant2(chromeos)
};
var detect$1 = function(userAgent, userAgentDataOpt, mediaMatch2) {
var browsers2 = PlatformInfo.browsers();
var oses2 = PlatformInfo.oses();
var browser = userAgentDataOpt.bind(function(userAgentData) {
return detectBrowser$1(browsers2, userAgentData);
}).orThunk(function() {
return detectBrowser(browsers2, userAgent);
}).fold(Browser.unknown, Browser.nu);
var os = detectOs(oses2, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
var deviceType = DeviceType(os, browser, userAgent, mediaMatch2);
return {
browser,
os,
deviceType
};
};
var PlatformDetection = { detect: detect$1 };
var mediaMatch = function(query) {
return window.matchMedia(query).matches;
};
var platform = cached2(function() {
return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
});
var detect = function() {
return platform();
};
var is2 = function(element, selector2) {
var dom = element.dom;
if (dom.nodeType !== ELEMENT) {
return false;
} else {
var elem = dom;
if (elem.matches !== void 0) {
return elem.matches(selector2);
} else if (elem.msMatchesSelector !== void 0) {
return elem.msMatchesSelector(selector2);
} else if (elem.webkitMatchesSelector !== void 0) {
return elem.webkitMatchesSelector(selector2);
} else if (elem.mozMatchesSelector !== void 0) {
return elem.mozMatchesSelector(selector2);
} else {
throw new Error("Browser lacks native selectors");
}
}
};
var bypassSelector = function(dom) {
return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
};
var all$1 = function(selector2, scope) {
var base = scope === void 0 ? document : scope.dom;
return bypassSelector(base) ? [] : map2(base.querySelectorAll(selector2), SugarElement.fromDom);
};
var eq2 = function(e1, e2) {
return e1.dom === e2.dom;
};
var owner = function(element) {
return SugarElement.fromDom(element.dom.ownerDocument);
};
var documentOrOwner = function(dos) {
return isDocument(dos) ? dos : owner(dos);
};
var parent2 = function(element) {
return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
};
var parents = function(element, isRoot) {
var stop2 = isFunction3(isRoot) ? isRoot : never;
var dom = element.dom;
var ret = [];
while (dom.parentNode !== null && dom.parentNode !== void 0) {
var rawParent = dom.parentNode;
var p = SugarElement.fromDom(rawParent);
ret.push(p);
if (stop2(p) === true) {
break;
} else {
dom = rawParent;
}
}
return ret;
};
var siblings$2 = function(element) {
var filterSelf = function(elements) {
return filter$1(elements, function(x2) {
return !eq2(element, x2);
});
};
return parent2(element).map(children).map(filterSelf).getOr([]);
};
var children = function(element) {
return map2(element.dom.childNodes, SugarElement.fromDom);
};
var isShadowRoot = function(dos) {
return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
};
var supported = isFunction3(Element.prototype.attachShadow) && isFunction3(Node.prototype.getRootNode);
var isSupported = constant2(supported);
var getRootNode = supported ? function(e2) {
return SugarElement.fromDom(e2.dom.getRootNode());
} : documentOrOwner;
var getShadowRoot = function(e2) {
var r3 = getRootNode(e2);
return isShadowRoot(r3) ? Optional.some(r3) : Optional.none();
};
var getShadowHost = function(e2) {
return SugarElement.fromDom(e2.dom.host);
};
var getOriginalEventTarget = function(event) {
if (isSupported() && isNonNullable(event.target)) {
var el = SugarElement.fromDom(event.target);
if (isElement2(el) && isOpenShadowHost(el)) {
if (event.composed && event.composedPath) {
var composedPath = event.composedPath();
if (composedPath) {
return head(composedPath);
}
}
}
}
return Optional.from(event.target);
};
var isOpenShadowHost = function(element) {
return isNonNullable(element.dom.shadowRoot);
};
var inBody = function(element) {
var dom = isText(element) ? element.dom.parentNode : element.dom;
if (dom === void 0 || dom === null || dom.ownerDocument === null) {
return false;
}
var doc = dom.ownerDocument;
return getShadowRoot(SugarElement.fromDom(dom)).fold(function() {
return doc.body.contains(dom);
}, compose1(inBody, getShadowHost));
};
var getBody2 = function(doc) {
var b2 = doc.dom.body;
if (b2 === null || b2 === void 0) {
throw new Error("Body is not available yet");
}
return SugarElement.fromDom(b2);
};
var rawSet = function(dom, key2, value25) {
if (isString3(value25) || isBoolean2(value25) || isNumber2(value25)) {
dom.setAttribute(key2, value25 + "");
} else {
console.error("Invalid call to Attribute.set. Key ", key2, ":: Value ", value25, ":: Element ", dom);
throw new Error("Attribute value was not simple");
}
};
var set2 = function(element, key2, value25) {
rawSet(element.dom, key2, value25);
};
var get$3 = function(element, key2) {
var v2 = element.dom.getAttribute(key2);
return v2 === null ? void 0 : v2;
};
var remove3 = function(element, key2) {
element.dom.removeAttribute(key2);
};
var internalSet = function(dom, property2, value25) {
if (!isString3(value25)) {
console.error("Invalid call to CSS.set. Property ", property2, ":: Value ", value25, ":: Element ", dom);
throw new Error("CSS value must be a string: " + value25);
}
if (isSupported$1(dom)) {
dom.style.setProperty(property2, value25);
}
};
var setAll = function(element, css2) {
var dom = element.dom;
each2(css2, function(v2, k2) {
internalSet(dom, k2, v2);
});
};
var get$22 = function(element, property2) {
var dom = element.dom;
var styles = window.getComputedStyle(dom);
var r3 = styles.getPropertyValue(property2);
return r3 === "" && !inBody(element) ? getUnsafeProperty(dom, property2) : r3;
};
var getUnsafeProperty = function(dom, property2) {
return isSupported$1(dom) ? dom.style.getPropertyValue(property2) : "";
};
var mkEvent = function(target, x2, y2, stop2, prevent, kill, raw) {
return {
target,
x: x2,
y: y2,
stop: stop2,
prevent,
kill,
raw
};
};
var fromRawEvent = function(rawEvent) {
var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
var stop2 = function() {
return rawEvent.stopPropagation();
};
var prevent = function() {
return rawEvent.preventDefault();
};
var kill = compose(prevent, stop2);
return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop2, prevent, kill, rawEvent);
};
var handle = function(filter2, handler7) {
return function(rawEvent) {
if (filter2(rawEvent)) {
handler7(fromRawEvent(rawEvent));
}
};
};
var binder = function(element, event, filter2, handler7, useCapture) {
var wrapped = handle(filter2, handler7);
element.dom.addEventListener(event, wrapped, useCapture);
return { unbind: curry(unbind, element, event, wrapped, useCapture) };
};
var bind$22 = function(element, event, filter2, handler7) {
return binder(element, event, filter2, handler7, false);
};
var unbind = function(element, event, handler7, useCapture) {
element.dom.removeEventListener(event, handler7, useCapture);
};
var filter = always;
var bind$12 = function(element, event, handler7) {
return bind$22(element, event, filter, handler7);
};
var r2 = function(left, top) {
var translate = function(x2, y2) {
return r2(left + x2, top + y2);
};
return {
left,
top,
translate
};
};
var SugarPosition = r2;
var get$12 = function(_DOC) {
var doc = _DOC !== void 0 ? _DOC.dom : document;
var x2 = doc.body.scrollLeft || doc.documentElement.scrollLeft;
var y2 = doc.body.scrollTop || doc.documentElement.scrollTop;
return SugarPosition(x2, y2);
};
var get2 = function(_win) {
var win = _win === void 0 ? window : _win;
if (detect().browser.isFirefox()) {
return Optional.none();
} else {
return Optional.from(win["visualViewport"]);
}
};
var bounds = function(x2, y2, width, height) {
return {
x: x2,
y: y2,
width,
height,
right: x2 + width,
bottom: y2 + height
};
};
var getBounds = function(_win) {
var win = _win === void 0 ? window : _win;
var doc = win.document;
var scroll = get$12(SugarElement.fromDom(doc));
return get2(win).fold(function() {
var html = win.document.documentElement;
var width = html.clientWidth;
var height = html.clientHeight;
return bounds(scroll.left, scroll.top, width, height);
}, function(visualViewport) {
return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
});
};
var bind4 = function(name, callback2, _win) {
return get2(_win).map(function(visualViewport) {
var handler7 = function(e2) {
return callback2(fromRawEvent(e2));
};
visualViewport.addEventListener(name, handler7);
return {
unbind: function() {
return visualViewport.removeEventListener(name, handler7);
}
};
}).getOrThunk(function() {
return { unbind: noop2 };
});
};
var global$2 = tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");
var global$12 = tinymce.util.Tools.resolve("tinymce.Env");
var global2 = tinymce.util.Tools.resolve("tinymce.util.Delay");
var fireFullscreenStateChanged = function(editor, state) {
editor.fire("FullscreenStateChanged", { state });
editor.fire("ResizeEditor");
};
var getFullscreenNative = function(editor) {
return editor.getParam("fullscreen_native", false, "boolean");
};
var getFullscreenRoot = function(editor) {
var elem = SugarElement.fromDom(editor.getElement());
return getShadowRoot(elem).map(getShadowHost).getOrThunk(function() {
return getBody2(owner(elem));
});
};
var getFullscreenElement = function(root2) {
if (root2.fullscreenElement !== void 0) {
return root2.fullscreenElement;
} else if (root2.msFullscreenElement !== void 0) {
return root2.msFullscreenElement;
} else if (root2.webkitFullscreenElement !== void 0) {
return root2.webkitFullscreenElement;
} else {
return null;
}
};
var getFullscreenchangeEventName = function() {
if (document.fullscreenElement !== void 0) {
return "fullscreenchange";
} else if (document.msFullscreenElement !== void 0) {
return "MSFullscreenChange";
} else if (document.webkitFullscreenElement !== void 0) {
return "webkitfullscreenchange";
} else {
return "fullscreenchange";
}
};
var requestFullscreen = function(sugarElem) {
var elem = sugarElem.dom;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.webkitRequestFullScreen) {
elem.webkitRequestFullScreen();
}
};
var exitFullscreen = function(sugarDoc) {
var doc = sugarDoc.dom;
if (doc.exitFullscreen) {
doc.exitFullscreen();
} else if (doc.msExitFullscreen) {
doc.msExitFullscreen();
} else if (doc.webkitCancelFullScreen) {
doc.webkitCancelFullScreen();
}
};
var isFullscreenElement = function(elem) {
return elem.dom === getFullscreenElement(owner(elem).dom);
};
var ancestors$1 = function(scope, predicate, isRoot) {
return filter$1(parents(scope, isRoot), predicate);
};
var siblings$1 = function(scope, predicate) {
return filter$1(siblings$2(scope), predicate);
};
var all2 = function(selector2) {
return all$1(selector2);
};
var ancestors = function(scope, selector2, isRoot) {
return ancestors$1(scope, function(e2) {
return is2(e2, selector2);
}, isRoot);
};
var siblings = function(scope, selector2) {
return siblings$1(scope, function(e2) {
return is2(e2, selector2);
});
};
var attr = "data-ephox-mobile-fullscreen-style";
var siblingStyles = "display:none!important;";
var ancestorPosition = "position:absolute!important;";
var ancestorStyles = "top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;";
var bgFallback = "background-color:rgb(255,255,255)!important;";
var isAndroid = global$12.os.isAndroid();
var matchColor = function(editorBody) {
var color = get$22(editorBody, "background-color");
return color !== void 0 && color !== "" ? "background-color:" + color + "!important" : bgFallback;
};
var clobberStyles = function(dom, container, editorBody) {
var gatherSiblings = function(element) {
return siblings(element, "*:not(.tox-silver-sink)");
};
var clobber = function(clobberStyle) {
return function(element) {
var styles = get$3(element, "style");
var backup = styles === void 0 ? "no-styles" : styles.trim();
if (backup === clobberStyle) {
return;
} else {
set2(element, attr, backup);
setAll(element, dom.parseStyle(clobberStyle));
}
};
};
var ancestors$12 = ancestors(container, "*");
var siblings$12 = bind$32(ancestors$12, gatherSiblings);
var bgColor = matchColor(editorBody);
each$12(siblings$12, clobber(siblingStyles));
each$12(ancestors$12, clobber(ancestorPosition + ancestorStyles + bgColor));
var containerStyles = isAndroid === true ? "" : ancestorPosition;
clobber(containerStyles + ancestorStyles + bgColor)(container);
};
var restoreStyles = function(dom) {
var clobberedEls = all2("[" + attr + "]");
each$12(clobberedEls, function(element) {
var restore = get$3(element, attr);
if (restore !== "no-styles") {
setAll(element, dom.parseStyle(restore));
} else {
remove3(element, "style");
}
remove3(element, attr);
});
};
var DOM = global$2.DOM;
var getScrollPos = function() {
return getBounds(window);
};
var setScrollPos = function(pos) {
return window.scrollTo(pos.x, pos.y);
};
var viewportUpdate = get2().fold(function() {
return {
bind: noop2,
unbind: noop2
};
}, function(visualViewport) {
var editorContainer = value24();
var resizeBinder = unbindable();
var scrollBinder = unbindable();
var refreshScroll = function() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
};
var refreshVisualViewport = function() {
window.requestAnimationFrame(function() {
editorContainer.on(function(container) {
return setAll(container, {
top: visualViewport.offsetTop + "px",
left: visualViewport.offsetLeft + "px",
height: visualViewport.height + "px",
width: visualViewport.width + "px"
});
});
});
};
var update = global2.throttle(function() {
refreshScroll();
refreshVisualViewport();
}, 50);
var bind$13 = function(element) {
editorContainer.set(element);
update();
resizeBinder.set(bind4("resize", update));
scrollBinder.set(bind4("scroll", update));
};
var unbind2 = function() {
editorContainer.on(function() {
resizeBinder.clear();
scrollBinder.clear();
});
editorContainer.clear();
};
return {
bind: bind$13,
unbind: unbind2
};
});
var toggleFullscreen = function(editor, fullscreenState) {
var body = document.body;
var documentElement = document.documentElement;
var editorContainer = editor.getContainer();
var editorContainerS = SugarElement.fromDom(editorContainer);
var fullscreenRoot = getFullscreenRoot(editor);
var fullscreenInfo = fullscreenState.get();
var editorBody = SugarElement.fromDom(editor.getBody());
var isTouch = global$12.deviceType.isTouch();
var editorContainerStyle = editorContainer.style;
var iframe = editor.iframeElement;
var iframeStyle = iframe.style;
var handleClasses = function(handler7) {
handler7(body, "tox-fullscreen");
handler7(documentElement, "tox-fullscreen");
handler7(editorContainer, "tox-fullscreen");
getShadowRoot(editorContainerS).map(function(root2) {
return getShadowHost(root2).dom;
}).each(function(host) {
handler7(host, "tox-fullscreen");
handler7(host, "tox-shadowhost");
});
};
var cleanup = function() {
if (isTouch) {
restoreStyles(editor.dom);
}
handleClasses(DOM.removeClass);
viewportUpdate.unbind();
Optional.from(fullscreenState.get()).each(function(info3) {
return info3.fullscreenChangeHandler.unbind();
});
};
if (!fullscreenInfo) {
var fullscreenChangeHandler = bind$12(owner(fullscreenRoot), getFullscreenchangeEventName(), function(_evt) {
if (getFullscreenNative(editor)) {
if (!isFullscreenElement(fullscreenRoot) && fullscreenState.get() !== null) {
toggleFullscreen(editor, fullscreenState);
}
}
});
var newFullScreenInfo = {
scrollPos: getScrollPos(),
containerWidth: editorContainerStyle.width,
containerHeight: editorContainerStyle.height,
containerTop: editorContainerStyle.top,
containerLeft: editorContainerStyle.left,
iframeWidth: iframeStyle.width,
iframeHeight: iframeStyle.height,
fullscreenChangeHandler
};
if (isTouch) {
clobberStyles(editor.dom, editorContainerS, editorBody);
}
iframeStyle.width = iframeStyle.height = "100%";
editorContainerStyle.width = editorContainerStyle.height = "";
handleClasses(DOM.addClass);
viewportUpdate.bind(editorContainerS);
editor.on("remove", cleanup);
fullscreenState.set(newFullScreenInfo);
if (getFullscreenNative(editor)) {
requestFullscreen(fullscreenRoot);
}
fireFullscreenStateChanged(editor, true);
} else {
fullscreenInfo.fullscreenChangeHandler.unbind();
if (getFullscreenNative(editor) && isFullscreenElement(fullscreenRoot)) {
exitFullscreen(owner(fullscreenRoot));
}
iframeStyle.width = fullscreenInfo.iframeWidth;
iframeStyle.height = fullscreenInfo.iframeHeight;
editorContainerStyle.width = fullscreenInfo.containerWidth;
editorContainerStyle.height = fullscreenInfo.containerHeight;
editorContainerStyle.top = fullscreenInfo.containerTop;
editorContainerStyle.left = fullscreenInfo.containerLeft;
cleanup();
setScrollPos(fullscreenInfo.scrollPos);
fullscreenState.set(null);
fireFullscreenStateChanged(editor, false);
editor.off("remove", cleanup);
}
};
var register$1 = function(editor, fullscreenState) {
editor.addCommand("mceFullScreen", function() {
toggleFullscreen(editor, fullscreenState);
});
};
var makeSetupHandler = function(editor, fullscreenState) {
return function(api2) {
api2.setActive(fullscreenState.get() !== null);
var editorEventCallback = function(e2) {
return api2.setActive(e2.state);
};
editor.on("FullscreenStateChanged", editorEventCallback);
return function() {
return editor.off("FullscreenStateChanged", editorEventCallback);
};
};
};
var register3 = function(editor, fullscreenState) {
var onAction = function() {
return editor.execCommand("mceFullScreen");
};
editor.ui.registry.addToggleMenuItem("fullscreen", {
text: "Fullscreen",
icon: "fullscreen",
shortcut: "Meta+Shift+F",
onAction,
onSetup: makeSetupHandler(editor, fullscreenState)
});
editor.ui.registry.addToggleButton("fullscreen", {
tooltip: "Fullscreen",
icon: "fullscreen",
onAction,
onSetup: makeSetupHandler(editor, fullscreenState)
});
};
function Plugin() {
global$3.add("fullscreen", function(editor) {
var fullscreenState = Cell3(null);
if (editor.inline) {
return get$5(fullscreenState);
}
register$1(editor, fullscreenState);
register3(editor, fullscreenState);
editor.addShortcut("Meta+Shift+F", "", "mceFullScreen");
return get$5(fullscreenState);
});
}
Plugin();
})();
(function() {
var global2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
var register$1 = function(editor) {
editor.addCommand("InsertHorizontalRule", function() {
editor.execCommand("mceInsertContent", false, "