slides_image.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. /*
  2. ArozOS Office - Slides picture tools
  3. ====================================
  4. Everything that acts on a selected picture, kept out of slides.js so
  5. that file stays about the document and the canvas:
  6. - the floating picture bar, the same shape as the text-edit bar but
  7. anchored to a selected image: crop, reset, format options
  8. - the shape grid: the crop shapes drawn as icons rather than listed
  9. as names, shared by the bar and the toolbar's crop button
  10. - the format panel: a docked side panel for size, position, rotation,
  11. alignment, re-colour and the brightness / contrast / transparency
  12. adjustments
  13. slides.js owns the document, so this module never touches the model
  14. directly - it asks through the host object passed to init():
  15. SlidesImageTools.init({
  16. getImage: fn -> the lone selected image object, or null,
  17. objEl: fn(id) -> its DOM element,
  18. commit: fn, // model changed, redraw + undo
  19. startCrop: fn(id), endCrop: fn(apply), isCropping: fn -> bool,
  20. resetImage: fn(obj), setMask: fn(obj, kind),
  21. shapeKinds: [{kind,label}],
  22. slideSize: [w,h], relayout: fn
  23. });
  24. and the host drives it with sync() / hide() / reposition().
  25. */
  26. var SlidesImageTools = (function () {
  27. "use strict";
  28. var host = null;
  29. var $bar = null;
  30. var $panel = null;
  31. var barObjId = null;
  32. /* Re-colour presets. Each is a CSS filter chain, and the swatches in
  33. the panel show the picture itself through that filter, so what is
  34. previewed is exactly what is applied. The tint recipe (grayscale,
  35. then sepia as a colour base, then rotate the hue) is the standard
  36. way to wash an arbitrary photo into one hue with plain CSS. */
  37. var RECOLORS = [
  38. { key: "", label: "No recolour", filter: "" },
  39. { key: "gray", label: "Greyscale", filter: "grayscale(1)" },
  40. { key: "sepia", label: "Sepia", filter: "sepia(1)" },
  41. { key: "washout", label: "Washed out", filter: "grayscale(0.4) brightness(1.35) contrast(0.7)" },
  42. { key: "blue-light", label: "Light blue", filter: tint(210, 0.55, 1.25) },
  43. { key: "blue-dark", label: "Dark blue", filter: tint(215, 1.1, 0.7) },
  44. { key: "teal", label: "Teal", filter: tint(175, 1.0, 0.95) },
  45. { key: "green", label: "Green", filter: tint(105, 0.95, 0.95) },
  46. { key: "lime", label: "Lime", filter: tint(75, 1.3, 1.15) },
  47. { key: "yellow", label: "Yellow", filter: tint(45, 1.4, 1.15) },
  48. { key: "orange", label: "Orange", filter: tint(15, 1.3, 1.0) },
  49. { key: "red", label: "Red", filter: tint(345, 1.2, 0.9) },
  50. { key: "purple", label: "Purple", filter: tint(265, 0.9, 0.9) },
  51. { key: "pink", label: "Pink", filter: tint(315, 0.9, 1.15) },
  52. { key: "black-white", label: "Black and white", filter: "grayscale(1) contrast(2.6) brightness(1.05)" },
  53. { key: "negative", label: "Negative", filter: "invert(1)" }
  54. ];
  55. // hue is where the wash lands, sat how strong it is, bright how light
  56. function tint(hue, sat, bright) {
  57. return "grayscale(1) sepia(1) hue-rotate(" + (hue - 40) + "deg) " +
  58. "saturate(" + sat + ") brightness(" + bright + ")";
  59. }
  60. function recolorByKey(key) {
  61. for (var i = 0; i < RECOLORS.length; i++) {
  62. if (RECOLORS[i].key === (key || "")) return RECOLORS[i];
  63. }
  64. return RECOLORS[0];
  65. }
  66. /* imageFilter is the single place that turns a picture's re-colour and
  67. adjustments into CSS, so the canvas, the thumbnails, present mode and
  68. the panel's own swatches all agree. Exported for slides.js to use
  69. while rendering. */
  70. function imageFilter(p) {
  71. var parts = [];
  72. var rc = recolorByKey(p.recolor);
  73. if (rc.filter) parts.push(rc.filter);
  74. var b = Number(p.bright) || 0;
  75. var c = Number(p.contrast) || 0;
  76. if (b) parts.push("brightness(" + (1 + clamp(b, -0.9, 2)) + ")");
  77. if (c) parts.push("contrast(" + (1 + clamp(c, -0.9, 2)) + ")");
  78. return parts.join(" ");
  79. }
  80. function clamp(v, a, b) { return Math.max(a, Math.min(b, v)); }
  81. function esc(t) { return OfficeApp.escapeHtml(t); }
  82. function num(v, d) { var n = Number(v); return isFinite(n) ? n : d; }
  83. /* ================= shape grid ================= */
  84. // shapeIcon draws one crop shape as a small outline. The catalogue draws
  85. // it, from the very same geometry the canvas uses, so the icon cannot
  86. // drift from the mask it stands for.
  87. function shapeIcon(kind, size) {
  88. return SlidesShapes.icon(kind || "rect", size || 22);
  89. }
  90. /* showShapeMenu opens the crop-shape picker under an element. The
  91. shapes are icons in a grid rather than a list of names, because the
  92. outline is the thing being chosen. */
  93. function showShapeMenu(anchorEl) {
  94. closeShapeMenu();
  95. if (!host) return;
  96. var o = host.getImage();
  97. if (!o) return;
  98. var $m = $('<div class="sl-shapegrid of-noprint"></div>');
  99. var $none = $('<button type="button" class="sl-shapegrid-none"></button>')
  100. .append($(shapeIcon("rect")))
  101. .append($("<span></span>").text("No shape (rectangle)"));
  102. if (!o.props.mask) $none.addClass("active");
  103. $none.on("click", function () { closeShapeMenu(); host.setMask(o, ""); });
  104. $m.append($none);
  105. var $grid = $('<div class="sl-shapegrid-cells"></div>');
  106. host.shapeKinds.forEach(function (s) {
  107. if (s.kind === "rect") return;
  108. var $b = $('<button type="button" class="sl-shapegrid-cell"></button>')
  109. .attr("title", s.label)
  110. .html(shapeIcon(s.kind));
  111. if (o.props.mask === s.kind) $b.addClass("active");
  112. $b.on("click", function () { closeShapeMenu(); host.setMask(o, s.kind); });
  113. $grid.append($b);
  114. });
  115. $m.append($grid);
  116. $("body").append($m);
  117. var r = anchorEl.getBoundingClientRect();
  118. var w = $m.outerWidth(), h = $m.outerHeight();
  119. var x = Math.min(r.left, window.innerWidth - w - 6);
  120. var y = r.bottom + 4;
  121. if (y + h > window.innerHeight - 6) y = Math.max(6, r.top - h - 4);
  122. $m.css({ left: Math.max(6, x) + "px", top: y + "px" });
  123. setTimeout(function () {
  124. $(document).on("mousedown.slshapegrid", function (e) {
  125. if (!$m[0].contains(e.target)) closeShapeMenu();
  126. });
  127. }, 0);
  128. }
  129. function closeShapeMenu() {
  130. $(".sl-shapegrid").remove();
  131. $(document).off("mousedown.slshapegrid");
  132. }
  133. /* ================= floating picture bar ================= */
  134. function barBtn(icon, title, fn) {
  135. var $b = $('<button type="button" class="of-te-btn" title="' + esc(title) + '">' +
  136. '<i class="' + icon + ' icon"></i></button>');
  137. $b.on("mousedown", function (e) { e.preventDefault(); });
  138. $b.on("click", fn);
  139. return $b;
  140. }
  141. function buildBar() {
  142. $bar = $('<div class="of-textedit-bar sl-imagebar of-noprint"></div>');
  143. var $row = $('<div class="of-te-row"></div>');
  144. $bar.append($row);
  145. // crop and the crop shapes are one control: the button crops, the
  146. // caret beside it picks the shape to crop to
  147. var $crop = barBtn("crop", "Crop image", function () {
  148. var o = host.getImage();
  149. if (!o) return;
  150. if (host.isCropping()) host.endCrop(true); else host.startCrop(o.id);
  151. });
  152. $crop.addClass("sl-imagebar-crop");
  153. $row.append($crop);
  154. var $caret = barBtn("caret down", "Crop to shape", function (e) {
  155. showShapeMenu(e.currentTarget);
  156. });
  157. $caret.addClass("sl-imagebar-caret");
  158. $row.append($caret);
  159. $row.append(barBtn("history", "Reset image (clear crop, shape and colour)", function () {
  160. var o = host.getImage();
  161. if (o) host.resetImage(o);
  162. }));
  163. $row.append('<div class="of-te-sep"></div>');
  164. var $fmt = barBtn("sliders horizontal", "Format options", function () {
  165. togglePanel();
  166. });
  167. $fmt.addClass("sl-imagebar-fmt");
  168. $row.append($fmt);
  169. $("body").append($bar);
  170. }
  171. function syncBarState() {
  172. if (!$bar) return;
  173. $bar.find(".sl-imagebar-crop").toggleClass("active", !!host.isCropping());
  174. $bar.find(".sl-imagebar-fmt").toggleClass("active", !!$panel);
  175. }
  176. function reposition() {
  177. if (!$bar || !host) return;
  178. var o = host.getImage();
  179. var el = o ? host.objEl(o.id) : null;
  180. if (!el) { hideBar(); return; }
  181. var r = el.getBoundingClientRect();
  182. var w = $bar.outerWidth(), h = $bar.outerHeight();
  183. var x = r.left + (r.width - w) / 2;
  184. // below the picture by default, like the reference: the space above
  185. // is usually where the slide's own content is
  186. var y = r.bottom + 8;
  187. if (y + h > window.innerHeight - 4) y = Math.max(4, r.top - h - 8);
  188. if (x + w > window.innerWidth - 4) x = window.innerWidth - w - 4;
  189. if (x < 4) x = 4;
  190. $bar.css({ left: x + "px", top: y + "px" });
  191. }
  192. function hideBar() {
  193. if ($bar) { $bar.remove(); $bar = null; }
  194. barObjId = null;
  195. closeShapeMenu();
  196. }
  197. /* sync is called whenever the selection or the document changes: it
  198. shows the bar for a lone picture and takes it away otherwise */
  199. function sync() {
  200. if (!host) return;
  201. var o = host.getImage();
  202. if (!o) {
  203. hideBar();
  204. if ($panel) renderPanel();
  205. return;
  206. }
  207. if (!$bar) buildBar();
  208. barObjId = o.id;
  209. syncBarState();
  210. reposition();
  211. if ($panel) renderPanel();
  212. }
  213. /* ================= format panel ================= */
  214. function togglePanel() {
  215. if (!host) return;
  216. if ($panel) closePanel(); else openPanel();
  217. }
  218. function openPanel() {
  219. if ($panel) return;
  220. $panel = $('<div id="slFormatPanel" class="of-noprint"></div>');
  221. $("#slMain").after($panel);
  222. renderPanel();
  223. syncBarState();
  224. if (host.relayout) host.relayout();
  225. }
  226. function closePanel() {
  227. if (!$panel) return;
  228. $panel.remove();
  229. $panel = null;
  230. syncBarState();
  231. if (host.relayout) host.relayout();
  232. }
  233. function section(title, key, $body) {
  234. var open = OfficeApp.getSetting("fmtSection." + key, true);
  235. var $s = $('<div class="sl-fp-section"></div>').toggleClass("closed", !open);
  236. var $h = $('<div class="sl-fp-head"><i class="chevron down icon"></i><span></span></div>');
  237. $h.find("span").text(title);
  238. $h.on("click", function () {
  239. var nowClosed = $s.toggleClass("closed").hasClass("closed");
  240. OfficeApp.setSetting("fmtSection." + key, !nowClosed);
  241. });
  242. return $s.append($h).append($('<div class="sl-fp-body"></div>').append($body));
  243. }
  244. // numField builds a labelled number input that writes straight through
  245. // to the model, committing on change
  246. function numField(label, unit, get, set, opts) {
  247. opts = opts || {};
  248. var $w = $('<div class="sl-fp-field"></div>');
  249. $w.append($("<label></label>").text(label));
  250. var $row = $('<div class="sl-fp-inputrow"></div>');
  251. var $i = $('<input type="number" class="sl-fp-num">')
  252. .attr("step", opts.step || 1).val(get());
  253. if (opts.min !== undefined) $i.attr("min", opts.min);
  254. if (opts.max !== undefined) $i.attr("max", opts.max);
  255. $i.on("change", function () { set(num($i.val(), get())); });
  256. $row.append($i);
  257. if (unit) $row.append($('<span class="sl-fp-unit"></span>').text(unit));
  258. return $w.append($row);
  259. }
  260. function slider(label, get, set) {
  261. var $w = $('<div class="sl-fp-field"></div>');
  262. var $lab = $("<label></label>").text(label);
  263. $w.append($lab);
  264. var $i = $('<input type="range" class="sl-fp-range" min="-90" max="100" step="1">')
  265. .val(Math.round(get() * 100));
  266. var $val = $('<span class="sl-fp-unit"></span>').text(Math.round(get() * 100) + "%");
  267. $i.on("input", function () { $val.text($i.val() + "%"); });
  268. $i.on("change", function () { set(num($i.val(), 0) / 100); });
  269. return $w.append($('<div class="sl-fp-inputrow"></div>').append($i).append($val));
  270. }
  271. function renderPanel() {
  272. if (!$panel || !host) return;
  273. $panel.empty();
  274. var $head = $('<div class="sl-fp-title"><i class="sliders horizontal icon"></i>' +
  275. "<span>Format options</span></div>");
  276. $head.append($('<button type="button" class="sl-fp-close" title="Close">' +
  277. '<i class="times icon"></i></button>').on("click", closePanel));
  278. $panel.append($head);
  279. var o = host.getImage();
  280. if (!o) {
  281. $panel.append('<div class="sl-fp-empty">Select a picture to see its ' +
  282. "format options.</div>");
  283. return;
  284. }
  285. var p = o.props;
  286. // commit() calls back into sync(), which re-renders this panel,
  287. // so reading the fresh values back is not this function's job
  288. var apply = function () { host.commit(); };
  289. /* ---- size and rotation ---- */
  290. var $size = $("<div></div>");
  291. var $grid = $('<div class="sl-fp-grid"></div>');
  292. $grid.append(numField("Width", "px", function () { return Math.round(o.w); },
  293. function (v) {
  294. v = Math.max(4, v);
  295. if (p.lockAspect && o.w > 0) o.h = Math.max(4, o.h * v / o.w);
  296. o.w = v;
  297. apply();
  298. }));
  299. $grid.append(numField("Height", "px", function () { return Math.round(o.h); },
  300. function (v) {
  301. v = Math.max(4, v);
  302. if (p.lockAspect && o.h > 0) o.w = Math.max(4, o.w * v / o.h);
  303. o.h = v;
  304. apply();
  305. }));
  306. $size.append($grid);
  307. var $lock = $('<label class="sl-fp-check"><input type="checkbox"> ' +
  308. "<span>Lock aspect ratio</span></label>");
  309. $lock.find("input").prop("checked", !!p.lockAspect).on("change", function () {
  310. p.lockAspect = this.checked;
  311. if (!p.lockAspect) delete p.lockAspect;
  312. host.commit();
  313. });
  314. $size.append($lock);
  315. var $rot = $('<div class="sl-fp-grid"></div>');
  316. $rot.append(numField("Angle", "deg", function () { return Math.round(o.rot || 0); },
  317. function (v) { o.rot = ((v % 360) + 360) % 360; apply(); }, { min: 0, max: 359 }));
  318. var $flips = $('<div class="sl-fp-field"><label>Rotate / flip</label></div>');
  319. var $frow = $('<div class="sl-fp-inputrow"></div>');
  320. $frow.append(iconBtn("redo", "Rotate 90 degrees", function () {
  321. o.rot = (((o.rot || 0) + 90) % 360); apply();
  322. }));
  323. $frow.append(iconBtn("arrows alternate horizontal", "Flip horizontally", function () {
  324. p.flipH = !p.flipH; if (!p.flipH) delete p.flipH; apply();
  325. }, !!p.flipH));
  326. $frow.append(iconBtn("arrows alternate vertical", "Flip vertically", function () {
  327. p.flipV = !p.flipV; if (!p.flipV) delete p.flipV; apply();
  328. }, !!p.flipV));
  329. $rot.append($flips.append($frow));
  330. $size.append($rot);
  331. $panel.append(section("Size and rotation", "size", $size));
  332. /* ---- position and alignment ---- */
  333. var $pos = $("<div></div>");
  334. var $pgrid = $('<div class="sl-fp-grid"></div>');
  335. $pgrid.append(numField("X", "px", function () { return Math.round(o.x); },
  336. function (v) { o.x = v; apply(); }));
  337. $pgrid.append(numField("Y", "px", function () { return Math.round(o.y); },
  338. function (v) { o.y = v; apply(); }));
  339. $pos.append($pgrid);
  340. var $al = $('<div class="sl-fp-field"><label>Align to slide</label></div>');
  341. var $arow = $('<div class="sl-fp-inputrow"></div>');
  342. [["align left", "Left", function () { o.x = 0; }],
  343. ["align center", "Centre", function () { o.x = (host.slideSize[0] - o.w) / 2; }],
  344. ["align right", "Right", function () { o.x = host.slideSize[0] - o.w; }],
  345. ["angle up", "Top", function () { o.y = 0; }],
  346. ["minus", "Middle", function () { o.y = (host.slideSize[1] - o.h) / 2; }],
  347. ["angle down", "Bottom", function () { o.y = host.slideSize[1] - o.h; }]
  348. ].forEach(function (a) {
  349. $arow.append(iconBtn(a[0], a[1], function () { a[2](); apply(); }));
  350. });
  351. $pos.append($al.append($arow));
  352. $panel.append(section("Position", "pos", $pos));
  353. /* ---- re-colour ---- */
  354. var $rc = $('<div class="sl-fp-swatches"></div>');
  355. RECOLORS.forEach(function (r) {
  356. var $b = $('<button type="button" class="sl-fp-swatch"></button>').attr("title", r.label);
  357. $b.append($('<img alt="">').attr("src", p.src || "").css("filter", r.filter || "none"));
  358. $b.append($("<span></span>").text(r.label));
  359. if ((p.recolor || "") === r.key) $b.addClass("active");
  360. $b.on("click", function () {
  361. if (r.key) p.recolor = r.key; else delete p.recolor;
  362. apply();
  363. });
  364. $rc.append($b);
  365. });
  366. $panel.append(section("Re-colour", "recolor", $rc));
  367. /* ---- adjustments ---- */
  368. var $adj = $("<div></div>");
  369. $adj.append(slider("Transparency", function () {
  370. return p.opacity ? 1 - clamp(Number(p.opacity), 0, 1) : 0;
  371. }, function (v) {
  372. v = clamp(v, 0, 1);
  373. if (v <= 0.001) delete p.opacity; else p.opacity = Math.round((1 - v) * 1000) / 1000;
  374. apply();
  375. }));
  376. $adj.append(slider("Brightness", function () { return Number(p.bright) || 0; },
  377. function (v) {
  378. if (Math.abs(v) < 0.005) delete p.bright; else p.bright = v;
  379. apply();
  380. }));
  381. $adj.append(slider("Contrast", function () { return Number(p.contrast) || 0; },
  382. function (v) {
  383. if (Math.abs(v) < 0.005) delete p.contrast; else p.contrast = v;
  384. apply();
  385. }));
  386. $panel.append(section("Adjustments", "adjust", $adj));
  387. }
  388. function iconBtn(icon, title, fn, active) {
  389. var $b = $('<button type="button" class="sl-fp-iconbtn" title="' + esc(title) + '">' +
  390. '<i class="' + icon + ' icon"></i></button>');
  391. if (active) $b.addClass("active");
  392. $b.on("click", fn);
  393. return $b;
  394. }
  395. /* ================= public ================= */
  396. function init(h) {
  397. host = h;
  398. $(window).on("resize.slimagebar", function () { reposition(); });
  399. }
  400. return {
  401. init: init,
  402. sync: sync,
  403. hide: function () { hideBar(); closeShapeMenu(); },
  404. reposition: reposition,
  405. syncState: syncBarState,
  406. togglePanel: togglePanel,
  407. panelOpen: function () { return !!$panel; },
  408. showShapeMenu: showShapeMenu,
  409. shapeIcon: shapeIcon,
  410. imageFilter: imageFilter,
  411. recolorFilter: function (key) { return recolorByKey(key).filter; },
  412. recolors: RECOLORS
  413. };
  414. })();