').appendTo(containerElm);
global$1.each(blockers, function (blocker) {
global$9('#' + id, containerElm).append('
');
});
global$1.each(handles, function (handle) {
global$9('#' + id, containerElm).append('
');
});
dragHelpers = global$1.map(handles, createDragHelper);
repaint(currentRect);
global$9(containerElm).on('focusin focusout', function (e) {
global$9(e.target).attr('aria-grabbed', e.type === 'focus');
});
global$9(containerElm).on('keydown', function (e) {
var activeHandle;
global$1.each(handles, function (handle) {
if (e.target.id === id + '-' + handle.name) {
activeHandle = handle;
return false;
}
});
function moveAndBlock(evt, handle, startRect, deltaX, deltaY) {
evt.stopPropagation();
evt.preventDefault();
moveRect(activeHandle, startRect, deltaX, deltaY);
}
switch (e.keyCode) {
case global$11.LEFT:
moveAndBlock(e, activeHandle, currentRect, -10, 0);
break;
case global$11.RIGHT:
moveAndBlock(e, activeHandle, currentRect, 10, 0);
break;
case global$11.UP:
moveAndBlock(e, activeHandle, currentRect, 0, -10);
break;
case global$11.DOWN:
moveAndBlock(e, activeHandle, currentRect, 0, 10);
break;
case global$11.ENTER:
case global$11.SPACEBAR:
e.preventDefault();
action();
break;
}
});
}
function toggleVisibility(state) {
var selectors;
selectors = global$1.map(handles, function (handle) {
return '#' + id + '-' + handle.name;
}).concat(global$1.map(blockers, function (blocker) {
return '#' + id + '-' + blocker;
})).join(',');
if (state) {
global$9(selectors, containerElm).show();
} else {
global$9(selectors, containerElm).hide();
}
}
function repaint(rect) {
function updateElementRect(name, rect) {
if (rect.h < 0) {
rect.h = 0;
}
if (rect.w < 0) {
rect.w = 0;
}
global$9('#' + id + '-' + name, containerElm).css({
left: rect.x,
top: rect.y,
width: rect.w,
height: rect.h
});
}
global$1.each(handles, function (handle) {
global$9('#' + 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);
}
function setRect(rect) {
currentRect = rect;
repaint(currentRect);
}
function setViewPortRect(rect) {
viewPortRect = rect;
repaint(currentRect);
}
function setInnerRect(rect) {
setRect(getAbsoluteRect(clampRect, rect));
}
function setClampRect(rect) {
clampRect = rect;
repaint(currentRect);
}
function destroy() {
global$1.each(dragHelpers, function (helper) {
helper.destroy();
});
dragHelpers = [];
}
render();
instance = global$1.extend({
toggleVisibility: toggleVisibility,
setClampRect: setClampRect,
setRect: setRect,
getInnerRect: getInnerRect,
setInnerRect: setInnerRect,
setViewPortRect: setViewPortRect,
destroy: destroy
}, global$10);
return instance;
}
var create$2 = function (settings) {
var Control = global$7.get('Control');
var ImagePanel = Control.extend({
Defaults: { classes: 'imagepanel' },
selection: function (rect) {
if (arguments.length) {
this.state.set('rect', rect);
return this;
}
return this.state.get('rect');
},
imageSize: function () {
var viewRect = this.state.get('viewRect');
return {
w: viewRect.w,
h: viewRect.h
};
},
toggleCropRect: function (state) {
this.state.set('cropEnabled', state);
},
imageSrc: function (url) {
var self = this, img = new Image();
img.src = url;
$_e5sosfdxjfuw8p93.loadImage(img).then(function () {
var rect, $img;
var lastRect = self.state.get('viewRect');
$img = self.$el.find('img');
if ($img[0]) {
$img.replaceWith(img);
} else {
var bg = document.createElement('div');
bg.className = 'mce-imagepanel-bg';
self.getEl().appendChild(bg);
self.getEl().appendChild(img);
}
rect = {
x: 0,
y: 0,
w: img.naturalWidth,
h: img.naturalHeight
};
self.state.set('viewRect', rect);
self.state.set('rect', global$8.inflate(rect, -20, -20));
if (!lastRect || lastRect.w !== rect.w || lastRect.h !== rect.h) {
self.zoomFit();
}
self.repaintImage();
self.fire('load');
});
},
zoom: function (value) {
if (arguments.length) {
this.state.set('zoom', value);
return this;
}
return this.state.get('zoom');
},
postRender: function () {
this.imageSrc(this.settings.imageSrc);
return this._super();
},
zoomFit: function () {
var self = this;
var $img, pw, ph, w, h, zoom, padding;
padding = 10;
$img = self.$el.find('img');
pw = self.getEl().clientWidth;
ph = self.getEl().clientHeight;
w = $img[0].naturalWidth;
h = $img[0].naturalHeight;
zoom = Math.min((pw - padding) / w, (ph - padding) / h);
if (zoom >= 1) {
zoom = 1;
}
self.zoom(zoom);
},
repaintImage: function () {
var x, y, w, h, pw, ph, $img, $bg, zoom, rect, elm;
elm = this.getEl();
zoom = this.zoom();
rect = this.state.get('rect');
$img = this.$el.find('img');
$bg = this.$el.find('.mce-imagepanel-bg');
pw = elm.offsetWidth;
ph = elm.offsetHeight;
w = $img[0].naturalWidth * zoom;
h = $img[0].naturalHeight * zoom;
x = Math.max(0, pw / 2 - w / 2);
y = Math.max(0, ph / 2 - h / 2);
$img.css({
left: x,
top: y,
width: w,
height: h
});
$bg.css({
left: x,
top: y,
width: w,
height: h
});
if (this.cropRect) {
this.cropRect.setRect({
x: rect.x * zoom + x,
y: rect.y * zoom + y,
w: rect.w * zoom,
h: rect.h * zoom
});
this.cropRect.setClampRect({
x: x,
y: y,
w: w,
h: h
});
this.cropRect.setViewPortRect({
x: 0,
y: 0,
w: pw,
h: ph
});
}
},
bindStates: function () {
var self = this;
function setupCropRect(rect) {
self.cropRect = CropRect(rect, self.state.get('viewRect'), self.state.get('viewRect'), self.getEl(), function () {
self.fire('crop');
});
self.cropRect.on('updateRect', function (e) {
var rect = e.rect;
var zoom = self.zoom();
rect = {
x: Math.round(rect.x / zoom),
y: Math.round(rect.y / zoom),
w: Math.round(rect.w / zoom),
h: Math.round(rect.h / zoom)
};
self.state.set('rect', rect);
});
self.on('remove', self.cropRect.destroy);
}
self.state.on('change:cropEnabled', function (e) {
self.cropRect.toggleVisibility(e.value);
self.repaintImage();
});
self.state.on('change:zoom', function () {
self.repaintImage();
});
self.state.on('change:rect', function (e) {
var rect = e.value;
if (!self.cropRect) {
setupCropRect(rect);
}
self.cropRect.setRect(rect);
});
}
});
return new ImagePanel(settings);
};
var $_fyl1tedvjfuw8p8z = { create: create$2 };
function createState(blob) {
return {
blob: blob,
url: $_c1346xdmjfuw8p89.createObjectURL(blob)
};
}
function destroyState(state) {
if (state) {
$_c1346xdmjfuw8p89.revokeObjectURL(state.url);
}
}
function destroyStates(states) {
global$1.each(states, destroyState);
}
function open(editor, currentState, resolve, reject) {
var win, undoStack = UndoStack(), mainPanel, filtersPanel, tempState, cropPanel, resizePanel, flipRotatePanel, imagePanel, sidePanel, mainViewContainer, invertPanel, brightnessPanel, huePanel, saturatePanel, contrastPanel, grayscalePanel, sepiaPanel, colorizePanel, sharpenPanel, embossPanel, gammaPanel, exposurePanel, panels, width, height, ratioW, ratioH;
var reverseIfRtl = function (items) {
return editor.rtl ? items.reverse() : items;
};
function recalcSize(e) {
var widthCtrl, heightCtrl, newWidth, newHeight;
widthCtrl = win.find('#w')[0];
heightCtrl = win.find('#h')[0];
newWidth = parseInt(widthCtrl.value(), 10);
newHeight = parseInt(heightCtrl.value(), 10);
if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) {
if (e.control.settings.name === 'w') {
newHeight = Math.round(newWidth * ratioW);
heightCtrl.value(newHeight);
} else {
newWidth = Math.round(newHeight * ratioH);
widthCtrl.value(newWidth);
}
}
width = newWidth;
height = newHeight;
}
function floatToPercent(value) {
return Math.round(value * 100) + '%';
}
function updateButtonUndoStates() {
win.find('#undo').disabled(!undoStack.canUndo());
win.find('#redo').disabled(!undoStack.canRedo());
win.statusbar.find('#save').disabled(!undoStack.canUndo());
}
function disableUndoRedo() {
win.find('#undo').disabled(true);
win.find('#redo').disabled(true);
}
function displayState(state) {
if (state) {
imagePanel.imageSrc(state.url);
}
}
function switchPanel(targetPanel) {
return function () {
var hidePanels = global$1.grep(panels, function (panel) {
return panel.settings.name !== targetPanel;
});
global$1.each(hidePanels, function (panel) {
panel.hide();
});
targetPanel.show();
targetPanel.focus();
};
}
function addTempState(blob) {
tempState = createState(blob);
displayState(tempState);
}
function addBlobState(blob) {
currentState = createState(blob);
displayState(currentState);
destroyStates(undoStack.add(currentState).removed);
updateButtonUndoStates();
}
function crop() {
var rect = imagePanel.selection();
$_9ujscsdljfuw8p87.blobToImageResult(currentState.blob).then(function (ir) {
$_5r6zxadfjfuw8p7b.crop(ir, rect.x, rect.y, rect.w, rect.h).then(imageResultToBlob).then(function (blob) {
addBlobState(blob);
cancel();
});
});
}
var tempAction = function (fn) {
var args = [].slice.call(arguments, 1);
return function () {
var state = tempState || currentState;
$_9ujscsdljfuw8p87.blobToImageResult(state.blob).then(function (ir) {
fn.apply(this, [ir].concat(args)).then(imageResultToBlob).then(addTempState);
});
};
};
function action(fn) {
var arg = [];
for (var _i = 1; _i < arguments.length; _i++) {
arg[_i - 1] = arguments[_i];
}
var args = [].slice.call(arguments, 1);
return function () {
$_9ujscsdljfuw8p87.blobToImageResult(currentState.blob).then(function (ir) {
fn.apply(this, [ir].concat(args)).then(imageResultToBlob).then(addBlobState);
});
};
}
function cancel() {
displayState(currentState);
destroyState(tempState);
switchPanel(mainPanel)();
updateButtonUndoStates();
}
function waitForTempState(times, applyCall) {
if (tempState) {
applyCall();
} else {
setTimeout(function () {
if (times-- > 0) {
waitForTempState(times, applyCall);
} else {
editor.windowManager.alert('Error: failed to apply image operation.');
}
}, 10);
}
}
function applyTempState() {
if (tempState) {
addBlobState(tempState.blob);
cancel();
} else {
waitForTempState(100, applyTempState);
}
}
function zoomIn() {
var zoom = imagePanel.zoom();
if (zoom < 2) {
zoom += 0.1;
}
imagePanel.zoom(zoom);
}
function zoomOut() {
var zoom = imagePanel.zoom();
if (zoom > 0.1) {
zoom -= 0.1;
}
imagePanel.zoom(zoom);
}
function undo() {
currentState = undoStack.undo();
displayState(currentState);
updateButtonUndoStates();
}
function redo() {
currentState = undoStack.redo();
displayState(currentState);
updateButtonUndoStates();
}
function save() {
resolve(currentState.blob);
win.close();
}
function createPanel(items) {
return global$7.create('Form', {
layout: 'flex',
direction: 'row',
labelGap: 5,
border: '0 0 1 0',
align: 'center',
pack: 'center',
padding: '0 10 0 10',
spacing: 5,
flex: 0,
minHeight: 60,
defaults: {
classes: 'imagetool',
type: 'button'
},
items: items
});
}
var imageResultToBlob = function (ir) {
return ir.toBlob();
};
function createFilterPanel(title, filter) {
return createPanel(reverseIfRtl([
{
text: 'Back',
onclick: cancel
},
{
type: 'spacer',
flex: 1
},
{
text: 'Apply',
subtype: 'primary',
onclick: applyTempState
}
])).hide().on('show', function () {
disableUndoRedo();
$_9ujscsdljfuw8p87.blobToImageResult(currentState.blob).then(function (ir) {
return filter(ir);
}).then(imageResultToBlob).then(function (blob) {
var newTempState = createState(blob);
displayState(newTempState);
destroyState(tempState);
tempState = newTempState;
});
});
}
function createVariableFilterPanel(title, filter, value, min, max) {
function update(value) {
$_9ujscsdljfuw8p87.blobToImageResult(currentState.blob).then(function (ir) {
return filter(ir, value);
}).then(imageResultToBlob).then(function (blob) {
var newTempState = createState(blob);
displayState(newTempState);
destroyState(tempState);
tempState = newTempState;
});
}
return createPanel(reverseIfRtl([
{
text: 'Back',
onclick: cancel
},
{
type: 'spacer',
flex: 1
},
{
type: 'slider',
flex: 1,
ondragend: function (e) {
update(e.value);
},
minValue: editor.rtl ? max : min,
maxValue: editor.rtl ? min : max,
value: value,
previewFilter: floatToPercent
},
{
type: 'spacer',
flex: 1
},
{
text: 'Apply',
subtype: 'primary',
onclick: applyTempState
}
])).hide().on('show', function () {
this.find('slider').value(value);
disableUndoRedo();
});
}
function createRgbFilterPanel(title, filter) {
function update() {
var r, g, b;
r = win.find('#r')[0].value();
g = win.find('#g')[0].value();
b = win.find('#b')[0].value();
$_9ujscsdljfuw8p87.blobToImageResult(currentState.blob).then(function (ir) {
return filter(ir, r, g, b);
}).then(imageResultToBlob).then(function (blob) {
var newTempState = createState(blob);
displayState(newTempState);
destroyState(tempState);
tempState = newTempState;
});
}
var min = editor.rtl ? 2 : 0;
var max = editor.rtl ? 0 : 2;
return createPanel(reverseIfRtl([
{
text: 'Back',
onclick: cancel
},
{
type: 'spacer',
flex: 1
},
{
type: 'slider',
label: 'R',
name: 'r',
minValue: min,
value: 1,
maxValue: max,
ondragend: update,
previewFilter: floatToPercent
},
{
type: 'slider',
label: 'G',
name: 'g',
minValue: min,
value: 1,
maxValue: max,
ondragend: update,
previewFilter: floatToPercent
},
{
type: 'slider',
label: 'B',
name: 'b',
minValue: min,
value: 1,
maxValue: max,
ondragend: update,
previewFilter: floatToPercent
},
{
type: 'spacer',
flex: 1
},
{
text: 'Apply',
subtype: 'primary',
onclick: applyTempState
}
])).hide().on('show', function () {
win.find('#r,#g,#b').value(1);
disableUndoRedo();
});
}
cropPanel = createPanel(reverseIfRtl([
{
text: 'Back',
onclick: cancel
},
{
type: 'spacer',
flex: 1
},
{
text: 'Apply',
subtype: 'primary',
onclick: crop
}
])).hide().on('show hide', function (e) {
imagePanel.toggleCropRect(e.type === 'show');
}).on('show', disableUndoRedo);
function toggleConstrain(e) {
if (e.control.value() === true) {
ratioW = height / width;
ratioH = width / height;
}
}
resizePanel = createPanel(reverseIfRtl([
{
text: 'Back',
onclick: cancel
},
{
type: 'spacer',
flex: 1
},
{
type: 'textbox',
name: 'w',
label: 'Width',
size: 4,
onkeyup: recalcSize
},
{
type: 'textbox',
name: 'h',
label: 'Height',
size: 4,
onkeyup: recalcSize
},
{
type: 'checkbox',
name: 'constrain',
text: 'Constrain proportions',
checked: true,
onchange: toggleConstrain
},
{
type: 'spacer',
flex: 1
},
{
text: 'Apply',
subtype: 'primary',
onclick: 'submit'
}
])).hide().on('submit', function (e) {
var width = parseInt(win.find('#w').value(), 10), height = parseInt(win.find('#h').value(), 10);
e.preventDefault();
action($_5r6zxadfjfuw8p7b.resize, width, height)();
cancel();
}).on('show', disableUndoRedo);
flipRotatePanel = createPanel(reverseIfRtl([
{
text: 'Back',
onclick: cancel
},
{
type: 'spacer',
flex: 1
},
{
icon: 'fliph',
tooltip: 'Flip horizontally',
onclick: tempAction($_5r6zxadfjfuw8p7b.flip, 'h')
},
{
icon: 'flipv',
tooltip: 'Flip vertically',
onclick: tempAction($_5r6zxadfjfuw8p7b.flip, 'v')
},
{
icon: 'rotateleft',
tooltip: 'Rotate counterclockwise',
onclick: tempAction($_5r6zxadfjfuw8p7b.rotate, -90)
},
{
icon: 'rotateright',
tooltip: 'Rotate clockwise',
onclick: tempAction($_5r6zxadfjfuw8p7b.rotate, 90)
},
{
type: 'spacer',
flex: 1
},
{
text: 'Apply',
subtype: 'primary',
onclick: applyTempState
}
])).hide().on('show', disableUndoRedo);
invertPanel = createFilterPanel('Invert', $_5r6zxadfjfuw8p7b.invert);
sharpenPanel = createFilterPanel('Sharpen', $_5r6zxadfjfuw8p7b.sharpen);
embossPanel = createFilterPanel('Emboss', $_5r6zxadfjfuw8p7b.emboss);
brightnessPanel = createVariableFilterPanel('Brightness', $_5r6zxadfjfuw8p7b.brightness, 0, -1, 1);
huePanel = createVariableFilterPanel('Hue', $_5r6zxadfjfuw8p7b.hue, 180, 0, 360);
saturatePanel = createVariableFilterPanel('Saturate', $_5r6zxadfjfuw8p7b.saturate, 0, -1, 1);
contrastPanel = createVariableFilterPanel('Contrast', $_5r6zxadfjfuw8p7b.contrast, 0, -1, 1);
grayscalePanel = createVariableFilterPanel('Grayscale', $_5r6zxadfjfuw8p7b.grayscale, 0, 0, 1);
sepiaPanel = createVariableFilterPanel('Sepia', $_5r6zxadfjfuw8p7b.sepia, 0, 0, 1);
colorizePanel = createRgbFilterPanel('Colorize', $_5r6zxadfjfuw8p7b.colorize);
gammaPanel = createVariableFilterPanel('Gamma', $_5r6zxadfjfuw8p7b.gamma, 0, -1, 1);
exposurePanel = createVariableFilterPanel('Exposure', $_5r6zxadfjfuw8p7b.exposure, 1, 0, 2);
filtersPanel = createPanel(reverseIfRtl([
{
text: 'Back',
onclick: cancel
},
{
type: 'spacer',
flex: 1
},
{
text: 'hue',
icon: 'hue',
onclick: switchPanel(huePanel)
},
{
text: 'saturate',
icon: 'saturate',
onclick: switchPanel(saturatePanel)
},
{
text: 'sepia',
icon: 'sepia',
onclick: switchPanel(sepiaPanel)
},
{
text: 'emboss',
icon: 'emboss',
onclick: switchPanel(embossPanel)
},
{
text: 'exposure',
icon: 'exposure',
onclick: switchPanel(exposurePanel)
},
{
type: 'spacer',
flex: 1
}
])).hide();
mainPanel = createPanel(reverseIfRtl([
{
tooltip: 'Crop',
icon: 'crop',
onclick: switchPanel(cropPanel)
},
{
tooltip: 'Resize',
icon: 'resize2',
onclick: switchPanel(resizePanel)
},
{
tooltip: 'Orientation',
icon: 'orientation',
onclick: switchPanel(flipRotatePanel)
},
{
tooltip: 'Brightness',
icon: 'sun',
onclick: switchPanel(brightnessPanel)
},
{
tooltip: 'Sharpen',
icon: 'sharpen',
onclick: switchPanel(sharpenPanel)
},
{
tooltip: 'Contrast',
icon: 'contrast',
onclick: switchPanel(contrastPanel)
},
{
tooltip: 'Color levels',
icon: 'drop',
onclick: switchPanel(colorizePanel)
},
{
tooltip: 'Gamma',
icon: 'gamma',
onclick: switchPanel(gammaPanel)
},
{
tooltip: 'Invert',
icon: 'invert',
onclick: switchPanel(invertPanel)
}
]));
imagePanel = $_fyl1tedvjfuw8p8z.create({
flex: 1,
imageSrc: currentState.url
});
sidePanel = global$7.create('Container', {
layout: 'flex',
direction: 'column',
pack: 'start',
border: '0 1 0 0',
padding: 5,
spacing: 5,
items: [
{
type: 'button',
icon: 'undo',
tooltip: 'Undo',
name: 'undo',
onclick: undo
},
{
type: 'button',
icon: 'redo',
tooltip: 'Redo',
name: 'redo',
onclick: redo
},
{
type: 'button',
icon: 'zoomin',
tooltip: 'Zoom in',
onclick: zoomIn
},
{
type: 'button',
icon: 'zoomout',
tooltip: 'Zoom out',
onclick: zoomOut
}
]
});
mainViewContainer = global$7.create('Container', {
type: 'container',
layout: 'flex',
direction: 'row',
align: 'stretch',
flex: 1,
items: reverseIfRtl([
sidePanel,
imagePanel
])
});
panels = [
mainPanel,
cropPanel,
resizePanel,
flipRotatePanel,
filtersPanel,
invertPanel,
brightnessPanel,
huePanel,
saturatePanel,
contrastPanel,
grayscalePanel,
sepiaPanel,
colorizePanel,
sharpenPanel,
embossPanel,
gammaPanel,
exposurePanel
];
win = editor.windowManager.open({
layout: 'flex',
direction: 'column',
align: 'stretch',
minWidth: Math.min(global$6.DOM.getViewPort().w, 800),
minHeight: Math.min(global$6.DOM.getViewPort().h, 650),
title: 'Edit image',
items: panels.concat([mainViewContainer]),
buttons: reverseIfRtl([
{
text: 'Save',
name: 'save',
subtype: 'primary',
onclick: save
},
{
text: 'Cancel',
onclick: 'close'
}
])
});
win.on('close', function () {
reject();
destroyStates(undoStack.data);
undoStack = null;
tempState = null;
});
undoStack.add(currentState);
updateButtonUndoStates();
imagePanel.on('load', function () {
width = imagePanel.imageSize().w;
height = imagePanel.imageSize().h;
ratioW = height / width;
ratioH = width / height;
win.find('#w').value(width);
win.find('#h').value(height);
});
imagePanel.on('crop', crop);
}
function edit(editor, imageResult) {
return new global$4(function (resolve, reject) {
return imageResult.toBlob().then(function (blob) {
open(editor, createState(blob), resolve, reject);
});
});
}
var $_90401edrjfuw8p8h = { edit: edit };
function getImageSize(img) {
var width, height;
function isPxValue(value) {
return /^[0-9\.]+px$/.test(value);
}
width = img.style.width;
height = img.style.height;
if (width || height) {
if (isPxValue(width) && isPxValue(height)) {
return {
w: parseInt(width, 10),
h: parseInt(height, 10)
};
}
return null;
}
width = img.width;
height = img.height;
if (width && height) {
return {
w: parseInt(width, 10),
h: parseInt(height, 10)
};
}
return null;
}
function setImageSize(img, size) {
var width, height;
if (size) {
width = img.style.width;
height = img.style.height;
if (width || height) {
img.style.width = size.w + 'px';
img.style.height = size.h + 'px';
img.removeAttribute('data-mce-style');
}
width = img.width;
height = img.height;
if (width || height) {
img.setAttribute('width', size.w);
img.setAttribute('height', size.h);
}
}
}
function getNaturalImageSize(img) {
return {
w: img.naturalWidth,
h: img.naturalHeight
};
}
var $_8ke5see2jfuw8p9d = {
getImageSize: getImageSize,
setImageSize: setImageSize,
getNaturalImageSize: getNaturalImageSize
};
var typeOf = function (x) {
if (x === null)
return 'null';
var t = typeof x;
if (t === 'object' && Array.prototype.isPrototypeOf(x))
return 'array';
if (t === 'object' && String.prototype.isPrototypeOf(x))
return 'string';
return t;
};
var isType = function (type) {
return function (value) {
return typeOf(value) === type;
};
};
var $_9dbzc3e6jfuw8pa6 = {
isString: isType('string'),
isObject: isType('object'),
isArray: isType('array'),
isNull: isType('null'),
isBoolean: isType('boolean'),
isUndefined: isType('undefined'),
isFunction: isType('function'),
isNumber: isType('number')
};
var rawIndexOf = function () {
var pIndexOf = Array.prototype.indexOf;
var fastIndex = function (xs, x) {
return pIndexOf.call(xs, x);
};
var slowIndex = function (xs, x) {
return slowIndexOf(xs, x);
};
return pIndexOf === undefined ? slowIndex : fastIndex;
}();
var indexOf = function (xs, x) {
var r = rawIndexOf(xs, x);
return r === -1 ? Option.none() : Option.some(r);
};
var contains = function (xs, x) {
return rawIndexOf(xs, x) > -1;
};
var exists = function (xs, pred) {
return findIndex(xs, pred).isSome();
};
var range = function (num, f) {
var r = [];
for (var i = 0; i < num; i++) {
r.push(f(i));
}
return r;
};
var chunk = function (array, size) {
var r = [];
for (var i = 0; i < array.length; i += size) {
var s = array.slice(i, i + size);
r.push(s);
}
return r;
};
var map = function (xs, f) {
var len = xs.length;
var r = new Array(len);
for (var i = 0; i < len; i++) {
var x = xs[i];
r[i] = f(x, i, xs);
}
return r;
};
var each = function (xs, f) {
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
f(x, i, xs);
}
};
var eachr = function (xs, f) {
for (var i = xs.length - 1; i >= 0; i--) {
var x = xs[i];
f(x, i, xs);
}
};
var partition = function (xs, pred) {
var pass = [];
var fail = [];
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
var arr = pred(x, i, xs) ? pass : fail;
arr.push(x);
}
return {
pass: pass,
fail: fail
};
};
var filter = function (xs, pred) {
var r = [];
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
if (pred(x, i, xs)) {
r.push(x);
}
}
return r;
};
var groupBy = function (xs, f) {
if (xs.length === 0) {
return [];
} else {
var wasType = f(xs[0]);
var r = [];
var group = [];
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
var type = f(x);
if (type !== wasType) {
r.push(group);
group = [];
}
wasType = type;
group.push(x);
}
if (group.length !== 0) {
r.push(group);
}
return r;
}
};
var foldr = function (xs, f, acc) {
eachr(xs, function (x) {
acc = f(acc, x);
});
return acc;
};
var foldl = function (xs, f, acc) {
each(xs, function (x) {
acc = f(acc, x);
});
return acc;
};
var find = function (xs, pred) {
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
if (pred(x, i, xs)) {
return Option.some(x);
}
}
return Option.none();
};
var findIndex = function (xs, pred) {
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
if (pred(x, i, xs)) {
return Option.some(i);
}
}
return Option.none();
};
var slowIndexOf = function (xs, x) {
for (var i = 0, len = xs.length; i < len; ++i) {
if (xs[i] === x) {
return i;
}
}
return -1;
};
var push = Array.prototype.push;
var flatten = function (xs) {
var r = [];
for (var i = 0, len = xs.length; i < len; ++i) {
if (!Array.prototype.isPrototypeOf(xs[i]))
throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
push.apply(r, xs[i]);
}
return r;
};
var bind = function (xs, f) {
var output = map(xs, f);
return flatten(output);
};
var forall = function (xs, pred) {
for (var i = 0, len = xs.length; i < len; ++i) {
var x = xs[i];
if (pred(x, i, xs) !== true) {
return false;
}
}
return true;
};
var equal = function (a1, a2) {
return a1.length === a2.length && forall(a1, function (x, i) {
return x === a2[i];
});
};
var slice = Array.prototype.slice;
var reverse = function (xs) {
var r = slice.call(xs, 0);
r.reverse();
return r;
};
var difference = function (a1, a2) {
return filter(a1, function (x) {
return !contains(a2, x);
});
};
var mapToObject = function (xs, f) {
var r = {};
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
r[String(x)] = f(x, i);
}
return r;
};
var pure = function (x) {
return [x];
};
var sort = function (xs, comparator) {
var copy = slice.call(xs, 0);
copy.sort(comparator);
return copy;
};
var head = function (xs) {
return xs.length === 0 ? Option.none() : Option.some(xs[0]);
};
var last = function (xs) {
return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]);
};
var from$1 = $_9dbzc3e6jfuw8pa6.isFunction(Array.from) ? Array.from : function (x) {
return slice.call(x);
};
var $_7pcc65e5jfuw8pa0 = {
map: map,
each: each,
eachr: eachr,
partition: partition,
filter: filter,
groupBy: groupBy,
indexOf: indexOf,
foldr: foldr,
foldl: foldl,
find: find,
findIndex: findIndex,
flatten: flatten,
bind: bind,
forall: forall,
exists: exists,
contains: contains,
equal: equal,
reverse: reverse,
chunk: chunk,
difference: difference,
mapToObject: mapToObject,
pure: pure,
sort: sort,
range: range,
head: head,
last: last,
from: from$1
};
function XMLHttpRequest$1 () {
var f = $_9b4fxbd9jfuw8p72.getOrDie('XMLHttpRequest');
return new f();
}
var isValue = function (obj) {
return obj !== null && obj !== undefined;
};
var traverse = function (json, path) {
var value;
value = path.reduce(function (result, key) {
return isValue(result) ? result[key] : undefined;
}, json);
return isValue(value) ? value : null;
};
var requestUrlAsBlob = function (url, headers, withCredentials) {
return new global$4(function (resolve) {
var xhr;
xhr = new XMLHttpRequest$1();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
resolve({
status: xhr.status,
blob: this.response
});
}
};
xhr.open('GET', url, true);
xhr.withCredentials = withCredentials;
global$1.each(headers, function (value, key) {
xhr.setRequestHeader(key, value);
});
xhr.responseType = 'blob';
xhr.send();
});
};
var readBlob = function (blob) {
return new global$4(function (resolve) {
var fr = new FileReader();
fr.onload = function (e) {
var data = e.target;
resolve(data.result);
};
fr.readAsText(blob);
});
};
var parseJson = function (text) {
var json;
try {
json = JSON.parse(text);
} catch (ex) {
}
return json;
};
var $_1782wge7jfuw8pa8 = {
traverse: traverse,
readBlob: readBlob,
requestUrlAsBlob: requestUrlAsBlob,
parseJson: parseJson
};
var friendlyHttpErrors = [
{
code: 404,
message: 'Could not find Image Proxy'
},
{
code: 403,
message: 'Rejected request'
},
{
code: 0,
message: 'Incorrect Image Proxy URL'
}
];
var friendlyServiceErrors = [
{
type: 'key_missing',
message: 'The request did not include an api key.'
},
{
type: 'key_not_found',
message: 'The provided api key could not be found.'
},
{
type: 'domain_not_trusted',
message: 'The api key is not valid for the request origins.'
}
];
var isServiceErrorCode = function (code) {
return code === 400 || code === 403 || code === 500;
};
var getHttpErrorMsg = function (status) {
var message = $_7pcc65e5jfuw8pa0.find(friendlyHttpErrors, function (error) {
return status === error.code;
}).fold($_9jziv0d7jfuw8p6z.constant('Unknown ImageProxy error'), function (error) {
return error.message;
});
return 'ImageProxy HTTP error: ' + message;
};
var handleHttpError = function (status) {
var message = getHttpErrorMsg(status);
return global$4.reject(message);
};
var getServiceErrorMsg = function (type) {
return $_7pcc65e5jfuw8pa0.find(friendlyServiceErrors, function (error) {
return error.type === type;
}).fold($_9jziv0d7jfuw8p6z.constant('Unknown service error'), function (error) {
return error.message;
});
};
var getServiceError = function (text) {
var serviceError = $_1782wge7jfuw8pa8.parseJson(text);
var errorType = $_1782wge7jfuw8pa8.traverse(serviceError, [
'error',
'type'
]);
var errorMsg = errorType ? getServiceErrorMsg(errorType) : 'Invalid JSON in service error message';
return 'ImageProxy Service error: ' + errorMsg;
};
var handleServiceError = function (status, blob) {
return $_1782wge7jfuw8pa8.readBlob(blob).then(function (text) {
var serviceError = getServiceError(text);
return global$4.reject(serviceError);
});
};
var handleServiceErrorResponse = function (status, blob) {
return isServiceErrorCode(status) ? handleServiceError(status, blob) : handleHttpError(status);
};
var $_2s68z4e4jfuw8p9j = {
handleServiceErrorResponse: handleServiceErrorResponse,
handleHttpError: handleHttpError,
getHttpErrorMsg: getHttpErrorMsg,
getServiceErrorMsg: getServiceErrorMsg
};
var appendApiKey = function (url, apiKey) {
var separator = url.indexOf('?') === -1 ? '?' : '&';
if (/[?&]apiKey=/.test(url) || !apiKey) {
return url;
} else {
return url + separator + 'apiKey=' + encodeURIComponent(apiKey);
}
};
var requestServiceBlob = function (url, apiKey) {
var headers = {
'Content-Type': 'application/json;charset=UTF-8',
'tiny-api-key': apiKey
};
return $_1782wge7jfuw8pa8.requestUrlAsBlob(appendApiKey(url, apiKey), headers, false).then(function (result) {
return result.status < 200 || result.status >= 300 ? $_2s68z4e4jfuw8p9j.handleServiceErrorResponse(result.status, result.blob) : global$4.resolve(result.blob);
});
};
function requestBlob(url, withCredentials) {
return $_1782wge7jfuw8pa8.requestUrlAsBlob(url, {}, withCredentials).then(function (result) {
return result.status < 200 || result.status >= 300 ? $_2s68z4e4jfuw8p9j.handleHttpError(result.status) : global$4.resolve(result.blob);
});
}
var getUrl = function (url, apiKey, withCredentials) {
return apiKey ? requestServiceBlob(url, apiKey) : requestBlob(url, withCredentials);
};
var $_e2n1vfe3jfuw8p9h = { getUrl: getUrl };
var count$1 = 0;
var isEditableImage = function (editor, img) {
var selectorMatched = editor.dom.is(img, 'img:not([data-mce-object],[data-mce-placeholder])');
return selectorMatched && (isLocalImage(editor, img) || isCorsImage(editor, img) || editor.settings.imagetools_proxy);
};
var displayError = function (editor, error) {
editor.notificationManager.open({
text: error,
type: 'error'
});
};
var getSelectedImage = function (editor) {
return editor.selection.getNode();
};
var extractFilename = function (editor, url) {
var m = url.match(/\/([^\/\?]+)?\.(?:jpeg|jpg|png|gif)(?:\?|$)/i);
if (m) {
return editor.dom.encode(m[1]);
}
return null;
};
var createId = function () {
return 'imagetools' + count$1++;
};
var isLocalImage = function (editor, img) {
var url = img.src;
return url.indexOf('data:') === 0 || url.indexOf('blob:') === 0 || new global$5(url).host === editor.documentBaseURI.host;
};
var isCorsImage = function (editor, img) {
return global$1.inArray(getCorsHosts(editor), new global$5(img.src).host) !== -1;
};
var isCorsWithCredentialsImage = function (editor, img) {
return global$1.inArray(getCredentialsHosts(editor), new global$5(img.src).host) !== -1;
};
var imageToBlob$2 = function (editor, img) {
var src = img.src, apiKey;
if (isCorsImage(editor, img)) {
return $_e2n1vfe3jfuw8p9h.getUrl(img.src, null, isCorsWithCredentialsImage(editor, img));
}
if (!isLocalImage(editor, img)) {
src = getProxyUrl(editor);
src += (src.indexOf('?') === -1 ? '?' : '&') + 'url=' + encodeURIComponent(img.src);
apiKey = getApiKey(editor);
return $_e2n1vfe3jfuw8p9h.getUrl(src, apiKey, false);
}
return $_5ofeufd1jfuw8p63.imageToBlob(img);
};
var findSelectedBlob = function (editor) {
var blobInfo;
blobInfo = editor.editorUpload.blobCache.getByUri(getSelectedImage(editor).src);
if (blobInfo) {
return global$4.resolve(blobInfo.blob());
}
return imageToBlob$2(editor, getSelectedImage(editor));
};
var startTimedUpload = function (editor, imageUploadTimerState) {
var imageUploadTimer = global$3.setEditorTimeout(editor, function () {
editor.editorUpload.uploadImagesAuto();
}, getUploadTimeout(editor));
imageUploadTimerState.set(imageUploadTimer);
};
var cancelTimedUpload = function (imageUploadTimerState) {
clearTimeout(imageUploadTimerState.get());
};
var updateSelectedImage = function (editor, ir, uploadImmediately, imageUploadTimerState, size) {
return ir.toBlob().then(function (blob) {
var uri, name, blobCache, blobInfo, selectedImage;
blobCache = editor.editorUpload.blobCache;
selectedImage = getSelectedImage(editor);
uri = selectedImage.src;
if (shouldReuseFilename(editor)) {
blobInfo = blobCache.getByUri(uri);
if (blobInfo) {
uri = blobInfo.uri();
name = blobInfo.name();
} else {
name = extractFilename(editor, uri);
}
}
blobInfo = blobCache.create({
id: createId(),
blob: blob,
base64: ir.toBase64(),
uri: uri,
name: name
});
blobCache.add(blobInfo);
editor.undoManager.transact(function () {
function imageLoadedHandler() {
editor.$(selectedImage).off('load', imageLoadedHandler);
editor.nodeChanged();
if (uploadImmediately) {
editor.editorUpload.uploadImagesAuto();
} else {
cancelTimedUpload(imageUploadTimerState);
startTimedUpload(editor, imageUploadTimerState);
}
}
editor.$(selectedImage).on('load', imageLoadedHandler);
if (size) {
editor.$(selectedImage).attr({
width: size.w,
height: size.h
});
}
editor.$(selectedImage).attr({ src: blobInfo.blobUri() }).removeAttr('data-mce-src');
});
return blobInfo;
});
};
var selectedImageOperation = function (editor, imageUploadTimerState, fn, size) {
return function () {
return editor._scanForImages().then($_9jziv0d7jfuw8p6z.curry(findSelectedBlob, editor)).then($_9ujscsdljfuw8p87.blobToImageResult).then(fn).then(function (imageResult) {
return updateSelectedImage(editor, imageResult, false, imageUploadTimerState, size);
}, function (error) {
displayError(editor, error);
});
};
};
var rotate$2 = function (editor, imageUploadTimerState, angle) {
return function () {
var size = $_8ke5see2jfuw8p9d.getImageSize(getSelectedImage(editor));
var flippedSize = size ? {
w: size.h,
h: size.w
} : null;
return selectedImageOperation(editor, imageUploadTimerState, function (imageResult) {
return $_5r6zxadfjfuw8p7b.rotate(imageResult, angle);
}, flippedSize)();
};
};
var flip$2 = function (editor, imageUploadTimerState, axis) {
return function () {
return selectedImageOperation(editor, imageUploadTimerState, function (imageResult) {
return $_5r6zxadfjfuw8p7b.flip(imageResult, axis);
})();
};
};
var editImageDialog = function (editor, imageUploadTimerState) {
return function () {
var img = getSelectedImage(editor), originalSize = $_8ke5see2jfuw8p9d.getNaturalImageSize(img);
var handleDialogBlob = function (blob) {
return new global$4(function (resolve) {
$_5ofeufd1jfuw8p63.blobToImage(blob).then(function (newImage) {
var newSize = $_8ke5see2jfuw8p9d.getNaturalImageSize(newImage);
if (originalSize.w !== newSize.w || originalSize.h !== newSize.h) {
if ($_8ke5see2jfuw8p9d.getImageSize(img)) {
$_8ke5see2jfuw8p9d.setImageSize(img, newSize);
}
}
$_c1346xdmjfuw8p89.revokeObjectURL(newImage.src);
resolve(blob);
});
});
};
var openDialog = function (editor, imageResult) {
return $_90401edrjfuw8p8h.edit(editor, imageResult).then(handleDialogBlob).then($_9ujscsdljfuw8p87.blobToImageResult).then(function (imageResult) {
return updateSelectedImage(editor, imageResult, true, imageUploadTimerState);
}, function () {
});
};
findSelectedBlob(editor).then($_9ujscsdljfuw8p87.blobToImageResult).then($_9jziv0d7jfuw8p6z.curry(openDialog, editor), function (error) {
displayError(editor, error);
});
};
};
var $_c2sybyd0jfuw8p5m = {
rotate: rotate$2,
flip: flip$2,
editImageDialog: editImageDialog,
isEditableImage: isEditableImage,
cancelTimedUpload: cancelTimedUpload
};
var register = function (editor, imageUploadTimerState) {
global$1.each({
mceImageRotateLeft: $_c2sybyd0jfuw8p5m.rotate(editor, imageUploadTimerState, -90),
mceImageRotateRight: $_c2sybyd0jfuw8p5m.rotate(editor, imageUploadTimerState, 90),
mceImageFlipVertical: $_c2sybyd0jfuw8p5m.flip(editor, imageUploadTimerState, 'v'),
mceImageFlipHorizontal: $_c2sybyd0jfuw8p5m.flip(editor, imageUploadTimerState, 'h'),
mceEditImage: $_c2sybyd0jfuw8p5m.editImageDialog(editor, imageUploadTimerState)
}, function (fn, cmd) {
editor.addCommand(cmd, fn);
});
};
var $_3c96qdcyjfuw8p5j = { register: register };
var setup = function (editor, imageUploadTimerState, lastSelectedImageState) {
editor.on('NodeChange', function (e) {
var lastSelectedImage = lastSelectedImageState.get();
if (lastSelectedImage && lastSelectedImage.src !== e.element.src) {
$_c2sybyd0jfuw8p5m.cancelTimedUpload(imageUploadTimerState);
editor.editorUpload.uploadImagesAuto();
lastSelectedImageState.set(null);
}
if ($_c2sybyd0jfuw8p5m.isEditableImage(editor, e.element)) {
lastSelectedImageState.set(e.element);
}
});
};
var $_ffveg8e9jfuw8pai = { setup: setup };
var register$1 = function (editor) {
editor.addButton('rotateleft', {
title: 'Rotate counterclockwise',
cmd: 'mceImageRotateLeft'
});
editor.addButton('rotateright', {
title: 'Rotate clockwise',
cmd: 'mceImageRotateRight'
});
editor.addButton('flipv', {
title: 'Flip vertically',
cmd: 'mceImageFlipVertical'
});
editor.addButton('fliph', {
title: 'Flip horizontally',
cmd: 'mceImageFlipHorizontal'
});
editor.addButton('editimage', {
title: 'Edit image',
cmd: 'mceEditImage'
});
editor.addButton('imageoptions', {
title: 'Image options',
icon: 'options',
cmd: 'mceImage'
});
};
var $_d28x8ueajfuw8paj = { register: register$1 };
var register$2 = function (editor) {
editor.addContextToolbar($_9jziv0d7jfuw8p6z.curry($_c2sybyd0jfuw8p5m.isEditableImage, editor), getToolbarItems(editor));
};
var $_bsi4uuebjfuw8pak = { register: register$2 };
global.add('imagetools', function (editor) {
var imageUploadTimerState = Cell(0);
var lastSelectedImageState = Cell(null);
$_3c96qdcyjfuw8p5j.register(editor, imageUploadTimerState);
$_d28x8ueajfuw8paj.register(editor);
$_bsi4uuebjfuw8pak.register(editor);
$_ffveg8e9jfuw8pai.setup(editor, imageUploadTimerState, lastSelectedImageState);
});
function Plugin () {
}
return Plugin;
}());
})();