import {
clientRenderBoundary,
completeBoundary,
completeSegment,
} from './ReactDOMFizzInstructionSetShared';
export {clientRenderBoundary, completeBoundary, completeSegment};
export function completeBoundaryWithStyles(
suspenseBoundaryID,
contentID,
stylesheetDescriptors,
) {
const completeBoundaryImpl = window['$RC'];
const resourceMap = window['$RM'];
const precedences = new Map();
const thisDocument = document;
let lastResource, node;
const nodes = thisDocument.querySelectorAll(
'link[data-precedence],style[data-precedence]',
);
const styleTagsToHoist = [];
for (let i = 0; (node = nodes[i++]); ) {
if (node.getAttribute('media') === 'not all') {
styleTagsToHoist.push(node);
} else {
if (node.tagName === 'LINK') {
resourceMap.set(node.getAttribute('href'), node);
}
precedences.set(node.dataset['precedence'], (lastResource = node));
}
}
let i = 0;
const dependencies = [];
let href, precedence, attr, loadingState, resourceEl, media;
function cleanupWith(cb) {
this['_p'] = null;
cb();
}
let sheetMode = true;
while (true) {
if (sheetMode) {
const stylesheetDescriptor = stylesheetDescriptors[i++];
if (!stylesheetDescriptor) {
sheetMode = false;
i = 0;
continue;
}
let avoidInsert = false;
let j = 0;
href = stylesheetDescriptor[j++];
if ((resourceEl = resourceMap.get(href))) {
loadingState = resourceEl['_p'];
avoidInsert = true;
} else {
resourceEl = thisDocument.createElement('link');
resourceEl.href = href;
resourceEl.rel = 'stylesheet';
resourceEl.dataset['precedence'] = precedence =
stylesheetDescriptor[j++];
while ((attr = stylesheetDescriptor[j++])) {
resourceEl.setAttribute(attr, stylesheetDescriptor[j++]);
}
loadingState = resourceEl['_p'] = new Promise((resolve, reject) => {
resourceEl.onload = cleanupWith.bind(resourceEl, resolve);
resourceEl.onerror = cleanupWith.bind(resourceEl, reject);
});
resourceMap.set(href, resourceEl);
}
media = resourceEl.getAttribute('media');
if (loadingState && (!media || window['matchMedia'](media).matches)) {
dependencies.push(loadingState);
}
if (avoidInsert) {
continue;
}
} else {
resourceEl = styleTagsToHoist[i++];
if (!resourceEl) {
break;
}
precedence = resourceEl.getAttribute('data-precedence');
resourceEl.removeAttribute('media');
}
const prior = precedences.get(precedence) || lastResource;
if (prior === lastResource) {
lastResource = resourceEl;
}
precedences.set(precedence, resourceEl);
if (prior) {
prior.parentNode.insertBefore(resourceEl, prior.nextSibling);
} else {
const head = thisDocument.head;
head.insertBefore(resourceEl, head.firstChild);
}
}
Promise.all(dependencies).then(
completeBoundaryImpl.bind(null, suspenseBoundaryID, contentID, ''),
completeBoundaryImpl.bind(
null,
suspenseBoundaryID,
contentID,
'Resource failed to load',
),
);
}