Skip to content

Instantly share code, notes, and snippets.

@iambriansreed
Created October 28, 2024 17:10
Show Gist options
  • Select an option

  • Save iambriansreed/ae8d99dee3215ca7094aa800e39a26fd to your computer and use it in GitHub Desktop.

Select an option

Save iambriansreed/ae8d99dee3215ca7094aa800e39a26fd to your computer and use it in GitHub Desktop.
A simple Ladle addon hook that can be used to hide and show addons on the fly. I don't want users to be able to view source on pure documentation pages for example.
import { useCallback, useEffect, useState } from 'react';
type AddonKey =
| 'control'
| 'theme'
| 'mode'
| 'width'
| 'rtl'
| 'source'
| 'a11y'
| 'ladle'
| 'action';
const ADDONS_META: readonly {
key: AddonKey;
element: () => HTMLElement | null | undefined;
}[] = [
{
key: 'control',
element: () =>
document.querySelector(
'[aria-label="Explore different versions of this story through controls."]',
)?.parentElement,
},
{
key: 'theme',
element: () =>
document.querySelector('[aria-label="Switch to light theme."]')
?.parentElement,
},
{
key: 'mode',
element: () =>
document.querySelector(
'[aria-label="Open fullscreen mode. Can be toggled by pressing f."]',
)?.parentElement,
},
{
key: 'width',
element: () =>
document.querySelector('[aria-label="Change the story viewport."]')
?.parentElement,
},
{
key: 'rtl',
element: () =>
document.querySelector(
'[aria-label="Switch text direction to right to left."]',
)?.parentElement,
},
{
key: 'source',
element: () =>
document.querySelector('[aria-label="Show the story source code."]')
?.parentElement,
},
{
key: 'a11y',
element: () =>
document.querySelector('[aria-label="Show accessibility report."]')
?.parentElement,
},
{
key: 'ladle',
element: () =>
document.querySelector('[aria-label="Get more information about Ladle."]')
?.parentElement,
},
{
key: 'action',
element: () =>
document.querySelector('[aria-label="Log of events triggered by user."]')
?.parentElement,
},
] as const;
export default function useAddonManager() {
const [addons, setAddons] = useState<Partial<Record<AddonKey, HTMLElement>>>(
{},
);
useEffect(() => {
setAddons(
Object.fromEntries(
ADDONS_META.flatMap(({ key, element }) => {
const el = element();
if (!el) return [];
return [[key, el]];
}),
),
);
}, []);
return {
hideAddons: useCallback(
(hideAddons: AddonKey[]) => {
(Object.entries(addons) as [AddonKey, HTMLElement][]).forEach(
([key, element]) => {
const hide = hideAddons.includes(key);
element.style.display = hide ? 'none' : '';
element.setAttribute('aria-hidden', hide ? 'true' : '');
},
);
},
[addons],
),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment