Files
Sable/src/app/components/theme/CssViewerButton.tsx
T
2026-07-15 12:46:20 -05:00

84 lines
2.3 KiB
TypeScript

import { useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { IconButton, Modal, Overlay, OverlayBackdrop, OverlayCenter } from 'folds';
import { Code, sizedIcon } from '$components/icons/phosphor';
import { TextViewer } from '$components/text-viewer';
import { ModalWide } from '$styles/Modal.css';
import { stopPropagation } from '$utils/keyboard';
type CssViewerButtonProps = {
title: string;
cssText?: string;
loadCssText?: () => Promise<string>;
ariaLabel: string;
};
export function CssViewerButton({ title, cssText, loadCssText, ariaLabel }: CssViewerButtonProps) {
const [open, setOpen] = useState(false);
const [loadedCssText, setLoadedCssText] = useState('');
const [loading, setLoading] = useState(false);
const viewerText = cssText?.trim() ? cssText : loadedCssText;
if (!cssText?.trim() && !loadCssText) return null;
const handleOpen = async () => {
if (viewerText) {
setOpen(true);
return;
}
if (!loadCssText || loading) return;
setLoading(true);
try {
const loaded = await loadCssText();
if (!loaded.trim()) return;
setLoadedCssText(loaded);
setOpen(true);
} finally {
setLoading(false);
}
};
return (
<>
<IconButton
size="300"
variant="Secondary"
fill="Soft"
outlined
radii="300"
aria-label={ariaLabel}
disabled={loading}
onClick={() => {
handleOpen().catch(() => undefined);
}}
>
{sizedIcon(Code, '200')}
</IconButton>
{open && (
<Overlay open backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setOpen(false),
clickOutsideDeactivates: true,
escapeDeactivates: stopPropagation,
}}
>
<Modal className={ModalWide} size="500">
<TextViewer
name={title}
text={viewerText}
langName="css"
requestClose={() => setOpen(false)}
/>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
)}
</>
);
}