svg_v3_highlighter.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import * as DomUtil from '../common/dom_util.js';
  2. import * as XpathUtil from '../common/xpath_util.js';
  3. import { ColorPicker } from './color_picker.js';
  4. import { SvgHighlighter } from './svg_highlighter.js';
  5. export class SvgV3Highlighter extends SvgHighlighter {
  6. constructor() {
  7. super();
  8. this.mactionName = 'maction';
  9. }
  10. highlightNode(node) {
  11. let info;
  12. if (this.isHighlighted(node)) {
  13. info = {
  14. node: node,
  15. background: this.colorString().background,
  16. foreground: this.colorString().foreground
  17. };
  18. return info;
  19. }
  20. if (node.tagName === 'svg' || node.tagName === 'MJX-CONTAINER') {
  21. info = {
  22. node: node,
  23. background: node.style.backgroundColor,
  24. foreground: node.style.color
  25. };
  26. node.style.backgroundColor = this.colorString().background;
  27. node.style.color = this.colorString().foreground;
  28. return info;
  29. }
  30. const rect = DomUtil.createElementNS('http://www.w3.org/2000/svg', 'rect');
  31. rect.setAttribute('sre-highlighter-added', 'true');
  32. const padding = 40;
  33. const bbox = node.getBBox();
  34. rect.setAttribute('x', (bbox.x - padding).toString());
  35. rect.setAttribute('y', (bbox.y - padding).toString());
  36. rect.setAttribute('width', (bbox.width + 2 * padding).toString());
  37. rect.setAttribute('height', (bbox.height + 2 * padding).toString());
  38. const transform = node.getAttribute('transform');
  39. if (transform) {
  40. rect.setAttribute('transform', transform);
  41. }
  42. rect.setAttribute('fill', this.colorString().background);
  43. node.setAttribute(this.ATTR, 'true');
  44. node.parentNode.insertBefore(rect, node);
  45. info = { node: node, foreground: node.getAttribute('fill') };
  46. if (node.nodeName === 'rect') {
  47. const picker = new ColorPicker({ alpha: 0, color: 'black' });
  48. node.setAttribute('fill', picker.rgba().foreground);
  49. }
  50. else {
  51. node.setAttribute('fill', this.colorString().foreground);
  52. }
  53. return info;
  54. }
  55. unhighlightNode(info) {
  56. const previous = info.node.previousSibling;
  57. if (previous && previous.hasAttribute('sre-highlighter-added')) {
  58. info.foreground
  59. ? info.node.setAttribute('fill', info.foreground)
  60. : info.node.removeAttribute('fill');
  61. info.node.parentNode.removeChild(previous);
  62. return;
  63. }
  64. info.node.style.backgroundColor = info.background;
  65. info.node.style.color = info.foreground;
  66. }
  67. isMactionNode(node) {
  68. return node.getAttribute('data-mml-node') === this.mactionName;
  69. }
  70. getMactionNodes(node) {
  71. return Array.from(XpathUtil.evalXPath(`.//*[@data-mml-node="${this.mactionName}"]`, node));
  72. }
  73. }