diff options
author | Jacob Fenton <jacob+github@dfenton.xyz> | 2024-04-01 09:42:03 -0500 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2024-04-01 15:52:44 +0100 |
commit | 48934416c3b924c5ae0e7dacc58c7e162b4dad8b (patch) | |
tree | 8849ad7cda3ec78bf6c0fbbd431ef70cf65b2ac5 | |
parent | e3cb9795f50a25c57344c00ff58c55dc3d0bfeca (diff) | |
download | tour-48934416c3b924c5ae0e7dacc58c7e162b4dad8b.tar.gz tour-48934416c3b924c5ae0e7dacc58c7e162b4dad8b.zip |
Add left/right arrow key handlers for easier navigation.
-rw-r--r-- | src/tour.gleam | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/src/tour.gleam b/src/tour.gleam index 2a64561..b1c13d1 100644 --- a/src/tour.gleam +++ b/src/tour.gleam @@ -594,6 +594,37 @@ pub fn theme_picker_script() -> Html { ) } +pub fn arrow_keys_navigation_script( + next: Option(String), + prev: Option(String), +) -> Html { + let to_handler = fn(maybe_link) { + case maybe_link { + None -> "null" + Some(link) -> "() => { window.location.href = '" <> link <> "' }" + } + } + + html_dangerous_inline_script(" + const keyHandlers = { + 'ArrowLeft': " <> to_handler(prev) <> ", + 'ArrowRight': " <> to_handler(next) <> ", + } + + document.addEventListener('keydown', function(event) { + // Don't hijack arrow keys when focus is on the code textarea. + if (document.querySelector('textarea.codeflask__textarea') === document.activeElement) { + return; + } + + const handler = keyHandlers[event.key]; + if (handler !== undefined && handler !== null) { + handler(); + } + }) + ", ScriptOptions(module: True, defer: False), []) +} + // Page Renders /// Renders a Lesson's page @@ -641,6 +672,7 @@ fn lesson_page_render(lesson: Lesson) -> String { scripts: ScriptConfig( body: [ theme_picker_script(), + arrow_keys_navigation_script(lesson.next, lesson.previous), h("script", [#("type", "gleam"), #("id", "code")], [ htmb.dangerous_unescaped_fragment(string_builder.from_string( lesson.code, |