RuleProvider.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import inherits from 'inherits';
  2. import CommandInterceptor from '../../command/CommandInterceptor';
  3. /**
  4. * A basic provider that may be extended to implement modeling rules.
  5. *
  6. * Extensions should implement the init method to actually add their custom
  7. * modeling checks. Checks may be added via the #addRule(action, fn) method.
  8. *
  9. * @param {EventBus} eventBus
  10. */
  11. export default function RuleProvider(eventBus) {
  12. CommandInterceptor.call(this, eventBus);
  13. this.init();
  14. }
  15. RuleProvider.$inject = [ 'eventBus' ];
  16. inherits(RuleProvider, CommandInterceptor);
  17. /**
  18. * Adds a modeling rule for the given action, implemented through
  19. * a callback function.
  20. *
  21. * The function will receive the modeling specific action context
  22. * to perform its check. It must return `false` to disallow the
  23. * action from happening or `true` to allow the action.
  24. *
  25. * A rule provider may pass over the evaluation to lower priority
  26. * rules by returning return nothing (or <code>undefined</code>).
  27. *
  28. * @example
  29. *
  30. * ResizableRules.prototype.init = function() {
  31. *
  32. * \/**
  33. * * Return `true`, `false` or nothing to denote
  34. * * _allowed_, _not allowed_ and _continue evaluating_.
  35. * *\/
  36. * this.addRule('shape.resize', function(context) {
  37. *
  38. * var shape = context.shape;
  39. *
  40. * if (!context.newBounds) {
  41. * // check general resizability
  42. * if (!shape.resizable) {
  43. * return false;
  44. * }
  45. *
  46. * // not returning anything (read: undefined)
  47. * // will continue the evaluation of other rules
  48. * // (with lower priority)
  49. * return;
  50. * } else {
  51. * // element must have minimum size of 10*10 points
  52. * return context.newBounds.width > 10 && context.newBounds.height > 10;
  53. * }
  54. * });
  55. * };
  56. *
  57. * @param {String|Array<String>} actions the identifier for the modeling action to check
  58. * @param {Number} [priority] the priority at which this rule is being applied
  59. * @param {Function} fn the callback function that performs the actual check
  60. */
  61. RuleProvider.prototype.addRule = function(actions, priority, fn) {
  62. var self = this;
  63. if (typeof actions === 'string') {
  64. actions = [ actions ];
  65. }
  66. actions.forEach(function(action) {
  67. self.canExecute(action, priority, function(context, action, event) {
  68. return fn(context);
  69. }, true);
  70. });
  71. };
  72. /**
  73. * Implement this method to add new rules during provider initialization.
  74. */
  75. RuleProvider.prototype.init = function() {};