{"id":13495135,"url":"https://github.com/mrmartineau/design-system-utils","last_synced_at":"2025-05-16T13:03:49.919Z","repository":{"id":57211973,"uuid":"102257345","full_name":"mrmartineau/design-system-utils","owner":"mrmartineau","description":"👩‍🎨 Access your design tokens with ease","archived":false,"fork":false,"pushed_at":"2020-03-06T05:37:05.000Z","size":1428,"stargazers_count":542,"open_issues_count":12,"forks_count":13,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-04-12T06:18:56.282Z","etag":null,"topics":["css-in-js","design-tokens","emotion","preact","react","styled-components","tokens","typescript"],"latest_commit_sha":null,"homepage":"https://zander.wtf","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/mrmartineau.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-09-03T10:39:18.000Z","updated_at":"2025-04-03T10:54:37.000Z","dependencies_parsed_at":"2022-09-05T23:30:40.860Z","dependency_job_id":null,"html_url":"https://github.com/mrmartineau/design-system-utils","commit_stats":null,"previous_names":[],"tags_count":27,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrmartineau%2Fdesign-system-utils","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrmartineau%2Fdesign-system-utils/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrmartineau%2Fdesign-system-utils/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mrmartineau%2Fdesign-system-utils/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mrmartineau","download_url":"https://codeload.github.com/mrmartineau/design-system-utils/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248525140,"owners_count":21118620,"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","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-in-js","design-tokens","emotion","preact","react","styled-components","tokens","typescript"],"created_at":"2024-07-31T19:01:31.457Z","updated_at":"2025-04-12T06:19:02.590Z","avatar_url":"https://github.com/mrmartineau.png","language":"TypeScript","funding_links":[],"categories":["TypeScript","Tools","CSS-in-JS","Libraries"],"sub_categories":["Collections"],"readme":"\u003ch1 align=\"center\"\u003e\n  👩‍🎨 \u003cbr/\u003e\n  Design System Utils\n\n[![npm](https://img.shields.io/npm/v/design-system-utils.svg?style=flat-square)](https://www.npmjs.com/package/design-system-utils)\n[![npm bundle size (minified + gzip)](https://img.shields.io/bundlephobia/minzip/design-system-utils.svg?style=flat-square)](https://www.npmjs.com/package/design-system-utils) [![Travis CI Build](https://img.shields.io/travis/mrmartineau/design-system-utils.svg?style=flat-square)](https://travis-ci.org/mrmartineau/design-system-utils)\n![](https://img.shields.io/badge/licence-MIT-blue.svg?style=flat-square)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)\n\n\u003c/h1\u003e\n\nDesign System Utils is a micro framework that standardises your design-system tokens \u0026 provides helpful utility functions to access the information. It can be used with [styled-components](https://styled-components.com), [emotion](https://emotion.sh), [glamorous](https://glamorous.rocks/) or any other [CSS-in-JS framework](https://css-in-js-playground.com/).\n\n## Install\n\n```sh\nyarn add design-system-utils\n\n# or\n\nnpm install --save design-system-utils\n```\n\n### Size\n\n```\n$ size-limit\n\n  build/cjs.js\n  Package size: 814 B\n  Size limit:   1 KB\n\n  es/index.js\n  Package size: 806 B\n  Size limit:   1 KB\n\n  With all dependencies, minified and gzipped\n```\n\n\u003cdetails\u003e\n  \u003csummary\u003e🤓 Table of contents\u003c/summary\u003e\n\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n\n\n- [Usage](#usage)\n  - [Setup](#setup)\n  - [Initialise the design system framework](#initialise-the-design-system-framework)\n- [Accessing the design system data in your app](#accessing-the-design-system-data-in-your%C2%A0app)\n- [Options](#options)\n- [Basic API methods](#basic-api-methods)\n  - [`tokens.get()` - Get a token value](#tokensget---get-a-token-value)\n  - [`tokens.set()` - Set a token value](#tokensset---set-a-token-value)\n- [API helper methods](#api-helper-methods)\n  - [`tokens.fontSize()` or `tokens.fs()` - Get font-size values](#tokensfontsize-or-tokensfs---get-font-size-values)\n    - [Modular scale](#modular-scale)\n  - [Color palette](#color-palette)\n    - [`tokens.color()` - Get color palette values](#tokenscolor---get-color-palette-values)\n    - [`tokens.brand()` - Get brand palette values](#tokensbrand---get-brand-palette-values)\n  - [`tokens.bp()` - Get responsive breakpoint values](#tokensbp---get-responsive-breakpoint-values)\n  - [`tokens.z()` - Get `z-index` values](#tokensz---get-z-index-values)\n  - [`tokens.spacing()` or `tokens.space()` - Get spacing values](#tokensspacing-or-tokensspace---get-spacing-values)\n    - [Array example:](#array-example)\n    - [Object example:](#object-example)\n  - [Calculations](#calculations)\n    - [`tokens.multiply()`](#tokensmultiply)\n    - [`pxTo()`](#pxto)\n    - [`toPx()`](#topx)\n    - [`parseUnit()`](#parseunit)\n- [Usage with Typescript](#usage-with-typescript)\n- [Aliases](#aliases)\n- [Demo \u0026 examples](#demo--examples)\n- [Licence](#licence)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\n\u003c/details\u003e\n\n## Usage\n\nFirst create your design system file, this contains all your design tokens that your app or site will use; things like font-sizes, color palette, spacing etc (kind of like a Sass/Less variables file).\n\nFor example you can create a top-level directory named `tokens`, `theme` or `designsystem`, and add an index.js inside, like so:\n\n```\n./tokens\n└── index.js\n```\n\nA simple version of a tokens file with Design System Utils:\n\n```js\n// ./tokens/index.js\nimport DesignSystem from 'design-system-utils'\n\n// your design tokens object goes here, see below for further details\nconst designTokens = {...}\n\nexport default new DesignSystem(designTokens)\n```\n\n### Setup\n\nThe \"shape\" and structure of your design tokens object **_can_** actually be anything you want, however, if you want to make use of the shortcut/helper methods like `tokens.fontSize|bp|z|color|brand|spacing` etc, there is a particular shape that your data will need to follow, see below:\n\n(🤔 the below code snippet includes some psuedo types for the values that occur in the different parts of the tokens object)\n\n```js\n{\n  type: {\n    // this should be set as a px value if you have `options.fontSizeUnit` set\n    // to 'rem' or 'em' so that the lib can convert the values properly\n    baseFontSize: '' // string,\n\n    // used with `tokens.fs('size')` or `tokens.fontSize('size')`\n    sizes: {\n      key: '' // \u003cnumber | string\u003e,\n    },\n  },\n\n  // Color palette\n  // Each object needs to have the same shape\n  // Each color object needs a `base` value to be the default\n  // Have as many color objects as you like\n  colors: {\n    // Used with `ds.color('colorName')`\n    colorPalette: {\n      colorName: {\n        base: '' // \u003cstring\u003e, // base is the default\n      },\n    },\n\n    // Used with `ds.brand('colorName)`\n    brand: {\n      colorName: '' // \u003cstring\u003e, base is the default\n    }\n  },\n\n  // Breakpoints\n  // Used with `ds.bp()`\n  // Keys can be anything you like\n  // Have as many breakpoints as you like\n  // Values can be use any unit you like\n  breakpoints: {\n    key: '' // \u003cnumber | string\u003e,\n  },\n\n  // Z-index\n  // Used with `ds.z()`\n  zIndex: {\n    key: 10 // \u003cnumber\u003e\n  },\n\n  // Spacing\n  // Used with `ds.spacing()` or `ds.space()`\n  spacing: {\n    scale: [] // \u003carray\u003e[\u003cnumber | string\u003e, ...], \u003cobject\u003e\n  },\n}\n```\n\nBelow is an excerpt from the example design-system. See a more complete version in the [`/example`](example/myDesignSystem.js) directory or some that are used in the design-system-utils tests: [1](https://github.com/mrmartineau/design-system-utils/blob/master/src/testData/ds1.js) \u0026 [2](https://github.com/mrmartineau/design-system-utils/blob/master/src/testData/ds1.js).\n\n```js\nconst designTokens = {\n  type: {\n    baseFontSize: '20px',\n\n    sizes: {\n      xs: '16px',\n      s: '20px',\n      base: '30px',\n      m: '36px',\n      l: '42px',\n      xl: '50px',\n      xxl: '58px',\n    },\n\n    fontFamily: {\n      system:\n        '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, \"Fira Sans\", \"Droid Sans\"',\n      sans: '\"Helvetica Neue\", Helvetica, Arial, sans-serif',\n      serif: 'Georgia, \"Times New Roman\", Times, serif',\n      mono: 'Menlo, Monaco, \"Courier New\", monospace',\n    },\n\n    lineHeight: {\n      headings: 1.1,\n    },\n\n    fontWeight: {\n      normal: 300, // Useful to set here if using anything other than `normal`\n      bold: 'bold', // Useful to set here when bold webfonts come as 400 font-weight.\n      headings: 'bold', // instead of browser default, bold\n    },\n  },\n}\n```\n\n### Initialise the design system framework\n\n```js\n// myDesignSystem.js\nimport DesignSystem from 'design-system'\nconst designTokens = {...}\nexport default new DesignSystem(designTokens)\n```\n\n## Accessing the design system data in your app\n\nTo access your design system, you just need to `import` it to the current file, like so:\n\n```js\nimport tokens from './tokens' // assuming you exported `default` from your design system file\n```\n\nHere is a very simple component using [styled-components](https://styled-components.com) and some values from the tokens, you should be able to see how easy it is to pull information from the design system.\n\n```js\n// Example using styled-components\nimport styled from 'styled-component'\nimport tokens from './tokens'\n\nexport const Box = styled.div`\n  font-family: ${tokens.get('type.fontFamilyBase')};\n  background-color: ${tokens.brand('primary')};\n  margin: ${tokens.space(2)} 0;\n`\n```\n\n## Options\n\nThere is only one option that can be passed to your design system class, it relates to font-sizing:\n\n```js\n// Use default options. do not convert the font-sizes to rems or ems\nexport default new DesignSystem(myDesignSystem)\n\n// OR: with custom options\nexport default new DesignSystem(myDesignSystem, {\n  // this is used to convert your `type.sizes` values from one unit to another\n  // e.g. to convert all `px` sizes  to `rem`, set this option:\n  fontSizeUnit: 'rem',\n  // this means you can define values using px and use rems in your app\n})\n```\n\n## Basic API methods\n\n### `tokens.get()` - Get a token value\n\nThe `tokens.get()` function can be used to get any value from the design-system. Use object dot notation to find the value you need from your design system object.\n\n```js\n// with the system setup, as above\ntokens.get('lineHeight.headings') // 1.1\ntokens.get('a.really.deeply.nested.value')\n```\n\n### `tokens.set()` - Set a token value\n\nThe `tokens.set()` function can be used to set tokens values. This means you can overwrite existing items, or create new items that are specific to your application.\n\nLike the `.get()` method, use object dot notation to find the value you need from your design system object.\n\nThis method uses [dset](https://github.com/lukeed/dset#usage) under the hood, so please read the docs there for more info.\n\n```js\n// with the system setup, as above\ntokens.set('forms.inputBackground', '#fff')\n\n// then use it later like so:\ntokens.get('forms.inputBackground')\n```\n\n## API helper methods\n\nThe helper methods make getting values _much_ more simple.\n\n- [`tokens.fontSize()` or `tokens.fs()`](#tokensfontsize-or-tokensfs---get-font-size-values) - Get font-size values\n- [`tokens.color()`](#tokenscolor---get-color-palette-values) - Get color palette values\n- [`tokens.brand()`](#tokensbrand---get-brand-palette-values) - Get brand palette values\n- [`tokens.bp()`](#tokensbp---get-responsive-breakpoint-values) - Get responsive breakpoint values\n- [`tokens.z()`](#tokensz---get-z-index-values) - Get `z-index` values\n- [`tokens.spacing()` or `tokens.space()`](#tokensspacing-or-tokensspace---get-spacing-values) - Get spacing values\n\n### `tokens.fontSize()` or `tokens.fs()` - Get font-size values\n\nThe `tokens.fontSize()` method is a short-hand for the `tokens.get()` method. It can be used to get a value from the `type.sizes` object.\n\nThe `type.sizes` object’s values can be formatted in a few ways:\n\n- as a string with any unit of measurement, e.g. `s: '13px'` / `px`, `rem` or `em`\n- as a template string using another function to calculate font-sizes, for example a modular-scale, e.g. `${ms(0, modularscale)}px`. **Note: this uses an external package, [modularscale-js](https://github.com/modularscale/modularscale-js)**\n\n```js\n// define some values// type.sizes object\nsizes: {\n  xs: '16px',\n  s: '20px',\n  base: '30px',\n  m: '36px',\n  l: '42px',\n  xl: '50px',\n  xxl: '58px',\n},\n\n// retrieve some values\ntokens.fontSize('xl')\ntokens.fs('xl') // `tokens.fs()` is a short-hand alias for `tokens.fontSize()`\ntokens.fs('xl', true) // return font-size in px regardless of `option.fontSizeUnit` value\n```\n\n#### Modular scale\n\n**Note: v0.x.x had modular scale functionality built-in, in v1.x.x, this has been removed to reduce file-size for those that don't need a modular scale.**\n\nTo make use of a modular scale, there are a few things that need to be done:\n\n- install a modular scale converter package, like [modularscale-js](https://github.com/modularscale/modularscale-js)\n- define your modular scale options outside of your design-system object\n- add the modular scale values to the `type.sizes` object\n\n```js\nconst modularscale = {\n  base: [30],\n  ratio: 1.5,\n}\n\n// design system\n...\nsizes: {\n  xs: `${ms(-2, modularscale)}px`,\n  s: `${ms(-1, modularscale)}px`,\n}\n...\n```\n\nTesting and remembering the values from your modular scale can be tricky, there are two options that can be used, either:\n\n- visit [modularscale.com](https://modularscale.com) and enter your settings, you can then view all the type sizes on the scale you specified\n- or, add the below snippet to your code to print out the values of your scale:\n\n```js\nconst sizes = tokens.get('type.sizes')\nObject.keys(sizes).forEach(item =\u003e {\n  console.log(item, ':', sizes[item]) // e.g. `base : 20px`\n})\n```\n\n### Color palette\n\nThere are two possible ways to access color information: the color palette and the brand colors.\n\nThe color palette is intended to contain all the colors (and their shades) that your app will use, and the brand palette _should_ contain the specific colors that your brand uses.\n\nTwo methods can be used to retrieve the values, these are: `tokens.color()` and `tokens.brand()`, below is what the data looks like for them:\n\n```js\ncolors: {\n  // With a color palette like this:\n  colorPalette: {\n    bright: {\n      base: '#F9FAFB',\n      dark: '#F4F6F8',\n      darker: '#DFE4E8',\n    },\n\n    dark: {\n      base: '#212B35',\n      light: '#454F5B',\n      lighter: '#637381',\n    },\n  },\n\n  // With a brand palette like this:\n  brand: {\n    red: '#e82219',\n    deeporange: '#ff7200',\n    orange: '#ff9500',\n    green: '#c4d000',\n    teal: '#1aa5c8',\n    navy: '#0052da',\n  }\n},\n```\n\n#### `tokens.color()` - Get color palette values\n\nThe `tokens.color()` function gets values from the `colorPalette` object. It assumes every color has a `base` property and other properties for different shades of the same color.\nThis is a short-hand for the `tokens.get()` function.\n\n```js\n// Get values like this:\ntokens.color('bright') // #F9FAFB - the `base` key is the default, so it is not needed\ntokens.color('bright', 'dark')\ntokens.color('background.extra.dark') // Accepts a path (in this case the second `variant` argument is ignored)\n```\n\n#### `tokens.brand()` - Get brand palette values\n\nThe `tokens.brand()` function gets values from the `colors.brand` object.\nThis is a short-hand for the `tokens.get()` function.\n\n```js\n// Get brand values like this:\ntokens.brand('orange')\ntokens.brand('pink')\ntokens.brand('primary.blue') // it is possible to nest this object as much as you like\n```\n\n### `tokens.bp()` - Get responsive breakpoint values\n\nThe `tokens.bp()` method is a short-hand for the `tokens.get()` method. It can be used to get a breakpoint from the `breakpoints` object.\n\n```js\ntokens.bp('m')\n```\n\n### `tokens.z()` - Get `z-index` values\n\nThe `tokens.z()` method is a short-hand for the `tokens.get()` method. It can be used to get a breakpoint from the `zIndex` object.\n\n```js\ntokens.z('low')\n```\n\n### `tokens.spacing()` or `tokens.space()` - Get spacing values\n\nThe `tokens.spacing()` method returns a value from your `spacing.scale` definition. **The spacing data could either be an array, or an object.**\n\n- If an array, it takes an `index` (number) for that array e.g. `tokens.space(2)`. This variant adds `px` to the end of the string, this will be deprecated in v2.0.0.\n- If an object, it takes a `key` (string) for the item in that object e.g. `tokens.space('m')`\n\n#### Array example:\n\n```js\nscale: [0, 8, 16, 24, 32, 40]\n\ntokens.spacing(2) // '16px'\n// Note: `tokens.space(2)` can also be used\n```\n\n#### Object example:\n\n```js\nscale: {\n  s: '10rem',\n  m: '100rem',\n  l: '1000rem',\n}\n\ntokens.spacing('m') // '100rem'\n// Note: `tokens.space('m')` can also be used\n```\n\n### Calculations\n\nThe framework currently provides a few calculation functions, `multiply`, `toPx` and `pxTo`:\n\n#### `tokens.multiply()`\n\n```js\ntokens.multiply(10, 2) // 20\n\n// you can pass in another value from the system\ntokens.multiply(tokens.get('spacing.baseline'), 2)\n\n// or just use the key from the system\n// the initial value will always be run through `parseFloat()`\ntokens.multiply('spacing.baseline', 2)\n```\n\n#### `pxTo()`\n\nConverts `px` to `rem` or `em`\n\n```js\nimport { pxTo } from 'design-system-utils'\n// pxTo(fontSize, baseFontSize, unit - 'rem'/'em')\npxTo(12, 20, 'rem') // 0.6rem\npxTo(12, 20, 'em') // 0.6em\n```\n\n#### `toPx()`\n\nConverts `rem` or `em` value to `px`\n\n```js\nimport { toPx } from 'design-system-utils'\n// toPx(fontSize, baseFontSize)\ntoPx('1.875rem', 16) // 30px\ntoPx('1.875em', 16) // 30px\n```\n\n#### `parseUnit()`\n\nParses a number and unit string, and returns the unit used\n\n```js\nimport { parseUnit } from 'design-system-utils'\nparseUnit('1.875rem') // 'rem'\nparseUnit('18px') // 'px'\n```\n\n## Usage with Typescript\n\nTypescript types and interfaces should be imported as named imports.\n\nSee all the type definitions in the [types.ts](https://github.com/mrmartineau/design-system-utils/blob/master/src/types.ts) file. Here are all the exported types that can be extended:\n\n```\n{\n  System,\n  SystemOptions,\n  SystemBreakpoints,\n  SystemZIndex,\n  SystemFontSizes,\n  SystemSpacing,\n  SystemScale,\n  SystemColorPalette,\n  SystemBrandPalette,\n  SystemType,\n  SystemOptionalKey,\n}\n```\n\nBelow is an example where a new item (`baseline`) is added to the `spacing` object.\n\n```ts\nimport DesignSystem, { System, SystemOptions, SystemSpacing } from '../index'\n\ninterface MySystemSpacing extends SystemSpacing {\n  baseline: number\n}\n\ninterface MySystem extends System {\n  spacing: MySystemSpacing\n}\n\nconst Tokens: MySystem = {\n  ...\n  ...\n\n  spacing: {\n    scale: [0, 8, 16, 24, 32, 40],\n    baseline: 20,\n  },\n}\n\nexport default new DesignSystem\u003cMySystem, SystemOptions\u003e(Tokens)\n```\n\n## Aliases\n\nIf you'd prefer to rename the above methods, or even add your own getter methods, to access your design tokens, it is very simple. See below for an example:\n\n```js\nexport tokens from './tokens' // import your design tokens\n\n// create new alias functions\n\n// this renames .bp()\nexport const breakpoints = bp =\u003e tokens.bp(bp)\n\n// this adds a new alias that doesn't already exist in Design System Utils\nexport const fontWeights = weight =\u003e tokens.get('type.fontWeights')\n\n// the aliases can also be for specific values\nexport const baseFontSize = ds1.get('type.baseFontSize')\nexport const brandPrimary = ds1.brand('red')\n```\n\nThen use them like so:\n\n```js\nimport { breakpoints, fontWeights, baseFontSize, brandPrimary } from './tokens'\n\nbreakpoints('m')\nfontWeights('normal')\n```\n\nTake a look at [`alias.ts`](https://github.com/mrmartineau/design-system-utils/blob/master/src/alias.ts) and [`alias.test.ts`](https://github.com/mrmartineau/design-system-utils/blob/master/src/alias.test.ts) to see working examples and their usage.\n\n## Demo \u0026 examples\n\nI created a demo on [codesandbox.io](https://codesandbox.io/s/6wrp94x7kk), it includes examples of using the design-system utils with [emotion](https://emotion.sh/), [styled-components](https://www.styled-components.com/) and [glamorous](https://glamorous.rocks). There is also a basic example [here](example/).\n\n## Licence\n\nMIT \u0026copy; [Zander Martineau](https://zander.wtf)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmrmartineau%2Fdesign-system-utils","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmrmartineau%2Fdesign-system-utils","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmrmartineau%2Fdesign-system-utils/lists"}