diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..3ddc189 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1792773339, + "narHash": "sha256-rZLrzrC6i+jnTAlvPZHogKDulY7WWDEv9hJeHieO7Zw=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..3c2cd9f --- /dev/null +++ b/flake.nix @@ -0,0 +1,27 @@ +{ + description = "Ai Resume — build environment (Go + templ + SQLite). Node, Vite and bundlers are deliberately absent."; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + outputs = { self, nixpkgs }: + let + systems = [ "x86_64-linux" "aarch64-linux" ]; + forAll = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); + in { + devShells = forAll (pkgs: { + default = pkgs.mkShell { + packages = [ + pkgs.go + pkgs.templ + pkgs.sqlite # the sqlite3 CLI, for inspecting the FTS5 index + pkgs.gnumake + pkgs.curl + ]; + shellHook = '' + echo "ai-resume dev shell — go $(go version | cut -d' ' -f3), templ $(templ version)" + echo "targets: make generate build test dev" + ''; + }; + }); + }; +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f062cca --- /dev/null +++ b/go.mod @@ -0,0 +1,25 @@ +module gitea.lab.audasmedia.com.au/sam/ai-resume + +go 1.25.0 + +require ( + github.com/a-h/templ v0.3.1020 + github.com/alecthomas/chroma/v2 v2.27.0 + github.com/yuin/goldmark v1.8.6 + github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/dlclark/regexp2/v2 v2.2.1 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sys v0.41.0 // indirect + modernc.org/libc v1.55.3 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.8.0 // indirect + modernc.org/sqlite v1.34.5 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..3fffab7 --- /dev/null +++ b/go.sum @@ -0,0 +1,46 @@ +github.com/a-h/templ v0.3.1020 h1:ypAT/L5ySWEnZ6Zft/5yfoWXYYkhFNvEFOeeqecg4tw= +github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM= +github.com/alecthomas/chroma/v2 v2.2.0/go.mod h1:vf4zrexSH54oEjJ7EdB65tGNHmH3pGZmVkgTP5RHvAs= +github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r5BXYZs= +github.com/alecthomas/chroma/v2 v2.27.0/go.mod h1:NjJ3ciIgrqBNeIkWZ4e46nseoLDslxU1LmfCoL+wcY8= +github.com/alecthomas/repr v0.0.0-20220113201626-b1b626ac65ae/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= +github.com/dlclark/regexp2 v1.7.0 h1:7lJfhqlPssTb1WQx4yvTHN0uElPEv52sbaECrAQxjAo= +github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dlclark/regexp2/v2 v2.2.1 h1:mf4KkFUj0gJuarK8P+LgiS+Lit7m9N1yAwEfPbee7R0= +github.com/dlclark/regexp2/v2 v2.2.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/yuin/goldmark v1.4.15/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/goldmark v1.8.6 h1:d0VcaP1sx9GkFVkoW+KtggpGi2KZ965i14b0+bDQST4= +github.com/yuin/goldmark v1.8.6/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= +github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc h1:+IAOyRda+RLrxa1WC7umKOZRsGq4QrFFMYApOeHzQwQ= +github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc/go.mod h1:ovIvrum6DQJA4QsJSovrkC4saKHQVs7TvcaeO8AIl5I= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= +modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= +modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= +modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g= +modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE= diff --git a/internal/content/content.go b/internal/content/content.go new file mode 100644 index 0000000..beed077 --- /dev/null +++ b/internal/content/content.go @@ -0,0 +1,456 @@ +// Package content loads the Markdown source of truth in content/ into documents +// that both renderers (Mode A static pages, Mode B corpus) read. +// +// The schema is frozen; see docs/content-schema.md. This package does not +// re-implement the validator (tools/validate_content.py is the gate). It does +// enforce the invariants the renderer needs, and it fails loudly rather than +// rendering a broken page. +package content + +import ( + "fmt" + "os" + "path" + "path/filepath" + "sort" + "strconv" + "strings" + + "gitea.lab.audasmedia.com.au/sam/ai-resume/internal/stage" + "gopkg.in/yaml.v3" +) + +// Confidence values. These are displayed on the page and are never promoted. +const ( + ConfidenceDelivered = "delivered" + ConfidenceRunning = "running" + ConfidenceInProgress = "in-progress" + ConfidenceAbandoned = "abandoned" + ConfidenceHistoric = "historic" +) + +// Area is one of the six top-level navigation areas. Structure lives in code +// (it comes from reference/content-map.md, not from the content tree); the +// documents that fill it live in content/. +type Area struct { + Key string + Title string + Role string + Blurb string + Gutter string // two-letter mark used by the nav and the stage panel +} + +// Areas is the fixed navigation order from reference/content-map.md. +var Areas = []Area{ + {Key: "ai", Title: "AI & Agentic Systems", Role: "AI / LLM Engineer", Gutter: "AI", + Blurb: "Harnesses, subagents and skills, memory, model routing and cost, retrieval, voice, guardrails, agent observability."}, + {Key: "platform", Title: "Platform & Infrastructure", Role: "Platform / DevOps Engineer", Gutter: "PL", + Blurb: "Declarative hosts, packaging, a fifty-container Docker estate, networking, storage and restore-tested backups, observability."}, + {Key: "edge", Title: "Edge & Devices", Role: "Edge / IoT Engineer", Gutter: "ED", + Blurb: "Twenty-node fleet on constrained devices, custom radio, solar power, deep sleep, sensors and actuation — and the failures."}, + {Key: "products", Title: "Products", Role: "", Gutter: "PR", + Blurb: "Three active businesses, built and run rather than advised on."}, + {Key: "history", Title: "History", Role: "", Gutter: "HI", + Blurb: "2000–2014: agencies, clients, engagements, and the code that survives from them."}, + {Key: "about", Title: "About", Role: "", Gutter: "AB", + Blurb: "The narrative, the non-IT work that came first, education, and how to get in touch."}, +} + +// Positioning is the site's single line of introduction. +const ( + Positioning = "Twenty-five years shipping software. Now building agent systems, the platforms under them, and the hardware at the edge." + SupportLine = "…and it all runs unattended." + Location = "Melbourne" +) + +// AreaByKey returns the area with the given key. +func AreaByKey(key string) (Area, bool) { + for _, a := range Areas { + if a.Key == key { + return a, true + } + } + return Area{}, false +} + +// Metric is one approved chip on a page, e.g. {label: "edge nodes", value: 20}. +type Metric struct { + Label string `yaml:"label"` + Value any `yaml:"value"` +} + +// String renders the chip value with its label: "20 edge nodes". +func (m Metric) String() string { + return fmt.Sprintf("%v %s", m.Value, m.Label) +} + +// Artefact is a drill-down link. Every URL must resolve to a file in this +// repository; nothing external is allowed. +type Artefact struct { + Type string `yaml:"type"` // repo | image | video | doc + Label string `yaml:"label"` + URL string `yaml:"url"` +} + +// Document is one Markdown file plus its front-matter. +type Document struct { + ID string `yaml:"id"` + Area string `yaml:"area"` + Level int `yaml:"level"` + Title string `yaml:"title"` + Claim string `yaml:"claim"` + Confidence string `yaml:"confidence"` + Period string `yaml:"period"` + Tech []string `yaml:"tech"` + Metrics []Metric `yaml:"metrics"` + Artefacts []Artefact `yaml:"artefacts"` + Public bool `yaml:"public"` + LastVerified string `yaml:"last_verified"` + Tags []string `yaml:"tags"` + + // Derived by Load. + Path string `yaml:"-"` // path relative to the content root, e.g. edge/edge-fleet.md + URL string `yaml:"-"` // canonical page URL, e.g. /edge/edge-fleet/ + HTML string `yaml:"-"` // rendered body + Plain string `yaml:"-"` // body reduced to text, for the search index + + bodyRaw string // Markdown body, rendered by the markdown renderer + + // Backlinks are the documents that reference this one as an artefact. + Backlinks []*Document `yaml:"-"` +} + +// ResolvedArtefact is an Artefact with its target resolved. +type ResolvedArtefact struct { + Artefact + Target *Document // non-nil when the artefact is an L3/L2 document + File string // absolute path on disk + Rel string // path relative to the content root, e.g. assets/x.svg + Href string // site URL: a page URL for documents, /assets/... for files + Kind string // Fragment kind: text | code | diagram | image | video | links +} + +// Set is every loaded document, indexed. +type Set struct { + Root string + Docs []*Document + byID map[string]*Document + byRel map[string]*Document +} + +// ByID returns the document with the given id. +func (s *Set) ByID(id string) (*Document, bool) { + d, ok := s.byID[id] + return d, ok +} + +// ByRel returns the document at the given content-relative path. +func (s *Set) ByRel(rel string) (*Document, bool) { + d, ok := s.byRel[rel] + return d, ok +} + +// InArea returns the public documents for an area, ordered L1, L2, L3. +func (s *Set) InArea(key string) []*Document { + var out []*Document + for _, d := range s.Docs { + if d.Area == key { + out = append(out, d) + } + } + sort.SliceStable(out, func(i, j int) bool { + if out[i].Level != out[j].Level { + return out[i].Level < out[j].Level + } + return out[i].Title < out[j].Title + }) + return out +} + +// AreaLanding returns the L1 document for an area. +func (s *Set) AreaLanding(key string) (*Document, bool) { + for _, d := range s.InArea(key) { + if d.Level == 1 { + return d, true + } + } + return nil, false +} + +// Load reads every Markdown file under root. Documents with public: false are +// loaded (so links to them still resolve) but are not published. +func Load(root string) (*Set, error) { + info, err := os.Stat(root) + if err != nil { + return nil, fmt.Errorf("content root %q: %w", root, err) + } + if !info.IsDir() { + return nil, fmt.Errorf("content root %q is not a directory", root) + } + + s := &Set{Root: root, byID: map[string]*Document{}, byRel: map[string]*Document{}} + + err = filepath.WalkDir(root, func(p string, e os.DirEntry, err error) error { + if err != nil { + return err + } + name := e.Name() + if e.IsDir() { + if p != root && (strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_")) { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(name, ".md") || strings.HasPrefix(name, ".") { + return nil + } + rel, rerr := filepath.Rel(root, p) + if rerr != nil { + return rerr + } + rel = filepath.ToSlash(rel) + + raw, rerr := os.ReadFile(p) + if rerr != nil { + return rerr + } + doc, derr := parse(rel, p, raw) + if derr != nil { + return derr + } + if prev, dup := s.byID[doc.ID]; dup { + return fmt.Errorf("%s: duplicate id %q (already used by %s)", rel, doc.ID, prev.Path) + } + doc.URL = PageURL(doc) + s.Docs = append(s.Docs, doc) + s.byID[doc.ID] = doc + s.byRel[rel] = doc + return nil + }) + if err != nil { + return nil, err + } + if len(s.Docs) == 0 { + return nil, fmt.Errorf("content root %q contains no documents", root) + } + sort.SliceStable(s.Docs, func(i, j int) bool { + if s.Docs[i].Area != s.Docs[j].Area { + return areaOrder(s.Docs[i].Area) < areaOrder(s.Docs[j].Area) + } + if s.Docs[i].Level != s.Docs[j].Level { + return s.Docs[i].Level < s.Docs[j].Level + } + return s.Docs[i].ID < s.Docs[j].ID + }) + + for _, d := range s.Docs { + for _, a := range d.Artefacts { + ra, rerr := s.Resolve(d, a) + if rerr != nil { + return nil, rerr + } + if ra.Target != nil && ra.Target.ID != d.ID { + ra.Target.Backlinks = append(ra.Target.Backlinks, d) + } + } + } + return s, nil +} + +func areaOrder(key string) int { + for i, a := range Areas { + if a.Key == key { + return i + } + } + return len(Areas) +} + +func parse(rel, abs string, raw []byte) (*Document, error) { + fm, body, err := splitFrontMatter(string(raw)) + if err != nil { + return nil, fmt.Errorf("%s: %w", rel, err) + } + var d Document + dec := yaml.NewDecoder(strings.NewReader(fm)) + dec.KnownFields(true) // unknown front-matter fields are a schema violation + if err := dec.Decode(&d); err != nil { + return nil, fmt.Errorf("%s: front-matter: %w", rel, err) + } + d.Path = rel + d.bodyRaw = body + + if err := d.check(rel); err != nil { + return nil, err + } + return &d, nil +} + +// BodyMarkdown returns the raw Markdown body (everything after the front-matter). +func (d *Document) BodyMarkdown() string { return d.bodyRaw } + +func (d *Document) check(rel string) error { + switch { + case d.ID == "": + return fmt.Errorf("%s: id is required", rel) + case d.Title == "": + return fmt.Errorf("%s: title is required", rel) + case d.Claim == "": + return fmt.Errorf("%s: claim is required", rel) + } + if _, ok := AreaByKey(d.Area); !ok { + return fmt.Errorf("%s: unknown area %q", rel, d.Area) + } + if d.Level < 1 || d.Level > 3 { + return fmt.Errorf("%s: level must be 1, 2 or 3, got %d", rel, d.Level) + } + switch d.Confidence { + case ConfidenceDelivered, ConfidenceRunning, ConfidenceInProgress, ConfidenceAbandoned, ConfidenceHistoric: + default: + return fmt.Errorf("%s: unknown confidence %q", rel, d.Confidence) + } + if d.LastVerified == "" { + return fmt.Errorf("%s: last_verified is required", rel) + } + stem := strings.TrimSuffix(path.Base(rel), ".md") + if stem != d.ID { + return fmt.Errorf("%s: id %q must equal the file name %q", rel, d.ID, stem) + } + for _, a := range d.Artefacts { + if a.URL == "" || a.Label == "" { + return fmt.Errorf("%s: artefact %q needs both label and url", rel, a.Label) + } + if strings.Contains(a.URL, "://") { + return fmt.Errorf("%s: artefact %q uses an external URL; create an in-repo stub instead", rel, a.URL) + } + } + return nil +} + +func splitFrontMatter(src string) (fm, body string, err error) { + src = strings.ReplaceAll(src, "\r\n", "\n") + if !strings.HasPrefix(src, "---\n") { + return "", "", fmt.Errorf("missing front-matter block on line 1") + } + rest := src[len("---\n"):] + for _, delim := range []string{"\n---\n", "\n...\n"} { + if i := strings.Index(rest, delim); i >= 0 { + return rest[:i], rest[i+len(delim):], nil + } + } + return "", "", fmt.Errorf("unterminated front-matter block") +} + +// PageURL is the canonical URL for a document. Depth maps onto the URL path so +// the drill-down is legible: /edge/ · /edge/edge-fleet/ · /edge/a/edge-zigbee/. +func PageURL(d *Document) string { + switch d.Level { + case 1: + return "/" + d.Area + "/" + case 2: + return "/" + d.Area + "/" + d.ID + "/" + default: + return "/" + d.Area + "/a/" + d.ID + "/" + } +} + +// Resolve maps an artefact reference onto a file, a site URL and a stage +// fragment kind. Paths may be repository-relative ("content/edge/l3/x.md") or +// document-relative ("./l3/x.md", "l3/x.md"). +func (s *Set) Resolve(from *Document, a Artefact) (ResolvedArtefact, error) { + rel := a.URL + var target string + switch { + case strings.HasPrefix(rel, "content/"): + target = strings.TrimPrefix(rel, "content/") + case strings.HasPrefix(rel, "/") || strings.HasPrefix(rel, "../"): + return ResolvedArtefact{}, fmt.Errorf("%s: artefact %q must not be root-absolute or escape the repo", from.Path, rel) + default: + target = path.Join(path.Dir(from.Path), rel) + } + target = path.Clean(target) + + out := ResolvedArtefact{Artefact: a, Rel: target} + abs := filepath.Join(s.Root, filepath.FromSlash(target)) + st, err := os.Stat(abs) + if err != nil { + return out, fmt.Errorf("%s: artefact %q does not resolve to a file (%s)", from.Path, a.URL, target) + } + if st.IsDir() { + return out, fmt.Errorf("%s: artefact %q resolves to a directory", from.Path, a.URL) + } + out.File = abs + if strings.HasSuffix(target, ".md") { + doc, ok := s.byRel[target] + if !ok { + return out, fmt.Errorf("%s: artefact %q is not a loaded document", from.Path, a.URL) + } + out.Target = doc + out.Href = doc.URL + out.Kind = stage.KindText + return out, nil + } + out.Href = "/assets/" + strings.TrimPrefix(target, "assets/") + out.Kind = KindForFile(target) + return out, nil +} + +var codeExtensions = map[string]string{ + ".go": "go", ".js": "javascript", ".mjs": "javascript", ".ts": "typescript", + ".nix": "nix", ".php": "php", ".as": "actionscript", ".hpp": "cpp", ".h": "cpp", + ".c": "c", ".cpp": "cpp", ".py": "python", ".sh": "bash", ".yaml": "yaml", + ".yml": "yaml", ".json": "json", ".css": "css", ".sql": "sql", ".templ": "templ", +} + +// KindForFile maps a file extension onto a stage fragment kind. +func KindForFile(name string) string { + ext := strings.ToLower(path.Ext(name)) + if lang, ok := codeExtensions[ext]; ok && lang != "" { + return stage.KindCode + } + switch ext { + case ".svg": + return stage.KindDiagram + case ".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif": + return stage.KindImage + case ".mp4", ".webm", ".mov": + return stage.KindVideo + case ".md": + return stage.KindText + } + return stage.KindLinks +} + +// LanguageFor returns the chroma language for a file, if it is code. +func LanguageFor(name string) string { + return codeExtensions[strings.ToLower(path.Ext(name))] +} + +// Truncate shortens s to at most n runes, on a word boundary where possible. +func Truncate(s string, n int) string { + s = strings.TrimSpace(s) + if len([]rune(s)) <= n { + return s + } + r := []rune(s)[:n] + if i := strings.LastIndex(string(r), " "); i > n/2 { + return strings.TrimSpace(string(r)[:i]) + "…" + } + return strings.TrimSpace(string(r)) + "…" +} + +// MetricValue renders a metric value for display. +func MetricValue(v any) string { + switch t := v.(type) { + case nil: + return "" + case string: + return t + case int: + return strconv.Itoa(t) + case bool: + return strconv.FormatBool(t) + default: + return fmt.Sprint(t) + } +} diff --git a/internal/content/markdown.go b/internal/content/markdown.go new file mode 100644 index 0000000..9f0d51b --- /dev/null +++ b/internal/content/markdown.go @@ -0,0 +1,180 @@ +package content + +import ( + "bytes" + "fmt" + stdhtml "html" + "io" + "path" + "regexp" + "strings" + + "github.com/alecthomas/chroma/v2" + chromahtml "github.com/alecthomas/chroma/v2/formatters/html" + "github.com/alecthomas/chroma/v2/lexers" + "github.com/alecthomas/chroma/v2/styles" + highlighting "github.com/yuin/goldmark-highlighting/v2" + "github.com/yuin/goldmark" + "github.com/yuin/goldmark/ast" + "github.com/yuin/goldmark/extension" + "github.com/yuin/goldmark/parser" + "github.com/yuin/goldmark/renderer/html" + "github.com/yuin/goldmark/util" + "github.com/yuin/goldmark/text" + + "gitea.lab.audasmedia.com.au/sam/ai-resume/internal/stage" +) + +// RendererStyle is the chroma style. Dark by default, matching the rest of +// Sam's surfaces. +const RendererStyle = "github-dark" + +// Renderer turns Markdown into server-side HTML. Nothing here runs in a +// browser: goldmark for structure and tables, chroma for code, at build time. +type Renderer struct { + md goldmark.Markdown + set *Set +} + +// NewRenderer builds a renderer bound to a document set (needed to rewrite +// relative .md links into site URLs). +func NewRenderer(s *Set) *Renderer { + r := &Renderer{set: s} + r.md = goldmark.New( + goldmark.WithExtensions( + extension.GFM, + extension.Footnote, + extension.Typographer, + highlighting.NewHighlighting( + highlighting.WithStyle(RendererStyle), + highlighting.WithFormatOptions(chromahtml.WithClasses(true)), + ), + ), + goldmark.WithParserOptions( + parser.WithAutoHeadingID(), + parser.WithASTTransformers(util.Prioritized(r, 100)), + ), + goldmark.WithRendererOptions(html.WithUnsafe()), // trusted, in-repo Markdown + ) + return r +} + +// Transform rewrites document-relative links into site URLs so the +// pre-rendered pages work as static files. The current document is carried in +// the parser context by Render and Highlight-free callers. +func (r *Renderer) Transform(doc *ast.Document, reader text.Reader, pc parser.Context) { + current, ok := pc.Get(docKey).(*Document) + if !ok || current == nil { + return + } + _ = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) { + if !entering { + return ast.WalkContinue, nil + } + switch node := n.(type) { + case *ast.Link: + node.Destination = r.rewrite(current, string(node.Destination), false) + case *ast.Image: + node.Destination = r.rewrite(current, string(node.Destination), true) + } + return ast.WalkContinue, nil + }) +} + +func (r *Renderer) rewrite(from *Document, dest string, image bool) []byte { + if dest == "" || strings.Contains(dest, "://") || strings.HasPrefix(dest, "/") || + strings.HasPrefix(dest, "#") || strings.HasPrefix(dest, "mailto:") { + return []byte(dest) + } + target := dest + suffix := "" + if i := strings.IndexAny(target, "#?"); i >= 0 { + suffix = target[i:] + target = target[:i] + } + rel := target + if strings.HasPrefix(rel, "content/") { + rel = strings.TrimPrefix(rel, "content/") + } else { + rel = path.Join(path.Dir(from.Path), rel) + } + rel = path.Clean(rel) + if d, ok := r.set.byRel[rel]; ok { + return []byte(d.URL + suffix) + } + if image || KindForFile(rel) != stage.KindLinks { + return []byte(AssetHref(rel) + suffix) + } + return []byte(dest) +} + +// docKey carries the document being rendered through the parser context so +// the link rewriter knows what "relative" means. +var docKey = parser.NewContextKey() + +// Render fills HTML and Plain on every document in the set. +func (r *Renderer) Render() error { + for _, d := range r.set.Docs { + var buf bytes.Buffer + ctx := parser.NewContext() + ctx.Set(docKey, d) + if err := r.md.Convert([]byte(d.BodyMarkdown()), &buf, parser.WithContext(ctx)); err != nil { + return fmt.Errorf("%s: render Markdown: %w", d.Path, err) + } + d.HTML = buf.String() + d.Plain = PlainText(d.HTML) + } + return nil +} + +// Highlight renders a standalone code file with chroma. Used by L3 code +// artefacts and by the make-target that keeps the code exhibits in sync. +func (r *Renderer) Highlight(w io.Writer, lang string, src []byte) error { + lexer := lexers.Get(lang) + if lexer == nil { + lexer = lexers.Analyse(string(src)) + } + if lexer == nil { + _, err := fmt.Fprintf(w, "
%s
", stdhtml.EscapeString(string(src))) + return err + } + lexer = chroma.Coalesce(lexer) + it, err := lexer.Tokenise(nil, string(src)) + if err != nil { + return err + } + style := styles.Get(RendererStyle) + if style == nil { + return fmt.Errorf("unknown chroma style %q", RendererStyle) + } + formatter := chromahtml.New(chromahtml.WithClasses(true), chromahtml.WithLineNumbers(false)) + return formatter.Format(w, style, it) +} + +// ChromaCSS returns the stylesheet for the highlighted classes, so the built +// site makes no colour decisions inline. +func (r *Renderer) ChromaCSS() (string, error) { + style := styles.Get(RendererStyle) + if style == nil { + return "", fmt.Errorf("unknown chroma style %q", RendererStyle) + } + var buf bytes.Buffer + if err := chromahtml.New(chromahtml.WithClasses(true)).WriteCSS(&buf, style); err != nil { + return "", err + } + return buf.String(), nil +} + +// AssetHref maps a content-relative asset path onto its published URL. +func AssetHref(rel string) string { + return "/assets/" + strings.TrimPrefix(path.Clean(rel), "assets/") +} + +var tagRe = regexp.MustCompile(`(?s)<[^>]*>`) + +// PlainText reduces rendered HTML to indexable text. +func PlainText(h string) string { + h = tagRe.ReplaceAllString(h, " ") + h = stdhtml.UnescapeString(h) + return strings.Join(strings.Fields(h), " ") +} diff --git a/internal/search/search.go b/internal/search/search.go new file mode 100644 index 0000000..61f1a7c --- /dev/null +++ b/internal/search/search.go @@ -0,0 +1,187 @@ +// Package search builds the SQLite FTS5 index over the static pages. +// +// The index is written by the build step and opened read-only by the server, so +// a search never touches the content tree and works with every AI service +// stopped. The same index is the keyword half of Phase 4's hybrid retrieval: +// its schema is documented in docs/phase-2-notes.md and must not change shape +// without both phases agreeing. +package search + +import ( + "database/sql" + "fmt" + "os" + "path/filepath" + "strings" + "unicode" + + _ "modernc.org/sqlite" +) + +// Doc is one indexable page. +type Doc struct { + ID string + URL string + Title string + Area string + Level int + Confidence string + Body string +} + +// Result is one hit. +type Result struct { + URL string `json:"url"` + Title string `json:"title"` + Area string `json:"area"` + Level int `json:"level"` + Confidence string `json:"confidence"` + Snippet string `json:"snippet"` + Score float64 `json:"score"` +} + +// Schema is the FTS5 table. Columns marked UNINDEXED are still selectable. +const schema = ` +CREATE VIRTUAL TABLE pages USING fts5( + id UNINDEXED, + url UNINDEXED, + title, + area UNINDEXED, + level UNINDEXED, + confidence UNINDEXED, + body, + tokenize = 'porter unicode61 remove_diacritics 2' +);` + +// Build writes a fresh index at path. Any existing file is replaced, so the +// index always describes exactly one build. +func Build(path string, docs []Doc) error { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return err + } + db, err := sql.Open("sqlite", "file:"+path) + if err != nil { + return fmt.Errorf("open index %s: %w", path, err) + } + defer db.Close() + db.SetMaxOpenConns(1) + + if _, err := db.Exec(`PRAGMA journal_mode = OFF; PRAGMA synchronous = OFF;`); err != nil { + return err + } + if _, err := db.Exec(schema); err != nil { + return fmt.Errorf("create fts5 table: %w", err) + } + tx, err := db.Begin() + if err != nil { + return err + } + stmt, err := tx.Prepare(`INSERT INTO pages (id, url, title, area, level, confidence, body) VALUES (?, ?, ?, ?, ?, ?, ?)`) + if err != nil { + return err + } + defer stmt.Close() + for _, d := range docs { + if _, err := stmt.Exec(d.ID, d.URL, d.Title, d.Area, d.Level, d.Confidence, d.Body); err != nil { + return fmt.Errorf("index %s: %w", d.ID, err) + } + } + if err := tx.Commit(); err != nil { + return err + } + if _, err := db.Exec(`INSERT INTO pages (pages) VALUES ('optimize')`); err != nil { + return err + } + return nil +} + +// Index is a read-only handle on a built index. +type Index struct { + db *sql.DB + path string +} + +// Open opens a built index read-only. +func Open(path string) (*Index, error) { + if _, err := os.Stat(path); err != nil { + return nil, fmt.Errorf("search index %s: %w", path, err) + } + db, err := sql.Open("sqlite", "file:"+path+"?mode=ro") + if err != nil { + return nil, err + } + db.SetMaxOpenConns(1) + if err := db.Ping(); err != nil { + db.Close() + return nil, err + } + return &Index{db: db, path: path}, nil +} + +// Close releases the handle. +func (i *Index) Close() error { return i.db.Close() } + +// Count returns the number of indexed pages. +func (i *Index) Count() (int, error) { + var n int + err := i.db.QueryRow(`SELECT count(*) FROM pages`).Scan(&n) + return n, err +} + +// Query runs a keyword search. Every term is matched as a prefix so "zigbee" +// finds "Zigbee" and "routing" finds "routers". +func (i *Index) Query(q string, limit int) ([]Result, error) { + match := MatchExpression(q) + if match == "" { + return nil, nil + } + if limit <= 0 || limit > 50 { + limit = 20 + } + rows, err := i.db.Query(` + SELECT url, title, area, CAST(level AS INTEGER), confidence, + snippet(pages, 6, '', '', '…', 18), + bm25(pages) + FROM pages + WHERE pages MATCH ? + ORDER BY bm25(pages) + LIMIT ?`, match, limit) + if err != nil { + return nil, fmt.Errorf("search %q: %w", q, err) + } + defer rows.Close() + + var out []Result + for rows.Next() { + var r Result + if err := rows.Scan(&r.URL, &r.Title, &r.Area, &r.Level, &r.Confidence, &r.Snippet, &r.Score); err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} + +// MatchExpression turns free text into a safe FTS5 query: bare words only, each +// as a prefix, all required. FTS5 operators in the input are never honoured, so +// a visitor cannot shape the query beyond words. +func MatchExpression(q string) string { + terms := strings.FieldsFunc(strings.ToLower(q), func(r rune) bool { + return !(unicode.IsLetter(r) || unicode.IsDigit(r) || r == '-') + }) + if len(terms) == 0 { + return "" + } + out := make([]string, 0, len(terms)) + for _, t := range terms { + t = strings.Trim(t, "-") + if t == "" { + continue + } + out = append(out, `"`+t+`"*`) + } + return strings.Join(out, " AND ") +} diff --git a/internal/stage/stage.go b/internal/stage/stage.go new file mode 100644 index 0000000..98a9ff1 --- /dev/null +++ b/internal/stage/stage.go @@ -0,0 +1,303 @@ +// Package stage defines the presentation panel as a content sink rather than a +// page renderer. +// +// The contract (docs/phase-2-static-site.md §2.4): +// +// Stage ← driver(route) // Mode A: HTMX fragment swap, pre-rendered files +// Stage ← driver(SSE) // Mode B: streamed fragments (Phase 5) +// +// Layout code renders a Binding. It never asks which driver produced it, so +// re-pointing the panel at a stream is a one-line change at the call site in +// Mode B's page and no change at all to Layout or Stage. +package stage + +import ( + "context" + "encoding/json" + "fmt" + "sort" + + "github.com/a-h/templ" +) + +// Fragment kinds the panel can display. These are the whole vocabulary: adding +// one is a deliberate change to §2.4. +const ( + KindText = "text" + KindCode = "code" + KindImage = "image" + KindVideo = "video" + KindDiagram = "diagram" + KindLinks = "links" +) + +// PanelID is the element both drivers swap into. The templates render this id +// and the bindings target it, so there is one name for it in the codebase. +const PanelID = "stage-content" + +// PanelTarget is the CSS selector for PanelID. +func PanelTarget() string { return "#" + PanelID } + +// Mode is how a panel receives content. +type Mode string + +const ( + // ModeRoute pulls one pre-rendered fragment per interaction. Mode A. + ModeRoute Mode = "route" + // ModeStream receives fragments pushed over SSE. Mode B. + ModeStream Mode = "stream" +) + +// Code is a highlighted code exhibit. +type Code struct { + Language string + Label string + HTML templ.Component // chroma-highlighted, or a
 fallback
+}
+
+// Link is one row of a link-list fragment.
+type Link struct {
+	Label string
+	Href  string
+	Note  string
+}
+
+// Fragment is one thing the panel can show. The same struct is rendered to a
+// static file for the route driver and pushed over SSE for the stream driver.
+type Fragment struct {
+	ID         string
+	Kind       string
+	Title      string
+	Subtitle   string
+	Body       templ.Component // pre-rendered HTML for text fragments
+	Code       *Code
+	Src        string // image, video or diagram source
+	Alt        string
+	Links      []Link
+	DocURL     string
+	DocTitle   string
+	Confidence string
+}
+
+// Binding is everything the Stage component needs to know about its driver.
+// Route mode contributes nothing but a marker; stream mode contributes the SSE
+// wiring. Both are rendered by the same Stage template.
+type Binding struct {
+	Mode     Mode
+	Endpoint string // stream: the SSE endpoint
+	Event    string // stream: the event name to swap on
+	Target   string // CSS selector the driver swaps into
+	Swap     string // htmx swap style
+	Label    string // human description of the driver, shown in the empty state
+	Hint     string // one line telling the reader what to do
+}
+
+// Attributes returns the htmx/SSE attributes for the panel. Only the stream
+// driver needs any: in route mode the trigger elements carry hx-get and
+// hx-target, because a fragment is chosen by clicking evidence.
+func (b Binding) Attributes() templ.Attributes {
+	attrs := templ.Attributes{"data-stage-driver": string(b.Mode)}
+	switch b.Mode {
+	case ModeStream:
+		attrs["hx-ext"] = "sse"
+		attrs["sse-connect"] = b.Endpoint
+		attrs["sse-swap"] = b.Event
+		attrs["hx-swap"] = b.Swap
+		attrs["aria-live"] = "polite"
+	}
+	return attrs
+}
+
+// TargetSelector is the panel a link or a stream should swap into.
+func (b Binding) TargetSelector() string {
+	if b.Target == "" {
+		return PanelTarget()
+	}
+	return b.Target
+}
+
+// Driver is the whole contract between the panel and whatever feeds it.
+type Driver interface {
+	Mode() Mode
+	// Bind returns the binding to render on the Stage panel.
+	Bind() Binding
+}
+
+// RouteDriver feeds the panel from pre-rendered fragment files. Mode A.
+type RouteDriver struct {
+	// BaseURL is where fragment files are served from, e.g. "/stage".
+	BaseURL string
+	Label   string
+	Hint    string
+}
+
+// Mode is part of the Driver contract.
+func (RouteDriver) Mode() Mode { return ModeRoute }
+
+// Bind is part of the Driver contract.
+func (d RouteDriver) Bind() Binding {
+	return Binding{
+		Mode:   ModeRoute,
+		Target: PanelTarget(),
+		Swap:   "innerHTML",
+		Label:  defaultString(d.Label, "Evidence panel · driven by route"),
+		Hint:   defaultString(d.Hint, "Choose a claim from the evidence table; the artefact appears here."),
+	}
+}
+
+// FragmentURL is the pre-rendered URL for a fragment id.
+func (d RouteDriver) FragmentURL(id string) string {
+	base := d.BaseURL
+	if base == "" {
+		base = "/stage"
+	}
+	return base + "/" + id
+}
+
+// SSEDriver feeds the panel from an event stream. Same panel, same fragments,
+// different transport. Used by the Phase 5 console; demonstrated in Phase 2 by
+// a stream of the pre-built fragments so the plumbing is provable without AI.
+type SSEDriver struct {
+	Endpoint string
+	Event    string
+	Label    string
+	Hint     string
+}
+
+// Mode is part of the Driver contract.
+func (SSEDriver) Mode() Mode { return ModeStream }
+
+// Bind is part of the Driver contract.
+func (d SSEDriver) Bind() Binding {
+	event := d.Event
+	if event == "" {
+		event = "stage"
+	}
+	return Binding{
+		Mode:     ModeStream,
+		Endpoint: d.Endpoint,
+		Event:    event,
+		Target:   PanelTarget(),
+		Swap:     "innerHTML",
+		Label:    defaultString(d.Label, "Evidence panel · driven by stream"),
+		Hint:     defaultString(d.Hint, "Frames arrive as they are produced and replace the panel each time."),
+	}
+}
+
+func defaultString(v, fallback string) string {
+	if v == "" {
+		return fallback
+	}
+	return v
+}
+
+// Source produces the fragments a stream driver pushes. Phase 2 provides
+// ManifestSource; Phase 5 provides the retrieval-driven source. Neither
+// touches the panel.
+type Source interface {
+	// Stream sends fragments for keys, in order, until done or ctx is done.
+	// Returning an error ends the stream; the panel keeps the last fragment.
+	Stream(ctx context.Context, keys []string, send func(Fragment) error) error
+}
+
+// Entry is one pre-rendered fragment, as recorded at build time.
+type Entry struct {
+	ID    string `json:"id"`
+	DocID string `json:"doc"`
+	Title string `json:"title"`
+	Kind  string `json:"kind"`
+	// File is relative to the published root, e.g. "stage/edge-fleet/1.html".
+	File string `json:"file"`
+}
+
+// Manifest is the build-time index of fragments. The server uses it to stream
+// fragments that were rendered once, and the route driver serves the same
+// files directly.
+type Manifest struct {
+	Entries []Entry `json:"entries"`
+}
+
+// ByID looks an entry up.
+func (m *Manifest) ByID(id string) (Entry, bool) {
+	for _, e := range m.Entries {
+		if e.ID == id {
+			return e, true
+		}
+	}
+	return Entry{}, false
+}
+
+// ForDoc returns the entries belonging to a document, oldest first.
+func (m *Manifest) ForDoc(docID string) []Entry {
+	var out []Entry
+	for _, e := range m.Entries {
+		if e.DocID == docID {
+			out = append(out, e)
+		}
+	}
+	return out
+}
+
+// Marshal encodes the manifest for the build to write.
+func (m *Manifest) Marshal() ([]byte, error) { return json.MarshalIndent(m, "", "  ") }
+
+// LoadManifest parses a manifest written by the build.
+func LoadManifest(b []byte) (*Manifest, error) {
+	var m Manifest
+	if err := json.Unmarshal(b, &m); err != nil {
+		return nil, fmt.Errorf("stage manifest: %w", err)
+	}
+	return &m, nil
+}
+
+// ManifestSource streams fragments that were pre-rendered at build time. It
+// exists to prove the stream path end to end without a model in the loop; the
+// Phase 5 source implements the same interface with retrieval behind it.
+type ManifestSource struct {
+	manifest *Manifest
+	// HTML returns the pre-rendered markup for an entry.
+	HTML func(Entry) (string, error)
+	// Frame is an optional hook called as each fragment is sent, for pacing.
+	Frame func(index int)
+}
+
+// NewManifestSource wires a manifest and a reader together.
+func NewManifestSource(m *Manifest, read func(Entry) (string, error), frame func(int)) *ManifestSource {
+	return &ManifestSource{manifest: m, HTML: read, Frame: frame}
+}
+
+// Stream is part of the Source contract.
+func (s *ManifestSource) Stream(ctx context.Context, keys []string, send func(Fragment) error) error {
+	entries := make([]Entry, 0, len(keys))
+	if len(keys) == 0 {
+		entries = append(entries, s.manifest.Entries...)
+	}
+	for _, k := range keys {
+		if e, ok := s.manifest.ByID(k); ok {
+			entries = append(entries, e)
+			continue
+		}
+		// A document id expands to that document's fragments.
+		entries = append(entries, s.manifest.ForDoc(k)...)
+	}
+	sort.SliceStable(entries, func(i, j int) bool { return entries[i].ID < entries[j].ID })
+
+	for i, e := range entries {
+		if err := ctx.Err(); err != nil {
+			return err
+		}
+		html, err := s.HTML(e)
+		if err != nil {
+			return err
+		}
+		if s.Frame != nil {
+			s.Frame(i)
+		}
+		frag := Fragment{ID: e.ID, Kind: e.Kind, Title: e.Title, Body: templ.Raw(html)}
+		if err := send(frag); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
diff --git a/internal/web/static/htmx.min.js b/internal/web/static/htmx.min.js
new file mode 100644
index 0000000..59937d7
--- /dev/null
+++ b/internal/web/static/htmx.min.js
@@ -0,0 +1 @@
+var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","
");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/internal/web/static/sse.js b/internal/web/static/sse.js new file mode 100644 index 0000000..9f5af5c --- /dev/null +++ b/internal/web/static/sse.js @@ -0,0 +1,290 @@ +/* +Server Sent Events Extension +============================ +This extension adds support for Server Sent Events to htmx. See /www/extensions/sse.md for usage instructions. + +*/ + +(function() { + /** @type {import("../htmx").HtmxInternalApi} */ + var api + + htmx.defineExtension('sse', { + + /** + * Init saves the provided reference to the internal HTMX API. + * + * @param {import("../htmx").HtmxInternalApi} api + * @returns void + */ + init: function(apiRef) { + // store a reference to the internal API. + api = apiRef + + // set a function in the public API for creating new EventSource objects + if (htmx.createEventSource == undefined) { + htmx.createEventSource = createEventSource + } + }, + + getSelectors: function() { + return ['[sse-connect]', '[data-sse-connect]', '[sse-swap]', '[data-sse-swap]'] + }, + + /** + * onEvent handles all events passed to this extension. + * + * @param {string} name + * @param {Event} evt + * @returns void + */ + onEvent: function(name, evt) { + var parent = evt.target || evt.detail.elt + switch (name) { + case 'htmx:beforeCleanupElement': + var internalData = api.getInternalData(parent) + // Try to remove remove an EventSource when elements are removed + var source = internalData.sseEventSource + if (source) { + api.triggerEvent(parent, 'htmx:sseClose', { + source, + type: 'nodeReplaced', + }) + internalData.sseEventSource.close() + } + + return + + // Try to create EventSources when elements are processed + case 'htmx:afterProcessNode': + ensureEventSourceOnElement(parent) + } + } + }) + + /// //////////////////////////////////////////// + // HELPER FUNCTIONS + /// //////////////////////////////////////////// + + /** + * createEventSource is the default method for creating new EventSource objects. + * it is hoisted into htmx.config.createEventSource to be overridden by the user, if needed. + * + * @param {string} url + * @returns EventSource + */ + function createEventSource(url) { + return new EventSource(url, { withCredentials: true }) + } + + /** + * registerSSE looks for attributes that can contain sse events, right + * now hx-trigger and sse-swap and adds listeners based on these attributes too + * the closest event source + * + * @param {HTMLElement} elt + */ + function registerSSE(elt) { + // Add message handlers for every `sse-swap` attribute + if (api.getAttributeValue(elt, 'sse-swap')) { + // Find closest existing event source + var sourceElement = api.getClosestMatch(elt, hasEventSource) + if (sourceElement == null) { + // api.triggerErrorEvent(elt, "htmx:noSSESourceError") + return null // no eventsource in parentage, orphaned element + } + + // Set internalData and source + var internalData = api.getInternalData(sourceElement) + var source = internalData.sseEventSource + + var sseSwapAttr = api.getAttributeValue(elt, 'sse-swap') + var sseEventNames = sseSwapAttr.split(',') + + for (var i = 0; i < sseEventNames.length; i++) { + const sseEventName = sseEventNames[i].trim() + const listener = function(event) { + // If the source is missing then close SSE + if (maybeCloseSSESource(sourceElement)) { + return + } + + // If the body no longer contains the element, remove the listener + if (!api.bodyContains(elt)) { + source.removeEventListener(sseEventName, listener) + return + } + + // swap the response into the DOM and trigger a notification + if (!api.triggerEvent(elt, 'htmx:sseBeforeMessage', event)) { + return + } + swap(elt, event.data) + api.triggerEvent(elt, 'htmx:sseMessage', event) + } + + // Register the new listener + api.getInternalData(elt).sseEventListener = listener + source.addEventListener(sseEventName, listener) + } + } + + // Add message handlers for every `hx-trigger="sse:*"` attribute + if (api.getAttributeValue(elt, 'hx-trigger')) { + // Find closest existing event source + var sourceElement = api.getClosestMatch(elt, hasEventSource) + if (sourceElement == null) { + // api.triggerErrorEvent(elt, "htmx:noSSESourceError") + return null // no eventsource in parentage, orphaned element + } + + // Set internalData and source + var internalData = api.getInternalData(sourceElement) + var source = internalData.sseEventSource + + var triggerSpecs = api.getTriggerSpecs(elt) + triggerSpecs.forEach(function(ts) { + if (ts.trigger.slice(0, 4) !== 'sse:') { + return + } + + var listener = function (event) { + if (maybeCloseSSESource(sourceElement)) { + return + } + if (!api.bodyContains(elt)) { + source.removeEventListener(ts.trigger.slice(4), listener) + } + // Trigger events to be handled by the rest of htmx + htmx.trigger(elt, ts.trigger, event) + htmx.trigger(elt, 'htmx:sseMessage', event) + } + + // Register the new listener + api.getInternalData(elt).sseEventListener = listener + source.addEventListener(ts.trigger.slice(4), listener) + }) + } + } + + /** + * ensureEventSourceOnElement creates a new EventSource connection on the provided element. + * If a usable EventSource already exists, then it is returned. If not, then a new EventSource + * is created and stored in the element's internalData. + * @param {HTMLElement} elt + * @param {number} retryCount + * @returns {EventSource | null} + */ + function ensureEventSourceOnElement(elt, retryCount) { + if (elt == null) { + return null + } + + // handle extension source creation attribute + if (api.getAttributeValue(elt, 'sse-connect')) { + var sseURL = api.getAttributeValue(elt, 'sse-connect') + if (sseURL == null) { + return + } + + ensureEventSource(elt, sseURL, retryCount) + } + + registerSSE(elt) + } + + function ensureEventSource(elt, url, retryCount) { + var source = htmx.createEventSource(url) + + source.onerror = function(err) { + // Log an error event + api.triggerErrorEvent(elt, 'htmx:sseError', { error: err, source }) + + // If parent no longer exists in the document, then clean up this EventSource + if (maybeCloseSSESource(elt)) { + return + } + + // Otherwise, try to reconnect the EventSource + if (source.readyState === EventSource.CLOSED) { + retryCount = retryCount || 0 + retryCount = Math.max(Math.min(retryCount * 2, 128), 1) + var timeout = retryCount * 500 + window.setTimeout(function() { + ensureEventSourceOnElement(elt, retryCount) + }, timeout) + } + } + + source.onopen = function(evt) { + api.triggerEvent(elt, 'htmx:sseOpen', { source }) + + if (retryCount && retryCount > 0) { + const childrenToFix = elt.querySelectorAll("[sse-swap], [data-sse-swap], [hx-trigger], [data-hx-trigger]") + for (let i = 0; i < childrenToFix.length; i++) { + registerSSE(childrenToFix[i]) + } + // We want to increase the reconnection delay for consecutive failed attempts only + retryCount = 0 + } + } + + api.getInternalData(elt).sseEventSource = source + + + var closeAttribute = api.getAttributeValue(elt, "sse-close"); + if (closeAttribute) { + // close eventsource when this message is received + source.addEventListener(closeAttribute, function() { + api.triggerEvent(elt, 'htmx:sseClose', { + source, + type: 'message', + }) + source.close() + }); + } + } + + /** + * maybeCloseSSESource confirms that the parent element still exists. + * If not, then any associated SSE source is closed and the function returns true. + * + * @param {HTMLElement} elt + * @returns boolean + */ + function maybeCloseSSESource(elt) { + if (!api.bodyContains(elt)) { + var source = api.getInternalData(elt).sseEventSource + if (source != undefined) { + api.triggerEvent(elt, 'htmx:sseClose', { + source, + type: 'nodeMissing', + }) + source.close() + // source = null + return true + } + } + return false + } + + + /** + * @param {HTMLElement} elt + * @param {string} content + */ + function swap(elt, content) { + api.withExtensions(elt, function(extension) { + content = extension.transformResponse(content, null, elt) + }) + + var swapSpec = api.getSwapSpecification(elt) + var target = api.getTarget(elt) + api.swap(target, content, swapSpec) + } + + + function hasEventSource(node) { + return api.getInternalData(node).sseEventSource != null + } +})() diff --git a/internal/web/templates/components.templ b/internal/web/templates/components.templ new file mode 100644 index 0000000..5496b34 --- /dev/null +++ b/internal/web/templates/components.templ @@ -0,0 +1,345 @@ +package templates + +import ( + "strconv" + + "github.com/a-h/templ" + + "gitea.lab.audasmedia.com.au/sam/ai-resume/internal/stage" +) + +// Layout is the whole document. It renders the stage binding it is handed and +// never inspects which driver produced it. +templ Layout(v LayoutView) { + + + + + + { v.Title } + + + + + + if v.Stage.Mode == stage.ModeStream { + + } + + + + @Nav(v.Nav, v.Area) +
+
+ @Breadcrumbs(v.Crumbs) + { children... } +
+ @Stage(StageView{Binding: v.Stage}) +
+ @Footer(v) + + +} + +// Nav is the six-area navigation: a sidebar on desktop, a
disclosure +// below 900 px so it still works with JavaScript disabled. +templ Nav(items []NavItem, current string) { +
+ + SR + + Sam Rolfe + AI · Platform · Edge + + + @SearchForm("", "nav-search") + + +
+} + +templ navLinks(items []NavItem, current string) { + for _, it := range items { + + + { it.Title } + + } +} + +templ evidenceLink(current string) { + + + Evidence index + +} + +// Breadcrumbs shows where the reader is, and is a real link trail. +templ Breadcrumbs(crumbs []Crumb) { + if len(crumbs) > 0 { + + } +} + +// SearchForm is a GET form: it works with JavaScript disabled and is upgraded by +// HTMX when scripts are available. +templ SearchForm(q string, class string) { + +} + +// Stage is the presentation panel. Everything about how it is fed comes from +// the binding: route mode swaps in pre-rendered fragments, stream mode listens +// on an event stream. The markup is identical either way. +templ Stage(v StageView) { + +} + +// FragmentView renders one stage fragment. This is the only place that knows +// what a fragment kind looks like, and it is shared by the route driver (at +// build time) and the stream driver (at request time). +templ FragmentView(f stage.Fragment) { +
+
+

{ f.Kind }

+

{ f.Title }

+ if f.Subtitle != "" { +

{ f.Subtitle }

+ } +
+ switch f.Kind { + case stage.KindText: +
{ f.Body }
+ case stage.KindCode: + if f.Code != nil { +
+
{ f.Code.Label }{ f.Code.Language }
+ @f.Code.HTML +
+ } + case stage.KindDiagram, stage.KindImage: +
+ { + if f.Subtitle != "" { +
{ f.Subtitle }
+ } +
+ case stage.KindVideo: +
+ + if f.Subtitle != "" { +
{ f.Subtitle }
+ } +
+ case stage.KindLinks: + if len(f.Links) > 0 { + + } + } +
+ if f.Confidence != "" { + { f.Confidence } + } + if f.DocURL != "" { + { f.DocTitle } + } +
+
+} + +// EvidenceTable lists artefacts. Rows with HXGet load the artefact into the +// stage panel; every row is also a plain link, so this works with JavaScript +// disabled. +templ EvidenceTable(rows []EvidenceRow) { + + + + + + + + + + for _, r := range rows { + + + + + + } + +
EvidenceKindStatus
+ if r.HXGet != "" { + { r.Label } + } else { + { r.Label } + } + { r.Kind } + if r.Confidence != "" { + { r.Confidence } + } +
+} + +// PillarCard is one landing-page pillar: the claim, the numbers, and the way in. +templ PillarCard(c PillarCardView) { + +} + +// Timeline renders the history area as a timeline. +templ Timeline(items []TimelineItem) { +
    + for _, it := range items { +
  1. +

    { it.Period }

    +
    +

    { it.Title }

    +

    { it.Claim }

    + { it.Confidence } +
    +
  2. + } +
+} + +// CodeBlock renders an already-highlighted code exhibit. +templ CodeBlock(c stage.Code) { +
+
{ c.Label }{ c.Language }
+ { c.HTML } +
+} + +// Footer closes the page with the honesty notes a recruiter needs. +templ Footer(v LayoutView) { +
+ + + +
+} + +func navClass(it NavItem) string { return navClassFor(it.Current) } + +func navClassFor(current bool) string { + if current { + return "nav-link nav-current" + } + return "nav-link" +} + +func currentAttr(it NavItem) string { + if it.Current { + return "page" + } + return "" +} + +func driverLabel(m stage.Mode) string { + if m == stage.ModeStream { + return "stream driver · SSE" + } + return "route driver · pre-rendered" +} diff --git a/internal/web/templates/pages.templ b/internal/web/templates/pages.templ new file mode 100644 index 0000000..180074b --- /dev/null +++ b/internal/web/templates/pages.templ @@ -0,0 +1,258 @@ +package templates + +import ( + "strconv" + + "github.com/a-h/templ" +) + +// HomePage is the landing page: the 90-second read. +templ HomePage(v HomeView) { + @Layout(v.Layout) { +
+

Melbourne · twenty-five years · AI · platform · edge

+

{ v.Positioning }

+

{ v.Support }

+

+ { strconv.Itoa(v.Areas) } areas + { strconv.Itoa(v.Pages) } pages + { strconv.Itoa(v.Artifacts) } linked artefacts + no page needs a model to render +

+ @SearchForm("", "hero-search") +
+ +
+ for _, c := range v.Cards { + @PillarCard(c) + } +
+ +
+

How to read this site

+
    +
  • Level 1 is one screen per area: the claim, the numbers, the way in.
  • +
  • Level 2 is what is actually run, with an evidence table and the trade-offs.
  • +
  • Level 3 is the artefact: code, diagram, screenshot, log.
  • +
  • Every claim carries a status, and finished, running, in-progress and abandoned are all shown as they are.
  • +
  • Every artefact is at most three clicks from here, and the evidence index lists all of them on one page.
  • +
+
+ } +} + +// DocPage renders an L1, L2 or L3 document. +templ DocPage(v DocView) { + @Layout(v.Layout) { +
+
+

{ v.AreaTitle } · { v.LevelLabel }

+

{ v.Doc.Title }

+

{ v.Doc.Claim }

+
+ { v.Doc.Confidence } + if v.Doc.Period != "" { + { v.Doc.Period } + } + for _, m := range v.Metrics { +
  • + { m.Value } + { m.Label } +
  • + } +
    + if len(v.Tech) > 0 { +
      + for _, t := range v.Tech { +
    • { t }
    • + } +
    + } +
    + +
    + @v.Body +
    + + if len(v.Evidence) > 0 { +
    +

    Evidence for this page

    +

    Select a row to load the artefact into the presentation panel. Each row is also a link, so this works without JavaScript.

    + @EvidenceTable(evidenceRows(v.Evidence)) +
    + } + + if len(v.Timeline) > 0 { +
    +

    In time order

    + @Timeline(v.Timeline) +
    + } + + if len(v.SubPages) > 0 { +
    +

    { subHeading(v.Doc.Level) }

    +
      + for _, s := range v.SubPages { +
    • + { s.Label } + { s.Kind } +
    • + } +
    +
    + } + + if len(v.Backlinks) > 0 { +
    +

    Referenced from

    +
      + for _, b := range v.Backlinks { +
    • { b.Label }
    • + } +
    +
    + } + +
    +

    Status { v.Doc.Confidence } — { ConfidenceNote(v.Doc.Confidence) }

    +

    Last verified { v.Doc.LastVerified } · id { v.Doc.ID } · { v.Doc.Path }

    +
    +
    + } +} + +// EvidencePage is one page listing every artefact, grouped by area. It is the +// shortest path from the landing page to any proof. +templ EvidencePage(v EvidenceView) { + @Layout(v.Layout) { +
    +
    +

    Index

    +

    Evidence index

    +

    Every artefact this site claims, on one page. { strconv.Itoa(v.Total) } links, each one a file in the repository.

    +
    + for _, g := range v.Groups { +
    +

    { g.AreaTitle }

    + @EvidenceTable(g.Rows) +
    + } +
    + } +} + +// SearchPage is the keyword search. The results block is swapped by HTMX on the +// same page; with JavaScript off the form simply reloads the page. +templ SearchPage(v SearchView) { + @Layout(v.Layout) { +
    +
    +

    Keyword search

    +

    Search { strconv.Itoa(v.Indexed) } pages

    +

    Full-text search over page titles and body text. Served from a local index — no model, no network call.

    +
    + @SearchForm(v.Query, "page-search") + @SearchResults(v) +
    + } +} + +// SearchResults is swapped into #search-results by HTMX. +templ SearchResults(v SearchView) { +
    + if v.Query == "" { +

    Try “zigbee”, “signage”, “routing”, “backups” or “guardrails”.

    + } else if v.Failed { +

    That query could not be run. Try fewer or simpler words.

    + } else if len(v.Results) == 0 { +

    No page matches { v.Query }. The evidence index lists everything by area.

    + } else { +

    { strconv.Itoa(len(v.Results)) } results for { v.Query }

    +
      + for _, r := range v.Results { +
    1. +

      { r.Title }

      +

      + { r.Area } + L{ strconv.Itoa(r.Level) } + { r.Confidence } +

      +

      { SafeSnippet(r.Snippet) }

      +
    2. + } +
    + } +
    +} + +// StreamPage proves the panel can be re-pointed at a stream. The layout and the +// panel markup are the ones every other page uses; only the binding differs. +templ StreamPage(v StreamView) { + @Layout(v.Layout) { +
    +
    +

    Design note · not a product feature

    +

    The panel takes content from a driver

    +

    This page renders the same layout and the same panel as every other page. Its panel is bound to an event stream instead of pre-rendered files, and no layout code changed.

    +
    +
    +

    The presentation panel is a content sink. In Mode A it takes pre-rendered fragments over + HTMX: you click a row in an evidence table and one file is swapped in. On this page the same + panel is bound to /api/stage/stream and receives { strconv.Itoa(v.Frames) } fragments + over server-sent events, one after another.

    +

    Fragments are pushed, not requested. Nothing about the panel — its markup, its fragment + view, its empty state — knows the difference. That is the point: the Phase 5 console + re-points this panel at retrieval output and the layout does not change.

    +

    This demonstration streams the artefacts already built for the site, with + no model in the loop. It exists to prove the transport, not to pretend an AI is answering.

    +
    + if len(v.Fragment) > 0 { +
    +

    Fragments in this stream

    +
      + for _, f := range v.Fragment { +
    • + { f.Label } + { f.Kind } +
    • + } +
    +
    + } +
    + } +} + +// NotFoundPage is the 404. +templ NotFoundPage(v NotFoundView) { + @Layout(v.Layout) { +
    +
    +

    404

    +

    That page is not here

    +

    The link may be from an older build. The six areas and the evidence index are the reliable ways in.

    +
    + +
    + } +} + +func evidenceRows(links []LinkView) []EvidenceRow { + rows := make([]EvidenceRow, 0, len(links)) + for _, l := range links { + rows = append(rows, EvidenceRow{Label: l.Label, Href: l.Href, HXGet: l.HXGet, Kind: l.Kind, Confidence: l.Confidence}) + } + return rows +} + +func subHeading(level int) string { + if level == 1 { + return "Drill-downs in this area" + } + return "Artefacts behind this page" +} diff --git a/internal/web/templates/view.go b/internal/web/templates/view.go new file mode 100644 index 0000000..b2e163b --- /dev/null +++ b/internal/web/templates/view.go @@ -0,0 +1,223 @@ +// Package templates holds every templ component and the view models they read. +// Layout never branches on the stage driver: it renders the binding it is given. +package templates + +import ( + stdhtml "html" + "strings" + + "github.com/a-h/templ" + + "gitea.lab.audasmedia.com.au/sam/ai-resume/internal/content" + "gitea.lab.audasmedia.com.au/sam/ai-resume/internal/search" + "gitea.lab.audasmedia.com.au/sam/ai-resume/internal/stage" +) + +// NavItem is one left-nav entry. +type NavItem struct { + Title string + Href string + Gutter string + Current bool +} + +// Crumb is one breadcrumb. +type Crumb struct { + Label string + Href string +} + +// LayoutView is everything the chrome needs. +type LayoutView struct { + Title string + Description string + Area string + Nav []NavItem + Crumbs []Crumb + Stage stage.Binding + SearchQuery string + Year int + SkipAI bool // true on Mode A pages, which never need a model +} + +// StageView wraps the binding so the Stage component has one argument. +type StageView struct { + Binding stage.Binding + // Fragment, when set, is rendered into the panel at build time. + Fragment *stage.Fragment +} + +// MetricView is one approved chip. +type MetricView struct { + Label string + Value string +} + +// LinkView is a drill-down link. HXGet makes it a stage trigger; Href keeps it +// a working link when JavaScript is off. +type LinkView struct { + Label string + Href string + HXGet string + Kind string + Note string + Confidence string +} + +// EvidenceRow is one row of an EvidenceTable. +type EvidenceRow struct { + Label string + Href string + HXGet string + Kind string + Confidence string +} + +// EvidenceGroup groups rows by area on the evidence index. +type EvidenceGroup struct { + AreaTitle string + Href string + Rows []EvidenceRow +} + +// TimelineItem is one row of a timeline. +type TimelineItem struct { + Period string + Title string + Href string + Confidence string + Claim string +} + +// PillarCardView is one of the six landing cards. +type PillarCardView struct { + Area content.Area + Title string + Claim string + Href string + Metrics []MetricView + Tech []string + Confidence string + Level int + Pages int +} + +// Layout of each page kind. +type ( + // HomeView is the landing page. + HomeView struct { + Layout LayoutView + Positioning string + Support string + Location string + Cards []PillarCardView + Artifacts int + Pages int + Areas int + } + + // DocView is an L1, L2 or L3 content page. + DocView struct { + Layout LayoutView + Doc *content.Document + AreaTitle string + Role string + Body templ.Component + Metrics []MetricView + Tech []string + Evidence []LinkView + Backlinks []LinkView + SubPages []LinkView + Timeline []TimelineItem + LevelLabel string + } + + // EvidenceView is the index of every artefact. + EvidenceView struct { + Layout LayoutView + Groups []EvidenceGroup + Total int + } + + // SearchView is the keyword search page. + SearchView struct { + Layout LayoutView + Query string + Results []search.Result + Total int + Indexed int + Failed bool + } + + // StreamView is the SSE-driven stage demonstration page. + StreamView struct { + Layout LayoutView + Frames int + Fragment []LinkView + } + + // NotFoundView is the 404 page. + NotFoundView struct { + Layout LayoutView + } +) + +// MarkdownBody wraps pre-rendered Markdown HTML. +func MarkdownBody(html string) templ.Component { return templ.Raw(html) } + +// SafeSnippet escapes a search snippet but keeps the tags the index +// inserted. Content is in-repo and trusted; escaping is defence in depth. +func SafeSnippet(s string) templ.Component { + s = stdhtml.EscapeString(s) + s = strings.ReplaceAll(s, "<mark>", "") + s = strings.ReplaceAll(s, "</mark>", "") + return templ.Raw(s) +} + +// ConfidenceClass maps a confidence value onto a CSS class. The value itself is +// always displayed — never softened. +func ConfidenceClass(c string) string { + switch c { + case content.ConfidenceDelivered: + return "conf conf-delivered" + case content.ConfidenceRunning: + return "conf conf-running" + case content.ConfidenceInProgress: + return "conf conf-in-progress" + case content.ConfidenceAbandoned: + return "conf conf-abandoned" + case content.ConfidenceHistoric: + return "conf conf-historic" + } + return "conf" +} + +// ConfidenceNote is the sentence shown under a status badge. +func ConfidenceNote(c string) string { + switch c { + case content.ConfidenceDelivered: + return "Delivered." + case content.ConfidenceRunning: + return "Running today." + case content.ConfidenceInProgress: + return "In progress — not finished." + case content.ConfidenceAbandoned: + return "Abandoned. Kept in the record deliberately." + case content.ConfidenceHistoric: + return "Historic — worked on, not maintained today." + } + return "" +} + +// LevelLabel names a depth level for the page kicker. +func LevelLabel(level int) string { + switch level { + case 1: + return "Level 1 · capability in one screen" + case 2: + return "Level 2 · what is actually run" + case 3: + return "Level 3 · artefact" + } + return "" +}