Style Utilities
The Style Module provides low-level operational capabilities for CSS and DOM class names. It encapsulates safe methods for class name manipulation (add, delete, update, query) and offers the ability to dynamically inject style tags into the <head> or generate CSS variable strings, serving as the underlying support for the TechUI theme system's dynamic skinning.
Import Method
import { cssVarGen, styleInit, tClass, tTheme } from "@techui/utils";Dynamic Styling
styleInit(id, info, cssStr)
Dynamically creates or updates a <style> tag.
- Mechanism: If a style tag with the specified ID already exists, its content is updated; otherwise, a new tag is created and appended to the
head. - Parameters:
id: The unique ID suffix for the tag (generates#style{id}).info: Description information attached todataset.info.cssStr: The specific CSS code string.
// Dynamically inject a piece of CSS
styleInit('custom-bg', 'red-theme', 'body { background: red; }');cssVarGen(prefix, styleObj)
CSS Variable Generator. Converts a JavaScript object into a CSS variable definition string.
- Format:
key: value->--prefix-key: value;
const colors = { base: '#fff', text: '#000' };
const css = cssVarGen('primary', colors);
console.log(css);
// Output: "--primary-base: #fff; --primary-text: #000"Class Name Operations
tClass provides a set of encapsulated methods for safely operating on DOM classList, preventing errors caused by non-existent elements.
Basic Methods
- add(el, cls): Adds a class name.
- del(el, cls): Deletes a class name.
- has(el, cls): Determines if a class name is present.
- toggle(el, cls): Toggles a class name.
- list(el): Retrieves the class list (
classList).
replace(el, prefix, suffix)
Prefix Replacement. This is the core method for state switching in TechUI. It searches for all class names on the element starting with prefix; if the suffix does not match, it removes them and adds the new ${prefix}${suffix} class name.
- Scenario: Used for switching state classes, such as moving from
status-loadingtostatus-success.
// Assume el current class: "btn status-loading"
// Switch status to success
tClass.replace(el, 'status-', 'success');
// Result class: "btn status-success" (the old status-loading is automatically removed)Theme Registration
tTheme is a singleton instance of the ThemeManager class, acting as the global theme registration center for TechUI.
tTheme.register(config)
Registers a new theme configuration object. This is typically called automatically by theme packages during application startup.
tTheme.register({
value: 'darkBlue',
label: 'Deep Sea Blue',
scheme: 'dark',
colors: ['#000', '#fff'],
data: { ... }
});tTheme.load()
Retrieves all registered theme configurations.
tTheme.loadIndex()
Retrieves a summary list of themes (containing only identifier, name, color scheme, and preview colors), usually used to build "Theme Switcher" UI components.
const themeList = tTheme.loadIndex();
// [{ value: 'darkBlue', label: 'Deep Sea Blue', ... }]