Fantasticon

repository·master·Indexed 19 days ago

https://github.com/tancredi/fantasticon

A CLI tool and library for generating web-font icon kits from SVG files. It supports multiple font formats (eot, woff2, woff, ttf, svg) and generates associated assets including CSS, SCSS, SASS, HTML, JSON, and TypeScript types. It can be used as a global npm package or integrated into Node.js applications via the generateFonts API.

Tokens
5.2K
Snippets
18
Records
25
Agent score
78%

What's inside fantasticon

  1. How icon IDs and CSS selectors are generated

    master

    By default, icon names and CSS class names are generated from a slug of the relative path + basename of each .svg file found in the input directory. This allows you to organize icons into namespaces using folders.

    Example Structure:

    icons
    ├── logo.svg
    └── social
        └── facebook.svg

    Resulting Mapping:

    • Icon ID: logo $\rightarrow$ CSS Selector: .icon-logo (assuming prefix icon and tag i)
    • Icon ID: social-facebook $\rightarrow$ CSS Selector: .icon-social-facebook

    You can override this behavior by providing a getIconId function in your configuration file. The function receives an object containing:

    • basename: The filename without extension (e.g., 'foo').
    • relativeDirPath: The path relative to the input directory (e.g., 'sub/dir').
    • absoluteFilePath: The full absolute path.
    • relativeFilePath: The path relative to the input directory including filename (e.g., 'sub/dir/foo.svg').
    • index: The zero-based index of the icon.
  2. Configure Fantasticon with a configuration file

    master

    For advanced control (e.g., formatOptions, pathOptions, getIconId, templates), use a configuration file. Fantasticon searches for the following files in the working directory:

    .fantasticonrc, fantasticonrc, .fantasticonrc.json, fantasticonrc.json, .fantasticonrc.js, fantasticonrc.js.

    You can specify a custom path using the --config CLI flag.

    module.exports = {
      inputDir: './icons', // (required)
      outputDir: './dist', // (required)
      fontTypes: ['ttf', 'woff', 'woff2'],
      assetTypes: ['ts', 'css', 'json', 'html'],
      fontsUrl: '/static/fonts',
      formatOptions: {
        woff: {
          metadata: '...'
        },
        json: {
          indent: 2
        },
        ts: {
          types: ['constant', 'literalId'],
          singleQuotes: true,
          enumName: 'MyIconType',
          constantName: 'MY_CODEPOINTS'
        }
      },
      templates: {
        css: './my-custom-tp.css.hbs'
      },
      pathOptions: {
        ts: './src/types/icon-types.ts',
        json: './misc/icon-codepoints.json'
      },
      codepoints: {
        'chevron-left': 57344,
        'chevron-right': 57345
      },
      getIconId: ({ basename, relativeDirPath, absoluteFilePath, relativeFilePath, index }) => [
        index, 
        basename
      ].join('_')
    };
  3. Use the Fantasticon CLI

    master

    Fantasticon can be run from the command line to generate font sets from a directory of icons. The CLI accepts an optional [input-dir] argument and can be configured via command-line flags or a configuration file.

    Basic Usage:

    # Generate fonts from the current directory
    fantasticon
    
    # Generate fonts from a specific input directory
    fantasticon ./icons
    fantasticon [input-dir]
  4. Use the Fantasticon JavaScript API

    master

    You can integrate Fantasticon directly into your Node.js applications using the generateFonts function.

    import { generateFonts } from 'fantasticon';
    
    const results = await generateFonts({
      name: 'icons',
      fontTypes: ['ttf', 'woff2', 'woff'],
      assetTypes: ['css', 'html', 'json', 'ts'],
      formatOptions: { json: { indent: 2 } },
      fontHeight: 300,
      prefix: 'icon',
      tag: 'i'
    });
    
    console.log('Done', results);
  5. Default configuration options for Fantasticon

    master

    When using Fantasticon via the API, the following default options are applied if not explicitly provided in the RunnerOptions object. Note that inputDir and outputDir must always be provided as they are omitted from the defaults.

    Default Values

    • name: 'icons'
    • fontTypes: ['eot', 'woff2', 'woff'] (via FontAssetType)
    • assetTypes: ['css', 'html', 'json', 'ts'] (via OtherAssetType)
    • formatOptions: { json: { indent: 4 } }
    • fontHeight: 300
    • tag: 'i'
    • prefix: 'icon'
    • getIconId: Uses the internal getIconId utility.

    Other keys like pathOptions, templates, codepoints, round, descent, normalize, selector, and fontsUrl are also available for configuration.

    // Example of how these defaults might look when passed to a runner
    const options = {
      inputDir: 'src/icons',
      outputDir: 'dist/fonts',
      name: 'my-custom-icons',
      // ... other overrides
    };
  6. Use the Fantasticon CLI with options

    master

    The CLI allows you to customize the generation process. Note that some advanced options like formatOptions, pathOptions, getIconId, and templates must be configured via a configuration file or the JavaScript API.

    Available CLI Options:

    OptionFlagDescription
    --version-VOutput the version number
    --config-cCustom config path (defaults to .fantasticonrc, fantasticonrc.json, etc.)
    --output-oSpecify output directory
    --name-nBase name of the font set (default: icons)
    --font-types-tFont formats to generate (available: eot, woff2, woff, ttf, svg)
    --asset-types-gOther asset types to generate (available: css, scss, sass, html, json, ts)
    --font-height-hOutput font height (default: 300)
    --descentThe font descent
    --normalizeNormalize icons by scaling them to the height of the highest icon
    --round-rSetup the SVG path rounding [10e12]
    --selectorUse a CSS selector instead of 'tag + prefix'
    --prefix-pCSS class prefix (default: icon)
    --tagCSS base tag for icons (default: i)
    --fonts-url-uPublic URL to the fonts directory (used in generated CSS)
    --debugDisplay error stack trace
    --silentRun with no logs
    --help-hDisplay help command
  7. Sanitise configuration options with sanitiseOptions

    master

    Use sanitiseOptions to merge user-provided options with DEFAULT_OPTIONS. This ensures that the resulting configuration object contains all necessary keys and follows the expected structure required by the Fantasticon runner. It uses parseConfig internally to resolve the final configuration.

    import { sanitiseOptions } from 'fantasticon';
    
    const options = sanitiseOptions({
      inputDir: 'path/to/glyphs',
      // ... other user options
    });
  8. Write generated assets to disk

    master

    The writeAssets function takes a collection of GeneratedAssets (an object where keys are file extensions and values are the file content) and writes them to the filesystem.

    It uses the following configuration from RunnerOptions:

    • name: The base filename for the output files.
    • outputDir: The directory where files will be written.
    • pathOptions: An optional object allowing you to override the destination path for specific extensions. For example, { 'png': 'custom/path/icon.png' }.

    The function returns an array of WriteResult objects, each containing the content (string or Buffer) and the writePath used.

    const results = await writeAssets(
      {
        svg: '<svg>...</svg>',
        png: Buffer.from([0x89, 0x50, ...])
      },
      {
        name: 'my-icon',
        outputDir: 'dist/icons',
        pathOptions: {
          svg: 'dist/vectors/my-icon.svg'
        }
      }
    );
  9. Define a custom icon ID generator with GetIconIdFn

    master

    If you need to customize how icon IDs are generated, you can provide a function matching the GetIconIdFn signature. This function receives a GetIconIdOptions object containing metadata about the icon being processed.

    Options object (GetIconIdOptions):

    • basename: The filename without extension.
    • relativeDirPath: The directory path relative to the project root.
    • absoluteFilePath: The full absolute path to the file.
    • relativeFilePath: The path to the file relative to the project root.
    • index: The index of the icon (useful for handling duplicate names).

    Example implementation:

    import { GetIconIdFn } from 'fantasticon';
    
    const myCustomIdGenerator: GetIconIdFn = (options) => {
      return `icon-${options.basename}`;
    };
    export interface GetIconIdOptions {
      basename: string;
      relativeDirPath: string;
      absoluteFilePath: string;
      relativeFilePath: string;
      index: number;
    }
    
    export type GetIconIdFn = (options: GetIconIdOptions) => string;