Changelog
Releases
All 15 @vitus-labs/* packages are released together at one version, so upgrading is a single bump. Generated from the packages' changelogs at build time; also on GitHub Releases.
2.9.0
Minor- core#403
Components and
csscreated throughconfigbeforeinit()(the default with ESM import hoisting) now expose_sel/_stylerso they work as${Comp}selectors and can be extended, render without an extra component layer once resolved, and memoize thecssthunk so a pre-init static template stays static. Bump the
react-isruntime dependency to^19.3.1.- styler#403
styled(StyledComponent)now folds into a single component at creation time (styled-components v6 semantics): the base template is followed by the extension in one rule, so the extension deterministically wins,$-transient props reach the base interpolations, and${Base}selectors still match extensions.styled(NonStyledComponent)and wrappers that hoist statics are unchanged. Dynamic styled components no longer forward the injected contextthemeto custom component targets (matches the static path).Released as a minor because both changes can alter existing output: an extension that relied on the base winning a specificity tie now loses to the extension, and a custom component that read the injected
themeprop should calluseTheme()instead (an explicitly passedthemeprop is still forwarded). - styler#403
Sheet eviction now only trims the cssText lookup caches and never the set of rules already in the DOM (it re-inserted live rules — duplicates and cascade reorder); production stores a marker instead of the cssText.
getClassName→insertshare the miss-path hash, and staticcsssnippets reached through a function interpolation are memoized from their second use. - styler#403
createGlobalStylerules are now mount-scoped and ref-counted: a dynamic global that changes value (A → B → A) replaces its previous rules instead of leaving the stale ones in effect, and rules are removed when the last instance unmounts (styled-components parity). Dynamic globals no longer hash the whole stylesheet on every client render. - styler#403
Fix SSR/hydration gaps: hydrate every token of a merged
data-href="vl-a vl-b"precedence tag (previously all SSR rules were duplicated on hydration), ship referenced@keyframesinside the component/global<style precedence>(they were missing from SSR HTML), and stopuseCSSfrom growing the shared server buffer forever (it emits no CSS on the server; documented). Fix Overlay, Iterator, Content and rocketstyle bugs found in the 2026-11 elements audit, and make two hot paths cheaper.
- rocketstyle:
mode(light, dark)values returned by transform-dimension callbacks (e.g. amodifiers"outlined" callback) are now resolved for the active mode. Before, the raw function was merged into$rocketstyleand emitted as CSS (border-color: (mode) => …). - Overlay: with nested modals only the topmost focus trap handles Tab. Before, the outer modal's trap pulled focus back to its own first control.
- Overlay: the modal focus trap skips
input[type="hidden"]and elements inside[hidden]/[inert]subtrees, so autofocus and Tab wrapping land on real controls. - Overlay:
alignX="center"/alignY="center"now fall back to the side that pulls the content back on-screen. Overflowing on the right right-aligns the content to the trigger (and the same for bottom, left and top). Before, it picked the opposite side and moved the content further off-screen. - Overlay: a hover overlay no longer stays stuck open after a nested overlay closes if the pointer left while the nested one was open. Presence tracking keeps running while blocked; only closing is held back until it unblocks.
- Overlay: a closed click-to-open overlay now listens for clicks on its trigger only. It adds a
documentlistener only while it is open. 500 closed overlays used to add about 280µs to every page click. - Iterator: in children mode,
false/nullchildren no longer count towardfirst/last/position, and the items of a nested.map()array each getitemPropsand their own positional metadata. Keyed items still keep their state across reorders. - Element / Content:
gapputs its margins on the correct side forreverseInline/reverseRows. - rocketstyle: the dimensions map, reserved-key list and omit
Setare now cached per dimension-themes object and shared across instances. Before, every instance rebuilt them on mount. - attrs / rocketstyle:
getDefaultAttrs()now includes.attrs(..., { priority: true })values in the same order as the HOC (priority attrs, then attrs).
- rocketstyle:
unistyle — responsive pipeline fixes from the 2026-11 audit:
makeItResponsiveno longer resolves CSS results with empty props when breakpoints exist. Styles whose CSS contains a function interpolation (extendCsscallbacks,colCss/rowCss, Elementcsscallbacks readingprops.theme) now take the unoptimized path and resolve with real render-time props instead of silently rendering the wrong value or dropping the line.- A
css\…`` result (or any non-plain object) used as a theme value is no longer mistaken for a breakpoint map and dropped. - The output cache is scoped per
stylesfunction andnormalizeflag: two components sharing one theme object no longer share output. - Behaviour change: responsive arrays with holes now inherit the previous breakpoint, as the README documents:
[12, null, 15]givessm: 12(wassm: 15), and a leading hole ([null, 4]) leavesxsunset (was4). createMediaQueriesdefaultsrootSizeto 16 (a missingrootSizeproducedNaNem).- The breakpoint delta optimizer re-emits declarations reset by related properties at an intermediate breakpoint (
border-top/border-color,border-width/border-top,grid-area/grid-row, logical / physical sides such asmargin-inline-start/margin-left), and ignores/* … */comments. - Faster responsive cache misses: family-indexed delta invalidation, key-indexed
styles()descriptor lookup, and a bounded content-keyed cache for fresh plain-data theme objects.
coolgrid —
Colclampssizetocolumns, sosize > columnsno longer produces a width over 100%.- hooks#398
Fix SSR hydration mismatches and several smaller hook bugs.
- SSR hydration:
useMediaQuery,useBreakpointanduseLocalStorage(and souseColorScheme/useReducedMotion) no longer read browser state in auseStateinitializer, which made React throw "Hydration failed" whenever the client's value differed from the server's. They now useuseSyncExternalStorewith a server snapshot (false/ the smallest breakpoint /initialValue). While hydrating they render the server value, then re-render with the real value straight after. Client-only renders still get the real value on the first render. useBreakpointnow shares one rAF-throttledresizelistener across all hook instances, instead of adding one listener per instance.useLocalStoragekeeps all instances that use the same key in sync within the same tab, including values that could not be persisted because of private mode or a full storage quota.useFocusTrap: focus can no longer escape. With no focusable children, Tab is always blocked. When focus is on the container itself (or anywhere outside the list), Tab moves to the first element and Shift+Tab to the last.useBreakpoint(React Native) re-computes the active breakpoint when the theme's breakpoints change.useEventListenerno longer removes and re-adds its listener on every render whenoptionsis passed as an inline object.
- SSR hydration:
Kinetic correctness fixes from the 2026-11 audit.
@vitus-labs/kinetic
- Settled transitions restore the inline styles a phase overwrote. Final
transform/filter/clip-pathvalues no longer linger afterentered(they brokeposition: fixeddescendants and clipped overflow), and the child's own inlinetransform/transitionsurvive. The finalenterToStylevalues are no longer left inline; put a resting state in the element's own style or classes. - Reversing a transition mid-flight no longer flashes the opposite phase's start state. It continues from the current state.
- Turning reduced motion on mid-transition now completes the phase instead of hanging.
Collapse: the content is a BFC (display: flow-root), so child margins are measured and the animation doesn't jump at the end. Reversing mid-animation now starts from the current height.- Phases also complete on
transitioncancel, or whengetAnimations()reports nothing running (for example a 0px → 0px collapse or adisplay: noneancestor). appearwith SSR renders the element in its enter start state instead of nothing, and the client's hydration render matches it.Stagger:onAfterLeavestill fires when a child is added during leave.onAfterEnterfires once, for the last child, the same askinetic().stagger().transition-delayis no longer copied into children'sstyle.TransitionGroup: the leaving-entry merge is O(n), with a fast path when nothing is leaving.
@vitus-labs/kinetic-presets
clipDiamond's end state now uncovers the corners.withEasingnow rewrites every segment of a multi-property transition, not just the last one.- Documented that
scaleOut,zoomOut*andpuffOutare entrances. Their names are unchanged.
- Settled transitions restore the inline styles a phase overwrote. Final
- connector-native#403
parseCSSparses leading-dot /+-signed numbers (.5→0.5) and skips balanced nested{…}blocks instead of corrupting the surrounding declarations.
2.8.0
MinorBump the
react-isruntime dependency to^19.3.0to track React 19.3.Correctness fixes:
isEqualcompares non-plain objects (Date/Map/Set/class instances) by reference instead of reporting distinct instances equal; rocketstyle.theme()keeps arrays and non-plain values intact and.config({ inversed: false })can now overridetrue; rocketstories no longer re-prepends the prefix when chaining and.config({ name })takes effect.- styler: without a
ThemeProvider, interpolations still receive an emptytheme, buttheme={}is no longer forwarded to wrapped components. - styler:
on*props are forwarded to DOM elements only when they are functions. - styler: a stray top-level
;in global CSS is no longer inserted as a (throwing) rule. - core:
init()only resets optional engine members (keyframes,createGlobalStyle,useTheme) when a full engine (css+styled) is supplied, so partialinit()calls keep them.
- styler: without a
- core#376
render(0)now renders0instead of nothing, andinit()clears optional engine members (keyframes,createGlobalStyle,useTheme) that a newly supplied engine does not provide. - all packages#386
Rebuild on
@vitus-labs/tools-*2.8.0.Build toolchain update only — the emitted JS and
.d.tsare byte-identical to the 2.7.1 build for all 15 packages. No source or public API changes. - styler#376
Add component selectors for static styled components (
${Button} { ... }resolves to its class; dynamic components throw a clear error) and function themes:<ThemeProvider theme={outer => ({ ...outer, x })}>. - styler#376
Fix stylesheet insertion: global CSS is split at top-level
;so@import/@charsetno longer breakinsertRule(and are inserted first), and boosted vs. unboosted identical CSS now get distinct class names so the boosted rule is actually inserted. Dynamic styled components without aThemeProvidernow receive an emptythemeobject instead ofundefined. - styler#376
Fix prop forwarding:
styled.svgnow keeps SVG attributes (viewBox,xmlns,d,fill,stroke*, ...), everyon[A-Z]*event handler is forwarded (capture, media, toggle, pointer, ...),inert/popover*/suppressHydrationWarningare allowed, and a customshouldForwardPropis now honoured for component targets. - kinetic: removing a
Staggersibling no longer restarts the remaining items' in-flight enter/leave (the recomputed delay is read via a ref and applied only when a phase starts). - kinetic-presets: README documents the corrected
reverse()semantics (visible end state preserved; motion direction reversed). - elements: a hover overlay no longer closes when its trigger blurs while the pointer is still over it.
- elements:
Iteratorfallback keys for unkeyed children are.${index}, so they can't collide with a user key like"1".
- kinetic: removing a
- elements#385
Overlay: a dropdown/popover dismissed by clicking outside no longer moves focus back to its trigger. Previously this happened in Safari (which doesn't focus clicked buttons), e.g. when opening a different overlay.
- elements#375
Overlay/Iterator/Element correctness fixes:
onClosefires once per close and nested overlays no longer close their parents; only the topmost overlay closes on Escape; focus returns to the trigger for dropdowns/popovers; hover overlays react to focus/blur; tooltip/popover ARIA roles; modal focus trap keeps Tab inside when nothing is focusable; parent container overflow is restored; Portal cleanup is safe and mounts before paint; Iterator preserves user keys and supports single-child fragments;equalBeforeAftercan shrink; Element re-attaches swapped refs; Overlay no longer injects component props into DOM element children; Text memoizes its$textprop. - unistyle#373
Fix responsive delta optimizer dropping re-emitted nested blocks and shorthand declarations after an intermediate override, fix unitless/length property conversion kinds (gridColumnStart, flexBasis, letterSpacing, ...), make
value()honourem,%and other output units, and remove deadspacingShorthand. - unistyle#382
Responsive breakpoint optimizer: shorthands whose longhands don't share their name prefix (
border-radius↔border-top-left-radius,inset↔top,margin-inline↔margin-left,place-items↔align-items,gap↔row-gap,grid-area↔grid-row-start,font↔line-height, …) now invalidate each other, so a declaration repeated after its shorthand reset it is no longer dropped. - coolgrid#373
Col: use the same relative unit for gap in width calc and margin, hide size-0 columns with
display: none(no longer focusable off-screen), and native Row now calls a user-suppliedonLayout. - hooks#374
Add
useIsClient,useWindowScroll,usePageVisibilityanduseOnlineStatushooks. - hooks#374
Fix hook correctness issues:
useIntersectionno longer loops with inline threshold arrays (and uses the last batched entry);useFocusTraptracks focusability attribute changes;useResizeObserver,useEventListeneranduseFocusTraphandle refs whose element mounts later;useMergedRefhonours React 19 ref cleanups;useCopyToClipboardfalls back toexecCommandwhenwriteTextrejects;useClickOutsidefires once per tap (pointerdown + composedPath);useBreakpointre-syncs after subscribing;useLocalStoragekeeps stable callbacks and re-reads on key change;useElementSizeuses the border box consistently;useMediaQueryguards a missingmatchMedia. Fix several kinetic transition correctness bugs.
kinetic:
Staggerand thedelayprop are no longer defeated by thetransitionshorthand; the delay is re-applied and cleared once entered.TransitionGroup/kinetic().group(): a leaving item keeps its position instead of jumping to the end (which cancelled its exit), and a re-added key that was in the initial render now animates in. Children without akeywarn in development.kinetic().stagger()/.group()forwardonEnter,onAfterEnter(stagger: last child) andonLeave.- Interrupted enter/leave transitions no longer leave stale classes behind.
- Animation end detection: completes via the fallback timeout when the child does not attach the ref (with a dev warning), restarts the timer when switching entering to leaving, waits for the longest running transition, and completes on the next frames when durations are explicitly zero.
kinetic-presets:
reverse()keeps the visible end state (the element is no longer hidden after entering).withDuration()/withDelay()handle comma-separated transitions,cubic-bezier(...)and decimal times like.3s, and replace an existing delay instead of adding a third time value.
- connector-emotion#371
Fix Emotion
keyframesinterpolation andcreateGlobalStyletheme access.cssstringified Emotionkeyframesobjects (_EMO_name_@keyframes…_EMO_), producing broken CSS foranimation: ${kf} 1s. Style objects are now preserved and serialized through Emotion's owncss.createGlobalStyledid not receive the context theme, so({ theme }) => …interpolations threw underThemeProvider. It now injectsuseTheme()(an explicitthemeprop still wins).
- connector-native#371
Fix several
css/parseCSScorrectness bugs in the native connector.- A nested
cssresult with its own dynamic interpolations is now treated as dynamic (previously resolved once with empty props, yielding e.g.{ width: "px color:red" }). Breakpoint results fromcreateMediaQueriesalso register as dynamic. parseCSSstrips/* */comments and//line comments (at declaration start), and splits declarations on;only outside parentheses and quotes (url(data:…;base64,…),content: ";").font-weightstays a string ('700'), as React Native requires.rem/emvalues and unitlessline-heightare intentionally not converted (documented); usepx.
- A nested
2.7.4
Patch- all packages#348
Rebuild on
@vitus-labs/tools-*2.7.1.Patch bump of the build toolchain — rolldown and rolldown-plugin-dts are unchanged from 2.7.0, so the emitted bundles are equivalent and every size budget still passes. No source or public API changes.
- all packages#348
Rebuild on
@vitus-labs/tools-*2.7.0.The build toolchain moves to rolldown 1.2.6 and rolldown-plugin-dts 0.28.2, so the published bundles are regenerated. No source or public API changes — bundle sizes shift by tens of bytes and all size budgets still pass.
2.7.0 also drops
rollup-plugin-filesizefromtools-rolldown, which removes thepacote->cacache/sigstore/node-gypsubtree from the install graph: 157 fewer packages and 5 fewer security advisories. - elements#350
Drop a redundant
useMemoin Element's axis resolution.The memo returned
{ wrapperDirection, wrapperAlignX, wrapperAlignY }, which is destructured immediately into three primitives passed straight to Wrapper — nothing downstream depends on the object's identity. Memoizing therefore cost a 7-element dependency array plus 7 comparisons per render to avoid three branches. The logic moves to a pureresolveWrapperAxes()inutils.ts.Behaviour is identical (
if (x) v = xisx || vfor these inputs). This is a simplification, not a measured speed-up: see the PR for why the local harness cannot resolve a change this size.
2.7.3
PatchAdapt to React Native 0.87 types and refresh the toolchain.
react-native@0.87regressedDimensions.addEventListener's generated types to a bareFunction, souseBreakpoint/useWindowResize(native) now annotate the handler withDimensionsPayloadand guard the optionalwindowfield.kinetic's nativeCollapseRenderergained an explicitReactElementreturn type so its declaration no longer has to name RN's internalReactNativeElement.No public API changes — dev/build tooling (
@vitus-labs/tools-*2.6.3, vitest 4.1.11, jsdom 30, biome 2.5.10, vite 8.2.2) moved to latest.
2.7.2
PatchDeep repo audit: 6 parallel auditors (memory leaks / wasted re-renders / correctness bugs / perf / bundle / security) followed by verified fixes across 8 packages. 27 new regression tests; 2821 total pass.
Correctness bugs fixed
- styler
normalizeCSS: the line-comment guard only protected//immediately after:, so protocol-relative URLs (url(//cdn...)), path double-slashes, and string contents (content: "//",content: "a b") were truncated or collapsed. The scanner now tracks quoted-string andurl(...)state and preserves those spans verbatim. - styler
splitAtRules/splitRules: brace counting ignored quotes, socontent: "{"corrupted depth tracking — an@mediablock after it was never extracted and its styles silently dropped in production (insertRulerejects the nested form). Both scanners now skip quoted spans (escape-aware). - attrs + rocketstyle ref forwarding:
useImperativeHandle(ref, () => internalRef.current, [])snapshotted the node once at mount — after a host remount (e.g.tag="div"→tag="button") the consumer's ref kept the detached old node. Replaced with a merged callback ref that re-fires per attach/detach, so refs always track the live node. - connector-native
parseCSS:!importantwas not stripped —margin: 10px !importantexpanded to invalid RN styles like{marginRight: "!important"}(throws in dev). The suffix is now stripped before dispatch. - hooks
useControllableState: functional updates computed from the render-captured value, so twosetValue(p => p+1)in one event handler yielded +1, and stale closures computed from old values. Updates now route through React's functional setState in uncontrolled mode with a current-value ref for the controlled branch andonChange.
Wasted re-renders fixed
- unistyle Provider: the context value
{ ...theme, __VITUS_LABS__: {...} }was rebuilt every render, re-rendering every theme consumer whenever the Provider's parent re-rendered. Now memoized. - core Provider: the external engine's ThemeProvider received the raw
themeprop instead of theuseStableValue-stabilized one, piercing every styled component's memo when consumers pass inline theme literals. Now passes the stabilized object. - rocketstyle
useTheme: thetheme = {}destructure default allocated a fresh object per render in no-Provider apps, missing the ThemeManager WeakMap caches and invalidatingfinalPropsuseMemo on every render of every rocketstyle component. Now a module-scope stable sentinel. - hooks
useWindowResize: resize ticks resolving to unchanged dimensions re-rendered all consumers; now bails via functional-update comparison (mirrorsuseElementSize), andonChangeonly fires on real changes. - connector-native
styled: every styled component subscribed touseWindowDimensions(), so rotation/resize re-rendered the entire tree — including fully static templates whose output can't change. Static templates now skip the hook entirely (variant chosen at creation time). - kinetic
Transition: a ~12-key config object was allocated every render but only consumed inside a[stage, delay]effect; now built inside the effect.TransitionGroupalso prunes its cachedonAfterLeaveclosure when a leaving key reappears (web + native).
Bundle
- unistyle −1 000 B gzipped (−8.9%): 238 property descriptors carried a
cssfield that was always exactlycamelToKebab(key); the field is now derived in one pass at module load.
Security hardening (audit found zero vulnerabilities — prototype-pollution guards, SHA-pinned actions, React 19 style-children escaping all verified)
- npm provenance attestations enabled (
NPM_CONFIG_PROVENANCE) — the workflow already grantedid-token: write; now it's actually used. release.ymlpassespublishedPackagesthroughenv:instead of inline${{ }}interpolation (injection-safe convention).- styler README documents the trusted-interpolation contract (same model as styled-components/Emotion) with do/don't examples.
Memory leaks: full sweep found none — every module-level cache is bounded/weak, every listener/observer has cleanup (verified, not assumed).
- styler
2.7.1
Patch- core#285
Fix
Maximum call stack size exceededinisEqualwhen comparing objects that contain self-references or mutual references.Reproduced in the wild as a consumer-app crash:
Uncaught RangeError: Maximum call stack size exceeded at isObjectEqual (index.js:156:23) at isEqual (index.js:170:9) at isObjectEqual …The recursion path is
isEqual → isObjectEqual → isEqual → …with no termination. Root cause:isEqual's docstring acknowledged it did not handle circular references, butuseStableValuecalls it on whatever props consumers pass — including props that may include React internals (fiber owners, refs), context-shaped objects with back-references, or any other graph that happens to cycle. Stack overflow.Fixed by threading a
WeakMap<object, object>of "currently comparing" pairs through the recursion. When the same(a, b)pair is re-entered, the cycle returnstrue— the structural walk will still returnfalseat any genuinely-differing leaf, so deep equality stays correct. Non-cyclic data is unaffected.Regression test coverage added:
- Self-referential objects (
a.self = a) - Mutually-referential object pairs (
a.other = b; b.other = a) - Cyclic structures with a genuine difference (still returns false)
- Self-referential arrays
- Self-referential objects (
2.7.0
Minoromit()now accepts a prebuiltReadonlySetof keys in addition to an array, and the three per-render callers feed it a stable Set so the lookup Set is no longer rebuilt on every render.Why
omitbuildsnew Set(keys)internally for O(1) lookups. When the key list is stable for a component's lifetime — which it is at every render-path caller — that Set was being reconstructed every render for nothing. The Set construction dominates the call cost when the source object is small (the usual case for props).Three hot callers, all previously passing a stable key array and paying the rebuild:
- rocketstyle (
rocketstyle.tsx,finalPropsassembly) — additionally rebuilt a 3-way[...RESERVED_STYLING_PROPS_KEYS, ...PSEUDO_KEYS, ...options.filterAttrs]array each render. Now memoized into a singleSetviauseMemo(all three sources are stable for the instance). - elements/List — built a module-scope
Setfrom the constantIterator.RESERVED_PROPS. - attrs — built the
Setonce in the factory closure fromoptions.filterAttrs(fixed at component-config time).
omitstays fully backward compatible: array callers hit the samenew Set(keys)path as before; only the internal length check moved fromkeys.lengthtokeysSet.size.Measured delta
Head-to-head microbench (median of 5 passes), realistic
finalPropscall: ~18-key mergeProps (dimension keywords + DOM/component props), 18 stable omit keys. Outputs byte-identical across all three strategies.| Strategy | V8 (Node) | JSC (Bun) | | ---------------------------------------- | --------------------- | --------------------- | | current (concat +
new Seteach render) | 1.6M ops/s | 1.5M ops/s | | memoized array (Set still rebuilt) | 1.7M ops/s (+5%) | 1.5M ops/s (+2%) | | prebuilt Set (this change) | 3.0M ops/s (+47%) | 6.5M ops/s (+77%) |Memoizing the array alone barely moves the needle — the per-render
new Setrebuild is the real cost, and passing a prebuilt Set removes it entirely.- rocketstyle (
Perf + correctness audit, round 3 — seven fixes across five packages, identified by a multi-modal codebase audit with 3-judge adversarial verification per finding.
Correctness fix (kinetic) —
nextFramenow returns a canceller that aborts both rAFs. The prior implementation returned only the OUTER rAF id, so cleanup left the inner rAF live and the transition callback fired against potentially-stale or detached elements on fast toggles (open-while-closing, StrictMode double-invoke). All 6 call sites inTransition/TransitionItem/TransitionRendererupdated in lockstep.Memory hygiene
styler:sheet.insertCacheandsheet.prepareCachewere keyed by full cssText (200–5000 B per entry) and only cleared by HMR/SSR hooks — long-running SPAs accumulated every unique cssText forever.evictIfNeeded()now bounds all three caches via the existingevictMapByPercent.kinetic:splitCache(className → string[] memoization) was unbounded module-level Map; now capped at 256 entries with the same oldest-10%-evict pattern.
Per-render allocations
coolgrid:omitCtxKeysrebuilt a 10-key Set on every Container/Row/Col render (5 components, web + native). Now uses a module-scopeCONTEXT_KEYS_SET, matching theomitKeysSet/filterAttrsSetpattern from PR #268.connector-native:styledre-spreadforwardedPropsintocreateElementdespite the object being freshly allocated one line earlier and held by no caller. Now mutates directly (mirrors the styler rawProps-mutation trick); also hoists theshouldForwardPropresolution to component-creation time.
Algorithmic / consistency
rocketstyle:removeNullableValueswas O(n²) (.filter().reduce(spread)allocates a fresh accumulator per step). Now O(n) single-pass, matching the sibling implementation in@vitus-labs/attrs.kinetic:parseTransformStringallocated a fresh statefulRegExpon every call.TRANSFORM_REnow hoisted to module scope (mirrors the existingEASING_NAMESpattern in the same file);lastIndexreset per use.
Verified by 2-of-3 adversarial judges (correctness / perf / safety lenses) per finding, with 9 separate candidates refuted and excluded. Full suite 2730+ pass; 5 new lock-in tests covering the nextFrame canceller and the multi-cache eviction.
- styler#281
Perf pass on the styler hot path — six micro-wins compounding to ~7-8% on SSR scenarios. Same engine, same output; no API or behavior changes.
styled.ts— dynamic render- Drop
delete rawProps.themeand replace withObject.assign({ theme }, rawProps)whenthemeisn't already provided. Thedeletewas poisoning V8's hidden-class shape for every dynamic render's props object; the spread keeps the shape stable. - Lazy
useRefinit for the 2-slot LRU cache — one less object literal allocated per render before the first cache hit.
sheet.ts—prepare()/insert()- 2-slot LRU in front of
prepareCacheandinsertCache. Reference compare hits beforeMap.get's hash + bucket walk, which matters on the typical SSR loop where the same component re-renders 500x with identical cssText. - No-
@fast path: when cssText contains no@-rules and no@layeris configured (~95% of styled CSS),prepare()/insert()build the rule string directly and skipsplitAtRulesentirely (regex, linear scan, two intermediate arrays, map, spread — all gone). splitAtRulesinline@-prefix dispatch: replaced thecssText.slice(i, i + 20)+ regex pattern with a 1-charcharCodeAtgate that callsstartsWithonly on a match. No per-@allocation;startsWithis a V8 intrinsic.
resolve.ts—normalizeCSS- 2-slot LRU in front of
normCache. Same shape and rationale as the sheet caches — SSR loops alternate between very few cssText values.
Bench numbers (median, single pass on the same machine; full table in
packages/styler/benchmarks/results.md):| Scenario | Pre | Post | Δ | | ----------- | ----- | ----- | ----- | | ssr-static | 674.5 | 730.4 | +8.3% | | ssr-dynamic | 400.7 | 429.5 | +7.2% | | ssr-themed | 346.1 | 371.2 | +7.3% |
CSR scenarios are within the noise floor (already cache-hit dominated by the per-tick repeated renders).
All 406 styler tests and 2776 monorepo tests pass. One test (
warns in dev when two different cssText strings produce the same hash) was updated to clear the new hot slots when bypassing the publicclearCache()to plant its synthetic collision. - Drop
- styler#282
Fix CSR regression introduced by PR #281 + further perf cleanup on hot caches.
PR #281's CI bench job showed csr-many −10.0%, csr-mount −6.2%, csr-update −6.6% vs main. The wins on SSR were real but came with these CSR regressions, which the PR shipped anyway because local bench variance hid them.
Root cause:
Object.assign({theme}, rawProps)inDynamicStyled. PR #281 replaced thedelete rawProps.themepattern withObject.assignto dodge a hypothesized V8 hidden-class deopt. But the deopt concern was misplaced —rawPropsis freshly destructured per render and discarded; nothing reads it after the function returns. TheObject.assignallocated a new object on every dynamic render, costing more than the deopt it was trying to avoid.Fix. Mutate
rawPropsdirectly. Skip the write entirely when there's no provider (csr-mount / csr-many runs withoutThemeProvider) AND the caller didn't pass an explicitthemeprop. This also savesbuildProps's for-in iteration one extra key.// Before (PR [#281](https://github.com/vitus-labs/ui-system/issues/281)): const resolveProps = rawProps.theme === undefined ? Object.assign({ theme }, rawProps) : rawProps; // After: if (theme !== undefined && rawProps.theme === undefined) rawProps.theme = theme;Hot-cache cold-miss cleanup. The 2-slot LRU hot caches in
sheet.insert(),sheet.prepare(), andnormalizeCSS()ran 4 reads + 4 compares before falling through toMap.geton cold-miss — paid by every csr-many call (50 distinct cssText per tick → 100% miss rate). Nested so the cold-start path is a singlenullcheck:// Before: if (hotA !== null && hotA.key === key) return hotA.value; if (hotB !== null && hotB.key === key) { /* promote */ } // → 4 ops on cold start // After: if (hotA !== null) { if (hotA.key === key) return hotA.value; const hotB = this.hotB; if (hotB !== null && hotB.key === key) { /* promote */ } } // → 1 op on cold start (hotA === null), same cost as before on hitAll 412 styler tests + 2782 monorepo tests pass; lint and typecheck clean.
elements:Overlay(modal) auto-traps focus and locks page scroll while open. Focus selector widened to includecontenteditable,video[controls],audio[controls],summary. Hooks inlined — no@vitus-labs/hookspeer.hooks: adduseLocalStorage,useEventListener,useCopyToClipboard,useResizeObserver.unistyle: addbetween(breakpoints, minKey, maxKey)for closed-range media queries; dev warning for unknown theme keys; CI-enforcedITheme↔propertyMapparity test.styler: hash-collision dev warning insheet.kinetic: fixStagger.nativedropping per-childdelay;Transition.nativehonorsuseReducedMotion.connector-emotion+connector-styled-components: per-connector smoke tests; brokenuseCSSshims removed (now styler-only).
Performance pass on
@vitus-labs/rocketstyleand@vitus-labs/attrs:attrsandrocketstyle: wrap the innermostEnhancedComponentinmemo(). attrs'attrsHocalready stabilizes its output viauseStableValue+useMemo; rocketstyle'srocketstyleAttrsHocnow follows the same pattern. With both, a content-equal parent re-render bails at the memo boundary instead of walking the HOC stack.rocketstyleAttrsHoc: brought to parity withattrsHoc(PR #170 pattern). AddsuseStableValue+useMemo+ a fast path for "no.attrs()configured" — the common case for rocketstyle components built with.theme()/dimensions only, which previously rebuilt every prop merge on every render.usePseudoState: handlers ref-captured. Consumers passing inlineonMouseEnter/onMouseLeave/etc (the common React idiom) no longer churn the wrapped handler identities every render, so downstream memoization actually takes effect on interactive components.useTheme: drop the pointlessuseMemowrapping{ theme, mode, isDark, isLight }. All call sites destructure the primitives; the memo bookkeeping cost more than the recomputation.useRefhooks (both packages): add empty[]deps touseImperativeHandleso the getter isn't re-registered every render.chainOrOptions+chainReservedKeyOptions(rocketstyle): replacereduce-with-spread-accumulator(O(K²)) with single-pass mutation (O(K)).validateInit(rocketstyle): replace nested.some()with module-levelSetlookup (O(R + D) instead of O(R × D)).calculateChainOptions(both): drop the deadconst result = {}allocation in the early-return path.
Dead code removed:
rocketstyle/constants/booleanTags.ts: 33-line constant array imported by nothing in production. Only its own test referenced it.rocketstyle/utils/theme.ts: orphancalculateChainOptions(a 2-arg variant unused outside its own test; the live impl lives inutils/attrs.ts).rocketstyle.tsx: duplicateIS_ROCKETSTYLE+displayNameassignment block.
- elements#278
Performance and correctness pass on
@vitus-labs/elements:ElementandWrapperare now wrapped inmemo()— parent re-renders no longer re-execute the full body when props are referentially stable. VL statics (displayName/pkgName/VITUS_LABS__COMPONENT) attach to the memoized wrapper so rocketstyle/attrs detection still works.ElementWRAPPER_PROPSliteral removed — keys inlined into the JSX so the build-then-spread copy pass disappears.WrapperCOMMON_PROPSliteral removed the same way.Wrapper's three separateuseMemocalls (normalElement/parentFixElement/childFixElement) collapsed into one — each render previously paid the dep-array compare cost for all three even though only one shape is used.ElementmergedRefis now ref-stable. The previoususeCallbacklistedexternalRefin its deps, so an inline parent ref-callback caused React to detach/attach the DOM ref every render.useOverlay:onOpen/onCloseref-captured. The previous dep array re-ran the lifecycle effect on every parent render and fired spuriousonClose/setUnblockedcleanup callbacks while the overlay was still open.useOverlay:isNodeOrChildcurry replaced with two stable predicates allocated once. The old shape allocated two fresh closures per click event.useOverlay: click listener usesdocumentinstead ofwindow(one fewer propagation hop, matchesuseFocusTrap's convention).useFocusTrap:for…ofoverNodeListswapped for an index loop (no iterator-protocol allocation). MutationObserver refreshes coalesced viarequestAnimationFrameso a burst of child mounts doesn't re-runquerySelectorAllper mutation.Element/equalize: skip the style write when both sides are already equal AND non-zero. Breaks a potentialResizeObserverloop in real browsers without affecting jsdom (where sizes always read 0).Overlay/component: dropped twouseMemocalls over primitive results (passHandlers,ariaHasPopup) where memo bookkeeping exceeded the recomputation cost. Replaced...(cond ? { … } : {})ternaries with conditional property assignment — no per-render{}allocation.Util/component: droppeduseMemoover a one-shot stringjoin(' ').positionMath: hoisted['dropdown', 'tooltip', 'popover'].includes(type)into a module-levelSetlookup. The array literal allocated percomputePositioncall (throttled scroll/resize hot path).Content/styled: deduped identicalequalColsCSSandtypeContentCSSliterals into oneFLEX_1constant.
Dead code removed:
types.ts: dropSimpleHoc,CssCallback,isEmpty,Ref,ExtractProps,VLForwardedComponent— zero monorepo consumers;SimpleHoc/ExtractPropswere also drift hazards (different shapes in attrs/rocketstyle).Element/constants.ts: dropRESERVED_PROPS(unused;Iteratorhas its own); dropkeygenfromEMPTY_ELEMENTS(removed from HTML5 spec in 2017).helpers/Wrapper/types.ts: dropReference = unknown(unused).
-
elements/Overlay: stripbody.overflowmanagement fromuseScrollReposition.useScrollLockis now the sole owner, gated onisContentLoaded. Fixes a silent permanent scroll-lock on async-mount modals. -
elements/Overlay/useOverlay: removeprevFocusRef(set, never read) and its dead effect. -
kinetic:Transition.tsxhonors thedelayprop (was advertised, ignored on web). -
hooks: dropuseFocusanduseHoverfrom the native re-exports — they return DOM-only handler names that no RN component fires. -
coolgrid: deleteContainer/utils.ts:getContainerWidth— exported but only consumed by its own tests.
-
- rocketstyle#266
calculateStylingAttrs: drop per-render allocations on the dimension-resolution hot path. ReplaceObject.keys(dimensions).forEachandObject.entries(result).forEachwithfor…inloops, and replace the per-dimensionnew Set(Object.keys(dimensions[key]))keyword lookup with directObject.hasOwnmembership.Why
calculateStylingAttrsruns in theEnhancedComponentrender body (rocketstyle.tsx:351) — once per render of every rocketstyle-wrapped component, not memoized. The old implementation allocated, per render: a keys array + closure forObject.keys(dimensions).forEach, an entries array + closure forObject.entries(result).forEach, and — for each unresolved boolean dimension — a freshSetplus its backingObject.keysarray. TheSetis rebuilt every render even thoughdimensions[key]is a stable config object, so the keyword membership was recomputed from scratch each time.Object.hasOwn(dimensions[key], k)is the exact equivalent of the priorkeywordSet.has(k)(own enumerable keys of a plain config object) with zero allocation, and matches thefor…inprecedent already established bypickStyledAttrsdirectly above.Measured delta
Head-to-head microbench (median of 5 passes, interleaved to neutralize drift), realistic fixture: 3 dimensions (~4–5 keywords each),
useBooleanson, props = mix of dimension keywords + typical non-dimension props (className,onClick,children,data-*,aria-*,style, …). Outputs byte-identical between old and new.| Engine | Old | New | Δ | | --------- | ---------- | ---------- | -------- | | V8 (Node) | 2.0M ops/s | 2.3M ops/s | +13% | | JSC (Bun) | 1.7M ops/s | 8.6M ops/s | +79% |
JavaScriptCore optimizes the
for…in+Object.hasOwnform far better thanObject.keys/forEach/Set; V8 gains are smaller but consistent. The rewrite is simpler code and faster on both engines. - unistyle#270
Fix
borderCollapse: it was declared in theIThemeprop type but had nopropertyMapdescriptor, so passing it type-checked yet emitted no CSS. Added the missingsimpledescriptor soborderCollapse: 'collapse' | 'separate'now producesborder-collapse: …. Verified by diffing all 305 typedIThemekeys against the property map — this was the only typed-but-unmapped key (the other,keyframe, is intentionally consumed by theanimationspecial handler). - hooks#276
elements/Overlay: stripbody.overflowmanagement fromuseScrollReposition.useScrollLockis now the sole owner, gated onisContentLoaded. Fixes a silent permanent scroll-lock on async-mount modals.elements/Overlay/useOverlay: removeprevFocusRef(set, never read) and its dead effect.kinetic:Transition.tsxhonors thedelayprop (was advertised, ignored on web).hooks: dropuseFocusanduseHoverfrom the native re-exports — they return DOM-only handler names that no RN component fires.coolgrid: deleteContainer/utils.ts:getContainerWidth— exported but only consumed by its own tests.
- connector-native#271
Fix two correctness bugs that broke responsive and themed styling on React Native:
-
Array interpolations were stringified to garbage.
unistyle'smakeItResponsiveemits an array of per-breakpoint results ([CSSResult, '', CSSResult, …]) and feeds it into the engine'scssas an interpolation. The nativecssresolver had no array branch, so the array fell through to the object path and produced"0: [object Object]; 1: ; …"instead of merged styles — i.e. every responsive (breakpoint-object) prop was broken on native. Added array flattening (mirrors the web styler'sresolve.ts), so entries resolve and cascade correctly with later breakpoints overriding earlier ones. -
The context theme was never injected. The native
styledcomponent resolved templates with the raw props only — it never calleduseTheme(), so${(p) => p.theme.x}interpolations resolved toundefined, andmakeItResponsive(which readsprops.theme) saw an empty theme. Nowstyledinjects the context theme into the resolve props (mirroring the web styler), without forwardingthemeto the underlying RN component. A consumer-passedthemeprop still takes precedence.
Both paths are now covered by tests, including an end-to-end responsive pipeline test (
createMediaQueries→ array →css) verifying the mobile-first breakpoint cascade. -
- connector-native#272
Fundamentally fix the two remaining React Native styling gaps:
-
Multi-value box shorthands now expand correctly.
padding: 8px 16px,margin: 0 auto,border-radius: 4px 8px 12px 16px, etc. previously parsed to just their first token (padding: 8), because React Native has no multi-value shorthand. They now expand into RN longhands following the CSS box-model value rules: edge shorthands (margin/padding/inset/border-width) →*Top/*Right/*Bottom/*Left,border-radius→ per-corner radii, andgap: row col→rowGap/columnGap. Single values are unchanged (RN supports them);calc()and elliptical (/) radii are left untouched. -
Responsive breakpoints are now reactive to rotation / resize.
createMediaQueriesdeferred itsDimensions.get('window').widthcheck from breakpoint-call time toresolve()time, so the current width is read on every resolve instead of being baked into upstream caches (e.g.makeItResponsive's per-theme cache). The nativestyledcomponent subscribes touseWindowDimensions()so a rotation/resize re-renders and re-resolves — matching how the browser re-evaluates@media. Previously a responsive component kept its first-render breakpoint until something else forced a re-render.
-
2.6.2
Patch- styler#242
Five targeted hot-path optimizations across
styled,useCSS,sheet,resolve,shared, andforward.What changed
DynamicStyledLRU-2 cacheRef (styled.ts) — the previous single-slot ref missed every render when a prop alternates between two values (toggle / hover / animation frame), forcing repeatedgetClassName/preparework even though both class names were already cached upstream. Two slots cover the alternation case without meaningfully growing per-instance state.splitAtRules/splitRuleschar access (sheet.ts) —cssText[i]allocates a fresh 1-char string in V8 per iteration;cssText.charCodeAt(i)returns a primitive. Material on long stylesheets with at-rule blocks.CSSResult._isDynamicmemoization (resolve.ts+shared.ts) —isDynamicwas rescanning the same nested CSSResult sub-trees every time a consumer (styled, useCSS, createGlobalStyle, nested interpolation) asked. Lazy-cache the result per instance; CSSResults are created once at module level and reused everywhere.buildPropsref skip (forward.ts) — when the caller passes noref, the destructure default isundefined. Assigning that as an own-property still costs React a traversal during reconciliation. Skip the assignment forundefined; explicitref={null}is preserved verbatim.useCSSsingle-pass content check (useCSS.ts) — replaces threecssText.trim()calls per render with onecssText.length > 0check.normalizeCSSalready strips leading/trailing whitespace, so the lengthier.trim()invariant was redundant.
Bench impact (bun 1.3.13, react 19.2.6, jsdom, three-run median):
| Scenario | Before (ops/s) | After (ops/s) | Δ | | ----------- | -------------- | ------------- | -------- | | ssr-static | 489.8 | ~712 | +45% | | ssr-dynamic | 412.9 | ~427 | +3–5% | | ssr-themed | 337.7 | ~360 | +6–7% | | csr-mount | 12195 | ~14000 | +5–20% | | csr-update | 10669 | ~13000 | +0–27% | | csr-many | 16958 | ~19500 | +15% |
csr-updatewas previously #3 (behindstyled-componentsand@emotion/styled); after the LRU-2 it ties or leads. SSR scenarios were already first; the static path gets the largest absolute win because most page CSS is static and now skips per-render rescans entirely. CSR variance is inherent — React's own work dominates these scenarios — but every reproduced delta is in styler's favour.Bundle: 4.65 KB → 4.72 KB gzipped (+70 B). Under the 12 KB size budget.
Verification: 393 styler tests + 2688 monorepo tests pass; biome / tsc /
pkgs:buildall green; all 6 bench scenarios show styler in the top spot vsstyled-components6 and@emotion/styled11. - styler#253
CSSResult._staticResolvedcache: memoize the resolved CSS string onCSSResultinstances thatshared.ts#isDynamichas classified as static. Safe because props don't affect the output when there are no function interpolations — the resolved string is then a pure function of the template literal.Why
shared.ts#isDynamicalready populates_isDynamicon everyCSSResultreached at styled-component / globalStyle creation time. The follow-upresolveValuepath re-walked the template'sstrings+valueson every render even when_isDynamic === falsewas already known. The common pattern is a shared static snippet (e.g.const base = css\padding: 12px;``) interpolated into many dynamic components — that snippet's resolve work was paid once per dynamic render of every consumer. Memoizing on the instance turns that into one resolve per snippet, total.Measured delta
Same-process microbench (median of 3 runs, bun 1.3.13 + tinybench, runnable at
packages/styler/benchmarks/perf-audit-bench.tsx):| Helper | Old ops/s | New ops/s | Δ | | ------------------------------------------------------------------- | --------- | --------- | ------------------- | |
nested-static resolve(8 repeated resolves of one shared snippet) | 2.6M | 6.5M | +149.4% (~2.5×) |The 8-repeat fixture models the realistic case: one static
css\…`` snippet that gets interpolated into many dynamic styled components. First call computes + caches; subsequent calls return the cached string in O(1).Other ideas explored and dropped
I also benched two other candidates in this round and dropped them after the numbers came in:
normalizeCSSslice-batching (replace per-charout += css[i]with run-basedsliceappends): +19% on long CSS strings but −15% on short CSS. The flushRun closure overhead dominates for short inputs. Real-app CSS is mixed, so a net regression risk on the common medium-length case wasn't worth keeping.sheet.insertCache/prepareCachesplit byboost(avoid${cssText}\0allocation in boosted lookups): when measured fairly with pre-allocated maps (matching production class-field lifetimes), the delta was +0.2% — noise. The string allocation V8 paid was already amortized; doubling the map count for ~0 gain isn't worth the complexity.
Verification
- 393 styler tests pass (no new tests — existing
resolve/ nested-CSSResult coverage exercises the new memoized path) - 2689 monorepo tests pass
bun run lint,bun run typecheckclean
- styler#254
Add behavioural lock-in tests for three perf-critical paths shipped earlier this session whose original tests were lost during PR #242's squash-merge.
What's tested
DynamicStyledLRU-2 cacheRef alternation (styled.test.tsx) — spy onsheet.getClassNameand assert zero additional calls across 6 alternation renders after both slots prime. Locks in the LRU-2 cache-hit behaviour from PR #242. Without this, a future regression that quietly broke the two-slot ring buffer would only show up via downstream perf signals.CSSResult._isDynamicmemoization (shared.test.ts) — four tests covering populate-on-first-call (static + dynamic), cache-on-subsequent-call (via sentinel mutation ofvalues), and nested-CSSResult propagation. Locks in the PR #242 memo behaviour.CSSResult._staticResolvedcache (resolve.test.ts) — four tests covering populate-on-first-resolveValue, cache-hit via sentinel mutation, no-cache for dynamic CSSResults, and fallthrough when_isDynamicis unclassified. Locks in the PR #253 static-resolve memoization.
Why now
The follow-up audit found these three perf-critical behaviours had no behavioural tests on
main. The original tests I added in PR #242's correction commitf4226464weren't captured in the squash because auto-merge had already snapped its squash body to the prior commits. Without tests, a future regression silently breaks the cache hit/miss path — downstream perf signals are too slow.No production code changes; tests only.
Verification
- 403 styler tests pass (+10 from this PR)
- 2699 monorepo tests pass
- Coverage: lines 99.34%, statements 98.71%, branches 94.46%, functions 98.45% — all above thresholds
bun run lint,bun run typecheckclean
- attrs#246
removeUndefinedProps: switch fromObject.keys(props).reduce(...)to a directfor...inloop.Why
The function fires on every content-equal re-render via
attrsHoc'suseMemobody. The priorreduceoverObject.keys(props)allocated an intermediate keys array per call. The for-in loop iterates the same own enumerable keys (React props are always plain objects) without the array allocation.Verification
- 83 attrs tests pass (existing suite exhaustively covers
removeUndefinedProps: undefined-stripping, null/false/0/'' preservation, all-undefined, empty-object edge cases) - 2688 monorepo tests pass
bun run lint,bun run typecheckclean
Honest framing
Structural cleanup, not a measurable headline perf win. No microbench in-tree for attrs, so no claimed delta. The win is one fewer array allocation per
attrsHocrender — it compounds across deep attrs-wrapped trees but is below single-component noise. - 83 attrs tests pass (existing suite exhaustively covers
- elements#244
Three small structural cleanups in
elements. No public API or behavioural changes.Changes
-
Iterator: fuse
filterValidItems+detectKindinto one scan (helpers/Iterator/component.tsx). The previous code allocated an intermediate filtered array, then iterated it again to detect whether the surviving items were uniformly simple (string/number) or complex (objects). The newfilterAndDetectKindbuilds the filtered array and detects kind in a single pass, then early-exits on mixed shape. Saves one full array allocation + traversal per data-driven Iterator render. The 48 existing Iterator tests cover the behaviour; all still pass. -
Text: drop the per-render
renderContentclosure (Text/component.tsx). The component was creating a wrapper function inside its render body and immediately calling it. Inlined the JSX directly — same output shape, one fewer function allocation per render. -
Overlay: hoist the
closeOnclick-kinds array (Overlay/useOverlay.tsx). The click-listeneruseEffectwas allocating a fresh['click', 'clickOnTrigger', 'clickOutsideContent']array on every re-run for anArray.includescheck. Replaced with a module-scopedReadonlySetchecked viaSet.has. Same semantics, one fewer allocation per effect re-run.
Verification
- 271 elements tests pass (no new tests added — the existing suite covers all three changes)
- 2694 monorepo tests pass
bun run lint,bun run typecheck,bun run pkgs:buildall green
Honest framing
These are structural/allocation cleanups, not headline perf bumps. The package has no microbench in-tree, so I am not claiming a measurable delta — the wins are theoretical (fewer allocations per Iterator render, per Overlay effect re-run, per Text render). They compound at scale (long lists, frequent overlay state changes, large text-heavy trees) but are below the noise floor of any single-component scenario.
-
- rocketstyle#247
Four small structural cleanups across the render path. No public API or behavioural changes.
Changes
pickStyledAttrs(utils/attrs.ts) — switch fromObject.keys(props).reduce(...)to a directfor...inloop. Fires once per render of every rocketstyle-wrapped component; drops the intermediateObject.keysarray allocation.isShallowEqualRocketstate(rocketstyle.tsx) — replaceObject.keys(a)+Object.keys(b)with twofor...inscans. Same key-walking semantics, two fewer transient string-array allocations per render.getThemeByMode(utils/theme.ts) — recursive theme walker: samereduce→for...inswap. Called inside cacheduseMemoblocks (one per theme/mode transition), so smaller payoff than per-render helpers but keeps the pattern consistent.PSEUDO_AND_META_KEYShoisted (constants/index.ts+rocketstyle.tsx) — the render body was allocating a fresh[...PSEUDO_KEYS, ...PSEUDO_META_KEYS]6-element array on every render to feedpick(). Pre-merged the constant at module scope.
Verification
- 236 rocketstyle tests pass (existing suite exhaustively covers
pickStyledAttrs,isShallowEqualRocketstate's shallow-equal contract,getThemeByMode's recursive resolution, and the pseudo-state pickup path) - 2688 monorepo tests pass
bun run lint,bun run typecheckclean
Honest framing
Structural cleanup, not a measurable headline perf win. No microbench in-tree for rocketstyle, so no claimed delta. The wins are a handful of array allocations skipped per render — they compound across deep rocketstyle component trees (large design systems with many wrapped primitives) but live below single-component noise.
- unistyle#249
Five structural cleanups across the responsive engine. No public API or behavioural changes.
Changes
createMediaQueries(responsive/createMediaQueries.ts) —Object.keys.reduce→ for-in + direct mutation. Avoids the keys array allocation + reduce callback overhead per breakpoint setup.shouldNormalize(responsive/normalizeTheme.ts) —Object.values(props).some(...)→ for-in early-exit. Drops the values array allocation; the earlyreturn trueis hit by any responsive token so most calls bail out quickly.normalizeTheme(responsive/normalizeTheme.ts) —Object.entries.forEach→ for-in. Avoids the entries-tuple array allocation per theme normalization.transformTheme(responsive/transformTheme.ts) — same pattern, applied to outer (theme) and inner (object-shape value) loops. Two entries-array allocations skipped per pivot.optimizeTheme/shallowEqual(responsive/optimizeTheme.ts) — twoObject.keysallocations replaced with for-in counting (same pattern as rocketstyle'sisShallowEqualRocketstate).alignContentisReverted check (styles/alignContent.ts) —['inline', 'reverseInline'].includes(direction)→ direct===comparison. Avoids the per-call 2-element array allocation on a path that fires for every styled component with adirectionprop.
Measured deltas
Same-process microbench (median of 3 runs, bun 1.3.13 + tinybench, runnable at
packages/styler/benchmarks/perf-audit-bench.tsx):| Helper | Old ops/s | New ops/s | Δ | | ------------------------------------------- | --------- | --------- | ------------- | |
createMediaQueries(5 breakpoints) | 18.8M | 21.6M | +15.9% | |shouldNormalize(5-prop theme) | 20.2M | 24.3M | +20.3% | |shallowEqual(5-key style objects, equal) | 23.2M | 24.1M | +4.0% | |alignContent isRevertedcheck | 24.5M | 24.6M | +0.3% (noise) |The
shallowEqualimprovement is smaller than the rocketstyle equivalent because the early-exita === breference check dominates; thealignContentchange is below noise but still a real allocation reduction. The structural argument stands for both — they just sit below tinybench's resolution for tiny inputs.Verification
- 207 unistyle tests pass (existing suite covers all five helpers via the responsive pipeline)
- 2688 monorepo tests pass
bun run lint,bun run typecheckclean
- coolgrid#245
Two small structural cleanups in
useContext.tsx. No public API or behavioural changes.Changes
- Drop the
pickThemePropswrapper. It was a one-line indirection aroundpick(props, keywords)used at a single call site. Inlined thepickcall and removed the unusedPickThemePropsexported type (no external consumers —useContext.tsxis not re-exported fromindex.ts). getGridContext: direct property access onpropsfor top-level keys. Callers always pass a plain object (apick()result or a user-supplied literal), so(props as Obj).columnsis equivalent toget(props, 'columns')but skipsget's path-parsing + safety-guard loop. The nested theme lookups ('grid.columns'/'coolgrid.columns') still go throughgetbecause they have real nested paths.
Verification
- 77 coolgrid tests pass (no new tests — the existing suite covers
getGridContext,useGridContext, and the Container/Row/Col consumer paths) - 2688 monorepo tests pass
bun run lint,bun run typecheckclean
Honest framing
Structural cleanup, not a measurable headline perf win. Two
getcalls saved pergetGridContextinvocation (which fires once per Container/Row/Col render), plus one less function call peruseGridContext. No microbench in-tree, so no claimed delta — the wins are theoretical and compound across deep grid trees but are not visible at single-component granularity. - Drop the
- hooks#251
useBreakpoint: build the sorted[name, min]tuples via a for-in scan + push instead ofObject.entries(breakpoints).sort(...). Applied to both the web (useBreakpoint.ts) and React Native (useBreakpoint.native.ts) variants.Why
The
Object.entries(...)call allocated an intermediate tuple-array that the subsequent.sort(...)mutates in place anyway. for-in + push builds the array we actually want directly, while also picking up atypeof value === 'number'type-guard along the way (kept the runtime contract; satisfiesnoUncheckedIndexedAccesscleanly).Wrapped in
useMemo([breakpoints])so this runs only when the breakpoints reference changes (typically once per Provider mount).Measured delta
Same-process microbench (median of 3 runs, bun 1.3.13 + tinybench, runnable at
packages/styler/benchmarks/perf-audit-bench.tsx):| Helper | Old ops/s | New ops/s | Δ | | ------------------------------------- | --------- | --------- | ---------- | |
buildSortedBpTuples(5 breakpoints) | 4.9M | 8.8M | +80.3% |The for-in + type-guard variant is materially faster than
Object.entries(...).sort(...). Useful even though useMemo caches the result — the cache miss happens at least once per Provider mount.Verification
- 2688 monorepo tests pass
bun run lint,bun run typecheckclean
- rocketstories#248
Five O(n²) → O(n) cleanups in the story-generation code paths. No public API or behavioural changes.
Changes
createControls(utils/controls.ts) —Object.entries.reducewithreturn { ...acc, [key]: value }per iteration was O(n²) (every assignment cloned the whole accumulator). Replaced with for-in + direct mutation.convertDimensionsToControls(utils/controls.ts) — same pattern. O(n²) → O(n).disableDimensionControls(utils/controls.ts) — nestedacc = { ...acc, ...disableControl(item) }reduce was O(n²) over the total number of dimension values. Replaced with two-level for-in walk. Removed the now-unused internaldisableControlhelper, and tightened thedimensionsparameter type fromRecord<string, boolean>toRecord<string, Record<string, unknown>>(the real runtime shape — the prior type lied about the input).extractDefaultBooleanProps(utils/dimensions.ts) — same pattern. O(n²) → O(n).parseProps(utils/code.ts) — same pattern, with threereturn { ...acc, [key]: value }branches consolidated into a single mutation path.
These functions all run at story-creation time (once per story load in Storybook). For dimension-heavy components — typical design-system buttons run 4-8 dimensions with 5-10 values each — the O(n²) builds add up to thousands of unnecessary object clones.
Verification
- 136 rocketstories tests pass (no new tests — existing suite covers all five functions:
createControls,convertDimensionsToControls,disableDimensionControls,extractDefaultBooleanProps,parsePropsvia the code-generation paths) - 2688 monorepo tests pass
bun run lint,bun run typecheckclean
Measured deltas are reported in the PR description (added to
perf-audit-bench.tsx). - connector-native#250
Three structural cleanups in the React Native CSS connector. No public API or behavioural changes.
Changes
styled.tsprop filter loop —for (const key of Object.keys(props))→for (const key in props). Saves the keys array allocation on every native styled render.createMediaQueries.ts—Object.keys.reduce→ for-in + direct mutation. Mirrors the same change in@vitus-labs/unistyle'screateMediaQueries.css.tsstyleObjectToString— extracted theObject.entries(o).map(([k,v]) => …).join('; ')pattern (two arrays + a join) used inresolveInterpolationinto a dedicated single-pass for-in concat helper. Saves the entries-tuple array + transformed array + the implicit array.join()consumes — three allocations skipped per nested-style stringification.
Measured deltas
Same-process microbench (median of 3 runs, bun 1.3.13 + tinybench, runnable at
packages/styler/benchmarks/perf-audit-bench.tsx):| Helper | Old ops/s | New ops/s | Δ | | ------------------------------------------ | --------- | --------- | ----------- | |
filterForwardedProps(12-key props) | 5.1M | 5.4M | +6.2% | |createMediaQueries(5 breakpoints) | 19.4M | 23.3M | +19.9% | |styleObjectToString(5-key style object) | 3.3M | 21.5M | +553.5% |styleObjectToStringis the biggest single win — the priorentries.map.joinchain allocated three intermediate arrays per call; the for-in concat skips all of them.Verification
- All connector-native tests pass via the monorepo suite (135 files, 2688 tests pass)
bun run lint,bun run typecheckclean
2.6.1
Patch- styler#231
Add a tracked CSS-in-JS perf benchmark at
packages/styler/benchmarks/. Run withbun run benchfrom the styler package. Compares@vitus-labs/styleragainststyled-components6 and@emotion/styled11 on six scenarios: SSR (static / dynamic / themed) + CSR (mount / update / many distinct components).Documents the runtime perf landscape and serves as a regression check — a >10% drop on any styler row vs
results.mdshould be investigated before merging.No runtime change; this only adds bench infra + devDependencies (
jsdom,tinybench) to styler. - styler#233
Cache the pre-built ReactElement for the no-extra-props case of static
styledcomponents.Most
<MyStyled />call sites pass no props beyondref— the destructure,buildPropsiteration, andcreateElementcalls produce the same element shape every render. Pre-build that element once at component creation and short-circuit in the render fn whenrawPropsis empty andrefis nullish.Impact: styler's overhead-over-bare-React for static SSR drops from ~0.065 μs/render to ~0.008 μs/render (~88% reduction). Net effect on full SSR throughput is +3–4% because React's
renderToStringitself dominates the remaining cost. Most-benefit consumers: pages that emit many static styled components with no extra props (typical layout/typography building blocks).ReactElement values are immutable so sharing the cached element across renders is safe; React still treats each render as a fresh tree by identity.
- kinetic#239
Perf + correctness micro-fixes from a
react-doctortriage (valid findings only; tool false-positives documented, not actioned):nativeParsers: hoisteasingNamesto a module-levelSet— was an O(n).includes()re-allocating a 5-element array per parsed transition token. Dropped a provably-deadtype &&guard (the regex group(\w+)guarantees a non-empty match).nativeAnimations: replace the O(n·m).find()-in-loop with a pre-built type→valueMap..find()-first semantics are preserved exactly (the Map is built skip-if-present, so a repeated transform type keeps its FIRST value, not last).
Behaviour is unchanged. New
nativeAnimations.test.ts(20 cases) pins the transform-merge parity, identity fallbacks, the non-transform style path,getPrimaryTransition, andmergeStyles— net coverage rises.
2.6.0
Minor- elements#229
Add a
LoosePropsfallback overload toIteratorComponentandListComponent.What changed
Iterator and List previously declared three call signatures (Simple, Object, Children). After 2.5.0 fixed the iterator-prop types for forwarding, one residual remained:
(typeof Wrapper)['$$types']['data']— derived via rocketstyle's 4-overload-awareExtractProps— is a wide union of every overload'sdata. Passing it back into<List data={…}>had no overload to bind to:- Simple wants
SimpleValue[]— union too wide. - Object wants
ObjectValue[]— union too wide. - Children doesn't take
dataand requireschildren— fails.
A fourth
(props: LooseProps & extras) => ReactNodeoverload gives the wide union a binding home. The narrow overloads still drive per-mode T-inference for direct callers; the loose fallback only matches when nothing narrower does.Result
type Props = { list?: (typeof MyList)["$$types"]["data"] }; const Component = ({ list }: Props) => <List data={list} component={Item} />; // ^^^^^^^^^^ // Pre-fix: no overload matches the wide union. // Post-fix: binds to LooseProps overload, compiles cleanly.Trade-off
Heterogeneous arrays like
(string | User)[]now compile (was rejected). Runtime handles per-item dispatch — the type-side fallback exists so forwarding round-trips work. If you want to reject mixed arrays, narrow yourdatatype before passing it.Why Option B (overload addition) over Option A (
children?on ChildrenProps)Option A would have made
<List />(no data, no component, no children) type-allowed — that's a meaningful loss of "you must do something" enforcement. The added overload preserves Children'schildren: ReactNoderequirement and only widens for legitimately-wide inputs. - Simple wants
2.5.0
Minor- elements#227
Relax
Iterator/Listiterator-prop types to support prop-forwarding patterns.What changed
The per-mode discriminators on
SimpleProps/ObjectProps/ChildrenPropspreviously used?: nevermarkers to mutually exclude props across branches (PR #199). Those markers broke any pattern that derives aPropstype from a wrapper and forwards back to JSX:type Props = Partial<(typeof MyList)["$$types"]>; const Component: FC<Props> = (props) => <MyList {...props} data={contacts} />; // ^^^^^^^^^^ // TS errors: spread's `valueName: string | undefined` doesn't fit // ObjectProps's `valueName?: never` slot, because `Partial<union>` // merges branches' values and the `string` from SimpleProps leaks // through into the spread.The
?: nevermarkers are dropped.valueName,children,data,component,itemKey,itemProps,wrapPropsnow share compatible signatures across all three branches:valueName?: stringon every branch (was:?: neveron Object/Children).children?: ReactNodeon Simple/Object (was:?: never).data?: Array<…>,component?: ElementTypeon Children (was:?: never).itemKey/itemProps/wrapPropsunify on a looseLooseItem = SimpleValue | ObjectValue | Record<string, SimpleValue>callback param. Object branch keepskeyof Tnarrowing onitemKeyfor direct callers.
Trade-off (what's lost)
Direct call-site discrimination:
<List data={users} valueName="x" />no longer errors (was: rejected becausevalueNameis meaningless on object iteration). Runtime still ignores valueName for object arrays; the call is type-safe but semantically a no-op.<List data={users}>{kids}</List>no longer errors (was: rejected because data + children mode-mix). Runtime still picks data-iteration.- Per-
Tnarrowing insideitemProps/wrapPropscallbacks goes away (item isLooseItem, notUser). Direct callers add an explicit annotation if they need concrete-T access:itemProps={(item: User) => …}.
What's kept:
- Discrimination via
data's element type (Simple vs Object) still applies — overload resolution picks the right branch. - ChildrenProps's
children: ReactNode(required) still differentiates the children mode at call sites that provide it. keyof Tnarrowing onitemKeyfor the Object branch (direct callers benefit from key-completion against concrete T).
Why
The forwarding pattern is broadly used (every parent component that exposes a wrapped iterator's surface). The discrimination caught a small class of no-op mistakes (
valueNameon object arrays). The cost / benefit favors forwarding. - rocketstyle#227
.attrs()callback form now keeps literal narrowing — no moreas constworkarounds.What changed
.attrs()is now an overloaded interface with two signatures:- Object form:
<P extends TObj = {}>(param: P & Partial<NoInfer<DFP>>, …). - Callback form:
<P extends TObj = {}>(param: AttrsCb<DFP & P, Theme<T>>, …).
The callback signature uses
AttrsCb<DFP & P, …>directly so the return literal narrows contextually againstDFP. Previously the single branched signature combined with thePartial<NoInfer<DFP>>from the object path caused literals in the callback's return to widen — consumers had to write:.attrs(({ rootElement }) => ({ tag: 'ul' as const, // ← needed before contentAlignX: 'block' as const, }))After this change, the
as constis no longer needed —'ul'contextually narrows toHTMLTags..attrs(({ rootElement }) => ({ tag: 'ul', // ✓ narrows to literal 'ul' assignable to HTMLTags contentAlignX: 'block', }))No behavioral change for existing object-form
.attrs({…})or explicit-<P>callback.attrs<P>((props) => …)patterns. The OA-overlapping widening and EA-key optionality from the previous release stay intact. - Object form:
2.4.0
Minor- rocketstyle#225
.attrs({ x: defaultValue })now makesxoptional at the JSX call site.Semantically,
.attrs()provides a runtime default — so the consumer shouldn't be required to pass that prop. The previous types didn't reflect that: keys passed to.attrs()stayed required at the call site (especially when they overlapped with the wrapped component's required props, e.g.componentonList).Two changes:
- DFP widening:
IRocketStyleComponent'sDFPnow strips OA keys that EA defaults and re-adds them asPartial, and feedsPartial<EA>into the merge — every.attrs()-provided key becomes optional at the call site. .attrs()inference: previously the object-form.attrs({ … })didn't update EA without an explicit<P>annotation (the param typePartial<MergeTypes<[DFP, P]>>defeated P inference). The new signature usesP & Partial<NoInfer<DFP>>, letting TS infer P from the param's keys while still accepting extra DFP defaults.
Result on wrappers like:
const CardList = rocketstyle()({ component: List, name: "CardList" }).attrs({ component: Card, rootElement: false, });<CardList data={users} itemKey="id" />— compiles (component default from .attrs).<CardList data={users} component={OtherCard} itemKey="id" />— still compiles (override).<CardList data={users} valueName="x" />— still rejected (per-mode narrowing from #222 preserved).
Behavior change to be aware of:
.attrs<{ isRequired: boolean }>({ isRequired: true })no longer requiresisRequiredat the JSX call site (it has a default). This is consistent with what.attrsmeans, but if anyone was relying on.attrs()keys being required JSX props, that no longer holds.Callback-form
.attrs((props) => …)does not infer P; pass it explicitly (.attrs<P>((props) => …)) if you want callback-set defaults to widen the type surface. - DFP widening:
2.3.0
Minor- rocketstyle#222
Preserve per-mode narrowing on overloaded components through
rocketstyle()wrapping.PR #199 made
IteratorandListoverloaded interfaces so direct call sites get strict per-mode discrimination (e.g.<List data={users} valueName="x" />is rejected becausevalueName?: neveron the object-array branch). Wrapping withrocketstyle()({ component: List })lost that —ExtractProps<C>picked the last overload, so the wrapper exposed onlyChildrenPropsand every iterator-style call errored.The fix is two-layered:
ExtractPropsnow pattern-matches against 1–4 callable overloads and returns the union of every overload's first-param type. Single-callable and plain-object inputs fall through to the previous behaviour unchanged.IRocketStyleComponent'sDFPdistributes overOA's union branches and intersects each branch raw (not viaMergeTypes), sovalueName?: nevermarkers survive —MergeTypes'ExtractNullableKeyswould otherwise strip them.
Result on wrapped components like
rocketstyle()({ component: List }):<StyledList data={users} component={Card} />— compiles (object-array branch).<StyledList data={users} valueName="x" component={Card} />— rejected.<StyledList data={strings} component={Item} valueName="x" />— compiles (string-array branch).<StyledList>{children}</StyledList>— compiles (children branch).<StyledList data={strings}>{children}</StyledList>— rejected (mode mixing).
Trade-off: per-
Tnarrowing insideitemProps/wrapPropscallbacks is lost through the wrap (the callback'sitemargument is the constraint's upper bound, not the consumer's concreteT). Direct<List data={users} itemProps={(u) => …} />keeps full per-Tnarrowing. Wrapped consumers who need the concrete type in callbacks can annotate explicitly:itemProps={(item: User) => …}.
2.2.1
Patch- all packages#217
Fix publishing of internal
peerDependencies— 2.2.0 shipped with the literal string"workspace:^"in publishedpeerDependencies, which Bun (correctly) refuses to install.npm publishrewrites the workspace protocol independenciesbut not inpeerDependencies, andchangeset publishinvokesnpm publishunder the hood. We now rewriteworkspace:^(andworkspace:~,workspace:*) to concrete caret ranges in a pre-publish step. The published artifact for@vitus-labs/corepeer dep, for example, is now"^2.2.1"instead of"workspace:^". Source declarations stay symbolic (workspace:^) so day-to-day workspace resolution is unchanged.
2.2.0
Minor- core#210
Add augmentable
CSSEngineResultinterface —css()'s return type now follows whichever engineinit()'d via TypeScript module declaration merging, replacing the previous engine-agnosticany. Connector packages declare their concrete result shape; consumer code automatically gets the right type without core depending on any specific engine package. - all packages#208
Migrate internal
peerDependenciesto theworkspace:^protocol. At publish time the protocol is rewritten to a real caret range (^X.Y.Z) — same end result for downstream consumers — but in-source declarations stay symbolic, so they don't need updating on every version bump. Deletesscripts/sync-peer-deps.mjsand theversionlifecycle hooks that invoked it across 10 packages. Combined with the newbumpVersionsWithWorkspaceProtocolOnlyandonlyUpdatePeerDependentsWhenOutOfRangeChangesets options, minor bumps in any one package now correctly propagate as minor across the whole fixed group instead of cascading into a major bump. - elements#210
Generic
Props<T>onIteratorandListwith discriminated branches —Tis inferred at the JSX call site from thedataarray. Primitive arrays getSimpleProps<T>(valueNamerequired), object arrays getObjectProps<T>(valueNameforbidden,itemKeytyped againstkeyof T), no-data calls getChildrenProps, and unparameterized callers fall back to the previous loose shape (LooseProps) for back-compat. Existing code keeps type-checking; new code gains stricter inference automatically. Two correctness fixes uncovered by the docs audit. Fix
isDark/isLightswap ingetDefaultAttrsmode helpers (rocketstyle.tsx:532-533) — runtime renders were correct viauseTheme, but the static introspection path used by rocketstories fed.attrs()callbacks inverted helpers, so any story whose attrs branched onhelpers.isDark/helpers.isLightshowed wrong-mode-sensitive defaults. TightenIRocketStories.initinterface from a method (() => {...}) to a property literal — the runtime is an object literal, sostories.init()typechecked but threwinit is not a functionat runtime; now the type matches runtime. Includes regression tests for both.- rocketstyle#210
Fix component-swap leak in
.config({ component }). WhencloneAndEnhanceswaps the underlying component, the priorattrs,priorityAttrs,compose, andfilterAttrschain values were silently carried forward — they were tailored to the previous component's prop shape and could leak invalid props onto the rendered output. Now those chain values reset on component change. Style-side state (themes, dimensions, statics, pseudo) is preserved. Same-component swaps remain a no-op for attrs. - rocketstories#210
Bundle of 5 fixes for rocketstories:
.replaceComponent()and.config({ component })now drop attrs on a real component swap (mirrors the rocketstyle fix); typo renamecloneAndEhnance→cloneAndEnhance; proper types forRocketType.getStaticDimensionsandgetDefaultAttrs(no moreany); threeas anycasts in render paths replaced with honest typed casts;@storybook/reactpeer dep loosened from exact10.3.6to^10.3.6. - rocketstories#210
Snapshot the theme into per-
storyOfConfiguration at construction time so each builder is isolated from latersetThememutations or competinginit({ theme })calls in the same process.RocketStoryHocandrenderDimensionnow read theme from Configuration instead of the module-level singleton — fixes a latent bug where twostoryOfinstances with different themes would have the second one's theme corrupt the first's static introspection. Existing defaultThemedecorator path (singleton-based) keeps working for back-compat.