myFavShrimp / turf

Macro based compile-time SCSS transpilation, CSS minification, and class name uniquification toolchain inspired by CSS modules.
MIT License
50 stars 2 forks source link

Use base64 ids rather than numeric ids for randomizing class ids #17

Closed BToersche closed 4 months ago

BToersche commented 4 months ago

Currently a u32 is used for randomizing ids. I'd like to suggest changing this in this PR to a base64 [a-zA-Z0-9-_] String with length 6 (a few examples: tOA2k7, JQcl_G, C6qIbv). for a couple of reasons:

CSS Compatibility

According to the CSS spec, a digit cannot be the first character of a class name (although in modern browsers this probably will work fine). According to the W3C CSS spec section 4.3.1:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); 
they cannot start with a digit, two hyphens, or a hyphen followed by a digit. 
Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

In general this works fine when using a class template like: myclass-<id>. But if the user uses a template like <id> or <id>-myclass the user unknowingly will use class names which aren't conforming to spec.

Character amount (Footprint)

The average amount of characters used for a randomized u32 number is 9.74. The base64 solution implemented in this PR always uses an id of 6 characters. Hence, the footprint will be a bit more efficient (a footprint of 6 / 9.74 = 61.6% compared to using u32).

Much less likely to generate id conflicts

Even though the footprint is less, the amount of possible base64 values (with 6 chars) is much larger than u32 (53 * 64^55 = 56,908,316,672 compared to 2^32 = 4,294,967,296). This results in 13.25 times more possible values. Hence the chances a conflict will happen is much lower.

If you have any questions, please do let me know.

myFavShrimp commented 4 months ago

Thank you very much for making the changes. The the proposal sounds reasonable and the pr looks good. Thank you for your contribution!