Wrapper.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /*************************************************************
  2. *
  3. * Copyright (c) 2018-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 Implements the SVGWrapper class
  19. *
  20. * @author dpvc@mathjax.org (Davide Cervone)
  21. */
  22. import {OptionList} from '../../util/Options.js';
  23. import {BBox} from '../../util/BBox.js';
  24. import {CommonWrapper, AnyWrapperClass, Constructor} from '../common/Wrapper.js';
  25. import {SVG, XLINKNS} from '../svg.js';
  26. import {SVGWrapperFactory} from './WrapperFactory.js';
  27. import {SVGFontData, SVGDelimiterData, SVGCharOptions} from './FontData.js';
  28. export {Constructor, StringMap} from '../common/Wrapper.js';
  29. /*****************************************************************/
  30. /**
  31. * Shorthand for makeing a SVGWrapper constructor
  32. */
  33. export type SVGConstructor<N, T, D> = Constructor<SVGWrapper<N, T, D>>;
  34. /*****************************************************************/
  35. /**
  36. * The type of the SVGWrapper class (used when creating the wrapper factory for this class)
  37. */
  38. export interface SVGWrapperClass extends AnyWrapperClass {
  39. kind: string;
  40. }
  41. /*****************************************************************/
  42. /**
  43. * The base SVGWrapper class
  44. *
  45. * @template N The HTMLElement node class
  46. * @template T The Text node class
  47. * @template D The Document class
  48. */
  49. export class SVGWrapper<N, T, D> extends
  50. CommonWrapper<
  51. SVG<N, T, D>,
  52. SVGWrapper<N, T, D>,
  53. SVGWrapperClass,
  54. SVGCharOptions,
  55. SVGDelimiterData,
  56. SVGFontData
  57. > {
  58. /**
  59. * The kind of wrapper
  60. */
  61. public static kind: string = 'unknown';
  62. /**
  63. * A fuzz factor for borders to avoid anti-alias problems at the edges
  64. */
  65. public static borderFuzz = 0.005;
  66. /**
  67. * The factory used to create more SVGWrappers
  68. */
  69. protected factory: SVGWrapperFactory<N, T, D>;
  70. /**
  71. * @override
  72. */
  73. public parent: SVGWrapper<N, T, D>;
  74. /**
  75. * @override
  76. */
  77. public childNodes: SVGWrapper<N, T, D>[];
  78. /**
  79. * The SVG element generated for this wrapped node
  80. */
  81. public element: N = null;
  82. /**
  83. * Offset due to border/padding
  84. */
  85. public dx: number = 0;
  86. /**
  87. * @override
  88. */
  89. public font: SVGFontData;
  90. /*******************************************************************/
  91. /**
  92. * Create the HTML for the wrapped node.
  93. *
  94. * @param {N} parent The HTML node where the output is added
  95. */
  96. public toSVG(parent: N) {
  97. this.addChildren(this.standardSVGnode(parent));
  98. }
  99. /**
  100. * @param {N} parent The element in which to add the children
  101. */
  102. public addChildren(parent: N) {
  103. let x = 0;
  104. for (const child of this.childNodes) {
  105. child.toSVG(parent);
  106. const bbox = child.getOuterBBox();
  107. if (child.element) {
  108. child.place(x + bbox.L * bbox.rscale, 0);
  109. }
  110. x += (bbox.L + bbox.w + bbox.R) * bbox.rscale;
  111. }
  112. }
  113. /*******************************************************************/
  114. /**
  115. * Create the standard SVG element for the given wrapped node.
  116. *
  117. * @param {N} parent The HTML element in which the node is to be created
  118. * @returns {N} The root of the HTML tree for the wrapped node's output
  119. */
  120. protected standardSVGnode(parent: N): N {
  121. const svg = this.createSVGnode(parent);
  122. this.handleStyles();
  123. this.handleScale();
  124. this.handleBorder();
  125. this.handleColor();
  126. this.handleAttributes();
  127. return svg;
  128. }
  129. /**
  130. * @param {N} parent The HTML element in which the node is to be created
  131. * @returns {N} The root of the HTML tree for the wrapped node's output
  132. */
  133. protected createSVGnode(parent: N): N {
  134. this.element = this.svg('g', {'data-mml-node': this.node.kind});
  135. const href = this.node.attributes.get('href');
  136. if (href) {
  137. parent = this.adaptor.append(parent, this.svg('a', {href: href})) as N;
  138. const {h, d, w} = this.getOuterBBox();
  139. this.adaptor.append(this.element, this.svg('rect', {
  140. 'data-hitbox': true, fill: 'none', stroke: 'none', 'pointer-events': 'all',
  141. width: this.fixed(w), height: this.fixed(h + d), y: this.fixed(-d)
  142. }));
  143. }
  144. this.adaptor.append(parent, this.element) as N;
  145. return this.element;
  146. }
  147. /**
  148. * Set the CSS styles for the svg element
  149. */
  150. protected handleStyles() {
  151. if (!this.styles) return;
  152. const styles = this.styles.cssText;
  153. if (styles) {
  154. this.adaptor.setAttribute(this.element, 'style', styles);
  155. }
  156. BBox.StyleAdjust.forEach(([name, , lr]) => {
  157. if (lr !== 0) return;
  158. const x = this.styles.get(name);
  159. if (x) {
  160. this.dx += this.length2em(x, 1, this.bbox.rscale);
  161. }
  162. });
  163. }
  164. /**
  165. * Set the (relative) scaling factor for the node
  166. */
  167. protected handleScale() {
  168. if (this.bbox.rscale !== 1) {
  169. const scale = 'scale(' + this.fixed(this.bbox.rscale / 1000, 3) + ')';
  170. this.adaptor.setAttribute(this.element, 'transform', scale);
  171. }
  172. }
  173. /**
  174. * Add the foreground and background colors
  175. * (Only look at explicit attributes, since inherited ones will
  176. * be applied to a parent element, and we will inherit from that)
  177. */
  178. protected handleColor() {
  179. const adaptor = this.adaptor;
  180. const attributes = this.node.attributes;
  181. const mathcolor = attributes.getExplicit('mathcolor') as string;
  182. const color = attributes.getExplicit('color') as string;
  183. const mathbackground = attributes.getExplicit('mathbackground') as string;
  184. const background = attributes.getExplicit('background') as string;
  185. const bgcolor = (this.styles?.get('background-color') || '');
  186. if (mathcolor || color) {
  187. adaptor.setAttribute(this.element, 'fill', mathcolor || color);
  188. adaptor.setAttribute(this.element, 'stroke', mathcolor || color);
  189. }
  190. if (mathbackground || background || bgcolor) {
  191. let {h, d, w} = this.getOuterBBox();
  192. let rect = this.svg('rect', {
  193. fill: mathbackground || background || bgcolor,
  194. x: this.fixed(-this.dx), y: this.fixed(-d),
  195. width: this.fixed(w),
  196. height: this.fixed(h + d),
  197. 'data-bgcolor': true
  198. });
  199. let child = adaptor.firstChild(this.element);
  200. if (child) {
  201. adaptor.insert(rect, child);
  202. } else {
  203. adaptor.append(this.element, rect);
  204. }
  205. }
  206. }
  207. /**
  208. * Create the borders, if any are requested.
  209. */
  210. protected handleBorder() {
  211. if (!this.styles) return;
  212. const width = Array(4).fill(0);
  213. const style = Array(4);
  214. const color = Array(4);
  215. for (const [name, i] of [['Top', 0], ['Right', 1], ['Bottom', 2], ['Left', 3]] as [string, number][]) {
  216. const key = 'border' + name;
  217. const w = this.styles.get(key + 'Width');
  218. if (!w) continue;
  219. width[i] = Math.max(0, this.length2em(w, 1, this.bbox.rscale));
  220. style[i] = this.styles.get(key + 'Style') || 'solid';
  221. color[i] = this.styles.get(key + 'Color') || 'currentColor';
  222. }
  223. const f = SVGWrapper.borderFuzz;
  224. const bbox = this.getOuterBBox();
  225. const [h, d, w] = [bbox.h + f, bbox.d + f, bbox.w + f];
  226. const outerRT = [w, h];
  227. const outerLT = [-f, h];
  228. const outerRB = [w, -d];
  229. const outerLB = [-f, -d];
  230. const innerRT = [w - width[1], h - width[0]];
  231. const innerLT = [-f + width[3], h - width[0]];
  232. const innerRB = [w - width[1], -d + width[2]];
  233. const innerLB = [-f + width[3], -d + width[2]];
  234. const paths: number[][][] = [
  235. [outerLT, outerRT, innerRT, innerLT],
  236. [outerRB, outerRT, innerRT, innerRB],
  237. [outerLB, outerRB, innerRB, innerLB],
  238. [outerLB, outerLT, innerLT, innerLB]
  239. ];
  240. const adaptor = this.adaptor;
  241. const child = adaptor.firstChild(this.element) as N;
  242. for (const i of [0, 1, 2, 3]) {
  243. if (!width[i]) continue;
  244. const path = paths[i];
  245. if (style[i] === 'dashed' || style[i] === 'dotted') {
  246. this.addBorderBroken(path, color[i], style[i], width[i], i);
  247. } else {
  248. this.addBorderSolid(path, color[i], child);
  249. }
  250. }
  251. }
  252. /**
  253. * Create a solid border piece with the given color
  254. *
  255. * @param {[number, number][]} path The points for the border segment
  256. * @param {string} color The color to use
  257. * @param {N} child Insert the border before this child, if any
  258. */
  259. protected addBorderSolid(path: number[][], color: string, child: N) {
  260. const border = this.svg('polygon', {
  261. points: path.map(([x, y]) => `${this.fixed(x - this.dx)},${this.fixed(y)}`).join(' '),
  262. stroke: 'none',
  263. fill: color
  264. });
  265. if (child) {
  266. this.adaptor.insert(border, child);
  267. } else {
  268. this.adaptor.append(this.element, border);
  269. }
  270. }
  271. /**
  272. * Create a dashed or dotted border line with the given width and color
  273. *
  274. * @param {[number, number][]} path The points for the border segment
  275. * @param {string} color The color to use
  276. * @param {string} style Either 'dotted' or 'dashed'
  277. * @param {number} t The thickness for the border line
  278. * @param {number} i The side being drawn
  279. */
  280. protected addBorderBroken(path: number[][], color: string, style: string, t: number, i: number) {
  281. const dot = (style === 'dotted');
  282. const t2 = t / 2;
  283. const [tx1, ty1, tx2, ty2] = [[t2, -t2, -t2, -t2], [-t2, t2, -t2, -t2], [t2, t2, -t2, t2], [t2, t2, t2, -t2]][i];
  284. const [A, B] = path;
  285. const x1 = A[0] + tx1 - this.dx, y1 = A[1] + ty1;
  286. const x2 = B[0] + tx2 - this.dx, y2 = B[1] + ty2;
  287. const W = Math.abs(i % 2 ? y2 - y1 : x2 - x1);
  288. const n = (dot ? Math.ceil(W / (2 * t)) : Math.ceil((W - t) / (4 * t)));
  289. const m = W / (4 * n + 1);
  290. const line = this.svg('line', {
  291. x1: this.fixed(x1), y1: this.fixed(y1),
  292. x2: this.fixed(x2), y2: this.fixed(y2),
  293. 'stroke-width': this.fixed(t), stroke: color, 'stroke-linecap': dot ? 'round' : 'square',
  294. 'stroke-dasharray': dot ? [1, this.fixed(W / n - .002)].join(' ') : [this.fixed(m), this.fixed(3 * m)].join(' ')
  295. });
  296. const adaptor = this.adaptor;
  297. const child = adaptor.firstChild(this.element);
  298. if (child) {
  299. adaptor.insert(line, child);
  300. } else {
  301. adaptor.append(this.element, line);
  302. }
  303. }
  304. /**
  305. * Copy RDFa, aria, and other tags from the MathML to the SVG output nodes.
  306. * Don't copy those in the skipAttributes list, or anything that already exists
  307. * as a property of the node (e.g., no "onlick", etc.). If a name in the
  308. * skipAttributes object is set to false, then the attribute WILL be copied.
  309. * Add the class to any other classes already in use.
  310. */
  311. protected handleAttributes() {
  312. const attributes = this.node.attributes;
  313. const defaults = attributes.getAllDefaults();
  314. const skip = SVGWrapper.skipAttributes;
  315. for (const name of attributes.getExplicitNames()) {
  316. if (skip[name] === false || (!(name in defaults) && !skip[name] &&
  317. !this.adaptor.hasAttribute(this.element, name))) {
  318. this.adaptor.setAttribute(this.element, name, attributes.getExplicit(name) as string);
  319. }
  320. }
  321. if (attributes.get('class')) {
  322. const names = (attributes.get('class') as string).trim().split(/ +/);
  323. for (const name of names) {
  324. this.adaptor.addClass(this.element, name);
  325. }
  326. }
  327. }
  328. /*******************************************************************/
  329. /**
  330. * @param {number} x The x-offset for the element
  331. * @param {number} y The y-offset for the element
  332. * @param {N} element The element to be placed
  333. */
  334. public place(x: number, y: number, element: N = null) {
  335. x += this.dx;
  336. if (!(x || y)) return;
  337. if (!element) {
  338. element = this.element;
  339. y = this.handleId(y);
  340. }
  341. const translate = `translate(${this.fixed(x)},${this.fixed(y)})`;
  342. const transform = this.adaptor.getAttribute(element, 'transform') || '';
  343. this.adaptor.setAttribute(element, 'transform', translate + (transform ? ' ' + transform : ''));
  344. }
  345. /**
  346. * Firefox and Safari don't scroll to the top of the element with an Id, so
  347. * we shift the element up and then translate its contents down in order to
  348. * correct for their positioning. Also, Safari will go to the baseline of
  349. * a <text> element (e.g., when mtextInheritFont is true), so add a text
  350. * element to help Safari get the right location.
  351. *
  352. * @param {number} y The current offset of the element
  353. * @return {number} The new offset for the element if it has an id
  354. */
  355. protected handleId(y: number): number {
  356. if (!this.node.attributes || !this.node.attributes.get('id')) {
  357. return y;
  358. }
  359. const adaptor = this.adaptor;
  360. const h = this.getBBox().h;
  361. //
  362. // Remove the element's children and put them into a <g> with transform
  363. //
  364. const children = adaptor.childNodes(this.element);
  365. children.forEach(child => adaptor.remove(child));
  366. const g = this.svg('g', {'data-idbox': true, transform: `translate(0,${this.fixed(-h)})`}, children);
  367. //
  368. // Add the text element (not transformed) and the transformed <g>
  369. //
  370. adaptor.append(this.element, this.svg('text', {'data-id-align': true} , [this.text('')]));
  371. adaptor.append(this.element, g);
  372. return y + h;
  373. }
  374. /**
  375. * Return the first child element, skipping id align boxes and href hit boxes
  376. *
  377. * @return {N} The first "real" child element
  378. */
  379. public firstChild(): N {
  380. const adaptor = this.adaptor;
  381. let child = adaptor.firstChild(this.element);
  382. if (child && adaptor.kind(child) === 'text' && adaptor.getAttribute(child, 'data-id-align')) {
  383. child = adaptor.firstChild(adaptor.next(child));
  384. }
  385. if (child && adaptor.kind(child) === 'rect' && adaptor.getAttribute(child, 'data-hitbox')) {
  386. child = adaptor.next(child);
  387. }
  388. return child;
  389. }
  390. /**
  391. * @param {number} n The character number
  392. * @param {number} x The x-position of the character
  393. * @param {number} y The y-position of the character
  394. * @param {N} parent The container for the character
  395. * @param {string} variant The variant to use for the character
  396. * @return {number} The width of the character
  397. */
  398. public placeChar(n: number, x: number, y: number, parent: N, variant: string = null): number {
  399. if (variant === null) {
  400. variant = this.variant;
  401. }
  402. const C = n.toString(16).toUpperCase();
  403. const [ , , w, data] = this.getVariantChar(variant, n);
  404. if ('p' in data) {
  405. const path = (data.p ? 'M' + data.p + 'Z' : '');
  406. this.place(x, y, this.adaptor.append(parent, this.charNode(variant, C, path)));
  407. } else if ('c' in data) {
  408. const g = this.adaptor.append(parent, this.svg('g', {'data-c': C}));
  409. this.place(x, y, g);
  410. x = 0;
  411. for (const n of this.unicodeChars(data.c, variant)) {
  412. x += this.placeChar(n, x, y, g, variant);
  413. }
  414. } else if (data.unknown) {
  415. const char = String.fromCodePoint(n);
  416. const text = this.adaptor.append(parent, this.jax.unknownText(char, variant));
  417. this.place(x, y, text);
  418. return this.jax.measureTextNodeWithCache(text, char, variant).w;
  419. }
  420. return w;
  421. }
  422. /**
  423. * @param {string} variant The name of the variant being used
  424. * @param {string} C The hex string for the character code
  425. * @param {string} path The data from the character
  426. * @return {N} The <path> or <use> node for the glyph
  427. */
  428. protected charNode(variant: string, C: string, path: string): N {
  429. const cache = this.jax.options.fontCache;
  430. return (cache !== 'none' ? this.useNode(variant, C, path) : this.pathNode(C, path));
  431. }
  432. /**
  433. * @param {string} C The hex string for the character code
  434. * @param {string} path The data from the character
  435. * @return {N} The <path> for the glyph
  436. */
  437. protected pathNode(C: string, path: string): N {
  438. return this.svg('path', {'data-c': C, d: path});
  439. }
  440. /**
  441. * @param {string} variant The name of the variant being used
  442. * @param {string} C The hex string for the character code
  443. * @param {string} path The data from the character
  444. * @return {N} The <use> node for the glyph
  445. */
  446. protected useNode(variant: string, C: string, path: string): N {
  447. const use = this.svg('use', {'data-c': C});
  448. const id = '#' + this.jax.fontCache.cachePath(variant, C, path);
  449. this.adaptor.setAttribute(use, 'href', id, XLINKNS);
  450. return use;
  451. }
  452. /*******************************************************************/
  453. /**
  454. * For debugging
  455. */
  456. public drawBBox() {
  457. let {w, h, d} = this.getBBox();
  458. const box = this.svg('g', {style: {
  459. opacity: .25
  460. }}, [
  461. this.svg('rect', {
  462. fill: 'red',
  463. height: this.fixed(h),
  464. width: this.fixed(w)
  465. }),
  466. this.svg('rect', {
  467. fill: 'green',
  468. height: this.fixed(d),
  469. width: this.fixed(w),
  470. y: this.fixed(-d)
  471. })
  472. ] as N[]);
  473. const node = this.element || this.parent.element;
  474. this.adaptor.append(node, box);
  475. }
  476. /*******************************************************************/
  477. /*
  478. * Easy access to some utility routines
  479. */
  480. /**
  481. * @param {string} type The tag name of the HTML node to be created
  482. * @param {OptionList} def The properties to set for the created node
  483. * @param {(N|T)[]} content The child nodes for the created HTML node
  484. * @return {N} The generated HTML tree
  485. */
  486. public html(type: string, def: OptionList = {}, content: (N | T)[] = []): N {
  487. return this.jax.html(type, def, content);
  488. }
  489. /**
  490. * @param {string} type The tag name of the svg node to be created
  491. * @param {OptionList} def The properties to set for the created node
  492. * @param {(N|T)[]} content The child nodes for the created SVG node
  493. * @return {N} The generated SVG tree
  494. */
  495. public svg(type: string, def: OptionList = {}, content: (N | T)[] = []): N {
  496. return this.jax.svg(type, def, content);
  497. }
  498. /**
  499. * @param {string} text The text from which to create an HTML text node
  500. * @return {T} The generated text node with the given text
  501. */
  502. public text(text: string): T {
  503. return this.jax.text(text);
  504. }
  505. /**
  506. * @param {number} x The dimension to display
  507. * @param {number=} n The number of digits to display
  508. * @return {string} The dimension with the given number of digits (minus trailing zeros)
  509. */
  510. public fixed(x: number, n: number = 1): string {
  511. return this.jax.fixed(x * 1000, n);
  512. }
  513. }