Skip to main content

arks_server/web/ui/
shell.rs

1//! Unified strict-CSP document shell (`PageShell`) shared across single-repo,
2//! multi-repo root dashboard, minimal auth pages, and `v2.0` Kinetic extensions.
3//!
4//! Automatically emits `<meta name="arks-mount">` and `<meta name="arks-csrf">`,
5//! renders authenticated session controls natively (eliminating post-render HTML
6//! string replacement), and switches cleanly to fragment responses on HTMX partial requests.
7
8use crate::http::HttpResponse;
9use crate::web::core::ctx::UiCtx;
10use crate::web::core::html::{Attr, HtmlBuf, Render, TrustedHtml};
11use crate::web::core::route::AppRoute;
12use crate::web::ui::components::{Badge, BadgeTone, Form};
13use crate::web::ui::icons::{Icon, IconSize, icon_sized};
14
15/// Strict CSP header enforced on every Web UI HTML response (zero inline style/script).
16pub const STRICT_WEB_UI_CSP: &str = crate::web::core::headers::WEB_UI_CSP;
17
18/// Standard forge navigation tab identifiers (plus `Custom` for `v2.0` tabs like `Graph`/`Stacks`).
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum RepoTab {
21    Code,
22    Issues,
23    Pulls,
24    Actions,
25    Projects,
26    Wiki,
27    Security,
28    Insights,
29    Settings,
30    Custom(&'static str),
31}
32
33impl RepoTab {
34    pub(crate) fn from_legacy(tab: crate::web_ui::ActiveTab) -> Self {
35        match tab {
36            crate::web_ui::ActiveTab::Code => Self::Code,
37            crate::web_ui::ActiveTab::Issues => Self::Issues,
38            crate::web_ui::ActiveTab::Pulls => Self::Pulls,
39            crate::web_ui::ActiveTab::Actions => Self::Actions,
40            crate::web_ui::ActiveTab::Projects => Self::Projects,
41            crate::web_ui::ActiveTab::Wiki => Self::Wiki,
42            crate::web_ui::ActiveTab::Security => Self::Security,
43            crate::web_ui::ActiveTab::Insights => Self::Insights,
44            crate::web_ui::ActiveTab::Settings => Self::Settings,
45        }
46    }
47}
48
49/// View-model projection for the repository chrome header (decoupled from legacy `web_ui`).
50#[derive(Debug, Clone)]
51pub struct RepoHeaderView<'a> {
52    pub name: &'a str,
53    pub description: &'a str,
54    pub default_branch: &'a str,
55    pub branch_count: usize,
56    pub tag_count: usize,
57    pub open_pr_count: usize,
58    pub clone_url: &'a str,
59}
60
61impl<'a> RepoHeaderView<'a> {
62    pub(crate) fn from_legacy(ctx: &'a crate::web_ui::RepoContext) -> Self {
63        let open_pr_count = ctx
64            .branches
65            .iter()
66            .filter(|(b, _)| b != &ctx.default_branch)
67            .count();
68        Self {
69            name: &ctx.name,
70            description: &ctx.description,
71            default_branch: &ctx.default_branch,
72            branch_count: ctx.branches.len(),
73            tag_count: ctx.tags.len(),
74            open_pr_count,
75            clone_url: &ctx.clone_url,
76        }
77    }
78}
79
80/// Additional navigation tab (used by `v2.0` extensions such as `Kinetic`).
81#[derive(Debug, Clone, Copy)]
82pub struct NavTab<'a> {
83    pub label: &'a str,
84    pub href: &'a str,
85    pub active: bool,
86    pub counter: Option<usize>,
87    pub icon: Option<Icon>,
88}
89
90/// Top-level layout chrome variant rendered by [`respond_page`].
91pub enum ShellKind<'a> {
92    /// Repository forge chrome (topbar, clone popover, 9 standard tabs + optional `extra_tabs`).
93    Repo {
94        header: RepoHeaderView<'a>,
95        tab: RepoTab,
96        extra_tabs: &'a [NavTab<'a>],
97    },
98    /// Multi-repo server dashboard chrome (`arks serve --root`).
99    MultiRepoRoot { repo_count: Option<usize> },
100    /// Minimal centered authentication shell (`/login`, `/register`).
101    MinimalAuth,
102}
103
104/// Typed page descriptor rendered into a full document or HTMX partial.
105pub struct Page<'a, M: Render> {
106    pub status: u16,
107    pub title: &'a str,
108    pub description: &'a str,
109    pub shell: ShellKind<'a>,
110    pub main: M,
111    pub extra_css: &'a [&'a str],
112    pub extra_js: &'a [&'a str],
113}
114
115/// Build an HTML [`HttpResponse`] with mandatory strict CSP and security headers.
116pub fn respond_html(status: u16, html: String) -> HttpResponse {
117    HttpResponse {
118        status,
119        content_type: "text/html; charset=utf-8".into(),
120        body: html.into_bytes(),
121        www_authenticate: None,
122        extra_headers: crate::web::core::headers::html_security_headers(false),
123    }
124}
125
126/// Build an HTML partial fragment [`HttpResponse`] for HTMX swap targets.
127pub fn respond_partial(status: u16, fragment: impl Render) -> HttpResponse {
128    let mut buf = HtmlBuf::with_capacity(512);
129    fragment.render_to(&mut buf);
130    HttpResponse {
131        status,
132        content_type: "text/html; charset=utf-8".into(),
133        body: buf.finish().into_bytes(),
134        www_authenticate: None,
135        extra_headers: crate::web::core::headers::html_security_headers(false),
136    }
137}
138
139/// Render [`Page`] as either an HTMX main-content partial or a full strict-CSP HTML5 document.
140pub fn respond_page<C: UiCtx + ?Sized, M: Render>(ctx: &C, page: Page<'_, M>) -> HttpResponse {
141    let mut resp = if ctx.htmx().wants_main_partial() {
142        respond_partial(page.status, |b: &mut HtmlBuf| {
143            b.el("div", &[Attr::Id("main-content")], |m: &mut HtmlBuf| {
144                page.main.render_to(m);
145            });
146        })
147    } else {
148        let mut out = HtmlBuf::with_capacity(4096);
149        out.raw_trusted(TrustedHtml::from_static("<!doctype html>\n"));
150        out.el(
151            "html",
152            &[Attr::Lang("en"), Attr::Data("theme", "dark")],
153            |doc: &mut HtmlBuf| {
154                render_head(ctx, &page, doc);
155                render_body(ctx, &page, doc);
156            },
157        );
158        respond_html(page.status, out.finish())
159    };
160    resp.extra_headers
161        .extend(crate::web::core::headers::html_cache_headers(
162            ctx.session().is_some(),
163        ));
164    resp
165}
166
167fn render_head<C: UiCtx + ?Sized, M: Render>(ctx: &C, page: &Page<'_, M>, out: &mut HtmlBuf) {
168    out.el("head", &[], |h: &mut HtmlBuf| {
169        h.void_el("meta", &[Attr::Charset("utf-8")]);
170        h.void_el(
171            "meta",
172            &[
173                Attr::Name("viewport"),
174                Attr::Content("width=device-width,initial-scale=1"),
175            ],
176        );
177        h.void_el(
178            "meta",
179            &[Attr::Name("color-scheme"), Attr::Content("light dark")],
180        );
181        h.void_el(
182            "meta",
183            &[Attr::Name("theme-color"), Attr::Content("#0a0a0a")],
184        );
185        // Synchronous external FOUC-free theme initializer (CSP script-src 'self', W-5).
186        let theme_init_src = crate::web::core::assets::core_asset_url("/assets/theme-init.js");
187        h.el("script", &[Attr::Src(theme_init_src)], ());
188        h.el("title", &[], page.title);
189        if !page.description.is_empty() {
190            h.void_el(
191                "meta",
192                &[Attr::Name("description"), Attr::Content(page.description)],
193            );
194        }
195        h.void_el(
196            "meta",
197            &[Attr::Property("og:title"), Attr::Content(page.title)],
198        );
199        if !page.description.is_empty() {
200            h.void_el(
201                "meta",
202                &[
203                    Attr::Property("og:description"),
204                    Attr::Content(page.description),
205                ],
206            );
207        }
208        // Client-side progressive enhancement reads mount prefix and CSRF token from meta tags.
209        h.void_el(
210            "meta",
211            &[
212                Attr::Name("arks-mount"),
213                Attr::Content(ctx.mount().as_str()),
214            ],
215        );
216        h.void_el(
217            "meta",
218            &[
219                Attr::Name("htmx-config"),
220                Attr::Content(r#"{"includeIndicatorStyles":false}"#),
221            ],
222        );
223        if let Some(tok) = ctx.csrf_token() {
224            h.void_el("meta", &[Attr::Name("arks-csrf"), Attr::Content(tok)]);
225        }
226        if crate::web::core::pwa::pwa_enabled() {
227            h.void_el(
228                "link",
229                &[Attr::Rel("manifest"), Attr::Href("/manifest.webmanifest")],
230            );
231        }
232        if matches!(page.shell, ShellKind::Repo { .. }) {
233            let atom_href = ctx.path("/commits.atom");
234            h.void_el(
235                "link",
236                &[
237                    Attr::Rel("alternate"),
238                    Attr::Type("application/atom+xml"),
239                    Attr::Title("Commits"),
240                    Attr::Href(&atom_href),
241                ],
242            );
243        }
244        let favicon_href = crate::web::core::assets::core_asset_url("/favicon.svg");
245        let diff_css_href = crate::web::core::assets::core_asset_url("/assets/diff2html.min.css");
246        let style_href = crate::web::core::assets::core_asset_url("/style.css");
247        let htmx_src = crate::web::core::assets::core_asset_url("/assets/htmx.min.js");
248        let diff_js_src = crate::web::core::assets::core_asset_url("/assets/diff2html.min.js");
249        let app_js_src = crate::web::core::assets::core_asset_url("/assets/app.js");
250
251        h.void_el(
252            "link",
253            &[
254                Attr::Rel("icon"),
255                Attr::Type("image/svg+xml"),
256                Attr::Href(favicon_href),
257            ],
258        );
259        h.void_el(
260            "link",
261            &[Attr::Rel("stylesheet"), Attr::Href(diff_css_href)],
262        );
263        h.void_el("link", &[Attr::Rel("stylesheet"), Attr::Href(style_href)]);
264        for css in page.extra_css {
265            h.void_el("link", &[Attr::Rel("stylesheet"), Attr::Href(css)]);
266        }
267        h.el("script", &[Attr::Src(htmx_src), Attr::Defer], ());
268        h.el("script", &[Attr::Src(diff_js_src), Attr::Defer], ());
269        h.el("script", &[Attr::Src(app_js_src), Attr::Defer], ());
270        for js in page.extra_js {
271            h.el("script", &[Attr::Src(js), Attr::Defer], ());
272        }
273    });
274}
275
276fn render_body<C: UiCtx + ?Sized, M: Render>(ctx: &C, page: &Page<'_, M>, out: &mut HtmlBuf) {
277    out.el("body", &[Attr::Hx("boost", "true")], |b: &mut HtmlBuf| {
278        // WCAG 2.4.1 bypass block skip link.
279        b.el(
280            "a",
281            &[Attr::Class("skip-link"), Attr::Href("#main-content")],
282            "Skip to main content",
283        );
284        match &page.shell {
285            ShellKind::Repo {
286                header,
287                tab,
288                extra_tabs,
289            } => {
290                render_repo_header(ctx, header, *tab, extra_tabs, b);
291                b.el("main", &[Attr::Id("main-content")], |m: &mut HtmlBuf| {
292                    page.main.render_to(m);
293                });
294                render_cmd_modal(ctx, header, b);
295            }
296            ShellKind::MultiRepoRoot { repo_count } => {
297                render_root_header(ctx, *repo_count, b);
298                b.el(
299                    "main",
300                    &[Attr::Id("main-content"), Attr::Class("mr-main")],
301                    |m: &mut HtmlBuf| page.main.render_to(m),
302                );
303            }
304            ShellKind::MinimalAuth => {
305                b.el(
306                    "main",
307                    &[Attr::Id("main-content"), Attr::Class("mr-auth-main")],
308                    |m: &mut HtmlBuf| page.main.render_to(m),
309                );
310            }
311        }
312        // WCAG 4.1.3 status live region for client-side toasts and copy feedback.
313        b.el(
314            "div",
315            &[
316                Attr::Id("arks-toast"),
317                Attr::Class("toast-region"),
318                Attr::Role("status"),
319                Attr::Aria("live", "polite"),
320                Attr::Aria("atomic", "true"),
321            ],
322            (),
323        );
324    });
325}
326
327fn render_auth_controls<C: UiCtx + ?Sized>(ctx: &C, out: &mut HtmlBuf) {
328    if let Some(session) = ctx.session() {
329        let handle = format!("@{}", session.username);
330        Badge::new(&handle, BadgeTone::Green).render_to(out);
331        let logout_action = ctx.url(AppRoute::Logout);
332        Form::post(ctx, &logout_action, "u-inline-form", |f: &mut HtmlBuf| {
333            f.el(
334                "button",
335                &[Attr::Class("btn"), Attr::Type("submit")],
336                |btn: &mut HtmlBuf| {
337                    icon_sized(Icon::LogOut, IconSize::Sm).render_to(btn);
338                    btn.text("Sign out");
339                },
340            );
341        })
342        .render_to(out);
343    } else {
344        let login_href = ctx.url(AppRoute::Login);
345        out.el(
346            "a",
347            &[Attr::Class("btn"), Attr::Href(&login_href)],
348            |a: &mut HtmlBuf| {
349                icon_sized(Icon::User, IconSize::Sm).render_to(a);
350                a.text("Sign in");
351            },
352        );
353    }
354}
355
356fn render_repo_header<C: UiCtx + ?Sized>(
357    ctx: &C,
358    header: &RepoHeaderView<'_>,
359    active_tab: RepoTab,
360    extra_tabs: &[NavTab<'_>],
361    out: &mut HtmlBuf,
362) {
363    let arks_clone = format!("arks clone {}", header.clone_url);
364    let git_clone = format!("git clone {}", header.clone_url);
365    let home_href = ctx.url(AppRoute::Home);
366    let notif_href = ctx.url(AppRoute::Notifications);
367    let rel_href = ctx.url(AppRoute::Releases);
368
369    out.el("header", &[Attr::Class("topbar")], |h: &mut HtmlBuf| {
370        h.el(
371            "div",
372            &[Attr::Class("topbar-inner")],
373            |inner: &mut HtmlBuf| {
374                inner.el("div", &[Attr::Class("repo-head")], |rh: &mut HtmlBuf| {
375                    rh.el("div", &[Attr::Class("repo-title")], |rt: &mut HtmlBuf| {
376                        rt.el(
377                            "a",
378                            &[
379                                Attr::Class("brand-mark"),
380                                Attr::Href("/"),
381                                Attr::Aria("label", "arks home"),
382                            ],
383                            |bm: &mut HtmlBuf| {
384                                icon_sized(Icon::Arks, IconSize::Brand).render_to(bm);
385                                bm.el("span", &[], "arks");
386                            },
387                        );
388                        rt.el(
389                            "span",
390                            &[Attr::Class("brand-sep"), Attr::Aria("hidden", "true")],
391                            "/",
392                        );
393                        rt.el("a", &[Attr::Href(&home_href)], header.name);
394                    });
395                    rh.el("div", &[Attr::Class("head-actions")], |ha: &mut HtmlBuf| {
396                        ha.el(
397                            "button",
398                            &[
399                                Attr::Type("button"),
400                                Attr::Class("btn"),
401                                Attr::Data("action", "open-cmd"),
402                                Attr::Aria("label", "Open command palette"),
403                            ],
404                            |btn: &mut HtmlBuf| {
405                                icon_sized(Icon::Search, IconSize::Sm).render_to(btn);
406                                btn.text("Search");
407                            },
408                        );
409                        ha.el(
410                            "a",
411                            &[
412                                Attr::Class("btn"),
413                                Attr::Href(&notif_href),
414                                Attr::Aria("label", "Notifications"),
415                            ],
416                            |a: &mut HtmlBuf| {
417                                icon_sized(Icon::Bell, IconSize::Sm).render_to(a);
418                                a.text("Notifications");
419                            },
420                        );
421                        ha.el(
422                            "a",
423                            &[Attr::Class("btn"), Attr::Href(&rel_href)],
424                            |a: &mut HtmlBuf| {
425                                icon_sized(Icon::Tag, IconSize::Sm).render_to(a);
426                                a.text("Releases");
427                            },
428                        );
429                        render_auth_controls(ctx, ha);
430                        ha.el("details", &[Attr::Class("popover")], |pop: &mut HtmlBuf| {
431                            pop.el(
432                                "summary",
433                                &[Attr::Class("btn btn-primary")],
434                                |s: &mut HtmlBuf| {
435                                    icon_sized(Icon::Code, IconSize::Sm).render_to(s);
436                                    s.text("Code");
437                                    icon_sized(Icon::ChevronDown, IconSize::Xs).render_to(s);
438                                },
439                            );
440                            pop.el(
441                                "div",
442                                &[Attr::Class("popover-panel right")],
443                                |panel: &mut HtmlBuf| {
444                                    panel.el(
445                                        "div",
446                                        &[Attr::Class("popover-head")],
447                                        "Clone repository",
448                                    );
449                                    panel.el(
450                                        "div",
451                                        &[Attr::Class("u-stack u-gap-2 u-pad-sm")],
452                                        |box_el: &mut HtmlBuf| {
453                                            box_el.el(
454                                                "div",
455                                                &[Attr::Class("btn-group")],
456                                                |bg: &mut HtmlBuf| {
457                                                    bg.el(
458                                                        "button",
459                                                        &[
460                                                            Attr::Type("button"),
461                                                            Attr::Class("btn active"),
462                                                            Attr::Data("clone-cmd", &arks_clone),
463                                                        ],
464                                                        "arks",
465                                                    );
466                                                    bg.el(
467                                                        "button",
468                                                        &[
469                                                            Attr::Type("button"),
470                                                            Attr::Class("btn"),
471                                                            Attr::Data("clone-cmd", &git_clone),
472                                                        ],
473                                                        "git",
474                                                    );
475                                                },
476                                            );
477                                            box_el.el(
478                                                "div",
479                                                &[Attr::Class("u-flex u-gap-1 u-items-center")],
480                                                |row: &mut HtmlBuf| {
481                                                    row.el(
482                                                        "code",
483                                                        &[
484                                                            Attr::Id("clone-cmd-text"),
485                                                            Attr::Class("input u-grow u-truncate"),
486                                                        ],
487                                                        &arks_clone,
488                                                    );
489                                                    row.el(
490                                                        "button",
491                                                        &[
492                                                            Attr::Type("button"),
493                                                            Attr::Class("btn"),
494                                                            Attr::Data(
495                                                                "copy-target",
496                                                                "clone-cmd-text",
497                                                            ),
498                                                        ],
499                                                        |btn: &mut HtmlBuf| {
500                                                            icon_sized(Icon::Copy, IconSize::Sm)
501                                                                .render_to(btn);
502                                                            btn.text("Copy");
503                                                        },
504                                                    );
505                                                },
506                                            );
507                                        },
508                                    );
509                                },
510                            );
511                        });
512                        ha.el(
513                            "button",
514                            &[
515                                Attr::Type("button"),
516                                Attr::Class("btn"),
517                                Attr::Data("action", "toggle-theme"),
518                                Attr::Aria("label", "Toggle color theme"),
519                            ],
520                            |btn: &mut HtmlBuf| {
521                                icon_sized(Icon::Sun, IconSize::Sm).render_to(btn);
522                                btn.text("Theme");
523                            },
524                        );
525                    });
526                });
527
528                let tabs: [(RepoTab, Icon, &str, String, Option<usize>); 9] = [
529                    (
530                        RepoTab::Code,
531                        Icon::Code,
532                        "Code",
533                        ctx.url(AppRoute::Home),
534                        None,
535                    ),
536                    (
537                        RepoTab::Issues,
538                        Icon::CircleDot,
539                        "Issues",
540                        ctx.url(AppRoute::Issues {
541                            state: None,
542                            label: None,
543                        }),
544                        None,
545                    ),
546                    (
547                        RepoTab::Pulls,
548                        Icon::GitPullRequest,
549                        "Pull Requests",
550                        ctx.url(AppRoute::Pulls),
551                        Some(header.open_pr_count),
552                    ),
553                    (
554                        RepoTab::Actions,
555                        Icon::CirclePlay,
556                        "Actions",
557                        ctx.url(AppRoute::Actions),
558                        None,
559                    ),
560                    (
561                        RepoTab::Projects,
562                        Icon::SquareKanban,
563                        "Projects",
564                        ctx.url(AppRoute::Projects),
565                        None,
566                    ),
567                    (
568                        RepoTab::Wiki,
569                        Icon::BookOpen,
570                        "Wiki",
571                        ctx.url(AppRoute::Wiki { slug: None }),
572                        None,
573                    ),
574                    (
575                        RepoTab::Security,
576                        Icon::Shield,
577                        "Security",
578                        ctx.url(AppRoute::Security),
579                        None,
580                    ),
581                    (
582                        RepoTab::Insights,
583                        Icon::ChartColumn,
584                        "Insights",
585                        ctx.url(AppRoute::Insights),
586                        None,
587                    ),
588                    (
589                        RepoTab::Settings,
590                        Icon::Settings,
591                        "Settings",
592                        ctx.url(AppRoute::Settings { section: None }),
593                        None,
594                    ),
595                ];
596                inner.el(
597                    "nav",
598                    &[
599                        Attr::Class("tabs"),
600                        Attr::Aria("label", "Repository navigation"),
601                    ],
602                    |nav: &mut HtmlBuf| {
603                        for (tab_id, tab_icon, label, href, count) in &tabs {
604                            let is_active = *tab_id == active_tab;
605                            let cls = if is_active { "tab active" } else { "tab" };
606                            let mut attrs: Vec<Attr<'_>> = vec![Attr::Class(cls), Attr::Href(href)];
607                            if is_active {
608                                attrs.push(Attr::Aria("current", "page"));
609                            }
610                            nav.el("a", &attrs, |a: &mut HtmlBuf| {
611                                icon_sized(*tab_icon, IconSize::Md).render_to(a);
612                                a.text(label);
613                                if let Some(n) = count {
614                                    a.text(" ");
615                                    a.el("span", &[Attr::Class("counter")], *n);
616                                }
617                            });
618                        }
619                        for ext in extra_tabs {
620                            let cls = if ext.active {
621                                "tab tab-kinetic active"
622                            } else {
623                                "tab tab-kinetic"
624                            };
625                            let mut attrs: Vec<Attr<'_>> =
626                                vec![Attr::Class(cls), Attr::Href(ext.href)];
627                            if ext.active {
628                                attrs.push(Attr::Aria("current", "page"));
629                            }
630                            nav.el("a", &attrs, |a: &mut HtmlBuf| {
631                                if let Some(ic) = ext.icon {
632                                    icon_sized(ic, IconSize::Md).render_to(a);
633                                }
634                                a.text(ext.label);
635                                if let Some(n) = ext.counter {
636                                    a.text(" ");
637                                    a.el("span", &[Attr::Class("counter")], n);
638                                }
639                            });
640                        }
641                    },
642                );
643            },
644        );
645    });
646}
647
648fn render_root_header<C: UiCtx + ?Sized>(ctx: &C, repo_count: Option<usize>, out: &mut HtmlBuf) {
649    let search_href = ctx.url(AppRoute::Search);
650    let reg_href = ctx.url(AppRoute::Register);
651    out.el("header", &[Attr::Class("mr-header")], |h: &mut HtmlBuf| {
652        h.el(
653            "div",
654            &[Attr::Class("mr-header-inner")],
655            |inner: &mut HtmlBuf| {
656                inner.el("div", &[Attr::Class("mr-brand")], |brand: &mut HtmlBuf| {
657                    brand.el(
658                        "a",
659                        &[Attr::Class("brand-mark"), Attr::Href("/")],
660                        |a: &mut HtmlBuf| {
661                            icon_sized(Icon::Arks, IconSize::Brand).render_to(a);
662                            a.el("strong", &[], "arks");
663                        },
664                    );
665                    if let Some(count) = repo_count {
666                        let label = format!("{count} repos");
667                        Badge::new(&label, BadgeTone::Green).render_to(brand);
668                    }
669                    brand.el(
670                        "a",
671                        &[Attr::Class("muted"), Attr::Href(&search_href)],
672                        "Search",
673                    );
674                    brand.el(
675                        "a",
676                        &[Attr::Class("muted"), Attr::Href("/healthz")],
677                        "Health",
678                    );
679                });
680                Form::get(&search_href, "mr-search-form", |f: &mut HtmlBuf| {
681                    f.el(
682                        "label",
683                        &[Attr::For("mr-search-q"), Attr::Class("sr-only")],
684                        "Search across repositories",
685                    );
686                    f.void_el(
687                        "input",
688                        &[
689                            Attr::Id("mr-search-q"),
690                            Attr::Type("search"),
691                            Attr::Name("q"),
692                            Attr::Class("input"),
693                            Attr::Placeholder("Search across repos..."),
694                        ],
695                    );
696                    f.el(
697                        "button",
698                        &[Attr::Class("btn"), Attr::Type("submit")],
699                        |btn: &mut HtmlBuf| {
700                            icon_sized(Icon::Search, IconSize::Sm).render_to(btn);
701                            btn.text("Search");
702                        },
703                    );
704                })
705                .render_to(inner);
706                inner.el(
707                    "div",
708                    &[Attr::Class("mr-auth-actions")],
709                    |auth: &mut HtmlBuf| {
710                        render_auth_controls(ctx, auth);
711                        if ctx.session().is_none() {
712                            auth.el(
713                                "a",
714                                &[Attr::Class("btn"), Attr::Href(&reg_href)],
715                                "Register",
716                            );
717                        }
718                        auth.el(
719                            "button",
720                            &[
721                                Attr::Type("button"),
722                                Attr::Class("btn"),
723                                Attr::Data("action", "toggle-theme"),
724                                Attr::Aria("label", "Toggle color theme"),
725                            ],
726                            |btn: &mut HtmlBuf| {
727                                icon_sized(Icon::Sun, IconSize::Sm).render_to(btn);
728                                btn.text("Theme");
729                            },
730                        );
731                    },
732                );
733            },
734        );
735    });
736}
737
738fn render_cmd_modal<C: UiCtx + ?Sized>(ctx: &C, header: &RepoHeaderView<'_>, out: &mut HtmlBuf) {
739    let commits_href = ctx.url(AppRoute::Commits {
740        rev: Some(header.default_branch),
741    });
742    let items: Vec<(&str, String, String)> = vec![
743        ("Code & File Tree", ctx.url(AppRoute::Home), "/".into()),
744        ("Commits History", commits_href, "/commits".into()),
745        (
746            "Branches",
747            ctx.url(AppRoute::Branches),
748            header.branch_count.to_string(),
749        ),
750        (
751            "Tags",
752            ctx.url(AppRoute::Tags),
753            header.tag_count.to_string(),
754        ),
755        (
756            "Releases & Assets",
757            ctx.url(AppRoute::Releases),
758            "/releases".into(),
759        ),
760        (
761            "New Pull Request",
762            ctx.url(AppRoute::PullNew),
763            "/pulls/new".into(),
764        ),
765        (
766            "Notifications (@mentions)",
767            ctx.url(AppRoute::Notifications),
768            "/notifications".into(),
769        ),
770        (
771            "Compare Branches",
772            ctx.url(AppRoute::Compare { spec: None }),
773            "/compare".into(),
774        ),
775        (
776            "Actions & Workflows",
777            ctx.url(AppRoute::Actions),
778            "/actions".into(),
779        ),
780        (
781            "Security & Signatures",
782            ctx.url(AppRoute::Security),
783            "/security".into(),
784        ),
785        (
786            "Insights & Contributors",
787            ctx.url(AppRoute::Insights),
788            "/insights".into(),
789        ),
790        (
791            "Repository Settings",
792            ctx.url(AppRoute::Settings { section: None }),
793            "/settings".into(),
794        ),
795        (
796            "Webhooks (HMAC-SHA256)",
797            ctx.url(AppRoute::Settings {
798                section: Some("webhooks"),
799            }),
800            "/settings/webhooks".into(),
801        ),
802        (
803            "Branch Protection Rules",
804            ctx.url(AppRoute::Settings {
805                section: Some("branches"),
806            }),
807            "/settings/branches".into(),
808        ),
809        (
810            "SSH Keys",
811            ctx.url(AppRoute::Settings {
812                section: Some("keys"),
813            }),
814            "/settings/keys".into(),
815        ),
816        (
817            "Personal Access Tokens",
818            ctx.url(AppRoute::Settings {
819                section: Some("tokens"),
820            }),
821            "/settings/tokens".into(),
822        ),
823    ];
824
825    out.el(
826        "dialog",
827        &[
828            Attr::Id("cmd-modal"),
829            Attr::Class("cmd-dialog-native"),
830            Attr::Aria("labelledby", "cmd-modal-title"),
831        ],
832        |dlg: &mut HtmlBuf| {
833            dlg.el(
834                "div",
835                &[Attr::Class("popover-head u-flex u-between u-items-center")],
836                |hd: &mut HtmlBuf| {
837                    hd.el("span", &[Attr::Id("cmd-modal-title")], "Quick Jump");
838                    hd.el(
839                        "button",
840                        &[
841                            Attr::Type("button"),
842                            Attr::Class("btn"),
843                            Attr::Data("action", "close-cmd"),
844                            Attr::Aria("label", "Close command palette"),
845                        ],
846                        |btn: &mut HtmlBuf| {
847                            icon_sized(Icon::X, IconSize::Sm).render_to(btn);
848                            btn.text("Close");
849                        },
850                    );
851                },
852            );
853            dlg.el(
854                "div",
855                &[Attr::Class("cmd-search-box")],
856                |sb: &mut HtmlBuf| {
857                    sb.el(
858                        "label",
859                        &[Attr::For("cmd-input"), Attr::Class("sr-only")],
860                        "Filter commands",
861                    );
862                    sb.void_el(
863                        "input",
864                        &[
865                            Attr::Id("cmd-input"),
866                            Attr::Type("search"),
867                            Attr::Class("input"),
868                            Attr::Placeholder("Filter commands..."),
869                        ],
870                    );
871                },
872            );
873            dlg.el("div", &[Attr::Class("cmd-list")], |list: &mut HtmlBuf| {
874                for (label, href, hint) in &items {
875                    list.el(
876                        "a",
877                        &[Attr::Class("cmd-item"), Attr::Href(href)],
878                        |item: &mut HtmlBuf| {
879                            item.el("span", &[], *label);
880                            item.el("span", &[Attr::Class("muted")], hint);
881                        },
882                    );
883                }
884            });
885        },
886    );
887}
888
889#[cfg(test)]
890mod tests {
891    use super::*;
892    use crate::http::HttpRequest;
893    use crate::web::core::ctx::{MountPrefix, RequestCtx, SessionCtx, UserRole};
894
895    fn sample_header() -> RepoHeaderView<'static> {
896        RepoHeaderView {
897            name: "alpha",
898            description: "Demo <repo>",
899            default_branch: "main",
900            branch_count: 2,
901            tag_count: 1,
902            open_pr_count: 1,
903            clone_url: "http://127.0.0.1:8080/alpha.git",
904        }
905    }
906
907    #[test]
908    fn repo_shell_emits_strict_csp_mount_meta_and_zero_inline_styles() {
909        let req = HttpRequest::new("GET", "/issues", "", Vec::new());
910        let ctx = RequestCtx::new(&req, MountPrefix::new("alpha")).with_session(Some(SessionCtx {
911            username: "alice".into(),
912            role: UserRole::Admin,
913            csrf_token: "csrf_xyz".into(),
914        }));
915        let resp = respond_page(
916            &ctx,
917            Page {
918                status: 200,
919                title: "Issues — alpha",
920                description: "Demo <repo>",
921                shell: ShellKind::Repo {
922                    header: sample_header(),
923                    tab: RepoTab::Issues,
924                    extra_tabs: &[],
925                },
926                main: "Hello <world>",
927                extra_css: &[],
928                extra_js: &[],
929            },
930        );
931        assert_eq!(resp.status, 200);
932        let html = String::from_utf8(resp.body).unwrap();
933        assert!(html.contains("name=\"arks-mount\" content=\"/alpha\""));
934        assert!(html.contains("name=\"arks-csrf\" content=\"csrf_xyz\""));
935        assert!(html.contains("href=\"/alpha/issues\""));
936        assert!(html.contains("action=\"/alpha/logout\""));
937        assert!(html.contains("name=\"_csrf\" value=\"csrf_xyz\""));
938        assert!(html.contains("Hello &lt;world&gt;"));
939        assert!(
940            !html.contains("style=\""),
941            "inline style must never appear in PageShell"
942        );
943    }
944
945    #[test]
946    fn htmx_partial_request_returns_fragment_without_doctype() {
947        let req = HttpRequest::new("GET", "/issues", "", Vec::new())
948            .with_header("HX-Request", "true")
949            .with_header("HX-Target", "main-content");
950        let ctx = RequestCtx::new(&req, MountPrefix::root());
951        let resp = respond_page(
952            &ctx,
953            Page {
954                status: 200,
955                title: "Issues",
956                description: "",
957                shell: ShellKind::Repo {
958                    header: sample_header(),
959                    tab: RepoTab::Issues,
960                    extra_tabs: &[],
961                },
962                main: "Partial body",
963                extra_css: &[],
964                extra_js: &[],
965            },
966        );
967        let html = String::from_utf8(resp.body).unwrap();
968        assert!(!html.contains("<!doctype html>"));
969        assert!(html.contains("id=\"main-content\""));
970        assert!(html.contains("Partial body"));
971    }
972
973    /// Static HTML accessibility lint helper (WP-A11Y-7):
974    /// checks skip link, active `aria-current="page"`, no duplicate `id="..."`,
975    /// `<dialog>` accessible name, and no unlabeled non-hidden `<input>`.
976    fn assert_static_a11y_baseline(html: &str, expect_nav: bool) {
977        assert!(
978            html.contains("class=\"skip-link\"") && html.contains("href=\"#main-content\""),
979            "missing WCAG 2.4.1 skip link to #main-content"
980        );
981        assert!(
982            html.contains("id=\"main-content\""),
983            "missing #main-content landmark target"
984        );
985        assert!(
986            html.contains("aria-live=\"polite\""),
987            "missing WCAG 4.1.3 aria-live toast region"
988        );
989        if expect_nav {
990            assert!(
991                html.contains("aria-current=\"page\""),
992                "missing aria-current=\"page\" on active navigation tab"
993            );
994        }
995        // Check duplicate id="..." attributes.
996        let mut ids = std::collections::HashSet::new();
997        let mut cursor = html;
998        while let Some(pos) = cursor.find(" id=\"") {
999            let rest = &cursor[pos + 5..];
1000            if let Some(end) = rest.find('"') {
1001                let id = &rest[..end];
1002                assert!(ids.insert(id.to_string()), "duplicate HTML id=\"{id}\"");
1003                cursor = &rest[end + 1..];
1004            } else {
1005                break;
1006            }
1007        }
1008        // Every <dialog ...> must carry aria-label or aria-labelledby.
1009        let mut dcur = html;
1010        while let Some(pos) = dcur.find("<dialog") {
1011            let rest = &dcur[pos..];
1012            if let Some(end) = rest.find('>') {
1013                let tag = &rest[..=end];
1014                assert!(
1015                    tag.contains("aria-label=") || tag.contains("aria-labelledby="),
1016                    "unlabelled <dialog>: {tag}"
1017                );
1018                dcur = &rest[end + 1..];
1019            } else {
1020                break;
1021            }
1022        }
1023        // Every non-hidden <input ...> must have aria-label or a matching <label for="id">.
1024        let mut icur = html;
1025        while let Some(pos) = icur.find("<input") {
1026            let rest = &icur[pos..];
1027            if let Some(end) = rest.find('>') {
1028                let tag = &rest[..=end];
1029                if !tag.contains("type=\"hidden\"") && !tag.contains("aria-label=") {
1030                    let has_for = tag
1031                        .find("id=\"")
1032                        .and_then(|ip| {
1033                            let r = &tag[ip + 4..];
1034                            r.find('"').map(|e| &r[..e])
1035                        })
1036                        .is_some_and(|id| html.contains(&format!("for=\"{id}\"")));
1037                    assert!(has_for, "unlabelled <input>: {tag}");
1038                }
1039                icur = &rest[end + 1..];
1040            } else {
1041                break;
1042            }
1043        }
1044    }
1045
1046    #[test]
1047    fn repo_and_multirepo_shells_pass_static_a11y_and_no_glyph_guards() {
1048        let req = HttpRequest::new("GET", "/issues", "", Vec::new());
1049        let ctx = RequestCtx::new(&req, MountPrefix::root());
1050        let repo_resp = respond_page(
1051            &ctx,
1052            Page {
1053                status: 200,
1054                title: "Issues — alpha",
1055                description: "Demo",
1056                shell: ShellKind::Repo {
1057                    header: sample_header(),
1058                    tab: RepoTab::Issues,
1059                    extra_tabs: &[],
1060                },
1061                main: "Main body",
1062                extra_css: &[],
1063                extra_js: &[],
1064            },
1065        );
1066        let repo_html = String::from_utf8(repo_resp.body).unwrap();
1067        assert_static_a11y_baseline(&repo_html, true);
1068        assert!(repo_html.contains("#i-arks"));
1069        assert!(repo_html.contains("#i-circle-dot"));
1070        assert!(!repo_html.contains("HTMX v2"));
1071        assert!(!repo_html.contains("arks serve"));
1072        for &glyph in crate::web::ui::icons::FORBIDDEN_GLYPH_ICONS {
1073            assert!(
1074                !repo_html.contains(glyph),
1075                "forbidden glyph icon '{glyph}' found in Repo shell HTML"
1076            );
1077        }
1078
1079        let mr_resp = respond_page(
1080            &ctx,
1081            Page {
1082                status: 200,
1083                title: "arks",
1084                description: "Multi-repo",
1085                shell: ShellKind::MultiRepoRoot {
1086                    repo_count: Some(3),
1087                },
1088                main: "Repos",
1089                extra_css: &[],
1090                extra_js: &[],
1091            },
1092        );
1093        let mr_html = String::from_utf8(mr_resp.body).unwrap();
1094        assert_static_a11y_baseline(&mr_html, false);
1095        for &glyph in crate::web::ui::icons::FORBIDDEN_GLYPH_ICONS {
1096            assert!(
1097                !mr_html.contains(glyph),
1098                "forbidden glyph icon '{glyph}' found in MultiRepo shell HTML"
1099            );
1100        }
1101    }
1102}