Make code blocks keyboard focusable

It would be nice if the code blocks would be keyboard focusable so they can be scrolled without mouse interaction.

This could be achieved for example by adding tabindex="0" to the <pre> element.

Keyboard accessible - Interactive elements must be focusable

For now I’m working around this with a custom pre shortcode:

<pre tabindex="0"><code>{{body}}
</code></pre>

but this has the downside of loosing the option of automatic syntax highlighting.

1 Like

There is no way to do that except enhancing Zola itself I suppose. Check mod.rs and fence.rs.

BTW, are code blocks interactive elements?

They become interactive when overflow scrollbars appear, I guess an alternative workaround would be to disable overflow in CSS.

I see. Do you think <pre> should have tabindex=”0” unconditionally? That’d be easy.

diff --git a/components/markdown/src/codeblock/mod.rs b/components/markdown/src/codeblock/mod.rs
index 2a632b6d..d8b25ab4 100644
--- a/components/markdown/src/codeblock/mod.rs
+++ b/components/markdown/src/codeblock/mod.rs
@@ -19,7 +19,7 @@ fn opening_html(
     line_numbers: bool,
     enable_copy: bool,
 ) -> String {
-    let mut html = String::from("<pre");
+    let mut html = String::from("<pre tabindex=\"0\"");
     if line_numbers {
         html.push_str(" data-linenos");
     }

Well, you could just do a

Array.from(document.getElementsByTagName("pre")).forEach(e => e.tabIndex = "0");

at page load. Not ideal, but gets the job done, and it’s a fairly marginal requirement.

Personally I’d say yes, whether that would be acceptable for the maintainers I do not know.