commit 5e9da58d235e285b6298ee19af183670674a9539 Author: Tobias Weiske Date: Sun Aug 23 14:37:54 2026 +0200 Vorlage fuer eigene Ableger-Installationen: Website + CMS-Code Bereinigt von Pilot-Spezifika (echte Inhalte, Erzbistum-Hamburg-Bezuege, Domain-Werte) - install.env und hugo.toml [params] mit generischen Platzhaltern. docs/ komplett entfernt: Konzept, Manifest, Installations- anleitungen leben jetzt auf der Projekt-Website statt redundant im Repo, README verweist dorthin. Decap-CMS-Version von einer floatenden ^3.0.0 auf ein festes 3.15.1 gepinnt. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4eb0a41 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# Hugo build output +hugo/public/ +hugo/resources/ +hugo/.hugo_build.lock + +# Generated from hugo/hugo.template.toml + install.env (WEBSITE_DOMAIN, +# GITEA_DOMAIN, METHODEN_REPO), see scripts/generate-config.sh - +# hugo.template.toml is the file to maintain, not hugo.toml. +/hugo/hugo.toml + +# Method content lives in the separate methods repo, see install.env and +# scripts/sync-methoden.sh +/_content/ + +# Creation/modification dates, computed from the git history of _content/ +# instead of maintained, see scripts/generate-dates.sh +/hugo/data/methoden.json +/hugo/data/varianten.json + +# Current commit of this repo itself, computed at deploy/build time - see +# scripts/generate-version-info.sh +/hugo/data/website.json + +# Generated from admin/config.template.yml + the vocabulary in +# _content/ableger.yml, see scripts/generate-config.sh - config.template.yml +# is the file to maintain, not config.yml. +/admin/config.yml + +# Generated by scripts/generate-vorlagen-manifest.rb, scans the docroot +# live (not just this folder) - see the Methoden-Set chapter on the project website. +/methoden-set/vorlagen/vorlagen-manifest.json + +# OS +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..71d5f18 --- /dev/null +++ b/LICENSE @@ -0,0 +1,31 @@ +Ableger – Sammlung von Methoden für kirchliche, pastorale und pädagogische Praxis + +Dieses Repository enthält Website und CMS-Code von Ableger. Die Methoden- +Inhalte selbst liegen im separaten Methoden-Repo mit eigener LICENSE-Datei +(Hintergrund zur Repo-Trennung: Konzept-Kapitel auf der Projekt-Website). + +Software- und Konfigurationsbestandteile dieses Repositories (u. a. +`hugo/`, `admin/config.yml`) sind lizenziert unter einer +Creative Commons Namensnennung 4.0 International Lizenz (CC BY 4.0). + +Um eine Kopie dieser Lizenz zu sehen, besuchen Sie: +https://creativecommons.org/licenses/by/4.0/deed.de + +Den vollständigen rechtsverbindlichen Lizenztext (Legal Code) finden Sie unter: +https://creativecommons.org/licenses/by/4.0/legalcode.de + +Kurzfassung: +Sie dürfen die Inhalte in jedem Format oder Medium vervielfältigen, +verbreiten, öffentlich zeigen, aufführen und in andere Sprachen und +Formate übertragen, sie remixen, verändern und darauf aufbauen – +für beliebige Zwecke, auch kommerziell. Einzige Bedingung: +angemessene Urheber- und Rechteangaben, ein Link zur Lizenz und +Angabe, ob Änderungen vorgenommen wurden. + +Ausgenommen sind einzelne eingebundene Drittkomponenten (z. B. Hugo, +Decap CMS), für die deren jeweils eigene Lizenz gilt. + +Hinweis für Forks: CC-BY regelt keinen Markenschutz. Forks dieses +Repositories sollten einen eigenen Namen tragen und als +"basierend auf Ableger von [Name der Ursprungsinstitution]" +gekennzeichnet werden (siehe Konzept-Kapitel auf der Projekt-Website). diff --git a/README.md b/README.md new file mode 100644 index 0000000..23f29b1 --- /dev/null +++ b/README.md @@ -0,0 +1,109 @@ +# Ableger + +Ableger ist eine öffentlich zugängliche, frei lizenzierte Sammlung von Methoden für kirchliche, pastorale und pädagogische Praxis. Inhalte liegen als einfache, versionierte Markdown-Dateien vor, sind über eine grafische Oberfläche (Decap CMS) pflegbar und können von jeder interessierten Institution geforkt und eigenständig weiterentwickelt werden. + +**Dies ist das Vorlagen-Repo** – der Ausgangspunkt für eine eigene Installation, ohne institutionsspezifische Inhalte (siehe `beispiel-methode` im zugehörigen Methoden-Repo). Konzept, Datenmodell (Manifest), Architektur und die vollständige Schritt-für-Schritt-Installationsanleitung stehen auf der **[Projekt-Website](https://space.bildungselemente.de/ableger)** – diese README ist nur eine praktische Kurzfassung. + +## Grundprinzipien + +1. **Öffentlichkeit** – jede Methode ist frei einsehbar, keine Zugangsschranken (mit einer bewussten, optionalen Ausnahme für einen privaten Erprobungsmodus) +2. **Einfache, portable Formate** – Markdown statt proprietärer Formate +3. **Versionierung** – jede Änderung ist über Git nachvollziehbar und rückbaubar +4. **Verzweigung** – Institutionen können eigene, unabhängige Varianten pflegen (siehe [Fork-Starter-Kit](#fork-starter-kit) unten) +5. **GUI als Vermittlungsschicht** – Git-Konzepte bleiben im Hintergrund, Beitragende arbeiten über Formulare +6. **Persönliche Begleitung** – ein Pat:innen-Modell begleitet neue Mitwirkende, nicht nur Dokumentation + +Ausführliche Begründung und Hintergrund: Konzept-Kapitel auf der Projekt-Website. + +## Repo-Struktur + +Zwei getrennte Repos – eigene Zugriffsrechte für Methoden-Inhalte und für Website/CMS-Code. + +**Dieses Repo (`ableger`) – Website + CMS-Code**, **separates Repo `ableger_methoden`** – nur Inhalte. Vollständige Ordnerübersicht: `CLAUDE.md`. + +`_content/` in diesem Repo entsteht erst durch `scripts/sync-methoden.sh` (lokal wie im Deploy); Hugo bindet darin `_content/methoden` und `_content/varianten` über `module.mounts` in `hugo/hugo.template.toml` ein (daraus generiert `scripts/generate-config.sh` das tatsächlich gelesene `hugo/hugo.toml`, siehe unten). + +**Warum Varianten?** Jede Methode kann mehrere Ausprägungen haben (z. B. eine Kurz- und eine Langform, eine Version für eine andere Altersgruppe) – der eigentliche Inhalt und die Anhänge liegen deshalb bei einer eigenen Variante, nicht bei der Methode selbst. Jede Methode startet mit mindestens einer Variante. Die beiden Platzhalter-Methoden `beispiel-methode` (eine Variante) und `beispiel-methode-mit-varianten` (drei Varianten) im Methoden-Repo zeigen beide Fälle mit selbsterklärend ausgefüllten Feldern. + +## Eine Methode beitragen + +**Über die Formular-Oberfläche** (für alle mit CMS-Zugang): + +1. `/admin` der jeweiligen Instanz aufrufen und mit dem eigenen Gitea-Konto anmelden. +2. Neue **Methode** anlegen – das Formular fragt die Steckbrief-Metadaten ab (Titel, Zielgruppe, Dauer, Material, Kompetenzbereich, Kategorie, Lernchancen, Herkunft, Initiator:innen …). Speichern committet direkt auf den Hauptbranch – kein Zwischenschritt (Decap CMS unterstützt gegen Gitea keinen PR-basierten Editorial Workflow). +3. Neue **Variante** anlegen und über das Feld "Methode" der eben angelegten Methode zuordnen – hier kommen der eigentliche Inhalt (Textkörper mit der vorgegebenen Gliederung Vorbereitung / Ablauf / Hintergründe), Autor:innen und Anhänge hinein. Jede Methode braucht mindestens eine Variante, sonst bleibt sie unsichtbar (siehe Punkt 4). +4. Solange das Häkchen "Veröffentlicht" bei der Variante nicht gesetzt ist, ist sie nur im CMS sichtbar, nicht auf der Website. Erst wenn mindestens eine Variante veröffentlicht ist, erscheint auch die zugehörige Methode auf der Website – die Methode selbst hat kein eigenes Veröffentlichungs-Feld. + +**Direkt per Git/PR** (unabhängig von CMS-Zugang, z. B. ohne eigenes Gitea-Konto mit Schreibrecht): im separaten Content-Repo über Giteas Web-Editor (forkt automatisch, öffnet einen Pull Request) oder lokal je einen neuen Ordner `methoden//index.md` und `varianten/--/index.md` anlegen, Frontmatter-Schema aus `methoden/beispiel-methode/index.md` bzw. `varianten/beispiel-methode--original/index.md` übernehmen, PR gegen `main` stellen. Ablehnungen erfolgen nie kommentarlos, immer mit Begründung oder Verbesserungsvorschlag. + +**Wer CMS-Zugang bekommt** ist eine offene Prozessfrage der jeweiligen Institution, nicht softwareseitig geregelt. + +## Lokale Entwicklung + +Voraussetzung: [Hugo](https://gohugo.io/) (aktuelle Version). Für die Volltextsuche (`/suche/`) zusätzlich [Pagefind](https://pagefind.app/) – ein statisches Binary ohne Node/npm-Abhängigkeit, Installationshinweise auf der Projekt-Website. + +`_content/` ist nicht Teil dieses Repos (siehe oben) – einmalig bzw. bei Bedarf aktualisieren. `hugo/hugo.toml` ist ebenfalls nicht Teil des Repos (generiert aus `hugo/hugo.template.toml` + `install.env`, siehe unten) – ohne diesen Schritt findet Hugo keine Konfiguration: + +```bash +./scripts/sync-methoden.sh +./scripts/generate-config.sh +./scripts/generate-version-info.sh +``` + +Danach: + +```bash +cd hugo +hugo server +``` + +Der lokale Server bindet automatisch die Methoden aus `../_content/methoden` ein. Änderungen an Layouts (`hugo/layouts/`) oder Styles (`hugo/static/`) werden live neu geladen; Änderungen an den Methoden-Inhalten erfordern einen erneuten Lauf von `sync-methoden.sh`. Die Volltextsuche unter `/suche/` bleibt unter `hugo server` ohne Treffer – der Pagefind-Index entsteht erst im Produktions-Build unten. + +Für einen Produktions-Build inkl. Such-Index: + +```bash +cd hugo +hugo +pagefind --site public +``` + +Das Ergebnis liegt in `hugo/public/` (per `.gitignore` nicht versioniert). + +### Decap CMS lokal testen + +Um das Formular (Feldtypen, Pflichtfelder, vorbelegte Gliederung) zu prüfen, ohne Gitea/OAuth/Deployment zu brauchen, unterstützt Decap CMS einen lokalen Testmodus: + +1. In `admin/config.template.yml` **temporär** die Zeile `local_backend: true` ergänzen (nicht committen) – **nicht** in `admin/config.yml`, das wird beim nächsten `generate-config.sh`-Lauf überschrieben. +2. `./scripts/sync-methoden.sh` ausführen, falls noch nicht geschehen. +3. `./scripts/generate-config.sh` ausführen, um `admin/config.yml` inkl. `local_backend: true` neu zu erzeugen. +4. `npx decap-server` **innerhalb von `_content/`** starten (läuft auf Port 8081, operiert direkt auf den echten Dateien dieses Checkouts). +5. Das Repo-Root von `ableger` mit einem beliebigen statischen Server ausliefern, z. B. `python3 -m http.server 8080`. +6. `http://localhost:8080/admin/` öffnen, auf **Login** klicken – Decap erkennt den lokalen Proxy automatisch und meldet an, ganz ohne Gitea-Konto. + +Speichern schreibt echte Dateien in `_content/methoden/` bzw. `_content/varianten/`. Zum Aufräumen nach dem Test in `_content/` `git status` prüfen und Testeinträge verwerfen (oder `./scripts/sync-methoden.sh` erneut laufen lassen, um zurückzusetzen). + +## Deployment + +Vollständige, Schritt-für-Schritt getestete Installationsanleitung (Uberspace als Referenz-Hosting): siehe Projekt-Website. + +## Lizenz + +Alle Methodeninhalte stehen unter **CC BY 4.0**, sofern in der jeweiligen Datei nicht anders angegeben. Details: [LICENSE](LICENSE). Namensnennung erfolgt über die Felder `initiatoren` und `herkunft` im Frontmatter der Methode sowie `autoren` und `quellen` bei der jeweiligen Variante. + +## Fork-Starter-Kit + +Möchte eine andere Institution (Bistum, Verband, Bildungswerk, Einzelperson) eine eigene, unabhängige Kopie von Ableger pflegen? Das geht vollständig über die grafische Oberfläche, ohne Terminal oder Git-Kenntnisse: + +1. **Beide Repos forken**: Auf den Repo-Seiten von `ableger` **und** `ableger_methoden` in Gitea/Forgejo den Button **„Fork"** klicken. Es entstehen in Sekunden zwei vollständige Kopien unter dem eigenen Account oder der eigenen Organisation. +2. **Config anpassen**: In [`install.env`](install.env) `METHODEN_REPO` auf den Namen des eigenen `ableger_methoden`-Forks ändern (`/`) – eine einzige Datei, direkt im Gitea-Web-Editor bearbeitbar (**nicht** `admin/config.yml` selbst: die wird bei jedem Deploy aus `admin/config.template.yml` + `install.env` neu erzeugt und ist nicht versioniert). Der Deploy-Hook muss ebenfalls auf den eigenen `ableger_methoden`-Fork zeigen – siehe Installationsanleitung auf der Projekt-Website für Details je nach Hosting-Konstellation. +3. **OAuth-App registrieren**: In der eigenen Gitea-Instanz eine OAuth2-Anwendung für Decap CMS anlegen und `GITEA_DOMAIN`, `OAUTH_CLIENT_ID` in `install.env` entsprechend eintragen – Schritt-für-Schritt-Anleitung auf der Projekt-Website. +4. **Eigene Rollen und Rechte**: Die eigene Decap-CMS-Instanz läuft jetzt gegen den eigenen `ableger_methoden`-Fork, mit eigener Benutzerverwaltung (lokale Gitea-Konten oder Anbindung an einen vorhandenen Identity-Provider) – vollständig unabhängig vom Ursprungsrepo. Wer nur an Methoden mitarbeiten soll, braucht nur Zugriff auf den `ableger_methoden`-Fork, nicht auf `ableger`. +5. **Optional: privater Modus**: Für eine geschützte Erprobungsphase kann die Website hinter ein Auth-Gateway gestellt werden, das dieselben Gitea-Konten prüft wie die Formular-Seite – Anleitung auf der Projekt-Website. +6. **Aktuell halten**: Änderungen aus den Ursprungsrepos lassen sich jederzeit per regulärem Pull Request in die eigenen Forks übernehmen (Gitea-Sync-Button, wo verfügbar) – für beide Repos separat. +7. **Rückfluss**: Verbesserungen aus einem Fork können jederzeit per Cross-Repo Pull Request zurück ins jeweilige Ursprungsrepo vorgeschlagen werden – geprüft nach demselben Vertrauensstufen-Modell. + +**Mehrserver-Installationen:** Nichts an diesem Modell erzwingt, dass Gitea-Instanz und Hugo-Build/Deploy auf demselben Server laufen. `scripts/sync-methoden.sh` holt `ableger_methoden` standardmäßig per SSH-URL, unabhängig vom Host. Die einzige echte Voraussetzung: `ableger_methoden` braucht eine Gitea/Forgejo-Instanz, weil Decaps Backend deren OAuth-API anspricht; wer zusätzlich den privaten Modus (Schritt 5) nutzt, muss den oauth2-proxy vor der Website gegen *dieselbe* Gitea-Instanz authentifizieren wie Decap CMS, damit ein Login beide Zugriffsarten (Redaktion + Website-Lesen) abdeckt. + +**Namenskonvention (empfohlen, nicht technisch erzwungen):** CC BY 4.0 regelt keinen Markenschutz. Forks sollten einen eigenen Namen tragen und sich als *„basierend auf Ableger von [Name der Ursprungsinstitution]"* kennzeichnen. + +Details und Hintergrund zu allem oben: **[Projekt-Website](https://space.bildungselemente.de/ableger)**. diff --git a/admin/config.template.yml b/admin/config.template.yml new file mode 100644 index 0000000..097c00c --- /dev/null +++ b/admin/config.template.yml @@ -0,0 +1,378 @@ +# admin/config.template.yml +# Template for the Decap CMS starting configuration. NOT served directly: +# scripts/generate-config.sh builds admin/config.yml from it (generated, +# not versioned, see .gitignore) - two independent substitution steps: +# (1) fields between "# VOKABULAR::START/END" markers are replaced +# if a matching entry exists in the content repo under _content/ableger.yml +# (key "vokabular") (a closed selection list instead of free text) - if the +# entry is missing, the block entered here stays unchanged. (2) +# "{{VARIABLE}}" placeholders (see backend/site_url below) are always +# replaced by the like-named values from install.env. +# Details: the Manifest chapter on the project website Teil C, vokabular/README.md. + +# Deliberately separate from the website/CMS code repo (ableger_demo/ableger): +# dedicated access rights for method content instead of full access to the +# whole repo via CMS access. Details: the concept chapter on the project website Abschnitt 4 and 9. +# repo/app_id/api_root/base_url/auth_endpoint come from install.env +# (adjust centrally there for a fork), not directly here. +backend: + name: gitea + repo: "{{METHODEN_REPO}}" + app_id: "{{OAUTH_CLIENT_ID}}" + api_root: "https://{{GITEA_DOMAIN}}/api/v1" + base_url: "https://{{GITEA_DOMAIN}}" + auth_endpoint: "https://{{GITEA_DOMAIN}}/login/oauth/authorize" + branch: main + +# For the "Preview" link in the editor toolbar (not in the list overview - +# per Decap's own docs, that only shows on the edit page). +# WEBSITE_DOMAIN comes from install.env, must match baseURL in hugo/hugo.toml. +site_url: "https://{{WEBSITE_DOMAIN}}" + +# editorial_workflow (branch + PR per submission) would be the actually +# intended model, but is not supported by the Gitea backend in Decap CMS +# (runtime error on load): https://github.com/decaporg/decap-cms/issues/7115 +# (open, no workaround). Hence simple: a direct commit for anyone with CMS +# access. Who gets access is a process question outside this config - see +# the concept chapter on the project website Abschnitt 5. +publish_mode: simple + +# Fallback for media without their own field-level media_folder (among +# others the global "Media" button in the navigation) - now points into the +# content repo (ableger_demo/ableger_methoden) instead of the website repo, +# see backend.repo above. +media_folder: "_assets" +public_folder: "/_assets" + +# Strip umlauts/accents from generated slugs: for the existence check Decap +# runs before every save (GET .../git/trees/main:), Gitea returns a +# 400 error ("sha not found") for a path with non-ASCII characters - and +# that's true even when the path exists, not only for new entries. Verified +# live against the real Gitea API (ableger_methoden, main). Affects not +# only creation but every subsequent save of an existing entry with an +# umlaut in the folder name. Since this is a quirk of Gitea's extended-SHA +# resolution (not a Decap bug), it can't be fixed in this repo's code - +# only worked around via ASCII-clean slugs. +slug: + clean_accents: true + +collections: + - name: "methoden" + label: "Methoden" + # Deliberately "methoden" instead of repo root ("") - Decap CMS crashes + # on an empty folder value (config processing sets collection.type only + # inside "if (folder) {...}", an empty string is falsy). Reproduced and + # verified locally, see the ableger_methoden commit "Methoden in + # methoden/-Unterordner verschieben". + folder: "methoden" + create: true + # Slug comes from the dedicated field "kennung", no longer from the + # title (Decap's default {{slug}}): the title may change at any time + # without moving the folder - see the "kennung" field below and + # the Manifest chapter on the project website, section "Bezeichner". Previously {{slug}} (derived + # from titel) - a title change demonstrably deleted the method page + # live and orphaned both variants, see the project website (background/analysis notes), + # Befund A. + slug: "{{fields.kennung}}" + path: "{{slug}}/index" + # {{slug}} in preview_path here (unlike slug: above) means the full + # path compiled from path: "{{slug}}/index", including "index" - would + # result in "beispiel-methode-index" instead of "beispiel-methode". + # {{dirname}} is the parent folder relative to the collection folder, + # which matches the slug exactly. Verified locally. + preview_path: "{{dirname}}" + identifier_field: "titel" + # Last-modified info in the overview, analogous to the variants + # collection below - {{commit_date}}/{{commit_author}} are Decap's own + # tokens fed from the Gitea API (checked live, also work in the summary + # template, not just in sortable_fields). + summary: "{{fields.titel}} | {{commit_date | date('D.M.YY')}} {{commit_author}}" + # Consistent vocabulary/order with the variants collection below: + # "Methode" instead of "Titel" as the label, "Zuletzt geändert am/durch" + # instead of Decap's default labels "Updated On"/"Author" - "Author" + # would be easily confused here with our own "Autor:innen" field (on + # variants), but actually means the commit author. + sortable_fields: + - { field: "titel", label: "Methode" } + - { field: "commit_date", label: "Zuletzt geändert am" } + - { field: "commit_author", label: "Zuletzt geändert durch" } + format: "frontmatter" + media_folder: "" + public_folder: "" + # Deliberately no draft field of its own here: publication is derived + # from the variants (see their "veroeffentlicht" field below) - as soon + # as at least one variant is published, the method is too. + # scripts/compute-methoden-sichtbarkeit.rb sets draft: true + # automatically for that, before every Hugo build, in the local + # _content copy (not in the repo), for every method without a + # published variant - Hugo's own, reliable draft mechanism then takes + # care of the rest (e.g. automatic exclusion from the + # homepage/search/taxonomies, not just the detail page). Details: + # the concept chapter on the project website Abschnitt 5. + # + # Equally deliberately no duration/group-size fields here: these depend + # on the respective variant (different versions of a method can take + # different amounts of time or be meant for different group sizes), + # hence they sit on the variant (see below) and are aggregated into a + # range for the method page from all its variants (see + # hugo/layouts/partials/variantenspanne.html). + # + # Equally deliberately no material field here (since August 2026, + # before that there was one): different variants of the same method + # often need different material - unlike duration/group size, there is + # also no aggregated display for this on the method page, since a + # material list as a union set would be misleading (could suggest you + # need everything together). Lives exclusively on the respective + # variant. + # + # License also on the variant, not here: what's copyrightable is not + # the method as an idea but the concrete description/write-up - which + # has lived entirely there since variants were introduced. The method + # page instead shows the set of licenses present across all variants + # (analogous to the duration range, see partials/variantenspanne.html). + fields: + # Stable identifier - becomes the folder name (see slug above) and + # thereby the target of every variant reference (see their "methode" + # field below). Assigned once, never changed afterward - the title + # may change freely, this may not. No technical lock in the editor + # possible (Decap has no readonly field), the validation script + # (scripts/validate.rb) flags later changes as an error. pattern + # also enforces ASCII-clean folder names directly in the form, + # rather than only via slug.clean_accents. + - label: "Kennung" + name: "kennung" + widget: "string" + hint: "Kurz und selbsterklärend. Kleinbuchstaben/Ziffern/Bindestriche/Unterstriche. Wird zum Ordnernamen und eindeutigen Identifier. Nach dem Anlegen nicht mehr ändern." + pattern: ["^[a-z0-9_]+(-[a-z0-9_]+)*$", "Nur Kleinbuchstaben, Ziffern, Unterstriche und Bindestriche, kein Bindestrich am Anfang/Ende"] + - { label: "Titel", name: "titel", widget: "string" } + - { label: "Kurzbeschreibung", name: "kurzbeschreibung", widget: "text", hint: "Kurze Zusammenfassung von Ziel und Ablauf, für den schnellen Überblick bei der Suche" } + - { label: "Verwendungsmöglichkeit", name: "verwendungsmoeglichkeit", widget: "text", hint: "Wann und wofür eignet sich die Methode?" } + # VOKABULAR:zielgruppe:START + - label: "Zielgruppe" + name: "zielgruppe" + widget: "select" + multiple: true + options: + - "Kinder" + - "Jugendliche" + - "Erwachsene" + - "Senior_innen" + # VOKABULAR:zielgruppe:END + - label: "Kompetenzbereich" + name: "kompetenzbereich" + widget: "select" + multiple: true + hint: "Kompetenzmodell nach Leipold, Kopf & Seidl (2010)" + options: + - "Fachkompetenz" + - "Methodenkompetenz" + - "Sozialkompetenz" + - "Selbstkompetenz" + # VOKABULAR:kategorie:START + - label: "Kategorie" + name: "kategorie" + widget: "list" + hint: "Frei wählbar, z. B. Advent, Firmvorbereitung, Kennenlernen, Konfliktbearbeitung – bewusst kein festes Vokabular" + # VOKABULAR:kategorie:END + - label: "Lernchancen" + name: "lernchancen" + widget: "list" + hint: "Stichsätze zu den (Lern-)Chancen, die mit der Methode verbunden werden" + summary: "{{fields.eintrag}}" + field: { label: "Lernchance", name: "eintrag", widget: "string" } + - label: "Herkunft" + name: "herkunft" + widget: "list" + required: false + hint: "Woher stammt die Methode ursprünglich? (Eigenentwicklung, Vorlage, Tradition o. Ä.) - wovon sich eine einzelne Variante ableitet, steht bei dieser selbst, siehe Collection \"Varianten\", Feld \"Quellen\"." + summary: "{{fields.eintrag}}" + field: { label: "Angabe", name: "eintrag", widget: "string" } + - label: "Initiator:innen" + name: "initiatoren" + widget: "list" + hint: "Wer die Methode ursprünglich entwickelt/eingebracht hat. Autor:innen einzelner Varianten stehen bei der jeweiligen Variante, siehe Collection \"Varianten\"." + summary: "{{fields.eintrag}}" + field: { label: "Initiator:in", name: "eintrag", widget: "string" } + # VOKABULAR:tags:START + - { label: "Tags", name: "tags", widget: "list", required: false } + # VOKABULAR:tags:END + + # Every method has at least one variant - no special case for "just one + # version" in the data model, otherwise adding a second variant would + # require a later migration (moving content out of the method into a + # first variant). A method without a variant is deliberately not + # intended, but not technically enforced by the CMS (no access to other + # collections while saving). Linked via a relation field instead of + # nested files in the method folder: whether Decap's path template can + # include the folder of a method referenced via relation is unclear/ + # unverified - the link instead happens only in Hugo (see + # hugo/layouts/_default/single.html), similar to a taxonomy. + # + # Own page bundle per variant (like methods), so that attachments - which + # belong to the respective variant, not the method, see the + # untertitel/varianten_beschreibung rationale above - have a fixed + # location where embedded images in the content (![]()) also resolve + # correctly via Hugo page resources. With only one variant, attachments + # stay functionally identical to the previous state (directly in the + # bundle folder of the - then only - variant, no dedicated src + # subfolder, same reason as for methods). + - name: "varianten" + label: "Varianten" + folder: "varianten" + create: true + # methode resolves via value_field (see relation field below) to the + # method's kennung, no longer to its title - title changes therefore no + # longer move variant folders, see the Manifest chapter on the project website and + # the project website (background/analysis notes), Befund A/E. + slug: "{{fields.methode}}--{{fields.kennung}}" + path: "{{slug}}/index" + # {{slug}} in preview_path here (as already with methods) means the + # full path compiled from path: "{{slug}}/index", including "index". + # {{dirname}} is the parent folder relative to the collection folder, + # which matches the slug exactly AND the real live URL: variants do + # live in Hugo's content structure under the "varianten" section (see + # hugo/hugo.toml module.mounts), but via the [permalinks] override + # there without a "varianten/" prefix in the URL - the section is kept + # for the template logic (where site.RegularPages "Section" + # "varianten"), only the URL becomes flat. Slug collisions with methods + # are ruled out, since variant slugs are always + # "--", and method slugs never + # contain "--". + preview_path: "{{dirname}}" + identifier_field: "untertitel" + # Without this line, the overview would only show the subtitle (e.g. + # "Kurzform") with no recognizable relation to the method - no longer + # distinguishable with several methods that have similar variant names. + # "Show variants on the method edit page" would be the more obvious + # solution, but Decap CMS doesn't support it (no reverse-relation + # feature) and would need a custom widget - deliberately not built + # here. Method first, then subtitle: this way the overview groups + # sensibly when sorted by "Methode", not just alphabetically by slug. + # {{commit_date}}/{{commit_author}} are Decap's own tokens fed from the + # Gitea API - checked live, also work in the summary template (not just + # in sortable_fields, where they were originally intended for this + # purpose). + summary: "{{fields.methode}} – {{fields.untertitel}} | {{commit_date | date('D.M.YY')}} {{commit_author}}" + # Decap doesn't automatically offer relation fields (like "methode") in + # "Sort by" (checked live: without this line, only "Untertitel" showed + # up there) - added explicitly, so the overview can also be grouped by + # method. "commit_author"/"commit_date" (Decap's built-in, git-based + # sort options) have to be listed explicitly here too: an explicit + # sortable_fields list REPLACES Decap's default selection entirely, + # instead of extending it - without these two entries they would have + # disappeared from this collection, even though they should appear the + # same way for methods (also explicitly set there now, see above). + # Consistent vocabulary/order with the methods collection above: + # "Methode" first, then - only here in addition, since only variants + # have this field - "Variante" (label for the untertitel field), then + # "Zuletzt geändert am/durch" instead of Decap's default labels + # "Updated On"/"Author" - "Author" would be easily confused here with + # our own "Autor:innen" field, but actually means the commit author. + sortable_fields: + - { field: "methode", label: "Methode" } + - { field: "untertitel", label: "Variante" } + - { field: "commit_date", label: "Zuletzt geändert am" } + - { field: "commit_author", label: "Zuletzt geändert durch" } + format: "frontmatter" + media_folder: "" + public_folder: "" + fields: + # Positive polarity (on = published) instead of a switch that writes + # directly into Hugo's "draft" field: marking "on" as "draft" (as + # required for an inverted draft field) is confusing UX. Decap cannot + # write a boolean field inverted into a differently named + # frontmatter field, so scripts/apply-veroeffentlicht.rb translates + # this field, inverted, into Hugo's native "draft" before every Hugo + # build, in the local _content copy (not in the repo) - Hugo's own + # draft mechanism then takes care of reliable build exclusion, as + # with methods (see above). + - label: "Veröffentlicht (auf der Website sichtbar)" + name: "veroeffentlicht" + widget: "boolean" + default: false + hint: "Häkchen setzen, um diese Variante (und damit auch die zugehörige Methode, siehe deren Hinweistext) auf der Website zu veröffentlichen. Bleibt bis dahin in Git gespeichert, ist aber nur im CMS sichtbar." + - label: "Methode" + name: "methode" + widget: "relation" + collection: "methoden" + search_fields: ["titel"] + display_fields: ["titel"] + # value_field determines what's actually stored/used for the slug - + # "kennung" instead of "titel" (the state before kennung was + # introduced), so that a title change on the method no longer + # breaks this reference (see the project website, background/analysis + # notes, Befund A). search_fields/display_fields stay on + # "titel", so the search in the dropdown still searches by the + # readable name, not the kennung. Neither {{slug}} nor {{dirname}} + # give a cleaned folder name here (reproduced live) - a direct + # field reference to "kennung" is the robust way. Linking in Hugo + # correspondingly happens via Params.kennung, not via Params.titel + # or the filename/slug. + value_field: "kennung" + hint: "Zu welcher Methode gehört diese Variante?" + # Stable identifier of this variant - becomes the second part of the + # folder name (see slug above). Assigned once, never changed + # afterward, see the Manifest chapter on the project website. Unlike the method, nothing + # currently references a variant from outside - kept consistent + # anyway, for later fork merges. + - label: "Kennung" + name: "kennung" + widget: "string" + hint: "Kurz und selbsterklärend. Kleinbuchstaben/Ziffern/Bindestriche/Unterstriche. Wird zum Ordnernamen und eindeutigen Identifier. Nach dem Anlegen nicht mehr ändern." + pattern: ["^[a-z0-9_]+(-[a-z0-9_]+)*$", "Nur Kleinbuchstaben, Ziffern, Unterstriche und Bindestriche, kein Bindestrich am Anfang/Ende"] + - { label: "Untertitel", name: "untertitel", widget: "string", hint: "Ein Wort, das die Besonderheit dieser Variante ausdrückt, z. B. \"Kurzform\" oder \"Sommer\"." } + - { label: "Varianten-Beschreibung", name: "varianten_beschreibung", widget: "text", hint: "Kurze Erläuterung, was diese Variante besonders macht - hilft später bei der Orientierung zwischen mehreren Varianten" } + - { label: "Dauer (Minuten)", name: "dauer_minuten", widget: "number", value_type: "int" } + - { label: "Gruppengröße (mindestens)", name: "gruppengroesse_min", widget: "number", value_type: "int", hint: "Für eine feste Gruppengröße hier und beim Maximum denselben Wert eintragen" } + - { label: "Gruppengröße (höchstens)", name: "gruppengroesse_max", widget: "number", value_type: "int" } + - label: "Material" + name: "material" + widget: "list" + hint: "Was für diese Variante konkret gebraucht wird - andere Varianten derselben Methode können anderes Material brauchen" + summary: "{{fields.eintrag}}" + field: { label: "Material", name: "eintrag", widget: "string" } + # VOKABULAR:lizenz:START + - { label: "Lizenz", name: "lizenz", widget: "string", default: "CC-BY 4.0", hint: "Gilt für diesen Text/diese Ausarbeitung - die Methode-Seite zeigt die Menge aller vorkommenden Lizenzen ihrer Varianten" } + # VOKABULAR:lizenz:END + - label: "Quellen" + name: "quellen" + widget: "list" + required: false + hint: "Worauf sich diese konkrete Ausarbeitung stützt (z. B. eine Handreichung, eine Adaption) - wovon die Methode allgemein abstammt, steht bei ihr selbst unter \"Herkunft\"" + summary: "{{fields.eintrag}}" + field: { label: "Quelle", name: "eintrag", widget: "string" } + - label: "Autor:innen" + name: "autoren" + widget: "list" + hint: "Wer diese Variante erarbeitet hat (kann sich von den Initiator:innen der Methode unterscheiden)" + summary: "{{fields.eintrag}}" + field: { label: "Autor:in", name: "eintrag", widget: "string" } + - label: "Inhalt (Vorbereitung, Ablauf, Hintergründe)" + name: "body" + widget: "markdown" + default: | + # Vorbereitung + + *Stichsätze, was erledigt werden muss, um mit den Inhalten zu starten (bei Bedarf auch Anmerkungen zum Material).* + + # Ablauf + + *Detaillierter Ablaufplan mit Anweisungen, möglicherweise in weiteren Überschriftenebenen verschachtelt.* + + # Hintergründe + + *Erläuterung von Hintergründen (Implizites im Ablauf explizit machen), um die Methode zugänglich zu gestalten.* + - label: "Anhänge" + name: "anhaenge" + widget: "list" + required: false + hint: "Arbeitsblätter, Vorlagen o. Ä. zum Herunterladen - gehören zu dieser Variante, nicht zur Methode allgemein" + # Deliberately no dedicated media_folder subfolder (e.g. "src"): a + # git folder that has never contained a file simply doesn't exist - + # Gitea returns HTTP 400 for that instead of an empty list, and + # Decap only catches 404. The variant's own bundle folder, on the + # other hand, always exists (because of index.md), hence + # attachments live directly there. + fields: + - { label: "Datei", name: "datei", widget: "file" } + - { label: "Beschreibung", name: "beschreibung", widget: "string", hint: "Kurze Einordnung, wofür der Anhang gedacht ist" } diff --git a/admin/index.html b/admin/index.html new file mode 100644 index 0000000..043c41c --- /dev/null +++ b/admin/index.html @@ -0,0 +1,256 @@ + + + + + + Ableger – Redaktion + + + + + + + +
+
+
+ + + + + diff --git a/admin/site-meta.js b/admin/site-meta.js new file mode 100644 index 0000000..ac5484c --- /dev/null +++ b/admin/site-meta.js @@ -0,0 +1,17 @@ +// Loads the site title from /site-meta.json (see hugo.toml, +// outputFormats.SiteMeta) instead of hardcoding "Ableger" - these pages run +// without Hugo templating (see the installation guide on the project website). On failure, the +// "Ableger" fallback already in the markup stays. Shared by admin/index.html +// and admin/status/index.html, which only differ in the title suffix - +// passed in via this script tag's own "data-title-suffix" attribute. +(function () { + var suffix = document.currentScript.dataset.titleSuffix || ''; + fetch('/site-meta.json') + .then(function (r) { return r.json(); }) + .then(function (meta) { + if (!meta.title) return; + document.title = meta.title + suffix; + document.getElementById('site-title-text').textContent = meta.title; + }) + .catch(function () {}); +})(); diff --git a/admin/status/index.html b/admin/status/index.html new file mode 100644 index 0000000..ba3b429 --- /dev/null +++ b/admin/status/index.html @@ -0,0 +1,115 @@ + + + + + + Ableger – Deploy-Status + + + + + +
+

Deploy-Status

+

Letzter Build (Cron alle 10 Minuten, oder manuell hier ausgelöst) inklusive Prüfskript-Ergebnissen (scripts/validate.rb).

+ +
+ + +
+ +
+

Lade Status …

+
+
+ + + + + diff --git a/hugo/content-static/suche/_index.md b/hugo/content-static/suche/_index.md new file mode 100644 index 0000000..c3bd507 --- /dev/null +++ b/hugo/content-static/suche/_index.md @@ -0,0 +1,3 @@ +--- +title: "Suche" +--- diff --git a/hugo/hugo.template.toml b/hugo/hugo.template.toml new file mode 100644 index 0000000..8f2b737 --- /dev/null +++ b/hugo/hugo.template.toml @@ -0,0 +1,175 @@ +# hugo/hugo.template.toml +# Root configuration for Ableger - template, not read by Hugo directly. +# scripts/generate-config.sh generates hugo/hugo.toml from this file (same +# {{VARIABLE}} substitution it already does for admin/config.yml), filling +# in WEBSITE_DOMAIN/GITEA_DOMAIN/METHODEN_REPO from install.env. hugo.toml +# itself is generated and not versioned (see .gitignore) - edit this file +# instead. Reason: Hugo's own config file can't read install.env, so these +# two values (baseURL, methoden_repo_url below) would otherwise have to be +# kept in sync by hand on every fork - found live, twice, while setting up +# a second test instance. + +baseURL = "https://{{WEBSITE_DOMAIN}}/" +locale = "de-DE" +title = "Ableger" + +# Once module.mounts is set at all, every mount needed must be listed +# explicitly - Hugo's default mounts no longer apply automatically then. + +[[module.mounts]] + # Method content lives in the separate repo ableger_demo/ableger_methoden + # (see the concept chapter on the project website Abschnitt 9). ../_content is freshly fetched by + # scripts/sync-methoden.sh (not versioned, see .gitignore) and itself + # contains a methoden/ subfolder (Decap CMS workaround, see + # admin/config.yml). + source = "../_content/methoden" + target = "content" + +[[module.mounts]] + # Variants (preparation/procedure/background per method, see Konzept + # Abschnitt 8) live as their own Decap collection in a dedicated top-level + # folder in the content repo, not inside the method's own folder - the + # link to the corresponding method happens via a relation field, + # evaluated in hugo/layouts/_default/single.html via "where", not via + # file paths. varianten/_index.md (in the content repo, not managed by + # Decap) hides variant pages from all views that list methods (cascade + # "_build.list: never") - they can still be opened individually, just + # aren't part of .Site.RegularPages. + source = "../_content/varianten" + target = "content/varianten" + +[[module.mounts]] + # protokoll_version for the footer (see layouts/_default/baseof.html) - + # the same file that the Manifest chapter on the project website requires as Regel 14. Lives at the + # root of the content repo, not in methoden/ or varianten/. + source = "../_content/ableger.yml" + target = "data/ableger.yml" + +[[module.mounts]] + # Static pages with no relation to the content repo (currently: /suche/, + # see layouts/suche/list.html) - a dedicated mount versioned here in the + # website repo instead of a local hugo/content/ folder, because + # module.mounts is already set, so Hugo's implicit default mount for + # "content" no longer applies (see comment above). + source = "content-static" + target = "content" + +[[module.mounts]] + source = "static" + target = "static" + +[[module.mounts]] + source = "layouts" + target = "layouts" + +[[module.mounts]] + source = "assets" + target = "assets" + +[[module.mounts]] + source = "data" + target = "data" + +# Taxonomies: map the metadata fields from the schema (Abschnitt 8 of the +# Konzept) directly to filterable, searchable categories - no extra code. +# Key and value deliberately kept identical (instead of e.g. +# zielgruppe = "zielgruppen"): Hugo's automatic singular/plural detection is +# built for English words and otherwise creates extra, empty ghost +# taxonomies for German plural forms. The only exception: `tag`/"tags", +# because the frontmatter field itself is already called "tags". +# Variants live in Hugo's "varianten" section (see module.mounts above), +# but are meant to appear in the URL without a folder prefix, just like +# methods (expected by the Decap preview button, preview_path: +# "{{dirname}}" in admin/config.template.yml - without this override, +# preview would point to a 404 URL without the "varianten/" prefix). :slug +# is always "--" for variants, so it doesn't collide +# with method slugs. +[permalinks] + # :slug stays empty here (variants have no title/slug frontmatter field - + # the slug is derived purely from the folder name assigned by Decap), + # :contentbasename is used instead, which takes the actual bundle folder + # name. Verified live: with :slug, all variant URLs collapsed onto "/" + # (":filename" would be the obvious name, but has been removed since Hugo + # 0.144). + varianten = "/:contentbasename/" + +# Raw markdown per variant, for the methoden-set tool (methoden-set/, see +# the Methoden-Set chapter on the project website) - serves a self-describing markdown document under +# "index.md" (own YAML header, steckbrief and variant fields, +# content, attachment links) that the client fetches via fetch(), instead +# of parsing HTML. +[outputFormats.MethodenSetMd] + mediaType = "text/markdown" + baseName = "index" + isPlainText = true + notAlternative = true + +[[cascade]] + outputs = ["HTML", "MethodenSetMd"] + [cascade.target] + kind = "page" + path = "{/varianten/**}" + +# Method URLs also serve "index.md" - with exactly one variant, using the +# same document as the variant itself (see partials/methoden-set- +# dokument.html and _default/single.md), otherwise a short notice document. +# Reason: if a method has only one variant, its HTML page +# (_default/single.html) embeds the variant text directly, without showing +# a visible link to the actual variant URL - so users are likely to copy +# the method URL, not the (non-obvious) variant URL. A dedicated, second +# cascade rule instead of a single "{/**}" pattern for both sections: +# method paths have exactly one segment ("/beispiel-methode"), variant +# paths have two ("/varianten/") - the "{/*}" glob (no "**") only +# matches single path segments, so it doesn't collide with the rule above. +[[cascade]] + outputs = ["HTML", "MethodenSetMd"] + [cascade.target] + kind = "page" + path = "{/*}" + +# Serves the site title (among other things) as JSON under /site-meta.json - +# admin/index.html and admin/status/index.html are plain static files +# without Hugo templating (see the installation guide on the project website, copied unchanged +# via rsync) and therefore load this file via fetch(), so "Ableger" isn't +# hardcoded a second time in the title/header but taken from .Site.Title. +[outputFormats.SiteMeta] + mediaType = "application/json" + baseName = "site-meta" + isPlainText = true + notAlternative = true + +[outputs] + home = ["HTML", "RSS", "SiteMeta"] + +[taxonomies] + zielgruppe = "zielgruppe" + kompetenzbereich = "kompetenzbereich" + kategorie = "kategorie" + tag = "tags" + +[params] + # First sentence on the homepage - deliberately generic instead of + # provider-specific, so forks don't have to change it. + beschreibung = "Ableger ist eine strukturierte Sammlung von Methoden." + # Primary (accent) color of the read UI - set as a CSS custom property in baseof.html. + farbe_primaer = "#3c8a98" + # Footer link to the content repo (see layouts/_default/baseof.html) - + # replaces a blanket license sentence, which would be wrong anyway since + # variants were introduced (no longer ONE value for all methods, see the + # "Manifest" chapter on the project website). Derived automatically from + # GITEA_DOMAIN + METHODEN_REPO in install.env, not edited here directly. + methoden_repo_url = "https://{{GITEA_DOMAIN}}/{{METHODEN_REPO}}" + # Provider name for the footer (see layouts/_default/baseof.html). + # Rendered as a link when betreiber_url is set, otherwise as plain text. + betreiber_name = "Ableger-Projekt" + # Link to the provider. Placeholder - adjust on a fork. + betreiber_url = "https://example.org" + # Imprint, privacy policy, and a link to the website repo (counterpart to + # methoden_repo_url above, for the footer placeholder "Ableger-Projekt") - + # still without a target, since there is no project page for it yet. As + # long as these three lines stay commented out, the footer keeps showing + # the previous "Folgt" placeholder (see baseof.html). On a fork, fill in + # your own URL here once you have one. + # impressum_url = "" + # datenschutz_url = "" + # website_repo_url = "" diff --git a/hugo/layouts/_default/_markup/render-image.html b/hugo/layouts/_default/_markup/render-image.html new file mode 100644 index 0000000..b3a680d --- /dev/null +++ b/hugo/layouts/_default/_markup/render-image.html @@ -0,0 +1,18 @@ +{{/* We resolve image paths in variant content (![](datei.svg)) via the + page resources of the page the content belongs to (the variant) - not + the page that embeds .Content. With only one variant, the method page + (hugo/layouts/_default/single.html) embeds this content directly; a + raw relative path would resolve against the wrong URL there (the file + lives in the variant's bundle folder, not the method's). An absolute + permalink makes the embed location-independent. */}} +{{- $resource := "" }} +{{- if not (urls.Parse .Destination).IsAbs }} + {{- with .Page.Resources.GetMatch .Destination }} + {{- $resource = . }} + {{- end }} +{{- end }} +{{- if $resource }} +{{ .Text }} +{{- else }} +{{ .Text }} +{{- end }} diff --git a/hugo/layouts/_default/baseof.html b/hugo/layouts/_default/baseof.html new file mode 100644 index 0000000..05edaf2 --- /dev/null +++ b/hugo/layouts/_default/baseof.html @@ -0,0 +1,191 @@ + + + + + + {{ $seiten_titel := .Params.titel | default .Title }} + {{ $beschreibung := .Params.kurzbeschreibung | default .Site.Params.beschreibung }} + {{ if eq .Section "varianten" }} + {{ with partial "methode-fuer-variante.html" . }} + {{ $seiten_titel = printf "%s – %s" (.Params.titel | default .Title) $.Params.untertitel }} + {{ $beschreibung = .Params.kurzbeschreibung | default $.Site.Params.beschreibung }} + {{ end }} + {{ end }} + {{ if .IsHome }}{{ .Site.Title }}{{ else }}{{ $seiten_titel }} · {{ .Site.Title }}{{ end }} + + + {{/* SVG first: has dark-mode switching built in (@media + prefers-color-scheme within the file itself) and is preferred by + current browsers. The PNG variants below are the fallback for + browsers/contexts without SVG favicon support - since PNGs can't do + @media queries themselves, there's a separate light/dark pair for + them with media="(prefers-color-scheme: ...)" on the itself + (introduced by Safari, meanwhile more widely supported). Without + this, the PNG fallback would be low-contrast in dark browser chrome + (dark green icon on a transparent background). */}} + + + + + + + {{ with .Site.Params.farbe_primaer }} + + {{ end }} + + + + + + {{/* data-pagefind-body limits the area indexed by Pagefind to the actual + page content - without this attribute, Pagefind would also index the + header (logo, "Suchen"/"Stöbern", navigation) and footer on every + single page, and every search hit would additionally carry these + terms in the index. This lives here in baseof.html, so it applies + equally to every page - no risk that individual pages drop out of + the index because of it (per Pagefind's own docs: "if + data-pagefind-body appears anywhere on the site, pages without this + attribute are no longer indexed at all"). */}} +
+ {{ block "main" . }}{{ end }} +
+ +
+ +
+ + + + diff --git a/hugo/layouts/_default/list.html b/hugo/layouts/_default/list.html new file mode 100644 index 0000000..72fdb0e --- /dev/null +++ b/hugo/layouts/_default/list.html @@ -0,0 +1,11 @@ +{{ define "main" }} +
+

{{ .Title }}

+ {{ with .Content }}
{{ . }}
{{ end }} +
+ {{ range sort .Pages "Params.titel" }} + {{ partial "method-card.html" . }} + {{ end }} +
+
+{{ end }} diff --git a/hugo/layouts/_default/single.html b/hugo/layouts/_default/single.html new file mode 100644 index 0000000..1f5003b --- /dev/null +++ b/hugo/layouts/_default/single.html @@ -0,0 +1,40 @@ +{{ define "main" }} +{{ $methode := . }} +
+
+

{{ .Params.titel | default .Title }}

+ {{ with .Params.kurzbeschreibung }}

{{ . }}

{{ end }} + {{ with index hugo.Data.methoden $.File.ContentBaseName }} +

Erstellt: {{ .erstellt | time.AsTime | dateFormat "02.01.2006" }}

+

Zuletzt geändert: {{ .geaendert | time.AsTime | dateFormat "02.01.2006" }}

+ {{ end }} +
+ + {{ partial "steckbrief-box.html" (dict "methode" $methode "zeigeKurzbeschreibung" false "zeigeLink" false) }} + + {{/* Linked via Params.kennung, not via Params.titel or the folder + name/slug: the title may change at any time (see + the Manifest chapter on the project website), the kennung may not - Decap's relation widget + therefore stores the method's kennung in the variant's "methode" + field (value_field: "kennung" in admin/config.template.yml). */}} + {{ $varianten := partial "varianten-fuer-methode.html" . }} + {{ $varianten = sort $varianten "Params.untertitel" }} + + {{ if eq (len $varianten) 1 }} + {{ with index $varianten 0 }} + {{ partial "diese-variante.html" . }} +
+ {{ .Content }} +
+ {{ partial "attachments.html" . }} + {{ end }} + {{ else if gt (len $varianten) 1 }} +
+

Varianten

+
+ {{ range $varianten }}{{ partial "variante-card.html" . }}{{ end }} +
+
+ {{ end }} +
+{{ end }} diff --git a/hugo/layouts/_default/single.md b/hugo/layouts/_default/single.md new file mode 100644 index 0000000..518084d --- /dev/null +++ b/hugo/layouts/_default/single.md @@ -0,0 +1,27 @@ +{{/* Served under "index.md" (see [outputFormats.MethodenSetMd] + and the second cascade rule in hugo/hugo.toml), for the methoden-set + tool (methoden-set/, see the Methoden-Set chapter on the project website). Same "one variant -> + embed" logic as _default/single.html (see there): if the method has + exactly one variant, this URL returns exactly the same document as + the variant URL itself (partials/methoden-set-dokument.html) - methods + with only one variant otherwise have no URL usable via the tool, + because the HTML page embeds the variant text directly, without + showing a visible link to the actual variant URL. With 0 or several + variants, a short notice document instead of a generic 404 in the + tool - see its error messages in methoden-set/app.js. */}} +{{- $methode := . -}} +{{- $varianten := partial "varianten-fuer-methode.html" . -}} +{{- if eq (len $varianten) 1 -}} +{{- partial "methoden-set-dokument.html" (index $varianten 0) -}} +{{- else -}} +--- +titel: {{ (.Params.titel | default .Title) | jsonify }} +quelle: {{ .Permalink | jsonify }} +fehler: {{ if gt (len $varianten) 1 }}"mehrere_varianten"{{ else }}"keine_variante"{{ end }} +--- +{{ if gt (len $varianten) 1 -}} +Diese Methode hat mehrere Varianten. Bitte auf der Methoden-Seite die gewünschte Variante öffnen und deren eigenen Link einfügen. +{{- else -}} +Diese Methode hat noch keine veröffentlichte Variante. +{{- end }} +{{- end -}} diff --git a/hugo/layouts/_default/terms.html b/hugo/layouts/_default/terms.html new file mode 100644 index 0000000..80a99f4 --- /dev/null +++ b/hugo/layouts/_default/terms.html @@ -0,0 +1,10 @@ +{{ define "main" }} +
+

{{ .Title }}

+
    + {{ range .Pages }} +
  • {{ .Title }} ({{ len .Pages }})
  • + {{ end }} +
+
+{{ end }} diff --git a/hugo/layouts/index.html b/hugo/layouts/index.html new file mode 100644 index 0000000..499ce41 --- /dev/null +++ b/hugo/layouts/index.html @@ -0,0 +1,135 @@ +{{ define "main" }} +{{/* Variants (section "varianten") are detail pages per method, not their + own methods - deliberately excluded everywhere here, otherwise they'd + show up twice in search/filter/card list. Methods themselves live at + the content root (section ""), see hugo/hugo.toml. */}} +{{ $methodenPages := where site.RegularPages "Section" "" }} + +{{/* Duration/group size/license no longer sit directly on the method since + variants were introduced, but are aggregated per method from its + variants into a range/set (partials/variantenspanne.html) - here + additionally aggregated across all methods, for the outer bounds of + the filter sliders resp. the license filter list. */}} +{{ $dauerMin := 0 }}{{ $dauerMax := 0 }}{{ $dauerSeen := false }} +{{ $groesseMin := 0 }}{{ $groesseMax := 0 }}{{ $groesseSeen := false }} +{{ $lizenzen := slice }} +{{ range $methodenPages }} + {{/* partialCached with .RelPermalink as the key: method-card.html below + computes the same partial for the same page again - caching avoids + running the variantenspanne.html aggregation twice per method. */}} + {{ $spanne := partialCached "variantenspanne.html" . .RelPermalink }} + {{ $lizenzen = $lizenzen | append $spanne.lizenzen }} + {{ if $spanne.dauerSeen }} + {{ if $dauerSeen }} + {{ if lt $spanne.dauerMin $dauerMin }}{{ $dauerMin = $spanne.dauerMin }}{{ end }} + {{ if gt $spanne.dauerMax $dauerMax }}{{ $dauerMax = $spanne.dauerMax }}{{ end }} + {{ else }} + {{ $dauerMin = $spanne.dauerMin }}{{ $dauerMax = $spanne.dauerMax }}{{ $dauerSeen = true }} + {{ end }} + {{ end }} + {{ if $spanne.groesseSeen }} + {{ if $groesseSeen }} + {{ if lt $spanne.groesseMin $groesseMin }}{{ $groesseMin = $spanne.groesseMin }}{{ end }} + {{ if gt $spanne.groesseMax $groesseMax }}{{ $groesseMax = $spanne.groesseMax }}{{ end }} + {{ else }} + {{ $groesseMin = $spanne.groesseMin }}{{ $groesseMax = $spanne.groesseMax }}{{ $groesseSeen = true }} + {{ end }} + {{ end }} +{{ end }} +{{ $lizenzen = $lizenzen | uniq | sort }} + +
+

+ {{/* Bridge to the Pagefind full-text search (layouts/suche/list.html): + the search up here only filters the cards' title/description/tags, + not the full variant text. filter.js keeps the href live in sync + with the current search field content. */}} + Volltextsuche über alle Inhalte + +
+ Filter +
+
+ Zielgruppe + {{ range $term, $pages := .Site.Taxonomies.zielgruppe }} + + {{ end }} +
+ +
+ Kompetenzbereich + {{ range $term, $pages := .Site.Taxonomies.kompetenzbereich }} + + {{ end }} +
+ +
+ Kategorie + {{ range $term, $pages := .Site.Taxonomies.kategorie }} + + {{ end }} +
+ + {{ if gt (len $lizenzen) 1 }} +
+ Lizenz + {{ range $lizenzen }} + + {{ end }} +
+ {{ end }} + + {{ if $dauerSeen }} +
+
+ Dauer: {{ $dauerMin }}–{{ $dauerMax }} Min. +
+
+
+
+ + +
+
+ {{ end }} + + {{ if $groesseSeen }} +
+
+ Gruppengröße: {{ $groesseMin }}–{{ $groesseMax }} +
+
+
+
+ + +
+
+ {{ end }} + + +
+
+
+ +
+
+ {{ range sort $methodenPages "Params.titel" }} + {{ partial "method-card.html" . }} + {{ end }} +
+ +
+{{ end }} diff --git a/hugo/layouts/index.json b/hugo/layouts/index.json new file mode 100644 index 0000000..c066914 --- /dev/null +++ b/hugo/layouts/index.json @@ -0,0 +1,5 @@ +{{- /* Site metadata for admin/index.html and admin/status/index.html (see + hugo.toml, outputFormats.SiteMeta) - these two files are plain static + HTML without Hugo templating and load this file via fetch(), so the + site title isn't hardcoded a second time. */ -}} +{{- dict "title" .Site.Title | jsonify -}} diff --git a/hugo/layouts/partials/attachments.html b/hugo/layouts/partials/attachments.html new file mode 100644 index 0000000..b1c4351 --- /dev/null +++ b/hugo/layouts/partials/attachments.html @@ -0,0 +1,16 @@ +{{/* Attachments belong to the variant (page resources in the respective + bundle folder), not the method - called with the respective variant + page as context. */}} +{{ with .Params.anhaenge }} +
+

Anhänge

+ +
+{{ end }} diff --git a/hugo/layouts/partials/diese-variante.html b/hugo/layouts/partials/diese-variante.html new file mode 100644 index 0000000..1d06325 --- /dev/null +++ b/hugo/layouts/partials/diese-variante.html @@ -0,0 +1,33 @@ +{{/* "Diese Variante" (this variant) - all variant-specific details, + deliberately NOT in the steckbrief box (see + partials/steckbrief-box.html), so the box always looks the same + regardless of the number of variants. The variant description is + deliberately shown first, right under the heading. Shared between the + method page (when the method has exactly one variant) and the variant + page itself - see the project website (background/analysis notes) Teil 2.3. Called with + the respective variant as context. */}} +{{ $variante := . }} +
+

Diese Variante

+ {{ with $variante.Params.varianten_beschreibung }}

{{ . }}

{{ end }} +
+ {{ if isset $variante.Params "dauer_minuten" }}
Dauer
{{ $variante.Params.dauer_minuten }} Minuten
{{ end }} + {{ if or (isset $variante.Params "gruppengroesse_min") (isset $variante.Params "gruppengroesse_max") }} +
Gruppengröße
{{ if eq $variante.Params.gruppengroesse_min $variante.Params.gruppengroesse_max }}{{ $variante.Params.gruppengroesse_min }}{{ else }}{{ $variante.Params.gruppengroesse_min }}–{{ $variante.Params.gruppengroesse_max }}{{ end }}
+ {{ end }} + {{ with $variante.Params.lizenz }}
Lizenz
{{ . }}
{{ end }} + {{ with $variante.Params.kennung }}
ID
{{ . }}
{{ end }} +
+ {{ with $variante.Params.material }} +

Material

+
    {{ range . }}
  • {{ . }}
  • {{ end }}
+ {{ end }} + {{ with $variante.Params.autoren }} +

Autor:innen

+
    {{ range . }}
  • {{ . }}
  • {{ end }}
+ {{ end }} + {{ with $variante.Params.quellen }} +

Quellen

+
    {{ range . }}
  • {{ . }}
  • {{ end }}
+ {{ end }} +
diff --git a/hugo/layouts/partials/method-card.html b/hugo/layouts/partials/method-card.html new file mode 100644 index 0000000..c1379b4 --- /dev/null +++ b/hugo/layouts/partials/method-card.html @@ -0,0 +1,65 @@ +{{ $p := . }} +{{ $spanne := partialCached "variantenspanne.html" $p $p.RelPermalink }} +{{ $searchbits := slice ($p.Params.titel | default $p.Title) }} +{{ with $p.Params.kurzbeschreibung }}{{ $searchbits = $searchbits | append . }}{{ end }} +{{ with $p.Params.verwendungsmoeglichkeit }}{{ $searchbits = $searchbits | append . }}{{ end }} +{{ with $p.Params.zielgruppe }}{{ $searchbits = $searchbits | append (delimit . " ") }}{{ end }} +{{ with $p.Params.kompetenzbereich }}{{ $searchbits = $searchbits | append (delimit . " ") }}{{ end }} +{{ with $p.Params.kategorie }}{{ $searchbits = $searchbits | append (delimit . " ") }}{{ end }} +{{ with $p.Params.tags }}{{ $searchbits = $searchbits | append (delimit . " ") }}{{ end }} +{{ with $spanne.lizenzen }}{{ $searchbits = $searchbits | append (delimit . " ") }}{{ end }} +{{ $searchtext := delimit $searchbits " " | lower }} +
+

{{ $p.Params.titel | default $p.Title }}

+ {{ with $p.Params.kurzbeschreibung }}

{{ . }}

{{ end }} +
+ {{ if $spanne.dauerSeen }} +
Dauer
{{ if eq $spanne.dauerMin $spanne.dauerMax }}{{ $spanne.dauerMin }}{{ else }}{{ $spanne.dauerMin }}–{{ $spanne.dauerMax }}{{ end }} Min.
+ {{ end }} + {{ if $spanne.groesseSeen }} +
Gruppengröße
{{ if eq $spanne.groesseMin $spanne.groesseMax }}{{ $spanne.groesseMin }}{{ else }}{{ $spanne.groesseMin }}–{{ $spanne.groesseMax }}{{ end }}
+ {{ end }} +
+ {{ with $p.Params.zielgruppe }} +
+

Zielgruppe

+
    + {{ range . }}
  • {{ end }} +
+
+ {{ end }} + {{ with $p.Params.kompetenzbereich }} +
+

Kompetenzbereich

+
    + {{ range . }}
  • {{ end }} +
+
+ {{ end }} + {{ with $p.Params.kategorie }} +
+

Kategorie

+
    + {{ range . }}
  • {{ end }} +
+
+ {{ end }} + {{ with $p.Params.tags }} +
+

Tags

+
    + {{ range . }}
  • {{ end }} +
+
+ {{ end }} +
diff --git a/hugo/layouts/partials/methode-fuer-variante.html b/hugo/layouts/partials/methode-fuer-variante.html new file mode 100644 index 0000000..6db1857 --- /dev/null +++ b/hugo/layouts/partials/methode-fuer-variante.html @@ -0,0 +1,7 @@ +{{/* Returns the method page belonging to the variant (or nil, if none is + found - should practically never happen due to Regel 1 in + scripts/validate.rb). Called with the respective variant as context. + Linked via Params.kennung, not via Params.titel or the filename/slug, + see admin/config.template.yml and the Manifest chapter on the project website. */}} +{{ $matches := where site.RegularPages "Params.kennung" .Params.methode }} +{{ if $matches }}{{ return (index $matches 0) }}{{ end }} diff --git a/hugo/layouts/partials/methoden-set-dokument.html b/hugo/layouts/partials/methoden-set-dokument.html new file mode 100644 index 0000000..49f78e5 --- /dev/null +++ b/hugo/layouts/partials/methoden-set-dokument.html @@ -0,0 +1,85 @@ +{{/* Self-describing markdown document for a variant, for the methoden-set + tool (methoden-set/, see the Methoden-Set chapter on the project website). Shared by + varianten/single.md (own variant URL) and _default/single.md (method + URL, when the method has exactly one variant - the same "one variant + -> embed" logic as _default/single.html, see there) - methods with + only one variant otherwise have no URL usable via the tool, because + their HTML page embeds the variant text directly, without showing a + visible link to the actual variant URL. Deliberately ONLY a minimal + YAML header (titel, quelle) - the client only needs the title from it + for the sort list and the source as a validation anchor; authors/ + license/origin are instead written as readable text directly into the + body (a prose citation at the end), no second metadata structure to + parse in JS needed for that - assembly happens here in Hugo, not in + the client. Fields/order follow partials/steckbrief-box.html and + partials/diese-variante.html, just rendered as markdown instead of + HTML. Called with the respective variant as context. */}} +{{- $variante := . -}} +{{- $methode := partial "methode-fuer-variante.html" . -}} +{{- $methodenTitel := "" -}} +{{- with $methode }}{{ $methodenTitel = (.Params.titel | default .Title) }}{{ end -}} +{{- $titel := printf "%s – %s" $methodenTitel $variante.Params.untertitel -}} +{{/* Embedded images (![](datei.svg)) are still relative in the raw + markdown - unlike .Content (see _markup/render-image.html), Hugo does + not apply its render hooks to .RawContent. So for every page resource + of the variant, the filename in the parenthesized part of a markdown + image reference is replaced here by the absolute permalink URL, so the + image also resolves outside the original page (zip/markdown/Word) - + covers the "![Alt](datei)" case used in practice, not every + conceivable markdown syntax variant (e.g. reference links). */ -}} +{{- $inhalt := $variante.RawContent -}} +{{- range $variante.Resources -}} + {{- $inhalt = replace $inhalt (printf "](%s)" .Name) (printf "](%s)" .Permalink) -}} +{{- end -}} +{{/* Sections written by users (preparation/procedure/background) are H1 in + the editor, but here should sit under the document heading and + "## Diese Variante", not next to it - see + partials/methoden-set-shift-headings.html. */ -}} +{{- $inhalt = partial "methoden-set-shift-headings.html" $inhalt -}} +--- +titel: {{ $titel | jsonify }} +quelle: {{ $variante.Permalink | jsonify }} +--- +# {{ $titel }} + +{{ with $methode }} +{{ with .Params.verwendungsmoeglichkeit }}{{ . }} +{{ end }} +## Steckbrief + +{{ with .Params.zielgruppe }}- Zielgruppe: {{ delimit . ", " }} +{{ end -}} +{{ with .Params.kompetenzbereich }}- Kompetenzbereich: {{ delimit . ", " }} +{{ end -}} +{{ with .Params.kategorie }}- Kategorie: {{ delimit . ", " }} +{{ end -}} +{{ if isset $variante.Params "dauer_minuten" }}- Dauer: {{ $variante.Params.dauer_minuten }} Minuten +{{ end -}} +{{ if or (isset $variante.Params "gruppengroesse_min") (isset $variante.Params "gruppengroesse_max") -}} +- Gruppengröße: {{ if eq $variante.Params.gruppengroesse_min $variante.Params.gruppengroesse_max }}{{ $variante.Params.gruppengroesse_min }}{{ else }}{{ $variante.Params.gruppengroesse_min }}–{{ $variante.Params.gruppengroesse_max }}{{ end }} +{{ end -}} +{{ with $variante.Params.lizenz }}- Lizenz: {{ . }} +{{ end }} +{{ with .Params.lernchancen }}**Lernchancen:** {{ delimit . ", " }} + +{{ end -}} +{{ end }} +## Diese Variante + +{{ with $variante.Params.varianten_beschreibung }}{{ . }} + +{{ end -}} +{{ $inhalt }} + +{{ with $variante.Params.anhaenge }} +## Anhänge + +{{ range . }} +{{ $anhang := . }} +{{ with $variante.Resources.GetMatch $anhang.datei }}- [{{ $anhang.beschreibung | default $anhang.datei }}]({{ .Permalink }}) +{{ end -}} +{{ end }} +{{ end }} +--- + +*Quelle: [{{ $titel }}]({{ $variante.Permalink }}){{ with $variante.Params.autoren }} · Autor:innen: {{ delimit . ", " }}{{ end }}{{ with $variante.Params.lizenz }} · Lizenz: {{ . }}{{ end }}* diff --git a/hugo/layouts/partials/methoden-set-shift-headings.html b/hugo/layouts/partials/methoden-set-shift-headings.html new file mode 100644 index 0000000..3906e15 --- /dev/null +++ b/hugo/layouts/partials/methoden-set-shift-headings.html @@ -0,0 +1,36 @@ +{{/* Shifts ATX headings (#, ##, ...) in the given markdown text down by one + level (H1->H2 etc.), outside fenced code blocks (``` or ~~~). Reason: + users write preparation/procedure/background as standalone H1 + sections (see the Decap CMS editor), which in the methoden-set + document (varianten/single.md) should sit under the document heading + and "## Diese Variante" though, not next to it at the same level. + Called with the text as context, returns the shifted text (see + hugo/layouts/varianten/single.md). Known limit: at most H5->H6, an H6 + would stay unshifted (no valid H7 in markdown) - doesn't occur in + practice for this content (preparation/procedure/background, rarely + deeper than H3). */}} +{{- $text := . -}} +{{- $lines := split $text "\n" -}} +{{- $inFence := false -}} +{{- $fenceChar := "" -}} +{{- $ergebnis := slice -}} +{{- range $lines -}} + {{- $line := . -}} + {{- $trimmed := trim $line " \t" -}} + {{- $neueZeile := $line -}} + {{- if or (hasPrefix $trimmed "```") (hasPrefix $trimmed "~~~") -}} + {{- $char := substr $trimmed 0 1 -}} + {{- if not $inFence -}} + {{- $inFence = true -}} + {{- $fenceChar = $char -}} + {{- else if eq $char $fenceChar -}} + {{- $inFence = false -}} + {{- end -}} + {{- else if not $inFence -}} + {{- if findRE "^#{1,5} " $line -}} + {{- $neueZeile = printf "#%s" $line -}} + {{- end -}} + {{- end -}} + {{- $ergebnis = $ergebnis | append $neueZeile -}} +{{- end -}} +{{- delimit $ergebnis "\n" -}} diff --git a/hugo/layouts/partials/steckbrief-box.html b/hugo/layouts/partials/steckbrief-box.html new file mode 100644 index 0000000..b1f6186 --- /dev/null +++ b/hugo/layouts/partials/steckbrief-box.html @@ -0,0 +1,51 @@ +{{/* The "Steckbrief" (profile) box looks the same everywhere, regardless of + whether it's seen on the method page (with one or several variants) + or on the variant page - see the project website (background/analysis notes) Teil 2.3. It + therefore contains exclusively method-owned details: + verwendungsmoeglichkeit, zielgruppe/kompetenzbereich/kategorie/ID, + lernchancen, herkunft, initiatoren, tags. Variant-specific fields + (variant description, duration, group size, material, authors, + license, sources) deliberately do NOT belong here, see + partials/diese-variante.html - otherwise the box would look different + depending on the number of variants. Expects a dict: methode, + zeigeKurzbeschreibung (true only on the variant page, since it's not + visible anywhere else there - on the method page it's already in + method__header), zeigeLink (true only on the variant page, for the + back-link to the method). */}} +{{ $methode := .methode }} +
+

Steckbrief

+ {{ if .zeigeKurzbeschreibung }} + {{ with $methode.Params.kurzbeschreibung }}

{{ . }}

{{ end }} + {{ end }} + {{ with $methode.Params.verwendungsmoeglichkeit }} +

Verwendungsmöglichkeit

+

{{ . }}

+ {{ end }} +
+ {{ with $methode.Params.zielgruppe }}
Zielgruppe
{{ delimit . ", " }}
{{ end }} + {{ with $methode.Params.kompetenzbereich }}
Kompetenzbereich
{{ delimit . ", " }}
{{ end }} + {{ with $methode.Params.kategorie }}
Kategorie
{{ delimit . ", " }}
{{ end }} + {{ with $methode.Params.kennung }}
ID
{{ . }}
{{ end }} +
+ {{ with $methode.Params.lernchancen }} +

Lernchancen

+
    {{ range . }}
  • {{ . }}
  • {{ end }}
+ {{ end }} + {{ with $methode.Params.herkunft }} +

Herkunft

+
    {{ range . }}
  • {{ . }}
  • {{ end }}
+ {{ end }} + {{ with $methode.Params.initiatoren }} +

Initiator:innen

+
    {{ range . }}
  • {{ . }}
  • {{ end }}
+ {{ end }} + {{ with $methode.Params.tags }} +
    + {{ range . }}
  • {{ . }}
  • {{ end }} +
+ {{ end }} + {{ if .zeigeLink }} +

Zur Methode „{{ $methode.Params.titel | default $methode.Title }}“ →

+ {{ end }} +
diff --git a/hugo/layouts/partials/variante-card.html b/hugo/layouts/partials/variante-card.html new file mode 100644 index 0000000..991f474 --- /dev/null +++ b/hugo/layouts/partials/variante-card.html @@ -0,0 +1,25 @@ +{{/* Comparison card for a variant - used both in the multi-variant list on + the method page and in the "Andere Varianten dieser Methode" (other + variants of this method) section on the variant page itself (see + hugo/layouts/_default/single.html and + hugo/layouts/varianten/single.html). Deliberately shows only the + fields meant for comparison - variant description, duration, group + size, authors, license, date - no material and no attachments (see + the project website (background/analysis notes) Teil 2.2), no highlighting of differing + values. Called with the respective variant as context. */}} +{{ $variante := . }} +
+

{{ $variante.Params.untertitel }}

+ {{ with $variante.Params.varianten_beschreibung }}

{{ . }}

{{ end }} +
+ {{ if isset $variante.Params "dauer_minuten" }}
Dauer
{{ $variante.Params.dauer_minuten }} Min.
{{ end }} + {{ if or (isset $variante.Params "gruppengroesse_min") (isset $variante.Params "gruppengroesse_max") }} +
Gruppengröße
{{ if eq $variante.Params.gruppengroesse_min $variante.Params.gruppengroesse_max }}{{ $variante.Params.gruppengroesse_min }}{{ else }}{{ $variante.Params.gruppengroesse_min }}–{{ $variante.Params.gruppengroesse_max }}{{ end }}
+ {{ end }} + {{ with $variante.Params.lizenz }}
Lizenz
{{ . }}
{{ end }} +
+ {{ with $variante.Params.autoren }}

Autor:innen: {{ delimit . ", " }}

{{ end }} + {{ with index hugo.Data.varianten $variante.File.ContentBaseName }} +

Zuletzt geändert: {{ .geaendert | time.AsTime | dateFormat "02.01.2006" }}

+ {{ end }} +
diff --git a/hugo/layouts/partials/varianten-fuer-methode.html b/hugo/layouts/partials/varianten-fuer-methode.html new file mode 100644 index 0000000..d262659 --- /dev/null +++ b/hugo/layouts/partials/varianten-fuer-methode.html @@ -0,0 +1,10 @@ +{{/* Returns all variant pages (section "varianten") belonging to the given + method page, matched via Params.kennung, not title/slug (see + admin/config.template.yml and the Manifest chapter on the project website) - the reverse + direction of partials/methode-fuer-variante.html. Called with the + respective method as context. Unsorted and unfiltered - callers apply + their own sort/exclusion on top (see hugo/layouts/_default/single.html, + hugo/layouts/varianten/single.html, partials/variantenspanne.html, + hugo/layouts/_default/single.md). */}} +{{ $varianten := where (where site.RegularPages "Section" "varianten") "Params.methode" .Params.kennung }} +{{ return $varianten }} diff --git a/hugo/layouts/partials/variantenspanne.html b/hugo/layouts/partials/variantenspanne.html new file mode 100644 index 0000000..37c824d --- /dev/null +++ b/hugo/layouts/partials/variantenspanne.html @@ -0,0 +1,37 @@ +{{/* Computes the duration/group-size range and the set of licenses present + for a method from its variants. Called with the respective method + page as context, returns a dict with dauerMin/dauerMax/dauerSeen, + groesseMin/groesseMax/groesseSeen ("Seen" distinguishes "no value + present" from "value is 0") and lizenzen (sorted, unique list). Used + by the method page, the cards on the homepage, and the filters there, + so the same logic doesn't exist multiple times. Material deliberately + NOT here: no aggregation planned on the method page, see + admin/config.template.yml. */}} +{{ $methode := . }} +{{ $varianten := partial "varianten-fuer-methode.html" $methode }} + +{{ $dauerMin := 0 }}{{ $dauerMax := 0 }}{{ $dauerSeen := false }} +{{ $groesseMin := 0 }}{{ $groesseMax := 0 }}{{ $groesseSeen := false }} +{{ $lizenzen := slice }} +{{ range $varianten }} + {{ if isset .Params "dauer_minuten" }} + {{ $dauer := .Params.dauer_minuten }} + {{ if $dauerSeen }} + {{ if lt $dauer $dauerMin }}{{ $dauerMin = $dauer }}{{ end }} + {{ if gt $dauer $dauerMax }}{{ $dauerMax = $dauer }}{{ end }} + {{ else }} + {{ $dauerMin = $dauer }}{{ $dauerMax = $dauer }}{{ $dauerSeen = true }} + {{ end }} + {{ end }} + {{ if isset .Params "gruppengroesse_min" }} + {{ $gmin := .Params.gruppengroesse_min }} + {{ if $groesseSeen }}{{ if lt $gmin $groesseMin }}{{ $groesseMin = $gmin }}{{ end }}{{ else }}{{ $groesseMin = $gmin }}{{ $groesseSeen = true }}{{ end }} + {{ end }} + {{ if isset .Params "gruppengroesse_max" }} + {{ if gt .Params.gruppengroesse_max $groesseMax }}{{ $groesseMax = .Params.gruppengroesse_max }}{{ end }} + {{ end }} + {{ with .Params.lizenz }}{{ $lizenzen = $lizenzen | append . }}{{ end }} +{{ end }} +{{ $lizenzen = $lizenzen | uniq | sort }} + +{{ return dict "dauerMin" $dauerMin "dauerMax" $dauerMax "dauerSeen" $dauerSeen "groesseMin" $groesseMin "groesseMax" $groesseMax "groesseSeen" $groesseSeen "lizenzen" $lizenzen }} diff --git a/hugo/layouts/suche/list.html b/hugo/layouts/suche/list.html new file mode 100644 index 0000000..4b73c66 --- /dev/null +++ b/hugo/layouts/suche/list.html @@ -0,0 +1,66 @@ +{{ define "main" }} +{{/* A dedicated, deliberately simple full-text search via Pagefind instead + of trying to merge it here with the homepage's facet search + (index.html, filter.js) into one component: Pagefind only knows + pages/URLs, not the method-vs-variant relationship, so mixing it with + the card facets there would be a lot of glue code for little benefit. + Robustness over feature scope: Pagefind's own bundled default widget + (PagefindUI) instead of custom rendering of the results - see + https://pagefind.app/docs/ui/. The index itself is only created AFTER + the Hugo build (command-line step "pagefind --site public", see + the installation guide on the project website) - under "hugo server" there is no index yet, + see the note below in the script. */}} +
+

{{ .Title }}

+

+ Durchsucht alle veröffentlichten Methoden und Varianten vollständig – + auch Vorbereitung, Ablauf und Hintergründe, nicht nur Titel und Tags. + Für eine schnelle Filterung nach Zielgruppe, Kompetenzbereich, Kategorie, + Dauer oder Gruppengröße: Startseite mit Filtern. +

+
+
+ + + + +{{ end }} diff --git a/hugo/layouts/varianten/list.html b/hugo/layouts/varianten/list.html new file mode 100644 index 0000000..f828af1 --- /dev/null +++ b/hugo/layouts/varianten/list.html @@ -0,0 +1,10 @@ +{{ define "main" }} +{{/* Deliberately empty: variants are detail pages per method and are only + linked from there (see hugo/layouts/_default/single.html), not via + their own overview page. A dedicated template instead of a + content/varianten/_index.md with "build.render: never", so that no + file sits in the content repo that Decap CMS would incorrectly list + as a (broken) entry in the variants collection - the same class of + bug as a README.md in the collection folder, see the concept chapter on the project website + Abschnitt 9. */}} +{{ end }} diff --git a/hugo/layouts/varianten/single.html b/hugo/layouts/varianten/single.html new file mode 100644 index 0000000..3290e3e --- /dev/null +++ b/hugo/layouts/varianten/single.html @@ -0,0 +1,42 @@ +{{ define "main" }} +{{/* Linked via Params.kennung, not via Params.titel or the folder + name/slug, see hugo/layouts/_default/single.html and + admin/config.template.yml. The steckbrief box and "Diese Variante" are + the same partials as on the method page (case: exactly one variant) - + see the project website (background/analysis notes) Teil 2.3. */}} +{{ $variante := . }} +{{ $methode := partial "methode-fuer-variante.html" . }} +
+
+ {{ with $methode }}

← {{ .Params.titel | default .Title }}

{{ end }} +

{{ with $methode }}{{ .Params.titel | default .Title }} – {{ end }}{{ $variante.Params.untertitel }}

+ {{ with index hugo.Data.varianten $.File.ContentBaseName }} +

Erstellt: {{ .erstellt | time.AsTime | dateFormat "02.01.2006" }}

+

Zuletzt geändert: {{ .geaendert | time.AsTime | dateFormat "02.01.2006" }}

+ {{ end }} +
+ + {{ with $methode }} + {{ partial "steckbrief-box.html" (dict "methode" . "zeigeKurzbeschreibung" true "zeigeLink" true) }} + {{ end }} + + {{ partial "diese-variante.html" $variante }} + +
+ {{ $variante.Content }} +
+ {{ partial "attachments.html" $variante }} + + {{ with $methode }} + {{ $andere := where (partial "varianten-fuer-methode.html" .) "Params.kennung" "ne" $variante.Params.kennung }} + {{ with $andere }} +
+

Andere Varianten dieser Methode

+
+ {{ range . }}{{ partial "variante-card.html" . }}{{ end }} +
+
+ {{ end }} + {{ end }} +
+{{ end }} diff --git a/hugo/layouts/varianten/single.md b/hugo/layouts/varianten/single.md new file mode 100644 index 0000000..4d6eb8c --- /dev/null +++ b/hugo/layouts/varianten/single.md @@ -0,0 +1,6 @@ +{{/* Served under "index.md" (see [outputFormats.MethodenSetMd] + and the cascade rule in hugo/hugo.toml) - the assembly logic lives + together with _default/single.md (method with exactly one variant) in + partials/methoden-set-dokument.html. Called with the respective + variant as context (section "varianten"). */ -}} +{{- partial "methoden-set-dokument.html" . -}} diff --git a/hugo/static/apple-touch-icon.png b/hugo/static/apple-touch-icon.png new file mode 100644 index 0000000..4ff8dc3 Binary files /dev/null and b/hugo/static/apple-touch-icon.png differ diff --git a/hugo/static/css/style.css b/hugo/static/css/style.css new file mode 100644 index 0000000..dabd91d --- /dev/null +++ b/hugo/static/css/style.css @@ -0,0 +1,517 @@ +:root { + --color-bg: #fdfcfb; + --color-text: #1f2320; + --color-muted: #5b645d; + --color-accent: #3c8a98; + --color-accent-contrast: #fff; + --color-border: #dcd8d0; + --color-card-bg: #ffffff; + --radius: 8px; + --spacing: 1rem; +} + +@media (prefers-color-scheme: dark) { + :root { + --color-bg: #16181a; + --color-text: #e9e9e6; + --color-muted: #a3aba5; + --color-accent: #6fc2d1; + --color-accent-contrast: #06272b; + --color-border: #33372f; + --color-card-bg: #1f2321; + } +} + +* { box-sizing: border-box; } + +body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + background: var(--color-bg); + color: var(--color-text); + line-height: 1.55; +} + +a { color: var(--color-accent); } +a:focus-visible, button:focus-visible { outline: 3px solid var(--color-accent); outline-offset: 2px; } + +.site-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: var(--spacing); + padding: var(--spacing) 1.5rem; + border-bottom: 1px solid var(--color-border); + /* Explicit background instead of inheriting from body: on + admin/index.html, Decap's own, later-loading CSS-in-JS overrides + body's background color with its light-gray default - our text color + here (.site-title, our own class, untouched by Decap) still switches + correctly in dark mode though, which resulted in light text on a + light background. Found and verified live. */ + background: var(--color-bg); +} + +.site-title { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 1.25rem; + font-weight: 700; + text-decoration: none; + color: var(--color-text); +} + +.site-logo { display: block; } + +.visually-hidden { + position: absolute; + width: 1px; height: 1px; + padding: 0; margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +/* --- Header: "Suchen" and "Stöbern" --------------------------------- + Both open on hover (only on pointer devices that support hover - + deliberately not on touch, see media query below), on keyboard focus + (:focus-within, e.g. Tab to the search field), or on click/tap (the + "is-open" class, toggled by the inline script in baseof.html - the + only way on touch devices without hover). The search additionally + stays open once it contains a value, even without hover/focus - also + driven via "is-open", see script. */ + +.site-header__actions { display: flex; gap: 1.5rem; align-items: flex-start; } + +.header-search, .header-browse { position: relative; } + +.header-toggle { + display: inline-block; + cursor: pointer; + padding: 0.5rem 0.25rem; + border: 0; + background: transparent; + color: var(--color-text); + font: inherit; + font-weight: 500; + font-size: 0.9rem; + user-select: none; +} +.header-toggle:hover, .header-toggle[aria-expanded="true"] { color: var(--color-accent); } +/* header-toggle was designed for the Suchen/Stöbern + + +

2Reihenfolge festlegen

+

Per Ziehen sortieren. Seitenumbruch-Regler wirken sich nur auf den Word-Export aus.

+
+ +
+ Gliederungsvorschau +
+
+ +

3Herunterladen

+ +
+ + +
+ +
+ + +
+ +
+ +
+ +
+ + +
+

Format, Vorlage, Inhaltsverzeichnis und Kapitelnummerierung wirken sich nur auf den Dokument-Export aus.

+ +
+ + + +
+ +

+ + + + + diff --git a/methoden-set/vendor/pandoc.wasm b/methoden-set/vendor/pandoc.wasm new file mode 100644 index 0000000..e8ab25e Binary files /dev/null and b/methoden-set/vendor/pandoc.wasm differ diff --git a/methoden-set/vendor/wasi-shim/debug.js b/methoden-set/vendor/wasi-shim/debug.js new file mode 100644 index 0000000..b7e03ac --- /dev/null +++ b/methoden-set/vendor/wasi-shim/debug.js @@ -0,0 +1 @@ +let Debug=class Debug{enable(enabled){this.log=createLogger(enabled===undefined?true:enabled,this.prefix)}get enabled(){return this.isEnabled}constructor(isEnabled){this.isEnabled=isEnabled;this.prefix="wasi:";this.enable(isEnabled)}};function createLogger(enabled,prefix){if(enabled){const a=console.log.bind(console,"%c%s","color: #265BA0",prefix);return a}else{return()=>{}}}export const debug=new Debug(false); \ No newline at end of file diff --git a/methoden-set/vendor/wasi-shim/fd.js b/methoden-set/vendor/wasi-shim/fd.js new file mode 100644 index 0000000..f71cd9b --- /dev/null +++ b/methoden-set/vendor/wasi-shim/fd.js @@ -0,0 +1 @@ +import*as wasi from"./wasi_defs.js";export class Fd{fd_allocate(offset,len){return wasi.ERRNO_NOTSUP}fd_close(){return 0}fd_fdstat_get(){return{ret:wasi.ERRNO_NOTSUP,fdstat:null}}fd_fdstat_set_flags(flags){return wasi.ERRNO_NOTSUP}fd_fdstat_set_rights(fs_rights_base,fs_rights_inheriting){return wasi.ERRNO_NOTSUP}fd_filestat_get(){return{ret:wasi.ERRNO_NOTSUP,filestat:null}}fd_filestat_set_size(size){return wasi.ERRNO_NOTSUP}fd_filestat_set_times(atim,mtim,fst_flags){return wasi.ERRNO_NOTSUP}fd_pread(size,offset){return{ret:wasi.ERRNO_NOTSUP,data:new Uint8Array}}fd_prestat_get(){return{ret:wasi.ERRNO_NOTSUP,prestat:null}}fd_pwrite(data,offset){return{ret:wasi.ERRNO_NOTSUP,nwritten:0}}fd_read(size){return{ret:wasi.ERRNO_NOTSUP,data:new Uint8Array}}fd_readdir_single(cookie){return{ret:wasi.ERRNO_NOTSUP,dirent:null}}fd_seek(offset,whence){return{ret:wasi.ERRNO_NOTSUP,offset:0n}}fd_sync(){return 0}fd_tell(){return{ret:wasi.ERRNO_NOTSUP,offset:0n}}fd_write(data){return{ret:wasi.ERRNO_NOTSUP,nwritten:0}}path_create_directory(path){return wasi.ERRNO_NOTSUP}path_filestat_get(flags,path){return{ret:wasi.ERRNO_NOTSUP,filestat:null}}path_filestat_set_times(flags,path,atim,mtim,fst_flags){return wasi.ERRNO_NOTSUP}path_link(path,inode,allow_dir){return wasi.ERRNO_NOTSUP}path_unlink(path){return{ret:wasi.ERRNO_NOTSUP,inode_obj:null}}path_lookup(path,dirflags){return{ret:wasi.ERRNO_NOTSUP,inode_obj:null}}path_open(dirflags,path,oflags,fs_rights_base,fs_rights_inheriting,fd_flags){return{ret:wasi.ERRNO_NOTDIR,fd_obj:null}}path_readlink(path){return{ret:wasi.ERRNO_NOTSUP,data:null}}path_remove_directory(path){return wasi.ERRNO_NOTSUP}path_rename(old_path,new_fd,new_path){return wasi.ERRNO_NOTSUP}path_unlink_file(path){return wasi.ERRNO_NOTSUP}}export class Inode{static issue_ino(){return Inode.next_ino++}static root_ino(){return 0n}constructor(){this.ino=Inode.issue_ino()}}Inode.next_ino=1n; \ No newline at end of file diff --git a/methoden-set/vendor/wasi-shim/fs_mem.js b/methoden-set/vendor/wasi-shim/fs_mem.js new file mode 100644 index 0000000..35f0026 --- /dev/null +++ b/methoden-set/vendor/wasi-shim/fs_mem.js @@ -0,0 +1 @@ +import{debug}from"./debug.js";import*as wasi from"./wasi_defs.js";import{Fd,Inode}from"./fd.js";export class OpenFile extends Fd{fd_allocate(offset,len){if(this.file.size>offset+len){}else{const new_data=new Uint8Array(Number(offset+len));new_data.set(this.file.data,0);this.file.data=new_data}return wasi.ERRNO_SUCCESS}fd_fdstat_get(){return{ret:0,fdstat:new wasi.Fdstat(wasi.FILETYPE_REGULAR_FILE,0)}}fd_filestat_set_size(size){if(this.file.size>size){this.file.data=new Uint8Array(this.file.data.buffer.slice(0,Number(size)))}else{const new_data=new Uint8Array(Number(size));new_data.set(this.file.data,0);this.file.data=new_data}return wasi.ERRNO_SUCCESS}fd_read(size){const slice=this.file.data.slice(Number(this.file_pos),Number(this.file_pos+BigInt(size)));this.file_pos+=BigInt(slice.length);return{ret:0,data:slice}}fd_pread(size,offset){const slice=this.file.data.slice(Number(offset),Number(offset+BigInt(size)));return{ret:0,data:slice}}fd_seek(offset,whence){let calculated_offset;switch(whence){case wasi.WHENCE_SET:calculated_offset=offset;break;case wasi.WHENCE_CUR:calculated_offset=this.file_pos+offset;break;case wasi.WHENCE_END:calculated_offset=BigInt(this.file.data.byteLength)+offset;break;default:return{ret:wasi.ERRNO_INVAL,offset:0n}}if(calculated_offset<0){return{ret:wasi.ERRNO_INVAL,offset:0n}}this.file_pos=calculated_offset;return{ret:0,offset:this.file_pos}}fd_tell(){return{ret:0,offset:this.file_pos}}fd_write(data){if(this.file.readonly)return{ret:wasi.ERRNO_BADF,nwritten:0};if(this.file_pos+BigInt(data.byteLength)>this.file.size){const old=this.file.data;this.file.data=new Uint8Array(Number(this.file_pos+BigInt(data.byteLength)));this.file.data.set(old)}this.file.data.set(data,Number(this.file_pos));this.file_pos+=BigInt(data.byteLength);return{ret:0,nwritten:data.byteLength}}fd_pwrite(data,offset){if(this.file.readonly)return{ret:wasi.ERRNO_BADF,nwritten:0};if(offset+BigInt(data.byteLength)>this.file.size){const old=this.file.data;this.file.data=new Uint8Array(Number(offset+BigInt(data.byteLength)));this.file.data.set(old)}this.file.data.set(data,Number(offset));return{ret:0,nwritten:data.byteLength}}fd_filestat_get(){return{ret:0,filestat:this.file.stat()}}constructor(file){super();this.file_pos=0n;this.file=file}}export class OpenDirectory extends Fd{fd_seek(offset,whence){return{ret:wasi.ERRNO_BADF,offset:0n}}fd_tell(){return{ret:wasi.ERRNO_BADF,offset:0n}}fd_allocate(offset,len){return wasi.ERRNO_BADF}fd_fdstat_get(){return{ret:0,fdstat:new wasi.Fdstat(wasi.FILETYPE_DIRECTORY,0)}}fd_readdir_single(cookie){if(debug.enabled){debug.log("readdir_single",cookie);debug.log(cookie,this.dir.contents.keys())}if(cookie==0n){return{ret:wasi.ERRNO_SUCCESS,dirent:new wasi.Dirent(1n,this.dir.ino,".",wasi.FILETYPE_DIRECTORY)}}else if(cookie==1n){return{ret:wasi.ERRNO_SUCCESS,dirent:new wasi.Dirent(2n,this.dir.parent_ino(),"..",wasi.FILETYPE_DIRECTORY)}}if(cookie>=BigInt(this.dir.contents.size)+2n){return{ret:0,dirent:null}}const[name,entry]=Array.from(this.dir.contents.entries())[Number(cookie-2n)];return{ret:0,dirent:new wasi.Dirent(cookie+1n,entry.ino,name,entry.stat().filetype)}}path_filestat_get(flags,path_str){const{ret:path_err,path}=Path.from(path_str);if(path==null){return{ret:path_err,filestat:null}}const{ret,entry}=this.dir.get_entry_for_path(path);if(entry==null){return{ret,filestat:null}}return{ret:0,filestat:entry.stat()}}path_lookup(path_str,dirflags){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return{ret:path_ret,inode_obj:null}}const{ret,entry}=this.dir.get_entry_for_path(path);if(entry==null){return{ret,inode_obj:null}}return{ret:wasi.ERRNO_SUCCESS,inode_obj:entry}}path_open(dirflags,path_str,oflags,fs_rights_base,fs_rights_inheriting,fd_flags){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return{ret:path_ret,fd_obj:null}}let{ret,entry}=this.dir.get_entry_for_path(path);if(entry==null){if(ret!=wasi.ERRNO_NOENT){return{ret,fd_obj:null}}if((oflags&wasi.OFLAGS_CREAT)==wasi.OFLAGS_CREAT){const{ret,entry:new_entry}=this.dir.create_entry_for_path(path_str,(oflags&wasi.OFLAGS_DIRECTORY)==wasi.OFLAGS_DIRECTORY);if(new_entry==null){return{ret,fd_obj:null}}entry=new_entry}else{return{ret:wasi.ERRNO_NOENT,fd_obj:null}}}else if((oflags&wasi.OFLAGS_EXCL)==wasi.OFLAGS_EXCL){return{ret:wasi.ERRNO_EXIST,fd_obj:null}}if((oflags&wasi.OFLAGS_DIRECTORY)==wasi.OFLAGS_DIRECTORY&&entry.stat().filetype!==wasi.FILETYPE_DIRECTORY){return{ret:wasi.ERRNO_NOTDIR,fd_obj:null}}return entry.path_open(oflags,fs_rights_base,fd_flags)}path_create_directory(path){return this.path_open(0,path,wasi.OFLAGS_CREAT|wasi.OFLAGS_DIRECTORY,0n,0n,0).ret}path_link(path_str,inode,allow_dir){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return path_ret}if(path.is_dir){return wasi.ERRNO_NOENT}const{ret:parent_ret,parent_entry,filename,entry}=this.dir.get_parent_dir_and_entry_for_path(path,true);if(parent_entry==null||filename==null){return parent_ret}if(entry!=null){const source_is_dir=inode.stat().filetype==wasi.FILETYPE_DIRECTORY;const target_is_dir=entry.stat().filetype==wasi.FILETYPE_DIRECTORY;if(source_is_dir&&target_is_dir){if(allow_dir&&entry instanceof Directory){if(entry.contents.size==0){}else{return wasi.ERRNO_NOTEMPTY}}else{return wasi.ERRNO_EXIST}}else if(source_is_dir&&!target_is_dir){return wasi.ERRNO_NOTDIR}else if(!source_is_dir&&target_is_dir){return wasi.ERRNO_ISDIR}else if(inode.stat().filetype==wasi.FILETYPE_REGULAR_FILE&&entry.stat().filetype==wasi.FILETYPE_REGULAR_FILE){}else{return wasi.ERRNO_EXIST}}if(!allow_dir&&inode.stat().filetype==wasi.FILETYPE_DIRECTORY){return wasi.ERRNO_PERM}parent_entry.contents.set(filename,inode);return wasi.ERRNO_SUCCESS}path_unlink(path_str){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return{ret:path_ret,inode_obj:null}}const{ret:parent_ret,parent_entry,filename,entry}=this.dir.get_parent_dir_and_entry_for_path(path,true);if(parent_entry==null||filename==null){return{ret:parent_ret,inode_obj:null}}if(entry==null){return{ret:wasi.ERRNO_NOENT,inode_obj:null}}parent_entry.contents.delete(filename);return{ret:wasi.ERRNO_SUCCESS,inode_obj:entry}}path_unlink_file(path_str){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return path_ret}const{ret:parent_ret,parent_entry,filename,entry}=this.dir.get_parent_dir_and_entry_for_path(path,false);if(parent_entry==null||filename==null||entry==null){return parent_ret}if(entry.stat().filetype===wasi.FILETYPE_DIRECTORY){return wasi.ERRNO_ISDIR}parent_entry.contents.delete(filename);return wasi.ERRNO_SUCCESS}path_remove_directory(path_str){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return path_ret}const{ret:parent_ret,parent_entry,filename,entry}=this.dir.get_parent_dir_and_entry_for_path(path,false);if(parent_entry==null||filename==null||entry==null){return parent_ret}if(!(entry instanceof Directory)||entry.stat().filetype!==wasi.FILETYPE_DIRECTORY){return wasi.ERRNO_NOTDIR}if(entry.contents.size!==0){return wasi.ERRNO_NOTEMPTY}if(!parent_entry.contents.delete(filename)){return wasi.ERRNO_NOENT}return wasi.ERRNO_SUCCESS}fd_filestat_get(){return{ret:0,filestat:this.dir.stat()}}fd_filestat_set_size(size){return wasi.ERRNO_BADF}fd_read(size){return{ret:wasi.ERRNO_BADF,data:new Uint8Array}}fd_pread(size,offset){return{ret:wasi.ERRNO_BADF,data:new Uint8Array}}fd_write(data){return{ret:wasi.ERRNO_BADF,nwritten:0}}fd_pwrite(data,offset){return{ret:wasi.ERRNO_BADF,nwritten:0}}constructor(dir){super();this.dir=dir}}export class PreopenDirectory extends OpenDirectory{fd_prestat_get(){return{ret:0,prestat:wasi.Prestat.dir(this.prestat_name)}}constructor(name,contents){super(new Directory(contents));this.prestat_name=name}}export class File extends Inode{path_open(oflags,fs_rights_base,fd_flags){if(this.readonly&&(fs_rights_base&BigInt(wasi.RIGHTS_FD_WRITE))==BigInt(wasi.RIGHTS_FD_WRITE)){return{ret:wasi.ERRNO_PERM,fd_obj:null}}if((oflags&wasi.OFLAGS_TRUNC)==wasi.OFLAGS_TRUNC){if(this.readonly)return{ret:wasi.ERRNO_PERM,fd_obj:null};this.data=new Uint8Array([])}const file=new OpenFile(this);if(fd_flags&wasi.FDFLAGS_APPEND)file.fd_seek(0n,wasi.WHENCE_END);return{ret:wasi.ERRNO_SUCCESS,fd_obj:file}}get size(){return BigInt(this.data.byteLength)}stat(){return new wasi.Filestat(this.ino,wasi.FILETYPE_REGULAR_FILE,this.size)}constructor(data,options){super();this.data=new Uint8Array(data);this.readonly=!!options?.readonly}}let Path=class Path{static from(path){const self=new Path;self.is_dir=path.endsWith("/");if(path.startsWith("/")){return{ret:wasi.ERRNO_NOTCAPABLE,path:null}}if(path.includes("\x00")){return{ret:wasi.ERRNO_INVAL,path:null}}for(const component of path.split("/")){if(component===""||component==="."){continue}if(component===".."){if(self.parts.pop()==undefined){return{ret:wasi.ERRNO_NOTCAPABLE,path:null}}continue}self.parts.push(component)}return{ret:wasi.ERRNO_SUCCESS,path:self}}to_path_string(){let s=this.parts.join("/");if(this.is_dir){s+="/"}return s}constructor(){this.parts=[];this.is_dir=false}};export class Directory extends Inode{parent_ino(){if(this.parent==null){return Inode.root_ino()}return this.parent.ino}path_open(oflags,fs_rights_base,fd_flags){return{ret:wasi.ERRNO_SUCCESS,fd_obj:new OpenDirectory(this)}}stat(){return new wasi.Filestat(this.ino,wasi.FILETYPE_DIRECTORY,0n)}get_entry_for_path(path){let entry=this;for(const component of path.parts){if(!(entry instanceof Directory)){return{ret:wasi.ERRNO_NOTDIR,entry:null}}const child=entry.contents.get(component);if(child!==undefined){entry=child}else{debug.log(component);return{ret:wasi.ERRNO_NOENT,entry:null}}}if(path.is_dir){if(entry.stat().filetype!=wasi.FILETYPE_DIRECTORY){return{ret:wasi.ERRNO_NOTDIR,entry:null}}}return{ret:wasi.ERRNO_SUCCESS,entry}}get_parent_dir_and_entry_for_path(path,allow_undefined){const filename=path.parts.pop();if(filename===undefined){return{ret:wasi.ERRNO_INVAL,parent_entry:null,filename:null,entry:null}}const{ret:entry_ret,entry:parent_entry}=this.get_entry_for_path(path);if(parent_entry==null){return{ret:entry_ret,parent_entry:null,filename:null,entry:null}}if(!(parent_entry instanceof Directory)){return{ret:wasi.ERRNO_NOTDIR,parent_entry:null,filename:null,entry:null}}const entry=parent_entry.contents.get(filename);if(entry===undefined){if(!allow_undefined){return{ret:wasi.ERRNO_NOENT,parent_entry:null,filename:null,entry:null}}else{return{ret:wasi.ERRNO_SUCCESS,parent_entry,filename,entry:null}}}if(path.is_dir){if(entry.stat().filetype!=wasi.FILETYPE_DIRECTORY){return{ret:wasi.ERRNO_NOTDIR,parent_entry:null,filename:null,entry:null}}}return{ret:wasi.ERRNO_SUCCESS,parent_entry,filename,entry}}create_entry_for_path(path_str,is_dir){const{ret:path_ret,path}=Path.from(path_str);if(path==null){return{ret:path_ret,entry:null}}let{ret:parent_ret,parent_entry,filename,entry}=this.get_parent_dir_and_entry_for_path(path,true);if(parent_entry==null||filename==null){return{ret:parent_ret,entry:null}}if(entry!=null){return{ret:wasi.ERRNO_EXIST,entry:null}}debug.log("create",path);let new_child;if(!is_dir){new_child=new File(new ArrayBuffer(0))}else{new_child=new Directory(new Map)}parent_entry.contents.set(filename,new_child);entry=new_child;return{ret:wasi.ERRNO_SUCCESS,entry}}constructor(contents){super();this.parent=null;if(contents instanceof Array){this.contents=new Map(contents)}else{this.contents=contents}for(const entry of this.contents.values()){if(entry instanceof Directory){entry.parent=this}}}}export class ConsoleStdout extends Fd{fd_filestat_get(){const filestat=new wasi.Filestat(this.ino,wasi.FILETYPE_CHARACTER_DEVICE,BigInt(0));return{ret:0,filestat}}fd_fdstat_get(){const fdstat=new wasi.Fdstat(wasi.FILETYPE_CHARACTER_DEVICE,0);fdstat.fs_rights_base=BigInt(wasi.RIGHTS_FD_WRITE);return{ret:0,fdstat}}fd_write(data){this.write(data);return{ret:0,nwritten:data.byteLength}}static lineBuffered(write){const dec=new TextDecoder("utf-8",{fatal:false});let line_buf="";return new ConsoleStdout(buffer=>{line_buf+=dec.decode(buffer,{stream:true});const lines=line_buf.split("\n");for(const[i,line]of lines.entries()){if(i console.log(`[WASI stdout] ${msg}`)), + ConsoleStdout.lineBuffered(msg => console.warn(`[WASI stderr] ${msg}`)), + new PreopenDirectory("/", fileSystem) + ] + const options = {debug: false} + const wasi = new WASI(args, env, fds, options) + + // Instantiate WASM + return WebAssembly.instantiate(wasmBinary, { + wasi_snapshot_preview1: wasi.wasiImport + }).then(({instance}) => { + wasi.initialize(instance) + instance.exports.__wasm_call_ctors() + + function memory_data_view() { + return new DataView(instance.exports.memory.buffer) + } + + const argc_ptr = instance.exports.malloc(4) + memory_data_view().setUint32(argc_ptr, args.length, true) + const argv = instance.exports.malloc(4 * (args.length + 1)) + for (let i = 0; i < args.length; ++i) { + const arg = instance.exports.malloc(args[i].length + 1) + new TextEncoder().encodeInto( + args[i], + new Uint8Array( + instance.exports.memory.buffer, + arg, + args[i].length + ) + ) + memory_data_view().setUint8(arg + args[i].length, 0) + memory_data_view().setUint32(argv + 4 * i, arg, true) + } + memory_data_view().setUint32(argv + 4 * args.length, 0, true) + const argv_ptr = instance.exports.malloc(4) + memory_data_view().setUint32(argv_ptr, argv, true) + + instance.exports.hs_init_with_rtsopts(argc_ptr, argv_ptr) + + // Helper function to add file to filesystem + // Accepts either a Blob or a string + async function addFile(filename, data, readonly) { + let uint8Array + if (typeof data === "string") { + // Convert string to Uint8Array + uint8Array = new TextEncoder().encode(data) + } else { + // Assume it's a Blob + const buffer = await data.arrayBuffer() + uint8Array = new Uint8Array(buffer) + } + const file = new File(uint8Array, {readonly: readonly}) + fileSystem.set(filename, file) + } + + // Main API: query function + function query(options) { + const opts_str = JSON.stringify(options) + const encoded = new TextEncoder().encode(opts_str) + // Allocate memory based on byte length, not character count + const opts_ptr = instance.exports.malloc(encoded.length) + new TextEncoder().encodeInto( + opts_str, + new Uint8Array( + instance.exports.memory.buffer, + opts_ptr, + encoded.length + ) + ) + + // Setup filesystem + fileSystem.clear() + const out_file = new File(new Uint8Array(), {readonly: false}) + const err_file = new File(new Uint8Array(), {readonly: false}) + fileSystem.set("stdout", out_file) + fileSystem.set("stderr", err_file) + + instance.exports.query(opts_ptr, encoded.length) + + const err_text = new TextDecoder("utf-8", {fatal: true}).decode( + err_file.data + ) + if (err_text) { + console.log(err_text) + } + const out_text = new TextDecoder("utf-8", {fatal: true}).decode( + out_file.data + ) + return JSON.parse(out_text) + } + + // Main API: convert function + async function convert(options, stdin, files) { + const opts_str = JSON.stringify(options) + + const encoded = new TextEncoder().encode(opts_str) + const opts_ptr = instance.exports.malloc(encoded.length) + new TextEncoder().encodeInto( + opts_str, + new Uint8Array( + instance.exports.memory.buffer, + opts_ptr, + encoded.length + ) + ) + + // Clone files object to avoid mutating the input parameter + files = {...files} + + // Setup filesystem + fileSystem.clear() + const in_file = new File(new Uint8Array(), {readonly: true}) + const out_file = new File(new Uint8Array(), {readonly: false}) + const err_file = new File(new Uint8Array(), {readonly: false}) + const warnings_file = new File(new Uint8Array(), {readonly: false}) + fileSystem.set("stdin", in_file) + fileSystem.set("stdout", out_file) + fileSystem.set("stderr", err_file) + fileSystem.set("warnings", warnings_file) + + // Track known files to detect newly created media files + // We track system files, input files, output files, and extract-media archives + const knownFiles = new Set([ + "stdin", + "stdout", + "stderr", + "warnings" + ]) + + // Add input files (can be Blobs or strings) + for (const filename in files) { + await addFile(filename, files[filename], true) + knownFiles.add(filename) + } + + // Track output file and extract-media separately + // These should NOT be included in mediaFiles (only extracted media should be) + const outputFileName = options["output-file"] || null + const extractMediaPath = options["extract-media"] || null + + // Add output file placeholder if specified + if (outputFileName) { + await addFile(outputFileName, new Blob(), false) + knownFiles.add(outputFileName) + } + + // Add placeholder file for extract-media zip archives. For + // directory targets nothing is pre-created: pandoc creates the + // directory itself, and a file placeholder at that path would + // make it fail with ENOTDIR. + if (extractMediaPath && extractMediaPath.endsWith(".zip")) { + await addFile(extractMediaPath, new Blob(), false) + knownFiles.add(extractMediaPath) + } + + // Set stdin content + if (stdin) { + in_file.data = new TextEncoder().encode(stdin) + } + + // Run conversion + instance.exports.convert(opts_ptr, encoded.length) + + // Collect output file if generated + if (options["output-file"]) { + const outputFile = fileSystem.get(options["output-file"]) + if ( + outputFile && + outputFile.data && + outputFile.data.length > 0 + ) { + files[options["output-file"]] = new Blob([outputFile.data]) + } + } + + // Collect extracted media if generated + if (options["extract-media"]) { + const mediaFile = fileSystem.get(options["extract-media"]) + if (mediaFile && mediaFile.data && mediaFile.data.length > 0) { + files[options["extract-media"]] = new Blob( + [mediaFile.data], + { + type: "application/zip" + } + ) + } + } + + // Collect any newly created files (e.g., extracted media images). + // Media extracted to a directory is nested (e.g. docx media lands + // at "/media/image1.png"), so walk directories + // recursively. mediaFiles should ONLY contain extracted media, + // NOT the output file or extract-media zip archive (both are + // tracked in knownFiles). + const mediaFiles = {} + const collectNewFiles = (map, prefix) => { + for (const [name, entry] of map.entries()) { + const path = prefix ? `${prefix}/${name}` : name + if (entry instanceof Directory) { + collectNewFiles(entry.contents, path) + } else if ( + !knownFiles.has(path) && + entry.data && + entry.data.length > 0 + ) { + const blob = new Blob([entry.data]) + files[path] = blob + mediaFiles[path] = blob + } + } + } + collectNewFiles(fileSystem, "") + + // Parse warnings + const rawWarnings = new TextDecoder("utf-8", {fatal: true}).decode( + warnings_file.data + ) + let warnings = [] + if (rawWarnings) { + try { + warnings = JSON.parse(rawWarnings) + } catch (e) { + console.warn("Failed to parse warnings:", e) + } + } + + return { + stdout: new TextDecoder("utf-8", {fatal: true}).decode( + out_file.data + ), + stderr: new TextDecoder("utf-8", {fatal: true}).decode( + err_file.data + ), + warnings: warnings, + files: files, + mediaFiles: mediaFiles + } + } + + // Helper function to convert data to Uint8Array + async function toUint8Array(inData) { + let uint8Array + + if (typeof inData === "string") { + const encoder = new TextEncoder() + uint8Array = encoder.encode(inData) + } else if (inData instanceof Blob) { + const arrayBuffer = await inData.arrayBuffer() + uint8Array = new Uint8Array(arrayBuffer) + } else { + throw new Error( + "Unsupported type: inData must be a string or a Blob" + ) + } + + return uint8Array + } + + const textDecoder = new TextDecoder("utf-8", {fatal: true}) + + function convertData(data) { + let outData + try { + // Attempt to decode as UTF-8 text + outData = textDecoder.decode(data) + } catch (_e) { + // If decoding fails, return as Blob + outData = new Blob([data]) + } + return outData + } + + // Legacy API: pandoc function (for backward compatibility) + async function pandoc(args_str, inData, resources = []) { + // Parse command line arguments into options object + const argParts = args_str.trim().split(/\s+/) + const options = {} + const files = {} + + let i = 0 + while (i < argParts.length) { + const arg = argParts[i] + + if (arg === "-f" || arg === "--from") { + options.from = argParts[++i] + } else if (arg === "-t" || arg === "--to") { + options.to = argParts[++i] + } else if (arg === "-o" || arg === "--output") { + options["output-file"] = argParts[++i] + } else if (arg === "-s" || arg === "--standalone") { + options.standalone = true + } else if (arg === "--extract-media") { + options["extract-media"] = argParts[++i] + } else if (arg === "--toc" || arg === "--table-of-contents") { + options["table-of-contents"] = true + } + i++ + } + + // Add resource files (convert to string or keep as Blob) + for (const resource of resources) { + // If contents is a string, keep it as string + // Otherwise, convert to Blob + if (typeof resource.contents === "string") { + files[resource.filename] = resource.contents + } else { + const contents = await toUint8Array(resource.contents) + files[resource.filename] = new Blob([contents]) + } + } + + // Convert stdin to string + let stdin = null + if (inData) { + if (typeof inData === "string") { + stdin = inData + } else { + const uint8Array = await toUint8Array(inData) + stdin = new TextDecoder("utf-8").decode(uint8Array) + } + } + + // Call convert + const result = await convert(options, stdin, files) + + // Convert mediaFiles from Object to Map for legacy API compatibility + const mediaFiles = new Map() + for (const [name, blob] of Object.entries(result.mediaFiles)) { + mediaFiles.set( + name, + convertData(new Uint8Array(await blob.arrayBuffer())) + ) + } + + // Return in legacy format + let out + if ( + options["output-file"] && + result.files[options["output-file"]] + ) { + out = convertData( + new Uint8Array( + await result.files[options["output-file"]].arrayBuffer() + ) + ) + } else { + out = result.stdout + } + + return { + out: out, + mediaFiles: mediaFiles + } + } + + // Return the API + return { + convert, + query, + pandoc + } + }) +} diff --git a/methoden-set/vendor/wasi-shim/wasi.js b/methoden-set/vendor/wasi-shim/wasi.js new file mode 100644 index 0000000..02579a1 --- /dev/null +++ b/methoden-set/vendor/wasi-shim/wasi.js @@ -0,0 +1 @@ +import*as wasi from"./wasi_defs.js";import{debug}from"./debug.js";export class WASIProcExit extends Error{constructor(code){super("exit with exit code "+code);this.code=code}}let WASI=class WASI{start(instance){this.inst=instance;try{instance.exports._start();return 0}catch(e){if(e instanceof WASIProcExit){return e.code}else{throw e}}}initialize(instance){this.inst=instance;if(instance.exports._initialize){instance.exports._initialize()}}constructor(args,env,fds,options={}){this.args=[];this.env=[];this.fds=[];debug.enable(options.debug);this.args=args;this.env=env;this.fds=fds;const self=this;this.wasiImport={args_sizes_get(argc,argv_buf_size){const buffer=new DataView(self.inst.exports.memory.buffer);buffer.setUint32(argc,self.args.length,true);let buf_size=0;for(const arg of self.args){buf_size+=arg.length+1}buffer.setUint32(argv_buf_size,buf_size,true);debug.log(buffer.getUint32(argc,true),buffer.getUint32(argv_buf_size,true));return 0},args_get(argv,argv_buf){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);const orig_argv_buf=argv_buf;for(let i=0;ipath_len?wasi.ERRNO_NAMETOOLONG:wasi.ERRNO_SUCCESS}else{return wasi.ERRNO_BADF}},fd_pwrite(fd,iovs_ptr,iovs_len,offset,nwritten_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const iovecs=wasi.Ciovec.read_bytes_array(buffer,iovs_ptr,iovs_len);let nwritten=0;for(const iovec of iovecs){const data=buffer8.slice(iovec.buf,iovec.buf+iovec.buf_len);const{ret,nwritten:nwritten_part}=self.fds[fd].fd_pwrite(data,offset);if(ret!=wasi.ERRNO_SUCCESS){buffer.setUint32(nwritten_ptr,nwritten,true);return ret}nwritten+=nwritten_part;offset+=BigInt(nwritten_part);if(nwritten_part!=data.byteLength){break}}buffer.setUint32(nwritten_ptr,nwritten,true);return wasi.ERRNO_SUCCESS}else{return wasi.ERRNO_BADF}},fd_read(fd,iovs_ptr,iovs_len,nread_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const iovecs=wasi.Iovec.read_bytes_array(buffer,iovs_ptr,iovs_len);let nread=0;for(const iovec of iovecs){const{ret,data}=self.fds[fd].fd_read(iovec.buf_len);if(ret!=wasi.ERRNO_SUCCESS){buffer.setUint32(nread_ptr,nread,true);return ret}buffer8.set(data,iovec.buf);nread+=data.length;if(data.length!=iovec.buf_len){break}}buffer.setUint32(nread_ptr,nread,true);return wasi.ERRNO_SUCCESS}else{return wasi.ERRNO_BADF}},fd_readdir(fd,buf,buf_len,cookie,bufused_ptr){const buffer=new DataView(self.inst.exports.memory.buffer);const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){let bufused=0;while(true){const{ret,dirent}=self.fds[fd].fd_readdir_single(cookie);if(ret!=0){buffer.setUint32(bufused_ptr,bufused,true);return ret}if(dirent==null){break}if(buf_len-bufusedbuf_len){buffer.setUint32(nread_ptr,0,true);return wasi.ERRNO_BADF}buffer8.set(data_buf,buf_ptr);buffer.setUint32(nread_ptr,data_buf.length,true)}return ret}else{return wasi.ERRNO_BADF}},path_remove_directory(fd,path_ptr,path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));return self.fds[fd].path_remove_directory(path)}else{return wasi.ERRNO_BADF}},path_rename(fd,old_path_ptr,old_path_len,new_fd,new_path_ptr,new_path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined&&self.fds[new_fd]!=undefined){const old_path=new TextDecoder("utf-8").decode(buffer8.slice(old_path_ptr,old_path_ptr+old_path_len));const new_path=new TextDecoder("utf-8").decode(buffer8.slice(new_path_ptr,new_path_ptr+new_path_len));let{ret,inode_obj}=self.fds[fd].path_unlink(old_path);if(inode_obj==null){return ret}ret=self.fds[new_fd].path_link(new_path,inode_obj,true);if(ret!=wasi.ERRNO_SUCCESS){if(self.fds[fd].path_link(old_path,inode_obj,true)!=wasi.ERRNO_SUCCESS){throw"path_link should always return success when relinking an inode back to the original place"}}return ret}else{return wasi.ERRNO_BADF}},path_symlink(old_path_ptr,old_path_len,fd,new_path_ptr,new_path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const old_path=new TextDecoder("utf-8").decode(buffer8.slice(old_path_ptr,old_path_ptr+old_path_len));const new_path=new TextDecoder("utf-8").decode(buffer8.slice(new_path_ptr,new_path_ptr+new_path_len));return wasi.ERRNO_NOTSUP}else{return wasi.ERRNO_BADF}},path_unlink_file(fd,path_ptr,path_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer);if(self.fds[fd]!=undefined){const path=new TextDecoder("utf-8").decode(buffer8.slice(path_ptr,path_ptr+path_len));return self.fds[fd].path_unlink_file(path)}else{return wasi.ERRNO_BADF}},poll_oneoff(in_ptr,out_ptr,nsubscriptions){if(nsubscriptions===0){return wasi.ERRNO_INVAL}if(nsubscriptions>1){debug.log("poll_oneoff: only a single subscription is supported");return wasi.ERRNO_NOTSUP}const buffer=new DataView(self.inst.exports.memory.buffer);const s=wasi.Subscription.read_bytes(buffer,in_ptr);const eventtype=s.eventtype;const clockid=s.clockid;const timeout=s.timeout;if(eventtype!==wasi.EVENTTYPE_CLOCK){debug.log("poll_oneoff: only clock subscriptions are supported");return wasi.ERRNO_NOTSUP}let getNow=undefined;if(clockid===wasi.CLOCKID_MONOTONIC){getNow=()=>BigInt(Math.round(performance.now()*1e6))}else if(clockid===wasi.CLOCKID_REALTIME){getNow=()=>BigInt(new Date().getTime())*1000000n}else{return wasi.ERRNO_INVAL}const endTime=(s.flags&wasi.SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME)!==0?timeout:getNow()+timeout;while(endTime>getNow()){}const event=new wasi.Event(s.userdata,wasi.ERRNO_SUCCESS,eventtype);event.write_bytes(buffer,out_ptr);return wasi.ERRNO_SUCCESS},proc_exit(exit_code){throw new WASIProcExit(exit_code)},proc_raise(sig){throw"raised signal "+sig},sched_yield(){},random_get(buf,buf_len){const buffer8=new Uint8Array(self.inst.exports.memory.buffer).subarray(buf,buf+buf_len);if("crypto"in globalThis&&(typeof SharedArrayBuffer==="undefined"||!(self.inst.exports.memory.buffer instanceof SharedArrayBuffer))){for(let i=0;i>> 1) : c >>> 1; + } + table[n] = c >>> 0; + } + return table; + })(); + + function crc32(bytes) { + let crc = 0xffffffff; + for (let i = 0; i < bytes.length; i++) { + crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8); + } + return (crc ^ 0xffffffff) >>> 0; + } + + function dosDateTime(date) { + const time = + ((date.getHours() & 0x1f) << 11) | + ((date.getMinutes() & 0x3f) << 5) | + ((date.getSeconds() >> 1) & 0x1f); + const dateVal = + (((date.getFullYear() - 1980) & 0x7f) << 9) | + (((date.getMonth() + 1) & 0xf) << 5) | + (date.getDate() & 0x1f); + return { time, date: dateVal }; + } + + function utf8Bytes(str) { + return new TextEncoder().encode(str); + } + + /* entries: Array<{ path: string, data: Uint8Array }> - path with "/" as + the folder separator, relative to the zip root. Returns a Blob. */ + function write(entries) { + const now = dosDateTime(new Date()); + const chunks = []; + const central = []; + let offset = 0; + + for (const entry of entries) { + const nameBytes = utf8Bytes(entry.path); + const data = entry.data; + const crc = crc32(data); + + const local = new DataView(new ArrayBuffer(30)); + local.setUint32(0, 0x04034b50, true); + local.setUint16(4, 20, true); // Version + local.setUint16(6, 0x0800, true); // Flags: UTF-8 filenames + local.setUint16(8, 0, true); // Method: 0 = stored + local.setUint16(10, now.time, true); + local.setUint16(12, now.date, true); + local.setUint32(14, crc, true); + local.setUint32(18, data.length, true); + local.setUint32(22, data.length, true); + local.setUint16(26, nameBytes.length, true); + local.setUint16(28, 0, true); + + chunks.push(new Uint8Array(local.buffer), nameBytes, data); + + const centralHeader = new DataView(new ArrayBuffer(46)); + centralHeader.setUint32(0, 0x02014b50, true); + centralHeader.setUint16(4, 20, true); + centralHeader.setUint16(6, 20, true); + centralHeader.setUint16(8, 0x0800, true); + centralHeader.setUint16(10, 0, true); + centralHeader.setUint16(12, now.time, true); + centralHeader.setUint16(14, now.date, true); + centralHeader.setUint32(16, crc, true); + centralHeader.setUint32(20, data.length, true); + centralHeader.setUint32(24, data.length, true); + centralHeader.setUint16(28, nameBytes.length, true); + centralHeader.setUint16(30, 0, true); + centralHeader.setUint16(32, 0, true); + centralHeader.setUint16(34, 0, true); + centralHeader.setUint16(36, 0, true); + centralHeader.setUint32(38, 0, true); + centralHeader.setUint32(42, offset, true); + central.push(new Uint8Array(centralHeader.buffer), nameBytes); + + offset += 30 + nameBytes.length + data.length; + } + + const centralStart = offset; + let centralSize = 0; + for (const part of central) centralSize += part.length; + + const end = new DataView(new ArrayBuffer(22)); + end.setUint32(0, 0x06054b50, true); + end.setUint16(4, 0, true); + end.setUint16(6, 0, true); + end.setUint16(8, entries.length, true); + end.setUint16(10, entries.length, true); + end.setUint32(12, centralSize, true); + end.setUint32(16, centralStart, true); + end.setUint16(20, 0, true); + + return new Blob([...chunks, ...central, new Uint8Array(end.buffer)], { + type: "application/zip" + }); + } + + global.AblegerZip = { write }; +})(window); diff --git a/scripts/admin-status-server.rb b/scripts/admin-status-server.rb new file mode 100644 index 0000000..f2d2b0d --- /dev/null +++ b/scripts/admin-status-server.rb @@ -0,0 +1,73 @@ +#!/usr/bin/env ruby +# Small, permanently running service for the whole "write" area (/admin/*, +# gated by the "write" oauth2-proxy instance, see +# the installation guide on the project website): normally serves the same static files as its +# former file:// upstream (Decap CMS, admin/status/), AND additionally +# answers the two dynamic endpoints below. A single upstream instead of two +# - oauth2-proxy 7.15.3 did not resolve the multiple, path-distinguished +# upstreams (file:// + http://) via URL fragment in the simple +# "upstreams = [...]" list form as documented (both ended up on path "/", +# "upstream ids must be unique"/"upstream paths must be unique" on start) - +# hence a WEBrick file handler here for the rest instead. +# +# This script itself does not check authorization, that is handled entirely +# by the oauth2-proxy gate in front of it. +# +# STATUS_FILE is written by the deploy hook itself (~/repos/ableger.git/ +# hooks/post-receive on the server, not part of this repo - see +# the installation guide on the project website), not by this script. +require 'webrick' +require 'json' + +# Small install.env parser instead of a dotenv gem dependency - install.env +# deliberately has a simple KEY="value" format (see there), not YAML. +def load_install_env(pfad) + werte = {} + File.readlines(pfad).each do |zeile| + zeile = zeile.strip + next if zeile.empty? || zeile.start_with?('#') + schluessel, wert = zeile.split('=', 2) + werte[schluessel] = wert.to_s.sub(/\A"/, '').sub(/"\z/, '') + end + werte +end + +INSTALL_ENV = load_install_env(File.expand_path('../install.env', __dir__)) + +STATUS_FILE = File.expand_path('~/deploy/status.json') +# Bare repo name (see the installation guide on the project website, Abschnitt 4) is derived from +# the website repo name, not maintained separately. +HOOK = File.expand_path("~/repos/#{INSTALL_ENV.fetch('WEBSITE_REPO').split('/').last}.git/hooks/post-receive") +DOCROOT = INSTALL_ENV.fetch('DEPLOY_DOCROOT') +PORT = INSTALL_ENV.fetch('STATUS_SERVER_PORT').to_i + +def status_body + File.exist?(STATUS_FILE) ? File.read(STATUS_FILE) : { error: 'noch kein Deploy-Status vorhanden' }.to_json +end + +server = WEBrick::HTTPServer.new(Port: PORT, BindAddress: '0.0.0.0', DocumentRoot: DOCROOT, Logger: WEBrick::Log.new($stdout), AccessLog: [[$stdout, WEBrick::AccessLog::COMBINED_LOG_FORMAT]]) + +server.mount_proc '/admin/status/api/data.json' do |req, res| + res['Content-Type'] = 'application/json; charset=utf-8' + res.body = status_body +end + +server.mount_proc '/admin/status/api/trigger' do |req, res| + res['Content-Type'] = 'application/json; charset=utf-8' + if req.request_method != 'POST' + res.status = 405 + res.body = { error: 'nur POST erlaubt' }.to_json + next + end + # Runs synchronously - the hook itself protects against an already + # running cron/trigger run with a non-blocking flock (see hook script): + # if one is already running, this call aborts immediately with a + # corresponding message in the status instead of waiting or duplicating - + # just click again shortly after. + system(HOOK) + res.body = status_body +end + +trap('INT') { server.shutdown } +trap('TERM') { server.shutdown } +server.start diff --git a/scripts/apply-veroeffentlicht.rb b/scripts/apply-veroeffentlicht.rb new file mode 100755 index 0000000..c1422d0 --- /dev/null +++ b/scripts/apply-veroeffentlicht.rb @@ -0,0 +1,35 @@ +#!/usr/bin/env ruby +# Translates the form field "veroeffentlicht" (Decap, positive polarity: on +# = published) into Hugo's native draft field (inverted: draft: true = +# unpublished) - only in the local _content copy (not in the content repo), +# before every Hugo build. Decap cannot write a boolean field inverted into +# a differently named frontmatter field, hence this translation step +# instead of a direct CMS mapping. Must run before +# compute-methoden-sichtbarkeit.rb, which in turn reads the draft field set +# here for variants (that script aborts if it still finds untranslated +# "veroeffentlicht" fields, see there). +require_relative 'lib/frontmatter' + +root = File.expand_path('..', __dir__) +varianten_dir = File.join(root, '_content', 'varianten') + +changed = 0 +if Dir.exist?(varianten_dir) + Dir.glob(File.join(varianten_dir, '*', 'index.md')).each do |file| + result = Frontmatter.read(file) + next unless result + fm, body = result + + # Missing "veroeffentlicht" (e.g. a variant committed directly via the + # PR path, bypassing Decap's boolean widget with its "default: false") + # must translate to unpublished, not be skipped untranslated - a + # missing "draft" frontmatter key defaults to visible in Hugo, so + # skipping this file entirely would publish it unintentionally. + veroeffentlicht = fm.key?('veroeffentlicht') ? fm.delete('veroeffentlicht') == true : false + fm['draft'] = !veroeffentlicht + Frontmatter.write(file, fm, body, feldreihenfolge: Frontmatter::VARIANTEN_FELDER) + changed += 1 + end +end + +puts "veroeffentlicht -> draft übersetzt: #{changed} Variante(n)" diff --git a/scripts/compute-methoden-sichtbarkeit.rb b/scripts/compute-methoden-sichtbarkeit.rb new file mode 100755 index 0000000..837f570 --- /dev/null +++ b/scripts/compute-methoden-sichtbarkeit.rb @@ -0,0 +1,71 @@ +#!/usr/bin/env ruby +# Sets draft: true in the LOCAL copy of every method (_content/methoden/*/index.md) +# whose variants are all still drafts (or has none) - not in the content repo +# itself, only in the working copy freshly fetched on every sync (see sync-methoden.sh). +# +# Methods deliberately no longer have their own draft field +# (admin/config.template.yml): publication is derived from the variants - as +# soon as at least one variant is published, the method is too. This can't +# be modeled as a Decap field (no access to other collections while saving), +# hence this preprocessing step before the Hugo build. Hugo's own draft +# mechanism then reliably takes care of the rest (e.g. automatic exclusion +# from the homepage/search/taxonomies, not just the detail page itself) - +# more robust than rebuilding a custom visibility check in the templates. +# +# Assumes apply-veroeffentlicht.rb has already run (see sync-methoden.sh) - +# otherwise variants would still have "veroeffentlicht" instead of "draft", +# published_methoden would stay empty, and EVERY method would be incorrectly +# marked as draft without anything reporting the error. Hence this safeguard +# here (Befund G/Schritt 6, see the project website (background/analysis notes)): instead of +# silently accepting that, the script aborts loudly as soon as it finds a +# variant with a still-untranslated "veroeffentlicht". +require_relative 'lib/frontmatter' +require 'set' + +root = File.expand_path('..', __dir__) +content = File.join(root, '_content') +methoden_dir = File.join(content, 'methoden') +varianten_dir = File.join(content, 'varianten') + +published_methoden = Set.new +if Dir.exist?(varianten_dir) + Dir.glob(File.join(varianten_dir, '*', 'index.md')).each do |file| + result = Frontmatter.read(file) + next unless result + fm, = result + if fm.key?('veroeffentlicht') + warn "compute-methoden-sichtbarkeit.rb: #{file} hat noch 'veroeffentlicht' statt 'draft' - apply-veroeffentlicht.rb muss vorher laufen (siehe sync-methoden.sh)" + exit 1 + end + next unless fm['draft'] == false + methode = fm['methode'] + published_methoden << methode if methode + end +end + +changed = 0 +Dir.glob(File.join(methoden_dir, '*', 'index.md')).each do |file| + result = Frontmatter.read(file) + next unless result + fm, body = result + kennung = fm['kennung'] + should_be_visible = published_methoden.include?(kennung) + # fm['draft'] == true instead of fm.key?('draft'): methods used to have + # their own draft field (since removed, see admin/config.template.yml) - + # so a file may still contain a leftover old "draft: false" value. + # Checking only for the key's presence would incorrectly treat that as + # "currently hidden". + currently_draft = fm['draft'] == true + + if should_be_visible == currently_draft + if should_be_visible + fm.delete('draft') + else + fm['draft'] = true + end + Frontmatter.write(file, fm, body, feldreihenfolge: Frontmatter::METHODEN_FELDER) + changed += 1 + end +end + +puts "Methoden-Sichtbarkeit aktualisiert: #{published_methoden.size} mit veröffentlichter Variante, #{changed} Datei(en) angepasst" diff --git a/scripts/generate-config.sh b/scripts/generate-config.sh new file mode 100755 index 0000000..07e5022 --- /dev/null +++ b/scripts/generate-config.sh @@ -0,0 +1,130 @@ +#!/bin/bash +# Generates admin/config.yml from admin/config.template.yml, AND +# hugo/hugo.toml from hugo/hugo.template.toml (see below) - both share the +# same "{{VARIABLE}}" substitution step, filled from install.env. +# +# admin/config.yml specifically has a second, independent substitution: +# fields between "# VOKABULAR::START/END" markers are replaced by a +# closed selection list if a vocabulary entry for exists in the +# content repo under _content/ableger.yml - otherwise the block from the +# template stays unchanged (fallback: free text as before). See the +# Manifest chapter on the project website Teil C, vokabular/README.md and +# install.env. +# +# Runs both locally and in deploy (see the installation guide on the +# project website), AFTER sync-methoden.sh (which fetches +# _content/ableger.yml in the first place). Both admin/config.yml and +# hugo/hugo.toml are generated and not versioned (see .gitignore) - +# admin/config.template.yml and hugo/hugo.template.toml are the files to +# maintain. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TEMPLATE="$ROOT/admin/config.template.yml" +OUT="$ROOT/admin/config.yml" +ABLEGER_YML="$ROOT/_content/ableger.yml" + +# shellcheck source=/dev/null +source "$ROOT/install.env" +export GITEA_DOMAIN METHODEN_REPO OAUTH_CLIENT_ID WEBSITE_DOMAIN + +# hugo.toml only needs the plain "{{VARIABLE}}" substitution, no VOKABULAR +# blocks - a plain sed pass is enough, no need for the Python step below. +HUGO_TEMPLATE="$ROOT/hugo/hugo.template.toml" +HUGO_OUT="$ROOT/hugo/hugo.toml" +sed -e "s|{{GITEA_DOMAIN}}|$GITEA_DOMAIN|g" \ + -e "s|{{METHODEN_REPO}}|$METHODEN_REPO|g" \ + -e "s|{{WEBSITE_DOMAIN}}|$WEBSITE_DOMAIN|g" \ + "$HUGO_TEMPLATE" > "$HUGO_OUT" +echo "hugo.toml generiert: $HUGO_OUT" + +# Export the vocabulary from ableger.yml (content repo) into a temporary +# directory with one text file per field (one allowed value per line) - this +# way the rest of the already-proven logic below (Python, reads from text +# files) stays unchanged. Ruby instead of Python for YAML parsing, since +# PyYAML isn't guaranteed to be available here, whereas Ruby's yaml library +# (standard library) is already used elsewhere in the project (see +# scripts/validate.rb). +VOKABULAR="$(mktemp -d)" +trap 'rm -rf "$VOKABULAR"' EXIT + +if [ -f "$ABLEGER_YML" ]; then + ruby -ryaml -e ' + daten = YAML.load_file(ARGV[0]) || {} + vokabular = daten["vokabular"] || {} + vokabular.each do |feld, werte| + File.write(File.join(ARGV[1], "#{feld}.txt"), Array(werte).join("\n") + "\n") + end + ' "$ABLEGER_YML" "$VOKABULAR" +fi + +python3 - "$TEMPLATE" "$OUT" "$VOKABULAR" <<'PYEOF' +import os +import re +import sys +from pathlib import Path + +template_path, out_path, vokabular_dir = sys.argv[1:4] +text = Path(template_path).read_text() +vokabular_dir = Path(vokabular_dir) + +# Always replace "{{VARIABLE}}" placeholders (see install.env), independent +# of the VOKABULAR mechanism below - no fallback logic needed, install.env +# (unlike _content/ableger.yml) is always versioned in this repo. +for feld in ("GITEA_DOMAIN", "METHODEN_REPO", "OAUTH_CLIENT_ID", "WEBSITE_DOMAIN"): + text = text.replace("{{" + feld + "}}", os.environ[feld]) + +def render_field(feld, indent, values): + lines = [f'{indent}- label: "{feld_labels.get(feld, feld)}"', + f'{indent} name: "{feld}"', + f'{indent} widget: "select"'] + # ONLY multi_fields determines multi-select - "more than one option to + # choose from" (len(values) > 1) is not the same as "multiple values + # selectable at once" and must not be conflated. Found live: "lizenz" + # has 3 options, but exactly ONE applies per entry - the earlier + # condition "len(values) > 1 or feld in multi_fields" incorrectly set + # multiple: true as soon as a second vocabulary value was added. Decap + # then stored lizenz as a list ("- CC0") instead of a plain string as + # soon as someone made a selection in the CMS - unnoticed until a value + # was actually changed. + if feld in multi_fields: + lines.append(f'{indent} multiple: true') + lines.append(f'{indent} options:') + for wert in values: + lines.append(f'{indent} - "{wert}"') + return "\n".join(lines) + +feld_labels = { + "zielgruppe": "Zielgruppe", + "kategorie": "Kategorie", + "lizenz": "Lizenz", + "tags": "Tags", +} +multi_fields = {"zielgruppe", "kategorie", "tags"} + +def replace_block(match): + feld = match.group("feld") + indent = match.group("indent") + vokabular_file = vokabular_dir / f"{feld}.txt" + start = match.group("start") + end = match.group("end") + if not vokabular_file.exists(): + return match.group(0) + values = [line.strip() for line in vokabular_file.read_text().splitlines() if line.strip()] + if not values: + return match.group(0) + block = render_field(feld, indent, values) + return f"{indent}{start}\n{block}\n{indent}{end}" + +pattern = re.compile( + r'(?P[ \t]*)(?P# VOKABULAR:(?P\w+):START)\n' + r'.*?\n' + r'[ \t]*(?P# VOKABULAR:(?P=feld):END)', + re.DOTALL, +) + +result = pattern.sub(replace_block, text) +Path(out_path).write_text(result) +PYEOF + +echo "config.yml generiert: $OUT" diff --git a/scripts/generate-dates.sh b/scripts/generate-dates.sh new file mode 100755 index 0000000..3dcd384 --- /dev/null +++ b/scripts/generate-dates.sh @@ -0,0 +1,62 @@ +#!/bin/bash +# Generates hugo/data/methoden.json and hugo/data/varianten.json: creation +# and last-modified date per method/variant, determined from the git +# history of _content/. +# +# Hugo's enableGitInfo/.GitInfo only looks for git history in the repo that +# contains the Hugo page root (ableger_demo/ableger) - but _content/ is a +# separate git repo (ableger_demo/ableger_methoden) mounted via +# module.mounts and is not recognized there (.GitInfo stays nil, no error, +# just silently empty). This has affected "last modified" ever since the +# repo split, unnoticed, because Hugo doesn't warn about it. +# For "created" there would be no Hugo-native equivalent anyway, see +# https://github.com/gohugoio/hugo/issues/11810 (open). +# +# So both dates are read here uniformly from git history ourselves, instead +# of relying on .GitInfo. Recomputed fresh on every sync rather than +# maintained (see sync-methoden.sh, which calls this script automatically) - +# no manual date field, git stays the single source of truth. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +CONTENT_REPO="$ROOT/_content" + +dates_for_path() { + local relpath="$1" + local history erstellt geaendert + # One "git log --follow" call instead of two: with the full (not -1) + # history for this path, the first line (newest) is "geaendert" and the + # last line (oldest, following through renames) is "erstellt" - no need + # for a second, separately filtered/unfollowed call to get either. + history="$(git -C "$CONTENT_REPO" log --follow --format=%aI -- "$relpath")" + geaendert="$(echo "$history" | head -1)" + erstellt="$(echo "$history" | tail -1)" + [ -n "$erstellt" ] && [ -n "$geaendert" ] || return 1 + jq -n --arg erstellt "$erstellt" --arg geaendert "$geaendert" '{erstellt: $erstellt, geaendert: $geaendert}' +} + +# Both methods and variants are one folder per entry with content in +# index.md (Hugo page bundle) - variants ever since attachments moved from +# the method to the respective variant, see admin/config.template.yml. +generate_bundle_dates() { + local name="$1" + local dir="$CONTENT_REPO/$name" + local out="$ROOT/hugo/data/$name.json" + mkdir -p "$(dirname "$out")" + local entries="{}" + if [ -d "$dir" ]; then + for entry_dir in "$dir"/*/; do + local slug + slug="$(basename "$entry_dir")" + [ -f "$entry_dir/index.md" ] || continue + local dates + dates="$(dates_for_path "$name/$slug/index.md")" || continue + entries="$(echo "$entries" | jq --arg slug "$slug" --argjson dates "$dates" '. + {($slug): $dates}')" + done + fi + echo "$entries" > "$out" + echo "$name.json aktualisiert: $(echo "$entries" | jq 'length') Einträge" +} + +generate_bundle_dates "methoden" +generate_bundle_dates "varianten" diff --git a/scripts/generate-version-info.sh b/scripts/generate-version-info.sh new file mode 100755 index 0000000..f6f6273 --- /dev/null +++ b/scripts/generate-version-info.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Generates hugo/data/website.json: the current commit (short hash + date) +# of THIS website/CMS-code repo itself - shown in the footer next to the +# Manifest version (see baseof.html) so an installation can tell at a +# glance which code state it's actually running, independent of whether +# it's still identical to the template or has since been developed further +# on its own. Deliberately NOT a frozen "forked from template version X" +# marker - once a fork's own commits land, this reflects those, not the +# template's history. +# +# Unlike hugo/data/methoden.json/varianten.json (generate-dates.sh), this +# reads the website repo's own git history directly - no separate +# module.mounts repo involved, Hugo's enableGitInfo/.GitInfo would actually +# work here, but a plain "git log" call keeps this consistent with the +# same approach already used for methoden/varianten dates. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +OUT="$ROOT/hugo/data/website.json" +mkdir -p "$(dirname "$OUT")" + +commit="$(git -C "$ROOT" rev-parse --short HEAD)" +datum="$(git -C "$ROOT" log -1 --format=%aI)" + +jq -n --arg commit "$commit" --arg datum "$datum" '{commit: $commit, datum: $datum}' > "$OUT" +echo "website.json aktualisiert: $commit ($datum)" diff --git a/scripts/generate-vorlagen-manifest.rb b/scripts/generate-vorlagen-manifest.rb new file mode 100755 index 0000000..6c49232 --- /dev/null +++ b/scripts/generate-vorlagen-manifest.rb @@ -0,0 +1,28 @@ +#!/usr/bin/env ruby +# Generates vorlagen-manifest.json in the given templates folder - lists all +# .docx/.odt files found there so the methoden-set tool (methoden-set/, see +# the Methoden-Set chapter on the project website) can offer them automatically as template choices, +# including files someone copied manually straight onto the server (not +# just the ones from this repo). Runs in the deploy hook AFTER the rsync of +# methoden-set/ into the docroot (see the installation guide on the project website) and +# therefore deliberately scans the docroot itself, not the git worktree - +# rsync runs there without --delete, so manually added files survive +# across deploys and show up here too. +require 'json' + +verzeichnis = ARGV[0] or abort "Verwendung: #{$0} " + +dateien = Dir.glob(File.join(verzeichnis, '*.{docx,odt}')).map { |pfad| File.basename(pfad) }.sort + +# Derive the label from the filename (without extension, hyphens/ +# underscores turned into spaces, each word capitalized) - no additional +# metadata field to maintain, the filename itself is the only source. +eintraege = dateien.map do |datei| + format = File.extname(datei).delete_prefix('.') + name = File.basename(datei, '.*') + label = name.gsub(/[-_]+/, ' ').strip.split(' ').map { |w| w.empty? ? w : w[0].upcase + w[1..] }.join(' ') + { 'datei' => datei, 'format' => format, 'label' => label } +end + +File.write(File.join(verzeichnis, 'vorlagen-manifest.json'), JSON.pretty_generate(eintraege)) +puts "vorlagen-manifest.json geschrieben: #{eintraege.length} Vorlage(n)" diff --git a/scripts/lib/frontmatter.rb b/scripts/lib/frontmatter.rb new file mode 100644 index 0000000..0674abc --- /dev/null +++ b/scripts/lib/frontmatter.rb @@ -0,0 +1,59 @@ +# Shared helpers for reading/writing YAML frontmatter in method and variant +# files - previously each script (validate.rb, apply-veroeffentlicht.rb, +# compute-methoden-sichtbarkeit.rb) had its own copy of +# read_frontmatter/write_frontmatter. +# +# More important than the duplication itself: a fixed field order when +# writing (Befund G, see the project website (background/analysis notes) Teil 5, Schritt 6). +# Ruby hashes preserve insertion order - a field that was deleted and +# re-set (e.g. "draft" after fm.delete/fm[]=) used to move to the end, +# creating unnecessary diff noise. Fields outside the canonical order are +# not discarded but appended at the end unchanged (in their previous +# order) - a script that doesn't know a field should still not silently +# lose it. +require 'yaml' +require 'date' + +module Frontmatter + # Order per the Manifest chapter on the project website Teil C (field catalog), "draft" added: a + # derived field that never appears in the content repo (see Regel 12), + # only in the local copy translated for Hugo (see compute-methoden- + # sichtbarkeit.rb). + METHODEN_FELDER = %w[ + kennung titel kurzbeschreibung verwendungsmoeglichkeit zielgruppe + kompetenzbereich kategorie tags lernchancen herkunft initiatoren draft + ].freeze + + # "draft" replaces "veroeffentlicht" at the same position in the local + # copy translated for Hugo (see apply-veroeffentlicht.rb) - the two sit + # next to each other in the canonical order, but only one of them ever + # appears in a given committed resp. translated file. + VARIANTEN_FELDER = %w[ + kennung methode untertitel varianten_beschreibung veroeffentlicht draft dauer_minuten + gruppengroesse_min gruppengroesse_max material autoren lizenz quellen + anhaenge + ].freeze + + def self.read(path) + parse(File.read(path, encoding: 'UTF-8')) + end + + # Same split+parse as read(), but for text already in memory (e.g. from + # `git show`) instead of a file on disk - see scripts/validate.rb, + # vorherige_kennung. + def self.parse(text) + return nil unless text.start_with?("---\n") + parts = text.split(/^---\s*$/, 3) + return nil unless parts.length == 3 + fm = YAML.safe_load(parts[1], permitted_classes: [Date, Time]) || {} + [fm, parts[2]] + end + + def self.write(path, fm, body, feldreihenfolge:) + geordnet = {} + feldreihenfolge.each { |feld| geordnet[feld] = fm[feld] if fm.key?(feld) } + (fm.keys - feldreihenfolge).each { |feld| geordnet[feld] = fm[feld] } + yaml = YAML.dump(geordnet).sub(/\A---\n/, '') + File.write(path, "---\n#{yaml}---#{body}", encoding: 'UTF-8') + end +end diff --git a/scripts/sync-methoden.sh b/scripts/sync-methoden.sh new file mode 100755 index 0000000..19b4602 --- /dev/null +++ b/scripts/sync-methoden.sh @@ -0,0 +1,65 @@ +#!/bin/bash +# Fetches the current state of the separate methods repo +# (ableger_demo/ableger_methoden) into ./_content - for local development and +# in the deploy hook on Uberspace. _content/ is deliberately not part of this +# repo (see .gitignore) and is freshly fetched here on every call instead of +# being pinned as a submodule. Hugo mounts _content/methoden (see +# hugo/hugo.toml) - the content repo itself contains a methoden/ subfolder, +# not just the methods directly at its root (Decap CMS workaround, see +# admin/config.yml). +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +# shellcheck source=/dev/null +source "$ROOT/install.env" + +# ABLEGER_METHODEN_URL completely overrides this fallback in the deploy hook +# (a local filesystem path on the same Uberspace account, see +# the installation guide on the project website) - the SSH fallback built here from install.env is +# only needed for local development without that environment variable set. +REPO_URL="${ABLEGER_METHODEN_URL:-ssh://${GITEA_SSH_USER}@${GITEA_DOMAIN}:${GITEA_SSH_PORT}/${METHODEN_REPO}.git}" +TARGET="$ROOT/_content" + +if [ -d "$TARGET/.git" ]; then + # "remote set-url" ALWAYS before the fetch, not only on first clone: an + # already existing worktree otherwise keeps the remote URL from its + # original clone time, even if REPO_URL has changed since (e.g. after a + # repo rename/transfer to a different organization). This broke live + # exactly this way: after transferring ableger_methoden to the + # "ableger_demo" organization, the worktree already present on the server + # kept pointing at the old path (tobias/ableger_methoden.git), and the + # cron job then failed on every run (every 10 minutes) until this was + # fixed manually. + git -C "$TARGET" remote set-url origin "$REPO_URL" + git -C "$TARGET" fetch origin main + git -C "$TARGET" reset --hard origin/main +else + rm -rf "$TARGET" + git clone "$REPO_URL" "$TARGET" +fi + +echo "_content/ aktuell: $(git -C "$TARGET" rev-parse --short HEAD)" + +# Validate against the Manifest chapter on the project website (website repo) BEFORE +# apply-veroeffentlicht.rb and compute-methoden-sichtbarkeit.rb translate the +# state for Hugo - the validation script needs the real, committed state +# (with "veroeffentlicht", without Hugo's "draft"), otherwise its own rules +# (e.g. Regel 12: no derived fields stored) could never be satisfiable +# against its own translation. set -e above ensures that an error (exit +# code 1) here aborts the entire sync/build before a broken reference or +# similar goes live unnoticed (see the project website (background/analysis notes), Befund A/B) - +# warnings (exit code 0) deliberately do not block. +ruby "$(dirname "${BASH_SOURCE[0]}")/validate.rb" + +# Recompute creation dates from the freshly fetched history. +"$(dirname "${BASH_SOURCE[0]}")/generate-dates.sh" + +# Translate the variants' "veroeffentlicht" field (positive polarity) into +# Hugo's native draft field - must run before compute-methoden- +# sichtbarkeit.rb, which reads that draft field. See +# admin/config.template.yml and the script's own comments. +ruby "$(dirname "${BASH_SOURCE[0]}")/apply-veroeffentlicht.rb" + +# Mark methods without a published variant as draft, locally (not in the +# content repo) - see admin/config.template.yml and the script's own comment. +ruby "$(dirname "${BASH_SOURCE[0]}")/compute-methoden-sichtbarkeit.rb" diff --git a/scripts/validate.rb b/scripts/validate.rb new file mode 100755 index 0000000..5ae22ce --- /dev/null +++ b/scripts/validate.rb @@ -0,0 +1,299 @@ +#!/usr/bin/env ruby +# Validates _content/ against the rules from the Manifest chapter on the project website, Teil D. Runs +# BEFORE apply-veroeffentlicht.rb and compute-methoden-sichtbarkeit.rb (see +# sync-methoden.sh) - so it checks the real, committed state in the content +# repo (with "veroeffentlicht", without Hugo's translated "draft"), not the +# copy translated for the Hugo build. +# +# Two severity levels: +# FEHLER (error) - structural (broken reference, duplicate/changed +# kennung, wrong folder name) - aborts the run with exit code +# 1; the deploy hook (sync-methoden.sh) must treat this as a +# build stop, otherwise e.g. a method with a broken variant +# reference could go live unnoticed (see the project website, +# background/analysis notes, Befund A - exactly this class of error). +# WARNUNG (warning) - content-related (missing required field, vocabulary +# violation) - is reported but does not block: a single +# incomplete entry shouldn't take down the whole site. +# +# Deliberately NO rule "a method needs at least one variant" - a normal +# in-progress state while creating an entry, not a violation (see Manifest +# Teil D). +# +# The required-field list below still duplicates admin/config.template.yml +# (website repo) - the vocabulary (Regel 9) has read from ableger.yml +# (content repo) since Schritt 5 (see the project website (background/analysis notes), Befund C), +# but the required-field list itself stays hardcoded here for now. +require_relative 'lib/frontmatter' +require 'set' + +root = File.expand_path('..', __dir__) +content = File.join(root, '_content') +methoden_dir = File.join(content, 'methoden') +varianten_dir = File.join(content, 'varianten') + +fehler = [] +warnungen = [] + +def read_frontmatter(path) + Frontmatter.read(path) +rescue Psych::SyntaxError => e + [{ '__parse_error__' => e.message }, ''] +end + +def kennung_pattern + # Underscore allowed (e.g. "sinnesparcours-fur-senior_innen" - our + # gender-inclusive spelling "Senior_innen"), otherwise identical to the + # pattern in admin/config.template.yml. + /\A[a-z0-9_]+(-[a-z0-9_]+)*\z/ +end + +# Reads the previous kennung of the same file from git history (the prior +# commit touching this path) - not the very first commit, since "kennung" +# was introduced later and older commits don't know the field yet (no +# comparison possible, no false positive wanted). +def vorherige_kennung(rel_path, content_dir) + # --follow is crucial here: when the kennung changes, the folder is + # usually renamed along with it (Decap does this automatically, since + # the folder name is derived from the kennung - see slug in + # admin/config.template.yml). Without --follow, "git log -- " stops + # right at that rename and only finds the one new commit - the actual + # violation would go undetected. Verified live against our own test case + # (git mv + kennung changed, without --follow: no warning). + # --name-only together with --follow, to get the historical path of the + # commit under which "git show" needs to read the content. + # Output format is "\n\n" per commit, WITHOUT a blank line + # between and the next - so split flatly by lines and read + # in pairs (hash, path, hash, path, ...), not block-wise by blank lines + # (verified live, initially produced mismatched pairs). + zeilen = `cd #{content_dir} && git log --follow --format=%H --name-only -- #{rel_path}`.split("\n").reject(&:empty?) + return nil if zeilen.length < 4 + + voriger_hash, voriger_pfad = zeilen[2], zeilen[3] + + vorheriger_inhalt = `cd #{content_dir} && git show #{voriger_hash}:#{voriger_pfad} 2>/dev/null`.force_encoding('UTF-8') + return nil if vorheriger_inhalt.empty? + result = Frontmatter.parse(vorheriger_inhalt) + return nil unless result + fm, = result + fm['kennung'] +rescue StandardError + nil +end + +def vokabular(daten, name) + werte = (daten['vokabular'] || {})[name] + werte && Array(werte) +end + +methoden_pflichtfelder = %w[kennung titel kurzbeschreibung verwendungsmoeglichkeit zielgruppe kompetenzbereich kategorie lernchancen initiatoren] +varianten_pflichtfelder = %w[veroeffentlicht methode kennung untertitel varianten_beschreibung dauer_minuten gruppengroesse_min gruppengroesse_max material lizenz autoren] + +# --- Regel 14: protokoll_version, also the source of the vocabulary (Regel 9) --- +ableger_yml = File.join(content, 'ableger.yml') +ableger_daten = {} +if File.exist?(ableger_yml) + ableger_daten = YAML.load_file(ableger_yml) || {} + version = ableger_daten['protokoll_version'] + fehler << "ableger.yml: protokoll_version fehlt" unless version + fehler << "ableger.yml: protokoll_version #{version.inspect} wird von diesem Skript nicht unterstützt (bekannt: 1)" if version && version != 1 +else + fehler << "ableger.yml fehlt an der Repo-Wurzel (Regel 14)" +end + +# --- Read methods --- +methoden_kennungen = Set.new +methoden_by_kennung = {} + +Dir.glob(File.join(methoden_dir, '*')).select { |d| File.directory?(d) }.each do |dir| + ordner = File.basename(dir) + index = File.join(dir, 'index.md') + + # Regel 7 + unless File.exist?(index) + fehler << "methoden/#{ordner}/: kein index.md gefunden (Regel 7)" + next + end + + fm, body = read_frontmatter(index) + if fm.nil? || fm.key?('__parse_error__') + fehler << "methoden/#{ordner}/index.md: YAML-Frontmatter ungültig#{fm ? " (#{fm['__parse_error__']})" : ''}" + next + end + + kennung = fm['kennung'] + rel_path = "methoden/#{ordner}/index.md" + + # Regel 5 + if kennung && !kennung_pattern.match?(kennung) + fehler << "#{rel_path}: kennung #{kennung.inspect} passt nicht zum Muster a-z/0-9/- (Regel 5)" + end + + # Regel 3 + if kennung && kennung != ordner + fehler << "#{rel_path}: Ordnername '#{ordner}' entspricht nicht der Kennung '#{kennung}' (Regel 3)" + end + + # Regel 2 (method kennungen unique) + if kennung + if methoden_kennungen.include?(kennung) + fehler << "#{rel_path}: Kennung '#{kennung}' ist nicht eindeutig (Regel 2)" + end + methoden_kennungen << kennung + methoden_by_kennung[kennung] = fm + end + + # Regel 6 (immutability) + if kennung + vorher = vorherige_kennung(rel_path, content) + if vorher && vorher != kennung + fehler << "#{rel_path}: Kennung wurde von '#{vorher}' zu '#{kennung}' geändert (Regel 6)" + end + end + + # Regel 11 (document body empty) + unless body.strip.empty? + warnungen << "#{rel_path}: Dokumentkörper ist nicht leer, gehört bei Methoden aber zur Variante (Regel 11)" + end + + # Regel 12 (no derived fields) + %w[draft dauer_minuten gruppengroesse_min gruppengroesse_max material lizenz erstellt geaendert].each do |feld| + warnungen << "#{rel_path}: enthält abgeleitetes/verschobenes Feld '#{feld}', gehört nicht (mehr) zur Methode (Regel 12)" if fm.key?(feld) + end + + # Regel 8 (required fields) + methoden_pflichtfelder.each do |feld| + wert = fm[feld] + leer = wert.nil? || (wert.respond_to?(:empty?) && wert.empty?) + warnungen << "#{rel_path}: Pflichtfeld '#{feld}' fehlt oder ist leer (Regel 8)" if leer + end + + # Regel 9 (vocabulary) + # lizenz has not been a method field since the field move, see below under variants. + { 'zielgruppe' => vokabular(ableger_daten, 'zielgruppe'), 'kompetenzbereich' => vokabular(ableger_daten, 'kompetenzbereich') }.each do |feld, erlaubt| + next unless erlaubt + werte = Array(fm[feld]) + werte.each do |w| + warnungen << "#{rel_path}: Wert '#{w}' bei '#{feld}' steht nicht im Vokabular (Regel 9)" unless erlaubt.include?(w) + end + end +end + +# --- Read variants --- +varianten_kennungen_je_methode = Hash.new { |h, k| h[k] = Set.new } + +Dir.glob(File.join(varianten_dir, '*')).select { |d| File.directory?(d) }.each do |dir| + ordner = File.basename(dir) + index = File.join(dir, 'index.md') + + unless File.exist?(index) + fehler << "varianten/#{ordner}/: kein index.md gefunden (Regel 7)" + next + end + + fm, _body = read_frontmatter(index) + if fm.nil? || fm.key?('__parse_error__') + fehler << "varianten/#{ordner}/index.md: YAML-Frontmatter ungültig#{fm ? " (#{fm['__parse_error__']})" : ''}" + next + end + + rel_path = "varianten/#{ordner}/index.md" + methode_kennung = fm['methode'] + eigene_kennung = fm['kennung'] + + # Regel 1 + if methode_kennung.nil? || !methoden_kennungen.include?(methode_kennung) + fehler << "#{rel_path}: methode '#{methode_kennung.inspect}' verweist auf keine existierende Methoden-Kennung (Regel 1)" + end + + # Regel 5 + if eigene_kennung && !kennung_pattern.match?(eigene_kennung) + fehler << "#{rel_path}: kennung #{eigene_kennung.inspect} passt nicht zum Muster a-z/0-9/- (Regel 5)" + end + + # Regel 4 + erwarteter_ordner = "#{methode_kennung}--#{eigene_kennung}" + if methode_kennung && eigene_kennung && ordner != erwarteter_ordner + fehler << "#{rel_path}: Ordnername '#{ordner}' entspricht nicht '--' ('#{erwarteter_ordner}') (Regel 4)" + end + + # Regel 2 (variant kennungen unique per method) + if methode_kennung && eigene_kennung + if varianten_kennungen_je_methode[methode_kennung].include?(eigene_kennung) + fehler << "#{rel_path}: Kennung '#{eigene_kennung}' ist bei Methode '#{methode_kennung}' nicht eindeutig (Regel 2)" + end + varianten_kennungen_je_methode[methode_kennung] << eigene_kennung + end + + # Regel 6 (immutability) + if eigene_kennung + vorher = vorherige_kennung(rel_path, content) + if vorher && vorher != eigene_kennung + fehler << "#{rel_path}: Kennung wurde von '#{vorher}' zu '#{eigene_kennung}' geändert (Regel 6)" + end + end + + # Regel 12 (no derived fields) + %w[draft erstellt geaendert].each do |feld| + warnungen << "#{rel_path}: enthält abgeleitetes Feld '#{feld}' - das übernimmt apply-veroeffentlicht.rb/generate-dates.sh selbst (Regel 12)" if fm.key?(feld) + end + + # Regel 8 (required fields) + varianten_pflichtfelder.each do |feld| + wert = fm[feld] + leer = wert.nil? || (wert.respond_to?(:empty?) && wert.empty?) || (feld == 'veroeffentlicht' && wert.nil?) + warnungen << "#{rel_path}: Pflichtfeld '#{feld}' fehlt oder ist leer (Regel 8)" if leer && feld != 'veroeffentlicht' + end + + # Regel 10 + gmin, gmax = fm['gruppengroesse_min'], fm['gruppengroesse_max'] + if gmin && gmax && gmin > gmax + fehler << "#{rel_path}: gruppengroesse_min (#{gmin}) > gruppengroesse_max (#{gmax}) (Regel 10)" + end + + # lizenz must be a plain string, not a list - found live: a bug in + # generate-config.sh (website repo) incorrectly set multiple: true for + # "lizenz" as soon as the vocabulary had more than one value. Decap then + # saved e.g. "- CC0" instead of "CC0" as soon as someone made a selection + # in the CMS. This type error is structural (Regel 8 wouldn't recognize + # it as "empty" at all, since a non-empty list is not an empty value) and + # is therefore handled separately here as an ERROR, not as a vocabulary + # warning. + if fm['lizenz'].is_a?(Array) + fehler << "#{rel_path}: 'lizenz' ist eine Liste (#{fm['lizenz'].inspect}) statt eines einzelnen Werts - Formularfehler beim Speichern, siehe scripts/generate-config.sh" + else + # Regel 9 (vocabulary) + erlaubt = vokabular(ableger_daten, 'lizenz') + if erlaubt && fm['lizenz'] + warnungen << "#{rel_path}: Wert '#{fm['lizenz']}' bei 'lizenz' steht nicht im Vokabular (Regel 9)" unless erlaubt.include?(fm['lizenz']) + end + end + + # Regel 13 (attachments exist) + Array(fm['anhaenge']).each do |anhang| + next unless anhang.is_a?(Hash) && anhang['datei'] + pfad = File.join(dir, anhang['datei']) + fehler << "#{rel_path}: Anhang '#{anhang['datei']}' existiert nicht im selben Ordner (Regel 13)" unless File.exist?(pfad) + end +end + +# --- Ausgabe --- +unless warnungen.empty? + puts "Warnungen (#{warnungen.size}):" + warnungen.each { |w| puts " ⚠ #{w}" } + puts +end + +unless fehler.empty? + puts "Fehler (#{fehler.size}):" + fehler.each { |f| puts " ✗ #{f}" } + puts +end + +if fehler.empty? + puts "Prüfung bestanden#{warnungen.empty? ? '' : " (#{warnungen.size} Warnung(en))"}." + exit 0 +else + puts "Prüfung fehlgeschlagen: #{fehler.size} Fehler." + exit 1 +end diff --git a/vokabular/README.md b/vokabular/README.md new file mode 100644 index 0000000..3df1f11 --- /dev/null +++ b/vokabular/README.md @@ -0,0 +1,12 @@ +# Vokabular + +Das Vokabular (erlaubte Werte für `zielgruppe`, `kompetenzbereich`, `lizenz`) liegt nicht hier, sondern im Content-Repo unter `_content/ableger.yml` (Schlüssel `vokabular`) – siehe das Manifest-Kapitel auf der Projekt-Website, Teil C. Grund: Ein Manifest, dessen Vokabular nur beim Website-Code liegt, teilt das Schicksal der Software, von der es unabhängig sein soll; Repo-Trennung ist für Zugriffsschutz ohnehin das falsche Werkzeug (die eigentliche Vertrauensfrage – wer CMS-Zugang bekommt – ist bewusst eine Prozessfrage außerhalb der Software, siehe `CLAUDE.md`). + +Zwei Verbraucher lesen von dort: + +- `scripts/validate.rb` (Regel 9) prüft Feldwerte dagegen. +- `scripts/generate-config.sh` baut daraus die geschlossenen Auswahllisten in `admin/config.yml` (exportiert das Vokabular zur Laufzeit in ein temporäres Verzeichnis, damit die Textdatei-Logik dort unverändert bleiben konnte). + +`kategorie` und `tags` haben weiterhin bewusst kein Vokabular und bleiben offen – keinen Eintrag dafür in `ableger.yml` ergänzen, ohne das vorher zur Diskussion zu stellen (siehe `CLAUDE.md`). + +Dieses Verzeichnis existiert nur noch für diese Erklärung.