UNPKG

1.51 kBJavaScriptView Raw
1/*
2 Copyright © 2018 Andrew Powell
3
4 This Source Code Form is subject to the terms of the Mozilla Public
5 License, v. 2.0. If a copy of the MPL was not distributed with this
6 file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8 The above copyright notice and this permission notice shall be
9 included in all copies or substantial portions of this Source Code Form.
10*/
11const Container = require('postcss/lib/container');
12
13const registerWalker = (constructor) => {
14 let walkerName = `walk${constructor.name}`;
15
16 // plural sugar
17 if (walkerName.lastIndexOf('s') !== walkerName.length - 1) {
18 walkerName += 's';
19 }
20
21 /* istanbul ignore next */
22 if (Container.prototype[walkerName]) {
23 return;
24 }
25
26 // we need access to `this` so we can't use an arrow function
27 Container.prototype[walkerName] = function walker(callback) {
28 return this.walkType(constructor, callback);
29 };
30};
31
32Container.prototype.walkType = function walkType(type, callback) {
33 /* istanbul ignore next */
34 if (!type || !callback) {
35 throw new Error('Parameters {type} and {callback} are required.');
36 }
37
38 // allow users to pass a constructor, or node type string; eg. Word.
39 const isTypeCallable = typeof type === 'function';
40
41 // eslint-disable-next-line consistent-return
42 return this.walk((node, index) => {
43 if ((isTypeCallable && node instanceof type) || (!isTypeCallable && node.type === type)) {
44 return callback.call(this, node, index);
45 }
46 });
47};
48
49module.exports = { registerWalker };