From 44383487589356838514810c044bb1c1704c5eab Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Mon, 1 Dec 2025 19:09:46 +0900 Subject: [PATCH 1/6] Update lib --- .../changepack_log_FcRb0f8Leq0YuM3WFhJIe.json | 5 + .github/workflows/publish.yml | 4 +- Cargo.lock | 227 ++++++++++++------ bindings/devup-ui-wasm/Cargo.toml | 8 +- libs/css/src/lib.rs | 3 +- libs/extractor/Cargo.toml | 16 +- libs/sheet/Cargo.toml | 4 +- libs/sheet/src/lib.rs | 16 +- .../snapshots/sheet__tests__import_css.snap | 4 +- .../sheet__tests__update_styles.snap | 4 +- 10 files changed, 190 insertions(+), 101 deletions(-) create mode 100644 .changepacks/changepack_log_FcRb0f8Leq0YuM3WFhJIe.json diff --git a/.changepacks/changepack_log_FcRb0f8Leq0YuM3WFhJIe.json b/.changepacks/changepack_log_FcRb0f8Leq0YuM3WFhJIe.json new file mode 100644 index 00000000..ace3e2a1 --- /dev/null +++ b/.changepacks/changepack_log_FcRb0f8Leq0YuM3WFhJIe.json @@ -0,0 +1,5 @@ +{ + "changes": { "bindings/devup-ui-wasm/package.json": "Patch" }, + "note": "Update lib", + "date": "2025-12-01T10:09:41.057039800Z" +} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 4a2bac0b..9a13d512 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -85,9 +85,11 @@ jobs: echo 'merge_derives = true' >> .rustfmt.toml echo 'use_small_heuristics = "Default"' >> .rustfmt.toml cargo fmt + - run: pnpm test + - name: Format Rollback + run: | rm -rf .rustfmt.toml cargo fmt - - run: pnpm test - name: Build Landing run: | pnpm -F components build-storybook diff --git a/Cargo.lock b/Cargo.lock index 3c319fa5..c2ee70f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11,6 +11,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloca" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4" +dependencies = [ + "cc", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -29,6 +38,17 @@ version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "autocfg" version = "1.5.0" @@ -86,9 +106,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.44" +version = "1.2.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37521ac7aabe3d13122dc382493e20c9416f299d2ccd5b3a5340a2570cdeb0f3" +checksum = "cd405d82c84ff7f35739f175f67d8b9fb7687a0e84ccdc78bd3568839827cf07" dependencies = [ "find-msvc-tools", "shlex", @@ -129,18 +149,18 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.51" +version = "4.5.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c26d721170e0295f191a69bd9a1f93efcdb0aff38684b61ab5750468972e5f5" +checksum = "c9e340e012a1bf4935f5282ed1436d1489548e8f72308207ea5df0e23d2d03f8" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" -version = "4.5.51" +version = "4.5.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75835f0c7bf681bfd05abe44e965760fea999a5286c6eb2d59883634fd02011a" +checksum = "d76b5d13eaa18c901fd2f7fca939fefe3a0727a953561fefdf3b2922b8569d00" dependencies = [ "anstyle", "clap_lex", @@ -175,7 +195,7 @@ dependencies = [ "encode_unicode", "libc", "once_cell", - "windows-sys 0.59.0", + "windows-sys", ] [[package]] @@ -196,10 +216,11 @@ checksum = "417bef24afe1460300965a25ff4a24b8b45ad011948302ec221e8a0a81eb2c79" [[package]] name = "criterion" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928" +checksum = "a0dfe5e9e71bdcf4e4954f7d14da74d1cdb92a3a07686452d1509652684b1aab" dependencies = [ + "alloca", "anes", "cast", "ciborium", @@ -208,6 +229,7 @@ dependencies = [ "itertools 0.13.0", "num-traits", "oorandom", + "page_size", "plotters", "rayon", "regex", @@ -219,9 +241,9 @@ dependencies = [ [[package]] name = "criterion-plot" -version = "0.6.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338" +checksum = "5de36c2bee19fba779808f92bf5d9b0fa5a40095c277aba10c458a12b35d21d6" dependencies = [ "cast", "itertools 0.13.0", @@ -343,9 +365,9 @@ checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "find-msvc-tools" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127" +checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844" [[package]] name = "futures" @@ -461,9 +483,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.16.0" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ "allocator-api2", ] @@ -486,9 +508,9 @@ dependencies = [ [[package]] name = "insta" -version = "1.43.2" +version = "1.44.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46fdb647ebde000f43b5b53f773c30cf9b0cb4300453208713fa38b2c70935a0" +checksum = "b5c943d4415edd8153251b6f197de5eb1640e56d84e8d9159bea190421c73698" dependencies = [ "console", "once_cell", @@ -521,9 +543,9 @@ checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "js-sys" -version = "0.3.82" +version = "0.3.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65" +checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" dependencies = [ "once_cell", "wasm-bindgen", @@ -541,6 +563,12 @@ version = "0.2.177" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" +[[package]] +name = "libm" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" + [[package]] name = "lock_api" version = "0.4.14" @@ -578,6 +606,15 @@ version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + [[package]] name = "num-bigint" version = "0.4.6" @@ -604,6 +641,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -658,9 +696,9 @@ dependencies = [ [[package]] name = "oxc_allocator" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "674f1447d47e26970ff13d8da8140ffb0d7fde347ab9af3e5c00e67943d4bc9b" +checksum = "5dd67b29aaa88b44af4d7d7b4752cf1dee9b6bc8b447015aad3470f818c3a24f" dependencies = [ "allocator-api2", "bumpalo", @@ -671,9 +709,9 @@ dependencies = [ [[package]] name = "oxc_ast" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6c0d01c611150a159b448272d08d198e57a69531b78c599133310a1e38177e2" +checksum = "508b3bd51231d6ea54f210ddf66d7859998e444deee1aa11490d7af76a8fcc85" dependencies = [ "bitflags", "oxc_allocator", @@ -688,9 +726,9 @@ dependencies = [ [[package]] name = "oxc_ast_macros" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a3373b0b8c5c1914cc7082f31cd81f3412f395f5e81970689fb6d547847a11" +checksum = "a5175058e196ee9bf6f00bf15f0da5e6ad05b2c649f13f8d231def53eaca4ed7" dependencies = [ "phf", "proc-macro2", @@ -700,9 +738,9 @@ dependencies = [ [[package]] name = "oxc_ast_visit" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8169aac113a81df22d73872e3a54dc6fa6c7465890b3379f83088977a894bdf9" +checksum = "3021dc3864afe1e2ec8da4696ea181549dd23e420c54eec8234b8063f96b9711" dependencies = [ "oxc_allocator", "oxc_ast", @@ -712,9 +750,9 @@ dependencies = [ [[package]] name = "oxc_codegen" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ace497cd606cd1dc74553cce8afec424b0b6ca3b97723610111df2797e3627ff" +checksum = "427fe5a089efc28ec4f0ff0ed226447abe3e8a993f5e611b568a5c5f8bb24010" dependencies = [ "bitflags", "cow-utils", @@ -733,15 +771,15 @@ dependencies = [ [[package]] name = "oxc_data_structures" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b15eb8528cea49be898e99b523653b27daed396fdf77d048547d94f091199c" +checksum = "2a6c288cce396a89d45998049658911f832c164f5653cf151c17d5d69c8baa15" [[package]] name = "oxc_diagnostics" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd2de22e8e8c94f10adc58f13ae94550e350b82e5143962c0e5c0cb9932acf5d" +checksum = "b0c0e9fd547155f3118dc1747389a38ffa4daff2218d229730175c44be66584d" dependencies = [ "cow-utils", "oxc-miette", @@ -750,9 +788,9 @@ dependencies = [ [[package]] name = "oxc_ecmascript" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "665d01392d92af2c7904a1106d19272fd62e4ab45079519f8c33fae5046b53a5" +checksum = "eb1b0ea5a50805d783611082c381f0b2703ab9eebce080269342720cc923178f" dependencies = [ "cow-utils", "num-bigint", @@ -765,9 +803,9 @@ dependencies = [ [[package]] name = "oxc_estree" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66ed73e88c330b977905de971e7a06ba4309c6658a83cfcf63f2013b37922beb" +checksum = "9ea2e2422277b5177b6e96effc77e9842c074a7d4e27582ae66db121b05a63dc" [[package]] name = "oxc_index" @@ -781,9 +819,9 @@ dependencies = [ [[package]] name = "oxc_parser" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e94af4e21a37daf13e4b8c2233566daa0e85cc25cf50bf2670ae6235b41767" +checksum = "653f0530c06a2deff988cecc378c53c2d3e39a50d48bb3c34170feae6f9340d0" dependencies = [ "bitflags", "cow-utils", @@ -804,9 +842,9 @@ dependencies = [ [[package]] name = "oxc_regular_expression" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bb5d767d654aac7cb95bffe2ae0bcc953e6c8330e0aa311b4c06edb65da384c" +checksum = "5374512dcbcc68ec232add5fb5386827bd1c3f8472ca4905fff7758d6f4c6b94" dependencies = [ "bitflags", "oxc_allocator", @@ -820,9 +858,9 @@ dependencies = [ [[package]] name = "oxc_semantic" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e38d51bf83b46fdb16caa8992da99a3c3df4cd7ae200bfe7abe6c5f7bbd52b65" +checksum = "aa86149b02f40f2597b370720ac2396895401e902b204ef8d78b15f7c4f9120e" dependencies = [ "itertools 0.14.0", "oxc_allocator", @@ -854,9 +892,9 @@ dependencies = [ [[package]] name = "oxc_span" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ad5a043ad3a15cafe9d50c3f8e289546d2ff66d039285af30829d667a81bbf2" +checksum = "b553fc7cfece123ec1460a063a3bdcc8d39f6f8f358af07f5524227e41d5f63f" dependencies = [ "compact_str", "oxc-miette", @@ -867,9 +905,9 @@ dependencies = [ [[package]] name = "oxc_syntax" -version = "0.98.0" +version = "0.99.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d87f83a206be495b3536c4ed11f6e444efbdaead4dc778192b2c2038afdd7acb" +checksum = "becb84744ca2cb19373ea654cc8532cd8623d6aa06cad9164cfc7646b294b0fd" dependencies = [ "bitflags", "cow-utils", @@ -885,6 +923,16 @@ dependencies = [ "unicode-id-start", ] +[[package]] +name = "page_size" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "parking_lot" version = "0.12.5" @@ -1348,9 +1396,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.110" +version = "2.0.111" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a99801b5bd34ede4cf3fc688c5919368fea4e4814a4664359503e6015b280aea" +checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87" dependencies = [ "proc-macro2", "quote", @@ -1476,9 +1524,9 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.105" +version = "0.2.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60" +checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" dependencies = [ "cfg-if", "once_cell", @@ -1489,9 +1537,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.55" +version = "0.4.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "551f88106c6d5e7ccc7cd9a16f312dd3b5d36ea8b4954304657d5dfba115d4a0" +checksum = "836d9622d604feee9e5de25ac10e3ea5f2d65b41eac0d9ce72eb5deae707ce7c" dependencies = [ "cfg-if", "js-sys", @@ -1502,9 +1550,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.105" +version = "0.2.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2" +checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -1512,9 +1560,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.105" +version = "0.2.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc" +checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" dependencies = [ "bumpalo", "proc-macro2", @@ -1525,21 +1573,29 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.105" +version = "0.2.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76" +checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" dependencies = [ "unicode-ident", ] [[package]] name = "wasm-bindgen-test" -version = "0.3.55" +version = "0.3.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfc379bfb624eb59050b509c13e77b4eb53150c350db69628141abce842f2373" +checksum = "25e90e66d265d3a1efc0e72a54809ab90b9c0c515915c67cdf658689d2c22c6c" dependencies = [ + "async-trait", + "cast", "js-sys", + "libm", "minicov", + "nu-ansi-term", + "num-traits", + "oorandom", + "serde", + "serde_json", "wasm-bindgen", "wasm-bindgen-futures", "wasm-bindgen-test-macro", @@ -1547,9 +1603,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-test-macro" -version = "0.3.55" +version = "0.3.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "085b2df989e1e6f9620c1311df6c996e83fe16f57792b272ce1e024ac16a90f1" +checksum = "7150335716dce6028bead2b848e72f47b45e7b9422f64cccdc23bedca89affc1" dependencies = [ "proc-macro2", "quote", @@ -1558,23 +1614,45 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.82" +version = "0.3.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a1f95c0d03a47f4ae1f7a64643a6bb97465d9b740f0fa8f90ea33915c99a9a1" +checksum = "9b32828d774c412041098d182a8b38b16ea816958e07cf40eec2bc080ae137ac" dependencies = [ "js-sys", "wasm-bindgen", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows-link" version = "0.2.1" @@ -1590,15 +1668,6 @@ dependencies = [ "windows-targets", ] -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - [[package]] name = "windows-targets" version = "0.52.6" @@ -1674,18 +1743,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.27" +version = "0.8.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" +checksum = "4ea879c944afe8a2b25fef16bb4ba234f47c694565e97383b36f3a878219065c" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.27" +version = "0.8.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" +checksum = "cf955aa904d6040f70dc8e9384444cb1030aed272ba3cb09bbc4ab9e7c1f34f5" dependencies = [ "proc-macro2", "quote", diff --git a/bindings/devup-ui-wasm/Cargo.toml b/bindings/devup-ui-wasm/Cargo.toml index e05d29f8..7859075a 100644 --- a/bindings/devup-ui-wasm/Cargo.toml +++ b/bindings/devup-ui-wasm/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "rlib"] default = ["console_error_panic_hook"] [dependencies] -wasm-bindgen = "0.2.105" +wasm-bindgen = "0.2.106" extractor = { path = "../../libs/extractor" } sheet = { path = "../../libs/sheet" } css = { path = "../../libs/css" } @@ -26,13 +26,13 @@ css = { path = "../../libs/css" } # code size when deploying. console_error_panic_hook = { version = "0.1.7", optional = true } once_cell = "1.21.3" -js-sys = "0.3.82" +js-sys = "0.3.83" serde_json = "1.0.145" serde-wasm-bindgen = "0.6.5" bimap = { version = "0.6.3", features = ["serde"] } [dev-dependencies] -wasm-bindgen-test = "0.3.55" +wasm-bindgen-test = "0.3.56" serial_test = "3.2.0" -insta = "1.43.2" +insta = "1.44.3" rstest = "0.26.1" diff --git a/libs/css/src/lib.rs b/libs/css/src/lib.rs index acdbeaef..1b0bfdff 100644 --- a/libs/css/src/lib.rs +++ b/libs/css/src/lib.rs @@ -215,7 +215,8 @@ pub fn sheet_to_classname( pub fn sheet_to_variable_name(property: &str, level: u8, selector: Option<&str>) -> String { if is_debug() { - let selector = selector.unwrap_or_default().trim(); + let selector = selector.unwrap_or_default(); + let selector = selector.trim(); format!( "--{}-{}-{}", property, diff --git a/libs/extractor/Cargo.toml b/libs/extractor/Cargo.toml index f38ab1de..69ea2a6c 100644 --- a/libs/extractor/Cargo.toml +++ b/libs/extractor/Cargo.toml @@ -4,19 +4,19 @@ version = "0.1.0" edition = "2024" [dependencies] -oxc_parser = "0.98.0" -oxc_syntax = "0.98.0" -oxc_span = "0.98.0" -oxc_allocator = "0.98.0" -oxc_ast = "0.98.0" -oxc_ast_visit = "0.98.0" -oxc_codegen = "0.98.0" +oxc_parser = "0.99.0" +oxc_syntax = "0.99.0" +oxc_span = "0.99.0" +oxc_allocator = "0.99.0" +oxc_ast = "0.99.0" +oxc_ast_visit = "0.99.0" +oxc_codegen = "0.99.0" css = { path = "../css" } phf = "0.13" strum = "0.27.2" strum_macros = "0.27.2" [dev-dependencies] -insta = "1.43.2" +insta = "1.44.3" serial_test = "3.2.0" rstest = "0.26.1" diff --git a/libs/sheet/Cargo.toml b/libs/sheet/Cargo.toml index c49df41d..1903fbcd 100644 --- a/libs/sheet/Cargo.toml +++ b/libs/sheet/Cargo.toml @@ -11,9 +11,9 @@ once_cell = "1.21.3" extractor = { path = "../extractor" } [dev-dependencies] -insta = "1.43.2" +insta = "1.44.3" serde_json = "1.0.145" -criterion = { version = "0.7", features = ["html_reports"] } +criterion = { version = "0.8", features = ["html_reports"] } rstest = "0.26.1" [[bench]] diff --git a/libs/sheet/src/lib.rs b/libs/sheet/src/lib.rs index 8d425158..a75f994d 100644 --- a/libs/sheet/src/lib.rs +++ b/libs/sheet/src/lib.rs @@ -792,7 +792,13 @@ mod tests { #[test] fn test_import_css() { let sheet = StyleSheet::default(); - assert_debug_snapshot!(sheet.create_css(Some("index.tsx"), true)); + assert_debug_snapshot!( + sheet + .create_css(Some("index.tsx"), true) + .split("*/") + .nth(1) + .unwrap() + ); } #[test] @@ -1751,7 +1757,13 @@ mod tests { fn test_update_styles() { let mut sheet = StyleSheet::default(); sheet.update_styles(&HashSet::new(), "index.tsx", true); - assert_debug_snapshot!(sheet.create_css(Some("index.tsx"), true)); + assert_debug_snapshot!( + sheet + .create_css(Some("index.tsx"), true) + .split("*/") + .nth(1) + .unwrap() + ); let mut sheet = StyleSheet::default(); let output = extract("index.tsx", "import {Box,globalCss,keyframes,Flex} from '@devup-ui/core';;keyframes({from:{opacity:0},to:{opacity:1}});;globalCss`div{color:red}`;globalCss({div:{display:flex},imports:['https://test.com/a.css'],fontFaces:[{fontFamily:'Roboto',src:'url(/fonts/Roboto-Regular.ttf)'}]})", ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false }).unwrap(); diff --git a/libs/sheet/src/snapshots/sheet__tests__import_css.snap b/libs/sheet/src/snapshots/sheet__tests__import_css.snap index 1b67cffb..5eb43c3a 100644 --- a/libs/sheet/src/snapshots/sheet__tests__import_css.snap +++ b/libs/sheet/src/snapshots/sheet__tests__import_css.snap @@ -1,5 +1,5 @@ --- source: libs/sheet/src/lib.rs -expression: "sheet.create_css(Some(\"index.tsx\"), true)" +expression: "sheet.create_css(Some(\"index.tsx\"), true).split(\"*/\").nth(1).unwrap()" --- -"/*! devup-ui v1.0.48, | Apache License 2.0 | https://devup-ui.com */@import \"./devup-ui.css\";" +"@import \"./devup-ui.css\";" diff --git a/libs/sheet/src/snapshots/sheet__tests__update_styles.snap b/libs/sheet/src/snapshots/sheet__tests__update_styles.snap index 1b67cffb..5eb43c3a 100644 --- a/libs/sheet/src/snapshots/sheet__tests__update_styles.snap +++ b/libs/sheet/src/snapshots/sheet__tests__update_styles.snap @@ -1,5 +1,5 @@ --- source: libs/sheet/src/lib.rs -expression: "sheet.create_css(Some(\"index.tsx\"), true)" +expression: "sheet.create_css(Some(\"index.tsx\"), true).split(\"*/\").nth(1).unwrap()" --- -"/*! devup-ui v1.0.48, | Apache License 2.0 | https://devup-ui.com */@import \"./devup-ui.css\";" +"@import \"./devup-ui.css\";" From 9494bedf4a50da14174bf5d2773253136d99f941 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Mon, 1 Dec 2025 19:25:48 +0900 Subject: [PATCH 2/6] Update lib --- .../changepack_log_FcRb0f8Leq0YuM3WFhJIe.json | 5 - .../changepack_log_hccYx0kvEWXzExEoR1Fkq.json | 10 + .rustfmt.toml | 8 + benchmark/next-chakra-ui/package.json | 2 +- benchmark/next-kuma-ui/package.json | 4 +- benchmark/next-stylex/package.json | 8 +- bindings/devup-ui-wasm/src/lib.rs | 208 +- bindings/devup-ui-wasm/tests/wasm.rs | 35 +- libs/css/src/class_map.rs | 3 +- libs/css/src/constant.rs | 54 +- libs/css/src/file_map.rs | 8 +- libs/css/src/is_special_property.rs | 519 +-- libs/css/src/lib.rs | 604 +-- libs/css/src/optimize_multi_css_value.rs | 40 +- libs/css/src/optimize_value.rs | 41 +- libs/css/src/rm_css_comment.rs | 13 +- libs/css/src/selector_separator.rs | 11 +- libs/css/src/style_selector.rs | 160 +- libs/css/src/utils.rs | 28 +- libs/extractor/src/as_visit.rs | 5 +- libs/extractor/src/component.rs | 149 +- libs/extractor/src/css_utils.rs | 134 +- .../extract_style/extract_dynamic_style.rs | 32 +- .../src/extract_style/extract_keyframes.rs | 4 +- .../src/extract_style/extract_static_style.rs | 50 +- .../src/extract_style/extract_style_value.rs | 31 +- .../src/extract_style/style_property.rs | 12 +- .../extract_global_style_from_expression.rs | 115 +- .../extract_keyframes_from_expression.rs | 18 +- .../extract_style_from_expression.rs | 517 +-- .../src/extractor/extract_style_from_jsx.rs | 23 +- .../extract_style_from_member_expression.rs | 132 +- libs/extractor/src/gen_class_name.rs | 152 +- libs/extractor/src/gen_style.rs | 195 +- libs/extractor/src/lib.rs | 2606 ++----------- libs/extractor/src/prop_modify_utils.rs | 366 +- libs/extractor/src/utils.rs | 242 +- libs/extractor/src/visit.rs | 346 +- libs/sheet/benches/my_benchmark.rs | 16 +- libs/sheet/src/lib.rs | 1082 +----- libs/sheet/src/theme.rs | 181 +- package.json | 2 +- packages/components/package.json | 12 +- packages/eslint-plugin/package.json | 6 +- packages/next-plugin/package.json | 2 +- pnpm-lock.yaml | 3237 +++++++++-------- 46 files changed, 2828 insertions(+), 8600 deletions(-) delete mode 100644 .changepacks/changepack_log_FcRb0f8Leq0YuM3WFhJIe.json create mode 100644 .changepacks/changepack_log_hccYx0kvEWXzExEoR1Fkq.json create mode 100644 .rustfmt.toml diff --git a/.changepacks/changepack_log_FcRb0f8Leq0YuM3WFhJIe.json b/.changepacks/changepack_log_FcRb0f8Leq0YuM3WFhJIe.json deleted file mode 100644 index ace3e2a1..00000000 --- a/.changepacks/changepack_log_FcRb0f8Leq0YuM3WFhJIe.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "changes": { "bindings/devup-ui-wasm/package.json": "Patch" }, - "note": "Update lib", - "date": "2025-12-01T10:09:41.057039800Z" -} diff --git a/.changepacks/changepack_log_hccYx0kvEWXzExEoR1Fkq.json b/.changepacks/changepack_log_hccYx0kvEWXzExEoR1Fkq.json new file mode 100644 index 00000000..b16133a2 --- /dev/null +++ b/.changepacks/changepack_log_hccYx0kvEWXzExEoR1Fkq.json @@ -0,0 +1,10 @@ +{ + "changes": { + "packages/next-plugin/package.json": "Patch", + "packages/eslint-plugin/package.json": "Patch", + "packages/components/package.json": "Patch", + "bindings/devup-ui-wasm/package.json": "Patch" + }, + "note": "Update lib", + "date": "2025-12-01T10:23:27.926765300Z" +} diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 00000000..0a6a7683 --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1,8 @@ +max_width = 100000 +tab_spaces = 4 +newline_style = "Unix" +fn_call_width = 100000 +fn_params_layout = "Compressed" +chain_width = 100000 +merge_derives = true +use_small_heuristics = "Default" diff --git a/benchmark/next-chakra-ui/package.json b/benchmark/next-chakra-ui/package.json index 95f53717..1a2c1eaa 100644 --- a/benchmark/next-chakra-ui/package.json +++ b/benchmark/next-chakra-ui/package.json @@ -10,7 +10,7 @@ "lint": "next lint" }, "dependencies": { - "@chakra-ui/react": "^3.29", + "@chakra-ui/react": "^3.30", "@emotion/react": "^11.14", "next": "^16.0", "next-themes": "^0.4", diff --git a/benchmark/next-kuma-ui/package.json b/benchmark/next-kuma-ui/package.json index dc77e642..2f089cc3 100644 --- a/benchmark/next-kuma-ui/package.json +++ b/benchmark/next-kuma-ui/package.json @@ -13,10 +13,10 @@ "react": "^19.2", "react-dom": "^19.2", "next": "^16.0", - "@kuma-ui/core": "^1.5" + "@kuma-ui/core": "^1.6" }, "devDependencies": { - "@kuma-ui/next-plugin": "^1.3", + "@kuma-ui/next-plugin": "^1.4", "typescript": "^5", "@types/node": "^24", "@types/react": "^19", diff --git a/benchmark/next-stylex/package.json b/benchmark/next-stylex/package.json index e57d9bf0..1c930012 100644 --- a/benchmark/next-stylex/package.json +++ b/benchmark/next-stylex/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@stylexjs/open-props": "^0.11", - "@stylexjs/stylex": "^0.16", + "@stylexjs/stylex": "^0.17", "bright": "^1.0", "next": "16.0", "react": "19.2", @@ -23,8 +23,8 @@ "@babel/plugin-syntax-flow": "^7.27", "@babel/plugin-syntax-jsx": "^7.27", "@babel/plugin-syntax-typescript": "^7.27", - "@stylexjs/babel-plugin": "^0.16", - "@stylexjs/eslint-plugin": "^0.16", + "@stylexjs/babel-plugin": "^0.17", + "@stylexjs/eslint-plugin": "^0.17", "@stylexjs/nextjs-plugin": "^0.11", "@types/node": "24.10", "@types/react": "19.2", @@ -32,7 +32,7 @@ "@types/react-test-renderer": "^19.1", "eslint": "9.39", "eslint-config-next": "16.0", - "prettier": "^3.6", + "prettier": "^3.7", "react-test-renderer": "^19.2", "rimraf": "^6.1", "ts_dependency_graph": "^2.1", diff --git a/bindings/devup-ui-wasm/src/lib.rs b/bindings/devup-ui-wasm/src/lib.rs index e21dedaf..c7e98679 100644 --- a/bindings/devup-ui-wasm/src/lib.rs +++ b/bindings/devup-ui-wasm/src/lib.rs @@ -8,8 +8,7 @@ use std::collections::HashSet; use std::sync::Mutex; use wasm_bindgen::prelude::*; -static GLOBAL_STYLE_SHEET: Lazy> = - Lazy::new(|| Mutex::new(StyleSheet::default())); +static GLOBAL_STYLE_SHEET: Lazy> = Lazy::new(|| Mutex::new(StyleSheet::default())); #[wasm_bindgen] pub struct Output { @@ -19,48 +18,25 @@ pub struct Output { updated_base_style: bool, css: Option, } -#[wasm_bindgen] -extern "C" { - #[wasm_bindgen(js_namespace = console)] - fn log(s: &JsValue); - #[wasm_bindgen(js_namespace = console, js_name = log)] - fn log_str(s: &str); - #[wasm_bindgen(js_namespace = console, js_name = time)] - fn time(s: &str); - #[wasm_bindgen(js_namespace = console, js_name = timeEnd)] - fn time_end(s: &str); -} +// #[wasm_bindgen] +// extern "C" { +// #[wasm_bindgen(js_namespace = console)] +// fn log(s: &JsValue); +// #[wasm_bindgen(js_namespace = console, js_name = log)] +// fn log_str(s: &str); +// #[wasm_bindgen(js_namespace = console, js_name = time)] +// fn time(s: &str); +// #[wasm_bindgen(js_namespace = console, js_name = timeEnd)] +// fn time_end(s: &str); +// } #[wasm_bindgen] impl Output { - fn new( - code: String, - styles: HashSet, - map: Option, - single_css: bool, - filename: String, - css_file: Option, - import_main_css: bool, - ) -> Self { + fn new(code: String, styles: HashSet, map: Option, single_css: bool, filename: String, css_file: Option, import_main_css: bool) -> Self { let mut sheet = GLOBAL_STYLE_SHEET.lock().unwrap(); let default_collected = sheet.rm_global_css(&filename, single_css); let (collected, updated_base_style) = sheet.update_styles(&styles, &filename, single_css); - Self { - code, - map, - css_file, - updated_base_style: updated_base_style || default_collected, - css: { - if !collected && !default_collected { - None - } else { - Some(sheet.create_css( - if !single_css { Some(&filename) } else { None }, - import_main_css, - )) - } - }, - } + Self { code, map, css_file, updated_base_style: updated_base_style || default_collected, css: { if !collected && !default_collected { None } else { Some(sheet.create_css(if !single_css { Some(&filename) } else { None }, import_main_css)) } } } } /// Get the code @@ -103,23 +79,18 @@ pub fn is_debug() -> bool { #[wasm_bindgen(js_name = "importSheet")] pub fn import_sheet(sheet_object: JsValue) -> Result<(), JsValue> { - *GLOBAL_STYLE_SHEET.lock().unwrap() = serde_wasm_bindgen::from_value(sheet_object) - .map_err(|e| JsValue::from_str(&e.to_string()))?; + *GLOBAL_STYLE_SHEET.lock().unwrap() = serde_wasm_bindgen::from_value(sheet_object).map_err(|e| JsValue::from_str(&e.to_string()))?; Ok(()) } #[wasm_bindgen(js_name = "exportSheet")] pub fn export_sheet() -> Result { - serde_json::to_string(&*GLOBAL_STYLE_SHEET.lock().unwrap()) - .map_err(|e| JsValue::from_str(&e.to_string())) + serde_json::to_string(&*GLOBAL_STYLE_SHEET.lock().unwrap()).map_err(|e| JsValue::from_str(&e.to_string())) } #[wasm_bindgen(js_name = "importClassMap")] pub fn import_class_map(sheet_object: JsValue) -> Result<(), JsValue> { - set_class_map( - serde_wasm_bindgen::from_value(sheet_object) - .map_err(|e| JsValue::from_str(&e.to_string()))?, - ); + set_class_map(serde_wasm_bindgen::from_value(sheet_object).map_err(|e| JsValue::from_str(&e.to_string()))?); Ok(()) } @@ -130,10 +101,7 @@ pub fn export_class_map() -> Result { #[wasm_bindgen(js_name = "importFileMap")] pub fn import_file_map(sheet_object: JsValue) -> Result<(), JsValue> { - set_file_map( - serde_wasm_bindgen::from_value(sheet_object) - .map_err(|e| JsValue::from_str(&e.to_string()))?, - ); + set_file_map(serde_wasm_bindgen::from_value(sheet_object).map_err(|e| JsValue::from_str(&e.to_string()))?); Ok(()) } @@ -143,44 +111,16 @@ pub fn export_file_map() -> Result { } #[wasm_bindgen(js_name = "codeExtract")] -pub fn code_extract( - filename: &str, - code: &str, - package: &str, - css_dir: String, - single_css: bool, - import_main_css_in_code: bool, - import_main_css_in_css: bool, -) -> Result { - match extract( - filename, - code, - ExtractOption { - package: package.to_string(), - css_dir, - single_css, - import_main_css: import_main_css_in_code, - }, - ) { - Ok(output) => Ok(Output::new( - output.code, - output.styles, - output.map, - single_css, - filename.to_string(), - output.css_file, - import_main_css_in_css, - )), +pub fn code_extract(filename: &str, code: &str, package: &str, css_dir: String, single_css: bool, import_main_css_in_code: bool, import_main_css_in_css: bool) -> Result { + match extract(filename, code, ExtractOption { package: package.to_string(), css_dir, single_css, import_main_css: import_main_css_in_code }) { + Ok(output) => Ok(Output::new(output.code, output.styles, output.map, single_css, filename.to_string(), output.css_file, import_main_css_in_css)), Err(error) => Err(JsValue::from_str(error.to_string().as_str())), } } #[wasm_bindgen(js_name = "registerTheme")] pub fn register_theme(theme_object: JsValue) -> Result<(), JsValue> { - GLOBAL_STYLE_SHEET.lock().unwrap().set_theme( - serde_wasm_bindgen::from_value(theme_object) - .map_err(|e| JsValue::from_str(e.to_string().as_str()))?, - ); + GLOBAL_STYLE_SHEET.lock().unwrap().set_theme(serde_wasm_bindgen::from_value(theme_object).map_err(|e| JsValue::from_str(e.to_string().as_str()))?); Ok(()) } @@ -193,26 +133,13 @@ pub fn get_default_theme() -> Result, JsValue> { #[wasm_bindgen(js_name = "getCss")] pub fn get_css(file_num: Option, import_main_css: bool) -> Result { let sheet = GLOBAL_STYLE_SHEET.lock().unwrap(); - Ok(sheet.create_css( - file_num.map(get_filename_by_file_num).as_deref(), - import_main_css, - )) + Ok(sheet.create_css(file_num.map(get_filename_by_file_num).as_deref(), import_main_css)) } #[wasm_bindgen(js_name = "getThemeInterface")] -pub fn get_theme_interface( - package_name: &str, - color_interface_name: &str, - typography_interface_name: &str, - theme_interface_name: &str, -) -> String { +pub fn get_theme_interface(package_name: &str, color_interface_name: &str, typography_interface_name: &str, theme_interface_name: &str) -> String { let sheet = GLOBAL_STYLE_SHEET.lock().unwrap(); - sheet.create_interface( - package_name, - color_interface_name, - typography_interface_name, - theme_interface_name, - ) + sheet.create_interface(package_name, color_interface_name, typography_interface_name, theme_interface_name) } #[cfg(test)] mod tests { @@ -231,10 +158,7 @@ mod tests { let mut sheet = GLOBAL_STYLE_SHEET.lock().unwrap(); *sheet = StyleSheet::default(); } - assert_eq!( - get_css(None, false).unwrap().split("*/").nth(1).unwrap(), - "" - ); + assert_eq!(get_css(None, false).unwrap().split("*/").nth(1).unwrap(), ""); { let mut sheet = GLOBAL_STYLE_SHEET.lock().unwrap(); @@ -347,48 +271,15 @@ mod tests { let mut color_theme = ColorTheme::default(); color_theme.add_color("primary", "#fff"); theme.add_color_theme("dark", color_theme); - theme.add_typography( - "default", - vec![ - Some(Typography::new( - Some("Arial".to_string()), - Some("16px".to_string()), - Some("400".to_string()), - Some("1.5".to_string()), - Some("0.5".to_string()), - )), - Some(Typography::new( - Some("Arial".to_string()), - Some("24px".to_string()), - Some("400".to_string()), - Some("1.5".to_string()), - Some("0.5".to_string()), - )), - ], - ); + theme.add_typography("default", vec![Some(Typography::new(Some("Arial".to_string()), Some("16px".to_string()), Some("400".to_string()), Some("1.5".to_string()), Some("0.5".to_string()))), Some(Typography::new(Some("Arial".to_string()), Some("24px".to_string()), Some("400".to_string()), Some("1.5".to_string()), Some("0.5".to_string())))]); - theme.add_typography( - "default1", - vec![ - None, - Some(Typography::new( - Some("Arial".to_string()), - Some("24px".to_string()), - Some("400".to_string()), - Some("1.5".to_string()), - Some("0.5".to_string()), - )), - ], - ); + theme.add_typography("default1", vec![None, Some(Typography::new(Some("Arial".to_string()), Some("24px".to_string()), Some("400".to_string()), Some("1.5".to_string()), Some("0.5".to_string())))]); let css = theme.to_css(); assert_debug_snapshot!(css); assert_eq!(Theme::default().to_css(), ""); let mut theme = Theme::default(); - theme.add_typography( - "default", - vec![Some(Typography::new(None, None, None, None, None))], - ); + theme.add_typography("default", vec![Some(Typography::new(None, None, None, None, None))]); assert_eq!(theme.to_css(), ""); let mut theme = Theme::default(); @@ -562,30 +453,14 @@ mod tests { #[serial] fn test_get_theme_interface() { let sheet = StyleSheet::default(); - assert_eq!( - sheet.create_interface( - "package", - "ColorInterface", - "TypographyInterface", - "ThemeInterface" - ), - "" - ); + assert_eq!(sheet.create_interface("package", "ColorInterface", "TypographyInterface", "ThemeInterface"), ""); let mut theme = Theme::default(); let mut color_theme = ColorTheme::default(); color_theme.add_color("primary", "#000"); theme.add_color_theme("dark", color_theme); GLOBAL_STYLE_SHEET.lock().unwrap().set_theme(theme); - assert_eq!( - get_theme_interface( - "package", - "ColorInterface", - "TypographyInterface", - "ThemeInterface" - ), - "import \"package\";declare module \"package\"{interface ColorInterface{$primary:null;}interface TypographyInterface{}interface ThemeInterface{dark:null;}}" - ); + assert_eq!(get_theme_interface("package", "ColorInterface", "TypographyInterface", "ThemeInterface"), "import \"package\";declare module \"package\"{interface ColorInterface{$primary:null;}interface TypographyInterface{}interface ThemeInterface{dark:null;}}"); // test wrong case let mut sheet = StyleSheet::default(); @@ -593,27 +468,10 @@ mod tests { let mut color_theme = ColorTheme::default(); color_theme.add_color("(primary)", "#000"); theme.add_color_theme("dark", color_theme); - theme.add_typography( - "prim``ary", - vec![Some(Typography::new( - Some("Arial".to_string()), - Some("16px".to_string()), - Some("400".to_string()), - Some("1.5".to_string()), - Some("0.5".to_string()), - ))], - ); + theme.add_typography("prim``ary", vec![Some(Typography::new(Some("Arial".to_string()), Some("16px".to_string()), Some("400".to_string()), Some("1.5".to_string()), Some("0.5".to_string())))]); sheet.set_theme(theme); *GLOBAL_STYLE_SHEET.lock().unwrap() = sheet; - assert_eq!( - get_theme_interface( - "package", - "ColorInterface", - "TypographyInterface", - "ThemeInterface" - ), - "import \"package\";declare module \"package\"{interface ColorInterface{[`$(primary)`]:null;}interface TypographyInterface{[`prim\\`\\`ary`]:null;}interface ThemeInterface{dark:null;}}" - ); + assert_eq!(get_theme_interface("package", "ColorInterface", "TypographyInterface", "ThemeInterface"), "import \"package\";declare module \"package\"{interface ColorInterface{[`$(primary)`]:null;}interface TypographyInterface{[`prim\\`\\`ary`]:null;}interface ThemeInterface{dark:null;}}"); } #[test] diff --git a/bindings/devup-ui-wasm/tests/wasm.rs b/bindings/devup-ui-wasm/tests/wasm.rs index 2b401d87..f5e1df46 100644 --- a/bindings/devup-ui-wasm/tests/wasm.rs +++ b/bindings/devup-ui-wasm/tests/wasm.rs @@ -7,36 +7,11 @@ use wasm_bindgen_test::*; #[wasm_bindgen_test] fn test_object_to_typography() { let obj = Object::new(); - Reflect::set( - &obj, - &JsValue::from_str("fontFamily"), - &JsValue::from_str("Arial"), - ) - .unwrap(); - Reflect::set( - &obj, - &JsValue::from_str("fontSize"), - &JsValue::from_str("12px"), - ) - .unwrap(); - Reflect::set( - &obj, - &JsValue::from_str("fontWeight"), - &JsValue::from_str("bold"), - ) - .unwrap(); - Reflect::set( - &obj, - &JsValue::from_str("lineHeight"), - &JsValue::from_str("1.5"), - ) - .unwrap(); - Reflect::set( - &obj, - &JsValue::from_str("letterSpacing"), - &JsValue::from_str("1px"), - ) - .unwrap(); + Reflect::set(&obj, &JsValue::from_str("fontFamily"), &JsValue::from_str("Arial")).unwrap(); + Reflect::set(&obj, &JsValue::from_str("fontSize"), &JsValue::from_str("12px")).unwrap(); + Reflect::set(&obj, &JsValue::from_str("fontWeight"), &JsValue::from_str("bold")).unwrap(); + Reflect::set(&obj, &JsValue::from_str("lineHeight"), &JsValue::from_str("1.5")).unwrap(); + Reflect::set(&obj, &JsValue::from_str("letterSpacing"), &JsValue::from_str("1px")).unwrap(); let typography: Typography = serde_wasm_bindgen::from_value(JsValue::from(obj)).unwrap(); assert_eq!(typography.font_family.unwrap(), "Arial"); assert_eq!(typography.font_size.unwrap(), "12px"); diff --git a/libs/css/src/class_map.rs b/libs/css/src/class_map.rs index ed30c15b..04726c44 100644 --- a/libs/css/src/class_map.rs +++ b/libs/css/src/class_map.rs @@ -2,8 +2,7 @@ use std::{collections::HashMap, sync::Mutex}; use once_cell::sync::Lazy; -pub(crate) static GLOBAL_CLASS_MAP: Lazy>>> = - Lazy::new(|| Mutex::new(HashMap::new())); +pub(crate) static GLOBAL_CLASS_MAP: Lazy>>> = Lazy::new(|| Mutex::new(HashMap::new())); /// for test pub fn reset_class_map() { diff --git a/libs/css/src/constant.rs b/libs/css/src/constant.rs index c988ec5b..4e2de3c9 100644 --- a/libs/css/src/constant.rs +++ b/libs/css/src/constant.rs @@ -6,17 +6,7 @@ use regex::Regex; pub(super) static SELECTOR_ORDER_MAP: Lazy> = Lazy::new(|| { let mut map = HashMap::new(); - for (idx, selector) in [ - "hover", - "focus-visible", - "focus", - "active", - "selected", - "disabled", - ] - .into_iter() - .enumerate() - { + for (idx, selector) in ["hover", "focus-visible", "focus", "active", "selected", "disabled"].into_iter().enumerate() { map.insert(format!(":{selector}"), idx as u8); } map @@ -162,46 +152,26 @@ pub(super) static ZERO_PERCENT_FUNCTION: phf::Set<&str> = phf_set! { }; pub(super) static F_SPACE_RE: Lazy = Lazy::new(|| Regex::new(r"\s*,\s*").unwrap()); -pub(super) static CSS_FUNCTION_RE: Lazy = - Lazy::new(|| Regex::new(r"^[a-zA-Z-]+(\(.*\))").unwrap()); +pub(super) static CSS_FUNCTION_RE: Lazy = Lazy::new(|| Regex::new(r"^[a-zA-Z-]+(\(.*\))").unwrap()); pub(super) static CHECK_QUOTES_RE: Lazy = Lazy::new(|| Regex::new(r"[()\s]").unwrap()); -pub(super) static CSS_COMMENT_RE: Lazy = - Lazy::new(|| Regex::new(r"/\*[\s\S]*?\*/").unwrap()); +pub(super) static CSS_COMMENT_RE: Lazy = Lazy::new(|| Regex::new(r"/\*[\s\S]*?\*/").unwrap()); pub(super) static F_DOT_RE: Lazy = Lazy::new(|| Regex::new(r"(\b|,)0\.(\d+)").unwrap()); -pub(super) static DOT_ZERO_RE: Lazy = - Lazy::new(|| Regex::new(r"(\b|,)-?0\.0+([^\d])").unwrap()); +pub(super) static DOT_ZERO_RE: Lazy = Lazy::new(|| Regex::new(r"(\b|,)-?0\.0+([^\d])").unwrap()); pub(super) static COLOR_HASH: Lazy = Lazy::new(|| Regex::new(r"#([0-9a-zA-Z]+)").unwrap()); -pub(super) static INNER_TRIM_RE: Lazy = - Lazy::new(|| Regex::new(r"\(\s*([^)]*?)\s*\)").unwrap()); +pub(super) static INNER_TRIM_RE: Lazy = Lazy::new(|| Regex::new(r"\(\s*([^)]*?)\s*\)").unwrap()); -pub(super) static RM_MINUS_ZERO_RE: Lazy = Lazy::new(|| { - Regex::new(r"-0(px|em|rem|vh|vw|%|dvh|dvw|vmax|vmin|mm|cm|in|pt|pc|lh|ic|deg|\)|,)").unwrap() -}); +pub(super) static RM_MINUS_ZERO_RE: Lazy = Lazy::new(|| Regex::new(r"-0(px|em|rem|vh|vw|%|dvh|dvw|vmax|vmin|mm|cm|in|pt|pc|lh|ic|deg|\)|,)").unwrap()); -pub(super) static NUM_TRIM_RE: Lazy = Lazy::new(|| { - Regex::new(r"(\d(px|em|rem|vh|vw|%|dvh|dvw|vmax|vmin|mm|cm|in|pt|pc|lh|ic|deg)?)\s+(\d)") - .unwrap() -}); -pub(super) static ZERO_RE: Lazy = Lazy::new(|| { - Regex::new(r"(\b|,|\(|^|\s)-?0(px|em|rem|vh|vw|%|dvh|dvw|vmax|vmin|mm|cm|in|pt|pc|lh|ic|deg)") - .unwrap() -}); +pub(super) static NUM_TRIM_RE: Lazy = Lazy::new(|| Regex::new(r"(\d(px|em|rem|vh|vw|%|dvh|dvw|vmax|vmin|mm|cm|in|pt|pc|lh|ic|deg)?)\s+(\d)").unwrap()); +pub(super) static ZERO_RE: Lazy = Lazy::new(|| Regex::new(r"(\b|,|\(|^|\s)-?0(px|em|rem|vh|vw|%|dvh|dvw|vmax|vmin|mm|cm|in|pt|pc|lh|ic|deg)").unwrap()); -pub(super) static F_RGBA_RE: Lazy = - Lazy::new(|| Regex::new(r"rgba\((\d+),(\d+),(\d+),(\d*\.?\d*)\)").unwrap()); +pub(super) static F_RGBA_RE: Lazy = Lazy::new(|| Regex::new(r"rgba\((\d+),(\d+),(\d+),(\d*\.?\d*)\)").unwrap()); -pub(super) static F_RGB_RE: Lazy = - Lazy::new(|| Regex::new(r"rgb\((\d+),(\d+),(\d+)\)").unwrap()); +pub(super) static F_RGB_RE: Lazy = Lazy::new(|| Regex::new(r"rgb\((\d+),(\d+),(\d+)\)").unwrap()); -pub(super) static N_BASE_ARRAY: [char; 27] = [ - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', - 't', 'u', 'v', 'w', 'x', 'y', 'z', '_', -]; +pub(super) static N_BASE_ARRAY: [char; 27] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '_']; -pub(super) static M_BASE_ARRAY: [char; 37] = [ - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', - 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_', -]; +pub(super) static M_BASE_ARRAY: [char; 37] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_']; diff --git a/libs/css/src/file_map.rs b/libs/css/src/file_map.rs index d3b78946..5ec22a28 100644 --- a/libs/css/src/file_map.rs +++ b/libs/css/src/file_map.rs @@ -3,8 +3,7 @@ use std::sync::Mutex; use once_cell::sync::Lazy; -pub(crate) static GLOBAL_FILE_MAP: Lazy>> = - Lazy::new(|| Mutex::new(BiHashMap::new())); +pub(crate) static GLOBAL_FILE_MAP: Lazy>> = Lazy::new(|| Mutex::new(BiHashMap::new())); /// for test pub fn reset_file_map() { @@ -32,10 +31,7 @@ pub fn get_file_num_by_filename(filename: &str) -> usize { pub fn get_filename_by_file_num(file_num: usize) -> String { let map = GLOBAL_FILE_MAP.lock().unwrap(); - map.get_by_right(&file_num) - .map(|s| s.as_str()) - .unwrap_or_default() - .to_string() + map.get_by_right(&file_num).map(|s| s.as_str()).unwrap_or_default().to_string() } #[cfg(test)] diff --git a/libs/css/src/is_special_property.rs b/libs/css/src/is_special_property.rs index fd833d66..ca9c8a3b 100644 --- a/libs/css/src/is_special_property.rs +++ b/libs/css/src/is_special_property.rs @@ -413,10 +413,7 @@ static SPECIAL_PROPERTIES: phf::Set<&str> = phf_set! { }; pub fn is_special_property(name: &str) -> bool { - name.starts_with("on") - || name.starts_with("data-") - || name.starts_with("aria-") - || SPECIAL_PROPERTIES.contains(name) + name.starts_with("on") || name.starts_with("data-") || name.starts_with("aria-") || SPECIAL_PROPERTIES.contains(name) } #[cfg(test)] @@ -445,519 +442,7 @@ mod tests { #[test] fn test_css_properties() { - let css: HashSet = HashSet::from_iter( - [ - "accent-color", - "align-content", - "align-items", - "align-self", - "align-tracks", - "alignment-baseline", - "all", - "anchor-name", - "anchor-scope", - "animation", - "animation-composition", - "animation-delay", - "animation-direction", - "animation-duration", - "animation-fill-mode", - "animation-iteration-count", - "animation-name", - "animation-play-state", - "animation-range", - "animation-range-end", - "animation-range-start", - "animation-timeline", - "animation-timing-function", - "appearance", - "aspect-ratio", - "backdrop-filter", - "backface-visibility", - "background", - "background-attachment", - "background-blend-mode", - "background-clip", - "background-color", - "background-image", - "background-origin", - "background-position", - "background-position-x", - "background-position-y", - "background-repeat", - "background-size", - "baseline-shift", - "block-size", - "border", - "border-block", - "border-block-color", - "border-block-end", - "border-block-end-color", - "border-block-end-style", - "border-block-end-width", - "border-block-start", - "border-block-start-color", - "border-block-start-style", - "border-block-start-width", - "border-block-style", - "border-block-width", - "border-bottom", - "border-bottom-color", - "border-bottom-left-radius", - "border-bottom-right-radius", - "border-bottom-style", - "border-bottom-width", - "border-collapse", - "border-color", - "border-end-end-radius", - "border-end-start-radius", - "border-image", - "border-image-outset", - "border-image-repeat", - "border-image-slice", - "border-image-source", - "border-image-width", - "border-inline", - "border-inline-color", - "border-inline-end", - "border-inline-end-color", - "border-inline-end-style", - "border-inline-end-width", - "border-inline-start", - "border-inline-start-color", - "border-inline-start-style", - "border-inline-start-width", - "border-inline-style", - "border-inline-width", - "border-left", - "border-left-color", - "border-left-style", - "border-left-width", - "border-radius", - "border-right", - "border-right-color", - "border-right-style", - "border-right-width", - "border-spacing", - "border-start-end-radius", - "border-start-start-radius", - "border-style", - "border-top", - "border-top-color", - "border-top-left-radius", - "border-top-right-radius", - "border-top-style", - "border-top-width", - "border-width", - "bottom", - "box-align", - "box-decoration-break", - "box-direction", - "box-flex", - "box-flex-group", - "box-lines", - "box-ordinal-group", - "box-orient", - "box-pack", - "box-shadow", - "box-sizing", - "break-after", - "break-before", - "break-inside", - "caption-side", - "caret", - "caret-color", - "caret-shape", - "clear", - "clip", - "clip-path", - "clip-rule", - "color", - "color-interpolation-filters", - "color-scheme", - "column-count", - "column-fill", - "column-gap", - "column-rule", - "column-rule-color", - "column-rule-style", - "column-rule-width", - "column-span", - "column-width", - "columns", - "contain", - "contain-intrinsic-block-size", - "contain-intrinsic-height", - "contain-intrinsic-inline-size", - "contain-intrinsic-size", - "contain-intrinsic-width", - "container", - "container-name", - "container-type", - "content", - "content-visibility", - "counter-increment", - "counter-reset", - "counter-set", - "cursor", - "cx", - "cy", - "d", - "direction", - "display", - "dominant-baseline", - "empty-cells", - "field-sizing", - "fill", - "fill-opacity", - "fill-rule", - "filter", - "flex", - "flex-basis", - "flex-direction", - "flex-flow", - "flex-grow", - "flex-shrink", - "flex-wrap", - "float", - "flood-color", - "flood-opacity", - "font", - "font-family", - "font-feature-settings", - "font-kerning", - "font-language-override", - "font-optical-sizing", - "font-palette", - "font-size", - "font-size-adjust", - "font-smooth", - "font-stretch", - "font-style", - "font-synthesis", - "font-synthesis-position", - "font-synthesis-small-caps", - "font-synthesis-style", - "font-synthesis-weight", - "font-variant", - "font-variant-alternates", - "font-variant-caps", - "font-variant-east-asian", - "font-variant-emoji", - "font-variant-ligatures", - "font-variant-numeric", - "font-variant-position", - "font-variation-settings", - "font-weight", - "font-width", - "forced-color-adjust", - "gap", - "grid", - "grid-area", - "grid-auto-columns", - "grid-auto-flow", - "grid-auto-rows", - "grid-column", - "grid-column-end", - "grid-column-gap", - "grid-column-start", - "grid-gap", - "grid-row", - "grid-row-end", - "grid-row-gap", - "grid-row-start", - "grid-template", - "grid-template-areas", - "grid-template-columns", - "grid-template-rows", - "hanging-punctuation", - "height", - "hyphenate-character", - "hyphenate-limit-chars", - "hyphens", - "image-orientation", - "image-rendering", - "image-resolution", - "ime-mode", - "initial-letter", - "initial-letter-align", - "inline-size", - "inset", - "inset-block", - "inset-block-end", - "inset-block-start", - "inset-inline", - "inset-inline-end", - "inset-inline-start", - "interpolate-size", - "isolation", - "justify-content", - "justify-items", - "justify-self", - "justify-tracks", - "left", - "letter-spacing", - "lighting-color", - "line-break", - "line-clamp", - "line-height", - "line-height-step", - "list-style", - "list-style-image", - "list-style-position", - "list-style-type", - "margin", - "margin-block", - "margin-block-end", - "margin-block-start", - "margin-bottom", - "margin-inline", - "margin-inline-end", - "margin-inline-start", - "margin-left", - "margin-right", - "margin-top", - "margin-trim", - "marker", - "marker-end", - "marker-mid", - "marker-start", - "mask", - "mask-border", - "mask-border-mode", - "mask-border-outset", - "mask-border-repeat", - "mask-border-slice", - "mask-border-source", - "mask-border-width", - "mask-clip", - "mask-composite", - "mask-image", - "mask-mode", - "mask-origin", - "mask-position", - "mask-repeat", - "mask-size", - "mask-type", - "masonry-auto-flow", - "math-depth", - "math-shift", - "math-style", - "max-block-size", - "max-height", - "max-inline-size", - "max-lines", - "max-width", - "min-block-size", - "min-height", - "min-inline-size", - "min-width", - "mix-blend-mode", - "object-fit", - "object-position", - "object-view-box", - "offset", - "offset-anchor", - "offset-distance", - "offset-path", - "offset-position", - "offset-rotate", - "opacity", - "order", - "orphans", - "outline", - "outline-color", - "outline-offset", - "outline-style", - "outline-width", - "overflow", - "overflow-anchor", - "overflow-block", - "overflow-clip-box", - "overflow-clip-margin", - "overflow-inline", - "overflow-wrap", - "overflow-x", - "overflow-y", - "overlay", - "overscroll-behavior", - "overscroll-behavior-block", - "overscroll-behavior-inline", - "overscroll-behavior-x", - "overscroll-behavior-y", - "padding", - "padding-block", - "padding-block-end", - "padding-block-start", - "padding-bottom", - "padding-inline", - "padding-inline-end", - "padding-inline-start", - "padding-left", - "padding-right", - "padding-top", - "page", - "page-break-after", - "page-break-before", - "page-break-inside", - "paint-order", - "perspective", - "perspective-origin", - "place-content", - "place-items", - "place-self", - "pointer-events", - "position", - "position-anchor", - "position-area", - "position-try", - "position-try-fallbacks", - "position-try-order", - "position-visibility", - "print-color-adjust", - "quotes", - "r", - "resize", - "right", - "rotate", - "row-gap", - "ruby-align", - "ruby-merge", - "ruby-overhang", - "ruby-position", - "rx", - "ry", - "scale", - "scroll-behavior", - "scroll-initial-target", - "scroll-margin", - "scroll-margin-block", - "scroll-margin-block-end", - "scroll-margin-block-start", - "scroll-margin-bottom", - "scroll-margin-inline", - "scroll-margin-inline-end", - "scroll-margin-inline-start", - "scroll-margin-left", - "scroll-margin-right", - "scroll-margin-top", - "scroll-padding", - "scroll-padding-block", - "scroll-padding-block-end", - "scroll-padding-block-start", - "scroll-padding-bottom", - "scroll-padding-inline", - "scroll-padding-inline-end", - "scroll-padding-inline-start", - "scroll-padding-left", - "scroll-padding-right", - "scroll-padding-top", - "scroll-snap-align", - "scroll-snap-coordinate", - "scroll-snap-destination", - "scroll-snap-points-x", - "scroll-snap-points-y", - "scroll-snap-stop", - "scroll-snap-type", - "scroll-snap-type-x", - "scroll-snap-type-y", - "scroll-timeline", - "scroll-timeline-axis", - "scroll-timeline-name", - "scrollbar-color", - "scrollbar-gutter", - "scrollbar-width", - "shape-image-threshold", - "shape-margin", - "shape-outside", - "shape-rendering", - "speak-as", - "stop-color", - "stop-opacity", - "stroke", - "stroke-color", - "stroke-dasharray", - "stroke-dashoffset", - "stroke-linecap", - "stroke-linejoin", - "stroke-miterlimit", - "stroke-opacity", - "stroke-width", - "tab-size", - "table-layout", - "text-align", - "text-align-last", - "text-anchor", - "text-box", - "text-box-edge", - "text-box-trim", - "text-combine-upright", - "text-decoration", - "text-decoration-color", - "text-decoration-line", - "text-decoration-skip", - "text-decoration-skip-ink", - "text-decoration-style", - "text-decoration-thickness", - "text-emphasis", - "text-emphasis-color", - "text-emphasis-position", - "text-emphasis-style", - "text-indent", - "text-justify", - "text-orientation", - "text-overflow", - "text-rendering", - "text-shadow", - "text-size-adjust", - "text-spacing-trim", - "text-transform", - "text-underline-offset", - "text-underline-position", - "text-wrap", - "text-wrap-mode", - "text-wrap-style", - "timeline-scope", - "top", - "touch-action", - "transform", - "transform-box", - "transform-origin", - "transform-style", - "transition", - "transition-behavior", - "transition-delay", - "transition-duration", - "transition-property", - "transition-timing-function", - "translate", - "unicode-bidi", - "user-select", - "vector-effect", - "vertical-align", - "view-timeline", - "view-timeline-axis", - "view-timeline-inset", - "view-timeline-name", - "view-transition-class", - "view-transition-name", - "visibility", - "white-space", - "white-space-collapse", - "widows", - "width", - "will-change", - "word-break", - "word-spacing", - "word-wrap", - "writing-mode", - "x", - "y", - "z-index", - "zoom", - ] - .map(to_camel_case), - ); + let css: HashSet = HashSet::from_iter(["accent-color", "align-content", "align-items", "align-self", "align-tracks", "alignment-baseline", "all", "anchor-name", "anchor-scope", "animation", "animation-composition", "animation-delay", "animation-direction", "animation-duration", "animation-fill-mode", "animation-iteration-count", "animation-name", "animation-play-state", "animation-range", "animation-range-end", "animation-range-start", "animation-timeline", "animation-timing-function", "appearance", "aspect-ratio", "backdrop-filter", "backface-visibility", "background", "background-attachment", "background-blend-mode", "background-clip", "background-color", "background-image", "background-origin", "background-position", "background-position-x", "background-position-y", "background-repeat", "background-size", "baseline-shift", "block-size", "border", "border-block", "border-block-color", "border-block-end", "border-block-end-color", "border-block-end-style", "border-block-end-width", "border-block-start", "border-block-start-color", "border-block-start-style", "border-block-start-width", "border-block-style", "border-block-width", "border-bottom", "border-bottom-color", "border-bottom-left-radius", "border-bottom-right-radius", "border-bottom-style", "border-bottom-width", "border-collapse", "border-color", "border-end-end-radius", "border-end-start-radius", "border-image", "border-image-outset", "border-image-repeat", "border-image-slice", "border-image-source", "border-image-width", "border-inline", "border-inline-color", "border-inline-end", "border-inline-end-color", "border-inline-end-style", "border-inline-end-width", "border-inline-start", "border-inline-start-color", "border-inline-start-style", "border-inline-start-width", "border-inline-style", "border-inline-width", "border-left", "border-left-color", "border-left-style", "border-left-width", "border-radius", "border-right", "border-right-color", "border-right-style", "border-right-width", "border-spacing", "border-start-end-radius", "border-start-start-radius", "border-style", "border-top", "border-top-color", "border-top-left-radius", "border-top-right-radius", "border-top-style", "border-top-width", "border-width", "bottom", "box-align", "box-decoration-break", "box-direction", "box-flex", "box-flex-group", "box-lines", "box-ordinal-group", "box-orient", "box-pack", "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", "caption-side", "caret", "caret-color", "caret-shape", "clear", "clip", "clip-path", "clip-rule", "color", "color-interpolation-filters", "color-scheme", "column-count", "column-fill", "column-gap", "column-rule", "column-rule-color", "column-rule-style", "column-rule-width", "column-span", "column-width", "columns", "contain", "contain-intrinsic-block-size", "contain-intrinsic-height", "contain-intrinsic-inline-size", "contain-intrinsic-size", "contain-intrinsic-width", "container", "container-name", "container-type", "content", "content-visibility", "counter-increment", "counter-reset", "counter-set", "cursor", "cx", "cy", "d", "direction", "display", "dominant-baseline", "empty-cells", "field-sizing", "fill", "fill-opacity", "fill-rule", "filter", "flex", "flex-basis", "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", "float", "flood-color", "flood-opacity", "font", "font-family", "font-feature-settings", "font-kerning", "font-language-override", "font-optical-sizing", "font-palette", "font-size", "font-size-adjust", "font-smooth", "font-stretch", "font-style", "font-synthesis", "font-synthesis-position", "font-synthesis-small-caps", "font-synthesis-style", "font-synthesis-weight", "font-variant", "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", "font-variant-emoji", "font-variant-ligatures", "font-variant-numeric", "font-variant-position", "font-variation-settings", "font-weight", "font-width", "forced-color-adjust", "gap", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap", "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns", "grid-template-rows", "hanging-punctuation", "height", "hyphenate-character", "hyphenate-limit-chars", "hyphens", "image-orientation", "image-rendering", "image-resolution", "ime-mode", "initial-letter", "initial-letter-align", "inline-size", "inset", "inset-block", "inset-block-end", "inset-block-start", "inset-inline", "inset-inline-end", "inset-inline-start", "interpolate-size", "isolation", "justify-content", "justify-items", "justify-self", "justify-tracks", "left", "letter-spacing", "lighting-color", "line-break", "line-clamp", "line-height", "line-height-step", "list-style", "list-style-image", "list-style-position", "list-style-type", "margin", "margin-block", "margin-block-end", "margin-block-start", "margin-bottom", "margin-inline", "margin-inline-end", "margin-inline-start", "margin-left", "margin-right", "margin-top", "margin-trim", "marker", "marker-end", "marker-mid", "marker-start", "mask", "mask-border", "mask-border-mode", "mask-border-outset", "mask-border-repeat", "mask-border-slice", "mask-border-source", "mask-border-width", "mask-clip", "mask-composite", "mask-image", "mask-mode", "mask-origin", "mask-position", "mask-repeat", "mask-size", "mask-type", "masonry-auto-flow", "math-depth", "math-shift", "math-style", "max-block-size", "max-height", "max-inline-size", "max-lines", "max-width", "min-block-size", "min-height", "min-inline-size", "min-width", "mix-blend-mode", "object-fit", "object-position", "object-view-box", "offset", "offset-anchor", "offset-distance", "offset-path", "offset-position", "offset-rotate", "opacity", "order", "orphans", "outline", "outline-color", "outline-offset", "outline-style", "outline-width", "overflow", "overflow-anchor", "overflow-block", "overflow-clip-box", "overflow-clip-margin", "overflow-inline", "overflow-wrap", "overflow-x", "overflow-y", "overlay", "overscroll-behavior", "overscroll-behavior-block", "overscroll-behavior-inline", "overscroll-behavior-x", "overscroll-behavior-y", "padding", "padding-block", "padding-block-end", "padding-block-start", "padding-bottom", "padding-inline", "padding-inline-end", "padding-inline-start", "padding-left", "padding-right", "padding-top", "page", "page-break-after", "page-break-before", "page-break-inside", "paint-order", "perspective", "perspective-origin", "place-content", "place-items", "place-self", "pointer-events", "position", "position-anchor", "position-area", "position-try", "position-try-fallbacks", "position-try-order", "position-visibility", "print-color-adjust", "quotes", "r", "resize", "right", "rotate", "row-gap", "ruby-align", "ruby-merge", "ruby-overhang", "ruby-position", "rx", "ry", "scale", "scroll-behavior", "scroll-initial-target", "scroll-margin", "scroll-margin-block", "scroll-margin-block-end", "scroll-margin-block-start", "scroll-margin-bottom", "scroll-margin-inline", "scroll-margin-inline-end", "scroll-margin-inline-start", "scroll-margin-left", "scroll-margin-right", "scroll-margin-top", "scroll-padding", "scroll-padding-block", "scroll-padding-block-end", "scroll-padding-block-start", "scroll-padding-bottom", "scroll-padding-inline", "scroll-padding-inline-end", "scroll-padding-inline-start", "scroll-padding-left", "scroll-padding-right", "scroll-padding-top", "scroll-snap-align", "scroll-snap-coordinate", "scroll-snap-destination", "scroll-snap-points-x", "scroll-snap-points-y", "scroll-snap-stop", "scroll-snap-type", "scroll-snap-type-x", "scroll-snap-type-y", "scroll-timeline", "scroll-timeline-axis", "scroll-timeline-name", "scrollbar-color", "scrollbar-gutter", "scrollbar-width", "shape-image-threshold", "shape-margin", "shape-outside", "shape-rendering", "speak-as", "stop-color", "stop-opacity", "stroke", "stroke-color", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tab-size", "table-layout", "text-align", "text-align-last", "text-anchor", "text-box", "text-box-edge", "text-box-trim", "text-combine-upright", "text-decoration", "text-decoration-color", "text-decoration-line", "text-decoration-skip", "text-decoration-skip-ink", "text-decoration-style", "text-decoration-thickness", "text-emphasis", "text-emphasis-color", "text-emphasis-position", "text-emphasis-style", "text-indent", "text-justify", "text-orientation", "text-overflow", "text-rendering", "text-shadow", "text-size-adjust", "text-spacing-trim", "text-transform", "text-underline-offset", "text-underline-position", "text-wrap", "text-wrap-mode", "text-wrap-style", "timeline-scope", "top", "touch-action", "transform", "transform-box", "transform-origin", "transform-style", "transition", "transition-behavior", "transition-delay", "transition-duration", "transition-property", "transition-timing-function", "translate", "unicode-bidi", "user-select", "vector-effect", "vertical-align", "view-timeline", "view-timeline-axis", "view-timeline-inset", "view-timeline-name", "view-transition-class", "view-transition-name", "visibility", "white-space", "white-space-collapse", "widows", "width", "will-change", "word-break", "word-spacing", "word-wrap", "writing-mode", "x", "y", "z-index", "zoom"].map(to_camel_case)); for property in SPECIAL_PROPERTIES.iter() { assert!(!css.contains(*property)); diff --git a/libs/css/src/lib.rs b/libs/css/src/lib.rs index 1b0bfdff..747d66b7 100644 --- a/libs/css/src/lib.rs +++ b/libs/css/src/lib.rs @@ -15,9 +15,7 @@ use std::collections::BTreeMap; use std::hash::{DefaultHasher, Hash, Hasher}; use crate::class_map::GLOBAL_CLASS_MAP; -use crate::constant::{ - COLOR_HASH, F_SPACE_RE, GLOBAL_ENUM_STYLE_PROPERTY, GLOBAL_STYLE_PROPERTY, ZERO_RE, -}; +use crate::constant::{COLOR_HASH, F_SPACE_RE, GLOBAL_ENUM_STYLE_PROPERTY, GLOBAL_STYLE_PROPERTY, ZERO_RE}; use crate::debug::is_debug; use crate::file_map::get_file_num_by_filename; use crate::num_to_nm_base::num_to_nm_base; @@ -50,51 +48,19 @@ pub fn disassemble_property(property: &str) -> Vec { 1 => vec![v[0].to_string()], _ => v.iter().map(|v| v.to_string()).collect(), }) - .unwrap_or_else(|| { - vec![if (property.starts_with("Webkit") - && property.len() > 6 - && property.chars().nth(6).unwrap().is_uppercase()) - || (property.starts_with("Moz") - && property.len() > 3 - && property.chars().nth(3).unwrap().is_uppercase()) - || (property.starts_with("ms") - && property.len() > 2 - && property.chars().nth(2).unwrap().is_uppercase()) - { - format!("-{}", to_kebab_case(property)) - } else { - to_kebab_case(property) - }] - }) + .unwrap_or_else(|| vec![if (property.starts_with("Webkit") && property.len() > 6 && property.chars().nth(6).unwrap().is_uppercase()) || (property.starts_with("Moz") && property.len() > 3 && property.chars().nth(3).unwrap().is_uppercase()) || (property.starts_with("ms") && property.len() > 2 && property.chars().nth(2).unwrap().is_uppercase()) { format!("-{}", to_kebab_case(property)) } else { to_kebab_case(property) }]) } pub fn add_selector_params(selector: StyleSelector, params: &str) -> StyleSelector { match selector { StyleSelector::Selector(value) => StyleSelector::Selector(format!("{}({})", value, params)), - StyleSelector::Global(value, file) => { - StyleSelector::Global(format!("{}({})", value, params), file) - } - StyleSelector::Media { query, selector } => StyleSelector::Media { - query: query.to_string(), - selector: selector.map(|s| format!("{}({})", s, params)), - }, + StyleSelector::Global(value, file) => StyleSelector::Global(format!("{}({})", value, params), file), + StyleSelector::Media { query, selector } => StyleSelector::Media { query: query.to_string(), selector: selector.map(|s| format!("{}({})", s, params)) }, } } pub fn get_enum_property_value(property: &str, value: &str) -> Option> { - if let Some(map) = GLOBAL_ENUM_STYLE_PROPERTY.get(property) { - if let Some(map) = map.get(value) { - Some( - map.entries() - .map(|(k, v)| (k.to_string(), v.to_string())) - .collect(), - ) - } else { - Some(vec![]) - } - } else { - None - } + if let Some(map) = GLOBAL_ENUM_STYLE_PROPERTY.get(property) { if let Some(map) = map.get(value) { Some(map.entries().map(|(k, v)| (k.to_string(), v.to_string())).collect()) } else { Some(vec![]) } } else { None } } pub fn get_enum_property_map(property: &str) -> Option>> { @@ -120,43 +86,19 @@ pub fn keyframes_to_keyframes_name(keyframes: &str, filename: Option<&str>) -> S let key = format!("k-{keyframes}"); let mut map = GLOBAL_CLASS_MAP.lock().unwrap(); let filename = filename.unwrap_or_default().to_string(); - let class_num = map - .entry(filename.to_string()) - .or_default() - .get(&key) - .map(|v| num_to_nm_base(*v).to_string()) - .unwrap_or_else(|| { - let m = map.entry(filename.to_string()).or_default(); - let len = m.len(); - m.insert(key, len); - num_to_nm_base(len).to_string() - }); - if !filename.is_empty() { - format!( - "{}-{}", - num_to_nm_base(get_file_num_by_filename(&filename)), - class_num - ) - } else { - class_num - } + let class_num = map.entry(filename.to_string()).or_default().get(&key).map(|v| num_to_nm_base(*v).to_string()).unwrap_or_else(|| { + let m = map.entry(filename.to_string()).or_default(); + let len = m.len(); + m.insert(key, len); + num_to_nm_base(len).to_string() + }); + if !filename.is_empty() { format!("{}-{}", num_to_nm_base(get_file_num_by_filename(&filename)), class_num) } else { class_num } } } -pub fn sheet_to_classname( - property: &str, - level: u8, - value: Option<&str>, - selector: Option<&str>, - style_order: Option, - filename: Option<&str>, -) -> String { +pub fn sheet_to_classname(property: &str, level: u8, value: Option<&str>, selector: Option<&str>, style_order: Option, filename: Option<&str>) -> String { // base style - let filename = if style_order == Some(0) { - None - } else { - filename - }; + let filename = if style_order == Some(0) { None } else { filename }; if is_debug() { let selector = selector.unwrap_or_default().trim(); format!( @@ -172,44 +114,19 @@ pub fn sheet_to_classname( hasher.finish().to_string() }, style_order.unwrap_or(255), - filename - .map(|v| format!("-{}", get_file_num_by_filename(v))) - .unwrap_or_default(), + filename.map(|v| format!("-{}", get_file_num_by_filename(v))).unwrap_or_default(), ) } else { - let key = format!( - "{}-{}-{}-{}-{}{}", - property.trim(), - level, - optimize_value(value.unwrap_or_default()), - selector.unwrap_or_default().trim(), - style_order.unwrap_or(255), - filename - .map(|v| format!("-{}", get_file_num_by_filename(v))) - .unwrap_or_default(), - ); + let key = format!("{}-{}-{}-{}-{}{}", property.trim(), level, optimize_value(value.unwrap_or_default()), selector.unwrap_or_default().trim(), style_order.unwrap_or(255), filename.map(|v| format!("-{}", get_file_num_by_filename(v))).unwrap_or_default(),); let mut map = GLOBAL_CLASS_MAP.lock().unwrap(); let filename = filename.map(|v| v.to_string()).unwrap_or_default(); - let clas_num = map - .entry(filename.to_string()) - .or_default() - .get(&key) - .map(|v| num_to_nm_base(*v)) - .unwrap_or_else(|| { - let m = map.entry(filename.to_string()).or_default(); - let len = m.len(); - m.insert(key, len); - num_to_nm_base(len) - }); - if !filename.is_empty() { - format!( - "{}-{}", - num_to_nm_base(get_file_num_by_filename(&filename)), - clas_num - ) - } else { - clas_num - } + let clas_num = map.entry(filename.to_string()).or_default().get(&key).map(|v| num_to_nm_base(*v)).unwrap_or_else(|| { + let m = map.entry(filename.to_string()).or_default(); + let len = m.len(); + m.insert(key, len); + num_to_nm_base(len) + }); + if !filename.is_empty() { format!("{}-{}", num_to_nm_base(get_file_num_by_filename(&filename)), clas_num) } else { clas_num } } } @@ -230,23 +147,14 @@ pub fn sheet_to_variable_name(property: &str, level: u8, selector: Option<&str>) } ) } else { - let key = format!( - "{}-{}-{}", - property, - level, - selector.unwrap_or_default().trim() - ); + let key = format!("{}-{}-{}", property, level, selector.unwrap_or_default().trim()); let mut map = GLOBAL_CLASS_MAP.lock().unwrap(); - map.entry("".to_string()) - .or_default() - .get(&key) - .map(|v| format!("--{}", num_to_nm_base(*v))) - .unwrap_or_else(|| { - let m = map.entry("".to_string()).or_default(); - let len = m.len(); - m.insert(key, len); - format!("--{}", num_to_nm_base(len)) - }) + map.entry("".to_string()).or_default().get(&key).map(|v| format!("--{}", num_to_nm_base(*v))).unwrap_or_else(|| { + let m = map.entry("".to_string()).or_default(); + let len = m.len(); + m.insert(key, len); + format!("--{}", num_to_nm_base(len)) + }) } } @@ -268,37 +176,19 @@ mod tests { reset_class_map(); set_debug(false); assert_eq!(sheet_to_variable_name("background", 0, None), "--a"); - assert_eq!( - sheet_to_variable_name("background", 0, Some("hover")), - "--b" - ); + assert_eq!(sheet_to_variable_name("background", 0, Some("hover")), "--b"); assert_eq!(sheet_to_variable_name("background", 1, None), "--c"); - assert_eq!( - sheet_to_variable_name("background", 1, Some("hover")), - "--d" - ); + assert_eq!(sheet_to_variable_name("background", 1, Some("hover")), "--d"); } #[test] #[serial] fn test_debug_sheet_to_variable_name() { set_debug(true); - assert_eq!( - sheet_to_variable_name("background", 0, None), - "--background-0-" - ); - assert_eq!( - sheet_to_variable_name("background", 0, Some("hover")), - "--background-0-12448419602614487988" - ); - assert_eq!( - sheet_to_variable_name("background", 1, None), - "--background-1-" - ); - assert_eq!( - sheet_to_variable_name("background", 1, Some("hover")), - "--background-1-12448419602614487988" - ); + assert_eq!(sheet_to_variable_name("background", 0, None), "--background-0-"); + assert_eq!(sheet_to_variable_name("background", 0, Some("hover")), "--background-0-12448419602614487988"); + assert_eq!(sheet_to_variable_name("background", 1, None), "--background-1-"); + assert_eq!(sheet_to_variable_name("background", 1, Some("hover")), "--background-1-12448419602614487988"); } #[test] @@ -306,361 +196,107 @@ mod tests { fn test_sheet_to_classname() { set_debug(false); reset_class_map(); - assert_eq!( - sheet_to_classname("background", 0, Some("red"), None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("background", 0, Some("red"), Some("hover"), None, None), - "b" - ); - assert_eq!( - sheet_to_classname("background", 1, None, None, None, None), - "c" - ); - assert_eq!( - sheet_to_classname("background", 1, None, Some("hover"), None, None), - "d" - ); + assert_eq!(sheet_to_classname("background", 0, Some("red"), None, None, None), "a"); + assert_eq!(sheet_to_classname("background", 0, Some("red"), Some("hover"), None, None), "b"); + assert_eq!(sheet_to_classname("background", 1, None, None, None, None), "c"); + assert_eq!(sheet_to_classname("background", 1, None, Some("hover"), None, None), "d"); reset_class_map(); - assert_eq!( - sheet_to_classname("background", 0, None, None, None, None), - sheet_to_classname("background", 0, None, None, None, None) - ); - assert_eq!( - sheet_to_classname("background", 0, Some("red"), None, None, None), - sheet_to_classname("background", 0, Some("red"), None, None, None), - ); - assert_eq!( - sheet_to_classname("background", 0, Some("red"), None, None, None), - sheet_to_classname(" background ", 0, Some(" red "), None, None, None), - ); - assert_eq!( - sheet_to_classname("background", 0, Some("red"), None, None, None), - sheet_to_classname(" background ", 0, Some("red;"), None, None, None), - ); - assert_eq!( - sheet_to_classname( - "background", - 0, - Some("rgba(255, 0, 0, 0.5)"), - None, - None, - None - ), - sheet_to_classname("background", 0, Some("rgba(255,0,0,0.5)"), None, None, None), - ); - - assert_eq!( - sheet_to_classname( - "background", - 0, - Some("rgba(255, 0, 0, 0.5)"), - None, - None, - None - ), - sheet_to_classname("background", 0, Some("rgba(255,0,0,.5)"), None, None, None), - ); - - assert_eq!( - sheet_to_classname( - "background", - 0, - Some("rgba(255, 0, 0, 0.5)"), - None, - None, - None - ), - sheet_to_classname("background", 0, Some("#FF000080"), None, None, None), - ); + assert_eq!(sheet_to_classname("background", 0, None, None, None, None), sheet_to_classname("background", 0, None, None, None, None)); + assert_eq!(sheet_to_classname("background", 0, Some("red"), None, None, None), sheet_to_classname("background", 0, Some("red"), None, None, None),); + assert_eq!(sheet_to_classname("background", 0, Some("red"), None, None, None), sheet_to_classname(" background ", 0, Some(" red "), None, None, None),); + assert_eq!(sheet_to_classname("background", 0, Some("red"), None, None, None), sheet_to_classname(" background ", 0, Some("red;"), None, None, None),); + assert_eq!(sheet_to_classname("background", 0, Some("rgba(255, 0, 0, 0.5)"), None, None, None), sheet_to_classname("background", 0, Some("rgba(255,0,0,0.5)"), None, None, None),); + + assert_eq!(sheet_to_classname("background", 0, Some("rgba(255, 0, 0, 0.5)"), None, None, None), sheet_to_classname("background", 0, Some("rgba(255,0,0,.5)"), None, None, None),); + + assert_eq!(sheet_to_classname("background", 0, Some("rgba(255, 0, 0, 0.5)"), None, None, None), sheet_to_classname("background", 0, Some("#FF000080"), None, None, None),); { let map = GLOBAL_CLASS_MAP.lock().unwrap(); - assert_eq!( - map.get("").unwrap().get("background-0-#FF000080--255"), - Some(&2) - ); + assert_eq!(map.get("").unwrap().get("background-0-#FF000080--255"), Some(&2)); } - assert_eq!( - sheet_to_classname("background", 0, Some("#fff"), None, None, None), - sheet_to_classname(" background ", 0, Some("#FFF"), None, None, None), - ); + assert_eq!(sheet_to_classname("background", 0, Some("#fff"), None, None, None), sheet_to_classname(" background ", 0, Some("#FFF"), None, None, None),); - assert_eq!( - sheet_to_classname("background", 0, Some("#ffffff"), None, None, None), - sheet_to_classname("background", 0, Some("#FFF"), None, None, None), - ); + assert_eq!(sheet_to_classname("background", 0, Some("#ffffff"), None, None, None), sheet_to_classname("background", 0, Some("#FFF"), None, None, None),); { let map = GLOBAL_CLASS_MAP.lock().unwrap(); assert_eq!(map.get("").unwrap().get("background-0-#FFF--255"), Some(&3)); } - assert_eq!( - sheet_to_classname("background", 0, Some("#ffffff"), None, None, None), - sheet_to_classname("background", 0, Some("#FFFFFF"), None, None, None), - ); + assert_eq!(sheet_to_classname("background", 0, Some("#ffffff"), None, None, None), sheet_to_classname("background", 0, Some("#FFFFFF"), None, None, None),); - assert_eq!( - sheet_to_classname("background", 0, Some("#ffffffAA"), None, None, None), - sheet_to_classname("background", 0, Some("#FFFFFFaa"), None, None, None), - ); + assert_eq!(sheet_to_classname("background", 0, Some("#ffffffAA"), None, None, None), sheet_to_classname("background", 0, Some("#FFFFFFaa"), None, None, None),); { let map = GLOBAL_CLASS_MAP.lock().unwrap(); - assert_eq!( - map.get("").unwrap().get("background-0-#FFFA--255"), - Some(&4) - ); + assert_eq!(map.get("").unwrap().get("background-0-#FFFA--255"), Some(&4)); } - assert_eq!( - sheet_to_classname( - "background", - 0, - Some("color-mix(in srgb,var(--primary) 80%, #000 20%)"), - None, - None, - None - ), - sheet_to_classname( - "background", - 0, - Some("color-mix(in srgb, var(--primary) 80%, #000000 20%)"), - None, - None, - None - ), - ); + assert_eq!(sheet_to_classname("background", 0, Some("color-mix(in srgb,var(--primary) 80%, #000 20%)"), None, None, None), sheet_to_classname("background", 0, Some("color-mix(in srgb, var(--primary) 80%, #000000 20%)"), None, None, None),); reset_class_map(); - assert_eq!( - sheet_to_classname("background", 0, None, None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("background", 0, None, None, Some(1), None), - "b" - ); + assert_eq!(sheet_to_classname("background", 0, None, None, None, None), "a"); + assert_eq!(sheet_to_classname("background", 0, None, None, Some(1), None), "b"); reset_class_map(); - assert_eq!( - sheet_to_classname("width", 0, Some("0px"), None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("width", 0, Some("0em"), None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("width", 0, Some("0rem"), None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("width", 0, Some("0vh"), None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("width", 0, Some("0%"), None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("width", 0, Some("0dvh"), None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("width", 0, Some("0dvw"), None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("width", 0, Some("0vw"), None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("width", 0, Some("0"), None, None, None), - "a" - ); - assert_eq!( - sheet_to_classname("border", 0, Some("solid 0px red"), None, None, None), - "b" - ); - assert_eq!( - sheet_to_classname("border", 0, Some("solid 0% red"), None, None, None), - "b" - ); - assert_eq!( - sheet_to_classname("border", 0, Some("solid 0em red"), None, None, None), - "b" - ); - assert_eq!( - sheet_to_classname("border", 0, Some("solid 0rem red"), None, None, None), - "b" - ); - assert_eq!( - sheet_to_classname("border", 0, Some("solid 0vh red"), None, None, None), - "b" - ); - assert_eq!( - sheet_to_classname("border", 0, Some("solid 0vw red"), None, None, None), - "b" - ); - assert_eq!( - sheet_to_classname("border", 0, Some("solid 0dvh red"), None, None, None), - "b" - ); - assert_eq!( - sheet_to_classname("border", 0, Some("solid 0dvw red"), None, None, None), - "b" - ); - - assert_eq!( - sheet_to_classname("test", 0, Some("0px 0"), None, None, None), - "c" - ); - assert_eq!( - sheet_to_classname("test", 0, Some("0em 0"), None, None, None), - "c" - ); - assert_eq!( - sheet_to_classname("test", 0, Some("0rem 0"), None, None, None), - "c" - ); - assert_eq!( - sheet_to_classname("test", 0, Some("0vh 0"), None, None, None), - "c" - ); - assert_eq!( - sheet_to_classname("test", 0, Some("0vw 0"), None, None, None), - "c" - ); - assert_eq!( - sheet_to_classname("test", 0, Some("0dvh 0"), None, None, None), - "c" - ); - - assert_eq!( - sheet_to_classname("test", 0, Some("0 0vh"), None, None, None), - "c" - ); - assert_eq!( - sheet_to_classname("test", 0, Some("0 0vw"), None, None, None), - "c" - ); + assert_eq!(sheet_to_classname("width", 0, Some("0px"), None, None, None), "a"); + assert_eq!(sheet_to_classname("width", 0, Some("0em"), None, None, None), "a"); + assert_eq!(sheet_to_classname("width", 0, Some("0rem"), None, None, None), "a"); + assert_eq!(sheet_to_classname("width", 0, Some("0vh"), None, None, None), "a"); + assert_eq!(sheet_to_classname("width", 0, Some("0%"), None, None, None), "a"); + assert_eq!(sheet_to_classname("width", 0, Some("0dvh"), None, None, None), "a"); + assert_eq!(sheet_to_classname("width", 0, Some("0dvw"), None, None, None), "a"); + assert_eq!(sheet_to_classname("width", 0, Some("0vw"), None, None, None), "a"); + assert_eq!(sheet_to_classname("width", 0, Some("0"), None, None, None), "a"); + assert_eq!(sheet_to_classname("border", 0, Some("solid 0px red"), None, None, None), "b"); + assert_eq!(sheet_to_classname("border", 0, Some("solid 0% red"), None, None, None), "b"); + assert_eq!(sheet_to_classname("border", 0, Some("solid 0em red"), None, None, None), "b"); + assert_eq!(sheet_to_classname("border", 0, Some("solid 0rem red"), None, None, None), "b"); + assert_eq!(sheet_to_classname("border", 0, Some("solid 0vh red"), None, None, None), "b"); + assert_eq!(sheet_to_classname("border", 0, Some("solid 0vw red"), None, None, None), "b"); + assert_eq!(sheet_to_classname("border", 0, Some("solid 0dvh red"), None, None, None), "b"); + assert_eq!(sheet_to_classname("border", 0, Some("solid 0dvw red"), None, None, None), "b"); + + assert_eq!(sheet_to_classname("test", 0, Some("0px 0"), None, None, None), "c"); + assert_eq!(sheet_to_classname("test", 0, Some("0em 0"), None, None, None), "c"); + assert_eq!(sheet_to_classname("test", 0, Some("0rem 0"), None, None, None), "c"); + assert_eq!(sheet_to_classname("test", 0, Some("0vh 0"), None, None, None), "c"); + assert_eq!(sheet_to_classname("test", 0, Some("0vw 0"), None, None, None), "c"); + assert_eq!(sheet_to_classname("test", 0, Some("0dvh 0"), None, None, None), "c"); + + assert_eq!(sheet_to_classname("test", 0, Some("0 0vh"), None, None, None), "c"); + assert_eq!(sheet_to_classname("test", 0, Some("0 0vw"), None, None, None), "c"); reset_class_map(); - assert_eq!( - sheet_to_classname( - "transition", - 0, - Some("all 0.3s ease-in-out"), - None, - None, - None - ), - "a" - ); - assert_eq!( - sheet_to_classname( - "transition", - 0, - Some("all .3s ease-in-out"), - None, - None, - None - ), - "a" - ); + assert_eq!(sheet_to_classname("transition", 0, Some("all 0.3s ease-in-out"), None, None, None), "a"); + assert_eq!(sheet_to_classname("transition", 0, Some("all .3s ease-in-out"), None, None, None), "a"); } #[test] #[serial] fn test_debug_sheet_to_classname() { set_debug(true); - assert_eq!( - sheet_to_classname("background", 0, None, None, None, None), - "background-0---255" - ); - assert_eq!( - sheet_to_classname("background", 0, Some("red"), Some("hover"), None, None), - "background-0-red-12448419602614487988-255" - ); - assert_eq!( - sheet_to_classname("background", 1, None, None, None, None), - "background-1---255" - ); - assert_eq!( - sheet_to_classname("background", 1, Some("red"), Some("hover"), None, None), - "background-1-red-12448419602614487988-255" - ); + assert_eq!(sheet_to_classname("background", 0, None, None, None, None), "background-0---255"); + assert_eq!(sheet_to_classname("background", 0, Some("red"), Some("hover"), None, None), "background-0-red-12448419602614487988-255"); + assert_eq!(sheet_to_classname("background", 1, None, None, None, None), "background-1---255"); + assert_eq!(sheet_to_classname("background", 1, Some("red"), Some("hover"), None, None), "background-1-red-12448419602614487988-255"); } #[test] fn test_merge_selector() { assert_eq!(merge_selector("cls", Some(&"hover".into())), ".cls:hover"); - assert_eq!( - merge_selector("cls", Some(&"placeholder".into())), - ".cls::placeholder" - ); - assert_eq!( - merge_selector("cls", Some(&"theme-dark".into())), - ":root[data-theme=dark] .cls" - ); - assert_eq!( - merge_selector( - "cls", - Some(&StyleSelector::Selector( - ":root[data-theme=dark]:hover &".to_string(), - )), - ), - ":root[data-theme=dark]:hover .cls" - ); - assert_eq!( - merge_selector( - "cls", - Some(&StyleSelector::Selector( - ":root[data-theme=dark]::placeholder &".to_string() - )), - ), - ":root[data-theme=dark]::placeholder .cls" - ); - - assert_eq!( - merge_selector("cls", Some(&["theme-dark", "hover"].into()),), - ":root[data-theme=dark] .cls:hover" - ); - assert_eq!( - merge_selector( - "cls", - Some(&StyleSelector::Media { - query: "print".to_string(), - selector: None - }) - ), - ".cls" - ); - - assert_eq!( - merge_selector( - "cls", - Some(&StyleSelector::Media { - query: "print".to_string(), - selector: Some("&:hover".to_string()) - }) - ), - ".cls:hover" - ); - - assert_eq!( - merge_selector( - "cls", - Some(&StyleSelector::Global( - "&".to_string(), - "file.ts".to_string() - )) - ), - "&" - ); + assert_eq!(merge_selector("cls", Some(&"placeholder".into())), ".cls::placeholder"); + assert_eq!(merge_selector("cls", Some(&"theme-dark".into())), ":root[data-theme=dark] .cls"); + assert_eq!(merge_selector("cls", Some(&StyleSelector::Selector(":root[data-theme=dark]:hover &".to_string(),)),), ":root[data-theme=dark]:hover .cls"); + assert_eq!(merge_selector("cls", Some(&StyleSelector::Selector(":root[data-theme=dark]::placeholder &".to_string())),), ":root[data-theme=dark]::placeholder .cls"); + + assert_eq!(merge_selector("cls", Some(&["theme-dark", "hover"].into()),), ":root[data-theme=dark] .cls:hover"); + assert_eq!(merge_selector("cls", Some(&StyleSelector::Media { query: "print".to_string(), selector: None })), ".cls"); + + assert_eq!(merge_selector("cls", Some(&StyleSelector::Media { query: "print".to_string(), selector: Some("&:hover".to_string()) })), ".cls:hover"); + + assert_eq!(merge_selector("cls", Some(&StyleSelector::Global("&".to_string(), "file.ts".to_string()))), "&"); } #[test] @@ -668,9 +304,7 @@ mod tests { fn test_set_class_map() { let mut map = HashMap::new(); map.insert("".to_string(), HashMap::new()); - map.get_mut("") - .unwrap() - .insert("background-0-rgba(255,0,0,0.5)-".to_string(), 1); + map.get_mut("").unwrap().insert("background-0-rgba(255,0,0,0.5)-".to_string(), 1); set_class_map(map); assert_eq!(get_class_map().len(), 1); } @@ -682,10 +316,7 @@ mod tests { set_debug(false); assert_eq!(keyframes_to_keyframes_name("spin", None), num_to_nm_base(0)); assert_eq!(keyframes_to_keyframes_name("spin", None), num_to_nm_base(0)); - assert_eq!( - keyframes_to_keyframes_name("spin2", None), - num_to_nm_base(1) - ); + assert_eq!(keyframes_to_keyframes_name("spin2", None), num_to_nm_base(1)); reset_class_map(); set_debug(true); assert_eq!(keyframes_to_keyframes_name("spin", None), "k-spin"); @@ -694,29 +325,8 @@ mod tests { #[test] fn test_add_selector_params() { - assert_eq!( - add_selector_params(StyleSelector::Selector("hover:is".to_string()), "test"), - StyleSelector::Selector("hover:is(test)".to_string()) - ); - assert_eq!( - add_selector_params( - StyleSelector::Global("&:is".to_string(), "file.ts".to_string()), - "test" - ), - StyleSelector::Global("&:is(test)".to_string(), "file.ts".to_string()) - ); - assert_eq!( - add_selector_params( - StyleSelector::Media { - query: "print".to_string(), - selector: Some("&:is".to_string()) - }, - "test" - ), - StyleSelector::Media { - query: "print".to_string(), - selector: Some("&:is(test)".to_string()) - } - ); + assert_eq!(add_selector_params(StyleSelector::Selector("hover:is".to_string()), "test"), StyleSelector::Selector("hover:is(test)".to_string())); + assert_eq!(add_selector_params(StyleSelector::Global("&:is".to_string(), "file.ts".to_string()), "test"), StyleSelector::Global("&:is(test)".to_string(), "file.ts".to_string())); + assert_eq!(add_selector_params(StyleSelector::Media { query: "print".to_string(), selector: Some("&:is".to_string()) }, "test"), StyleSelector::Media { query: "print".to_string(), selector: Some("&:is(test)".to_string()) }); } } diff --git a/libs/css/src/optimize_multi_css_value.rs b/libs/css/src/optimize_multi_css_value.rs index ff0e1a0f..e356e727 100644 --- a/libs/css/src/optimize_multi_css_value.rs +++ b/libs/css/src/optimize_multi_css_value.rs @@ -5,29 +5,15 @@ pub fn optimize_mutli_css_value(value: &str) -> String { .split(",") .map(|s| { let s = s.trim(); - let s = if s.starts_with("'") && s.ends_with("'") - || s.starts_with('"') && s.ends_with('"') - { - s[1..s.len() - 1].to_string() - } else { - s.to_string() - }; - if CHECK_QUOTES_RE.is_match(&s) && !CSS_FUNCTION_RE.is_match(&s) { - format!("\"{s}\"") - } else { - s - } + let s = if s.starts_with("'") && s.ends_with("'") || s.starts_with('"') && s.ends_with('"') { s[1..s.len() - 1].to_string() } else { s.to_string() }; + if CHECK_QUOTES_RE.is_match(&s) && !CSS_FUNCTION_RE.is_match(&s) { format!("\"{s}\"") } else { s } }) .collect::>() .join(",") } pub fn wrap_url(s: &str) -> String { - if CSS_FUNCTION_RE.is_match(s) { - s.to_string() - } else { - format!("url({s})") - } + if CSS_FUNCTION_RE.is_match(s) { s.to_string() } else { format!("url({s})") } } pub fn check_multi_css_optimize(property: &str) -> bool { @@ -50,10 +36,7 @@ mod tests { #[case("'Roboto'", "Roboto")] #[case("\"Roboto\"", "Roboto")] #[case("url('/fonts/Roboto-Regular.ttf')", "url('/fonts/Roboto-Regular.ttf')")] - #[case( - "url(\"/fonts/Roboto-Regular.ttf\")", - "url(\"/fonts/Roboto-Regular.ttf\")" - )] + #[case("url(\"/fonts/Roboto-Regular.ttf\")", "url(\"/fonts/Roboto-Regular.ttf\")")] #[case("'A B', 'C D', E", "\"A B\",\"C D\",E")] #[case("A,B,C", "A,B,C")] #[case("A, B, C", "A,B,C")] @@ -79,22 +62,13 @@ mod tests { #[rstest] #[case("url('/fonts/Roboto-Regular.ttf')", "url('/fonts/Roboto-Regular.ttf')")] - #[case( - "url(\"/fonts/Roboto-Regular.ttf\")", - "url(\"/fonts/Roboto-Regular.ttf\")" - )] + #[case("url(\"/fonts/Roboto-Regular.ttf\")", "url(\"/fonts/Roboto-Regular.ttf\")")] #[case("//fonts/Roboto-Regular.ttf", "url(//fonts/Roboto-Regular.ttf)")] #[case("fonts/Roboto-Regular.ttf", "url(fonts/Roboto-Regular.ttf)")] - #[case( - "local('fonts/Roboto Regular.ttf')", - "local('fonts/Roboto Regular.ttf')" - )] + #[case("local('fonts/Roboto Regular.ttf')", "local('fonts/Roboto Regular.ttf')")] #[case("(hello)", "url(\"(hello)\")")] #[case("(hello world)", "url(\"(hello world)\")")] fn test_wrap_url(#[case] input: &str, #[case] expected: &str) { - assert_eq!( - super::wrap_url(&super::optimize_mutli_css_value(input)), - expected - ); + assert_eq!(super::wrap_url(&super::optimize_mutli_css_value(input)), expected); } } diff --git a/libs/css/src/optimize_value.rs b/libs/css/src/optimize_value.rs index 611045b2..d7cd98f6 100644 --- a/libs/css/src/optimize_value.rs +++ b/libs/css/src/optimize_value.rs @@ -1,9 +1,6 @@ use crate::{ COLOR_HASH, F_SPACE_RE, ZERO_RE, - constant::{ - DOT_ZERO_RE, F_DOT_RE, F_RGB_RE, F_RGBA_RE, INNER_TRIM_RE, NUM_TRIM_RE, RM_MINUS_ZERO_RE, - ZERO_PERCENT_FUNCTION, - }, + constant::{DOT_ZERO_RE, F_DOT_RE, F_RGB_RE, F_RGBA_RE, INNER_TRIM_RE, NUM_TRIM_RE, RM_MINUS_ZERO_RE, ZERO_PERCENT_FUNCTION}, }; pub fn optimize_value(value: &str) -> String { @@ -21,13 +18,7 @@ pub fn optimize_value(value: &str) -> String { let g = c[2].parse::().unwrap(); let b = c[3].parse::().unwrap(); let a = c[4].parse::().unwrap(); - format!( - "#{:02X}{:02X}{:02X}{:02X}", - r, - g, - b, - (a * 255.0).round() as i32 - ) + format!("#{:02X}{:02X}{:02X}{:02X}", r, g, b, (a * 255.0).round() as i32) }) .to_string(); ret = F_RGB_RE @@ -39,9 +30,7 @@ pub fn optimize_value(value: &str) -> String { }) .to_string(); if ret.contains("#") { - ret = COLOR_HASH - .replace_all(&ret, |c: ®ex::Captures| optimize_color(&c[1])) - .to_string(); + ret = COLOR_HASH.replace_all(&ret, |c: ®ex::Captures| optimize_color(&c[1])).to_string(); } if ret.contains("0") { ret = DOT_ZERO_RE.replace_all(&ret, "${1}0${2}").to_string(); @@ -59,12 +48,7 @@ pub fn optimize_value(value: &str) -> String { depth += 1; } else if tmp[i..i + 1].eq(")") { depth -= 1; - } else if tmp[i..i + 1].eq("0") - && !tmp[i - 1..i].chars().next().unwrap().is_ascii_digit() - && (tmp.len() == i + 1 - || !tmp[i + 1..i + 2].chars().next().unwrap().is_ascii_digit()) - && depth == 0 - { + } else if tmp[i..i + 1].eq("0") && !tmp[i - 1..i].chars().next().unwrap().is_ascii_digit() && (tmp.len() == i + 1 || !tmp[i + 1..i + 2].chars().next().unwrap().is_ascii_digit()) && depth == 0 { zero_idx.push(i); } } @@ -77,17 +61,9 @@ pub fn optimize_value(value: &str) -> String { // remove ; from dynamic value for str_symbol in ["", "`", "\"", "'"] { if ret.ends_with(&format!(";{str_symbol}")) { - ret = format!( - "{}{}", - ret[..ret.len() - str_symbol.len() - 1].trim_end_matches(';'), - str_symbol - ); + ret = format!("{}{}", ret[..ret.len() - str_symbol.len() - 1].trim_end_matches(';'), str_symbol); } else if ret.ends_with(&format!(";{str_symbol})")) { - ret = format!( - "{}{})", - ret[..ret.len() - str_symbol.len() - 2].trim_end_matches(';'), - str_symbol - ); + ret = format!("{}{})", ret[..ret.len() - str_symbol.len() - 2].trim_end_matches(';'), str_symbol); } } @@ -224,10 +200,7 @@ mod tests { #[case("max(10px, any(0", "max(10px,any(0))")] #[case("10px, any(0))", "(10px,any(0))")] #[case("scale(0deg, 0deg)", "scale(0,0)")] - #[case( - "scaleX(0deg) scaleY(0deg) scaleZ(0deg)", - "scaleX(0) scaleY(0) scaleZ(0)" - )] + #[case("scaleX(0deg) scaleY(0deg) scaleZ(0deg)", "scaleX(0) scaleY(0) scaleZ(0)")] #[case("scaleX(0deg)", "scaleX(0)")] #[case("scaleY(0deg)", "scaleY(0)")] #[case("scaleZ(0deg)", "scaleZ(0)")] diff --git a/libs/css/src/rm_css_comment.rs b/libs/css/src/rm_css_comment.rs index 7178a123..f90090e0 100644 --- a/libs/css/src/rm_css_comment.rs +++ b/libs/css/src/rm_css_comment.rs @@ -1,13 +1,7 @@ use crate::constant::CSS_COMMENT_RE; pub fn rm_css_comment(value: &str) -> String { - CSS_COMMENT_RE - .replace_all(value, "") - .trim() - .split_ascii_whitespace() - .collect::>() - .join(" ") - .replace(", ", ",") + CSS_COMMENT_RE.replace_all(value, "").trim().split_ascii_whitespace().collect::>().join(" ").replace(", ", ",") } #[cfg(test)] @@ -28,10 +22,7 @@ mod tests { */ div /* comment */ div /* comment */", "div div div" )] - #[case( - "div /* comment */ div /* comment */ div /* comment */ div", - "div div div div" - )] + #[case("div /* comment */ div /* comment */ div /* comment */ div", "div div div div")] fn test_rm_css_comment(#[case] input: &str, #[case] expected: &str) { assert_eq!(rm_css_comment(input), expected); } diff --git a/libs/css/src/selector_separator.rs b/libs/css/src/selector_separator.rs index ff0f2116..c27e8377 100644 --- a/libs/css/src/selector_separator.rs +++ b/libs/css/src/selector_separator.rs @@ -24,11 +24,7 @@ impl Display for SelectorSeparator { } impl From<&str> for SelectorSeparator { fn from(value: &str) -> Self { - if value.starts_with(":") - || value.is_empty() - || value.starts_with("[") - || value.starts_with(" ") - { + if value.starts_with(":") || value.is_empty() || value.starts_with("[") || value.starts_with(" ") { SelectorSeparator::None } else if DOUBLE_SEPARATOR.contains(value) { SelectorSeparator::Double @@ -56,10 +52,7 @@ mod tests { assert!(matches!("::placeholder".into(), SelectorSeparator::None)); - assert!(matches!( - "[aria-disabled='true']".into(), - SelectorSeparator::None - )); + assert!(matches!("[aria-disabled='true']".into(), SelectorSeparator::None)); } #[test] diff --git a/libs/css/src/style_selector.rs b/libs/css/src/style_selector.rs index e070a887..18592b65 100644 --- a/libs/css/src/style_selector.rs +++ b/libs/css/src/style_selector.rs @@ -5,43 +5,24 @@ use std::{ use serde::{Deserialize, Serialize}; -use crate::{ - constant::SELECTOR_ORDER_MAP, selector_separator::SelectorSeparator, to_kebab_case, - utils::to_camel_case, -}; +use crate::{constant::SELECTOR_ORDER_MAP, selector_separator::SelectorSeparator, to_kebab_case, utils::to_camel_case}; #[derive(Debug, PartialEq, Clone, Hash, Eq, Serialize, Deserialize)] pub enum StyleSelector { - Media { - query: String, - selector: Option, - }, + Media { query: String, selector: Option }, Selector(String), // selector, file Global(String, String), } fn optimize_selector_string(selector: &str) -> String { - selector - .split_whitespace() - .collect::>() - .join(" ") - .replace(", ", ",") + selector.split_whitespace().collect::>().join(" ").replace(", ", ",") } pub fn optimize_selector(selector: StyleSelector) -> StyleSelector { match selector { - StyleSelector::Media { query, selector } => StyleSelector::Media { - query: query.to_string(), - selector: selector - .as_ref() - .map(|s| optimize_selector_string(s.as_str())), - }, - StyleSelector::Selector(selector) => { - StyleSelector::Selector(optimize_selector_string(&selector)) - } - StyleSelector::Global(selector, file) => { - StyleSelector::Global(optimize_selector_string(&selector), file.to_string()) - } + StyleSelector::Media { query, selector } => StyleSelector::Media { query: query.to_string(), selector: selector.as_ref().map(|s| optimize_selector_string(s.as_str())) }, + StyleSelector::Selector(selector) => StyleSelector::Selector(optimize_selector_string(&selector)), + StyleSelector::Global(selector, file) => StyleSelector::Global(optimize_selector_string(&selector), file.to_string()), } } @@ -53,41 +34,16 @@ impl PartialOrd for StyleSelector { impl Ord for StyleSelector { fn cmp(&self, other: &Self) -> Ordering { match (self, other) { - ( - StyleSelector::Media { - query: a, - selector: aa, - }, - StyleSelector::Media { - query: b, - selector: bb, - }, - ) => { + (StyleSelector::Media { query: a, selector: aa }, StyleSelector::Media { query: b, selector: bb }) => { let c = a.cmp(b); if c == Ordering::Equal { aa.cmp(bb) } else { c } } (StyleSelector::Selector(a), StyleSelector::Selector(b)) => { let order_cmp = get_selector_order(a).cmp(&get_selector_order(b)); - if order_cmp == Ordering::Equal { - a.cmp(b) - } else { - order_cmp - } + if order_cmp == Ordering::Equal { a.cmp(b) } else { order_cmp } } - ( - StyleSelector::Media { - selector: _, - query: _, - }, - StyleSelector::Selector(_), - ) => Ordering::Greater, - ( - StyleSelector::Selector(_), - StyleSelector::Media { - selector: _, - query: _, - }, - ) => Ordering::Less, + (StyleSelector::Media { selector: _, query: _ }, StyleSelector::Selector(_)) => Ordering::Greater, + (StyleSelector::Selector(_), StyleSelector::Media { selector: _, query: _ }) => Ordering::Less, (StyleSelector::Global(a, _), StyleSelector::Global(b, _)) => { if a == b { return Ordering::Equal; @@ -106,11 +62,7 @@ impl Ord for StyleSelector { b_order_value = *order_value; } } - if a_order_value == b_order_value { - a.cmp(b) - } else { - a_order_value.cmp(&b_order_value) - } + if a_order_value == b_order_value { a.cmp(b) } else { a_order_value.cmp(&b_order_value) } } (true, false) => Ordering::Greater, (false, true) => Ordering::Less, @@ -125,69 +77,36 @@ impl Ord for StyleSelector { impl From<&str> for StyleSelector { fn from(value: &str) -> Self { - let value = value - .split_whitespace() - .collect::>() - .join(" ") - .replace(", ", ","); + let value = value.split_whitespace().collect::>().join(" ").replace(", ", ","); if value.contains("&") { StyleSelector::Selector(value.to_string()) } else if let Some(s) = value.strip_prefix("group-") { let post = to_kebab_case(s); - StyleSelector::Selector(format!( - "{}{}{} &", - "*[role=group]", - SelectorSeparator::from(post.as_str()), - post - )) + StyleSelector::Selector(format!("{}{}{} &", "*[role=group]", SelectorSeparator::from(post.as_str()), post)) } else if let Some(s) = value.strip_prefix("theme-") { // first character should lower case StyleSelector::Selector(format!(":root[data-theme={}] &", to_camel_case(s))) } else if value == "print" { - StyleSelector::Media { - query: "print".to_string(), - selector: None, - } + StyleSelector::Media { query: "print".to_string(), selector: None } } else { let post = to_kebab_case(&value); - StyleSelector::Selector(format!( - "&{}{}", - SelectorSeparator::from(post.as_str()), - post - )) + StyleSelector::Selector(format!("&{}{}", SelectorSeparator::from(post.as_str()), post)) } } } impl From<[&str; 2]> for StyleSelector { fn from(value: [&str; 2]) -> Self { - let post = if value[1].contains("&:") { - to_kebab_case(value[1].split(":").last().unwrap()) - } else { - to_kebab_case(value[1]) - }; - StyleSelector::Selector(format!( - "{}{}{}", - StyleSelector::from(value[0]), - SelectorSeparator::from(post.as_str()), - post - )) + let post = if value[1].contains("&:") { to_kebab_case(value[1].split(":").last().unwrap()) } else { to_kebab_case(value[1]) }; + StyleSelector::Selector(format!("{}{}{}", StyleSelector::from(value[0]), SelectorSeparator::from(post.as_str()), post)) } } impl From<(&StyleSelector, &str)> for StyleSelector { fn from(value: (&StyleSelector, &str)) -> Self { if let StyleSelector::Global(_, file) = value.0 { let post = to_kebab_case(value.1); - StyleSelector::Global( - format!( - "{}{}{}", - value.0, - SelectorSeparator::from(post.as_str()), - post - ), - file.clone(), - ) + StyleSelector::Global(format!("{}{}{}", value.0, SelectorSeparator::from(post.as_str()), post), file.clone()) } else { StyleSelector::from([&value.0.to_string(), value.1]) } @@ -202,11 +121,7 @@ impl Display for StyleSelector { match self { StyleSelector::Selector(value) => value.to_string(), StyleSelector::Media { query, selector } => { - if let Some(selector) = selector { - format!("@{query} {selector}") - } else { - format!("@{query}") - } + if let Some(selector) = selector { format!("@{query} {selector}") } else { format!("@{query}") } } StyleSelector::Global(value, _) => value.to_string(), } @@ -216,19 +131,9 @@ impl Display for StyleSelector { fn get_selector_order(selector: &str) -> u8 { // & count - let t = if selector.chars().filter(|c| c == &'&').count() == 1 { - selector - .split('&') - .next_back() - .map(|a| a.to_string()) - .unwrap_or(selector.to_string()) - } else { - selector.to_string() - }; + let t = if selector.chars().filter(|c| c == &'&').count() == 1 { selector.split('&').next_back().map(|a| a.to_string()).unwrap_or(selector.to_string()) } else { selector.to_string() }; - *SELECTOR_ORDER_MAP - .get(&t) - .unwrap_or(if t.starts_with("&") { &0 } else { &99 }) + *SELECTOR_ORDER_MAP.get(&t).unwrap_or(if t.starts_with("&") { &0 } else { &99 }) } #[cfg(test)] @@ -246,10 +151,7 @@ mod tests { #[case(["theme-dark", "placeholder"], StyleSelector::Selector(":root[data-theme=dark] &::placeholder".to_string()))] #[case("theme-light", StyleSelector::Selector(":root[data-theme=light] &".to_string()))] #[case("*[aria=disabled='true'] &:hover", StyleSelector::Selector("*[aria=disabled='true'] &:hover".to_string()))] - fn test_style_selector( - #[case] input: impl Into, - #[case] expected: StyleSelector, - ) { + fn test_style_selector(#[case] input: impl Into, #[case] expected: StyleSelector) { assert_eq!(input.into(), expected); } @@ -297,11 +199,7 @@ mod tests { StyleSelector::Global(":root[data-theme=light]".to_string(), "file2.rs".to_string()), std::cmp::Ordering::Less )] - #[case( - StyleSelector::from(":root[data-theme=dark] &:hover"), - StyleSelector::from(":root[data-theme=dark] &:focus-visible"), - std::cmp::Ordering::Less - )] + #[case(StyleSelector::from(":root[data-theme=dark] &:hover"), StyleSelector::from(":root[data-theme=dark] &:focus-visible"), std::cmp::Ordering::Less)] #[case( StyleSelector::Selector("&:hover".to_string()), StyleSelector::Media { @@ -310,11 +208,7 @@ mod tests { }, std::cmp::Ordering::Less )] - #[case( - StyleSelector::from("&:hover"), - StyleSelector::from("&:hover"), - std::cmp::Ordering::Equal - )] + #[case(StyleSelector::from("&:hover"), StyleSelector::from("&:hover"), std::cmp::Ordering::Equal)] #[case( StyleSelector::Global(":root[data-theme=dark]".to_string(), "file1.rs".to_string()), StyleSelector::Global(":root[data-theme=dark]".to_string(), "file2.rs".to_string()), @@ -356,11 +250,7 @@ mod tests { StyleSelector::Global("div:".to_string(), "file2.rs".to_string()), std::cmp::Ordering::Greater )] - fn test_style_selector_ord( - #[case] a: StyleSelector, - #[case] b: StyleSelector, - #[case] expected: std::cmp::Ordering, - ) { + fn test_style_selector_ord(#[case] a: StyleSelector, #[case] b: StyleSelector, #[case] expected: std::cmp::Ordering) { assert_eq!(a.cmp(&b), expected); assert_eq!(a.partial_cmp(&b), Some(expected)); } diff --git a/libs/css/src/utils.rs b/libs/css/src/utils.rs index 686ea48b..ad7b3094 100644 --- a/libs/css/src/utils.rs +++ b/libs/css/src/utils.rs @@ -1,33 +1,9 @@ pub fn to_kebab_case(value: &str) -> String { - value - .chars() - .enumerate() - .map(|(i, c)| { - if c.is_uppercase() { - if i == 0 { - c.to_ascii_lowercase().to_string() - } else { - format!("-{}", c.to_ascii_lowercase()) - } - } else { - c.to_string() - } - }) - .collect() + value.chars().enumerate().map(|(i, c)| if c.is_uppercase() { if i == 0 { c.to_ascii_lowercase().to_string() } else { format!("-{}", c.to_ascii_lowercase()) } } else { c.to_string() }).collect() } pub fn to_camel_case(value: &str) -> String { - value - .split('-') - .enumerate() - .map(|(i, s)| { - if i == 0 { - s.to_string() - } else { - format!("{}{}", s[0..1].to_uppercase(), &s[1..]) - } - }) - .collect() + value.split('-').enumerate().map(|(i, s)| if i == 0 { s.to_string() } else { format!("{}{}", s[0..1].to_uppercase(), &s[1..]) }).collect() } #[cfg(test)] diff --git a/libs/extractor/src/as_visit.rs b/libs/extractor/src/as_visit.rs index d9a4fe61..1ce98d3c 100644 --- a/libs/extractor/src/as_visit.rs +++ b/libs/extractor/src/as_visit.rs @@ -14,10 +14,7 @@ pub struct AsVisitor<'a> { impl<'a> AsVisitor<'a> { pub fn new(allocator: &'a Allocator, element: JSXElement<'a>) -> Self { - Self { - ast: AstBuilder::new(allocator), - element, - } + Self { ast: AstBuilder::new(allocator), element } } } diff --git a/libs/extractor/src/component.rs b/libs/extractor/src/component.rs index 201bc561..4c95b2cc 100644 --- a/libs/extractor/src/component.rs +++ b/libs/extractor/src/component.rs @@ -1,9 +1,7 @@ use strum::IntoEnumIterator; use strum_macros::{Display, EnumIter}; -use crate::extract_style::{ - extract_static_style::ExtractStaticStyle, extract_style_value::ExtractStyleValue, -}; +use crate::extract_style::{extract_static_style::ExtractStaticStyle, extract_style_value::ExtractStyleValue}; /// devup-ui export variable kind #[derive(Debug, PartialEq, Clone, EnumIter, Display)] @@ -23,11 +21,7 @@ impl ExportVariableKind { /// Convert the kind to a tag pub fn to_tag(&self) -> Result<&str, &str> { match self { - ExportVariableKind::Center - | ExportVariableKind::VStack - | ExportVariableKind::Grid - | ExportVariableKind::Flex - | ExportVariableKind::Box => Ok("div"), + ExportVariableKind::Center | ExportVariableKind::VStack | ExportVariableKind::Grid | ExportVariableKind::Flex | ExportVariableKind::Box => Ok("div"), ExportVariableKind::Text => Ok("span"), ExportVariableKind::Image => Ok("img"), ExportVariableKind::Button => Ok("button"), @@ -39,52 +33,18 @@ impl ExportVariableKind { impl ExportVariableKind { pub fn extract(&self) -> Vec { match self { - ExportVariableKind::Input - | ExportVariableKind::Button - | ExportVariableKind::Text - | ExportVariableKind::Image - | ExportVariableKind::Box => vec![], + ExportVariableKind::Input | ExportVariableKind::Button | ExportVariableKind::Text | ExportVariableKind::Image | ExportVariableKind::Box => vec![], ExportVariableKind::Flex => { - vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "display", "flex", 0, None, - ))] + vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic("display", "flex", 0, None))] } ExportVariableKind::VStack => { - vec![ - ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "display", "flex", 0, None, - )), - ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "flex-direction", - "column", - 0, - None, - )), - ] + vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic("display", "flex", 0, None)), ExtractStyleValue::Static(ExtractStaticStyle::new_basic("flex-direction", "column", 0, None))] } ExportVariableKind::Center => { - vec![ - ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "display", "flex", 0, None, - )), - ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "justify-content", - "center", - 0, - None, - )), - ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "align-items", - "center", - 0, - None, - )), - ] + vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic("display", "flex", 0, None)), ExtractStyleValue::Static(ExtractStaticStyle::new_basic("justify-content", "center", 0, None)), ExtractStyleValue::Static(ExtractStaticStyle::new_basic("align-items", "center", 0, None))] } ExportVariableKind::Grid => { - vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "display", "grid", 0, None, - ))] + vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic("display", "grid", 0, None))] } } } @@ -109,42 +69,15 @@ mod tests { #[test] fn test_kind_from_export_variable() { - assert_eq!( - ExportVariableKind::try_from("Box".to_string()), - Ok(ExportVariableKind::Box) - ); - assert_eq!( - ExportVariableKind::try_from("Text".to_string()), - Ok(ExportVariableKind::Text) - ); - assert_eq!( - ExportVariableKind::try_from("Image".to_string()), - Ok(ExportVariableKind::Image) - ); - assert_eq!( - ExportVariableKind::try_from("Button".to_string()), - Ok(ExportVariableKind::Button) - ); - assert_eq!( - ExportVariableKind::try_from("Input".to_string()), - Ok(ExportVariableKind::Input) - ); - assert_eq!( - ExportVariableKind::try_from("Flex".to_string()), - Ok(ExportVariableKind::Flex) - ); - assert_eq!( - ExportVariableKind::try_from("VStack".to_string()), - Ok(ExportVariableKind::VStack) - ); - assert_eq!( - ExportVariableKind::try_from("Center".to_string()), - Ok(ExportVariableKind::Center) - ); - assert_eq!( - ExportVariableKind::try_from("Grid".to_string()), - Ok(ExportVariableKind::Grid) - ); + assert_eq!(ExportVariableKind::try_from("Box".to_string()), Ok(ExportVariableKind::Box)); + assert_eq!(ExportVariableKind::try_from("Text".to_string()), Ok(ExportVariableKind::Text)); + assert_eq!(ExportVariableKind::try_from("Image".to_string()), Ok(ExportVariableKind::Image)); + assert_eq!(ExportVariableKind::try_from("Button".to_string()), Ok(ExportVariableKind::Button)); + assert_eq!(ExportVariableKind::try_from("Input".to_string()), Ok(ExportVariableKind::Input)); + assert_eq!(ExportVariableKind::try_from("Flex".to_string()), Ok(ExportVariableKind::Flex)); + assert_eq!(ExportVariableKind::try_from("VStack".to_string()), Ok(ExportVariableKind::VStack)); + assert_eq!(ExportVariableKind::try_from("Center".to_string()), Ok(ExportVariableKind::Center)); + assert_eq!(ExportVariableKind::try_from("Grid".to_string()), Ok(ExportVariableKind::Grid)); assert!(ExportVariableKind::try_from("css".to_string()).is_err()); assert!(ExportVariableKind::try_from("foo".to_string()).is_err()); } @@ -169,51 +102,9 @@ mod tests { assert_eq!(ExportVariableKind::Image.extract(), vec![]); assert_eq!(ExportVariableKind::Button.extract(), vec![]); assert_eq!(ExportVariableKind::Input.extract(), vec![]); - assert_eq!( - ExportVariableKind::Flex.extract(), - vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "display", "flex", 0, None, - ))] - ); - assert_eq!( - ExportVariableKind::VStack.extract(), - vec![ - ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "display", "flex", 0, None, - )), - ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "flex-direction", - "column", - 0, - None, - )) - ] - ); - assert_eq!( - ExportVariableKind::Center.extract(), - vec![ - ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "display", "flex", 0, None, - )), - ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "justify-content", - "center", - 0, - None, - )), - ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "align-items", - "center", - 0, - None, - )) - ] - ); - assert_eq!( - ExportVariableKind::Grid.extract(), - vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic( - "display", "grid", 0, None, - ))] - ); + assert_eq!(ExportVariableKind::Flex.extract(), vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic("display", "flex", 0, None,))]); + assert_eq!(ExportVariableKind::VStack.extract(), vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic("display", "flex", 0, None,)), ExtractStyleValue::Static(ExtractStaticStyle::new_basic("flex-direction", "column", 0, None,))]); + assert_eq!(ExportVariableKind::Center.extract(), vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic("display", "flex", 0, None,)), ExtractStyleValue::Static(ExtractStaticStyle::new_basic("justify-content", "center", 0, None,)), ExtractStyleValue::Static(ExtractStaticStyle::new_basic("align-items", "center", 0, None,))]); + assert_eq!(ExportVariableKind::Grid.extract(), vec![ExtractStyleValue::Static(ExtractStaticStyle::new_basic("display", "grid", 0, None,))]); } } diff --git a/libs/extractor/src/css_utils.rs b/libs/extractor/src/css_utils.rs index 1ffe19ae..5bc881cd 100644 --- a/libs/extractor/src/css_utils.rs +++ b/libs/extractor/src/css_utils.rs @@ -8,11 +8,7 @@ use css::{ use crate::extract_style::extract_static_style::ExtractStaticStyle; -pub fn css_to_style( - css: &str, - level: u8, - selector: &Option, -) -> Vec { +pub fn css_to_style(css: &str, level: u8, selector: &Option) -> Vec { let mut styles = vec![]; let mut input = css; @@ -39,39 +35,16 @@ pub fn css_to_style( while let Some(start) = input.find('{') { let rest = &input[start + 1..]; - let end = if selector.is_none() { - rest.rfind('}').unwrap() - } else { - rest.find('}').unwrap() - }; + let end = if selector.is_none() { rest.rfind('}').unwrap() } else { rest.find('}').unwrap() }; let block = &rest[..end]; let sel = &if let Some(StyleSelector::Media { query, .. }) = selector { let local_sel = input[..start].trim().to_string(); - Some(StyleSelector::Media { - query: query.clone(), - selector: if local_sel == "&" { - None - } else { - Some(local_sel) - }, - }) + Some(StyleSelector::Media { query: query.clone(), selector: if local_sel == "&" { None } else { Some(local_sel) } }) } else { let sel = input[..start].trim().to_string(); - if sel.starts_with("@media") { - Some(StyleSelector::Media { - query: sel.replace(" ", "").replace("and(", "and (")["@media".len()..] - .to_string(), - selector: None, - }) - } else { - Some(StyleSelector::Selector(sel)) - } - }; - let block = if block.contains('{') { - css_to_style(block, level, sel) - } else { - css_to_style_block(block, level, sel) + if sel.starts_with("@media") { Some(StyleSelector::Media { query: sel.replace(" ", "").replace("and(", "and (")["@media".len()..].to_string(), selector: None }) } else { Some(StyleSelector::Selector(sel)) } }; + let block = if block.contains('{') { css_to_style(block, level, sel) } else { css_to_style_block(block, level, sel) }; let input_end = input.rfind('}').unwrap() + 1; input = &input[start + end + 2..input_end]; @@ -85,11 +58,7 @@ pub fn css_to_style( styles } -fn css_to_style_block( - css: &str, - level: u8, - selector: &Option, -) -> Vec { +fn css_to_style_block(css: &str, level: u8, selector: &Option) -> Vec { rm_css_comment(css) .split(";") .filter_map(|s| { @@ -100,17 +69,8 @@ fn css_to_style_block( let mut iter = s.split(":").map(|s| s.trim()); let property = iter.next().unwrap(); let value = iter.next().unwrap(); - let value = if check_multi_css_optimize(property) { - optimize_mutli_css_value(value) - } else { - value.to_string() - }; - Some(ExtractStaticStyle::new( - property, - &value, - level, - selector.clone(), - )) + let value = if check_multi_css_optimize(property) { optimize_mutli_css_value(value) } else { value.to_string() }; + Some(ExtractStaticStyle::new(property, &value, level, selector.clone())) } }) .collect() @@ -150,11 +110,7 @@ pub fn optimize_css_block(css: &str) -> String { .split(";") .map(|s| { let parts = s.split("{").collect::>(); - let first_part = if parts.len() == 1 { - "".to_string() - } else { - format!("{}{{", parts.first().unwrap().trim()) - }; + let first_part = if parts.len() == 1 { "".to_string() } else { format!("{}{{", parts.first().unwrap().trim()) }; let last_part = parts.last().unwrap().trim(); if !last_part.contains(":") { format!("{first_part}{last_part}") @@ -163,11 +119,7 @@ pub fn optimize_css_block(css: &str) -> String { let property = iter.next().unwrap().trim(); let value = iter.next().unwrap().trim(); - let value = if check_multi_css_optimize(property.split("{").last().unwrap()) { - optimize_mutli_css_value(value) - } else { - value.to_string() - }; + let value = if check_multi_css_optimize(property.split("{").last().unwrap()) { optimize_mutli_css_value(value) } else { value.to_string() }; format!("{first_part}{property}:{value}") } }) @@ -199,45 +151,21 @@ mod tests { }*/", "" )] - #[case( - " img { background-color : red; } ", - "img{background-color:red}" - )] - #[case( - " img { background-color : red; color : blue; } ", - "img{background-color:red;color:blue}" - )] + #[case(" img { background-color : red; } ", "img{background-color:red}")] + #[case(" img { background-color : red; color : blue; } ", "img{background-color:red;color:blue}")] #[case("div{margin : 0 ; padding : 0 ; }", "div{margin:0;padding:0}")] - #[case( - "a { text-decoration : none ; color : black ; }", - "a{text-decoration:none;color:black}" - )] + #[case("a { text-decoration : none ; color : black ; }", "a{text-decoration:none;color:black}")] #[case("body{background: #fff;}", "body{background:#fff}")] - #[case( - "h1{ font-size : 2rem ; font-weight : bold ; }", - "h1{font-size:2rem;font-weight:bold}" - )] + #[case("h1{ font-size : 2rem ; font-weight : bold ; }", "h1{font-size:2rem;font-weight:bold}")] #[case("span { }", "span{}")] #[case("p{color:blue;}", "p{color:blue}")] - #[case( - "ul { list-style : none ; margin : 0 ; padding : 0 ; }", - "ul{list-style:none;margin:0;padding:0}" - )] - #[case( - "ul { font-family: 'Roboto', sans-serif; }", - "ul{font-family:Roboto,sans-serif}" - )] - #[case( - "ul { font-family: \"Roboto Hello\", sans-serif; }", - "ul{font-family:\"Roboto Hello\",sans-serif}" - )] + #[case("ul { list-style : none ; margin : 0 ; padding : 0 ; }", "ul{list-style:none;margin:0;padding:0}")] + #[case("ul { font-family: 'Roboto', sans-serif; }", "ul{font-family:Roboto,sans-serif}")] + #[case("ul { font-family: \"Roboto Hello\", sans-serif; }", "ul{font-family:\"Roboto Hello\",sans-serif}")] #[case("section{ }", "section{}")] #[case(":root{ }", ":root{}")] #[case(":root{ background: red; }", ":root{background:red}")] - #[case( - ":root, :section{ background: red; }", - ":root,:section{background:red}" - )] + #[case(":root, :section{ background: red; }", ":root,:section{background:red}")] #[case("*:hover{ background: red; }", "*:hover{background:red}")] #[case(":root {color-scheme: light dark }", ":root{color-scheme:light dark}")] fn test_optimize_css_block(#[case] input: &str, #[case] expected: &str) { @@ -482,15 +410,9 @@ mod tests { ("font-family", "\"Roboto Hello\",sans-serif", Some(StyleSelector::Selector("ul".to_string()))), ] )] - fn test_css_to_style( - #[case] input: &str, - #[case] expected: Vec<(&str, &str, Option)>, - ) { + fn test_css_to_style(#[case] input: &str, #[case] expected: Vec<(&str, &str, Option)>) { let styles = css_to_style(input, 0, &None); - let mut result: Vec<(&str, &str, Option)> = styles - .iter() - .map(|prop| (prop.property(), prop.value(), prop.selector().cloned())) - .collect(); + let mut result: Vec<(&str, &str, Option)> = styles.iter().map(|prop| (prop.property(), prop.value(), prop.selector().cloned())).collect(); result.sort(); let mut expected_sorted = expected.clone(); expected_sorted.sort(); @@ -548,26 +470,16 @@ mod tests { vec![ ], )] - fn test_keyframes_to_keyframes_style( - #[case] input: &str, - #[case] expected: Vec<(&str, Vec<(&str, &str)>)>, - ) { + fn test_keyframes_to_keyframes_style(#[case] input: &str, #[case] expected: Vec<(&str, Vec<(&str, &str)>)>) { let styles = keyframes_to_keyframes_style(input); if styles.len() != expected.len() { panic!("styles.len() != expected.len()"); } for (expected_key, expected_styles) in styles.iter() { let styles = expected_styles; - let mut result: Vec<(&str, &str)> = styles - .iter() - .map(|prop| (prop.property(), prop.value())) - .collect(); + let mut result: Vec<(&str, &str)> = styles.iter().map(|prop| (prop.property(), prop.value())).collect(); result.sort(); - let mut expected_sorted = expected - .iter() - .find(|(k, _)| k == expected_key) - .map(|(_, v)| v.clone()) - .unwrap(); + let mut expected_sorted = expected.iter().find(|(k, _)| k == expected_key).map(|(_, v)| v.clone()).unwrap(); expected_sorted.sort(); assert_eq!(result, expected_sorted); } diff --git a/libs/extractor/src/extract_style/extract_dynamic_style.rs b/libs/extractor/src/extract_style/extract_dynamic_style.rs index bb896e4f..1374ee5d 100644 --- a/libs/extractor/src/extract_style/extract_dynamic_style.rs +++ b/libs/extractor/src/extract_style/extract_dynamic_style.rs @@ -22,19 +22,8 @@ pub struct ExtractDynamicStyle { impl ExtractDynamicStyle { /// create a new ExtractDynamicStyle - pub fn new( - property: &str, - level: u8, - identifier: &str, - selector: Option, - ) -> Self { - Self { - property: property.to_string(), - level, - identifier: optimize_value(identifier), - selector: selector.map(optimize_selector), - style_order: None, - } + pub fn new(property: &str, level: u8, identifier: &str, selector: Option) -> Self { + Self { property: property.to_string(), level, identifier: optimize_value(identifier), selector: selector.map(optimize_selector), style_order: None } } pub fn property(&self) -> &str { @@ -61,22 +50,7 @@ impl ExtractDynamicStyle { impl ExtractStyleProperty for ExtractDynamicStyle { fn extract(&self, filename: Option<&str>) -> StyleProperty { let selector = self.selector.clone().map(|s| s.to_string()); - StyleProperty::Variable { - class_name: sheet_to_classname( - self.property.as_str(), - self.level, - None, - selector.as_deref(), - self.style_order, - filename, - ), - variable_name: sheet_to_variable_name( - self.property.as_str(), - self.level, - selector.as_deref(), - ), - identifier: self.identifier.clone(), - } + StyleProperty::Variable { class_name: sheet_to_classname(self.property.as_str(), self.level, None, selector.as_deref(), self.style_order, filename), variable_name: sheet_to_variable_name(self.property.as_str(), self.level, selector.as_deref()), identifier: self.identifier.clone() } } } diff --git a/libs/extractor/src/extract_style/extract_keyframes.rs b/libs/extractor/src/extract_style/extract_keyframes.rs index d3479f84..d2f2f45d 100644 --- a/libs/extractor/src/extract_style/extract_keyframes.rs +++ b/libs/extractor/src/extract_style/extract_keyframes.rs @@ -5,9 +5,7 @@ use std::{ use css::keyframes_to_keyframes_name; -use crate::extract_style::{ - ExtractStyleProperty, extract_static_style::ExtractStaticStyle, style_property::StyleProperty, -}; +use crate::extract_style::{ExtractStyleProperty, extract_static_style::ExtractStaticStyle, style_property::StyleProperty}; #[derive(Debug, Default, PartialEq, Clone, Eq, Hash, Ord, PartialOrd)] pub struct ExtractKeyframes { diff --git a/libs/extractor/src/extract_style/extract_static_style.rs b/libs/extractor/src/extract_style/extract_static_style.rs index 73d2f119..d9512c43 100644 --- a/libs/extractor/src/extract_style/extract_static_style.rs +++ b/libs/extractor/src/extract_style/extract_static_style.rs @@ -6,9 +6,7 @@ use css::{ }; use crate::{ - extract_style::{ - ExtractStyleProperty, constant::MAINTAIN_VALUE_PROPERTIES, style_property::StyleProperty, - }, + extract_style::{ExtractStyleProperty, constant::MAINTAIN_VALUE_PROPERTIES, style_property::StyleProperty}, utils::{convert_value, gcd}, }; @@ -32,11 +30,7 @@ impl ExtractStaticStyle { Self { value: optimize_value(&if MAINTAIN_VALUE_PROPERTIES.contains(property) { if property == "aspect-ratio" && value.contains("/") { - if let [Ok(a), Ok(b)] = value - .split('/') - .map(|v| v.trim().parse::()) - .collect::>()[..] - { + if let [Ok(a), Ok(b)] = value.split('/').map(|v| v.trim().parse::()).collect::>()[..] { let gcd = gcd(a, b); format!("{}/{}", a / gcd, b / gcd) } else { @@ -55,23 +49,8 @@ impl ExtractStaticStyle { } } - pub fn new_basic( - property: &str, - value: &str, - level: u8, - selector: Option, - ) -> Self { - Self { - value: optimize_value(&if MAINTAIN_VALUE_PROPERTIES.contains(property) { - value.to_string() - } else { - convert_value(value) - }), - property: property.to_string(), - level, - selector, - style_order: Some(0), - } + pub fn new_basic(property: &str, value: &str, level: u8, selector: Option) -> Self { + Self { value: optimize_value(&if MAINTAIN_VALUE_PROPERTIES.contains(property) { value.to_string() } else { convert_value(value) }), property: property.to_string(), level, selector, style_order: Some(0) } } pub fn property(&self) -> &str { @@ -98,24 +77,9 @@ impl ExtractStaticStyle { impl ExtractStyleProperty for ExtractStaticStyle { fn extract(&self, filename: Option<&str>) -> StyleProperty { let s = self.selector.clone().map(|s| s.to_string()); - let v = optimize_value(&if MAINTAIN_VALUE_PROPERTIES.contains(&self.property) { - self.value.to_string() - } else { - convert_value(&self.value) - }); - let v = if check_multi_css_optimize(&self.property) { - optimize_mutli_css_value(&v) - } else { - v - }; - StyleProperty::ClassName(sheet_to_classname( - &self.property, - self.level, - Some(&v), - s.as_deref(), - self.style_order, - filename, - )) + let v = optimize_value(&if MAINTAIN_VALUE_PROPERTIES.contains(&self.property) { self.value.to_string() } else { convert_value(&self.value) }); + let v = if check_multi_css_optimize(&self.property) { optimize_mutli_css_value(&v) } else { v }; + StyleProperty::ClassName(sheet_to_classname(&self.property, self.level, Some(&v), s.as_deref(), self.style_order, filename)) } } diff --git a/libs/extractor/src/extract_style/extract_style_value.rs b/libs/extractor/src/extract_style/extract_style_value.rs index 8e8fbad5..e7d950b9 100644 --- a/libs/extractor/src/extract_style/extract_style_value.rs +++ b/libs/extractor/src/extract_style/extract_style_value.rs @@ -1,9 +1,4 @@ -use crate::extract_style::{ - ExtractStyleProperty, extract_css::ExtractCss, extract_dynamic_style::ExtractDynamicStyle, - extract_font_face::ExtractFontFace, extract_import::ExtractImport, - extract_keyframes::ExtractKeyframes, extract_static_style::ExtractStaticStyle, - style_property::StyleProperty, -}; +use crate::extract_style::{ExtractStyleProperty, extract_css::ExtractCss, extract_dynamic_style::ExtractDynamicStyle, extract_font_face::ExtractFontFace, extract_import::ExtractImport, extract_keyframes::ExtractKeyframes, extract_static_style::ExtractStaticStyle, style_property::StyleProperty}; #[derive(Debug, PartialEq, Clone, Eq, Hash, Ord, PartialOrd)] pub enum ExtractStyleValue { @@ -22,12 +17,8 @@ impl ExtractStyleValue { ExtractStyleValue::Static(style) => Some(style.extract(filename)), ExtractStyleValue::Dynamic(style) => Some(style.extract(filename)), ExtractStyleValue::Keyframes(keyframes) => Some(keyframes.extract(filename)), - ExtractStyleValue::Typography(typo) => { - Some(StyleProperty::ClassName(format!("typo-{typo}"))) - } - ExtractStyleValue::Css(_) - | ExtractStyleValue::Import(_) - | ExtractStyleValue::FontFace(_) => None, + ExtractStyleValue::Typography(typo) => Some(StyleProperty::ClassName(format!("typo-{typo}"))), + ExtractStyleValue::Css(_) | ExtractStyleValue::Import(_) | ExtractStyleValue::FontFace(_) => None, } } pub fn set_style_order(&mut self, order: u8) { @@ -51,14 +42,12 @@ mod tests { #[test] fn test_style_order() { - let mut style = - ExtractStyleValue::Static(ExtractStaticStyle::new("margin", "10px", 0, None)); + let mut style = ExtractStyleValue::Static(ExtractStaticStyle::new("margin", "10px", 0, None)); style.set_style_order(1); if let ExtractStyleValue::Static(style) = style { assert_eq!(style.style_order(), Some(1)); } - let mut style = - ExtractStyleValue::Dynamic(ExtractDynamicStyle::new("margin", 0, "10px", None)); + let mut style = ExtractStyleValue::Dynamic(ExtractDynamicStyle::new("margin", 0, "10px", None)); style.set_style_order(1); if let ExtractStyleValue::Dynamic(style) = style { assert_eq!(style.style_order(), Some(1)); @@ -85,16 +74,10 @@ mod tests { let extracted = value.extract(None); assert!(matches!(extracted, Some(StyleProperty::ClassName(_)))); - let value = ExtractStyleValue::Css(ExtractCss { - css: "".to_string(), - file: "".to_string(), - }); + let value = ExtractStyleValue::Css(ExtractCss { css: "".to_string(), file: "".to_string() }); assert!(value.extract(None).is_none()); - let value = ExtractStyleValue::Import(ExtractImport { - url: "".to_string(), - file: "".to_string(), - }); + let value = ExtractStyleValue::Import(ExtractImport { url: "".to_string(), file: "".to_string() }); assert!(value.extract(None).is_none()); } } diff --git a/libs/extractor/src/extract_style/style_property.rs b/libs/extractor/src/extract_style/style_property.rs index 6d508906..93387f98 100644 --- a/libs/extractor/src/extract_style/style_property.rs +++ b/libs/extractor/src/extract_style/style_property.rs @@ -2,11 +2,7 @@ use std::fmt::{Display, Error, Formatter}; pub enum StyleProperty { ClassName(String), - Variable { - class_name: String, - variable_name: String, - identifier: String, - }, + Variable { class_name: String, variable_name: String, identifier: String }, } impl Display for StyleProperty { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { @@ -28,11 +24,7 @@ mod tests { #[test] fn test_to_string_variable() { - let prop = StyleProperty::Variable { - class_name: "cls".to_string(), - variable_name: "--var-name".to_string(), - identifier: "id".to_string(), - }; + let prop = StyleProperty::Variable { class_name: "cls".to_string(), variable_name: "--var-name".to_string(), identifier: "id".to_string() }; assert_eq!(prop.to_string(), "var(--var-name)".to_string()); } } diff --git a/libs/extractor/src/extractor/extract_global_style_from_expression.rs b/libs/extractor/src/extractor/extract_global_style_from_expression.rs index 70d8498e..2268de71 100644 --- a/libs/extractor/src/extractor/extract_global_style_from_expression.rs +++ b/libs/extractor/src/extractor/extract_global_style_from_expression.rs @@ -3,13 +3,8 @@ use std::collections::BTreeMap; use crate::{ ExtractStyleProp, css_utils::css_to_style, - extract_style::{ - extract_font_face::ExtractFontFace, extract_import::ExtractImport, - extract_style_value::ExtractStyleValue, - }, - extractor::{ - GlobalExtractResult, extract_style_from_expression::extract_style_from_expression, - }, + extract_style::{extract_font_face::ExtractFontFace, extract_import::ExtractImport, extract_style_value::ExtractStyleValue}, + extractor::{GlobalExtractResult, extract_style_from_expression::extract_style_from_expression}, utils::{get_string_by_literal_expression, get_string_by_property_key}, }; use css::{ @@ -22,11 +17,7 @@ use oxc_ast::{ ast::{ArrayExpressionElement, Expression, ObjectPropertyKind}, }; -pub fn extract_global_style_from_expression<'a>( - ast_builder: &AstBuilder<'a>, - expression: &mut Expression<'a>, - file: &str, -) -> GlobalExtractResult<'a> { +pub fn extract_global_style_from_expression<'a>(ast_builder: &AstBuilder<'a>, expression: &mut Expression<'a>, file: &str) -> GlobalExtractResult<'a> { let mut styles = vec![]; if let Expression::ObjectExpression(obj) = expression { @@ -43,45 +34,22 @@ pub fn extract_global_style_from_expression<'a>( for p in obj.properties.iter() { if let ObjectPropertyKind::ObjectProperty(o) = p && let Some(ident) = o.key.as_expression() - && let Some(ident) = - get_string_by_literal_expression(ident) + && let Some(ident) = get_string_by_literal_expression(ident) { if ident == "url" { - url = - get_string_by_literal_expression(&o.value); + url = get_string_by_literal_expression(&o.value); } else if ident == "query" { - query = - get_string_by_literal_expression(&o.value); + query = get_string_by_literal_expression(&o.value); } } } if let Some(url) = url { - styles.push(ExtractStyleProp::Static( - ExtractStyleValue::Import(ExtractImport { - url: format!( - "\"{url}\"{}", - if let Some(query) = query { - format!(" {query}") - } else { - "".to_string() - } - ), - file: file.to_string(), - }), - )); + styles.push(ExtractStyleProp::Static(ExtractStyleValue::Import(ExtractImport { url: format!("\"{url}\"{}", if let Some(query) = query { format!(" {query}") } else { "".to_string() }), file: file.to_string() }))); } - } else if !matches!( - p.to_expression(), - Expression::NumericLiteral(_) - ) && let Some(url) = - get_string_by_literal_expression(p.to_expression()) + } else if !matches!(p.to_expression(), Expression::NumericLiteral(_)) + && let Some(url) = get_string_by_literal_expression(p.to_expression()) { - styles.push(ExtractStyleProp::Static( - ExtractStyleValue::Import(ExtractImport { - url, - file: file.to_string(), - }), - )); + styles.push(ExtractStyleProp::Static(ExtractStyleValue::Import(ExtractImport { url, file: file.to_string() }))); } } } @@ -116,74 +84,21 @@ pub fn extract_global_style_from_expression<'a>( file: file.to_string(), }))); } else if let ArrayExpressionElement::TemplateLiteral(t) = p { - let css_styles = css_to_style( - t.quasis - .iter() - .map(|q| q.value.raw.as_str()) - .collect::() - .trim(), - 0, - &None, - ) - .into_iter() - .map(ExtractStyleValue::Static) - .collect::>(); - styles.push(ExtractStyleProp::Static( - ExtractStyleValue::FontFace(ExtractFontFace { - properties: BTreeMap::from_iter( - css_styles.iter().filter_map(|p| { - if let ExtractStyleValue::Static(st) = p { - Some(( - st.property().to_string(), - st.value().to_string(), - )) - } else { - None - } - }), - ), - file: file.to_string(), - }), - )); + let css_styles = css_to_style(t.quasis.iter().map(|q| q.value.raw.as_str()).collect::().trim(), 0, &None).into_iter().map(ExtractStyleValue::Static).collect::>(); + styles.push(ExtractStyleProp::Static(ExtractStyleValue::FontFace(ExtractFontFace { properties: BTreeMap::from_iter(css_styles.iter().filter_map(|p| if let ExtractStyleValue::Static(st) = p { Some((st.property().to_string(), st.value().to_string())) } else { None })), file: file.to_string() }))); } } } } else { - styles.extend( - extract_style_from_expression( - ast_builder, - None, - &mut o.value, - 0, - &Some(StyleSelector::Global( - if let Some(name) = name.strip_prefix("_") { - StyleSelector::from(name).to_string().replace("&", "*") - } else { - name.to_string() - }, - file.to_string(), - )), - ) - .styles, - ); + styles.extend(extract_style_from_expression(ast_builder, None, &mut o.value, 0, &Some(StyleSelector::Global(if let Some(name) = name.strip_prefix("_") { StyleSelector::from(name).to_string().replace("&", "*") } else { name.to_string() }, file.to_string()))).styles); } } } ObjectPropertyKind::SpreadProperty(o) => { - styles.extend( - extract_global_style_from_expression( - ast_builder, - o.argument.get_inner_expression_mut(), - file, - ) - .styles, - ); + styles.extend(extract_global_style_from_expression(ast_builder, o.argument.get_inner_expression_mut(), file).styles); } } } } - GlobalExtractResult { - styles, - style_order: None, - } + GlobalExtractResult { styles, style_order: None } } diff --git a/libs/extractor/src/extractor/extract_keyframes_from_expression.rs b/libs/extractor/src/extractor/extract_keyframes_from_expression.rs index 4d8f72d4..eb97f98b 100644 --- a/libs/extractor/src/extractor/extract_keyframes_from_expression.rs +++ b/libs/extractor/src/extractor/extract_keyframes_from_expression.rs @@ -1,10 +1,7 @@ use crate::{ ExtractStyleProp, extract_style::{extract_keyframes::ExtractKeyframes, extract_style_value::ExtractStyleValue}, - extractor::{ - ExtractResult, KeyframesExtractResult, - extract_style_from_expression::extract_style_from_expression, - }, + extractor::{ExtractResult, KeyframesExtractResult, extract_style_from_expression::extract_style_from_expression}, utils::get_string_by_property_key, }; use oxc_ast::{ @@ -12,10 +9,7 @@ use oxc_ast::{ ast::{Expression, ObjectPropertyKind}, }; -pub fn extract_keyframes_from_expression<'a>( - ast_builder: &AstBuilder<'a>, - expression: &mut Expression<'a>, -) -> KeyframesExtractResult { +pub fn extract_keyframes_from_expression<'a>(ast_builder: &AstBuilder<'a>, expression: &mut Expression<'a>) -> KeyframesExtractResult { let mut keyframes = ExtractKeyframes::default(); if let Expression::ObjectExpression(obj) = expression { @@ -23,8 +17,7 @@ pub fn extract_keyframes_from_expression<'a>( if let ObjectPropertyKind::ObjectProperty(o) = p && let Some(name) = get_string_by_property_key(&o.key) { - let ExtractResult { styles, .. } = - extract_style_from_expression(ast_builder, None, &mut o.value, 0, &None); + let ExtractResult { styles, .. } = extract_style_from_expression(ast_builder, None, &mut o.value, 0, &None); let mut styles = styles .into_iter() @@ -34,10 +27,7 @@ pub fn extract_keyframes_from_expression<'a>( }) .collect::>(); styles.sort_by_key(|a| a.property().to_string()); - keyframes.keyframes.insert( - name.parse::().map(|v| format!("{v}%")).unwrap_or(name), - styles, - ); + keyframes.keyframes.insert(name.parse::().map(|v| format!("{v}%")).unwrap_or(name), styles); } } } diff --git a/libs/extractor/src/extractor/extract_style_from_expression.rs b/libs/extractor/src/extractor/extract_style_from_expression.rs index c78973d8..379dc5cb 100644 --- a/libs/extractor/src/extractor/extract_style_from_expression.rs +++ b/libs/extractor/src/extractor/extract_style_from_expression.rs @@ -1,41 +1,21 @@ use crate::{ ExtractStyleProp, css_utils::css_to_style, - extract_style::{ - extract_dynamic_style::ExtractDynamicStyle, extract_static_style::ExtractStaticStyle, - extract_style_value::ExtractStyleValue, - }, - extractor::{ - ExtractResult, extract_style_from_member_expression::extract_style_from_member_expression, - }, - utils::{ - expression_to_code, get_number_by_literal_expression, get_string_by_literal_expression, - get_string_by_property_key, is_same_expression, - }, -}; -use css::{ - add_selector_params, disassemble_property, get_enum_property_map, get_enum_property_value, - is_special_property::is_special_property, style_selector::StyleSelector, utils::to_kebab_case, + extract_style::{extract_dynamic_style::ExtractDynamicStyle, extract_static_style::ExtractStaticStyle, extract_style_value::ExtractStyleValue}, + extractor::{ExtractResult, extract_style_from_member_expression::extract_style_from_member_expression}, + utils::{expression_to_code, get_number_by_literal_expression, get_string_by_literal_expression, get_string_by_property_key, is_same_expression}, }; +use css::{add_selector_params, disassemble_property, get_enum_property_map, get_enum_property_value, is_special_property::is_special_property, style_selector::StyleSelector, utils::to_kebab_case}; use oxc_allocator::CloneIn; use oxc_ast::{ AstBuilder, - ast::{ - BinaryOperator, Expression, LogicalOperator, ObjectPropertyKind, TemplateElementValue, - UnaryOperator, - }, + ast::{BinaryOperator, Expression, LogicalOperator, ObjectPropertyKind, TemplateElementValue, UnaryOperator}, }; use oxc_span::SPAN; const IGNORED_IDENTIFIERS: [&str; 3] = ["undefined", "NaN", "Infinity"]; -pub fn extract_style_from_expression<'a>( - ast_builder: &AstBuilder<'a>, - name: Option<&str>, - expression: &mut Expression<'a>, - level: u8, - selector: &Option, -) -> ExtractResult<'a> { +pub fn extract_style_from_expression<'a>(ast_builder: &AstBuilder<'a>, name: Option<&str>, expression: &mut Expression<'a>, level: u8, selector: &Option) -> ExtractResult<'a> { let mut typo = false; if name.is_none() && selector.is_none() { @@ -56,23 +36,13 @@ pub fn extract_style_from_expression<'a>( let property_name = name.to_string(); for name in disassemble_property(&property_name) { if &property_name == "styleOrder" { - style_order = get_number_by_literal_expression(&prop.value) - .map(|v| v as u8); + style_order = get_number_by_literal_expression(&prop.value).map(|v| v as u8); } else if &property_name == "styleVars" { - style_vars = - Some(prop.value.clone_in(ast_builder.allocator)); + style_vars = Some(prop.value.clone_in(ast_builder.allocator)); } else if &property_name == "props" { props = Some(prop.value.clone_in(ast_builder.allocator)); } else { - let ExtractResult { - styles, tag: _tag, .. - } = extract_style_from_expression( - ast_builder, - Some(&name), - &mut prop.value, - 0, - &None, - ); + let ExtractResult { styles, tag: _tag, .. } = extract_style_from_expression(ast_builder, Some(&name), &mut prop.value, 0, &None); props_styles.extend(styles); tag = _tag.or(tag); } @@ -83,15 +53,7 @@ pub fn extract_style_from_expression<'a>( } } ObjectPropertyKind::SpreadProperty(prop) => { - let ExtractResult { - styles, tag: _tag, .. - } = extract_style_from_expression( - ast_builder, - None, - &mut prop.argument, - 0, - &None, - ); + let ExtractResult { styles, tag: _tag, .. } = extract_style_from_expression(ast_builder, None, &mut prop.argument, 0, &None); props_styles.extend(styles); tag = _tag.or(tag); false @@ -100,74 +62,18 @@ pub fn extract_style_from_expression<'a>( obj.properties.insert(idx, prop); } } - ExtractResult { - styles: props_styles, - tag, - style_order, - style_vars, - props, - } + ExtractResult { styles: props_styles, tag, style_order, style_vars, props } } - Expression::ConditionalExpression(conditional) => ExtractResult { - props: None, - styles: vec![ExtractStyleProp::Conditional { - condition: conditional.test.clone_in(ast_builder.allocator), - consequent: Some(Box::new(ExtractStyleProp::StaticArray( - extract_style_from_expression( - ast_builder, - None, - &mut conditional.consequent, - level, - &None, - ) - .styles, - ))), - alternate: Some(Box::new(ExtractStyleProp::StaticArray( - extract_style_from_expression( - ast_builder, - None, - &mut conditional.alternate, - level, - selector, - ) - .styles, - ))), - }], - tag: None, - style_order, - style_vars, - }, - Expression::ParenthesizedExpression(parenthesized) => extract_style_from_expression( - ast_builder, - None, - &mut parenthesized.expression, - level, - &None, - ), - Expression::TemplateLiteral(tmp) => ExtractResult { - styles: css_to_style( - &tmp.quasis - .iter() - .map(|q| q.value.raw.as_str()) - .collect::(), - level, - selector, - ) - .into_iter() - .map(|ex| ExtractStyleProp::Static(ExtractStyleValue::Static(ex))) - .collect(), - ..ExtractResult::default() - }, + Expression::ConditionalExpression(conditional) => ExtractResult { props: None, styles: vec![ExtractStyleProp::Conditional { condition: conditional.test.clone_in(ast_builder.allocator), consequent: Some(Box::new(ExtractStyleProp::StaticArray(extract_style_from_expression(ast_builder, None, &mut conditional.consequent, level, &None).styles))), alternate: Some(Box::new(ExtractStyleProp::StaticArray(extract_style_from_expression(ast_builder, None, &mut conditional.alternate, level, selector).styles))) }], tag: None, style_order, style_vars }, + Expression::ParenthesizedExpression(parenthesized) => extract_style_from_expression(ast_builder, None, &mut parenthesized.expression, level, &None), + Expression::TemplateLiteral(tmp) => ExtractResult { styles: css_to_style(&tmp.quasis.iter().map(|q| q.value.raw.as_str()).collect::(), level, selector).into_iter().map(|ex| ExtractStyleProp::Static(ExtractStyleValue::Static(ex))).collect(), ..ExtractResult::default() }, _ => ExtractResult::default(), }; } if let Some(name) = name { if name == "as" { - return ExtractResult { - tag: Some(expression.clone_in(ast_builder.allocator)), - ..ExtractResult::default() - }; + return ExtractResult { tag: Some(expression.clone_in(ast_builder.allocator)), ..ExtractResult::default() }; } if name == "selectors" && let Expression::ObjectExpression(obj) = expression @@ -199,65 +105,22 @@ pub fn extract_style_from_expression<'a>( for sel in part_of_selector.iter().map(|name| { if let Some(selector) = selector { - if name.starts_with("_") { - if name.starts_with("_theme") { - StyleSelector::from([ - to_kebab_case(name.strip_prefix("_").unwrap_or(name)) - .as_str(), - &selector.to_string(), - ]) - .to_string() - } else { - StyleSelector::from([ - &selector.to_string(), - to_kebab_case(name.strip_prefix("_").unwrap_or(name)) - .as_str(), - ]) - .to_string() - } - } else { - name.replace("&", &selector.to_string()) - } + if name.starts_with("_") { if name.starts_with("_theme") { StyleSelector::from([to_kebab_case(name.strip_prefix("_").unwrap_or(name)).as_str(), &selector.to_string()]).to_string() } else { StyleSelector::from([&selector.to_string(), to_kebab_case(name.strip_prefix("_").unwrap_or(name)).as_str()]).to_string() } } else { name.replace("&", &selector.to_string()) } } else if name.starts_with("_") { - StyleSelector::from( - to_kebab_case(name.strip_prefix("_").unwrap_or(name)).as_str(), - ) - .to_string() + StyleSelector::from(to_kebab_case(name.strip_prefix("_").unwrap_or(name)).as_str()).to_string() } else { StyleSelector::from(name.strip_prefix("_").unwrap_or(name)).to_string() } }) { - props.extend( - extract_style_from_expression( - ast_builder, - None, - &mut o.value, - level, - &Some(StyleSelector::Selector(sel)), - ) - .styles, - ); + props.extend(extract_style_from_expression(ast_builder, None, &mut o.value, level, &Some(StyleSelector::Selector(sel))).styles); } } } - return ExtractResult { - styles: props, - ..ExtractResult::default() - }; + return ExtractResult { styles: props, ..ExtractResult::default() }; } if let Some(new_selector) = name.strip_prefix("_") { - return extract_style_from_expression( - ast_builder, - None, - expression, - level, - &Some(if let Some(selector) = selector { - (selector, new_selector).into() - } else { - new_selector.into() - }), - ); + return extract_style_from_expression(ast_builder, None, expression, level, &Some(if let Some(selector) = selector { (selector, new_selector).into() } else { new_selector.into() })); } typo = name == "typography"; } @@ -265,299 +128,55 @@ pub fn extract_style_from_expression<'a>( if let Some(name) = name { ExtractResult { styles: if typo { - vec![ExtractStyleProp::Static(ExtractStyleValue::Typography( - value.to_string(), - ))] + vec![ExtractStyleProp::Static(ExtractStyleValue::Typography(value.to_string()))] } else { // Create a new ExtractStaticStyle - if let Some(map) = get_enum_property_value(name, &value) { - map.into_iter() - .map(|(k, v)| { - ExtractStyleProp::Static(ExtractStyleValue::Static( - ExtractStaticStyle::new(&k, &v, level, selector.clone()), - )) - }) - .collect() - } else { - vec![ExtractStyleProp::Static(ExtractStyleValue::Static( - ExtractStaticStyle::new(name, &value, level, selector.clone()), - ))] - } + if let Some(map) = get_enum_property_value(name, &value) { map.into_iter().map(|(k, v)| ExtractStyleProp::Static(ExtractStyleValue::Static(ExtractStaticStyle::new(&k, &v, level, selector.clone())))).collect() } else { vec![ExtractStyleProp::Static(ExtractStyleValue::Static(ExtractStaticStyle::new(name, &value, level, selector.clone())))] } }, ..ExtractResult::default() } } else { - ExtractResult { - styles: css_to_style(&value, level, selector) - .into_iter() - .map(|ex| ExtractStyleProp::Static(ExtractStyleValue::Static(ex))) - .collect(), - ..ExtractResult::default() - } + ExtractResult { styles: css_to_style(&value, level, selector).into_iter().map(|ex| ExtractStyleProp::Static(ExtractStyleValue::Static(ex))).collect(), ..ExtractResult::default() } } } else { match expression { - Expression::UnaryExpression(un) => ExtractResult { - styles: if un.operator == UnaryOperator::Void { - vec![] - } else { - vec![dynamic_style( - ast_builder, - name.unwrap(), - expression, - level, - selector, - )] - }, - ..ExtractResult::default() - }, - Expression::BinaryExpression(_) - | Expression::StaticMemberExpression(_) - | Expression::CallExpression(_) => ExtractResult { - styles: vec![dynamic_style( - ast_builder, - name.unwrap(), - expression, - level, - selector, - )], - ..ExtractResult::default() - }, - Expression::TSAsExpression(exp) => extract_style_from_expression( - ast_builder, - name, - &mut exp.expression, - level, - selector, - ), - Expression::ComputedMemberExpression(mem) => { - extract_style_from_member_expression(ast_builder, name, mem, level, selector) - } - Expression::TemplateLiteral(_) => ExtractResult { - styles: if typo { - vec![ExtractStyleProp::Expression { - expression: ast_builder.expression_template_literal( - SPAN, - ast_builder.vec_from_array([ - ast_builder.template_element( - SPAN, - TemplateElementValue { - raw: ast_builder.atom("typo-"), - cooked: None, - }, - false, - ), - ast_builder.template_element( - SPAN, - TemplateElementValue { - raw: ast_builder.atom(""), - cooked: None, - }, - true, - ), - ]), - ast_builder - .vec_from_array([expression.clone_in(ast_builder.allocator)]), - ), - styles: vec![], - }] - } else { - vec![dynamic_style( - ast_builder, - name.unwrap(), - expression, - level, - selector, - )] - }, - ..ExtractResult::default() - }, + Expression::UnaryExpression(un) => ExtractResult { styles: if un.operator == UnaryOperator::Void { vec![] } else { vec![dynamic_style(ast_builder, name.unwrap(), expression, level, selector)] }, ..ExtractResult::default() }, + Expression::BinaryExpression(_) | Expression::StaticMemberExpression(_) | Expression::CallExpression(_) => ExtractResult { styles: vec![dynamic_style(ast_builder, name.unwrap(), expression, level, selector)], ..ExtractResult::default() }, + Expression::TSAsExpression(exp) => extract_style_from_expression(ast_builder, name, &mut exp.expression, level, selector), + Expression::ComputedMemberExpression(mem) => extract_style_from_member_expression(ast_builder, name, mem, level, selector), + Expression::TemplateLiteral(_) => ExtractResult { styles: if typo { vec![ExtractStyleProp::Expression { expression: ast_builder.expression_template_literal(SPAN, ast_builder.vec_from_array([ast_builder.template_element(SPAN, TemplateElementValue { raw: ast_builder.atom("typo-"), cooked: None }, false), ast_builder.template_element(SPAN, TemplateElementValue { raw: ast_builder.atom(""), cooked: None }, true)]), ast_builder.vec_from_array([expression.clone_in(ast_builder.allocator)])), styles: vec![] }] } else { vec![dynamic_style(ast_builder, name.unwrap(), expression, level, selector)] }, ..ExtractResult::default() }, Expression::Identifier(identifier) => { if IGNORED_IDENTIFIERS.contains(&identifier.name.as_str()) { ExtractResult::default() } else { let name = name.unwrap(); - if typo { - ExtractResult { - styles: vec![ExtractStyleProp::Expression { - expression: ast_builder.expression_conditional( - SPAN, - ast_builder - .expression_identifier(SPAN, identifier.name.as_str()), - ast_builder.expression_template_literal( - SPAN, - ast_builder.vec_from_array([ - ast_builder.template_element( - SPAN, - TemplateElementValue { - raw: ast_builder.atom("typo-"), - cooked: None, - }, - false, - ), - ast_builder.template_element( - SPAN, - TemplateElementValue { - raw: ast_builder.atom(""), - cooked: None, - }, - true, - ), - ]), - ast_builder.vec_from_array([ - expression.clone_in(ast_builder.allocator) - ]), - ), - ast_builder.expression_string_literal(SPAN, "", None), - ), - styles: vec![], - }], - ..ExtractResult::default() - } - } else { - ExtractResult { - styles: vec![dynamic_style( - ast_builder, - name, - expression, - level, - selector, - )], - ..ExtractResult::default() - } - } + if typo { ExtractResult { styles: vec![ExtractStyleProp::Expression { expression: ast_builder.expression_conditional(SPAN, ast_builder.expression_identifier(SPAN, identifier.name.as_str()), ast_builder.expression_template_literal(SPAN, ast_builder.vec_from_array([ast_builder.template_element(SPAN, TemplateElementValue { raw: ast_builder.atom("typo-"), cooked: None }, false), ast_builder.template_element(SPAN, TemplateElementValue { raw: ast_builder.atom(""), cooked: None }, true)]), ast_builder.vec_from_array([expression.clone_in(ast_builder.allocator)])), ast_builder.expression_string_literal(SPAN, "", None)), styles: vec![] }], ..ExtractResult::default() } } else { ExtractResult { styles: vec![dynamic_style(ast_builder, name, expression, level, selector)], ..ExtractResult::default() } } } } Expression::LogicalExpression(logical) => { - let res = Some(Box::new(ExtractStyleProp::StaticArray( - extract_style_from_expression( - ast_builder, - name, - &mut logical.right, - level, - selector, - ) - .styles, - ))); + let res = Some(Box::new(ExtractStyleProp::StaticArray(extract_style_from_expression(ast_builder, name, &mut logical.right, level, selector).styles))); match logical.operator { - LogicalOperator::Or => ExtractResult { - styles: vec![ExtractStyleProp::Conditional { - condition: logical.left.clone_in(ast_builder.allocator), - consequent: None, - alternate: res, - }], - ..ExtractResult::default() - }, - LogicalOperator::And => ExtractResult { - styles: vec![ExtractStyleProp::Conditional { - condition: logical.left.clone_in(ast_builder.allocator), - consequent: res, - alternate: None, - }], - ..ExtractResult::default() - }, - LogicalOperator::Coalesce => ExtractResult { - styles: vec![ExtractStyleProp::Conditional { - condition: ast_builder.expression_logical( - SPAN, - ast_builder.expression_binary( - SPAN, - logical.left.clone_in(ast_builder.allocator), - BinaryOperator::StrictInequality, - ast_builder.expression_null_literal(SPAN), - ), - LogicalOperator::And, - ast_builder.expression_binary( - SPAN, - logical.left.clone_in(ast_builder.allocator), - BinaryOperator::StrictInequality, - ast_builder.expression_identifier(SPAN, "undefined"), - ), - ), - consequent: Some(Box::new(ExtractStyleProp::StaticArray( - extract_style_from_expression( - ast_builder, - name, - &mut logical.left, - level, - selector, - ) - .styles, - ))), - alternate: res, - }], - ..ExtractResult::default() - }, + LogicalOperator::Or => ExtractResult { styles: vec![ExtractStyleProp::Conditional { condition: logical.left.clone_in(ast_builder.allocator), consequent: None, alternate: res }], ..ExtractResult::default() }, + LogicalOperator::And => ExtractResult { styles: vec![ExtractStyleProp::Conditional { condition: logical.left.clone_in(ast_builder.allocator), consequent: res, alternate: None }], ..ExtractResult::default() }, + LogicalOperator::Coalesce => ExtractResult { styles: vec![ExtractStyleProp::Conditional { condition: ast_builder.expression_logical(SPAN, ast_builder.expression_binary(SPAN, logical.left.clone_in(ast_builder.allocator), BinaryOperator::StrictInequality, ast_builder.expression_null_literal(SPAN)), LogicalOperator::And, ast_builder.expression_binary(SPAN, logical.left.clone_in(ast_builder.allocator), BinaryOperator::StrictInequality, ast_builder.expression_identifier(SPAN, "undefined"))), consequent: Some(Box::new(ExtractStyleProp::StaticArray(extract_style_from_expression(ast_builder, name, &mut logical.left, level, selector).styles))), alternate: res }], ..ExtractResult::default() }, } } - Expression::ParenthesizedExpression(parenthesized) => extract_style_from_expression( - ast_builder, - name, - &mut parenthesized.expression, - level, - selector, - ), + Expression::ParenthesizedExpression(parenthesized) => extract_style_from_expression(ast_builder, name, &mut parenthesized.expression, level, selector), Expression::ArrayExpression(array) => { let mut props = vec![]; for (idx, element) in array.elements.iter_mut().enumerate() { if let Some(element) = element.as_expression_mut() { - props.extend( - extract_style_from_expression( - ast_builder, - name, - element, - idx as u8, - selector, - ) - .styles, - ); + props.extend(extract_style_from_expression(ast_builder, name, element, idx as u8, selector).styles); } } - ExtractResult { - styles: vec![ExtractStyleProp::StaticArray(props)], - tag: None, - style_order: None, - style_vars: None, - props: None, - } + ExtractResult { styles: vec![ExtractStyleProp::StaticArray(props)], tag: None, style_order: None, style_vars: None, props: None } } Expression::ConditionalExpression(conditional) => { if is_same_expression(&conditional.consequent, &conditional.alternate) { - extract_style_from_expression( - ast_builder, - name, - &mut conditional.consequent, - level, - selector, - ) + extract_style_from_expression(ast_builder, name, &mut conditional.consequent, level, selector) } else { - ExtractResult { - styles: vec![ExtractStyleProp::Conditional { - condition: conditional.test.clone_in(ast_builder.allocator), - consequent: Some(Box::new(ExtractStyleProp::StaticArray( - extract_style_from_expression( - ast_builder, - name, - &mut conditional.consequent, - level, - selector, - ) - .styles, - ))), - alternate: Some(Box::new(ExtractStyleProp::StaticArray( - extract_style_from_expression( - ast_builder, - name, - &mut conditional.alternate, - level, - selector, - ) - .styles, - ))), - }], - ..ExtractResult::default() - } + ExtractResult { styles: vec![ExtractStyleProp::Conditional { condition: conditional.test.clone_in(ast_builder.allocator), consequent: Some(Box::new(ExtractStyleProp::StaticArray(extract_style_from_expression(ast_builder, name, &mut conditional.consequent, level, selector).styles))), alternate: Some(Box::new(ExtractStyleProp::StaticArray(extract_style_from_expression(ast_builder, name, &mut conditional.alternate, level, selector).styles))) }], ..ExtractResult::default() } } } Expression::ObjectExpression(obj) => { @@ -588,74 +207,24 @@ pub fn extract_style_from_expression<'a>( } }); - let selector = selector.clone().map(|s| { - if let Some(params) = params { - add_selector_params(s, ¶ms) - } else { - s - } - }); + let selector = selector.clone().map(|s| if let Some(params) = params { add_selector_params(s, ¶ms) } else { s }); for p in obj.properties.iter_mut() { if let ObjectPropertyKind::ObjectProperty(o) = p && o.key.name().unwrap() != "params" { for name in disassemble_property(&o.key.name().unwrap()) { - props.extend( - extract_style_from_expression( - ast_builder, - Some(&name), - &mut o.value, - level, - &selector, - ) - .styles, - ); + props.extend(extract_style_from_expression(ast_builder, Some(&name), &mut o.value, level, &selector).styles); } } } - ExtractResult { - styles: props, - ..ExtractResult::default() - } + ExtractResult { styles: props, ..ExtractResult::default() } } _ => ExtractResult::default(), } } } -pub fn dynamic_style<'a>( - ast_builder: &AstBuilder<'a>, - name: &str, - expression: &Expression<'a>, - level: u8, - selector: &Option, -) -> ExtractStyleProp<'a> { - if let Some(map) = get_enum_property_map(name) { - ExtractStyleProp::Enum { - condition: expression.clone_in(ast_builder.allocator), - map: map - .into_iter() - .map(|(k, v)| { - ( - k.to_string(), - v.into_iter() - .map(|(k, v)| { - ExtractStyleProp::Static(ExtractStyleValue::Static( - ExtractStaticStyle::new(k, v, level, selector.clone()), - )) - }) - .collect::>(), - ) - }) - .collect(), - } - } else { - ExtractStyleProp::Static(ExtractStyleValue::Dynamic(ExtractDynamicStyle::new( - name, - level, - &expression_to_code(expression), - selector.clone(), - ))) - } +pub fn dynamic_style<'a>(ast_builder: &AstBuilder<'a>, name: &str, expression: &Expression<'a>, level: u8, selector: &Option) -> ExtractStyleProp<'a> { + if let Some(map) = get_enum_property_map(name) { ExtractStyleProp::Enum { condition: expression.clone_in(ast_builder.allocator), map: map.into_iter().map(|(k, v)| (k.to_string(), v.into_iter().map(|(k, v)| ExtractStyleProp::Static(ExtractStyleValue::Static(ExtractStaticStyle::new(k, v, level, selector.clone())))).collect::>())).collect() } } else { ExtractStyleProp::Static(ExtractStyleValue::Dynamic(ExtractDynamicStyle::new(name, level, &expression_to_code(expression), selector.clone()))) } } diff --git a/libs/extractor/src/extractor/extract_style_from_jsx.rs b/libs/extractor/src/extractor/extract_style_from_jsx.rs index b77b6d81..ced3580c 100644 --- a/libs/extractor/src/extractor/extract_style_from_jsx.rs +++ b/libs/extractor/src/extractor/extract_style_from_jsx.rs @@ -1,29 +1,16 @@ -use crate::extractor::{ - ExtractResult, extract_style_from_expression::extract_style_from_expression, -}; +use crate::extractor::{ExtractResult, extract_style_from_expression::extract_style_from_expression}; use oxc_allocator::CloneIn; use oxc_ast::{ AstBuilder, ast::{Expression, JSXAttributeValue}, }; -pub fn extract_style_from_jsx<'a>( - ast_builder: &AstBuilder<'a>, - name: &str, - value: &mut JSXAttributeValue<'a>, -) -> ExtractResult<'a> { +pub fn extract_style_from_jsx<'a>(ast_builder: &AstBuilder<'a>, name: &str, value: &mut JSXAttributeValue<'a>) -> ExtractResult<'a> { match value { - JSXAttributeValue::ExpressionContainer(expression) => expression - .expression - .as_expression() - .map(|expression| expression.clone_in(ast_builder.allocator)), - JSXAttributeValue::StringLiteral(literal) => Some(Expression::StringLiteral( - literal.clone_in(ast_builder.allocator), - )), + JSXAttributeValue::ExpressionContainer(expression) => expression.expression.as_expression().map(|expression| expression.clone_in(ast_builder.allocator)), + JSXAttributeValue::StringLiteral(literal) => Some(Expression::StringLiteral(literal.clone_in(ast_builder.allocator))), _ => None, } - .map(|mut expression| { - extract_style_from_expression(ast_builder, Some(name), &mut expression, 0, &None) - }) + .map(|mut expression| extract_style_from_expression(ast_builder, Some(name), &mut expression, 0, &None)) .unwrap_or_default() } diff --git a/libs/extractor/src/extractor/extract_style_from_member_expression.rs b/libs/extractor/src/extractor/extract_style_from_member_expression.rs index 091e4f27..7667551a 100644 --- a/libs/extractor/src/extractor/extract_style_from_member_expression.rs +++ b/libs/extractor/src/extractor/extract_style_from_member_expression.rs @@ -4,10 +4,7 @@ use crate::{ ExtractResult, extract_style_from_expression::{dynamic_style, extract_style_from_expression}, }, - utils::{ - get_number_by_literal_expression, get_string_by_literal_expression, - get_string_by_property_key, - }, + utils::{get_number_by_literal_expression, get_string_by_literal_expression, get_string_by_property_key}, }; use css::style_selector::StyleSelector; use oxc_allocator::CloneIn; @@ -18,13 +15,7 @@ use oxc_ast::{ use oxc_span::SPAN; use std::collections::BTreeMap; -pub(super) fn extract_style_from_member_expression<'a>( - ast_builder: &AstBuilder<'a>, - name: Option<&str>, - mem: &mut ComputedMemberExpression<'a>, - level: u8, - selector: &Option, -) -> ExtractResult<'a> { +pub(super) fn extract_style_from_member_expression<'a>(ast_builder: &AstBuilder<'a>, name: Option<&str>, mem: &mut ComputedMemberExpression<'a>, level: u8, selector: &Option) -> ExtractResult<'a> { let mem_expression = &mem.expression.clone_in(ast_builder.allocator); let mut ret: Vec = vec![]; @@ -45,66 +36,19 @@ pub(super) fn extract_style_from_member_expression<'a>( return extract_style_from_expression(ast_builder, name, p, level, selector); } } - return ExtractResult { - props: None, - styles: etc - .map(|etc| { - vec![dynamic_style( - ast_builder, - name.unwrap(), - &Expression::ComputedMemberExpression( - ast_builder.alloc_computed_member_expression( - SPAN, - etc, - mem_expression.clone_in(ast_builder.allocator), - false, - ), - ), - level, - selector, - )] - }) - .unwrap_or_default(), - tag: None, - style_order: None, - style_vars: None, - }; + return ExtractResult { props: None, styles: etc.map(|etc| vec![dynamic_style(ast_builder, name.unwrap(), &Expression::ComputedMemberExpression(ast_builder.alloc_computed_member_expression(SPAN, etc, mem_expression.clone_in(ast_builder.allocator), false)), level, selector)]).unwrap_or_default(), tag: None, style_order: None, style_vars: None }; } let mut map = BTreeMap::new(); for (idx, p) in array.elements.iter_mut().enumerate() { if let ArrayExpressionElement::SpreadElement(sp) = p { - map.insert( - idx.to_string(), - Box::new(dynamic_style( - ast_builder, - name.unwrap(), - &Expression::ComputedMemberExpression( - ast_builder.alloc_computed_member_expression( - SPAN, - sp.argument.clone_in(ast_builder.allocator), - mem_expression.clone_in(ast_builder.allocator), - false, - ), - ), - level, - &selector.clone(), - )), - ); + map.insert(idx.to_string(), Box::new(dynamic_style(ast_builder, name.unwrap(), &Expression::ComputedMemberExpression(ast_builder.alloc_computed_member_expression(SPAN, sp.argument.clone_in(ast_builder.allocator), mem_expression.clone_in(ast_builder.allocator), false)), level, &selector.clone()))); } else if let Some(p) = p.as_expression_mut() { - map.insert( - idx.to_string(), - Box::new(ExtractStyleProp::StaticArray( - extract_style_from_expression(ast_builder, name, p, level, selector).styles, - )), - ); + map.insert(idx.to_string(), Box::new(ExtractStyleProp::StaticArray(extract_style_from_expression(ast_builder, name, p, level, selector).styles))); } } - ret.push(ExtractStyleProp::MemberExpression { - expression: mem_expression.clone_in(ast_builder.allocator), - map, - }); + ret.push(ExtractStyleProp::MemberExpression { expression: mem_expression.clone_in(ast_builder.allocator), map }); } else if let Expression::ObjectExpression(obj) = &mut mem.object && !obj.properties.is_empty() { @@ -116,17 +60,7 @@ pub(super) fn extract_style_from_member_expression<'a>( if let Some(property_name) = get_string_by_property_key(&o.key) && property_name == k { - return ExtractResult { - styles: extract_style_from_expression( - ast_builder, - name, - &mut o.value, - level, - selector, - ) - .styles, - ..ExtractResult::default() - }; + return ExtractResult { styles: extract_style_from_expression(ast_builder, name, &mut o.value, level, selector).styles, ..ExtractResult::default() }; } } else if let ObjectPropertyKind::SpreadProperty(sp) = p { etc = Some(sp.argument.clone_in(ast_builder.allocator)); @@ -135,20 +69,7 @@ pub(super) fn extract_style_from_member_expression<'a>( match etc { None => return ExtractResult::default(), - Some(etc) => ret.push(dynamic_style( - ast_builder, - name.unwrap(), - &Expression::ComputedMemberExpression( - ast_builder.alloc_computed_member_expression( - SPAN, - etc, - mem_expression.clone_in(ast_builder.allocator), - false, - ), - ), - level, - selector, - )), + Some(etc) => ret.push(dynamic_style(ast_builder, name.unwrap(), &Expression::ComputedMemberExpression(ast_builder.alloc_computed_member_expression(SPAN, etc, mem_expression.clone_in(ast_builder.allocator), false)), level, selector)), } } @@ -156,42 +77,13 @@ pub(super) fn extract_style_from_member_expression<'a>( if let ObjectPropertyKind::ObjectProperty(o) = p && let Some(property_name) = get_string_by_property_key(&o.key) { - map.insert( - property_name, - Box::new(ExtractStyleProp::StaticArray( - extract_style_from_expression( - ast_builder, - name, - &mut o.value, - level, - selector, - ) - .styles, - )), - ); + map.insert(property_name, Box::new(ExtractStyleProp::StaticArray(extract_style_from_expression(ast_builder, name, &mut o.value, level, selector).styles))); } } - ret.push(ExtractStyleProp::MemberExpression { - expression: mem_expression.clone_in(ast_builder.allocator), - map, - }); + ret.push(ExtractStyleProp::MemberExpression { expression: mem_expression.clone_in(ast_builder.allocator), map }); } else if let Expression::Identifier(_) = &mut mem.object { - ret.push(dynamic_style( - ast_builder, - name.unwrap(), - &Expression::ComputedMemberExpression(ast_builder.alloc_computed_member_expression( - SPAN, - mem.object.clone_in(ast_builder.allocator), - mem_expression.clone_in(ast_builder.allocator), - false, - )), - level, - selector, - )) + ret.push(dynamic_style(ast_builder, name.unwrap(), &Expression::ComputedMemberExpression(ast_builder.alloc_computed_member_expression(SPAN, mem.object.clone_in(ast_builder.allocator), mem_expression.clone_in(ast_builder.allocator), false)), level, selector)) } - ExtractResult { - styles: ret, - ..ExtractResult::default() - } + ExtractResult { styles: ret, ..ExtractResult::default() } } diff --git a/libs/extractor/src/gen_class_name.rs b/libs/extractor/src/gen_class_name.rs index 9ffb45c9..7379a258 100644 --- a/libs/extractor/src/gen_class_name.rs +++ b/libs/extractor/src/gen_class_name.rs @@ -7,67 +7,16 @@ use oxc_ast::AstBuilder; use oxc_ast::ast::{Expression, PropertyKey, PropertyKind, TemplateElementValue}; use oxc_span::SPAN; -pub fn gen_class_names<'a>( - ast_builder: &AstBuilder<'a>, - style_props: &mut [ExtractStyleProp<'a>], - style_order: Option, - filename: Option<&str>, -) -> Option> { - merge_expression_for_class_name( - ast_builder, - style_props - .iter_mut() - .filter_map(|st| gen_class_name(ast_builder, st, style_order, filename)) - .rev() - .collect(), - ) +pub fn gen_class_names<'a>(ast_builder: &AstBuilder<'a>, style_props: &mut [ExtractStyleProp<'a>], style_order: Option, filename: Option<&str>) -> Option> { + merge_expression_for_class_name(ast_builder, style_props.iter_mut().filter_map(|st| gen_class_name(ast_builder, st, style_order, filename)).rev().collect()) } -fn gen_class_name<'a>( - ast_builder: &AstBuilder<'a>, - style_prop: &mut ExtractStyleProp<'a>, - style_order: Option, - filename: Option<&str>, -) -> Option> { +fn gen_class_name<'a>(ast_builder: &AstBuilder<'a>, style_prop: &mut ExtractStyleProp<'a>, style_order: Option, filename: Option<&str>) -> Option> { match style_prop { ExtractStyleProp::Enum { map, condition } => { - let properties = map.iter_mut().map(|(key, value)| { - ast_builder.object_property_kind_object_property( - SPAN, - PropertyKind::Init, - PropertyKey::StringLiteral(ast_builder.alloc_string_literal( - SPAN, - ast_builder.atom(key), - None, - )), - merge_expression_for_class_name( - ast_builder, - value - .iter_mut() - .map(|v| gen_class_name(ast_builder, v, style_order, filename).unwrap()) - .collect::>(), - ) - .unwrap(), - false, - false, - false, - ) - }); - let obj = ast_builder.expression_object( - SPAN, - oxc_allocator::Vec::from_iter_in(properties, ast_builder.allocator), - ); - Some(convert_class_name( - ast_builder, - &Expression::ComputedMemberExpression( - ast_builder.alloc_computed_member_expression( - SPAN, - obj, - condition.clone_in(ast_builder.allocator), - false, - ), - ), - )) + let properties = map.iter_mut().map(|(key, value)| ast_builder.object_property_kind_object_property(SPAN, PropertyKind::Init, PropertyKey::StringLiteral(ast_builder.alloc_string_literal(SPAN, ast_builder.atom(key), None)), merge_expression_for_class_name(ast_builder, value.iter_mut().map(|v| gen_class_name(ast_builder, v, style_order, filename).unwrap()).collect::>()).unwrap(), false, false, false)); + let obj = ast_builder.expression_object(SPAN, oxc_allocator::Vec::from_iter_in(properties, ast_builder.allocator)); + Some(convert_class_name(ast_builder, &Expression::ComputedMemberExpression(ast_builder.alloc_computed_member_expression(SPAN, obj, condition.clone_in(ast_builder.allocator), false)))) } ExtractStyleProp::Static(st) => { if let Some(style_order) = style_order { @@ -81,88 +30,23 @@ fn gen_class_name<'a>( ast_builder.expression_string_literal(SPAN, v, None) }) } - ExtractStyleProp::StaticArray(res) => merge_expression_for_class_name( - ast_builder, - res.iter_mut() - .filter_map(|st| gen_class_name(ast_builder, st, style_order, filename)) - .collect(), - ), - ExtractStyleProp::Conditional { - condition, - consequent, - alternate, - .. - } => { - let consequent = consequent - .as_mut() - .and_then(|ref mut con| { - gen_class_name(ast_builder, con.as_mut(), style_order, filename) - }) - .unwrap_or_else(|| ast_builder.expression_string_literal(SPAN, "", None)); + ExtractStyleProp::StaticArray(res) => merge_expression_for_class_name(ast_builder, res.iter_mut().filter_map(|st| gen_class_name(ast_builder, st, style_order, filename)).collect()), + ExtractStyleProp::Conditional { condition, consequent, alternate, .. } => { + let consequent = consequent.as_mut().and_then(|ref mut con| gen_class_name(ast_builder, con.as_mut(), style_order, filename)).unwrap_or_else(|| ast_builder.expression_string_literal(SPAN, "", None)); - let alternate = alternate - .as_mut() - .and_then(|ref mut alt| gen_class_name(ast_builder, alt, style_order, filename)) - .unwrap_or_else(|| ast_builder.expression_string_literal(SPAN, "", None)); - if is_same_expression(&consequent, &alternate) { - Some(consequent) - } else { - Some(ast_builder.expression_conditional( - SPAN, - condition.clone_in(ast_builder.allocator), - consequent, - alternate, - )) - } - } - ExtractStyleProp::Expression { expression, .. } => { - Some(expression.clone_in(ast_builder.allocator)) + let alternate = alternate.as_mut().and_then(|ref mut alt| gen_class_name(ast_builder, alt, style_order, filename)).unwrap_or_else(|| ast_builder.expression_string_literal(SPAN, "", None)); + if is_same_expression(&consequent, &alternate) { Some(consequent) } else { Some(ast_builder.expression_conditional(SPAN, condition.clone_in(ast_builder.allocator), consequent, alternate)) } } + ExtractStyleProp::Expression { expression, .. } => Some(expression.clone_in(ast_builder.allocator)), // direct select ExtractStyleProp::MemberExpression { map, expression } => { - let exp = - Expression::ComputedMemberExpression(ast_builder.alloc_computed_member_expression( - SPAN, - ast_builder.expression_object( - SPAN, - ast_builder.vec_from_iter(map.iter_mut().filter_map(|(key, value)| { - gen_class_name(ast_builder, value.as_mut(), style_order, filename).map( - |expr| { - ast_builder.object_property_kind_object_property( - SPAN, - PropertyKind::Init, - PropertyKey::StringLiteral( - ast_builder.alloc_string_literal( - SPAN, - ast_builder.atom(key), - None, - ), - ), - expr, - false, - false, - false, - ) - }, - ) - })), - ), - expression.clone_in(ast_builder.allocator), - false, - )); - if let Expression::Identifier(_) = &expression { - Some(convert_class_name(ast_builder, &exp)) - } else { - Some(exp) - } + let exp = Expression::ComputedMemberExpression(ast_builder.alloc_computed_member_expression(SPAN, ast_builder.expression_object(SPAN, ast_builder.vec_from_iter(map.iter_mut().filter_map(|(key, value)| gen_class_name(ast_builder, value.as_mut(), style_order, filename).map(|expr| ast_builder.object_property_kind_object_property(SPAN, PropertyKind::Init, PropertyKey::StringLiteral(ast_builder.alloc_string_literal(SPAN, ast_builder.atom(key), None)), expr, false, false, false))))), expression.clone_in(ast_builder.allocator), false)); + if let Expression::Identifier(_) = &expression { Some(convert_class_name(ast_builder, &exp)) } else { Some(exp) } } } } -pub fn merge_expression_for_class_name<'a>( - ast_builder: &AstBuilder<'a>, - expressions: Vec>, -) -> Option> { +pub fn merge_expression_for_class_name<'a>(ast_builder: &AstBuilder<'a>, expressions: Vec>) -> Option> { let mut class_names = vec![]; let mut unknown_expr = vec![]; for expr in expressions { @@ -201,11 +85,7 @@ pub fn merge_expression_for_class_name<'a>( qu.push(ast_builder.template_element(SPAN, t, tail)); } - Some(ast_builder.expression_template_literal( - SPAN, - qu, - oxc_allocator::Vec::from_iter_in(unknown_expr, ast_builder.allocator), - )) + Some(ast_builder.expression_template_literal(SPAN, qu, oxc_allocator::Vec::from_iter_in(unknown_expr, ast_builder.allocator))) } } else if class_name.is_empty() { None diff --git a/libs/extractor/src/gen_style.rs b/libs/extractor/src/gen_style.rs index 2bac6c6c..47ca5d58 100644 --- a/libs/extractor/src/gen_style.rs +++ b/libs/extractor/src/gen_style.rs @@ -5,111 +5,38 @@ use oxc_ast::AstBuilder; use oxc_ast::ast::{Expression, ObjectPropertyKind, PropertyKey, PropertyKind}; use oxc_span::SPAN; use std::collections::BTreeMap; -pub fn gen_styles<'a>( - ast_builder: &AstBuilder<'a>, - style_props: &[ExtractStyleProp<'a>], - filename: Option<&str>, -) -> Option> { +pub fn gen_styles<'a>(ast_builder: &AstBuilder<'a>, style_props: &[ExtractStyleProp<'a>], filename: Option<&str>) -> Option> { if style_props.is_empty() { return None; } - let properties: Vec<_> = style_props - .iter() - .flat_map(|style| gen_style(ast_builder, style, filename)) - .rev() - .collect(); + let properties: Vec<_> = style_props.iter().flat_map(|style| gen_style(ast_builder, style, filename)).rev().collect(); if properties.is_empty() { return None; } - Some(ast_builder.expression_object( - SPAN, - oxc_allocator::Vec::from_iter_in(properties, ast_builder.allocator), - )) + Some(ast_builder.expression_object(SPAN, oxc_allocator::Vec::from_iter_in(properties, ast_builder.allocator))) } -fn gen_style<'a>( - ast_builder: &AstBuilder<'a>, - style: &ExtractStyleProp<'a>, - filename: Option<&str>, -) -> Vec> { +fn gen_style<'a>(ast_builder: &AstBuilder<'a>, style: &ExtractStyleProp<'a>, filename: Option<&str>) -> Vec> { let mut properties = vec![]; if let ExtractStyleProp::Static(st) = style { - if let Some(StyleProperty::Variable { - variable_name, - identifier, - .. - }) = st.extract(filename) - { - properties.push(ast_builder.object_property_kind_object_property( - SPAN, - PropertyKind::Init, - PropertyKey::StringLiteral(ast_builder.alloc_string_literal( - SPAN, - ast_builder.atom(&variable_name), - None, - )), - ast_builder.expression_identifier(SPAN, ast_builder.atom(&identifier)), - false, - false, - false, - )); + if let Some(StyleProperty::Variable { variable_name, identifier, .. }) = st.extract(filename) { + properties.push(ast_builder.object_property_kind_object_property(SPAN, PropertyKind::Init, PropertyKey::StringLiteral(ast_builder.alloc_string_literal(SPAN, ast_builder.atom(&variable_name), None)), ast_builder.expression_identifier(SPAN, ast_builder.atom(&identifier)), false, false, false)); } } else if let ExtractStyleProp::StaticArray(res) = style { - properties.append( - &mut res - .iter() - .flat_map(|r| gen_style(ast_builder, r, filename)) - .rev() - .collect(), - ); - } else if let ExtractStyleProp::Conditional { - condition, - consequent, - alternate, - } = style - { + properties.append(&mut res.iter().flat_map(|r| gen_style(ast_builder, r, filename)).rev().collect()); + } else if let ExtractStyleProp::Conditional { condition, consequent, alternate } = style { let r = (consequent, alternate); if let (None, Some(c)) = r { - gen_style(ast_builder, c, filename) - .into_iter() - .for_each(|p| { - if let ObjectPropertyKind::ObjectProperty(p) = p { - properties.push(ast_builder.object_property_kind_object_property( - SPAN, - PropertyKind::Init, - p.key.clone_in(ast_builder.allocator), - ast_builder.expression_conditional( - SPAN, - condition.clone_in(ast_builder.allocator), - ast_builder.expression_identifier(SPAN, "undefined"), - p.value.clone_in(ast_builder.allocator), - ), - false, - false, - false, - )) - } - }); + gen_style(ast_builder, c, filename).into_iter().for_each(|p| { + if let ObjectPropertyKind::ObjectProperty(p) = p { + properties.push(ast_builder.object_property_kind_object_property(SPAN, PropertyKind::Init, p.key.clone_in(ast_builder.allocator), ast_builder.expression_conditional(SPAN, condition.clone_in(ast_builder.allocator), ast_builder.expression_identifier(SPAN, "undefined"), p.value.clone_in(ast_builder.allocator)), false, false, false)) + } + }); } else if let (Some(c), None) = r { - gen_style(ast_builder, c, filename) - .into_iter() - .for_each(|p| { - if let ObjectPropertyKind::ObjectProperty(p) = p { - properties.push(ast_builder.object_property_kind_object_property( - SPAN, - PropertyKind::Init, - p.key.clone_in(ast_builder.allocator), - ast_builder.expression_conditional( - SPAN, - condition.clone_in(ast_builder.allocator), - p.value.clone_in(ast_builder.allocator), - ast_builder.expression_identifier(SPAN, "undefined"), - ), - false, - false, - false, - )) - } - }); + gen_style(ast_builder, c, filename).into_iter().for_each(|p| { + if let ObjectPropertyKind::ObjectProperty(p) = p { + properties.push(ast_builder.object_property_kind_object_property(SPAN, PropertyKind::Init, p.key.clone_in(ast_builder.allocator), ast_builder.expression_conditional(SPAN, condition.clone_in(ast_builder.allocator), p.value.clone_in(ast_builder.allocator), ast_builder.expression_identifier(SPAN, "undefined")), false, false, false)) + } + }); } else if let (Some(c), Some(a)) = r { let collect_c = gen_style(ast_builder, c, filename); let collect_a = gen_style(ast_builder, a, filename); @@ -128,30 +55,14 @@ fn gen_style<'a>( r }); if !found && let ObjectPropertyKind::ObjectProperty(p) = p { - properties.push(ast_builder.object_property_kind_object_property( - SPAN, - PropertyKind::Init, - p.key.clone_in(ast_builder.allocator), - p.value.clone_in(ast_builder.allocator), - false, - false, - false, - )); + properties.push(ast_builder.object_property_kind_object_property(SPAN, PropertyKind::Init, p.key.clone_in(ast_builder.allocator), p.value.clone_in(ast_builder.allocator), false, false, false)); } } for q in collect_a.iter() { let found = collect_c.iter().any(|p| matches!((p, q), (ObjectPropertyKind::ObjectProperty(p), ObjectPropertyKind::ObjectProperty(q)) if p.key.name() == q.key.name())); if !found && let ObjectPropertyKind::ObjectProperty(q) = q { - properties.push(ast_builder.object_property_kind_object_property( - SPAN, - PropertyKind::Init, - q.key.clone_in(ast_builder.allocator), - q.value.clone_in(ast_builder.allocator), - false, - false, - false, - )); + properties.push(ast_builder.object_property_kind_object_property(SPAN, PropertyKind::Init, q.key.clone_in(ast_builder.allocator), q.value.clone_in(ast_builder.allocator), false, false, false)); } } } @@ -159,16 +70,8 @@ fn gen_style<'a>( let mut tmp_map = BTreeMap::>::new(); for (key, value) in map.iter() { for style in value.extract() { - if let Some(StyleProperty::Variable { - variable_name, - identifier, - .. - }) = style.extract(filename) - { - tmp_map - .entry(variable_name) - .or_default() - .push((key.to_string(), identifier)); + if let Some(StyleProperty::Variable { variable_name, identifier, .. }) = style.extract(filename) { + tmp_map.entry(variable_name).or_default().push((key.to_string(), identifier)); } } } @@ -178,60 +81,12 @@ fn gen_style<'a>( // do not create object expression when property is single ast_builder.expression_identifier(SPAN, ast_builder.atom(&value[0].1)) } else { - Expression::ComputedMemberExpression( - ast_builder.alloc_computed_member_expression( - SPAN, - ast_builder.expression_object( - SPAN, - oxc_allocator::Vec::from_iter_in( - value - .into_iter() - .map(|(k, v)| { - ast_builder.object_property_kind_object_property( - SPAN, - PropertyKind::Init, - ast_builder.property_key_static_identifier( - SPAN, - ast_builder.atom(&k), - ), - ast_builder - .expression_identifier(SPAN, ast_builder.atom(&v)), - false, - false, - false, - ) - }) - .collect::>(), - ast_builder.allocator, - ), - ), - expression.clone_in(ast_builder.allocator), - false, - ), - ) + Expression::ComputedMemberExpression(ast_builder.alloc_computed_member_expression(SPAN, ast_builder.expression_object(SPAN, oxc_allocator::Vec::from_iter_in(value.into_iter().map(|(k, v)| ast_builder.object_property_kind_object_property(SPAN, PropertyKind::Init, ast_builder.property_key_static_identifier(SPAN, ast_builder.atom(&k)), ast_builder.expression_identifier(SPAN, ast_builder.atom(&v)), false, false, false)).collect::>(), ast_builder.allocator)), expression.clone_in(ast_builder.allocator), false)) }; - properties.push(ast_builder.object_property_kind_object_property( - SPAN, - PropertyKind::Init, - PropertyKey::StringLiteral(ast_builder.alloc_string_literal( - SPAN, - ast_builder.atom(&key), - None, - )), - v, - false, - false, - false, - )); + properties.push(ast_builder.object_property_kind_object_property(SPAN, PropertyKind::Init, PropertyKey::StringLiteral(ast_builder.alloc_string_literal(SPAN, ast_builder.atom(&key), None)), v, false, false, false)); } } - properties.sort_by_key(|p| { - if let ObjectPropertyKind::ObjectProperty(p) = p { - p.key.name() - } else { - None - } - }); + properties.sort_by_key(|p| if let ObjectPropertyKind::ObjectProperty(p) = p { p.key.name() } else { None }); properties.reverse(); properties } diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs index 4d8a11ee..340af6c0 100644 --- a/libs/extractor/src/lib.rs +++ b/libs/extractor/src/lib.rs @@ -25,34 +25,17 @@ use std::path::PathBuf; pub enum ExtractStyleProp<'a> { Static(ExtractStyleValue), StaticArray(Vec>), - Conditional { - condition: Expression<'a>, - consequent: Option>>, - alternate: Option>>, - }, - Enum { - condition: Expression<'a>, - map: BTreeMap>>, - }, - Expression { - styles: Vec, - expression: Expression<'a>, - }, - MemberExpression { - map: BTreeMap>>, - expression: Expression<'a>, - }, + Conditional { condition: Expression<'a>, consequent: Option>>, alternate: Option>> }, + Enum { condition: Expression<'a>, map: BTreeMap>> }, + Expression { styles: Vec, expression: Expression<'a> }, + MemberExpression { map: BTreeMap>>, expression: Expression<'a> }, } impl ExtractStyleProp<'_> { pub fn extract(&self) -> Vec { match self { ExtractStyleProp::Static(style) => vec![style.clone()], - ExtractStyleProp::Conditional { - consequent, - alternate, - .. - } => { + ExtractStyleProp::Conditional { consequent, alternate, .. } => { let mut styles = vec![]; if let Some(consequent) = consequent { styles.append(&mut consequent.extract()); @@ -62,17 +45,10 @@ impl ExtractStyleProp<'_> { } styles } - ExtractStyleProp::StaticArray(array) => { - array.iter().flat_map(|s| s.extract()).collect() - } + ExtractStyleProp::StaticArray(array) => array.iter().flat_map(|s| s.extract()).collect(), ExtractStyleProp::Expression { styles, .. } => styles.to_vec(), - ExtractStyleProp::MemberExpression { map, .. } => { - map.values().flat_map(|s| s.extract()).collect() - } - ExtractStyleProp::Enum { map, .. } => map - .values() - .flat_map(|s| s.iter().flat_map(|s| s.extract())) - .collect(), + ExtractStyleProp::MemberExpression { map, .. } => map.values().flat_map(|s| s.extract()).collect(), + ExtractStyleProp::Enum { map, .. } => map.values().flat_map(|s| s.iter().flat_map(|s| s.extract())).collect(), } } } @@ -96,31 +72,14 @@ pub struct ExtractOption { pub import_main_css: bool, } -pub fn extract( - filename: &str, - code: &str, - option: ExtractOption, -) -> Result> { +pub fn extract(filename: &str, code: &str, option: ExtractOption) -> Result> { if !code.contains(option.package.as_str()) { // skip if not using package - return Ok(ExtractOutput { - styles: HashSet::new(), - code: code.to_string(), - map: None, - css_file: None, - }); + return Ok(ExtractOutput { styles: HashSet::new(), code: code.to_string(), map: None, css_file: None }); } let source_type = SourceType::from_path(filename)?; - let css_file = if option.single_css { - format!("{}/devup-ui.css", option.css_dir) - } else { - format!( - "{}/devup-ui-{}.css", - option.css_dir, - get_file_num_by_filename(filename) - ) - }; + let css_file = if option.single_css { format!("{}/devup-ui.css", option.css_dir) } else { format!("{}/devup-ui-{}.css", option.css_dir, get_file_num_by_filename(filename)) }; let mut css_files = vec![css_file.clone()]; if option.import_main_css && !option.single_css { css_files.insert(0, format!("{}/devup-ui.css", option.css_dir)); @@ -135,31 +94,11 @@ pub fn extract( if panicked { return Err("Parser panicked".into()); } - let mut visitor = DevupVisitor::new( - &allocator, - filename, - &option.package, - css_files, - if !option.single_css { - Some(filename.to_string()) - } else { - None - }, - ); + let mut visitor = DevupVisitor::new(&allocator, filename, &option.package, css_files, if !option.single_css { Some(filename.to_string()) } else { None }); visitor.visit_program(&mut program); - let result = Codegen::new() - .with_options(CodegenOptions { - source_map_path: Some(PathBuf::from(filename)), - ..Default::default() - }) - .build(&program); + let result = Codegen::new().with_options(CodegenOptions { source_map_path: Some(PathBuf::from(filename)), ..Default::default() }).build(&program); - Ok(ExtractOutput { - styles: visitor.styles, - code: result.code, - map: result.map.map(|m| m.to_json_string()), - css_file: Some(css_file), - }) + Ok(ExtractOutput { styles: visitor.styles, code: result.code, map: result.map.map(|m| m.to_json_string()), css_file: Some(css_file) }) } #[cfg(test)] @@ -197,34 +136,10 @@ mod tests { #[serial] fn extract_just_tsx() { reset_class_map(); - assert_debug_snapshot!(ToBTreeSet::from( - extract( - "test.tsx", - "const a = 1;", - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - }, - ) - .unwrap() - )); + assert_debug_snapshot!(ToBTreeSet::from(extract("test.tsx", "const a = 1;", ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false },).unwrap())); reset_class_map(); - assert_debug_snapshot!(ToBTreeSet::from( - extract( - "test.tsx", - "", - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - }, - ) - .unwrap() - )); + assert_debug_snapshot!(ToBTreeSet::from(extract("test.tsx", "", ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false },).unwrap())); } #[test] #[serial] @@ -248,12 +163,7 @@ mod tests { r#"import {Input} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -269,12 +179,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -286,12 +191,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -303,12 +203,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -320,12 +215,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -337,12 +227,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -354,12 +239,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -371,12 +251,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -388,12 +263,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -405,12 +275,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -422,12 +287,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -439,12 +299,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -456,12 +311,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -473,12 +323,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -490,12 +335,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -531,12 +371,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -548,12 +383,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -565,12 +395,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -583,12 +408,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -601,12 +421,7 @@ mod tests { r#"import {Box} from '@devup-ui/core' "#, - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -621,12 +436,7 @@ mod tests { r"import {Box} from '@devup-ui/core' /> ", - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -637,12 +447,7 @@ mod tests { r"import {Box as C} from '@devup-ui/core' ", - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -653,12 +458,7 @@ mod tests { r"import {Input} from '@devup-ui/core' ", - ExtractOption { - package: "@devup-ui/core".to_string(), - css_dir: "@devup-ui/core".to_string(), - single_css: true, - import_main_css: false - } + ExtractOption { package: "@devup-ui/core".to_string(), css_dir: "@devup-ui/core".to_string(), single_css: true, import_main_css: false } ) .unwrap() )); @@ -670,12 +470,7 @@ mod tests { r"import {Button} from '@devup-ui/core'