shikeying
2023-03-17 8c1a723d62a6aa5d6266ca613ae4eb77c789db06
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
 
var Validator = require('./Validator');
 
/**
 * The guy responsible for template loading.
 *
 * Provide the actual templates via the `config.elementTemplates`.
 *
 * That configuration can either be an array of template
 * descriptors or a node style callback to retrieve
 * the templates asynchronously.
 *
 * @param {Array<TemplateDescriptor>|Function} loadTemplates
 * @param {EventBus} eventBus
 * @param {ElementTemplates} elementTemplates
 */
function ElementTemplatesLoader(loadTemplates, eventBus, elementTemplates) {
  this._loadTemplates = loadTemplates;
  this._eventBus = eventBus;
  this._elementTemplates = elementTemplates;
 
  var self = this;
 
  eventBus.on('diagram.init', function() {
    self.reload();
  });
}
 
module.exports = ElementTemplatesLoader;
 
ElementTemplatesLoader.$inject = [
  'config.elementTemplates',
  'eventBus',
  'elementTemplates'
];
 
 
ElementTemplatesLoader.prototype.reload = function() {
 
  var self = this;
 
  var loadTemplates = this._loadTemplates;
 
  // no templates specified
  if (typeof loadTemplates === 'undefined') {
    return;
  }
 
  // template loader function specified
  if (typeof loadTemplates === 'function') {
 
    return loadTemplates(function(err, templates) {
 
      if (err) {
        return self.templateErrors([ err ]);
      }
 
      self.setTemplates(templates);
    });
  }
 
  // templates array specified
  if (loadTemplates.length) {
    return this.setTemplates(loadTemplates);
  }
 
};
 
ElementTemplatesLoader.prototype.setTemplates = function(templates) {
 
  var elementTemplates = this._elementTemplates;
 
  var validator = new Validator().addAll(templates);
 
  var errors = validator.getErrors(),
      validTemplates = validator.getValidTemplates();
 
  elementTemplates.set(validTemplates);
 
  if (errors.length) {
    this.templateErrors(errors);
  }
 
  this.templatesChanged();
};
 
ElementTemplatesLoader.prototype.templatesChanged = function() {
  this._eventBus.fire('elementTemplates.changed');
};
 
ElementTemplatesLoader.prototype.templateErrors = function(errors) {
  this._eventBus.fire('elementTemplates.errors', {
    errors: errors
  });
};