Skip to content

Commit 87d016f

Browse files
committed
Get FinalizationRegistry working
1 parent 2706cd1 commit 87d016f

File tree

1 file changed

+35
-8
lines changed

1 file changed

+35
-8
lines changed

packages/@react-spectrum/s2/style/style-macro.ts

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -393,18 +393,45 @@ export function createTheme<T extends Theme>(theme: T): StyleFunction<ThemePrope
393393
if (isStatic && process.env.NODE_ENV !== 'production') {
394394
let id = toBase62(hash(className));
395395
className += ` -macro$${id}`;
396-
return {toString: new Function(`
397-
(globalThis.__macros ??= {})[${JSON.stringify(id)}] = ${JSON.stringify({loc, style})};
398-
return ${JSON.stringify(className)};
399-
`)};
396+
397+
let styleObject = {};
398+
399+
let toStringFunc = new Function(`
400+
if (!globalThis.__macrosRegistry) {
401+
globalThis.__macrosRegistry = new globalThis.FinalizationRegistry((val) => {
402+
console.log('cleaning up,', val);
403+
delete globalThis.__macros[val];
404+
});
405+
}
406+
(globalThis.__macros ??= {})[${JSON.stringify(id)}] = ${JSON.stringify({loc, style})};
407+
globalThis.__macrosRegistry.register(this, ${JSON.stringify(id)});
408+
return ${JSON.stringify(className)};
409+
`);
410+
411+
styleObject.toString = toStringFunc as () => string;
412+
413+
return styleObject;
400414
}
401415

402416
// TODO: Why can't i move this inside the string? that way people can strip out the macro data in production?
403417
if (process.env.NODE_ENV !== 'production') {
404-
js += 'let hash = 5381;for (let i = 0; i < rules.length; i++) { hash = ((hash << 5) + hash) + rules.charCodeAt(i) >>> 0; }\n';
405-
js += 'rules += " -macro$" + hash.toString(36);\n';
406-
js += `(globalThis.__macros ??= {})[hash.toString(36)] = {loc: ${JSON.stringify(loc)}, style: currentRules};\n`;
407-
js += 'window.postMessage("update-macros", "*");\n';
418+
js += `
419+
let hash = 5381;
420+
for (let i = 0; i < rules.length; i++) {
421+
hash = ((hash << 5) + hash) + rules.charCodeAt(i) >>> 0;
422+
}
423+
let id = hash.toString(36);
424+
rules += " -macro$" + id;
425+
if (!globalThis.__macrosRegistry) {
426+
globalThis.__macrosRegistry = new globalThis.FinalizationRegistry((val) => {
427+
console.log('cleaning up,', val);
428+
delete globalThis.__macros[val];
429+
});
430+
}
431+
(globalThis.__macros ??= {})[id] = {loc: ${JSON.stringify(loc)}, style: currentRules};
432+
globalThis.__macrosRegistry.register(globalThis.__macros[id], id);
433+
window.postMessage("update-macros", "*");
434+
`;
408435
}
409436
js += 'return rules;';
410437
if (allowedOverrides) {

0 commit comments

Comments
 (0)