Repository navigation
Expand file tree
/
Copy pathdocument-name.tsx
More file actions
84 lines (84 loc) · 2.39 KB
/
Copy pathdocument-name.tsx
File metadata and controls
84 lines (84 loc) · 2.39 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { TitleInput } from "./title-input.js";
import { useEffect, useRef, useState } from "react";
import { api, type Resource } from "@web/shared/api.js";
import { Feedback } from "@web/shared/components/feedback.js";
export function DocumentName({
resource,
changed,
}: {
resource: Resource;
changed(): void;
}) {
const [editing, setEditing] = useState(false),
[value, setValue] = useState(resource.title),
[width, setWidth] = useState<number>(),
[error, setError] = useState("");
const saving = useRef(false),
cancel = useRef(false);
useEffect(() => {
if (!editing) setValue(resource.title);
}, [resource.title, editing]);
async function save() {
if (saving.current || cancel.current) return;
const title = value.trim() || "未命名";
if (title === resource.title) {
setEditing(false);
return;
}
saving.current = true;
try {
await api(`/resources/${resource.id}`, "PATCH", {
title,
version: resource.version,
});
setEditing(false);
changed();
setError("");
} catch (e) {
setError((e as Error).message);
} finally {
saving.current = false;
}
}
return (
<>
{editing ? (
<div className="document-name-field" onBlur={event => { if (!event.currentTarget.contains(event.relatedTarget)) void save() }}>
<TitleInput
className="document-name-editor"
style={{ width }}
autoFocus
maxLength={160}
value={value}
aria-label="修改文档标题"
onFocus={(e) => e.target.select()}
onValueChange={setValue}
onKeyDown={(e) => {
if (e.nativeEvent.isComposing || e.keyCode === 229) return;
if (e.key === "Enter") {
e.preventDefault();
void save();
}
if (e.key === "Escape") {
cancel.current = true;
setEditing(false);
}
}}
/></div>
) : (
<button
className="document-title-edit"
title={resource.title + " · 点击修改标题"}
onClick={(e) => {
setWidth(e.currentTarget.getBoundingClientRect().width);
cancel.current = false;
setEditing(true);
}}
>
{resource.title}
</button>
)}
<Feedback message={error} tone="error" />
</>
);
}