DEV Community

Seif Ahmed
Seif Ahmed

Posted on Edited on AI-assisted

Refactoring Vlox's Theme Engine 🎨

Most standard theme systems swap a single global class on the <body> element. My engine can handle many themes at once.


The Update:

In the past, themes were tracked by index. I noticed that reordering the array broke saved themes for existing users.

To fix this, I used unique keys for themes instead of indexes.


The Configuration:

Each unique theme contains an array of configuration objects. Every configuration object contains 4 keys:

  • class: (Required): The target CSS class name.
  • elements: (Required): Elements targeted immediately on page load.
  • postsElements: (Optional): Elements targeted ONLY after Vlox posts finish loading.
  • remove: (Optional): Specifies whether to add or remove the class.

The Logic:

The current theme is tracked in a variable called currentTheme. When a page reload happens, it reads the value from localStorage. If the value in the localStorage doesn't match any theme name, currentTheme value becomes "default" without updating the broken value in localStorage. I did this to prevent Vlox from breaking other apps that may use the same localStorage key while keeping my theme engine 100% working. Also, users won't be stuck on the invalid value. Once they choose a valid theme from Vlox, the localStorage value gets updated.


If you liked Vlox, please consider giving it a 🌟 on GitHub at https://github.com/Hfs2024/Vlox. It means the 🌎 to me!

Top comments (2)

Collapse
 
alexandersstudi profile image
Alexander •

Moving to unique keys instead of array indexes is definitely the right call for persisting user preferences without breaking state. The "blender" concept is interesting, though relying on JS to imperatively query and inject classes across the DOM can introduce layout thrashing or flashes of unstyled content as the app scales. Have you considered shifting the blending logic to CSS custom properties scoped to data attributes? Letting the browser natively handle the cascade usually drops the JS overhead to near zero.

Collapse
 
codemaster_121482 profile image
Seif Ahmed • • Edited

Hey Alexander!

Thanks for your suggestion, but I avoided this method because it requires you to add inline attributes to every single element you want to style which can become hard to maintain as Vlox scales. Also, there is no flashes or layout trashing as the theme engine executes immediately after the initial page load.