');
});
global$c.each(handles, function (handle) {
global$e('#' + id, containerElm).append('
');
});
dragHelpers = global$c.map(handles, createDragHelper);
repaint(currentRect);
global$e(containerElm).on('focusin focusout', function (e) {
global$e(e.target).attr('aria-grabbed', e.type === 'focus' ? 'true' : 'false');
});
global$e(containerElm).on('keydown', function (e) {
var activeHandle;
global$c.each(handles, function (handle) {
if (e.target.id === id + '-' + handle.name) {
activeHandle = handle;
return false;
}
});
var moveAndBlock = function (evt, handle, startRect, deltaX, deltaY) {
evt.stopPropagation();
evt.preventDefault();
moveRect(activeHandle, startRect, deltaX, deltaY);
};
switch (e.keyCode) {
case global$g.LEFT:
moveAndBlock(e, activeHandle, currentRect, -10, 0);
break;
case global$g.RIGHT:
moveAndBlock(e, activeHandle, currentRect, 10, 0);
break;
case global$g.UP:
moveAndBlock(e, activeHandle, currentRect, 0, -10);
break;
case global$g.DOWN:
moveAndBlock(e, activeHandle, currentRect, 0, 10);
break;
case global$g.ENTER:
case global$g.SPACEBAR:
e.preventDefault();
action();
break;
}
});
};
var toggleVisibility = function (state) {
var selectors = global$c.map(handles, function (handle) {
return '#' + id + '-' + handle.name;
}).concat(global$c.map(blockers, function (blocker) {
return '#' + id + '-' + blocker;
})).join(',');
if (state) {
global$e(selectors, containerElm).show();
} else {
global$e(selectors, containerElm).hide();
}
};
var repaint = function (rect) {
var updateElementRect = function (name, rect) {
if (rect.h < 0) {
rect.h = 0;
}
if (rect.w < 0) {
rect.w = 0;
}
global$e('#' + id + '-' + name, containerElm).css({
left: rect.x,
top: rect.y,
width: rect.w,
height: rect.h
});
};
global$c.each(handles, function (handle) {
global$e('#' + id + '-' + handle.name, containerElm).css({
left: rect.w * handle.xMul + rect.x,
top: rect.h * handle.yMul + rect.y
});
});
updateElementRect('top', {
x: viewPortRect.x,
y: viewPortRect.y,
w: viewPortRect.w,
h: rect.y - viewPortRect.y
});
updateElementRect('right', {
x: rect.x + rect.w,
y: rect.y,
w: viewPortRect.w - rect.x - rect.w + viewPortRect.x,
h: rect.h
});
updateElementRect('bottom', {
x: viewPortRect.x,
y: rect.y + rect.h,
w: viewPortRect.w,
h: viewPortRect.h - rect.y - rect.h + viewPortRect.y
});
updateElementRect('left', {
x: viewPortRect.x,
y: rect.y,
w: rect.x - viewPortRect.x,
h: rect.h
});
updateElementRect('move', rect);
};
var setRect = function (rect) {
currentRect = rect;
repaint(currentRect);
};
var setViewPortRect = function (rect) {
viewPortRect = rect;
repaint(currentRect);
};
var setInnerRect = function (rect) {
setRect(getAbsoluteRect(clampRect, rect));
};
var setClampRect = function (rect) {
clampRect = rect;
repaint(currentRect);
};
var destroy = function () {
global$c.each(dragHelpers, function (helper) {
helper.destroy();
});
dragHelpers = [];
};
render();
var instance = global$c.extend({
toggleVisibility: toggleVisibility,
setClampRect: setClampRect,
setRect: setRect,
getInnerRect: getInnerRect,
setInnerRect: setInnerRect,
setViewPortRect: setViewPortRect,
destroy: destroy
}, global$f);
return instance;
};
var CropRect = { create: create$7 };
var loadImage = function (image) {
return new global$4(function (resolve) {
var loaded = function () {
image.removeEventListener('load', loaded);
resolve(image);
};
if (image.complete) {
resolve(image);
} else {
image.addEventListener('load', loaded);
}
});
};
var renderImagePanel = function (initialUrl) {
var memBg = record({
dom: {
tag: 'div',
classes: ['tox-image-tools__image-bg'],
attributes: { role: 'presentation' }
}
});
var zoomState = Cell(1);
var cropRect = Cell(Optional.none());
var rectState = Cell({
x: 0,
y: 0,
w: 1,
h: 1
});
var viewRectState = Cell({
x: 0,
y: 0,
w: 1,
h: 1
});
var repaintImg = function (anyInSystem, img) {
memContainer.getOpt(anyInSystem).each(function (panel) {
var zoom = zoomState.get();
var panelW = get$8(panel.element);
var panelH = get$7(panel.element);
var width = img.dom.naturalWidth * zoom;
var height = img.dom.naturalHeight * zoom;
var left = Math.max(0, panelW / 2 - width / 2);
var top = Math.max(0, panelH / 2 - height / 2);
var css = {
left: left.toString() + 'px',
top: top.toString() + 'px',
width: width.toString() + 'px',
height: height.toString() + 'px',
position: 'absolute'
};
setAll$1(img, css);
memBg.getOpt(panel).each(function (bg) {
setAll$1(bg.element, css);
});
cropRect.get().each(function (cRect) {
var rect = rectState.get();
cRect.setRect({
x: rect.x * zoom + left,
y: rect.y * zoom + top,
w: rect.w * zoom,
h: rect.h * zoom
});
cRect.setClampRect({
x: left,
y: top,
w: width,
h: height
});
cRect.setViewPortRect({
x: 0,
y: 0,
w: panelW,
h: panelH
});
});
});
};
var zoomFit = function (anyInSystem, img) {
memContainer.getOpt(anyInSystem).each(function (panel) {
var panelW = get$8(panel.element);
var panelH = get$7(panel.element);
var width = img.dom.naturalWidth;
var height = img.dom.naturalHeight;
var zoom = Math.min(panelW / width, panelH / height);
if (zoom >= 1) {
zoomState.set(1);
} else {
zoomState.set(zoom);
}
});
};
var updateSrc = function (anyInSystem, url) {
var img = SugarElement.fromTag('img');
set$1(img, 'src', url);
return loadImage(img.dom).then(function () {
return memContainer.getOpt(anyInSystem).map(function (panel) {
var aImg = external({ element: img });
Replacing.replaceAt(panel, 1, Optional.some(aImg));
var lastViewRect = viewRectState.get();
var viewRect = {
x: 0,
y: 0,
w: img.dom.naturalWidth,
h: img.dom.naturalHeight
};
viewRectState.set(viewRect);
var rect = global$d.inflate(viewRect, -20, -20);
rectState.set(rect);
if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) {
zoomFit(panel, img);
}
repaintImg(panel, img);
return img;
});
});
};
var zoom = function (anyInSystem, direction) {
var currentZoom = zoomState.get();
var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1);
zoomState.set(newZoom);
memContainer.getOpt(anyInSystem).each(function (panel) {
var img = panel.components()[1].element;
repaintImg(panel, img);
});
};
var showCrop = function () {
cropRect.get().each(function (cRect) {
cRect.toggleVisibility(true);
});
};
var hideCrop = function () {
cropRect.get().each(function (cRect) {
cRect.toggleVisibility(false);
});
};
var getRect = function () {
return rectState.get();
};
var container = Container.sketch({
dom: {
tag: 'div',
classes: ['tox-image-tools__image']
},
components: [
memBg.asSpec(),
{
dom: {
tag: 'img',
attributes: { src: initialUrl }
}
},
{
dom: { tag: 'div' },
behaviours: derive$1([config('image-panel-crop-events', [runOnAttached(function (comp) {
memContainer.getOpt(comp).each(function (container) {
var el = container.element.dom;
var cRect = CropRect.create({
x: 10,
y: 10,
w: 100,
h: 100
}, {
x: 0,
y: 0,
w: 200,
h: 200
}, {
x: 0,
y: 0,
w: 200,
h: 200
}, el, noop);
cRect.toggleVisibility(false);
cRect.on('updateRect', function (e) {
var rect = e.rect;
var zoom = zoomState.get();
var newRect = {
x: Math.round(rect.x / zoom),
y: Math.round(rect.y / zoom),
w: Math.round(rect.w / zoom),
h: Math.round(rect.h / zoom)
};
rectState.set(newRect);
});
cropRect.set(Optional.some(cRect));
});
})])])
}
],
containerBehaviours: derive$1([
Replacing.config({}),
config('image-panel-events', [runOnAttached(function (comp) {
updateSrc(comp, initialUrl);
})])
])
});
var memContainer = record(container);
var getMeasurements = function () {
var viewRect = viewRectState.get();
return {
width: viewRect.w,
height: viewRect.h
};
};
return {
memContainer: memContainer,
updateSrc: updateSrc,
zoom: zoom,
showCrop: showCrop,
hideCrop: hideCrop,
getRect: getRect,
getMeasurements: getMeasurements
};
};
var createButton = function (innerHtml, icon, disabled, action, providersBackstage) {
return renderIconButton({
name: innerHtml,
icon: Optional.some(icon),
disabled: disabled,
tooltip: Optional.some(innerHtml),
primary: false,
borderless: false
}, action, providersBackstage);
};
var setButtonEnabled = function (button, enabled) {
if (enabled) {
Disabling.enable(button);
} else {
Disabling.disable(button);
}
};
var renderSideBar = function (providersBackstage) {
var updateButtonUndoStates = function (anyInSystem, undoEnabled, redoEnabled) {
memUndo.getOpt(anyInSystem).each(function (undo) {
setButtonEnabled(undo, undoEnabled);
});
memRedo.getOpt(anyInSystem).each(function (redo) {
setButtonEnabled(redo, redoEnabled);
});
};
var memUndo = record(createButton('Undo', 'undo', true, function (button) {
emitWith(button, internal.undo(), { direction: 1 });
}, providersBackstage));
var memRedo = record(createButton('Redo', 'redo', true, function (button) {
emitWith(button, internal.redo(), { direction: 1 });
}, providersBackstage));
var container = Container.sketch({
dom: {
tag: 'div',
classes: [
'tox-image-tools__toolbar',
'tox-image-tools__sidebar'
]
},
components: [
memUndo.asSpec(),
memRedo.asSpec(),
createButton('Zoom in', 'zoom-in', false, function (button) {
emitWith(button, internal.zoom(), { direction: 1 });
}, providersBackstage),
createButton('Zoom out', 'zoom-out', false, function (button) {
emitWith(button, internal.zoom(), { direction: -1 });
}, providersBackstage)
]
});
return {
container: container,
updateButtonUndoStates: updateButtonUndoStates
};
};
function UndoStack () {
var data = [];
var index = -1;
var add = function (state) {
var removed = data.splice(++index);
data.push(state);
return {
state: state,
removed: removed
};
};
var undo = function () {
if (canUndo()) {
return data[--index];
}
};
var redo = function () {
if (canRedo()) {
return data[++index];
}
};
var canUndo = function () {
return index > 0;
};
var canRedo = function () {
return index !== -1 && index < data.length - 1;
};
return {
data: data,
add: add,
undo: undo,
redo: redo,
canUndo: canUndo,
canRedo: canRedo
};
}
var makeState = function (initialState) {
var blobState = Cell(initialState);
var tempState = Cell(Optional.none());
var undoStack = UndoStack();
undoStack.add(initialState);
var getBlobState = function () {
return blobState.get();
};
var setBlobState = function (state) {
blobState.set(state);
};
var getTempState = function () {
return tempState.get().fold(function () {
return blobState.get();
}, function (temp) {
return temp;
});
};
var updateTempState = function (blob) {
var newTempState = createState(blob);
destroyTempState();
tempState.set(Optional.some(newTempState));
return newTempState.url;
};
var createState = function (blob) {
return {
blob: blob,
url: URL.createObjectURL(blob)
};
};
var destroyState = function (state) {
URL.revokeObjectURL(state.url);
};
var destroyStates = function (states) {
global$c.each(states, destroyState);
};
var destroyTempState = function () {
tempState.get().each(destroyState);
tempState.set(Optional.none());
};
var addBlobState = function (blob) {
var newState = createState(blob);
setBlobState(newState);
var removed = undoStack.add(newState).removed;
destroyStates(removed);
return newState.url;
};
var addTempState = function (blob) {
var newState = createState(blob);
tempState.set(Optional.some(newState));
return newState.url;
};
var applyTempState = function (postApply) {
return tempState.get().fold(noop, function (temp) {
addBlobState(temp.blob);
postApply();
});
};
var undo = function () {
var currentState = undoStack.undo();
setBlobState(currentState);
return currentState.url;
};
var redo = function () {
var currentState = undoStack.redo();
setBlobState(currentState);
return currentState.url;
};
var getHistoryStates = function () {
var undoEnabled = undoStack.canUndo();
var redoEnabled = undoStack.canRedo();
return {
undoEnabled: undoEnabled,
redoEnabled: redoEnabled
};
};
return {
getBlobState: getBlobState,
setBlobState: setBlobState,
addBlobState: addBlobState,
getTempState: getTempState,
updateTempState: updateTempState,
addTempState: addTempState,
applyTempState: applyTempState,
destroyTempState: destroyTempState,
undo: undo,
redo: redo,
getHistoryStates: getHistoryStates
};
};
var renderImageTools = function (detail, providersBackstage) {
var state = makeState(detail.currentState);
var zoom = function (anyInSystem, simulatedEvent) {
var direction = simulatedEvent.event.direction;
imagePanel.zoom(anyInSystem, direction);
};
var updateButtonUndoStates = function (anyInSystem) {
var historyStates = state.getHistoryStates();
sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled);
emitWith(anyInSystem, external$2.formActionEvent, {
name: external$2.saveState(),
value: historyStates.undoEnabled
});
};
var disableUndoRedo = function (anyInSystem) {
sideBar.updateButtonUndoStates(anyInSystem, false, false);
};
var undo = function (anyInSystem, _simulatedEvent) {
var url = state.undo();
updateSrc(anyInSystem, url).then(function (_oImg) {
unblock(anyInSystem);
updateButtonUndoStates(anyInSystem);
});
};
var redo = function (anyInSystem, _simulatedEvent) {
var url = state.redo();
updateSrc(anyInSystem, url).then(function (_oImg) {
unblock(anyInSystem);
updateButtonUndoStates(anyInSystem);
});
};
var imageResultToBlob = function (ir) {
return ir.toBlob();
};
var block = function (anyInSystem) {
emitWith(anyInSystem, external$2.formActionEvent, {
name: external$2.disable(),
value: {}
});
};
var unblock = function (anyInSystem) {
editPanel.getApplyButton(anyInSystem).each(function (applyButton) {
Disabling.enable(applyButton);
});
emitWith(anyInSystem, external$2.formActionEvent, {
name: external$2.enable(),
value: {}
});
};
var updateSrc = function (anyInSystem, src) {
block(anyInSystem);
return imagePanel.updateSrc(anyInSystem, src);
};
var blobManipulate = function (anyInSystem, blob, filter, action, swap) {
block(anyInSystem);
return blobToImageResult(blob).then(filter).then(imageResultToBlob).then(action).then(function (url) {
return updateSrc(anyInSystem, url).then(function (oImg) {
updateButtonUndoStates(anyInSystem);
swap();
unblock(anyInSystem);
return oImg;
});
}).catch(function (err) {
console.log(err);
unblock(anyInSystem);
return err;
});
};
var manipulate = function (anyInSystem, filter, swap) {
var blob = state.getBlobState().blob;
var action = function (blob) {
return state.updateTempState(blob);
};
blobManipulate(anyInSystem, blob, filter, action, swap);
};
var tempManipulate = function (anyInSystem, filter) {
var blob = state.getTempState().blob;
var action = function (blob) {
return state.addTempState(blob);
};
blobManipulate(anyInSystem, blob, filter, action, noop);
};
var manipulateApply = function (anyInSystem, filter, swap) {
var blob = state.getBlobState().blob;
var action = function (blob) {
var url = state.addBlobState(blob);
destroyTempState(anyInSystem);
return url;
};
blobManipulate(anyInSystem, blob, filter, action, swap);
};
var apply = function (anyInSystem, simulatedEvent) {
var postApply = function () {
destroyTempState(anyInSystem);
var swap = simulatedEvent.event.swap;
swap();
};
state.applyTempState(postApply);
};
var destroyTempState = function (anyInSystem) {
var currentUrl = state.getBlobState().url;
state.destroyTempState();
updateButtonUndoStates(anyInSystem);
return currentUrl;
};
var cancel = function (anyInSystem) {
var currentUrl = destroyTempState(anyInSystem);
updateSrc(anyInSystem, currentUrl).then(function (_oImg) {
unblock(anyInSystem);
});
};
var back = function (anyInSystem, simulatedEvent) {
cancel(anyInSystem);
var swap = simulatedEvent.event.swap;
swap();
imagePanel.hideCrop();
};
var transform = function (anyInSystem, simulatedEvent) {
return manipulate(anyInSystem, simulatedEvent.event.transform, noop);
};
var tempTransform = function (anyInSystem, simulatedEvent) {
return tempManipulate(anyInSystem, simulatedEvent.event.transform);
};
var transformApply = function (anyInSystem, simulatedEvent) {
return manipulateApply(anyInSystem, simulatedEvent.event.transform, simulatedEvent.event.swap);
};
var imagePanel = renderImagePanel(detail.currentState.url);
var sideBar = renderSideBar(providersBackstage);
var editPanel = renderEditPanel(imagePanel, providersBackstage);
var swap = function (anyInSystem, simulatedEvent) {
disableUndoRedo(anyInSystem);
var transform = simulatedEvent.event.transform;
var swap = simulatedEvent.event.swap;
transform.fold(function () {
swap();
}, function (transform) {
manipulate(anyInSystem, transform, swap);
});
};
return {
dom: {
tag: 'div',
attributes: { role: 'presentation' }
},
components: [
editPanel.memContainer.asSpec(),
imagePanel.memContainer.asSpec(),
sideBar.container
],
behaviours: derive$1([
Representing.config({
store: {
mode: 'manual',
getValue: function () {
return state.getBlobState();
}
}
}),
config('image-tools-events', [
run(internal.undo(), undo),
run(internal.redo(), redo),
run(internal.zoom(), zoom),
run(internal.back(), back),
run(internal.apply(), apply),
run(internal.transform(), transform),
run(internal.tempTransform(), tempTransform),
run(internal.transformApply(), transformApply),
run(internal.swap(), swap)
]),
ComposingConfigs.self()
])
};
};
var renderLabel$2 = function (spec, backstageShared) {
var label = {
dom: {
tag: 'label',
innerHtml: backstageShared.providers.translate(spec.label),
classes: ['tox-label']
}
};
var comps = map(spec.items, backstageShared.interpreter);
return {
dom: {
tag: 'div',
classes: ['tox-form__group']
},
components: [label].concat(comps),
behaviours: derive$1([
ComposingConfigs.self(),
Replacing.config({}),
RepresentingConfigs.domHtml(Optional.none()),
Keying.config({ mode: 'acyclic' })
])
};
};
var isSingleListItem = function (item) {
return !has(item, 'items');
};
var dataAttribute = 'data-value';
var fetchItems = function (dropdownComp, name, items, selectedValue) {
return map(items, function (item) {
if (!isSingleListItem(item)) {
return {
type: 'nestedmenuitem',
text: item.text,
getSubmenuItems: function () {
return fetchItems(dropdownComp, name, item.items, selectedValue);
}
};
} else {
return {
type: 'togglemenuitem',
text: item.text,
value: item.value,
active: item.value === selectedValue,
onAction: function () {
Representing.setValue(dropdownComp, item.value);
emitWith(dropdownComp, formChangeEvent, { name: name });
Focusing.focus(dropdownComp);
}
};
}
});
};
var findItemByValue = function (items, value) {
return findMap(items, function (item) {
if (!isSingleListItem(item)) {
return findItemByValue(item.items, value);
} else {
return someIf(item.value === value, item);
}
});
};
var renderListBox = function (spec, backstage) {
var providersBackstage = backstage.shared.providers;
var initialItem = head(spec.items).filter(isSingleListItem);
var pLabel = spec.label.map(function (label) {
return renderLabel(label, providersBackstage);
});
var pField = FormField.parts.field({
dom: {},
factory: {
sketch: function (sketchSpec) {
return renderCommonDropdown({
uid: sketchSpec.uid,
text: initialItem.map(function (item) {
return item.text;
}),
icon: Optional.none(),
tooltip: spec.label,
role: Optional.none(),
fetch: function (comp, callback) {
var items = fetchItems(comp, spec.name, spec.items, Representing.getValue(comp));
callback(build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
},
onSetup: constant(noop),
getApi: constant({}),
columns: 1,
presets: 'normal',
classes: [],
dropdownBehaviours: [
Tabstopping.config({}),
Representing.config({
store: {
mode: 'manual',
initialValue: initialItem.map(function (item) {
return item.value;
}).getOr(''),
getValue: function (comp) {
return get$3(comp.element, dataAttribute);
},
setValue: function (comp, data) {
findItemByValue(spec.items, data).each(function (item) {
set$1(comp.element, dataAttribute, item.value);
emitWith(comp, updateMenuText, { text: item.text });
});
}
}
})
]
}, 'tox-listbox', backstage.shared);
}
}
});
var listBoxWrap = {
dom: {
tag: 'div',
classes: ['tox-listboxfield']
},
components: [pField]
};
return FormField.sketch({
dom: {
tag: 'div',
classes: ['tox-form__group']
},
components: flatten([
pLabel.toArray(),
[listBoxWrap]
]),
fieldBehaviours: derive$1([Disabling.config({
disabled: constant(spec.disabled),
onDisabled: function (comp) {
FormField.getField(comp).each(Disabling.disable);
},
onEnabled: function (comp) {
FormField.getField(comp).each(Disabling.enable);
}
})])
});
};
var renderPanel = function (spec, backstage) {
return {
dom: {
tag: 'div',
classes: spec.classes
},
components: map(spec.items, backstage.shared.interpreter)
};
};
var factory$8 = function (detail, _spec) {
var options = map(detail.options, function (option) {
return {
dom: {
tag: 'option',
value: option.value,
innerHtml: option.text
}
};
});
var initialValues = detail.data.map(function (v) {
return wrap$1('initialValue', v);
}).getOr({});
return {
uid: detail.uid,
dom: {
tag: 'select',
classes: detail.selectClasses,
attributes: detail.selectAttributes
},
components: options,
behaviours: augment(detail.selectBehaviours, [
Focusing.config({}),
Representing.config({
store: __assign({
mode: 'manual',
getValue: function (select) {
return get$6(select.element);
},
setValue: function (select, newValue) {
var found = find(detail.options, function (opt) {
return opt.value === newValue;
});
if (found.isSome()) {
set$3(select.element, newValue);
}
}
}, initialValues)
})
])
};
};
var HtmlSelect = single$2({
name: 'HtmlSelect',
configFields: [
strict$1('options'),
field$1('selectBehaviours', [
Focusing,
Representing
]),
defaulted$1('selectClasses', []),
defaulted$1('selectAttributes', {}),
option('data')
],
factory: factory$8
});
var renderSelectBox = function (spec, providersBackstage) {
var translatedOptions = map(spec.items, function (item) {
return {
text: providersBackstage.translate(item.text),
value: item.value
};
});
var pLabel = spec.label.map(function (label) {
return renderLabel(label, providersBackstage);
});
var pField = FormField.parts.field({
dom: {},
selectAttributes: { size: spec.size },
options: translatedOptions,
factory: HtmlSelect,
selectBehaviours: derive$1([
Disabling.config({
disabled: function () {
return spec.disabled || providersBackstage.isDisabled();
}
}),
Tabstopping.config({}),
config('selectbox-change', [run(change(), function (component, _) {
emitWith(component, formChangeEvent, { name: spec.name });
})])
])
});
var chevron = spec.size > 1 ? Optional.none() : Optional.some({
dom: {
tag: 'div',
classes: ['tox-selectfield__icon-js'],
innerHtml: get$e('chevron-down', providersBackstage.icons)
}
});
var selectWrap = {
dom: {
tag: 'div',
classes: ['tox-selectfield']
},
components: flatten([
[pField],
chevron.toArray()
])
};
return FormField.sketch({
dom: {
tag: 'div',
classes: ['tox-form__group']
},
components: flatten([
pLabel.toArray(),
[selectWrap]
]),
fieldBehaviours: derive$1([
Disabling.config({
disabled: function () {
return spec.disabled || providersBackstage.isDisabled();
},
onDisabled: function (comp) {
FormField.getField(comp).each(Disabling.disable);
},
onEnabled: function (comp) {
FormField.getField(comp).each(Disabling.enable);
}
}),
receivingConfig()
])
});
};
var renderTable = function (spec, providersBackstage) {
var renderTh = function (text) {
return {
dom: {
tag: 'th',
innerHtml: providersBackstage.translate(text)
}
};
};
var renderHeader = function (header) {
return {
dom: { tag: 'thead' },
components: [{
dom: { tag: 'tr' },
components: map(header, renderTh)
}]
};
};
var renderTd = function (text) {
return {
dom: {
tag: 'td',
innerHtml: providersBackstage.translate(text)
}
};
};
var renderTr = function (row) {
return {
dom: { tag: 'tr' },
components: map(row, renderTd)
};
};
var renderRows = function (rows) {
return {
dom: { tag: 'tbody' },
components: map(rows, renderTr)
};
};
return {
dom: {
tag: 'table',
classes: ['tox-dialog__table']
},
components: [
renderHeader(spec.header),
renderRows(spec.cells)
],
behaviours: derive$1([
Tabstopping.config({}),
Focusing.config({})
])
};
};
var renderTextField = function (spec, providersBackstage) {
var pLabel = spec.label.map(function (label) {
return renderLabel(label, providersBackstage);
});
var baseInputBehaviours = [
Disabling.config({
disabled: function () {
return spec.disabled || providersBackstage.isDisabled();
}
}),
receivingConfig(),
Keying.config({
mode: 'execution',
useEnter: spec.multiline !== true,
useControlEnter: spec.multiline === true,
execute: function (comp) {
emit(comp, formSubmitEvent);
return Optional.some(true);
}
}),
config('textfield-change', [
run(input(), function (component, _) {
emitWith(component, formChangeEvent, { name: spec.name });
}),
run(postPaste(), function (component, _) {
emitWith(component, formChangeEvent, { name: spec.name });
})
]),
Tabstopping.config({})
];
var validatingBehaviours = spec.validation.map(function (vl) {
return Invalidating.config({
getRoot: function (input) {
return parent(input.element);
},
invalidClass: 'tox-invalid',
validator: {
validate: function (input) {
var v = Representing.getValue(input);
var result = vl.validator(v);
return Future.pure(result === true ? Result.value(v) : Result.error(result));
},
validateOnLoad: vl.validateOnLoad
}
});
}).toArray();
var placeholder = spec.placeholder.fold(constant({}), function (p) {
return { placeholder: providersBackstage.translate(p) };
});
var inputMode = spec.inputMode.fold(constant({}), function (mode) {
return { inputmode: mode };
});
var inputAttributes = __assign(__assign({}, placeholder), inputMode);
var pField = FormField.parts.field({
tag: spec.multiline === true ? 'textarea' : 'input',
inputAttributes: inputAttributes,
inputClasses: [spec.classname],
inputBehaviours: derive$1(flatten([
baseInputBehaviours,
validatingBehaviours
])),
selectOnFocus: false,
factory: Input
});
var extraClasses = spec.flex ? ['tox-form__group--stretched'] : [];
var extraClasses2 = extraClasses.concat(spec.maximized ? ['tox-form-group--maximize'] : []);
var extraBehaviours = [
Disabling.config({
disabled: function () {
return spec.disabled || providersBackstage.isDisabled();
},
onDisabled: function (comp) {
FormField.getField(comp).each(Disabling.disable);
},
onEnabled: function (comp) {
FormField.getField(comp).each(Disabling.enable);
}
}),
receivingConfig()
];
return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
};
var renderInput = function (spec, providersBackstage) {
return renderTextField({
name: spec.name,
multiline: false,
label: spec.label,
inputMode: spec.inputMode,
placeholder: spec.placeholder,
flex: false,
disabled: spec.disabled,
classname: 'tox-textfield',
validation: Optional.none(),
maximized: spec.maximized
}, providersBackstage);
};
var renderTextarea = function (spec, providersBackstage) {
return renderTextField({
name: spec.name,
multiline: true,
label: spec.label,
inputMode: Optional.none(),
placeholder: spec.placeholder,
flex: true,
disabled: spec.disabled,
classname: 'tox-textarea',
validation: Optional.none(),
maximized: spec.maximized
}, providersBackstage);
};
var events$c = function (streamConfig, streamState) {
var streams = streamConfig.stream.streams;
var processor = streams.setup(streamConfig, streamState);
return derive([
run(streamConfig.event, processor),
runOnDetached(function () {
return streamState.cancel();
})
].concat(streamConfig.cancelEvent.map(function (e) {
return [run(e, function () {
return streamState.cancel();
})];
}).getOr([])));
};
var ActiveStreaming = /*#__PURE__*/Object.freeze({
__proto__: null,
events: events$c
});
var throttle = function (_config) {
var state = Cell(null);
var readState = function () {
return { timer: state.get() !== null ? 'set' : 'unset' };
};
var setTimer = function (t) {
state.set(t);
};
var cancel = function () {
var t = state.get();
if (t !== null) {
t.cancel();
}
};
return nu$5({
readState: readState,
setTimer: setTimer,
cancel: cancel
});
};
var init$6 = function (spec) {
return spec.stream.streams.state(spec);
};
var StreamingState = /*#__PURE__*/Object.freeze({
__proto__: null,
throttle: throttle,
init: init$6
});
var setup$2 = function (streamInfo, streamState) {
var sInfo = streamInfo.stream;
var throttler = last$2(streamInfo.onStream, sInfo.delay);
streamState.setTimer(throttler);
return function (component, simulatedEvent) {
throttler.throttle(component, simulatedEvent);
if (sInfo.stopEvent) {
simulatedEvent.stop();
}
};
};
var StreamingSchema = [
strictOf('stream', choose$1('mode', {
throttle: [
strict$1('delay'),
defaulted$1('stopEvent', true),
output('streams', {
setup: setup$2,
state: throttle
})
]
})),
defaulted$1('event', 'input'),
option('cancelEvent'),
onStrictHandler('onStream')
];
var Streaming = create$1({
fields: StreamingSchema,
name: 'streaming',
active: ActiveStreaming,
state: StreamingState
});
var setValueFromItem = function (model, input, item) {
var itemData = Representing.getValue(item);
Representing.setValue(input, itemData);
setCursorAtEnd(input);
};
var setSelectionOn = function (input, f) {
var el = input.element;
var value = get$6(el);
var node = el.dom;
if (get$3(el, 'type') !== 'number') {
f(node, value);
}
};
var setCursorAtEnd = function (input) {
setSelectionOn(input, function (node, value) {
return node.setSelectionRange(value.length, value.length);
});
};
var setSelectionToEnd = function (input, startOffset) {
setSelectionOn(input, function (node, value) {
return node.setSelectionRange(startOffset, value.length);
});
};
var attemptSelectOver = function (model, input, item) {
if (!model.selectsOver) {
return Optional.none();
} else {
var currentValue = Representing.getValue(input);
var inputDisplay_1 = model.getDisplayText(currentValue);
var itemValue = Representing.getValue(item);
var itemDisplay = model.getDisplayText(itemValue);
return itemDisplay.indexOf(inputDisplay_1) === 0 ? Optional.some(function () {
setValueFromItem(model, input, item);
setSelectionToEnd(input, inputDisplay_1.length);
}) : Optional.none();
}
};
var itemExecute = constant('alloy.typeahead.itemexecute');
var make$5 = function (detail, components, spec, externals) {
var navigateList = function (comp, simulatedEvent, highlighter) {
detail.previewing.set(false);
var sandbox = Coupling.getCoupled(comp, 'sandbox');
if (Sandboxing.isOpen(sandbox)) {
Composing.getCurrent(sandbox).each(function (menu) {
Highlighting.getHighlighted(menu).fold(function () {
highlighter(menu);
}, function () {
dispatchEvent(sandbox, menu.element, 'keydown', simulatedEvent);
});
});
} else {
var onOpenSync = function (sandbox) {
Composing.getCurrent(sandbox).each(highlighter);
};
open$1(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
}
};
var focusBehaviours$1 = focusBehaviours(detail);
var mapFetch = function (comp) {
return function (tdata) {
return tdata.map(function (data) {
var menus = values(data.menus);
var items = bind(menus, function (menu) {
return filter(menu.items, function (item) {
return item.type === 'item';
});
});
var repState = Representing.getState(comp);
repState.update(map(items, function (item) {
return item.data;
}));
return data;
});
};
};
var behaviours = [
Focusing.config({}),
Representing.config({
onSetValue: detail.onSetValue,
store: __assign({
mode: 'dataset',
getDataKey: function (comp) {
return get$6(comp.element);
},
getFallbackEntry: function (itemString) {
return {
value: itemString,
meta: {}
};
},
setValue: function (comp, data) {
set$3(comp.element, detail.model.getDisplayText(data));
}
}, detail.initialData.map(function (d) {
return wrap$1('initialValue', d);
}).getOr({}))
}),
Streaming.config({
stream: {
mode: 'throttle',
delay: detail.responseTime,
stopEvent: false
},
onStream: function (component, _simulatedEvent) {
var sandbox = Coupling.getCoupled(component, 'sandbox');
var focusInInput = Focusing.isFocused(component);
if (focusInInput) {
if (get$6(component.element).length >= detail.minChars) {
var previousValue_1 = Composing.getCurrent(sandbox).bind(function (menu) {
return Highlighting.getHighlighted(menu).map(Representing.getValue);
});
detail.previewing.set(true);
var onOpenSync = function (_sandbox) {
Composing.getCurrent(sandbox).each(function (menu) {
previousValue_1.fold(function () {
if (detail.model.selectsOver) {
Highlighting.highlightFirst(menu);
}
}, function (pv) {
Highlighting.highlightBy(menu, function (item) {
var itemData = Representing.getValue(item);
return itemData.value === pv.value;
});
Highlighting.getHighlighted(menu).orThunk(function () {
Highlighting.highlightFirst(menu);
return Optional.none();
});
});
});
};
open$1(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
}
}
},
cancelEvent: typeaheadCancel()
}),
Keying.config({
mode: 'special',
onDown: function (comp, simulatedEvent) {
navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
return Optional.some(true);
},
onEscape: function (comp) {
var sandbox = Coupling.getCoupled(comp, 'sandbox');
if (Sandboxing.isOpen(sandbox)) {
Sandboxing.close(sandbox);
return Optional.some(true);
}
return Optional.none();
},
onUp: function (comp, simulatedEvent) {
navigateList(comp, simulatedEvent, Highlighting.highlightLast);
return Optional.some(true);
},
onEnter: function (comp) {
var sandbox = Coupling.getCoupled(comp, 'sandbox');
var sandboxIsOpen = Sandboxing.isOpen(sandbox);
if (sandboxIsOpen && !detail.previewing.get()) {
return Composing.getCurrent(sandbox).bind(function (menu) {
return Highlighting.getHighlighted(menu);
}).map(function (item) {
emitWith(comp, itemExecute(), { item: item });
return true;
});
} else {
var currentValue = Representing.getValue(comp);
emit(comp, typeaheadCancel());
detail.onExecute(sandbox, comp, currentValue);
if (sandboxIsOpen) {
Sandboxing.close(sandbox);
}
return Optional.some(true);
}
}
}),
Toggling.config({
toggleClass: detail.markers.openClass,
aria: { mode: 'expanded' }
}),
Coupling.config({
others: {
sandbox: function (hotspot) {
return makeSandbox(detail, hotspot, {
onOpen: function () {
return Toggling.on(hotspot);
},
onClose: function () {
return Toggling.off(hotspot);
}
});
}
}
}),
config('typeaheadevents', [
runOnExecute(function (comp) {
var onOpenSync = noop;
togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
}),
run(itemExecute(), function (comp, se) {
var sandbox = Coupling.getCoupled(comp, 'sandbox');
setValueFromItem(detail.model, comp, se.event.item);
emit(comp, typeaheadCancel());
detail.onItemExecute(comp, sandbox, se.event.item, Representing.getValue(comp));
Sandboxing.close(sandbox);
setCursorAtEnd(comp);
})
].concat(detail.dismissOnBlur ? [run(postBlur(), function (typeahead) {
var sandbox = Coupling.getCoupled(typeahead, 'sandbox');
if (search(sandbox.element).isNone()) {
Sandboxing.close(sandbox);
}
})] : []))
];
return {
uid: detail.uid,
dom: dom$2(deepMerge(detail, {
inputAttributes: {
'role': 'combobox',
'aria-autocomplete': 'list',
'aria-haspopup': 'true'
}
})),
behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours)),
eventOrder: detail.eventOrder
};
};
var schema$j = constant([
option('lazySink'),
strict$1('fetch'),
defaulted$1('minChars', 5),
defaulted$1('responseTime', 1000),
onHandler('onOpen'),
defaulted$1('getHotspot', Optional.some),
defaulted$1('getAnchorOverrides', constant({})),
defaulted$1('layouts', Optional.none()),
defaulted$1('eventOrder', {}),
defaultedObjOf('model', {}, [
defaulted$1('getDisplayText', function (itemData) {
return itemData.meta !== undefined && itemData.meta.text !== undefined ? itemData.meta.text : itemData.value;
}),
defaulted$1('selectsOver', true),
defaulted$1('populateFromBrowse', true)
]),
onHandler('onSetValue'),
onKeyboardHandler('onExecute'),
onHandler('onItemExecute'),
defaulted$1('inputClasses', []),
defaulted$1('inputAttributes', {}),
defaulted$1('inputStyles', {}),
defaulted$1('matchWidth', true),
defaulted$1('useMinWidth', false),
defaulted$1('dismissOnBlur', true),
markers(['openClass']),
option('initialData'),
field$1('typeaheadBehaviours', [
Focusing,
Representing,
Streaming,
Keying,
Toggling,
Coupling
]),
state$1('previewing', function () {
return Cell(true);
})
].concat(schema$f()).concat(sandboxFields()));
var parts$6 = constant([external$1({
schema: [tieredMenuMarkers()],
name: 'menu',
overrides: function (detail) {
return {
fakeFocus: true,
onHighlight: function (menu, item) {
if (!detail.previewing.get()) {
menu.getSystem().getByUid(detail.uid).each(function (input) {
if (detail.model.populateFromBrowse) {
setValueFromItem(detail.model, input, item);
}
});
} else {
menu.getSystem().getByUid(detail.uid).each(function (input) {
attemptSelectOver(detail.model, input, item).fold(function () {
return Highlighting.dehighlight(menu, item);
}, function (fn) {
return fn();
});
});
}
detail.previewing.set(false);
},
onExecute: function (menu, item) {
return menu.getSystem().getByUid(detail.uid).toOptional().map(function (typeahead) {
emitWith(typeahead, itemExecute(), { item: item });
return true;
});
},
onHover: function (menu, item) {
detail.previewing.set(false);
menu.getSystem().getByUid(detail.uid).each(function (input) {
if (detail.model.populateFromBrowse) {
setValueFromItem(detail.model, input, item);
}
});
}
};
}
})]);
var Typeahead = composite$1({
name: 'Typeahead',
configFields: schema$j(),
partFields: parts$6(),
factory: make$5
});
var wrap$2 = function (delegate) {
var toCached = function () {
return wrap$2(delegate.toCached());
};
var bindFuture = function (f) {
return wrap$2(delegate.bind(function (resA) {
return resA.fold(function (err) {
return Future.pure(Result.error(err));
}, function (a) {
return f(a);
});
}));
};
var bindResult = function (f) {
return wrap$2(delegate.map(function (resA) {
return resA.bind(f);
}));
};
var mapResult = function (f) {
return wrap$2(delegate.map(function (resA) {
return resA.map(f);
}));
};
var mapError = function (f) {
return wrap$2(delegate.map(function (resA) {
return resA.mapError(f);
}));
};
var foldResult = function (whenError, whenValue) {
return delegate.map(function (res) {
return res.fold(whenError, whenValue);
});
};
var withTimeout = function (timeout, errorThunk) {
return wrap$2(Future.nu(function (callback) {
var timedOut = false;
var timer = setTimeout(function () {
timedOut = true;
callback(Result.error(errorThunk()));
}, timeout);
delegate.get(function (result) {
if (!timedOut) {
clearTimeout(timer);
callback(result);
}
});
}));
};
return __assign(__assign({}, delegate), {
toCached: toCached,
bindFuture: bindFuture,
bindResult: bindResult,
mapResult: mapResult,
mapError: mapError,
foldResult: foldResult,
withTimeout: withTimeout
});
};
var nu$c = function (worker) {
return wrap$2(Future.nu(worker));
};
var value$2 = function (value) {
return wrap$2(Future.pure(Result.value(value)));
};
var error$1 = function (error) {
return wrap$2(Future.pure(Result.error(error)));
};
var fromResult$1 = function (result) {
return wrap$2(Future.pure(result));
};
var fromFuture = function (future) {
return wrap$2(future.map(Result.value));
};
var fromPromise = function (promise) {
return nu$c(function (completer) {
promise.then(function (value) {
completer(Result.value(value));
}, function (error) {
completer(Result.error(error));
});
});
};
var FutureResult = {
nu: nu$c,
wrap: wrap$2,
pure: value$2,
value: value$2,
error: error$1,
fromResult: fromResult$1,
fromFuture: fromFuture,
fromPromise: fromPromise
};
var separator$2 = { type: 'separator' };
var toMenuItem = function (target) {
return {
type: 'menuitem',
value: target.url,
text: target.title,
meta: { attach: target.attach },
onAction: noop
};
};
var staticMenuItem = function (title, url) {
return {
type: 'menuitem',
value: url,
text: title,
meta: { attach: undefined },
onAction: noop
};
};
var toMenuItems = function (targets) {
return map(targets, toMenuItem);
};
var filterLinkTargets = function (type, targets) {
return filter(targets, function (target) {
return target.type === type;
});
};
var filteredTargets = function (type, targets) {
return toMenuItems(filterLinkTargets(type, targets));
};
var headerTargets = function (linkInfo) {
return filteredTargets('header', linkInfo.targets);
};
var anchorTargets = function (linkInfo) {
return filteredTargets('anchor', linkInfo.targets);
};
var anchorTargetTop = function (linkInfo) {
return Optional.from(linkInfo.anchorTop).map(function (url) {
return staticMenuItem('
', url);
}).toArray();
};
var anchorTargetBottom = function (linkInfo) {
return Optional.from(linkInfo.anchorBottom).map(function (url) {
return staticMenuItem('', url);
}).toArray();
};
var historyTargets = function (history) {
return map(history, function (url) {
return staticMenuItem(url, url);
});
};
var joinMenuLists = function (items) {
return foldl(items, function (a, b) {
var bothEmpty = a.length === 0 || b.length === 0;
return bothEmpty ? a.concat(b) : a.concat(separator$2, b);
}, []);
};
var filterByQuery = function (term, menuItems) {
var lowerCaseTerm = term.toLowerCase();
return filter(menuItems, function (item) {
var text = item.meta !== undefined && item.meta.text !== undefined ? item.meta.text : item.text;
return contains$1(text.toLowerCase(), lowerCaseTerm) || contains$1(item.value.toLowerCase(), lowerCaseTerm);
});
};
var getItems = function (fileType, input, urlBackstage) {
var urlInputValue = Representing.getValue(input);
var term = urlInputValue.meta.text !== undefined ? urlInputValue.meta.text : urlInputValue.value;
var info = urlBackstage.getLinkInformation();
return info.fold(function () {
return [];
}, function (linkInfo) {
var history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
return fileType === 'file' ? joinMenuLists([
history,
filterByQuery(term, headerTargets(linkInfo)),
filterByQuery(term, flatten([
anchorTargetTop(linkInfo),
anchorTargets(linkInfo),
anchorTargetBottom(linkInfo)
]))
]) : history;
});
};
var errorId = generate$1('aria-invalid');
var renderUrlInput = function (spec, backstage, urlBackstage) {
var _a;
var providersBackstage = backstage.shared.providers;
var updateHistory = function (component) {
var urlEntry = Representing.getValue(component);
urlBackstage.addToHistory(urlEntry.value, spec.filetype);
};
var pField = FormField.parts.field({
factory: Typeahead,
dismissOnBlur: true,
inputClasses: ['tox-textfield'],
sandboxClasses: ['tox-dialog__popups'],
inputAttributes: {
'aria-errormessage': errorId,
'type': 'url'
},
minChars: 0,
responseTime: 0,
fetch: function (input) {
var items = getItems(spec.filetype, input, urlBackstage);
var tdata = build$2(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
return Future.pure(tdata);
},
getHotspot: function (comp) {
return memUrlBox.getOpt(comp);
},
onSetValue: function (comp, _newValue) {
if (comp.hasConfigured(Invalidating)) {
Invalidating.run(comp).get(noop);
}
},
typeaheadBehaviours: derive$1(flatten([
urlBackstage.getValidationHandler().map(function (handler) {
return Invalidating.config({
getRoot: function (comp) {
return parent(comp.element);
},
invalidClass: 'tox-control-wrap--status-invalid',
notify: {
onInvalid: function (comp, err) {
memInvalidIcon.getOpt(comp).each(function (invalidComp) {
set$1(invalidComp.element, 'title', providersBackstage.translate(err));
});
}
},
validator: {
validate: function (input) {
var urlEntry = Representing.getValue(input);
return FutureResult.nu(function (completer) {
handler({
type: spec.filetype,
url: urlEntry.value
}, function (validation) {
if (validation.status === 'invalid') {
var err = Result.error(validation.message);
completer(err);
} else {
var val = Result.value(validation.message);
completer(val);
}
});
});
},
validateOnLoad: false
}
});
}).toArray(),
[
Disabling.config({
disabled: function () {
return spec.disabled || providersBackstage.isDisabled();
}
}),
Tabstopping.config({}),
config('urlinput-events', flatten([
spec.filetype === 'file' ? [run(input(), function (comp) {
emitWith(comp, formChangeEvent, { name: spec.name });
})] : [],
[
run(change(), function (comp) {
emitWith(comp, formChangeEvent, { name: spec.name });
updateHistory(comp);
}),
run(postPaste(), function (comp) {
emitWith(comp, formChangeEvent, { name: spec.name });
updateHistory(comp);
})
]
]))
]
])),
eventOrder: (_a = {}, _a[input()] = [
'streaming',
'urlinput-events',
'invalidating'
], _a),
model: {
getDisplayText: function (itemData) {
return itemData.value;
},
selectsOver: false,
populateFromBrowse: false
},
markers: { openClass: 'tox-textfield--popup-open' },
lazySink: backstage.shared.getSink,
parts: { menu: part(false, 1, 'normal') },
onExecute: function (_menu, component, _entry) {
emitWith(component, formSubmitEvent, {});
},
onItemExecute: function (typeahead, _sandbox, _item, _value) {
updateHistory(typeahead);
emitWith(typeahead, formChangeEvent, { name: spec.name });
}
});
var pLabel = spec.label.map(function (label) {
return renderLabel(label, providersBackstage);
});
var makeIcon = function (name, errId, icon, label) {
if (icon === void 0) {
icon = name;
}
if (label === void 0) {
label = name;
}
return {
dom: {
tag: 'div',
classes: [
'tox-icon',
'tox-control-wrap__status-icon-' + name
],
innerHtml: get$e(icon, providersBackstage.icons),
attributes: __assign({
'title': providersBackstage.translate(label),
'aria-live': 'polite'
}, errId.fold(function () {
return {};
}, function (id) {
return { id: id };
}))
}
};
};
var memInvalidIcon = record(makeIcon('invalid', Optional.some(errorId), 'warning'));
var memStatus = record({
dom: {
tag: 'div',
classes: ['tox-control-wrap__status-icon-wrap']
},
components: [memInvalidIcon.asSpec()]
});
var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
var browseUrlEvent = generate$1('browser.url.event');
var memUrlBox = record({
dom: {
tag: 'div',
classes: ['tox-control-wrap']
},
components: [
pField,
memStatus.asSpec()
],
behaviours: derive$1([Disabling.config({
disabled: function () {
return spec.disabled || providersBackstage.isDisabled();
}
})])
});
var memUrlPickerButton = record(renderButton({
name: spec.name,
icon: Optional.some('browse'),
text: spec.label.getOr(''),
disabled: spec.disabled,
primary: false,
borderless: true
}, function (component) {
return emit(component, browseUrlEvent);
}, providersBackstage, [], ['tox-browse-url']));
var controlHWrapper = function () {
return {
dom: {
tag: 'div',
classes: ['tox-form__controls-h-stack']
},
components: flatten([
[memUrlBox.asSpec()],
optUrlPicker.map(function () {
return memUrlPickerButton.asSpec();
}).toArray()
])
};
};
var openUrlPicker = function (comp) {
Composing.getCurrent(comp).each(function (field) {
var componentData = Representing.getValue(field);
var urlData = __assign({ fieldname: spec.name }, componentData);
optUrlPicker.each(function (picker) {
picker(urlData).get(function (chosenData) {
Representing.setValue(field, chosenData);
emitWith(comp, formChangeEvent, { name: spec.name });
});
});
});
};
return FormField.sketch({
dom: renderFormFieldDom(),
components: pLabel.toArray().concat([controlHWrapper()]),
fieldBehaviours: derive$1([
Disabling.config({
disabled: function () {
return spec.disabled || providersBackstage.isDisabled();
},
onDisabled: function (comp) {
FormField.getField(comp).each(Disabling.disable);
memUrlPickerButton.getOpt(comp).each(Disabling.disable);
},
onEnabled: function (comp) {
FormField.getField(comp).each(Disabling.enable);
memUrlPickerButton.getOpt(comp).each(Disabling.enable);
}
}),
receivingConfig(),
config('url-input-events', [run(browseUrlEvent, openUrlPicker)])
])
});
};
var renderAlertBanner = function (spec, providersBackstage) {
return Container.sketch({
dom: {
tag: 'div',
attributes: { role: 'alert' },
classes: [
'tox-notification',
'tox-notification--in',
'tox-notification--' + spec.level
]
},
components: [
{
dom: {
tag: 'div',
classes: ['tox-notification__icon']
},
components: [Button.sketch({
dom: {
tag: 'button',
classes: [
'tox-button',
'tox-button--naked',
'tox-button--icon'
],
innerHtml: get$e(spec.icon, providersBackstage.icons),
attributes: { title: providersBackstage.translate(spec.iconTooltip) }
},
action: function (comp) {
emitWith(comp, formActionEvent, {
name: 'alert-banner',
value: spec.url
});
}
})]
},
{
dom: {
tag: 'div',
classes: ['tox-notification__body'],
innerHtml: providersBackstage.translate(spec.text)
}
}
]
});
};
var renderCheckbox = function (spec, providerBackstage) {
var repBehaviour = Representing.config({
store: {
mode: 'manual',
getValue: function (comp) {
var el = comp.element.dom;
return el.checked;
},
setValue: function (comp, value) {
var el = comp.element.dom;
el.checked = value;
}
}
});
var toggleCheckboxHandler = function (comp) {
comp.element.dom.click();
return Optional.some(true);
};
var pField = FormField.parts.field({
factory: { sketch: identity },
dom: {
tag: 'input',
classes: ['tox-checkbox__input'],
attributes: { type: 'checkbox' }
},
behaviours: derive$1([
ComposingConfigs.self(),
Disabling.config({
disabled: function () {
return spec.disabled || providerBackstage.isDisabled();
}
}),
Tabstopping.config({}),
Focusing.config({}),
repBehaviour,
Keying.config({
mode: 'special',
onEnter: toggleCheckboxHandler,
onSpace: toggleCheckboxHandler,
stopSpaceKeyup: true
}),
config('checkbox-events', [run(change(), function (component, _) {
emitWith(component, formChangeEvent, { name: spec.name });
})])
])
});
var pLabel = FormField.parts.label({
dom: {
tag: 'span',
classes: ['tox-checkbox__label'],
innerHtml: providerBackstage.translate(spec.label)
},
behaviours: derive$1([Unselecting.config({})])
});
var makeIcon = function (className) {
var iconName = className === 'checked' ? 'selected' : 'unselected';
return {
dom: {
tag: 'span',
classes: [
'tox-icon',
'tox-checkbox-icon__' + className
],
innerHtml: get$e(iconName, providerBackstage.icons)
}
};
};
var memIcons = record({
dom: {
tag: 'div',
classes: ['tox-checkbox__icons']
},
components: [
makeIcon('checked'),
makeIcon('unchecked')
]
});
return FormField.sketch({
dom: {
tag: 'label',
classes: ['tox-checkbox']
},
components: [
pField,
memIcons.asSpec(),
pLabel
],
fieldBehaviours: derive$1([
Disabling.config({
disabled: function () {
return spec.disabled || providerBackstage.isDisabled();
},
disableClass: 'tox-checkbox--disabled',
onDisabled: function (comp) {
FormField.getField(comp).each(Disabling.disable);
},
onEnabled: function (comp) {
FormField.getField(comp).each(Disabling.enable);
}
}),
receivingConfig()
])
});
};
var renderHtmlPanel = function (spec) {
if (spec.presets === 'presentation') {
return Container.sketch({
dom: {
tag: 'div',
classes: ['tox-form__group'],
innerHtml: spec.html
}
});
} else {
return Container.sketch({
dom: {
tag: 'div',
classes: ['tox-form__group'],
innerHtml: spec.html,
attributes: { role: 'document' }
},
containerBehaviours: derive$1([
Tabstopping.config({}),
Focusing.config({})
])
});
}
};
var make$6 = function (render) {
return function (parts, spec, backstage) {
return get$1(spec, 'name').fold(function () {
return render(spec, backstage);
}, function (fieldName) {
return parts.field(fieldName, render(spec, backstage));
});
};
};
var makeIframe = function (render) {
return function (parts, spec, backstage) {
var iframeSpec = deepMerge(spec, { source: 'dynamic' });
return make$6(render)(parts, iframeSpec, backstage);
};
};
var factories = {
bar: make$6(function (spec, backstage) {
return renderBar(spec, backstage.shared);
}),
collection: make$6(function (spec, backstage) {
return renderCollection(spec, backstage.shared.providers);
}),
alertbanner: make$6(function (spec, backstage) {
return renderAlertBanner(spec, backstage.shared.providers);
}),
input: make$6(function (spec, backstage) {
return renderInput(spec, backstage.shared.providers);
}),
textarea: make$6(function (spec, backstage) {
return renderTextarea(spec, backstage.shared.providers);
}),
label: make$6(function (spec, backstage) {
return renderLabel$2(spec, backstage.shared);
}),
iframe: makeIframe(function (spec, backstage) {
return renderIFrame(spec, backstage.shared.providers);
}),
button: make$6(function (spec, backstage) {
return renderDialogButton(spec, backstage.shared.providers);
}),
checkbox: make$6(function (spec, backstage) {
return renderCheckbox(spec, backstage.shared.providers);
}),
colorinput: make$6(function (spec, backstage) {
return renderColorInput(spec, backstage.shared, backstage.colorinput);
}),
colorpicker: make$6(renderColorPicker),
dropzone: make$6(function (spec, backstage) {
return renderDropZone(spec, backstage.shared.providers);
}),
grid: make$6(function (spec, backstage) {
return renderGrid(spec, backstage.shared);
}),
listbox: make$6(function (spec, backstage) {
return renderListBox(spec, backstage);
}),
selectbox: make$6(function (spec, backstage) {
return renderSelectBox(spec, backstage.shared.providers);
}),
sizeinput: make$6(function (spec, backstage) {
return renderSizeInput(spec, backstage.shared.providers);
}),
urlinput: make$6(function (spec, backstage) {
return renderUrlInput(spec, backstage, backstage.urlinput);
}),
customeditor: make$6(renderCustomEditor),
htmlpanel: make$6(renderHtmlPanel),
imagetools: make$6(function (spec, backstage) {
return renderImageTools(spec, backstage.shared.providers);
}),
table: make$6(function (spec, backstage) {
return renderTable(spec, backstage.shared.providers);
}),
panel: make$6(function (spec, backstage) {
return renderPanel(spec, backstage);
})
};
var noFormParts = {
field: function (_name, spec) {
return spec;
}
};
var interpretInForm = function (parts, spec, oldBackstage) {
var newBackstage = deepMerge(oldBackstage, {
shared: {
interpreter: function (childSpec) {
return interpretParts(parts, childSpec, newBackstage);
}
}
});
return interpretParts(parts, spec, newBackstage);
};
var interpretParts = function (parts, spec, backstage) {
return get$1(factories, spec.type).fold(function () {
console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec);
return spec;
}, function (factory) {
return factory(parts, spec, backstage);
});
};
var interpretWithoutForm = function (spec, backstage) {
var parts = noFormParts;
return interpretParts(parts, spec, backstage);
};
var bubbleAlignments = {
valignCentre: [],
alignCentre: [],
alignLeft: [],
alignRight: [],
right: [],
left: [],
bottom: [],
top: []
};
var getInlineDialogAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
var bubble = nu$8(-12, 12, bubbleAlignments);
var overrides = { maxHeightFunction: expandable() };
var editableAreaAnchor = function () {
return {
anchor: 'node',
root: getContentContainer(contentAreaElement()),
node: Optional.from(contentAreaElement()),
bubble: bubble,
layouts: {
onRtl: function () {
return [northwest$3];
},
onLtr: function () {
return [northeast$3];
}
},
overrides: overrides
};
};
var standardAnchor = function () {
return {
anchor: 'hotspot',
hotspot: lazyAnchorbar(),
bubble: bubble,
layouts: {
onRtl: function () {
return [southeast$1];
},
onLtr: function () {
return [southwest$1];
}
},
overrides: overrides
};
};
return function () {
return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
};
};
var getBannerAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
var editableAreaAnchor = function () {
return {
anchor: 'node',
root: getContentContainer(contentAreaElement()),
node: Optional.from(contentAreaElement()),
layouts: {
onRtl: function () {
return [north$3];
},
onLtr: function () {
return [north$3];
}
}
};
};
var standardAnchor = function () {
return {
anchor: 'hotspot',
hotspot: lazyAnchorbar(),
layouts: {
onRtl: function () {
return [south$1];
},
onLtr: function () {
return [south$1];
}
}
};
};
return function () {
return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
};
};
var getCursorAnchor = function (editor, bodyElement) {
return function () {
return {
anchor: 'selection',
root: bodyElement(),
getSelection: function () {
var rng = editor.selection.getRng();
return Optional.some(SimSelection.range(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
}
};
};
};
var getNodeAnchor = function (bodyElement) {
return function (element) {
return {
anchor: 'node',
root: bodyElement(),
node: element
};
};
};
var getAnchors = function (editor, lazyAnchorbar, isToolbarTop) {
var useFixedToolbarContainer = useFixedContainer(editor);
var bodyElement = function () {
return SugarElement.fromDom(editor.getBody());
};
var contentAreaElement = function () {
return SugarElement.fromDom(editor.getContentAreaContainer());
};
var lazyUseEditableAreaAnchor = function () {
return useFixedToolbarContainer || !isToolbarTop();
};
return {
inlineDialog: getInlineDialogAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
banner: getBannerAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
cursor: getCursorAnchor(editor, bodyElement),
node: getNodeAnchor(bodyElement)
};
};
var colorPicker = function (editor) {
return function (callback, value) {
var dialog = colorPickerDialog(editor);
dialog(callback, value);
};
};
var hasCustomColors$1 = function (editor) {
return function () {
return hasCustomColors(editor);
};
};
var getColors$2 = function (editor) {
return function () {
return getColors(editor);
};
};
var getColorCols$2 = function (editor) {
return function () {
return getColorCols$1(editor);
};
};
var ColorInputBackstage = function (editor) {
return {
colorPicker: colorPicker(editor),
hasCustomColors: hasCustomColors$1(editor),
getColors: getColors$2(editor),
getColorCols: getColorCols$2(editor)
};
};
var isDraggableModal$1 = function (editor) {
return function () {
return isDraggableModal(editor);
};
};
var DialogBackstage = function (editor) {
return { isDraggableModal: isDraggableModal$1(editor) };
};
var HeaderBackstage = function (editor) {
var mode = Cell(isToolbarLocationBottom(editor) ? 'bottom' : 'top');
return {
isPositionedAtTop: function () {
return mode.get() === 'top';
},
getDockingMode: mode.get,
setDockingMode: mode.set
};
};
var defaultStyleFormats = [
{
title: 'Headings',
items: [
{
title: 'Heading 1',
format: 'h1'
},
{
title: 'Heading 2',
format: 'h2'
},
{
title: 'Heading 3',
format: 'h3'
},
{
title: 'Heading 4',
format: 'h4'
},
{
title: 'Heading 5',
format: 'h5'
},
{
title: 'Heading 6',
format: 'h6'
}
]
},
{
title: 'Inline',
items: [
{
title: 'Bold',
format: 'bold'
},
{
title: 'Italic',
format: 'italic'
},
{
title: 'Underline',
format: 'underline'
},
{
title: 'Strikethrough',
format: 'strikethrough'
},
{
title: 'Superscript',
format: 'superscript'
},
{
title: 'Subscript',
format: 'subscript'
},
{
title: 'Code',
format: 'code'
}
]
},
{
title: 'Blocks',
items: [
{
title: 'Paragraph',
format: 'p'
},
{
title: 'Blockquote',
format: 'blockquote'
},
{
title: 'Div',
format: 'div'
},
{
title: 'Pre',
format: 'pre'
}
]
},
{
title: 'Align',
items: [
{
title: 'Left',
format: 'alignleft'
},
{
title: 'Center',
format: 'aligncenter'
},
{
title: 'Right',
format: 'alignright'
},
{
title: 'Justify',
format: 'alignjustify'
}
]
}
];
var isNestedFormat = function (format) {
return has(format, 'items');
};
var isBlockFormat = function (format) {
return has(format, 'block');
};
var isInlineFormat = function (format) {
return has(format, 'inline');
};
var isSelectorFormat = function (format) {
return has(format, 'selector');
};
var mapFormats = function (userFormats) {
return foldl(userFormats, function (acc, fmt) {
if (isNestedFormat(fmt)) {
var result = mapFormats(fmt.items);
return {
customFormats: acc.customFormats.concat(result.customFormats),
formats: acc.formats.concat([{
title: fmt.title,
items: result.formats
}])
};
} else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
var formatName = isString(fmt.name) ? fmt.name : fmt.title.toLowerCase();
var formatNameWithPrefix = 'custom-' + formatName;
return {
customFormats: acc.customFormats.concat([{
name: formatNameWithPrefix,
format: fmt
}]),
formats: acc.formats.concat([{
title: fmt.title,
format: formatNameWithPrefix,
icon: fmt.icon
}])
};
} else {
return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) });
}
}, {
customFormats: [],
formats: []
});
};
var registerCustomFormats = function (editor, userFormats) {
var result = mapFormats(userFormats);
var registerFormats = function (customFormats) {
each(customFormats, function (fmt) {
if (!editor.formatter.has(fmt.name)) {
editor.formatter.register(fmt.name, fmt.format);
}
});
};
if (editor.formatter) {
registerFormats(result.customFormats);
} else {
editor.on('init', function () {
registerFormats(result.customFormats);
});
}
return result.formats;
};
var getStyleFormats = function (editor) {
return getUserStyleFormats(editor).map(function (userFormats) {
var registeredUserFormats = registerCustomFormats(editor, userFormats);
return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
}).getOr(defaultStyleFormats);
};
var processBasic = function (item, isSelectedFor, getPreviewFor) {
var formatterSpec = {
type: 'formatter',
isSelected: isSelectedFor(item.format),
getStylePreview: getPreviewFor(item.format)
};
return deepMerge(item, formatterSpec);
};
var register$3 = function (editor, formats, isSelectedFor, getPreviewFor) {
var enrichSupported = function (item) {
return processBasic(item, isSelectedFor, getPreviewFor);
};
var enrichMenu = function (item) {
var submenuSpec = { type: 'submenu' };
return deepMerge(item, submenuSpec);
};
var enrichCustom = function (item) {
var formatName = isString(item.name) ? item.name : generate$1(item.title);
var formatNameWithPrefix = 'custom-' + formatName;
var customSpec = {
type: 'formatter',
format: formatNameWithPrefix,
isSelected: isSelectedFor(formatNameWithPrefix),
getStylePreview: getPreviewFor(formatNameWithPrefix)
};
var newItem = deepMerge(item, customSpec);
editor.formatter.register(formatName, newItem);
return newItem;
};
var doEnrich = function (items) {
return map(items, function (item) {
var keys$1 = keys(item);
if (hasNonNullableKey(item, 'items')) {
var newItems_1 = doEnrich(item.items);
return deepMerge(enrichMenu(item), {
getStyleItems: function () {
return newItems_1;
}
});
} else if (hasNonNullableKey(item, 'format')) {
return enrichSupported(item);
} else if (keys$1.length === 1 && contains(keys$1, 'title')) {
return deepMerge(item, { type: 'separator' });
} else {
return enrichCustom(item);
}
});
};
return doEnrich(formats);
};
var init$7 = function (editor) {
var isSelectedFor = function (format) {
return function () {
return editor.formatter.match(format);
};
};
var getPreviewFor = function (format) {
return function () {
var fmt = editor.formatter.get(format);
return fmt !== undefined ? Optional.some({
tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
}) : Optional.none();
};
};
var flatten = function (fmt) {
var subs = fmt.items;
return subs !== undefined && subs.length > 0 ? bind(subs, flatten) : [fmt.format];
};
var settingsFormats = Cell([]);
var settingsFlattenedFormats = Cell([]);
var eventsFormats = Cell([]);
var eventsFlattenedFormats = Cell([]);
var replaceSettings = Cell(false);
editor.on('PreInit', function (_e) {
var formats = getStyleFormats(editor);
var enriched = register$3(editor, formats, isSelectedFor, getPreviewFor);
settingsFormats.set(enriched);
settingsFlattenedFormats.set(bind(enriched, flatten));
});
editor.on('addStyleModifications', function (e) {
var modifications = register$3(editor, e.items, isSelectedFor, getPreviewFor);
eventsFormats.set(modifications);
replaceSettings.set(e.replace);
eventsFlattenedFormats.set(bind(modifications, flatten));
});
var getData = function () {
var fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
var fromEvents = eventsFormats.get();
return fromSettings.concat(fromEvents);
};
var getFlattenedKeys = function () {
var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
var fromEvents = eventsFlattenedFormats.get();
return fromSettings.concat(fromEvents);
};
return {
getData: getData,
getFlattenedKeys: getFlattenedKeys
};
};
var isElement$2 = function (node) {
return isNonNullable(node) && node.nodeType === 1;
};
var trim$1 = global$c.trim;
var hasContentEditableState = function (value) {
return function (node) {
if (isElement$2(node)) {
if (node.contentEditable === value) {
return true;
}
if (node.getAttribute('data-mce-contenteditable') === value) {
return true;
}
}
return false;
};
};
var isContentEditableTrue = hasContentEditableState('true');
var isContentEditableFalse = hasContentEditableState('false');
var create$8 = function (type, title, url, level, attach) {
return {
type: type,
title: title,
url: url,
level: level,
attach: attach
};
};
var isChildOfContentEditableTrue = function (node) {
while (node = node.parentNode) {
var value = node.contentEditable;
if (value && value !== 'inherit') {
return isContentEditableTrue(node);
}
}
return false;
};
var select = function (selector, root) {
return map(descendants(SugarElement.fromDom(root), selector), function (element) {
return element.dom;
});
};
var getElementText = function (elm) {
return elm.innerText || elm.textContent;
};
var getOrGenerateId = function (elm) {
return elm.id ? elm.id : generate$1('h');
};
var isAnchor = function (elm) {
return elm && elm.nodeName === 'A' && (elm.id || elm.name) !== undefined;
};
var isValidAnchor = function (elm) {
return isAnchor(elm) && isEditable(elm);
};
var isHeader = function (elm) {
return elm && /^(H[1-6])$/.test(elm.nodeName);
};
var isEditable = function (elm) {
return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
};
var isValidHeader = function (elm) {
return isHeader(elm) && isEditable(elm);
};
var getLevel = function (elm) {
return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
};
var headerTarget = function (elm) {
var headerId = getOrGenerateId(elm);
var attach = function () {
elm.id = headerId;
};
return create$8('header', getElementText(elm), '#' + headerId, getLevel(elm), attach);
};
var anchorTarget = function (elm) {
var anchorId = elm.id || elm.name;
var anchorText = getElementText(elm);
return create$8('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, noop);
};
var getHeaderTargets = function (elms) {
return map(filter(elms, isValidHeader), headerTarget);
};
var getAnchorTargets = function (elms) {
return map(filter(elms, isValidAnchor), anchorTarget);
};
var getTargetElements = function (elm) {
var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm);
return elms;
};
var hasTitle = function (target) {
return trim$1(target.title).length > 0;
};
var find$5 = function (elm) {
var elms = getTargetElements(elm);
return filter(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
};
var LinkTargets = { find: find$5 };
var STORAGE_KEY = 'tinymce-url-history';
var HISTORY_LENGTH = 5;
var isHttpUrl = function (url) {
return isString(url) && /^https?/.test(url);
};
var isArrayOfUrl = function (a) {
return isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl);
};
var isRecordOfUrlArray = function (r) {
return isObject(r) && find$1(r, function (value) {
return !isArrayOfUrl(value);
}).isNone();
};
var getAllHistory = function () {
var unparsedHistory = global$9.getItem(STORAGE_KEY);
if (unparsedHistory === null) {
return {};
}
var history;
try {
history = JSON.parse(unparsedHistory);
} catch (e) {
if (e instanceof SyntaxError) {
console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e);
return {};
}
throw e;
}
if (!isRecordOfUrlArray(history)) {
console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history);
return {};
}
return history;
};
var setAllHistory = function (history) {
if (!isRecordOfUrlArray(history)) {
throw new Error('Bad format for history:\n' + JSON.stringify(history));
}
global$9.setItem(STORAGE_KEY, JSON.stringify(history));
};
var getHistory = function (fileType) {
var history = getAllHistory();
return Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : [];
};
var addToHistory = function (url, fileType) {
if (!isHttpUrl(url)) {
return;
}
var history = getAllHistory();
var items = Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : [];
var itemsWithoutUrl = filter(items, function (item) {
return item !== url;
});
history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
setAllHistory(history);
};
var isTruthy = function (value) {
return !!value;
};
var makeMap = function (value) {
return map$2(global$c.makeMap(value, /[, ]/), isTruthy);
};
var getPicker = function (editor) {
return Optional.from(getFilePickerCallback(editor)).filter(isFunction);
};
var getPickerTypes = function (editor) {
var optFileTypes = Optional.some(getFilePickerTypes(editor)).filter(isTruthy);
var optLegacyTypes = Optional.some(getFileBrowserCallbackTypes(editor)).filter(isTruthy);
var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap);
return getPicker(editor).fold(never, function (_picker) {
return optTypes.fold(always, function (types) {
return keys(types).length > 0 ? types : false;
});
});
};
var getPickerSetting = function (editor, filetype) {
var pickerTypes = getPickerTypes(editor);
if (isBoolean(pickerTypes)) {
return pickerTypes ? getPicker(editor) : Optional.none();
} else {
return pickerTypes[filetype] ? getPicker(editor) : Optional.none();
}
};
var getUrlPicker = function (editor, filetype) {
return getPickerSetting(editor, filetype).map(function (picker) {
return function (entry) {
return Future.nu(function (completer) {
var handler = function (value, meta) {
if (!isString(value)) {
throw new Error('Expected value to be string');
}
if (meta !== undefined && !isObject(meta)) {
throw new Error('Expected meta to be a object');
}
var r = {
value: value,
meta: meta
};
completer(r);
};
var meta = __assign({
filetype: filetype,
fieldname: entry.fieldname
}, Optional.from(entry.meta).getOr({}));
picker.call(editor, handler, entry.value, meta);
});
};
});
};
var getTextSetting = function (value) {
return Optional.from(value).filter(isString).getOrUndefined();
};
var getLinkInformation = function (editor) {
if (noTypeaheadUrls(editor)) {
return Optional.none();
}
return Optional.some({
targets: LinkTargets.find(editor.getBody()),
anchorTop: getTextSetting(getAnchorTop(editor)),
anchorBottom: getTextSetting(getAnchorBottom(editor))
});
};
var getValidationHandler = function (editor) {
return Optional.from(getFilePickerValidatorHandler(editor));
};
var UrlInputBackstage = function (editor) {
return {
getHistory: getHistory,
addToHistory: addToHistory,
getLinkInformation: function () {
return getLinkInformation(editor);
},
getValidationHandler: function () {
return getValidationHandler(editor);
},
getUrlPicker: function (filetype) {
return getUrlPicker(editor, filetype);
}
};
};
var init$8 = function (sink, editor, lazyAnchorbar) {
var contextMenuState = Cell(false);
var toolbar = HeaderBackstage(editor);
var backstage = {
shared: {
providers: {
icons: function () {
return editor.ui.registry.getAll().icons;
},
menuItems: function () {
return editor.ui.registry.getAll().menuItems;
},
translate: global$6.translate,
isDisabled: function () {
return editor.mode.isReadOnly() || editor.ui.isDisabled();
},
getSetting: editor.getParam.bind(editor)
},
interpreter: function (s) {
return interpretWithoutForm(s, backstage);
},
anchors: getAnchors(editor, lazyAnchorbar, toolbar.isPositionedAtTop),
header: toolbar,
getSink: function () {
return Result.value(sink);
}
},
urlinput: UrlInputBackstage(editor),
styleselect: init$7(editor),
colorinput: ColorInputBackstage(editor),
dialog: DialogBackstage(editor),
isContextMenuOpen: function () {
return contextMenuState.get();
},
setContextMenuState: function (state) {
return contextMenuState.set(state);
}
};
return backstage;
};
var expandable$1 = constant(function (element, available) {
setMax$1(element, Math.floor(available));
});
var showContextToolbarEvent = 'contexttoolbar-show';
var hideContextToolbarEvent = 'contexttoolbar-hide';
var schema$k = constant([
strict$1('dom'),
defaulted$1('shell', true),
field$1('toolbarBehaviours', [Replacing])
]);
var enhanceGroups = function () {
return { behaviours: derive$1([Replacing.config({})]) };
};
var parts$7 = constant([optional({
name: 'groups',
overrides: enhanceGroups
})]);
var factory$9 = function (detail, components, _spec, _externals) {
var setGroups = function (toolbar, groups) {
getGroupContainer(toolbar).fold(function () {
console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
}, function (container) {
Replacing.set(container, groups);
});
};
var getGroupContainer = function (component) {
return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups');
};
var extra = detail.shell ? {
behaviours: [Replacing.config({})],
components: []
} : {
behaviours: [],
components: components
};
return {
uid: detail.uid,
dom: detail.dom,
components: extra.components,
behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
apis: { setGroups: setGroups },
domModification: { attributes: { role: 'group' } }
};
};
var Toolbar = composite$1({
name: 'Toolbar',
configFields: schema$k(),
partFields: parts$7(),
factory: factory$9,
apis: {
setGroups: function (apis, toolbar, groups) {
apis.setGroups(toolbar, groups);
}
}
});
var generate$6 = function (xs, f) {
var init = {
len: 0,
list: []
};
var r = foldl(xs, function (b, a) {
var value = f(a, b.len);
return value.fold(constant(b), function (v) {
return {
len: v.finish,
list: b.list.concat([v])
};
});
}, init);
return r.list;
};
var output$1 = function (within, extra, withinWidth) {
return {
within: within,
extra: extra,
withinWidth: withinWidth
};
};
var apportion = function (units, total, len) {
var parray = generate$6(units, function (unit, current) {
var width = len(unit);
return Optional.some({
element: unit,
start: current,
finish: current + width,
width: width
});
});
var within = filter(parray, function (unit) {
return unit.finish <= total;
});
var withinWidth = foldr(within, function (acc, el) {
return acc + el.width;
}, 0);
var extra = parray.slice(within.length);
return {
within: within,
extra: extra,
withinWidth: withinWidth
};
};
var toUnit = function (parray) {
return map(parray, function (unit) {
return unit.element;
});
};
var fitLast = function (within, extra, withinWidth) {
var fits = toUnit(within.concat(extra));
return output$1(fits, [], withinWidth);
};
var overflow = function (within, extra, overflower, withinWidth) {
var fits = toUnit(within).concat([overflower]);
return output$1(fits, toUnit(extra), withinWidth);
};
var fitAll = function (within, extra, withinWidth) {
return output$1(toUnit(within), [], withinWidth);
};
var tryFit = function (total, units, len) {
var divide = apportion(units, total, len);
return divide.extra.length === 0 ? Optional.some(divide) : Optional.none();
};
var partition$3 = function (total, units, len, overflower) {
var divide = tryFit(total, units, len).getOrThunk(function () {
return apportion(units, total - len(overflower), len);
});
var within = divide.within;
var extra = divide.extra;
var withinWidth = divide.withinWidth;
if (extra.length === 1 && extra[0].width <= len(overflower)) {
return fitLast(within, extra, withinWidth);
} else if (extra.length >= 1) {
return overflow(within, extra, overflower, withinWidth);
} else {
return fitAll(within, extra, withinWidth);
}
};
var setGroups = function (toolbar, storedGroups) {
var bGroups = map(storedGroups, function (g) {
return premade$1(g);
});
Toolbar.setGroups(toolbar, bGroups);
};
var findFocusedComp = function (comps) {
return findMap(comps, function (comp) {
return search(comp.element).bind(function (focusedElm) {
return comp.getSystem().getByDom(focusedElm).toOptional();
});
});
};
var refresh = function (toolbar, detail, setOverflow) {
var primary = getPartOrDie(toolbar, detail, 'primary');
var overflowGroup = Coupling.getCoupled(toolbar, 'overflowGroup');
set$2(primary.element, 'visibility', 'hidden');
var groups = detail.builtGroups.get().concat([overflowGroup]);
var focusedComp = findFocusedComp(groups);
setOverflow([]);
setGroups(primary, groups);
var availableWidth = get$8(primary.element);
var overflows = partition$3(availableWidth, detail.builtGroups.get(), function (comp) {
return get$8(comp.element);
}, overflowGroup);
if (overflows.extra.length === 0) {
Replacing.remove(primary, overflowGroup);
setOverflow([]);
} else {
setGroups(primary, overflows.within);
setOverflow(overflows.extra);
}
remove$6(primary.element, 'visibility');
reflow(primary.element);
focusedComp.each(Focusing.focus);
};
var schema$l = constant([
field$1('splitToolbarBehaviours', [Coupling]),
state$1('builtGroups', function () {
return Cell([]);
})
]);
var schema$m = constant([
markers(['overflowToggledClass']),
optionFunction('getOverflowBounds'),
strict$1('lazySink'),
state$1('overflowGroups', function () {
return Cell([]);
})
].concat(schema$l()));
var parts$8 = constant([
required({
factory: Toolbar,
schema: schema$k(),
name: 'primary'
}),
external$1({
schema: schema$k(),
name: 'overflow'
}),
external$1({ name: 'overflow-button' }),
external$1({ name: 'overflow-group' })
]);
var schema$n = constant([
markers(['toggledClass']),
strict$1('lazySink'),
strictFunction('fetch'),
optionFunction('getBounds'),
optionObjOf('fireDismissalEventInstead', [defaulted$1('event', dismissRequested())]),
schema$1()
]);
var parts$9 = constant([
external$1({
name: 'button',
overrides: function (detail) {
return {
dom: { attributes: { 'aria-haspopup': 'true' } },
buttonBehaviours: derive$1([Toggling.config({
toggleClass: detail.markers.toggledClass,
aria: { mode: 'expanded' },
toggleOnExecute: false
})])
};
}
}),
external$1({
factory: Toolbar,
schema: schema$k(),
name: 'toolbar',
overrides: function (detail) {
return {
toolbarBehaviours: derive$1([Keying.config({
mode: 'cyclic',
onEscape: function (comp) {
getPart(comp, detail, 'button').each(Focusing.focus);
return Optional.none();
}
})])
};
}
})
]);
var toggle$2 = function (button, externals) {
var toolbarSandbox = Coupling.getCoupled(button, 'toolbarSandbox');
if (Sandboxing.isOpen(toolbarSandbox)) {
Sandboxing.close(toolbarSandbox);
} else {
Sandboxing.open(toolbarSandbox, externals.toolbar());
}
};
var position$2 = function (button, toolbar, detail, layouts) {
var bounds = detail.getBounds.map(function (bounder) {
return bounder();
});
var sink = detail.lazySink(button).getOrDie();
Positioning.positionWithinBounds(sink, {
anchor: 'hotspot',
hotspot: button,
layouts: layouts,
overrides: { maxWidthFunction: expandable$1() }
}, toolbar, bounds);
};
var setGroups$1 = function (button, toolbar, detail, layouts, groups) {
Toolbar.setGroups(toolbar, groups);
position$2(button, toolbar, detail, layouts);
Toggling.on(button);
};
var makeSandbox$1 = function (button, spec, detail) {
var ariaOwner = manager();
var onOpen = function (sandbox, toolbar) {
detail.fetch().get(function (groups) {
setGroups$1(button, toolbar, detail, spec.layouts, groups);
ariaOwner.link(button.element);
Keying.focusIn(toolbar);
});
};
var onClose = function () {
Toggling.off(button);
Focusing.focus(button);
ariaOwner.unlink(button.element);
};
return {
dom: {
tag: 'div',
attributes: { id: ariaOwner.id }
},
behaviours: derive$1([
Keying.config({
mode: 'special',
onEscape: function (comp) {
Sandboxing.close(comp);
return Optional.some(true);
}
}),
Sandboxing.config({
onOpen: onOpen,
onClose: onClose,
isPartOf: function (container, data, queryElem) {
return isPartOf(data, queryElem) || isPartOf(button, queryElem);
},
getAttachPoint: function () {
return detail.lazySink(button).getOrDie();
}
}),
Receiving.config({
channels: __assign(__assign({}, receivingChannel(__assign({ isExtraPart: never }, detail.fireDismissalEventInstead.map(function (fe) {
return { fireEventInstead: { event: fe.event } };
}).getOr({})))), receivingChannel$1({
doReposition: function () {
Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
position$2(button, toolbar, detail, spec.layouts);
});
}
}))
})
])
};
};
var factory$a = function (detail, components, spec, externals) {
return __assign(__assign({}, Button.sketch(__assign(__assign({}, externals.button()), {
action: function (button) {
toggle$2(button, externals);
},
buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({
others: {
toolbarSandbox: function (button) {
return makeSandbox$1(button, spec, detail);
}
}
})])
}))), {
apis: {
setGroups: function (button, groups) {
Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
setGroups$1(button, toolbar, detail, spec.layouts, groups);
});
},
reposition: function (button) {
Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
position$2(button, toolbar, detail, spec.layouts);
});
},
toggle: function (button) {
toggle$2(button, externals);
},
getToolbar: function (button) {
return Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox'));
},
isOpen: function (button) {
return Sandboxing.isOpen(Coupling.getCoupled(button, 'toolbarSandbox'));
}
}
});
};
var FloatingToolbarButton = composite$1({
name: 'FloatingToolbarButton',
factory: factory$a,
configFields: schema$n(),
partFields: parts$9(),
apis: {
setGroups: function (apis, button, groups) {
apis.setGroups(button, groups);
},
reposition: function (apis, button) {
apis.reposition(button);
},
toggle: function (apis, button) {
apis.toggle(button);
},
getToolbar: function (apis, button) {
return apis.getToolbar(button);
},
isOpen: function (apis, button) {
return apis.isOpen(button);
}
}
});
var schema$o = constant([
strict$1('items'),
markers(['itemSelector']),
field$1('tgroupBehaviours', [Keying])
]);
var parts$a = constant([group({
name: 'items',
unit: 'item'
})]);
var factory$b = function (detail, components, _spec, _externals) {
return {
uid: detail.uid,
dom: detail.dom,
components: components,
behaviours: augment(detail.tgroupBehaviours, [Keying.config({
mode: 'flow',
selector: detail.markers.itemSelector
})]),
domModification: { attributes: { role: 'toolbar' } }
};
};
var ToolbarGroup = composite$1({
name: 'ToolbarGroup',
configFields: schema$o(),
partFields: parts$a(),
factory: factory$b
});
var buildGroups = function (comps) {
return map(comps, function (g) {
return premade$1(g);
});
};
var refresh$1 = function (toolbar, memFloatingToolbarButton, detail) {
refresh(toolbar, detail, function (overflowGroups) {
detail.overflowGroups.set(overflowGroups);
memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups));
});
});
};
var factory$c = function (detail, components, spec, externals) {
var memFloatingToolbarButton = record(FloatingToolbarButton.sketch({
fetch: function () {
return Future.nu(function (resolve) {
resolve(buildGroups(detail.overflowGroups.get()));
});
},
layouts: {
onLtr: function () {
return [
southwest$1,
southeast$1
];
},
onRtl: function () {
return [
southeast$1,
southwest$1
];
},
onBottomLtr: function () {
return [
northwest$1,
northeast$1
];
},
onBottomRtl: function () {
return [
northeast$1,
northwest$1
];
}
},
getBounds: spec.getOverflowBounds,
lazySink: detail.lazySink,
fireDismissalEventInstead: {},
markers: { toggledClass: detail.markers.overflowToggledClass },
parts: {
button: externals['overflow-button'](),
toolbar: externals.overflow()
}
}));
return {
uid: detail.uid,
dom: detail.dom,
components: components,
behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({
others: {
overflowGroup: function () {
return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), { items: [memFloatingToolbarButton.asSpec()] }));
}
}
})]),
apis: {
setGroups: function (toolbar, groups) {
detail.builtGroups.set(map(groups, toolbar.getSystem().build));
refresh$1(toolbar, memFloatingToolbarButton, detail);
},
refresh: function (toolbar) {
return refresh$1(toolbar, memFloatingToolbarButton, detail);
},
toggle: function (toolbar) {
memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
FloatingToolbarButton.toggle(floatingToolbarButton);
});
},
isOpen: function (toolbar) {
return memFloatingToolbarButton.getOpt(toolbar).map(FloatingToolbarButton.isOpen).getOr(false);
},
reposition: function (toolbar) {
memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
FloatingToolbarButton.reposition(floatingToolbarButton);
});
},
getOverflow: function (toolbar) {
return memFloatingToolbarButton.getOpt(toolbar).bind(FloatingToolbarButton.getToolbar);
}
},
domModification: { attributes: { role: 'group' } }
};
};
var SplitFloatingToolbar = composite$1({
name: 'SplitFloatingToolbar',
configFields: schema$m(),
partFields: parts$8(),
factory: factory$c,
apis: {
setGroups: function (apis, toolbar, groups) {
apis.setGroups(toolbar, groups);
},
refresh: function (apis, toolbar) {
apis.refresh(toolbar);
},
reposition: function (apis, toolbar) {
apis.reposition(toolbar);
},
toggle: function (apis, toolbar) {
apis.toggle(toolbar);
},
isOpen: function (apis, toolbar) {
return apis.isOpen(toolbar);
},
getOverflow: function (apis, toolbar) {
return apis.getOverflow(toolbar);
}
}
});
var getAnimationRoot = function (component, slideConfig) {
return slideConfig.getAnimationRoot.fold(function () {
return component.element;
}, function (get) {
return get(component);
});
};
var getDimensionProperty = function (slideConfig) {
return slideConfig.dimension.property;
};
var getDimension = function (slideConfig, elem) {
return slideConfig.dimension.getDimension(elem);
};
var disableTransitions = function (component, slideConfig) {
var root = getAnimationRoot(component, slideConfig);
remove$5(root, [
slideConfig.shrinkingClass,
slideConfig.growingClass
]);
};
var setShrunk = function (component, slideConfig) {
remove$4(component.element, slideConfig.openClass);
add$2(component.element, slideConfig.closedClass);
set$2(component.element, getDimensionProperty(slideConfig), '0px');
reflow(component.element);
};
var setGrown = function (component, slideConfig) {
remove$4(component.element, slideConfig.closedClass);
add$2(component.element, slideConfig.openClass);
remove$6(component.element, getDimensionProperty(slideConfig));
};
var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
slideState.setCollapsed();
set$2(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
reflow(component.element);
disableTransitions(component, slideConfig);
setShrunk(component, slideConfig);
slideConfig.onStartShrink(component);
slideConfig.onShrunk(component);
};
var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
var size = calculatedSize.getOrThunk(function () {
return getDimension(slideConfig, component.element);
});
slideState.setCollapsed();
set$2(component.element, getDimensionProperty(slideConfig), size);
reflow(component.element);
var root = getAnimationRoot(component, slideConfig);
remove$4(root, slideConfig.growingClass);
add$2(root, slideConfig.shrinkingClass);
setShrunk(component, slideConfig);
slideConfig.onStartShrink(component);
};
var doStartSmartShrink = function (component, slideConfig, slideState) {
var size = getDimension(slideConfig, component.element);
var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
shrinker(component, slideConfig, slideState, Optional.some(size));
};
var doStartGrow = function (component, slideConfig, slideState) {
var root = getAnimationRoot(component, slideConfig);
var wasShrinking = has$2(root, slideConfig.shrinkingClass);
var beforeSize = getDimension(slideConfig, component.element);
setGrown(component, slideConfig);
var fullSize = getDimension(slideConfig, component.element);
var startPartialGrow = function () {
set$2(component.element, getDimensionProperty(slideConfig), beforeSize);
reflow(component.element);
};
var startCompleteGrow = function () {
setShrunk(component, slideConfig);
};
var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
setStartSize();
remove$4(root, slideConfig.shrinkingClass);
add$2(root, slideConfig.growingClass);
setGrown(component, slideConfig);
set$2(component.element, getDimensionProperty(slideConfig), fullSize);
slideState.setExpanded();
slideConfig.onStartGrow(component);
};
var refresh$2 = function (component, slideConfig, slideState) {
if (slideState.isExpanded()) {
remove$6(component.element, getDimensionProperty(slideConfig));
var fullSize = getDimension(slideConfig, component.element);
set$2(component.element, getDimensionProperty(slideConfig), fullSize);
}
};
var grow = function (component, slideConfig, slideState) {
if (!slideState.isExpanded()) {
doStartGrow(component, slideConfig, slideState);
}
};
var shrink = function (component, slideConfig, slideState) {
if (slideState.isExpanded()) {
doStartSmartShrink(component, slideConfig, slideState);
}
};
var immediateShrink = function (component, slideConfig, slideState) {
if (slideState.isExpanded()) {
doImmediateShrink(component, slideConfig, slideState, Optional.none());
}
};
var hasGrown = function (component, slideConfig, slideState) {
return slideState.isExpanded();
};
var hasShrunk = function (component, slideConfig, slideState) {
return slideState.isCollapsed();
};
var isGrowing = function (component, slideConfig, _slideState) {
var root = getAnimationRoot(component, slideConfig);
return has$2(root, slideConfig.growingClass) === true;
};
var isShrinking = function (component, slideConfig, _slideState) {
var root = getAnimationRoot(component, slideConfig);
return has$2(root, slideConfig.shrinkingClass) === true;
};
var isTransitioning = function (component, slideConfig, slideState) {
return isGrowing(component, slideConfig) || isShrinking(component, slideConfig);
};
var toggleGrow = function (component, slideConfig, slideState) {
var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
f(component, slideConfig, slideState);
};
var SlidingApis = /*#__PURE__*/Object.freeze({
__proto__: null,
refresh: refresh$2,
grow: grow,
shrink: shrink,
immediateShrink: immediateShrink,
hasGrown: hasGrown,
hasShrunk: hasShrunk,
isGrowing: isGrowing,
isShrinking: isShrinking,
isTransitioning: isTransitioning,
toggleGrow: toggleGrow,
disableTransitions: disableTransitions
});
var exhibit$6 = function (base, slideConfig, _slideState) {
var expanded = slideConfig.expanded;
return expanded ? nu$6({
classes: [slideConfig.openClass],
styles: {}
}) : nu$6({
classes: [slideConfig.closedClass],
styles: wrap$1(slideConfig.dimension.property, '0px')
});
};
var events$d = function (slideConfig, slideState) {
return derive([runOnSource(transitionend(), function (component, simulatedEvent) {
var raw = simulatedEvent.event.raw;
if (raw.propertyName === slideConfig.dimension.property) {
disableTransitions(component, slideConfig);
if (slideState.isExpanded()) {
remove$6(component.element, slideConfig.dimension.property);
}
var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
notify(component);
}
})]);
};
var ActiveSliding = /*#__PURE__*/Object.freeze({
__proto__: null,
exhibit: exhibit$6,
events: events$d
});
var SlidingSchema = [
strict$1('closedClass'),
strict$1('openClass'),
strict$1('shrinkingClass'),
strict$1('growingClass'),
option('getAnimationRoot'),
onHandler('onShrunk'),
onHandler('onStartShrink'),
onHandler('onGrown'),
onHandler('onStartGrow'),
defaulted$1('expanded', false),
strictOf('dimension', choose$1('property', {
width: [
output('property', 'width'),
output('getDimension', function (elem) {
return get$8(elem) + 'px';
})
],
height: [
output('property', 'height'),
output('getDimension', function (elem) {
return get$7(elem) + 'px';
})
]
}))
];
var init$9 = function (spec) {
var state = Cell(spec.expanded);
var readState = function () {
return 'expanded: ' + state.get();
};
return nu$5({
isExpanded: function () {
return state.get() === true;
},
isCollapsed: function () {
return state.get() === false;
},
setCollapsed: curry(state.set, false),
setExpanded: curry(state.set, true),
readState: readState
});
};
var SlidingState = /*#__PURE__*/Object.freeze({
__proto__: null,
init: init$9
});
var Sliding = create$1({
fields: SlidingSchema,
name: 'sliding',
active: ActiveSliding,
apis: SlidingApis,
state: SlidingState
});
var schema$p = constant([
markers([
'closedClass',
'openClass',
'shrinkingClass',
'growingClass',
'overflowToggledClass'
]),
onHandler('onOpened'),
onHandler('onClosed')
].concat(schema$l()));
var parts$b = constant([
required({
factory: Toolbar,
schema: schema$k(),
name: 'primary'
}),
required({
factory: Toolbar,
schema: schema$k(),
name: 'overflow',
overrides: function (detail) {
return {
toolbarBehaviours: derive$1([
Sliding.config({
dimension: { property: 'height' },
closedClass: detail.markers.closedClass,
openClass: detail.markers.openClass,
shrinkingClass: detail.markers.shrinkingClass,
growingClass: detail.markers.growingClass,
onShrunk: function (comp) {
getPart(comp, detail, 'overflow-button').each(function (button) {
Toggling.off(button);
Focusing.focus(button);
});
detail.onClosed(comp);
},
onGrown: function (comp) {
Keying.focusIn(comp);
detail.onOpened(comp);
},
onStartGrow: function (comp) {
getPart(comp, detail, 'overflow-button').each(Toggling.on);
}
}),
Keying.config({
mode: 'acyclic',
onEscape: function (comp) {
getPart(comp, detail, 'overflow-button').each(Focusing.focus);
return Optional.some(true);
}
})
])
};
}
}),
external$1({
name: 'overflow-button',
overrides: function (detail) {
return {
buttonBehaviours: derive$1([Toggling.config({
toggleClass: detail.markers.overflowToggledClass,
aria: { mode: 'pressed' },
toggleOnExecute: false
})])
};
}
}),
external$1({ name: 'overflow-group' })
]);
var isOpen$1 = function (toolbar, detail) {
return getPart(toolbar, detail, 'overflow').map(Sliding.hasGrown).getOr(false);
};
var toggleToolbar = function (toolbar, detail) {
getPart(toolbar, detail, 'overflow-button').bind(function () {
return getPart(toolbar, detail, 'overflow');
}).each(function (overf) {
refresh$3(toolbar, detail);
Sliding.toggleGrow(overf);
});
};
var refresh$3 = function (toolbar, detail) {
getPart(toolbar, detail, 'overflow').each(function (overflow) {
refresh(toolbar, detail, function (groups) {
var builtGroups = map(groups, function (g) {
return premade$1(g);
});
Toolbar.setGroups(overflow, builtGroups);
});
getPart(toolbar, detail, 'overflow-button').each(function (button) {
if (Sliding.hasGrown(overflow)) {
Toggling.on(button);
}
});
Sliding.refresh(overflow);
});
};
var factory$d = function (detail, components, spec, externals) {
var toolbarToggleEvent = 'alloy.toolbar.toggle';
var doSetGroups = function (toolbar, groups) {
var built = map(groups, toolbar.getSystem().build);
detail.builtGroups.set(built);
};
return {
uid: detail.uid,
dom: detail.dom,
components: components,
behaviours: augment(detail.splitToolbarBehaviours, [
Coupling.config({
others: {
overflowGroup: function (toolbar) {
return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), {
items: [Button.sketch(__assign(__assign({}, externals['overflow-button']()), {
action: function (_button) {
emit(toolbar, toolbarToggleEvent);
}
}))]
}));
}
}
}),
config('toolbar-toggle-events', [run(toolbarToggleEvent, function (toolbar) {
toggleToolbar(toolbar, detail);
})])
]),
apis: {
setGroups: function (toolbar, groups) {
doSetGroups(toolbar, groups);
refresh$3(toolbar, detail);
},
refresh: function (toolbar) {
return refresh$3(toolbar, detail);
},
toggle: function (toolbar) {
return toggleToolbar(toolbar, detail);
},
isOpen: function (toolbar) {
return isOpen$1(toolbar, detail);
}
},
domModification: { attributes: { role: 'group' } }
};
};
var SplitSlidingToolbar = composite$1({
name: 'SplitSlidingToolbar',
configFields: schema$p(),
partFields: parts$b(),
factory: factory$d,
apis: {
setGroups: function (apis, toolbar, groups) {
apis.setGroups(toolbar, groups);
},
refresh: function (apis, toolbar) {
apis.refresh(toolbar);
},
toggle: function (apis, toolbar) {
apis.toggle(toolbar);
},
isOpen: function (apis, toolbar) {
return apis.isOpen(toolbar);
}
}
});
var toolbarHeightChange = constant(generate$1('toolbar-height-change'));
var renderToolbarGroupCommon = function (toolbarGroup) {
var attributes = toolbarGroup.title.fold(function () {
return {};
}, function (title) {
return { attributes: { title: title } };
});
return {
dom: __assign({
tag: 'div',
classes: ['tox-toolbar__group']
}, attributes),
components: [ToolbarGroup.parts.items({})],
items: toolbarGroup.items,
markers: { itemSelector: '*:not(.tox-split-button) > .tox-tbtn:not([disabled]), ' + '.tox-split-button:not([disabled]), ' + '.tox-toolbar-nav-js:not([disabled])' },
tgroupBehaviours: derive$1([
Tabstopping.config({}),
Focusing.config({})
])
};
};
var renderToolbarGroup = function (toolbarGroup) {
return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
};
var getToolbarbehaviours = function (toolbarSpec, modeName) {
var onAttached = runOnAttached(function (component) {
var groups = map(toolbarSpec.initGroups, renderToolbarGroup);
Toolbar.setGroups(component, groups);
});
return derive$1([
DisablingConfigs.toolbarButton(toolbarSpec.providers.isDisabled),
receivingConfig(),
Keying.config({
mode: modeName,
onEscape: toolbarSpec.onEscape,
selector: '.tox-toolbar__group'
}),
config('toolbar-events', [onAttached])
]);
};
var renderMoreToolbarCommon = function (toolbarSpec) {
var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
return {
uid: toolbarSpec.uid,
dom: {
tag: 'div',
classes: ['tox-toolbar-overlord']
},
parts: {
'overflow-group': renderToolbarGroupCommon({
title: Optional.none(),
items: []
}),
'overflow-button': renderIconButtonSpec({
name: 'more',
icon: Optional.some('more-drawer'),
disabled: false,
tooltip: Optional.some('More...'),
primary: false,
borderless: false
}, Optional.none(), toolbarSpec.providers)
},
splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
};
};
var renderFloatingMoreToolbar = function (toolbarSpec) {
var baseSpec = renderMoreToolbarCommon(toolbarSpec);
var overflowXOffset = 4;
var primary = SplitFloatingToolbar.parts.primary({
dom: {
tag: 'div',
classes: ['tox-toolbar__primary']
}
});
return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), {
lazySink: toolbarSpec.getSink,
getOverflowBounds: function () {
var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element;
var headerBounds = absolute$1(headerElem);
var docElem = documentElement(headerElem);
var docBounds = absolute$1(docElem);
var height = Math.max(docElem.dom.scrollHeight, docBounds.height);
return bounds$1(headerBounds.x + overflowXOffset, docBounds.y, headerBounds.width - overflowXOffset * 2, height);
},
parts: __assign(__assign({}, baseSpec.parts), {
overflow: {
dom: {
tag: 'div',
classes: ['tox-toolbar__overflow'],
attributes: toolbarSpec.attributes
}
}
}),
components: [primary],
markers: { overflowToggledClass: 'tox-tbtn--enabled' }
}));
};
var renderSlidingMoreToolbar = function (toolbarSpec) {
var primary = SplitSlidingToolbar.parts.primary({
dom: {
tag: 'div',
classes: ['tox-toolbar__primary']
}
});
var overflow = SplitSlidingToolbar.parts.overflow({
dom: {
tag: 'div',
classes: ['tox-toolbar__overflow']
}
});
var baseSpec = renderMoreToolbarCommon(toolbarSpec);
return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), {
components: [
primary,
overflow
],
markers: {
openClass: 'tox-toolbar__overflow--open',
closedClass: 'tox-toolbar__overflow--closed',
growingClass: 'tox-toolbar__overflow--growing',
shrinkingClass: 'tox-toolbar__overflow--shrinking',
overflowToggledClass: 'tox-tbtn--enabled'
},
onOpened: function (comp) {
comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'opened' });
},
onClosed: function (comp) {
comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'closed' });
}
}));
};
var renderToolbar = function (toolbarSpec) {
var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
return Toolbar.sketch({
uid: toolbarSpec.uid,
dom: {
tag: 'div',
classes: ['tox-toolbar'].concat(toolbarSpec.type === ToolbarMode.scrolling ? ['tox-toolbar--scrolling'] : [])
},
components: [Toolbar.parts.groups({})],
toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
});
};
var groupToolbarButtonSchema = objOf([
strictString('type'),
strictOf('items', oneOf([
arrOfObj$1([
strictString('name'),
strictArrayOf('items', string)
]),
string
]))
].concat(baseToolbarButtonFields));
var createGroupToolbarButton = function (spec) {
return asRaw('GroupToolbarButton', groupToolbarButtonSchema, spec);
};
var baseMenuButtonFields = [
optionString('text'),
optionString('tooltip'),
optionString('icon'),
strictFunction('fetch'),
defaultedFunction('onSetup', function () {
return noop;
})
];
var MenuButtonSchema = objOf(__spreadArrays([strictString('type')], baseMenuButtonFields));
var createMenuButton = function (spec) {
return asRaw('menubutton', MenuButtonSchema, spec);
};
var splitButtonSchema = objOf([
strictString('type'),
optionString('tooltip'),
optionString('icon'),
optionString('text'),
optionFunction('select'),
strictFunction('fetch'),
defaultedFunction('onSetup', function () {
return noop;
}),
defaultedStringEnum('presets', 'normal', [
'normal',
'color',
'listpreview'
]),
defaulted$1('columns', 1),
strictFunction('onAction'),
strictFunction('onItemAction')
]);
var createSplitButton = function (spec) {
return asRaw('SplitButton', splitButtonSchema, spec);
};
var events$e = function (reflectingConfig, reflectingState) {
var update = function (component, data) {
reflectingConfig.updateState.each(function (updateState) {
var newState = updateState(component, data);
reflectingState.set(newState);
});
reflectingConfig.renderComponents.each(function (renderComponents) {
var newComponents = renderComponents(data, reflectingState.get());
var newChildren = map(newComponents, component.getSystem().build);
replaceChildren(component, newChildren);
});
};
return derive([
run(receive(), function (component, message) {
var receivingData = message;
if (!receivingData.universal) {
var channel = reflectingConfig.channel;
if (contains(receivingData.channels, channel)) {
update(component, receivingData.data);
}
}
}),
runOnAttached(function (comp, _se) {
reflectingConfig.initialData.each(function (rawData) {
update(comp, rawData);
});
})
]);
};
var ActiveReflecting = /*#__PURE__*/Object.freeze({
__proto__: null,
events: events$e
});
var getState$2 = function (component, replaceConfig, reflectState) {
return reflectState;
};
var ReflectingApis = /*#__PURE__*/Object.freeze({
__proto__: null,
getState: getState$2
});
var ReflectingSchema = [
strict$1('channel'),
option('renderComponents'),
option('updateState'),
option('initialData')
];
var init$a = function () {
var cell = Cell(Optional.none());
var set = function (optS) {
return cell.set(optS);
};
var clear = function () {
return cell.set(Optional.none());
};
var get = function () {
return cell.get();
};
var readState = function () {
return cell.get().fold(function () {
return 'none';
}, function (x) {
return x;
});
};
return {
readState: readState,
get: get,
set: set,
clear: clear
};
};
var ReflectingState = /*#__PURE__*/Object.freeze({
__proto__: null,
init: init$a
});
var Reflecting = create$1({
fields: ReflectingSchema,
name: 'reflecting',
active: ActiveReflecting,
apis: ReflectingApis,
state: ReflectingState
});
var schema$q = constant([
strict$1('toggleClass'),
strict$1('fetch'),
onStrictHandler('onExecute'),
defaulted$1('getHotspot', Optional.some),
defaulted$1('getAnchorOverrides', constant({})),
schema$1(),
onStrictHandler('onItemExecute'),
option('lazySink'),
strict$1('dom'),
onHandler('onOpen'),
field$1('splitDropdownBehaviours', [
Coupling,
Keying,
Focusing
]),
defaulted$1('matchWidth', false),
defaulted$1('useMinWidth', false),
defaulted$1('eventOrder', {}),
option('role')
].concat(sandboxFields()));
var arrowPart = required({
factory: Button,
schema: [strict$1('dom')],
name: 'arrow',
defaults: function () {
return { buttonBehaviours: derive$1([Focusing.revoke()]) };
},
overrides: function (detail) {
return {
dom: {
tag: 'span',
attributes: { role: 'presentation' }
},
action: function (arrow) {
arrow.getSystem().getByUid(detail.uid).each(emitExecute);
},
buttonBehaviours: derive$1([Toggling.config({
toggleOnExecute: false,
toggleClass: detail.toggleClass
})])
};
}
});
var buttonPart = required({
factory: Button,
schema: [strict$1('dom')],
name: 'button',
defaults: function () {
return { buttonBehaviours: derive$1([Focusing.revoke()]) };
},
overrides: function (detail) {
return {
dom: {
tag: 'span',
attributes: { role: 'presentation' }
},
action: function (btn) {
btn.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
detail.onExecute(splitDropdown, btn);
});
}
};
}
});
var parts$c = constant([
arrowPart,
buttonPart,
optional({
factory: {
sketch: function (spec) {
return {
uid: spec.uid,
dom: {
tag: 'span',
styles: { display: 'none' },
attributes: { 'aria-hidden': 'true' },
innerHtml: spec.text
}
};
}
},
schema: [strict$1('text')],
name: 'aria-descriptor'
}),
external$1({
schema: [tieredMenuMarkers()],
name: 'menu',
defaults: function (detail) {
return {
onExecute: function (tmenu, item) {
tmenu.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
detail.onItemExecute(splitDropdown, tmenu, item);
});
}
};
}
}),
partType()
]);
var factory$e = function (detail, components, spec, externals) {
var _a;
var switchToMenu = function (sandbox) {
Composing.getCurrent(sandbox).each(function (current) {
Highlighting.highlightFirst(current);
Keying.focusIn(current);
});
};
var action = function (component) {
var onOpenSync = switchToMenu;
togglePopup(detail, function (x) {
return x;
}, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
};
var openMenu = function (comp) {
action(comp);
return Optional.some(true);
};
var executeOnButton = function (comp) {
var button = getPartOrDie(comp, detail, 'button');
emitExecute(button);
return Optional.some(true);
};
var buttonEvents = __assign(__assign({}, derive([runOnAttached(function (component, _simulatedEvent) {
var ariaDescriptor = getPart(component, detail, 'aria-descriptor');
ariaDescriptor.each(function (descriptor) {
var descriptorId = generate$1('aria');
set$1(descriptor.element, 'id', descriptorId);
set$1(component.element, 'aria-describedby', descriptorId);
});
})])), events$7(Optional.some(action)));
var apis = {
repositionMenus: function (comp) {
if (Toggling.isOn(comp)) {
repositionMenus(comp);
}
}
};
return {
uid: detail.uid,
dom: detail.dom,
components: components,
apis: apis,
eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute()] = [
'disabling',
'toggling',
'alloy.base.behaviour'
], _a)),
events: buttonEvents,
behaviours: augment(detail.splitDropdownBehaviours, [
Coupling.config({
others: {
sandbox: function (hotspot) {
var arrow = getPartOrDie(hotspot, detail, 'arrow');
var extras = {
onOpen: function () {
Toggling.on(arrow);
Toggling.on(hotspot);
},
onClose: function () {
Toggling.off(arrow);
Toggling.off(hotspot);
}
};
return makeSandbox(detail, hotspot, extras);
}
}
}),
Keying.config({
mode: 'special',
onSpace: executeOnButton,
onEnter: executeOnButton,
onDown: openMenu
}),
Focusing.config({}),
Toggling.config({
toggleOnExecute: false,
aria: { mode: 'expanded' }
})
]),
domModification: {
attributes: {
'role': detail.role.getOr('button'),
'aria-haspopup': true
}
}
};
};
var SplitDropdown = composite$1({
name: 'SplitDropdown',
configFields: schema$q(),
partFields: parts$c(),
factory: factory$e,
apis: {
repositionMenus: function (apis, comp) {
return apis.repositionMenus(comp);
}
}
});
var getButtonApi = function (component) {
return {
isDisabled: function () {
return Disabling.isDisabled(component);
},
setDisabled: function (state) {
return Disabling.set(component, state);
}
};
};
var getToggleApi = function (component) {
return {
setActive: function (state) {
Toggling.set(component, state);
},
isActive: function () {
return Toggling.isOn(component);
},
isDisabled: function () {
return Disabling.isDisabled(component);
},
setDisabled: function (state) {
return Disabling.set(component, state);
}
};
};
var getTooltipAttributes = function (tooltip, providersBackstage) {
return tooltip.map(function (tooltip) {
return {
'aria-label': providersBackstage.translate(tooltip),
'title': providersBackstage.translate(tooltip)
};
}).getOr({});
};
var focusButtonEvent = generate$1('focus-button');
var rtlIcon$1 = [
'checklist',
'ordered-list'
];
var rtlTransform$1 = [
'indent',
'outdent',
'table-insert-column-after',
'table-insert-column-before',
'unordered-list'
];
var renderCommonStructure = function (icon, text, tooltip, receiver, behaviours, providersBackstage) {
var _d;
var getIconName = function (iconName) {
return global$6.isRtl() && contains(rtlIcon$1, iconName) ? iconName + '-rtl' : iconName;
};
var needsRtlClass = global$6.isRtl() && icon.exists(function (name) {
return contains(rtlTransform$1, name);
});
return {
dom: {
tag: 'button',
classes: ['tox-tbtn'].concat(text.isSome() ? ['tox-tbtn--select'] : []).concat(needsRtlClass ? ['tox-tbtn__icon-rtl'] : []),
attributes: getTooltipAttributes(tooltip, providersBackstage)
},
components: componentRenderPipeline([
icon.map(function (iconName) {
return renderIconFromPack(getIconName(iconName), providersBackstage.icons);
}),
text.map(function (text) {
return renderLabel$1(text, 'tox-tbtn', providersBackstage);
})
]),
eventOrder: (_d = {}, _d[mousedown()] = [
'focusing',
'alloy.base.behaviour',
'common-button-display-events'
], _d),
buttonBehaviours: derive$1([
DisablingConfigs.toolbarButton(providersBackstage.isDisabled),
receivingConfig(),
config('common-button-display-events', [run(mousedown(), function (button, se) {
se.event.prevent();
emit(button, focusButtonEvent);
})])
].concat(receiver.map(function (r) {
return Reflecting.config({
channel: r,
initialData: {
icon: icon,
text: text
},
renderComponents: function (data, _state) {
return componentRenderPipeline([
data.icon.map(function (iconName) {
return renderIconFromPack(getIconName(iconName), providersBackstage.icons);
}),
data.text.map(function (text) {
return renderLabel$1(text, 'tox-tbtn', providersBackstage);
})
]);
}
});
}).toArray()).concat(behaviours.getOr([])))
};
};
var renderFloatingToolbarButton = function (spec, backstage, identifyButtons, attributes) {
var sharedBackstage = backstage.shared;
return FloatingToolbarButton.sketch({
lazySink: sharedBackstage.getSink,
fetch: function () {
return Future.nu(function (resolve) {
resolve(map(identifyButtons(spec.items), renderToolbarGroup));
});
},
markers: { toggledClass: 'tox-tbtn--enabled' },
parts: {
button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), sharedBackstage.providers),
toolbar: {
dom: {
tag: 'div',
classes: ['tox-toolbar__overflow'],
attributes: attributes
}
}
}
});
};
var renderCommonToolbarButton = function (spec, specialisation, providersBackstage) {
var editorOffCell = Cell(noop);
var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), providersBackstage);
return Button.sketch({
dom: structure.dom,
components: structure.components,
eventOrder: toolbarButtonEventOrder,
buttonBehaviours: derive$1([
config('toolbar-button-events', [
onToolbarButtonExecute({
onAction: spec.onAction,
getApi: specialisation.getApi
}),
onControlAttached(specialisation, editorOffCell),
onControlDetached(specialisation, editorOffCell)
]),
DisablingConfigs.toolbarButton(function () {
return spec.disabled || providersBackstage.isDisabled();
}),
receivingConfig()
].concat(specialisation.toolbarButtonBehaviours))
});
};
var renderToolbarButton = function (spec, providersBackstage) {
return renderToolbarButtonWith(spec, providersBackstage, []);
};
var renderToolbarButtonWith = function (spec, providersBackstage, bonusEvents) {
return renderCommonToolbarButton(spec, {
toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config('toolbarButtonWith', bonusEvents)] : []),
getApi: getButtonApi,
onSetup: spec.onSetup
}, providersBackstage);
};
var renderToolbarToggleButton = function (spec, providersBackstage) {
return renderToolbarToggleButtonWith(spec, providersBackstage, []);
};
var renderToolbarToggleButtonWith = function (spec, providersBackstage, bonusEvents) {
return deepMerge(renderCommonToolbarButton(spec, {
toolbarButtonBehaviours: [
Replacing.config({}),
Toggling.config({
toggleClass: 'tox-tbtn--enabled',
aria: { mode: 'pressed' },
toggleOnExecute: false
})
].concat(bonusEvents.length > 0 ? [config('toolbarToggleButtonWith', bonusEvents)] : []),
getApi: getToggleApi,
onSetup: spec.onSetup
}, providersBackstage));
};
var fetchChoices = function (getApi, spec, providersBackstage) {
return function (comp) {
return Future.nu(function (callback) {
return spec.fetch(callback);
}).map(function (items) {
return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
spec.onItemAction(getApi(comp), value);
}, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(never), providersBackstage), {
movement: deriveMenuMovement(spec.columns, spec.presets),
menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
detectSize(comp, 4, classForPreset(spec.presets)).each(function (_d) {
var numRows = _d.numRows, numColumns = _d.numColumns;
Keying.setGridSize(comp, numRows, numColumns);
});
})])
})));
});
};
};
var renderSplitButton = function (spec, sharedBackstage) {
var _d;
var displayChannel = generate$1('channel-update-split-dropdown-display');
var getApi = function (comp) {
return {
isDisabled: function () {
return Disabling.isDisabled(comp);
},
setDisabled: function (state) {
return Disabling.set(comp, state);
},
setIconFill: function (id, value) {
descendant$1(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
set$1(underlinePath, 'fill', value);
});
},
setIconStroke: function (id, value) {
descendant$1(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
set$1(underlinePath, 'stroke', value);
});
},
setActive: function (state) {
if (comp.getSystem().isConnected()) {
set$1(comp.element, 'aria-pressed', state);
descendant$1(comp.element, 'span').each(function (button) {
comp.getSystem().getByDom(button).each(function (buttonComp) {
return Toggling.set(buttonComp, state);
});
});
}
},
isActive: function () {
return descendant$1(comp.element, 'span').exists(function (button) {
if (comp.getSystem().isConnected()) {
return comp.getSystem().getByDom(button).exists(Toggling.isOn);
} else {
return false;
}
});
}
};
};
var editorOffCell = Cell(noop);
var specialisation = {
getApi: getApi,
onSetup: spec.onSetup
};
return SplitDropdown.sketch({
dom: {
tag: 'div',
classes: ['tox-split-button'],
attributes: __assign({ 'aria-pressed': false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers))
},
onExecute: function (button) {
spec.onAction(getApi(button));
},
onItemExecute: function (_a, _b, _c) {
},
splitDropdownBehaviours: derive$1([
DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
receivingConfig(),
config('split-dropdown-events', [
run(focusButtonEvent, Focusing.focus),
onControlAttached(specialisation, editorOffCell),
onControlDetached(specialisation, editorOffCell)
]),
Unselecting.config({})
]),
eventOrder: (_d = {}, _d[attachedToDom()] = [
'alloy.base.behaviour',
'split-dropdown-events'
], _d),
toggleClass: 'tox-tbtn--enabled',
lazySink: sharedBackstage.getSink,
fetch: fetchChoices(getApi, spec, sharedBackstage.providers),
parts: { menu: part(false, spec.columns, spec.presets) },
components: [
SplitDropdown.parts.button(renderCommonStructure(spec.icon, spec.text, Optional.none(), Optional.some(displayChannel), Optional.some([Toggling.config({
toggleClass: 'tox-tbtn--enabled',
toggleOnExecute: false
})]), sharedBackstage.providers)),
SplitDropdown.parts.arrow({
dom: {
tag: 'button',
classes: [
'tox-tbtn',
'tox-split-button__chevron'
],
innerHtml: get$e('chevron-down', sharedBackstage.providers.icons)
},
buttonBehaviours: derive$1([
DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
receivingConfig()
])
}),
SplitDropdown.parts['aria-descriptor']({ text: sharedBackstage.providers.translate('To open the popup, press Shift+Enter') })
]
});
};
var getFormApi = function (input) {
return {
hide: function () {
return emit(input, sandboxClose());
},
getValue: function () {
return Representing.getValue(input);
}
};
};
var runOnExecute$1 = function (memInput, original) {
return run(internalToolbarButtonExecute, function (comp, se) {
var input = memInput.get(comp);
var formApi = getFormApi(input);
original.onAction(formApi, se.event.buttonApi);
});
};
var renderContextButton = function (memInput, button, extras) {
var _a = button.original, primary = _a.primary, rest = __rest(_a, ['primary']);
var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), {
type: 'button',
onAction: noop
})));
return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute$1(memInput, button)]);
};
var renderContextToggleButton = function (memInput, button, extras) {
var _a = button.original, primary = _a.primary, rest = __rest(_a, ['primary']);
var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), {
type: 'togglebutton',
onAction: noop
})));
return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute$1(memInput, button)]);
};
var generateOne$1 = function (memInput, button, providersBackstage) {
var extras = { backstage: { shared: { providers: providersBackstage } } };
if (button.type === 'contextformtogglebutton') {
return renderContextToggleButton(memInput, button, extras);
} else {
return renderContextButton(memInput, button, extras);
}
};
var generate$7 = function (memInput, buttons, providersBackstage) {
var mementos = map(buttons, function (button) {
return record(generateOne$1(memInput, button, providersBackstage));
});
var asSpecs = function () {
return map(mementos, function (mem) {
return mem.asSpec();
});
};
var findPrimary = function (compInSystem) {
return findMap(buttons, function (button, i) {
if (button.primary) {
return Optional.from(mementos[i]).bind(function (mem) {
return mem.getOpt(compInSystem);
}).filter(not(Disabling.isDisabled));
} else {
return Optional.none();
}
});
};
return {
asSpecs: asSpecs,
findPrimary: findPrimary
};
};
var buildInitGroups = function (ctx, providers) {
var inputAttributes = ctx.label.fold(function () {
return {};
}, function (label) {
return { 'aria-label': label };
});
var memInput = record(Input.sketch({
inputClasses: [
'tox-toolbar-textfield',
'tox-toolbar-nav-js'
],
data: ctx.initValue(),
inputAttributes: inputAttributes,
selectOnFocus: true,
inputBehaviours: derive$1([Keying.config({
mode: 'special',
onEnter: function (input) {
return commands.findPrimary(input).map(function (primary) {
emitExecute(primary);
return true;
});
},
onLeft: function (comp, se) {
se.cut();
return Optional.none();
},
onRight: function (comp, se) {
se.cut();
return Optional.none();
}
})])
}));
var commands = generate$7(memInput, ctx.commands, providers);
return [
{
title: Optional.none(),
items: [memInput.asSpec()]
},
{
title: Optional.none(),
items: commands.asSpecs()
}
];
};
var renderContextForm = function (toolbarType, ctx, providers) {
return renderToolbar({
type: toolbarType,
uid: generate$1('context-toolbar'),
initGroups: buildInitGroups(ctx, providers),
onEscape: Optional.none,
cyclicKeying: true,
providers: providers
});
};
var ContextForm = {
renderContextForm: renderContextForm,
buildInitGroups: buildInitGroups
};
var getHorizontalBounds = function (contentAreaBox, viewportBounds) {
var x = Math.max(viewportBounds.x, contentAreaBox.x);
var contentBoxWidth = contentAreaBox.right - x;
var maxViewportWidth = viewportBounds.width - (x - viewportBounds.x);
var width = Math.min(contentBoxWidth, maxViewportWidth);
return {
x: x,
width: width
};
};
var getVerticalBounds = function (editor, contentAreaBox, viewportBounds, isToolbarLocationTop) {
var container = SugarElement.fromDom(editor.getContainer());
var header = descendant$1(container, '.tox-editor-header').getOr(container);
var headerBox = box(header);
var isToolbarBelowContentArea = headerBox.y >= contentAreaBox.bottom;
var isToolbarAbove = isToolbarLocationTop && !isToolbarBelowContentArea;
if (editor.inline && isToolbarAbove) {
return {
y: Math.max(headerBox.bottom, viewportBounds.y),
bottom: viewportBounds.bottom
};
}
if (editor.inline && !isToolbarAbove) {
return {
y: viewportBounds.y,
bottom: Math.min(headerBox.y, viewportBounds.bottom)
};
}
var containerBounds = box(container);
if (isToolbarAbove) {
return {
y: Math.max(headerBox.bottom, viewportBounds.y),
bottom: Math.min(containerBounds.bottom, viewportBounds.bottom)
};
}
return {
y: Math.max(containerBounds.y, viewportBounds.y),
bottom: Math.min(headerBox.y, viewportBounds.bottom)
};
};
var getContextToolbarBounds = function (editor, sharedBackstage) {
var viewportBounds = getBounds(window);
var contentAreaBox = box(SugarElement.fromDom(editor.getContentAreaContainer()));
var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
var _a = getHorizontalBounds(contentAreaBox, viewportBounds), x = _a.x, width = _a.width;
if (editor.inline && !toolbarOrMenubarEnabled) {
return bounds$1(x, viewportBounds.y, width, viewportBounds.height);
} else {
var isToolbarTop = sharedBackstage.header.isPositionedAtTop();
var _b = getVerticalBounds(editor, contentAreaBox, viewportBounds, isToolbarTop), y = _b.y, bottom = _b.bottom;
return bounds$1(x, y, width, bottom - y);
}
};
var matchTargetWith = function (elem, candidates) {
var ctxs = filter(candidates, function (toolbarApi) {
return toolbarApi.predicate(elem.dom);
});
var _a = partition(ctxs, function (t) {
return t.type === 'contexttoolbar';
}), pass = _a.pass, fail = _a.fail;
return {
contextToolbars: pass,
contextForms: fail
};
};
var filterByPositionForStartNode = function (toolbars) {
if (toolbars.length <= 1) {
return toolbars;
} else {
var doesPositionExist = function (value) {
return exists(toolbars, function (t) {
return t.position === value;
});
};
var filterToolbarsByPosition = function (value) {
return filter(toolbars, function (t) {
return t.position === value;
});
};
var hasSelectionToolbars = doesPositionExist('selection');
var hasNodeToolbars = doesPositionExist('node');
if (hasSelectionToolbars || hasNodeToolbars) {
if (hasNodeToolbars && hasSelectionToolbars) {
var nodeToolbars = filterToolbarsByPosition('node');
var selectionToolbars = map(filterToolbarsByPosition('selection'), function (t) {
return __assign(__assign({}, t), { position: 'node' });
});
return nodeToolbars.concat(selectionToolbars);
} else {
return hasSelectionToolbars ? filterToolbarsByPosition('selection') : filterToolbarsByPosition('node');
}
} else {
return filterToolbarsByPosition('line');
}
}
};
var filterByPositionForAncestorNode = function (toolbars) {
if (toolbars.length <= 1) {
return toolbars;
} else {
var findPosition_1 = function (value) {
return find(toolbars, function (t) {
return t.position === value;
});
};
var basePosition = findPosition_1('selection').orThunk(function () {
return findPosition_1('node');
}).orThunk(function () {
return findPosition_1('line');
}).map(function (t) {
return t.position;
});
return basePosition.fold(function () {
return [];
}, function (pos) {
return filter(toolbars, function (t) {
return t.position === pos;
});
});
}
};
var matchStartNode = function (elem, nodeCandidates, editorCandidates) {
var nodeMatches = matchTargetWith(elem, nodeCandidates);
if (nodeMatches.contextForms.length > 0) {
return Optional.some({
elem: elem,
toolbars: [nodeMatches.contextForms[0]]
});
} else {
var editorMatches = matchTargetWith(elem, editorCandidates);
if (editorMatches.contextForms.length > 0) {
return Optional.some({
elem: elem,
toolbars: [editorMatches.contextForms[0]]
});
} else if (nodeMatches.contextToolbars.length > 0 || editorMatches.contextToolbars.length > 0) {
var toolbars = filterByPositionForStartNode(nodeMatches.contextToolbars.concat(editorMatches.contextToolbars));
return Optional.some({
elem: elem,
toolbars: toolbars
});
} else {
return Optional.none();
}
}
};
var matchAncestor = function (isRoot, startNode, scopes) {
if (isRoot(startNode)) {
return Optional.none();
} else {
return ancestor(startNode, function (ancestorElem) {
var _a = matchTargetWith(ancestorElem, scopes.inNodeScope), contextToolbars = _a.contextToolbars, contextForms = _a.contextForms;
var toolbars = contextForms.length > 0 ? contextForms : filterByPositionForAncestorNode(contextToolbars);
return toolbars.length > 0 ? Optional.some({
elem: ancestorElem,
toolbars: toolbars
}) : Optional.none();
}, isRoot);
}
};
var lookup$1 = function (scopes, editor) {
var rootElem = SugarElement.fromDom(editor.getBody());
var isRoot = function (elem) {
return eq$1(elem, rootElem);
};
var isOutsideRoot = function (startNode) {
return !isRoot(startNode) && !contains$2(rootElem, startNode);
};
var startNode = SugarElement.fromDom(editor.selection.getNode());
if (isOutsideRoot(startNode)) {
return Optional.none();
}
return matchStartNode(startNode, scopes.inNodeScope, scopes.inEditorScope).orThunk(function () {
return matchAncestor(isRoot, startNode, scopes);
});
};
var categorise = function (contextToolbars, navigate) {
var forms = {};
var inNodeScope = [];
var inEditorScope = [];
var formNavigators = {};
var lookupTable = {};
var registerForm = function (key, toolbarSpec) {
var contextForm = getOrDie(createContextForm(toolbarSpec));
forms[key] = contextForm;
contextForm.launch.map(function (launch) {
formNavigators['form:' + key + ''] = __assign(__assign({}, toolbarSpec.launch), {
type: launch.type === 'contextformtogglebutton' ? 'togglebutton' : 'button',
onAction: function () {
navigate(contextForm);
}
});
});
if (contextForm.scope === 'editor') {
inEditorScope.push(contextForm);
} else {
inNodeScope.push(contextForm);
}
lookupTable[key] = contextForm;
};
var registerToolbar = function (key, toolbarSpec) {
createContextToolbar(toolbarSpec).each(function (contextToolbar) {
if (toolbarSpec.scope === 'editor') {
inEditorScope.push(contextToolbar);
} else {
inNodeScope.push(contextToolbar);
}
lookupTable[key] = contextToolbar;
});
};
var keys$1 = keys(contextToolbars);
each(keys$1, function (key) {
var toolbarApi = contextToolbars[key];
if (toolbarApi.type === 'contextform') {
registerForm(key, toolbarApi);
} else if (toolbarApi.type === 'contexttoolbar') {
registerToolbar(key, toolbarApi);
}
});
return {
forms: forms,
inNodeScope: inNodeScope,
inEditorScope: inEditorScope,
lookupTable: lookupTable,
formNavigators: formNavigators
};
};
var forwardSlideEvent = generate$1('forward-slide');
var backSlideEvent = generate$1('backward-slide');
var changeSlideEvent = generate$1('change-slide-event');
var resizingClass = 'tox-pop--resizing';
var renderContextToolbar = function (spec) {
var stack = Cell([]);
return InlineView.sketch({
dom: {
tag: 'div',
classes: ['tox-pop']
},
fireDismissalEventInstead: { event: 'doNotDismissYet' },
onShow: function (comp) {
stack.set([]);
InlineView.getContent(comp).each(function (c) {
remove$6(c.element, 'visibility');
});
remove$4(comp.element, resizingClass);
remove$6(comp.element, 'width');
},
inlineBehaviours: derive$1([
config('context-toolbar-events', [
runOnSource(transitionend(), function (comp, _se) {
remove$4(comp.element, resizingClass);
remove$6(comp.element, 'width');
}),
run(changeSlideEvent, function (comp, se) {
var elem = comp.element;
remove$6(elem, 'width');
var currentWidth = get$8(elem);
InlineView.setContent(comp, se.event.contents);
add$2(elem, resizingClass);
var newWidth = get$8(elem);
set$2(elem, 'width', currentWidth + 'px');
InlineView.getContent(comp).each(function (newContents) {
se.event.focus.bind(function (f) {
focus$1(f);
return search(elem);
}).orThunk(function () {
Keying.focusIn(newContents);
return active(getRootNode(elem));
});
});
global$2.setTimeout(function () {
set$2(comp.element, 'width', newWidth + 'px');
}, 0);
}),
run(forwardSlideEvent, function (comp, se) {
InlineView.getContent(comp).each(function (oldContents) {
stack.set(stack.get().concat([{
bar: oldContents,
focus: active(getRootNode(comp.element))
}]));
});
emitWith(comp, changeSlideEvent, {
contents: se.event.forwardContents,
focus: Optional.none()
});
}),
run(backSlideEvent, function (comp, _se) {
last(stack.get()).each(function (last) {
stack.set(stack.get().slice(0, stack.get().length - 1));
emitWith(comp, changeSlideEvent, {
contents: premade$1(last.bar),
focus: last.focus
});
});
})
]),
Keying.config({
mode: 'special',
onEscape: function (comp) {
return last(stack.get()).fold(function () {
return spec.onEscape();
}, function (_) {
emit(comp, backSlideEvent);
return Optional.some(true);
});
}
})
]),
lazySink: function () {
return Result.value(spec.sink);
}
});
};
var generateSelectItems = function (_editor, backstage, spec) {
var generateItem = function (rawItem, response, disabled, value) {
var translatedText = backstage.shared.providers.translate(rawItem.title);
if (rawItem.type === 'separator') {
return Optional.some({
type: 'separator',
text: translatedText
});
} else if (rawItem.type === 'submenu') {
var items = bind(rawItem.getStyleItems(), function (si) {
return validate(si, response, value);
});
if (response === 0 && items.length <= 0) {
return Optional.none();
} else {
return Optional.some({
type: 'nestedmenuitem',
text: translatedText,
disabled: items.length <= 0,
getSubmenuItems: function () {
return bind(rawItem.getStyleItems(), function (si) {
return validate(si, response, value);
});
}
});
}
} else {
return Optional.some(__assign({
type: 'togglemenuitem',
text: translatedText,
icon: rawItem.icon,
active: rawItem.isSelected(value),
disabled: disabled,
onAction: spec.onAction(rawItem)
}, rawItem.getStylePreview().fold(function () {
return {};
}, function (preview) {
return { meta: { style: preview } };
})));
}
};
var validate = function (item, response, value) {
var invalid = item.type === 'formatter' && spec.isInvalid(item);
if (response === 0) {
return invalid ? [] : generateItem(item, response, false, value).toArray();
} else {
return generateItem(item, response, invalid, value).toArray();
}
};
var validateItems = function (preItems) {
var value = spec.getCurrentValue();
var response = spec.shouldHide ? 0 : 1;
return bind(preItems, function (item) {
return validate(item, response, value);
});
};
var getFetch = function (backstage, getStyleItems) {
return function (comp, callback) {
var preItems = getStyleItems();
var items = validateItems(preItems);
var menu = build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false);
callback(menu);
};
};
return {
validateItems: validateItems,
getFetch: getFetch
};
};
var createMenuItems = function (editor, backstage, spec) {
var dataset = spec.dataset;
var getStyleItems = dataset.type === 'basic' ? function () {
return map(dataset.data, function (d) {
return processBasic(d, spec.isSelectedFor, spec.getPreviewFor);
});
} : dataset.getData;
return {
items: generateSelectItems(editor, backstage, spec),
getStyleItems: getStyleItems
};
};
var createSelectButton = function (editor, backstage, spec) {
var _a = createMenuItems(editor, backstage, spec), items = _a.items, getStyleItems = _a.getStyleItems;
var getApi = function (comp) {
return { getComponent: constant(comp) };
};
var onSetup = function (api) {
var updateText = function () {
var comp = api.getComponent();
if (comp.getSystem().isConnected()) {
spec.updateText(comp);
}
};
updateText();
editor.on('NodeChange', updateText);
return function () {
editor.off('NodeChange', updateText);
};
};
return renderCommonDropdown({
text: spec.icon.isSome() ? Optional.none() : Optional.some(''),
icon: spec.icon,
tooltip: Optional.from(spec.tooltip),
role: Optional.none(),
fetch: items.getFetch(backstage, getStyleItems),
onSetup: onSetup,
getApi: getApi,
columns: 1,
presets: 'normal',
classes: spec.icon.isSome() ? [] : ['bespoke'],
dropdownBehaviours: []
}, 'tox-tbtn', backstage.shared);
};
var process = function (rawFormats) {
return map(rawFormats, function (item) {
var title = item, format = item;
var values = item.split('=');
if (values.length > 1) {
title = values[0];
format = values[1];
}
return {
title: title,
format: format
};
});
};
var buildBasicStaticDataset = function (data) {
return {
type: 'basic',
data: data
};
};
var Delimiter;
(function (Delimiter) {
Delimiter[Delimiter['SemiColon'] = 0] = 'SemiColon';
Delimiter[Delimiter['Space'] = 1] = 'Space';
}(Delimiter || (Delimiter = {})));
var split = function (rawFormats, delimiter) {
if (delimiter === Delimiter.SemiColon) {
return rawFormats.replace(/;$/, '').split(';');
} else {
return rawFormats.split(' ');
}
};
var buildBasicSettingsDataset = function (editor, settingName, defaults, delimiter) {
var rawFormats = editor.getParam(settingName, defaults, 'string');
var data = process(split(rawFormats, delimiter));
return {
type: 'basic',
data: data
};
};
var alignMenuItems = [
{
title: 'Left',
icon: 'align-left',
format: 'alignleft',
command: 'JustifyLeft'
},
{
title: 'Center',
icon: 'align-center',
format: 'aligncenter',
command: 'JustifyCenter'
},
{
title: 'Right',
icon: 'align-right',
format: 'alignright',
command: 'JustifyRight'
},
{
title: 'Justify',
icon: 'align-justify',
format: 'alignjustify',
command: 'JustifyFull'
}
];
var getSpec = function (editor) {
var getMatchingValue = function () {
return find(alignMenuItems, function (item) {
return editor.formatter.match(item.format);
});
};
var isSelectedFor = function (format) {
return function () {
return editor.formatter.match(format);
};
};
var getPreviewFor = function (_format) {
return function () {
return Optional.none();
};
};
var updateSelectMenuIcon = function (comp) {
var match = getMatchingValue();
var alignment = match.fold(function () {
return 'left';
}, function (item) {
return item.title.toLowerCase();
});
emitWith(comp, updateMenuIcon, { icon: 'align-' + alignment });
};
var dataset = buildBasicStaticDataset(alignMenuItems);
var onAction = function (rawItem) {
return function () {
return find(alignMenuItems, function (item) {
return item.format === rawItem.format;
}).each(function (item) {
return editor.execCommand(item.command);
});
};
};
return {
tooltip: 'Align',
icon: Optional.some('align-left'),
isSelectedFor: isSelectedFor,
getCurrentValue: Optional.none,
getPreviewFor: getPreviewFor,
onAction: onAction,
updateText: updateSelectMenuIcon,
dataset: dataset,
shouldHide: false,
isInvalid: function (item) {
return !editor.formatter.canApply(item.format);
}
};
};
var createAlignSelect = function (editor, backstage) {
return createSelectButton(editor, backstage, getSpec(editor));
};
var alignSelectMenu = function (editor, backstage) {
var menuItems = createMenuItems(editor, backstage, getSpec(editor));
editor.ui.registry.addNestedMenuItem('align', {
text: backstage.shared.providers.translate('Align'),
getSubmenuItems: function () {
return menuItems.items.validateItems(menuItems.getStyleItems());
}
});
};
var defaultFontsFormats = 'Andale Mono=andale mono,monospace;' + 'Arial=arial,helvetica,sans-serif;' + 'Arial Black=arial black,sans-serif;' + 'Book Antiqua=book antiqua,palatino,serif;' + 'Comic Sans MS=comic sans ms,sans-serif;' + 'Courier New=courier new,courier,monospace;' + 'Georgia=georgia,palatino,serif;' + 'Helvetica=helvetica,arial,sans-serif;' + 'Impact=impact,sans-serif;' + 'Symbol=symbol;' + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + 'Terminal=terminal,monaco,monospace;' + 'Times New Roman=times new roman,times,serif;' + 'Trebuchet MS=trebuchet ms,geneva,sans-serif;' + 'Verdana=verdana,geneva,sans-serif;' + 'Webdings=webdings;' + 'Wingdings=wingdings,zapf dingbats';
var systemStackFonts = [
'-apple-system',
'Segoe UI',
'Roboto',
'Helvetica Neue',
'sans-serif'
];
var splitFonts = function (fontFamily) {
var fonts = fontFamily.split(/\s*,\s*/);
return map(fonts, function (font) {
return font.replace(/^['"]+|['"]+$/g, '');
});
};
var isSystemFontStack = function (fontFamily) {
var matchesSystemStack = function () {
var fonts = splitFonts(fontFamily.toLowerCase());
return forall(systemStackFonts, function (font) {
return fonts.indexOf(font.toLowerCase()) > -1;
});
};
return fontFamily.indexOf('-apple-system') === 0 && matchesSystemStack();
};
var getSpec$1 = function (editor) {
var getMatchingValue = function () {
var getFirstFont = function (fontFamily) {
return fontFamily ? splitFonts(fontFamily)[0] : '';
};
var fontFamily = editor.queryCommandValue('FontName');
var items = dataset.data;
var font = fontFamily ? fontFamily.toLowerCase() : '';
var matchOpt = find(items, function (item) {
var format = item.format;
return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase();
}).orThunk(function () {
if (isSystemFontStack(font)) {
return Optional.from({
title: 'System Font',
format: font
});
} else {
return Optional.none();
}
});
return {
matchOpt: matchOpt,
font: fontFamily
};
};
var isSelectedFor = function (item) {
return function (valueOpt) {
return valueOpt.exists(function (value) {
return value.format === item;
});
};
};
var getCurrentValue = function () {
var matchOpt = getMatchingValue().matchOpt;
return matchOpt;
};
var getPreviewFor = function (item) {
return function () {
return Optional.some({
tag: 'div',
styles: item.indexOf('dings') === -1 ? { 'font-family': item } : {}
});
};
};
var onAction = function (rawItem) {
return function () {
editor.undoManager.transact(function () {
editor.focus();
editor.execCommand('FontName', false, rawItem.format);
});
};
};
var updateSelectMenuText = function (comp) {
var _a = getMatchingValue(), matchOpt = _a.matchOpt, font = _a.font;
var text = matchOpt.fold(function () {
return font;
}, function (item) {
return item.title;
});
emitWith(comp, updateMenuText, { text: text });
};
var dataset = buildBasicSettingsDataset(editor, 'font_formats', defaultFontsFormats, Delimiter.SemiColon);
return {
tooltip: 'Fonts',
icon: Optional.none(),
isSelectedFor: isSelectedFor,
getCurrentValue: getCurrentValue,
getPreviewFor: getPreviewFor,
onAction: onAction,
updateText: updateSelectMenuText,
dataset: dataset,
shouldHide: false,
isInvalid: never
};
};
var createFontSelect = function (editor, backstage) {
return createSelectButton(editor, backstage, getSpec$1(editor));
};
var fontSelectMenu = function (editor, backstage) {
var menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
editor.ui.registry.addNestedMenuItem('fontformats', {
text: backstage.shared.providers.translate('Fonts'),
getSubmenuItems: function () {
return menuItems.items.validateItems(menuItems.getStyleItems());
}
});
};
var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
var legacyFontSizes = {
'8pt': '1',
'10pt': '2',
'12pt': '3',
'14pt': '4',
'18pt': '5',
'24pt': '6',
'36pt': '7'
};
var keywordFontSizes = {
'xx-small': '7pt',
'x-small': '8pt',
'small': '10pt',
'medium': '12pt',
'large': '14pt',
'x-large': '18pt',
'xx-large': '24pt'
};
var round$1 = function (number, precision) {
var factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
};
var toPt = function (fontSize, precision) {
if (/[0-9.]+px$/.test(fontSize)) {
return round$1(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
} else {
return get$1(keywordFontSizes, fontSize).getOr(fontSize);
}
};
var toLegacy = function (fontSize) {
return get$1(legacyFontSizes, fontSize).getOr('');
};
var getSpec$2 = function (editor) {
var getMatchingValue = function () {
var matchOpt = Optional.none();
var items = dataset.data;
var fontSize = editor.queryCommandValue('FontSize');
if (fontSize) {
var _loop_1 = function (precision) {
var pt = toPt(fontSize, precision);
var legacy = toLegacy(pt);
matchOpt = find(items, function (item) {
return item.format === fontSize || item.format === pt || item.format === legacy;
});
};
for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
_loop_1(precision);
}
}
return {
matchOpt: matchOpt,
size: fontSize
};
};
var isSelectedFor = function (item) {
return function (valueOpt) {
return valueOpt.exists(function (value) {
return value.format === item;
});
};
};
var getCurrentValue = function () {
var matchOpt = getMatchingValue().matchOpt;
return matchOpt;
};
var getPreviewFor = constant(Optional.none);
var onAction = function (rawItem) {
return function () {
editor.undoManager.transact(function () {
editor.focus();
editor.execCommand('FontSize', false, rawItem.format);
});
};
};
var updateSelectMenuText = function (comp) {
var _a = getMatchingValue(), matchOpt = _a.matchOpt, size = _a.size;
var text = matchOpt.fold(function () {
return size;
}, function (match) {
return match.title;
});
emitWith(comp, updateMenuText, { text: text });
};
var dataset = buildBasicSettingsDataset(editor, 'fontsize_formats', defaultFontsizeFormats, Delimiter.Space);
return {
tooltip: 'Font sizes',
icon: Optional.none(),
isSelectedFor: isSelectedFor,
getPreviewFor: getPreviewFor,
getCurrentValue: getCurrentValue,
onAction: onAction,
updateText: updateSelectMenuText,
dataset: dataset,
shouldHide: false,
isInvalid: never
};
};
var createFontsizeSelect = function (editor, backstage) {
return createSelectButton(editor, backstage, getSpec$2(editor));
};
var fontsizeSelectMenu = function (editor, backstage) {
var menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
editor.ui.registry.addNestedMenuItem('fontsizes', {
text: 'Font sizes',
getSubmenuItems: function () {
return menuItems.items.validateItems(menuItems.getStyleItems());
}
});
};
var findNearest = function (editor, getStyles) {
var styles = getStyles();
var formats = map(styles, function (style) {
return style.format;
});
return Optional.from(editor.formatter.closest(formats)).bind(function (fmt) {
return find(styles, function (data) {
return data.format === fmt;
});
}).orThunk(function () {
return someIf(editor.formatter.match('p'), {
title: 'Paragraph',
format: 'p'
});
});
};
var revocable = function (doRevoke) {
var subject = Cell(Optional.none());
var revoke = function () {
return subject.get().each(doRevoke);
};
var clear = function () {
revoke();
subject.set(Optional.none());
};
var isSet = function () {
return subject.get().isSome();
};
var set = function (s) {
revoke();
subject.set(Optional.some(s));
};
return {
clear: clear,
isSet: isSet,
set: set
};
};
var destroyable = function () {
return revocable(function (s) {
return s.destroy();
});
};
var unbindable = function () {
return revocable(function (s) {
return s.unbind();
});
};
var value$3 = function () {
var subject = Cell(Optional.none());
var clear = function () {
return subject.set(Optional.none());
};
var set = function (s) {
return subject.set(Optional.some(s));
};
var isSet = function () {
return subject.get().isSome();
};
var on = function (f) {
return subject.get().each(f);
};
return {
clear: clear,
set: set,
isSet: isSet,
on: on
};
};
var onSetupFormatToggle = function (editor, name) {
return function (api) {
var boundCallback = unbindable();
var init = function () {
api.setActive(editor.formatter.match(name));
var binding = editor.formatter.formatChanged(name, api.setActive);
boundCallback.set(binding);
};
editor.initialized ? init() : editor.on('init', init);
return boundCallback.clear;
};
};
var onActionToggleFormat = function (editor) {
return function (rawItem) {
return function () {
editor.undoManager.transact(function () {
editor.focus();
editor.execCommand('mceToggleFormat', false, rawItem.format);
});
};
};
};
var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre';
var getSpec$3 = function (editor) {
var isSelectedFor = function (format) {
return function () {
return editor.formatter.match(format);
};
};
var getPreviewFor = function (format) {
return function () {
var fmt = editor.formatter.get(format);
return Optional.some({
tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
});
};
};
var updateSelectMenuText = function (comp) {
var detectedFormat = findNearest(editor, function () {
return dataset.data;
});
var text = detectedFormat.fold(function () {
return 'Paragraph';
}, function (fmt) {
return fmt.title;
});
emitWith(comp, updateMenuText, { text: text });
};
var dataset = buildBasicSettingsDataset(editor, 'block_formats', defaultBlocks, Delimiter.SemiColon);
return {
tooltip: 'Blocks',
icon: Optional.none(),
isSelectedFor: isSelectedFor,
getCurrentValue: Optional.none,
getPreviewFor: getPreviewFor,
onAction: onActionToggleFormat(editor),
updateText: updateSelectMenuText,
dataset: dataset,
shouldHide: false,
isInvalid: function (item) {
return !editor.formatter.canApply(item.format);
}
};
};
var createFormatSelect = function (editor, backstage) {
return createSelectButton(editor, backstage, getSpec$3(editor));
};
var formatSelectMenu = function (editor, backstage) {
var menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
editor.ui.registry.addNestedMenuItem('blockformats', {
text: 'Blocks',
getSubmenuItems: function () {
return menuItems.items.validateItems(menuItems.getStyleItems());
}
});
};
var getSpec$4 = function (editor, dataset) {
var isSelectedFor = function (format) {
return function () {
return editor.formatter.match(format);
};
};
var getPreviewFor = function (format) {
return function () {
var fmt = editor.formatter.get(format);
return fmt !== undefined ? Optional.some({
tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
}) : Optional.none();
};
};
var updateSelectMenuText = function (comp) {
var getFormatItems = function (fmt) {
var subs = fmt.items;
return subs !== undefined && subs.length > 0 ? bind(subs, getFormatItems) : [{
title: fmt.title,
format: fmt.format
}];
};
var flattenedItems = bind(getStyleFormats(editor), getFormatItems);
var detectedFormat = findNearest(editor, function () {
return flattenedItems;
});
var text = detectedFormat.fold(function () {
return 'Paragraph';
}, function (fmt) {
return fmt.title;
});
emitWith(comp, updateMenuText, { text: text });
};
return {
tooltip: 'Formats',
icon: Optional.none(),
isSelectedFor: isSelectedFor,
getCurrentValue: Optional.none,
getPreviewFor: getPreviewFor,
onAction: onActionToggleFormat(editor),
updateText: updateSelectMenuText,
shouldHide: editor.getParam('style_formats_autohide', false, 'boolean'),
isInvalid: function (item) {
return !editor.formatter.canApply(item.format);
},
dataset: dataset
};
};
var createStyleSelect = function (editor, backstage) {
var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
return createSelectButton(editor, backstage, getSpec$4(editor, dataset));
};
var styleSelectMenu = function (editor, backstage) {
var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
var menuItems = createMenuItems(editor, backstage, getSpec$4(editor, dataset));
editor.ui.registry.addNestedMenuItem('formats', {
text: 'Formats',
getSubmenuItems: function () {
return menuItems.items.validateItems(menuItems.getStyleItems());
}
});
};
var defaultToolbar = [
{
name: 'history',
items: [
'undo',
'redo'
]
},
{
name: 'styles',
items: ['styleselect']
},
{
name: 'formatting',
items: [
'bold',
'italic'
]
},
{
name: 'alignment',
items: [
'alignleft',
'aligncenter',
'alignright',
'alignjustify'
]
},
{
name: 'indentation',
items: [
'outdent',
'indent'
]
},
{
name: 'permanent pen',
items: ['permanentpen']
},
{
name: 'comments',
items: ['addcomment']
}
];
var renderFromBridge = function (bridgeBuilder, render) {
return function (spec, extras, editor) {
var internal = bridgeBuilder(spec).mapError(function (errInfo) {
return formatError(errInfo);
}).getOrDie();
return render(internal, extras, editor);
};
};
var types = {
button: renderFromBridge(createToolbarButton, function (s, extras) {
return renderToolbarButton(s, extras.backstage.shared.providers);
}),
togglebutton: renderFromBridge(createToggleButton, function (s, extras) {
return renderToolbarToggleButton(s, extras.backstage.shared.providers);
}),
menubutton: renderFromBridge(createMenuButton, function (s, extras) {
return renderMenuButton(s, 'tox-tbtn', extras.backstage, Optional.none());
}),
splitbutton: renderFromBridge(createSplitButton, function (s, extras) {
return renderSplitButton(s, extras.backstage.shared);
}),
grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, function (s, extras, editor) {
var _a;
var buttons = editor.ui.registry.getAll().buttons;
var identify = function (toolbar) {
return identifyButtons(editor, {
buttons: buttons,
toolbar: toolbar,
allowToolbarGroups: false
}, extras, Optional.none());
};
var attributes = (_a = {}, _a[Attribute] = extras.backstage.shared.header.isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a);
switch (getToolbarMode(editor)) {
case ToolbarMode.floating:
return renderFloatingToolbarButton(s, extras.backstage, identify, attributes);
default:
throw new Error('Toolbar groups are only supported when using floating toolbar mode');
}
}),
styleSelectButton: function (editor, extras) {
return createStyleSelect(editor, extras.backstage);
},
fontsizeSelectButton: function (editor, extras) {
return createFontsizeSelect(editor, extras.backstage);
},
fontSelectButton: function (editor, extras) {
return createFontSelect(editor, extras.backstage);
},
formatButton: function (editor, extras) {
return createFormatSelect(editor, extras.backstage);
},
alignMenuButton: function (editor, extras) {
return createAlignSelect(editor, extras.backstage);
}
};
var extractFrom = function (spec, extras, editor) {
return get$1(types, spec.type).fold(function () {
console.error('skipping button defined by', spec);
return Optional.none();
}, function (render) {
return Optional.some(render(spec, extras, editor));
});
};
var bespokeButtons = {
styleselect: types.styleSelectButton,
fontsizeselect: types.fontsizeSelectButton,
fontselect: types.fontSelectButton,
formatselect: types.formatButton,
align: types.alignMenuButton
};
var removeUnusedDefaults = function (buttons) {
var filteredItemGroups = map(defaultToolbar, function (group) {
var items = filter(group.items, function (subItem) {
return has(buttons, subItem) || has(bespokeButtons, subItem);
});
return {
name: group.name,
items: items
};
});
return filter(filteredItemGroups, function (group) {
return group.items.length > 0;
});
};
var convertStringToolbar = function (strToolbar) {
var groupsStrings = strToolbar.split('|');
return map(groupsStrings, function (g) {
return { items: g.trim().split(' ') };
});
};
var isToolbarGroupSettingArray = function (toolbar) {
return isArrayOf(toolbar, function (t) {
return has(t, 'name') && has(t, 'items');
});
};
var createToolbar = function (toolbarConfig) {
var toolbar = toolbarConfig.toolbar;
var buttons = toolbarConfig.buttons;
if (toolbar === false) {
return [];
} else if (toolbar === undefined || toolbar === true) {
return removeUnusedDefaults(buttons);
} else if (isString(toolbar)) {
return convertStringToolbar(toolbar);
} else if (isToolbarGroupSettingArray(toolbar)) {
return toolbar;
} else {
console.error('Toolbar type should be string, string[], boolean or ToolbarGroup[]');
return [];
}
};
var lookupButton = function (editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) {
return get$1(buttons, toolbarItem.toLowerCase()).orThunk(function () {
return prefixes.bind(function (ps) {
return findMap(ps, function (prefix) {
return get$1(buttons, prefix + toolbarItem.toLowerCase());
});
});
}).fold(function () {
return get$1(bespokeButtons, toolbarItem.toLowerCase()).map(function (r) {
return r(editor, extras);
}).orThunk(function () {
return Optional.none();
});
}, function (spec) {
if (spec.type === 'grouptoolbarbutton' && !allowToolbarGroups) {
console.warn('Ignoring the \'' + toolbarItem + '\' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.');
return Optional.none();
} else {
return extractFrom(spec, extras, editor);
}
});
};
var identifyButtons = function (editor, toolbarConfig, extras, prefixes) {
var toolbarGroups = createToolbar(toolbarConfig);
var groups = map(toolbarGroups, function (group) {
var items = bind(group.items, function (toolbarItem) {
return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray();
});
return {
title: Optional.from(editor.translate(group.name)),
items: items
};
});
return filter(groups, function (group) {
return group.items.length > 0;
});
};
var bubbleSize = 12;
var bubbleAlignments$1 = {
valignCentre: [],
alignCentre: [],
alignLeft: ['tox-pop--align-left'],
alignRight: ['tox-pop--align-right'],
right: ['tox-pop--right'],
left: ['tox-pop--left'],
bottom: ['tox-pop--bottom'],
top: ['tox-pop--top']
};
var anchorOverrides = {
maxHeightFunction: expandable(),
maxWidthFunction: expandable$1()
};
var desktopAnchorSpecLayouts = {
onLtr: function () {
return [
north$1,
south$1,
northeast$1,
southeast$1,
northwest$1,
southwest$1,
north$3,
south$3,
northeast$3,
southeast$3,
northwest$3,
southwest$3
];
},
onRtl: function () {
return [
north$1,
south$1,
northwest$1,
southwest$1,
northeast$1,
southeast$1,
north$3,
south$3,
northwest$3,
southwest$3,
northeast$3,
southeast$3
];
}
};
var mobileAnchorSpecLayouts = {
onLtr: function () {
return [
south$1,
southeast$1,
southwest$1,
northeast$1,
northwest$1,
north$1,
north$3,
south$3,
northeast$3,
southeast$3,
northwest$3,
southwest$3
];
},
onRtl: function () {
return [
south$1,
southwest$1,
southeast$1,
northwest$1,
northeast$1,
north$1,
north$3,
south$3,
northwest$3,
southwest$3,
northeast$3,
southeast$3
];
}
};
var getAnchorLayout = function (position, isTouch) {
if (position === 'line') {
return {
bubble: nu$8(bubbleSize, 0, bubbleAlignments$1),
layouts: {
onLtr: function () {
return [east$1];
},
onRtl: function () {
return [west$1];
}
},
overrides: anchorOverrides
};
} else {
return {
bubble: nu$8(0, bubbleSize, bubbleAlignments$1),
layouts: isTouch ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts,
overrides: anchorOverrides
};
}
};
var register$4 = function (editor, registryContextToolbars, sink, extras) {
var isTouch = detect$3().deviceType.isTouch;
var contextbar = build$1(renderContextToolbar({
sink: sink,
onEscape: function () {
editor.focus();
return Optional.some(true);
}
}));
var getBounds = function () {
return getContextToolbarBounds(editor, extras.backstage.shared);
};
var isRangeOverlapping = function (aTop, aBottom, bTop, bBottom) {
return Math.max(aTop, bTop) <= Math.min(aBottom, bBottom);
};
var getLastElementVerticalBound = function () {
var nodeBounds = lastElement.get().filter(function (ele) {
return inBody(SugarElement.fromDom(ele));
}).map(function (ele) {
return ele.getBoundingClientRect();
}).getOrThunk(function () {
return editor.selection.getRng().getBoundingClientRect();
});
var diffTop = editor.inline ? get$9().top : absolute$1(SugarElement.fromDom(editor.getBody())).y;
return {
y: nodeBounds.top + diffTop,
bottom: nodeBounds.bottom + diffTop
};
};
var shouldContextToolbarHide = function () {
if (isTouch() && extras.backstage.isContextMenuOpen()) {
return true;
}
var lastElementBounds = getLastElementVerticalBound();
var contextToolbarBounds = getBounds();
return !isRangeOverlapping(lastElementBounds.y, lastElementBounds.bottom, contextToolbarBounds.y, contextToolbarBounds.bottom);
};
var close = function () {
lastAnchor.set(Optional.none());
InlineView.hide(contextbar);
};
var forceHide = function () {
InlineView.hide(contextbar);
};
var hideOrRepositionIfNecessary = function () {
lastAnchor.get().each(function (anchor) {
var contextBarEle = contextbar.element;
remove$6(contextBarEle, 'display');
if (shouldContextToolbarHide()) {
set$2(contextBarEle, 'display', 'none');
} else {
Positioning.positionWithinBounds(sink, anchor, contextbar, Optional.some(getBounds()));
}
});
};
var lastAnchor = Cell(Optional.none());
var lastElement = Cell(Optional.none());
var timer = Cell(null);
var wrapInPopDialog = function (toolbarSpec) {
return {
dom: {
tag: 'div',
classes: ['tox-pop__dialog']
},
components: [toolbarSpec],
behaviours: derive$1([
Keying.config({ mode: 'acyclic' }),
config('pop-dialog-wrap-events', [
runOnAttached(function (comp) {
editor.shortcuts.add('ctrl+F9', 'focus statusbar', function () {
return Keying.focusIn(comp);
});
}),
runOnDetached(function (_comp) {
editor.shortcuts.remove('ctrl+F9');
})
])
])
};
};
var getScopes = cached(function () {
return categorise(registryContextToolbars, function (toolbarApi) {
var alloySpec = buildToolbar([toolbarApi]);
emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
});
});
var buildContextToolbarGroups = function (allButtons, ctx) {
return identifyButtons(editor, {
buttons: allButtons,
toolbar: ctx.items,
allowToolbarGroups: false
}, extras, Optional.some(['form:']));
};
var buildContextMenuGroups = function (ctx, providers) {
return ContextForm.buildInitGroups(ctx, providers);
};
var buildToolbar = function (toolbars) {
var buttons = editor.ui.registry.getAll().buttons;
var scopes = getScopes();
var allButtons = __assign(__assign({}, buttons), scopes.formNavigators);
var toolbarType = getToolbarMode(editor) === ToolbarMode.scrolling ? ToolbarMode.scrolling : ToolbarMode.default;
var initGroups = flatten(map(toolbars, function (ctx) {
return ctx.type === 'contexttoolbar' ? buildContextToolbarGroups(allButtons, ctx) : buildContextMenuGroups(ctx, extras.backstage.shared.providers);
}));
return renderToolbar({
type: toolbarType,
uid: generate$1('context-toolbar'),
initGroups: initGroups,
onEscape: Optional.none,
cyclicKeying: true,
providers: extras.backstage.shared.providers
});
};
editor.on(showContextToolbarEvent, function (e) {
var scopes = getScopes();
get$1(scopes.lookupTable, e.toolbarKey).each(function (ctx) {
launchContext([ctx], e.target === editor ? Optional.none() : Optional.some(e));
InlineView.getContent(contextbar).each(Keying.focusIn);
});
});
var getAnchor = function (position, element) {
var anchorage = position === 'node' ? extras.backstage.shared.anchors.node(element) : extras.backstage.shared.anchors.cursor();
return deepMerge(anchorage, getAnchorLayout(position, isTouch()));
};
var launchContext = function (toolbarApi, elem) {
clearTimer();
if (isTouch() && extras.backstage.isContextMenuOpen()) {
return;
}
var toolbarSpec = buildToolbar(toolbarApi);
var sElem = elem.map(SugarElement.fromDom);
var anchor = getAnchor(toolbarApi[0].position, sElem);
lastAnchor.set(Optional.some(anchor));
lastElement.set(elem);
var contextBarEle = contextbar.element;
remove$6(contextBarEle, 'display');
InlineView.showWithinBounds(contextbar, anchor, wrapInPopDialog(toolbarSpec), function () {
return Optional.some(getBounds());
});
if (shouldContextToolbarHide()) {
set$2(contextBarEle, 'display', 'none');
}
};
var launchContextToolbar = function () {
if (!editor.hasFocus()) {
return;
}
var scopes = getScopes();
lookup$1(scopes, editor).fold(close, function (info) {
launchContext(info.toolbars, Optional.some(info.elem.dom));
});
};
var clearTimer = function () {
var current = timer.get();
if (current !== null) {
global$2.clearTimeout(current);
timer.set(null);
}
};
var asyncOpen = function () {
clearTimer();
timer.set(global$2.setEditorTimeout(editor, launchContextToolbar, 0));
};
editor.on('init', function () {
editor.on(hideContextToolbarEvent, forceHide);
editor.on('ScrollContent ScrollWindow longpress', hideOrRepositionIfNecessary);
editor.on('click keyup focus SetContent ObjectResized ResizeEditor', function () {
asyncOpen();
});
editor.on('focusout', function (_e) {
global$2.setEditorTimeout(editor, function () {
if (search(sink.element).isNone() && search(contextbar.element).isNone()) {
close();
}
}, 0);
});
editor.on('SwitchMode', function () {
if (editor.mode.isReadOnly()) {
close();
}
});
editor.on('AfterProgressState', function (event) {
if (event.state) {
close();
} else if (editor.hasFocus()) {
asyncOpen();
}
});
editor.on('NodeChange', function (_e) {
search(contextbar.element).fold(asyncOpen, noop);
});
});
};
var setup$3 = function (editor, mothership, uiMothership) {
var broadcastEvent = function (name, evt) {
each([
mothership,
uiMothership
], function (ship) {
ship.broadcastEvent(name, evt);
});
};
var broadcastOn = function (channel, message) {
each([
mothership,
uiMothership
], function (ship) {
ship.broadcastOn([channel], message);
});
};
var fireDismissPopups = function (evt) {
return broadcastOn(dismissPopups(), { target: evt.target });
};
var onTouchstart = bind$3(SugarElement.fromDom(document), 'touchstart', fireDismissPopups);
var onTouchmove = bind$3(SugarElement.fromDom(document), 'touchmove', function (evt) {
return broadcastEvent(documentTouchmove(), evt);
});
var onTouchend = bind$3(SugarElement.fromDom(document), 'touchend', function (evt) {
return broadcastEvent(documentTouchend(), evt);
});
var onMousedown = bind$3(SugarElement.fromDom(document), 'mousedown', fireDismissPopups);
var onMouseup = bind$3(SugarElement.fromDom(document), 'mouseup', function (evt) {
if (evt.raw.button === 0) {
broadcastOn(mouseReleased(), { target: evt.target });
}
});
var onContentClick = function (raw) {
return broadcastOn(dismissPopups(), { target: SugarElement.fromDom(raw.target) });
};
var onContentMouseup = function (raw) {
if (raw.button === 0) {
broadcastOn(mouseReleased(), { target: SugarElement.fromDom(raw.target) });
}
};
var onWindowScroll = function (evt) {
return broadcastEvent(windowScroll(), fromRawEvent$1(evt));
};
var onWindowResize = function (evt) {
broadcastOn(repositionPopups(), {});
broadcastEvent(windowResize(), fromRawEvent$1(evt));
};
var onEditorResize = function () {
return broadcastOn(repositionPopups(), {});
};
var onEditorProgress = function (evt) {
if (evt.state) {
broadcastOn(dismissPopups(), { target: SugarElement.fromDom(editor.getContainer()) });
}
};
editor.on('PostRender', function () {
editor.on('click', onContentClick);
editor.on('tap', onContentClick);
editor.on('mouseup', onContentMouseup);
editor.on('ScrollWindow', onWindowScroll);
editor.on('ResizeWindow', onWindowResize);
editor.on('ResizeEditor', onEditorResize);
editor.on('AfterProgressState', onEditorProgress);
});
editor.on('remove', function () {
editor.off('click', onContentClick);
editor.off('tap', onContentClick);
editor.off('mouseup', onContentMouseup);
editor.off('ScrollWindow', onWindowScroll);
editor.off('ResizeWindow', onWindowResize);
editor.off('ResizeEditor', onEditorResize);
editor.off('AfterProgressState', onEditorProgress);
onMousedown.unbind();
onTouchstart.unbind();
onTouchmove.unbind();
onTouchend.unbind();
onMouseup.unbind();
});
editor.on('detach', function () {
detachSystem(mothership);
detachSystem(uiMothership);
mothership.destroy();
uiMothership.destroy();
});
};
var parts$d = AlloyParts;
var partType$1 = PartType;
var schema$r = constant([
defaulted$1('shell', false),
strict$1('makeItem'),
defaulted$1('setupItem', noop),
SketchBehaviours.field('listBehaviours', [Replacing])
]);
var customListDetail = function () {
return { behaviours: derive$1([Replacing.config({})]) };
};
var itemsPart = optional({
name: 'items',
overrides: customListDetail
});
var parts$e = constant([itemsPart]);
var name$2 = constant('CustomList');
var factory$f = function (detail, components, _spec, _external) {
var setItems = function (list, items) {
getListContainer(list).fold(function () {
console.error('Custom List was defined to not be a shell, but no item container was specified in components');
throw new Error('Custom List was defined to not be a shell, but no item container was specified in components');
}, function (container) {
var itemComps = Replacing.contents(container);
var numListsRequired = items.length;
var numListsToAdd = numListsRequired - itemComps.length;
var itemsToAdd = numListsToAdd > 0 ? range(numListsToAdd, function () {
return detail.makeItem();
}) : [];
var itemsToRemove = itemComps.slice(numListsRequired);
each(itemsToRemove, function (item) {
return Replacing.remove(container, item);
});
each(itemsToAdd, function (item) {
return Replacing.append(container, item);
});
var builtLists = Replacing.contents(container);
each(builtLists, function (item, i) {
detail.setupItem(list, item, items[i], i);
});
});
};
var extra = detail.shell ? {
behaviours: [Replacing.config({})],
components: []
} : {
behaviours: [],
components: components
};
var getListContainer = function (component) {
return detail.shell ? Optional.some(component) : getPart(component, detail, 'items');
};
return {
uid: detail.uid,
dom: detail.dom,
components: extra.components,
behaviours: augment(detail.listBehaviours, extra.behaviours),
apis: { setItems: setItems }
};
};
var CustomList = composite$1({
name: name$2(),
configFields: schema$r(),
partFields: parts$e(),
factory: factory$f,
apis: {
setItems: function (apis, list, items) {
apis.setItems(list, items);
}
}
});
var setup$4 = noop;
var isDocked = never;
var getBehaviours$2 = constant([]);
var StaticHeader = /*#__PURE__*/Object.freeze({
__proto__: null,
setup: setup$4,
isDocked: isDocked,
getBehaviours: getBehaviours$2
});
var getOffsetParent = function (element) {
var isFixed = getRaw(element, 'position').is('fixed');
var offsetParent$1 = isFixed ? Optional.none() : offsetParent(element);
return offsetParent$1.orThunk(function () {
var marker = SugarElement.fromTag('span');
return parent(element).bind(function (parent) {
append(parent, marker);
var offsetParent$1 = offsetParent(marker);
remove(marker);
return offsetParent$1;
});
});
};
var getOrigin = function (element) {
return getOffsetParent(element).map(absolute).getOrThunk(function () {
return SugarPosition(0, 0);
});
};
var morphAdt = Adt.generate([
{ static: [] },
{ absolute: ['positionCss'] },
{ fixed: ['positionCss'] }
]);
var appear = function (component, contextualInfo) {
var elem = component.element;
add$2(elem, contextualInfo.transitionClass);
remove$4(elem, contextualInfo.fadeOutClass);
add$2(elem, contextualInfo.fadeInClass);
contextualInfo.onShow(component);
};
var disappear = function (component, contextualInfo) {
var elem = component.element;
add$2(elem, contextualInfo.transitionClass);
remove$4(elem, contextualInfo.fadeInClass);
add$2(elem, contextualInfo.fadeOutClass);
contextualInfo.onHide(component);
};
var isPartiallyVisible = function (box, viewport) {
return box.y < viewport.bottom && box.bottom > viewport.y;
};
var isTopCompletelyVisible = function (box, viewport) {
return box.y >= viewport.y;
};
var isBottomCompletelyVisible = function (box, viewport) {
return box.bottom <= viewport.bottom;
};
var isVisibleForModes = function (modes, box, viewport) {
return forall(modes, function (mode) {
switch (mode) {
case 'bottom':
return isBottomCompletelyVisible(box, viewport);
case 'top':
return isTopCompletelyVisible(box, viewport);
}
});
};
var getPrior = function (elem, state) {
return state.getInitialPosition().map(function (pos) {
return bounds$1(pos.bounds.x, pos.bounds.y, get$8(elem), get$7(elem));
});
};
var storePrior = function (elem, box, state) {
state.setInitialPosition(Optional.some({
style: getAllRaw(elem),
position: get$5(elem, 'position') || 'static',
bounds: box
}));
};
var revertToOriginal = function (elem, box$1, state) {
return state.getInitialPosition().bind(function (position) {
state.setInitialPosition(Optional.none());
switch (position.position) {
case 'static':
return Optional.some(morphAdt.static());
case 'absolute':
var offsetBox_1 = getOffsetParent(elem).map(box).getOrThunk(function () {
return box(body());
});
return Optional.some(morphAdt.absolute(NuPositionCss('absolute', get$1(position.style, 'left').map(function (_left) {
return box$1.x - offsetBox_1.x;
}), get$1(position.style, 'top').map(function (_top) {
return box$1.y - offsetBox_1.y;
}), get$1(position.style, 'right').map(function (_right) {
return offsetBox_1.right - box$1.right;
}), get$1(position.style, 'bottom').map(function (_bottom) {
return offsetBox_1.bottom - box$1.bottom;
}))));
default:
return Optional.none();
}
});
};
var morphToOriginal = function (elem, viewport, state) {
return getPrior(elem, state).filter(function (box) {
return isVisibleForModes(state.getModes(), box, viewport);
}).bind(function (box) {
return revertToOriginal(elem, box, state);
});
};
var morphToFixed = function (elem, viewport, state) {
var box$1 = box(elem);
if (!isVisibleForModes(state.getModes(), box$1, viewport)) {
storePrior(elem, box$1, state);
var winBox = win();
var left = box$1.x - winBox.x;
var top_1 = viewport.y - winBox.y;
var bottom = winBox.bottom - viewport.bottom;
var isTop = box$1.y <= viewport.y;
return Optional.some(morphAdt.fixed(NuPositionCss('fixed', Optional.some(left), isTop ? Optional.some(top_1) : Optional.none(), Optional.none(), !isTop ? Optional.some(bottom) : Optional.none())));
} else {
return Optional.none();
}
};
var getMorph = function (component, viewport, state) {
var elem = component.element;
var isDocked = getRaw(elem, 'position').is('fixed');
return isDocked ? morphToOriginal(elem, viewport, state) : morphToFixed(elem, viewport, state);
};
var getMorphToOriginal = function (component, state) {
var elem = component.element;
return getPrior(elem, state).bind(function (box) {
return revertToOriginal(elem, box, state);
});
};
var morphToStatic = function (component, config) {
each([
'left',
'right',
'top',
'bottom',
'position'
], function (prop) {
return remove$6(component.element, prop);
});
config.onUndocked(component);
};
var morphToCoord = function (component, config, position) {
applyPositionCss(component.element, position);
var method = position.position === 'fixed' ? config.onDocked : config.onUndocked;
method(component);
};
var updateVisibility = function (component, config, state, viewport, morphToDocked) {
if (morphToDocked === void 0) {
morphToDocked = false;
}
config.contextual.each(function (contextInfo) {
contextInfo.lazyContext(component).each(function (box) {
var isVisible = isPartiallyVisible(box, viewport);
if (isVisible !== state.isVisible()) {
state.setVisible(isVisible);
if (morphToDocked && !isVisible) {
add$3(component.element, [contextInfo.fadeOutClass]);
contextInfo.onHide(component);
} else {
var method = isVisible ? appear : disappear;
method(component, contextInfo);
}
}
});
});
};
var refreshInternal = function (component, config, state) {
var viewport = config.lazyViewport(component);
var isDocked = state.isDocked();
if (isDocked) {
updateVisibility(component, config, state, viewport);
}
getMorph(component, viewport, state).each(function (morph) {
state.setDocked(!isDocked);
morph.fold(function () {
return morphToStatic(component, config);
}, function (position) {
return morphToCoord(component, config, position);
}, function (position) {
updateVisibility(component, config, state, viewport, true);
morphToCoord(component, config, position);
});
});
};
var resetInternal = function (component, config, state) {
var elem = component.element;
state.setDocked(false);
getMorphToOriginal(component, state).each(function (morph) {
morph.fold(function () {
return morphToStatic(component, config);
}, function (position) {
return morphToCoord(component, config, position);
}, noop);
});
state.setVisible(true);
config.contextual.each(function (contextInfo) {
remove$5(elem, [
contextInfo.fadeInClass,
contextInfo.fadeOutClass,
contextInfo.transitionClass
]);
contextInfo.onShow(component);
});
refresh$4(component, config, state);
};
var refresh$4 = function (component, config, state) {
if (component.getSystem().isConnected()) {
refreshInternal(component, config, state);
}
};
var reset = function (component, config, state) {
if (state.isDocked()) {
resetInternal(component, config, state);
}
};
var isDocked$1 = function (component, config, state) {
return state.isDocked();
};
var setModes = function (component, config, state, modes) {
return state.setModes(modes);
};
var getModes = function (component, config, state) {
return state.getModes();
};
var DockingApis = /*#__PURE__*/Object.freeze({
__proto__: null,
refresh: refresh$4,
reset: reset,
isDocked: isDocked$1,
getModes: getModes,
setModes: setModes
});
var events$f = function (dockInfo, dockState) {
return derive([
runOnSource(transitionend(), function (component, simulatedEvent) {
dockInfo.contextual.each(function (contextInfo) {
if (has$2(component.element, contextInfo.transitionClass)) {
remove$5(component.element, [
contextInfo.transitionClass,
contextInfo.fadeInClass
]);
var notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
notify(component);
}
simulatedEvent.stop();
});
}),
run(windowScroll(), function (component, _) {
refresh$4(component, dockInfo, dockState);
}),
run(windowResize(), function (component, _) {
reset(component, dockInfo, dockState);
})
]);
};
var ActiveDocking = /*#__PURE__*/Object.freeze({
__proto__: null,
events: events$f
});
var DockingSchema = [
optionObjOf('contextual', [
strictString('fadeInClass'),
strictString('fadeOutClass'),
strictString('transitionClass'),
strictFunction('lazyContext'),
onHandler('onShow'),
onHandler('onShown'),
onHandler('onHide'),
onHandler('onHidden')
]),
defaultedFunction('lazyViewport', win),
defaultedArrayOf('modes', [
'top',
'bottom'
], string),
onHandler('onDocked'),
onHandler('onUndocked')
];
var init$b = function (spec) {
var docked = Cell(false);
var visible = Cell(true);
var initialBounds = Cell(Optional.none());
var modes = Cell(spec.modes);
var readState = function () {
return 'docked: ' + docked.get() + ', visible: ' + visible.get() + ', modes: ' + modes.get().join(',');
};
return nu$5({
isDocked: docked.get,
setDocked: docked.set,
getInitialPosition: initialBounds.get,
setInitialPosition: initialBounds.set,
isVisible: visible.get,
setVisible: visible.set,
getModes: modes.get,
setModes: modes.set,
readState: readState
});
};
var DockingState = /*#__PURE__*/Object.freeze({
__proto__: null,
init: init$b
});
var Docking = create$1({
fields: DockingSchema,
name: 'docking',
active: ActiveDocking,
apis: DockingApis,
state: DockingState
});
var visibility = {
fadeInClass: 'tox-editor-dock-fadein',
fadeOutClass: 'tox-editor-dock-fadeout',
transitionClass: 'tox-editor-dock-transition'
};
var editorStickyOnClass = 'tox-tinymce--toolbar-sticky-on';
var editorStickyOffClass = 'tox-tinymce--toolbar-sticky-off';
var scrollFromBehindHeader = function (e, containerHeader) {
var doc = owner(containerHeader);
var viewHeight = doc.dom.defaultView.innerHeight;
var scrollPos = get$9(doc);
var markerElement = SugarElement.fromDom(e.elm);
var markerPos = absolute$1(markerElement);
var markerHeight = get$7(markerElement);
var markerTop = markerPos.y;
var markerBottom = markerTop + markerHeight;
var editorHeaderPos = absolute(containerHeader);
var editorHeaderHeight = get$7(containerHeader);
var editorHeaderTop = editorHeaderPos.top;
var editorHeaderBottom = editorHeaderTop + editorHeaderHeight;
var editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top) < 2;
var editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top + viewHeight)) < 2;
if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) {
to(scrollPos.left, markerTop - editorHeaderHeight, doc);
} else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) {
var y = markerTop - viewHeight + markerHeight + editorHeaderHeight;
to(scrollPos.left, y, doc);
}
};
var isDockedMode = function (header, mode) {
return contains(Docking.getModes(header), mode);
};
var updateIframeContentFlow = function (header) {
var getOccupiedHeight = function (elm) {
return getOuter$1(elm) + (parseInt(get$5(elm, 'margin-top'), 10) || 0) + (parseInt(get$5(elm, 'margin-bottom'), 10) || 0);
};
var elm = header.element;
parent(elm).each(function (parentElem) {
var padding = 'padding-' + Docking.getModes(header)[0];
if (Docking.isDocked(header)) {
var parentWidth = get$8(parentElem);
set$2(elm, 'width', parentWidth + 'px');
set$2(parentElem, padding, getOccupiedHeight(elm) + 'px');
} else {
remove$6(elm, 'width');
remove$6(parentElem, padding);
}
});
};
var updateSinkVisibility = function (sinkElem, visible) {
if (visible) {
remove$4(sinkElem, visibility.fadeOutClass);
add$3(sinkElem, [
visibility.transitionClass,
visibility.fadeInClass
]);
} else {
remove$4(sinkElem, visibility.fadeInClass);
add$3(sinkElem, [
visibility.fadeOutClass,
visibility.transitionClass
]);
}
};
var updateEditorClasses = function (editor, docked) {
var editorContainer = SugarElement.fromDom(editor.getContainer());
if (docked) {
add$2(editorContainer, editorStickyOnClass);
remove$4(editorContainer, editorStickyOffClass);
} else {
add$2(editorContainer, editorStickyOffClass);
remove$4(editorContainer, editorStickyOnClass);
}
};
var restoreFocus = function (headerElem, focusedElem) {
var ownerDoc = owner(focusedElem);
active(ownerDoc).filter(function (activeElm) {
return !eq$1(focusedElem, activeElm);
}).filter(function (activeElm) {
return eq$1(activeElm, SugarElement.fromDom(ownerDoc.dom.body)) || contains$2(headerElem, activeElm);
}).each(function () {
return focus$1(focusedElem);
});
};
var findFocusedElem = function (rootElm, lazySink) {
return search(rootElm).orThunk(function () {
return lazySink().toOptional().bind(function (sink) {
return search(sink.element);
});
});
};
var setup$5 = function (editor, sharedBackstage, lazyHeader) {
if (!editor.inline) {
if (!sharedBackstage.header.isPositionedAtTop()) {
editor.on('ResizeEditor', function () {
lazyHeader().each(Docking.reset);
});
}
editor.on('ResizeWindow ResizeEditor', function () {
lazyHeader().each(updateIframeContentFlow);
});
editor.on('SkinLoaded', function () {
lazyHeader().each(function (comp) {
Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp);
});
});
editor.on('FullscreenStateChanged', function () {
lazyHeader().each(Docking.reset);
});
}
editor.on('AfterScrollIntoView', function (e) {
lazyHeader().each(function (header) {
Docking.refresh(header);
var headerElem = header.element;
if (isVisible(headerElem)) {
scrollFromBehindHeader(e, headerElem);
}
});
});
editor.on('PostRender', function () {
updateEditorClasses(editor, false);
});
};
var isDocked$2 = function (lazyHeader) {
return lazyHeader().map(Docking.isDocked).getOr(false);
};
var getIframeBehaviours = function () {
var _a;
return [Receiving.config({ channels: (_a = {}, _a[toolbarHeightChange()] = { onReceive: updateIframeContentFlow }, _a) })];
};
var getBehaviours$3 = function (editor, sharedBackstage) {
var focusedElm = Cell(Optional.none());
var lazySink = sharedBackstage.getSink;
var runOnSinkElement = function (f) {
lazySink().each(function (sink) {
return f(sink.element);
});
};
var onDockingSwitch = function (comp) {
if (!editor.inline) {
updateIframeContentFlow(comp);
}
updateEditorClasses(editor, Docking.isDocked(comp));
comp.getSystem().broadcastOn([repositionPopups()], {});
lazySink().each(function (sink) {
return sink.getSystem().broadcastOn([repositionPopups()], {});
});
};
var additionalBehaviours = editor.inline ? [] : getIframeBehaviours();
return __spreadArrays([
Focusing.config({}),
Docking.config({
contextual: __assign({
lazyContext: function (comp) {
var headerHeight = getOuter$1(comp.element);
var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
var box$1 = box(SugarElement.fromDom(container));
var boxHeight = box$1.height - headerHeight;
var topBound = box$1.y + (isDockedMode(comp, 'top') ? 0 : headerHeight);
return Optional.some(bounds$1(box$1.x, topBound, box$1.width, boxHeight));
},
onShow: function () {
runOnSinkElement(function (elem) {
return updateSinkVisibility(elem, true);
});
},
onShown: function (comp) {
runOnSinkElement(function (elem) {
return remove$5(elem, [
visibility.transitionClass,
visibility.fadeInClass
]);
});
focusedElm.get().each(function (elem) {
restoreFocus(comp.element, elem);
focusedElm.set(Optional.none());
});
},
onHide: function (comp) {
focusedElm.set(findFocusedElem(comp.element, lazySink));
runOnSinkElement(function (elem) {
return updateSinkVisibility(elem, false);
});
},
onHidden: function () {
runOnSinkElement(function (elem) {
return remove$5(elem, [visibility.transitionClass]);
});
}
}, visibility),
modes: [sharedBackstage.header.getDockingMode()],
onDocked: onDockingSwitch,
onUndocked: onDockingSwitch
})
], additionalBehaviours);
};
var StickyHeader = /*#__PURE__*/Object.freeze({
__proto__: null,
setup: setup$5,
isDocked: isDocked$2,
getBehaviours: getBehaviours$3
});
var renderHeader = function (spec) {
var editor = spec.editor;
var getBehaviours = spec.sticky ? getBehaviours$3 : getBehaviours$2;
return {
uid: spec.uid,
dom: spec.dom,
components: spec.components,
behaviours: derive$1(getBehaviours(editor, spec.sharedBackstage))
};
};
var factory$g = function (detail, spec) {
var setMenus = function (comp, menus) {
var newMenus = map(menus, function (m) {
var buttonSpec = {
type: 'menubutton',
text: m.text,
fetch: function (callback) {
callback(m.getItems());
}
};
var internal = createMenuButton(buttonSpec).mapError(function (errInfo) {
return formatError(errInfo);
}).getOrDie();
return renderMenuButton(internal, 'tox-mbtn', spec.backstage, Optional.some('menuitem'));
});
Replacing.set(comp, newMenus);
};
var apis = {
focus: Keying.focusIn,
setMenus: setMenus
};
return {
uid: detail.uid,
dom: detail.dom,
components: [],
behaviours: derive$1([
Replacing.config({}),
config('menubar-events', [
runOnAttached(function (component) {
detail.onSetup(component);
}),
run(mouseover(), function (comp, se) {
descendant$1(comp.element, '.' + 'tox-mbtn--active').each(function (activeButton) {
closest$3(se.event.target, '.' + 'tox-mbtn').each(function (hoveredButton) {
if (!eq$1(activeButton, hoveredButton)) {
comp.getSystem().getByDom(activeButton).each(function (activeComp) {
comp.getSystem().getByDom(hoveredButton).each(function (hoveredComp) {
Dropdown.expand(hoveredComp);
Dropdown.close(activeComp);
Focusing.focus(hoveredComp);
});
});
}
});
});
}),
run(focusShifted(), function (comp, se) {
se.event.prevFocus.bind(function (prev) {
return comp.getSystem().getByDom(prev).toOptional();
}).each(function (prev) {
se.event.newFocus.bind(function (nu) {
return comp.getSystem().getByDom(nu).toOptional();
}).each(function (nu) {
if (Dropdown.isOpen(prev)) {
Dropdown.expand(nu);
Dropdown.close(prev);
}
});
});
})
]),
Keying.config({
mode: 'flow',
selector: '.' + 'tox-mbtn',
onEscape: function (comp) {
detail.onEscape(comp);
return Optional.some(true);
}
}),
Tabstopping.config({})
]),
apis: apis,
domModification: { attributes: { role: 'menubar' } }
};
};
var SilverMenubar = single$2({
factory: factory$g,
name: 'silver.Menubar',
configFields: [
strict$1('dom'),
strict$1('uid'),
strict$1('onEscape'),
strict$1('backstage'),
defaulted$1('onSetup', noop)
],
apis: {
focus: function (apis, comp) {
apis.focus(comp);
},
setMenus: function (apis, comp, menus) {
apis.setMenus(comp, menus);
}
}
});
var owner$4 = 'container';
var schema$s = [field$1('slotBehaviours', [])];
var getPartName$1 = function (name) {
return '';
};
var sketch$2 = function (sSpec) {
var parts = function () {
var record = [];
var slot = function (name, config) {
record.push(name);
return generateOne(owner$4, getPartName$1(name), config);
};
return {
slot: slot,
record: function () {
return record;
}
};
}();
var spec = sSpec(parts);
var partNames = parts.record();
var fieldParts = map(partNames, function (n) {
return required({
name: n,
pname: getPartName$1(n)
});
});
return composite(owner$4, schema$s, fieldParts, make$7, spec);
};
var make$7 = function (detail, components) {
var getSlotNames = function (_) {
return getAllPartNames(detail);
};
var getSlot = function (container, key) {
return getPart(container, detail, key);
};
var onSlot = function (f, def) {
return function (container, key) {
return getPart(container, detail, key).map(function (slot) {
return f(slot, key);
}).getOr(def);
};
};
var onSlots = function (f) {
return function (container, keys) {
each(keys, function (key) {
return f(container, key);
});
};
};
var doShowing = function (comp, _key) {
return get$3(comp.element, 'aria-hidden') !== 'true';
};
var doShow = function (comp, key) {
if (!doShowing(comp)) {
var element = comp.element;
remove$6(element, 'display');
remove$1(element, 'aria-hidden');
emitWith(comp, slotVisibility(), {
name: key,
visible: true
});
}
};
var doHide = function (comp, key) {
if (doShowing(comp)) {
var element = comp.element;
set$2(element, 'display', 'none');
set$1(element, 'aria-hidden', 'true');
emitWith(comp, slotVisibility(), {
name: key,
visible: false
});
}
};
var isShowing = onSlot(doShowing, false);
var hideSlot = onSlot(doHide);
var hideSlots = onSlots(hideSlot);
var hideAllSlots = function (container) {
return hideSlots(container, getSlotNames());
};
var showSlot = onSlot(doShow);
var apis = {
getSlotNames: getSlotNames,
getSlot: getSlot,
isShowing: isShowing,
hideSlot: hideSlot,
hideAllSlots: hideAllSlots,
showSlot: showSlot
};
return {
uid: detail.uid,
dom: detail.dom,
components: components,
behaviours: get$d(detail.slotBehaviours),
apis: apis
};
};
var slotApis = map$2({
getSlotNames: function (apis, c) {
return apis.getSlotNames(c);
},
getSlot: function (apis, c, key) {
return apis.getSlot(c, key);
},
isShowing: function (apis, c, key) {
return apis.isShowing(c, key);
},
hideSlot: function (apis, c, key) {
return apis.hideSlot(c, key);
},
hideAllSlots: function (apis, c) {
return apis.hideAllSlots(c);
},
showSlot: function (apis, c, key) {
return apis.showSlot(c, key);
}
}, function (value) {
return makeApi(value);
});
var SlotContainer = __assign(__assign({}, slotApis), { sketch: sketch$2 });
var sidebarSchema = objOf([
optionString('icon'),
optionString('tooltip'),
defaultedFunction('onShow', noop),
defaultedFunction('onHide', noop),
defaultedFunction('onSetup', function () {
return noop;
})
]);
var createSidebar = function (spec) {
return asRaw('sidebar', sidebarSchema, spec);
};
var setup$6 = function (editor) {
var sidebars = editor.ui.registry.getAll().sidebars;
each(keys(sidebars), function (name) {
var spec = sidebars[name];
var isActive = function () {
return Optional.from(editor.queryCommandValue('ToggleSidebar')).is(name);
};
editor.ui.registry.addToggleButton(name, {
icon: spec.icon,
tooltip: spec.tooltip,
onAction: function (buttonApi) {
editor.execCommand('ToggleSidebar', false, name);
buttonApi.setActive(isActive());
},
onSetup: function (buttonApi) {
var handleToggle = function () {
return buttonApi.setActive(isActive());
};
editor.on('ToggleSidebar', handleToggle);
return function () {
editor.off('ToggleSidebar', handleToggle);
};
}
});
});
};
var getApi = function (comp) {
return {
element: function () {
return comp.element.dom;
}
};
};
var makePanels = function (parts, panelConfigs) {
var specs = map(keys(panelConfigs), function (name) {
var spec = panelConfigs[name];
var bridged = getOrDie(createSidebar(spec));
return {
name: name,
getApi: getApi,
onSetup: bridged.onSetup,
onShow: bridged.onShow,
onHide: bridged.onHide
};
});
return map(specs, function (spec) {
var editorOffCell = Cell(noop);
return parts.slot(spec.name, {
dom: {
tag: 'div',
classes: ['tox-sidebar__pane']
},
behaviours: SimpleBehaviours.unnamedEvents([
onControlAttached(spec, editorOffCell),
onControlDetached(spec, editorOffCell),
run(slotVisibility(), function (sidepanel, se) {
var data = se.event;
var optSidePanelSpec = find(specs, function (config) {
return config.name === data.name;
});
optSidePanelSpec.each(function (sidePanelSpec) {
var handler = data.visible ? sidePanelSpec.onShow : sidePanelSpec.onHide;
handler(sidePanelSpec.getApi(sidepanel));
});
})
])
});
});
};
var makeSidebar = function (panelConfigs) {
return SlotContainer.sketch(function (parts) {
return {
dom: {
tag: 'div',
classes: ['tox-sidebar__pane-container']
},
components: makePanels(parts, panelConfigs),
slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function (slotContainer) {
return SlotContainer.hideAllSlots(slotContainer);
})])
};
});
};
var setSidebar = function (sidebar, panelConfigs) {
var optSlider = Composing.getCurrent(sidebar);
optSlider.each(function (slider) {
return Replacing.set(slider, [makeSidebar(panelConfigs)]);
});
};
var toggleSidebar = function (sidebar, name) {
var optSlider = Composing.getCurrent(sidebar);
optSlider.each(function (slider) {
var optSlotContainer = Composing.getCurrent(slider);
optSlotContainer.each(function (slotContainer) {
if (Sliding.hasGrown(slider)) {
if (SlotContainer.isShowing(slotContainer, name)) {
Sliding.shrink(slider);
} else {
SlotContainer.hideAllSlots(slotContainer);
SlotContainer.showSlot(slotContainer, name);
}
} else {
SlotContainer.hideAllSlots(slotContainer);
SlotContainer.showSlot(slotContainer, name);
Sliding.grow(slider);
}
});
});
};
var whichSidebar = function (sidebar) {
var optSlider = Composing.getCurrent(sidebar);
return optSlider.bind(function (slider) {
var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
if (sidebarOpen) {
var optSlotContainer = Composing.getCurrent(slider);
return optSlotContainer.bind(function (slotContainer) {
return find(SlotContainer.getSlotNames(slotContainer), function (name) {
return SlotContainer.isShowing(slotContainer, name);
});
});
} else {
return Optional.none();
}
});
};
var fixSize = generate$1('FixSizeEvent');
var autoSize = generate$1('AutoSizeEvent');
var renderSidebar = function (spec) {
return {
uid: spec.uid,
dom: {
tag: 'div',
classes: ['tox-sidebar'],
attributes: { role: 'complementary' }
},
components: [{
dom: {
tag: 'div',
classes: ['tox-sidebar__slider']
},
components: [],
behaviours: derive$1([
Tabstopping.config({}),
Focusing.config({}),
Sliding.config({
dimension: { property: 'width' },
closedClass: 'tox-sidebar--sliding-closed',
openClass: 'tox-sidebar--sliding-open',
shrinkingClass: 'tox-sidebar--sliding-shrinking',
growingClass: 'tox-sidebar--sliding-growing',
onShrunk: function (slider) {
var optSlotContainer = Composing.getCurrent(slider);
optSlotContainer.each(SlotContainer.hideAllSlots);
emit(slider, autoSize);
},
onGrown: function (slider) {
emit(slider, autoSize);
},
onStartGrow: function (slider) {
emitWith(slider, fixSize, { width: getRaw(slider.element, 'width').getOr('') });
},
onStartShrink: function (slider) {
emitWith(slider, fixSize, { width: get$8(slider.element) + 'px' });
}
}),
Replacing.config({}),
Composing.config({
find: function (comp) {
var children = Replacing.contents(comp);
return head(children);
}
})
])
}],
behaviours: derive$1([
ComposingConfigs.childAt(0),
config('sidebar-sliding-events', [
run(fixSize, function (comp, se) {
set$2(comp.element, 'width', se.event.width);
}),
run(autoSize, function (comp, _se) {
remove$6(comp.element, 'width');
})
])
])
};
};
var getAttrs = function (elem) {
var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : [];
return foldl(attributes, function (b, attr) {
var _a;
if (attr.name === 'class') {
return b;
} else {
return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
}
}, {});
};
var getClasses = function (elem) {
return Array.prototype.slice.call(elem.dom.classList, 0);
};
var fromHtml$2 = function (html) {
var elem = SugarElement.fromHtml(html);
var children$1 = children(elem);
var attrs = getAttrs(elem);
var classes = getClasses(elem);
var contents = children$1.length === 0 ? {} : { innerHtml: get$2(elem) };
return __assign({
tag: name(elem),
classes: classes,
attributes: attrs
}, contents);
};
var renderSpinner = function (providerBackstage) {
return {
dom: {
tag: 'div',
attributes: { 'aria-label': providerBackstage.translate('Loading...') },
classes: ['tox-throbber__busy-spinner']
},
components: [{ dom: fromHtml$2('') }],
behaviours: derive$1([
Keying.config({
mode: 'special',
onTab: function () {
return Optional.some(true);
},
onShiftTab: function () {
return Optional.some(true);
}
}),
Focusing.config({})
])
};
};
var toggleThrobber = function (comp, state, providerBackstage) {
var element = comp.element;
if (state === true) {
Replacing.set(comp, [renderSpinner(providerBackstage)]);
remove$6(element, 'display');
remove$1(element, 'aria-hidden');
} else {
Replacing.set(comp, []);
set$2(element, 'display', 'none');
set$1(element, 'aria-hidden', 'true');
}
};
var renderThrobber = function (spec) {
return {
uid: spec.uid,
dom: {
tag: 'div',
attributes: { 'aria-hidden': 'true' },
classes: ['tox-throbber'],
styles: { display: 'none' }
},
behaviours: derive$1([Replacing.config({})]),
components: []
};
};
var setup$7 = function (editor, lazyThrobber, sharedBackstage) {
var throbberState = Cell(false);
var timer = Cell(Optional.none());
var toggle = function (state) {
if (state !== throbberState.get()) {
toggleThrobber(lazyThrobber(), state, sharedBackstage.providers);
throbberState.set(state);
editor.fire('AfterProgressState', { state: state });
}
};
editor.on('ProgressState', function (e) {
timer.get().each(global$2.clearTimeout);
if (isNumber(e.time)) {
var timerId = global$2.setEditorTimeout(editor, function () {
return toggle(e.state);
}, e.time);
timer.set(Optional.some(timerId));
} else {
toggle(e.state);
timer.set(Optional.none());
}
});
};
var factory$h = function (detail, components, _spec) {
var apis = {
getSocket: function (comp) {
return parts$d.getPart(comp, detail, 'socket');
},
setSidebar: function (comp, panelConfigs) {
parts$d.getPart(comp, detail, 'sidebar').each(function (sidebar) {
return setSidebar(sidebar, panelConfigs);
});
},
toggleSidebar: function (comp, name) {
parts$d.getPart(comp, detail, 'sidebar').each(function (sidebar) {
return toggleSidebar(sidebar, name);
});
},
whichSidebar: function (comp) {
return parts$d.getPart(comp, detail, 'sidebar').bind(whichSidebar).getOrNull();
},
getHeader: function (comp) {
return parts$d.getPart(comp, detail, 'header');
},
getToolbar: function (comp) {
return parts$d.getPart(comp, detail, 'toolbar');
},
setToolbar: function (comp, groups) {
parts$d.getPart(comp, detail, 'toolbar').each(function (toolbar) {
toolbar.getApis().setGroups(toolbar, groups);
});
},
setToolbars: function (comp, toolbars) {
parts$d.getPart(comp, detail, 'multiple-toolbar').each(function (mToolbar) {
CustomList.setItems(mToolbar, toolbars);
});
},
refreshToolbar: function (comp) {
var toolbar = parts$d.getPart(comp, detail, 'toolbar');
toolbar.each(function (toolbar) {
return toolbar.getApis().refresh(toolbar);
});
},
toggleToolbarDrawer: function (comp) {
parts$d.getPart(comp, detail, 'toolbar').each(function (toolbar) {
mapFrom(toolbar.getApis().toggle, function (toggle) {
return toggle(toolbar);
});
});
},
isToolbarDrawerToggled: function (comp) {
return parts$d.getPart(comp, detail, 'toolbar').bind(function (toolbar) {
return Optional.from(toolbar.getApis().isOpen).map(function (isOpen) {
return isOpen(toolbar);
});
}).getOr(false);
},
getThrobber: function (comp) {
return parts$d.getPart(comp, detail, 'throbber');
},
focusToolbar: function (comp) {
var optToolbar = parts$d.getPart(comp, detail, 'toolbar').orThunk(function () {
return parts$d.getPart(comp, detail, 'multiple-toolbar');
});
optToolbar.each(function (toolbar) {
Keying.focusIn(toolbar);
});
},
setMenubar: function (comp, menus) {
parts$d.getPart(comp, detail, 'menubar').each(function (menubar) {
SilverMenubar.setMenus(menubar, menus);
});
},
focusMenubar: function (comp) {
parts$d.getPart(comp, detail, 'menubar').each(function (menubar) {
SilverMenubar.focus(menubar);
});
}
};
return {
uid: detail.uid,
dom: detail.dom,
components: components,
apis: apis,
behaviours: detail.behaviours
};
};
var partMenubar = partType$1.optional({
factory: SilverMenubar,
name: 'menubar',
schema: [strict$1('backstage')]
});
var toolbarFactory = function (spec) {
if (spec.type === ToolbarMode.sliding) {
return renderSlidingMoreToolbar;
} else if (spec.type === ToolbarMode.floating) {
return renderFloatingMoreToolbar;
} else {
return renderToolbar;
}
};
var partMultipleToolbar = partType$1.optional({
factory: {
sketch: function (spec) {
return CustomList.sketch({
uid: spec.uid,
dom: spec.dom,
listBehaviours: derive$1([Keying.config({
mode: 'acyclic',
selector: '.tox-toolbar'
})]),
makeItem: function () {
return renderToolbar({
type: spec.type,
uid: generate$1('multiple-toolbar-item'),
cyclicKeying: false,
initGroups: [],
providers: spec.providers,
onEscape: function () {
spec.onEscape();
return Optional.some(true);
}
});
},
setupItem: function (_mToolbar, tc, data, _index) {
Toolbar.setGroups(tc, data);
},
shell: true
});
}
},
name: 'multiple-toolbar',
schema: [
strict$1('dom'),
strict$1('onEscape')
]
});
var partToolbar = partType$1.optional({
factory: {
sketch: function (spec) {
var renderer = toolbarFactory(spec);
var toolbarSpec = {
type: spec.type,
uid: spec.uid,
onEscape: function () {
spec.onEscape();
return Optional.some(true);
},
cyclicKeying: false,
initGroups: [],
getSink: spec.getSink,
providers: spec.providers,
moreDrawerData: {
lazyToolbar: spec.lazyToolbar,
lazyMoreButton: spec.lazyMoreButton,
lazyHeader: spec.lazyHeader
},
attributes: spec.attributes
};
return renderer(toolbarSpec);
}
},
name: 'toolbar',
schema: [
strict$1('dom'),
strict$1('onEscape'),
strict$1('getSink')
]
});
var partHeader = partType$1.optional({
factory: { sketch: renderHeader },
name: 'header',
schema: [strict$1('dom')]
});
var partSocket = partType$1.optional({
name: 'socket',
schema: [strict$1('dom')]
});
var partSidebar = partType$1.optional({
factory: { sketch: renderSidebar },
name: 'sidebar',
schema: [strict$1('dom')]
});
var partThrobber = partType$1.optional({
factory: { sketch: renderThrobber },
name: 'throbber',
schema: [strict$1('dom')]
});
var OuterContainer = composite$1({
name: 'OuterContainer',
factory: factory$h,
configFields: [
strict$1('dom'),
strict$1('behaviours')
],
partFields: [
partHeader,
partMenubar,
partToolbar,
partMultipleToolbar,
partSocket,
partSidebar,
partThrobber
],
apis: {
getSocket: function (apis, comp) {
return apis.getSocket(comp);
},
setSidebar: function (apis, comp, panelConfigs) {
apis.setSidebar(comp, panelConfigs);
},
toggleSidebar: function (apis, comp, name) {
apis.toggleSidebar(comp, name);
},
whichSidebar: function (apis, comp) {
return apis.whichSidebar(comp);
},
getHeader: function (apis, comp) {
return apis.getHeader(comp);
},
getToolbar: function (apis, comp) {
return apis.getToolbar(comp);
},
setToolbar: function (apis, comp, grps) {
var groups = map(grps, function (grp) {
return renderToolbarGroup(grp);
});
apis.setToolbar(comp, groups);
},
setToolbars: function (apis, comp, ts) {
var renderedToolbars = map(ts, function (g) {
return map(g, renderToolbarGroup);
});
apis.setToolbars(comp, renderedToolbars);
},
refreshToolbar: function (apis, comp) {
return apis.refreshToolbar(comp);
},
toggleToolbarDrawer: function (apis, comp) {
apis.toggleToolbarDrawer(comp);
},
isToolbarDrawerToggled: function (apis, comp) {
return apis.isToolbarDrawerToggled(comp);
},
getThrobber: function (apis, comp) {
return apis.getThrobber(comp);
},
setMenubar: function (apis, comp, menus) {
apis.setMenubar(comp, menus);
},
focusMenubar: function (apis, comp) {
apis.focusMenubar(comp);
},
focusToolbar: function (apis, comp) {
apis.focusToolbar(comp);
}
}
});
var defaultMenubar = 'file edit view insert format tools table help';
var defaultMenus = {
file: {
title: 'File',
items: 'newdocument restoredraft | preview | export print | deleteallconversations'
},
edit: {
title: 'Edit',
items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'
},
view: {
title: 'View',
items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments'
},
insert: {
title: 'Insert',
items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime'
},
format: {
title: 'Format',
items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | removeformat'
},
tools: {
title: 'Tools',
items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount'
},
table: {
title: 'Table',
items: 'inserttable | cell row column | advtablesort | tableprops deletetable'
},
help: {
title: 'Help',
items: 'help'
}
};
var make$8 = function (menu, registry, editor) {
var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
return {
text: menu.title,
getItems: function () {
return bind(menu.items, function (i) {
var itemName = i.toLowerCase();
if (itemName.trim().length === 0) {
return [];
} else if (exists(removedMenuItems, function (removedMenuItem) {
return removedMenuItem === itemName;
})) {
return [];
} else if (itemName === 'separator' || itemName === '|') {
return [{ type: 'separator' }];
} else if (registry.menuItems[itemName]) {
return [registry.menuItems[itemName]];
} else {
return [];
}
});
}
};
};
var parseItemsString = function (items) {
if (typeof items === 'string') {
return items.split(' ');
}
return items;
};
var identifyMenus = function (editor, registry) {
var rawMenuData = __assign(__assign({}, defaultMenus), registry.menus);
var userDefinedMenus = keys(registry.menus).length > 0;
var menubar = registry.menubar === undefined || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? '' : registry.menubar);
var validMenus = filter(menubar, function (menuName) {
return userDefinedMenus ? registry.menus.hasOwnProperty(menuName) && registry.menus[menuName].hasOwnProperty('items') || defaultMenus.hasOwnProperty(menuName) : defaultMenus.hasOwnProperty(menuName);
});
var menus = map(validMenus, function (menuName) {
var menuData = rawMenuData[menuName];
return make$8({
title: menuData.title,
items: parseItemsString(menuData.items)
}, registry, editor);
});
return filter(menus, function (menu) {
var isNotSeparator = function (item) {
return item.type !== 'separator';
};
return menu.getItems().length > 0 && exists(menu.getItems(), isNotSeparator);
});
};
var fireSkinLoaded$1 = function (editor) {
var done = function () {
editor._skinLoaded = true;
fireSkinLoaded(editor);
};
return function () {
if (editor.initialized) {
done();
} else {
editor.on('init', done);
}
};
};
var fireSkinLoadError$1 = function (editor, err) {
return function () {
return fireSkinLoadError(editor, { message: err });
};
};
var loadStylesheet = function (editor, stylesheetUrl, styleSheetLoader) {
return new global$4(function (resolve, reject) {
styleSheetLoader.load(stylesheetUrl, resolve, reject);
editor.on('remove', function () {
return styleSheetLoader.unload(stylesheetUrl);
});
});
};
var loadUiSkins = function (editor, skinUrl) {
var skinUiCss = skinUrl + '/skin.min.css';
return loadStylesheet(editor, skinUiCss, editor.ui.styleSheetLoader);
};
var loadShadowDomUiSkins = function (editor, skinUrl) {
var isInShadowRoot$1 = isInShadowRoot(SugarElement.fromDom(editor.getElement()));
if (isInShadowRoot$1) {
var shadowDomSkinCss = skinUrl + '/skin.shadowdom.min.css';
return loadStylesheet(editor, shadowDomSkinCss, global$5.DOM.styleSheetLoader);
} else {
return global$4.resolve();
}
};
var loadSkin = function (isInline, editor) {
var skinUrl = getSkinUrl(editor);
if (skinUrl) {
editor.contentCSS.push(skinUrl + (isInline ? '/content.inline' : '/content') + '.min.css');
}
if (isSkinDisabled(editor) === false && isString(skinUrl)) {
global$4.all([
loadUiSkins(editor, skinUrl),
loadShadowDomUiSkins(editor, skinUrl)
]).then(fireSkinLoaded$1(editor), fireSkinLoadError$1(editor, 'Skin could not be loaded'));
} else {
fireSkinLoaded$1(editor)();
}
};
var iframe = curry(loadSkin, false);
var inline = curry(loadSkin, true);
var setToolbar = function (editor, uiComponents, rawUiConfig, backstage) {
var comp = uiComponents.outerContainer;
var toolbarConfig = rawUiConfig.toolbar;
var toolbarButtonsConfig = rawUiConfig.buttons;
if (isArrayOf(toolbarConfig, isString)) {
var toolbars = toolbarConfig.map(function (t) {
var config = {
toolbar: t,
buttons: toolbarButtonsConfig,
allowToolbarGroups: rawUiConfig.allowToolbarGroups
};
return identifyButtons(editor, config, { backstage: backstage }, Optional.none());
});
OuterContainer.setToolbars(comp, toolbars);
} else {
OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage: backstage }, Optional.none()));
}
};
var detection = detect$3();
var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
var setupEvents = function (editor, uiComponents) {
var dom = editor.dom;
var contentWindow = editor.getWin();
var initialDocEle = editor.getDoc().documentElement;
var lastWindowDimensions = Cell(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
var lastDocumentDimensions = Cell(SugarPosition(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
var resizeWindow = function () {
var outer = lastWindowDimensions.get();
if (outer.left !== contentWindow.innerWidth || outer.top !== contentWindow.innerHeight) {
lastWindowDimensions.set(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
fireResizeContent(editor);
}
};
var resizeDocument = function () {
var docEle = editor.getDoc().documentElement;
var inner = lastDocumentDimensions.get();
if (inner.left !== docEle.offsetWidth || inner.top !== docEle.offsetHeight) {
lastDocumentDimensions.set(SugarPosition(docEle.offsetWidth, docEle.offsetHeight));
fireResizeContent(editor);
}
};
var scroll = function (e) {
return fireScrollContent(editor, e);
};
dom.bind(contentWindow, 'resize', resizeWindow);
dom.bind(contentWindow, 'scroll', scroll);
var elementLoad = capture$1(SugarElement.fromDom(editor.getBody()), 'load', resizeDocument);
var mothership = uiComponents.uiMothership.element;
editor.on('hide', function () {
set$2(mothership, 'display', 'none');
});
editor.on('show', function () {
remove$6(mothership, 'display');
});
editor.on('NodeChange', resizeDocument);
editor.on('remove', function () {
elementLoad.unbind();
dom.unbind(contentWindow, 'resize', resizeWindow);
dom.unbind(contentWindow, 'scroll', scroll);
contentWindow = null;
});
};
var render$1 = function (editor, uiComponents, rawUiConfig, backstage, args) {
var lastToolbarWidth = Cell(0);
var outerContainer = uiComponents.outerContainer;
iframe(editor);
var eTargetNode = SugarElement.fromDom(args.targetNode);
var uiRoot = getContentContainer(getRootNode(eTargetNode));
attachSystemAfter(eTargetNode, uiComponents.mothership);
attachSystem(uiRoot, uiComponents.uiMothership);
editor.on('PostRender', function () {
setToolbar(editor, uiComponents, rawUiConfig, backstage);
lastToolbarWidth.set(editor.getWin().innerWidth);
OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
OuterContainer.setSidebar(outerContainer, rawUiConfig.sidebar);
setupEvents(editor, uiComponents);
});
var socket = OuterContainer.getSocket(outerContainer).getOrDie('Could not find expected socket element');
if (isiOS12) {
setAll$1(socket.element, {
'overflow': 'scroll',
'-webkit-overflow-scrolling': 'touch'
});
var limit = first(function () {
editor.fire('ScrollContent');
}, 20);
var unbinder = bind$3(socket.element, 'scroll', limit.throttle);
editor.on('remove', unbinder.unbind);
}
setupReadonlyModeSwitch(editor, uiComponents);
editor.addCommand('ToggleSidebar', function (_ui, value) {
OuterContainer.toggleSidebar(outerContainer, value);
editor.fire('ToggleSidebar');
});
editor.addQueryValueHandler('ToggleSidebar', function () {
return OuterContainer.whichSidebar(outerContainer);
});
var toolbarMode = getToolbarMode(editor);
var refreshDrawer = function () {
OuterContainer.refreshToolbar(uiComponents.outerContainer);
};
if (toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating) {
editor.on('ResizeWindow ResizeEditor ResizeContent', function () {
var width = editor.getWin().innerWidth;
if (width !== lastToolbarWidth.get()) {
refreshDrawer();
lastToolbarWidth.set(width);
}
});
}
var api = {
enable: function () {
broadcastReadonly(uiComponents, false);
},
disable: function () {
broadcastReadonly(uiComponents, true);
},
isDisabled: function () {
return Disabling.isDisabled(outerContainer);
}
};
return {
iframeContainer: socket.element.dom,
editorContainer: outerContainer.element.dom,
api: api
};
};
var Iframe = /*#__PURE__*/Object.freeze({
__proto__: null,
render: render$1
});
var parseToInt = function (val) {
var re = /^[0-9\.]+(|px)$/i;
if (re.test('' + val)) {
return Optional.some(parseInt('' + val, 10));
}
return Optional.none();
};
var numToPx = function (val) {
return isNumber(val) ? val + 'px' : val;
};
var calcCappedSize = function (size, minSize, maxSize) {
var minOverride = minSize.filter(function (min) {
return size < min;
});
var maxOverride = maxSize.filter(function (max) {
return size > max;
});
return minOverride.or(maxOverride).getOr(size);
};
var getHeight$1 = function (editor) {
var baseHeight = getHeightSetting(editor);
var minHeight = getMinHeightSetting(editor);
var maxHeight = getMaxHeightSetting(editor);
return parseToInt(baseHeight).map(function (height) {
return calcCappedSize(height, minHeight, maxHeight);
});
};
var getHeightWithFallback = function (editor) {
var height = getHeight$1(editor);
return height.getOr(getHeightSetting(editor));
};
var getWidth$1 = function (editor) {
var baseWidth = getWidthSetting(editor);
var minWidth = getMinWidthSetting(editor);
var maxWidth = getMaxWidthSetting(editor);
return parseToInt(baseWidth).map(function (width) {
return calcCappedSize(width, minWidth, maxWidth);
});
};
var getWidthWithFallback = function (editor) {
var width = getWidth$1(editor);
return width.getOr(getWidthSetting(editor));
};
var InlineHeader = function (editor, targetElm, uiComponents, backstage, floatContainer) {
var uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
var DOM = global$5.DOM;
var useFixedToolbarContainer = useFixedContainer(editor);
var isSticky = isStickyToolbar(editor);
var editorMaxWidthOpt = getMaxWidthSetting(editor).or(getWidth$1(editor));
var headerBackstage = backstage.shared.header;
var isPositionedAtTop = headerBackstage.isPositionedAtTop;
var toolbarMode = getToolbarMode(editor);
var isSplitToolbar = toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating;
var visible = Cell(false);
var isVisible = function () {
return visible.get() && !editor.removed;
};
var calcToolbarOffset = function (toolbar) {
return isSplitToolbar ? toolbar.fold(function () {
return 0;
}, function (tbar) {
return tbar.components().length > 1 ? get$7(tbar.components()[1].element) : 0;
}) : 0;
};
var calcMode = function (container) {
switch (getToolbarLocation(editor)) {
case ToolbarLocation.auto:
var toolbar_1 = OuterContainer.getToolbar(outerContainer);
var offset = calcToolbarOffset(toolbar_1);
var toolbarHeight = get$7(container.element) - offset;
var targetBounds = box(targetElm);
var roomAtTop = targetBounds.y > toolbarHeight;
if (roomAtTop) {
return 'top';
} else {
var doc = documentElement(targetElm);
var docHeight = Math.max(doc.dom.scrollHeight, get$7(doc));
var roomAtBottom = targetBounds.bottom < docHeight - toolbarHeight;
if (roomAtBottom) {
return 'bottom';
} else {
var winBounds = win();
var isRoomAtBottomViewport = winBounds.bottom < targetBounds.bottom - toolbarHeight;
return isRoomAtBottomViewport ? 'bottom' : 'top';
}
}
case ToolbarLocation.bottom:
return 'bottom';
case ToolbarLocation.top:
default:
return 'top';
}
};
var setupMode = function (mode) {
var container = floatContainer.get();
Docking.setModes(container, [mode]);
headerBackstage.setDockingMode(mode);
var verticalDir = isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop;
set$1(container.element, Attribute, verticalDir);
};
var updateChromeWidth = function () {
var maxWidth = editorMaxWidthOpt.getOrThunk(function () {
var bodyMargin = parseToInt(get$5(body(), 'margin-left')).getOr(0);
return get$8(body()) - absolute(targetElm).left + bodyMargin;
});
set$2(floatContainer.get().element, 'max-width', maxWidth + 'px');
};
var updateChromePosition = function () {
var toolbar = OuterContainer.getToolbar(outerContainer);
var offset = calcToolbarOffset(toolbar);
var targetBounds = box(targetElm);
var top = isPositionedAtTop() ? Math.max(targetBounds.y - get$7(floatContainer.get().element) + offset, 0) : targetBounds.bottom;
setAll$1(outerContainer.element, {
position: 'absolute',
top: Math.round(top) + 'px',
left: Math.round(targetBounds.x) + 'px'
});
};
var repositionPopups$1 = function () {
uiMothership.broadcastOn([repositionPopups()], {});
};
var updateChromeUi = function (resetDocking) {
if (resetDocking === void 0) {
resetDocking = false;
}
if (!isVisible()) {
return;
}
if (!useFixedToolbarContainer) {
updateChromeWidth();
}
if (isSplitToolbar) {
OuterContainer.refreshToolbar(outerContainer);
}
if (!useFixedToolbarContainer) {
updateChromePosition();
}
if (isSticky) {
var floatContainerComp = floatContainer.get();
resetDocking ? Docking.reset(floatContainerComp) : Docking.refresh(floatContainerComp);
}
repositionPopups$1();
};
var updateMode = function (updateUi) {
if (updateUi === void 0) {
updateUi = true;
}
if (useFixedToolbarContainer || !isSticky || !isVisible()) {
return;
}
var currentMode = headerBackstage.getDockingMode();
var newMode = calcMode(floatContainer.get());
if (newMode !== currentMode) {
setupMode(newMode);
if (updateUi) {
updateChromeUi(true);
}
}
};
var show = function () {
visible.set(true);
set$2(outerContainer.element, 'display', 'flex');
DOM.addClass(editor.getBody(), 'mce-edit-focus');
remove$6(uiMothership.element, 'display');
updateMode(false);
updateChromeUi();
};
var hide = function () {
visible.set(false);
if (uiComponents.outerContainer) {
set$2(outerContainer.element, 'display', 'none');
DOM.removeClass(editor.getBody(), 'mce-edit-focus');
}
set$2(uiMothership.element, 'display', 'none');
};
return {
isVisible: isVisible,
isPositionedAtTop: isPositionedAtTop,
show: show,
hide: hide,
update: updateChromeUi,
updateMode: updateMode,
repositionPopups: repositionPopups$1
};
};
var getTargetPosAndBounds = function (targetElm, isToolbarTop) {
var bounds = box(targetElm);
return {
pos: isToolbarTop ? bounds.y : bounds.bottom,
bounds: bounds
};
};
var setupEvents$1 = function (editor, targetElm, ui, toolbarPersist) {
var prevPosAndBounds = Cell(getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()));
var resizeContent = function (e) {
var _a = getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()), pos = _a.pos, bounds = _a.bounds;
var _b = prevPosAndBounds.get(), prevPos = _b.pos, prevBounds = _b.bounds;
var hasResized = bounds.height !== prevBounds.height || bounds.width !== prevBounds.width;
prevPosAndBounds.set({
pos: pos,
bounds: bounds
});
if (hasResized) {
fireResizeContent(editor, e);
}
if (ui.isVisible()) {
if (prevPos !== pos) {
ui.update(true);
} else if (hasResized) {
ui.updateMode();
ui.repositionPopups();
}
}
};
if (!toolbarPersist) {
editor.on('activate', ui.show);
editor.on('deactivate', ui.hide);
}
editor.on('SkinLoaded ResizeWindow', function () {
return ui.update(true);
});
editor.on('NodeChange keydown', function (e) {
global$2.requestAnimationFrame(function () {
return resizeContent(e);
});
});
editor.on('ScrollWindow', function () {
return ui.updateMode();
});
var elementLoad = unbindable();
elementLoad.set(capture$1(SugarElement.fromDom(editor.getBody()), 'load', resizeContent));
editor.on('remove', function () {
elementLoad.clear();
});
};
var render$2 = function (editor, uiComponents, rawUiConfig, backstage, args) {
var mothership = uiComponents.mothership, uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
var floatContainer = Cell(null);
var targetElm = SugarElement.fromDom(args.targetNode);
var ui = InlineHeader(editor, targetElm, uiComponents, backstage, floatContainer);
var toolbarPersist = isToolbarPersist(editor);
inline(editor);
var render = function () {
if (floatContainer.get()) {
ui.show();
return;
}
floatContainer.set(OuterContainer.getHeader(outerContainer).getOrDie());
var uiContainer = getUiContainer(editor);
attachSystem(uiContainer, mothership);
attachSystem(uiContainer, uiMothership);
setToolbar(editor, uiComponents, rawUiConfig, backstage);
OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
ui.show();
setupEvents$1(editor, targetElm, ui, toolbarPersist);
editor.nodeChanged();
};
var delayedRender = function () {
return global$2.setEditorTimeout(editor, render, 0);
};
editor.on('show', render);
editor.on('hide', ui.hide);
if (!toolbarPersist) {
editor.on('focus', delayedRender);
editor.on('blur', ui.hide);
}
editor.on('init', function () {
if (editor.hasFocus() || toolbarPersist) {
delayedRender();
}
});
setupReadonlyModeSwitch(editor, uiComponents);
var api = {
show: function () {
ui.show();
},
hide: function () {
ui.hide();
},
enable: function () {
broadcastReadonly(uiComponents, false);
},
disable: function () {
broadcastReadonly(uiComponents, true);
},
isDisabled: function () {
return Disabling.isDisabled(outerContainer);
}
};
return {
editorContainer: outerContainer.element.dom,
api: api
};
};
var Inline = /*#__PURE__*/Object.freeze({
__proto__: null,
render: render$2
});
var register$5 = function (editor) {
var alignToolbarButtons = [
{
name: 'alignleft',
text: 'Align left',
cmd: 'JustifyLeft',
icon: 'align-left'
},
{
name: 'aligncenter',
text: 'Align center',
cmd: 'JustifyCenter',
icon: 'align-center'
},
{
name: 'alignright',
text: 'Align right',
cmd: 'JustifyRight',
icon: 'align-right'
},
{
name: 'alignjustify',
text: 'Justify',
cmd: 'JustifyFull',
icon: 'align-justify'
}
];
global$c.each(alignToolbarButtons, function (item) {
editor.ui.registry.addToggleButton(item.name, {
tooltip: item.text,
onAction: function () {
return editor.execCommand(item.cmd);
},
icon: item.icon,
onSetup: onSetupFormatToggle(editor, item.name)
});
});
var alignNoneToolbarButton = {
name: 'alignnone',
text: 'No alignment',
cmd: 'JustifyNone',
icon: 'align-none'
};
editor.ui.registry.addButton(alignNoneToolbarButton.name, {
tooltip: alignNoneToolbarButton.text,
onAction: function () {
return editor.execCommand(alignNoneToolbarButton.cmd);
},
icon: alignNoneToolbarButton.icon
});
};
var register$6 = function (editor, backstage) {
alignSelectMenu(editor, backstage);
fontSelectMenu(editor, backstage);
styleSelectMenu(editor, backstage);
formatSelectMenu(editor, backstage);
fontsizeSelectMenu(editor, backstage);
};
var toggleOutdentState = function (api, editor) {
api.setDisabled(!editor.queryCommandState('outdent'));
var onNodeChange = function () {
api.setDisabled(!editor.queryCommandState('outdent'));
};
editor.on('NodeChange', onNodeChange);
return function () {
return editor.off('NodeChange', onNodeChange);
};
};
var registerButtons = function (editor) {
editor.ui.registry.addButton('outdent', {
tooltip: 'Decrease indent',
icon: 'outdent',
onSetup: function (api) {
return toggleOutdentState(api, editor);
},
onAction: function () {
return editor.execCommand('outdent');
}
});
editor.ui.registry.addButton('indent', {
tooltip: 'Increase indent',
icon: 'indent',
onAction: function () {
return editor.execCommand('indent');
}
});
};
var register$7 = function (editor) {
registerButtons(editor);
};
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 pattern = 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 float = '[+-]?(?:' + unsignedDecimalLiteral + ')';
return new RegExp('^(' + float + ')(.*)$');
}();
var isUnit = function (unit, accepted) {
return exists(accepted, function (acc) {
return exists(units[acc], function (check) {
return unit === check;
});
});
};
var parse = function (input, accepted) {
var match = Optional.from(pattern.exec(input));
return match.bind(function (array) {
var value = Number(array[1]);
var unitRaw = array[2];
if (isUnit(unitRaw, accepted)) {
return Optional.some({
value: value,
unit: unitRaw
});
} else {
return Optional.none();
}
});
};
var normalise = function (input, accepted) {
return parse(input, accepted).map(function (_a) {
var value = _a.value, unit = _a.unit;
return value + unit;
});
};
var normaliseLineHeight = function (input) {
return normalise(input, [
'fixed',
'relative',
'empty'
]).getOr(input);
};
var getLineHeights = function (editor) {
var options = getLineHeightFormats(editor);
var apis = new Map();
var lastApi = destroyable();
var callback = function () {
var current = normaliseLineHeight(editor.queryCommandValue('LineHeight'));
Optional.from(apis.get(current)).fold(function () {
return lastApi.clear();
}, function (api) {
lastApi.set({
destroy: function () {
api.setActive(false);
}
});
api.setActive(true);
});
};
editor.on('nodeChange', callback);
return map(options, function (value, i) {
return {
type: 'togglemenuitem',
text: value,
onSetup: function (api) {
apis.set(normaliseLineHeight(value), api);
if (i + 1 === options.length) {
callback();
}
return function () {
if (i === 0) {
editor.off('nodeChange', callback);
lastApi.clear();
}
};
},
onAction: function () {
return editor.execCommand('LineHeight', false, value);
}
};
});
};
var registerMenuItems = function (editor) {
editor.ui.registry.addNestedMenuItem('lineheight', {
type: 'nestedmenuitem',
text: 'Line height',
getSubmenuItems: function () {
return getLineHeights(editor);
}
});
};
var registerButtons$1 = function (editor) {
editor.ui.registry.addMenuButton('lineheight', {
tooltip: 'Line height',
icon: 'line-height',
fetch: function (callback) {
return callback(getLineHeights(editor));
}
});
};
var register$8 = function (editor) {
registerMenuItems(editor);
registerButtons$1(editor);
};
var toggleFormat = function (editor, fmt) {
return function () {
editor.execCommand('mceToggleFormat', false, fmt);
};
};
var registerFormatButtons = function (editor) {
global$c.each([
{
name: 'bold',
text: 'Bold',
icon: 'bold'
},
{
name: 'italic',
text: 'Italic',
icon: 'italic'
},
{
name: 'underline',
text: 'Underline',
icon: 'underline'
},
{
name: 'strikethrough',
text: 'Strikethrough',
icon: 'strike-through'
},
{
name: 'subscript',
text: 'Subscript',
icon: 'subscript'
},
{
name: 'superscript',
text: 'Superscript',
icon: 'superscript'
}
], function (btn, _idx) {
editor.ui.registry.addToggleButton(btn.name, {
tooltip: btn.text,
icon: btn.icon,
onSetup: onSetupFormatToggle(editor, btn.name),
onAction: toggleFormat(editor, btn.name)
});
});
for (var i = 1; i <= 6; i++) {
var name_1 = 'h' + i;
editor.ui.registry.addToggleButton(name_1, {
text: name_1.toUpperCase(),
tooltip: 'Heading ' + i,
onSetup: onSetupFormatToggle(editor, name_1),
onAction: toggleFormat(editor, name_1)
});
}
};
var registerCommandButtons = function (editor) {
global$c.each([
{
name: 'cut',
text: 'Cut',
action: 'Cut',
icon: 'cut'
},
{
name: 'copy',
text: 'Copy',
action: 'Copy',
icon: 'copy'
},
{
name: 'paste',
text: 'Paste',
action: 'Paste',
icon: 'paste'
},
{
name: 'help',
text: 'Help',
action: 'mceHelp',
icon: 'help'
},
{
name: 'selectall',
text: 'Select all',
action: 'SelectAll',
icon: 'select-all'
},
{
name: 'newdocument',
text: 'New document',
action: 'mceNewDocument',
icon: 'new-document'
},
{
name: 'removeformat',
text: 'Clear formatting',
action: 'RemoveFormat',
icon: 'remove-formatting'
},
{
name: 'remove',
text: 'Remove',
action: 'Delete',
icon: 'remove'
}
], function (btn) {
editor.ui.registry.addButton(btn.name, {
tooltip: btn.text,
icon: btn.icon,
onAction: function () {
return editor.execCommand(btn.action);
}
});
});
};
var registerCommandToggleButtons = function (editor) {
global$c.each([{
name: 'blockquote',
text: 'Blockquote',
action: 'mceBlockQuote',
icon: 'quote'
}], function (btn) {
editor.ui.registry.addToggleButton(btn.name, {
tooltip: btn.text,
icon: btn.icon,
onAction: function () {
return editor.execCommand(btn.action);
},
onSetup: onSetupFormatToggle(editor, btn.name)
});
});
};
var registerButtons$2 = function (editor) {
registerFormatButtons(editor);
registerCommandButtons(editor);
registerCommandToggleButtons(editor);
};
var registerMenuItems$1 = function (editor) {
global$c.each([
{
name: 'bold',
text: 'Bold',
action: 'Bold',
icon: 'bold',
shortcut: 'Meta+B'
},
{
name: 'italic',
text: 'Italic',
action: 'Italic',
icon: 'italic',
shortcut: 'Meta+I'
},
{
name: 'underline',
text: 'Underline',
action: 'Underline',
icon: 'underline',
shortcut: 'Meta+U'
},
{
name: 'strikethrough',
text: 'Strikethrough',
action: 'Strikethrough',
icon: 'strike-through',
shortcut: ''
},
{
name: 'subscript',
text: 'Subscript',
action: 'Subscript',
icon: 'subscript',
shortcut: ''
},
{
name: 'superscript',
text: 'Superscript',
action: 'Superscript',
icon: 'superscript',
shortcut: ''
},
{
name: 'removeformat',
text: 'Clear formatting',
action: 'RemoveFormat',
icon: 'remove-formatting',
shortcut: ''
},
{
name: 'newdocument',
text: 'New document',
action: 'mceNewDocument',
icon: 'new-document',
shortcut: ''
},
{
name: 'cut',
text: 'Cut',
action: 'Cut',
icon: 'cut',
shortcut: 'Meta+X'
},
{
name: 'copy',
text: 'Copy',
action: 'Copy',
icon: 'copy',
shortcut: 'Meta+C'
},
{
name: 'paste',
text: 'Paste',
action: 'Paste',
icon: 'paste',
shortcut: 'Meta+V'
},
{
name: 'selectall',
text: 'Select all',
action: 'SelectAll',
icon: 'select-all',
shortcut: 'Meta+A'
}
], function (btn) {
editor.ui.registry.addMenuItem(btn.name, {
text: btn.text,
icon: btn.icon,
shortcut: btn.shortcut,
onAction: function () {
return editor.execCommand(btn.action);
}
});
});
editor.ui.registry.addMenuItem('codeformat', {
text: 'Code',
icon: 'sourcecode',
onAction: toggleFormat(editor, 'code')
});
};
var register$9 = function (editor) {
registerButtons$2(editor);
registerMenuItems$1(editor);
};
var toggleUndoRedoState = function (api, editor, type) {
var checkState = function () {
return editor.undoManager ? editor.undoManager[type]() : false;
};
var onUndoStateChange = function () {
api.setDisabled(editor.mode.isReadOnly() || !checkState());
};
api.setDisabled(!checkState());
editor.on('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', onUndoStateChange);
return function () {
return editor.off('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', onUndoStateChange);
};
};
var registerMenuItems$2 = function (editor) {
editor.ui.registry.addMenuItem('undo', {
text: 'Undo',
icon: 'undo',
shortcut: 'Meta+Z',
onSetup: function (api) {
return toggleUndoRedoState(api, editor, 'hasUndo');
},
onAction: function () {
return editor.execCommand('undo');
}
});
editor.ui.registry.addMenuItem('redo', {
text: 'Redo',
icon: 'redo',
shortcut: 'Meta+Y',
onSetup: function (api) {
return toggleUndoRedoState(api, editor, 'hasRedo');
},
onAction: function () {
return editor.execCommand('redo');
}
});
};
var registerButtons$3 = function (editor) {
editor.ui.registry.addButton('undo', {
tooltip: 'Undo',
icon: 'undo',
onSetup: function (api) {
return toggleUndoRedoState(api, editor, 'hasUndo');
},
onAction: function () {
return editor.execCommand('undo');
}
});
editor.ui.registry.addButton('redo', {
tooltip: 'Redo',
icon: 'redo',
onSetup: function (api) {
return toggleUndoRedoState(api, editor, 'hasRedo');
},
onAction: function () {
return editor.execCommand('redo');
}
});
};
var register$a = function (editor) {
registerMenuItems$2(editor);
registerButtons$3(editor);
};
var toggleVisualAidState = function (api, editor) {
api.setActive(editor.hasVisual);
var onVisualAid = function (e) {
api.setActive(e.hasVisual);
};
editor.on('VisualAid', onVisualAid);
return function () {
return editor.off('VisualAid', onVisualAid);
};
};
var registerMenuItems$3 = function (editor) {
editor.ui.registry.addToggleMenuItem('visualaid', {
text: 'Visual aids',
onSetup: function (api) {
return toggleVisualAidState(api, editor);
},
onAction: function () {
editor.execCommand('mceToggleVisualAid');
}
});
};
var registerToolbarButton = function (editor) {
editor.ui.registry.addButton('visualaid', {
tooltip: 'Visual aids',
text: 'Visual aids',
onAction: function () {
return editor.execCommand('mceToggleVisualAid');
}
});
};
var register$b = function (editor) {
registerToolbarButton(editor);
registerMenuItems$3(editor);
};
var setup$8 = function (editor, backstage) {
register$5(editor);
register$9(editor);
register$6(editor, backstage);
register$a(editor);
register$1(editor);
register$b(editor);
register$7(editor);
register$8(editor);
};
var nu$d = function (x, y) {
return {
anchor: 'makeshift',
x: x,
y: y
};
};
var transpose$1 = function (pos, dx, dy) {
return nu$d(pos.x + dx, pos.y + dy);
};
var isTouchEvent$1 = function (e) {
return e.type === 'longpress' || e.type.indexOf('touch') === 0;
};
var fromPageXY = function (e) {
if (isTouchEvent$1(e)) {
var touch = e.touches[0];
return nu$d(touch.pageX, touch.pageY);
} else {
return nu$d(e.pageX, e.pageY);
}
};
var fromClientXY = function (e) {
if (isTouchEvent$1(e)) {
var touch = e.touches[0];
return nu$d(touch.clientX, touch.clientY);
} else {
return nu$d(e.clientX, e.clientY);
}
};
var transposeContentAreaContainer = function (element, pos) {
var containerPos = global$5.DOM.getPos(element);
return transpose$1(pos, containerPos.x, containerPos.y);
};
var getPointAnchor = function (editor, e) {
if (e.type === 'contextmenu' || e.type === 'longpress') {
if (editor.inline) {
return fromPageXY(e);
} else {
return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
}
} else {
return getSelectionAnchor(editor);
}
};
var getSelectionAnchor = function (editor) {
return {
anchor: 'selection',
root: SugarElement.fromDom(editor.selection.getNode())
};
};
var getNodeAnchor$1 = function (editor) {
return {
anchor: 'node',
node: Optional.some(SugarElement.fromDom(editor.selection.getNode())),
root: SugarElement.fromDom(editor.getBody())
};
};
var initAndShow = function (editor, e, buildMenu, backstage, contextmenu, useNodeAnchor) {
var items = buildMenu();
var anchorSpec = useNodeAnchor ? getNodeAnchor$1(editor) : getPointAnchor(editor, e);
build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function (menuData) {
e.preventDefault();
InlineView.showMenuAt(contextmenu, anchorSpec, {
menu: { markers: markers$1('normal') },
data: menuData
});
});
};
var layouts = {
onLtr: function () {
return [
south$1,
southeast$1,
southwest$1,
northeast$1,
northwest$1,
north$1,
north$3,
south$3,
northeast$3,
southeast$3,
northwest$3,
southwest$3
];
},
onRtl: function () {
return [
south$1,
southwest$1,
southeast$1,
northwest$1,
northeast$1,
north$1,
north$3,
south$3,
northwest$3,
southwest$3,
northeast$3,
southeast$3
];
}
};
var bubbleSize$1 = 12;
var bubbleAlignments$2 = {
valignCentre: [],
alignCentre: [],
alignLeft: ['tox-pop--align-left'],
alignRight: ['tox-pop--align-right'],
right: ['tox-pop--right'],
left: ['tox-pop--left'],
bottom: ['tox-pop--bottom'],
top: ['tox-pop--top']
};
var isTouchWithinSelection = function (editor, e) {
var selection = editor.selection;
if (selection.isCollapsed() || e.touches.length < 1) {
return false;
} else {
var touch_1 = e.touches[0];
var rng = selection.getRng();
var rngRectOpt = getFirstRect$1(editor.getWin(), SimSelection.domRange(rng));
return rngRectOpt.exists(function (rngRect) {
return rngRect.left <= touch_1.clientX && rngRect.right >= touch_1.clientX && rngRect.top <= touch_1.clientY && rngRect.bottom >= touch_1.clientY;
});
}
};
var getPointAnchorSpec = function (editor, e) {
return __assign({
bubble: nu$8(0, bubbleSize$1, bubbleAlignments$2),
layouts: layouts,
overrides: {
maxWidthFunction: expandable$1(),
maxHeightFunction: expandable()
}
}, getPointAnchor(editor, e));
};
var setupiOSOverrides = function (editor) {
var originalSelection = editor.selection.getRng();
var selectionReset = function () {
global$2.setEditorTimeout(editor, function () {
editor.selection.setRng(originalSelection);
}, 10);
unbindEventListeners();
};
editor.once('touchend', selectionReset);
var preventMousedown = function (e) {
e.preventDefault();
e.stopImmediatePropagation();
};
editor.on('mousedown', preventMousedown, true);
var clearSelectionReset = function () {
return unbindEventListeners();
};
editor.once('longpresscancel', clearSelectionReset);
var unbindEventListeners = function () {
editor.off('touchend', selectionReset);
editor.off('longpresscancel', clearSelectionReset);
editor.off('mousedown', preventMousedown);
};
};
var show = function (editor, e, items, backstage, contextmenu, useNodeAnchor, highlightImmediately) {
var anchorSpec = useNodeAnchor ? getNodeAnchor$1(editor) : getPointAnchorSpec(editor, e);
build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function (menuData) {
e.preventDefault();
InlineView.showMenuWithinBounds(contextmenu, anchorSpec, {
menu: {
markers: markers$1('normal'),
highlightImmediately: highlightImmediately
},
data: menuData,
type: 'horizontal'
}, function () {
return Optional.some(getContextToolbarBounds(editor, backstage.shared));
});
editor.fire(hideContextToolbarEvent);
});
};
var initAndShow$1 = function (editor, e, buildMenu, backstage, contextmenu, useNodeAnchor) {
var detection = detect$3();
var isiOS = detection.os.isiOS();
var isOSX = detection.os.isOSX();
var isAndroid = detection.os.isAndroid();
var isTouch = detection.deviceType.isTouch();
var shouldHighlightImmediately = function () {
return !(isAndroid || isiOS || isOSX && isTouch);
};
var open = function () {
var items = buildMenu();
show(editor, e, items, backstage, contextmenu, useNodeAnchor, shouldHighlightImmediately());
};
if ((isOSX || isiOS) && !useNodeAnchor) {
var openiOS_1 = function () {
setupiOSOverrides(editor);
open();
};
if (isTouchWithinSelection(editor, e)) {
openiOS_1();
} else {
editor.once('selectionchange', openiOS_1);
editor.once('touchend', function () {
return editor.off('selectionchange', openiOS_1);
});
}
} else {
if (isAndroid && !useNodeAnchor) {
editor.selection.setCursorLocation(e.target, 0);
}
open();
}
};
var patchPipeConfig = function (config) {
return typeof config === 'string' ? config.split(/[ ,]/) : config;
};
var shouldNeverUseNative = function (editor) {
return editor.getParam('contextmenu_never_use_native', false, 'boolean');
};
var getMenuItems = function (editor, name, defaultItems) {
var contextMenus = editor.ui.registry.getAll().contextMenus;
return Optional.from(editor.getParam(name)).map(patchPipeConfig).getOrThunk(function () {
return filter(patchPipeConfig(defaultItems), function (item) {
return has(contextMenus, item);
});
});
};
var isContextMenuDisabled = function (editor) {
return editor.getParam('contextmenu') === false;
};
var getContextMenu = function (editor) {
return getMenuItems(editor, 'contextmenu', 'link linkchecker image imagetools table spellchecker configurepermanentpen');
};
var getAvoidOverlapSelector = function (editor) {
return editor.getParam('contextmenu_avoid_overlap', '', 'string');
};
var isSeparator$1 = function (item) {
return isString(item) ? item === '|' : item.type === 'separator';
};
var separator$3 = { type: 'separator' };
var makeContextItem = function (item) {
var commonMenuItem = function (item) {
return {
text: item.text,
icon: item.icon,
disabled: item.disabled,
shortcut: item.shortcut
};
};
if (isString(item)) {
return item;
} else {
switch (item.type) {
case 'separator':
return separator$3;
case 'submenu':
return __assign(__assign({ type: 'nestedmenuitem' }, commonMenuItem(item)), {
getSubmenuItems: function () {
var items = item.getSubmenuItems();
if (isString(items)) {
return items;
} else {
return map(items, makeContextItem);
}
}
});
default:
return __assign(__assign({ type: 'menuitem' }, commonMenuItem(item)), { onAction: noarg(item.onAction) });
}
}
};
var addContextMenuGroup = function (xs, groupItems) {
if (groupItems.length === 0) {
return xs;
}
var lastMenuItem = last(xs).filter(function (item) {
return !isSeparator$1(item);
});
var before = lastMenuItem.fold(function () {
return [];
}, function (_) {
return [separator$3];
});
return xs.concat(before).concat(groupItems).concat([separator$3]);
};
var generateContextMenu = function (contextMenus, menuConfig, selectedElement) {
var sections = foldl(menuConfig, function (acc, name) {
return get$1(contextMenus, name.toLowerCase()).map(function (menu) {
var items = menu.update(selectedElement);
if (isString(items)) {
return addContextMenuGroup(acc, items.split(' '));
} else if (items.length > 0) {
var allItems = map(items, makeContextItem);
return addContextMenuGroup(acc, allItems);
} else {
return acc;
}
}).getOrThunk(function () {
return acc.concat([name]);
});
}, []);
if (sections.length > 0 && isSeparator$1(sections[sections.length - 1])) {
sections.pop();
}
return sections;
};
var isNativeOverrideKeyEvent = function (editor, e) {
return e.ctrlKey && !shouldNeverUseNative(editor);
};
var isTriggeredByKeyboard = function (editor, e) {
return e.type !== 'longpress' && (e.button !== 2 || e.target === editor.getBody() && e.pointerType === '');
};
var getSelectedElement = function (editor, e) {
return isTriggeredByKeyboard(editor, e) ? editor.selection.getStart(true) : e.target;
};
var shouldUseNodeAnchor = function (editor, e) {
var selector = getAvoidOverlapSelector(editor);
if (isTriggeredByKeyboard(editor, e)) {
return true;
} else if (selector) {
var target = getSelectedElement(editor, e);
return closest$4(SugarElement.fromDom(target), selector);
} else {
return false;
}
};
var setup$9 = function (editor, lazySink, backstage) {
var detection = detect$3();
var isTouch = detection.deviceType.isTouch;
var contextmenu = build$1(InlineView.sketch({
dom: { tag: 'div' },
lazySink: lazySink,
onEscape: function () {
return editor.focus();
},
onShow: function () {
return backstage.setContextMenuState(true);
},
onHide: function () {
return backstage.setContextMenuState(false);
},
fireDismissalEventInstead: {},
inlineBehaviours: derive$1([config('dismissContextMenu', [run(dismissRequested(), function (comp, _se) {
Sandboxing.close(comp);
editor.focus();
})])])
}));
var hideContextMenu = function (_e) {
return InlineView.hide(contextmenu);
};
var showContextMenu = function (e) {
if (shouldNeverUseNative(editor)) {
e.preventDefault();
}
if (isNativeOverrideKeyEvent(editor, e) || isContextMenuDisabled(editor)) {
return;
}
var useNodeAnchor = shouldUseNodeAnchor(editor, e);
var buildMenu = function () {
var selectedElement = getSelectedElement(editor, e);
var registry = editor.ui.registry.getAll();
var menuConfig = getContextMenu(editor);
return generateContextMenu(registry.contextMenus, menuConfig, selectedElement);
};
var initAndShow$2 = isTouch() ? initAndShow$1 : initAndShow;
initAndShow$2(editor, e, buildMenu, backstage, contextmenu, useNodeAnchor);
};
editor.on('init', function () {
var hideEvents = 'ResizeEditor ScrollContent ScrollWindow longpresscancel' + (isTouch() ? '' : ' ResizeWindow');
editor.on(hideEvents, hideContextMenu);
editor.on('longpress contextmenu', showContextMenu);
});
};
var adt$c = Adt.generate([
{
offset: [
'x',
'y'
]
},
{
absolute: [
'x',
'y'
]
},
{
fixed: [
'x',
'y'
]
}
]);
var subtract = function (change) {
return function (point) {
return point.translate(-change.left, -change.top);
};
};
var add$4 = function (change) {
return function (point) {
return point.translate(change.left, change.top);
};
};
var transform$1 = function (changes) {
return function (x, y) {
return foldl(changes, function (rest, f) {
return f(rest);
}, SugarPosition(x, y));
};
};
var asFixed = function (coord, scroll, origin) {
return coord.fold(transform$1([
add$4(origin),
subtract(scroll)
]), transform$1([subtract(scroll)]), transform$1([]));
};
var asAbsolute = function (coord, scroll, origin) {
return coord.fold(transform$1([add$4(origin)]), transform$1([]), transform$1([add$4(scroll)]));
};
var asOffset = function (coord, scroll, origin) {
return coord.fold(transform$1([]), transform$1([subtract(origin)]), transform$1([
add$4(scroll),
subtract(origin)
]));
};
var withinRange = function (coord1, coord2, xRange, yRange, scroll, origin) {
var a1 = asAbsolute(coord1, scroll, origin);
var a2 = asAbsolute(coord2, scroll, origin);
return Math.abs(a1.left - a2.left) <= xRange && Math.abs(a1.top - a2.top) <= yRange;
};
var getDeltas = function (coord1, coord2, xRange, yRange, scroll, origin) {
var a1 = asAbsolute(coord1, scroll, origin);
var a2 = asAbsolute(coord2, scroll, origin);
var left = Math.abs(a1.left - a2.left);
var top = Math.abs(a1.top - a2.top);
return SugarPosition(left, top);
};
var toStyles = function (coord, scroll, origin) {
var stylesOpt = coord.fold(function (x, y) {
return {
position: Optional.some('absolute'),
left: Optional.some(x + 'px'),
top: Optional.some(y + 'px')
};
}, function (x, y) {
return {
position: Optional.some('absolute'),
left: Optional.some(x - origin.left + 'px'),
top: Optional.some(y - origin.top + 'px')
};
}, function (x, y) {
return {
position: Optional.some('fixed'),
left: Optional.some(x + 'px'),
top: Optional.some(y + 'px')
};
});
return __assign({
right: Optional.none(),
bottom: Optional.none()
}, stylesOpt);
};
var translate$2 = function (coord, deltaX, deltaY) {
return coord.fold(function (x, y) {
return offset(x + deltaX, y + deltaY);
}, function (x, y) {
return absolute$3(x + deltaX, y + deltaY);
}, function (x, y) {
return fixed$1(x + deltaX, y + deltaY);
});
};
var absorb = function (partialCoord, originalCoord, scroll, origin) {
var absorbOne = function (stencil, nu) {
return function (optX, optY) {
var original = stencil(originalCoord, scroll, origin);
return nu(optX.getOr(original.left), optY.getOr(original.top));
};
};
return partialCoord.fold(absorbOne(asOffset, offset), absorbOne(asAbsolute, absolute$3), absorbOne(asFixed, fixed$1));
};
var offset = adt$c.offset;
var absolute$3 = adt$c.absolute;
var fixed$1 = adt$c.fixed;
var parseAttrToInt = function (element, name) {
var value = get$3(element, name);
return isUndefined(value) ? NaN : parseInt(value, 10);
};
var get$f = function (component, snapsInfo) {
var element = component.element;
var x = parseAttrToInt(element, snapsInfo.leftAttr);
var y = parseAttrToInt(element, snapsInfo.topAttr);
return isNaN(x) || isNaN(y) ? Optional.none() : Optional.some(SugarPosition(x, y));
};
var set$8 = function (component, snapsInfo, pt) {
var element = component.element;
set$1(element, snapsInfo.leftAttr, pt.left + 'px');
set$1(element, snapsInfo.topAttr, pt.top + 'px');
};
var clear = function (component, snapsInfo) {
var element = component.element;
remove$1(element, snapsInfo.leftAttr);
remove$1(element, snapsInfo.topAttr);
};
var getCoords = function (component, snapInfo, coord, delta) {
return get$f(component, snapInfo).fold(function () {
return coord;
}, function (fixed) {
return fixed$1(fixed.left + delta.left, fixed.top + delta.top);
});
};
var moveOrSnap = function (component, snapInfo, coord, delta, scroll, origin) {
var newCoord = getCoords(component, snapInfo, coord, delta);
var snap = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
var fixedCoord = asFixed(newCoord, scroll, origin);
set$8(component, snapInfo, fixedCoord);
return snap.fold(function () {
return {
coord: fixed$1(fixedCoord.left, fixedCoord.top),
extra: Optional.none()
};
}, function (spanned) {
return {
coord: spanned.output,
extra: spanned.extra
};
});
};
var stopDrag = function (component, snapInfo) {
clear(component, snapInfo);
};
var findMatchingSnap = function (snaps, newCoord, scroll, origin) {
return findMap(snaps, function (snap) {
var sensor = snap.sensor;
var inRange = withinRange(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
return inRange ? Optional.some({
output: absorb(snap.output, newCoord, scroll, origin),
extra: snap.extra
}) : Optional.none();
});
};
var findClosestSnap = function (component, snapInfo, newCoord, scroll, origin) {
var snaps = snapInfo.getSnapPoints(component);
var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
return matchSnap.orThunk(function () {
var bestSnap = foldl(snaps, function (acc, snap) {
var sensor = snap.sensor;
var deltas = getDeltas(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
return acc.deltas.fold(function () {
return {
deltas: Optional.some(deltas),
snap: Optional.some(snap)
};
}, function (bestDeltas) {
var currAvg = (deltas.left + deltas.top) / 2;
var bestAvg = (bestDeltas.left + bestDeltas.top) / 2;
if (currAvg <= bestAvg) {
return {
deltas: Optional.some(deltas),
snap: Optional.some(snap)
};
} else {
return acc;
}
});
}, {
deltas: Optional.none(),
snap: Optional.none()
});
return bestSnap.snap.map(function (snap) {
return {
output: absorb(snap.output, newCoord, scroll, origin),
extra: snap.extra
};
});
});
};
var findSnap = function (component, snapInfo, newCoord, scroll, origin) {
var snaps = snapInfo.getSnapPoints(component);
return findMatchingSnap(snaps, newCoord, scroll, origin);
};
var snapTo = function (snap, scroll, origin) {
return {
coord: absorb(snap.output, snap.output, scroll, origin),
extra: snap.extra
};
};
var snapTo$1 = function (component, dragConfig, _state, snap) {
var target = dragConfig.getTarget(component.element);
if (dragConfig.repositionTarget) {
var doc = owner(component.element);
var scroll_1 = get$9(doc);
var origin_1 = getOrigin(target);
var snapPin = snapTo(snap, scroll_1, origin_1);
var styles = toStyles(snapPin.coord, scroll_1, origin_1);
setOptions(target, styles);
}
};
var DraggingApis = /*#__PURE__*/Object.freeze({
__proto__: null,
snapTo: snapTo$1
});
var initialAttribute = 'data-initial-z-index';
var resetZIndex = function (blocker) {
parent(blocker.element).filter(isElement).each(function (root) {
getOpt(root, initialAttribute).fold(function () {
return remove$6(root, 'z-index');
}, function (zIndex) {
return set$2(root, 'z-index', zIndex);
});
remove$1(root, initialAttribute);
});
};
var changeZIndex = function (blocker) {
parent(blocker.element).filter(isElement).each(function (root) {
getRaw(root, 'z-index').each(function (zindex) {
set$1(root, initialAttribute, zindex);
});
set$2(root, 'z-index', get$5(blocker.element, 'z-index'));
});
};
var instigate = function (anyComponent, blocker) {
anyComponent.getSystem().addToGui(blocker);
changeZIndex(blocker);
};
var discard = function (blocker) {
resetZIndex(blocker);
blocker.getSystem().removeFromGui(blocker);
};
var createComponent = function (component, blockerClass, blockerEvents) {
return component.getSystem().build(Container.sketch({
dom: {
styles: {
'left': '0px',
'top': '0px',
'width': '100%',
'height': '100%',
'position': 'fixed',
'z-index': '1000000000000000'
},
classes: [blockerClass]
},
events: blockerEvents
}));
};
var SnapSchema = optionObjOf('snaps', [
strict$1('getSnapPoints'),
onHandler('onSensor'),
strict$1('leftAttr'),
strict$1('topAttr'),
defaulted$1('lazyViewport', win),
defaulted$1('mustSnap', false)
]);
var schema$t = [
defaulted$1('useFixed', never),
strict$1('blockerClass'),
defaulted$1('getTarget', identity),
defaulted$1('onDrag', noop),
defaulted$1('repositionTarget', true),
defaulted$1('onDrop', noop),
defaultedFunction('getBounds', win),
SnapSchema
];
var getCurrentCoord = function (target) {
return lift3(getRaw(target, 'left'), getRaw(target, 'top'), getRaw(target, 'position'), function (left, top, position) {
var nu = position === 'fixed' ? fixed$1 : offset;
return nu(parseInt(left, 10), parseInt(top, 10));
}).getOrThunk(function () {
var location = absolute(target);
return absolute$3(location.left, location.top);
});
};
var clampCoords = function (component, coords, scroll, origin, startData) {
var bounds = startData.bounds;
var absoluteCoord = asAbsolute(coords, scroll, origin);
var newX = clamp(absoluteCoord.left, bounds.x, bounds.x + bounds.width - startData.width);
var newY = clamp(absoluteCoord.top, bounds.y, bounds.y + bounds.height - startData.height);
var newCoords = absolute$3(newX, newY);
return coords.fold(function () {
var offset$1 = asOffset(newCoords, scroll, origin);
return offset(offset$1.left, offset$1.top);
}, function () {
return newCoords;
}, function () {
var fixed = asFixed(newCoords, scroll, origin);
return fixed$1(fixed.left, fixed.top);
});
};
var calcNewCoord = function (component, optSnaps, currentCoord, scroll, origin, delta, startData) {
var newCoord = optSnaps.fold(function () {
var translated = translate$2(currentCoord, delta.left, delta.top);
var fixedCoord = asFixed(translated, scroll, origin);
return fixed$1(fixedCoord.left, fixedCoord.top);
}, function (snapInfo) {
var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
snapping.extra.each(function (extra) {
snapInfo.onSensor(component, extra);
});
return snapping.coord;
});
return clampCoords(component, newCoord, scroll, origin, startData);
};
var dragBy = function (component, dragConfig, startData, delta) {
var target = dragConfig.getTarget(component.element);
if (dragConfig.repositionTarget) {
var doc = owner(component.element);
var scroll_1 = get$9(doc);
var origin_1 = getOrigin(target);
var currentCoord = getCurrentCoord(target);
var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll_1, origin_1, delta, startData);
var styles = toStyles(newCoord, scroll_1, origin_1);
setOptions(target, styles);
}
dragConfig.onDrag(component, target, delta);
};
var calcStartData = function (dragConfig, comp) {
return {
bounds: dragConfig.getBounds(),
height: getOuter$1(comp.element),
width: getOuter$2(comp.element)
};
};
var move$1 = function (component, dragConfig, dragState, dragMode, event) {
var delta = dragState.update(dragMode, event);
var dragStartData = dragState.getStartData().getOrThunk(function () {
return calcStartData(dragConfig, component);
});
delta.each(function (dlt) {
dragBy(component, dragConfig, dragStartData, dlt);
});
};
var stop = function (component, blocker, dragConfig, dragState) {
blocker.each(discard);
dragConfig.snaps.each(function (snapInfo) {
stopDrag(component, snapInfo);
});
var target = dragConfig.getTarget(component.element);
dragState.reset();
dragConfig.onDrop(component, target);
};
var handlers = function (events) {
return function (dragConfig, dragState) {
var updateStartState = function (comp) {
dragState.setStartData(calcStartData(dragConfig, comp));
};
return derive(__spreadArrays([run(windowScroll(), function (comp) {
dragState.getStartData().each(function () {
return updateStartState(comp);
});
})], events(dragConfig, dragState, updateStartState)));
};
};
var init$c = function (dragApi) {
return derive([
run(mousedown(), dragApi.forceDrop),
run(mouseup(), dragApi.drop),
run(mousemove(), function (comp, simulatedEvent) {
dragApi.move(simulatedEvent.event);
}),
run(mouseout(), dragApi.delayDrop)
]);
};
var getData$1 = function (event) {
return Optional.from(SugarPosition(event.x, event.y));
};
var getDelta$1 = function (old, nu) {
return SugarPosition(nu.left - old.left, nu.top - old.top);
};
var MouseData = /*#__PURE__*/Object.freeze({
__proto__: null,
getData: getData$1,
getDelta: getDelta$1
});
var events$g = function (dragConfig, dragState, updateStartState) {
return [run(mousedown(), function (component, simulatedEvent) {
var raw = simulatedEvent.event.raw;
if (raw.button !== 0) {
return;
}
simulatedEvent.stop();
var stop$1 = function () {
return stop(component, Optional.some(blocker), dragConfig, dragState);
};
var delayDrop = DelayedFunction(stop$1, 200);
var dragApi = {
drop: stop$1,
delayDrop: delayDrop.schedule,
forceDrop: stop$1,
move: function (event) {
delayDrop.cancel();
move$1(component, dragConfig, dragState, MouseData, event);
}
};
var blocker = createComponent(component, dragConfig.blockerClass, init$c(dragApi));
var start = function () {
updateStartState(component);
instigate(component, blocker);
};
start();
})];
};
var schema$u = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$g) })]);
var init$d = function (dragApi) {
return derive([
run(touchstart(), dragApi.forceDrop),
run(touchend(), dragApi.drop),
run(touchcancel(), dragApi.drop),
run(touchmove(), function (comp, simulatedEvent) {
dragApi.move(simulatedEvent.event);
})
]);
};
var getDataFrom = function (touches) {
var touch = touches[0];
return Optional.some(SugarPosition(touch.clientX, touch.clientY));
};
var getData$2 = function (event) {
var raw = event.raw;
var touches = raw.touches;
return touches.length === 1 ? getDataFrom(touches) : Optional.none();
};
var getDelta$2 = function (old, nu) {
return SugarPosition(nu.left - old.left, nu.top - old.top);
};
var TouchData = /*#__PURE__*/Object.freeze({
__proto__: null,
getData: getData$2,
getDelta: getDelta$2
});
var events$h = function (dragConfig, dragState, updateStartState) {
var blockerCell = Cell(Optional.none());
return [
run(touchstart(), function (component, simulatedEvent) {
simulatedEvent.stop();
var stop$1 = function () {
stop(component, blockerCell.get(), dragConfig, dragState);
blockerCell.set(Optional.none());
};
var dragApi = {
drop: stop$1,
delayDrop: noop,
forceDrop: stop$1,
move: function (event) {
move$1(component, dragConfig, dragState, TouchData, event);
}
};
var blocker = createComponent(component, dragConfig.blockerClass, init$d(dragApi));
blockerCell.set(Optional.some(blocker));
var start = function () {
updateStartState(component);
instigate(component, blocker);
};
start();
}),
run(touchmove(), function (component, simulatedEvent) {
simulatedEvent.stop();
move$1(component, dragConfig, dragState, TouchData, simulatedEvent.event);
}),
run(touchend(), function (component, simulatedEvent) {
simulatedEvent.stop();
stop(component, blockerCell.get(), dragConfig, dragState);
blockerCell.set(Optional.none());
}),
run(touchcancel(), function (component) {
stop(component, blockerCell.get(), dragConfig, dragState);
blockerCell.set(Optional.none());
})
];
};
var schema$v = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$h) })]);
var events$i = function (dragConfig, dragState, updateStartState) {
return __spreadArrays(events$g(dragConfig, dragState, updateStartState), events$h(dragConfig, dragState, updateStartState));
};
var schema$w = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$i) })]);
var mouse = schema$u;
var touch = schema$v;
var mouseOrTouch = schema$w;
var DraggingBranches = /*#__PURE__*/Object.freeze({
__proto__: null,
mouse: mouse,
touch: touch,
mouseOrTouch: mouseOrTouch
});
var init$e = function () {
var previous = Optional.none();
var startData = Optional.none();
var reset = function () {
previous = Optional.none();
startData = Optional.none();
};
var calculateDelta = function (mode, nu) {
var result = previous.map(function (old) {
return mode.getDelta(old, nu);
});
previous = Optional.some(nu);
return result;
};
var update = function (mode, dragEvent) {
return mode.getData(dragEvent).bind(function (nuData) {
return calculateDelta(mode, nuData);
});
};
var setStartData = function (data) {
startData = Optional.some(data);
};
var getStartData = function () {
return startData;
};
var readState = constant({});
return nu$5({
readState: readState,
reset: reset,
update: update,
getStartData: getStartData,
setStartData: setStartData
});
};
var DragState = /*#__PURE__*/Object.freeze({
__proto__: null,
init: init$e
});
var Dragging = createModes$1({
branchKey: 'mode',
branches: DraggingBranches,
name: 'dragging',
active: {
events: function (dragConfig, dragState) {
var dragger = dragConfig.dragger;
return dragger.handlers(dragConfig, dragState);
}
},
extra: {
snap: function (sConfig) {
return {
sensor: sConfig.sensor,
range: sConfig.range,
output: sConfig.output,
extra: Optional.from(sConfig.extra)
};
}
},
state: DragState,
apis: DraggingApis
});
var snapWidth = 40;
var snapOffset = snapWidth / 2;
var calcSnap = function (selectorOpt, td, x, y, width, height) {
return selectorOpt.fold(function () {
return Dragging.snap({
sensor: absolute$3(x - snapOffset, y - snapOffset),
range: SugarPosition(width, height),
output: absolute$3(Optional.some(x), Optional.some(y)),
extra: { td: td }
});
}, function (selectorHandle) {
var sensorLeft = x - snapOffset;
var sensorTop = y - snapOffset;
var sensorWidth = snapWidth;
var sensorHeight = snapWidth;
var rect = selectorHandle.element.dom.getBoundingClientRect();
return Dragging.snap({
sensor: absolute$3(sensorLeft, sensorTop),
range: SugarPosition(sensorWidth, sensorHeight),
output: absolute$3(Optional.some(x - rect.width / 2), Optional.some(y - rect.height / 2)),
extra: { td: td }
});
});
};
var getSnapsConfig = function (getSnapPoints, cell, onChange) {
var isSameCell = function (cellOpt, td) {
return cellOpt.exists(function (currentTd) {
return eq$1(currentTd, td);
});
};
return {
getSnapPoints: getSnapPoints,
leftAttr: 'data-drag-left',
topAttr: 'data-drag-top',
onSensor: function (component, extra) {
var td = extra.td;
if (!isSameCell(cell.get(), td)) {
cell.set(Optional.some(td));
onChange(td);
}
},
mustSnap: true
};
};
var createSelector = function (snaps) {
return record(Button.sketch({
dom: {
tag: 'div',
classes: ['tox-selector']
},
buttonBehaviours: derive$1([
Dragging.config({
mode: 'mouseOrTouch',
blockerClass: 'blocker',
snaps: snaps
}),
Unselecting.config({})
]),
eventOrder: {
mousedown: [
'dragging',
'alloy.base.behaviour'
],
touchstart: [
'dragging',
'alloy.base.behaviour'
]
}
}));
};
var setup$a = function (editor, sink) {
var tlTds = Cell([]);
var brTds = Cell([]);
var isVisible = Cell(false);
var startCell = Cell(Optional.none());
var finishCell = Cell(Optional.none());
var getTopLeftSnap = function (td) {
var box = absolute$1(td);
return calcSnap(memTopLeft.getOpt(sink), td, box.x, box.y, box.width, box.height);
};
var getTopLeftSnaps = function () {
return map(tlTds.get(), function (td) {
return getTopLeftSnap(td);
});
};
var getBottomRightSnap = function (td) {
var box = absolute$1(td);
return calcSnap(memBottomRight.getOpt(sink), td, box.right, box.bottom, box.width, box.height);
};
var getBottomRightSnaps = function () {
return map(brTds.get(), function (td) {
return getBottomRightSnap(td);
});
};
var topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, function (start) {
finishCell.get().each(function (finish) {
editor.fire('TableSelectorChange', {
start: start,
finish: finish
});
});
});
var bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, function (finish) {
startCell.get().each(function (start) {
editor.fire('TableSelectorChange', {
start: start,
finish: finish
});
});
});
var memTopLeft = createSelector(topLeftSnaps);
var memBottomRight = createSelector(bottomRightSnaps);
var topLeft = build$1(memTopLeft.asSpec());
var bottomRight = build$1(memBottomRight.asSpec());
var showOrHideHandle = function (selector, cell, isAbove, isBelow) {
var cellRect = cell.dom.getBoundingClientRect();
remove$6(selector.element, 'display');
var viewportHeight = defaultView(SugarElement.fromDom(editor.getBody())).dom.innerHeight;
var aboveViewport = isAbove(cellRect);
var belowViewport = isBelow(cellRect, viewportHeight);
if (aboveViewport || belowViewport) {
set$2(selector.element, 'display', 'none');
}
};
var snapTo = function (selector, cell, getSnapConfig, pos) {
var snap = getSnapConfig(cell);
Dragging.snapTo(selector, snap);
var isAbove = function (rect) {
return rect[pos] < 0;
};
var isBelow = function (rect, viewportHeight) {
return rect[pos] > viewportHeight;
};
showOrHideHandle(selector, cell, isAbove, isBelow);
};
var snapTopLeft = function (cell) {
return snapTo(topLeft, cell, getTopLeftSnap, 'top');
};
var snapLastTopLeft = function () {
return startCell.get().each(snapTopLeft);
};
var snapBottomRight = function (cell) {
return snapTo(bottomRight, cell, getBottomRightSnap, 'bottom');
};
var snapLastBottomRight = function () {
return finishCell.get().each(snapBottomRight);
};
if (detect$3().deviceType.isTouch()) {
editor.on('TableSelectionChange', function (e) {
if (!isVisible.get()) {
attach$1(sink, topLeft);
attach$1(sink, bottomRight);
isVisible.set(true);
}
startCell.set(Optional.some(e.start));
finishCell.set(Optional.some(e.finish));
e.otherCells.each(function (otherCells) {
tlTds.set(otherCells.upOrLeftCells);
brTds.set(otherCells.downOrRightCells);
snapTopLeft(e.start);
snapBottomRight(e.finish);
});
});
editor.on('ResizeEditor ResizeWindow ScrollContent', function () {
snapLastTopLeft();
snapLastBottomRight();
});
editor.on('TableSelectionClear', function () {
if (isVisible.get()) {
detach(topLeft);
detach(bottomRight);
isVisible.set(false);
}
startCell.set(Optional.none());
finishCell.set(Optional.none());
});
}
};
var isHidden$1 = function (elm) {
if (elm.nodeType === 1) {
if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) {
return true;
}
if (elm.getAttribute('data-mce-type') === 'bookmark') {
return true;
}
}
return false;
};
var renderElementPath = function (editor, settings, providersBackstage) {
if (!settings.delimiter) {
settings.delimiter = '\xBB';
}
var getDataPath = function (data) {
var parts = data || [];
var newPathElements = map(parts, function (part, index) {
return Button.sketch({
dom: {
tag: 'div',
classes: ['tox-statusbar__path-item'],
attributes: {
'role': 'button',
'data-index': index,
'tab-index': -1,
'aria-level': index + 1
},
innerHtml: part.name
},
action: function (_btn) {
editor.focus();
editor.selection.select(part.element);
editor.nodeChanged();
},
buttonBehaviours: derive$1([
DisablingConfigs.button(providersBackstage.isDisabled),
receivingConfig()
])
});
});
var divider = {
dom: {
tag: 'div',
classes: ['tox-statusbar__path-divider'],
attributes: { 'aria-hidden': true },
innerHtml: ' ' + settings.delimiter + ' '
}
};
return foldl(newPathElements.slice(1), function (acc, element) {
var newAcc = acc;
newAcc.push(divider);
newAcc.push(element);
return newAcc;
}, [newPathElements[0]]);
};
var updatePath = function (parents) {
var newPath = [];
var i = parents.length;
while (i-- > 0) {
var parent_1 = parents[i];
if (parent_1.nodeType === 1 && !isHidden$1(parent_1)) {
var args = editor.fire('ResolveName', {
name: parent_1.nodeName.toLowerCase(),
target: parent_1
});
if (!args.isDefaultPrevented()) {
newPath.push({
name: args.name,
element: parent_1
});
}
if (args.isPropagationStopped()) {
break;
}
}
}
return newPath;
};
return {
dom: {
tag: 'div',
classes: ['tox-statusbar__path'],
attributes: { role: 'navigation' }
},
behaviours: derive$1([
Keying.config({
mode: 'flow',
selector: 'div[role=button]'
}),
Disabling.config({ disabled: providersBackstage.isDisabled }),
receivingConfig(),
Tabstopping.config({}),
Replacing.config({}),
config('elementPathEvents', [runOnAttached(function (comp, _e) {
editor.shortcuts.add('alt+F11', 'focus statusbar elementpath', function () {
return Keying.focusIn(comp);
});
editor.on('NodeChange', function (e) {
var newPath = updatePath(e.parents);
if (newPath.length > 0) {
Replacing.set(comp, getDataPath(newPath));
} else {
Replacing.set(comp, []);
}
});
})])
]),
components: []
};
};
var ResizeTypes;
(function (ResizeTypes) {
ResizeTypes[ResizeTypes['None'] = 0] = 'None';
ResizeTypes[ResizeTypes['Both'] = 1] = 'Both';
ResizeTypes[ResizeTypes['Vertical'] = 2] = 'Vertical';
}(ResizeTypes || (ResizeTypes = {})));
var getDimensions = function (editor, deltas, resizeType, originalHeight, originalWidth) {
var dimensions = {};
dimensions.height = calcCappedSize(originalHeight + deltas.top, getMinHeightSetting(editor), getMaxHeightSetting(editor));
if (resizeType === ResizeTypes.Both) {
dimensions.width = calcCappedSize(originalWidth + deltas.left, getMinWidthSetting(editor), getMaxWidthSetting(editor));
}
return dimensions;
};
var resize$3 = function (editor, deltas, resizeType) {
var container = SugarElement.fromDom(editor.getContainer());
var dimensions = getDimensions(editor, deltas, resizeType, get$7(container), get$8(container));
each$1(dimensions, function (val, dim) {
return set$2(container, dim, numToPx(val));
});
fireResizeEditor(editor);
};
var getResizeType = function (editor) {
var fallback = !editor.hasPlugin('autoresize');
var resize = editor.getParam('resize', fallback);
if (resize === false) {
return ResizeTypes.None;
} else if (resize === 'both') {
return ResizeTypes.Both;
} else {
return ResizeTypes.Vertical;
}
};
var keyboardHandler = function (editor, resizeType, x, y) {
var scale = 20;
var delta = SugarPosition(x * scale, y * scale);
resize$3(editor, delta, resizeType);
return Optional.some(true);
};
var renderResizeHandler = function (editor, providersBackstage) {
var resizeType = getResizeType(editor);
if (resizeType === ResizeTypes.None) {
return Optional.none();
}
return Optional.some({
dom: {
tag: 'div',
classes: ['tox-statusbar__resize-handle'],
attributes: { title: providersBackstage.translate('Resize') },
innerHtml: get$e('resize-handle', providersBackstage.icons)
},
behaviours: derive$1([
Dragging.config({
mode: 'mouse',
repositionTarget: false,
onDrag: function (_comp, _target, delta) {
return resize$3(editor, delta, resizeType);
},
blockerClass: 'tox-blocker'
}),
Keying.config({
mode: 'special',
onLeft: function () {
return keyboardHandler(editor, resizeType, -1, 0);
},
onRight: function () {
return keyboardHandler(editor, resizeType, 1, 0);
},
onUp: function () {
return keyboardHandler(editor, resizeType, 0, -1);
},
onDown: function () {
return keyboardHandler(editor, resizeType, 0, 1);
}
}),
Tabstopping.config({}),
Focusing.config({})
])
});
};
var renderWordCount = function (editor, providersBackstage) {
var _a;
var replaceCountText = function (comp, count, mode) {
return Replacing.set(comp, [text(providersBackstage.translate([
'{0} ' + mode,
count[mode]
]))]);
};
return Button.sketch({
dom: {
tag: 'button',
classes: ['tox-statusbar__wordcount']
},
components: [],
buttonBehaviours: derive$1([
DisablingConfigs.button(providersBackstage.isDisabled),
receivingConfig(),
Tabstopping.config({}),
Replacing.config({}),
Representing.config({
store: {
mode: 'memory',
initialValue: {
mode: 'words',
count: {
words: 0,
characters: 0
}
}
}
}),
config('wordcount-events', [
runOnExecute(function (comp) {
var currentVal = Representing.getValue(comp);
var newMode = currentVal.mode === 'words' ? 'characters' : 'words';
Representing.setValue(comp, {
mode: newMode,
count: currentVal.count
});
replaceCountText(comp, currentVal.count, newMode);
}),
runOnAttached(function (comp) {
editor.on('wordCountUpdate', function (e) {
var mode = Representing.getValue(comp).mode;
Representing.setValue(comp, {
mode: mode,
count: e.wordCount
});
replaceCountText(comp, e.wordCount, mode);
});
})
])
]),
eventOrder: (_a = {}, _a[execute()] = [
'disabling',
'alloy.base.behaviour',
'wordcount-events'
], _a)
});
};
var renderStatusbar = function (editor, providersBackstage) {
var renderBranding = function () {
var label = global$6.translate([
'Powered by {0}',
'Tiny'
]);
var linkHtml = '' + label + '';
return {
dom: {
tag: 'span',
classes: ['tox-statusbar__branding'],
innerHtml: linkHtml
}
};
};
var getTextComponents = function () {
var components = [];
if (editor.getParam('elementpath', true, 'boolean')) {
components.push(renderElementPath(editor, {}, providersBackstage));
}
if (editor.hasPlugin('wordcount')) {
components.push(renderWordCount(editor, providersBackstage));
}
if (editor.getParam('branding', true, 'boolean')) {
components.push(renderBranding());
}
if (components.length > 0) {
return [{
dom: {
tag: 'div',
classes: ['tox-statusbar__text-container']
},
components: components
}];
}
return [];
};
var getComponents = function () {
var components = getTextComponents();
var resizeHandler = renderResizeHandler(editor, providersBackstage);
return components.concat(resizeHandler.toArray());
};
return {
dom: {
tag: 'div',
classes: ['tox-statusbar']
},
components: getComponents()
};
};
var setup$b = function (editor) {
var _a;
var isInline = editor.inline;
var mode = isInline ? Inline : Iframe;
var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
var lazyOuterContainer = Optional.none();
var platform = detect$3();
var isIE = platform.browser.isIE();
var platformClasses = isIE ? ['tox-platform-ie'] : [];
var isTouch = platform.deviceType.isTouch();
var touchPlatformClass = 'tox-platform-touch';
var deviceClasses = isTouch ? [touchPlatformClass] : [];
var isToolbarBottom = isToolbarLocationBottom(editor);
var uiContainer = getUiContainer(editor);
var dirAttributes = global$6.isRtl() ? { attributes: { dir: 'rtl' } } : {};
var verticalDirAttributes = { attributes: (_a = {}, _a[Attribute] = isToolbarBottom ? AttributeValue.BottomToTop : AttributeValue.TopToBottom, _a) };
var lazyHeader = function () {
return lazyOuterContainer.bind(OuterContainer.getHeader);
};
var isHeaderDocked = function () {
return header.isDocked(lazyHeader);
};
var resizeUiMothership = function () {
set$2(uiMothership.element, 'width', document.body.clientWidth + 'px');
};
var makeSinkDefinition = function () {
var isGridUiContainer = eq$1(body(), uiContainer) && get$5(uiContainer, 'display') === 'grid';
var sinkSpec = {
dom: __assign({
tag: 'div',
classes: [
'tox',
'tox-silver-sink',
'tox-tinymce-aux'
].concat(platformClasses).concat(deviceClasses)
}, dirAttributes),
behaviours: derive$1([Positioning.config({
useFixed: function () {
return isHeaderDocked();
}
})])
};
var reactiveWidthSpec = {
dom: { styles: { width: document.body.clientWidth + 'px' } },
events: derive([run(windowResize(), resizeUiMothership)])
};
return deepMerge(sinkSpec, isGridUiContainer ? reactiveWidthSpec : {});
};
var sink = build$1(makeSinkDefinition());
var lazySink = function () {
return Result.value(sink);
};
var memAnchorBar = record({
dom: {
tag: 'div',
classes: ['tox-anchorbar']
}
});
var lazyAnchorBar = function () {
return lazyOuterContainer.bind(function (container) {
return memAnchorBar.getOpt(container);
}).getOrDie('Could not find a anchor bar element');
};
var lazyToolbar = function () {
return lazyOuterContainer.bind(function (container) {
return OuterContainer.getToolbar(container);
}).getOrDie('Could not find more toolbar element');
};
var lazyThrobber = function () {
return lazyOuterContainer.bind(function (container) {
return OuterContainer.getThrobber(container);
}).getOrDie('Could not find throbber element');
};
var backstage = init$8(sink, editor, lazyAnchorBar);
var partMenubar = OuterContainer.parts.menubar({
dom: {
tag: 'div',
classes: ['tox-menubar']
},
backstage: backstage,
onEscape: function () {
editor.focus();
}
});
var toolbarMode = getToolbarMode(editor);
var partToolbar = OuterContainer.parts.toolbar(__assign({
dom: {
tag: 'div',
classes: ['tox-toolbar']
},
getSink: lazySink,
providers: backstage.shared.providers,
onEscape: function () {
editor.focus();
},
type: toolbarMode,
lazyToolbar: lazyToolbar,
lazyHeader: function () {
return lazyHeader().getOrDie('Could not find header element');
}
}, verticalDirAttributes));
var partMultipleToolbar = OuterContainer.parts['multiple-toolbar']({
dom: {
tag: 'div',
classes: ['tox-toolbar-overlord']
},
providers: backstage.shared.providers,
onEscape: function () {
editor.focus();
},
type: toolbarMode
});
var partSocket = OuterContainer.parts.socket({
dom: {
tag: 'div',
classes: ['tox-edit-area']
}
});
var partSidebar = OuterContainer.parts.sidebar({
dom: {
tag: 'div',
classes: ['tox-sidebar']
}
});
var partThrobber = OuterContainer.parts.throbber({
dom: {
tag: 'div',
classes: ['tox-throbber']
},
backstage: backstage
});
var sb = editor.getParam('statusbar', true, 'boolean');
var statusbar = sb && !isInline ? Optional.some(renderStatusbar(editor, backstage.shared.providers)) : Optional.none();
var socketSidebarContainer = {
dom: {
tag: 'div',
classes: ['tox-sidebar-wrap']
},
components: [
partSocket,
partSidebar
]
};
var hasMultipleToolbar = isMultipleToolbars(editor);
var hasToolbar = isToolbarEnabled(editor);
var hasMenubar = isMenubarEnabled(editor);
var getPartToolbar = function () {
if (hasMultipleToolbar) {
return [partMultipleToolbar];
} else if (hasToolbar) {
return [partToolbar];
} else {
return [];
}
};
var partHeader = OuterContainer.parts.header({
dom: __assign({
tag: 'div',
classes: ['tox-editor-header']
}, verticalDirAttributes),
components: flatten([
hasMenubar ? [partMenubar] : [],
getPartToolbar(),
useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
]),
sticky: isStickyToolbar(editor),
editor: editor,
sharedBackstage: backstage.shared
});
var editorComponents = flatten([
isToolbarBottom ? [] : [partHeader],
isInline ? [] : [socketSidebarContainer],
isToolbarBottom ? [partHeader] : []
]);
var editorContainer = {
dom: {
tag: 'div',
classes: ['tox-editor-container']
},
components: editorComponents
};
var containerComponents = flatten([
[editorContainer],
isInline ? [] : statusbar.toArray(),
[partThrobber]
]);
var isHidden = isDistractionFree(editor);
var attributes = __assign(__assign({ role: 'application' }, global$6.isRtl() ? { dir: 'rtl' } : {}), isHidden ? { 'aria-hidden': 'true' } : {});
var outerContainer = build$1(OuterContainer.sketch({
dom: {
tag: 'div',
classes: [
'tox',
'tox-tinymce'
].concat(isInline ? ['tox-tinymce-inline'] : []).concat(isToolbarBottom ? ['tox-tinymce--toolbar-bottom'] : []).concat(deviceClasses).concat(platformClasses),
styles: __assign({ visibility: 'hidden' }, isHidden ? {
opacity: '0',
border: '0'
} : {}),
attributes: attributes
},
components: containerComponents,
behaviours: derive$1([
receivingConfig(),
Disabling.config({ disableClass: 'tox-tinymce--disabled' }),
Keying.config({
mode: 'cyclic',
selector: '.tox-menubar, .tox-toolbar, .tox-toolbar__primary, .tox-toolbar__overflow--open, .tox-sidebar__overflow--open, .tox-statusbar__path, .tox-statusbar__wordcount, .tox-statusbar__branding a, .tox-statusbar__resize-handle'
})
])
}));
lazyOuterContainer = Optional.some(outerContainer);
editor.shortcuts.add('alt+F9', 'focus menubar', function () {
OuterContainer.focusMenubar(outerContainer);
});
editor.shortcuts.add('alt+F10', 'focus toolbar', function () {
OuterContainer.focusToolbar(outerContainer);
});
editor.addCommand('ToggleToolbarDrawer', function () {
OuterContainer.toggleToolbarDrawer(outerContainer);
});
editor.addQueryStateHandler('ToggleToolbarDrawer', function () {
return OuterContainer.isToolbarDrawerToggled(outerContainer);
});
var mothership = takeover(outerContainer);
var uiMothership = takeover(sink);
setup$3(editor, mothership, uiMothership);
var getUi = function () {
var channels = {
broadcastAll: uiMothership.broadcast,
broadcastOn: uiMothership.broadcastOn,
register: noop
};
return { channels: channels };
};
var setEditorSize = function () {
var parsedHeight = numToPx(getHeightWithFallback(editor));
var parsedWidth = numToPx(getWidthWithFallback(editor));
if (!editor.inline) {
if (isValidValue('div', 'width', parsedWidth)) {
set$2(outerContainer.element, 'width', parsedWidth);
}
if (isValidValue('div', 'height', parsedHeight)) {
set$2(outerContainer.element, 'height', parsedHeight);
} else {
set$2(outerContainer.element, 'height', '200px');
}
}
return parsedHeight;
};
var renderUI = function () {
header.setup(editor, backstage.shared, lazyHeader);
setup$8(editor, backstage);
setup$9(editor, lazySink, backstage);
setup$6(editor);
setup$7(editor, lazyThrobber, backstage.shared);
map$2(getToolbarGroups(editor), function (toolbarGroupButtonConfig, name) {
editor.ui.registry.addGroupToolbarButton(name, toolbarGroupButtonConfig);
});
var _a = editor.ui.registry.getAll(), buttons = _a.buttons, menuItems = _a.menuItems, contextToolbars = _a.contextToolbars, sidebars = _a.sidebars;
var toolbarOpt = getMultipleToolbarsSetting(editor);
var rawUiConfig = {
menuItems: menuItems,
menus: getMenus(editor),
menubar: getMenubar(editor),
toolbar: toolbarOpt.getOrThunk(function () {
return getToolbar(editor);
}),
allowToolbarGroups: toolbarMode === ToolbarMode.floating,
buttons: buttons,
sidebar: sidebars
};
register$4(editor, contextToolbars, sink, { backstage: backstage });
setup$a(editor, sink);
var elm = editor.getElement();
var height = setEditorSize();
var uiComponents = {
mothership: mothership,
uiMothership: uiMothership,
outerContainer: outerContainer
};
var args = {
targetNode: elm,
height: height
};
return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
};
return {
mothership: mothership,
uiMothership: uiMothership,
backstage: backstage,
renderUI: renderUI,
getUi: getUi
};
};
var describedBy = function (describedElement, describeElement) {
var describeId = Optional.from(get$3(describedElement, 'id')).fold(function () {
var id = generate$1('dialog-describe');
set$1(describeElement, 'id', id);
return id;
}, identity);
set$1(describedElement, 'aria-describedby', describeId);
};
var labelledBy = function (labelledElement, labelElement) {
var labelId = getOpt(labelledElement, 'id').fold(function () {
var id = generate$1('dialog-label');
set$1(labelElement, 'id', id);
return id;
}, identity);
set$1(labelledElement, 'aria-labelledby', labelId);
};
var schema$x = constant([
strict$1('lazySink'),
option('dragBlockClass'),
defaultedFunction('getBounds', win),
defaulted$1('useTabstopAt', always),
defaulted$1('eventOrder', {}),
field$1('modalBehaviours', [Keying]),
onKeyboardHandler('onExecute'),
onStrictKeyboardHandler('onEscape')
]);
var basic = { sketch: identity };
var parts$f = constant([
optional({
name: 'draghandle',
overrides: function (detail, spec) {
return {
behaviours: derive$1([Dragging.config({
mode: 'mouse',
getTarget: function (handle) {
return ancestor$2(handle, '[role="dialog"]').getOr(handle);
},
blockerClass: detail.dragBlockClass.getOrDie(new Error('The drag blocker class was not specified for a dialog with a drag handle: \n' + JSON.stringify(spec, null, 2)).message),
getBounds: detail.getDragBounds
})])
};
}
}),
required({
schema: [strict$1('dom')],
name: 'title'
}),
required({
factory: basic,
schema: [strict$1('dom')],
name: 'close'
}),
required({
factory: basic,
schema: [strict$1('dom')],
name: 'body'
}),
optional({
factory: basic,
schema: [strict$1('dom')],
name: 'footer'
}),
external$1({
factory: {
sketch: function (spec, detail) {
return __assign(__assign({}, spec), {
dom: detail.dom,
components: detail.components
});
}
},
schema: [
defaulted$1('dom', {
tag: 'div',
styles: {
position: 'fixed',
left: '0px',
top: '0px',
right: '0px',
bottom: '0px'
}
}),
defaulted$1('components', [])
],
name: 'blocker'
})
]);
var block = function (component, config, state, getBusySpec) {
set$1(component.element, 'aria-busy', true);
var root = config.getRoot(component).getOr(component);
var blockerBehaviours = derive$1([
Keying.config({
mode: 'special',
onTab: function () {
return Optional.some(true);
},
onShiftTab: function () {
return Optional.some(true);
}
}),
Focusing.config({})
]);
var blockSpec = getBusySpec(root, blockerBehaviours);
var blocker = root.getSystem().build(blockSpec);
Replacing.append(root, premade$1(blocker));
if (blocker.hasConfigured(Keying)) {
Keying.focusIn(blocker);
}
if (!state.isBlocked()) {
config.onBlock(component);
}
state.blockWith(function () {
return Replacing.remove(root, blocker);
});
};
var unblock = function (component, config, state) {
remove$1(component.element, 'aria-busy');
if (state.isBlocked()) {
config.onUnblock(component);
}
state.clear();
};
var BlockingApis = /*#__PURE__*/Object.freeze({
__proto__: null,
block: block,
unblock: unblock
});
var BlockingSchema = [
defaultedFunction('getRoot', Optional.none),
onHandler('onBlock'),
onHandler('onUnblock')
];
var init$f = function () {
var blocker = destroyable();
var blockWith = function (destroy) {
blocker.set({ destroy: destroy });
};
return nu$5({
readState: blocker.isSet,
blockWith: blockWith,
clear: blocker.clear,
isBlocked: blocker.isSet
});
};
var BlockingState = /*#__PURE__*/Object.freeze({
__proto__: null,
init: init$f
});
var Blocking = create$1({
fields: BlockingSchema,
name: 'blocking',
apis: BlockingApis,
state: BlockingState
});
var factory$i = function (detail, components, spec, externals) {
var _a;
var dialogComp = Cell(Optional.none());
var showDialog = function (dialog) {
dialogComp.set(Optional.some(dialog));
var sink = detail.lazySink(dialog).getOrDie();
var externalBlocker = externals.blocker();
var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), {
components: externalBlocker.components.concat([premade$1(dialog)]),
behaviours: derive$1([
Focusing.config({}),
config('dialog-blocker-events', [runOnSource(focusin(), function () {
Keying.focusIn(dialog);
})])
])
}));
attach$1(sink, blocker);
Keying.focusIn(dialog);
};
var hideDialog = function (dialog) {
dialogComp.set(Optional.none());
parent(dialog.element).each(function (blockerDom) {
dialog.getSystem().getByDom(blockerDom).each(function (blocker) {
detach(blocker);
});
});
};
var getDialogBody = function (dialog) {
return getPartOrDie(dialog, detail, 'body');
};
var getDialogFooter = function (dialog) {
return getPartOrDie(dialog, detail, 'footer');
};
var setBusy = function (dialog, getBusySpec) {
Blocking.block(dialog, getBusySpec);
};
var setIdle = function (dialog) {
Blocking.unblock(dialog);
};
var modalEventsId = generate$1('modal-events');
var eventOrder = __assign(__assign({}, detail.eventOrder), (_a = {}, _a[attachedToDom()] = [modalEventsId].concat(detail.eventOrder['alloy.system.attached'] || []), _a));
return {
uid: detail.uid,
dom: detail.dom,
components: components,
apis: {
show: showDialog,
hide: hideDialog,
getBody: getDialogBody,
getFooter: getDialogFooter,
setIdle: setIdle,
setBusy: setBusy
},
eventOrder: eventOrder,
domModification: {
attributes: {
'role': 'dialog',
'aria-modal': 'true'
}
},
behaviours: augment(detail.modalBehaviours, [
Replacing.config({}),
Keying.config({
mode: 'cyclic',
onEnter: detail.onExecute,
onEscape: detail.onEscape,
useTabstopAt: detail.useTabstopAt
}),
Blocking.config({ getRoot: dialogComp.get }),
config(modalEventsId, [runOnAttached(function (c) {
labelledBy(c.element, getPartOrDie(c, detail, 'title').element);
describedBy(c.element, getPartOrDie(c, detail, 'body').element);
})])
])
};
};
var ModalDialog = composite$1({
name: 'ModalDialog',
configFields: schema$x(),
partFields: parts$f(),
factory: factory$i,
apis: {
show: function (apis, dialog) {
apis.show(dialog);
},
hide: function (apis, dialog) {
apis.hide(dialog);
},
getBody: function (apis, dialog) {
return apis.getBody(dialog);
},
getFooter: function (apis, dialog) {
return apis.getFooter(dialog);
},
setBusy: function (apis, dialog, getBusySpec) {
apis.setBusy(dialog, getBusySpec);
},
setIdle: function (apis, dialog) {
apis.setIdle(dialog);
}
}
});
var dialogToggleMenuItemSchema = objOf([
strictString('type'),
strictString('name')
].concat(commonMenuItemFields));
var dialogToggleMenuItemDataProcessor = boolean;
var baseFooterButtonFields = [
field('name', 'name', defaultedThunk(function () {
return generate$1('button-name');
}), string),
optionString('icon'),
defaultedStringEnum('align', 'end', [
'start',
'end'
]),
defaultedBoolean('primary', false),
defaultedBoolean('disabled', false)
];
var dialogFooterButtonFields = __spreadArrays(baseFooterButtonFields, [strictString('text')]);
var normalFooterButtonFields = __spreadArrays([strictStringEnum('type', [
'submit',
'cancel',
'custom'
])], dialogFooterButtonFields);
var menuFooterButtonFields = __spreadArrays([
strictStringEnum('type', ['menu']),
optionString('text'),
optionString('tooltip'),
optionString('icon'),
strictArrayOf('items', dialogToggleMenuItemSchema)
], baseFooterButtonFields);
var dialogFooterButtonSchema = choose$1('type', {
submit: normalFooterButtonFields,
cancel: normalFooterButtonFields,
custom: normalFooterButtonFields,
menu: menuFooterButtonFields
});
var alertBannerFields = [
strictString('type'),
strictString('text'),
strictStringEnum('level', [
'info',
'warn',
'error',
'success'
]),
strictString('icon'),
defaulted$1('url', '')
];
var alertBannerSchema = objOf(alertBannerFields);
var createBarFields = function (itemsField) {
return [
strictString('type'),
itemsField
];
};
var buttonFields = [
strictString('type'),
strictString('text'),
defaultedBoolean('disabled', false),
defaultedBoolean('primary', false),
field('name', 'name', defaultedThunk(function () {
return generate$1('button-name');
}), string),
optionString('icon'),
defaultedBoolean('borderless', false)
];
var buttonSchema = objOf(buttonFields);
var checkboxFields = [
strictString('type'),
strictString('name'),
strictString('label'),
defaultedBoolean('disabled', false)
];
var checkboxSchema = objOf(checkboxFields);
var checkboxDataProcessor = boolean;
var formComponentFields = [
strictString('type'),
strictString('name')
];
var formComponentWithLabelFields = formComponentFields.concat([optionString('label')]);
var collectionFields = formComponentWithLabelFields.concat([defaulted$1('columns', 'auto')]);
var collectionSchema = objOf(collectionFields);
var collectionDataProcessor = arrOfObj$1([
strictString('value'),
strictString('text'),
strictString('icon')
]);
var colorInputFields = formComponentWithLabelFields;
var colorInputSchema = objOf(colorInputFields);
var colorInputDataProcessor = string;
var colorPickerFields = formComponentWithLabelFields;
var colorPickerSchema = objOf(colorPickerFields);
var colorPickerDataProcessor = string;
var customEditorFields = formComponentFields.concat([
defaultedString('tag', 'textarea'),
strictString('scriptId'),
strictString('scriptUrl'),
defaultedPostMsg('settings', undefined)
]);
var customEditorFieldsOld = formComponentFields.concat([
defaultedString('tag', 'textarea'),
strictFunction('init')
]);
var customEditorSchema = valueOf(function (v) {
return asRaw('customeditor.old', objOfOnly(customEditorFieldsOld), v).orThunk(function () {
return asRaw('customeditor.new', objOfOnly(customEditorFields), v);
});
});
var customEditorDataProcessor = string;
var dropZoneFields = formComponentWithLabelFields;
var dropZoneSchema = objOf(dropZoneFields);
var dropZoneDataProcessor = arrOfVal();
var createGridFields = function (itemsField) {
return [
strictString('type'),
strictNumber('columns'),
itemsField
];
};
var htmlPanelFields = [
strictString('type'),
strictString('html'),
defaultedStringEnum('presets', 'presentation', [
'presentation',
'document'
])
];
var htmlPanelSchema = objOf(htmlPanelFields);
var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean('sandboxed', true)]);
var iframeSchema = objOf(iframeFields);
var iframeDataProcessor = string;
var imageToolsFields = formComponentWithLabelFields.concat([strictOf('currentState', objOf([
strict$1('blob'),
strictString('url')
]))]);
var imageToolsSchema = objOf(imageToolsFields);
var inputFields = formComponentWithLabelFields.concat([
optionString('inputMode'),
optionString('placeholder'),
defaultedBoolean('maximized', false),
defaultedBoolean('disabled', false)
]);
var inputSchema = objOf(inputFields);
var inputDataProcessor = string;
var createLabelFields = function (itemsField) {
return [
strictString('type'),
strictString('label'),
itemsField
];
};
var listBoxSingleItemFields = [
strictString('text'),
strictString('value')
];
var listBoxNestedItemFields = [
strictString('text'),
strictArrayOf('items', thunkOf('items', function () {
return listBoxItemSchema;
}))
];
var listBoxItemSchema = oneOf([
objOf(listBoxSingleItemFields),
objOf(listBoxNestedItemFields)
]);
var listBoxFields = formComponentWithLabelFields.concat([
strictArrayOf('items', listBoxItemSchema),
defaultedBoolean('disabled', false)
]);
var listBoxSchema = objOf(listBoxFields);
var listBoxDataProcessor = string;
var selectBoxFields = formComponentWithLabelFields.concat([
strictArrayOfObj('items', [
strictString('text'),
strictString('value')
]),
defaultedNumber('size', 1),
defaultedBoolean('disabled', false)
]);
var selectBoxSchema = objOf(selectBoxFields);
var selectBoxDataProcessor = string;
var sizeInputFields = formComponentWithLabelFields.concat([
defaultedBoolean('constrain', true),
defaultedBoolean('disabled', false)
]);
var sizeInputSchema = objOf(sizeInputFields);
var sizeInputDataProcessor = objOf([
strictString('width'),
strictString('height')
]);
var tableFields = [
strictString('type'),
strictArrayOf('header', string),
strictArrayOf('cells', arrOf(string))
];
var tableSchema = objOf(tableFields);
var textAreaFields = formComponentWithLabelFields.concat([
optionString('placeholder'),
defaultedBoolean('maximized', false),
defaultedBoolean('disabled', false)
]);
var textAreaSchema = objOf(textAreaFields);
var textAreaDataProcessor = string;
var urlInputFields = formComponentWithLabelFields.concat([
defaultedStringEnum('filetype', 'file', [
'image',
'media',
'file'
]),
defaulted$1('disabled', false)
]);
var urlInputSchema = objOf(urlInputFields);
var urlInputDataProcessor = objOf([
strictString('value'),
defaulted$1('meta', {})
]);
var createItemsField = function (name) {
return field('items', 'items', strict(), arrOf(valueOf(function (v) {
return asRaw('Checking item of ' + name, itemSchema$3, v).fold(function (sErr) {
return Result.error(formatError(sErr));
}, function (passValue) {
return Result.value(passValue);
});
})));
};
var itemSchema$3 = valueThunkOf(function () {
return chooseProcessor('type', {
alertbanner: alertBannerSchema,
bar: objOf(createBarFields(createItemsField('bar'))),
button: buttonSchema,
checkbox: checkboxSchema,
colorinput: colorInputSchema,
colorpicker: colorPickerSchema,
dropzone: dropZoneSchema,
grid: objOf(createGridFields(createItemsField('grid'))),
iframe: iframeSchema,
input: inputSchema,
listbox: listBoxSchema,
selectbox: selectBoxSchema,
sizeinput: sizeInputSchema,
textarea: textAreaSchema,
urlinput: urlInputSchema,
customeditor: customEditorSchema,
htmlpanel: htmlPanelSchema,
imagetools: imageToolsSchema,
collection: collectionSchema,
label: objOf(createLabelFields(createItemsField('label'))),
table: tableSchema,
panel: panelSchema
});
});
var panelFields = [
strictString('type'),
defaulted$1('classes', []),
strictArrayOf('items', itemSchema$3)
];
var panelSchema = objOf(panelFields);
var tabFields = [
field('name', 'name', defaultedThunk(function () {
return generate$1('tab-name');
}), string),
strictString('title'),
strictArrayOf('items', itemSchema$3)
];
var tabPanelFields = [
strictString('type'),
strictArrayOfObj('tabs', tabFields)
];
var tabPanelSchema = objOf(tabPanelFields);
var dialogButtonFields = dialogFooterButtonFields;
var dialogButtonSchema = dialogFooterButtonSchema;
var dialogSchema = objOf([
strictString('title'),
strictOf('body', chooseProcessor('type', {
panel: panelSchema,
tabpanel: tabPanelSchema
})),
defaultedString('size', 'normal'),
strictArrayOf('buttons', dialogButtonSchema),
defaulted$1('initialData', {}),
defaultedFunction('onAction', noop),
defaultedFunction('onChange', noop),
defaultedFunction('onSubmit', noop),
defaultedFunction('onClose', noop),
defaultedFunction('onCancel', noop),
defaulted$1('onTabChange', noop)
]);
var createDialog = function (spec) {
return asRaw('dialog', dialogSchema, spec);
};
var urlDialogButtonSchema = objOf(__spreadArrays([strictStringEnum('type', [
'cancel',
'custom'
])], dialogButtonFields));
var urlDialogSchema = objOf([
strictString('title'),
strictString('url'),
optionNumber('height'),
optionNumber('width'),
optionArrayOf('buttons', urlDialogButtonSchema),
defaultedFunction('onAction', noop),
defaultedFunction('onCancel', noop),
defaultedFunction('onClose', noop),
defaultedFunction('onMessage', noop)
]);
var createUrlDialog = function (spec) {
return asRaw('dialog', urlDialogSchema, spec);
};
var getAllObjects = function (obj) {
if (isObject(obj)) {
return [obj].concat(bind(values(obj), getAllObjects));
} else if (isArray(obj)) {
return bind(obj, getAllObjects);
} else {
return [];
}
};
var isNamedItem = function (obj) {
return isString(obj.type) && isString(obj.name);
};
var dataProcessors = {
checkbox: checkboxDataProcessor,
colorinput: colorInputDataProcessor,
colorpicker: colorPickerDataProcessor,
dropzone: dropZoneDataProcessor,
input: inputDataProcessor,
iframe: iframeDataProcessor,
sizeinput: sizeInputDataProcessor,
selectbox: selectBoxDataProcessor,
listbox: listBoxDataProcessor,
size: sizeInputDataProcessor,
textarea: textAreaDataProcessor,
urlinput: urlInputDataProcessor,
customeditor: customEditorDataProcessor,
collection: collectionDataProcessor,
togglemenuitem: dialogToggleMenuItemDataProcessor
};
var getDataProcessor = function (item) {
return Optional.from(dataProcessors[item.type]);
};
var getNamedItems = function (structure) {
return filter(getAllObjects(structure), isNamedItem);
};
var createDataValidator = function (structure) {
var namedItems = getNamedItems(structure);
var fields = bind(namedItems, function (item) {
return getDataProcessor(item).fold(function () {
return [];
}, function (schema) {
return [strictOf(item.name, schema)];
});
});
return objOf(fields);
};
var extract$1 = function (structure) {
var internalDialog = getOrDie(createDialog(structure));
var dataValidator = createDataValidator(structure);
var initialData = structure.initialData;
return {
internalDialog: internalDialog,
dataValidator: dataValidator,
initialData: initialData
};
};
var DialogManager = {
open: function (factory, structure) {
var extraction = extract$1(structure);
return factory(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
},
openUrl: function (factory, structure) {
var internalDialog = getOrDie(createUrlDialog(structure));
return factory(internalDialog);
},
redial: function (structure) {
return extract$1(structure);
}
};
var toValidValues = function (values) {
var errors = [];
var result = {};
each$1(values, function (value, name) {
value.fold(function () {
errors.push(name);
}, function (v) {
result[name] = v;
});
});
return errors.length > 0 ? Result.error(errors) : Result.value(result);
};
var renderBodyPanel = function (spec, backstage) {
var memForm = record(Form.sketch(function (parts) {
return {
dom: {
tag: 'div',
classes: ['tox-form'].concat(spec.classes)
},
components: map(spec.items, function (item) {
return interpretInForm(parts, item, backstage);
})
};
}));
return {
dom: {
tag: 'div',
classes: ['tox-dialog__body']
},
components: [{
dom: {
tag: 'div',
classes: ['tox-dialog__body-content']
},
components: [memForm.asSpec()]
}],
behaviours: derive$1([
Keying.config({
mode: 'acyclic',
useTabstopAt: not(isPseudoStop)
}),
ComposingConfigs.memento(memForm),
RepresentingConfigs.memento(memForm, {
postprocess: function (formValue) {
return toValidValues(formValue).fold(function (err) {
console.error(err);
return {};
}, function (vals) {
return vals;
});
}
})
])
};
};
var factory$j = function (detail, _spec) {
return {
uid: detail.uid,
dom: detail.dom,
components: detail.components,
events: events$7(detail.action),
behaviours: augment(detail.tabButtonBehaviours, [
Focusing.config({}),
Keying.config({
mode: 'execution',
useSpace: true,
useEnter: true
}),
Representing.config({
store: {
mode: 'memory',
initialValue: detail.value
}
})
]),
domModification: detail.domModification
};
};
var TabButton = single$2({
name: 'TabButton',
configFields: [
defaulted$1('uid', undefined),
strict$1('value'),
field('dom', 'dom', mergeWithThunk(function () {
return {
attributes: {
'role': 'tab',
'id': generate$1('aria'),
'aria-selected': 'false'
}
};
}), anyValue$1()),
option('action'),
defaulted$1('domModification', {}),
field$1('tabButtonBehaviours', [
Focusing,
Keying,
Representing
]),
strict$1('view')
],
factory: factory$j
});
var schema$y = constant([
strict$1('tabs'),
strict$1('dom'),
defaulted$1('clickToDismiss', false),
field$1('tabbarBehaviours', [
Highlighting,
Keying
]),
markers([
'tabClass',
'selectedClass'
])
]);
var tabsPart = group({
factory: TabButton,
name: 'tabs',
unit: 'tab',
overrides: function (barDetail) {
var dismissTab$1 = function (tabbar, button) {
Highlighting.dehighlight(tabbar, button);
emitWith(tabbar, dismissTab(), {
tabbar: tabbar,
button: button
});
};
var changeTab$1 = function (tabbar, button) {
Highlighting.highlight(tabbar, button);
emitWith(tabbar, changeTab(), {
tabbar: tabbar,
button: button
});
};
return {
action: function (button) {
var tabbar = button.getSystem().getByUid(barDetail.uid).getOrDie();
var activeButton = Highlighting.isHighlighted(tabbar, button);
var response = function () {
if (activeButton && barDetail.clickToDismiss) {
return dismissTab$1;
} else if (!activeButton) {
return changeTab$1;
} else {
return noop;
}
}();
response(tabbar, button);
},
domModification: { classes: [barDetail.markers.tabClass] }
};
}
});
var parts$g = constant([tabsPart]);
var factory$k = function (detail, components, _spec, _externals) {
return {
'uid': detail.uid,
'dom': detail.dom,
components: components,
'debug.sketcher': 'Tabbar',
'domModification': { attributes: { role: 'tablist' } },
'behaviours': augment(detail.tabbarBehaviours, [
Highlighting.config({
highlightClass: detail.markers.selectedClass,
itemClass: detail.markers.tabClass,
onHighlight: function (tabbar, tab) {
set$1(tab.element, 'aria-selected', 'true');
},
onDehighlight: function (tabbar, tab) {
set$1(tab.element, 'aria-selected', 'false');
}
}),
Keying.config({
mode: 'flow',
getInitial: function (tabbar) {
return Highlighting.getHighlighted(tabbar).map(function (tab) {
return tab.element;
});
},
selector: '.' + detail.markers.tabClass,
executeOnMove: true
})
])
};
};
var Tabbar = composite$1({
name: 'Tabbar',
configFields: schema$y(),
partFields: parts$g(),
factory: factory$k
});
var factory$l = function (detail, _spec) {
return {
uid: detail.uid,
dom: detail.dom,
behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
domModification: { attributes: { role: 'tabpanel' } }
};
};
var Tabview = single$2({
name: 'Tabview',
configFields: [field$1('tabviewBehaviours', [Replacing])],
factory: factory$l
});
var schema$z = constant([
defaulted$1('selectFirst', true),
onHandler('onChangeTab'),
onHandler('onDismissTab'),
defaulted$1('tabs', []),
field$1('tabSectionBehaviours', [])
]);
var barPart = required({
factory: Tabbar,
schema: [
strict$1('dom'),
strictObjOf('markers', [
strict$1('tabClass'),
strict$1('selectedClass')
])
],
name: 'tabbar',
defaults: function (detail) {
return { tabs: detail.tabs };
}
});
var viewPart = required({
factory: Tabview,
name: 'tabview'
});
var parts$h = constant([
barPart,
viewPart
]);
var factory$m = function (detail, components, _spec, _externals) {
var changeTab$1 = function (button) {
var tabValue = Representing.getValue(button);
getPart(button, detail, 'tabview').each(function (tabview) {
var tabWithValue = find(detail.tabs, function (t) {
return t.value === tabValue;
});
tabWithValue.each(function (tabData) {
var panel = tabData.view();
getOpt(button.element, 'id').each(function (id) {
set$1(tabview.element, 'aria-labelledby', id);
});
Replacing.set(tabview, panel);
detail.onChangeTab(tabview, button, panel);
});
});
};
var changeTabBy = function (section, byPred) {
getPart(section, detail, 'tabbar').each(function (tabbar) {
byPred(tabbar).each(emitExecute);
});
};
return {
uid: detail.uid,
dom: detail.dom,
components: components,
behaviours: get$d(detail.tabSectionBehaviours),
events: derive(flatten([
detail.selectFirst ? [runOnAttached(function (section, _simulatedEvent) {
changeTabBy(section, Highlighting.getFirst);
})] : [],
[
run(changeTab(), function (section, simulatedEvent) {
var button = simulatedEvent.event.button;
changeTab$1(button);
}),
run(dismissTab(), function (section, simulatedEvent) {
var button = simulatedEvent.event.button;
detail.onDismissTab(section, button);
})
]
])),
apis: {
getViewItems: function (section) {
return getPart(section, detail, 'tabview').map(function (tabview) {
return Replacing.contents(tabview);
}).getOr([]);
},
showTab: function (section, tabKey) {
var getTabIfNotActive = function (tabbar) {
var candidates = Highlighting.getCandidates(tabbar);
var optTab = find(candidates, function (c) {
return Representing.getValue(c) === tabKey;
});
return optTab.filter(function (tab) {
return !Highlighting.isHighlighted(tabbar, tab);
});
};
changeTabBy(section, getTabIfNotActive);
}
}
};
};
var TabSection = composite$1({
name: 'TabSection',
configFields: schema$z(),
partFields: parts$h(),
factory: factory$m,
apis: {
getViewItems: function (apis, component) {
return apis.getViewItems(component);
},
showTab: function (apis, component, tabKey) {
apis.showTab(component, tabKey);
}
}
});
var measureHeights = function (allTabs, tabview, tabviewComp) {
return map(allTabs, function (_tab, i) {
Replacing.set(tabviewComp, allTabs[i].view());
var rect = tabview.dom.getBoundingClientRect();
Replacing.set(tabviewComp, []);
return rect.height;
});
};
var getMaxHeight = function (heights) {
return head(sort(heights, function (a, b) {
if (a > b) {
return -1;
} else if (a < b) {
return +1;
} else {
return 0;
}
}));
};
var getMaxTabviewHeight = function (dialog, tabview, tablist) {
var documentElement$1 = documentElement(dialog).dom;
var rootElm = ancestor$2(dialog, '.tox-dialog-wrap').getOr(dialog);
var isFixed = get$5(rootElm, 'position') === 'fixed';
var maxHeight;
if (isFixed) {
maxHeight = Math.max(documentElement$1.clientHeight, window.innerHeight);
} else {
maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight);
}
var tabviewHeight = get$7(tabview);
var isTabListBeside = tabview.dom.offsetLeft >= tablist.dom.offsetLeft + get$8(tablist);
var currentTabHeight = isTabListBeside ? Math.max(get$7(tablist), tabviewHeight) : tabviewHeight;
var dialogTopMargin = parseInt(get$5(dialog, 'margin-top'), 10) || 0;
var dialogBottomMargin = parseInt(get$5(dialog, 'margin-bottom'), 10) || 0;
var dialogHeight = get$7(dialog) + dialogTopMargin + dialogBottomMargin;
var chromeHeight = dialogHeight - currentTabHeight;
return maxHeight - chromeHeight;
};
var showTab = function (allTabs, comp) {
head(allTabs).each(function (tab) {
return TabSection.showTab(comp, tab.value);
});
};
var setTabviewHeight = function (tabview, height) {
set$2(tabview, 'height', height + 'px');
if (!detect$3().browser.isIE()) {
set$2(tabview, 'flex-basis', height + 'px');
} else {
remove$6(tabview, 'flex-basis');
}
};
var updateTabviewHeight = function (dialogBody, tabview, maxTabHeight) {
ancestor$2(dialogBody, '[role="dialog"]').each(function (dialog) {
descendant$1(dialog, '[role="tablist"]').each(function (tablist) {
maxTabHeight.get().map(function (height) {
set$2(tabview, 'height', '0');
set$2(tabview, 'flex-basis', '0');
return Math.min(height, getMaxTabviewHeight(dialog, tabview, tablist));
}).each(function (height) {
setTabviewHeight(tabview, height);
});
});
});
};
var getTabview = function (dialog) {
return descendant$1(dialog, '[role="tabpanel"]');
};
var setMode = function (allTabs) {
var smartTabHeight = function () {
var maxTabHeight = Cell(Optional.none());
var extraEvents = [
runOnAttached(function (comp) {
var dialog = comp.element;
getTabview(dialog).each(function (tabview) {
set$2(tabview, 'visibility', 'hidden');
comp.getSystem().getByDom(tabview).toOptional().each(function (tabviewComp) {
var heights = measureHeights(allTabs, tabview, tabviewComp);
var maxTabHeightOpt = getMaxHeight(heights);
maxTabHeight.set(maxTabHeightOpt);
});
updateTabviewHeight(dialog, tabview, maxTabHeight);
remove$6(tabview, 'visibility');
showTab(allTabs, comp);
global$2.requestAnimationFrame(function () {
updateTabviewHeight(dialog, tabview, maxTabHeight);
});
});
}),
run(windowResize(), function (comp) {
var dialog = comp.element;
getTabview(dialog).each(function (tabview) {
updateTabviewHeight(dialog, tabview, maxTabHeight);
});
}),
run(formResizeEvent, function (comp, _se) {
var dialog = comp.element;
getTabview(dialog).each(function (tabview) {
var oldFocus = active(getRootNode(tabview));
set$2(tabview, 'visibility', 'hidden');
var oldHeight = getRaw(tabview, 'height').map(function (h) {
return parseInt(h, 10);
});
remove$6(tabview, 'height');
remove$6(tabview, 'flex-basis');
var newHeight = tabview.dom.getBoundingClientRect().height;
var hasGrown = oldHeight.forall(function (h) {
return newHeight > h;
});
if (hasGrown) {
maxTabHeight.set(Optional.from(newHeight));
updateTabviewHeight(dialog, tabview, maxTabHeight);
} else {
oldHeight.each(function (h) {
setTabviewHeight(tabview, h);
});
}
remove$6(tabview, 'visibility');
oldFocus.each(focus$1);
});
})
];
var selectFirst = false;
return {
extraEvents: extraEvents,
selectFirst: selectFirst
};
}();
var naiveTabHeight = function () {
var extraEvents = [];
var selectFirst = true;
return {
extraEvents: extraEvents,
selectFirst: selectFirst
};
}();
return {
smartTabHeight: smartTabHeight,
naiveTabHeight: naiveTabHeight
};
};
var SendDataToSectionChannel = 'send-data-to-section';
var SendDataToViewChannel = 'send-data-to-view';
var renderTabPanel = function (spec, backstage) {
var storedValue = Cell({});
var updateDataWithForm = function (form) {
var formData = Representing.getValue(form);
var validData = toValidValues(formData).getOr({});
var currentData = storedValue.get();
var newData = deepMerge(currentData, validData);
storedValue.set(newData);
};
var setDataOnForm = function (form) {
var tabData = storedValue.get();
Representing.setValue(form, tabData);
};
var oldTab = Cell(null);
var allTabs = map(spec.tabs, function (tab) {
return {
value: tab.name,
dom: {
tag: 'div',
classes: ['tox-dialog__body-nav-item'],
innerHtml: backstage.shared.providers.translate(tab.title)
},
view: function () {
return [Form.sketch(function (parts) {
return {
dom: {
tag: 'div',
classes: ['tox-form']
},
components: map(tab.items, function (item) {
return interpretInForm(parts, item, backstage);
}),
formBehaviours: derive$1([
Keying.config({
mode: 'acyclic',
useTabstopAt: not(isPseudoStop)
}),
config('TabView.form.events', [
runOnAttached(setDataOnForm),
runOnDetached(updateDataWithForm)
]),
Receiving.config({
channels: wrapAll$1([
{
key: SendDataToSectionChannel,
value: { onReceive: updateDataWithForm }
},
{
key: SendDataToViewChannel,
value: { onReceive: setDataOnForm }
}
])
})
])
};
})];
}
};
});
var tabMode = setMode(allTabs).smartTabHeight;
return TabSection.sketch({
dom: {
tag: 'div',
classes: ['tox-dialog__body']
},
onChangeTab: function (section, button, _viewItems) {
var name = Representing.getValue(button);
emitWith(section, formTabChangeEvent, {
name: name,
oldName: oldTab.get()
});
oldTab.set(name);
},
tabs: allTabs,
components: [
TabSection.parts.tabbar({
dom: {
tag: 'div',
classes: ['tox-dialog__body-nav']
},
components: [Tabbar.parts.tabs({})],
markers: {
tabClass: 'tox-tab',
selectedClass: 'tox-dialog__body-nav-item--active'
},
tabbarBehaviours: derive$1([Tabstopping.config({})])
}),
TabSection.parts.tabview({
dom: {
tag: 'div',
classes: ['tox-dialog__body-content']
}
})
],
selectFirst: tabMode.selectFirst,
tabSectionBehaviours: derive$1([
config('tabpanel', tabMode.extraEvents),
Keying.config({ mode: 'acyclic' }),
Composing.config({
find: function (comp) {
return head(TabSection.getViewItems(comp));
}
}),
Representing.config({
store: {
mode: 'manual',
getValue: function (tsection) {
tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
return storedValue.get();
},
setValue: function (tsection, value) {
storedValue.set(value);
tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
}
}
})
])
});
};
var dialogChannel = generate$1('update-dialog');
var titleChannel = generate$1('update-title');
var bodyChannel = generate$1('update-body');
var footerChannel = generate$1('update-footer');
var bodySendMessageChannel = generate$1('body-send-message');
var renderBody = function (spec, id, backstage, ariaAttrs) {
var renderComponents = function (incoming) {
switch (incoming.body.type) {
case 'tabpanel': {
return [renderTabPanel(incoming.body, backstage)];
}
default: {
return [renderBodyPanel(incoming.body, backstage)];
}
}
};
var updateState = function (_comp, incoming) {
return Optional.some({
isTabPanel: function () {
return incoming.body.type === 'tabpanel';
}
});
};
var ariaAttributes = { 'aria-live': 'polite' };
return {
dom: {
tag: 'div',
classes: ['tox-dialog__content-js'],
attributes: __assign(__assign({}, id.map(function (x) {
return { id: x };
}).getOr({})), ariaAttrs ? ariaAttributes : {})
},
components: [],
behaviours: derive$1([
ComposingConfigs.childAt(0),
Reflecting.config({
channel: bodyChannel,
updateState: updateState,
renderComponents: renderComponents,
initialData: spec
})
])
};
};
var renderInlineBody = function (spec, contentId, backstage, ariaAttrs) {
return renderBody(spec, Optional.some(contentId), backstage, ariaAttrs);
};
var renderModalBody = function (spec, backstage) {
var bodySpec = renderBody(spec, Optional.none(), backstage, false);
return ModalDialog.parts.body(bodySpec);
};
var renderIframeBody = function (spec) {
var bodySpec = {
dom: {
tag: 'div',
classes: ['tox-dialog__content-js']
},
components: [{
dom: {
tag: 'div',
classes: ['tox-dialog__body-iframe']
},
components: [craft({
dom: {
tag: 'iframe',
attributes: { src: spec.url }
},
behaviours: derive$1([
Tabstopping.config({}),
Focusing.config({})
])
})]
}],
behaviours: derive$1([Keying.config({
mode: 'acyclic',
useTabstopAt: not(isPseudoStop)
})])
};
return ModalDialog.parts.body(bodySpec);
};
var isTouch = global$8.deviceType.isTouch();
var hiddenHeader = function (title, close) {
return {
dom: {
tag: 'div',
styles: { display: 'none' },
classes: ['tox-dialog__header']
},
components: [
title,
close
]
};
};
var pClose = function (onClose, providersBackstage) {
return ModalDialog.parts.close(Button.sketch({
dom: {
tag: 'button',
classes: [
'tox-button',
'tox-button--icon',
'tox-button--naked'
],
attributes: {
'type': 'button',
'aria-label': providersBackstage.translate('Close')
}
},
action: onClose,
buttonBehaviours: derive$1([Tabstopping.config({})])
}));
};
var pUntitled = function () {
return ModalDialog.parts.title({
dom: {
tag: 'div',
classes: ['tox-dialog__title'],
innerHtml: '',
styles: { display: 'none' }
}
});
};
var pBodyMessage = function (message, providersBackstage) {
return ModalDialog.parts.body({
dom: {
tag: 'div',
classes: ['tox-dialog__body']
},
components: [{
dom: {
tag: 'div',
classes: ['tox-dialog__body-content']
},
components: [{ dom: fromHtml$2('' + providersBackstage.translate(message) + '
') }]
}]
});
};
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 = function (spec) {
var _a;
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: __spreadArrays([
spec.header,
spec.body
], spec.footer.toArray()),
parts: {
blocker: {
dom: fromHtml$2(''),
components: [{
dom: {
tag: 'div',
classes: isTouch ? [
blockerBackdropClass,
blockerBackdropClass + '--opaque'
] : [blockerBackdropClass]
}
}]
}
},
dragBlockClass: blockerClass,
modalBehaviours: derive$1(__spreadArrays([
Focusing.config({}),
config('dialog-events', spec.dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
Keying.focusIn(comp);
})])),
config('scroll-lock', [
runOnAttached(function () {
add$2(body(), scrollLockClass);
}),
runOnDetached(function () {
remove$4(body(), scrollLockClass);
})
])
], spec.extraBehaviours)),
eventOrder: __assign((_a = {}, _a[execute()] = ['dialog-events'], _a[attachedToDom()] = [
'scroll-lock',
'dialog-events',
'alloy.base.behaviour'
], _a[detachedFromDom()] = [
'alloy.base.behaviour',
'dialog-events',
'scroll-lock'
], _a), spec.eventOrder)
});
};
var renderClose = function (providersBackstage) {
return Button.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: [{
dom: {
tag: 'div',
classes: ['tox-icon'],
innerHtml: get$e('close', providersBackstage.icons)
}
}],
action: function (comp) {
emit(comp, formCancelEvent);
}
});
};
var renderTitle = function (spec, id, providersBackstage) {
var renderComponents = function (data) {
return [text(providersBackstage.translate(data.title))];
};
return {
dom: {
tag: 'div',
classes: ['tox-dialog__title'],
attributes: __assign({}, id.map(function (x) {
return { id: x };
}).getOr({}))
},
components: renderComponents(spec),
behaviours: derive$1([Reflecting.config({
channel: titleChannel,
renderComponents: renderComponents
})])
};
};
var renderDragHandle = function () {
return { dom: fromHtml$2('') };
};
var renderInlineHeader = function (spec, titleId, providersBackstage) {
return Container.sketch({
dom: fromHtml$2(''),
components: [
renderTitle(spec, Optional.some(titleId), providersBackstage),
renderDragHandle(),
renderClose(providersBackstage)
],
containerBehaviours: derive$1([Dragging.config({
mode: 'mouse',
blockerClass: 'blocker',
getTarget: function (handle) {
return closest$3(handle, '[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(renderTitle(spec, Optional.none(), providersBackstage));
var pHandle = ModalDialog.parts.draghandle(renderDragHandle());
var pClose = ModalDialog.parts.close(renderClose(providersBackstage));
var components = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose]);
return Container.sketch({
dom: fromHtml$2(''),
components: components
});
};
var getHeader = function (title, backstage) {
return renderModalHeader({
title: backstage.shared.providers.translate(title),
draggable: backstage.dialog.isDraggableModal()
}, backstage.shared.providers);
};
var getBusySpec = function (message, bs, providers) {
return {
dom: {
tag: 'div',
classes: ['tox-dialog__busy-spinner'],
attributes: { 'aria-label': providers.translate(message) },
styles: {
left: '0px',
right: '0px',
bottom: '0px',
top: '0px',
position: 'absolute'
}
},
behaviours: bs,
components: [{ dom: fromHtml$2('') }]
};
};
var getEventExtras = function (lazyDialog, providers, extra) {
return {
onClose: function () {
return extra.closeWindow();
},
onBlock: function (blockEvent) {
ModalDialog.setBusy(lazyDialog(), function (_comp, bs) {
return getBusySpec(blockEvent.message, bs, providers);
});
},
onUnblock: function () {
ModalDialog.setIdle(lazyDialog());
}
};
};
var renderModalDialog = function (spec, initialData, dialogEvents, backstage) {
var _a;
var updateState = function (_comp, incoming) {
return Optional.some(incoming);
};
return build$1(renderDialog(__assign(__assign({}, spec), {
lazySink: backstage.shared.getSink,
extraBehaviours: __spreadArrays([
Reflecting.config({
channel: dialogChannel,
updateState: updateState,
initialData: initialData
}),
RepresentingConfigs.memory({})
], spec.extraBehaviours),
onEscape: function (comp) {
emit(comp, formCancelEvent);
},
dialogEvents: dialogEvents,
eventOrder: (_a = {}, _a[receive()] = [
Reflecting.name(),
Receiving.name()
], _a[attachedToDom()] = [
'scroll-lock',
Reflecting.name(),
'messages',
'dialog-events',
'alloy.base.behaviour'
], _a[detachedFromDom()] = [
'alloy.base.behaviour',
'dialog-events',
'messages',
Reflecting.name(),
'scroll-lock'
], _a)
})));
};
var mapMenuButtons = function (buttons) {
var mapItems = function (button) {
var items = map(button.items, function (item) {
var cell = Cell(false);
return __assign(__assign({}, item), { storage: cell });
});
return __assign(__assign({}, button), { items: items });
};
return map(buttons, function (button) {
if (button.type === 'menu') {
return mapItems(button);
}
return button;
});
};
var extractCellsToObject = function (buttons) {
return foldl(buttons, function (acc, button) {
if (button.type === 'menu') {
var menuButton = button;
return foldl(menuButton.items, function (innerAcc, item) {
innerAcc[item.name] = item.storage;
return innerAcc;
}, acc);
}
return acc;
}, {});
};
var initCommonEvents = function (fireApiEvent, extras) {
return [
runWithTarget(focusin(), onFocus$1),
fireApiEvent(formCloseEvent, function (_api, spec) {
extras.onClose();
spec.onClose();
}),
fireApiEvent(formCancelEvent, function (api, spec, _event, self) {
spec.onCancel(api);
emit(self, formCloseEvent);
}),
run(formUnblockEvent, function (_c, _se) {
return extras.onUnblock();
}),
run(formBlockEvent, function (_c, se) {
return extras.onBlock(se.event);
})
];
};
var initUrlDialog = function (getInstanceApi, extras) {
var fireApiEvent = function (eventName, f) {
return run(eventName, function (c, se) {
withSpec(c, function (spec, _c) {
f(getInstanceApi(), spec, se.event, c);
});
});
};
var withSpec = function (c, f) {
Reflecting.getState(c).get().each(function (currentDialog) {
f(currentDialog, c);
});
};
return __spreadArrays(initCommonEvents(fireApiEvent, extras), [fireApiEvent(formActionEvent, function (api, spec, event) {
spec.onAction(api, { name: event.name });
})]);
};
var initDialog = function (getInstanceApi, extras, getSink) {
var fireApiEvent = function (eventName, f) {
return run(eventName, function (c, se) {
withSpec(c, function (spec, _c) {
f(getInstanceApi(), spec, se.event, c);
});
});
};
var withSpec = function (c, f) {
Reflecting.getState(c).get().each(function (currentDialogInit) {
f(currentDialogInit.internalDialog, c);
});
};
return __spreadArrays(initCommonEvents(fireApiEvent, extras), [
fireApiEvent(formSubmitEvent, function (api, spec) {
return spec.onSubmit(api);
}),
fireApiEvent(formChangeEvent, function (api, spec, event) {
spec.onChange(api, { name: event.name });
}),
fireApiEvent(formActionEvent, function (api, spec, event, component) {
var focusIn = function () {
return Keying.focusIn(component);
};
var isDisabled = function (focused) {
return has$1(focused, 'disabled') || getOpt(focused, 'aria-disabled').exists(function (val) {
return val === 'true';
});
};
var rootNode = getRootNode(component.element);
var current = active(rootNode);
spec.onAction(api, {
name: event.name,
value: event.value
});
active(rootNode).fold(focusIn, function (focused) {
if (isDisabled(focused)) {
focusIn();
} else if (current.exists(function (cur) {
return contains$2(focused, cur) && isDisabled(cur);
})) {
focusIn();
} else {
getSink().toOptional().filter(function (sink) {
return !contains$2(sink.element, focused);
}).each(focusIn);
}
});
}),
fireApiEvent(formTabChangeEvent, function (api, spec, event) {
spec.onTabChange(api, {
newTabName: event.name,
oldTabName: event.oldName
});
}),
runOnDetached(function (component) {
var api = getInstanceApi();
Representing.setValue(component, api.getData());
})
]);
};
var SilverDialogEvents = {
initUrlDialog: initUrlDialog,
initDialog: initDialog
};
var makeButton = function (button, backstage) {
return renderFooterButton(button, button.type, backstage);
};
var lookup$2 = function (compInSystem, footerButtons, buttonName) {
return find(footerButtons, function (button) {
return button.name === buttonName;
}).bind(function (memButton) {
return memButton.memento.getOpt(compInSystem);
});
};
var renderComponents = function (_data, state) {
var footerButtons = state.map(function (s) {
return s.footerButtons;
}).getOr([]);
var buttonGroups = partition(footerButtons, function (button) {
return button.align === 'start';
});
var makeGroup = function (edge, buttons) {
return Container.sketch({
dom: {
tag: 'div',
classes: ['tox-dialog__footer-' + edge]
},
components: map(buttons, function (button) {
return button.memento.asSpec();
})
});
};
var startButtons = makeGroup('start', buttonGroups.pass);
var endButtons = makeGroup('end', buttonGroups.fail);
return [
startButtons,
endButtons
];
};
var renderFooter = function (initSpec, backstage) {
var updateState = function (_comp, data) {
var footerButtons = map(data.buttons, function (button) {
var memButton = record(makeButton(button, backstage));
return {
name: button.name,
align: button.align,
memento: memButton
};
});
var lookupByName = function (compInSystem, buttonName) {
return lookup$2(compInSystem, footerButtons, buttonName);
};
return Optional.some({
lookupByName: lookupByName,
footerButtons: footerButtons
});
};
return {
dom: fromHtml$2(''),
components: [],
behaviours: derive$1([Reflecting.config({
channel: footerChannel,
initialData: initSpec,
updateState: updateState,
renderComponents: renderComponents
})])
};
};
var renderInlineFooter = function (initSpec, backstage) {
return renderFooter(initSpec, backstage);
};
var renderModalFooter = function (initSpec, backstage) {
return ModalDialog.parts.footer(renderFooter(initSpec, backstage));
};
var getCompByName = function (access, name) {
var root = access.getRoot();
if (root.getSystem().isConnected()) {
var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
return Form.getField(form_1, name).fold(function () {
var footer = access.getFooter();
var footerState = Reflecting.getState(footer);
return footerState.get().bind(function (f) {
return f.lookupByName(form_1, name);
});
}, function (comp) {
return Optional.some(comp);
});
} else {
return Optional.none();
}
};
var validateData = function (access, data) {
var root = access.getRoot();
return Reflecting.getState(root).get().map(function (dialogState) {
return getOrDie(asRaw('data', dialogState.dataValidator, data));
}).getOr(data);
};
var getDialogApi = function (access, doRedial, menuItemStates) {
var withRoot = function (f) {
var root = access.getRoot();
if (root.getSystem().isConnected()) {
f(root);
}
};
var getData = function () {
var root = access.getRoot();
var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
var representedValues = Representing.getValue(valueComp);
var menuItemCurrentState = map$2(menuItemStates, function (cell) {
return cell.get();
});
return __assign(__assign({}, representedValues), menuItemCurrentState);
};
var setData = function (newData) {
withRoot(function (_) {
var prevData = instanceApi.getData();
var mergedData = __assign(__assign({}, prevData), newData);
var newInternalData = validateData(access, mergedData);
var form = access.getFormWrapper();
Representing.setValue(form, newInternalData);
each$1(menuItemStates, function (v, k) {
if (has(mergedData, k)) {
v.set(mergedData[k]);
}
});
});
};
var disable = function (name) {
getCompByName(access, name).each(Disabling.disable);
};
var enable = function (name) {
getCompByName(access, name).each(Disabling.enable);
};
var focus = function (name) {
getCompByName(access, name).each(Focusing.focus);
};
var block = function (message) {
if (!isString(message)) {
throw new Error('The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
}
withRoot(function (root) {
emitWith(root, formBlockEvent, { message: message });
});
};
var unblock = function () {
withRoot(function (root) {
emit(root, formUnblockEvent);
});
};
var showTab = function (name) {
withRoot(function (_) {
var body = access.getBody();
var bodyState = Reflecting.getState(body);
if (bodyState.get().exists(function (b) {
return b.isTabPanel();
})) {
Composing.getCurrent(body).each(function (tabSection) {
TabSection.showTab(tabSection, name);
});
}
});
};
var redial = function (d) {
withRoot(function (root) {
var dialogInit = doRedial(d);
root.getSystem().broadcastOn([dialogChannel], dialogInit);
root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog);
root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog);
root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog);
instanceApi.setData(dialogInit.initialData);
});
};
var close = function () {
withRoot(function (root) {
emit(root, formCloseEvent);
});
};
var instanceApi = {
getData: getData,
setData: setData,
disable: disable,
enable: enable,
focus: focus,
block: block,
unblock: unblock,
showTab: showTab,
redial: redial,
close: close
};
return instanceApi;
};
var getDialogSizeClasses = function (size) {
switch (size) {
case 'large':
return ['tox-dialog--width-lg'];
case 'medium':
return ['tox-dialog--width-md'];
default:
return [];
}
};
var renderDialog$1 = function (dialogInit, extra, backstage) {
var header = getHeader(dialogInit.internalDialog.title, backstage);
var body = renderModalBody({ body: dialogInit.internalDialog.body }, backstage);
var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
var objOfCells = extractCellsToObject(storagedMenuButtons);
var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage);
var dialogEvents = SilverDialogEvents.initDialog(function () {
return instanceApi;
}, getEventExtras(function () {
return dialog;
}, backstage.shared.providers, extra), backstage.shared.getSink);
var dialogSize = getDialogSizeClasses(dialogInit.internalDialog.size);
var spec = {
header: header,
body: body,
footer: Optional.some(footer),
extraClasses: dialogSize,
extraBehaviours: [],
extraStyles: {}
};
var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
var modalAccess = function () {
var getForm = function () {
var outerForm = ModalDialog.getBody(dialog);
return Composing.getCurrent(outerForm).getOr(outerForm);
};
return {
getRoot: function () {
return dialog;
},
getBody: function () {
return ModalDialog.getBody(dialog);
},
getFooter: function () {
return ModalDialog.getFooter(dialog);
},
getFormWrapper: getForm
};
}();
var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
return {
dialog: dialog,
instanceApi: instanceApi
};
};
var renderInlineDialog = function (dialogInit, extra, backstage, ariaAttrs) {
var _a, _b;
var dialogLabelId = generate$1('dialog-label');
var dialogContentId = generate$1('dialog-content');
var updateState = function (_comp, incoming) {
return Optional.some(incoming);
};
var memHeader = record(renderInlineHeader({
title: dialogInit.internalDialog.title,
draggable: true
}, dialogLabelId, backstage.shared.providers));
var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs));
var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
var objOfCells = extractCellsToObject(storagedMenuButtons);
var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage));
var dialogEvents = SilverDialogEvents.initDialog(function () {
return instanceApi;
}, {
onBlock: function (event) {
Blocking.block(dialog, function (_comp, bs) {
return getBusySpec(event.message, bs, backstage.shared.providers);
});
},
onUnblock: function () {
Blocking.unblock(dialog);
},
onClose: function () {
return extra.closeWindow();
}
}, backstage.shared.getSink);
var dialog = build$1({
dom: {
tag: 'div',
classes: [
'tox-dialog',
'tox-dialog-inline'
],
attributes: (_a = { role: 'dialog' }, _a['aria-labelledby'] = dialogLabelId, _a['aria-describedby'] = '' + dialogContentId, _a)
},
eventOrder: (_b = {}, _b[receive()] = [
Reflecting.name(),
Receiving.name()
], _b[execute()] = ['execute-on-form'], _b[attachedToDom()] = [
'reflecting',
'execute-on-form'
], _b),
behaviours: derive$1([
Keying.config({
mode: 'cyclic',
onEscape: function (c) {
emit(c, formCloseEvent);
return Optional.some(true);
},
useTabstopAt: function (elem) {
return !isPseudoStop(elem) && (name(elem) !== 'button' || get$3(elem, 'disabled') !== 'disabled');
}
}),
Reflecting.config({
channel: dialogChannel,
updateState: updateState,
initialData: dialogInit
}),
Focusing.config({}),
config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
Keying.focusIn(comp);
})])),
Blocking.config({
getRoot: function () {
return Optional.some(dialog);
}
}),
Replacing.config({}),
RepresentingConfigs.memory({})
]),
components: [
memHeader.asSpec(),
memBody.asSpec(),
memFooter.asSpec()
]
});
var instanceApi = getDialogApi({
getRoot: function () {
return dialog;
},
getFooter: function () {
return memFooter.get(dialog);
},
getBody: function () {
return memBody.get(dialog);
},
getFormWrapper: function () {
var body = memBody.get(dialog);
return Composing.getCurrent(body).getOr(body);
}
}, extra.redial, objOfCells);
return {
dialog: dialog,
instanceApi: instanceApi
};
};
var global$h = tinymce.util.Tools.resolve('tinymce.util.URI');
var getUrlDialogApi = function (root) {
var withRoot = function (f) {
if (root.getSystem().isConnected()) {
f(root);
}
};
var block = function (message) {
if (!isString(message)) {
throw new Error('The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
}
withRoot(function (root) {
emitWith(root, formBlockEvent, { message: message });
});
};
var unblock = function () {
withRoot(function (root) {
emit(root, formUnblockEvent);
});
};
var close = function () {
withRoot(function (root) {
emit(root, formCloseEvent);
});
};
var sendMessage = function (data) {
withRoot(function (root) {
root.getSystem().broadcastOn([bodySendMessageChannel], data);
});
};
return {
block: block,
unblock: unblock,
close: close,
sendMessage: sendMessage
};
};
var SUPPORTED_MESSAGE_ACTIONS = [
'insertContent',
'setContent',
'execCommand',
'close',
'block',
'unblock'
];
var isSupportedMessage = function (data) {
return isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
};
var isCustomMessage = function (data) {
return !isSupportedMessage(data) && isObject(data) && has(data, 'mceAction');
};
var handleMessage = function (editor, api, data) {
switch (data.mceAction) {
case 'insertContent':
editor.insertContent(data.content);
break;
case 'setContent':
editor.setContent(data.content);
break;
case 'execCommand':
var ui = isBoolean(data.ui) ? data.ui : false;
editor.execCommand(data.cmd, ui, data.value);
break;
case 'close':
api.close();
break;
case 'block':
api.block(data.message);
break;
case 'unblock':
api.unblock();
break;
}
};
var renderUrlDialog = function (internalDialog, extra, editor, backstage) {
var _a;
var header = getHeader(internalDialog.title, backstage);
var body = renderIframeBody(internalDialog);
var footer = internalDialog.buttons.bind(function (buttons) {
if (buttons.length === 0) {
return Optional.none();
} else {
return Optional.some(renderModalFooter({ buttons: buttons }, backstage));
}
});
var dialogEvents = SilverDialogEvents.initUrlDialog(function () {
return instanceApi;
}, getEventExtras(function () {
return dialog;
}, backstage.shared.providers, extra));
var styles = __assign(__assign({}, internalDialog.height.fold(function () {
return {};
}, function (height) {
return {
'height': height + 'px',
'max-height': height + 'px'
};
})), internalDialog.width.fold(function () {
return {};
}, function (width) {
return {
'width': width + 'px',
'max-width': width + 'px'
};
}));
var classes = internalDialog.width.isNone() && internalDialog.height.isNone() ? ['tox-dialog--width-lg'] : [];
var iframeUri = new global$h(internalDialog.url, { base_uri: new global$h(window.location.href) });
var iframeDomain = iframeUri.protocol + '://' + iframeUri.host + (iframeUri.port ? ':' + iframeUri.port : '');
var messageHandlerUnbinder = Cell(Optional.none());
var extraBehaviours = [
config('messages', [
runOnAttached(function () {
var unbind = bind$3(SugarElement.fromDom(window), 'message', function (e) {
if (iframeUri.isSameOrigin(new global$h(e.raw.origin))) {
var data = e.raw.data;
if (isSupportedMessage(data)) {
handleMessage(editor, instanceApi, data);
} else if (isCustomMessage(data)) {
internalDialog.onMessage(instanceApi, data);
}
}
});
messageHandlerUnbinder.set(Optional.some(unbind));
}),
runOnDetached(function () {
messageHandlerUnbinder.get().each(function (unbinder) {
return unbinder.unbind();
});
})
]),
Receiving.config({
channels: (_a = {}, _a[bodySendMessageChannel] = {
onReceive: function (comp, data) {
descendant$1(comp.element, 'iframe').each(function (iframeEle) {
var iframeWin = iframeEle.dom.contentWindow;
iframeWin.postMessage(data, iframeDomain);
});
}
}, _a)
})
];
var spec = {
header: header,
body: body,
footer: footer,
extraClasses: classes,
extraBehaviours: extraBehaviours,
extraStyles: styles
};
var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
var instanceApi = getUrlDialogApi(dialog);
return {
dialog: dialog,
instanceApi: instanceApi
};
};
var setup$c = function (extras) {
var sharedBackstage = extras.backstage.shared;
var open = function (message, callback) {
var closeDialog = function () {
ModalDialog.hide(alertDialog);
callback();
};
var memFooterClose = record(renderFooterButton({
name: 'close-alert',
text: 'OK',
primary: true,
align: 'end',
disabled: false,
icon: Optional.none()
}, 'cancel', extras.backstage));
var titleSpec = pUntitled();
var closeSpec = pClose(closeDialog, sharedBackstage.providers);
var alertDialog = build$1(renderDialog({
lazySink: function () {
return sharedBackstage.getSink();
},
header: hiddenHeader(titleSpec, closeSpec),
body: pBodyMessage(message, sharedBackstage.providers),
footer: Optional.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))),
onEscape: closeDialog,
extraClasses: ['tox-alert-dialog'],
extraBehaviours: [],
extraStyles: {},
dialogEvents: [run(formCancelEvent, closeDialog)],
eventOrder: {}
}));
ModalDialog.show(alertDialog);
var footerCloseButton = memFooterClose.get(alertDialog);
Focusing.focus(footerCloseButton);
};
return { open: open };
};
var setup$d = function (extras) {
var sharedBackstage = extras.backstage.shared;
var open = function (message, callback) {
var closeDialog = function (state) {
ModalDialog.hide(confirmDialog);
callback(state);
};
var memFooterYes = record(renderFooterButton({
name: 'yes',
text: 'Yes',
primary: true,
align: 'end',
disabled: false,
icon: Optional.none()
}, 'submit', extras.backstage));
var footerNo = renderFooterButton({
name: 'no',
text: 'No',
primary: false,
align: 'end',
disabled: false,
icon: Optional.none()
}, 'cancel', extras.backstage);
var titleSpec = pUntitled();
var closeSpec = pClose(function () {
return closeDialog(false);
}, sharedBackstage.providers);
var confirmDialog = build$1(renderDialog({
lazySink: function () {
return sharedBackstage.getSink();
},
header: hiddenHeader(titleSpec, closeSpec),
body: pBodyMessage(message, sharedBackstage.providers),
footer: Optional.some(pFooter(pFooterGroup([], [
footerNo,
memFooterYes.asSpec()
]))),
onEscape: function () {
return closeDialog(false);
},
extraClasses: ['tox-confirm-dialog'],
extraBehaviours: [],
extraStyles: {},
dialogEvents: [
run(formCancelEvent, function () {
return closeDialog(false);
}),
run(formSubmitEvent, function () {
return closeDialog(true);
})
],
eventOrder: {}
}));
ModalDialog.show(confirmDialog);
var footerYesButton = memFooterYes.get(confirmDialog);
Focusing.focus(footerYesButton);
};
return { open: open };
};
var validateData$1 = function (data, validator) {
return getOrDie(asRaw('data', validator, data));
};
var isAlertOrConfirmDialog = function (target) {
return closest$4(target, '.tox-alert-dialog') || closest$4(target, '.tox-confirm-dialog');
};
var inlineAdditionalBehaviours = function (editor, isStickyToolbar, isToolbarLocationTop) {
if (isStickyToolbar && isToolbarLocationTop) {
return [];
} else {
return [Docking.config({
contextual: {
lazyContext: function () {
return Optional.some(box(SugarElement.fromDom(editor.getContentAreaContainer())));
},
fadeInClass: 'tox-dialog-dock-fadein',
fadeOutClass: 'tox-dialog-dock-fadeout',
transitionClass: 'tox-dialog-dock-transition'
},
modes: ['top']
})];
}
};
var setup$e = function (extras) {
var backstage = extras.backstage;
var editor = extras.editor;
var isStickyToolbar$1 = isStickyToolbar(editor);
var alertDialog = setup$c(extras);
var confirmDialog = setup$d(extras);
var open = function (config, params, closeWindow) {
if (params !== undefined && params.inline === 'toolbar') {
return openInlineDialog(config, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs);
} else if (params !== undefined && params.inline === 'cursor') {
return openInlineDialog(config, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
} else {
return openModalDialog(config, closeWindow);
}
};
var openUrl = function (config, closeWindow) {
return openModalUrlDialog(config, closeWindow);
};
var openModalUrlDialog = function (config, closeWindow) {
var factory = function (contents) {
var dialog = renderUrlDialog(contents, {
closeWindow: function () {
ModalDialog.hide(dialog.dialog);
closeWindow(dialog.instanceApi);
}
}, editor, backstage);
ModalDialog.show(dialog.dialog);
return dialog.instanceApi;
};
return DialogManager.openUrl(factory, config);
};
var openModalDialog = function (config, closeWindow) {
var factory = function (contents, internalInitialData, dataValidator) {
var initialData = internalInitialData;
var dialogInit = {
dataValidator: dataValidator,
initialData: initialData,
internalDialog: contents
};
var dialog = renderDialog$1(dialogInit, {
redial: DialogManager.redial,
closeWindow: function () {
ModalDialog.hide(dialog.dialog);
closeWindow(dialog.instanceApi);
}
}, backstage);
ModalDialog.show(dialog.dialog);
dialog.instanceApi.setData(initialData);
return dialog.instanceApi;
};
return DialogManager.open(factory, config);
};
var openInlineDialog = function (config$1, anchor, closeWindow, ariaAttrs) {
var factory = function (contents, internalInitialData, dataValidator) {
var initialData = validateData$1(internalInitialData, dataValidator);
var inlineDialog = value$3();
var isToolbarLocationTop = backstage.shared.header.isPositionedAtTop();
var dialogInit = {
dataValidator: dataValidator,
initialData: initialData,
internalDialog: contents
};
var refreshDocking = function () {
return inlineDialog.on(function (dialog) {
InlineView.reposition(dialog);
Docking.refresh(dialog);
});
};
var dialogUi = renderInlineDialog(dialogInit, {
redial: DialogManager.redial,
closeWindow: function () {
inlineDialog.on(InlineView.hide);
editor.off('ResizeEditor', refreshDocking);
inlineDialog.clear();
closeWindow(dialogUi.instanceApi);
}
}, backstage, ariaAttrs);
var inlineDialogComp = build$1(InlineView.sketch(__assign(__assign({
lazySink: backstage.shared.getSink,
dom: {
tag: 'div',
classes: []
},
fireDismissalEventInstead: {}
}, isToolbarLocationTop ? {} : { fireRepositionEventInstead: {} }), {
inlineBehaviours: derive$1(__spreadArrays([config('window-manager-inline-events', [run(dismissRequested(), function (_comp, _se) {
emit(dialogUi.dialog, formCancelEvent);
})])], inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop))),
isExtraPart: function (_comp, target) {
return isAlertOrConfirmDialog(target);
}
})));
inlineDialog.set(inlineDialogComp);
InlineView.showWithin(inlineDialogComp, anchor, premade$1(dialogUi.dialog), Optional.some(body()));
if (!isStickyToolbar$1 || !isToolbarLocationTop) {
Docking.refresh(inlineDialogComp);
editor.on('ResizeEditor', refreshDocking);
}
dialogUi.instanceApi.setData(initialData);
Keying.focusIn(dialogUi.dialog);
return dialogUi.instanceApi;
};
return DialogManager.open(factory, config$1);
};
var confirm = function (message, callback) {
confirmDialog.open(message, function (state) {
callback(state);
});
};
var alert = function (message, callback) {
alertDialog.open(message, function () {
callback();
});
};
var close = function (instanceApi) {
instanceApi.close();
};
return {
open: open,
openUrl: openUrl,
alert: alert,
close: close,
confirm: confirm
};
};
function Theme () {
global$1.add('silver', function (editor) {
var _a = setup$b(editor), uiMothership = _a.uiMothership, backstage = _a.backstage, renderUI = _a.renderUI, getUi = _a.getUi;
Autocompleter.register(editor, backstage.shared);
var windowMgr = setup$e({
editor: editor,
backstage: backstage
});
return {
renderUI: renderUI,
getWindowManagerImpl: constant(windowMgr),
getNotificationManagerImpl: function () {
return NotificationManagerImpl(editor, { backstage: backstage }, uiMothership);
},
ui: getUi()
};
});
}
Theme();
}());