### Storybook Branch Switcher CLI Configuration File Example (JSON) Source: https://github.com/utarwyn/storybook-branch-switcher/blob/main/README.md A JSON configuration file example for the 'sb-branch-switcher' CLI. It specifies source and destination directories, default branch, root directory handling, and provider-specific settings for Bitbucket. ```json { "from": "dist/storybook", "to": "dist/storybook-bundle", "default_branch": "master", "default_root": true, "provider": { "type": "bitbucket", "project": "my-project", "repository": "my-design-system" } } ``` -------------------------------- ### Branch State Management Example (TypeScript) Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Illustrates the internal state structure used by the branch switcher addon for managing branch information. It shows an example state object and how it's stringified into an environment variable for the CLI and addon communication. ```typescript // Internal state structure (automatically managed by CLI) interface BranchSwitcherState { list: string[]; // All available branches defaultBranch: string; // The main/master branch currentBranch: string; // Currently displayed branch } // Example state during build process const exampleState = { list: ['main', 'PR-123', 'PR-456'], defaultBranch: 'main', currentBranch: 'PR-123' }; // CLI sets this internally via environment variable process.env['STORYBOOK_BRANCH_SWITCHER_STATE'] = JSON.stringify(exampleState); // The addon automatically reads this in the built Storybook ``` -------------------------------- ### Bash: Example CLI Workflow for Storybook Branch Switching Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt An example bash script demonstrating a typical workflow executed by the CLI tool. This involves cleaning, checking out branches, updating submodules, building Storybook, and copying the output to a bundle directory for each branch. ```bash # Example workflow executed by CLI: # 1. Clean: rm -rf dist/storybook-bundle # 2. Checkout: git fetch origin && git checkout abc123def # 3. Update submodules: git submodule update --init # 4. Build: npm run build-storybook # 5. Copy: cp -r storybook-static dist/storybook-bundle/PR-123 # 6. Repeat for each branch ``` -------------------------------- ### Install Storybook Branch Switcher with npm or yarn Source: https://github.com/utarwyn/storybook-branch-switcher/blob/main/README.md Commands to install the 'storybook-branch-switcher' package as a development dependency using either npm or yarn. ```sh npm i --save-dev storybook-branch-switcher ``` ```sh yarn add -D storybook-branch-switcher ``` -------------------------------- ### CLI Command to Generate Storybook Instances per Branch Source: https://github.com/utarwyn/storybook-branch-switcher/blob/main/README.md Example of how to use the 'sb-branch-switcher' CLI command, specifying a custom configuration file path using the '--config' or '--c' argument. This command automates the generation of Storybook instances for different branches. ```sh sb-branch-switcher --config libs/storybook-host/.storybook/.branches.json ``` -------------------------------- ### Build and Test Storybook with Subpath Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Provides bash commands to build and test the Storybook with subpath configuration. It demonstrates how to set environment variables for building and how to locally serve the built Storybook for testing. ```bash # Build with subpath configuration STORYBOOK_PUBLISH_FOR_WEB=true npx sb-branch-switcher # Test locally with subpath # 1. Set hostname in preview.js to "localhost:6006/storybook-bundle" # 2. Build: STORYBOOK_PUBLISH_FOR_WEB=true sb-branch-switcher # 3. Serve: npx http-server dist # Access at: http://localhost:8080/storybook-bundle ``` -------------------------------- ### Bitbucket Provider Configuration and Usage Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Configures the CLI to fetch open pull requests from a Bitbucket repository (cloud or self-hosted) and build Storybook instances. Supports Bearer token or Basic authentication. ```typescript // .storybook/.branches.json with Bitbucket provider { "from": "build/storybook", "to": "public/storybook-preview", "default_branch": "develop", "provider": { "type": "bitbucket", "project": "MYPROJ", "repository": "design-system", "url": "https://bitbucket.mycompany.com" } } ``` ```bash # Option 1: Bearer token authentication export BITBUCKET_TOKEN="your_access_token" # Option 2: Basic authentication export BITBUCKET_USERNAME="john.doe" export BITBUCKET_PASSWORD="secret_password" # Run CLI npx sb-branch-switcher --config .storybook/.branches.json # Expected output: # 😎 Your workspace looks good! # 👐 Branches to build: develop, PR-789, PR-790 # 🚚 Move to the develop branch # 🚚 Move to the PR-789 branch # 🚚 Move to the PR-790 branch # 🎉 Bundle ready! ``` -------------------------------- ### GitLab Provider Configuration and Usage Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Configures the CLI to fetch open merge requests from a GitLab project and generate Storybook builds. Requires GitLab token for authentication. Output structure depends on `default_root` setting. ```typescript // .storybook/.branches.json with GitLab provider { "from": ".storybook-out", "to": "public/previews", "default_branch": "main", "default_root": false, "provider": { "type": "gitlab", "projectId": "12345678", "url": "https://gitlab.com" } } ``` ```bash # Authentication via private token export GITLAB_TOKEN="glpat-xxxxxxxxxxxxxxxxxxxx" # Execute the build npx sb-branch-switcher # Directory structure (default_root: false): # public/previews/main/ (main branch in subdirectory) # public/previews/123/ (MR !123) # public/previews/456/ (MR !456) ``` -------------------------------- ### GitHub Provider Configuration and Usage Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Configures the CLI to fetch open pull requests from a GitHub repository and generate separate Storybook instances for each. Requires GitHub token for authentication. Output is structured by PR number. ```typescript // .storybook/.branches.json with GitHub provider { "from": "storybook-static", "to": "dist/storybook-all-prs", "default_branch": "main", "default_root": true, "provider": { "type": "github", "owner": "my-company", "repository": "component-library", "url": "https://api.github.com" } } ``` ```bash # Authentication required via environment variable export GITHUB_TOKEN="ghp_xxxxxxxxxxxxxxxxxxxx" # Run the CLI to build all PRs npx sb-branch-switcher # Output structure: dist/storybook-all-prs/ (main branch - default_root: true) dist/storybook-all-prs/PR-123/ (PR #123) dist/storybook-all-prs/PR-456/ (PR #456) ``` -------------------------------- ### CLI Configuration and Execution (.storybook/.branches.json) Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Defines the configuration for the Storybook Branch Switcher CLI, including source and destination directories, default branch, and Git provider details. Supports custom config paths and verbose output. ```typescript // .storybook/.branches.json { "from": "dist/storybook", "to": "dist/storybook-bundle", "directory": "/absolute/path/to/project", "script_name": "build-storybook", "default_branch": "master", "default_root": true, "provider": { "type": "github", "owner": "my-org", "repository": "my-design-system" } } ``` ```bash # Run with default config location npx sb-branch-switcher # Run with custom config path npx sb-branch-switcher --config libs/storybook-host/.storybook/.branches.json # Run with verbose output npx sb-branch-switcher --verbose # Set environment variable for GitHub authentication export GITHUB_TOKEN="ghp_your_token_here" npx sb-branch-switcher ``` -------------------------------- ### Storybook Default Preview Configuration Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Sets the default configuration for Storybook's preview file (.storybook/preview.js). This includes defining parameters for actions and controls, which are essential for Storybook's interactive features. ```javascript // .storybook/preview.js - Default configuration export default { parameters: { actions: { argTypesRegex: '^on[A-Z].*' }, controls: { matchers: { color: /(background|color)$/i, date: /Date$/ } } } }; ``` -------------------------------- ### TypeScript: Storybook Build Process Functions Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Core TypeScript functions for managing Git operations and Storybook builds. Includes cleaning previous builds, checking out specific commits, building the Storybook, and preparing the output directory. Dependencies include 'fs' and shell commands via '$'. ```typescript import fs from 'fs-extra'; // Clean previous builds const cleanPreviousBundle = async (directory: string): Promise => { fs.removeSync(directory); }; // Checkout specific commit const checkoutCommit = async (commit: string): Promise => { await $`git fetch origin`; await $`git checkout ${commit}`; await $`git submodule update --init`; // Handle submodules }; // Build Storybook for current branch const buildStorybook = async (scriptName?: string): Promise => { await $`npm run ${scriptName ?? 'build-storybook'}`.pipe(process.stdout); }; // Copy built Storybook to bundle directory const prepareStorybook = async (from: string, to: string): Promise => { fs.cpSync(from, to, { recursive: true }); }; ``` -------------------------------- ### Configure Storybook for Subpath Hosting (.storybook/preview.js) Source: https://github.com/utarwyn/storybook-branch-switcher/blob/main/README.md This snippet shows how to modify the `.storybook/preview.js` file to enable subpath hosting for Storybook. It conditionally sets the 'branches.hostname' parameter based on the STORYBOOK_PUBLISH_FOR_WEB environment variable, allowing for custom deployment paths like GitHub Pages. ```javascript /** @type { import('@storybook/react').Preview } */ const preview = { parameters: { controls: { matchers: { color: /(background|color)$/i, date: /Date$/ } }, }, }; /* Any envvar prefixed with STORYBOOK_ will be available in the built storybook, ie. preview.js * See: https://storybook.js.org/docs/configure/environment-variables * * Set STORYBOOK_PUBLISH_FOR_WEB=true in your build environment, along with the * domain and path you'd like to host from. */ if (process.env["STORYBOOK_PUBLISH_FOR_WEB"]) { preview.parameters = { branches: { hostname: `your-username.github.io/your-repo` } } } export default preview; ``` -------------------------------- ### Custom Branch Provider Implementation (TypeScript) Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Demonstrates how to implement a custom branch provider for integrating with other Git hosting services. It defines the necessary interface, applicability check, and a fetcher function to retrieve branch data. ```typescript // src/run/providers/custom-provider.ts import type { ProviderConfig } from '../../cli'; import type { BranchProvider } from './index'; export interface CustomProviderConfig extends ProviderConfig { type: 'custom'; url: string; projectKey: string; } const isApplicable = (config: CustomProviderConfig) => config.type === 'custom' && config.projectKey != null; const fetcher = async (config: CustomProviderConfig) => { const response = await fetch(`${config.url}/api/branches/${config.projectKey}`, { headers: { 'Authorization': `Bearer ${$.env['CUSTOM_TOKEN']}` } }); if (!response.ok) { throw new Error(`Fetch failed: ${response.status} ${response.statusText}`); } const data = await response.json(); return data.branches.map((branch: any) => ({ id: branch.name, commit: branch.sha })); }; const provider: BranchProvider = { isApplicable, fetcher }; export default provider; ``` -------------------------------- ### Register Storybook Addon Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Registers the 'storybook-branch-switcher' addon in the Storybook configuration file (.storybook/main.js). This allows Storybook to recognize and utilize the addon's features. ```javascript // .storybook/main.js module.exports = { stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'], addons: [ '@storybook/addon-essentials', 'storybook-branch-switcher' ], framework: '@storybook/react', core: { builder: '@storybook/builder-vite' } }; ``` -------------------------------- ### Configure Storybook to use the Branch Switcher Addon Source: https://github.com/utarwyn/storybook-branch-switcher/blob/main/README.md JavaScript code to add the 'storybook-branch-switcher' to the list of addons in your Storybook configuration file (.storybook/main.js). This enables the addon's functionality within Storybook. ```javascript module.exports = { addons: ["storybook-branch-switcher"], }; ``` -------------------------------- ### Storybook Subpath Hosting Configuration Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt Configures Storybook for hosting in a subpath, commonly used for deployments like GitHub Pages. It conditionally sets the 'branches.hostname' parameter based on an environment variable, enabling correct URL resolution for different branches. ```javascript // .storybook/preview.js - Subpath hosting example const preview = { parameters: { controls: { matchers: { color: /(background|color)$/i, date: /Date$/ } } } }; // Configure for GitHub Pages deployment if (process.env['STORYBOOK_PUBLISH_FOR_WEB']) { preview.parameters = { ...preview.parameters, branches: { hostname: 'your-username.github.io/your-repo' } }; } export default preview; ``` -------------------------------- ### Branch Link Generation Utility (TypeScript) Source: https://context7.com/utarwyn/storybook-branch-switcher/llms.txt An internal utility function for generating URLs to switch between different branch-specific Storybook instances. It handles constructing the correct path based on whether the target branch is the default branch. ```typescript // Internal utility for generating branch URLs const generateLink = ( location: Location, targetHost: string, defaultBranch: string, targetBranch: string ): string => { const hostname = targetHost || `${location.hostname}:${location.port}`; let path: string; // Default branch goes to root, others to subdirectories if (targetBranch !== defaultBranch) { path = `/${targetBranch}/`; } else { path = '/'; } return `${location.protocol}//${hostname}${path}${location.search}${location.hash}`; }; // Example usage in deployed environment // Current: https://storybook.example.com/PR-123/?path=/story/button--primary // Clicking "main" branch generates: https://storybook.example.com/?path=/story/button--primary // Clicking "PR-456" generates: https://storybook.example.com/PR-456/?path=/story/button--primary ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.