BasicMatcherRulePlugin.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */
  7. /** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */
  8. class BasicMatcherRulePlugin {
  9. constructor(ruleProperty, dataProperty, invert) {
  10. this.ruleProperty = ruleProperty;
  11. this.dataProperty = dataProperty || ruleProperty;
  12. this.invert = invert || false;
  13. }
  14. /**
  15. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  16. * @returns {void}
  17. */
  18. apply(ruleSetCompiler) {
  19. ruleSetCompiler.hooks.rule.tap(
  20. "BasicMatcherRulePlugin",
  21. (path, rule, unhandledProperties, result) => {
  22. if (unhandledProperties.has(this.ruleProperty)) {
  23. unhandledProperties.delete(this.ruleProperty);
  24. const value = rule[this.ruleProperty];
  25. const condition = ruleSetCompiler.compileCondition(
  26. `${path}.${this.ruleProperty}`,
  27. value
  28. );
  29. const fn = condition.fn;
  30. result.conditions.push({
  31. property: this.dataProperty,
  32. matchWhenEmpty: this.invert
  33. ? !condition.matchWhenEmpty
  34. : condition.matchWhenEmpty,
  35. fn: this.invert ? v => !fn(v) : fn
  36. });
  37. }
  38. }
  39. );
  40. }
  41. }
  42. module.exports = BasicMatcherRulePlugin;