Quote:
Originally Posted by dgatwood
If you want to take a crack at implementing the full set of sanity checks and fixup tweaks, JavaScript would be a really good way to do it. My first thought as far as implementation would be something like this:
- Iterate all the elements and css rules, and create an associative array with every single CSS class name used in either one. You'll need this for uniqueness checks later.
- Iterate all the elements looking for elements with multiple classes. Change the spaces to hyphens or underscores. Add a random number if needed to make the resulting class name unique. Create an associative array mapping each of the original classes to an array, and in that array, put the names of any combined classes based on the original class. That way, you can quickly obtain a list of all the new combined classes that are derived from each of the original classes.
- Iterate all the CSS rules. For each rule, if any part of the rule matches one of the original classes, add a new copy of that rule with the combined class substituted in place of the original class, but do not remove the original rule, because it might also affect other non-combining elements.
- Iterate all the CSS styles a second time. This time, for each rule with a complex selector (multi-element or multi-class or both), take the selector, remove all the characters that would be invalid in a class name, add a random number if needed to make the class name unique, and create a copy of that rule under the new name. Delete the original rule. Then use getElementsBySelector to obtain a list of elements that match the original selector. For each element, add the newly generated class name to its list of classes.
- Repeat steps 2–4 in a loop until nothing changes. (Step 4 can cause you to need to repeat step 2.)
- Optional: For each CSS style, perform a getElementsBySelector, and if it returns an empty list of elements, delete the unused style.
Be careful when handling the @ styles, e.g. @media, @font-face, etc. You can probably just ignore @font-face rules entirely, and emit them in the final output.
You'll want to process the rules within an @media query just like you would any other rule, being sure to add any replacement rules inside the same @media query that the original came from. I wouldn't try to process the @media rules separately, because my gut says that could cause a nasty mess.
I'm suddenly tempted to try this.
|
Heh. I may have to build this, because I have all my processing scripts in JS and I actually need to confront making sure I have my ducks in a row for KF7. Maybe in a few days I'll get to it, I'm tied up right now.
Question: It seems like you could do point #4 first, and then you'd only have to do point #2 once. Right?