Files
o2o-weather/frontend/src/b/ui.tsx
T

221 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState, type CSSProperties, type ReactNode } from 'react'
import { Link } from 'react-router'
import { cx } from '../lib/utils'
import { useCarousel, type Carousel } from './carousel'
import { AVATAR_COLORS, iconSrc, moodEmoji, naverMap, type Load } from './lib'
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
export function Ic({ name, className, alt = '', style }: IcProps) {
const src = iconSrc(name)
if (!src) return <span aria-hidden className={cx('block', className)} style={style} />
return <img src={src} alt={alt} className={cx('block', className)} style={style} decoding="async" />
}
/** 사진 출처 표기 (공공누리 조건). 사진 위에서도 읽히게 반투명 배경. 위치는 className 으로 */
export function Credit({ text, className = 'right-1 bottom-1' }: { text: string; className?: string }) {
return <small className={cx('pointer-events-none absolute z-[1] rounded-[5px] bg-[rgb(16_20_34/0.5)] px-1 py-px text-[9px] leading-tight font-semibold whitespace-nowrap text-white', className)}>{text}</small>
}
type ThumbProps = { image?: string | null; icon: string; credit?: string | null; className?: string; iconClassName?: string; creditClassName?: string; children?: ReactNode }
/** 사진이 있으면 사진(+출처), 없거나 못 불러오면 아이콘 */
export function Thumb({ image, icon, credit, className, iconClassName, creditClassName, children }: ThumbProps) {
const [failed, setFailed] = useState<string | null>(null)
const photo = image && image !== failed ? image : null
return (
<span className={cx('relative grid place-items-center overflow-hidden', className)}>
{photo ? <img src={photo} alt="" loading="lazy" decoding="async" onError={() => setFailed(photo)} className="absolute inset-0 size-full object-cover" /> : <Ic name={icon} className={iconClassName} />}
{photo && credit && <Credit text={credit} className={creditClassName} />}
{children}
</span>
)
}
type AvatarProps = { character: string; color?: string | null; mood?: string | null; size?: number; className?: string }
/** 프로필 동그라미: 고른 배경색 위에 캐릭터, 오른쪽 위에 오늘 기분 */
export function Avatar({ character, color, mood, size = 34, className }: AvatarProps) {
const emoji = moodEmoji(mood)
return (
<span className={cx('relative inline-grid shrink-0 place-items-center rounded-full', className)} style={{ width: size, height: size, background: AVATAR_COLORS[color ?? ''] ?? AVATAR_COLORS.orange }}>
<Ic name={character} style={{ width: size * 0.7 }} />
{emoji && (
<span className="absolute -top-1 -right-1 grid place-items-center rounded-full bg-white leading-none shadow-[0_1px_3px_rgb(40_48_74/0.25)]" style={{ width: size * 0.48, height: size * 0.48, fontSize: size * 0.3 }} aria-hidden="true">
{emoji}
</span>
)}
</span>
)
}
type SecProps = { title: string; sub?: ReactNode; more?: { to: string; label?: string }; className?: string }
export function Sec({ title, sub, more, className }: SecProps) {
return (
<div className={cx('flex items-end justify-between px-4 pt-[22px] pb-1.5', className)}>
<div>
<h2 className="m-0 font-jua text-[21px] font-normal">{title}</h2>
{sub && <p className="mt-0.5 text-[13px] font-semibold text-(--ink2)">{sub}</p>}
</div>
{more && (
<Link to={more.to} className="text-[13px] font-bold text-(--ink2)">
{more.label ?? '전체 보기'}
</Link>
)}
</div>
)
}
/** PC(마우스)에서만 보이는 좌우 화살표 */
export function Arrows({ api, prev, next, className }: { api: Carousel; prev: boolean; next: boolean; className?: string }) {
const btn = 'absolute top-1/2 z-[3] hidden size-8 -translate-y-1/2 cursor-pointer place-items-center rounded-full bg-white/90 text-lg font-extrabold text-[#28304a] shadow-[0_4px_10px_rgb(40_48_74/0.18)] pointer-fine:grid'
return (
<>
{prev && (
<button type="button" data-noshot onClick={() => api?.scrollPrev()} aria-label="이전" className={cx(btn, 'left-1.5', className)}>
‹
</button>
)}
{next && (
<button type="button" data-noshot onClick={() => api?.scrollNext()} aria-label="다음" className={cx(btn, 'right-1.5', className)}>
›
</button>
)}
</>
)
}
const STRIP = { align: 'start', dragFree: true, containScroll: 'trimSnaps' } as const
/** Rail 과 같은 틀(여백·간격)로 스켈레톤 칸을 늘어놓는다. 넘기기·화살표는 없음 */
export function SkelRail({ children, className }: { children: ReactNode; className?: string }) {
return (
<div className="overflow-hidden" aria-hidden="true">
<div className={cx('flex gap-2.5 px-4 pt-3 pb-1 *:shrink-0', className)}>{children}</div>
</div>
)
}
export function Rail({ children, className, label }: { children: ReactNode; className?: string; label?: string }) {
const { ref, api, prev, next } = useCarousel(STRIP)
return (
<div className="relative" role={label ? 'group' : undefined} aria-label={label}>
<div ref={ref} className="overflow-hidden">
<div className={cx('flex gap-2.5 px-4 pt-3 pb-1 *:shrink-0', className)}>{children}</div>
</div>
<Arrows api={api} prev={prev} next={next} />
</div>
)
}
// 보이는 크기는 두고 누르는 영역만 가운데 44×44로 넓힌다 (위치 지정된 요소에 붙인다)
export const TAP44 = 'after:absolute after:top-1/2 after:left-1/2 after:size-11 after:-translate-1/2'
type ChipsProps<K extends string> = { items: readonly (readonly [K, string])[]; value: K; onChange: (k: K) => void; label: string; disabled?: boolean }
export function Chips<K extends string>({ items, value, onChange, label, disabled }: ChipsProps<K>) {
return (
<ChipStrip label={label}>
{items.map(([k, l]) => (
<button
key={k}
type="button"
aria-pressed={value === k}
disabled={disabled}
onClick={() => onChange(k)}
className={cx('shrink-0 cursor-pointer rounded-full disabled:cursor-default px-3.5 py-[7px] text-[13.5px] font-bold', value === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2) shadow-[inset_0_-3px_0_var(--shade)]')}
>
{l}
</button>
))}
</ChipStrip>
)
}
function ChipStrip({ children, label }: { children: ReactNode; label: string }) {
const { ref, api, prev, next } = useCarousel(STRIP)
return (
<div className="relative" role="group" aria-label={label}>
<div ref={ref} className="overflow-hidden">
<div className="flex gap-2 px-4 pt-3 pb-0.5">{children}</div>
</div>
<Arrows api={api} prev={prev} next={next} className="mt-[5px] size-7 text-base" />
</div>
)
}
type SkelProps = { className?: string; shape?: boolean; style?: CSSProperties }
/**
* 불러오는 동안 자리만 잡는 막대. 기본은 글자 자리: 감싼 글자 요소 안에 넣으면 그 줄 높이(1lh)를 그대로 차지한다.
* shape 면 className 으로 준 크기의 블록(사진·동그라미 자리).
*/
export function Skel({ className, shape = false, style }: SkelProps) {
return (
<span
aria-hidden="true"
style={style}
className={cx('bg-(--skel) motion-safe:animate-pulse', shape ? 'block' : 'inline-block h-[1lh] max-w-full rounded-full bg-clip-content py-[0.22lh] align-top', className)}
/>
)
}
type StateProps = { load: Load; onRetry?: () => void; empty?: string; className?: string; hold?: ReactNode }
/**
* 실패·빈 목록 안내. 불러오는 중엔 그리지 않는다(그 자리는 스켈레톤).
* hold 에 스켈레톤을 주면 그 크기를 보이지 않게 깔고 안내를 그 위에 띄운다 — 로딩·실패·빈 상태의 자리 크기가 같다.
* 이때 className 은 안내 상자의 위치(스켈레톤 바깥 여백만큼 inset).
*/
export function StateBox({ load, onRetry, empty, className, hold }: StateProps) {
const failed = load === 'error' || load === 'retrying'
const text = failed ? '정보를 불러오지 못했어요.' : load === 'ready' ? empty : undefined
if (!text) return null
const box = (
<div
className={cx('flex flex-col items-center justify-center gap-2 rounded-[22px] bg-white px-4 py-6 text-center text-[13.5px] font-semibold text-(--ink2) shadow-[inset_0_-5px_0_var(--shade)]', hold ? cx('absolute', className ?? 'inset-x-3 top-3 bottom-0') : (className ?? 'mx-3 mt-3'))}
role={load === 'error' ? 'alert' : 'status'}
>
<span>{text}</span>
{failed && onRetry && (
<button type="button" onClick={onRetry} disabled={load === 'retrying'} className="cursor-pointer rounded-full bg-(--ink) px-4 py-1.5 text-[13px] font-bold text-white disabled:cursor-default disabled:opacity-60">
{load === 'retrying' ? '다시 불러오는 중…' : '다시 시도'}
</button>
)}
</div>
)
if (!hold) return box
return (
<div className="relative flow-root">
<div className="invisible" aria-hidden="true" inert>
{hold}
</div>
{box}
</div>
)
}
/** 줄 목록 (라벨 · 값) */
/** 위치가 정해진 장소 이름. 누르면 네이버 지도가 새 탭으로 열린다 */
export function MapLink({ place, children, className }: { place: string; children: ReactNode; className?: string }) {
return (
<a href={naverMap(place)} target="_blank" rel="noopener noreferrer" aria-label={`${place}, 네이버 지도에서 보기`} className={cx('underline decoration-dotted decoration-1 underline-offset-[3px]', className)}>
{children}
</a>
)
}
export function Rows({ rows, dark = false }: { rows: { label: string; value: string; place?: string | null }[]; dark?: boolean }) {
return (
<div className="mt-auto flex flex-col">
{rows.map((r) => (
<div key={r.label} className={cx('flex justify-between gap-2.5 border-b-2 py-2.5 font-bold last:border-b-0', dark ? 'border-white/18' : 'border-[rgb(40_48_74/0.08)]')}>
<span>{r.label}</span>
<b className="text-right font-jua text-[17px] font-normal">{r.place ? <MapLink place={r.place}>{r.value}</MapLink> : r.value}</b>
</div>
))}
</div>
)
}