tools.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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. #boundOnTextLayerRendered = this.onTextLayerRendered.bind(this);
  258. #previousStates = {
  259. isEditing: false,
  260. isEmpty: true,
  261. hasEmptyClipboard: true,
  262. hasSomethingToUndo: false,
  263. hasSomethingToRedo: false,
  264. hasSelectedEditor: false
  265. };
  266. #container = null;
  267. 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]]);
  268. constructor(container, eventBus) {
  269. this.#container = container;
  270. this.#eventBus = eventBus;
  271. this.#eventBus._on("editingaction", this.#boundOnEditingAction);
  272. this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
  273. this.#eventBus._on("textlayerrendered", this.#boundOnTextLayerRendered);
  274. }
  275. destroy() {
  276. this.#removeKeyboardManager();
  277. this.#eventBus._off("editingaction", this.#boundOnEditingAction);
  278. this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
  279. this.#eventBus._off("textlayerrendered", this.#boundOnTextLayerRendered);
  280. for (const layer of this.#allLayers.values()) {
  281. layer.destroy();
  282. }
  283. this.#allLayers.clear();
  284. this.#allEditors.clear();
  285. this.#activeEditor = null;
  286. this.#selectedEditors.clear();
  287. this.#clipboardManager.destroy();
  288. this.#commandManager.destroy();
  289. }
  290. onPageChanging({
  291. pageNumber
  292. }) {
  293. this.#currentPageIndex = pageNumber - 1;
  294. }
  295. onTextLayerRendered({
  296. pageNumber
  297. }) {
  298. const pageIndex = pageNumber - 1;
  299. const layer = this.#allLayers.get(pageIndex);
  300. layer?.onTextLayerRendered();
  301. }
  302. focusMainContainer() {
  303. this.#container.focus();
  304. }
  305. #addKeyboardManager() {
  306. this.#container.addEventListener("keydown", this.#boundKeydown);
  307. }
  308. #removeKeyboardManager() {
  309. this.#container.removeEventListener("keydown", this.#boundKeydown);
  310. }
  311. keydown(event) {
  312. if (!this.getActive()?.shouldGetKeyboardEvents()) {
  313. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  314. }
  315. }
  316. onEditingAction(details) {
  317. if (["undo", "redo", "cut", "copy", "paste", "delete", "selectAll"].includes(details.name)) {
  318. this[details.name]();
  319. }
  320. }
  321. #dispatchUpdateStates(details) {
  322. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  323. if (hasChanged) {
  324. this.#eventBus.dispatch("annotationeditorstateschanged", {
  325. source: this,
  326. details: Object.assign(this.#previousStates, details)
  327. });
  328. }
  329. }
  330. #dispatchUpdateUI(details) {
  331. this.#eventBus.dispatch("annotationeditorparamschanged", {
  332. source: this,
  333. details
  334. });
  335. }
  336. setEditingState(isEditing) {
  337. if (isEditing) {
  338. this.#addKeyboardManager();
  339. this.#dispatchUpdateStates({
  340. isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
  341. isEmpty: this.#isEmpty(),
  342. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  343. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  344. hasSelectedEditor: false,
  345. hasEmptyClipboard: this.#clipboardManager.isEmpty()
  346. });
  347. } else {
  348. this.#removeKeyboardManager();
  349. this.#dispatchUpdateStates({
  350. isEditing: false
  351. });
  352. }
  353. }
  354. registerEditorTypes(types) {
  355. this.#editorTypes = types;
  356. for (const editorType of this.#editorTypes) {
  357. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  358. }
  359. }
  360. getId() {
  361. return this.#idManager.getId();
  362. }
  363. addLayer(layer) {
  364. this.#allLayers.set(layer.pageIndex, layer);
  365. if (this.#isEnabled) {
  366. layer.enable();
  367. } else {
  368. layer.disable();
  369. }
  370. }
  371. removeLayer(layer) {
  372. this.#allLayers.delete(layer.pageIndex);
  373. }
  374. updateMode(mode) {
  375. this.#mode = mode;
  376. if (mode === _util.AnnotationEditorType.NONE) {
  377. this.setEditingState(false);
  378. this.#disableAll();
  379. } else {
  380. this.setEditingState(true);
  381. this.#enableAll();
  382. for (const layer of this.#allLayers.values()) {
  383. layer.updateMode(mode);
  384. }
  385. }
  386. }
  387. updateToolbar(mode) {
  388. if (mode === this.#mode) {
  389. return;
  390. }
  391. this.#eventBus.dispatch("switchannotationeditormode", {
  392. source: this,
  393. mode
  394. });
  395. }
  396. updateParams(type, value) {
  397. for (const editor of this.#selectedEditors) {
  398. editor.updateParams(type, value);
  399. }
  400. for (const editorType of this.#editorTypes) {
  401. editorType.updateDefaultParams(type, value);
  402. }
  403. }
  404. #enableAll() {
  405. if (!this.#isEnabled) {
  406. this.#isEnabled = true;
  407. for (const layer of this.#allLayers.values()) {
  408. layer.enable();
  409. }
  410. }
  411. }
  412. #disableAll() {
  413. this.unselectAll();
  414. if (this.#isEnabled) {
  415. this.#isEnabled = false;
  416. for (const layer of this.#allLayers.values()) {
  417. layer.disable();
  418. }
  419. }
  420. }
  421. getEditors(pageIndex) {
  422. const editors = [];
  423. for (const editor of this.#allEditors.values()) {
  424. if (editor.pageIndex === pageIndex) {
  425. editors.push(editor);
  426. }
  427. }
  428. return editors;
  429. }
  430. getEditor(id) {
  431. return this.#allEditors.get(id);
  432. }
  433. addEditor(editor) {
  434. this.#allEditors.set(editor.id, editor);
  435. }
  436. removeEditor(editor) {
  437. this.#allEditors.delete(editor.id);
  438. this.unselect(editor);
  439. }
  440. #addEditorToLayer(editor) {
  441. const layer = this.#allLayers.get(editor.pageIndex);
  442. if (layer) {
  443. layer.addOrRebuild(editor);
  444. } else {
  445. this.addEditor(editor);
  446. }
  447. }
  448. setActiveEditor(editor) {
  449. if (this.#activeEditor === editor) {
  450. return;
  451. }
  452. this.#activeEditor = editor;
  453. if (editor) {
  454. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  455. }
  456. }
  457. toggleSelected(editor) {
  458. if (this.#selectedEditors.has(editor)) {
  459. this.#selectedEditors.delete(editor);
  460. editor.unselect();
  461. this.#dispatchUpdateStates({
  462. hasSelectedEditor: this.hasSelection
  463. });
  464. return;
  465. }
  466. this.#selectedEditors.add(editor);
  467. editor.select();
  468. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  469. this.#dispatchUpdateStates({
  470. hasSelectedEditor: true
  471. });
  472. }
  473. setSelected(editor) {
  474. for (const ed of this.#selectedEditors) {
  475. if (ed !== editor) {
  476. ed.unselect();
  477. }
  478. }
  479. this.#selectedEditors.clear();
  480. this.#selectedEditors.add(editor);
  481. editor.select();
  482. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  483. this.#dispatchUpdateStates({
  484. hasSelectedEditor: true
  485. });
  486. }
  487. isSelected(editor) {
  488. return this.#selectedEditors.has(editor);
  489. }
  490. unselect(editor) {
  491. editor.unselect();
  492. this.#selectedEditors.delete(editor);
  493. this.#dispatchUpdateStates({
  494. hasSelectedEditor: this.hasSelection
  495. });
  496. }
  497. get hasSelection() {
  498. return this.#selectedEditors.size !== 0;
  499. }
  500. undo() {
  501. this.#commandManager.undo();
  502. this.#dispatchUpdateStates({
  503. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  504. hasSomethingToRedo: true,
  505. isEmpty: this.#isEmpty()
  506. });
  507. }
  508. redo() {
  509. this.#commandManager.redo();
  510. this.#dispatchUpdateStates({
  511. hasSomethingToUndo: true,
  512. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  513. isEmpty: this.#isEmpty()
  514. });
  515. }
  516. addCommands(params) {
  517. this.#commandManager.add(params);
  518. this.#dispatchUpdateStates({
  519. hasSomethingToUndo: true,
  520. hasSomethingToRedo: false,
  521. isEmpty: this.#isEmpty()
  522. });
  523. }
  524. #isEmpty() {
  525. if (this.#allEditors.size === 0) {
  526. return true;
  527. }
  528. if (this.#allEditors.size === 1) {
  529. for (const editor of this.#allEditors.values()) {
  530. return editor.isEmpty();
  531. }
  532. }
  533. return false;
  534. }
  535. delete() {
  536. if (this.#activeEditor) {
  537. this.#activeEditor.commitOrRemove();
  538. }
  539. if (!this.hasSelection) {
  540. return;
  541. }
  542. const editors = [...this.#selectedEditors];
  543. const cmd = () => {
  544. for (const editor of editors) {
  545. editor.remove();
  546. }
  547. };
  548. const undo = () => {
  549. for (const editor of editors) {
  550. this.#addEditorToLayer(editor);
  551. }
  552. };
  553. this.addCommands({
  554. cmd,
  555. undo,
  556. mustExec: true
  557. });
  558. }
  559. copy() {
  560. if (this.#activeEditor) {
  561. this.#activeEditor.commitOrRemove();
  562. }
  563. if (this.hasSelection) {
  564. const editors = [];
  565. for (const editor of this.#selectedEditors) {
  566. if (!editor.isEmpty()) {
  567. editors.push(editor);
  568. }
  569. }
  570. if (editors.length === 0) {
  571. return;
  572. }
  573. this.#clipboardManager.copy(editors);
  574. this.#dispatchUpdateStates({
  575. hasEmptyClipboard: false
  576. });
  577. }
  578. }
  579. cut() {
  580. this.copy();
  581. this.delete();
  582. }
  583. paste() {
  584. if (this.#clipboardManager.isEmpty()) {
  585. return;
  586. }
  587. this.unselectAll();
  588. const layer = this.#allLayers.get(this.#currentPageIndex);
  589. const newEditors = this.#clipboardManager.paste().map(data => layer.deserialize(data));
  590. const cmd = () => {
  591. for (const editor of newEditors) {
  592. this.#addEditorToLayer(editor);
  593. }
  594. this.#selectEditors(newEditors);
  595. };
  596. const undo = () => {
  597. for (const editor of newEditors) {
  598. editor.remove();
  599. }
  600. };
  601. this.addCommands({
  602. cmd,
  603. undo,
  604. mustExec: true
  605. });
  606. }
  607. #selectEditors(editors) {
  608. this.#selectedEditors.clear();
  609. for (const editor of editors) {
  610. if (editor.isEmpty()) {
  611. continue;
  612. }
  613. this.#selectedEditors.add(editor);
  614. editor.select();
  615. }
  616. this.#dispatchUpdateStates({
  617. hasSelectedEditor: true
  618. });
  619. }
  620. selectAll() {
  621. for (const editor of this.#selectedEditors) {
  622. editor.commit();
  623. }
  624. this.#selectEditors(this.#allEditors.values());
  625. }
  626. unselectAll() {
  627. if (this.#activeEditor) {
  628. this.#activeEditor.commitOrRemove();
  629. return;
  630. }
  631. if (this.#selectEditors.size === 0) {
  632. return;
  633. }
  634. for (const editor of this.#selectedEditors) {
  635. editor.unselect();
  636. }
  637. this.#selectedEditors.clear();
  638. this.#dispatchUpdateStates({
  639. hasSelectedEditor: false
  640. });
  641. }
  642. isActive(editor) {
  643. return this.#activeEditor === editor;
  644. }
  645. getActive() {
  646. return this.#activeEditor;
  647. }
  648. getMode() {
  649. return this.#mode;
  650. }
  651. }
  652. exports.AnnotationEditorUIManager = AnnotationEditorUIManager;