3 var typeOf = require('kind-of');
4 var utils = module.exports;
7 * Returns true if the given value is a node.
10 * var Node = require('snapdragon-node');
11 * var node = new Node({type: 'foo'});
12 * console.log(utils.isNode(node)); //=> true
13 * console.log(utils.isNode({})); //=> false
15 * @param {Object} `node` Instance of [snapdragon-node][]
20 utils.isNode = function(node) {
21 return typeOf(node) === 'object' && node.isNode === true;
25 * Emit an empty string for the given `node`.
28 * // do nothing for beginning-of-string
29 * snapdragon.compiler.set('bos', utils.noop);
31 * @param {Object} `node` Instance of [snapdragon-node][]
32 * @returns {undefined}
36 utils.noop = function(node) {
37 append(this, '', node);
41 * Appdend `node.val` to `compiler.output`, exactly as it was created
45 * snapdragon.compiler.set('text', utils.identity);
47 * @param {Object} `node` Instance of [snapdragon-node][]
48 * @returns {undefined}
52 utils.identity = function(node) {
53 append(this, node.val, node);
57 * Previously named `.emit`, this method appends the given `val`
58 * to `compiler.output` for the given node. Useful when you know
59 * what value should be appended advance, regardless of the actual
60 * value of `node.val`.
64 * .set('i', function(node) {
65 * this.mapVisit(node);
67 * .set('i.open', utils.append('<i>'))
68 * .set('i.close', utils.append('</i>'))
70 * @param {Object} `node` Instance of [snapdragon-node][]
71 * @returns {Function} Returns a compiler middleware function.
75 utils.append = function(val) {
76 return function(node) {
77 append(this, val, node);
82 * Used in compiler middleware, this onverts an AST node into
83 * an empty `text` node and deletes `node.nodes` if it exists.
84 * The advantage of this method is that, as opposed to completely
85 * removing the node, indices will not need to be re-calculated
86 * in sibling nodes, and nothing is appended to the output.
90 * // convert `node.nodes` to the given value instead of deleting it
91 * utils.toNoop(node, []);
93 * @param {Object} `node` Instance of [snapdragon-node][]
94 * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array.
98 utils.toNoop = function(node, nodes) {
109 * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon
110 * automatically calls registered compilers, this allows you to pass a visitor
114 * snapdragon.compiler.set('i', function(node) {
115 * utils.visit(node, function(childNode) {
116 * // do stuff with "childNode"
121 * @param {Object} `node` Instance of [snapdragon-node][]
122 * @param {Function} `fn`
123 * @return {Object} returns the node after recursively visiting all child nodes.
127 utils.visit = function(node, fn) {
128 assert(utils.isNode(node), 'expected node to be an instance of Node');
129 assert(isFunction(fn), 'expected a visitor function');
131 return node.nodes ? utils.mapVisit(node, fn) : node;
135 * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by
136 * [visit](#visit), use this method if you do not want `fn` to be called on
140 * snapdragon.compiler.set('i', function(node) {
141 * utils.mapVisit(node, function(childNode) {
142 * // do stuff with "childNode"
147 * @param {Object} `node` Instance of [snapdragon-node][]
148 * @param {Object} `options`
149 * @param {Function} `fn`
150 * @return {Object} returns the node
154 utils.mapVisit = function(node, fn) {
155 assert(utils.isNode(node), 'expected node to be an instance of Node');
156 assert(isArray(node.nodes), 'expected node.nodes to be an array');
157 assert(isFunction(fn), 'expected a visitor function');
159 for (var i = 0; i < node.nodes.length; i++) {
160 utils.visit(node.nodes[i], fn);
166 * Unshift an `*.open` node onto `node.nodes`.
169 * var Node = require('snapdragon-node');
170 * snapdragon.parser.set('brace', function(node) {
171 * var match = this.match(/^{/);
173 * var parent = new Node({type: 'brace'});
174 * utils.addOpen(parent, Node);
175 * console.log(parent.nodes[0]):
176 * // { type: 'brace.open', val: '' };
178 * // push the parent "brace" node onto the stack
181 * // return the parent node, so it's also added to the AST
186 * @param {Object} `node` Instance of [snapdragon-node][]
187 * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
188 * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
189 * @return {Object} Returns the created opening node.
193 utils.addOpen = function(node, Node, val, filter) {
194 assert(utils.isNode(node), 'expected node to be an instance of Node');
195 assert(isFunction(Node), 'expected Node to be a constructor function');
197 if (typeof val === 'function') {
202 if (typeof filter === 'function' && !filter(node)) return;
203 var open = new Node({ type: node.type + '.open', val: val});
204 var unshift = node.unshift || node.unshiftNode;
205 if (typeof unshift === 'function') {
206 unshift.call(node, open);
208 utils.unshiftNode(node, open);
214 * Push a `*.close` node onto `node.nodes`.
217 * var Node = require('snapdragon-node');
218 * snapdragon.parser.set('brace', function(node) {
219 * var match = this.match(/^}/);
221 * var parent = this.parent();
222 * if (parent.type !== 'brace') {
223 * throw new Error('missing opening: ' + '}');
226 * utils.addClose(parent, Node);
227 * console.log(parent.nodes[parent.nodes.length - 1]):
228 * // { type: 'brace.close', val: '' };
230 * // no need to return a node, since the parent
231 * // was already added to the AST
236 * @param {Object} `node` Instance of [snapdragon-node][]
237 * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
238 * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
239 * @return {Object} Returns the created closing node.
243 utils.addClose = function(node, Node, val, filter) {
244 assert(utils.isNode(node), 'expected node to be an instance of Node');
245 assert(isFunction(Node), 'expected Node to be a constructor function');
247 if (typeof val === 'function') {
252 if (typeof filter === 'function' && !filter(node)) return;
253 var close = new Node({ type: node.type + '.close', val: val});
254 var push = node.push || node.pushNode;
255 if (typeof push === 'function') {
256 push.call(node, close);
258 utils.pushNode(node, close);
264 * Wraps the given `node` with `*.open` and `*.close` nodes.
266 * @param {Object} `node` Instance of [snapdragon-node][]
267 * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
268 * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
269 * @return {Object} Returns the node
273 utils.wrapNodes = function(node, Node, filter) {
274 assert(utils.isNode(node), 'expected node to be an instance of Node');
275 assert(isFunction(Node), 'expected Node to be a constructor function');
277 utils.addOpen(node, Node, filter);
278 utils.addClose(node, Node, filter);
283 * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent.
286 * var parent = new Node({type: 'foo'});
287 * var node = new Node({type: 'bar'});
288 * utils.pushNode(parent, node);
289 * console.log(parent.nodes[0].type) // 'bar'
290 * console.log(node.parent.type) // 'foo'
292 * @param {Object} `parent`
293 * @param {Object} `node` Instance of [snapdragon-node][]
294 * @return {Object} Returns the child node
298 utils.pushNode = function(parent, node) {
299 assert(utils.isNode(parent), 'expected parent node to be an instance of Node');
300 assert(utils.isNode(node), 'expected node to be an instance of Node');
302 node.define('parent', parent);
303 parent.nodes = parent.nodes || [];
304 parent.nodes.push(node);
309 * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent.
312 * var parent = new Node({type: 'foo'});
313 * var node = new Node({type: 'bar'});
314 * utils.unshiftNode(parent, node);
315 * console.log(parent.nodes[0].type) // 'bar'
316 * console.log(node.parent.type) // 'foo'
318 * @param {Object} `parent`
319 * @param {Object} `node` Instance of [snapdragon-node][]
320 * @return {undefined}
324 utils.unshiftNode = function(parent, node) {
325 assert(utils.isNode(parent), 'expected parent node to be an instance of Node');
326 assert(utils.isNode(node), 'expected node to be an instance of Node');
328 node.define('parent', parent);
329 parent.nodes = parent.nodes || [];
330 parent.nodes.unshift(node);
334 * Pop the last `node` off of `parent.nodes`. The advantage of
335 * using this method is that it checks for `node.nodes` and works
336 * with any version of `snapdragon-node`.
339 * var parent = new Node({type: 'foo'});
340 * utils.pushNode(parent, new Node({type: 'foo'}));
341 * utils.pushNode(parent, new Node({type: 'bar'}));
342 * utils.pushNode(parent, new Node({type: 'baz'}));
343 * console.log(parent.nodes.length); //=> 3
344 * utils.popNode(parent);
345 * console.log(parent.nodes.length); //=> 2
347 * @param {Object} `parent`
348 * @param {Object} `node` Instance of [snapdragon-node][]
349 * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.
353 utils.popNode = function(node) {
354 assert(utils.isNode(node), 'expected node to be an instance of Node');
355 if (typeof node.pop === 'function') {
358 return node.nodes && node.nodes.pop();
362 * Shift the first `node` off of `parent.nodes`. The advantage of
363 * using this method is that it checks for `node.nodes` and works
364 * with any version of `snapdragon-node`.
367 * var parent = new Node({type: 'foo'});
368 * utils.pushNode(parent, new Node({type: 'foo'}));
369 * utils.pushNode(parent, new Node({type: 'bar'}));
370 * utils.pushNode(parent, new Node({type: 'baz'}));
371 * console.log(parent.nodes.length); //=> 3
372 * utils.shiftNode(parent);
373 * console.log(parent.nodes.length); //=> 2
375 * @param {Object} `parent`
376 * @param {Object} `node` Instance of [snapdragon-node][]
377 * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.
381 utils.shiftNode = function(node) {
382 assert(utils.isNode(node), 'expected node to be an instance of Node');
383 if (typeof node.shift === 'function') {
386 return node.nodes && node.nodes.shift();
390 * Remove the specified `node` from `parent.nodes`.
393 * var parent = new Node({type: 'abc'});
394 * var foo = new Node({type: 'foo'});
395 * utils.pushNode(parent, foo);
396 * utils.pushNode(parent, new Node({type: 'bar'}));
397 * utils.pushNode(parent, new Node({type: 'baz'}));
398 * console.log(parent.nodes.length); //=> 3
399 * utils.removeNode(parent, foo);
400 * console.log(parent.nodes.length); //=> 2
402 * @param {Object} `parent`
403 * @param {Object} `node` Instance of [snapdragon-node][]
404 * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`.
408 utils.removeNode = function(parent, node) {
409 assert(utils.isNode(parent), 'expected parent.node to be an instance of Node');
410 assert(utils.isNode(node), 'expected node to be an instance of Node');
416 if (typeof parent.remove === 'function') {
417 return parent.remove(node);
420 var idx = parent.nodes.indexOf(node);
422 return parent.nodes.splice(idx, 1);
427 * Returns true if `node.type` matches the given `type`. Throws a
428 * `TypeError` if `node` is not an instance of `Node`.
431 * var Node = require('snapdragon-node');
432 * var node = new Node({type: 'foo'});
433 * console.log(utils.isType(node, 'foo')); // false
434 * console.log(utils.isType(node, 'bar')); // true
436 * @param {Object} `node` Instance of [snapdragon-node][]
437 * @param {String} `type`
442 utils.isType = function(node, type) {
443 assert(utils.isNode(node), 'expected node to be an instance of Node');
444 switch (typeOf(type)) {
446 var types = type.slice();
447 for (var i = 0; i < types.length; i++) {
448 if (utils.isType(node, types[i])) {
454 return node.type === type;
456 return type.test(node.type);
458 throw new TypeError('expected "type" to be an array, string or regexp');
464 * Returns true if the given `node` has the given `type` in `node.nodes`.
465 * Throws a `TypeError` if `node` is not an instance of `Node`.
468 * var Node = require('snapdragon-node');
469 * var node = new Node({
472 * new Node({type: 'bar'}),
473 * new Node({type: 'baz'})
476 * console.log(utils.hasType(node, 'xyz')); // false
477 * console.log(utils.hasType(node, 'baz')); // true
479 * @param {Object} `node` Instance of [snapdragon-node][]
480 * @param {String} `type`
485 utils.hasType = function(node, type) {
486 assert(utils.isNode(node), 'expected node to be an instance of Node');
487 if (!Array.isArray(node.nodes)) return false;
488 for (var i = 0; i < node.nodes.length; i++) {
489 if (utils.isType(node.nodes[i], type)) {
497 * Returns the first node from `node.nodes` of the given `type`
500 * var node = new Node({
503 * new Node({type: 'text', val: 'abc'}),
504 * new Node({type: 'text', val: 'xyz'})
508 * var textNode = utils.firstOfType(node.nodes, 'text');
509 * console.log(textNode.val);
512 * @param {Array} `nodes`
513 * @param {String} `type`
514 * @return {Object|undefined} Returns the first matching node or undefined.
518 utils.firstOfType = function(nodes, type) {
519 for (var i = 0; i < nodes.length; i++) {
521 if (utils.isType(node, type)) {
528 * Returns the node at the specified index, or the first node of the
529 * given `type` from `node.nodes`.
532 * var node = new Node({
535 * new Node({type: 'text', val: 'abc'}),
536 * new Node({type: 'text', val: 'xyz'})
540 * var nodeOne = utils.findNode(node.nodes, 'text');
541 * console.log(nodeOne.val);
544 * var nodeTwo = utils.findNode(node.nodes, 1);
545 * console.log(nodeTwo.val);
549 * @param {Array} `nodes`
550 * @param {String|Number} `type` Node type or index.
551 * @return {Object} Returns a node or undefined.
555 utils.findNode = function(nodes, type) {
556 if (!Array.isArray(nodes)) {
559 if (typeof type === 'number') {
562 return utils.firstOfType(nodes, type);
566 * Returns true if the given node is an "*.open" node.
569 * var Node = require('snapdragon-node');
570 * var brace = new Node({type: 'brace'});
571 * var open = new Node({type: 'brace.open'});
572 * var close = new Node({type: 'brace.close'});
574 * console.log(utils.isOpen(brace)); // false
575 * console.log(utils.isOpen(open)); // true
576 * console.log(utils.isOpen(close)); // false
578 * @param {Object} `node` Instance of [snapdragon-node][]
583 utils.isOpen = function(node) {
584 assert(utils.isNode(node), 'expected node to be an instance of Node');
585 return node.type.slice(-5) === '.open';
589 * Returns true if the given node is a "*.close" node.
592 * var Node = require('snapdragon-node');
593 * var brace = new Node({type: 'brace'});
594 * var open = new Node({type: 'brace.open'});
595 * var close = new Node({type: 'brace.close'});
597 * console.log(utils.isClose(brace)); // false
598 * console.log(utils.isClose(open)); // false
599 * console.log(utils.isClose(close)); // true
601 * @param {Object} `node` Instance of [snapdragon-node][]
606 utils.isClose = function(node) {
607 assert(utils.isNode(node), 'expected node to be an instance of Node');
608 return node.type.slice(-6) === '.close';
612 * Returns true if `node.nodes` **has** an `.open` node
615 * var Node = require('snapdragon-node');
616 * var brace = new Node({
621 * var open = new Node({type: 'brace.open'});
622 * console.log(utils.hasOpen(brace)); // false
624 * brace.pushNode(open);
625 * console.log(utils.hasOpen(brace)); // true
627 * @param {Object} `node` Instance of [snapdragon-node][]
632 utils.hasOpen = function(node) {
633 assert(utils.isNode(node), 'expected node to be an instance of Node');
634 var first = node.first || node.nodes ? node.nodes[0] : null;
635 if (utils.isNode(first)) {
636 return first.type === node.type + '.open';
642 * Returns true if `node.nodes` **has** a `.close` node
645 * var Node = require('snapdragon-node');
646 * var brace = new Node({
651 * var close = new Node({type: 'brace.close'});
652 * console.log(utils.hasClose(brace)); // false
654 * brace.pushNode(close);
655 * console.log(utils.hasClose(brace)); // true
657 * @param {Object} `node` Instance of [snapdragon-node][]
662 utils.hasClose = function(node) {
663 assert(utils.isNode(node), 'expected node to be an instance of Node');
664 var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null;
665 if (utils.isNode(last)) {
666 return last.type === node.type + '.close';
672 * Returns true if `node.nodes` has both `.open` and `.close` nodes
675 * var Node = require('snapdragon-node');
676 * var brace = new Node({
681 * var open = new Node({type: 'brace.open'});
682 * var close = new Node({type: 'brace.close'});
683 * console.log(utils.hasOpen(brace)); // false
684 * console.log(utils.hasClose(brace)); // false
686 * brace.pushNode(open);
687 * brace.pushNode(close);
688 * console.log(utils.hasOpen(brace)); // true
689 * console.log(utils.hasClose(brace)); // true
691 * @param {Object} `node` Instance of [snapdragon-node][]
696 utils.hasOpenAndClose = function(node) {
697 return utils.hasOpen(node) && utils.hasClose(node);
701 * Push the given `node` onto the `state.inside` array for the
702 * given type. This array is used as a specialized "stack" for
703 * only the given `node.type`.
706 * var state = { inside: {}};
707 * var node = new Node({type: 'brace'});
708 * utils.addType(state, node);
709 * console.log(state.inside);
710 * //=> { brace: [{type: 'brace'}] }
712 * @param {Object} `state` The `compiler.state` object or custom state object.
713 * @param {Object} `node` Instance of [snapdragon-node][]
714 * @return {Array} Returns the `state.inside` stack for the given type.
718 utils.addType = function(state, node) {
719 assert(utils.isNode(node), 'expected node to be an instance of Node');
720 assert(isObject(state), 'expected state to be an object');
722 var type = node.parent
724 : node.type.replace(/\.open$/, '');
726 if (!state.hasOwnProperty('inside')) {
729 if (!state.inside.hasOwnProperty(type)) {
730 state.inside[type] = [];
733 var arr = state.inside[type];
739 * Remove the given `node` from the `state.inside` array for the
740 * given type. This array is used as a specialized "stack" for
741 * only the given `node.type`.
744 * var state = { inside: {}};
745 * var node = new Node({type: 'brace'});
746 * utils.addType(state, node);
747 * console.log(state.inside);
748 * //=> { brace: [{type: 'brace'}] }
749 * utils.removeType(state, node);
752 * @param {Object} `state` The `compiler.state` object or custom state object.
753 * @param {Object} `node` Instance of [snapdragon-node][]
754 * @return {Array} Returns the `state.inside` stack for the given type.
758 utils.removeType = function(state, node) {
759 assert(utils.isNode(node), 'expected node to be an instance of Node');
760 assert(isObject(state), 'expected state to be an object');
762 var type = node.parent
764 : node.type.replace(/\.close$/, '');
766 if (state.inside.hasOwnProperty(type)) {
767 return state.inside[type].pop();
772 * Returns true if `node.val` is an empty string, or `node.nodes` does
773 * not contain any non-empty text nodes.
776 * var node = new Node({type: 'text'});
777 * utils.isEmpty(node); //=> true
779 * utils.isEmpty(node); //=> false
781 * @param {Object} `node` Instance of [snapdragon-node][]
782 * @param {Function} `fn`
787 utils.isEmpty = function(node, fn) {
788 assert(utils.isNode(node), 'expected node to be an instance of Node');
790 if (!Array.isArray(node.nodes)) {
791 if (node.type !== 'text') {
794 if (typeof fn === 'function') {
795 return fn(node, node.parent);
797 return !utils.trim(node.val);
800 for (var i = 0; i < node.nodes.length; i++) {
801 var child = node.nodes[i];
802 if (utils.isOpen(child) || utils.isClose(child)) {
805 if (!utils.isEmpty(child, fn)) {
814 * Returns true if the `state.inside` stack for the given type exists
815 * and has one or more nodes on it.
818 * var state = { inside: {}};
819 * var node = new Node({type: 'brace'});
820 * console.log(utils.isInsideType(state, 'brace')); //=> false
821 * utils.addType(state, node);
822 * console.log(utils.isInsideType(state, 'brace')); //=> true
823 * utils.removeType(state, node);
824 * console.log(utils.isInsideType(state, 'brace')); //=> false
826 * @param {Object} `state`
827 * @param {String} `type`
832 utils.isInsideType = function(state, type) {
833 assert(isObject(state), 'expected state to be an object');
834 assert(isString(type), 'expected type to be a string');
836 if (!state.hasOwnProperty('inside')) {
840 if (!state.inside.hasOwnProperty(type)) {
844 return state.inside[type].length > 0;
848 * Returns true if `node` is either a child or grand-child of the given `type`,
849 * or `state.inside[type]` is a non-empty array.
852 * var state = { inside: {}};
853 * var node = new Node({type: 'brace'});
854 * var open = new Node({type: 'brace.open'});
855 * console.log(utils.isInside(state, open, 'brace')); //=> false
856 * utils.pushNode(node, open);
857 * console.log(utils.isInside(state, open, 'brace')); //=> true
859 * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object.
860 * @param {Object} `node` Instance of [snapdragon-node][]
861 * @param {String} `type` The `node.type` to check for.
866 utils.isInside = function(state, node, type) {
867 assert(utils.isNode(node), 'expected node to be an instance of Node');
868 assert(isObject(state), 'expected state to be an object');
870 if (Array.isArray(type)) {
871 for (var i = 0; i < type.length; i++) {
872 if (utils.isInside(state, node, type[i])) {
879 var parent = node.parent;
880 if (typeof type === 'string') {
881 return (parent && parent.type === type) || utils.isInsideType(state, type);
884 if (typeOf(type) === 'regexp') {
885 if (parent && parent.type && type.test(parent.type)) {
889 var keys = Object.keys(state.inside);
890 var len = keys.length;
892 while (++idx < len) {
894 var val = state.inside[key];
896 if (Array.isArray(val) && val.length !== 0 && type.test(key)) {
905 * Get the last `n` element from the given `array`. Used for getting
906 * a node from `node.nodes.`
908 * @param {Array} `array`
909 * @param {Number} `n`
910 * @return {undefined}
914 utils.last = function(arr, n) {
915 return arr[arr.length - (n || 1)];
919 * Cast the given `val` to an array.
922 * console.log(utils.arrayify(''));
924 * console.log(utils.arrayify('foo'));
926 * console.log(utils.arrayify(['foo']));
934 utils.arrayify = function(val) {
935 if (typeof val === 'string' && val !== '') {
938 if (!Array.isArray(val)) {
945 * Convert the given `val` to a string by joining with `,`. Useful
946 * for creating a cheerio/CSS/DOM-style selector from a list of strings.
953 utils.stringify = function(val) {
954 return utils.arrayify(val).join(',');
958 * Ensure that the given value is a string and call `.trim()` on it,
959 * or return an empty string.
961 * @param {String} `str`
966 utils.trim = function(str) {
967 return typeof str === 'string' ? str.trim() : '';
971 * Return true if val is an object
974 function isObject(val) {
975 return typeOf(val) === 'object';
979 * Return true if val is a string
982 function isString(val) {
983 return typeof val === 'string';
987 * Return true if val is a function
990 function isFunction(val) {
991 return typeof val === 'function';
995 * Return true if val is an array
998 function isArray(val) {
999 return Array.isArray(val);
1003 * Shim to ensure the `.append` methods work with any version of snapdragon
1006 function append(compiler, val, node) {
1007 if (typeof compiler.append !== 'function') {
1008 return compiler.emit(val, node);
1010 return compiler.append(val, node);
1014 * Simplified assertion. Throws an error is `val` is falsey.
1017 function assert(val, message) {
1018 if (!val) throw new Error(message);