Skip to content

Commit

Permalink
chore: 🎉 initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
DerZade committed Mar 22, 2024
0 parents commit 4f486f7
Show file tree
Hide file tree
Showing 40 changed files with 1,433 additions and 0 deletions.
21 changes: 21 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
on:
workflow_dispatch:
push:

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- run: pip install fonttools

- uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://npm.pkg.github.com'
scope: '@arma-events'

- run: npm ci

- run: npm run build
25 changes: 25 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
on:
release:
types: [published]

jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- run: pip install fonttools

- uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://npm.pkg.github.com'
scope: '@arma-events'

- run: npm ci

- run: npm run build

- run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
dist/
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 2,
"printWidth": 120
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Jonas "DerZade" Schade

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
94 changes: 94 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Web Fonts for arma.events

This package includes all web fonts used in arma.events and related projects. Each font is segmented in multiple unicode ranges so that a browser only needs to download the font resource needed for the displayed text content.
Furthermore each font is accompanied by a fallback font that should be displayed while the resources are loading. It is a font that is locally available on most systems and is adjusted to match the size of the target font as closely as possible to reduce layout shift.

## Installation

```
npm i @arma-events/web-fonts
```

> [!IMPORTANT]
> Make sure the `.npmrc` file in your project correctly configures the GitHub package registry for the `@arma-events/`-namespace:
>
> ```
> # .npmrc
> @arma-events:registry=https://npm.pkg.github.com
> ```
## Usage
Simply include the css file, which includes font-faces for all font as well as their fallback fonts:
```css
@import '@arma-events/web-fonts/dist/index.css';
/* Use the font */
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'Raleway', 'Raleway Fallback', sans-serif; /* Make sure to include the fallback font to reduce layout shift */
}
```
## Contributing

### Building locally

> [!TIP]
> [NodeJS 20 or higher](https://nodejs.org/) is required.
To build the package locally, simply install all dependencies:

```sh
npm ci
```

then run the build script:

```sh
npm run build
```

### Directory structure

#### `build/`

This directory contains the scripts used to build the package. They takes care of:

- Generating all `woff2` files from the input `tff`
- Automatically generating [`@font faces`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) rules for all fallback fonts
- Generating the output scss and css files.

#### `fallback_fonts/`

This directory contains all TrueType Fonts, that can be used as a fallback. These fonts are not included in the output and are just used to calculate the override values ([`size-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/size-adjust), [`ascent-override`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/ascent-override), [`descent-override`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/descent-override) and [`line-gap-override`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/line-gap-override)).

> [!NOTE]
> Fonts in this directory should be ["web-safe"](https://www.cssfontstack.com/) (generally available locally on most people's (> 70%) systems)
#### `fonts/`

This directory contains all fonts that should be built. Each font has a subdirectory and must includes the following five files:

- `normal.ttf`: The [variable font](https://fonts.google.com/knowledge/introducing_type/introducing_variable_fonts) in the normal style
- `italic.ttf`: The [variable font](https://fonts.google.com/knowledge/introducing_type/introducing_variable_fonts) in the italic style
- `static/normal.ttf`: The static font in the normal style and regular weight _(is only used to calculate the overrides of the fallback font)_
- `static/italic.ttf`: The static font in the normal style and italic weight _(is only used to calculate the overrides of the fallback font)_
- `config.json`: The configuration for the font. Includes an object, which has to have the following properties:
| Key | Example | Description |
| --- | --- | --- |
| `weight` | `200 900` | Value to set for [`font-weight`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-weight) in the [`@font-face` at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) |
| `fallbackFontFamily` | `Trebuchet MS` | Name of the fallback font family to use. `" Italic"` is automatically appended for the italic style. See the `fallback_fonts/`-directory for possible values. |

#### `_template.scss`

This file includes all the logic to generate the output scss and css files. It is loaded in the `index.scss`, which is auto generated by the build script. But the `index.scss` does not include any logic. It just loads the `_template.scss` with the correct values for base path, unicode ranges, fonts as well as font weights.

#### `unicode_ranges.json`

This JSON file includes all unicode ranges, that should be built. It's contains a simple object with the key being the name and the value being a valid [unicode range](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range#values).
63 changes: 63 additions & 0 deletions _template.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
$base-path: '@arma-events/web-fonts/dist' !default;
$unicode-ranges: () !default;
$fonts: () !default;
$weights: () !default;

@use 'sass:map';
@use 'sass:string';

@mixin -default-descriptors($font) {
font-family: $font;
font-display: swap;
@if map.has-key($weights, $font) {
font-weight: string.unquote(map.get($weights, $font));
} @else {
font-weight: 200 900;
}
}

@function -path($font, $style, $subset) {
@return '#{$base-path}/#{$font}/#{$style}.#{$subset}.woff2';
}

@each $font in $fonts {
@each $subset, $range in $unicode-ranges {
@each $style in (normal, italic) {
@font-face {
@include -default-descriptors($font);
font-style: $style;

src:
local('#{$font}'),
url(-path($font, $style, $subset)) format('woff2-variations');
unicode-range: string.unquote($range);
}
}
}
}

/* Source Sans 3: use ∞ Symbol (U+221E) from Raleway */
@each $style in (normal, italic) {
@font-face {
@include -default-descriptors('Source Sans 3');
font-style: $style;

src:
local('Raleway'),
url(-path('Raleway', $style, 'latin')) format('woff2-variations');
unicode-range: U+221E;
}
}

/* Raleway: use @ Symbol (U+0040) from Source Sans 3 */
@each $style in (normal, italic) {
@font-face {
@include -default-descriptors('Raleway');
font-style: $style;

src:
local('Source Sans 3'),
url(-path('Source Sans 3', $style, 'latin')) format('woff2-variations');
unicode-range: U+0040;
}
}
25 changes: 25 additions & 0 deletions build/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// @ts-check

import { join } from 'node:path';
import { Type } from '@sinclair/typebox';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import { importJSON } from './utils.js';
import { IN_DIR } from './consts.js';

const CONFIG_SCHEMA = TypeCompiler.Compile(
Type.Object(
{
weight: Type.String(),
fallbackFontFamily: Type.String(),
},
{ additionalProperties: false },
),
);

/**
* @param {string} name
*/
export async function loadFontConfig(name) {
const json = await importJSON(join(IN_DIR, name, 'config.json'));
return { ...CONFIG_SCHEMA.Decode(json), path: join(IN_DIR, name) };
}
19 changes: 19 additions & 0 deletions build/consts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// @ts-check

import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { importJSON } from './utils.js';

const __dirname = dirname(fileURLToPath(import.meta.url));

export const ROOT_DIR = join(__dirname, '..');
export const IN_DIR = join(ROOT_DIR, 'fonts');
export const OUT_DIR = join(ROOT_DIR, 'dist');
export const FALLBACK_FONTS_DIR = join(ROOT_DIR, 'fallback_fonts');

/**
* @type {import('../unicode_ranges.json')}
*/
export const UNICODE_RANGES = await importJSON(join(ROOT_DIR, 'unicode_ranges.json'));

export const STYLES = /** @type {const} */ (['normal', 'italic']);
39 changes: 39 additions & 0 deletions build/fallback.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// @ts-check

import { join, resolve } from 'node:path';
import { generateFontFace, readMetrics } from 'fontaine';
import { FALLBACK_FONTS_DIR, STYLES } from './consts.js';

/**
* @param {Record<string, Awaited<ReturnType<import('./config')['loadFontConfig']>>>} configs
*/
export async function renderFallbackFontsCSS(configs) {
let css = '';
for (const [font, config] of Object.entries(configs)) {
for (const style of STYLES) {
const metrics = await loadMetrics(join(config.path, 'static', `${style}.ttf`));

const fallbackFamily = config.fallbackFontFamily + (style === 'normal' ? '' : ' Italic');
const fallbackMetrics = await loadMetrics(join(FALLBACK_FONTS_DIR, fallbackFamily + '.ttf'));

css += generateFontFace(metrics, {
font: fallbackFamily,
name: `${font} Fallback`,
metrics: fallbackMetrics,
'font-style': style,
});
}
}

return css;
}

/**
* @param {string} path
*/
export async function loadMetrics(path) {
const metrics = await readMetrics('file://' + resolve(path));
if (metrics === null) throw new Error(`Failed to get metrics for file '${path}'.`);

return metrics;
}
Loading

0 comments on commit 4f486f7

Please sign in to comment.