tools.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
  27. exports.bindEvents = bindEvents;
  28. exports.opacityToHex = opacityToHex;
  29. var _util = require("../../shared/util.js");
  30. var _display_utils = require("../display_utils.js");
  31. function bindEvents(obj, element, names) {
  32. for (const name of names) {
  33. element.addEventListener(name, obj[name].bind(obj));
  34. }
  35. }
  36. function opacityToHex(opacity) {
  37. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  38. }
  39. class IdManager {
  40. #id = 0;
  41. getId() {
  42. return `${_util.AnnotationEditorPrefix}${this.#id++}`;
  43. }
  44. }
  45. class CommandManager {
  46. #commands = [];
  47. #locked = false;
  48. #maxSize;
  49. #position = -1;
  50. constructor(maxSize = 128) {
  51. this.#maxSize = maxSize;
  52. }
  53. add({
  54. cmd,
  55. undo,
  56. mustExec,
  57. type = NaN,
  58. overwriteIfSameType = false,
  59. keepUndo = false
  60. }) {
  61. if (mustExec) {
  62. cmd();
  63. }
  64. if (this.#locked) {
  65. return;
  66. }
  67. const save = {
  68. cmd,
  69. undo,
  70. type
  71. };
  72. if (this.#position === -1) {
  73. if (this.#commands.length > 0) {
  74. this.#commands.length = 0;
  75. }
  76. this.#position = 0;
  77. this.#commands.push(save);
  78. return;
  79. }
  80. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  81. if (keepUndo) {
  82. save.undo = this.#commands[this.#position].undo;
  83. }
  84. this.#commands[this.#position] = save;
  85. return;
  86. }
  87. const next = this.#position + 1;
  88. if (next === this.#maxSize) {
  89. this.#commands.splice(0, 1);
  90. } else {
  91. this.#position = next;
  92. if (next < this.#commands.length) {
  93. this.#commands.splice(next);
  94. }
  95. }
  96. this.#commands.push(save);
  97. }
  98. undo() {
  99. if (this.#position === -1) {
  100. return;
  101. }
  102. this.#locked = true;
  103. this.#commands[this.#position].undo();
  104. this.#locked = false;
  105. this.#position -= 1;
  106. }
  107. redo() {
  108. if (this.#position < this.#commands.length - 1) {
  109. this.#position += 1;
  110. this.#locked = true;
  111. this.#commands[this.#position].cmd();
  112. this.#locked = false;
  113. }
  114. }
  115. hasSomethingToUndo() {
  116. return this.#position !== -1;
  117. }
  118. hasSomethingToRedo() {
  119. return this.#position < this.#commands.length - 1;
  120. }
  121. destroy() {
  122. this.#commands = null;
  123. }
  124. }
  125. exports.CommandManager = CommandManager;
  126. class KeyboardManager {
  127. constructor(callbacks) {
  128. this.buffer = [];
  129. this.callbacks = new Map();
  130. this.allKeys = new Set();
  131. const isMac = KeyboardManager.platform.isMac;
  132. for (const [keys, callback] of callbacks) {
  133. for (const key of keys) {
  134. const isMacKey = key.startsWith("mac+");
  135. if (isMac && isMacKey) {
  136. this.callbacks.set(key.slice(4), callback);
  137. this.allKeys.add(key.split("+").at(-1));
  138. } else if (!isMac && !isMacKey) {
  139. this.callbacks.set(key, callback);
  140. this.allKeys.add(key.split("+").at(-1));
  141. }
  142. }
  143. }
  144. }
  145. static get platform() {
  146. const platform = typeof navigator !== "undefined" ? navigator.platform : "";
  147. return (0, _util.shadow)(this, "platform", {
  148. isWin: platform.includes("Win"),
  149. isMac: platform.includes("Mac")
  150. });
  151. }
  152. #serialize(event) {
  153. if (event.altKey) {
  154. this.buffer.push("alt");
  155. }
  156. if (event.ctrlKey) {
  157. this.buffer.push("ctrl");
  158. }
  159. if (event.metaKey) {
  160. this.buffer.push("meta");
  161. }
  162. if (event.shiftKey) {
  163. this.buffer.push("shift");
  164. }
  165. this.buffer.push(event.key);
  166. const str = this.buffer.join("+");
  167. this.buffer.length = 0;
  168. return str;
  169. }
  170. exec(self, event) {
  171. if (!this.allKeys.has(event.key)) {
  172. return;
  173. }
  174. const callback = this.callbacks.get(this.#serialize(event));
  175. if (!callback) {
  176. return;
  177. }
  178. callback.bind(self)();
  179. event.stopPropagation();
  180. event.preventDefault();
  181. }
  182. }
  183. exports.KeyboardManager = KeyboardManager;
  184. class ClipboardManager {
  185. #elements = null;
  186. copy(element) {
  187. if (!element) {
  188. return;
  189. }
  190. if (Array.isArray(element)) {
  191. this.#elements = element.map(el => el.serialize());
  192. } else {
  193. this.#elements = [element.serialize()];
  194. }
  195. this.#elements = this.#elements.filter(el => !!el);
  196. if (this.#elements.length === 0) {
  197. this.#elements = null;
  198. }
  199. }
  200. paste() {
  201. return this.#elements;
  202. }
  203. isEmpty() {
  204. return this.#elements === null;
  205. }
  206. destroy() {
  207. this.#elements = null;
  208. }
  209. }
  210. class ColorManager {
  211. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  212. get _colors() {
  213. if (typeof document === "undefined") {
  214. return (0, _util.shadow)(this, "_colors", ColorManager._colorsMapping);
  215. }
  216. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  217. (0, _display_utils.getColorValues)(colors);
  218. return (0, _util.shadow)(this, "_colors", colors);
  219. }
  220. convert(color) {
  221. const rgb = (0, _display_utils.getRGB)(color);
  222. if (!window.matchMedia("(forced-colors: active)").matches) {
  223. return rgb;
  224. }
  225. for (const [name, RGB] of this._colors) {
  226. if (RGB.every((x, i) => x === rgb[i])) {
  227. return ColorManager._colorsMapping.get(name);
  228. }
  229. }
  230. return rgb;
  231. }
  232. getHexCode(name) {
  233. const rgb = this._colors.get(name);
  234. if (!rgb) {
  235. return name;
  236. }
  237. return _util.Util.makeHexColor(...rgb);
  238. }
  239. }
  240. exports.ColorManager = ColorManager;
  241. class AnnotationEditorUIManager {
  242. #activeEditor = null;
  243. #allEditors = new Map();
  244. #allLayers = new Map();
  245. #clipboardManager = new ClipboardManager();
  246. #commandManager = new CommandManager();
  247. #currentPageIndex = 0;
  248. #editorTypes = null;
  249. #eventBus = null;
  250. #idManager = new IdManager();
  251. #isEnabled = false;
  252. #mode = _util.AnnotationEditorType.NONE;
  253. #selectedEditors = new Set();
  254. #boundKeydown = this.keydown.bind(this);
  255. #boundOnEditingAction = this.onEditingAction.bind(this);
  256. #boundOnPageChanging = this.onPageChanging.bind(this);
  257. #previousStates = {
  258. isEditing: false,
  259. isEmpty: true,
  260. hasEmptyClipboard: true,
  261. hasSomethingToUndo: false,
  262. hasSomethingToRedo: false,
  263. hasSelectedEditor: false
  264. };
  265. #container = null;
  266. static _keyboardManager = new KeyboardManager([[["ctrl+a", "mac+meta+a"], AnnotationEditorUIManager.prototype.selectAll], [["ctrl+c", "mac+meta+c"], AnnotationEditorUIManager.prototype.copy], [["ctrl+v", "mac+meta+v"], AnnotationEditorUIManager.prototype.paste], [["ctrl+x", "mac+meta+x"], AnnotationEditorUIManager.prototype.cut], [["ctrl+z", "mac+meta+z"], AnnotationEditorUIManager.prototype.undo], [["ctrl+y", "ctrl+shift+Z", "mac+meta+shift+Z"], AnnotationEditorUIManager.prototype.redo], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete"], AnnotationEditorUIManager.prototype.delete], [["Escape", "mac+Escape"], AnnotationEditorUIManager.prototype.unselectAll]]);
  267. constructor(container, eventBus) {
  268. this.#container = container;
  269. this.#eventBus = eventBus;
  270. this.#eventBus._on("editingaction", this.#boundOnEditingAction);
  271. this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
  272. }
  273. destroy() {
  274. this.#removeKeyboardManager();
  275. this.#eventBus._off("editingaction", this.#boundOnEditingAction);
  276. this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
  277. for (const layer of this.#allLayers.values()) {
  278. layer.destroy();
  279. }
  280. this.#allLayers.clear();
  281. this.#allEditors.clear();
  282. this.#activeEditor = null;
  283. this.#selectedEditors.clear();
  284. this.#clipboardManager.destroy();
  285. this.#commandManager.destroy();
  286. }
  287. onPageChanging({
  288. pageNumber
  289. }) {
  290. this.#currentPageIndex = pageNumber - 1;
  291. }
  292. focusMainContainer() {
  293. this.#container.focus();
  294. }
  295. #addKeyboardManager() {
  296. this.#container.addEventListener("keydown", this.#boundKeydown);
  297. }
  298. #removeKeyboardManager() {
  299. this.#container.removeEventListener("keydown", this.#boundKeydown);
  300. }
  301. keydown(event) {
  302. if (!this.getActive()?.shouldGetKeyboardEvents()) {
  303. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  304. }
  305. }
  306. onEditingAction(details) {
  307. if (["undo", "redo", "cut", "copy", "paste", "delete", "selectAll"].includes(details.name)) {
  308. this[details.name]();
  309. }
  310. }
  311. #dispatchUpdateStates(details) {
  312. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  313. if (hasChanged) {
  314. this.#eventBus.dispatch("annotationeditorstateschanged", {
  315. source: this,
  316. details: Object.assign(this.#previousStates, details)
  317. });
  318. }
  319. }
  320. #dispatchUpdateUI(details) {
  321. this.#eventBus.dispatch("annotationeditorparamschanged", {
  322. source: this,
  323. details
  324. });
  325. }
  326. setEditingState(isEditing) {
  327. if (isEditing) {
  328. this.#addKeyboardManager();
  329. this.#dispatchUpdateStates({
  330. isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
  331. isEmpty: this.#isEmpty(),
  332. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  333. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  334. hasSelectedEditor: false,
  335. hasEmptyClipboard: this.#clipboardManager.isEmpty()
  336. });
  337. } else {
  338. this.#removeKeyboardManager();
  339. this.#dispatchUpdateStates({
  340. isEditing: false
  341. });
  342. }
  343. }
  344. registerEditorTypes(types) {
  345. this.#editorTypes = types;
  346. for (const editorType of this.#editorTypes) {
  347. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  348. }
  349. }
  350. getId() {
  351. return this.#idManager.getId();
  352. }
  353. addLayer(layer) {
  354. this.#allLayers.set(layer.pageIndex, layer);
  355. if (this.#isEnabled) {
  356. layer.enable();
  357. } else {
  358. layer.disable();
  359. }
  360. }
  361. removeLayer(layer) {
  362. this.#allLayers.delete(layer.pageIndex);
  363. }
  364. updateMode(mode) {
  365. this.#mode = mode;
  366. if (mode === _util.AnnotationEditorType.NONE) {
  367. this.setEditingState(false);
  368. this.#disableAll();
  369. } else {
  370. this.setEditingState(true);
  371. this.#enableAll();
  372. for (const layer of this.#allLayers.values()) {
  373. layer.updateMode(mode);
  374. }
  375. }
  376. }
  377. updateToolbar(mode) {
  378. if (mode === this.#mode) {
  379. return;
  380. }
  381. this.#eventBus.dispatch("switchannotationeditormode", {
  382. source: this,
  383. mode
  384. });
  385. }
  386. updateParams(type, value) {
  387. for (const editor of this.#selectedEditors) {
  388. editor.updateParams(type, value);
  389. }
  390. for (const editorType of this.#editorTypes) {
  391. editorType.updateDefaultParams(type, value);
  392. }
  393. }
  394. #enableAll() {
  395. if (!this.#isEnabled) {
  396. this.#isEnabled = true;
  397. for (const layer of this.#allLayers.values()) {
  398. layer.enable();
  399. }
  400. }
  401. }
  402. #disableAll() {
  403. this.unselectAll();
  404. if (this.#isEnabled) {
  405. this.#isEnabled = false;
  406. for (const layer of this.#allLayers.values()) {
  407. layer.disable();
  408. }
  409. }
  410. }
  411. getEditors(pageIndex) {
  412. const editors = [];
  413. for (const editor of this.#allEditors.values()) {
  414. if (editor.pageIndex === pageIndex) {
  415. editors.push(editor);
  416. }
  417. }
  418. return editors;
  419. }
  420. getEditor(id) {
  421. return this.#allEditors.get(id);
  422. }
  423. addEditor(editor) {
  424. this.#allEditors.set(editor.id, editor);
  425. }
  426. removeEditor(editor) {
  427. this.#allEditors.delete(editor.id);
  428. this.unselect(editor);
  429. }
  430. #addEditorToLayer(editor) {
  431. const layer = this.#allLayers.get(editor.pageIndex);
  432. if (layer) {
  433. layer.addOrRebuild(editor);
  434. } else {
  435. this.addEditor(editor);
  436. }
  437. }
  438. setActiveEditor(editor) {
  439. if (this.#activeEditor === editor) {
  440. return;
  441. }
  442. this.#activeEditor = editor;
  443. if (editor) {
  444. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  445. }
  446. }
  447. toggleSelected(editor) {
  448. if (this.#selectedEditors.has(editor)) {
  449. this.#selectedEditors.delete(editor);
  450. editor.unselect();
  451. this.#dispatchUpdateStates({
  452. hasSelectedEditor: this.hasSelection
  453. });
  454. return;
  455. }
  456. this.#selectedEditors.add(editor);
  457. editor.select();
  458. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  459. this.#dispatchUpdateStates({
  460. hasSelectedEditor: true
  461. });
  462. }
  463. setSelected(editor) {
  464. for (const ed of this.#selectedEditors) {
  465. if (ed !== editor) {
  466. ed.unselect();
  467. }
  468. }
  469. this.#selectedEditors.clear();
  470. this.#selectedEditors.add(editor);
  471. editor.select();
  472. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  473. this.#dispatchUpdateStates({
  474. hasSelectedEditor: true
  475. });
  476. }
  477. isSelected(editor) {
  478. return this.#selectedEditors.has(editor);
  479. }
  480. unselect(editor) {
  481. editor.unselect();
  482. this.#selectedEditors.delete(editor);
  483. this.#dispatchUpdateStates({
  484. hasSelectedEditor: this.hasSelection
  485. });
  486. }
  487. get hasSelection() {
  488. return this.#selectedEditors.size !== 0;
  489. }
  490. undo() {
  491. this.#commandManager.undo();
  492. this.#dispatchUpdateStates({
  493. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  494. hasSomethingToRedo: true,
  495. isEmpty: this.#isEmpty()
  496. });
  497. }
  498. redo() {
  499. this.#commandManager.redo();
  500. this.#dispatchUpdateStates({
  501. hasSomethingToUndo: true,
  502. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  503. isEmpty: this.#isEmpty()
  504. });
  505. }
  506. addCommands(params) {
  507. this.#commandManager.add(params);
  508. this.#dispatchUpdateStates({
  509. hasSomethingToUndo: true,
  510. hasSomethingToRedo: false,
  511. isEmpty: this.#isEmpty()
  512. });
  513. }
  514. #isEmpty() {
  515. if (this.#allEditors.size === 0) {
  516. return true;
  517. }
  518. if (this.#allEditors.size === 1) {
  519. for (const editor of this.#allEditors.values()) {
  520. return editor.isEmpty();
  521. }
  522. }
  523. return false;
  524. }
  525. delete() {
  526. if (this.#activeEditor) {
  527. this.#activeEditor.commitOrRemove();
  528. }
  529. if (!this.hasSelection) {
  530. return;
  531. }
  532. const editors = [...this.#selectedEditors];
  533. const cmd = () => {
  534. for (const editor of editors) {
  535. editor.remove();
  536. }
  537. };
  538. const undo = () => {
  539. for (const editor of editors) {
  540. this.#addEditorToLayer(editor);
  541. }
  542. };
  543. this.addCommands({
  544. cmd,
  545. undo,
  546. mustExec: true
  547. });
  548. }
  549. copy() {
  550. if (this.#activeEditor) {
  551. this.#activeEditor.commitOrRemove();
  552. }
  553. if (this.hasSelection) {
  554. const editors = [];
  555. for (const editor of this.#selectedEditors) {
  556. if (!editor.isEmpty()) {
  557. editors.push(editor);
  558. }
  559. }
  560. if (editors.length === 0) {
  561. return;
  562. }
  563. this.#clipboardManager.copy(editors);
  564. this.#dispatchUpdateStates({
  565. hasEmptyClipboard: false
  566. });
  567. }
  568. }
  569. cut() {
  570. this.copy();
  571. this.delete();
  572. }
  573. paste() {
  574. if (this.#clipboardManager.isEmpty()) {
  575. return;
  576. }
  577. this.unselectAll();
  578. const layer = this.#allLayers.get(this.#currentPageIndex);
  579. const newEditors = this.#clipboardManager.paste().map(data => layer.deserialize(data));
  580. const cmd = () => {
  581. for (const editor of newEditors) {
  582. this.#addEditorToLayer(editor);
  583. }
  584. this.#selectEditors(newEditors);
  585. };
  586. const undo = () => {
  587. for (const editor of newEditors) {
  588. editor.remove();
  589. }
  590. };
  591. this.addCommands({
  592. cmd,
  593. undo,
  594. mustExec: true
  595. });
  596. }
  597. #selectEditors(editors) {
  598. this.#selectedEditors.clear();
  599. for (const editor of editors) {
  600. if (editor.isEmpty()) {
  601. continue;
  602. }
  603. this.#selectedEditors.add(editor);
  604. editor.select();
  605. }
  606. this.#dispatchUpdateStates({
  607. hasSelectedEditor: true
  608. });
  609. }
  610. selectAll() {
  611. for (const editor of this.#selectedEditors) {
  612. editor.commit();
  613. }
  614. this.#selectEditors(this.#allEditors.values());
  615. }
  616. unselectAll() {
  617. if (this.#activeEditor) {
  618. this.#activeEditor.commitOrRemove();
  619. return;
  620. }
  621. if (this.#selectEditors.size === 0) {
  622. return;
  623. }
  624. for (const editor of this.#selectedEditors) {
  625. editor.unselect();
  626. }
  627. this.#selectedEditors.clear();
  628. this.#dispatchUpdateStates({
  629. hasSelectedEditor: false
  630. });
  631. }
  632. isActive(editor) {
  633. return this.#activeEditor === editor;
  634. }
  635. getActive() {
  636. return this.#activeEditor;
  637. }
  638. getMode() {
  639. return this.#mode;
  640. }
  641. }
  642. exports.AnnotationEditorUIManager = AnnotationEditorUIManager;