/* eslint-env node */ import StyleDictionary from "style-dictionary"; import type { TransformedToken } from "style-dictionary"; import * as prettier from "prettier"; import { trim } from "./utils.js"; // https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src const MAP_EXT_TO_FORMAT_NAME = { woff2: "woff2", woff: "woff", ttf: "truetype", otf: "opentype", svg: "svg", eot: "embedded-opentype", }; interface FontAssetToken extends TransformedToken { attributes: { [key: string]: any; family: string; weight: string; style: string; }; formats: string[]; value: string; } function tokenIsFontAssetToken(token: TransformedToken): token is FontAssetToken { return token.attributes.category === "asset" && token.attributes.type === "font"; } StyleDictionary.registerFormat({ name: "font-face", formatter: ({ dictionary: { allTokens }, file }) => { const fontFaceRules = allTokens .filter(tokenIsFontAssetToken) .map((token) => { const { attributes: { family, weight, style }, formats, value: path, } = token; const urls = formats.map( (extension) => trim(` url("${process.env.ASSETS_BASE_PATH}/${path}.${extension}") format("${MAP_EXT_TO_FORMAT_NAME[extension]}") `), ).join(","); return trim(` @font-face { font-family: "${family}"; font-style: ${style}; font-weight: ${weight}; src: ${urls}; font-display: fallback; } `); }) .join("\n"); return prettier.format(` ${StyleDictionary.formatHelpers.fileHeader({ file })} ${fontFaceRules} * { font-family: "Source Sans Pro", sans-serif; } `, { parser: "css" }); }, });