You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 26KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  1. 'use strict';
  2. var typeOf = require('kind-of');
  3. var utils = module.exports;
  4. /**
  5. * Returns true if the given value is a node.
  6. *
  7. * ```js
  8. * var Node = require('snapdragon-node');
  9. * var node = new Node({type: 'foo'});
  10. * console.log(utils.isNode(node)); //=> true
  11. * console.log(utils.isNode({})); //=> false
  12. * ```
  13. * @param {Object} `node` Instance of [snapdragon-node][]
  14. * @returns {Boolean}
  15. * @api public
  16. */
  17. utils.isNode = function(node) {
  18. return typeOf(node) === 'object' && node.isNode === true;
  19. };
  20. /**
  21. * Emit an empty string for the given `node`.
  22. *
  23. * ```js
  24. * // do nothing for beginning-of-string
  25. * snapdragon.compiler.set('bos', utils.noop);
  26. * ```
  27. * @param {Object} `node` Instance of [snapdragon-node][]
  28. * @returns {undefined}
  29. * @api public
  30. */
  31. utils.noop = function(node) {
  32. append(this, '', node);
  33. };
  34. /**
  35. * Appdend `node.val` to `compiler.output`, exactly as it was created
  36. * by the parser.
  37. *
  38. * ```js
  39. * snapdragon.compiler.set('text', utils.identity);
  40. * ```
  41. * @param {Object} `node` Instance of [snapdragon-node][]
  42. * @returns {undefined}
  43. * @api public
  44. */
  45. utils.identity = function(node) {
  46. append(this, node.val, node);
  47. };
  48. /**
  49. * Previously named `.emit`, this method appends the given `val`
  50. * to `compiler.output` for the given node. Useful when you know
  51. * what value should be appended advance, regardless of the actual
  52. * value of `node.val`.
  53. *
  54. * ```js
  55. * snapdragon.compiler
  56. * .set('i', function(node) {
  57. * this.mapVisit(node);
  58. * })
  59. * .set('i.open', utils.append('<i>'))
  60. * .set('i.close', utils.append('</i>'))
  61. * ```
  62. * @param {Object} `node` Instance of [snapdragon-node][]
  63. * @returns {Function} Returns a compiler middleware function.
  64. * @api public
  65. */
  66. utils.append = function(val) {
  67. return function(node) {
  68. append(this, val, node);
  69. };
  70. };
  71. /**
  72. * Used in compiler middleware, this onverts an AST node into
  73. * an empty `text` node and deletes `node.nodes` if it exists.
  74. * The advantage of this method is that, as opposed to completely
  75. * removing the node, indices will not need to be re-calculated
  76. * in sibling nodes, and nothing is appended to the output.
  77. *
  78. * ```js
  79. * utils.toNoop(node);
  80. * // convert `node.nodes` to the given value instead of deleting it
  81. * utils.toNoop(node, []);
  82. * ```
  83. * @param {Object} `node` Instance of [snapdragon-node][]
  84. * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array.
  85. * @api public
  86. */
  87. utils.toNoop = function(node, nodes) {
  88. if (nodes) {
  89. node.nodes = nodes;
  90. } else {
  91. delete node.nodes;
  92. node.type = 'text';
  93. node.val = '';
  94. }
  95. };
  96. /**
  97. * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon
  98. * automatically calls registered compilers, this allows you to pass a visitor
  99. * function.
  100. *
  101. * ```js
  102. * snapdragon.compiler.set('i', function(node) {
  103. * utils.visit(node, function(childNode) {
  104. * // do stuff with "childNode"
  105. * return childNode;
  106. * });
  107. * });
  108. * ```
  109. * @param {Object} `node` Instance of [snapdragon-node][]
  110. * @param {Function} `fn`
  111. * @return {Object} returns the node after recursively visiting all child nodes.
  112. * @api public
  113. */
  114. utils.visit = function(node, fn) {
  115. assert(utils.isNode(node), 'expected node to be an instance of Node');
  116. assert(isFunction(fn), 'expected a visitor function');
  117. fn(node);
  118. return node.nodes ? utils.mapVisit(node, fn) : node;
  119. };
  120. /**
  121. * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by
  122. * [visit](#visit), use this method if you do not want `fn` to be called on
  123. * the first node.
  124. *
  125. * ```js
  126. * snapdragon.compiler.set('i', function(node) {
  127. * utils.mapVisit(node, function(childNode) {
  128. * // do stuff with "childNode"
  129. * return childNode;
  130. * });
  131. * });
  132. * ```
  133. * @param {Object} `node` Instance of [snapdragon-node][]
  134. * @param {Object} `options`
  135. * @param {Function} `fn`
  136. * @return {Object} returns the node
  137. * @api public
  138. */
  139. utils.mapVisit = function(node, fn) {
  140. assert(utils.isNode(node), 'expected node to be an instance of Node');
  141. assert(isArray(node.nodes), 'expected node.nodes to be an array');
  142. assert(isFunction(fn), 'expected a visitor function');
  143. for (var i = 0; i < node.nodes.length; i++) {
  144. utils.visit(node.nodes[i], fn);
  145. }
  146. return node;
  147. };
  148. /**
  149. * Unshift an `*.open` node onto `node.nodes`.
  150. *
  151. * ```js
  152. * var Node = require('snapdragon-node');
  153. * snapdragon.parser.set('brace', function(node) {
  154. * var match = this.match(/^{/);
  155. * if (match) {
  156. * var parent = new Node({type: 'brace'});
  157. * utils.addOpen(parent, Node);
  158. * console.log(parent.nodes[0]):
  159. * // { type: 'brace.open', val: '' };
  160. *
  161. * // push the parent "brace" node onto the stack
  162. * this.push(parent);
  163. *
  164. * // return the parent node, so it's also added to the AST
  165. * return brace;
  166. * }
  167. * });
  168. * ```
  169. * @param {Object} `node` Instance of [snapdragon-node][]
  170. * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
  171. * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
  172. * @return {Object} Returns the created opening node.
  173. * @api public
  174. */
  175. utils.addOpen = function(node, Node, val, filter) {
  176. assert(utils.isNode(node), 'expected node to be an instance of Node');
  177. assert(isFunction(Node), 'expected Node to be a constructor function');
  178. if (typeof val === 'function') {
  179. filter = val;
  180. val = '';
  181. }
  182. if (typeof filter === 'function' && !filter(node)) return;
  183. var open = new Node({ type: node.type + '.open', val: val});
  184. var unshift = node.unshift || node.unshiftNode;
  185. if (typeof unshift === 'function') {
  186. unshift.call(node, open);
  187. } else {
  188. utils.unshiftNode(node, open);
  189. }
  190. return open;
  191. };
  192. /**
  193. * Push a `*.close` node onto `node.nodes`.
  194. *
  195. * ```js
  196. * var Node = require('snapdragon-node');
  197. * snapdragon.parser.set('brace', function(node) {
  198. * var match = this.match(/^}/);
  199. * if (match) {
  200. * var parent = this.parent();
  201. * if (parent.type !== 'brace') {
  202. * throw new Error('missing opening: ' + '}');
  203. * }
  204. *
  205. * utils.addClose(parent, Node);
  206. * console.log(parent.nodes[parent.nodes.length - 1]):
  207. * // { type: 'brace.close', val: '' };
  208. *
  209. * // no need to return a node, since the parent
  210. * // was already added to the AST
  211. * return;
  212. * }
  213. * });
  214. * ```
  215. * @param {Object} `node` Instance of [snapdragon-node][]
  216. * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
  217. * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
  218. * @return {Object} Returns the created closing node.
  219. * @api public
  220. */
  221. utils.addClose = function(node, Node, val, filter) {
  222. assert(utils.isNode(node), 'expected node to be an instance of Node');
  223. assert(isFunction(Node), 'expected Node to be a constructor function');
  224. if (typeof val === 'function') {
  225. filter = val;
  226. val = '';
  227. }
  228. if (typeof filter === 'function' && !filter(node)) return;
  229. var close = new Node({ type: node.type + '.close', val: val});
  230. var push = node.push || node.pushNode;
  231. if (typeof push === 'function') {
  232. push.call(node, close);
  233. } else {
  234. utils.pushNode(node, close);
  235. }
  236. return close;
  237. };
  238. /**
  239. * Wraps the given `node` with `*.open` and `*.close` nodes.
  240. *
  241. * @param {Object} `node` Instance of [snapdragon-node][]
  242. * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
  243. * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
  244. * @return {Object} Returns the node
  245. * @api public
  246. */
  247. utils.wrapNodes = function(node, Node, filter) {
  248. assert(utils.isNode(node), 'expected node to be an instance of Node');
  249. assert(isFunction(Node), 'expected Node to be a constructor function');
  250. utils.addOpen(node, Node, filter);
  251. utils.addClose(node, Node, filter);
  252. return node;
  253. };
  254. /**
  255. * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent.
  256. *
  257. * ```js
  258. * var parent = new Node({type: 'foo'});
  259. * var node = new Node({type: 'bar'});
  260. * utils.pushNode(parent, node);
  261. * console.log(parent.nodes[0].type) // 'bar'
  262. * console.log(node.parent.type) // 'foo'
  263. * ```
  264. * @param {Object} `parent`
  265. * @param {Object} `node` Instance of [snapdragon-node][]
  266. * @return {Object} Returns the child node
  267. * @api public
  268. */
  269. utils.pushNode = function(parent, node) {
  270. assert(utils.isNode(parent), 'expected parent node to be an instance of Node');
  271. assert(utils.isNode(node), 'expected node to be an instance of Node');
  272. node.define('parent', parent);
  273. parent.nodes = parent.nodes || [];
  274. parent.nodes.push(node);
  275. return node;
  276. };
  277. /**
  278. * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent.
  279. *
  280. * ```js
  281. * var parent = new Node({type: 'foo'});
  282. * var node = new Node({type: 'bar'});
  283. * utils.unshiftNode(parent, node);
  284. * console.log(parent.nodes[0].type) // 'bar'
  285. * console.log(node.parent.type) // 'foo'
  286. * ```
  287. * @param {Object} `parent`
  288. * @param {Object} `node` Instance of [snapdragon-node][]
  289. * @return {undefined}
  290. * @api public
  291. */
  292. utils.unshiftNode = function(parent, node) {
  293. assert(utils.isNode(parent), 'expected parent node to be an instance of Node');
  294. assert(utils.isNode(node), 'expected node to be an instance of Node');
  295. node.define('parent', parent);
  296. parent.nodes = parent.nodes || [];
  297. parent.nodes.unshift(node);
  298. };
  299. /**
  300. * Pop the last `node` off of `parent.nodes`. The advantage of
  301. * using this method is that it checks for `node.nodes` and works
  302. * with any version of `snapdragon-node`.
  303. *
  304. * ```js
  305. * var parent = new Node({type: 'foo'});
  306. * utils.pushNode(parent, new Node({type: 'foo'}));
  307. * utils.pushNode(parent, new Node({type: 'bar'}));
  308. * utils.pushNode(parent, new Node({type: 'baz'}));
  309. * console.log(parent.nodes.length); //=> 3
  310. * utils.popNode(parent);
  311. * console.log(parent.nodes.length); //=> 2
  312. * ```
  313. * @param {Object} `parent`
  314. * @param {Object} `node` Instance of [snapdragon-node][]
  315. * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.
  316. * @api public
  317. */
  318. utils.popNode = function(node) {
  319. assert(utils.isNode(node), 'expected node to be an instance of Node');
  320. if (typeof node.pop === 'function') {
  321. return node.pop();
  322. }
  323. return node.nodes && node.nodes.pop();
  324. };
  325. /**
  326. * Shift the first `node` off of `parent.nodes`. The advantage of
  327. * using this method is that it checks for `node.nodes` and works
  328. * with any version of `snapdragon-node`.
  329. *
  330. * ```js
  331. * var parent = new Node({type: 'foo'});
  332. * utils.pushNode(parent, new Node({type: 'foo'}));
  333. * utils.pushNode(parent, new Node({type: 'bar'}));
  334. * utils.pushNode(parent, new Node({type: 'baz'}));
  335. * console.log(parent.nodes.length); //=> 3
  336. * utils.shiftNode(parent);
  337. * console.log(parent.nodes.length); //=> 2
  338. * ```
  339. * @param {Object} `parent`
  340. * @param {Object} `node` Instance of [snapdragon-node][]
  341. * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.
  342. * @api public
  343. */
  344. utils.shiftNode = function(node) {
  345. assert(utils.isNode(node), 'expected node to be an instance of Node');
  346. if (typeof node.shift === 'function') {
  347. return node.shift();
  348. }
  349. return node.nodes && node.nodes.shift();
  350. };
  351. /**
  352. * Remove the specified `node` from `parent.nodes`.
  353. *
  354. * ```js
  355. * var parent = new Node({type: 'abc'});
  356. * var foo = new Node({type: 'foo'});
  357. * utils.pushNode(parent, foo);
  358. * utils.pushNode(parent, new Node({type: 'bar'}));
  359. * utils.pushNode(parent, new Node({type: 'baz'}));
  360. * console.log(parent.nodes.length); //=> 3
  361. * utils.removeNode(parent, foo);
  362. * console.log(parent.nodes.length); //=> 2
  363. * ```
  364. * @param {Object} `parent`
  365. * @param {Object} `node` Instance of [snapdragon-node][]
  366. * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`.
  367. * @api public
  368. */
  369. utils.removeNode = function(parent, node) {
  370. assert(utils.isNode(parent), 'expected parent.node to be an instance of Node');
  371. assert(utils.isNode(node), 'expected node to be an instance of Node');
  372. if (!parent.nodes) {
  373. return null;
  374. }
  375. if (typeof parent.remove === 'function') {
  376. return parent.remove(node);
  377. }
  378. var idx = parent.nodes.indexOf(node);
  379. if (idx !== -1) {
  380. return parent.nodes.splice(idx, 1);
  381. }
  382. };
  383. /**
  384. * Returns true if `node.type` matches the given `type`. Throws a
  385. * `TypeError` if `node` is not an instance of `Node`.
  386. *
  387. * ```js
  388. * var Node = require('snapdragon-node');
  389. * var node = new Node({type: 'foo'});
  390. * console.log(utils.isType(node, 'foo')); // false
  391. * console.log(utils.isType(node, 'bar')); // true
  392. * ```
  393. * @param {Object} `node` Instance of [snapdragon-node][]
  394. * @param {String} `type`
  395. * @return {Boolean}
  396. * @api public
  397. */
  398. utils.isType = function(node, type) {
  399. assert(utils.isNode(node), 'expected node to be an instance of Node');
  400. switch (typeOf(type)) {
  401. case 'array':
  402. var types = type.slice();
  403. for (var i = 0; i < types.length; i++) {
  404. if (utils.isType(node, types[i])) {
  405. return true;
  406. }
  407. }
  408. return false;
  409. case 'string':
  410. return node.type === type;
  411. case 'regexp':
  412. return type.test(node.type);
  413. default: {
  414. throw new TypeError('expected "type" to be an array, string or regexp');
  415. }
  416. }
  417. };
  418. /**
  419. * Returns true if the given `node` has the given `type` in `node.nodes`.
  420. * Throws a `TypeError` if `node` is not an instance of `Node`.
  421. *
  422. * ```js
  423. * var Node = require('snapdragon-node');
  424. * var node = new Node({
  425. * type: 'foo',
  426. * nodes: [
  427. * new Node({type: 'bar'}),
  428. * new Node({type: 'baz'})
  429. * ]
  430. * });
  431. * console.log(utils.hasType(node, 'xyz')); // false
  432. * console.log(utils.hasType(node, 'baz')); // true
  433. * ```
  434. * @param {Object} `node` Instance of [snapdragon-node][]
  435. * @param {String} `type`
  436. * @return {Boolean}
  437. * @api public
  438. */
  439. utils.hasType = function(node, type) {
  440. assert(utils.isNode(node), 'expected node to be an instance of Node');
  441. if (!Array.isArray(node.nodes)) return false;
  442. for (var i = 0; i < node.nodes.length; i++) {
  443. if (utils.isType(node.nodes[i], type)) {
  444. return true;
  445. }
  446. }
  447. return false;
  448. };
  449. /**
  450. * Returns the first node from `node.nodes` of the given `type`
  451. *
  452. * ```js
  453. * var node = new Node({
  454. * type: 'foo',
  455. * nodes: [
  456. * new Node({type: 'text', val: 'abc'}),
  457. * new Node({type: 'text', val: 'xyz'})
  458. * ]
  459. * });
  460. *
  461. * var textNode = utils.firstOfType(node.nodes, 'text');
  462. * console.log(textNode.val);
  463. * //=> 'abc'
  464. * ```
  465. * @param {Array} `nodes`
  466. * @param {String} `type`
  467. * @return {Object|undefined} Returns the first matching node or undefined.
  468. * @api public
  469. */
  470. utils.firstOfType = function(nodes, type) {
  471. for (var i = 0; i < nodes.length; i++) {
  472. var node = nodes[i];
  473. if (utils.isType(node, type)) {
  474. return node;
  475. }
  476. }
  477. };
  478. /**
  479. * Returns the node at the specified index, or the first node of the
  480. * given `type` from `node.nodes`.
  481. *
  482. * ```js
  483. * var node = new Node({
  484. * type: 'foo',
  485. * nodes: [
  486. * new Node({type: 'text', val: 'abc'}),
  487. * new Node({type: 'text', val: 'xyz'})
  488. * ]
  489. * });
  490. *
  491. * var nodeOne = utils.findNode(node.nodes, 'text');
  492. * console.log(nodeOne.val);
  493. * //=> 'abc'
  494. *
  495. * var nodeTwo = utils.findNode(node.nodes, 1);
  496. * console.log(nodeTwo.val);
  497. * //=> 'xyz'
  498. * ```
  499. *
  500. * @param {Array} `nodes`
  501. * @param {String|Number} `type` Node type or index.
  502. * @return {Object} Returns a node or undefined.
  503. * @api public
  504. */
  505. utils.findNode = function(nodes, type) {
  506. if (!Array.isArray(nodes)) {
  507. return null;
  508. }
  509. if (typeof type === 'number') {
  510. return nodes[type];
  511. }
  512. return utils.firstOfType(nodes, type);
  513. };
  514. /**
  515. * Returns true if the given node is an "*.open" node.
  516. *
  517. * ```js
  518. * var Node = require('snapdragon-node');
  519. * var brace = new Node({type: 'brace'});
  520. * var open = new Node({type: 'brace.open'});
  521. * var close = new Node({type: 'brace.close'});
  522. *
  523. * console.log(utils.isOpen(brace)); // false
  524. * console.log(utils.isOpen(open)); // true
  525. * console.log(utils.isOpen(close)); // false
  526. * ```
  527. * @param {Object} `node` Instance of [snapdragon-node][]
  528. * @return {Boolean}
  529. * @api public
  530. */
  531. utils.isOpen = function(node) {
  532. assert(utils.isNode(node), 'expected node to be an instance of Node');
  533. return node.type.slice(-5) === '.open';
  534. };
  535. /**
  536. * Returns true if the given node is a "*.close" node.
  537. *
  538. * ```js
  539. * var Node = require('snapdragon-node');
  540. * var brace = new Node({type: 'brace'});
  541. * var open = new Node({type: 'brace.open'});
  542. * var close = new Node({type: 'brace.close'});
  543. *
  544. * console.log(utils.isClose(brace)); // false
  545. * console.log(utils.isClose(open)); // false
  546. * console.log(utils.isClose(close)); // true
  547. * ```
  548. * @param {Object} `node` Instance of [snapdragon-node][]
  549. * @return {Boolean}
  550. * @api public
  551. */
  552. utils.isClose = function(node) {
  553. assert(utils.isNode(node), 'expected node to be an instance of Node');
  554. return node.type.slice(-6) === '.close';
  555. };
  556. /**
  557. * Returns true if `node.nodes` **has** an `.open` node
  558. *
  559. * ```js
  560. * var Node = require('snapdragon-node');
  561. * var brace = new Node({
  562. * type: 'brace',
  563. * nodes: []
  564. * });
  565. *
  566. * var open = new Node({type: 'brace.open'});
  567. * console.log(utils.hasOpen(brace)); // false
  568. *
  569. * brace.pushNode(open);
  570. * console.log(utils.hasOpen(brace)); // true
  571. * ```
  572. * @param {Object} `node` Instance of [snapdragon-node][]
  573. * @return {Boolean}
  574. * @api public
  575. */
  576. utils.hasOpen = function(node) {
  577. assert(utils.isNode(node), 'expected node to be an instance of Node');
  578. var first = node.first || node.nodes ? node.nodes[0] : null;
  579. if (utils.isNode(first)) {
  580. return first.type === node.type + '.open';
  581. }
  582. return false;
  583. };
  584. /**
  585. * Returns true if `node.nodes` **has** a `.close` node
  586. *
  587. * ```js
  588. * var Node = require('snapdragon-node');
  589. * var brace = new Node({
  590. * type: 'brace',
  591. * nodes: []
  592. * });
  593. *
  594. * var close = new Node({type: 'brace.close'});
  595. * console.log(utils.hasClose(brace)); // false
  596. *
  597. * brace.pushNode(close);
  598. * console.log(utils.hasClose(brace)); // true
  599. * ```
  600. * @param {Object} `node` Instance of [snapdragon-node][]
  601. * @return {Boolean}
  602. * @api public
  603. */
  604. utils.hasClose = function(node) {
  605. assert(utils.isNode(node), 'expected node to be an instance of Node');
  606. var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null;
  607. if (utils.isNode(last)) {
  608. return last.type === node.type + '.close';
  609. }
  610. return false;
  611. };
  612. /**
  613. * Returns true if `node.nodes` has both `.open` and `.close` nodes
  614. *
  615. * ```js
  616. * var Node = require('snapdragon-node');
  617. * var brace = new Node({
  618. * type: 'brace',
  619. * nodes: []
  620. * });
  621. *
  622. * var open = new Node({type: 'brace.open'});
  623. * var close = new Node({type: 'brace.close'});
  624. * console.log(utils.hasOpen(brace)); // false
  625. * console.log(utils.hasClose(brace)); // false
  626. *
  627. * brace.pushNode(open);
  628. * brace.pushNode(close);
  629. * console.log(utils.hasOpen(brace)); // true
  630. * console.log(utils.hasClose(brace)); // true
  631. * ```
  632. * @param {Object} `node` Instance of [snapdragon-node][]
  633. * @return {Boolean}
  634. * @api public
  635. */
  636. utils.hasOpenAndClose = function(node) {
  637. return utils.hasOpen(node) && utils.hasClose(node);
  638. };
  639. /**
  640. * Push the given `node` onto the `state.inside` array for the
  641. * given type. This array is used as a specialized "stack" for
  642. * only the given `node.type`.
  643. *
  644. * ```js
  645. * var state = { inside: {}};
  646. * var node = new Node({type: 'brace'});
  647. * utils.addType(state, node);
  648. * console.log(state.inside);
  649. * //=> { brace: [{type: 'brace'}] }
  650. * ```
  651. * @param {Object} `state` The `compiler.state` object or custom state object.
  652. * @param {Object} `node` Instance of [snapdragon-node][]
  653. * @return {Array} Returns the `state.inside` stack for the given type.
  654. * @api public
  655. */
  656. utils.addType = function(state, node) {
  657. assert(utils.isNode(node), 'expected node to be an instance of Node');
  658. assert(isObject(state), 'expected state to be an object');
  659. var type = node.parent
  660. ? node.parent.type
  661. : node.type.replace(/\.open$/, '');
  662. if (!state.hasOwnProperty('inside')) {
  663. state.inside = {};
  664. }
  665. if (!state.inside.hasOwnProperty(type)) {
  666. state.inside[type] = [];
  667. }
  668. var arr = state.inside[type];
  669. arr.push(node);
  670. return arr;
  671. };
  672. /**
  673. * Remove the given `node` from the `state.inside` array for the
  674. * given type. This array is used as a specialized "stack" for
  675. * only the given `node.type`.
  676. *
  677. * ```js
  678. * var state = { inside: {}};
  679. * var node = new Node({type: 'brace'});
  680. * utils.addType(state, node);
  681. * console.log(state.inside);
  682. * //=> { brace: [{type: 'brace'}] }
  683. * utils.removeType(state, node);
  684. * //=> { brace: [] }
  685. * ```
  686. * @param {Object} `state` The `compiler.state` object or custom state object.
  687. * @param {Object} `node` Instance of [snapdragon-node][]
  688. * @return {Array} Returns the `state.inside` stack for the given type.
  689. * @api public
  690. */
  691. utils.removeType = function(state, node) {
  692. assert(utils.isNode(node), 'expected node to be an instance of Node');
  693. assert(isObject(state), 'expected state to be an object');
  694. var type = node.parent
  695. ? node.parent.type
  696. : node.type.replace(/\.close$/, '');
  697. if (state.inside.hasOwnProperty(type)) {
  698. return state.inside[type].pop();
  699. }
  700. };
  701. /**
  702. * Returns true if `node.val` is an empty string, or `node.nodes` does
  703. * not contain any non-empty text nodes.
  704. *
  705. * ```js
  706. * var node = new Node({type: 'text'});
  707. * utils.isEmpty(node); //=> true
  708. * node.val = 'foo';
  709. * utils.isEmpty(node); //=> false
  710. * ```
  711. * @param {Object} `node` Instance of [snapdragon-node][]
  712. * @param {Function} `fn`
  713. * @return {Boolean}
  714. * @api public
  715. */
  716. utils.isEmpty = function(node, fn) {
  717. assert(utils.isNode(node), 'expected node to be an instance of Node');
  718. if (!Array.isArray(node.nodes)) {
  719. if (node.type !== 'text') {
  720. return true;
  721. }
  722. if (typeof fn === 'function') {
  723. return fn(node, node.parent);
  724. }
  725. return !utils.trim(node.val);
  726. }
  727. for (var i = 0; i < node.nodes.length; i++) {
  728. var child = node.nodes[i];
  729. if (utils.isOpen(child) || utils.isClose(child)) {
  730. continue;
  731. }
  732. if (!utils.isEmpty(child, fn)) {
  733. return false;
  734. }
  735. }
  736. return true;
  737. };
  738. /**
  739. * Returns true if the `state.inside` stack for the given type exists
  740. * and has one or more nodes on it.
  741. *
  742. * ```js
  743. * var state = { inside: {}};
  744. * var node = new Node({type: 'brace'});
  745. * console.log(utils.isInsideType(state, 'brace')); //=> false
  746. * utils.addType(state, node);
  747. * console.log(utils.isInsideType(state, 'brace')); //=> true
  748. * utils.removeType(state, node);
  749. * console.log(utils.isInsideType(state, 'brace')); //=> false
  750. * ```
  751. * @param {Object} `state`
  752. * @param {String} `type`
  753. * @return {Boolean}
  754. * @api public
  755. */
  756. utils.isInsideType = function(state, type) {
  757. assert(isObject(state), 'expected state to be an object');
  758. assert(isString(type), 'expected type to be a string');
  759. if (!state.hasOwnProperty('inside')) {
  760. return false;
  761. }
  762. if (!state.inside.hasOwnProperty(type)) {
  763. return false;
  764. }
  765. return state.inside[type].length > 0;
  766. };
  767. /**
  768. * Returns true if `node` is either a child or grand-child of the given `type`,
  769. * or `state.inside[type]` is a non-empty array.
  770. *
  771. * ```js
  772. * var state = { inside: {}};
  773. * var node = new Node({type: 'brace'});
  774. * var open = new Node({type: 'brace.open'});
  775. * console.log(utils.isInside(state, open, 'brace')); //=> false
  776. * utils.pushNode(node, open);
  777. * console.log(utils.isInside(state, open, 'brace')); //=> true
  778. * ```
  779. * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object.
  780. * @param {Object} `node` Instance of [snapdragon-node][]
  781. * @param {String} `type` The `node.type` to check for.
  782. * @return {Boolean}
  783. * @api public
  784. */
  785. utils.isInside = function(state, node, type) {
  786. assert(utils.isNode(node), 'expected node to be an instance of Node');
  787. assert(isObject(state), 'expected state to be an object');
  788. if (Array.isArray(type)) {
  789. for (var i = 0; i < type.length; i++) {
  790. if (utils.isInside(state, node, type[i])) {
  791. return true;
  792. }
  793. }
  794. return false;
  795. }
  796. var parent = node.parent;
  797. if (typeof type === 'string') {
  798. return (parent && parent.type === type) || utils.isInsideType(state, type);
  799. }
  800. if (typeOf(type) === 'regexp') {
  801. if (parent && parent.type && type.test(parent.type)) {
  802. return true;
  803. }
  804. var keys = Object.keys(state.inside);
  805. var len = keys.length;
  806. var idx = -1;
  807. while (++idx < len) {
  808. var key = keys[idx];
  809. var val = state.inside[key];
  810. if (Array.isArray(val) && val.length !== 0 && type.test(key)) {
  811. return true;
  812. }
  813. }
  814. }
  815. return false;
  816. };
  817. /**
  818. * Get the last `n` element from the given `array`. Used for getting
  819. * a node from `node.nodes.`
  820. *
  821. * @param {Array} `array`
  822. * @param {Number} `n`
  823. * @return {undefined}
  824. * @api public
  825. */
  826. utils.last = function(arr, n) {
  827. return arr[arr.length - (n || 1)];
  828. };
  829. /**
  830. * Cast the given `val` to an array.
  831. *
  832. * ```js
  833. * console.log(utils.arrayify(''));
  834. * //=> []
  835. * console.log(utils.arrayify('foo'));
  836. * //=> ['foo']
  837. * console.log(utils.arrayify(['foo']));
  838. * //=> ['foo']
  839. * ```
  840. * @param {any} `val`
  841. * @return {Array}
  842. * @api public
  843. */
  844. utils.arrayify = function(val) {
  845. if (typeof val === 'string' && val !== '') {
  846. return [val];
  847. }
  848. if (!Array.isArray(val)) {
  849. return [];
  850. }
  851. return val;
  852. };
  853. /**
  854. * Convert the given `val` to a string by joining with `,`. Useful
  855. * for creating a cheerio/CSS/DOM-style selector from a list of strings.
  856. *
  857. * @param {any} `val`
  858. * @return {Array}
  859. * @api public
  860. */
  861. utils.stringify = function(val) {
  862. return utils.arrayify(val).join(',');
  863. };
  864. /**
  865. * Ensure that the given value is a string and call `.trim()` on it,
  866. * or return an empty string.
  867. *
  868. * @param {String} `str`
  869. * @return {String}
  870. * @api public
  871. */
  872. utils.trim = function(str) {
  873. return typeof str === 'string' ? str.trim() : '';
  874. };
  875. /**
  876. * Return true if val is an object
  877. */
  878. function isObject(val) {
  879. return typeOf(val) === 'object';
  880. }
  881. /**
  882. * Return true if val is a string
  883. */
  884. function isString(val) {
  885. return typeof val === 'string';
  886. }
  887. /**
  888. * Return true if val is a function
  889. */
  890. function isFunction(val) {
  891. return typeof val === 'function';
  892. }
  893. /**
  894. * Return true if val is an array
  895. */
  896. function isArray(val) {
  897. return Array.isArray(val);
  898. }
  899. /**
  900. * Shim to ensure the `.append` methods work with any version of snapdragon
  901. */
  902. function append(compiler, val, node) {
  903. if (typeof compiler.append !== 'function') {
  904. return compiler.emit(val, node);
  905. }
  906. return compiler.append(val, node);
  907. }
  908. /**
  909. * Simplified assertion. Throws an error is `val` is falsey.
  910. */
  911. function assert(val, message) {
  912. if (!val) throw new Error(message);
  913. }