Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changepacks/changepack_log_lazy_transform_css.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": {
"bindings/devup-ui-binding/package.json": "Patch",
"bindings/devup-ui-wasm/package.json": "Patch",
"packages/next-plugin/package.json": "Patch",
"packages/webpack-plugin/package.json": "Patch"
},
"note": "Serialize the CSS a transform returns only when it is read: a read after later transforms or setting changes still returns the sheet as that transform left it. The Next.js loader and prewarm never read it, and the Webpack loader reads it only when it writes it, so single-CSS builds no longer serialize the whole sheet after every module. The output is byte-identical.",
"date": "2026-11-15T00:00:00.000Z"
}
3 changes: 2 additions & 1 deletion bindings/devup-ui-binding/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use napi::{Env, Result};
use napi_derive::napi;

use crate::value::binding_error;
use devup_ui_binding_core::LazyCss;

/// Materialized native output with an explicitly consumable payload.
#[napi(js_name = "Output")]
Expand Down Expand Up @@ -42,7 +43,7 @@ impl NativeOutput {
/// Copy changed CSS, using undefined for absence.
#[napi(getter)]
pub fn css(&self, env: Env) -> Result<Either<String, Undefined>> {
Ok(self.live(env)?.css.clone().into())
Ok(self.live(env)?.css.as_ref().map(LazyCss::get).into())
}
/// Copy the optional stylesheet filename.
#[napi(getter, js_name = "cssFile")]
Expand Down
4 changes: 2 additions & 2 deletions bindings/devup-ui-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub struct Output {
map: Option<String>,
css_file: Option<String>,
updated_base_style: bool,
css: Option<String>,
css: Option<binding_core::LazyCss>,
dependencies: Vec<String>,
}

Expand Down Expand Up @@ -132,7 +132,7 @@ impl Output {
#[wasm_bindgen(getter, js_name = "css")]
#[must_use]
pub fn css(&self) -> Option<String> {
self.css.clone()
self.css.as_ref().map(binding_core::LazyCss::get)
}

/// Files read through the module resolver, for the bundler to watch
Expand Down
2 changes: 1 addition & 1 deletion bindings/devup-ui-wasm/src/reservation/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ fn resolved_token_keys_are_reserved_before_real_output() -> TestResult {
),
&option,
)?;
let css = output.css.ok_or("expected token CSS")?;
let css = output.css.ok_or("expected token CSS")?.get();
assert!(css.contains("width:var(--size)"));
assert!(css.contains("box-shadow:var(--card)"));
assert!(!css.contains("$size"));
Expand Down
1 change: 1 addition & 0 deletions libs/binding/src/css_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ impl Deref for SheetGuard<'_> {

impl DerefMut for SheetGuard<'_> {
fn deref_mut(&mut self) -> &mut StyleSheet {
crate::lazy_css::settle(&self.0);
invalidate_css();
&mut self.0
}
Expand Down
77 changes: 77 additions & 0 deletions libs/binding/src/lazy_css.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//! The CSS a transform returns, serialized only when the host reads it.
//!
//! Most hosts never read it, and serializing the shared base after every
//! transform is quadratic over a single-CSS build. The value is still the sheet
//! as that transform left it: the sheet, and every setting a serialization
//! reads, changes only after the one unread result has been serialized.

use css::atom_hoist::{AtomModeGuard, is_suppressed};
use sheet::StyleSheet;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};

use crate::css_cache::cached_css;
use crate::with_style_sheet;

struct Pending {
bucket: Option<String>,
import_main_css: bool,
/// Whether the transform suppressed atom mode while it committed.
suppressed: bool,
value: Mutex<Option<String>>,
}

/// The latest transform result, which alone can describe the current sheet.
static PENDING: Mutex<Weak<Pending>> = Mutex::new(Weak::new());

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

impl Pending {
/// The value, serializing `sheet` under the transform's atom mode on the first call.
fn value(&self, sheet: &StyleSheet) -> String {
lock(&self.value)
.get_or_insert_with(|| {
let _mode = AtomModeGuard::exact(self.suppressed);
cached_css(sheet, self.bucket.as_deref(), self.import_main_css)
})
.clone()
}
}

/// CSS of a transform, serialized on its first read.
pub struct LazyCss(Arc<Pending>);

impl LazyCss {
/// Defer serializing `bucket` (the shared base when `None`) of the sheet as it stands.
pub(crate) fn defer(bucket: Option<&str>, import_main_css: bool) -> Self {
let pending = Arc::new(Pending {
bucket: bucket.map(str::to_string),
import_main_css,
suppressed: is_suppressed(),
value: Mutex::default(),
});
*lock(&PENDING) = Arc::downgrade(&pending);
Self(pending)
}

/// The CSS of the sheet as the transform left it.
#[must_use]
pub fn get(&self) -> String {
with_style_sheet(|sheet| self.0.value(sheet))
}
}

/// Serialize the unread result of the latest transform before `sheet`, or a
/// setting its serialization reads, changes. A dropped result costs nothing.
pub(crate) fn settle(sheet: &StyleSheet) {
let pending = std::mem::take(&mut *lock(&PENDING)).upgrade();
if let Some(pending) = pending {
pending.value(sheet);
}
}

/// Settle before a setting that serializations read changes.
pub(crate) fn settle_live() {
with_style_sheet(settle);
}
41 changes: 25 additions & 16 deletions libs/binding/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Host-neutral binding orchestration; JavaScript values belong to the host adapter.

mod css_cache;
mod lazy_css;
mod output;
mod reservation;
mod resolver_state;
Expand All @@ -10,6 +11,7 @@ pub use css::slot_reservation::unreserved_slot_count as get_unreserved_class_slo
pub use css::{get_prefix, set_custom_shorthands as register_shorthands_internal, set_prefix};
pub use css_cache::{SheetCell, SheetGuard};
pub use extractor::{has_devup_ui, has_devup_ui_with};
pub use lazy_css::LazyCss;
pub use output::{CssOptions, ExtractionMode, Output, SourceMapMode, code_extract};
pub use reservation::{ReservationInput, reserve_class_slots_internal};
pub use resolver_state::{ResolverRequest, ResolverState, check_resolved_path, resolved_module};
Expand Down Expand Up @@ -47,8 +49,8 @@ where
f(&mut guard)
}

/// Mutably borrow the live stylesheet for a change that forgets the
/// serializations itself, and only when it changed the sheet.
/// Mutably borrow the live stylesheet for a change that settles the unread CSS
/// and forgets the serializations itself, and only when it changed the sheet.
fn with_style_sheet_untracked<F, R>(f: F) -> R
where
F: FnOnce(&mut StyleSheet) -> R,
Expand All @@ -61,13 +63,19 @@ where

/// Hoist atoms shared by `threshold` routes, or stop hoisting with `None`.
pub fn set_atom_hoist(threshold: Option<usize>) {
css::atom_hoist::set_atom_hoist(threshold);
invalidate_css();
change_setting(|| css::atom_hoist::set_atom_hoist(threshold));
}

/// Restore the routes each file reaches, which plan atom hoisting.
pub fn import_file_routes_internal(map: HashMap<String, HashSet<u32>>) {
css::file_routes::set_file_routes(map);
change_setting(|| css::file_routes::set_file_routes(map));
}

/// Change a setting that serializations read: the unread CSS of the latest
/// transform is serialized before, and every serialization forgotten after.
fn change_setting(change: impl FnOnce()) {
lazy_css::settle_live();
change();
invalidate_css();
}

Expand All @@ -78,7 +86,7 @@ fn error_text(error: impl std::fmt::Display) -> String {

/// Restore the sheet and its frozen atom plan together.
pub fn import_sheet_internal(sheet: StyleSheet) {
css::atom_hoist::restore_atom_plan(sheet.atom_plan.clone());
change_setting(|| css::atom_hoist::restore_atom_plan(sheet.atom_plan.clone()));
with_style_sheet_mut(|global_sheet| *global_sheet = sheet);
}

Expand Down Expand Up @@ -120,8 +128,7 @@ pub fn export_file_map_internal() -> Result<String, String> {

/// Restore canonical bucket identities decoded by a host adapter.
pub fn import_canonical_map_internal(map: HashMap<String, String>) {
set_canonical_map(map);
invalidate_css();
change_setting(|| set_canonical_map(map));
}

/// Export canonical bucket identities in path order.
Expand Down Expand Up @@ -154,14 +161,16 @@ pub fn remove_file_internal(filename: &str) -> bool {
/// Clear production build state, retaining theme registries, shorthands and debug.
/// The host adapter separately clears its resolver handle.
pub fn reset_build_state_internal() {
css::slot_reservation::reset();
css::class_map::reset_class_map();
css::file_map::reset_file_map();
css::file_map::reset_canonical_map();
css::file_routes::set_file_routes(HashMap::new());
css::atom_hoist::set_atom_hoist(None);
css::atom_hoist::restore_atom_plan(None);
css::set_prefix(None);
change_setting(|| {
css::slot_reservation::reset();
css::class_map::reset_class_map();
css::file_map::reset_file_map();
css::file_map::reset_canonical_map();
css::file_routes::set_file_routes(HashMap::new());
css::atom_hoist::set_atom_hoist(None);
css::atom_hoist::restore_atom_plan(None);
css::set_prefix(None);
});
with_style_sheet_mut(|sheet| *sheet = StyleSheet::default());
}

Expand Down
13 changes: 7 additions & 6 deletions libs/binding/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use extractor::{
extract_without_source_map,
};

use crate::css_cache::{cached_css, invalidate_css};
use crate::css_cache::invalidate_css;
use crate::lazy_css::{LazyCss, settle};
use crate::with_style_sheet_untracked;

/// Whether extraction generates a source map.
Expand Down Expand Up @@ -47,14 +48,14 @@ pub struct Output {
pub css_file: Option<String>,
/// Whether shared base CSS changed.
pub updated_base_style: bool,
/// Changed CSS, absent when the stylesheet is unchanged.
pub css: Option<String>,
/// Changed CSS, serialized on its first read; absent when the stylesheet is unchanged.
pub css: Option<LazyCss>,
/// Files read through the module resolver.
pub dependencies: Vec<String>,
}

impl Output {
/// Commit extracted styles to their existing bucket and materialize changed CSS.
/// Commit extracted styles to their existing bucket, deferring the changed CSS.
pub fn new(output: ExtractOutput, filename: String, options: CssOptions) -> Self {
// Use the bucket identity (single-importer collapse) so the sheet's CSS
// naming + property bucket + emitted chunk match the canonical class names
Expand All @@ -65,6 +66,7 @@ impl Output {
let canonical_filename = canonical(&filename);
let global = options.single_css || is_global(&filename);
with_style_sheet_untracked(|sheet| {
settle(sheet);
let planned = sheet.atom_plan.is_some();
// Global CSS belongs to the raw SOURCE file, never its collapsed bucket.
let default_collected = sheet.rm_global_css(&filename, global);
Expand All @@ -91,8 +93,7 @@ impl Output {
if !collected && !default_collected {
None
} else {
Some(cached_css(
sheet,
Some(LazyCss::defer(
if global {
None
} else {
Expand Down
2 changes: 1 addition & 1 deletion libs/binding/tests/css.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ fn numbered_css_selects_its_file_when_other_files_exist() -> Result<(), String>
let selected = devup_ui_binding_core::get_css(Some(7), false);

// Then: only the same file CSS returned by that transform is selected.
assert_eq!(Some(selected), red.css);
assert_eq!(Some(selected), red.css.map(|css| css.get()));
Ok(())
}
2 changes: 1 addition & 1 deletion libs/binding/tests/css_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ fn css_is_reused_until_an_extraction_changes_the_sheet() -> Result<(), String> {
let changed = get_css(None, false);

// Then: the unchanged sheet reads the same, the changed one holds both.
assert_eq!(red.css.as_deref(), Some(first.as_str()));
assert_eq!(red.css.map(|css| css.get()), Some(first.clone()));
assert_eq!(again, first);
assert!(!first.contains("blue"));
assert!(changed.contains("red") && changed.contains("blue"));
Expand Down
Loading
Loading