index.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. }