added compass direction finding

This commit is contained in:
Joren de Graaf
2026-10-01 16:38:13 +02:00
parent a5dbbf3aed
commit 884e2e8a11
80 changed files with 3369 additions and 64 deletions
+1
View File
@@ -0,0 +1 @@
"""Portable Django template tags for Vite assets."""
Binary file not shown.
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ViteIntegrationConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "vite_integration"
@@ -0,0 +1,3 @@
{% load vite %}
{# Add this once inside a base template's <head> or just before </body>. #}
{% vite_asset "frontend/src/main.js" %}
@@ -0,0 +1 @@
"""Template-tag package for the portable Vite integration."""
+106
View File
@@ -0,0 +1,106 @@
"""Django template tags that select Vite HMR or manifest-backed assets."""
import json
import os
from functools import lru_cache
from pathlib import Path
from urllib.parse import urljoin
from django import template
from django.conf import settings
from django.contrib.staticfiles import finders
from django.template import TemplateSyntaxError
from django.templatetags.static import static
from django.utils.safestring import mark_safe
from django.utils.html import format_html
register = template.Library()
def _setting(name, default=None):
value = getattr(settings, name, None)
return value if value is not None else os.environ.get(name, default)
def _as_bool(value):
return str(value).lower() in {"1", "true", "yes", "on"}
def _use_dev_server():
return _as_bool(_setting("VITE_USE_DEV_SERVER", False))
def _static_prefix():
return str(_setting("VITE_STATIC_PREFIX", "vite")).strip("/")
def _manifest_path():
configured_path = _setting("VITE_MANIFEST_PATH")
if configured_path:
return Path(configured_path)
found_path = finders.find(f"{_static_prefix()}/.vite/manifest.json")
if found_path:
return Path(found_path)
raise TemplateSyntaxError(
"Vite manifest not found. Run `npm run build`, then `python manage.py collectstatic`."
)
@lru_cache(maxsize=8)
def _read_manifest(path, modified_time):
with Path(path).open(encoding="utf-8") as manifest_file:
manifest = json.load(manifest_file)
if not isinstance(manifest, dict):
raise TemplateSyntaxError("Vite manifest must contain a JSON object.")
return manifest
def _manifest():
path = _manifest_path()
try:
modified_time = path.stat().st_mtime_ns
except OSError as error:
raise TemplateSyntaxError("Vite manifest could not be read.") from error
return _read_manifest(str(path), modified_time)
def _production_tags(entrypoint):
manifest = _manifest()
try:
entry = manifest[entrypoint]
except KeyError as error:
raise TemplateSyntaxError(f"Vite entry point `{entrypoint}` is missing from the manifest.") from error
css_files = []
visited = set()
def visit(chunk_name):
if chunk_name in visited:
return
visited.add(chunk_name)
chunk = manifest.get(chunk_name, {})
for imported_chunk in chunk.get("imports", []):
visit(imported_chunk)
for css_file in chunk.get("css", []):
if css_file not in css_files:
css_files.append(css_file)
visit(entrypoint)
tags = [format_html('<link rel="stylesheet" href="{}">', static(f"{_static_prefix()}/{css_file}")) for css_file in css_files]
tags.append(format_html('<script type="module" src="{}"></script>', static(f"{_static_prefix()}/{entry['file']}")))
return mark_safe("\n".join(tags))
@register.simple_tag
def vite_asset(entrypoint):
"""Render one entry point from Vite's dev server or production manifest."""
if _use_dev_server():
dev_server_url = _setting("VITE_DEV_SERVER_URL", "http://127.0.0.1:5173/").rstrip("/") + "/"
hmr_client_url = urljoin(dev_server_url, "@vite/client")
entry_url = urljoin(dev_server_url, entrypoint.lstrip("/"))
return format_html(
'<script type="module" src="{}"></script>\n<script type="module" src="{}"></script>',
hmr_client_url,
entry_url,
)
return _production_tags(entrypoint)
+31
View File
@@ -0,0 +1,31 @@
import json
from pathlib import Path
from tempfile import TemporaryDirectory
from django.template import Context, Template
from django.test import SimpleTestCase, override_settings
from .templatetags.vite import _read_manifest
class ViteAssetTemplateTagTests(SimpleTestCase):
def setUp(self):
_read_manifest.cache_clear()
def render_asset(self):
return Template('{% load vite %}{% vite_asset "frontend/src/main.js" %}').render(Context())
@override_settings(VITE_USE_DEV_SERVER=True, VITE_DEV_SERVER_URL="http://vite.test:4173/")
def test_development_renders_hmr_client_and_entrypoint(self):
rendered = self.render_asset()
self.assertIn("http://vite.test:4173/@vite/client", rendered)
self.assertIn("http://vite.test:4173/frontend/src/main.js", rendered)
def test_production_resolves_css_and_script_from_manifest(self):
with TemporaryDirectory() as temporary_directory:
manifest_path = Path(temporary_directory) / "manifest.json"
manifest_path.write_text(json.dumps({"frontend/src/main.js": {"file": "assets/main-hash.js", "css": ["assets/main-hash.css"]}}), encoding="utf-8")
with override_settings(VITE_USE_DEV_SERVER=False, VITE_MANIFEST_PATH=manifest_path, VITE_STATIC_PREFIX="vite", STATIC_URL="/static/"):
rendered = self.render_asset()