diff --git a/AGENTS.md b/AGENTS.md index f7cc49d..a3ed401 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,15 +21,16 @@ thor/ ├── markdown/ # Content transformation pipeline (imports ../treesitter) ├── mustache/ # Template engine with lambdas + pipe filters + diagnostics ├── content.odin # Page struct, Pending_File, scan_content_files, collect_languages, load_page -├── render.odin # Template rendering, data structs, RSS, sitemap -├── site.odin # Config (Flags, Config_File, Site), init_site +├── render.odin # Template rendering, Template_Context, sort_pages, RSS, sitemap +├── menus.odin # Menu_Entry, DEFAULT_WEIGHT, build_menus, collect_auto_menus, merge_page_menus, parse_page_menus, parse_config_menus +├── site.odin # Config (Flags, Config_File, Site, Site_Context), init_site ├── minify.odin # HTML/CSS minification (imports treesitter) ├── feed.odin # RSS + sitemap generation ├── vfs.odin # Union file system (defaults → modules → site) ├── assets.odin # VFS-based asset copying -├── html.odin # HTML helpers: strip_html_tags, unescape_html, generate_summary (word-count truncation), generate_description (scrub to plain text) +├── html.odin # HTML helpers: strip_html_tags, unescape_html, generate_summary, generate_description ├── opengraph.odin # Open_Graph struct + og_for_site/og_for_page -├── frontmatter.odin # JSON frontmatter parser (supports nested og + lastmod) +├── frontmatter.odin # JSON frontmatter parser (supports nested og + lastmod + weight + menus) ├── defaults.odin # DEFAULTS_PATH constant (#directory) ├── main.odin # Entry point ├── bench/ # Template rendering benchmark @@ -41,16 +42,17 @@ thor/ | File | Responsibility | |---|---| | `main.odin` | Entry point. Sets `context.logger`, calls `init_site`, `build_vfs`, wires `treesitter.grammar_dir`/`query_dir` from config, `site_load_content`, `render_site`. Optional Spall profiling via `SPALL` config flag. | -| `site.odin` | `Flags` (CLI), `Config_File` (thor.json, includes `og: Open_Graph`), `Site` (runtime state + arena + VFS + pages + modules + `og`). `Feature` enum. 5-step `init_site`. Imports `md "markdown"` for `Extension` enum. | -| `content.odin` | `Page` struct (includes `lastmod`, `og`), `Pending_File` struct, `scan_content_files` (section-aware walk that handles leaf bundles), `collect_languages` (pre-scan for code fence languages), `load_page`, `infer_layout`. Calls `md.process()` for the markdown pipeline. | -| `render.odin` | Template rendering: `render_site`, `render_page_html`, `render_home_html`, `render_section`. Data structs (`Base_Data`, `Page_Data`, `Home_Data`, `Section_Data`). VFS-based template loading with fallback chain (`get_template`). | +| `site.odin` | `Flags` (CLI), `Config_File` (thor.json), `Site_Context` (template-facing: `title`, `description`, `base_url`, `params`, `og`, `menus`), `Site` (runtime state + arena + VFS + pages + `og`). `Feature` enum. 5-step `init_site`. Config menu parsing in `site_apply_config`. | +| `content.odin` | `Page` struct (includes `weight`, `menus: map[string]Menu_Entry`, `og`), `Pending_File` struct, `scan_content_files` (section-aware walk that handles leaf bundles), `collect_languages` (pre-scan for code fence languages), `load_page` (falls back to file mtime when no frontmatter date), `infer_layout`. Calls `md.process()` for the markdown pipeline. | +| `render.odin` | Template rendering: `render_site`, `render_page_html`, `render_home_html`, `render_section`. `Template_Context` (unified render struct with `site: Site_Context`, `page: Page`, `menus`, `posts`, `pages`). 3-frame context stack via `[]any{ctx.site, ctx.page, ctx}`. `sort_pages` (weight primary, date secondary). `to_title_case` for section display names. VFS-based template loading with fallback chain (`get_template`). | +| `menus.odin` | Menu system: `Menu_Entry {name, url, weight}`, `DEFAULT_WEIGHT = 10`. `build_menus` (priority chain: config → auto + page frontmatter). `collect_auto_menus` (sections + root-level pages). `merge_page_menus` (frontmatter entries with effective weight fallback). `parse_page_menus` (string/array/object forms). `parse_config_menus` (from thor.json). `sort_menu_entries` / `compare_menu_entries` (weight primary, name secondary). | | `minify.odin` | HTML/CSS minification via tree-sitter. Imports `ts "treesitter"`. | | `feed.odin` | RSS feed + sitemap XML. Uses `page.url` for canonical URLs. | | `vfs.odin` | Union file system: `VFS`, `build_vfs`, `mount_dir`, `mount_subdir`, `mount_recursive`, `vfs_get`, `vfs_get_entry`, `vfs_entry_data`. Layers defaults → modules → site. | | `assets.odin` | `copy_assets_dir` — iterates VFS entries with `assets/` prefix, minifies CSS, copies verbatim or via `os.copy_file`. | | `html.odin` | `strip_html_tags`, `unescape_html`, `generate_summary` (word-count truncation, zero-alloc), `generate_description` (HTML→plain text: strip tags, decode entities, collapse whitespace). | -| `opengraph.odin` | `Open_Graph` struct (fields ordered per OGP spec, `is_article: Maybe(bool)`). `og_for_site(site)` for site defaults (from config + derived), `og_for_page(site_og, page)` for page-specific (overlay page.og + derive from page data). | -| `frontmatter.odin` | JSON frontmatter parser (`{ }` delimited). Supports `layout`, `lastmod`, and nested `og` object (via `json_get_open_graph`). | +| `opengraph.odin` | `Open_Graph` struct (fields ordered per OGP spec, `is_article: Maybe(bool)`). `og_for_site(site)` for site defaults (from config + derived), `og_for_page(site_og, page)` for page-specific (overlay page.og + derive from page data). Description falls back to `generate_description(generate_summary(body_html))`. | +| `frontmatter.odin` | JSON frontmatter parser (`{ }` delimited). Supports `layout`, `lastmod`, `weight`, `menus`, and nested `og` object (via `json_get_open_graph`). Helpers: `json_get_string`, `json_get_bool`, `json_get_int`. | | `defaults.odin` | `DEFAULTS_PATH` constant, resolved at compile time via `#directory` so bundled templates ship in the binary. | ### Subpackages @@ -64,6 +66,7 @@ thor/ | | `emoji.odin` | `expand_emoji` — `:shortcode:` → unicode emoji | | | `sectionate.odin` | `wrap_sections` — splits HTML at `

` into `
` wrappers | | | `highlight.odin` | Syntax highlighting via tree-sitter. Imports `../treesitter`. | +| | `heading_ids.odin` | `inject_heading_ids` — adds `id` attributes to `

`-`

` from heading text. Slug-based, deduplicated. | | `mustache/` | See [Mustache engine](#mustache-engine) below | Template engine | | `bench/` | `bench.odin` + `templates/` | Standalone template rendering benchmark. Generates 500 posts + 100 comments, renders with indented partials + inheritance + pipes. `--dump ` for output validation, positional arg for iteration count (default 250). | @@ -74,10 +77,10 @@ Icon SVGs live as HTML partials in `layouts/partials/icons/` (home, github, rss, ``` thor.json → find_config → init_site (5-step) → build_vfs (defaults/layouts → modules → site/layouts, site/assets) - → site_load_content (scan_content_files + collect_languages + preload_grammars + load_page + url computation) + → site_load_content (scan_content_files + collect_languages + preload_grammars + load_page + url computation + build_menus) → render_site → load_partials + get_template (VFS + fallback chain) - → render_page_html / render_home_html / render_section + → render_page_html / render_home_html / render_section (3-frame context stack: site, page, ctx) → optional minify_html → public/ ``` @@ -94,12 +97,14 @@ Page :: struct { title: string, description: string, date: string, + year: string, + weight: int, // page ordering (default DEFAULT_WEIGHT = 10) lastmod: string, - menu: string, - body_html: string, + menus: map[string]Menu_Entry, // frontmatter menu assignments + content: string, // rendered HTML body + og: Open_Graph, draft: bool, - is_starred: bool, - og: Open_Graph, // per-page OG overrides from frontmatter + starred: bool, _is_index: bool `private`, } ``` @@ -113,6 +118,33 @@ No `Page_Type` enum — page type is inferred from section + `_is_index`. Layout **Template fallback chain** (in `get_template`): for content pages, `post → page → base`; for section indexes, `posts_index → section_index → page → base`. Fallbacks logged at debug level. Frontmatter `layout` field overrides the inferred value. +## Menus + +Menu system in `menus.odin`. `Menu_Entry :: struct {name: string, url: string, weight: int}`. `DEFAULT_WEIGHT = 10`. + +### Sources (priority chain, no mixing) + +1. **Config menus** (`"menus"` key in `thor.json`) — exclusive. `"menus": {}` = explicit opt-out (no menus). Config entries sorted by weight. +2. **Auto-menus + page frontmatter** — always run together when no config menus: + - Auto: one entry per section directory + one per root-level non-index page. Alphabetical. + - Page frontmatter: `"menus": "main"` (string), `["main", "footer"]` (array), or `{"main": {"weight": 30}}` (object with per-menu weight). Merged with auto entries, sorted by weight. + +### Weight + +- `Page.weight` — general page ordering (default `DEFAULT_WEIGHT`). Affects `sort_pages` (weight primary, date secondary). +- Per-menu weight — from object frontmatter form. Falls back to `Page.weight` when `DEFAULT_WEIGHT`. +- `Menu_Entry.weight` — effective weight after fallback. Sorted ascending, name alphabetical for ties. + +### Templates + +```html +{{#menus.main}} +
  • {{name}}
  • +{{/menus.main}} +``` + +`Template_Context.menus` resolves above `Page.menus` (frontmatter assignments) on the 3-frame context stack. Accessible as `{{#menus.main}}` or `{{#site.menus.main}}`. + ## Config system Config is split into three structs with a clear 5-step initialization flow: @@ -146,6 +178,12 @@ Config precedence: `CLI flags > thor.json values > hardcoded defaults`. "grammars": "~/.config/helix/runtime/grammars/", "queries": "/path/to/tree-sitter/queries", "markdown_extensions": { "emoji": true, "highlight": false }, + "menus": { + "main": [ + {"name": "Home", "url": "/", "weight": 1}, + {"name": "About", "url": "/about/"} + ] + }, "params": { "social": [ { "name": "github", "url": "...", "icon": "icons/github" } @@ -225,36 +263,26 @@ Templates use Mustache with template inheritance (`{{ (fm: Frontmatter, body: string, ok fm.publishDate = json_get_string(obj, "publishDate") fm.draft = json_get_bool(obj, "draft") fm.isStarred = json_get_bool(obj, "isStarred") - fm.menu = json_get_string(obj, "menu") + if v, ok := obj["menus"]; ok { + fm.menus = v + } fm.layout = json_get_string(obj, "layout") fm.og = json_get_open_graph(obj, "og") @@ -81,6 +83,20 @@ json_get_bool :: proc(obj: json.Object, key: string) -> bool { return false } +json_get_int :: proc(obj: json.Object, key: string) -> int { + if v, ok := obj[key]; ok { + switch val in v { + case json.Integer: + return int(val) + case json.Float: + return int(val) + case json.Boolean, json.String, json.Array, json.Object, json.Null: + return 0 + } + } + return 0 +} + json_get_open_graph :: proc(obj: json.Object, key: string) -> Open_Graph { og: Open_Graph if v, ok := obj[key]; ok { @@ -99,3 +115,4 @@ json_get_open_graph :: proc(obj: json.Object, key: string) -> Open_Graph { } return og } + diff --git a/menus.odin b/menus.odin index dc392e8..fbf625e 100644 --- a/menus.odin +++ b/menus.odin @@ -3,12 +3,111 @@ package main import "core:encoding/json" import "core:fmt" import "core:log" +import "core:mem" import "core:os" import "core:strings" Menu_Entry :: struct { - name: string, - url: string, + name: string, + url: string, + weight: int, +} + +// parse_page_menus converts raw frontmatter JSON into map[string]Menu_Entry. +// Supports three forms: +// "menus": "main" → {main: {name=title, url=permalink, weight=0}} +// "menus": ["main", "footer"] → {main: {...}, footer: {...}} +// "menus": {"main": {"weight": 30}} → {main: {name=title, url=permalink, weight=30}} +parse_page_menus :: proc( + raw: json.Value, + page: Page, + allocator: mem.Allocator, +) -> map[string]Menu_Entry { + result: map[string]Menu_Entry + + if raw == nil { + return nil + } + + switch v in raw { + case json.String: + result = make(map[string]Menu_Entry, allocator) + result[string(v)] = Menu_Entry { + name = page.title, + url = page.permalink, + } + + case json.Array: + result = make(map[string]Menu_Entry, allocator) + for item in v { + if s, ok := item.(json.String); ok { + result[string(s)] = Menu_Entry { + name = page.title, + url = page.permalink, + } + } else { + log.warnf("menus: ignoring non-string item in menus array: %v", item) + } + } + + case json.Object: + result = make(map[string]Menu_Entry, allocator) + for menu_name, entry_val in v { + weight := 0 + if entry_obj, ok := entry_val.(json.Object); ok { + if w, ok := entry_obj["weight"]; ok { + #partial switch wval in w { + case json.Integer: + weight = int(wval) + case json.Float: + weight = int(wval) + case: + log.warnf( + "menus: '%s' entry 'weight' must be a number, got %v", + menu_name, + w, + ) + } + } + if _, has_name := entry_obj["name"]; has_name { + log.warnf( + "menus: '%s' entry 'name' override not yet supported, ignoring", + menu_name, + ) + } + if _, has_url := entry_obj["url"]; has_url { + log.warnf( + "menus: '%s' entry 'url' override not yet supported, ignoring", + menu_name, + ) + } + } else { + log.warnf( + "menus: '%s' entry must be an object, got %v, using defaults", + menu_name, + entry_val, + ) + } + result[menu_name] = Menu_Entry { + name = page.title, + url = page.permalink, + weight = weight, + } + } + + case json.Null: + return nil + + case json.Integer, json.Float, json.Boolean: + log.warnf("menus: expected string, array, or object, got %v", raw) + return nil + } + + if page.title == "" { + log.warnf("menus: page '%s' has no title, menu entry will be blank", page.permalink) + } + + return result } // build_menus populates site.menus: @@ -21,7 +120,7 @@ build_menus :: proc(site: ^Site) { if site.menus != nil { has_menus := false for page in site.pages { - if page.menu != "" { + if len(page.menus) > 0 { has_menus = true break } @@ -50,22 +149,21 @@ build_menus :: proc(site: ^Site) { merge_page_menus(site) } -// merge_page_menus collects frontmatter "menu" entries from pages and merges +// merge_page_menus collects frontmatter menu entries from pages and merges // them into site.menus (which may already contain auto-generated entries). -// If no pages have "menu" set, this is a no-op. +// If no pages have menus set, this is a no-op. merge_page_menus :: proc(site: ^Site) { alloc := site_allocator(site) // Collect page entries by menu name page_entries := make(map[string][dynamic]Menu_Entry, 16, alloc) for page in site.pages { - if page.menu == "" { - continue + for menu_name, entry in page.menus { + if _, ok := page_entries[menu_name]; !ok { + page_entries[menu_name] = make([dynamic]Menu_Entry, 0, 4, alloc) + } + append(&page_entries[menu_name], entry) } - if _, ok := page_entries[page.menu]; !ok { - page_entries[page.menu] = make([dynamic]Menu_Entry, 0, 4, alloc) - } - append(&page_entries[page.menu], Menu_Entry{name = page.title, url = page.permalink}) } if len(page_entries) == 0 { @@ -221,3 +319,4 @@ parse_config_menus :: proc( return result } + diff --git a/menus_test.odin b/menus_test.odin new file mode 100644 index 0000000..6c077c6 --- /dev/null +++ b/menus_test.odin @@ -0,0 +1,201 @@ +#+test +package main + +import "core:encoding/json" +import "core:log" +import "core:mem" +import "core:testing" + +make_page :: proc(title: string, permalink: string) -> Page { + return Page{title = title, permalink = permalink} +} + +parse_raw :: proc(s: string) -> json.Value { + v, _ := json.parse_string(s, spec = .JSON) + return v +} + + + +@(test) +test_menus_string_form :: proc(t: ^testing.T) { + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("About", "/about/") + menus := parse_page_menus(parse_raw(`"main"`), page, context.allocator) + testing.expect(t, len(menus) == 1, "expected 1 menu") + entry, ok := menus["main"] + testing.expect(t, ok, "expected 'main' menu") + testing.expect_value(t, entry.name, "About") + testing.expect_value(t, entry.url, "/about/") + testing.expect_value(t, entry.weight, 0) +} + +@(test) +test_menus_array_form :: proc(t: ^testing.T) { + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("Contact", "/contact/") + menus := parse_page_menus(parse_raw(`["main", "footer"]`), page, context.allocator) + testing.expect(t, len(menus) == 2, "expected 2 menus") + + main, ok1 := menus["main"] + testing.expect(t, ok1) + testing.expect_value(t, main.name, "Contact") + + footer, ok2 := menus["footer"] + testing.expect(t, ok2) + testing.expect_value(t, footer.name, "Contact") +} + +@(test) +test_menus_object_with_weight :: proc(t: ^testing.T) { + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("Posts", "/posts/") + menus := parse_page_menus(parse_raw(`{"main": {"weight": 30}}`), page, context.allocator) + testing.expect(t, len(menus) == 1) + entry, ok := menus["main"] + testing.expect(t, ok) + testing.expect_value(t, entry.weight, 30) + testing.expect_value(t, entry.name, "Posts") +} + +@(test) +test_menus_object_no_weight :: proc(t: ^testing.T) { + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("About", "/about/") + menus := parse_page_menus(parse_raw(`{"main": {}}`), page, context.allocator) + testing.expect(t, len(menus) == 1) + entry, ok := menus["main"] + testing.expect(t, ok) + testing.expect_value(t, entry.weight, 0) +} + +@(test) +test_menus_nil_input :: proc(t: ^testing.T) { + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("Test", "/test/") + menus := parse_page_menus(nil, page, context.allocator) + testing.expect(t, menus == nil, "nil input should return nil") +} + +@(test) +test_menus_invalid_type :: proc(t: ^testing.T) { + context.logger = log.nil_logger() + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("Test", "/test/") + menus := parse_page_menus(parse_raw(`42`), page, context.allocator) + testing.expect(t, menus == nil, "integer should return nil") +} + +@(test) +test_menus_array_non_string :: proc(t: ^testing.T) { + context.logger = log.nil_logger() + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("Test", "/test/") + menus := parse_page_menus(parse_raw(`["main", 42, "footer"]`), page, context.allocator) + testing.expect(t, len(menus) == 2, "42 should be dropped") + _, ok1 := menus["main"] + testing.expect(t, ok1) + _, ok2 := menus["footer"] + testing.expect(t, ok2) +} + +@(test) +test_menus_object_non_object_value :: proc(t: ^testing.T) { + context.logger = log.nil_logger() + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("Test", "/test/") + menus := parse_page_menus(parse_raw(`{"main": "oops"}`), page, context.allocator) + testing.expect(t, len(menus) == 1, "entry created with defaults") + entry, ok := menus["main"] + testing.expect(t, ok) + testing.expect_value(t, entry.weight, 0) +} + +@(test) +test_menus_non_numeric_weight :: proc(t: ^testing.T) { + context.logger = log.nil_logger() + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("Test", "/test/") + menus := parse_page_menus(parse_raw(`{"main": {"weight": "30"}}`), page, context.allocator) + entry, ok := menus["main"] + testing.expect(t, ok) + testing.expect_value(t, entry.weight, 0) +} + +@(test) +test_menus_empty_title :: proc(t: ^testing.T) { + context.logger = log.nil_logger() + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("", "/test/") + menus := parse_page_menus(parse_raw(`"main"`), page, context.allocator) + testing.expect(t, len(menus) == 1) + entry, ok := menus["main"] + testing.expect(t, ok) + testing.expect_value(t, entry.name, "") +} + +@(test) +test_menus_object_with_float_weight :: proc(t: ^testing.T) { + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("Test", "/test/") + menus := parse_page_menus(parse_raw(`{"main": {"weight": 15.0}}`), page, context.allocator) + entry, ok := menus["main"] + testing.expect(t, ok) + testing.expect_value(t, entry.weight, 15) +} + +@(test) +test_menus_null_json :: proc(t: ^testing.T) { + arena: mem.Dynamic_Arena + mem.dynamic_arena_init(&arena) + defer mem.dynamic_arena_destroy(&arena) + context.allocator = mem.dynamic_arena_allocator(&arena) + + page := make_page("Test", "/test/") + menus := parse_page_menus(parse_raw(`null`), page, context.allocator) + testing.expect(t, menus == nil, "null JSON should return nil") +} diff --git a/render.odin b/render.odin index 0a96e01..b87c125 100644 --- a/render.odin +++ b/render.odin @@ -16,6 +16,7 @@ Template_Context :: struct { timezone: ^datetime.TZ_Region, og: Open_Graph, site: Site_Context, + menus: map[string][]Menu_Entry, page: Page, // Home data @@ -151,6 +152,7 @@ render_site :: proc(site: ^Site) { ctx := Template_Context { site = site.site_context, + menus = site.menus, now = now, og = site.og, date_format = site.date.format,