Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.index.navigation

Requirements index · View definition

evidence Valid

Requirement

Each requirement and example definition badge MUST link to its own anchored definition on the current page. The badge MUST have a separate adjacent link containing an accessible right-arrow icon in an integrated segment matching the badge color linking to its evidence detail page. The badge and arrow MUST remain aligned in one non-wrapping row. Definitions MUST NOT be followed by a separate plaintext evidence link. Each detail page MUST link back to the definition’s anchored badge and to the index. Reference badges MUST continue to link to the definition. These links MUST resolve when a requirement name contains .md, as in requirements.cli.mdbook.

Rationale

The reviewed tests cover each obligation in requirements.index.navigation. I found no gap.

  • Badge links to its own anchored definition on the current page.
    • definitions_without_a_marker_get_a_default_index_and_detail_pages asserts id="habeas-{kind}-rules.{name}" href="#habeas-{kind}-rules.{name}" for a requirement, an example and a .md-containing name.
    • index_shows_evidence_states_and_links_generated_chapters asserts the same id/href pair for requirements.core.ready.
  • Separate adjacent arrow link to the evidence detail page.
    • mdbook_preprocessor_renders_definitions_between_stdin_and_stdout splits out each habeas-definition-badge span. It checks that each row has an <img, a habeas-detail-icon link, and exactly two </a> (badge link plus icon link), and that the detail href is requirements-index/rules.ready.html.
    • index_owns_details_in_book_order_with_badge_icons checks the View evidence title, the aria-label and the stroke="#fff" arrow.
    • definition_evidence_link_targets_are_escaped checks the exact escaped href and aria-label on the icon anchor.
  • Icon segment matches the badge color. definition_badge_and_evidence_icon_share_colors compares the shield color with the icon background-color for both req and example. In fn[replace_definitions] the color depends only on the definition kind, so these two cases cover every variation.
  • One non-wrapping aligned row. definition_badge_stylesheet_keeps_the_arrow_in_one_row asserts the wrapper, link and icon CSS declarations: inline-flex, nowrap, flex-shrink: 0, centered alignment and a fixed height.
  • No separate plaintext evidence link. Several tests assert !content.contains("See evidence").
  • Detail page links back to the anchored badge and to the index.
    • The default-index test checks every detail page for the [Requirements index](../requirements-index.html) link. It checks the [View definition](...#habeas-req-...) anchored link for the cli.mdbook page and the nested-chapter page.
    • The evidence-states test checks the explicit-index placement.
    • The ordering test checks the ../../more.html#habeas-example-... link.
  • Reference badges still link to the definition. references_in_nested_chapters_link_to_the_requirement_definition checks the impl, cite and test reference badges. Each links to ../requirements.html#habeas-req-requirements.ready.
  • .md in names.
    • links_preserve_requirement_names_containing_md asserts %2Emd encoding for both the detail href and the definition anchor href.
    • The default-index test and the ordering test also assert cli%2Emdbook in the badge, icon and detail-page links.

The tests only partly check that the icon is a right arrow (they look for the white stroke, not the path). The test for .md names in reference badges goes through chapter_href rather than a rendered reference to such a name. Neither is a named obligation with a plausible violation that the tests would accept.

Inputs

Implementation

Input 11: outline src/lib.rs fn[replace_definitions]
// {impl}`requirements.index.navigation`
// {impl}`requirements.references.book_badges`
// {impl}`requirements.examples.definition`
// {impl}`requirements.examples.index`
fn replace_definitions(
    content: &str,
    namespace: &str,
    current_path: Option<&Path>,
    plan: Option<&index::DetailPlan>,
) -> String {
    let mut result = String::with_capacity(content.len());
    let mut cursor = 0;

    // A directive whose full name is invalid remains literal.
    for block in definition_blocks(content)
        .into_iter()
        .filter(|block| block.closed && valid_name(&full_requirement_name(namespace, &block.name)))
    {
        if block.start < cursor {
            continue;
        }
        result.push_str(&content[cursor..block.start]);
        let full_name = full_requirement_name(namespace, &block.name);
        // Valid names contain no HTML-special characters, so this escaping
        // only guards the inserted HTML against future name rules.
        // {impl}`requirements.references.safe_badges`
        let escaped_name = escape_html(&full_name);
        if block.kind == DefinitionKind::Term {
            if let Ok((phrase, body)) =
                terms::declaration(&content[block.body_start..block.body_end])
            {
                result.push_str(&format!(
                    "<strong id=\"{}\">{}</strong>\n\n",
                    escape_html(&block.kind.anchor(&full_name)),
                    terms::escaped_phrase(phrase)
                ));
                result.push_str(body);
                result.push('\n');
            } else {
                result.push_str(&content[block.start..block.end]);
            }
            cursor = block.end;
            continue;
        }
        let color = if block.kind == DefinitionKind::Example {
            "5b62a8"
        } else {
            "006ba8"
        };
        let badge = shield_badge(block.kind.badge(), &full_name, color);
        let detail_href = current_path
            .zip(plan)
            .and_then(|(current, plan)| plan.detail_path(&full_name).map(|path| (current, path)))
            .map(|(current, path)| escape_html(&chapter_href(current, path, None)));
        let anchor = format!("habeas-{}-{escaped_name}", block.kind.badge());
        let permalink = format!("#{anchor}").replace(".md", "%2Emd");
        result.push_str(&format!(
            "<span class=\"habeas-definition-badge\"><a class=\"habeas-req-badge\" id=\"{anchor}\" href=\"{permalink}\" title=\"Link to this definition\">{badge}</a>"
        ));
        if let Some(href) = &detail_href {
            result.push_str(&format!(
                "<a class=\"habeas-detail-icon\" href=\"{href}\" style=\"background-color: #{color}\" title=\"View evidence\" aria-label=\"View evidence for {escaped_name}\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"#fff\" stroke-width=\"1.5\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M3 8h10M8 3l5 5-5 5\"/></svg></a>"
            ));
        }
        result.push_str("</span>\n\n");
        // Option lines such as anchors are metadata, not body text.
        let body = &content[block.text_start..block.body_end];
        let body = if block.kind == DefinitionKind::Requirement {
            replace_query_directives(body)
        } else {
            body.to_owned()
        };
        result.push_str(&replace_definitions(&body, namespace, current_path, plan));
        result.push('\n');
        cursor = block.end;
    }

    result.push_str(&content[cursor..]);
    result
}
Input 12: outline src/lib.rs fn[chapter_href]
// {impl}`requirements.index.navigation`
// Relative chapter links, including `../` from nested chapters.
pub(crate) fn chapter_href(current: &Path, target: &Path, anchor: Option<&str>) -> String {
    let current_dir = current
        .parent()
        .into_iter()
        .flat_map(Path::components)
        .filter_map(|component| match component {
            Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect::<Vec<_>>();
    let target_html = target
        .with_extension("html")
        .components()
        .filter_map(|component| match component {
            Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect::<Vec<_>>();
    let shared = current_dir
        .iter()
        .zip(&target_html)
        .take_while(|(left, right)| left == right)
        .count();
    let mut href = "../".repeat(current_dir.len() - shared);
    href.push_str(&target_html[shared..].join("/"));
    if let Some(anchor) = anchor {
        href.push('#');
        href.push_str(anchor);
    }
    // mdBook interprets ".md" inside a generated URL as a chapter suffix.
    href.replace(".md", "%2Emd")
}

Tests

Input 2: outline src/index.rs mod[tests]/fn[index_shows_evidence_states_and_links_generated_chapters]
  • File: src/index.rs
  • Selector: mod[tests]/fn[index_shows_evidence_states_and_links_generated_chapters]
  • Kind: fn
  • src/index.rs:1101–1306
    // {test}`requirements.index.chapter`
    // {test}`requirements.index.state`
    // {test}`requirements.index.navigation`
    // {test}`requirements.index.source_links`
    // {test}`requirements.cli.shared_status_rendering`
    // {test}`requirements.index.detail_format`
    // {test}`requirements.index.invalid_detail`
    // {test}`requirements.test-coverage.index`
    // {test}`requirements.index.detail_pages`
    #[test]
    fn index_shows_evidence_states_and_links_generated_chapters() {
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join("md/requirements")).unwrap();
        fs::create_dir_all(temp.path().join("evidence")).unwrap();
        fs::create_dir_all(temp.path().join("src")).unwrap();
        fs::write(temp.path().join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
        let requirements = [
            ("ready", "Ready MUST work."),
            ("pending", "Pending MUST work."),
            ("changed", "Changed MUST work."),
            ("absent", "Absent MUST work."),
            ("uncovered", "Uncovered MUST work."),
        ];
        let mut source = String::from("# Requirements\n\n");
        for (name, body) in requirements {
            source.push_str(&format!(":::{{req}} {name}\n{body}\n:::\n\n"));
        }
        fs::write(temp.path().join("md/requirements/core.md"), &source).unwrap();
        fs::write(
            temp.path().join("src/main.rs"),
            "// {test}`requirements.core.uncovered`\n",
        )
        .unwrap();
        for (name, body, determination) in [
            ("ready", "Ready MUST work.", true),
            ("pending", "Pending MUST work.", false),
            ("changed", "Old requirement.", true),
            ("uncovered", "Uncovered MUST work.", true),
        ] {
            fs::write(
                temp.path()
                    .join(format!("evidence/requirements.core.{name}.json")),
                json!({
                    "requirement": body,
                    "determination": determination,
                    "rationale": "The fixture records the evidence state.",
                    "inputs": []
                })
                .to_string(),
            )
            .unwrap();
        }

        let mut book = Book::new();
        let mut definition_chapter =
            Chapter::new("Requirements", source, "requirements/core.md", Vec::new());
        definition_chapter.number = Some(SectionNumber::new(vec![3]));
        book.push_item(definition_chapter);
        let mut index_chapter = Chapter::new(
            "Requirements index",
            "# Requirements index\n\n:::{requirements-index}\n:::\n".to_owned(),
            "appendix/requirements-index.md",
            Vec::new(),
        );
        index_chapter.number = Some(SectionNumber::new(vec![4]));
        book.push_item(index_chapter);
        crate::evidence::tests::stamp_reference_sets(temp.path());
        preprocess_book(&mut book, temp.path()).unwrap();

        let definition = book.chapters().next().unwrap();
        assert!(definition.content.contains(
            "id=\"habeas-req-requirements.core.ready\" href=\"#habeas-req-requirements.core.ready\""
        ));
        let index = book
            .chapters()
            .find(|chapter| chapter.name == "Requirements index")
            .unwrap();
        assert!(!index.content.contains("{requirements-index}"));
        for (name, state) in [
            ("ready", "Valid"),
            ("pending", "Determination false"),
            ("changed", "Invalid"),
            ("absent", "Missing"),
            ("uncovered", "Invalid"),
        ] {
            let link = format!(
                "| [`requirements.core.{name}`](requirements-index/requirements.core.{name}.html)"
            );
            let row = index
                .content
                .lines()
                .find(|line| line.starts_with(&link))
                .unwrap_or_else(|| panic!("missing {link} in:\n{}", index.content));
            assert_eq!(row.split('|').nth(2).unwrap().trim(), state);
        }
        let table = index
            .content
            .lines()
            .skip_while(|line| !line.starts_with("| "))
            .take_while(|line| line.starts_with("| "))
            .collect::<Vec<_>>();
        let pipes = table[0]
            .match_indices('|')
            .map(|(position, _)| position)
            .collect::<Vec<_>>();
        assert_eq!(pipes.len(), 3);
        assert!(table.iter().all(|line| {
            line.match_indices('|')
                .map(|(position, _)| position)
                .collect::<Vec<_>>()
                == pipes
        }));
        for column in 0..2 {
            let widest = table
                .iter()
                .map(|line| line.split('|').nth(column + 1).unwrap().trim().len())
                .max()
                .unwrap();
            assert_eq!(pipes[column + 1] - pipes[column] - 3, widest);
        }
        assert!(definition.sub_items.is_empty());
        assert_eq!(index.sub_items.len(), 6);
        let coverage = index
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) if chapter.name == "Coverage gaps" => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(coverage.len(), 1);
        assert_eq!(
            coverage[0].path.as_deref(),
            Some(Path::new("appendix/requirements-index/coverage.md"))
        );
        assert_eq!(coverage[0].parent_names, ["Requirements index"]);
        assert!(
            index
                .content
                .contains("[Coverage gaps](requirements-index/coverage.html)")
        );
        let ready = index
            .sub_items
            .iter()
            .find_map(|item| match item {
                BookItem::Chapter(chapter) if chapter.name == "requirements.core.ready" => {
                    Some(chapter)
                }
                _ => None,
            })
            .unwrap();
        assert_eq!(
            ready.source_path.as_deref(),
            Some(Path::new("../evidence/requirements.core.ready.json"))
        );
        assert_eq!(
            ready.number.as_deref().map(Vec::as_slice),
            Some(&[4, 2][..])
        );
        assert_eq!(
            ready.path.as_deref(),
            Some(Path::new(
                "appendix/requirements-index/requirements.core.ready.md"
            ))
        );
        assert!(ready.content.contains(
            "[View definition](../../requirements/core.html#habeas-req-requirements.core.ready)"
        ));
        assert!(
            ready
                .content
                .contains("[Requirements index](../requirements-index.html) · [View definition]")
        );
        assert!(
            ready
                .content
                .contains("img.shields.io/badge/evidence-Valid-237346")
        );
        assert!(ready.content.contains("> Ready MUST work."));
        assert!(!ready.content.contains("## Evidence record"));
        let changed = index
            .sub_items
            .iter()
            .find_map(|item| match item {
                BookItem::Chapter(chapter) if chapter.name == "requirements.core.changed" => {
                    Some(chapter)
                }
                _ => None,
            })
            .unwrap();
        assert!(changed.content.contains("requirement text changed"));
        let absent = index
            .sub_items
            .iter()
            .find_map(|item| match item {
                BookItem::Chapter(chapter) if chapter.name == "requirements.core.absent" => {
                    Some(chapter)
                }
                _ => None,
            })
            .unwrap();
        assert_eq!(
            absent.source_path.as_deref(),
            Some(Path::new("requirements/core.md"))
        );
    }
Input 3: outline src/lib.rs mod[tests]/fn[definitions_without_a_marker_get_a_default_index_and_detail_pages]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[definitions_without_a_marker_get_a_default_index_and_detail_pages]
  • Kind: fn
  • src/lib.rs:1050–1185
    // {test}`requirements.index.detail_pages`
    // {test}`requirements.index.chapter`
    // {test}`requirements.index.chapter.default`
    // {test}`requirements.index.navigation`
    // {test}`requirements.examples.index`
    // {test}`requirements.test-coverage.index`
    // {test}`requirements.references.anchors`
    #[test]
    fn definitions_without_a_marker_get_a_default_index_and_detail_pages() {
        let mut book = Book::new();
        let mut chapter = Chapter::new(
            "Rules",
            "# Rules\n\n:::{req} zeta\n:impl: notes.txt\nZeta.\n:::\n\n:::{example} alpha\nAlpha case. {cite}`rules.zeta`\n:::\n\n:::{req} cli.mdbook\nMdbook.\n:::\n".to_owned(),
            "rules.md",
            Vec::new(),
        );
        chapter.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![2]));
        chapter.sub_items.push(BookItem::Chapter(Chapter::new(
            "Child",
            ":::{req} nested\nNested.\n:::\n".to_owned(),
            "rules/child.md",
            vec!["Rules".to_owned()],
        )));
        book.push_item(chapter);
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();

        let rules = book.chapters().next().unwrap();
        let pages = rules
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(pages.len(), 1);
        assert_eq!(pages[0].name, "Child");
        assert_eq!(book.items.len(), 2);
        assert_eq!(book.chapters().count(), 8);
        assert!(rules.content.contains("habeas-detail-icon"));
        assert!(!rules.content.contains("See evidence"));
        assert!(!rules.content.contains("notes.txt"));
        for (kind, name) in [("req", "zeta"), ("example", "alpha"), ("req", "cli.mdbook")] {
            assert!(rules.content.contains(&format!(
                "id=\"habeas-{kind}-rules.{name}\" href=\"#habeas-{kind}-rules.{}\"",
                name.replace(".md", "%2Emd")
            )));
        }
        assert!(
            rules
                .content
                .contains("href=\"requirements-index/rules.cli%2Emdbook.html\"")
        );
        assert!(
            pages[0]
                .content
                .contains("href=\"../requirements-index/rules.child.nested.html\"")
        );
        let BookItem::Chapter(index) = book.items.last().unwrap() else {
            panic!("the default index must be a top-level chapter");
        };
        assert_eq!(index.name, "Requirements index");
        assert_eq!(
            index.path.as_deref(),
            Some(Path::new("requirements-index.md"))
        );
        assert!(index.source_path.is_none());
        assert!(index.parent_names.is_empty());
        assert_eq!(index.number.as_deref().map(Vec::as_slice), Some(&[3][..]));
        assert!(!index.content.contains("{requirements-index}"));
        assert!(index.content.contains("(requirement)"));
        assert!(index.content.contains("(example)"));
        assert!(index.content.contains("Missing"));
        let coverage = index
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) if chapter.name == "Coverage gaps" => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(coverage.len(), 1);
        assert_eq!(
            coverage[0].path.as_deref(),
            Some(Path::new("requirements-index/coverage.md"))
        );
        assert_eq!(coverage[0].parent_names, ["Requirements index"]);
        assert!(
            index
                .content
                .contains("[Coverage gaps](requirements-index/coverage.html)")
        );
        let details = index
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) if chapter.name != "Coverage gaps" => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(
            details
                .iter()
                .map(|page| page.name.as_str())
                .collect::<Vec<_>>(),
            [
                "rules.zeta",
                "rules.alpha",
                "rules.cli.mdbook",
                "rules.child.nested"
            ]
        );
        for (offset, page) in details.iter().enumerate() {
            assert_eq!(page.parent_names, ["Requirements index"]);
            assert_eq!(
                page.number.as_deref().map(Vec::as_slice),
                Some(&[3, offset as u32 + 2][..])
            );
            assert!(
                page.content
                    .contains("[Requirements index](../requirements-index.html)")
            );
        }
        assert!(
            details[2]
                .content
                .contains("[View definition](../rules.html#habeas-req-rules.cli%2Emdbook)")
        );
        assert!(
            details[3]
                .content
                .contains("[View definition](../rules/child.html#habeas-req-rules.child.nested)")
        );
        assert!(!root.path().join("md/requirements-index.md").exists());
    }
Input 4: outline src/lib.rs mod[tests]/fn[index_owns_details_in_book_order_with_badge_icons]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[index_owns_details_in_book_order_with_badge_icons]
  • Kind: fn
  • src/lib.rs:1268–1350
    // {test}`requirements.index.chapter`
    // {test}`requirements.index.detail_pages`
    // {test}`requirements.index.navigation`
    #[test]
    fn index_owns_details_in_book_order_with_badge_icons() {
        let mut book = Book::new();
        book.push_item(Chapter::new(
            "Rules",
            ":::{req} zeta\nZeta.\n:::\n".into(),
            "rules.md",
            vec![],
        ));
        book.push_item(Chapter::new(
            "More",
            ":::{example} cli.mdbook\nExample.\n:::\n".into(),
            "more.md",
            vec![],
        ));
        let mut index = Chapter::new(
            "Index",
            ":::{requirements-index}\n:::\n".into(),
            "appendix/index.md",
            vec![],
        );
        index.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![3]));
        let mut child = Chapter::new(
            "Existing",
            "Existing.".into(),
            "appendix/existing.md",
            vec!["Index".into()],
        );
        child.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![3, 1]));
        index.sub_items.push(BookItem::Chapter(child));
        book.push_item(index);
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();
        assert_eq!(
            book.items.len(),
            3,
            "the explicit index keeps its placement"
        );
        let chapters = book.chapters().collect::<Vec<_>>();
        for chapter in &chapters[..2] {
            assert!(chapter.sub_items.is_empty());
            assert!(
                chapter
                    .content
                    .contains("title=\"View evidence\" aria-label=\"View evidence for ")
            );
            assert!(chapter.content.contains("stroke=\"#fff\""));
            assert!(!chapter.content.contains("See evidence"));
        }
        assert!(
            chapters[1]
                .content
                .contains("href=\"appendix/index/more.cli%2Emdbook.html\"")
        );
        let pages = chapters[2]
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(
            pages
                .iter()
                .map(|page| page.name.as_str())
                .collect::<Vec<_>>(),
            ["Coverage gaps", "Existing", "rules.zeta", "more.cli.mdbook"]
        );
        assert_eq!(pages[3].parent_names, ["Index"]);
        assert_eq!(
            pages[3].number.as_deref().map(Vec::as_slice),
            Some(&[3, 4][..])
        );
        assert!(
            pages[3]
                .content
                .contains("[View definition](../../more.html#habeas-example-more.cli%2Emdbook)")
        );
    }
Input 5: outline src/lib.rs mod[tests]/fn[definition_badge_and_evidence_icon_share_colors]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[definition_badge_and_evidence_icon_share_colors]
  • Kind: fn
  • src/lib.rs:1352–1390
    // {test}`requirements.index.navigation`
    #[test]
    fn definition_badge_and_evidence_icon_share_colors() {
        let mut book = Book::new();
        book.push_item(Chapter::new(
            "Rules",
            ":::{req} ready\nReady.\n:::\n\n:::{example} case\nA case. {cite}`rules.ready`\n:::\n"
                .into(),
            "rules.md",
            vec![],
        ));
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();
        let content = &book.chapters().next().unwrap().content;
        for (kind, name) in [("req", "ready"), ("example", "case")] {
            let segment = content
                .split(&format!("id=\"habeas-{kind}-rules.{name}\""))
                .nth(1)
                .unwrap()
                .split("</span>")
                .next()
                .unwrap();
            let badge_color = segment
                .split(&format!("/badge/{kind}-rules.{name}-"))
                .nth(1)
                .unwrap()
                .split('?')
                .next()
                .unwrap();
            let icon_color = segment
                .split("style=\"background-color: #")
                .nth(1)
                .unwrap()
                .split('"')
                .next()
                .unwrap();
            assert_eq!(icon_color, badge_color, "{segment}");
        }
    }
Input 6: outline src/lib.rs mod[tests]/fn[definition_evidence_link_targets_are_escaped]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[definition_evidence_link_targets_are_escaped]
  • Kind: fn
  • src/lib.rs:1392–1427
    // {test}`requirements.references.safe_badges`
    // {test}`requirements.index.navigation`
    #[test]
    fn definition_evidence_link_targets_are_escaped() {
        let mut book = Book::new();
        book.push_item(Chapter::new(
            "Rules",
            ":::{req} ready\nReady.\n:::\n".into(),
            "rules.md",
            vec![],
        ));
        book.push_item(Chapter::new(
            "Index",
            ":::{requirements-index}\n:::\n".into(),
            "a&b \"q\" <x>.md",
            vec![],
        ));
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();
        let content = &book.chapters().next().unwrap().content;
        let icon = content
            .split("<a class=\"habeas-detail-icon\"")
            .nth(1)
            .unwrap()
            .split("</a>")
            .next()
            .unwrap();
        assert!(
            icon.contains("href=\"a&amp;b &quot;q&quot; &lt;x&gt;/rules.ready.html\""),
            "{icon}"
        );
        assert!(icon.contains("aria-label=\"View evidence for rules.ready\""));
        assert!(!icon.contains("a&b"));
        assert!(!icon.contains("\"q\""));
        assert!(!icon.contains("<x>"));
    }
Input 7: outline src/lib.rs mod[tests]/fn[links_preserve_requirement_names_containing_md]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[links_preserve_requirement_names_containing_md]
  • Kind: fn
  • src/lib.rs:1461–1480
    // {test}`requirements.index.navigation`
    #[test]
    fn links_preserve_requirement_names_containing_md() {
        let detail = chapter_href(
            Path::new("requirements.md"),
            Path::new("requirements-index/requirements.cli.mdbook.md"),
            None,
        );
        assert_eq!(detail, "requirements-index/requirements.cli%2Emdbook.html");

        let definition = chapter_href(
            Path::new("requirements-index/requirements.cli.mdbook.md"),
            Path::new("requirements.md"),
            Some("habeas-req-requirements.cli.mdbook"),
        );
        assert_eq!(
            definition,
            "../requirements.html#habeas-req-requirements.cli%2Emdbook"
        );
    }
Input 8: outline src/lib.rs mod[tests]/fn[definition_badge_stylesheet_keeps_the_arrow_in_one_row]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[definition_badge_stylesheet_keeps_the_arrow_in_one_row]
  • Kind: fn
  • src/lib.rs:1644–1675
    // {test}`requirements.index.navigation`
    #[test]
    fn definition_badge_stylesheet_keeps_the_arrow_in_one_row() {
        let rules = stylesheet_rules();
        let declarations = |selector: &str| {
            rules
                .iter()
                .filter(|(selectors, _)| selectors.iter().any(|candidate| candidate == selector))
                .flat_map(|(_, declarations)| declarations.iter().map(String::as_str))
                .collect::<Vec<_>>()
        };
        let wrapper = declarations(".habeas-definition-badge");
        for declaration in [
            "display: inline-flex",
            "align-items: center",
            "flex-wrap: nowrap",
            "white-space: nowrap",
        ] {
            assert!(wrapper.contains(&declaration), "{wrapper:?}");
        }
        let links = declarations(".habeas-definition-badge > a");
        assert!(links.contains(&"flex-shrink: 0"), "{links:?}");
        let icon = declarations("a.habeas-detail-icon");
        for declaration in [
            "display: inline-flex",
            "align-items: center",
            "justify-content: center",
            "height: 20px",
        ] {
            assert!(icon.contains(&declaration), "{icon:?}");
        }
    }
Input 9: outline src/lib.rs mod[tests]/fn[references_in_nested_chapters_link_to_the_requirement_definition]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[references_in_nested_chapters_link_to_the_requirement_definition]
  • Kind: fn
  • src/lib.rs:1755–1798
    // {test}`requirements.references.book_badges`
    // {test}`requirements.index.navigation`
    #[test]
    fn references_in_nested_chapters_link_to_the_requirement_definition() {
        let mut book = Book::new();
        book.push_item(Chapter::new(
            "Requirements",
            ":::{req} ready\nReady.\n:::".to_owned(),
            "requirements.md",
            Vec::new(),
        ));
        let references = ["impl", "cite", "test"]
            .iter()
            .map(|kind| format!("{{{kind}}}`requirements.ready`"))
            .collect::<Vec<_>>()
            .join(" ");
        book.push_item(Chapter::new(
            "Guide",
            references,
            "guides/deep.md",
            Vec::new(),
        ));

        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();
        // Generated detail pages are titled by full name.
        let chapters = book
            .chapters()
            .filter(|chapter| !chapter.name.contains('.'))
            .collect::<Vec<_>>();
        assert!(
            chapters[0]
                .content
                .contains("id=\"habeas-req-requirements.ready\"")
        );
        for (kind, color) in [("impl", "237346"), ("cite", "7151a1"), ("test", "ae5d14")] {
            assert!(chapters[1].content.contains(&format!(
                "class=\"habeas-req-badge habeas-req-ref-{kind}\" href=\"../requirements.html#habeas-req-requirements.ready\""
            )));
            assert!(chapters[1].content.contains(&format!(
                "img.shields.io/badge/{kind}-requirements.ready-{color}"
            )));
        }
    }
Input 10: outline tests/repository.rs fn[mdbook_preprocessor_renders_definitions_between_stdin_and_stdout]
  • File: tests/repository.rs
  • Selector: fn[mdbook_preprocessor_renders_definitions_between_stdin_and_stdout]
  • Kind: fn
  • tests/repository.rs:160–260
// {test}`requirements.cli.mdbook`
// {test}`requirements.index.chapter.default`
// {test}`requirements.index.detail_pages`
// {test}`requirements.index.navigation`
#[test]
fn mdbook_preprocessor_renders_definitions_between_stdin_and_stdout() {
    let temp = TempDir::new().unwrap();
    let root = temp.path();
    fs::create_dir_all(root.join("md")).unwrap();
    fs::write(root.join("Cargo.toml"), "[package]\nname = \"fixture\"\n").unwrap();
    fs::write(root.join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
    let content =
        ":::{req} ready\nReady MUST work.\n:::\n\n:::{req} cites\nSee {cite}`rules.ready`.\n:::\n"
            .to_owned();
    fs::write(root.join("md/rules.md"), &content).unwrap();
    let mut book = Book::new();
    book.push_item(Chapter::new("Rules", content, "rules.md", Vec::new()));
    let context = PreprocessorContext::new(root.to_path_buf(), Config::default(), "html".into());

    let mut child = Command::new(env!("CARGO_BIN_EXE_habeas"))
        .arg("mdbook")
        .current_dir(root)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(&serde_json::to_vec(&(&context, &book)).unwrap())
        .unwrap();
    let output = child.wait_with_output().unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let rendered: Book = serde_json::from_slice(&output.stdout).unwrap();
    let BookItem::Chapter(chapter) = &rendered.items[0] else {
        panic!("{rendered:?}");
    };
    assert!(!chapter.content.contains(":::{req}"), "{}", chapter.content);
    assert!(
        chapter.content.contains("https://img.shields.io/badge/"),
        "{}",
        chapter.content
    );
    assert!(
        chapter.content.contains("cite") && chapter.content.contains("rules.ready"),
        "{}",
        chapter.content
    );
    let badge_rows = chapter
        .content
        .split("<span class=\"habeas-definition-badge\">")
        .skip(1)
        .map(|row| row.split("</span>").next().unwrap())
        .collect::<Vec<_>>();
    assert_eq!(badge_rows.len(), 2, "{}", chapter.content);
    for row in badge_rows {
        assert!(row.contains("<img "), "{row}");
        assert!(row.contains("class=\"habeas-detail-icon\""), "{row}");
        assert_eq!(row.matches("</a>").count(), 2, "{row}");
    }
    assert!(chapter.sub_items.is_empty());
    assert!(
        chapter.content.contains("href=\"#habeas-req-rules.ready\""),
        "{}",
        chapter.content
    );
    assert!(
        chapter
            .content
            .contains("href=\"requirements-index/rules.ready.html\""),
        "{}",
        chapter.content
    );
    assert_eq!(rendered.items.len(), 2);
    let BookItem::Chapter(index) = &rendered.items[1] else {
        panic!("{rendered:?}");
    };
    assert_eq!(index.name, "Requirements index");
    assert_eq!(
        index.path.as_deref(),
        Some(Path::new("requirements-index.md"))
    );
    assert!(index.source_path.is_none());
    assert_eq!(
        index
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(detail) => Some(detail.name.as_str()),
                _ => None,
            })
            .collect::<Vec<_>>(),
        ["Coverage gaps", "rules.ready", "rules.cites"]
    );
}

Other sources

Input 1: requirements selection requirements.index.navigation
:::{req} navigation
Each requirement and example definition badge MUST link to its own anchored definition on the current page. The badge MUST have a separate adjacent link containing an accessible right-arrow icon in an integrated segment matching the badge color linking to its evidence detail page. The badge and arrow MUST remain aligned in one non-wrapping row. Definitions MUST NOT be followed by a separate plaintext evidence link. Each detail page MUST link back to the definition's anchored badge and to the index. Reference badges MUST continue to link to the definition. These links MUST resolve when a requirement name contains `.md`, as in `requirements.cli.mdbook`.
:::