SelectableInfo.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*************************************************************
  2. *
  3. * Copyright (c) 2019-2022 The MathJax Consortium
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /**
  18. * @fileoverview An info box that allows text selection and has copy-to-clipboard functions
  19. *
  20. * @author dpvc@mathjax.org (Davide Cervone)
  21. */
  22. import {Info} from 'mj-context-menu/js/info.js';
  23. import {HtmlClasses} from 'mj-context-menu/js/html_classes.js';
  24. /*==========================================================================*/
  25. /**
  26. * The SelectableInfo class definition
  27. */
  28. export class SelectableInfo extends Info {
  29. /**
  30. * Add a keypress event to handle "select all" so that only
  31. * the info-box's text is selected (not the whole page)
  32. *
  33. * @override
  34. */
  35. public addEvents(element: HTMLElement) {
  36. element.addEventListener('keypress', (event: KeyboardEvent) => {
  37. if (event.key === 'a' && (event.ctrlKey || event.metaKey)) {
  38. this.selectAll();
  39. this.stop(event);
  40. }
  41. });
  42. }
  43. /**
  44. * Select all the main text of the info box
  45. */
  46. public selectAll() {
  47. const selection = document.getSelection();
  48. selection.selectAllChildren(this.html.querySelector('pre'));
  49. }
  50. /**
  51. * Implement the copy-to-clipboard action
  52. */
  53. public copyToClipboard() {
  54. this.selectAll();
  55. try {
  56. document.execCommand('copy');
  57. } catch (err) {
  58. alert('Can\'t copy to clipboard: ' + err.message);
  59. }
  60. document.getSelection().removeAllRanges();
  61. }
  62. /**
  63. * Attach the copy-to-clipboard action to its button
  64. */
  65. public generateHtml() {
  66. super.generateHtml();
  67. const footer = this.html.querySelector('span.' + HtmlClasses['INFOSIGNATURE']);
  68. const button = footer.appendChild(document.createElement('input'));
  69. button.type = 'button';
  70. button.value = 'Copy to Clipboard';
  71. button.addEventListener('click', (_event: MouseEvent) => this.copyToClipboard());
  72. }
  73. }