Style Switcher - Documentation

Introduction

What is Style Switcher?

Style Switcher is a [insert technology, e.g., JavaScript library, CSS framework component] designed to allow users to easily change the visual style of a website or web application. This is achieved by dynamically switching between pre-defined stylesheets or themes, without requiring a page reload. The switcher itself can be implemented as a simple interface (e.g., dropdown menu, radio buttons) that allows users to select their preferred style.

Why Use Style Switcher?

Using a Style Switcher offers several advantages:

Key Features

Target Audience

This Style Switcher is intended for web developers, front-end engineers, and designers who need a simple and efficient way to implement theme switching capabilities into their web projects. It is suitable for both small and large-scale applications and requires a basic understanding of HTML, CSS, and JavaScript.

Getting Started

Installation

There are [insert number] ways to install the Style Switcher:

Method 1: Using a Package Manager (e.g., npm, yarn)

If you are using a package manager, you can install the Style Switcher via:

npm install style-switcher-package-name  // Replace with actual package name
# or
yarn add style-switcher-package-name     // Replace with actual package name

Method 2: Downloading the Files

Alternatively, you can download the Style Switcher directly from [insert download link]. Extract the downloaded archive and include the necessary files (usually CSS and JavaScript) in your project.

Basic Usage

After installation, include the Style Switcher’s JavaScript and CSS files in your HTML file within the <head> section:

<link rel="stylesheet" href="path/to/style-switcher.css">
<script src="path/to/style-switcher.js"></script>

Then, add a container element in your HTML where the Style Switcher interface will be rendered. This could be a <div> or any suitable element. Give it a unique ID, for example style-switcher-container:

<div id="style-switcher-container"></div>

Finally, initialize the Style Switcher with the following JavaScript code:

const styleSwitcher = new StyleSwitcher({
  containerId: 'style-switcher-container', // ID of the container element
  themes: [ // Array of theme objects (see "Setting up Stylesheets" below)
    { name: 'light', url: 'light.css' },
    { name: 'dark', url: 'dark.css' },
    // ... more themes
  ]
});

Setting up the Stylesheets

Create your theme stylesheets (e.g., light.css, dark.css) and place them in the appropriate directory. Each stylesheet should define the visual styles for your website. In the themes array passed to the StyleSwitcher constructor (see Basic Usage), each theme object requires a name (used for identification and display in the switcher UI) and a url (path to the stylesheet).

First Example

Let’s create a simple example with two themes: “light” and “dark.”

  1. Create Stylesheets: Create light.css and dark.css with the following content (replace these with your actual styles):

    light.css:

    body {
      background-color: #fff;
      color: #333;
    }

    dark.css:

    body {
      background-color: #333;
      color: #fff;
    }
  2. Include Files and Initialize: In your HTML, include the Style Switcher files (as shown in “Basic Usage”) and initialize it:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Style Switcher Example</title>
      <link rel="stylesheet" href="path/to/style-switcher.css">  </link>
      <script src="path/to/style-switcher.js"></script>
    </head>
    <body>
      <div id="style-switcher-container"></div>
      <script>
        const styleSwitcher = new StyleSwitcher({
          containerId: 'style-switcher-container',
          themes: [
            { name: 'light', url: 'light.css' },
            { name: 'dark', url: 'dark.css' }
          ]
        });
      </script>
    </body>
    </html>

Remember to replace "path/to/style-switcher.css" and "path/to/style-switcher.js" with the actual paths to your Style Switcher files. Now, running this HTML should display a Style Switcher allowing you to toggle between light and dark themes.

Core Functionality

Switching Styles

The Style Switcher allows users to switch between different stylesheets through its user interface (UI). By default, the UI provides a selection mechanism (e.g., dropdown, radio buttons) allowing the user to choose a theme. The selection triggers the StyleSwitcher to load the corresponding stylesheet and apply it to the page. The selected style is typically persisted using local storage, ensuring that the user’s preference is remembered across sessions. Programmatically, you can switch styles using the selectTheme() method:

styleSwitcher.selectTheme('dark'); // Selects the theme named 'dark'

Adding New Stylesheets

New stylesheets can be added dynamically after the Style Switcher has been initialized. This allows you to add themes without restarting the application. Use the addTheme() method:

styleSwitcher.addTheme({ name: 'newTheme', url: 'new-theme.css' });

This will add a new option to the Style Switcher’s UI, representing the new theme. The name property is displayed to the user, while the url points to the new stylesheet.

Removing Stylesheets

Similarly, you can remove existing stylesheets using the removeTheme() method. This removes the theme option from the UI and unloads the stylesheet if it’s currently active:

styleSwitcher.removeTheme('light'); // Removes the theme named 'light'

Be aware that removing an active theme will switch the page back to the default style or the next available theme.

Event Handling

The StyleSwitcher object emits events that you can listen for to perform actions based on theme changes. The primary event is themeChanged. You can listen to this event using the addEventListener() method:

styleSwitcher.addEventListener('themeChanged', (event) => {
  console.log('Theme changed to:', event.detail.themeName);
  // Perform any necessary actions, e.g., update UI elements based on the new theme
});

The event.detail.themeName property contains the name of the newly selected theme. You can use this information to update other parts of your application accordingly. [Mention any other relevant events, e.g., themeAdded, themeRemoved]

Asynchronous Loading

Stylesheets are loaded asynchronously to prevent blocking the page rendering. The Style Switcher handles the loading process internally. The themeChanged event is fired after the new stylesheet has been successfully loaded and applied. However, you might want to include a loading indicator in your UI to inform the user that a theme is being switched. This loading indicator should be hidden after the themeChanged event is fired.

Advanced Usage

Customizing the Switching Mechanism

The default Style Switcher UI provides a simple selection mechanism (e.g., dropdown, radio buttons). You can customize this by providing a custom rendering function during initialization. This function receives the available themes as an array of objects and should return the HTML for your custom UI. The returned HTML should include elements that allow users to select different themes; these elements must have a data attribute data-theme-name that matches the name property of the themes. When a user interacts with these elements, the Style Switcher automatically updates the active theme.

For example:

const styleSwitcher = new StyleSwitcher({
  containerId: 'style-switcher-container',
  themes: [ /* ... your themes ... */ ],
  renderUI: (themes) => {
    let html = '<ul>';
    themes.forEach(theme => {
      html += `<li><a href="#" data-theme-name="${theme.name}">${theme.name}</a></li>`;
    });
    html += '</ul>';
    return html;
  }
});

This example creates an unordered list (<ul>) with links (<a>) for each theme. Clicking a link triggers the theme switch. You can adapt this approach to create any custom UI design.

Using LocalStorage for Persistence

By default, the Style Switcher uses localStorage to persist the user’s theme selection across sessions. This ensures that the user’s preferred theme is loaded when they revisit the website. You can disable this functionality by setting the useLocalStorage option to false during initialization:

const styleSwitcher = new StyleSwitcher({
  containerId: 'style-switcher-container',
  themes: [ /* ... your themes ... */ ],
  useLocalStorage: false // Disables localStorage persistence
});

However, in most cases, leaving useLocalStorage enabled is recommended for a better user experience.

Integration with Other Libraries

The Style Switcher is designed to be compatible with most other JavaScript libraries and frameworks. You can integrate it into your existing projects without significant modifications. Ensure that you include the Style Switcher’s JavaScript and CSS files after any other dependencies that might affect the DOM. If you encounter conflicts, carefully review the loading order of your scripts and stylesheets.

Handling Multiple Style Switchers

It is possible to have multiple Style Switcher instances on a single page. Each instance should have a unique containerId to avoid conflicts. Remember to initialize each instance separately with its own configuration:

const styleSwitcher1 = new StyleSwitcher({ /* ... configuration for the first switcher ... */ });
const styleSwitcher2 = new StyleSwitcher({ /* ... configuration for the second switcher ... */ });

Performance Optimization

For optimal performance, especially with many themes or large stylesheets:

API Reference

Style Switcher Constructor

The StyleSwitcher constructor initializes a new Style Switcher instance.

Syntax:

new StyleSwitcher(options)

Parameters:

Example:

const styleSwitcher = new StyleSwitcher({
  containerId: 'mySwitcher',
  themes: [
    { name: 'light', url: 'light.css' },
    { name: 'dark', url: 'dark.css' }
  ],
  defaultTheme: 'dark'
});

Methods

Events

Properties

The StyleSwitcher object doesn’t expose public properties directly for modification. The active theme can be retrieved using the getTheme() method. Direct manipulation of internal properties is discouraged, as it might lead to unexpected behavior and break functionality. The API is designed to be used through the methods described above to ensure consistent and predictable operation.

Troubleshooting

Common Issues

Debugging Tips

Error Handling

The Style Switcher includes basic error handling. However, it’s important to handle potential errors such as network issues when loading stylesheets. You can listen to the themeChanged event and check the event.detail object for any error messages provided by the Style Switcher. In a production environment, you should implement robust error handling to gracefully degrade and provide informative feedback to the user in case of issues. For example, displaying an appropriate message if a stylesheet fails to load.

FAQ

Contributing

We welcome contributions to the Style Switcher project! Whether you’re fixing bugs, adding features, or improving documentation, your help is valuable. This section outlines the process for contributing.

Setting up the Development Environment

  1. Fork the Repository: Fork the official Style Switcher repository on [insert platform, e.g., GitHub] to your personal account.

  2. Clone the Repository: Clone your forked repository to your local machine:

    git clone <your-fork-url>
  3. Install Dependencies: Navigate to the project directory and install the required dependencies using npm or yarn:

    npm install  //or yarn install
  4. Set up a Development Server (if applicable): If the project uses a development server (e.g., using Webpack), start it according to the instructions in the project’s README file. This will usually involve a command like:

    npm start // or yarn start
  5. Create a New Branch: Create a new branch for your contribution:

    git checkout -b <your-branch-name>

Coding Style Guidelines

Adhere to the existing coding style and conventions used in the project. Generally this will involve:

Testing

The Style Switcher project likely includes unit tests. Before submitting a pull request, ensure that your changes don’t introduce regressions by running the tests. The test suite might be executed via a command like:

npm test // or yarn test

If new functionality is added, write corresponding tests to ensure its correctness and maintainability.

Submitting Pull Requests

  1. Commit Your Changes: Commit your changes with clear and concise commit messages:

    git add .
    git commit -m "Your descriptive commit message"
  2. Push Your Branch: Push your branch to your forked repository:

    git push origin <your-branch-name>
  3. Create a Pull Request: Go to your forked repository on [insert platform] and create a pull request to merge your branch into the main branch of the original repository. Provide a clear description of your changes and address any feedback from the maintainers. Make sure your pull request passes the project’s CI/CD pipeline (if there is one).

Remember to follow any specific contribution guidelines mentioned in the project’s README file.

License

License Type

The Style Switcher is licensed under the [Insert License Name, e.g., MIT License].

License Agreement

The [Insert License Name, e.g., MIT License] grants you permission to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

[If your license has additional clauses or conditions, include them here. For example, you might include a specific clause related to limitations of liability or disclaimers of warranties.] You can find the complete license text at [Insert Link to License File].