chore: simplify add_locations (#11757)

* chore: simplify add_locations

* tiny tweak
pull/11759/head
Rich Harris 7 months ago committed by GitHub
parent 3dfa343ea2
commit 196d7e41b1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -12,15 +12,8 @@ export function add_locations(fn, filename, locations) {
return (/** @type {any[]} */ ...args) => { return (/** @type {any[]} */ ...args) => {
const dom = fn(...args); const dom = fn(...args);
const nodes = hydrating var node = hydrating && is_array(dom) ? dom[0] : dom.nodeType === 11 ? dom.firstChild : dom;
? is_array(dom) assign_locations(node, filename, locations);
? dom
: [dom]
: dom.nodeType === 11
? Array.from(dom.childNodes)
: [dom];
assign_locations(nodes, filename, locations);
return dom; return dom;
}; };
@ -38,34 +31,30 @@ function assign_location(element, filename, location) {
}; };
if (location[2]) { if (location[2]) {
assign_locations( assign_locations(element.firstChild, filename, location[2]);
/** @type {import('#client').TemplateNode[]} */ (Array.from(element.childNodes)),
filename,
location[2]
);
} }
} }
/** /**
* @param {import('#client').TemplateNode[]} nodes * @param {Node | null} node
* @param {string} filename * @param {string} filename
* @param {import('../../../compiler/phases/3-transform/client/types.js').SourceLocation[]} locations * @param {import('../../../compiler/phases/3-transform/client/types.js').SourceLocation[]} locations
*/ */
function assign_locations(nodes, filename, locations) { function assign_locations(node, filename, locations) {
var j = 0; var i = 0;
var depth = 0; var depth = 0;
for (var i = 0; i < nodes.length; i += 1) { while (node && i < locations.length) {
var node = nodes[i];
if (hydrating && node.nodeType === 8) { if (hydrating && node.nodeType === 8) {
var comment = /** @type {Comment} */ (node); var comment = /** @type {Comment} */ (node);
if (comment.data === HYDRATION_START) depth += 1; if (comment.data === HYDRATION_START) depth += 1;
if (comment.data.startsWith(HYDRATION_END)) depth -= 1; else if (comment.data[0] === HYDRATION_END) depth -= 1;
} }
if (depth === 0 && node.nodeType === 1) { if (depth === 0 && node.nodeType === 1) {
assign_location(/** @type {Element} */ (node), filename, locations[j++]); assign_location(/** @type {Element} */ (node), filename, locations[i++]);
} }
node = node.nextSibling;
} }
} }

Loading…
Cancel
Save