Skip to main content

carve/extensions/
code_group.rs

1//! Render a `::: code-group` container as a set of radio-driven tabs, one per
2//! fenced code block.
3//!
4//! Port of carve-js `code-group.ts` and carve-php `CodeGroupExtension`.
5//! carve-js keys a block renderer on the `admonition` and `div` node types;
6//! carve-rs has no per-node render hook for an existing node, so this follows
7//! the same shape [`crate::Details`] uses: a `before_render` pass rewrites
8//! every code group into a [`BlockNode::ExtensionCarrier`] carrier, and
9//! [`CarveExtension::render_extension_carrier`] renders it.
10//!
11//! ```
12//! use carve::{CodeGroup, Options};
13//! let ext = CodeGroup::new();
14//! let opts = Options::new().with_extension(&ext);
15//! let src = "::: code-group\n``` js\nlet a = 1\n```\n:::";
16//! let html = carve::to_html_with_options(src, &opts);
17//! assert!(html.contains("class=\"code-group\""));
18//! assert!(html.contains("type=\"radio\""));
19//! ```
20
21use std::cell::Cell;
22
23use crate::ast::{AttrSlot, Attrs, BlockNode, CodeBlock, Document, ExtensionCarrier};
24use crate::extension::{BeforeRenderContext, CarveExtension, RenderContext};
25use crate::extensions::tabs::{apply_single_selection, SingleSelect, TabsMode};
26use crate::render::{render_attrs, render_attrs_for};
27
28/// Sentinel name for the rewritten carrier node. The profile filter still
29/// gates it as a `div` (its origin), so a restrictive profile strips the group
30/// exactly as it would the underlying container.
31pub(crate) const CARRIER: &str = "carve-code-group";
32
33/// CSS class names and the id prefix the rendered markup uses.
34#[derive(Debug, Clone)]
35pub struct CodeGroupOptions {
36    /// `Css` (default) or `Aria`, the same two-valued option Tabs carries.
37    ///
38    /// THE SAME TYPE, not a copy of it: extensions §13.1 states one `mode`
39    /// option with one vocabulary binding both constructs, and "two constructs
40    /// of the same shape do not get different accessibility ceilings because
41    /// one of them was written second". Two identical enums would be two places
42    /// for that vocabulary to drift.
43    ///
44    /// `Css` is the default and an implementation MUST NOT ship `Aria` as one.
45    /// That is §2.5 rather than compatibility: `Aria` reveals with `hidden`, so
46    /// a page that registers it and ships no script loses every panel but the
47    /// first, while `Css` with no stylesheet at all shows every panel. In Rust
48    /// an unknown value is rejected by the type, which is what §13.1 asks of a
49    /// host that spells the mode as a string.
50    pub mode: TabsMode,
51    /// Class on the wrapper. Default `code-group`.
52    pub wrapper_class: String,
53    /// Class on each code panel. Default `code-group-panel`.
54    pub panel_class: String,
55    /// Class on each tab label. Default `code-group-label`.
56    pub label_class: String,
57    /// Class on each radio input. Default `code-group-radio`.
58    pub radio_class: String,
59    /// Prefix for generated ids and radio-group names. Default `codegroup`.
60    pub id_prefix: String,
61    /// Accessible name for the code group AS A WHOLE, overriding the render's
62    /// `labels` map for this instance; empty writes no name.
63    ///
64    /// Each tab was already named by its own `<label>`; the GROUP was anonymous
65    /// (markup-carve/carve#1468). `None` reads `codeGroup` from the map.
66    pub group_label: Option<String>,
67}
68
69impl Default for CodeGroupOptions {
70    fn default() -> Self {
71        Self {
72            wrapper_class: "code-group".to_string(),
73            mode: TabsMode::Css,
74            panel_class: "code-group-panel".to_string(),
75            label_class: "code-group-label".to_string(),
76            radio_class: "code-group-radio".to_string(),
77            id_prefix: "codegroup".to_string(),
78            group_label: None,
79        }
80    }
81}
82
83/// Render `::: code-group` containers as tabbed code panels.
84#[derive(Debug, Default)]
85pub struct CodeGroup {
86    opts: CodeGroupOptions,
87    /// Per-document counter, reset in `before_render`. `Cell` because the
88    /// render hooks take `&self`; the trait has no `Sync` bound, and an
89    /// extension instance renders one document at a time. Same shape as
90    /// `Tabs::set_counter`, for the same reason.
91    group_counter: Cell<usize>,
92}
93
94impl CodeGroup {
95    /// A code-group extension with the default class names.
96    pub fn new() -> Self {
97        Self::default()
98    }
99
100    /// A code-group extension with caller-chosen class names.
101    pub fn with_options(opts: CodeGroupOptions) -> Self {
102        Self {
103            opts,
104            group_counter: Cell::new(0),
105        }
106    }
107}
108
109/// One tab: the code block, plus the name and initial state resolved for it.
110struct GroupItem<'a> {
111    block: &'a CodeBlock,
112    language: Option<&'a str>,
113    label: String,
114    selected: bool,
115}
116
117impl SingleSelect for GroupItem<'_> {
118    fn selected_mut(&mut self) -> &mut bool {
119        &mut self.selected
120    }
121}
122
123impl CarveExtension for CodeGroup {
124    fn name(&self) -> &'static str {
125        "code-group"
126    }
127
128    fn before_render(&self, mut doc: Document, _ctx: &BeforeRenderContext<'_>) -> Document {
129        self.group_counter.set(0);
130        rewrite_blocks(&mut doc.children);
131        // Footnote bodies live outside the tree but are still rendered, so a
132        // group inside a footnote definition must be rewritten too.
133        for blocks in doc.footnote_defs.values_mut() {
134            rewrite_blocks(blocks);
135        }
136        doc
137    }
138
139    fn render_extension_carrier(
140        &self,
141        node: &ExtensionCarrier,
142        ctx: &RenderContext<'_>,
143    ) -> Option<String> {
144        if node.name != CARRIER {
145            return None;
146        }
147
148        let items = collect_items(&node.children);
149        // No code blocks: hand it back to the core renderer rather than
150        // emitting an empty tab strip.
151        if items.is_empty() {
152            return None;
153        }
154
155        let level = ctx.level();
156        // The core renderer pads the opener; this pad belongs to the closer.
157        let pad = ctx.indent(level);
158        let inner_pad = ctx.indent(level + 1);
159        if ctx.is_static() {
160            // A STATIC RENDER TAKES NEITHER MODE (extensions §13.1). There are
161            // no tabs left to list: `renderStatic` flattens the set to one
162            // `<section>` per panel headed by its `[label]`, and the heading IS
163            // the name. So `tablist` here would describe an interaction that
164            // this output does not contain, whatever `mode` the host configured
165            // - the role has to come from what was EMITTED and not from the
166            // option. `group` regardless, which is also what this renderer
167            // emitted before the option existed.
168            let attrs = self.wrapper_attrs(node.attrs.as_ref(), "group", ctx);
169            let mut html = format!("<div{}>\n", render_attrs_for(&attrs, "div"));
170            for item in &items {
171                html.push_str(&format!(
172                    "{inner_pad}<section class=\"{}\">\n",
173                    ctx.escape_attr(&self.opts.panel_class),
174                ));
175                html.push_str(&format!(
176                    "{inner_pad}<h3 class=\"{}\">{}</h3>\n",
177                    ctx.escape_attr(&self.opts.label_class),
178                    ctx.escape_html(&item.label),
179                ));
180                html.push_str(&self.render_code(item, ctx));
181                html.push_str(&format!("{inner_pad}</section>\n"));
182            }
183            html.push_str(&format!("{pad}</div>"));
184
185            return Some(html);
186        }
187
188        let role = match self.opts.mode {
189            TabsMode::Css => "group",
190            TabsMode::Aria => "tablist",
191        };
192        let attrs = self.wrapper_attrs(node.attrs.as_ref(), role, ctx);
193
194        // Number the group FIRST, then reserve the numbered string in the
195        // document id namespace. Taking the bare prefix instead made the first
196        // group `codegroup` and left `-2` to arrive as a COLLISION suffix, so
197        // carve-js and carve-php said `codegroup-1` where this said
198        // `codegroup`, and an unrelated `{#codegroup}` elsewhere in the
199        // document shifted every group's name. Tabs has always done it this
200        // way (`tabs.rs`); this is that shape.
201        self.group_counter.set(self.group_counter.get() + 1);
202        let group_id = ctx.unique_id(&format!(
203            "{}-{}",
204            self.opts.id_prefix,
205            self.group_counter.get()
206        ));
207        match self.opts.mode {
208            TabsMode::Css => Some(self.render_css(&attrs, &items, &group_id, ctx)),
209            TabsMode::Aria => Some(self.render_aria(&attrs, &items, &group_id, ctx)),
210        }
211    }
212}
213
214impl CodeGroup {
215    /// Wrapper attributes: the wrapper class first, then the author's other
216    /// classes in order, minus the structural `code-group` that selected this
217    /// renderer in the first place.
218    fn wrapper_attrs(
219        &self,
220        source: Option<&Attrs>,
221        role: &str,
222        ctx: &RenderContext<'_>,
223    ) -> Option<Attrs> {
224        let mut attrs = source.cloned().unwrap_or_default();
225        let mut classes = vec![self.opts.wrapper_class.clone()];
226        for class in &attrs.classes {
227            if class != "code-group" && class != &self.opts.wrapper_class {
228                classes.push(class.clone());
229            }
230        }
231        attrs.classes = classes;
232        // The group carries a ROLE and a NAME (markup-carve/carve#1468). Each
233        // tab was named by its own `<label>` and the group was not; this
234        // extension's own docs used to send you to Tabs for it, which costs the
235        // language labels and the highlighting that are the reason to use it.
236        //
237        // Anything the author wrote WINS, matched ASCII-case-insensitively.
238        let authored = |name: &str| {
239            source.is_some_and(|a| a.key_values.keys().any(|k| k.eq_ignore_ascii_case(name)))
240        };
241        if !authored("role") {
242            // `group` in `css` mode, `tablist` in `aria` - the same split
243            // `tabs.rs` makes, for the same reason: the CSS mode has no
244            // tab/panel roles to associate, so `group` is all it can claim.
245            attrs
246                .key_values
247                .insert("role".to_string(), role.to_string());
248            crate::extension::record_attr_order(&mut attrs, "role");
249        }
250        let group_label = self
251            .opts
252            .group_label
253            .clone()
254            .unwrap_or_else(|| ctx.label(crate::extension::LABEL_CODE_GROUP));
255        if !group_label.is_empty() && !authored("aria-label") && !authored("aria-labelledby") {
256            attrs
257                .key_values
258                .insert("aria-label".to_string(), group_label);
259            crate::extension::record_attr_order(&mut attrs, "aria-label");
260        }
261
262        Some(attrs)
263    }
264
265    /// `css` mode: a radio per panel plus a sibling `<label for=…>`, revealed
266    /// by a stylesheet. No script, and with no stylesheet at all every panel is
267    /// visible - which is why extensions §13.1 makes this the default.
268    fn render_css(
269        &self,
270        attrs: &Option<Attrs>,
271        items: &[GroupItem<'_>],
272        group_id: &str,
273        ctx: &RenderContext<'_>,
274    ) -> String {
275        let level = ctx.level();
276        // The core renderer pads the opener; this pad belongs to the closer.
277        let pad = ctx.indent(level);
278        // Extensions §13.6: only the wrapper's own two tags take the ambient
279        // indentation. Every line between them is the cross-impl contract at
280        // column 0, and a panel closes on a line this function does not pad.
281        let mut html = format!("<div{}>\n", render_attrs_for(attrs, "div"));
282
283        for (index, item) in items.iter().enumerate() {
284            let input_id = ctx.unique_id(&format!("{group_id}-tab-{}", index + 1));
285            html.push_str(&format!(
286                "<input type=\"radio\" name=\"{}\" id=\"{}\" class=\"{}\"{}>\n",
287                ctx.escape_attr(group_id),
288                ctx.escape_attr(&input_id),
289                ctx.escape_attr(&self.opts.radio_class),
290                if item.selected { " checked" } else { "" },
291            ));
292            html.push_str(&format!(
293                "<label for=\"{}\" class=\"{}\">{}</label>\n",
294                ctx.escape_attr(&input_id),
295                ctx.escape_attr(&self.opts.label_class),
296                ctx.escape_html(&item.label),
297            ));
298        }
299
300        // THE PANEL CARRIES ITS OWN LABEL (extensions §13.2), keyed on the tab
301        // name where one was written and the language word otherwise - which is
302        // already what `item.label` resolves to. Same reasoning as Tabs:
303        // `role="group"` rather than `tabpanel` because a radio reveals it, no
304        // `<section>` because one landmark per panel is N per group, and no
305        // `labels` key because the string is DERIVED from the document.
306        for item in items {
307            html.push_str(&format!(
308                "<div class=\"{}\" role=\"group\" aria-label=\"{}\">",
309                ctx.escape_attr(&self.opts.panel_class),
310                ctx.escape_attr(&item.label),
311            ));
312            html.push_str(&self.render_code(item, ctx));
313            html.push_str("</div>\n");
314        }
315
316        html.push_str(&format!("{pad}</div>"));
317
318        html
319    }
320
321    /// `aria` mode: `role="tablist"` with buttons, `role="tabpanel"` panels
322    /// bound by `aria-labelledby`, and `hidden` on every panel but the selected
323    /// one. Needs a client script, which is why it is not the default.
324    ///
325    /// A PANEL HERE TAKES NEITHER `role="group"` NOR A NAME (§13.3): the
326    /// association already exists, and naming it as well would give one element
327    /// two accessible names and pull it out of the `tablist` relationship that
328    /// is the only reason to be in this mode.
329    fn render_aria(
330        &self,
331        attrs: &Option<Attrs>,
332        items: &[GroupItem<'_>],
333        group_id: &str,
334        ctx: &RenderContext<'_>,
335    ) -> String {
336        let level = ctx.level();
337        // The core renderer pads the opener; this pad belongs to the closer.
338        let pad = ctx.indent(level);
339
340        // Both ids per panel are computed ONCE and reused by the two loops, so
341        // a bumped generated id keeps the aria-controls / aria-labelledby
342        // wiring pointing at the right element. `tabs.rs` says the same.
343        let pairs: Vec<(String, String)> = (0..items.len())
344            .map(|index| {
345                (
346                    ctx.unique_id(&format!("{group_id}-tab-{}", index + 1)),
347                    ctx.unique_id(&format!("{group_id}-panel-{}", index + 1)),
348                )
349            })
350            .collect();
351
352        let mut html = format!("<div{}>\n", render_attrs_for(attrs, "div"));
353
354        for (item, (tab_id, panel_id)) in items.iter().zip(&pairs) {
355            html.push_str(&format!(
356                // `type="button"`, NOT the implicit `submit` (extensions
357                // §13.3). A bare `<button>` is a submit button, so a code group
358                // inside a `<form>` submitted the form instead of switching
359                // panels - the one interaction this mode exists to provide,
360                // traded for the one thing the page never asked for.
361                "<button type=\"button\" role=\"tab\" id=\"{}\" aria-selected=\"{}\" \
362                 aria-controls=\"{}\" class=\"{}\"{}>{}</button>\n",
363                ctx.escape_attr(tab_id),
364                if item.selected { "true" } else { "false" },
365                ctx.escape_attr(panel_id),
366                ctx.escape_attr(&self.opts.label_class),
367                if item.selected {
368                    ""
369                } else {
370                    " tabindex=\"-1\""
371                },
372                ctx.escape_html(&item.label),
373            ));
374        }
375
376        for (item, (tab_id, panel_id)) in items.iter().zip(&pairs) {
377            html.push_str(&format!(
378                "<div role=\"tabpanel\" id=\"{}\" aria-labelledby=\"{}\" \
379                 class=\"{}\"{}>",
380                ctx.escape_attr(panel_id),
381                ctx.escape_attr(tab_id),
382                ctx.escape_attr(&self.opts.panel_class),
383                if item.selected { "" } else { " hidden" },
384            ));
385            html.push_str(&self.render_code(item, ctx));
386            html.push_str("</div>\n");
387        }
388
389        html.push_str(&format!("{pad}</div>"));
390
391        html
392    }
393
394    fn render_code(&self, item: &GroupItem<'_>, ctx: &RenderContext<'_>) -> String {
395        let lang_attr = match item.language {
396            Some(lang) => format!(" class=\"language-{}\"", ctx.escape_attr(lang)),
397            None => String::new(),
398        };
399        let attrs = strip_selected(item.block.attrs.as_ref());
400
401        format!(
402            "<pre{}><code{lang_attr}>{}</code></pre>\n",
403            render_attrs(&attrs),
404            ctx.escape_html(&item.block.content),
405        )
406    }
407}
408
409/// The `selected` marker is this extension's own input, not something to hand
410/// on to the rendered `<pre>`.
411fn strip_selected(source: Option<&Attrs>) -> Option<Attrs> {
412    let attrs = source?;
413    if !attrs.key_values.contains_key("selected") {
414        return Some(attrs.clone());
415    }
416
417    let mut stripped = attrs.clone();
418    stripped.key_values.remove("selected");
419    stripped
420        .order
421        .retain(|slot| !matches!(slot, AttrSlot::Key(key) if key == "selected"));
422
423    Some(stripped)
424}
425
426/// Resolve one tab per fenced code block: its name and whether it opens first.
427fn collect_items(blocks: &[BlockNode]) -> Vec<GroupItem<'_>> {
428    let mut items = Vec::new();
429
430    for block in blocks {
431        let BlockNode::CodeBlock(code) = block else {
432            continue;
433        };
434
435        let language = code.lang.as_deref().filter(|lang| !lang.is_empty());
436        let label = code
437            .label
438            .as_deref()
439            .map(str::trim)
440            .filter(|label| !label.is_empty())
441            .map(str::to_string)
442            .or_else(|| language.map(str::to_string))
443            .unwrap_or_else(|| format!("Code {}", items.len() + 1));
444        let selected = code
445            .attrs
446            .as_ref()
447            .is_some_and(|attrs| attrs.key_values.contains_key("selected"));
448
449        items.push(GroupItem {
450            block: code,
451            language,
452            label,
453            selected,
454        });
455    }
456
457    // EXACTLY ONE PANEL IS SELECTED (extensions §13.5): the first one the
458    // document marks, or the first block where it marks none. The SAME step
459    // the Tabs renderer runs, because §13 binds both constructs.
460    apply_single_selection(&mut items);
461
462    items
463}
464
465/// Does this container hold a code block this extension would render as a panel?
466///
467/// Asked BEFORE the rewrite, for the reason `tabs::holds_a_tab` gives: the
468/// render-stage decline hands the CARRIER to the core renderer, which writes the
469/// sentinel name as the class and drops every authored attribute
470/// (markup-carve/carve-rs#1979).
471fn holds_a_code_block(block: &BlockNode) -> bool {
472    let children = match block {
473        BlockNode::Admonition(admonition) => &admonition.children,
474        BlockNode::Div(div) => &div.children,
475        _ => return false,
476    };
477    children
478        .iter()
479        .any(|child| matches!(child, BlockNode::CodeBlock(_)))
480}
481
482/// Is this node a code group - either the `::: code-group` typed div, which
483/// parses to an admonition, or a div carrying the class?
484fn is_code_group(block: &BlockNode) -> bool {
485    match block {
486        BlockNode::Admonition(admonition) => admonition.kind == "code-group",
487        BlockNode::Div(div) => div
488            .attrs
489            .as_ref()
490            .is_some_and(|attrs| attrs.classes.iter().any(|class| class == "code-group")),
491        _ => false,
492    }
493}
494
495fn rewrite_blocks(blocks: &mut [BlockNode]) {
496    for block in blocks.iter_mut() {
497        if is_code_group(block) && holds_a_code_block(block) {
498            *block = match block {
499                BlockNode::Admonition(admonition) => {
500                    rewrite_blocks(&mut admonition.children);
501                    BlockNode::ExtensionCarrier(ExtensionCarrier {
502                        attrs: admonition.attrs.take(),
503                        name: CARRIER.to_string(),
504                        children: std::mem::take(&mut admonition.children),
505                        summary: None,
506                        label: admonition.label.take(),
507                        pos: None,
508                    })
509                }
510                BlockNode::Div(div) => {
511                    rewrite_blocks(&mut div.children);
512                    BlockNode::ExtensionCarrier(ExtensionCarrier {
513                        attrs: div.attrs.take(),
514                        name: CARRIER.to_string(),
515                        children: std::mem::take(&mut div.children),
516                        summary: None,
517                        label: div.label.take(),
518                        pos: None,
519                    })
520                }
521                _ => unreachable!("is_code_group matched neither variant"),
522            };
523
524            continue;
525        }
526
527        match block {
528            BlockNode::List(list) => {
529                for item in &mut list.items {
530                    rewrite_blocks(&mut item.children);
531                }
532            }
533            BlockNode::BlockQuote(quote) => rewrite_blocks(&mut quote.children),
534            BlockNode::Admonition(admonition) => rewrite_blocks(&mut admonition.children),
535            BlockNode::Directive(div) => rewrite_blocks(&mut div.children),
536            BlockNode::Div(div) => rewrite_blocks(&mut div.children),
537            BlockNode::Section(section) => rewrite_blocks(&mut section.children),
538            BlockNode::Table(table) => {
539                for row in &mut table.rows {
540                    for cell in &mut row.cells {
541                        if let Some(blocks) = &mut cell.blocks {
542                            rewrite_blocks(blocks);
543                        }
544                    }
545                }
546            }
547            BlockNode::ExtensionCarrier(extension) => rewrite_blocks(&mut extension.children),
548            BlockNode::DefinitionList(definition_list) => {
549                for item in &mut definition_list.items {
550                    for definition in &mut item.definitions {
551                        rewrite_blocks(definition);
552                    }
553                }
554            }
555            _ => {}
556        }
557    }
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563    use crate::{Mode, Options};
564
565    fn html(source: &str) -> String {
566        let ext = CodeGroup::new();
567        let opts = Options::new().with_extension(&ext);
568        crate::to_html_with_options(source, &opts)
569    }
570
571    fn static_html(source: &str) -> String {
572        let ext = CodeGroup::new();
573        let opts = Options::new().with_extension(&ext).with_mode(Mode::Static);
574        crate::to_html_with_options(source, &opts)
575    }
576
577    fn aria_html(source: &str) -> String {
578        let ext = CodeGroup::with_options(CodeGroupOptions {
579            mode: TabsMode::Aria,
580            ..CodeGroupOptions::default()
581        });
582        let opts = Options::new().with_extension(&ext);
583        crate::to_html_with_options(source, &opts)
584    }
585
586    const TWO_PANELS: &str = "::: code-group\n``` js\nlet a = 1\n```\n\n``` php\n$a = 1;\n```\n:::";
587
588    /// A `css` panel takes its own label (extensions §13.2), keyed on the tab
589    /// name where one was written and the LANGUAGE WORD otherwise.
590    #[test]
591    fn a_css_panel_is_named_after_its_own_label() {
592        let out = html(TWO_PANELS);
593        assert!(
594            out.contains("<div class=\"code-group-panel\" role=\"group\" aria-label=\"js\">"),
595            "{out}"
596        );
597        assert!(
598            out.contains("<div class=\"code-group-panel\" role=\"group\" aria-label=\"php\">"),
599            "{out}"
600        );
601
602        // An authored `[label]` wins over the language word, and the panel
603        // follows the tab rather than carrying a name of its own.
604        let labelled = html("::: code-group\n``` js [Node]\nlet a = 1\n```\n:::");
605        assert!(labelled.contains("aria-label=\"Node\">"), "{labelled}");
606        assert!(!labelled.contains("aria-label=\"js\">"), "{labelled}");
607    }
608
609    /// The same escape split Tabs has: `&quot;` in the attribute, a bare quote
610    /// in the `<label>` element.
611    #[test]
612    fn a_panel_name_is_escaped_for_an_attribute() {
613        let out = html("::: code-group\n``` js [R&D \"core\" <x>]\nlet a = 1\n```\n:::");
614        assert!(
615            out.contains("aria-label=\"R&amp;D &quot;core&quot; &lt;x&gt;\""),
616            "{out}"
617        );
618    }
619
620    /// `aria` mode mirrors the Tabs one, and its panel takes NEITHER
621    /// `role="group"` nor a name (§13.3) - it is bound already.
622    #[test]
623    fn aria_mode_binds_its_panels_rather_than_naming_them() {
624        let out = aria_html(TWO_PANELS);
625        assert!(out.contains("role=\"tablist\""), "{out}");
626        assert_eq!(out.matches("role=\"tab\"").count(), 2, "{out}");
627        assert_eq!(out.matches("role=\"tabpanel\"").count(), 2, "{out}");
628        assert!(out.contains("aria-labelledby="), "{out}");
629        // Exactly one panel is hidden: the reveal §13.1 says needs a script.
630        assert_eq!(out.matches(" hidden>").count(), 1, "{out}");
631        assert!(!out.contains("type=\"radio\""), "{out}");
632        for panel in out.split("<div role=\"tabpanel\"").skip(1) {
633            let opener = panel.split('>').next().unwrap_or_default();
634            assert!(!opener.contains("role=\"group\""), "{out}");
635            assert!(!opener.contains("aria-label="), "{out}");
636        }
637    }
638
639    /// A STATIC RENDER TAKES NEITHER MODE (§13.1). `renderStatic` flattens the
640    /// set to one `<section>` per panel headed by its `[label]`, so there are no
641    /// tabs left to list and `role="tablist"` would describe an interaction the
642    /// output does not contain - whatever the host configured.
643    #[test]
644    fn a_static_render_is_a_group_under_either_mode() {
645        let css = static_html(TWO_PANELS);
646        assert!(css.contains("role=\"group\""), "{css}");
647        assert!(!css.contains("role=\"tablist\""), "{css}");
648
649        let ext = CodeGroup::with_options(CodeGroupOptions {
650            mode: TabsMode::Aria,
651            ..CodeGroupOptions::default()
652        });
653        let opts = Options::new().with_extension(&ext).with_mode(Mode::Static);
654        let aria = crate::to_html_with_options(TWO_PANELS, &opts);
655        assert!(
656            !aria.contains("role=\"tablist\""),
657            "the interactive mode leaked into a static render: {aria}"
658        );
659        assert!(aria.contains("role=\"group\""), "{aria}");
660        // And the pair: the same option DOES reach an interactive render, or
661        // the assertion above would pass on a build where the mode did nothing.
662        let interactive = aria_html(TWO_PANELS);
663        assert!(interactive.contains("role=\"tablist\""), "{interactive}");
664    }
665
666    /// `css` IS THE DEFAULT (§13.1 on top of §2.5): `aria` reveals with
667    /// `hidden`, so registering it without a script loses every panel but the
668    /// first, while `css` with no stylesheet shows all of them.
669    #[test]
670    fn css_is_the_default_mode() {
671        assert_eq!(CodeGroupOptions::default().mode, TabsMode::Css);
672        assert!(
673            !html(TWO_PANELS).contains(" hidden"),
674            "{}",
675            html(TWO_PANELS)
676        );
677        assert!(
678            aria_html(TWO_PANELS).contains("hidden"),
679            "{}",
680            aria_html(TWO_PANELS)
681        );
682    }
683
684    #[test]
685    fn a_typed_div_becomes_a_tab_strip() {
686        let out = html(TWO_PANELS);
687        assert!(out.contains("class=\"code-group\""), "{out}");
688        assert_eq!(out.matches("type=\"radio\"").count(), 2, "{out}");
689        assert_eq!(out.matches("code-group-panel").count(), 2, "{out}");
690    }
691
692    #[test]
693    fn the_language_names_the_tab() {
694        let out = html(TWO_PANELS);
695        assert!(out.contains(">js</label>"), "{out}");
696        assert!(out.contains(">php</label>"), "{out}");
697        assert!(out.contains("class=\"language-js\""), "{out}");
698    }
699
700    #[test]
701    fn the_first_tab_opens_when_no_block_claims_it() {
702        let out = html(TWO_PANELS);
703        assert_eq!(out.matches(" checked>").count(), 1, "{out}");
704        let checked = out.find(" checked>").unwrap();
705        let second = out.find("-tab-2").unwrap();
706        assert!(checked < second, "the FIRST tab should be checked: {out}");
707    }
708
709    #[test]
710    fn a_class_carrying_div_is_a_group_too() {
711        let out = html("{.code-group}\n:::\n``` js\nlet a = 1\n```\n:::");
712        assert!(out.contains("type=\"radio\""), "{out}");
713    }
714
715    #[test]
716    fn a_group_with_no_code_block_is_left_to_the_core_renderer() {
717        let out = html("::: code-group\nJust prose.\n:::");
718        assert!(!out.contains("type=\"radio\""), "{out}");
719        assert!(out.contains("Just prose."), "{out}");
720    }
721
722    #[test]
723    fn an_author_class_survives_beside_the_wrapper_class() {
724        let out = html("{.code-group .tight}\n:::\n``` js\nlet a = 1\n```\n:::");
725        assert!(out.contains("class=\"code-group tight\""), "{out}");
726    }
727
728    #[test]
729    fn static_mode_drops_the_radios_for_headed_sections() {
730        let out = static_html(TWO_PANELS);
731        assert!(!out.contains("type=\"radio\""), "{out}");
732        assert_eq!(out.matches("<section").count(), 2, "{out}");
733        assert!(
734            out.contains("<h3 class=\"code-group-label\">js</h3>"),
735            "{out}"
736        );
737    }
738
739    #[test]
740    fn two_groups_in_one_document_get_distinct_ids() {
741        let out = html(&format!("{TWO_PANELS}\n\n{TWO_PANELS}"));
742        let ids: Vec<&str> = out
743            .match_indices("name=\"")
744            .map(|(i, _)| &out[i..i + 24])
745            .collect();
746        assert!(ids.len() >= 4, "{out}");
747        assert!(
748            ids.iter().any(|id| !id.contains("codegroup\"")),
749            "a second group must not reuse the first group's name: {out}"
750        );
751    }
752
753    /// The names carve-js and carve-php emit, asserted literally. The test
754    /// above cannot see this defect: it only asks that SOME name differs from
755    /// `codegroup`, which held while the first group was named `codegroup` and
756    /// the second `codegroup-2`.
757    #[test]
758    fn the_first_group_is_numbered_like_the_other_engines() {
759        let out = html(&format!("{TWO_PANELS}\n\n{TWO_PANELS}"));
760        assert!(out.contains("name=\"codegroup-1\""), "{out}");
761        assert!(out.contains("id=\"codegroup-1-tab-1\""), "{out}");
762        assert!(out.contains("for=\"codegroup-1-tab-1\""), "{out}");
763        assert!(out.contains("name=\"codegroup-2\""), "{out}");
764        assert!(
765            !out.contains("name=\"codegroup\""),
766            "the bare prefix is carve-rs-only: {out}"
767        );
768    }
769
770    /// A group's number depends on how many groups precede it, and on nothing
771    /// else. Reserving the bare prefix made an unrelated `{#codegroup}` in the
772    /// document push the FIRST group to `codegroup-2`.
773    #[test]
774    fn an_unrelated_explicit_id_does_not_renumber_the_group() {
775        let out = html(&format!("# H {{#codegroup}}\n\n{TWO_PANELS}"));
776        assert!(out.contains("name=\"codegroup-1\""), "{out}");
777    }
778
779    /// Extensions §13.6: the wrapper's own two tags take the ambient
780    /// indentation, and every line between them is the cross-impl contract at
781    /// COLUMN 0. The second document opens a heading section first, so the
782    /// wrapper is indented and a padded inner line shows - at top level the
783    /// ambient column is 0 and this class cannot appear.
784    #[test]
785    fn inner_lines_sit_at_column_zero_wherever_the_group_was_written() {
786        for source in [TWO_PANELS.to_string(), format!("# H\n\n{TWO_PANELS}")] {
787            for out in [html(&source), aria_html(&source)] {
788                let inner: Vec<&str> = out
789                    .lines()
790                    .filter(|line| {
791                        let line = line.trim_start();
792                        line.starts_with("<input")
793                            || line.starts_with("<label")
794                            || line.starts_with("<button")
795                            || line.contains("code-group-panel")
796                    })
797                    .collect();
798                assert!(inner.len() >= 2, "no inner lines to measure: {out}");
799                for line in inner {
800                    assert!(
801                        !line.starts_with(' '),
802                        "an inner line is indented: {line:?} in {out}"
803                    );
804                }
805            }
806        }
807    }
808
809    #[test]
810    fn wrapper_tags_share_a_column_at_each_nesting_depth() {
811        for source in [
812            TWO_PANELS.to_string(),
813            format!("# H\n\n{TWO_PANELS}"),
814            format!("# H\n\n## Subheading\n\n{TWO_PANELS}"),
815            format!("> {}", TWO_PANELS.replace('\n', "\n> ")),
816            format!("- item\n\n  {}", TWO_PANELS.replace('\n', "\n  ")),
817        ] {
818            for out in [html(&source), aria_html(&source), static_html(&source)] {
819                let opener = out
820                    .lines()
821                    .find(|line| line.trim_start().starts_with("<div class=\"code-group\""))
822                    .expect("extension wrapper opener");
823                let closer = out
824                    .lines()
825                    .rev()
826                    .find(|line| line.trim_start() == "</div>")
827                    .expect("extension wrapper closer");
828                assert_eq!(
829                    opener.len() - opener.trim_start().len(),
830                    closer.len() - closer.trim_start().len(),
831                    "wrapper tags occupy different columns: {out}"
832                );
833            }
834        }
835    }
836}