npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@butility/style

v1.0.4

Published

@butility/style provides utilities to manage web fonts, CSS styles, and color manipulations for web development. It includes tools for managing themes, applying dynamic styles, and handling color operations.

Downloads

11

Readme

Butility Style Utils

@butility/style provides utilities to manage web fonts, CSS styles, and color manipulations for web development. It includes tools for managing themes, applying dynamic styles, and handling color operations.

Table of Contents

  1. Installation
  2. Usage
  3. API Reference

Installation

To install the package, you can use npm or CDN:

npm install @butility/style
<!-- To use all the functions and methods -->
<script src="https://unpkg.com/@butility/style@latest/style.js" type="module"></script>
<script src="https://cdn.jsdelivr.net/npm/@butility/style@latest/style.js" type="module"></script>
<!-- To use Color utils -->
<script src="https://unpkg.com/@butility/style@latest/color.js" type="module"></script>
<script src="https://cdn.jsdelivr.net/npm/@butility/style@latest/color.js" type="module"></script>
<!-- To use CSS utils -->
<script src="https://unpkg.com/@butility/style@latest/css.js" type="module"></script>
<script src="https://cdn.jsdelivr.net/npm/@butility/style@latest/css.js" type="module"></script>
<!-- To use Font Utils -->
<script src="https://unpkg.com/@butility/style@latest/font.js" type="module"></script>
<script src="https://cdn.jsdelivr.net/npm/@butility/style@latest/font.js" type="module"></script>
<!-- To use state utils -->
<script src="https://unpkg.com/@butility/style@latest/state.js" type="module"></script>
<script src="https://cdn.jsdelivr.net/npm/@butility/style@latest/state.js" type="module"></script>
<!-- To use theme utils -->
<script src="https://unpkg.com/@butility/style@latest/theme.js" type="module"></script>
<script src="https://cdn.jsdelivr.net/npm/@butility/style@latest/theme.js" type="module"></script>

Usage

Theme Management

You can manage multiple themes for your web app using the ThemeManager class.

import { ThemeManager } from '@butility/style';
import { button, body } from '@butility/dom/html'; // Used for example only; you can install it.

// Define your themes
const themes = {
    light: {
        background: '#ffffff',
        color: '#000000',
        // Add more properties as needed
    },
    dark: {
        background: '#000000',
        color: '#ffffff',
        // Add more properties as needed
    },
};

// Instantiate ThemeManager with the defined themes
const themeManager = new ThemeManager(themes);

// Function to toggle between light and dark themes
function toggleTheme() {
    const currentTheme = themeManager.getCurrentTheme();
    const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
    themeManager.setTheme(newTheme);
}

// Initial setup to apply the current theme
document.addEventListener('DOMContentLoaded', () => {
    const currentTheme = themeManager.getCurrentTheme();
    if (currentTheme) {
        themeManager.setTheme(currentTheme);
    } else {
        themeManager.setTheme('light');
    }
});

// Example of a button to toggle themes
const toggleButton = button('Toggle Theme');
toggleButton.onclick = toggleTheme;
body(toggleButton);

Font Management

Use the Font module to load web fonts dynamically, either synchronously or asynchronously.

Load Web Font

import { loadWebFont, loadWebFontAsync } from '@butility/style/font';

// Loading a Google Font using loadWebFont 
loadWebFont({
    family: 'Roboto',
    weight: '400',
    style: 'normal',
    subsets: ['latin'],
    elements: ['body', 'h1', 'p'], // Apply to body, h1, and p tags
    fallbackFonts: ['Arial', 'sans-serif'],
    display: 'swap',
    lazyLoad: false,  // Load immediately, if true, then unless the specified elementis in view the font won't load
    preload: true,    // Preload for better performance
});

// Asynchronously loading a Google Font
loadWebFontAsync({
    family: 'Open Sans',
    weight: '600',
    style: 'normal',
    subsets: ['latin'],
    elements: ['body', 'h1'],
    fallbackFonts: ['Verdana', 'sans-serif'],
    display: 'swap',
    lazyLoad: true,   // Load font lazily when elements are visible
    preload: true,    // Preload the font for better performance
    timeout: 3000,    // Set a 3-second timeout
    onLoadSuccess: () => {
        console.log('Font successfully loaded!');
    },
    onLoadError: (error) => {
        console.error('Error loading font:', error);
    },
    observerOptions: { threshold: 0.5 }, // Load font when 50% of the element is visible
})
    .then(() => {
        console.log('Font is applied to the elements.');
    })
    .catch((error) => {
        console.error('Font loading failed:', error);
    });

CSS Style Management

Manipulate styles dynamically in your web application.

import { addStyles, getAllStyles, removeStylesByProps } from '@butility/style';

// Add styles to elements
addStyles(document.body, { backgroundColor: '#f0f0f0', color: '#333' });

// Get all styles of an element
const styles = getAllStyles(document.body);

// Remove specific styles from an element
removeStylesByProps(document.body, 'backgroundColor', 'color');

Color Utilities

Perform various color manipulations such as generating gradients or converting between color formats.

import { lightenColor, hexToRgb, generateColorGradient } from '@butility/style';

// Lighten a color
const lighterColor = lightenColor('#ff0000', 10);

// Convert HEX to RGB
const rgbColor = hexToRgb('#ff0000');

// Generate a color gradient
const gradient = generateColorGradient('#ff0000', '#00ff00', 5);

API Reference

ThemeManager

A utility for managing themes in a web application.

Methods:

  • createTheme(name: string, theme: object): Creates a new theme.
  • setTheme(name: string): Sets the current theme by name.
  • getCurrentTheme(): string | null: Returns the current theme.
  • loadThemeFromStorage(): void (private): Loads the theme from local storage.
  • detectSystemTheme(): void (private): Detects the system theme (light/dark) and applies it.
  • watchSystemTheme(): void (private): Watches for system theme changes and updates the theme accordingly.

Font Utilities

loadWebFont(options: FontOptions): void

Synchronously loads a web font.

Options:
  • family: The font family to load (e.g., 'Roboto').
  • weight: (Optional) Font weight, defaults to '400'.
  • style: (Optional) Font style, defaults to 'normal'.
  • elements: (Optional) Elements to apply the font to (default: ['body']).
  • fallbackFonts: (Optional) Array of fallback fonts.
  • preload: (Optional) Whether to preload the font.
  • lazyLoad: (Optional) Lazy load the font using IntersectionObserver.

loadWebFontAsync(options: FontOptions): Promise<void>

Asynchronously loads a web font. Includes callbacks for success and error handling.

Additional Options:
  • onLoadSuccess: (Optional) Callback when the font is loaded successfully.
  • onLoadError: (Optional) Callback when the font fails to load.
  • timeout: (Optional) Timeout in milliseconds for loading the font.

CSS Utilities

addStyles(elements: HTMLElement | HTMLElement[], styles: CSSStyleDeclaration): void

Dynamically adds CSS styles to the specified elements.

getAllStyles(element: HTMLElement): CSSStyleDeclaration

Retrieves all styles applied to a specified element.

removeStylesByProps(element: HTMLElement, ...properties: string[]): void

Removes specified CSS properties from an element.

resetStyles(element: HTMLElement, styles: CSSStyleDeclaration): void

Resets an element's styles to a given state.

load(url: string): StyleResult

Loads external CSS and returns its style object.

loadAsync(url: string): Promise<StyleResult>

Asynchronously loads external CSS.

Color Utilities

calculateLuminance(color: string): number

Calculates the luminance of a given color.

colorBrightness(color: string): number

Determines the brightness level of a color.

colorContrast(color1: string, color2: string): number

Calculates the contrast between two colors.

darkenColor(color: string, percentage: number): string

Darkens a color by a given percentage.

lightenColor(color: string, percentage: number): string

Lightens a color by a given percentage.

generateColorGradient(startColor: string, endColor: string, steps: number): string[]

Generates a gradient between two colors over a given number of steps.

generateRandomColor(): string

Generates a random color.

hexToRgb(hex: string): { r: number, g: number, b: number }

Converts a hex color code to its RGB components.

rgbToHex(r: number, g: number, b: number): string

Converts RGB values to a hex color code.

License

MIT License. See LICENSE for details.