From 8d4cfa025484ea5740a2dbc317a06e625b24c991 Mon Sep 17 00:00:00 2001 From: Andre Wiggins Date: Sun, 29 Dec 2024 16:00:31 -0600 Subject: [PATCH] Make query param switch a generic util --- src/pages/events/[id].astro | 20 +++++--------------- src/scripts/queryParamSwitch.ts | 32 ++++++++++++++++++++++++++++++++ src/styles/main.css | 4 ++++ src/utils/markdown.ts | 5 +++++ 4 files changed, 46 insertions(+), 15 deletions(-) create mode 100644 src/scripts/queryParamSwitch.ts create mode 100644 src/utils/markdown.ts diff --git a/src/pages/events/[id].astro b/src/pages/events/[id].astro index 26131c8..02331db 100644 --- a/src/pages/events/[id].astro +++ b/src/pages/events/[id].astro @@ -187,16 +187,8 @@ let location = event.location ?? null - - diff --git a/src/scripts/queryParamSwitch.ts b/src/scripts/queryParamSwitch.ts new file mode 100644 index 0000000..0648828 --- /dev/null +++ b/src/scripts/queryParamSwitch.ts @@ -0,0 +1,32 @@ +/** + * Show certain elements only when certain query parameters are available. This + * function takes an array of queryKey to element selector mappings and shows + * the element corresponding to the first queryKey that is present in the URL. + * + * They are mutually exclusive, so only one element will be shown at a time. + * + * A key of empty string will represent the default case, which will be shown + * when no other query parameters are present. + * + * @param cases - A mapping of query parameter values to element selectors. + */ +export function initializeSwitch( + cases: Array<[queryKey: string, selector: string]>, +): void { + const searchParams = new URLSearchParams(location.search) + const queryKey = + cases.map(([key]) => key).find(key => searchParams.has(key)) || '' + + for (const [key, selector] of cases) { + const elements = document.querySelectorAll(selector) + for (const element of elements) { + if (key === queryKey) { + element.removeAttribute('hidden') + element.style.display = 'block' + } else { + element.setAttribute('hidden', '') + element.style.display = 'none' + } + } + } +} diff --git a/src/styles/main.css b/src/styles/main.css index 7ecc706..24f27aa 100644 --- a/src/styles/main.css +++ b/src/styles/main.css @@ -72,6 +72,10 @@ a[target='_blank']:after { content: '\f35d'; } +[hidden] { + display: none; +} + #page { padding: 8px 24px; } diff --git a/src/utils/markdown.ts b/src/utils/markdown.ts new file mode 100644 index 0000000..7e7e91c --- /dev/null +++ b/src/utils/markdown.ts @@ -0,0 +1,5 @@ +import { marked } from 'marked' + +export function toHTML(markdown: string): string { + return marked(markdown, { async: false }) +}