| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
export default function Rules (options) { |
| 6 |
this.options = options |
| 7 |
this._keep = [] |
| 8 |
this._remove = [] |
| 9 |
|
| 10 |
this.blankRule = { |
| 11 |
replacement: options.blankReplacement |
| 12 |
} |
| 13 |
|
| 14 |
this.keepReplacement = options.keepReplacement |
| 15 |
|
| 16 |
this.defaultRule = { |
| 17 |
replacement: options.defaultReplacement |
| 18 |
} |
| 19 |
|
| 20 |
this.array = [] |
| 21 |
for (const key in options.rules) this.array.push(options.rules[key]) |
| 22 |
} |
| 23 |
|
| 24 |
Rules.prototype = { |
| 25 |
add: function (key, rule) { |
| 26 |
this.array.unshift(rule) |
| 27 |
}, |
| 28 |
|
| 29 |
keep: function (filter) { |
| 30 |
this._keep.unshift({ |
| 31 |
filter, |
| 32 |
replacement: this.keepReplacement |
| 33 |
}) |
| 34 |
}, |
| 35 |
|
| 36 |
remove: function (filter) { |
| 37 |
this._remove.unshift({ |
| 38 |
filter, |
| 39 |
replacement: function () { |
| 40 |
return '' |
| 41 |
} |
| 42 |
}) |
| 43 |
}, |
| 44 |
|
| 45 |
forNode: function (node) { |
| 46 |
if (node.isBlank) return this.blankRule |
| 47 |
let rule |
| 48 |
|
| 49 |
if ((rule = findRule(this.array, node, this.options))) return rule |
| 50 |
if ((rule = findRule(this._keep, node, this.options))) return rule |
| 51 |
if ((rule = findRule(this._remove, node, this.options))) return rule |
| 52 |
|
| 53 |
return this.defaultRule |
| 54 |
}, |
| 55 |
|
| 56 |
forEach: function (fn) { |
| 57 |
for (let i = 0; i < this.array.length; i++) fn(this.array[i], i) |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
function findRule (rules, node, options) { |
| 62 |
for (let i = 0; i < rules.length; i++) { |
| 63 |
const rule = rules[i] |
| 64 |
if (filterValue(rule, node, options)) return rule |
| 65 |
} |
| 66 |
return undefined |
| 67 |
} |
| 68 |
|
| 69 |
function filterValue (rule, node, options) { |
| 70 |
const filter = rule.filter |
| 71 |
if (typeof filter === 'string') { |
| 72 |
if (filter === node.nodeName.toLowerCase()) return true |
| 73 |
} else if (Array.isArray(filter)) { |
| 74 |
if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true |
| 75 |
} else if (typeof filter === 'function') { |
| 76 |
if (filter.call(rule, node, options)) return true |
| 77 |
} else { |
| 78 |
throw new TypeError('`filter` needs to be a string, array, or function') |
| 79 |
} |
| 80 |
} |