2.0.4 • Published 10 months ago

@awal-solution/tailwind-theming v2.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

Features:

  • Dynamic Theme Management:
    • Add, update, and remove themes programmatically.
  • Flexible Theme Configuration:
    • Define themes using extend to seamlessly integrate with TailwindCSS.
  • Data Attributes Selectors:
    • Apply themes via data-theme attributes.
  • Default Theme Support:
    • Specify a default theme to be applied globally.
  • Customizable Media Queries:
    • Apply themes based on user preferences, such as dark mode.

Installation:

Install the package via your package manager:

yarn add @awal-solution/tailwind-theming
# or
npm install @awal-solution/tailwind-theming

Getting Started:

1. Configure TailwindCSS Plugin

Add the themePlugin to your TailwindCSS configuration:

// tailwind.config.js|ts
import { themePlugin } from '@awal-solution/tailwind-theming'

export default {
  content: ['./src/**/*.{html,js,ts}'],
  plugins: [themePlugin()],
}

2. Initialize Themes in Your Application

Create a ThemeManager instance and define your themes:

import { ThemeManager } from '@awal-solution/tailwind-theming'

const themeManager = new ThemeManager({
  themes: {
    'light-theme': {
      colors: {
        background: { DEFAULT: '#FFFFFF' },
        foreground: { DEFAULT: '#000000' },
        primary: { DEFAULT: '#0000FF', light: '#0096FF' },
      },
    },
    'dark-theme': {
      colors: {
        background: { DEFAULT: '#000000' },
        foreground: { DEFAULT: '#FFFFFF' },
        primary: { DEFAULT: '#0000FF', light: '#0096FF' },
      },
    },
  },
  defaultTheme: 'light-theme',
})

export { themeManager }

3. Apply Themes

Use the generated selectors to toggle themes in your application:

// Apply the default theme
document.documentElement.setAttribute('data-theme', 'light-theme')

// Toggle between themes
function toggleTheme() {
  const currentTheme = document.documentElement.getAttribute('data-theme')
  const newTheme = currentTheme === 'light-theme' ? 'dark-theme' : 'light-theme'
  document.documentElement.setAttribute('data-theme', newTheme)
}

API Reference

ThemeManager

Constructor

constructor({ themes: Record<string, Theme>, defaultTheme?: string });
  • themes: A record of theme names and their configurations.
  • defaultTheme: (Optional) The default theme to apply initially.

Methods

get()

Returns all themes, including the default theme and additional themes.

themeManager.get()
getThemeSelectors()

Returns an object containing theme names and their associated selectors.

themeManager.getThemeSelectors()
add(theme: AddThemeType)

Adds a new theme to the existing themes.

themeManager.add({
  name: 'custom-theme',
  selectors: ['[data-theme="custom-theme"]'],
  theme: {
    colors: {
      background: { DEFAULT: '#555' },
    },
  },
})
update(themeName: string, properties: Partial<TailwindExtension>)

Updates an existing theme's configuration.

themeManager.update('custom-theme', {
  colors: {
    primary: { DEFAULT: '#FF0000' },
  },
})
remove(themeName: string)

Removes an existing theme by name.

themeManager.remove('custom-theme')

Plugin Options

The themePlugin provides the following options:

  • defaultTheme: (Optional) Default theme configuration.
  • themes: An array of theme configurations.

Example usage in TailwindCSS:

import { themePlugin } from '@awal-solution/tailwind-theming'
import { themeManager } from './themeManager'

export default {
  content: ['./src/**/*.{html,js,ts}'],
  plugins: [themePlugin(themeManager.get())],
}

Example CSS:

@tailwind base;
@tailwind components;
@tailwind utilities;

Example

An example setup for toggling themes in your app:

import './index.css'
import { storage } from './storage'
import { themeManager } from './themeManager'

let themeNames = themeManager.getThemeSelectors()
let currentTheme = storage.get<string>('APP_THEME') ?? Object.keys(themeNames)[0]

const initializeApp = () => {
  const root = document.documentElement

  // Apply the saved theme or system theme as default
  root.className = currentTheme
  root.setAttribute('data-theme', currentTheme)
  storage.set('APP_THEME', currentTheme)
}

const toggleTheme = () => {
  const root = document.documentElement
  const themeKeys = Object.keys(themeNames)
  const currentIndex = themeKeys.findIndex((key) => key === currentTheme)

  // Determine the next theme
  const nextIndex = (currentIndex + 1) % themeKeys.length
  currentTheme = themeKeys[nextIndex]

  // Apply the new theme
  root.className = currentTheme
  root.setAttribute('data-theme', currentTheme)
  storage.set('APP_THEME', currentTheme)

  // Update button text to show the next theme
  const button = document.querySelector<HTMLButtonElement>('#theme-toggle')
  if (button) {
    const nextTheme = themeNames[themeKeys[(nextIndex + 1) % themeKeys.length]].name
    button.textContent = `Switch to ${nextTheme.charAt(0).toUpperCase() + nextTheme.slice(1)} Mode`
  }
}

const renderApp = () => {
  const app = document.querySelector<HTMLDivElement>('#app')
  if (!app) return

  app.innerHTML = `
    <div class="min-h-screen flex gap-4 items-center justify-center bg-background text-foreground">
      <button id="theme-toggle" class="px-4 py-2 bg-primary text-white rounded">
        Switch to ${Object.keys(themeNames)[0]} Mode
      </button>
      <h1 class="border-b border-divider">
        Hello, TailwindCSS Theme Toggling!
      </h1>
    </div>
  `

  // Attach event listener for the theme toggle button
  const button = document.querySelector<HTMLButtonElement>('#theme-toggle')
  if (button) {
    button.addEventListener('click', toggleTheme)
  }
}

initializeApp()
renderApp()

License

This library is open-source and licensed under the MIT License.


Contributions

Contributions are welcome! If you find a bug or want to suggest a feature, please open an issue or submit a pull request.

Commits

Patch release

fix(theme): correct issue with theme manager

Minor release

feat(utils): add utility functions for theming

Major release

fix!: update API endpoints (BREAKING CHANGE: endpoint changes)

Happy coding! 🎉


2.0.4

10 months ago

2.0.3

10 months ago

2.0.2

10 months ago

2.0.1

10 months ago

2.0.0

10 months ago

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago

1.0.0-pre-release.1

10 months ago

0.0.5

10 months ago

0.0.4

10 months ago

0.0.3

10 months ago

0.0.2

10 months ago

0.0.1

10 months ago