-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
hot-replacement-component.js
182 lines (163 loc) · 6.13 KB
/
hot-replacement-component.js
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import Ember from 'ember';
import { later } from '@ember/runloop';
import Component from '@ember/component';
import { computed } from '@ember/object';
import HotComponentMixin from 'ember-cli-hot-loader/mixins/hot-component';
import config from 'ember-get-config';
import clearCache from 'ember-cli-hot-loader/utils/clear-container-cache';
import clearRequirejs from 'ember-cli-hot-loader/utils/clear-requirejs';
function regexEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); // eslint-disable-line
}
export const TEMPLATE_CACHE_MAX_SIZE = 10000;
export const TEMPLATE_CACHE_GC_TIMEOUT = 1000;
export var TemplatesCache = {};
export var TemplateCacheCheckTimeout = null;
// this is fast-hashing function for string, taken from
// https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript
export function hashString(str) {
let hash = 0;
if (str.length == 0) {
return hash;
}
for (let i = 0; i < str.length; i++) {
let char = str.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return String(hash);
}
// Object keys may be so expensive on large objects (on 10k, ~ 6ms), so it's kinda debounce logic
export function checkTemplatesCacheLimit(timeout = TEMPLATE_CACHE_GC_TIMEOUT) {
// allow only 10k component templates in cache
clearTimeout(TemplateCacheCheckTimeout);
TemplateCacheCheckTimeout = setTimeout(()=>{
if (Object.keys(TemplatesCache).length > TEMPLATE_CACHE_MAX_SIZE) {
TemplatesCache = {};
}
}, timeout);
}
export function matchesPodConvention (componentName, modulePath) {
var basePath = 'components/' + componentName;
var componentRegexp = new RegExp(regexEscape(basePath + '/component.js') + '$');
if (componentRegexp.test(modulePath)) {
return true;
}
var templateRegex = new RegExp(regexEscape(basePath + '/template.hbs') + '$');
if (templateRegex.test(modulePath)) {
return true;
}
return false;
}
export function matchesClassicConvention (componentName, modulePath) {
var componentRegexp = new RegExp(regexEscape('components/' + componentName + '.js') + '$');
if (componentRegexp.test(modulePath)) {
return true;
}
var templateRegexp = new RegExp(regexEscape('templates/components/' + componentName + '.hbs') + '$');
if (templateRegexp.test(modulePath)) {
return true;
}
return false;
}
export function matchingComponent (componentName, modulePath) {
if(!componentName) {
return false;
}
var standardModulePath = modulePath.split('\\').join('/');
var javascriptPath = standardModulePath.replace(/\.ts$/, '.js');
return matchesClassicConvention(componentName, javascriptPath) ||
matchesPodConvention(componentName, javascriptPath);
}
function getPositionalParamsArray (constructor) {
const positionalParams = constructor.positionalParams;
return typeof(positionalParams) === 'string' ?
[positionalParams] :
positionalParams;
}
const HotReplacementComponent = Component.extend(HotComponentMixin, {
init() {
const configuration = config['ember-cli-hot-loader'];
const tagless = configuration && configuration['tagless'];
const tagName = tagless ? '' : 'div';
this.set('tagName', tagName);
return this._super();
},
parsedName: null,
layout: computed(function () {
let positionalParams = getPositionalParamsArray(this.constructor).join('');
let attrs = this.attrs || {};
const attributesMap = Object.keys(attrs)
.filter(key => positionalParams.indexOf(key) === -1)
.map(key =>`${key}=${key}`).join(' ');
const templateLayout = `
{{#if hasBlock}}
{{#if (hasBlock "inverse")}}
{{#component wrappedComponentName ${positionalParams} ${attributesMap} target=target as |a b c d e f g h i j k|}}
{{yield a b c d e f g h i j k}}
{{else}}
{{yield to="inverse"}}
{{/component}}
{{else}}
{{#component wrappedComponentName ${positionalParams} ${attributesMap} target=target as |a b c d e f g h i j k|}}
{{yield a b c d e f g h i j k}}
{{/component}}
{{/if}}
{{else}}
{{component wrappedComponentName ${positionalParams} ${attributesMap} target=target}}
{{/if}}
`;
const templateHash = hashString(templateLayout);
if (!TemplatesCache[templateHash]) {
TemplatesCache[templateHash] = Ember.HTMLBars.compile(templateLayout);
}
checkTemplatesCacheLimit();
return TemplatesCache[templateHash];
}).volatile(),
__willLiveReload (event) {
const baseComponentName = this.get('baseComponentName');
if (matchingComponent(baseComponentName, event.modulePath)) {
event.cancel = true;
clearRequirejs(this, baseComponentName);
}
},
__isAlive() {
return !this.isDestroyed && !this.isDestroying;
},
__rerenderOnTemplateUpdate (modulePath) {
const baseComponentName = this.get('baseComponentName');
const wrappedComponentName = this.get('wrappedComponentName');
if(matchingComponent(baseComponentName, modulePath)) {
this._super(...arguments);
clearCache(this, baseComponentName);
clearCache(this, wrappedComponentName);
this.setProperties({
wrappedComponentName: undefined,
baseComponentName: undefined
});
this.rerender();
later(() => {
if (!this.__isAlive()) {
return;
}
this.setProperties({
wrappedComponentName: wrappedComponentName,
baseComponentName: baseComponentName
});
});
}
}
});
HotReplacementComponent.reopenClass({
createClass(OriginalComponentClass, parsedName) {
const NewComponentClass = HotReplacementComponent.extend({
baseComponentName: parsedName.fullNameWithoutType,
wrappedComponentName: parsedName.fullNameWithoutType + '-original'
});
NewComponentClass.reopenClass({
positionalParams: OriginalComponentClass.positionalParams ? OriginalComponentClass.positionalParams.slice() : []
});
return NewComponentClass;
}
});
export default HotReplacementComponent;