-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathindex.tsx
More file actions
557 lines (524 loc) · 17.6 KB
/
Copy pathindex.tsx
File metadata and controls
557 lines (524 loc) · 17.6 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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import { DEFAULT_WORDPRESS_VERSION } from '@studio/common/constants';
import { generateCustomDomainFromSiteName } from '@studio/common/lib/domains';
import { generatePassword } from '@studio/common/lib/passwords';
import { RecommendedPHPVersion } from '@studio/common/types/php-versions';
import { BaseControl, CheckboxControl } from '@wordpress/components';
import { DataForm, useFormValidity } from '@wordpress/dataviews';
import { __, sprintf } from '@wordpress/i18n';
import { chevronLeft, chevronDown, chevronRight } from '@wordpress/icons';
import { Button, Icon } from '@wordpress/ui';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { BusyOverlay } from '@/components/busy-overlay';
import { LearnHowLink, LearnMoreLink } from '@/components/learn-more';
import { OnboardingFooter } from '@/components/onboarding-footer';
import {
adminEmailField,
adminPasswordField,
adminUsernameField,
customDomainField,
phpVersionField,
siteNameField,
customDomainToggleField,
wpVersionField,
} from '@/components/site-fields';
import { usePathValidator } from '@/data/queries/use-create-site-helpers';
import { useSites } from '@/data/queries/use-sites';
import { useWordPressVersions } from '@/data/queries/use-wordpress-versions';
import styles from './style.module.css';
import type { SupportedPHPVersion } from '@studio/common/types/php-versions';
import type {
DataFormControlProps,
Field,
FieldValidity,
Form,
FormField,
FormValidity,
} from '@wordpress/dataviews';
import type { FormEvent } from 'react';
export interface CreateSiteFormValues {
name: string;
path: string;
phpVersion: SupportedPHPVersion;
wpVersion: string;
customDomain?: string;
enableHttps: boolean;
adminUsername: string;
adminPassword: string;
adminEmail: string;
}
interface CreateSiteFormProps {
/** Applied once when first defined — user edits win after. */
initialValues?: Partial< CreateSiteFormValues >;
existingDomainNames: string[];
onSubmit: ( values: CreateSiteFormValues ) => void;
onCancel: () => void;
isSubmitting?: boolean;
submitError?: string;
submitLabel?: string;
}
interface FormData {
name: string;
path: string;
// Stops the name→path auto-gen from overriding a manually picked folder.
hasCustomPath: boolean;
pathError: string;
// Suppresses the path field's required check during the auto-gen async
// window so a seeded name doesn't flash "1 error found" on the Advanced
// toggle before `generateProposedPath` resolves.
isPathPending: boolean;
phpVersion: SupportedPHPVersion;
wpVersion: string;
useCustomDomain: boolean;
customDomain: string;
enableHttps: boolean;
adminUsername: string;
adminPassword: string;
adminEmail: string;
}
function hasAnyValue( values: Partial< CreateSiteFormValues > ): boolean {
return Object.values( values ).some( ( value ) => value !== undefined && value !== '' );
}
// Only fields the caller actually provided overwrite prev — user edits to
// everything else survive an async initial-value arrival.
function applyInitialValues( prev: FormData, values: Partial< CreateSiteFormValues > ): FormData {
const next: FormData = { ...prev };
if ( values.name !== undefined && ! prev.name ) next.name = values.name;
if ( values.phpVersion !== undefined ) next.phpVersion = values.phpVersion;
if ( values.wpVersion !== undefined ) next.wpVersion = values.wpVersion;
if ( values.adminUsername !== undefined ) next.adminUsername = values.adminUsername;
if ( values.adminPassword !== undefined ) next.adminPassword = values.adminPassword;
if ( values.adminEmail !== undefined ) next.adminEmail = values.adminEmail;
if ( values.customDomain ) {
next.useCustomDomain = true;
next.customDomain = values.customDomain;
}
if ( values.enableHttps !== undefined ) next.enableHttps = values.enableHttps;
return next;
}
// Called from the form (not `PathField`) so it runs even when Advanced is
// collapsed — otherwise `data.path` would stay empty on first load and the
// Advanced toggle would falsely show "1 error found".
function usePathAutoGenerate( data: FormData, onChange: ( update: Partial< FormData > ) => void ) {
const { data: sites } = useSites();
const { generateProposedPath } = usePathValidator( sites );
const onChangeRef = useRef( onChange );
useEffect( () => {
onChangeRef.current = onChange;
}, [ onChange ] );
const pendingNameRef = useRef< string | null >( null );
useEffect( () => {
if ( data.hasCustomPath ) return;
const trimmed = data.name.trim();
if ( ! trimmed ) {
if ( data.path || data.pathError || data.isPathPending ) {
onChangeRef.current( { path: '', pathError: '', isPathPending: false } );
}
return;
}
pendingNameRef.current = trimmed;
if ( ! data.isPathPending ) {
onChangeRef.current( { isPathPending: true } );
}
let cancelled = false;
void ( async () => {
const result = await generateProposedPath( trimmed );
if ( cancelled || pendingNameRef.current !== trimmed ) return;
onChangeRef.current( {
path: result.path,
pathError: result.error ?? '',
isPathPending: false,
} );
} )();
return () => {
cancelled = true;
};
// `data.isPathPending` intentionally omitted — the effect writes it,
// so including it would re-trigger a redundant generate each cycle.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ data.name, data.hasCustomPath, data.path, data.pathError, generateProposedPath ] );
}
// Rendered as a button (not an input) because the value is always set by
// the name→path auto-gen or the native folder dialog — never typed. Also
// sidesteps the browser's refusal to expose `validationMessage` on readonly
// inputs, which was swallowing async errors like path collisions.
function PathField( {
data: item,
field,
hideLabelFromVision,
onChange,
validity,
}: DataFormControlProps< FormData > ) {
const { data: sites } = useSites();
const { selectPath } = usePathValidator( sites );
const handleSelect = useCallback( async () => {
const result = await selectPath( item.hasCustomPath ? item.path : '' );
if ( ! result ) return;
onChange( {
path: result.path,
hasCustomPath: true,
pathError: result.error ?? '',
...( ! item.name && result.name ? { name: result.name } : {} ),
} );
}, [ item.hasCustomPath, item.name, item.path, onChange, selectPath ] );
const errorMessage = validity?.custom?.message;
const triggerLabel = item.path
? sprintf(
// translators: %s is the currently selected folder path.
__( '%s, select a different folder' ),
item.path
)
: __( 'Select a folder' );
return (
<BaseControl
__nextHasNoMarginBottom
label={ field.label }
hideLabelFromVision={ hideLabelFromVision }
help={
errorMessage ? (
<span className={ styles.pathErrorHelp }>{ errorMessage }</span>
) : (
<>
{ __( 'Select an empty directory or a directory with an existing WordPress site.' ) }{ ' ' }
<LearnMoreLink docsLinksKey="docsSites" />
</>
)
}
>
<button
type="button"
onClick={ handleSelect }
aria-label={ triggerLabel }
aria-invalid={ !! errorMessage || undefined }
className={ `${ styles.pathTrigger } ${ errorMessage ? styles.pathTriggerError : '' }` }
>
<span
className={ `${ styles.pathValue } ${ item.path ? '' : styles.pathValuePlaceholder }` }
aria-hidden="true"
>
{ item.path || __( 'Choose a folder…' ) }
</span>
<span className={ styles.pathTriggerAction } aria-hidden="true">
{ __( 'Choose\u2026' ) }
</span>
</button>
</BaseControl>
);
}
function EnableHttpsControl( { data: item, field, onChange }: DataFormControlProps< FormData > ) {
return (
<CheckboxControl
__nextHasNoMarginBottom
label={ field.label }
checked={ item.enableHttps }
onChange={ ( checked ) => onChange( { enableHttps: checked } ) }
help={
<>
{ __(
'You need to manually add the Studio root certificate authority to your keychain and trust it to enable HTTPS.'
) }{ ' ' }
<LearnHowLink docsLinksKey="docsSslInStudio" />
</>
}
/>
);
}
function countAdvancedErrors( validity: FormValidity, form: Form ): number {
const fieldIds: string[] = [];
const collect = ( field: FormField | string ) => {
if ( typeof field === 'string' ) {
fieldIds.push( field );
return;
}
if ( field.children ) {
field.children.forEach( collect );
} else {
fieldIds.push( field.id );
}
};
form.fields?.forEach( collect );
return fieldIds.reduce( ( total, id ) => {
const fieldValidity: FieldValidity | undefined = validity?.[ id ];
if ( ! fieldValidity ) return total;
const hasInvalid = Object.values( fieldValidity ).some(
( rule ) => rule && typeof rule === 'object' && 'type' in rule && rule.type === 'invalid'
);
return hasInvalid ? total + 1 : total;
}, 0 );
}
export function CreateSiteForm( {
initialValues,
existingDomainNames,
onSubmit,
onCancel,
isSubmitting,
submitError,
submitLabel,
}: CreateSiteFormProps ) {
const [ data, setData ] = useState< FormData >( () => {
const base: FormData = {
name: '',
path: '',
hasCustomPath: false,
pathError: '',
isPathPending: false,
phpVersion: RecommendedPHPVersion,
wpVersion: DEFAULT_WORDPRESS_VERSION,
useCustomDomain: false,
customDomain: '',
enableHttps: false,
adminUsername: 'admin',
adminPassword: generatePassword(),
adminEmail: 'admin@localhost.com',
};
if ( ! initialValues ) return base;
const seeded = applyInitialValues( base, initialValues );
if ( seeded.name.trim() && ! seeded.path ) seeded.isPathPending = true;
return seeded;
} );
// Handles the async seed case (e.g. `useProposedSiteName` resolving after
// mount) without clobbering user edits on subsequent renders.
const hasAppliedInitialValues = useRef( initialValues ? hasAnyValue( initialValues ) : false );
useEffect( () => {
if ( hasAppliedInitialValues.current || ! initialValues ) return;
if ( ! hasAnyValue( initialValues ) ) return;
hasAppliedInitialValues.current = true;
setData( ( prev ) => {
const next = applyInitialValues( prev, initialValues );
if ( next.name.trim() && ! next.path ) next.isPathPending = true;
return next;
} );
}, [ initialValues ] );
const { data: wpVersions } = useWordPressVersions();
// Land keyboard focus in the Site name field on mount — it's the first
// thing every flow asks for. The onboarding layout's heading-focus
// fallback yields when a page claims focus itself.
const formRef = useRef< HTMLFormElement >( null );
useEffect( () => {
const input = formRef.current?.querySelector< HTMLInputElement >(
'input[type="text"], input:not([type])'
);
input?.focus();
}, [] );
// Drop a wpVersion that isn't in the installable-versions list (e.g. a
// blueprint preferring a release below the minimum supported version) —
// mirrors the desktop renderer, which silently ignores unsupported
// preferred versions. Keyed on the current value as well as the list:
// initial values seed asynchronously, so with a warm versions cache the
// list alone would never change again and a late seed would slip through.
useEffect( () => {
if ( ! wpVersions?.length ) {
return;
}
setData( ( prev ) =>
wpVersions.some( ( version ) => version.value === prev.wpVersion )
? prev
: { ...prev, wpVersion: DEFAULT_WORDPRESS_VERSION }
);
}, [ wpVersions, data.wpVersion ] );
const fields = useMemo< Field< FormData >[] >(
() => [
siteNameField< FormData >(),
{
id: 'path',
label: __( 'Local path' ),
Edit: PathField,
// Required check lives inside `custom` so it can opt out while
// `isPathPending` is true — see the `FormData` comment above.
isValid: {
custom: ( item: FormData ) => {
if ( item.pathError ) return item.pathError;
if ( item.isPathPending ) return null;
if ( ! item.path ) return __( 'Local path is required.' );
return null;
},
},
},
phpVersionField< FormData >(),
wpVersionField< FormData >( DEFAULT_WORDPRESS_VERSION, wpVersions ),
adminUsernameField< FormData >(),
adminPasswordField< FormData >(),
adminEmailField< FormData >(),
customDomainToggleField< FormData >(),
customDomainField< FormData >( existingDomainNames ),
{
id: 'enableHttps',
type: 'boolean',
label: __( 'Enable HTTPS' ),
isVisible: ( item: FormData ) => item.useCustomDomain,
Edit: EnableHttpsControl,
},
],
[ existingDomainNames, wpVersions ]
);
const basicForm = useMemo< Form >(
() => ( {
layout: { type: 'regular', labelPosition: 'top' },
fields: [ 'name' ],
} ),
[]
);
const advancedForm = useMemo< Form >(
() => ( {
layout: { type: 'regular', labelPosition: 'top' },
fields: [
{
id: 'path',
layout: { type: 'regular', labelPosition: 'top' },
},
{
id: 'versions',
layout: { type: 'row' },
children: [ 'phpVersion', 'wpVersion' ],
},
{
id: 'adminCredentials',
layout: { type: 'row' },
children: [ 'adminUsername', 'adminPassword' ],
},
'adminEmail',
'useCustomDomain',
'customDomain',
'enableHttps',
],
} ),
[]
);
// Covers both sections so the collapsed Advanced toggle still picks up
// errors from fields that aren't currently mounted.
const fullForm = useMemo< Form >(
() => ( {
layout: { type: 'regular', labelPosition: 'top' },
fields: [ ...basicForm.fields!, ...advancedForm.fields! ],
} ),
[ basicForm, advancedForm ]
);
const { validity, isValid } = useFormValidity( data, fields, fullForm );
const [ isAdvancedOpen, setIsAdvancedOpen ] = useState( false );
const handleChangePartial = useCallback( ( update: Partial< FormData > ) => {
setData( ( prev ) => ( { ...prev, ...update } ) );
}, [] );
usePathAutoGenerate( data, handleChangePartial );
const handleChange = useCallback( ( update: Record< string, unknown > ) => {
setData( ( prev ) => {
const next: FormData = { ...prev, ...( update as Partial< FormData > ) };
// Seed the custom-domain input on first toggle with a sensible
// default derived from the site name.
if ( ! prev.useCustomDomain && next.useCustomDomain && ! next.customDomain ) {
next.customDomain = generateCustomDomainFromSiteName( next.name );
}
return next;
} );
}, [] );
// `isPathPending` is deliberately absent from `isValid` (so the Advanced
// toggle doesn't flash), so gate submit on it separately.
const canSubmit = isValid && ! isSubmitting && ! data.isPathPending;
const handleSubmit = ( event: FormEvent ) => {
event.preventDefault();
if ( ! canSubmit ) return;
onSubmit( {
name: data.name.trim(),
path: data.path,
phpVersion: data.phpVersion,
wpVersion: data.wpVersion,
customDomain: data.useCustomDomain
? data.customDomain || generateCustomDomainFromSiteName( data.name )
: undefined,
enableHttps: data.useCustomDomain && data.enableHttps,
adminUsername: data.adminUsername,
adminPassword: data.adminPassword,
adminEmail: data.adminEmail,
} );
};
const advancedErrorCount = countAdvancedErrors( validity, advancedForm );
// The buttons stay inside the <form> element so the submit button keeps
// its implicit form association while floating in the footer.
const actionButtons = (
<>
<Button
type="button"
variant="minimal"
tone="neutral"
onClick={ onCancel }
disabled={ isSubmitting }
>
<Icon icon={ chevronLeft } size={ 16 } />
<span>{ __( 'Back' ) }</span>
</Button>
<Button
type="submit"
variant="solid"
tone="brand"
disabled={ ! canSubmit }
loading={ isSubmitting }
loadingAnnouncement={ __( 'Creating site' ) }
data-testid="create-site-submit"
>
{ submitLabel ?? __( 'Create site' ) }
</Button>
</>
);
return (
<form ref={ formRef } className={ styles.form } onSubmit={ handleSubmit }>
{ /* While creating, shield the rest of the window and freeze the
fields (inert) — the submit button's spinner is the progress
indication. */ }
<BusyOverlay active={ !! isSubmitting } />
{ /* The frosted panel wraps only the fields: its backdrop-filter
turns it into a containing block for fixed descendants, so the
fixed OnboardingFooter must stay outside (but inside the form
for the submit button's implicit association). */ }
<div className={ styles.panel } inert={ isSubmitting || undefined }>
<DataForm< FormData >
data={ data }
fields={ fields }
form={ basicForm }
onChange={ handleChange }
validity={ validity }
/>
<Button
type="button"
variant="unstyled"
tone="neutral"
className={ styles.advancedToggle }
onClick={ () => setIsAdvancedOpen( ( value ) => ! value ) }
aria-expanded={ isAdvancedOpen }
>
<Icon icon={ isAdvancedOpen ? chevronDown : chevronRight } />
<span>{ __( 'Advanced settings' ) }</span>
{ ! isAdvancedOpen && advancedErrorCount > 0 && (
<span className={ styles.advancedErrorCount }>
{ advancedErrorCount === 1
? __( '1 error found' )
: /* translators: %d: number of errors */
`${ advancedErrorCount } ${ __( 'errors found' ) }` }
</span>
) }
</Button>
<div
className={
isAdvancedOpen
? `${ styles.advancedCollapse } ${ styles.advancedCollapseOpen }`
: styles.advancedCollapse
}
inert={ ! isAdvancedOpen || undefined }
>
<div className={ styles.advancedCollapseInner }>
<DataForm< FormData >
data={ data }
fields={ fields }
form={ advancedForm }
onChange={ handleChange }
validity={ validity }
/>
</div>
</div>
{ submitError && (
<div role="alert" className={ styles.submitError }>
{ submitError }
</div>
) }
</div>
<OnboardingFooter>{ actionButtons }</OnboardingFooter>
</form>
);
}