-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
debug.js
358 lines (318 loc) · 11.4 KB
/
debug.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import { checkPropTypes } from './check-props';
import { getDisplayName } from './devtools/custom';
import { options, toChildArray } from 'preact';
import { ELEMENT_NODE, DOCUMENT_NODE, DOCUMENT_FRAGMENT_NODE } from './constants';
function getClosestDomNodeParent(parent) {
if (!parent) return {};
if (typeof parent.type === 'function') {
return getClosestDomNodeParent(parent._parent);
}
return parent;
}
export function initDebug() {
/* eslint-disable no-console */
let oldBeforeDiff = options._diff;
let oldDiffed = options.diffed;
let oldVnode = options.vnode;
let oldCatchError = options._catchError;
const warnedComponents = { useEffect: {}, useLayoutEffect: {}, lazyPropTypes: {} };
const serializedConstructorMap = typeof WeakMap!=='undefined' && new WeakMap();
options._catchError = (error, vnode, oldVNode) => {
let component = vnode && vnode._component;
if (component && typeof error.then === 'function') {
const promise = error;
error = new Error('Missing Suspense. The throwing component was: ' + getDisplayName(vnode));
let parent = vnode;
for (; parent; parent = parent._parent) {
if (parent._component && parent._component._childDidSuspend) {
error = promise;
break;
}
}
// We haven't recovered and we know at this point that there is no
// Suspense component higher up in the tree
if (error instanceof Error) {
throw error;
}
}
oldCatchError(error, vnode, oldVNode);
};
options._root = (vnode, parentNode) => {
if (!parentNode) {
throw new Error('Undefined parent passed to render(), this is the second argument.\nCheck if the element is available in the DOM/has the correct id.');
}
let isValid;
switch (parentNode.nodeType) {
case ELEMENT_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE: isValid = true; break;
default: isValid = false;
}
if (!isValid) throw new Error(`
Expected a valid HTML node as a second argument to render.
Received ${parentNode} instead: render(<${vnode.type.name || vnode.type} />, ${parentNode});
`);
};
options._diff = (vnode, oldVnode) => {
if (vnode == null) {
if (oldBeforeDiff) oldBeforeDiff(vnode, oldVnode);
return;
}
let { type, props, _parent: parent } = vnode;
let children = props && props.children;
let parentVNode = getClosestDomNodeParent(parent);
if (type===undefined) {
throw new Error('Undefined component passed to createElement()\n\n'+
'You likely forgot to export your component or might have mixed up default and named imports'+
serializeVNode(vnode));
}
else if (type!=null && typeof type==='object') {
if (type._lastDomChild!==undefined && type._dom!==undefined) {
let info = 'Did you accidentally pass a JSX literal as JSX twice?\n\n'+
' let My'+getDisplayName(type)+' = '+serializeVNode(type)+';\n'+
' let vnode = <My'+getDisplayName(type)+' />;\n\n'+
'This usually happens when you export a JSX literal and not the component.';
throw new Error('Invalid type passed to createElement(): '+type+'\n\n'+info+'\n');
}
throw new Error('Invalid type passed to createElement(): '+(Array.isArray(type) ? 'array' : type));
}
if ((type==='thead' || type==='tfoot' || type==='tbody') && parentVNode.type!=='table') {
console.error(
'Improper nesting of table.' +
'Your <thead/tbody/tfoot> should have a <table> parent.'
+ serializeVNode(vnode)
);
}
else if (
type==='tr' && (
parentVNode.type!=='thead' &&
parentVNode.type!=='tfoot' &&
parentVNode.type!=='tbody' &&
parentVNode.type!=='table'
)) {
console.error(
'Improper nesting of table.' +
'Your <tr> should have a <thead/tbody/tfoot/table> parent.'
+ serializeVNode(vnode)
);
}
else if (type==='td' && parentVNode.type!=='tr') {
console.error(
'Improper nesting of table.' +
'Your <td> should have a <tr> parent.'
+ serializeVNode(vnode)
);
}
else if (type==='th' && parentVNode.type!=='tr') {
console.error(
'Improper nesting of table.' +
'Your <th> should have a <tr>.'
+ serializeVNode(vnode)
);
}
if (
vnode.ref!==undefined &&
typeof vnode.ref!=='function' &&
typeof vnode.ref!=='object' &&
!('$$typeof' in vnode) // allow string refs when preact-compat is installed
) {
throw new Error(
`Component's "ref" property should be a function, or an object created ` +
`by createRef(), but got [${typeof vnode.ref}] instead\n` +
serializeVNode(vnode)
);
}
if (typeof vnode.type==='string') {
for (const key in vnode.props) {
if (key[0]==='o' && key[1]==='n' && typeof vnode.props[key]!=='function' && vnode.props[key]!=null) {
throw new Error(
`Component's "${key}" property should be a function, ` +
`but got [${typeof vnode.props[key]}] instead\n` +
serializeVNode(vnode)
);
}
}
}
// Detect component thrashing.
// This is a common problem where the diff sees a component reference
// on every render, since it can't infer semantic equivalence.
if (
// it's a component vnode
typeof type=='function' && typeof oldVnode.type==='function' &&
// and the constructor reference got changed
type !== oldVnode.type &&
// ... but they seem to be the same source
componentsAreEquivalent(type, oldVnode.type)
) {
console.error(
`🚨It looks like ${getDisplayName(vnode)} is being recreated on every render, causing serious performance problems.\n` +
`This usually means the component is being defined within another component or render function.\n` +
`For more information, see http://preactjs.com/errors/1`
);
}
// Check prop-types if available
if (typeof vnode.type==='function' && vnode.type.propTypes) {
if (vnode.type.displayName === 'Lazy' && !warnedComponents.lazyPropTypes[vnode.type]) {
const m = 'PropTypes are not supported on lazy(). Use propTypes on the wrapped component itself. ';
try {
const lazyVNode = vnode.type();
warnedComponents.lazyPropTypes[vnode.type] = true;
console.warn(m + 'Component wrapped in lazy() is ' + (lazyVNode.type.displayName || lazyVNode.type.name));
}
catch (promise) {
console.warn(m + 'We will log the wrapped component\'s name once it is loaded.');
}
}
checkPropTypes(vnode.type.propTypes, vnode.props, getDisplayName(vnode), serializeVNode(vnode));
}
let keys = [];
for (let deepChild of toChildArray(children)) {
if (!deepChild || deepChild.key==null) continue;
let key = deepChild.key;
if (keys.indexOf(key) !== -1) {
console.error(
'Following component has two or more children with the ' +
`same key attribute: "${key}". This may cause glitches and misbehavior ` +
'in rendering process. Component: \n\n' +
serializeVNode(vnode)
);
// Break early to not spam the console
break;
}
keys.push(key);
}
if (oldBeforeDiff) oldBeforeDiff(vnode, oldVnode);
};
// If the constructor source text and prototype properties match,
// two different component references are likely to be the same.
function componentsAreEquivalent(a, b) {
return componentToString(a) === componentToString(b);
}
function componentToString(c) {
let str;
if (serializedConstructorMap && (str = serializedConstructorMap.get(c))) {
return str;
}
str = Function.prototype.toString.call(c) + Object.keys(c.prototype).join();
if (serializedConstructorMap) {
serializedConstructorMap.set(c, str);
}
return str;
}
options._hook = (comp) => {
if (!comp) {
throw new Error('Hook can only be invoked from render methods.');
}
};
const warn = (property, err) => ({
get() {
throw new Error(`getting vnode.${property} is deprecated, ${err}`);
},
set() {
throw new Error(`setting vnode.${property} is not allowed, ${err}`);
}
});
const deprecatedAttributes = {
nodeName: warn('nodeName', 'use vnode.type'),
attributes: warn('attributes', 'use vnode.props'),
children: warn('children', 'use vnode.props.children')
};
options.vnode = (vnode) => {
let source, self;
if (vnode.props && vnode.props.__source) {
source = vnode.props.__source;
delete vnode.props.__source;
}
if (vnode.props && vnode.props.__self) {
self = vnode.props.__self;
delete vnode.props.__self;
}
vnode.__self = self;
vnode.__source = source;
Object.defineProperties(vnode, deprecatedAttributes);
if (oldVnode) oldVnode(vnode);
};
options.diffed = (vnode) => {
if (oldDiffed) oldDiffed(vnode);
if (vnode._component && vnode._component.__hooks) {
let hooks = vnode._component.__hooks;
(hooks._list || []).forEach(hook => {
if (hook._callback && (!hook._args || !Array.isArray(hook._args))) {
/* istanbul ignore next */
console.warn(
`In ${vnode.type.name || vnode.type} you are calling useMemo/useCallback without passing arguments.\n` +
`This is a noop since it will not be able to memoize, it will execute it every render.`
);
}
});
if (hooks._pendingEffects && Array.isArray(hooks._pendingEffects)) {
hooks._pendingEffects.forEach((effect) => {
if ((!effect._args || !Array.isArray(effect._args)) && !warnedComponents.useEffect[vnode.type]) {
warnedComponents.useEffect[vnode.type] = true;
/* istanbul ignore next */
console.warn('You should provide an array of arguments as the second argument to the "useEffect" hook.\n\n' +
'Not doing so will invoke this effect on every render.\n\n' +
'This effect can be found in the render of ' + (vnode.type.name || vnode.type) + '.');
}
});
}
if (hooks._pendingLayoutEffects && Array.isArray(hooks._pendingLayoutEffects)) {
hooks._pendingLayoutEffects.forEach((layoutEffect) => {
if ((!layoutEffect._args || !Array.isArray(layoutEffect._args)) && !warnedComponents.useLayoutEffect[vnode.type]) {
warnedComponents.useLayoutEffect[vnode.type] = true;
/* istanbul ignore next */
console.warn('You should provide an array of arguments as the second argument to the "useLayoutEffect" hook.\n\n' +
'Not doing so will invoke this effect on every render.\n\n' +
'This effect can be found in the render of ' + (vnode.type.name || vnode.type) + '.');
}
});
}
}
if (vnode._children != null) {
const keys = [];
for (let i = 0; i < vnode._children.length; i++) {
const child = vnode._children[i];
if (!child || child.key==null) continue;
const key = child.key;
if (keys.indexOf(key) !== -1) {
console.error(
'Following component has two or more children with the ' +
`same key attribute: "${key}". This may cause glitches and misbehavior ` +
'in rendering process. Component: \n\n' +
serializeVNode(vnode)
);
// Break early to not spam the console
break;
}
keys.push(key);
}
}
};
}
/**
* Serialize a vnode tree to a string
* @param {import('./internal').VNode} vnode
* @returns {string}
*/
export function serializeVNode(vnode) {
let { props } = vnode;
let name = getDisplayName(vnode);
let attrs = '';
for (let prop in props) {
if (props.hasOwnProperty(prop) && prop!=='children') {
let value = props[prop];
// If it is an object but doesn't have toString(), use Object.toString
if (typeof value==='function') {
value = `function ${value.displayName || value.name}() {}`;
}
value = Object(value) === value && !value.toString
? Object.prototype.toString.call(value)
: value + '';
attrs += ` ${prop}=${JSON.stringify(value)}`;
}
}
let children = props.children;
return `<${name}${attrs}${children && children.length
? '>..</'+name+'>'
: ' />'}`;
}