Coverage for fastblocks / adapters / fonts / squirrel.py: 85%
178 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""Font Squirrel adapter implementation for self-hosted fonts."""
3import typing as t
4from contextlib import suppress
5from pathlib import Path
6from uuid import UUID
8from oneiric.core.resolution import Resolver
10from ._base import FontsBase, FontsBaseSettings
12# Oneiric resolver for dependency injection
13depends = Resolver()
16class FontSquirrelFontsSettings(FontsBaseSettings):
17 """Font Squirrel-specific settings."""
19 fonts_dir: str = "/static/fonts"
20 fonts: list[dict[str, t.Any]] = []
21 preload_critical: bool = True
22 display: str = "swap"
25class FontSquirrelFonts(FontsBase):
26 """Font Squirrel adapter for self-hosted fonts."""
28 # Required ACB 0.19.0+ metadata
29 MODULE_ID: UUID = UUID("01937d86-4f2a-7b3c-8d9e-f3b4d3c2e1a2") # Static UUID7
30 MODULE_STATUS = "stable"
32 # Common font format priorities (most modern first)
33 FORMAT_PRIORITIES = ["woff2", "woff", "ttf", "otf", "eot"]
35 def __init__(self) -> None:
36 """Initialize Font Squirrel adapter."""
37 super().__init__()
38 self.settings = FontSquirrelFontsSettings()
40 # Register with Oneiric resolver (fail gracefully if not supported)
41 with suppress(Exception):
42 depends.set(self)
44 async def get_font_import(self) -> str:
45 """Generate @font-face declarations for self-hosted fonts."""
46 if not self.settings.fonts:
47 return "<!-- No self-hosted fonts configured -->"
49 font_faces = []
51 for font_config in self.settings.fonts:
52 font_face = self._generate_font_face(font_config)
53 if font_face:
54 font_faces.append(font_face)
56 if font_faces:
57 return f"<style>\n{chr(10).join(font_faces)}\n</style>"
58 return ""
60 def get_font_family(self, font_type: str) -> str:
61 """Get font family CSS values for configured fonts."""
62 # Look for a font with the specified type
63 for font_config in self.settings.fonts:
64 if font_config.get("type") == font_type:
65 family_name = font_config.get("family", font_config.get("name", ""))
66 fallback = font_config.get(
67 "fallback", self._get_default_fallback(font_type)
68 )
69 return f"'{family_name}', {fallback}" if family_name else fallback
71 # Return default fallbacks if no specific font found
72 return self._get_default_fallback(font_type)
74 def _generate_font_face(self, font_config: dict[str, t.Any]) -> str:
75 """Generate a single @font-face declaration."""
76 family = font_config.get("family") or font_config.get("name")
77 if not family:
78 return ""
80 # Build font-face properties
81 properties = [
82 f" font-family: '{family}';",
83 f" font-display: {self.settings.display};",
84 ]
86 # Add font style
87 style = font_config.get("style", "normal")
88 properties.append(f" font-style: {style};")
90 # Add font weight
91 weight = font_config.get("weight", "400")
92 properties.append(f" font-weight: {weight};")
94 # Build src declaration
95 src_parts = self._build_src_declaration(font_config)
96 if not src_parts:
97 return "" # No valid sources found
99 properties.append(f" src: {src_parts};")
101 # Add unicode-range if specified
102 if "unicode_range" in font_config:
103 properties.append(f" unicode-range: {font_config['unicode_range']};")
105 return f"@font-face {{\n{chr(10).join(properties)}\n}}"
107 def _handle_single_file_path(self, font_config: dict[str, t.Any]) -> list[str]:
108 """Handle single file path configuration."""
109 src_parts = []
110 file_path = font_config["path"]
111 format_hint = self._get_format_from_path(file_path)
112 url = self._normalize_font_url(file_path)
113 src_parts.append(f"url('{url}') format('{format_hint}')")
114 return src_parts
116 def _handle_multiple_file_paths(self, font_config: dict[str, t.Any]) -> list[str]:
117 """Handle multiple file paths with formats."""
118 src_parts = []
119 files = font_config["files"]
121 # Sort files by format priority
122 sorted_files = sorted(
123 files,
124 key=lambda f: self.FORMAT_PRIORITIES.index(f.get("format", "ttf"))
125 if f.get("format") in self.FORMAT_PRIORITIES
126 else 999,
127 )
129 for file_info in sorted_files:
130 file_path = file_info.get("path")
131 format_hint = file_info.get("format") or self._get_format_from_path(
132 file_path
133 )
135 if file_path and format_hint:
136 url = self._normalize_font_url(file_path)
137 src_parts.append(f"url('{url}') format('{format_hint}')")
139 return src_parts
141 def _handle_directory_discovery(self, font_config: dict[str, t.Any]) -> list[str]:
142 """Handle directory-based font discovery."""
143 src_parts = []
144 directory = font_config["directory"]
145 family = font_config.get("family") or font_config.get("name", "")
146 weight = font_config.get("weight", "400")
147 style = font_config.get("style", "normal")
149 # Look for font files in directory
150 if family: # Only proceed if family name is available
151 discovered_files = self._discover_font_files(
152 directory, family, weight, style
153 )
154 for file_path, format_hint in discovered_files:
155 url = self._normalize_font_url(file_path)
156 src_parts.append(f"url('{url}') format('{format_hint}')")
158 return src_parts
160 def _build_src_declaration(self, font_config: dict[str, t.Any]) -> str:
161 """Build the src property for @font-face."""
162 src_parts = []
164 # Handle single file path
165 if "path" in font_config:
166 src_parts.extend(self._handle_single_file_path(font_config))
168 # Handle multiple file paths with formats
169 elif "files" in font_config:
170 src_parts.extend(self._handle_multiple_file_paths(font_config))
172 # Handle directory-based discovery
173 elif "directory" in font_config:
174 src_parts.extend(self._handle_directory_discovery(font_config))
176 return ", ".join(src_parts)
178 def _get_format_from_path(self, file_path: str) -> str:
179 """Determine font format from file extension."""
180 path = Path(file_path)
181 extension = path.suffix.lower()
183 format_map = {
184 ".woff2": "woff2",
185 ".woff": "woff",
186 ".ttf": "truetype",
187 ".otf": "opentype",
188 ".eot": "embedded-opentype",
189 ".svg": "svg",
190 }
192 return format_map.get(extension, "truetype")
194 def _normalize_font_url(self, file_path: str) -> str:
195 """Normalize font file path to URL."""
196 # If already a full URL, return as-is
197 if file_path.startswith(("http://", "https://", "//")):
198 return file_path
200 # If relative path, prepend fonts directory
201 if not file_path.startswith("/"):
202 return f"{self.settings.fonts_dir.rstrip('/')}/{file_path}"
204 return file_path
206 def _discover_font_files(
207 self, directory: str, family: str, weight: str, style: str
208 ) -> list[tuple[str, str]]:
209 """Discover font files in a directory based on naming patterns."""
210 discovered = []
212 # Common naming patterns for font files
213 patterns = [
214 f"{family.lower().replace(' ', '-')}-{weight}-{style}",
215 f"{family.lower().replace(' ', '')}{weight}{style}",
216 f"{family.replace(' ', '')}-{weight}",
217 f"{family.lower()}-{style}",
218 family.lower().replace(" ", "-"),
219 ]
221 for pattern in patterns:
222 for ext in (".woff2", ".woff", ".ttf", ".otf"):
223 file_path = f"{directory.rstrip('/')}/{pattern}{ext}"
224 format_hint = self._get_format_from_path(file_path)
225 discovered.append((file_path, format_hint))
227 return discovered
229 def _get_default_fallback(self, font_type: str) -> str:
230 """Get default fallback fonts for different types."""
231 fallbacks = {
232 "primary": "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
233 "secondary": "Georgia, 'Times New Roman', serif",
234 "heading": "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
235 "body": "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
236 "monospace": "'Courier New', monospace",
237 "display": "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
238 "sans-serif": "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
239 "serif": "Georgia, 'Times New Roman', serif",
240 }
241 return fallbacks.get(font_type, "inherit")
243 def _get_default_critical_fonts(self) -> list[str]:
244 """Get default critical fonts (first font of each type).
246 Returns:
247 List of font family names to preload
248 """
249 fonts_to_preload = []
250 seen_types = set()
252 for font_config in self.settings.fonts:
253 font_type = font_config.get("type")
254 if font_type and font_type not in seen_types:
255 font_family = font_config.get("family") or font_config.get("name")
256 if font_family:
257 fonts_to_preload.append(font_family)
258 seen_types.add(font_type)
260 return fonts_to_preload
262 def _generate_preload_links_for_fonts(self, font_families: list[str]) -> list[str]:
263 """Generate preload links for specified font families.
265 Args:
266 font_families: List of font family names
268 Returns:
269 List of preload link HTML strings
270 """
271 preload_links: list[str] = []
273 for font_family in font_families:
274 for font_config in self.settings.fonts:
275 config_family = font_config.get("family") or font_config.get("name")
276 if config_family == font_family:
277 preload_link = self._generate_preload_link(font_config)
278 if preload_link:
279 preload_links.append(preload_link)
280 break
282 return preload_links
284 def get_preload_links(self, critical_fonts: list[str] | None = None) -> str:
285 """Generate preload links for critical fonts."""
286 if not self.settings.preload_critical:
287 return ""
289 # Determine which fonts to preload
290 fonts_to_preload = critical_fonts or self._get_default_critical_fonts()
292 # Generate preload links
293 preload_links = self._generate_preload_links_for_fonts(fonts_to_preload)
295 return "\n".join(preload_links)
297 def _find_best_font_file(self, font_config: dict[str, t.Any]) -> str | None:
298 """Find the best format file (woff2 preferred, then woff).
300 Args:
301 font_config: Font configuration dictionary
303 Returns:
304 Path to best font file or None
305 """
306 if "path" in font_config:
307 # Dictionary access returns Any, so we cast to the expected type
308 return t.cast(str | None, font_config["path"])
310 if "files" not in font_config:
311 return None
313 # Search for woff2 first
314 for file_info in font_config["files"]:
315 if file_info.get("format") == "woff2":
316 # Dictionary.get() returns Any, so we cast to the expected type
317 return t.cast(str | None, file_info.get("path"))
319 # Fall back to woff
320 for file_info in font_config["files"]:
321 if file_info.get("format") == "woff":
322 # Dictionary.get() returns Any, so we cast to the expected type
323 return t.cast(str | None, file_info.get("path"))
325 return None
327 def _generate_preload_link(self, font_config: dict[str, t.Any]) -> str:
328 """Generate a preload link for a specific font."""
329 best_file = self._find_best_font_file(font_config)
331 if best_file:
332 url = self._normalize_font_url(best_file)
333 return f'<link rel="preload" as="font" type="font/woff2" href="{url}" crossorigin>'
335 return ""
337 def validate_font_files(self) -> dict[str, list[str]]:
338 """Validate that configured font files exist and are accessible."""
339 validation_results: dict[str, list[str]] = {
340 "valid": [],
341 "invalid": [],
342 "warnings": [],
343 }
345 for font_config in self.settings.fonts:
346 family = font_config.get("family") or font_config.get("name", "Unknown")
348 if "path" in font_config:
349 # Single file validation would go here
350 validation_results["valid"].append(f"{family}: {font_config['path']}")
351 elif "files" in font_config:
352 # Multiple files validation would go here
353 for file_info in font_config["files"]:
354 validation_results["valid"].append(
355 f"{family}: {file_info.get('path', 'Unknown path')}"
356 )
357 else:
358 validation_results["warnings"].append(
359 f"{family}: No font files specified"
360 )
362 return validation_results
365FontsSettings = FontSquirrelFontsSettings
366Fonts = FontSquirrelFonts
368# Register with Oneiric resolver (fail gracefully if not supported)
369with suppress(Exception):
370 depends.set(Fonts, "squirrel")