Files
readest/apps/readest-app/src/components/Dialog.tsx
T
Huang Xin 772bb73b46 ui/ux: codify design system and migrate settings to shared primitives (#4116)
* ui/ux: codify design system and migrate settings to shared primitives

Document Readest's design language in DESIGN.md (Adwaita-aligned, e-ink-first,
RTL-correct) and migrate every settings panel onto a small set of primitives
(BoxedList, SettingsRow, SettingsSwitchRow, SettingsSelect, SettingsInput,
NavigationRow, Tips, SubPageHeader). AGENTS.md links to DESIGN.md so contributors
land there before inventing new chassis classes.

Replace the standalone KOReader/Readwise/Hardcover Config dialogs with a single
Integrations panel (Reading Sync + Content Sources sub-pages). The reader's
BookMenu now hides each provider until it's configured, and Hardcover's per-book
"Enable for This Book" toggle is dropped — there's no auto-sync to gate, so the
flag was just extra clicks.

Refresh highlight colors (two-trigger swatch + label, translatable default
names), background texture / theme color selectors (border-current keeps
selection legible on any backdrop), CustomFonts/CustomDictionaries (quiet
list-extension style + shared Tips primitive), the OPDS catalog manager
(debounced auto-download, right-aligned Browse), Set PIN, and the KOSync
conflict resolver. Translate the ~30 new strings across all 33 locales.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* ui/ux: responsive typography, OPDS card polish, deep-link return paths

Restore the .settings-content responsive cascade (14px desktop / 16px
mobile) the legacy panels relied on by dropping hardcoded `text-sm`/`text-xs`
from the new primitives. Secondary text moves to em-relative `text-[0.85em]`
so it scales with the parent. Form controls (`<input>`, `<select>`) re-apply
the cascade explicitly via the `settings-content` class since browsers don't
inherit font-size onto form elements.

Extract `<SectionTitle>` primitive (caseless-language aware via
`isCaselessUILang`/`isCaselessLang`) and route every uppercase tag-style
header through it: BoxedList groups, Reading Sync, Content Sources, Theme
Color, Background Image, integration form labels, KOSyncResolver device
labels, and the OPDS My Catalogs / Popular Catalogs sections. CJK / Arabic
/ Hebrew / Indic / Thai / Tibetan locales bump to `1em` since `uppercase`
is a no-op on those scripts.

Redesign the OPDS My Catalogs cards: whole card becomes the browse trigger
(role='button'), edit/delete collapse into a 3-dot dropdown menu, and the
sync-status moves to a sub-line under Auto-download so the card height stays
constant whether the toggle is on/off or sync data has arrived.

Plumb a `from=settings-integrations` URL marker through the OPDS browser so
both manual close and auto-close-on-failure (preserved as `router.back()`
for transient failures, paired with a new `stashOPDSReturnTarget` helper)
return the user to Settings -> Integrations -> OPDS Catalogs sub-page
rather than the dialog's top level. Backed by new `requestedSubPage`
deep-link store field.

Skip the OPDS catalog passphrase prompt when credentials sync is disabled
-- `replicaPublish` already drops encrypted fields at the wire, so prompting
was both pointless and confusing.

Fix `SettingsDialog` calling `setRequestedPanel(null)` inside a `useState`
lazy initializer (zustand setter during render -> React warning); move the
clear into a one-shot `useEffect`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* ui/ux: opt Settings into OverlayScrollbars + caseless typography polish

Add an opt-in `useOverlayScroll` prop to `<Dialog>` that swaps the body's
native `overflow-y-auto` for `<OverlayScrollbarsComponent>` (autohide,
click-scroll, no native overlaid bars). SettingsDialog flips it on so the
long Layout / Color panels keep a visible, theme-aware scroll track on
Android / iOS webviews where native scrollbars auto-hide entirely. Other
short-modal callers stay on the native scrollbar.

Drop the `uppercase tracking-wider` SectionTitle styling for caseless
scripts and pair it with body-weight `font-medium` instead — those
typographic effects are no-ops on Han / Hangul / Devanagari / Thai etc.,
so a plain medium-weight body-size title reads more correctly than a
shrunken pseudo-uppercase one. SettingsRow / NavigationRow primary labels
follow the same rule (drop `font-medium` in caseless locales since the
inherited body weight already carries; CJK fonts bold poorly at body
size).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* ui/ux: SettingLabel primitive + KOSyncForm select polish + Tips alignment

Add `<SettingLabel>` primitive — caseless-aware row/field label that pairs
with `<SectionTitle>` (groups) for per-item labels. Cased scripts get
`font-medium`; caseless scripts (CJK / Arabic / Hebrew / Indic / Thai /
Tibetan) drop the weight since Han / Hangul / Devanagari etc. bold poorly
at body size. No font-size class so it inherits the `.settings-content`
14/16 cascade. Routed through `SettingsRow`, `NavigationRow`, and the
~12 ad-hoc inline `text-sm font-medium` callsites in AIPanel / FontPanel
/ ColorPanel / IntegrationsPanel / KOSync / Readwise / Hardcover forms.

Refactor KOSyncForm's Sync Strategy + Checksum Method rows onto the
shared `<SettingsSelect>` primitive — the inline 17-line div/select/
MdArrowDropDown chassis becomes a single SettingsSelect call with an
options array. Drops the unused MdArrowDropDown import and ~25 lines.

Fix Tips list-item alignment: callers traditionally pass `<li>` elements
(semantic) but the primitive was double-wrapping into `<li><span><li>...</li></span></li>` — invalid HTML, and the inner `<li>`'s
`display: list-item` broke line-wrap alignment on multi-line items.
Unwrap caller `<li>` to its content; add `flex-1` on the text span so
wrapped lines align under the first line instead of falling back to the
bullet column. Bullet container switches to `h-[1.4em]` so it tracks the
text line-height and pins to the first line's optical center via
`items-center` regardless of how much the content wraps.

DESIGN.md §5 typography updated to point primary-label callers at
`<SettingLabel>`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 17:46:25 +02:00

326 lines
11 KiB
TypeScript

import clsx from 'clsx';
import React, { ReactNode, useEffect, useRef, useState } from 'react';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-react';
import 'overlayscrollbars/overlayscrollbars.css';
import { MdArrowBackIosNew, MdArrowForwardIos } from 'react-icons/md';
import { useEnv } from '@/context/EnvContext';
import { useDrag } from '@/hooks/useDrag';
import { useThemeStore } from '@/store/themeStore';
import { useTranslation } from '@/hooks/useTranslation';
import { useDeviceControlStore } from '@/store/deviceStore';
import { useResponsiveSize } from '@/hooks/useResponsiveSize';
import { impactFeedback } from '@tauri-apps/plugin-haptics';
import { getDirFromUILanguage } from '@/utils/rtl';
import { eventDispatcher } from '@/utils/event';
import { Overlay } from './Overlay';
const VELOCITY_THRESHOLD = 0.5;
const SNAP_THRESHOLD = 0.2;
interface DialogProps {
id?: string;
isOpen: boolean;
children: ReactNode;
snapHeight?: number;
dismissible?: boolean;
header?: ReactNode;
title?: string;
className?: string;
bgClassName?: string;
boxClassName?: string;
contentClassName?: string;
/**
* Replace the body's native `overflow-y-auto` with OverlayScrollbars so
* the scrollbar is the floating, theme-aware kind instead of the host's
* native one (which Android/iOS webviews auto-hide entirely, leaving the
* user with no visible scrollbar). Opt-in per dialog — set true for
* long-content dialogs like Settings; leave false for short modals where
* native scrolling is fine.
*/
useOverlayScroll?: boolean;
onClose: () => void;
}
const Dialog: React.FC<DialogProps> = ({
id,
isOpen,
children,
snapHeight,
dismissible = true,
header,
title,
className,
bgClassName,
boxClassName,
contentClassName,
useOverlayScroll = false,
onClose,
}) => {
const _ = useTranslation();
const { appService } = useEnv();
const { systemUIVisible, statusBarHeight, safeAreaInsets } = useThemeStore();
const { acquireBackKeyInterception, releaseBackKeyInterception } = useDeviceControlStore();
const [isFullHeightInMobile, setIsFullHeightInMobile] = useState(!snapHeight);
const [isRtl] = useState(() => getDirFromUILanguage() === 'rtl');
const dialogRef = useRef<HTMLDialogElement>(null);
const previousActiveElementRef = useRef<HTMLElement | null>(null);
const iconSize22 = useResponsiveSize(22);
const isMobile = window.innerWidth < 640 || window.innerHeight < 640;
const handleKeyDown = (event: KeyboardEvent | CustomEvent) => {
if (event instanceof CustomEvent) {
if (event.detail.keyName === 'Back') {
onClose();
return true;
}
} else {
if (event.key === 'Escape') {
onClose();
}
event.stopPropagation();
}
return false;
};
useEffect(() => {
if (!isOpen) {
if (previousActiveElementRef.current) {
previousActiveElementRef.current.focus();
previousActiveElementRef.current = null;
}
return;
}
previousActiveElementRef.current = document.activeElement as HTMLElement;
setIsFullHeightInMobile(!snapHeight && isMobile);
window.addEventListener('keydown', handleKeyDown);
if (dialogRef.current) {
dialogRef.current.addEventListener('keydown', handleKeyDown);
}
if (appService?.isAndroidApp) {
acquireBackKeyInterception();
eventDispatcher.onSync('native-key-down', handleKeyDown);
}
const timer = setTimeout(() => {
if (dialogRef.current) {
dialogRef.current.focus();
}
}, 100);
return () => {
clearTimeout(timer);
window.removeEventListener('keydown', handleKeyDown);
if (appService?.isAndroidApp) {
releaseBackKeyInterception();
eventDispatcher.offSync('native-key-down', handleKeyDown);
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen]);
const handleDragMove = (data: { clientY: number; deltaY: number }) => {
if (!dismissible || !isMobile || !dialogRef.current) return;
const modal = dialogRef.current.querySelector('.modal-box') as HTMLElement;
const overlay = dialogRef.current.querySelector('.overlay') as HTMLElement;
const heightFraction = data.clientY / window.innerHeight;
const newTop = Math.max(0.0, Math.min(1, heightFraction));
if (modal && overlay) {
modal.style.height = '100%';
modal.style.transform = `translateY(${newTop * 100}%)`;
overlay.style.opacity = `${1 - heightFraction}`;
setIsFullHeightInMobile(data.clientY < 44);
modal.style.transition = `padding-top 0.3s ease-out`;
}
};
const handleDragEnd = (data: { velocity: number; clientY: number }) => {
if (!dismissible || !isMobile || !dialogRef.current) return;
const modal = dialogRef.current.querySelector('.modal-box') as HTMLElement;
const overlay = dialogRef.current.querySelector('.overlay') as HTMLElement;
if (!modal || !overlay) return;
const snapUpper = snapHeight ? 1 - snapHeight - SNAP_THRESHOLD : 0.5;
const snapLower = snapHeight ? 1 - snapHeight + SNAP_THRESHOLD : 0.5;
if (
data.velocity > VELOCITY_THRESHOLD ||
(data.velocity >= 0 && data.clientY >= window.innerHeight * snapLower)
) {
// dialog is dismissed
const transitionDuration = 0.15 / Math.max(data.velocity, 0.5);
modal.style.height = '100%';
modal.style.transition = `transform ${transitionDuration}s ease-out`;
modal.style.transform = 'translateY(100%)';
overlay.style.transition = `opacity ${transitionDuration}s ease-out`;
overlay.style.opacity = '0';
onClose();
setTimeout(() => {
modal.style.transform = 'translateY(0%)';
}, 300);
} else if (
snapHeight &&
data.clientY > window.innerHeight * snapUpper &&
data.clientY < window.innerHeight * snapLower
) {
// dialog is snapped
overlay.style.transition = `opacity 0.3s ease-out`;
overlay.style.opacity = `${1 - snapHeight}`;
modal.style.height = `${snapHeight * 100}%`;
modal.style.bottom = '0';
modal.style.transition = `transform 0.3s ease-out`;
modal.style.transform = '';
} else {
// dialog is opened without snap
setIsFullHeightInMobile(true);
modal.style.height = '100%';
modal.style.transition = `transform 0.3s ease-out`;
modal.style.transform = `translateY(0%)`;
overlay.style.opacity = '0';
}
if (appService?.hasHaptics) {
impactFeedback('medium');
}
};
const handleDragKeyDown = () => {};
const { handleDragStart } = useDrag(handleDragMove, handleDragKeyDown, handleDragEnd);
return (
<dialog
ref={dialogRef}
id={id ?? 'dialog'}
tabIndex={-1}
open={isOpen}
aria-label={title}
aria-hidden={!isOpen}
className={clsx(
'modal sm:min-w-90 z-50 h-full w-full !items-start !bg-transparent sm:w-full sm:!items-center',
className,
)}
dir={isRtl ? 'rtl' : undefined}
>
<Overlay
className={clsx(
'dialog-overlay z-10 bg-black/50 sm:bg-black/50',
appService?.hasRoundedWindow && 'rounded-window',
bgClassName,
)}
onDismiss={onClose}
/>
<div
className={clsx(
'modal-box settings-content absolute z-20 flex flex-col rounded-none rounded-tl-2xl rounded-tr-2xl p-0 sm:rounded-2xl',
'h-full max-h-full w-full max-w-full',
window.innerWidth < window.innerHeight
? 'sm:h-[50%] sm:w-3/4'
: 'sm:h-[65%] sm:w-1/2 sm:max-w-[600px]',
boxClassName,
)}
style={{
paddingTop:
appService?.hasSafeAreaInset && isFullHeightInMobile
? `${Math.max(safeAreaInsets?.top || 0, systemUIVisible ? statusBarHeight : 0)}px`
: '0px',
...(isMobile
? snapHeight
? { height: `${snapHeight * 100}%`, top: 'auto', bottom: 0 }
: { height: '100%', bottom: 0 }
: {}),
}}
>
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
<div
className={clsx(
'drag-handle mb-2 h-6 max-h-6 min-h-6 w-full cursor-row-resize items-center justify-center',
'transition-padding-top flex duration-300 ease-out sm:hidden',
)}
onMouseDown={handleDragStart}
onTouchStart={handleDragStart}
>
<div className='bg-base-content/50 h-1 w-10 rounded-full'></div>
</div>
<div className='dialog-header sticky top-1 z-10 flex items-center justify-between px-2 sm:pe-3 sm:ps-2'>
{header ? (
header
) : (
<div className='flex h-11 w-full items-center justify-between'>
<button
aria-label={_('Close')}
aria-hidden={!isOpen}
onClick={onClose}
disabled={!dismissible}
className={
'btn btn-ghost btn-circle flex h-8 min-h-8 w-8 hover:bg-transparent focus:outline-none disabled:bg-transparent sm:hidden'
}
>
{isRtl ? (
<MdArrowForwardIos size={iconSize22} />
) : (
<MdArrowBackIosNew size={iconSize22} />
)}
</button>
<div className='z-15 pointer-events-none absolute inset-0 flex h-11 items-center justify-center'>
<span className='line-clamp-1 text-center font-bold'>{title ?? ''}</span>
</div>
<button
aria-label={_('Close')}
aria-hidden={!isOpen}
onClick={onClose}
disabled={!dismissible}
className={
'bg-base-300/65 btn btn-ghost btn-circle ml-auto hidden h-6 min-h-6 w-6 focus:outline-none sm:flex'
}
>
<svg
xmlns='http://www.w3.org/2000/svg'
width='1em'
height='1em'
viewBox='0 0 24 24'
>
<path
fill='currentColor'
d='M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12z'
/>
</svg>
</button>
</div>
)}
</div>
{useOverlayScroll ? (
// OverlayScrollbarsComponent owns the scroller; the inner viewport
// gets `overflow-y-auto` automatically. Keep the same flex /
// padding chassis so the body still occupies remaining height
// and the children's horizontal rhythm is unchanged.
<OverlayScrollbarsComponent
className={clsx('text-base-content my-2 flex-grow px-6 sm:px-[10%]', contentClassName)}
options={{
scrollbars: { autoHide: 'scroll', clickScroll: true },
showNativeOverlaidScrollbars: false,
}}
defer
>
{children}
</OverlayScrollbarsComponent>
) : (
<div
className={clsx(
'text-base-content my-2 flex-grow overflow-y-auto px-6 sm:px-[10%]',
contentClassName,
)}
>
{children}
</div>
)}
</div>
</dialog>
);
};
export default Dialog;