|
| 1 | +'use strict' |
| 2 | + |
| 3 | +module.exports = x |
| 4 | + |
| 5 | +var slice = [].slice |
| 6 | + |
| 7 | +// Creating xast elements. |
| 8 | +function x(name, attributes) { |
| 9 | + var attrs = {} |
| 10 | + var childrenIndex = 2 |
| 11 | + var attribute |
| 12 | + var value |
| 13 | + var node |
| 14 | + |
| 15 | + if (typeof name !== 'string' || name === '') { |
| 16 | + throw new Error('Expected element name, got `' + name + '`') |
| 17 | + } |
| 18 | + |
| 19 | + node = {type: 'element', name: name, attributes: attrs, children: []} |
| 20 | + |
| 21 | + // Note that we do not accept a node instead of attributes. |
| 22 | + if ( |
| 23 | + typeof attributes === 'number' || |
| 24 | + typeof attributes === 'string' || |
| 25 | + (attributes && 'length' in attributes) |
| 26 | + ) { |
| 27 | + childrenIndex = 1 |
| 28 | + attributes = null |
| 29 | + } |
| 30 | + |
| 31 | + if (attributes !== null && attributes !== undefined) { |
| 32 | + for (attribute in attributes) { |
| 33 | + value = attributes[attribute] |
| 34 | + |
| 35 | + // Ignore nully and NaN values. |
| 36 | + if (value !== null && value !== undefined && value === value) { |
| 37 | + attrs[attribute] = String(value) |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + add(node.children, slice.call(arguments, childrenIndex)) |
| 43 | + |
| 44 | + return node |
| 45 | +} |
| 46 | + |
| 47 | +function add(siblings, value) { |
| 48 | + var index |
| 49 | + var length |
| 50 | + |
| 51 | + if (value === null || value === undefined) { |
| 52 | + // Empty. |
| 53 | + } else if (typeof value === 'string' || typeof value === 'number') { |
| 54 | + siblings.push({type: 'text', value: String(value)}) |
| 55 | + } else if (typeof value === 'object' && 'length' in value) { |
| 56 | + index = -1 |
| 57 | + length = value.length |
| 58 | + |
| 59 | + while (++index < length) { |
| 60 | + add(siblings, value[index]) |
| 61 | + } |
| 62 | + } else if (typeof value === 'object' && typeof value.type === 'string') { |
| 63 | + siblings.push(value) |
| 64 | + } else { |
| 65 | + throw new TypeError('Expected node, nodes, string, got `' + value + '`') |
| 66 | + } |
| 67 | +} |
0 commit comments