Skip to content

Commit f1ee646

Browse files
committed
Generate globally unique common names for unnamed components, instead of falling back to "Component". Unnamed components are now rendered as <UnnamedComponent0>, where 0 is an internal ID. Two identical components (referentially equal) will render with the same name, useful for testing unnamed components.
1 parent ad4630f commit f1ee646

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

src/index.js

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ const VOID_ELEMENTS = [
2727
'wbr'
2828
];
2929

30+
// components without names, kept as a hash for later comparison to return consistent UnnamedComponentXX names.
31+
const UNNAMED = [];
32+
3033
const objectKeys = Object.keys || (obj => {
3134
let keys = [];
3235
for (let i in obj) if (obj.hasOwnProperty(i)) keys.push(i);
@@ -163,5 +166,28 @@ export default function renderToString(vnode, context, opts, inner) {
163166
}
164167

165168
function getComponentName(component) {
166-
return component.displayName || component.name || component.prototype.displayName || component.prototype.name || (Function.prototype.toString.call(component).match(/\s([^\(]+)/) || EMPTY)[1] || 'Component';
169+
let proto = component.prototype,
170+
ctor = proto && proto.constructor;
171+
return component.displayName || component.name || (proto && (proto.displayName || proto.name)) || getFallbackComponentName(component);
172+
}
173+
174+
function getFallbackComponentName(component) {
175+
let str = Function.prototype.toString.call(component),
176+
name = (str.match(/^\s*function\s+([^\( ]+)/) || EMPTY)[1];
177+
if (!name) {
178+
// search for an existing indexed name for the given component:
179+
let index = -1;
180+
for (let i=UNNAMED.length; i--; ) {
181+
if (UNNAMED[i]===component) {
182+
index = i;
183+
break;
184+
}
185+
}
186+
// not found, create a new indexed name:
187+
if (index<0) {
188+
index = UNNAMED.push(component) - 1;
189+
}
190+
name = `UnnamedComponent${index}`;
191+
}
192+
return name;
167193
}

0 commit comments

Comments
 (0)