-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathField.tsx
More file actions
397 lines (373 loc) · 11.2 KB
/
Copy pathField.tsx
File metadata and controls
397 lines (373 loc) · 11.2 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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import { useEffect, useMemo, useRef, useState } from 'react';
import type { Question } from '@rp2/shared';
import { isRenderable } from '@rp2/shared';
import { SignatureField } from './fields/SignatureField';
import { RankedList } from './fields/RankedList';
import { AvailabilityGrid } from './fields/AvailabilityGrid';
import { FileUploadField } from './fields/FileUploadField';
type Props = {
question: Question;
value: unknown;
disabled?: boolean | undefined;
onSave: (value: unknown) => void;
};
export function Field({ question, value, disabled, onSave }: Props) {
if (!isRenderable(question)) return <ComingSoon question={question} />;
switch (question.type) {
case 'short_text':
case 'email':
case 'phone':
return (
<TextInput
question={question}
value={value}
disabled={disabled}
onSave={onSave}
type={question.type === 'email' ? 'email' : question.type === 'phone' ? 'tel' : 'text'}
/>
);
case 'date':
return <TextInput question={question} value={value} disabled={disabled} onSave={onSave} type="date" />;
case 'timezone':
return <TimezoneInput question={question} value={value} disabled={disabled} onSave={onSave} />;
case 'long_text':
return <LongText question={question} value={value} disabled={disabled} onSave={onSave} />;
case 'single_select':
return <SingleSelect question={question} value={value} disabled={disabled} onSave={onSave} />;
case 'multi_select':
return <MultiSelect question={question} value={value} disabled={disabled} onSave={onSave} />;
case 'ranked':
return <RankedList question={question} value={value} disabled={disabled} onSave={onSave} />;
case 'availability_grid':
return <AvailabilityGrid question={question} value={value} disabled={disabled} onSave={onSave} />;
case 'file_upload':
return <FileUploadField question={question} disabled={disabled} />;
case 'signature':
return <SignatureField question={question} value={value} disabled={disabled} onSave={onSave} />;
default:
return null;
}
}
function Wrapper({
question,
children,
}: {
question: Question;
children: React.ReactNode;
}) {
return (
<div className="mb-8">
<label className="block">
<span className="block text-ink leading-snug">
{question.prompt}
{question.required && <RequiredMark />}
</span>
{question.help && (
<span className="block text-muted text-sm italic mt-1">{question.help}</span>
)}
<div className="mt-3">{children}</div>
</label>
</div>
);
}
export function RequiredMark() {
return (
<sup
aria-hidden
title="required"
className="text-accent font-sans font-normal text-[0.7em] ml-1 tracking-normal cursor-help"
>
∗
</sup>
);
}
function TextInput({
question,
value,
disabled,
onSave,
type,
}: Props & { type: 'text' | 'email' | 'tel' | 'date' }) {
const [local, setLocal] = useState(stringify(value));
useEffect(() => {
setLocal(stringify(value));
}, [value]);
return (
<Wrapper question={question}>
<input
type={type}
className="field-input"
value={local}
disabled={disabled}
maxLength={
question.type === 'short_text' ? question.maxLength ?? undefined : undefined
}
onChange={(e) => setLocal(e.target.value)}
onBlur={() => {
if (local !== stringify(value)) onSave(local);
}}
/>
</Wrapper>
);
}
function TimezoneInput({ question, value, disabled, onSave }: Props) {
const [local, setLocal] = useState(stringify(value));
useEffect(() => {
setLocal(stringify(value));
}, [value]);
const detected = useMemo(() => {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || null;
} catch {
return null;
}
}, []);
const zones = useMemo(() => allTimezones(), []);
const isKnown = useMemo(
() => (local ? zones.some((z) => z === local) : true),
[local, zones],
);
function commit(v: string) {
setLocal(v);
onSave(v);
}
return (
<Wrapper question={question}>
<input
type="text"
className="field-input font-mono"
list="rp2-timezones"
value={local}
disabled={disabled}
autoComplete="off"
placeholder={detected ?? 'e.g. America/New_York'}
onChange={(e) => setLocal(e.target.value)}
onBlur={() => {
if (local !== stringify(value)) onSave(local);
}}
/>
<datalist id="rp2-timezones">
{zones.map((tz) => (
<option key={tz} value={tz} />
))}
</datalist>
<div className="mt-2 text-sm text-muted flex flex-wrap items-baseline gap-3">
{detected && local !== detected && (
<button
type="button"
className="text-accent hover:underline"
disabled={disabled}
onClick={() => commit(detected)}
>
Use my browser’s zone: <span className="font-mono">{detected}</span>
</button>
)}
{local && !isKnown && (
<span className="italic">
<span className="font-mono not-italic">“{local}”</span> is not
a standard IANA zone — we’ll follow up if we can’t find a
match.
</span>
)}
{local && isKnown && <TimezoneNow zone={local} />}
</div>
</Wrapper>
);
}
function TimezoneNow({ zone }: { zone: string }) {
const [tick, setTick] = useState(0);
useEffect(() => {
const id = window.setInterval(() => setTick((t) => t + 1), 30_000);
return () => window.clearInterval(id);
}, []);
const now = useMemo(() => {
try {
return new Intl.DateTimeFormat(undefined, {
timeZone: zone,
weekday: 'short',
hour: 'numeric',
minute: '2-digit',
timeZoneName: 'short',
}).format(new Date());
} catch {
return null;
}
// tick is intentional to refresh
}, [zone, tick]);
if (!now) return null;
return <span className="italic">Local time there: {now}</span>;
}
// Curated fallback for browsers without Intl.supportedValuesOf (older Safari,
// old mobile). Everything else uses the browser's full IANA list at runtime.
const FALLBACK_TIMEZONES: readonly string[] = [
'Pacific/Honolulu',
'America/Anchorage',
'America/Los_Angeles',
'America/Denver',
'America/Chicago',
'America/New_York',
'America/Sao_Paulo',
'Europe/London',
'Europe/Berlin',
'Europe/Moscow',
'Africa/Cairo',
'Africa/Johannesburg',
'Asia/Jerusalem',
'Asia/Dubai',
'Asia/Kolkata',
'Asia/Singapore',
'Asia/Shanghai',
'Asia/Tokyo',
'Asia/Seoul',
'Australia/Perth',
'Australia/Sydney',
'Pacific/Auckland',
'UTC',
];
function allTimezones(): readonly string[] {
try {
const fn = (
Intl as unknown as {
supportedValuesOf?: (input: string) => string[];
}
).supportedValuesOf;
if (typeof fn === 'function') {
const values = fn('timeZone');
if (Array.isArray(values) && values.length > 0) return values;
}
} catch {
/* fall through */
}
return FALLBACK_TIMEZONES;
}
function LongText({ question, value, disabled, onSave }: Props) {
const [local, setLocal] = useState(stringify(value));
const ref = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
setLocal(stringify(value));
}, [value]);
useEffect(() => {
autosize(ref.current);
}, [local]);
return (
<Wrapper question={question}>
<textarea
ref={ref}
className="field-input font-serif leading-relaxed py-3"
rows={4}
value={local}
disabled={disabled}
onChange={(e) => {
setLocal(e.target.value);
}}
onBlur={() => {
if (local !== stringify(value)) onSave(local);
}}
/>
<div className="text-muted text-xs mt-1 flex justify-end tabular-nums">
{wordCount(local)} {wordCount(local) === 1 ? 'word' : 'words'}
</div>
</Wrapper>
);
}
function SingleSelect({ question, value, disabled, onSave }: Props) {
if (question.type !== 'single_select') return null;
const selected = stringify(value);
return (
<Wrapper question={question}>
<div className="space-y-2 mt-1">
{question.options.map((opt) => (
<label
key={opt.value}
className="flex items-baseline gap-3 cursor-pointer group"
>
<input
type="radio"
name={question.key}
value={opt.value}
checked={selected === opt.value}
disabled={disabled}
onChange={() => onSave(opt.value)}
className="accent-accent shrink-0 translate-y-[2px]"
/>
<span className="group-hover:text-ink text-ink/95">{opt.label}</span>
</label>
))}
</div>
</Wrapper>
);
}
function MultiSelect({ question, value, disabled, onSave }: Props) {
if (question.type !== 'multi_select') return null;
const current = Array.isArray(value) ? (value as string[]) : [];
return (
<Wrapper question={question}>
<div className="space-y-2 mt-1">
{question.options.map((opt) => {
const checked = current.includes(opt.value);
return (
<label
key={opt.value}
className="flex items-baseline gap-3 cursor-pointer group"
>
<input
type="checkbox"
value={opt.value}
checked={checked}
disabled={disabled}
onChange={() => {
const next = checked
? current.filter((v) => v !== opt.value)
: [...current, opt.value];
onSave(next);
}}
className="accent-accent shrink-0 translate-y-[2px]"
/>
<span className="group-hover:text-ink text-ink/95">{opt.label}</span>
</label>
);
})}
</div>
</Wrapper>
);
}
function ComingSoon({ question }: { question: Question }) {
return (
<Wrapper question={question}>
<div className="border border-dashed border-rule text-muted italic px-4 py-3 text-sm">
This question needs a <span className="not-italic font-sans">{humanType(question.type)}</span>{' '}
input. Coming in the next iteration — you'll be able to fill it in
before you submit.
</div>
</Wrapper>
);
}
function humanType(t: Question['type']): string {
switch (t) {
case 'availability_grid':
return 'availability grid';
case 'file_upload':
return 'file upload';
case 'ranked':
return 'drag-to-rank';
case 'signature':
return 'signature';
default:
return t;
}
}
function stringify(v: unknown): string {
if (v === null || v === undefined) return '';
if (typeof v === 'string') return v;
return String(v);
}
function wordCount(s: string): number {
const trimmed = s.trim();
if (!trimmed) return 0;
return trimmed.split(/\s+/).length;
}
function autosize(el: HTMLTextAreaElement | null): void {
if (!el) return;
el.style.height = 'auto';
el.style.height = `${el.scrollHeight}px`;
}