{"id":31497685,"url":"https://github.com/productive-codebases/build-variants","last_synced_at":"2025-10-02T15:44:51.198Z","repository":{"id":41187159,"uuid":"508011386","full_name":"productive-codebases/build-variants","owner":"productive-codebases","description":"Declare and compose styles variants with ease.","archived":false,"fork":false,"pushed_at":"2025-03-10T16:50:23.000Z","size":631,"stargazers_count":6,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-09-10T11:03:02.904Z","etag":null,"topics":["css","css-in-js","design-system","react","styled-components","styling","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/productive-codebases.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-06-27T17:58:33.000Z","updated_at":"2025-03-10T16:50:25.000Z","dependencies_parsed_at":"2024-12-16T03:30:21.370Z","dependency_job_id":"90b5c9f9-0877-457c-a3d1-f8ed2047462d","html_url":"https://github.com/productive-codebases/build-variants","commit_stats":null,"previous_names":["cr0ck/build-variants"],"tags_count":12,"template":false,"template_full_name":null,"purl":"pkg:github/productive-codebases/build-variants","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/productive-codebases%2Fbuild-variants","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/productive-codebases%2Fbuild-variants/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/productive-codebases%2Fbuild-variants/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/productive-codebases%2Fbuild-variants/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/productive-codebases","download_url":"https://codeload.github.com/productive-codebases/build-variants/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/productive-codebases%2Fbuild-variants/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":276274278,"owners_count":25614380,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-21T02:00:07.055Z","response_time":72,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["css","css-in-js","design-system","react","styled-components","styling","typescript"],"created_at":"2025-10-02T15:44:50.553Z","updated_at":"2025-10-02T15:44:51.191Z","avatar_url":"https://github.com/productive-codebases.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Build-variants\n\nDeclaratively build style objects based on your React component props with a clean, type-safe API.\n\n---\n\n## Introduction\n\n**Build-variants** helps you organize and compose CSS (or any style values) based on component props. It separates styling logic from component logic, making your code easier to maintain and extend. Note that it is a *builder*—it doesn’t apply styles by itself but returns an object your CSS-in-JS library can use.\n\n---\n\n## Installation\n\n```bash\nnpm install @productive-codebases/build-variants\n```\n\n---\n\n## Usage\n\n### 1. Setup Your Factory Function\n\nConfigure **build-variants** with your styling engine. For example, with _styled-components_:\n\n```ts\nimport type { CSSObject } from '@emotion/react'\nimport { newBuildVariants } from '@productive-codebases/build-variants'\n\nexport function buildVariants\u003cTProps extends object\u003e(props: TProps) {\n  return newBuildVariants\u003cTProps, CSSObject\u003e(props)\n}\n```\n\n*This sets up a function that accepts props and returns a builder configured for CSSObject objects.*\n\n---\n\n### 2. Decorate a Component\n\nIntegrate the builder with any styled function that accepts a CSSObject-like object. Whether you're using Emotion, styled-components, MUI, or any other library, the generated style object will work seamlessly.\n\n```tsx\nimport styled from '@emotion/styled'\n// Alternatively:\n// import styled from 'styled-components'\n// or import { styled } from '@mui/material', etc.\nimport { buildVariants } from './buildVariants'\n\nconst Div = styled.div(props =\u003e buildVariants(props).end())\n\nexport default function Button() {\n  return \u003cDiv\u003eMy Button\u003c/Div\u003e\n}\n```\n\n*In this example, no extra styles are added; the builder returns an empty style object.*\n\n---\n\n### 3. Adding CSS Blocks\n\nChain CSS blocks to add styles:\n\n```ts\nconst Div = styled.div(props =\u003e {\n  return buildVariants(props)\n    .css({\n      display: 'inline-block',\n      padding: '10px'\n    })\n    .css({\n      background: 'blue',\n      color: 'white'\n    })\n    .end()\n})\n```\n\n**Applied styles:**\n- `display: inline-block`\n- `padding: 10px`\n- `background: blue`\n- `color: white`\n\n---\n\n### 4. Declaring Variants\n\n#### Simple Variant\n\nDefine a style variant based on a prop value:\n\n```tsx\nimport styled from '@emotion/styled'\nimport { buildVariants } from './buildVariants'\n\ninterface IButtonProps {\n  type: 'primary' | 'secondary'\n}\n\nconst Div = styled.div\u003cIButtonProps\u003e(props =\u003e {\n  return buildVariants(props)\n    .css({\n      display: 'inline-block',\n      padding: '10px'\n    })\n    .variant('type', props.type, {\n      primary: {\n        background: 'blue',\n        color: 'white'\n      },\n      secondary: {\n        background: 'silver',\n        color: 'black'\n      }\n    })\n    .end()\n})\n\nexport default function Button(props: IButtonProps) {\n  return \u003cDiv type={props.type}\u003eMy Button\u003c/Div\u003e\n}\n```\n\n**Applied styles:**\n\n- **When `type=\"primary\"`:**\n  - Common: `display: inline-block`, `padding: 10px`\n  - Variant: `background: blue`, `color: white`\n\n- **When `type=\"secondary\"`:**\n  - Common: `display: inline-block`, `padding: 10px`\n  - Variant: `background: silver`, `color: black`\n\n---\n\n#### Multiple Variants\n\nAllow multiple variant values (e.g., text styles):\n\n```tsx\ninterface IButtonProps {\n  type: 'primary' | 'secondary'\n  text?: Array\u003c'strong' | 'success' | 'error'\u003e\n}\n\nconst Div = styled.div\u003cIButtonProps\u003e(props =\u003e {\n  return buildVariants(props)\n    .css({\n      display: 'inline-block',\n      padding: '10px'\n    })\n    .variant('type', props.type, {\n      primary: {\n        background: 'blue',\n        color: 'white'\n      },\n      secondary: {\n        background: 'silver',\n        color: 'black'\n      }\n    })\n    .variants('text', props.text, {\n      strong: { fontWeight: 'bold' },\n      success: { color: 'green' },\n      error: { color: 'red' }\n    })\n    .end()\n})\n```\n\nUsage example:\n\n```tsx\n// Renders a primary button with both bold and red text styles\n\u003cButton type=\"primary\" text={['strong', 'error']} /\u003e\n```\n\n**Applied styles:**\n\n- **Type \"primary\":** `background: blue`, `color: white`\n- **Text variants:**\n  - `strong` adds `fontWeight: bold`\n  - `error` adds `color: red`\n*Note: In case of conflicting styles (like two colors), the later applied style wins.*\n\n---\n\n#### Compound Variants\n\nCompose multiple variants using private (internal) and public (external) props:\n\n```tsx\ninterface IButtonProps {\n  // Private variants (used for composing public ones)\n  _background?: 'primary' | 'secondary' | 'success' | 'error'\n  _text?: Array\u003c'dark' | 'light' | 'success' | 'error' | 'strong'\u003e\n  // Public variant: the component's API\n  type: 'primary' | 'secondary' | 'success' | 'error'\n  children: string\n}\n\nconst Div = styled.div\u003cIButtonProps\u003e(props =\u003e {\n  return buildVariants(props)\n    .css({\n      display: 'inline-block',\n      padding: '10px'\n    })\n    // Define private variants first.\n    .variant('_background', props._background, {\n      primary: { background: 'blue' },\n      secondary: { background: 'silver' },\n      success: { background: '#eaff96' },\n      error: { background: '#ffdbdb' }\n    })\n    .variants('_text', props._text, {\n      dark: { color: 'black' },\n      light: { color: 'white' },\n      success: { color: 'green' },\n      error: { color: 'red' },\n      strong: { fontWeight: 'bold' }\n    })\n    // Define compound variants mapping public 'type' to private ones.\n    .compoundVariant('type', props.type, {\n      primary: builder_ =\u003e\n        builder_.get('_background', 'primary').get('_text', ['light']).end(),\n      secondary: builder_ =\u003e\n        builder_.get('_background', 'secondary').get('_text', ['dark']).end(),\n      success: builder_ =\u003e\n        builder_.get('_background', 'success').get('_text', ['success']).end(),\n      error: builder_ =\u003e\n        builder_\n          .get('_background', 'error')\n          .get('_text', ['error', 'strong'])\n          .css({ border: '1px solid red' })\n          .end()\n    })\n    .end()\n})\n```\n\nUsage examples:\n\n```tsx\n\u003cButton type=\"primary\"\u003ePrimary button\u003c/Button\u003e\n\u003cButton type=\"secondary\"\u003eSecondary button\u003c/Button\u003e\n\u003cButton type=\"success\"\u003eSuccess button\u003c/Button\u003e\n\u003cButton type=\"error\"\u003eError button\u003c/Button\u003e\n```\n\n**Applied styles:**\n\n- **Primary:**\n  - Private `_background: primary` → `background: blue`\n  - Private `_text: ['light']` → `color: white`\n\n- **Secondary:**\n  - Private `_background: secondary` → `background: silver`\n  - Private `_text: ['dark']` → `color: black`\n\n- **Success:**\n  - Private `_background: success` → `background: #eaff96`\n  - Private `_text: ['success']` → `color: green`\n\n- **Error:**\n  - Private `_background: error` → `background: #ffdbdb`\n  - Private `_text: ['error', 'strong']` → `color: red` and `fontWeight: bold`\n  - Additional style: `border: 1px solid red`\n\n---\n\n### 5. Overriding with Private Variants\n\nPrivate variants have a higher precedence than public ones, allowing you to override the default behavior for specific use cases.\n\n```tsx\n\u003cButton type=\"error\"\u003eError button\u003c/Button\u003e\n\n\u003cButton type=\"error\" _background=\"success\"\u003e\n  Error button with success background\n\u003c/Button\u003e\n```\n\n**Applied styles:**\n- The first button applies the default compound variant for `error`.\n- The second button overrides the `_background` variant to `\"success\"`, so it receives `background: #eaff96` (as defined in the success mapping) while keeping the other error-related styles.\n\n---\n\n### 6. Conditional Blocks\n\nEnable or skip blocks of styles based on a condition:\n\n```tsx\nconst Div = styled.div\u003cIButtonProps\u003e(props =\u003e {\n  return buildVariants(props)\n    // Other style blocks…\n    .if(props.applyTextVariant === true, builder_ =\u003e {\n      return builder_\n        .variants('_text', props._text, {\n          dark: { color: 'black' },\n          light: { color: 'white' },\n          success: { color: 'green' },\n          error: { color: 'red' },\n          strong: { fontWeight: 'bold' }\n        })\n        .end()\n    })\n\n    // Alternatively, if you only need to add simple CSS:\n    // .if(props.applyTextVariant === true, {\n    //   color: 'red'\n    // })\n\n    .compoundVariant('type', props.type, {\n      // …\n    })\n    .end()\n})\n```\n\n**Applied styles:**\n- If `applyTextVariant` is true, the text-related styles are applied. Otherwise, they are skipped.\n\n---\n\n### 7. Blocks Weight\n\nControl the order of style application by assigning a weight to each block:\n\n```ts\nconst Div = styled.div\u003cIButtonProps\u003e(props =\u003e {\n  return buildVariants(props)\n    .css({\n      display: 'inline-block',\n      padding: '10px'\n    })\n    .css(\n      { color: 'silver' },\n      { weight: 10 }  // This block is applied later.\n    )\n    .variants('_text', props._text, {\n      dark: { color: 'black' },\n      // …\n    })\n    .end()\n})\n```\n\n**Applied styles:**\n- The `color: silver` style with weight 10 overrides any earlier conflicting `color` from `_text` if applied later.\n\n---\n\n### 8. Debugging\n\nLog internal builder state to help diagnose complex style applications:\n\n```tsx\nconst Div = styled.div\u003cIButtonProps\u003e(props =\u003e {\n  return buildVariants(props)\n    // Other style definitions…\n    .debug()\n    .end()\n})\n```\n\nOr enable debugging conditionally:\n\n```tsx\ninterface IButtonProps {\n  debug?: boolean\n}\n\nconst Div = styled.div\u003cIButtonProps\u003e(props =\u003e {\n  return buildVariants(props)\n    // Other style definitions…\n    .debug(props.debug === true)\n    .end()\n})\n```\n\n**Result:** Detailed logs in the console show which styles are applied and the builder's internal state.\n\n---\n\n## Examples\n\n- https://codesandbox.io/s/1-init-b5t24e?file=/src/buildVariants.ts\n- https://codesandbox.io/s/1-init-b5t24e?file=/src/Button.tsx\n- https://codesandbox.io/s/2-add-css-0zmimn?file=/src/Button.tsx\n- https://codesandbox.io/s/3-add-variant-9b3bvh?file=/src/Button.tsx\n- https://codesandbox.io/s/4-multiple-variants-v9bxds?file=/src/Button.tsx\n- https://codesandbox.io/s/5-variants-composition-m6b5zs?file=/src/Button.tsx\n- https://codesandbox.io/s/overrides-with-private-variants-w72ed1?file=/src/App.tsx\n- https://codesandbox.io/s/7-condition-blocks-0xko7x?file=/src/Button.tsx\n- https://codesandbox.io/s/8-blocks-weight-d0fbz3?file=/src/Button.tsx\n- https://codesandbox.io/s/9-debug-f6ozbu?file=/src/Button.tsx:463-2386\n\n---\n\n## Summary\n\nBuild-variants empowers you to:\n- **Declare and compose style variants** with a clean, declarative, and type-safe API.\n- **Separate styling logic** from component code.\n- **Support multiple, compound, and conditional variants** for flexible component design.\n- **Control style precedence** with block weights.\n- **Debug** style composition effortlessly.\n\nEnjoy building maintainable, flexible UI components with Build-variants!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fproductive-codebases%2Fbuild-variants","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fproductive-codebases%2Fbuild-variants","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fproductive-codebases%2Fbuild-variants/lists"}