-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathEditTags.tsx
76 lines (67 loc) · 2.08 KB
/
EditTags.tsx
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
import { createRef, Component } from "react"
import { action } from "mobx"
import { observer } from "mobx-react"
import { DbChartTagJoin } from "@ourworldindata/utils"
import {
ReactTags,
ReactTagsAPI,
Tag as TagAutocomplete,
} from "react-tag-autocomplete"
@observer
export class EditTags extends Component<{
tags: DbChartTagJoin[]
suggestions: DbChartTagJoin[]
onDelete: (index: number) => void
onAdd: (tag: DbChartTagJoin) => void
onSave: () => void
}> {
dismissable: boolean = true
reactTagsApi = createRef<ReactTagsAPI>()
@action.bound onClickSomewhere() {
if (this.dismissable) this.props.onSave()
this.dismissable = true
}
@action.bound onClick() {
this.dismissable = false
}
@action.bound onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
this.props.onSave()
}
}
onAdd = (tag: TagAutocomplete) => {
this.props.onAdd(convertAutocompleteTotag(tag))
}
componentDidMount() {
document.addEventListener("click", this.onClickSomewhere)
document.addEventListener("keydown", this.onKeyDown)
this.reactTagsApi.current?.input?.focus()
}
componentWillUnmount() {
document.removeEventListener("click", this.onClickSomewhere)
document.removeEventListener("keydown", this.onKeyDown)
}
render() {
const { tags, suggestions } = this.props
return (
<div className="EditTags" onClick={this.onClick}>
<ReactTags
selected={tags.map(convertTagToAutocomplete)}
suggestions={suggestions.map(convertTagToAutocomplete)}
activateFirstOption
onAdd={this.onAdd}
onDelete={this.props.onDelete}
ref={this.reactTagsApi}
/>
</div>
)
}
}
const convertTagToAutocomplete = (t: DbChartTagJoin) => ({
value: t.id,
label: t.name,
})
const convertAutocompleteTotag = (t: TagAutocomplete) => ({
id: t.value as number,
name: t.label,
})