⚡️ refactor: co-locate images (#200)
This commit is contained in:
193
content/blog/custom-font-subset/index.ca.md
Normal file
193
content/blog/custom-font-subset/index.ca.md
Normal file
@@ -0,0 +1,193 @@
|
||||
+++
|
||||
title = "Optimitza la càrrega amb un subconjunt de font personalitzat"
|
||||
date = 2023-04-29
|
||||
updated = 2023-07-08
|
||||
description = "Aprèn com crear un subconjunt personalitzat que només inclogui els glifs necessaris."
|
||||
|
||||
[taxonomies]
|
||||
tags = ["funcionalitat", "tutorial"]
|
||||
|
||||
[extra]
|
||||
social_media_card = "social_cards/ca_blog_custom_font_subset.jpg"
|
||||
+++
|
||||
|
||||
## El problema
|
||||
|
||||
Les fonts personalitzades causen parpelleig de text a Firefox. Per veure un gif i més detalls, mira [aquesta issue](https://github.com/welpo/tabi/issues/75).
|
||||
|
||||
## La solució
|
||||
|
||||
Per solucionar això, tabi carrega un subconjunt de glifs per a l'encapçalament. Donat que això augmenta lleugerament el temps de càrrega inicial, és una bona idea intentar minimitzar la mida d'aquest subconjunt.
|
||||
|
||||
Per defecte, tabi inclou fitxers de subconjunts per a caràcters en anglès i espanyol (amb alguns símbols). Aquests fitxers es carreguen quan la pàgina o el lloc web de Zola està en aquest idioma.
|
||||
|
||||
Per a una optimització addicional, pots crear un subconjunt de fonts personalitzat que només inclogui els caràcters utilitzats en el teu encapçalament.
|
||||
|
||||
## Requisits
|
||||
|
||||
Instal·la aquestes eines:
|
||||
|
||||
- [fonttools](https://github.com/fonttools/fonttools)
|
||||
|
||||
- [brotli](https://github.com/google/brotli)
|
||||
|
||||
Executa `pip install fonttools brotli` per instal·lar totes dues.
|
||||
|
||||
## L'script
|
||||
|
||||
El següent script pren un fitxer `config.toml` i un fitxer de font com a entrada, extreu els caràcters necessaris, crea un subconjunt de la font i genera un fitxer CSS que conté el subconjunt codificat en base64.
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 [--config | -c CONFIG_FILE] [--font | -f FONT_FILE] [--output | -o OUTPUT_PATH]"
|
||||
echo
|
||||
echo "Options:"
|
||||
echo " --config, -c Path to the config.toml file."
|
||||
echo " --font, -f Path to the font file."
|
||||
echo " --output, -o Output path for the generated custom_subset.css file (default: current directory)"
|
||||
echo " --help, -h Show this help message and exit"
|
||||
}
|
||||
|
||||
# La sortida per defecte és el directori actual.
|
||||
output_path="."
|
||||
|
||||
# Opcions de la línia de comandes.
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--config|-c)
|
||||
config_file="$2"
|
||||
shift 2
|
||||
;;
|
||||
--font|-f)
|
||||
font_file="$2"
|
||||
shift 2
|
||||
;;
|
||||
--output|-o)
|
||||
output_path="$2"
|
||||
shift 2
|
||||
;;
|
||||
--help|-h)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown option: $1"
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Comprova si s'han proporcionat les opcions -c i -f.
|
||||
if [ -z "$config_file" ]; then
|
||||
echo "Error: --config|-c option is required."
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$font_file" ]; then
|
||||
echo "Error: --font|-f option is required."
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Comprova si els fitxers de configuració i de font existeixen.
|
||||
if [ ! -f "$config_file" ]; then
|
||||
echo "Error: Config file '$config_file' not found."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f "$font_file" ]; then
|
||||
echo "Error: Font file '$font_file' not found."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extreu el títol i els noms del menú del fitxer de configuració.
|
||||
title=$(awk -F' = ' '/^title/{print $2}' "$config_file" | tr -d '"')
|
||||
menu_names=$(awk -F' = ' '/^menu/{f=1;next} /socials/{f=0} f && /name/{print $2}' "$config_file" | cut -d',' -f1 | tr -d '"' )
|
||||
language_names=$(awk -F' = ' '/^language_name\./{print $2}' "$config_file" | tr -d '"' )
|
||||
|
||||
# Si el lloc web és multilingüe, obté les traduccions del menú.
|
||||
if [ -n "$language_names" ]; then
|
||||
for menu_name in $menu_names; do
|
||||
# Find the line with the menu name inside a [languages.*.translations] section and get the translated menus.
|
||||
menu_translation=$(awk -F' = ' "/\\[languages.*\\.translations\\]/{f=1;next} /^\\[/ {f=0} f && /$menu_name =/{print \$2}" "$config_file" | tr -d '"' )
|
||||
# Add the found menu value to the translations string
|
||||
menu_names+="$menu_translation"
|
||||
done
|
||||
fi
|
||||
|
||||
# Combina les cadenes extretes.
|
||||
combined="$title$menu_names$language_names"
|
||||
|
||||
# Obté els caràcters únics.
|
||||
unique_chars=$(echo "$combined" | grep -o . | sort -u | tr -d '\n')
|
||||
|
||||
# Crea un fitxer temporal per a subset.woff2.
|
||||
temp_subset=$(mktemp)
|
||||
|
||||
# Crea el subconjunto.
|
||||
pyftsubset "$font_file" \
|
||||
--text="$unique_chars" \
|
||||
--layout-features="*" --flavor="woff2" --output-file="$temp_subset" --with-zopfli
|
||||
|
||||
# Codifica en base64 el fitxer temporal subset.woff2 i crea el fitxer CSS.
|
||||
base64_encoded_font=$(base64 -i "$temp_subset")
|
||||
echo "@font-face{font-family:\"Inter Subset\";src:url(data:application/font-woff2;base64,$base64_encoded_font);}" > "$output_path/custom_subset.css"
|
||||
|
||||
# Elimina el fitxer temporal subset.woff2.
|
||||
rm "$temp_subset"
|
||||
```
|
||||
|
||||
## Ús
|
||||
|
||||
Guarda l'script a algun lloc com `~/bin/subset_font`. Fes-lo executable amb `chmod +x ~/bin/subset_font`.
|
||||
|
||||
Ara pots executar-lo amb les opcions requerides `--config` i `--font`:
|
||||
|
||||
```bash
|
||||
~/bin/subset_font --config path/to/config.toml --font path/to/font.woff2
|
||||
```
|
||||
|
||||
De forma predeterminada, això generarà un fitxer `custom_subset.css` al directori actual. Utilitza `-o` o `--output` per especificar una ruta diferent:
|
||||
|
||||
```bash
|
||||
~/bin/subset_font -c path/to/config.toml -f path/to/font.woff2 -o path/to/output
|
||||
```
|
||||
|
||||
Col·loca aquest fitxer `custom_subset.css` dins del directori `static/` del teu projecte de Zola.
|
||||
|
||||
## Automatització amb un Pre-commit Hook
|
||||
|
||||
És possible que canviïs el títol o les opcions del menú del teu lloc web, la qual cosa faria que el subconjunt personalitzat deixés de ser útil.
|
||||
|
||||
Per automatitzar el procés de creació d'aquest fitxer, pots integrar l'script en un ganxo (hook) pre-commit de Git que s'activi en detectar canvis al fitxer `config.toml`, executi l'script i guardi el fitxer CSS resultant al directori `static/` del teu lloc web.
|
||||
|
||||
1. Crea un fitxer `.git/hooks/pre-commit` al teu projecte de Git, si encara no existeix.
|
||||
|
||||
2. Fes-lo executable amb `chmod +x .git/hooks/pre-commit`.
|
||||
|
||||
3. Afegeix el següent codi al fitxer:
|
||||
|
||||
```bash
|
||||
# Comprova si config.toml s'ha modificat.
|
||||
if git diff --cached --name-only | grep -q "config.toml"; then
|
||||
echo "config.toml modified. Running subset_font…"
|
||||
|
||||
# Executa l'script subset_font.
|
||||
~/bin/subset_font -c config.toml -f static/fonts/Inter4.woff2 -o static/
|
||||
|
||||
# Afegeix el fitxer subset.css generat al commit.
|
||||
git add static/custom_subset.css
|
||||
fi
|
||||
```
|
||||
|
||||
Asegura't de modificar l'script perquè coincideixi amb la ruta on has guardat l'script `subset_font`. Les rutes de configuració i font haurien de funcionar correctament amb la configuració predeterminada de tabi.
|
||||
|
||||
Ara, cada vegada que facis canvis al teu projecte de Git i facis commit, el ganxo pre-commit verificarà les modificacions al fitxer `config.toml` i executarà automàticament l'script `subset_font` per actualitzar el fitxer `custom_subset.css`.
|
||||
|
||||
Per cert, si t'interessa una forma d'actualitzar automàticament la data de les teves publicacions a Zola o comprimir automàticament els teus fitxers PNG, fes un cop d'ull a [aquesta publicació](https://osc.garden/ca/blog/zola-date-git-hook/).
|
||||
|
||||
Si desitges utilitzar tots els scripts alhora (compressió de fitxers PNG, actualització de la data i creació del subconjunt de fonts), combina el seu codi en un sol fitxer `.git/hooks/pre-commit`.
|
194
content/blog/custom-font-subset/index.es.md
Normal file
194
content/blog/custom-font-subset/index.es.md
Normal file
@@ -0,0 +1,194 @@
|
||||
+++
|
||||
title = "Optimiza la carga con un subconjunto de fuente personalizado"
|
||||
date = 2023-04-29
|
||||
updated = 2023-07-08
|
||||
description = "Aprende cómo crear un subconjunto personalizado que solo incluya los glifos necesarios."
|
||||
|
||||
[taxonomies]
|
||||
tags = ["funcionalidad", "tutorial"]
|
||||
|
||||
[extra]
|
||||
social_media_card = "social_cards/es_blog_custom_font_subset.jpg"
|
||||
+++
|
||||
|
||||
## El problema
|
||||
|
||||
Las fuentes personalizadas causan parpadeo de texto en Firefox. Para ver un gif y más detalles, mira [esta issue](https://github.com/welpo/tabi/issues/75).
|
||||
|
||||
## La solución
|
||||
|
||||
Para solucionar esto, tabi carga un subconjunto de glifos para el encabezado. Dado que esto aumenta ligeramente el tiempo de carga inicial, es una buena idea tratar de minimizar el tamaño de este subconjunto.
|
||||
|
||||
Por defecto, tabi incluye archivos de subconjuntos para caracteres en inglés y español (con algunos símbolos). Estos archivos se cargan cuando la página o el sitio de Zola está en ese idioma.
|
||||
|
||||
Para una optimización adicional, puedes crear un subconjunto de fuentes personalizado que solo incluya los caracteres utilizados en tu encabezado.
|
||||
|
||||
## Requisitos
|
||||
|
||||
Instala estas herramientas:
|
||||
|
||||
- [fonttools](https://github.com/fonttools/fonttools)
|
||||
|
||||
- [brotli](https://github.com/google/brotli)
|
||||
|
||||
Ejecuta `pip install fonttools brotli` para instalar ambas.
|
||||
|
||||
## El script
|
||||
|
||||
El script que sigue toma un archivo `config.toml` y un archivo de fuente como entrada, extrae los caracteres necesarios, crea un subconjunto de la fuente y genera un archivo CSS que contiene el subconjunto codificado en base64.
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 [--config | -c CONFIG_FILE] [--font | -f FONT_FILE] [--output | -o OUTPUT_PATH]"
|
||||
echo
|
||||
echo "Options:"
|
||||
echo " --config, -c Path to the config.toml file."
|
||||
echo " --font, -f Path to the font file."
|
||||
echo " --output, -o Output path for the generated custom_subset.css file (default: current directory)"
|
||||
echo " --help, -h Show this help message and exit"
|
||||
}
|
||||
|
||||
# La salida predeterminada es el directorio actual.
|
||||
output_path="."
|
||||
|
||||
# Analiza las opciones de la línea de comandos.
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--config|-c)
|
||||
config_file="$2"
|
||||
shift 2
|
||||
;;
|
||||
--font|-f)
|
||||
font_file="$2"
|
||||
shift 2
|
||||
;;
|
||||
--output|-o)
|
||||
output_path="$2"
|
||||
shift 2
|
||||
;;
|
||||
--help|-h)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown option: $1"
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Comprueba si se proporcionan las opciones -c y -f.
|
||||
if [ -z "$config_file" ]; then
|
||||
echo "Error: --config|-c option is required."
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$font_file" ]; then
|
||||
echo "Error: --font|-f option is required."
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Comprueba si existen los archivos de configuración y de fuentes.
|
||||
if [ ! -f "$config_file" ]; then
|
||||
echo "Error: Config file '$config_file' not found."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f "$font_file" ]; then
|
||||
echo "Error: Font file '$font_file' not found."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extrae el título y los nombres de los menús del archivo de configuración.
|
||||
title=$(awk -F' = ' '/^title/{print $2}' "$config_file" | tr -d '"')
|
||||
menu_names=$(awk -F' = ' '/^menu/{f=1;next} /socials/{f=0} f && /name/{print $2}' "$config_file" | cut -d',' -f1 | tr -d '"' )
|
||||
language_names=$(awk -F' = ' '/^language_name\./{print $2}' "$config_file" | tr -d '"' )
|
||||
|
||||
# Si el sitio es multilingüe, obtiene las traducciones de los menús.
|
||||
if [ -n "$language_names" ]; then
|
||||
for menu_name in $menu_names; do
|
||||
# Find the line with the menu name inside a [languages.*.translations] section and get the translated menus.
|
||||
menu_translation=$(awk -F' = ' "/\\[languages.*\\.translations\\]/{f=1;next} /^\\[/ {f=0} f && /$menu_name =/{print \$2}" "$config_file" | tr -d '"' )
|
||||
# Add the found menu value to the translations string
|
||||
menu_names+="$menu_translation"
|
||||
done
|
||||
fi
|
||||
|
||||
# Combina las cadenas extraídas.
|
||||
combined="$title$menu_names$language_names"
|
||||
|
||||
# Obtiene los caracteres únicos.
|
||||
unique_chars=$(echo "$combined" | grep -o . | sort -u | tr -d '\n')
|
||||
|
||||
# Crea un archivo temporal para subset.woff2.
|
||||
temp_subset=$(mktemp)
|
||||
|
||||
# Crea el subconjunto.
|
||||
pyftsubset "$font_file" \
|
||||
--text="$unique_chars" \
|
||||
--layout-features="*" --flavor="woff2" --output-file="$temp_subset" --with-zopfli
|
||||
|
||||
# Codifica en Base64 el archivo temporal subset.woff2 y crea el archivo CSS.
|
||||
base64_encoded_font=$(base64 -i "$temp_subset")
|
||||
echo "@font-face{font-family:\"Inter Subset\";src:url(data:application/font-woff2;base64,$base64_encoded_font);}" > "$output_path/custom_subset.css"
|
||||
|
||||
# Elimina el archivo temporal subset.woff2.
|
||||
rm "$temp_subset"
|
||||
```
|
||||
|
||||
## Uso
|
||||
|
||||
Guarda el script en algún lugar como `~/bin/subset_font`. Hazlo ejecutable con `chmod +x ~/bin/subset_font`.
|
||||
|
||||
Ahora puedes ejecutarlo con las opciones requeridas `--config` y `--font`:
|
||||
|
||||
```bash
|
||||
~/bin/subset_font --config path/to/config.toml --font path/to/font.woff2
|
||||
```
|
||||
|
||||
De forma predeterminada, esto generará un archivo `custom_subset.css` en el directorio actual. Usa `-o` o `--output` para especificar una ruta diferente:
|
||||
|
||||
```bash
|
||||
~/bin/subset_font -c path/to/config.toml -f path/to/font.woff2 -o path/to/output
|
||||
```
|
||||
|
||||
Coloca este archivo `custom_subset.css` dentro del directorio `static/`.
|
||||
|
||||
|
||||
## Automatización con un Pre-commit Hook
|
||||
|
||||
Es posible que cambies el título o las opciones del menú de tu sitio, lo que haría que el subconjunto personalizado deje de ser útil.
|
||||
|
||||
Para automatizar el proceso de creación de este archivo, puedes integrar el script en un gancho (hook) pre-commit de Git que se active al detectar cambios en el archivo `config.toml`, ejecute el script y guarde el archivo CSS resultante en el directorio `static/` de tu sitio.
|
||||
|
||||
1. Crea un archivo `.git/hooks/pre-commit` en tu proyecto de Git, si aún no existe.
|
||||
|
||||
2. Hazlo ejecutable con `chmod +x .git/hooks/pre-commit`.
|
||||
|
||||
3. Agrega el siguiente código al archivo:
|
||||
|
||||
```bash
|
||||
# Comprueba si config.toml se ha modificado.
|
||||
if git diff --cached --name-only | grep -q "config.toml"; then
|
||||
echo "config.toml modified. Running subset_font…"
|
||||
|
||||
# Ejecuta el script subset_font.
|
||||
~/bin/subset_font -c config.toml -f static/fonts/Inter4.woff2 -o static/
|
||||
|
||||
# Añadie el subset.css recién generado al commit.
|
||||
git add static/custom_subset.css
|
||||
fi
|
||||
```
|
||||
|
||||
Asegúrate de modificar el script para que coincida con la ruta donde has guardado el script `subset_font`. Las rutas de configuración y fuente deberían funcionar correctamente con la configuración predeterminada de tabi.
|
||||
|
||||
Ahora, cada vez que hagas cambios en tu proyecto de Git y los confirmes, el gancho pre-commit verificará las modificaciones en el archivo `config.toml` y ejecutará automáticamente el script `subset_font` para actualizar el archivo `custom_subset.css`.
|
||||
|
||||
Por cierto, si te interesa una forma de actualizar automáticamente la fecha de tus publicaciones en Zola o comprimir automáticamente tus archivos PNG, echa un vistazo a [esta publicación](https://osc.garden/es/blog/zola-date-git-hook/).
|
||||
|
||||
Si deseas utilizar todos los scripts a la vez (compresión de archivos PNG, actualización de la fecha y creación del subconjunto de fuentes), combina su código en un solo archivo `.git/hooks/pre-commit`.
|
196
content/blog/custom-font-subset/index.md
Normal file
196
content/blog/custom-font-subset/index.md
Normal file
@@ -0,0 +1,196 @@
|
||||
+++
|
||||
title = "Optimise loading times with a custom font subset"
|
||||
date = 2023-04-29
|
||||
updated = 2023-07-08
|
||||
description = "Learn how to create a custom subset that only includes the necessary glyphs."
|
||||
|
||||
[taxonomies]
|
||||
tags = ["showcase", "tutorial"]
|
||||
|
||||
[extra]
|
||||
social_media_card = "social_cards/blog_custom_font_subset.jpg"
|
||||
+++
|
||||
|
||||
## The problem
|
||||
|
||||
Custom fonts cause flashing text in Firefox. For a gif and more details, see [this issue](https://github.com/welpo/tabi/issues/75).
|
||||
|
||||
## The solution
|
||||
|
||||
To fix this, tabi loads a subset of glyphs for the header. Since this (slightly) increases the initial load time, it's a good idea to try and minimise the size of this subset.
|
||||
|
||||
By default, there are subset files for English and Spanish characters (with a few symbols). These files are loaded when the Zola page/site is set to that language.
|
||||
|
||||
For further optimisation, you can create a custom font subset that only includes the characters used in your header.
|
||||
|
||||
## Requirements
|
||||
|
||||
Install these tools:
|
||||
|
||||
- [fonttools](https://github.com/fonttools/fonttools)
|
||||
|
||||
- [brotli](https://github.com/google/brotli)
|
||||
|
||||
Run `pip install fonttools brotli` to install both.
|
||||
|
||||
## The script
|
||||
|
||||
The script below takes a `config.toml` file and a font file as input, extracts the necessary characters, creates a subset of the font, and generates a CSS file containing the base64 encoded subset.
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 [--config | -c CONFIG_FILE] [--font | -f FONT_FILE] [--output | -o OUTPUT_PATH]"
|
||||
echo
|
||||
echo "Options:"
|
||||
echo " --config, -c Path to the config.toml file."
|
||||
echo " --font, -f Path to the font file."
|
||||
echo " --output, -o Output path for the generated subset.css file (default: current directory)"
|
||||
echo " --help, -h Show this help message and exit"
|
||||
}
|
||||
|
||||
# Default output is current directory.
|
||||
output_path="."
|
||||
|
||||
# Parse command line options
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--config|-c)
|
||||
config_file="$2"
|
||||
shift 2
|
||||
;;
|
||||
--font|-f)
|
||||
font_file="$2"
|
||||
shift 2
|
||||
;;
|
||||
--output|-o)
|
||||
output_path="$2"
|
||||
shift 2
|
||||
;;
|
||||
--help|-h)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown option: $1"
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Check if -c and -f options are provided
|
||||
if [ -z "$config_file" ]; then
|
||||
echo "Error: --config|-c option is required."
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$font_file" ]; then
|
||||
echo "Error: --font|-f option is required."
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if config and font files exist.
|
||||
if [ ! -f "$config_file" ]; then
|
||||
echo "Error: Config file '$config_file' not found."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f "$font_file" ]; then
|
||||
echo "Error: Font file '$font_file' not found."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extract the title and menu names from the config file.
|
||||
title=$(awk -F' = ' '/^title/{print $2}' "$config_file" | tr -d '"')
|
||||
menu_names=$(awk -F' = ' '/^menu/{f=1;next} /socials/{f=0} f && /name/{print $2}' "$config_file" | cut -d',' -f1 | tr -d '"' )
|
||||
language_names=$(awk -F' = ' '/^language_name\./{print $2}' "$config_file" | tr -d '"' )
|
||||
|
||||
# If the site is multilingual, get the menu translations.
|
||||
if [ -n "$language_names" ]; then
|
||||
for menu_name in $menu_names; do
|
||||
# Find the line with the menu name inside a [languages.*.translations] section and get the translated menus.
|
||||
menu_translation=$(awk -F' = ' "/\\[languages.*\\.translations\\]/{f=1;next} /^\\[/ {f=0} f && /$menu_name =/{print \$2}" "$config_file" | tr -d '"' )
|
||||
# Add the found menu value to the translations string
|
||||
menu_names+="$menu_translation"
|
||||
done
|
||||
fi
|
||||
|
||||
# Combine the extracted strings.
|
||||
combined="$title$menu_names$language_names"
|
||||
|
||||
# Get unique characters.
|
||||
unique_chars=$(echo "$combined" | grep -o . | sort -u | tr -d '\n')
|
||||
|
||||
# Create a temporary file for subset.woff2.
|
||||
temp_subset=$(mktemp)
|
||||
|
||||
# Create the subset.
|
||||
pyftsubset "$font_file" \
|
||||
--text="$unique_chars" \
|
||||
--layout-features="*" --flavor="woff2" --output-file="$temp_subset" --with-zopfli
|
||||
|
||||
# Remove trailing slash from output path, if present.
|
||||
output_path=${output_path%/}
|
||||
|
||||
# Base64 encode the temporary subset.woff2 file and create the CSS file.
|
||||
base64_encoded_font=$(base64 -i "$temp_subset")
|
||||
echo "@font-face{font-family:\"Inter Subset\";src:url(data:application/font-woff2;base64,$base64_encoded_font);}" > "$output_path/custom_subset.css"
|
||||
|
||||
# Remove the temporary subset.woff2 file.
|
||||
rm "$temp_subset"
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Save the script somewhere like `~/bin/subset_font`. Make it executable with `chmod +x ~/bin/subset_font`.
|
||||
|
||||
Now you can run it with the required `--config` and `--font` options:
|
||||
|
||||
```bash
|
||||
~/bin/subset_font --config path/to/config.toml --font path/to/font.woff2
|
||||
```
|
||||
By default, this generates a `custom_subset.css` file in the current directory. Use `-o` or `--output` to specify a different path:
|
||||
|
||||
```bash
|
||||
~/bin/subset_font -c path/to/config.toml -f path/to/font.woff2 -o path/to/output
|
||||
```
|
||||
|
||||
You should place this `custom_subset.css` file inside the `static/` directory.
|
||||
|
||||
|
||||
## Automating with Pre-commit Hook
|
||||
|
||||
You might change the title or menu options of your site, making the custom subset no longer useful.
|
||||
|
||||
To automate the process of creating this file, you can integrate the script into a Git pre-commit hook that checks for changes in the `config.toml` file, runs the script, and stores the resulting CSS file in the `static/` directory of your site.
|
||||
|
||||
1. Create a `.git/hooks/pre-commit` file in your Git project, if it doesn't already exist.
|
||||
|
||||
2. Make it executable with `chmod +x .git/hooks/pre-commit`.
|
||||
|
||||
3. Add the following code to the file:
|
||||
|
||||
```bash
|
||||
# Check if config.toml has been modified.
|
||||
if git diff --cached --name-only | grep -q "config.toml"; then
|
||||
echo "config.toml modified. Running subset_font…"
|
||||
|
||||
# Call the subset_font script.
|
||||
~/bin/subset_font -c config.toml -f static/fonts/Inter4.woff2 -o static/
|
||||
|
||||
# Add the generated subset.css file to the commit.
|
||||
git add static/custom_subset.css
|
||||
fi
|
||||
```
|
||||
|
||||
Make sure to modify the script to match the path where you stored the `subset_font` script. The config and font paths should work fine with tabi's default setup.
|
||||
|
||||
Now, every time you commit changes to your Git project, the pre-commit hook will check for modifications in the `config.toml` file and automatically run the `subset_font` script to update the `custom_subset.css` file.
|
||||
|
||||
By the way, if you're interested in a way to automatically update the date of your Zola posts or compress your PNG files, check out [this post](https://osc.garden/blog/zola-date-git-hook/).
|
||||
|
||||
If you want to use all scripts at once (compressing PNG files, updating the date, and creating the font subset), combine their code into a single `.git/hooks/pre-commit` file.
|
Binary file not shown.
After Width: | Height: | Size: 53 KiB |
Binary file not shown.
After Width: | Height: | Size: 61 KiB |
Binary file not shown.
After Width: | Height: | Size: 62 KiB |
Reference in New Issue
Block a user