forked from WordPress/ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstage.tsx
More file actions
997 lines (894 loc) · 25.3 KB
/
stage.tsx
File metadata and controls
997 lines (894 loc) · 25.3 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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
/**
* WordPress dependencies
*/
import { Page } from '@wordpress/admin-ui';
import {
Button,
ExternalLink,
Icon,
Notice,
Popover,
Spinner,
ToggleControl,
} from '@wordpress/components';
import { store as coreStore } from '@wordpress/core-data';
import { useSelect, useDispatch, useRegistry } from '@wordpress/data';
import { DataForm } from '@wordpress/dataviews';
import { useCallback, useMemo, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';
import type { DataFormControlProps, Field, Form } from '@wordpress/dataviews';
/**
* Internal dependencies
*/
import './style.scss';
import AIIcon from './ai-icon';
type AISettings = Record< string, boolean >;
interface FeatureGroupData {
id: string;
label: string;
description: string;
}
interface SettingsFieldData {
id: string;
label: string;
type: string;
default?: unknown;
elements?: Array< { value: string; label: string } >;
isValid?: Record< string, number >;
}
interface FeatureData {
id: string;
settingName: string;
label: string;
description: string;
category: string;
settingsFields: SettingsFieldData[];
stability: string;
image: string;
}
interface PageData {
hasCredentials: boolean;
hasValidCredentials: boolean;
connectorsUrl: string;
featureGroups: FeatureGroupData[];
features: FeatureData[];
}
const FEATURE_SETTING_PATTERN = /^wpai_feature_(.+)_enabled$/;
const GLOBAL_FIELD_ID = 'wpai_features_enabled';
const noop = () => {};
function isRecord( value: unknown ): value is Record< string, unknown > {
return typeof value === 'object' && value !== null;
}
function toStringValue( value: unknown ): string {
return typeof value === 'string' ? value : '';
}
function isDefined< T >( value: T | null | undefined ): value is T {
return value !== null && value !== undefined;
}
function isSettingsField( value: unknown ): value is SettingsFieldData {
if ( ! isRecord( value ) ) {
return false;
}
// eslint-disable-next-line dot-notation
const id = value[ 'id' ];
return typeof id === 'string' && id !== '';
}
function parseFeatureGroup( value: unknown ): FeatureGroupData | null {
if ( ! isRecord( value ) ) {
return null;
}
const featureGroup = value as Partial< FeatureGroupData >;
const id = toStringValue( featureGroup.id );
if ( ! id ) {
return null;
}
return {
id,
label: toStringValue( featureGroup.label ) || id,
description: toStringValue( featureGroup.description ),
};
}
function parseFeature( value: unknown ): FeatureData | null {
if ( ! isRecord( value ) ) {
return null;
}
const feature = value as Partial< FeatureData >;
const settingName = toStringValue( feature.settingName );
if ( ! settingName ) {
return null;
}
const id =
toStringValue( feature.id ) ||
getFeatureIdFromSettingName( settingName );
const rawFields = Array.isArray( feature.settingsFields )
? feature.settingsFields
: [];
return {
id,
settingName,
label: toStringValue( feature.label ) || getDefaultLabel( id ),
description: toStringValue( feature.description ),
category: toStringValue( feature.category ) || 'other',
settingsFields: ( rawFields as unknown[] ).filter( isSettingsField ),
stability: toStringValue( feature.stability ) || 'experimental',
image: toStringValue( feature.image ),
};
}
function getFeatureIdFromSettingName( settingName: string ): string {
const match = FEATURE_SETTING_PATTERN.exec( settingName );
return match?.[ 1 ] ?? settingName;
}
function getDefaultLabel( key: string ): string {
return key
.split( /[-_]/ )
.filter( Boolean )
.map( ( part ) => part[ 0 ]?.toUpperCase() + part.slice( 1 ) )
.join( ' ' );
}
function getSectionId( groupId: string ): string {
return `feature-group-${ groupId.replace( /[^a-zA-Z0-9_-]/g, '-' ) }`;
}
function buildFallbackFeatureGroups(
features: FeatureData[]
): FeatureGroupData[] {
const categories = Array.from(
new Set( features.map( ( feature ) => feature.category || 'other' ) )
);
return categories.map( ( category ) => ( {
id: category,
label:
category === 'other'
? __( 'Other Features', 'ai' )
: getDefaultLabel( category ),
description:
category === 'other'
? __( 'Additional AI-powered features.', 'ai' )
: '',
} ) );
}
function getPageData(): PageData {
const fallback: PageData = {
hasCredentials: false,
hasValidCredentials: false,
connectorsUrl: '',
featureGroups: [],
features: [],
};
try {
const rawData = JSON.parse(
document.getElementById( 'wp-script-module-data-ai-wp-admin' )
?.textContent ?? '{}'
);
if ( ! isRecord( rawData ) ) {
return fallback;
}
const pageData = rawData as Partial< PageData >;
const featureGroups = Array.isArray( pageData.featureGroups )
? pageData.featureGroups
.map( parseFeatureGroup )
.filter( isDefined )
: [];
const features = Array.isArray( pageData.features )
? pageData.features.map( parseFeature ).filter( isDefined )
: [];
return {
hasCredentials: Boolean( pageData.hasCredentials ),
hasValidCredentials: Boolean( pageData.hasValidCredentials ),
connectorsUrl: toStringValue( pageData.connectorsUrl ),
featureGroups,
features,
};
} catch {
return fallback;
}
}
const PAGE_DATA = getPageData();
const GLOBAL_FIELD: Field< AISettings > = {
id: GLOBAL_FIELD_ID,
label: __( 'Enable AI', 'ai' ),
type: 'boolean',
Edit: 'toggle',
};
function buildToggleMessage(
edits: Record< string, unknown >,
featureDefinitions: FeatureData[]
): string {
const entries = Object.entries( edits );
if ( entries.length === 0 ) {
return __( 'Settings saved.', 'ai' );
}
// Bulk toggle (multiple experiments).
if ( entries.length > 1 ) {
const allEnabled = entries.every( ( [ , value ] ) => value === true );
const allDisabled = entries.every( ( [ , value ] ) => value === false );
const count = entries.length;
if ( allEnabled ) {
return sprintf(
// translators: %d: Number of experiments.
__( '%d experiments enabled', 'ai' ),
count
);
}
if ( allDisabled ) {
return sprintf(
// translators: %d: Number of experiments.
__( '%d experiments disabled', 'ai' ),
count
);
}
// Just a fallback for mixed state (shouldn't happen with our buttons, but handle it).
return sprintf(
// translators: %d: Number of experiments.
__( '%d experiments updated', 'ai' ),
count
);
}
// Single toggle
const entry = entries[ 0 ];
if ( ! entry ) {
return __( 'Settings saved.', 'ai' );
}
if ( entry[ 0 ] === GLOBAL_FIELD_ID ) {
return entry[ 1 ]
? __( 'AI enabled.', 'ai' )
: __( 'AI disabled.', 'ai' );
}
const feature = featureDefinitions.find(
( f ) => f.settingName === entry[ 0 ]
);
const label = feature?.label ?? entry[ 0 ];
return entry[ 1 ]
? // translators: %s: Feature label.
sprintf( __( '%s enabled.', 'ai' ), label )
: // translators: %s: Feature label.
sprintf( __( '%s disabled.', 'ai' ), label );
}
function DisabledToggle( { field, data }: DataFormControlProps< AISettings > ) {
return (
<ToggleControl
__nextHasNoMarginBottom
label={ field.label }
help={ field.description }
checked={ !! field.getValue( { item: data } ) }
// No-op handler required to satisfy React's controlled-component warning; the toggle is disabled.
onChange={ noop }
disabled
/>
);
}
interface SectionActionsProps extends DataFormControlProps< AISettings > {
experimentSettings: string[];
globalEnabled: boolean;
onBulkChange: ( edits: Record< string, boolean > ) => void;
}
function SectionActions( {
experimentSettings,
data,
globalEnabled,
onBulkChange,
}: SectionActionsProps ) {
const allEnabled = useMemo( () => {
return experimentSettings.every(
( settingName ) => data[ settingName ]
);
}, [ experimentSettings, data ] );
const allDisabled = useMemo( () => {
return experimentSettings.every(
( settingName ) => ! data[ settingName ]
);
}, [ experimentSettings, data ] );
const handleEnableAll = useCallback( () => {
const edits: Record< string, boolean > = {};
let enabledCount = 0;
for ( const settingName of experimentSettings ) {
if ( ! data[ settingName ] ) {
edits[ settingName ] = true;
enabledCount++;
}
}
if ( enabledCount > 0 ) {
onBulkChange( edits );
}
}, [ experimentSettings, data, onBulkChange ] );
const handleDisableAll = useCallback( () => {
const edits: Record< string, boolean > = {};
let disabledCount = 0;
for ( const settingName of experimentSettings ) {
if ( data[ settingName ] ) {
edits[ settingName ] = false;
disabledCount++;
}
}
if ( disabledCount > 0 ) {
onBulkChange( edits );
}
}, [ experimentSettings, data, onBulkChange ] );
return (
<div className="ai-section-actions">
<Button
variant="secondary"
size="compact"
onClick={ handleEnableAll }
disabled={ ! globalEnabled || allEnabled }
>
{ __( 'Enable all', 'ai' ) }
</Button>
<Button
variant="secondary"
size="compact"
onClick={ handleDisableAll }
disabled={ ! globalEnabled || allDisabled }
>
{ __( 'Disable all', 'ai' ) }
</Button>
</div>
);
}
function InlineFeatureSettings( { feature }: { feature: FeatureData } ) {
const fieldIds = useMemo(
() => feature.settingsFields.map( ( f ) => f.id ),
[ feature.settingsFields ]
);
const { editedRecord, nonTransientEdits } = useSelect( ( select ) => {
const store: any = select( coreStore );
return {
editedRecord: store.getEditedEntityRecord( 'root', 'site' ) as
| Record< string, unknown >
| undefined,
nonTransientEdits: ( store.getEntityRecordNonTransientEdits(
'root',
'site'
) ?? {} ) as Record< string, unknown >,
};
}, [] );
const [ isSaving, setIsSaving ] = useState( false );
const isDirty = useMemo(
() => fieldIds.some( ( id ) => id in nonTransientEdits ),
[ fieldIds, nonTransientEdits ]
);
const { editEntityRecord } = useDispatch( coreStore );
const { __experimentalSaveSpecifiedEntityEdits: saveSpecifiedEdits } =
useDispatch( coreStore ) as any;
const { createSuccessNotice, createErrorNotice } =
useDispatch( noticesStore );
const data = useMemo( () => {
const base: Record< string, unknown > = {};
for ( const field of feature.settingsFields ) {
base[ field.id ] = editedRecord?.[ field.id ] ?? field.default;
}
return base;
}, [ feature.settingsFields, editedRecord ] );
const fields = useMemo< Field< Record< string, unknown > >[] >(
() =>
feature.settingsFields.map(
( { default: _, ...fieldProps } ) =>
fieldProps as Field< Record< string, unknown > >
),
[ feature.settingsFields ]
);
const form = useMemo< Form >(
() => ( {
fields: feature.settingsFields.map( ( f ) => f.id ),
} ),
[ feature.settingsFields ]
);
const handleChange = useCallback(
( edits: Record< string, unknown > ) => {
// @ts-expect-error -- core-data types don't expose editEntityRecord for 'root'/'site' args.
editEntityRecord( 'root', 'site', undefined, edits );
},
[ editEntityRecord ]
);
const handleSave = useCallback( async () => {
setIsSaving( true );
try {
await saveSpecifiedEdits( 'root', 'site', undefined, fieldIds, {
throwOnError: true,
} );
createSuccessNotice(
sprintf(
// translators: %s: Feature label.
__( '%s settings saved.', 'ai' ),
feature.label
),
{ type: 'snackbar' }
);
} catch {
// Edits remain in the store — user can retry or adjust values.
createErrorNotice( __( 'Failed to save settings.', 'ai' ), {
type: 'snackbar',
} );
} finally {
setIsSaving( false );
}
}, [
saveSpecifiedEdits,
fieldIds,
createSuccessNotice,
createErrorNotice,
feature.label,
] );
return (
<div className="ai-feature-settings-form">
<DataForm< Record< string, unknown > >
data={ data }
fields={ fields }
form={ form }
onChange={ handleChange }
/>
{ isDirty && (
<div className="ai-feature-settings-form__actions">
<Button
variant="primary"
onClick={ handleSave }
isBusy={ isSaving }
disabled={ isSaving }
size="compact"
aria-label={ sprintf(
// translators: %s: Feature label.
__( 'Save %s settings', 'ai' ),
feature.label
) }
>
{ __( 'Save', 'ai' ) }
</Button>
</div>
) }
</div>
);
}
const FEATURES_BY_SETTING = new Map(
PAGE_DATA.features
.filter( ( f ) => f.settingsFields.length > 0 )
.map( ( f ) => [ f.settingName, f ] as const )
);
function FeatureToggleWithSettings( {
field,
data,
onChange,
}: DataFormControlProps< AISettings > ) {
const feature = FEATURES_BY_SETTING.get( field.id );
const checked = !! field.getValue( { item: data } );
return (
<div className="ai-feature-toggle-with-settings">
<ToggleControl
__nextHasNoMarginBottom
label={ field.label }
help={ field.description }
checked={ checked }
onChange={ ( value ) => {
onChange( { [ field.id ]: value } );
} }
/>
{ checked && feature && (
<InlineFeatureSettings feature={ feature } />
) }
</div>
);
}
const VISUAL_CARD_FEATURES = new Map(
PAGE_DATA.features
.filter( ( f ) => f.stability === 'stable' && f.image !== '' )
.map( ( f ) => [ f.settingName, f ] as const )
);
function GlobalEnableControl( {
enabled,
onToggle,
disabled,
}: {
enabled: boolean;
onToggle: ( value: boolean ) => void;
disabled: boolean;
} ) {
const [ isInfoOpen, setIsInfoOpen ] = useState( false );
return (
<div className="ai-settings-page__global-control">
<ToggleControl
__nextHasNoMarginBottom
label={ __( 'Enable AI', 'ai' ) }
checked={ enabled }
disabled={ disabled }
onChange={ onToggle }
/>
<Button
className="ai-settings-page__global-info-button"
variant="tertiary"
icon={
<Icon
icon={
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
width={ 18 }
height={ 18 }
>
<path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 4a1.25 1.25 0 1 1 0 2.5A1.25 1.25 0 0 1 12 6Zm1.5 12h-3v-1.5h.75V11h-1V9.5h2.5v6.75h.75V18Z" />
</svg>
}
/>
}
label={ __( 'About global AI setting', 'ai' ) }
onClick={ () => setIsInfoOpen( ( open ) => ! open ) }
/>
{ isInfoOpen && (
<Popover
placement="bottom-end"
onClose={ () => setIsInfoOpen( false ) }
>
<p className="ai-settings-page__global-info-text">
{ __(
'Control whether AI is enabled for your site. When disabled, all features and experiments are inactive regardless of their individual settings.',
'ai'
) }
</p>
</Popover>
) }
</div>
);
}
function VisualCardToggle( {
field,
data,
onChange,
}: DataFormControlProps< AISettings > ) {
const feature = VISUAL_CARD_FEATURES.get( field.id );
const globalEnabled = !! data[ GLOBAL_FIELD_ID ];
const checked = !! field.getValue( { item: data } );
return (
<div
className={ `ai-showcase-card${
! globalEnabled ? ' ai-showcase-card--disabled' : ''
}` }
>
{ feature?.image && (
<div className="ai-showcase-card__image">
<img src={ feature.image } alt="" loading="lazy" />
</div>
) }
<div className="ai-showcase-card__content">
<h3 className="ai-showcase-card__title">{ field.label }</h3>
<p className="ai-showcase-card__description">
{ field.description }
</p>
<div className="ai-showcase-card__actions">
<Button
variant={ checked ? 'secondary' : 'primary' }
onClick={ () =>
onChange( { [ field.id ]: ! checked } )
}
disabled={ ! globalEnabled }
size="compact"
>
{ checked
? __( 'Disable', 'ai' )
: __( 'Enable', 'ai' ) }
</Button>
{ checked && (
<span className="ai-showcase-card__enabled-badge">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
width={ 16 }
height={ 16 }
fill="currentColor"
>
<path d="M16.5 7.5 10 13.9l-2.5-2.4-1 1 3.5 3.6 7.5-7.6z" />
</svg>
{ __( 'Enabled', 'ai' ) }
</span>
) }
</div>
</div>
</div>
);
}
function AISettingsPage() {
const { editedRecord, isLoading } = useSelect( ( select ) => {
const store: any = select( coreStore );
return {
editedRecord: store.getEditedEntityRecord( 'root', 'site' ) as
| Record< string, unknown >
| undefined,
isLoading: ! store.hasFinishedResolution( 'getEntityRecord', [
'root',
'site',
] ) as boolean,
};
}, [] );
const { editEntityRecord } = useDispatch( coreStore );
const { __experimentalSaveSpecifiedEntityEdits: saveSpecifiedEdits } =
useDispatch( coreStore ) as any;
const { createSuccessNotice, createErrorNotice } =
useDispatch( noticesStore );
const registry = useRegistry();
const featureDefinitions = useMemo< FeatureData[] >( () => {
const sourceFeatures =
PAGE_DATA.features.length > 0
? PAGE_DATA.features
: Object.keys( editedRecord ?? {} )
.filter( ( key ) =>
FEATURE_SETTING_PATTERN.test( key )
)
.sort()
.map( ( settingName ) => {
const id =
getFeatureIdFromSettingName( settingName );
return {
id,
settingName,
label: getDefaultLabel( id ),
description: '',
category: 'other',
settingsFields: [],
stability: 'experimental',
image: '',
};
} );
const uniqueFeatures: FeatureData[] = [];
const seenSettingNames = new Set< string >();
for ( const feature of sourceFeatures ) {
if ( seenSettingNames.has( feature.settingName ) ) {
continue;
}
seenSettingNames.add( feature.settingName );
uniqueFeatures.push( feature );
}
return uniqueFeatures;
}, [ editedRecord ] );
const featureGroups = useMemo< FeatureGroupData[] >(
() =>
PAGE_DATA.featureGroups.length > 0
? PAGE_DATA.featureGroups
: buildFallbackFeatureGroups( featureDefinitions ),
[ featureDefinitions ]
);
const aiSettingKeys = useMemo( () => {
const settingKeys = new Set< string >( [ GLOBAL_FIELD_ID ] );
for ( const feature of featureDefinitions ) {
settingKeys.add( feature.settingName );
}
return Array.from( settingKeys );
}, [ featureDefinitions ] );
const data: AISettings = useMemo( () => {
const aiSettings: AISettings = {};
for ( const key of aiSettingKeys ) {
aiSettings[ key ] = Boolean( editedRecord?.[ key ] ?? false );
}
return aiSettings;
}, [ aiSettingKeys, editedRecord ] );
const globalEnabled = Boolean( data[ GLOBAL_FIELD.id ] );
const handleChange = useCallback(
async ( edits: Record< string, unknown > ) => {
const keys = Object.keys( edits );
// Optimistic update — the UI reflects the new value immediately.
// @ts-expect-error -- core-data types don't expose editEntityRecord for 'root'/'site' args.
editEntityRecord( 'root', 'site', undefined, edits );
const message = buildToggleMessage( edits, featureDefinitions );
try {
await saveSpecifiedEdits( 'root', 'site', undefined, keys, {
throwOnError: true,
} );
createSuccessNotice( message, { type: 'snackbar' } );
} catch {
// Revert only the toggled keys to their server-side values.
const serverRecord = ( registry as any )
.select( coreStore )
.getEntityRecord( 'root', 'site' ) as
| Record< string, unknown >
| undefined;
const revert: Record< string, unknown > = {};
for ( const key of keys ) {
revert[ key ] = serverRecord?.[ key ];
}
// @ts-expect-error -- core-data types don't expose editEntityRecord for 'root'/'site' args.
editEntityRecord( 'root', 'site', undefined, revert );
createErrorNotice( __( 'Failed to save settings.', 'ai' ), {
type: 'snackbar',
} );
}
},
[
editEntityRecord,
saveSpecifiedEdits,
createSuccessNotice,
createErrorNotice,
featureDefinitions,
registry,
]
);
const fields = useMemo< Field< AISettings >[] >( () => {
const sectionActionsFields: Field< AISettings >[] = [];
const groupedFields = new Map< string, string[] >();
// Group features by category
for ( const feature of featureDefinitions ) {
const category = feature.category || 'other';
const categoryFields = groupedFields.get( category ) ?? [];
categoryFields.push( feature.settingName );
groupedFields.set( category, categoryFields );
}
// Create section action fields for each group
for ( const group of featureGroups ) {
const experimentSettings = groupedFields.get( group.id ) ?? [];
if ( experimentSettings.length === 0 ) {
continue;
}
const actionFieldId = `section-actions-${ group.id }`;
sectionActionsFields.push( {
id: actionFieldId,
label: '',
type: 'text',
Edit: ( props ) => (
<SectionActions
{ ...props }
experimentSettings={ experimentSettings }
globalEnabled={ globalEnabled }
onBulkChange={ handleChange }
/>
),
} );
}
// Create feature toggle fields
const featureFields = featureDefinitions.map( ( feature ) => {
const baseField: Field< AISettings > = {
id: feature.settingName,
label: feature.label,
description: feature.description,
type: 'boolean' as const,
};
if ( VISUAL_CARD_FEATURES.has( feature.settingName ) ) {
baseField.Edit = VisualCardToggle;
} else if ( ! globalEnabled ) {
baseField.Edit = DisabledToggle;
} else if ( feature.settingsFields.length > 0 ) {
baseField.Edit = FeatureToggleWithSettings;
} else {
baseField.Edit = 'toggle' as const;
}
return baseField;
} );
return [ ...sectionActionsFields, ...featureFields ];
}, [ featureDefinitions, featureGroups, globalEnabled, handleChange ] );
const form = useMemo< Form >( () => {
const showcaseChildren: string[] = [];
const groupedFields = new Map< string, string[] >();
for ( const feature of featureDefinitions ) {
if ( VISUAL_CARD_FEATURES.has( feature.settingName ) ) {
showcaseChildren.push( feature.settingName );
} else {
const category = feature.category || 'other';
const categoryFields = groupedFields.get( category ) ?? [];
categoryFields.push( feature.settingName );
groupedFields.set( category, categoryFields );
}
}
const sectionFields: NonNullable< Form[ 'fields' ] > = [];
// Add showcase section with row layout (2 per row).
if ( showcaseChildren.length > 0 ) {
const rows: NonNullable< Form[ 'fields' ] > = [];
for ( let i = 0; i < showcaseChildren.length; i += 2 ) {
rows.push( {
id: `showcase-row-${ i }`,
layout: { type: 'row' as const },
children: showcaseChildren.slice( i, i + 2 ),
} );
}
sectionFields.push( {
id: 'feature-group-showcase',
layout: {
type: 'regular',
labelPosition: 'none',
},
children: rows,
} );
}
const seenCategories = new Set< string >();
for ( const group of featureGroups ) {
const children = groupedFields.get( group.id ) ?? [];
if ( children.length === 0 ) {
continue;
}
seenCategories.add( group.id );
const actionFieldId = `section-actions-${ group.id }`;
sectionFields.push( {
id: getSectionId( group.id ),
label: group.label,
description: group.description,
layout: {
type: 'card',
withHeader: true,
isOpened: true,
isCollapsible: true,
},
children: [ ...children, actionFieldId ],
} );
}
for ( const [ category, children ] of groupedFields.entries() ) {
if ( children.length === 0 || seenCategories.has( category ) ) {
continue;
}
const actionFieldId = `section-actions-${ category }`;
sectionFields.push( {
id: getSectionId( category ),
label: getDefaultLabel( category ),
description: '',
layout: {
type: 'card',
withHeader: true,
isOpened: true,
isCollapsible: true,
},
children: [ ...children, actionFieldId ],
} );
}
return {
fields: sectionFields,
};
}, [ featureDefinitions, featureGroups ] );
return (
<Page
title={
<>
<AIIcon />
{ __( 'AI', 'ai' ) }
</>
}
subTitle={ __(
'Configure AI features and experiments for your WordPress site.',
'ai'
) }
actions={
<div className="ai-settings-page__actions">
<GlobalEnableControl
enabled={ globalEnabled }
disabled={ isLoading }
onToggle={ ( value ) =>
void handleChange( { [ GLOBAL_FIELD_ID ]: value } )
}
/>
<ExternalLink href="https://github.com/WordPress/ai/tree/develop/docs">
{ __( 'Docs', 'ai' ) }
</ExternalLink>
<ExternalLink href="https://github.com/WordPress/ai/blob/develop/CONTRIBUTING.md">
{ __( 'Contribute', 'ai' ) }
</ExternalLink>
</div>
}
>
<div className="ai-settings-page">
{ ! PAGE_DATA.hasValidCredentials && (
<Notice status="error" isDismissible={ false }>
{ ! PAGE_DATA.hasCredentials
? __(
'The AI plugin requires a valid AI Connector to function properly. Verify you have one or more AI Connectors configured.',
'ai'
)
: __(
'The AI plugin requires a valid AI Connector to function properly. Please review the AI Connectors you have configured to ensure they are valid.',
'ai'
) }{ ' ' }
{ PAGE_DATA.connectorsUrl && (
<Button
variant="link"
href={ PAGE_DATA.connectorsUrl }
>
{ __( 'Manage Connectors', 'ai' ) }
</Button>
) }
</Notice>
) }
{ isLoading ? (
<Spinner />
) : (
<DataForm< AISettings >
data={ data }
fields={ fields }
form={ form }
onChange={ handleChange }
/>
) }
</div>
</Page>
);
}
export const stage = AISettingsPage;