sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
78.37k stars 4.1k forks source link

Advanced search for unused css classes using types #13028

Open AlexRMU opened 2 weeks ago

AlexRMU commented 2 weeks ago

Describe the problem

This is a issue of the distant future. If the type passed to the class value has a literal type, then it can be assumed that the user knows what he is doing and use this type to search for unused classes.

Describe the proposed solution

Here is an example for getting the final type of a class value:

let class1: "" = "";
let class_attr1 = `Comp ${class1} ${class1 ? (`Comp-${class1}` as const) : ``}` as const;
// "Comp  "

let class2: "q" = "" as any;
let class_attr2 = `Comp ${class2} ${class2 ? (`Comp-${class2}` as const) : ``}` as const;
// "Comp q " | "Comp q Comp-q"

let class3: "q" | "w" | "e" | "" = "";
let class_attr3 = `Comp ${class3} ${class3 ? (`Comp-${class3}` as const) : ``}` as const;
// "Comp  " | "Comp q " | "Comp q Comp-q" | "Comp  Comp-q" | "Comp  Comp-w" | "Comp  Comp-e" | "Comp q Comp-w" | "Comp q Comp-e" | "Comp w " | "Comp w Comp-q" | "Comp w Comp-w" | "Comp w Comp-e" | "Comp e " | "Comp e Comp-q" | "Comp e Comp-w" | "Comp e Comp-e"
// bad - unnecessary non-existent values

type T1 = "q" | "w" | "e" | "";
type T2 = `Comp ${T1} Comp-${T1}`; // bad - unnecessary non-existent values
type T3 = T1 extends infer I extends string ? (I extends any ? `Comp ${I} Comp-${I}` : never) : never;
// "Comp q Comp-q" | "Comp w Comp-w" | "Comp e Comp-e" | "Comp  Comp-"

let class4: `w${string}e` | "" = "";
let class_attr4 = `Comp ${class4} ${class4 ? (`Comp-${class4}` as const) : ``}` as const;
// "Comp  " | `Comp  Comp-w${string}e` | `Comp w${string}e ` | `Comp w${string}e Comp-w${string}e`

CSSTypes Playground

https://github.com/ghoullier/awesome-template-literal-types

Importance

nice to have

AlexRMU commented 2 weeks ago

Accordingly, if a string is passed to the class attribute instead of a variable, a const assertion must be applied to it.

david-plugge commented 2 weeks ago

What? Can you elaborate a bit what you want to achieve with this (with an example maybe)

AlexRMU commented 2 weeks ago

https://svelte.dev/repl/5dd04bf9ed6a4b0d96e54bb65d60c7b2?version=4.2.19

Now, if a variable or expression is present in a class attribute, then checking for unused classes is disabled. This can be fixed by using types.