liteAdaptor.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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 a lightweight DOM adaptor
  19. *
  20. * @author dpvc@mathjax.org (Davide Cervone)
  21. */
  22. import {AbstractDOMAdaptor} from '../core/DOMAdaptor.js';
  23. import {NodeMixin, Constructor} from './NodeMixin.js';
  24. import {LiteDocument} from './lite/Document.js';
  25. import {LiteElement, LiteNode} from './lite/Element.js';
  26. import {LiteText, LiteComment} from './lite/Text.js';
  27. import {LiteList} from './lite/List.js';
  28. import {LiteWindow} from './lite/Window.js';
  29. import {LiteParser} from './lite/Parser.js';
  30. import {Styles} from '../util/Styles.js';
  31. import {OptionList} from '../util/Options.js';
  32. /************************************************************/
  33. /**
  34. * Implements a lightweight DOMAdaptor on liteweight HTML elements
  35. */
  36. export class LiteBase extends AbstractDOMAdaptor<LiteElement, LiteText, LiteDocument> {
  37. /**
  38. * The document in which the HTML nodes will be created
  39. */
  40. public document: LiteDocument;
  41. /**
  42. * The window for the document
  43. */
  44. public window: LiteWindow;
  45. /**
  46. * The parser for serialized HTML
  47. */
  48. public parser: LiteParser;
  49. /**
  50. * @param {OptionList} options The options for the lite adaptor (e.g., fontSize)
  51. * @constructor
  52. */
  53. constructor() {
  54. super();
  55. this.parser = new LiteParser();
  56. this.window = new LiteWindow();
  57. }
  58. /**
  59. * @override
  60. */
  61. public parse(text: string, format?: string): LiteDocument {
  62. return this.parser.parseFromString(text, format, this);
  63. }
  64. /**
  65. * @override
  66. */
  67. protected create(kind: string, _ns: string = null) {
  68. return new LiteElement(kind);
  69. }
  70. /**
  71. * @override
  72. */
  73. public text(text: string) {
  74. return new LiteText(text);
  75. }
  76. /**
  77. * @param {string} text The text of the comment
  78. * @return {LiteComment} The comment node
  79. */
  80. public comment(text: string): LiteComment {
  81. return new LiteComment(text);
  82. }
  83. /**
  84. * @return {LiteDocument} A new document element
  85. */
  86. public createDocument(): LiteDocument {
  87. return new LiteDocument();
  88. }
  89. /**
  90. * @override
  91. */
  92. public head(doc: LiteDocument) {
  93. return doc.head;
  94. }
  95. /**
  96. * @override
  97. */
  98. public body(doc: LiteDocument) {
  99. return doc.body;
  100. }
  101. /**
  102. * @override
  103. */
  104. public root(doc: LiteDocument) {
  105. return doc.root;
  106. }
  107. /**
  108. * @override
  109. */
  110. public doctype(doc: LiteDocument) {
  111. return doc.type;
  112. }
  113. /**
  114. * @override
  115. */
  116. public tags(node: LiteElement, name: string, ns: string = null) {
  117. let stack = [] as LiteNode[];
  118. let tags = [] as LiteElement[];
  119. if (ns) {
  120. return tags; // we don't have namespaces
  121. }
  122. let n: LiteNode = node;
  123. while (n) {
  124. let kind = n.kind;
  125. if (kind !== '#text' && kind !== '#comment') {
  126. n = n as LiteElement;
  127. if (kind === name) {
  128. tags.push(n);
  129. }
  130. if (n.children.length) {
  131. stack = n.children.concat(stack);
  132. }
  133. }
  134. n = stack.shift();
  135. }
  136. return tags;
  137. }
  138. /**
  139. * @param {LiteElement} node The node to be searched
  140. * @param {string} id The id of the node to look for
  141. * @return {LiteElement} The child node having the given id
  142. */
  143. public elementById(node: LiteElement, id: string): LiteElement {
  144. let stack = [] as LiteNode[];
  145. let n = node as LiteNode;
  146. while (n) {
  147. if (n.kind !== '#text' && n.kind !== '#comment') {
  148. n = n as LiteElement;
  149. if (n.attributes['id'] === id) {
  150. return n;
  151. }
  152. if (n.children.length) {
  153. stack = n.children.concat(stack);
  154. }
  155. }
  156. n = stack.shift();
  157. }
  158. return null;
  159. }
  160. /**
  161. * @param {LiteElement} node The node to be searched
  162. * @param {string} name The name of the class to find
  163. * @return {LiteElement[]} The nodes with the given class
  164. */
  165. public elementsByClass(node: LiteElement, name: string): LiteElement[] {
  166. let stack = [] as LiteNode[];
  167. let tags = [] as LiteElement[];
  168. let n: LiteNode = node;
  169. while (n) {
  170. if (n.kind !== '#text' && n.kind !== '#comment') {
  171. n = n as LiteElement;
  172. const classes = (n.attributes['class'] || '').trim().split(/ +/);
  173. if (classes.includes(name)) {
  174. tags.push(n);
  175. }
  176. if (n.children.length) {
  177. stack = n.children.concat(stack);
  178. }
  179. }
  180. n = stack.shift();
  181. }
  182. return tags;
  183. }
  184. /**
  185. * @override
  186. */
  187. public getElements(nodes: (string | LiteElement | LiteElement[])[], document: LiteDocument) {
  188. let containers = [] as LiteElement[];
  189. const body = this.body(document);
  190. for (const node of nodes) {
  191. if (typeof(node) === 'string') {
  192. if (node.charAt(0) === '#') {
  193. const n = this.elementById(body, node.slice(1));
  194. if (n) {
  195. containers.push(n);
  196. }
  197. } else if (node.charAt(0) === '.') {
  198. containers = containers.concat(this.elementsByClass(body, node.slice(1)));
  199. } else if (node.match(/^[-a-z][-a-z0-9]*$/i)) {
  200. containers = containers.concat(this.tags(body, node));
  201. }
  202. } else if (Array.isArray(node)) {
  203. containers = containers.concat(node);
  204. } else if (node instanceof this.window.NodeList || node instanceof this.window.HTMLCollection) {
  205. containers = containers.concat((node as LiteList<LiteElement>).nodes);
  206. } else {
  207. containers.push(node);
  208. }
  209. }
  210. return containers;
  211. }
  212. /**
  213. * @override
  214. */
  215. public contains(container: LiteNode, node: LiteNode | LiteText) {
  216. while (node && node !== container) {
  217. node = this.parent(node);
  218. }
  219. return !!node;
  220. }
  221. /**
  222. * @override
  223. */
  224. public parent(node: LiteNode) {
  225. return node.parent;
  226. }
  227. /**
  228. * @param {LiteNode} node The node whose index is needed
  229. * @return {number} The index of the node it its parent's children array
  230. */
  231. public childIndex(node: LiteNode): number {
  232. return (node.parent ? node.parent.children.findIndex(n => n === node) : -1);
  233. }
  234. /**
  235. * @override
  236. */
  237. public append(node: LiteElement, child: LiteNode) {
  238. if (child.parent) {
  239. this.remove(child);
  240. }
  241. node.children.push(child);
  242. child.parent = node;
  243. return child;
  244. }
  245. /**
  246. * @override
  247. */
  248. public insert(nchild: LiteNode, ochild: LiteNode) {
  249. if (nchild.parent) {
  250. this.remove(nchild);
  251. }
  252. if (ochild && ochild.parent) {
  253. const i = this.childIndex(ochild);
  254. ochild.parent.children.splice(i, 0, nchild);
  255. nchild.parent = ochild.parent;
  256. }
  257. }
  258. /**
  259. * @override
  260. */
  261. public remove(child: LiteNode) {
  262. const i = this.childIndex(child);
  263. if (i >= 0) {
  264. child.parent.children.splice(i, 1);
  265. }
  266. child.parent = null;
  267. return child;
  268. }
  269. /**
  270. * @override
  271. */
  272. public replace(nnode: LiteNode, onode: LiteNode) {
  273. const i = this.childIndex(onode);
  274. if (i >= 0) {
  275. onode.parent.children[i] = nnode;
  276. nnode.parent = onode.parent;
  277. onode.parent = null;
  278. }
  279. return onode;
  280. }
  281. /**
  282. * @override
  283. */
  284. public clone(node: LiteElement) {
  285. const nnode = new LiteElement(node.kind);
  286. nnode.attributes = {...node.attributes};
  287. nnode.children = node.children.map(n => {
  288. if (n.kind === '#text') {
  289. return new LiteText((n as LiteText).value);
  290. } else if (n.kind === '#comment') {
  291. return new LiteComment((n as LiteComment).value);
  292. } else {
  293. const m = this.clone(n as LiteElement);
  294. m.parent = nnode;
  295. return m;
  296. }
  297. });
  298. return nnode;
  299. }
  300. /**
  301. * @override
  302. */
  303. public split(node: LiteText, n: number) {
  304. const text = new LiteText(node.value.slice(n));
  305. node.value = node.value.slice(0, n);
  306. node.parent.children.splice(this.childIndex(node) + 1, 0, text);
  307. text.parent = node.parent;
  308. return text;
  309. }
  310. /**
  311. * @override
  312. */
  313. public next(node: LiteNode) {
  314. const parent = node.parent;
  315. if (!parent) return null;
  316. const i = this.childIndex(node) + 1;
  317. return (i >= 0 && i < parent.children.length ? parent.children[i] : null);
  318. }
  319. /**
  320. * @override
  321. */
  322. public previous(node: LiteNode) {
  323. const parent = node.parent;
  324. if (!parent) return null;
  325. const i = this.childIndex(node) - 1;
  326. return (i >= 0 ? parent.children[i] : null);
  327. }
  328. /**
  329. * @override
  330. */
  331. public firstChild(node: LiteElement) {
  332. return node.children[0];
  333. }
  334. /**
  335. * @override
  336. */
  337. public lastChild(node: LiteElement) {
  338. return node.children[node.children.length - 1];
  339. }
  340. /**
  341. * @override
  342. */
  343. public childNodes(node: LiteElement) {
  344. return [...node.children];
  345. }
  346. /**
  347. * @override
  348. */
  349. public childNode(node: LiteElement, i: number) {
  350. return node.children[i];
  351. }
  352. /**
  353. * @override
  354. */
  355. public kind(node: LiteNode) {
  356. return node.kind;
  357. }
  358. /**
  359. * @override
  360. */
  361. public value(node: LiteNode | LiteText) {
  362. return (node.kind === '#text' ? (node as LiteText).value :
  363. node.kind === '#comment' ? (node as LiteComment).value.replace(/^<!(--)?((?:.|\n)*)\1>$/, '$2') : '');
  364. }
  365. /**
  366. * @override
  367. */
  368. public textContent(node: LiteElement): string {
  369. return node.children.reduce((s: string, n: LiteNode) => {
  370. return s + (n.kind === '#text' ? (n as LiteText).value :
  371. n.kind === '#comment' ? '' : this.textContent(n as LiteElement));
  372. }, '');
  373. }
  374. /**
  375. * @override
  376. */
  377. public innerHTML(node: LiteElement): string {
  378. return this.parser.serializeInner(this, node);
  379. }
  380. /**
  381. * @override
  382. */
  383. public outerHTML(node: LiteElement): string {
  384. return this.parser.serialize(this, node);
  385. }
  386. /**
  387. * @override
  388. */
  389. public serializeXML(node: LiteElement): string {
  390. return this.parser.serialize(this, node, true);
  391. }
  392. /**
  393. * @override
  394. */
  395. public setAttribute(node: LiteElement, name: string, value: string | number, ns: string = null) {
  396. if (typeof value !== 'string') {
  397. value = String(value);
  398. }
  399. if (ns) {
  400. name = ns.replace(/.*\//, '') + ':' + name.replace(/^.*:/, '');
  401. }
  402. node.attributes[name] = value;
  403. if (name === 'style') {
  404. node.styles = null;
  405. }
  406. }
  407. /**
  408. * @override
  409. */
  410. public getAttribute(node: LiteElement, name: string) {
  411. return node.attributes[name];
  412. }
  413. /**
  414. * @override
  415. */
  416. public removeAttribute(node: LiteElement, name: string) {
  417. delete node.attributes[name];
  418. }
  419. /**
  420. * @override
  421. */
  422. public hasAttribute(node: LiteElement, name: string) {
  423. return node.attributes.hasOwnProperty(name);
  424. }
  425. /**
  426. * @override
  427. */
  428. public allAttributes(node: LiteElement) {
  429. const attributes = node.attributes;
  430. const list = [];
  431. for (const name of Object.keys(attributes)) {
  432. list.push({name: name, value: attributes[name] as string});
  433. }
  434. return list;
  435. }
  436. /**
  437. * @override
  438. */
  439. public addClass(node: LiteElement, name: string) {
  440. const classes = (node.attributes['class'] as string || '').split(/ /);
  441. if (!classes.find(n => n === name)) {
  442. classes.push(name);
  443. node.attributes['class'] = classes.join(' ');
  444. }
  445. }
  446. /**
  447. * @override
  448. */
  449. public removeClass(node: LiteElement, name: string) {
  450. const classes = (node.attributes['class'] as string || '').split(/ /);
  451. const i = classes.findIndex(n => n === name);
  452. if (i >= 0) {
  453. classes.splice(i, 1);
  454. node.attributes['class'] = classes.join(' ');
  455. }
  456. }
  457. /**
  458. * @override
  459. */
  460. public hasClass(node: LiteElement, name: string) {
  461. const classes = (node.attributes['class'] as string || '').split(/ /);
  462. return !!classes.find(n => n === name);
  463. }
  464. /**
  465. * @override
  466. */
  467. public setStyle(node: LiteElement, name: string, value: string) {
  468. if (!node.styles) {
  469. node.styles = new Styles(this.getAttribute(node, 'style'));
  470. }
  471. node.styles.set(name, value);
  472. node.attributes['style'] = node.styles.cssText;
  473. }
  474. /**
  475. * @override
  476. */
  477. public getStyle(node: LiteElement, name: string) {
  478. if (!node.styles) {
  479. const style = this.getAttribute(node, 'style');
  480. if (!style) {
  481. return '';
  482. }
  483. node.styles = new Styles(style);
  484. }
  485. return node.styles.get(name);
  486. }
  487. /**
  488. * @override
  489. */
  490. public allStyles(node: LiteElement) {
  491. return this.getAttribute(node, 'style');
  492. }
  493. /**
  494. * @override
  495. */
  496. public insertRules(node: LiteElement, rules: string[]) {
  497. node.children = [this.text(rules.join('\n\n') + '\n\n' + this.textContent(node))];
  498. }
  499. /*******************************************************************/
  500. /*
  501. * The next four methods get overridden by the NodeMixin below
  502. */
  503. /**
  504. * @override
  505. */
  506. public fontSize(_node: LiteElement) {
  507. return 0;
  508. }
  509. /**
  510. * @override
  511. */
  512. public fontFamily(_node: LiteElement) {
  513. return '';
  514. }
  515. /**
  516. * @override
  517. */
  518. public nodeSize(_node: LiteElement, _em: number = 1, _local: boolean = null) {
  519. return [0, 0] as [number, number];
  520. }
  521. /**
  522. * @override
  523. */
  524. public nodeBBox(_node: LiteElement) {
  525. return {left: 0, right: 0, top: 0, bottom: 0};
  526. }
  527. }
  528. /**
  529. * The LiteAdaptor class (add in the NodeMixin methods and options)
  530. */
  531. export class LiteAdaptor extends NodeMixin<LiteElement, LiteText, LiteDocument, Constructor<LiteBase>>(LiteBase) {}
  532. /************************************************************/
  533. /**
  534. * The function to call to obtain a LiteAdaptor
  535. *
  536. * @param {OptionList} options The options for the adaptor
  537. * @return {LiteAdaptor} The newly created adaptor
  538. */
  539. export function liteAdaptor(options: OptionList = null): LiteAdaptor {
  540. return new LiteAdaptor(null, options);
  541. }