npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@nclsndr/w3c-design-tokens-parser

v0.0.2

Published

a TypeScript implementation of the parser for the W3C Design Tokens Format Module specification

Downloads

150

Readme

W3C Design Tokens Parser

This package provides a TypeScript implementation of the parser for the W3C Design Tokens Format Module specification. It also includes several methods to work with the tokens and their values.

Installation

Using npm

$ npm install @nclsndr/w3c-design-tokens-parser

Using yarn

$ yarn add @nclsndr/w3c-design-tokens-parser

Using pnpm

$ pnpm add @nclsndr/w3c-design-tokens-parser

Usage

Parse an initial token tree

We start from a JSON parsed JavaScript object that represents a design token tree.

import { parseDesignTokens } from '@nclsndr/w3c-design-tokens-parser';

const tokens = {
  color: {
    $type: 'color',
    blue: {
      100: {
        $value: '#0d3181',
      },
    },
  },
};

const tokenTree = parseDesignTokens();

The TokenTree exposes various methods to either get the parse errors, the tokens, or work with the values of the tokens.

// Get errors
tokenTree.getErrors();

// Get a given token
tokenTree.getToken(['color', 'blue', 100]);
// with a type guard to help out the TS compiler
tokenTree.getTokenOfType('color', ['color', 'blue', 100]);

// Get tokens
tokenTree.getAllTokens();
tokenTree.getAllTokensByType('color');
// With a callback style
tokenTree.mapTokensByType('color', (token) => {
  // ...
});

// Get groups
tokenTree.getAllGroups();
tokenTree.getGroup(['color']);

Once we grabbed some tokens, we can use the Token methods to move further.

The most basic operation is to get the JSON value of a token. Let's take the following:

const tokens: JSONTokenTree = {
  color: {
    $type: 'color',
    blue: {
      $value: '#0000FF',
    },
    accent: {
      $value: '{color.blue}',
    },
    borderActive: {
      $value: '{color.accent}',
    },
  },
  border: {
    $type: 'border',
    active: {
      $value: {
        width: '1px',
        style: 'solid',
        color: '{color.borderActive}',
      },
    },
  },
};
const tokenTree = parseDesignTokens(tokens);

const fullyResolvedColorValues = tokenTree.mapTokensByType('color', (token) => {
  console.log(token.summary);

  return token.getJSONValue({
    resolveToDepth: Infinity,
    // resolveToDepth allows to resolve the token value to a certain depth.
    // resolveToDepth: -1 is equivalent to resolveToDepth: Infinity
  });
});
console.log(fullyResolvedColorValues); // [ '#0000FF', '#0000FF', '#0000FF' ]

const partiallyResolvedColorValues = tokenTree.mapTokensByType(
  'color',
  (token) => {
    return token.getJSONValue({
      resolveToDepth: 1, // resolving aliases up to 1 level
    });
  },
);
console.log(partiallyResolvedColorValues); // [ '#0000FF', '#0000FF', '{color.blue}' ]

Whenever we want to work with the value of a token, we need to consider all the potential forms the value might take. The token .getValueMapper() method provides an API to generalize the approach to the token values where most of them can be aliased at any point in the tree.

With a color, we might have a raw value or an alias reference.

const colorValues = tokenTree.mapTokensByType('color', (colorToken) => {
  return colorToken
    .getValueMapper()
    .mapScalarValue((scalarValue) => scalarValue.raw)
    .mapAliasReference(
      (aliasReference) =>
        `var(--${aliasReference.to.treePath.array.join('-')})`,
    )
    .unwrap();
});
console.log(colorValues); // [ '#0000FF', 'var(--color-blue)', 'var(--color-accent)' ]

With a border, we might have an alias reference or an object, which might contain an alias reference for each of its properties.

const borderValues = tokenTree.mapTokensByType('border', (token) => {
  return token
    .getValueMapper()
    .mapAliasReference((ref) => `var(--${ref.to.treePath.join('-')})`)
    .mapObjectValue((obj) =>
      obj.flatMap((value) => {
        const width = value.width
          .mapAliasReference((ref) => `var(--${ref.to.treePath.join('-')}`)
          .mapScalarValue((value) => value.raw)
          .unwrap();
        const style = value.style
          .mapAliasReference((ref) => `var(--${ref.to.treePath.join('-')}`)
          .mapScalarValue((value) => value.raw)
          .unwrap();
        const color = value.color
          .mapAliasReference((ref) => `var(--${ref.to.treePath.join('-')}`)
          .mapScalarValue((value) => value.raw)
          .unwrap();

        return [width, style, color].join(' ');
      }),
    )
    .unwrap();
});

console.log(borderValues); // [ '1px solid var(--color-borderActive' ]

In order to cut down the complexity of aliases one would have to resolve, the token .getValueMapper() methods takes a resolveAtDepth option, which can bring back the raw value of the token at a certain depth, as far as the referenced token exists.

const cssColorTokens = tokenTree.mapTokensByType('color', (colorToken) => {
  return {
    key: colorToken.name,
    value: colorToken
      .getValueMapper({
        resolveAtDepth: Infinity,
      })
      .mapScalarValue((scalarValue) => scalarValue.raw)
      .mapAliasReference(
        (aliasReference) =>
          `var(--${aliasReference.to.treePath.array.join('-')})`,
      )
      .unwrap(),
  };
});

API