jsAPI.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. 'use strict';
  2. const { selectAll, selectOne, is } = require('css-select');
  3. const svgoCssSelectAdapter = require('./css-select-adapter');
  4. const CSSClassList = require('./css-class-list');
  5. const CSSStyleDeclaration = require('./css-style-declaration');
  6. /**
  7. * @type {(name: string) => { prefix: string, local: string }}
  8. */
  9. const parseName = (name) => {
  10. if (name == null) {
  11. return {
  12. prefix: '',
  13. local: '',
  14. };
  15. }
  16. if (name === 'xmlns') {
  17. return {
  18. prefix: 'xmlns',
  19. local: '',
  20. };
  21. }
  22. const chunks = name.split(':');
  23. if (chunks.length === 1) {
  24. return {
  25. prefix: '',
  26. local: chunks[0],
  27. };
  28. }
  29. return {
  30. prefix: chunks[0],
  31. local: chunks[1],
  32. };
  33. };
  34. var cssSelectOpts = {
  35. xmlMode: true,
  36. adapter: svgoCssSelectAdapter,
  37. };
  38. const attrsHandler = {
  39. get: (attributes, name) => {
  40. // eslint-disable-next-line no-prototype-builtins
  41. if (attributes.hasOwnProperty(name)) {
  42. return {
  43. name,
  44. get value() {
  45. return attributes[name];
  46. },
  47. set value(value) {
  48. attributes[name] = value;
  49. },
  50. };
  51. }
  52. },
  53. set: (attributes, name, attr) => {
  54. attributes[name] = attr.value;
  55. return true;
  56. },
  57. };
  58. var JSAPI = function (data, parentNode) {
  59. Object.assign(this, data);
  60. if (this.type === 'element') {
  61. if (this.attributes == null) {
  62. this.attributes = {};
  63. }
  64. if (this.children == null) {
  65. this.children = [];
  66. }
  67. Object.defineProperty(this, 'class', {
  68. writable: true,
  69. configurable: true,
  70. value: new CSSClassList(this),
  71. });
  72. Object.defineProperty(this, 'style', {
  73. writable: true,
  74. configurable: true,
  75. value: new CSSStyleDeclaration(this),
  76. });
  77. Object.defineProperty(this, 'parentNode', {
  78. writable: true,
  79. value: parentNode,
  80. });
  81. // temporary attrs polyfill
  82. // TODO remove after migration
  83. const element = this;
  84. Object.defineProperty(this, 'attrs', {
  85. configurable: true,
  86. get() {
  87. return new Proxy(element.attributes, attrsHandler);
  88. },
  89. set(value) {
  90. const newAttributes = {};
  91. for (const attr of Object.values(value)) {
  92. newAttributes[attr.name] = attr.value;
  93. }
  94. element.attributes = newAttributes;
  95. },
  96. });
  97. }
  98. };
  99. module.exports = JSAPI;
  100. /**
  101. * Perform a deep clone of this node.
  102. *
  103. * @return {Object} element
  104. */
  105. JSAPI.prototype.clone = function () {
  106. const { children, ...nodeData } = this;
  107. // Deep-clone node data.
  108. const clonedNode = new JSAPI(JSON.parse(JSON.stringify(nodeData)), null);
  109. if (children) {
  110. clonedNode.children = children.map((child) => {
  111. const clonedChild = child.clone();
  112. clonedChild.parentNode = clonedNode;
  113. return clonedChild;
  114. });
  115. }
  116. return clonedNode;
  117. };
  118. /**
  119. * Determine if item is an element
  120. * (any, with a specific name or in a names array).
  121. *
  122. * @param {String|Array} [param] element name or names arrays
  123. * @return {Boolean}
  124. */
  125. JSAPI.prototype.isElem = function (param) {
  126. if (this.type !== 'element') {
  127. return false;
  128. }
  129. if (param == null) {
  130. return true;
  131. }
  132. if (Array.isArray(param)) {
  133. return param.includes(this.name);
  134. }
  135. return this.name === param;
  136. };
  137. /**
  138. * Renames an element
  139. *
  140. * @param {String} name new element name
  141. * @return {Object} element
  142. */
  143. JSAPI.prototype.renameElem = function (name) {
  144. if (name && typeof name === 'string') this.name = name;
  145. return this;
  146. };
  147. /**
  148. * Determine if element is empty.
  149. *
  150. * @return {Boolean}
  151. */
  152. JSAPI.prototype.isEmpty = function () {
  153. return !this.children || !this.children.length;
  154. };
  155. /**
  156. * Find the closest ancestor of the current element.
  157. * @param elemName
  158. *
  159. * @return {?Object}
  160. */
  161. JSAPI.prototype.closestElem = function (elemName) {
  162. var elem = this;
  163. while ((elem = elem.parentNode) && !elem.isElem(elemName));
  164. return elem;
  165. };
  166. /**
  167. * Changes children by removing elements and/or adding new elements.
  168. *
  169. * @param {Number} start Index at which to start changing the children.
  170. * @param {Number} n Number of elements to remove.
  171. * @param {Array|Object} [insertion] Elements to add to the children.
  172. * @return {Array} Removed elements.
  173. */
  174. JSAPI.prototype.spliceContent = function (start, n, insertion) {
  175. if (arguments.length < 2) return [];
  176. if (!Array.isArray(insertion))
  177. insertion = Array.apply(null, arguments).slice(2);
  178. insertion.forEach(function (inner) {
  179. inner.parentNode = this;
  180. }, this);
  181. return this.children.splice.apply(
  182. this.children,
  183. [start, n].concat(insertion)
  184. );
  185. };
  186. /**
  187. * Determine if element has an attribute
  188. * (any, or by name or by name + value).
  189. *
  190. * @param {String} [name] attribute name
  191. * @param {String} [val] attribute value (will be toString()'ed)
  192. * @return {Boolean}
  193. */
  194. JSAPI.prototype.hasAttr = function (name, val) {
  195. if (this.type !== 'element') {
  196. return false;
  197. }
  198. if (Object.keys(this.attributes).length === 0) {
  199. return false;
  200. }
  201. if (name == null) {
  202. return true;
  203. }
  204. // eslint-disable-next-line no-prototype-builtins
  205. if (this.attributes.hasOwnProperty(name) === false) {
  206. return false;
  207. }
  208. if (val !== undefined) {
  209. return this.attributes[name] === val.toString();
  210. }
  211. return true;
  212. };
  213. /**
  214. * Determine if element has an attribute by local name
  215. * (any, or by name or by name + value).
  216. *
  217. * @param {String} [localName] local attribute name
  218. * @param {Number|String|RegExp|Function} [val] attribute value (will be toString()'ed or executed, otherwise ignored)
  219. * @return {Boolean}
  220. */
  221. JSAPI.prototype.hasAttrLocal = function (localName, val) {
  222. if (!this.attrs || !Object.keys(this.attrs).length) return false;
  223. if (!arguments.length) return !!this.attrs;
  224. var callback;
  225. switch (val != null && val.constructor && val.constructor.name) {
  226. case 'Number': // same as String
  227. case 'String':
  228. callback = stringValueTest;
  229. break;
  230. case 'RegExp':
  231. callback = regexpValueTest;
  232. break;
  233. case 'Function':
  234. callback = funcValueTest;
  235. break;
  236. default:
  237. callback = nameTest;
  238. }
  239. return this.someAttr(callback);
  240. function nameTest(attr) {
  241. const { local } = parseName(attr.name);
  242. return local === localName;
  243. }
  244. function stringValueTest(attr) {
  245. const { local } = parseName(attr.name);
  246. return local === localName && val == attr.value;
  247. }
  248. function regexpValueTest(attr) {
  249. const { local } = parseName(attr.name);
  250. return local === localName && val.test(attr.value);
  251. }
  252. function funcValueTest(attr) {
  253. const { local } = parseName(attr.name);
  254. return local === localName && val(attr.value);
  255. }
  256. };
  257. /**
  258. * Get a specific attribute from an element
  259. * (by name or name + value).
  260. *
  261. * @param {String} name attribute name
  262. * @param {String} [val] attribute value (will be toString()'ed)
  263. * @return {Object|Undefined}
  264. */
  265. JSAPI.prototype.attr = function (name, val) {
  266. if (this.hasAttr(name, val)) {
  267. return this.attrs[name];
  268. }
  269. };
  270. /**
  271. * Get computed attribute value from an element
  272. *
  273. * @param {String} name attribute name
  274. * @return {Object|Undefined}
  275. */
  276. JSAPI.prototype.computedAttr = function (name, val) {
  277. if (!arguments.length) return;
  278. for (
  279. var elem = this;
  280. elem && (!elem.hasAttr(name) || !elem.attributes[name]);
  281. elem = elem.parentNode
  282. );
  283. if (val != null) {
  284. return elem ? elem.hasAttr(name, val) : false;
  285. } else if (elem && elem.hasAttr(name)) {
  286. return elem.attributes[name];
  287. }
  288. };
  289. /**
  290. * Remove a specific attribute.
  291. *
  292. * @param {String|Array} name attribute name
  293. * @param {String} [val] attribute value
  294. * @return {Boolean}
  295. */
  296. JSAPI.prototype.removeAttr = function (name, val) {
  297. if (this.type !== 'element') {
  298. return false;
  299. }
  300. if (arguments.length === 0) {
  301. return false;
  302. }
  303. if (Array.isArray(name)) {
  304. for (const nameItem of name) {
  305. this.removeAttr(nameItem, val);
  306. }
  307. return false;
  308. }
  309. if (this.hasAttr(name, val) === false) {
  310. return false;
  311. }
  312. delete this.attributes[name];
  313. return true;
  314. };
  315. /**
  316. * Add attribute.
  317. *
  318. * @param {Object} [attr={}] attribute object
  319. * @return {Object|Boolean} created attribute or false if no attr was passed in
  320. */
  321. JSAPI.prototype.addAttr = function (attr) {
  322. attr = attr || {};
  323. if (attr.name === undefined) return false;
  324. this.attributes[attr.name] = attr.value;
  325. if (attr.name === 'class') {
  326. // newly added class attribute
  327. this.class.addClassValueHandler();
  328. }
  329. if (attr.name === 'style') {
  330. // newly added style attribute
  331. this.style.addStyleValueHandler();
  332. }
  333. return this.attrs[attr.name];
  334. };
  335. /**
  336. * Iterates over all attributes.
  337. *
  338. * @param {Function} callback callback
  339. * @param {Object} [context] callback context
  340. * @return {Boolean} false if there are no any attributes
  341. */
  342. JSAPI.prototype.eachAttr = function (callback, context) {
  343. if (this.type !== 'element') {
  344. return false;
  345. }
  346. if (callback == null) {
  347. return false;
  348. }
  349. for (const attr of Object.values(this.attrs)) {
  350. callback.call(context, attr);
  351. }
  352. return true;
  353. };
  354. /**
  355. * Tests whether some attribute passes the test.
  356. *
  357. * @param {Function} callback callback
  358. * @param {Object} [context] callback context
  359. * @return {Boolean} false if there are no any attributes
  360. */
  361. JSAPI.prototype.someAttr = function (callback, context) {
  362. if (this.type !== 'element') {
  363. return false;
  364. }
  365. for (const attr of Object.values(this.attrs)) {
  366. if (callback.call(context, attr)) return true;
  367. }
  368. return false;
  369. };
  370. /**
  371. * Evaluate a string of CSS selectors against the element and returns matched elements.
  372. *
  373. * @param {String} selectors CSS selector(s) string
  374. * @return {Array} null if no elements matched
  375. */
  376. JSAPI.prototype.querySelectorAll = function (selectors) {
  377. var matchedEls = selectAll(selectors, this, cssSelectOpts);
  378. return matchedEls.length > 0 ? matchedEls : null;
  379. };
  380. /**
  381. * Evaluate a string of CSS selectors against the element and returns only the first matched element.
  382. *
  383. * @param {String} selectors CSS selector(s) string
  384. * @return {Array} null if no element matched
  385. */
  386. JSAPI.prototype.querySelector = function (selectors) {
  387. return selectOne(selectors, this, cssSelectOpts);
  388. };
  389. /**
  390. * Test if a selector matches a given element.
  391. *
  392. * @param {String} selector CSS selector string
  393. * @return {Boolean} true if element would be selected by selector string, false if it does not
  394. */
  395. JSAPI.prototype.matches = function (selector) {
  396. return is(this, selector, cssSelectOpts);
  397. };