forked from owid/owid-grapher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSiteRedirectsIndexPage.tsx
229 lines (218 loc) · 8.32 KB
/
SiteRedirectsIndexPage.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import cx from "classnames"
import React, { useContext, useEffect, useState } from "react"
import { useForm } from "react-hook-form"
import { BAKED_BASE_URL } from "../settings/clientSettings.js"
import { AdminAppContext } from "./AdminAppContext.js"
import { AdminLayout } from "./AdminLayout.js"
import { Link } from "./Link.js"
const SOURCE_PATTERN = /^\/$|^\/.*[^\/]+$/
const INVALID_SOURCE_MESSAGE =
"URL must start with a slash and cannot end with a slash, unless it's the root."
const TARGET_PATTERN = /^\/$|^(https?:\/\/|\/).*[^\/]+$/
const INVALID_TARGET_MESSAGE =
"URL must start with a slash or http(s):// and cannot end with a slash, unless it's the root."
type Redirect = {
id: number
source: string
target: string
}
function RedirectRow({
redirect,
onDelete,
}: {
redirect: Redirect
onDelete: (redirect: Redirect) => void
}) {
const targetUrl = new URL(redirect.target, BAKED_BASE_URL)
return (
<tr>
<td className="text-break">{redirect.source}</td>
<td className="text-break">
<a href={targetUrl.href} target="_blank" rel="noopener">
{redirect.target}
</a>
</td>
<td>
<button
className="btn btn-danger"
onClick={() => onDelete(redirect)}
>
Delete
</button>
</td>
</tr>
)
}
type FormData = {
source: string
target: string
}
export default function SiteRedirectsIndexPage() {
const { admin } = useContext(AdminAppContext)
const [redirects, setRedirects] = useState<Redirect[]>([])
const [error, setError] = useState<string | null>(null)
const {
register,
formState: { errors, isSubmitting },
handleSubmit,
setValue,
watch,
} = useForm<FormData>()
const source = watch("source")
useEffect(() => {
admin
.getJSON("/api/site-redirects.json")
.then((json) => {
setRedirects(json.redirects)
})
.catch(() => {
setError("Error loading redirects.")
})
}, [admin])
function validateTarget(value: string) {
if (value === source) {
return "Source and target cannot be the same."
}
return undefined
}
async function onSubmit({ source, target }: FormData) {
const sourceUrl = new URL(source, window.location.origin)
const sourcePath = sourceUrl.pathname
setValue("source", sourcePath)
setError(null)
const json = await admin.requestJSON(
"/api/site-redirects/new",
{ source: sourcePath, target },
"POST"
)
if (json.success) {
setRedirects([json.redirect, ...redirects])
} else {
setError("Error creating a redirect.")
}
}
async function handleDelete(redirect: Redirect) {
if (!window.confirm(`Delete the redirect from ${redirect.source}?`)) {
return
}
setError(null)
const json = await admin.requestJSON(
`/api/site-redirects/${redirect.id}`,
{},
"DELETE"
)
if (json.success) {
setRedirects(redirects.filter((r) => r.id !== redirect.id))
} else {
setError("Error deleting the redirect.")
}
}
return (
<AdminLayout title="Site Redirects">
<main>
<div className="row">
<div className="col-12 col-md-8">
<p>
This page is used to create and delete redirects for
the site. Don't use this page to create redirects
for charts, use the{" "}
<Link to="/redirects">chart redirects page</Link>{" "}
instead.
</p>
<p>
The source has to start with a slash and any query
parameters (/war-and-peace
<span className="redirect-emphasis">
?insight=insightid
</span>
) or fragments (/war-and-peace
<span className="redirect-emphasis">
#all-charts
</span>
) will be stripped, if present.
</p>
<p>
The target can point to a full URL at another domain
or a relative URL starting with a slash and both
query parameters and fragments are allowed.
</p>
<p>
To redirect to our homepage use a single slash as
the target.
</p>
</div>
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form-row">
<div className="form-group col-12 col-md-4">
<label>Source</label>
<input
className={cx("form-control", {
"is-invalid": errors.source,
})}
placeholder="/fertility-can-decline-extremely-fast"
{...register("source", {
required: "Please provide a source.",
pattern: {
value: SOURCE_PATTERN,
message: INVALID_SOURCE_MESSAGE,
},
})}
/>
<div className="invalid-feedback">
{errors.source?.message}
</div>
</div>
<div className="form-group col-12 col-md-4">
<label>Target</label>
<input
className={cx("form-control", {
"is-invalid": errors.target,
})}
placeholder="/fertility-rate"
{...register("target", {
required: "Please provide a target.",
pattern: {
value: TARGET_PATTERN,
message: INVALID_TARGET_MESSAGE,
},
validate: validateTarget,
})}
/>
<div className="invalid-feedback">
{errors.target?.message}
</div>
</div>
</div>
<button
className="btn btn-primary mb-3"
type="submit"
disabled={isSubmitting}
>
Create
</button>
{error && <div className="text-danger mb-3">{error}</div>}
</form>
<p>Showing {redirects.length} redirects</p>
<table className="table table-bordered">
<thead>
<tr>
<th>Source</th>
<th>Target</th>
<th></th>
</tr>
</thead>
<tbody>
{redirects.map((redirect) => (
<RedirectRow
key={redirect.id}
redirect={redirect}
onDelete={handleDelete}
/>
))}
</tbody>
</table>
</main>
</AdminLayout>
)
}