dialog.tsx
2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 应用内的输入框 / 确认框,替代 window.prompt / window.confirm ——
* 后者在内嵌浏览器、部分企业浏览器策略下会被禁用,而且样式和系统完全脱节。
* 用法:`const v = await promptText("撤销原因")`(取消返回 null),`if (await confirmDialog("删除?"))`。
*/
import { useEffect, useRef, useState } from "react";
import { create } from "zustand";
import { Modal } from "@/components/ui";
interface Req { kind: "prompt" | "confirm"; title: string; desc?: string; placeholder?: string; initial?: string;
danger?: boolean; resolve: (v: string | null) => void }
const useDialog = create<{ req: Req | null; set: (r: Req | null) => void }>((set) => ({ req: null, set: (req) => set({ req }) }));
export function promptText(title: string, opts: { desc?: string; placeholder?: string; initial?: string } = {}): Promise<string | null> {
return new Promise((resolve) => useDialog.getState().set({ kind: "prompt", title, ...opts, resolve }));
}
export async function confirmDialog(title: string, opts: { desc?: string; danger?: boolean } = {}): Promise<boolean> {
const v = await new Promise<string | null>((resolve) => useDialog.getState().set({ kind: "confirm", title, ...opts, resolve }));
return v !== null;
}
export function DialogHost() {
const { req, set } = useDialog();
const [val, setVal] = useState("");
const input = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (req) { setVal(req.initial || ""); window.setTimeout(() => input.current?.focus(), 30); }
}, [req]);
if (!req) return null;
const done = (v: string | null) => { set(null); req.resolve(v); };
return (
<Modal open onClose={() => done(null)} title={req.title} desc={req.desc} width="max-w-md"
footer={<>
<button className="btn" onClick={() => done(null)}>取消</button>
<button className={req.danger ? "btn btn-danger" : "btn btn-primary"}
disabled={req.kind === "prompt" && !val.trim()}
onClick={() => done(req.kind === "prompt" ? val.trim() : "ok")}>确定</button>
</>}>
{req.kind === "prompt" ? (
<textarea ref={input} className="input min-h-[70px]" value={val} placeholder={req.placeholder}
onChange={(e) => setVal(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey && val.trim()) { e.preventDefault(); done(val.trim()); } }} />
) : <p className="text-body text-muted">{req.desc ? "" : "请确认这个操作。"}</p>}
</Modal>
);
}