Dialog.tsx

6.4 KB v1.0
import { createContext, useCallback, useContext, useState, type ReactNode } from 'react'

type ConfirmOpts = {
  title?: string
  message: string
  confirmText?: string
  cancelText?: string
  danger?: boolean
}
type PromptOpts = {
  title?: string
  message: string
  placeholder?: string
  defaultValue?: string
  confirmText?: string
}
type SelectOpts = {
  title?: string
  message: string
  options: { value: string; label: string; hint?: string }[]
  confirmText?: string
}
type ToastOpts = { message: string; type?: 'success' | 'error' | 'info' }

type DialogApi = {
  confirm: (o: ConfirmOpts | string) => Promise<boolean>
  prompt: (o: PromptOpts | string) => Promise<string | null>
  select: (o: SelectOpts) => Promise<string | null>
  toast: (o: ToastOpts | string) => void
}

const Ctx = createContext<DialogApi | null>(null)

export function useDialog(): DialogApi {
  const ctx = useContext(Ctx)
  if (!ctx) throw new Error('useDialog 必须在 DialogProvider 内使用')
  return ctx
}

interface ConfirmState extends ConfirmOpts { resolve: (v: boolean) => void }
interface PromptState extends PromptOpts { resolve: (v: string | null) => void }
interface SelectState extends SelectOpts { resolve: (v: string | null) => void }

export function DialogProvider({ children }: { children: ReactNode }) {
  const [confirmState, setConfirmState] = useState<ConfirmState | null>(null)
  const [promptState, setPromptState] = useState<PromptState | null>(null)
  const [selectState, setSelectState] = useState<SelectState | null>(null)
  const [promptValue, setPromptValue] = useState('')
  const [selectValue, setSelectValue] = useState('')
  const [toasts, setToasts] = useState<(ToastOpts & { id: number })[]>([])

  const confirm = useCallback((o: ConfirmOpts | string) => new Promise<boolean>(resolve => {
    setConfirmState(typeof o === 'string' ? { message: o, resolve } : { ...o, resolve })
  }), [])

  const prompt = useCallback((o: PromptOpts | string) => new Promise<string | null>(resolve => {
    const opts = typeof o === 'string' ? { message: o } : o
    setPromptValue(opts.defaultValue || '')
    setPromptState({ ...opts, resolve })
  }), [])

  const select = useCallback((o: SelectOpts) => new Promise<string | null>(resolve => {
    setSelectValue(o.options[0]?.value || '')
    setSelectState({ ...o, resolve })
  }), [])

  const toast = useCallback((o: ToastOpts | string) => {
    const item = { ...(typeof o === 'string' ? { message: o } : o), id: Date.now() + Math.random() }
    setToasts(t => [...t, item])
    setTimeout(() => setToasts(t => t.filter(x => x.id !== item.id)), 3200)
  }, [])

  const closeConfirm = (v: boolean) => { confirmState?.resolve(v); setConfirmState(null) }
  const closePrompt = (v: string | null) => { promptState?.resolve(v); setPromptState(null) }
  const closeSelect = (v: string | null) => { selectState?.resolve(v); setSelectState(null) }

  const api: DialogApi = { confirm, prompt, select, toast }

  return (
    <Ctx.Provider value={api}>
      {children}

      {/* 确认框 */}
      {confirmState && (
        <div className="dlg-backdrop" onMouseDown={e => { if (e.target === e.currentTarget) closeConfirm(false) }}>
          <div className="dlg-card">
            <div className={`dlg-icon ${confirmState.danger ? 'danger' : 'info'}`}>
              {confirmState.danger ? '!' : '?'}
            </div>
            <h3>{confirmState.title || '请确认'}</h3>
            <p>{confirmState.message}</p>
            <div className="dlg-actions">
              <button className="btn btn-ghost" onClick={() => closeConfirm(false)}>
                {confirmState.cancelText || '取消'}
              </button>
              <button className={`btn ${confirmState.danger ? 'btn-danger' : 'btn-primary'}`}
                onClick={() => closeConfirm(true)} autoFocus>
                {confirmState.confirmText || '确定'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 输入框 */}
      {promptState && (
        <div className="dlg-backdrop" onMouseDown={e => { if (e.target === e.currentTarget) closePrompt(null) }}>
          <div className="dlg-card">
            <h3>{promptState.title || '请输入'}</h3>
            <p>{promptState.message}</p>
            <input className="dlg-input" value={promptValue}
              placeholder={promptState.placeholder} autoFocus
              onChange={e => setPromptValue(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') closePrompt(promptValue) }} />
            <div className="dlg-actions">
              <button className="btn btn-ghost" onClick={() => closePrompt(null)}>取消</button>
              <button className="btn btn-primary" onClick={() => closePrompt(promptValue)}>
                {promptState.confirmText || '确定'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 选择框 */}
      {selectState && (
        <div className="dlg-backdrop" onMouseDown={e => { if (e.target === e.currentTarget) closeSelect(null) }}>
          <div className="dlg-card">
            <h3>{selectState.title || '请选择'}</h3>
            <p>{selectState.message}</p>
            <div className="dlg-options">
              {selectState.options.length === 0 && <div className="empty-mini">暂无可选项</div>}
              {selectState.options.map(o => (
                <button key={o.value}
                  className={`dlg-option ${selectValue === o.value ? 'active' : ''}`}
                  onClick={() => setSelectValue(o.value)}>
                  <span className="radio-dot" />
                  <span className="dlg-option-label">{o.label}</span>
                  {o.hint && <small>{o.hint}</small>}
                </button>
              ))}
            </div>
            <div className="dlg-actions">
              <button className="btn btn-ghost" onClick={() => closeSelect(null)}>取消</button>
              <button className="btn btn-primary" disabled={!selectValue}
                onClick={() => closeSelect(selectValue)}>
                {selectState.confirmText || '确定'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 轻提示 */}
      <div className="toast-stack">
        {toasts.map(t => (
          <div key={t.id} className={`toast toast-${t.type || 'info'}`}>
            <span className="toast-icon">{t.type === 'error' ? '×' : t.type === 'success' ? '✓' : 'i'}</span>
            {t.message}
          </div>
        ))}
      </div>
    </Ctx.Provider>
  )
}