Newer
Older
plugin.inpaste = true;
if (typeof(cd) === 'undefined')
return bail();
if (cd.items && cd.items.length)
{
for (i = 0, k = cd.items.length; i < k; i++) {
if (cd.items[i].kind == 'file' && cd.items[i].type.indexOf('image/') !== -1) {
file = cd.items[i].getAsFile();
if (file !== null)
files.push(file);
}
}
}
else if (cd.files && cd.files.length)
{
}
else if (cd.types.length) {
for (i = 0, k = cd.types.length; i < k; i++) {
if (cd.types[i].indexOf('image/') != -1) {
var data = cd.getData(cd.types[i]);
files.push(new Blob([data], {type: cd.types[i]}));
if (!files.length)
return bail();
e.preventDefault();
e.stopImmediatePropagation();
if (plugin.offset == 0) {
// Assume top left of editor window since no last position is known
var offset = self.$editor.offset();
plugin.offset = {
clientX: offset.left - $(document).scrollLeft() + 20,
clientY: offset.top - $(document).scrollTop() + self.$toolbar.height() + 20
}
}
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
// Add cool wait cursor
var waitCursor = $('<span class="-image-upload-placeholder icon-stack"><i class="icon-circle icon-stack-base"></i><i class="icon-picture icon-light icon-spin"></i></span>');
self.insert.nodeToCaretPositionFromPoint(plugin.offset, waitCursor);
var oldIUC = self.opts.imageUploadCallback;
self.opts.imageUploadCallback = function(image, json) {
if ($.contains(waitCursor.get(0), image))
waitCursor.replaceWith(image);
else
waitCursor.remove();
self.opts.imageUploadCallback = oldIUC;
// Add a zero-width space so that the caret:getOffset will find
// locations after pictures if only <br> tags exist otherwise. In
// other words, ensure there is at least one character after the
// image for text character counting. Additionally, Redactor will
// strip the zero-width space when saving
$(document.createTextNode("\u200b")).insertAfter($(image));
bail();
};
// Upload clipboard files
for (i = 0, k = files.length; i < k; i++)
self.upload.directUpload(files[i], plugin.offset);
RedactorPlugins.imageannotate = function() {
return {
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
var redactor = this,
self = this.imageannotate;
$(document).on('click', '.redactor-box img', function() {
var $image = $(this),
image_box = $('#redactor-image-box');
if (!image_box.length || !redactor.image.editter)
return;
var edit_size = redactor.image.editter.outerWidth();
self.annotateButton = redactor.image.editter
.on('remove.annotate',
function() { self.teardownAnnotate.call(redactor, image_box); })
.clone()
.text(' '+__('Annotate'))
.prepend('<i class="icon-pencil"></i>')
.addClass('annotate-button')
.insertAfter(redactor.image.editter)
.data('image', this)
.on('click',
function() { self.startAnnotate.call(redactor, $image) });
var diff = (edit_size - self.annotateButton.outerWidth()) / 2;
self.annotateButton.css('margin-left',
(diff + 5) + 'px');
redactor.image.editter.css('margin-left',
(-edit_size + diff - 5) + 'px');
});
},
startAnnotate: function(img) {
canvas = this.imageannotate.initCanvas(img);
this.imageannotate.buildToolbar(img);
this.image.editter.hide();
this.imageannotate.annotateButton.hide();
},
teardownAnnotate: function(box) {
this.image.editter.off('.annotate');
this.opts.keydownCallback = false;
this.opts.keyupCallback = false;
box.find('.annotate-toolbar').remove();
box.find('.annotate-button').remove();
var img = box.find('img')[0],
$img = $(img),
fcanvas = $img.data('canvas'),
state = fcanvas.toObject();
// Capture current annotations
delete state.backgroundImage;
$img.attr('data-annotations', btoa(JSON.stringify(state)));
// Drop the canvas
fcanvas.dispose();
box.find('canvas').parent().remove();
$img.data('canvas', false);
// Deselect the image
this.image.hideResize();
// Show the original image
$img.removeClass('hidden');
},
buildToolbar: function(img) {
var box = img.parent(),
redactor = this,
plugin = this.imageannotate,
shapes = $('<span>')
.attr('data-redactor', 'verified')
.attr('contenteditable', 'false')
.css({'display': 'inline-block', 'vertical-align': 'top'}),
swatches = shapes.clone(),
actions = shapes.clone(),
container = $('<div></div>')
.addClass('annotate-toolbar')
.attr('data-redactor', 'verified')
.attr('contenteditable', 'false')
.css({position: 'absolute', bottom: 0, 'min-height': '28px',
width: '100%', 'background-color': 'rgba(0,0,0,0.5)',
margin: 0, 'padding-top': '4px' })
.appendTo(box)
.append(shapes)
.append(swatches)
.append(actions);
var button = $('<a></a>')
.attr('href', '#')
.attr('data-redactor', 'verified')
.attr('contenteditable', 'false')
.css({color: 'white', padding: '0 7px 1px', margin: '1px 3px',
'text-decoration': 'none', 'vertical-align': 'top'});
shapes
.append(button.clone()
.append($('<i class="icon-arrow-right icon-large"></i>')
.on('click', plugin.drawArrow.bind(redactor))
.attr('title', __('Add Arrow')))
)
.append(button.clone()
.append($('<i class="icon-check-empty icon-large"></i>')
.on('click', plugin.drawBox.bind(redactor))
.attr('title', __('Add Rectangle')))
)
.append(button.clone()
.append($('<i class="icon-circle-blank icon-large"></i>')
.on('click', plugin.drawEllipse.bind(redactor))
.attr('title', __('Add Ellipse')))
)
.append(button.clone()
.append($('<i class="icon-text-height icon-large"></i>')
.on('click', plugin.drawText.bind(redactor))
.attr('title', __('Add Text')))
);
var colors = [
'#ffffff', '#888888', '#000000', 'fuchsia', 'blue', 'red',
'lime', 'blueviolet', 'cyan', '#f4a63b', 'yellow']
len = colors.length;
swatches.append(
$('<span><i class="icon-ellipsis-vertical icon-large"></i></span>')
.css({color: 'white', padding: '0 3px 1px', margin: '1px 3px',
height: '21px', position: 'relative', bottom: '8px'}
)
);
for (var z = 0; z < len; z++) {
var color = colors[z];
var $swatch = $('<a rel="' + color + '" href="#" style="font-size: 0; padding: 0; margin: 2px; width: 22px; height: 22px;"></a>');
$swatch.css({'background-color': color, 'border': '1px dotted rgba(255,255,255,0.4)'});
$swatch.attr('data-redactor', 'verified');
$swatch.attr('contenteditable', 'false');
$swatch.on('click', plugin.setColor.bind(redactor));
swatches.append($swatch);
}
actions
.append(
$('<span><i class="icon-ellipsis-vertical icon-large"></i></span>')
.css({color: 'white', padding: '0 3px 1px', margin: '1px 3px',
height: '21px'}
)
)
.append(button.clone()
.css('padding-left', '1px')
.append($('<span></span>').css('position','relative')
.append($('<i class="icon-font"></i>'))
.append($('<i class="icon-minus"></i>')
.css({position: 'absolute', right: '-4px', top: '5px',
'text-shadow': '0 0 2px black', 'font-size':'80%'})
)
)
.on('click', plugin.smallerFont.bind(redactor))
.attr('title', __('Decrease Font Size'))
)
.append(button.clone()
.css('padding-left', '1px')
.append($('<span></span>').css('position','relative')
.append($('<i class="icon-font icon-large"></i>'))
.append($('<i class="icon-plus"></i>')
.css({position: 'absolute', right: '-8px', top: '4px',
'text-shadow': '0 0 2px black'})
)
)
.on('click', plugin.biggerFont.bind(redactor))
.attr('title', __('Increase Font Size'))
)
.append(button.clone()
.attr('id', 'annotate-set-stroke')
.append($('<span></span>').css({'position': 'relative', 'top': '2px'})
.append($('<i class="icon-check-empty icon-large"></i>')
.css('font-size', '120%')
).append($('<i class="icon-tint"></i>')
.css({position: 'absolute', left: '4.5px', top: 0})
)
)
.on('click', plugin.paintStroke.bind(redactor))
.attr('title', __('Set Stroke'))
)
.append(button.clone()
.attr('id', 'annotate-set-fill')
.append($('<span></span>').css('position','relative')
.append($('<i class="icon-sign-blank icon-large"></i>'))
.append($('<i class="icon-tint icon-dark"></i>')
.css({position: 'absolute', left: '4px', top: '2px'})
)
)
.on('click', plugin.paintFill.bind(redactor))
.attr('title', __('Set Fill'))
)
.append(button.clone()
.append($('<i class="icon-eye-close icon-large"></i>'))
.on('click', plugin.setOpacity.bind(redactor))
.attr('title', __('Toggle Opacity'))
)
.append(button.clone()
.append($('<i class="icon-double-angle-up icon-large"></i>'))
.on('click', plugin.bringForward.bind(redactor))
.attr('title', __('Bring Forward'))
)
.append(button.clone()
.append($('<i class="icon-trash icon-large"></i>'))
.on('click', plugin.discard.bind(redactor))
.attr('title', __('Delete Object'))
);
container.append(button.clone()
.append($('<i class="icon-save icon-large"></i>'))
.on('click', plugin.commit.bind(redactor))
.addClass('pull-right')
.attr('title', __('Commit Annotations'))
);
plugin.paintStroke();
},
setColor: function(e) {
e.preventDefault();
var plugin = this.imageannotate,
redactor = this,
swatch = e.target,
image_box = $('#redactor-image-box'),
img = image_box.find('img')[0],
fcanvas = $(img).data('canvas');
$.each(fcanvas.getObjects(), function() {
if (this.get('active')) {
if (plugin.paintMode == 'fill')
this.setFill($(e.target).attr('rel'));
else
this.setStroke($(e.target).attr('rel'));
}
});
fcanvas.renderAll();
// Shapes
drawShape: function(ondown, onmove, onup, cursor) {
// @see http://jsfiddle.net/URWru/
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
var plugin = this.imageannotate,
redactor = this,
image_box = $('#redactor-image-box'),
img = image_box.find('img')[0],
fcanvas = $(img).data('canvas'),
isDown, shape,
mousedown = function(o) {
isDown = true;
plugin.setBuffer();
var pointer = fcanvas.getPointer(o.e);
shape = ondown(pointer, o.e);
fcanvas.add(shape);
},
mousemove = function(o) {
if (!isDown) return;
var pointer = fcanvas.getPointer(o.e);
onmove(shape, pointer, o.e);
fcanvas.renderAll();
},
mouseup = function(o) {
isDown = false;
if (onup) {
if (shape2 = onup(shape, fcanvas.getPointer(o.e))) {
shape.remove();
fcanvas.add(shape2);
shape = shape2;
}
}
shape.setCoords()
.set({
transparentCorners: false,
borderColor: 'rgba(102,153,255,0.9)',
cornerColor: 'rgba(102,153,255,0.5)',
cornerSize: 10
});
fcanvas.calcOffset()
.off('mouse:down', mousedown)
.off('mouse:up', mouseup)
.off('mouse:move', mousemove)
.deactivateAll()
.setActiveObject(shape)
.renderAll();
fcanvas.selection = true;
fcanvas.defaultCursor = 'default';
};
fcanvas.selection = false;
fcanvas.defaultCursor = cursor || 'crosshair';
// Ensure double presses of same button are squelched
fcanvas.off('mouse:down');
fcanvas.off('mouse:up');
fcanvas.off('mouse:move');
fcanvas.on('mouse:down', mousedown);
fcanvas.on('mouse:up', mouseup);
fcanvas.on('mouse:move', mousemove);
return false;
},
drawArrow: function(e) {
e.preventDefault();
var top, left;
return this.imageannotate.drawShape(
function(pointer) {
top = pointer.y;
left = pointer.x;
return new fabric.Group([
new fabric.Line([0, 5, 0, 5], {
strokeWidth: 5,
fill: 'red',
stroke: 'red',
originX: 'center',
originY: 'center',
selectable: false,
hasBorders: false
}),
new fabric.Polygon([
{x: 20, y: 0},
{x: 0, y: -5},
{x: 0, y: 5}
], {
strokeWidth: 0,
fill: 'red',
originX: 'center',
originY: 'center',
selectable: false,
hasBorders: false
})
], {
left: pointer.x,
top: pointer.y,
originX: 'center',
originY: 'center'
});
},
function(group, pointer) {
var dx = pointer.x - left,
dy = pointer.y - top,
angle = Math.atan(dy / dx),
d = Math.sqrt(dx * dx + dy * dy) - 10,
sign = dx < 0 ? -1 : 1,
dy2 = Math.sin(angle) * d * sign;
dx2 = Math.cos(angle) * d * sign,
group.item(0)
.set({ x2: dx2, y2: dy2 });
group.item(1)
.set({
angle: angle * 180 / Math.PI,
flipX: dx < 0,
flipY: dy < 0
})
.setPositionByOrigin(new fabric.Point(dx, dy),
'center', 'center');
},
function(shape, pointer) {
var dx = pointer.x - left,
dy = pointer.y - top,
angle = Math.atan(dy / dx),
d = Math.sqrt(dx * dx + dy * dy);
// Mess with the next two lines and you *will* be sorry!
shape.forEachObject(function(e) { shape.removeWithUpdate(e); });
return new fabric.Path(
'M '+left+' '+top+' l '+(d-20)+' 0 0 -3 15 3 -15 3 0 -3 z', {
angle: angle * 180 / Math.PI + (dx < 0 ? 180 : 0),
stroke: 'red'
});
}
);
},
drawEllipse: function(e) {
e.preventDefault();
return this.imageannotate.drawShape(
function(pointer) {
return new fabric.Ellipse({
top: pointer.y,
left: pointer.x,
strokeWidth: 5,
fill: 'transparent',
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
},
function(circle, pointer, event) {
var x = circle.get('left'), y = circle.get('top'),
dx = pointer.x - x, dy = pointer.y - y,
sw = circle.getStrokeWidth()/2;
// Use SHIFT to draw circles
if (event.shiftKey) {
dy = dx = Math.max(dx, dy);
}
circle.set({
rx: Math.max(0, Math.abs(dx/2) - sw),
ry: Math.max(0, Math.abs(dy/2) - sw),
originX: dx < 0 ? 'right' : 'left',
originY: dy < 0 ? 'bottom' : 'top'});
}
);
},
drawBox: function(e) {
e.preventDefault();
return this.imageannotate.drawShape(
function(pointer) {
return new fabric.Rect({
top: pointer.y,
left: pointer.x,
strokeWidth: 5,
fill: 'transparent',
stroke: 'red',
originX: 'left',
originY: 'top'
});
},
function(rect, pointer, event) {
var x = rect.get('left'), y = rect.get('top'),
dx = pointer.x - x, dy = pointer.y - y;
// Use SHIFT to draw squares
if (event.shiftKey) {
dy = dx = Math.max(dx, dy);
}
rect.set({ width: Math.abs(dx), height: Math.abs(dy),
originX: dx < 0 ? 'right' : 'left',
originY: dy < 0 ? 'bottom' : 'top'});
}
);
},
drawText: function(e) {
e.preventDefault();
return this.imageannotate.drawShape(
function(pointer) {
return new fabric.IText(__('Text'), {
top: pointer.y,
left: pointer.x,
fill: 'red',
originX: 'left',
originY: 'top',
fontFamily: 'sans-serif',
fontSize: 30
});
},
function(rect, pointer, event) {
var x = rect.get('left'), y = rect.get('top'),
dx = pointer.x - x, dy = pointer.y - y;
// Use SHIFT to draw squares
if (event.shiftKey) {
dy = dx = Math.max(dx, dy);
}
rect.set({ width: Math.abs(dx), height: Math.abs(dy),
originX: dx < 0 ? 'right' : 'left',
originY: dy < 0 ? 'bottom' : 'top'});
},
function(shape) {
shape.on('editing:exited', function() {
if (!shape.getText())
shape.remove();
});
// Action buttons
biggerFont: function(e) {
e.preventDefault();
var image_box = $('#redactor-image-box'),
img = image_box.find('img')[0],
fcanvas = $(img).data('canvas');
$.each(fcanvas.getObjects(), function() {
if (this.get('active') && this instanceof fabric.IText) {
if (this.getSelectedText()) {
this.setSelectionStyles({
fontSize: (this.getSelectionStyles().fontSize || this.getFontSize()) + 5
this.setFontSize(this.getFontSize() + 5);
fcanvas.renderAll();
return false;
smallerFont: function(e) {
e.preventDefault();
var image_box = $('#redactor-image-box'),
img = image_box.find('img')[0],
fcanvas = $(img).data('canvas');
$.each(fcanvas.getObjects(), function() {
if (this.get('active') && this instanceof fabric.IText) {
if (this.getSelectedText()) {
this.setSelectionStyles({
fontSize: (this.getSelectionStyles().fontSize || this.getFontSize()) - 5
this.setFontSize(this.getFontSize() - 5);
}
}
});
fcanvas.renderAll();
return false;
},
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
paintStroke: function(e) {
$('#annotate-set-stroke').css({'background-color': 'rgba(255,255,255,0.3)'});
$('#annotate-set-fill').css({'background-color': 'transparent'});
this.imageannotate.paintMode = 'stroke';
return false;
},
paintFill: function(e) {
$('#annotate-set-fill').css({'background-color': 'rgba(255,255,255,0.3)'});
$('#annotate-set-stroke').css({'background-color': 'transparent'});
this.imageannotate.paintMode = 'fill';
return false;
},
setOpacity: function(e) {
e.preventDefault();
var image_box = $('#redactor-image-box'),
img = image_box.find('img')[0],
fcanvas = $(img).data('canvas');
$.each(fcanvas.getObjects(), function() {
if (this.get('active')) {
if (this.getOpacity() != 1)
this.setOpacity(1);
else
this.setOpacity(0.6);
});
fcanvas.renderAll();
return false;
},
bringForward: function(e) {
e.preventDefault();
var image_box = $('#redactor-image-box'),
img = image_box.find('img')[0],
fcanvas = $(img).data('canvas');
$.each(fcanvas.getObjects(), function() {
if (this.get('active')) {
this.bringForward();
});
},
keydown: function(e) {
var image_box = $('#redactor-image-box'),
img = image_box.find('img')[0],
fcanvas = $(img).data('canvas');
if (!fcanvas)
return;
var active = fcanvas.getActiveObject();
// Check if editing a text element
if (active instanceof fabric.IText && active.get('isEditing')) {
// This keystroke is not for redactor
var ss = active.get('selectionStart'),
se = active.get('selectionEnd');
active.exitEditing();
active.enterEditing();
active.set({
'selectionStart': ss,
'selectionEnd': se
});
if (e.type == 'keydown')
active.onKeyDown(e);
else
active.onKeyPress(e);
return false;
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
// Check if [delete] was pressed with selected objects
if (e.keyCode == 8 || e.keyCode == 46)
return this.imageannotate.discard(e);
else if (e.keyCode == 90 && (e.metaKey || e.ctrlKey)) {
fcanvas.loadFromJSON(atob($(img).attr('data-annotations')));
return false;
}
},
discard: function(e) {
var image_box = $('#redactor-image-box', this.$editor),
img = image_box && image_box.find('img')[0],
fcanvas = img && $(img).data('canvas');
if (!fcanvas)
// Not annotating
return;
e.preventDefault();
this.imageannotate.setBuffer();
$.each(fcanvas.getObjects(), function() {
if (this.get('active'))
this.remove();
});
fcanvas.renderAll();
return false;
},
commit: function(e) {
e.preventDefault();
var redactor = this,
image_box = $('#redactor-image-box'),
img = image_box.find('img')[0],
$img = $(img),
fcanvas = $(img).data('canvas');
fcanvas.deactivateAll();
// Upload to server
redactor.buffer.set();
var annotated = fcanvas.toDataURL({
format: 'jpg', quality: 4,
multiplier: 1/fcanvas.getZoom()
}),
file = new Blob([annotated], {type: 'image/jpeg'});
// Fallback to the data URL — show while the image is being uploaded
var origSrc = $img.attr('src');
$img.attr('src', annotated);
var origCallback = redactor.opts.imageUploadCallback,
origErrorCbk = redactor.opts.imageUploadErrorCallback;
// After successful upload, replace the old image with the new one.
// Transfer the annotation state to the new image for replay.
redactor.opts.imageUploadCallback = function(image, json) {
redactor.opts.imageUploadCallback = origCallback;
redactor.opts.imageUploadErrorCallback = origErrorCbk;
// Transfer the annotation JSON data and drop the original image.
image.attr('data-annotations', $img.attr('data-annotations'));
// Record the image that was originally annotated. If the committed
// image is annotated again, it should be the original image with
// the annotations placed live on the original image. The image
// being committed here will be discarded.
image.attr('data-orig-annotated-image-src',
$img.attr('data-orig-annotated-image-src') || origSrc
);
$img.remove();
// Redactor will add <br> before and after the image in linebreaks
// mode
var N = image.next();
if (N.is('br')) N.remove();
var P = image.prev();
if (N.is('br')) P.remove();
};
// Handle upload issues
redactor.opts.imageUploadErrorCallback = function(json) {
redactor.opts.imageUploadCallback = origCallback;
redactor.opts.imageUploadErrorCallback = origErrorCbk;
$img.show();
};
redactor.imageannotate.teardownAnnotate(image_box);
$img.css({opacity: 0.5});
redactor.upload.directUpload(file, e);
return false;
},
// Utils
resizeShape: function(o) {
var shape = o.target;
if (shape instanceof fabric.Ellipse) {
shape.set({
rx: shape.get('rx') * shape.get('scaleX'),
ry: shape.get('ry') * shape.get('scaleY'),
scaleX: 1,
scaleY: 1
});
}
else if (shape instanceof fabric.Rect) {
shape.set({
width: shape.get('width') * shape.get('scaleX'),
height: shape.get('height') * shape.get('scaleY'),
scaleX: 1,
scaleY: 1
});
}
},
setBuffer: function() {
var image_box = $('#redactor-image-box'),
img = image_box.find('img')[0],
$img = $(img),
fcanvas = $img.data('canvas'),
state = fcanvas.toObject();
// Capture current annotations
delete state.backgroundImage;
$img.attr('data-annotations', btoa(JSON.stringify(state)));
},
// Startup
initCanvas: function(img) {
var self = this,
plugin = this.imageannotate,
$img = $(img);
if ($img.data('canvas'))
return;
var box = $img.parent(),
canvas = $('<canvas>').css({
position: 'absolute',
top: 0, bottom: 0, left: 0, right: 0,
width: '100%', height: '100%'
}).appendTo(box),
fcanvas = new fabric.Canvas(canvas[0], {
backgroundColor: 'rgba(0,0,0,0,0)',
containerClass: 'no-margin',
includeDefaultValues: false,
}),
previous = $(img).attr('data-annotations');
// Catch [delete] key and map to delete object
self.opts.keydownCallback = plugin.keydown.bind(self);
self.opts.keyupCallback = plugin.keydown.bind(self);
var I = new Image(), scale;
I.src = $img.attr('src');
// Use a maximum zoom-out of 0.7, so that very large pictures do not
// result in unusually small annotations (esp. stroke widths which are
// not adjustable).
scale = Math.max(0.7, $img.width() / I.width);
var scaleWidth = $img.width() / scale,
scaleHeight = $img.height() / scale;
fcanvas
.setDimensions({width: $img.width(), height: $img.height()})
.setBackgroundImage(
$img.attr('data-orig-annotated-image-src') || $img.attr('src'),
fcanvas.renderAll.bind(fcanvas), {
width: scaleWidth,
height: scaleHeight,
// Needed to position overlayImage at 0/0
originX: 'left',
originY: 'top'
})
.on('object:scaling', plugin.resizeShape.bind(self));
if (previous) {
fcanvas.loadFromJSON(atob(previous));
fcanvas.forEachObject(function(o) {
o.set({
transparentCorners: false,
borderColor: 'rgba(102,153,255,0.9)',
cornerColor: 'rgba(102,153,255,0.5)',
cornerSize: 10
});
});
}
$img.data('canvas', fcanvas).addClass('hidden');
return fcanvas;
RedactorPlugins.contexttypeahead = function() {
return {
typeahead: false,
context: false,
init: function() {
if (!this.$element.data('rootContext'))
return;
this.opts.keyupCallback = this.contexttypeahead.watch.bind(this);
this.opts.keydownCallback = this.contexttypeahead.watch.bind(this);
this.$editor.on('click', this.contexttypeahead.watch.bind(this));
},
watch: function(e) {
var current = this.selection.getCurrent(),
allText = this.$editor.text(),
offset = this.caret.getOffset(),
lhs = allText.substring(0, offset),
search = new RegExp(/%\{([^}]*)$/),
match;
if (!lhs) {
return !e.isDefaultPrevented();
}
if (e.which == 27 || !(match = search.exec(lhs)))
// No longer in a element — close typeahead
return this.contexttypeahead.destroy();
if (e.type == 'click')
return;
// Locate the position of the cursor and the number of characters back
// to the `%{` symbols
var sel = this.selection.get(),
range = this.sel.getRangeAt(0),
content = current.textContent,
clientRects = range.getClientRects(),
position = clientRects[0],
backText = match[1],
parent = this.selection.getParent() || this.$editor,
plugin = this.contexttypeahead;
// Insert a hidden text input to receive the typed text and add a
// typeahead widget
if (!this.contexttypeahead.typeahead) {
this.contexttypeahead.typeahead = $('<input type="text">')
.css({position: 'absolute', visibility: 'hidden'})
.width(0).height(position.height - 4)
.appendTo(document.body)
.typeahead({
property: 'variable',
minLength: 0,
arrow: $('<span class="pull-right"><i class="icon-muted icon-chevron-right"></i></span>')
.css('padding', '0 0 0 6px'),
highlighter: function(variable, item) {
var base = $.fn.typeahead.Constructor.prototype.highlighter
.call(this, variable),
further = new RegExp(variable + '\\.'),
extendable = Object.keys(plugin.variables).some(function(v) {
return v.match(further);
}),
arrow = extendable ? this.options.arrow.clone() : '';
return $('<div/>').html(base).prepend(arrow).html()
+ $('<span class="faded">')
.text(' — ' + item.desc)
.wrap('<div>').parent().html();
item: '<li><a href="#" style="display:block"></a></li>',
source: this.contexttypeahead.getContext.bind(this),
sorter: function(items) {
items.sort(
function(a,b) {return a.variable > b.variable ? 1 : -1;}
);
return items;
},
matcher: function(item) {
if (item.toLowerCase().indexOf(this.query.toLowerCase()) !== 0)
return false;
return (this.query.match(/\./g) || []).length == (item.match(/\./g) || []).length;
},
onselect: this.contexttypeahead.select.bind(this),
scroll: true,
items: 100
if (position) {
var width = plugin.textWidth(
backText,
this.selection.getParent() || $('<div class="redactor-editor">')
),
pleft = $(parent).offset().left,
left = position.left - width;
if (left < pleft)
// This is a bug in chrome, but I'm not sure how to adjust it
left += pleft;
plugin.typeahead
.css({top: position.top + $(window).scrollTop(), left: left});
}
plugin.typeahead
return !e.isDefaultPrevented();
},
getContext: function(typeahead, query) {
var dfd, that=this.contexttypeahead,
root = this.$element.data('rootContext');
if (!this.contexttypeahead.context) {
dfd = $.Deferred();
$.ajax('ajax.php/content/context', {
data: {root: root},
success: function(json) {
var items = $.map(json, function(v,k) {
return {variable: k, desc: v};
});
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
dfd.resolve(items);
}
});
this.contexttypeahead.context = dfd;
}
// Only fetch the context once for this redactor box
this.contexttypeahead.context.then(function(items) {
typeahead.process(items);
});
},
textWidth: function(text, clone) {
var c = $(clone),
o = c.clone().text(text)
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden'})
.css({'font-family': c.css('font-family'), 'font-weight': c.css('font-weight'),
'font-size': c.css('font-size')})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
},
destroy: function() {
if (this.contexttypeahead.typeahead) {
this.contexttypeahead.typeahead.typeahead('hide');
this.contexttypeahead.typeahead.remove();
this.contexttypeahead.typeahead = false;
}
},
select: function(item, event) {
// Collapse multiple textNodes together
(this.selection.getBlock() || this.$editor.get(0)).normalize();
var current = this.selection.getCurrent(),
sel = this.selection.get(),
range = this.sel.getRangeAt(0),
cursorAt = range.endOffset,
// TODO: Consume immediately following `}` symbols
plugin = this.contexttypeahead,
search = new RegExp(/%\{([^}]*)(\}?)$/);
// FIXME: ENTER will end up here, but current will be empty