-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
actions.js
1202 lines (1099 loc) · 29.9 KB
/
actions.js
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
998
999
1000
/**
* WordPress dependencies
*/
import { speak } from '@wordpress/a11y';
import apiFetch from '@wordpress/api-fetch';
import deprecated from '@wordpress/deprecated';
import {
parse,
synchronizeBlocksWithTemplate,
__unstableSerializeAndClean,
} from '@wordpress/blocks';
import { store as noticesStore } from '@wordpress/notices';
import { store as coreStore } from '@wordpress/core-data';
import { store as blockEditorStore } from '@wordpress/block-editor';
import {
applyFilters,
applyFiltersAsync,
doActionAsync,
} from '@wordpress/hooks';
import { store as preferencesStore } from '@wordpress/preferences';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { TRASH_POST_NOTICE_ID } from './constants';
import { localAutosaveSet } from './local-autosave';
import {
getNotificationArgumentsForSaveSuccess,
getNotificationArgumentsForSaveFail,
getNotificationArgumentsForTrashFail,
} from './utils/notice-builder';
import { unlock } from '../lock-unlock';
/**
* Returns an action generator used in signalling that editor has initialized with
* the specified post object and editor settings.
*
* @param {Object} post Post object.
* @param {Object} edits Initial edited attributes object.
* @param {Array} [template] Block Template.
*/
export const setupEditor =
( post, edits, template ) =>
( { dispatch } ) => {
dispatch.setEditedPost( post.type, post.id );
// Apply a template for new posts only, if exists.
const isNewPost = post.status === 'auto-draft';
if ( isNewPost && template ) {
// In order to ensure maximum of a single parse during setup, edits are
// included as part of editor setup action. Assume edited content as
// canonical if provided, falling back to post.
let content;
if ( 'content' in edits ) {
content = edits.content;
} else {
content = post.content.raw;
}
let blocks = parse( content );
blocks = synchronizeBlocksWithTemplate( blocks, template );
dispatch.resetEditorBlocks( blocks, {
__unstableShouldCreateUndoLevel: false,
} );
}
if (
edits &&
Object.values( edits ).some(
( [ key, edit ] ) =>
edit !== ( post[ key ]?.raw ?? post[ key ] )
)
) {
dispatch.editPost( edits );
}
};
/**
* Returns an action object signalling that the editor is being destroyed and
* that any necessary state or side-effect cleanup should occur.
*
* @deprecated
*
* @return {Object} Action object.
*/
export function __experimentalTearDownEditor() {
deprecated(
"wp.data.dispatch( 'core/editor' ).__experimentalTearDownEditor",
{
since: '6.5',
}
);
return { type: 'DO_NOTHING' };
}
/**
* Returns an action object used in signalling that the latest version of the
* post has been received, either by initialization or save.
*
* @deprecated Since WordPress 6.0.
*/
export function resetPost() {
deprecated( "wp.data.dispatch( 'core/editor' ).resetPost", {
since: '6.0',
version: '6.3',
alternative: 'Initialize the editor with the setupEditorState action',
} );
return { type: 'DO_NOTHING' };
}
/**
* Returns an action object used in signalling that a patch of updates for the
* latest version of the post have been received.
*
* @return {Object} Action object.
* @deprecated since Gutenberg 9.7.0.
*/
export function updatePost() {
deprecated( "wp.data.dispatch( 'core/editor' ).updatePost", {
since: '5.7',
alternative: 'Use the core entities store instead',
} );
return {
type: 'DO_NOTHING',
};
}
/**
* Setup the editor state.
*
* @deprecated
*
* @param {Object} post Post object.
*/
export function setupEditorState( post ) {
deprecated( "wp.data.dispatch( 'core/editor' ).setupEditorState", {
since: '6.5',
alternative: "wp.data.dispatch( 'core/editor' ).setEditedPost",
} );
return setEditedPost( post.type, post.id );
}
/**
* Returns an action that sets the current post Type and post ID.
*
* @param {string} postType Post Type.
* @param {string} postId Post ID.
*
* @return {Object} Action object.
*/
export function setEditedPost( postType, postId ) {
return {
type: 'SET_EDITED_POST',
postType,
postId,
};
}
/**
* Returns an action object used in signalling that attributes of the post have
* been edited.
*
* @param {Object} edits Post attributes to edit.
* @param {Object} [options] Options for the edit.
*
* @example
* ```js
* // Update the post title
* wp.data.dispatch( 'core/editor' ).editPost( { title: `${ newTitle }` } );
* ```
*
* @example
*```js
* // Get specific media size based on the featured media ID
* // Note: change sizes?.large for any registered size
* const getFeaturedMediaUrl = useSelect( ( select ) => {
* const getFeaturedMediaId =
* select( 'core/editor' ).getEditedPostAttribute( 'featured_media' );
* const getMedia = select( 'core' ).getMedia( getFeaturedMediaId );
*
* return (
* getMedia?.media_details?.sizes?.large?.source_url || getMedia?.source_url || ''
* );
* }, [] );
* ```
*
* @return {Object} Action object
*/
export const editPost =
( edits, options ) =>
( { select, registry } ) => {
const { id, type } = select.getCurrentPost();
registry
.dispatch( coreStore )
.editEntityRecord( 'postType', type, id, edits, options );
};
/**
* Action for saving the current post in the editor.
*
* @param {Object} [options]
*/
export const savePost =
( options = {} ) =>
async ( { select, dispatch, registry } ) => {
if ( ! select.isEditedPostSaveable() ) {
return;
}
const content = select.getEditedPostContent();
if ( ! options.isAutosave ) {
dispatch.editPost( { content }, { undoIgnore: true } );
}
const previousRecord = select.getCurrentPost();
let edits = {
id: previousRecord.id,
...registry
.select( coreStore )
.getEntityRecordNonTransientEdits(
'postType',
previousRecord.type,
previousRecord.id
),
content,
};
dispatch( { type: 'REQUEST_POST_UPDATE_START', options } );
let error = false;
try {
edits = await applyFiltersAsync(
'editor.preSavePost',
edits,
options
);
} catch ( err ) {
error = err;
}
if ( ! error ) {
try {
await registry
.dispatch( coreStore )
.saveEntityRecord(
'postType',
previousRecord.type,
edits,
options
);
} catch ( err ) {
error =
err.message && err.code !== 'unknown_error'
? err.message
: __( 'An error occurred while updating.' );
}
}
if ( ! error ) {
error = registry
.select( coreStore )
.getLastEntitySaveError(
'postType',
previousRecord.type,
previousRecord.id
);
}
// Run the hook with legacy unstable name for backward compatibility
if ( ! error ) {
try {
await applyFilters(
'editor.__unstableSavePost',
Promise.resolve(),
options
);
} catch ( err ) {
error = err;
}
}
if ( ! error ) {
try {
await doActionAsync(
'editor.savePost',
{ id: previousRecord.id },
options
);
} catch ( err ) {
error = err;
}
}
dispatch( { type: 'REQUEST_POST_UPDATE_FINISH', options } );
if ( error ) {
const args = getNotificationArgumentsForSaveFail( {
post: previousRecord,
edits,
error,
} );
if ( args.length ) {
registry.dispatch( noticesStore ).createErrorNotice( ...args );
}
} else {
const updatedRecord = select.getCurrentPost();
const args = getNotificationArgumentsForSaveSuccess( {
previousPost: previousRecord,
post: updatedRecord,
postType: await registry
.resolveSelect( coreStore )
.getPostType( updatedRecord.type ),
options,
} );
if ( args.length ) {
registry
.dispatch( noticesStore )
.createSuccessNotice( ...args );
}
// Make sure that any edits after saving create an undo level and are
// considered for change detection.
if ( ! options.isAutosave ) {
registry
.dispatch( blockEditorStore )
.__unstableMarkLastChangeAsPersistent();
}
}
};
/**
* Action for refreshing the current post.
*
* @deprecated Since WordPress 6.0.
*/
export function refreshPost() {
deprecated( "wp.data.dispatch( 'core/editor' ).refreshPost", {
since: '6.0',
version: '6.3',
alternative: 'Use the core entities store instead',
} );
return { type: 'DO_NOTHING' };
}
/**
* Action for trashing the current post in the editor.
*/
export const trashPost =
() =>
async ( { select, dispatch, registry } ) => {
const postTypeSlug = select.getCurrentPostType();
const postType = await registry
.resolveSelect( coreStore )
.getPostType( postTypeSlug );
registry.dispatch( noticesStore ).removeNotice( TRASH_POST_NOTICE_ID );
const { rest_base: restBase, rest_namespace: restNamespace = 'wp/v2' } =
postType;
dispatch( { type: 'REQUEST_POST_DELETE_START' } );
try {
const post = select.getCurrentPost();
await apiFetch( {
path: `/${ restNamespace }/${ restBase }/${ post.id }`,
method: 'DELETE',
} );
await dispatch.savePost();
} catch ( error ) {
registry
.dispatch( noticesStore )
.createErrorNotice(
...getNotificationArgumentsForTrashFail( { error } )
);
}
dispatch( { type: 'REQUEST_POST_DELETE_FINISH' } );
};
/**
* Action that autosaves the current post. This
* includes server-side autosaving (default) and client-side (a.k.a. local)
* autosaving (e.g. on the Web, the post might be committed to Session
* Storage).
*
* @param {Object} [options] Extra flags to identify the autosave.
* @param {boolean} [options.local] Whether to perform a local autosave.
*/
export const autosave =
( { local = false, ...options } = {} ) =>
async ( { select, dispatch } ) => {
const post = select.getCurrentPost();
// Currently template autosaving is not supported.
if ( post.type === 'wp_template' ) {
return;
}
if ( local ) {
const isPostNew = select.isEditedPostNew();
const title = select.getEditedPostAttribute( 'title' );
const content = select.getEditedPostAttribute( 'content' );
const excerpt = select.getEditedPostAttribute( 'excerpt' );
localAutosaveSet( post.id, isPostNew, title, content, excerpt );
} else {
await dispatch.savePost( { isAutosave: true, ...options } );
}
};
export const __unstableSaveForPreview =
( { forceIsAutosaveable } = {} ) =>
async ( { select, dispatch } ) => {
if (
( forceIsAutosaveable || select.isEditedPostAutosaveable() ) &&
! select.isPostLocked()
) {
const isDraft = [ 'draft', 'auto-draft' ].includes(
select.getEditedPostAttribute( 'status' )
);
if ( isDraft ) {
await dispatch.savePost( { isPreview: true } );
} else {
await dispatch.autosave( { isPreview: true } );
}
}
return select.getEditedPostPreviewLink();
};
/**
* Action that restores last popped state in undo history.
*/
export const redo =
() =>
( { registry } ) => {
registry.dispatch( coreStore ).redo();
};
/**
* Action that pops a record from undo history and undoes the edit.
*/
export const undo =
() =>
( { registry } ) => {
registry.dispatch( coreStore ).undo();
};
/**
* Action that creates an undo history record.
*
* @deprecated Since WordPress 6.0
*/
export function createUndoLevel() {
deprecated( "wp.data.dispatch( 'core/editor' ).createUndoLevel", {
since: '6.0',
version: '6.3',
alternative: 'Use the core entities store instead',
} );
return { type: 'DO_NOTHING' };
}
/**
* Action that locks the editor.
*
* @param {Object} lock Details about the post lock status, user, and nonce.
* @return {Object} Action object.
*/
export function updatePostLock( lock ) {
return {
type: 'UPDATE_POST_LOCK',
lock,
};
}
/**
* Enable the publish sidebar.
*/
export const enablePublishSidebar =
() =>
( { registry } ) => {
registry
.dispatch( preferencesStore )
.set( 'core', 'isPublishSidebarEnabled', true );
};
/**
* Disables the publish sidebar.
*/
export const disablePublishSidebar =
() =>
( { registry } ) => {
registry
.dispatch( preferencesStore )
.set( 'core', 'isPublishSidebarEnabled', false );
};
/**
* Action that locks post saving.
*
* @param {string} lockName The lock name.
*
* @example
* ```
* const { subscribe } = wp.data;
*
* const initialPostStatus = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'status' );
*
* // Only allow publishing posts that are set to a future date.
* if ( 'publish' !== initialPostStatus ) {
*
* // Track locking.
* let locked = false;
*
* // Watch for the publish event.
* let unssubscribe = subscribe( () => {
* const currentPostStatus = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'status' );
* if ( 'publish' !== currentPostStatus ) {
*
* // Compare the post date to the current date, lock the post if the date isn't in the future.
* const postDate = new Date( wp.data.select( 'core/editor' ).getEditedPostAttribute( 'date' ) );
* const currentDate = new Date();
* if ( postDate.getTime() <= currentDate.getTime() ) {
* if ( ! locked ) {
* locked = true;
* wp.data.dispatch( 'core/editor' ).lockPostSaving( 'futurelock' );
* }
* } else {
* if ( locked ) {
* locked = false;
* wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'futurelock' );
* }
* }
* }
* } );
* }
* ```
*
* @return {Object} Action object
*/
export function lockPostSaving( lockName ) {
return {
type: 'LOCK_POST_SAVING',
lockName,
};
}
/**
* Action that unlocks post saving.
*
* @param {string} lockName The lock name.
*
* @example
* ```
* // Unlock post saving with the lock key `mylock`:
* wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'mylock' );
* ```
*
* @return {Object} Action object
*/
export function unlockPostSaving( lockName ) {
return {
type: 'UNLOCK_POST_SAVING',
lockName,
};
}
/**
* Action that locks post autosaving.
*
* @param {string} lockName The lock name.
*
* @example
* ```
* // Lock post autosaving with the lock key `mylock`:
* wp.data.dispatch( 'core/editor' ).lockPostAutosaving( 'mylock' );
* ```
*
* @return {Object} Action object
*/
export function lockPostAutosaving( lockName ) {
return {
type: 'LOCK_POST_AUTOSAVING',
lockName,
};
}
/**
* Action that unlocks post autosaving.
*
* @param {string} lockName The lock name.
*
* @example
* ```
* // Unlock post saving with the lock key `mylock`:
* wp.data.dispatch( 'core/editor' ).unlockPostAutosaving( 'mylock' );
* ```
*
* @return {Object} Action object
*/
export function unlockPostAutosaving( lockName ) {
return {
type: 'UNLOCK_POST_AUTOSAVING',
lockName,
};
}
/**
* Returns an action object used to signal that the blocks have been updated.
*
* @param {Array} blocks Block Array.
* @param {Object} [options] Optional options.
*/
export const resetEditorBlocks =
( blocks, options = {} ) =>
( { select, dispatch, registry } ) => {
const { __unstableShouldCreateUndoLevel, selection } = options;
const edits = { blocks, selection };
if ( __unstableShouldCreateUndoLevel !== false ) {
const { id, type } = select.getCurrentPost();
const noChange =
registry
.select( coreStore )
.getEditedEntityRecord( 'postType', type, id ).blocks ===
edits.blocks;
if ( noChange ) {
registry
.dispatch( coreStore )
.__unstableCreateUndoLevel( 'postType', type, id );
return;
}
// We create a new function here on every persistent edit
// to make sure the edit makes the post dirty and creates
// a new undo level.
edits.content = ( { blocks: blocksForSerialization = [] } ) =>
__unstableSerializeAndClean( blocksForSerialization );
}
dispatch.editPost( edits );
};
/*
* Returns an action object used in signalling that the post editor settings have been updated.
*
* @param {Object} settings Updated settings
*
* @return {Object} Action object
*/
export function updateEditorSettings( settings ) {
return {
type: 'UPDATE_EDITOR_SETTINGS',
settings,
};
}
/**
* Returns an action used to set the rendering mode of the post editor. We support multiple rendering modes:
*
* - `post-only`: This mode extracts the post blocks from the template and renders only those. The idea is to allow the user to edit the post/page in isolation without the wrapping template.
* - `template-locked`: This mode renders both the template and the post blocks but the template blocks are locked and can't be edited. The post blocks are editable.
*
* @param {string} mode Mode (one of 'post-only' or 'template-locked').
*/
export const setRenderingMode =
( mode ) =>
( { dispatch, registry, select } ) => {
if ( select.__unstableIsEditorReady() ) {
// We clear the block selection but we also need to clear the selection from the core store.
registry.dispatch( blockEditorStore ).clearSelectedBlock();
dispatch.editPost( { selection: undefined }, { undoIgnore: true } );
}
dispatch( {
type: 'SET_RENDERING_MODE',
mode,
} );
};
/**
* Action that changes the width of the editing canvas.
*
* @param {string} deviceType
*
* @return {Object} Action object.
*/
export function setDeviceType( deviceType ) {
return {
type: 'SET_DEVICE_TYPE',
deviceType,
};
}
/**
* Returns an action object used to enable or disable a panel in the editor.
*
* @param {string} panelName A string that identifies the panel to enable or disable.
*
* @return {Object} Action object.
*/
export const toggleEditorPanelEnabled =
( panelName ) =>
( { registry } ) => {
const inactivePanels =
registry
.select( preferencesStore )
.get( 'core', 'inactivePanels' ) ?? [];
const isPanelInactive = !! inactivePanels?.includes( panelName );
// If the panel is inactive, remove it to enable it, else add it to
// make it inactive.
let updatedInactivePanels;
if ( isPanelInactive ) {
updatedInactivePanels = inactivePanels.filter(
( invactivePanelName ) => invactivePanelName !== panelName
);
} else {
updatedInactivePanels = [ ...inactivePanels, panelName ];
}
registry
.dispatch( preferencesStore )
.set( 'core', 'inactivePanels', updatedInactivePanels );
};
/**
* Opens a closed panel and closes an open panel.
*
* @param {string} panelName A string that identifies the panel to open or close.
*/
export const toggleEditorPanelOpened =
( panelName ) =>
( { registry } ) => {
const openPanels =
registry.select( preferencesStore ).get( 'core', 'openPanels' ) ??
[];
const isPanelOpen = !! openPanels?.includes( panelName );
// If the panel is open, remove it to close it, else add it to
// make it open.
let updatedOpenPanels;
if ( isPanelOpen ) {
updatedOpenPanels = openPanels.filter(
( openPanelName ) => openPanelName !== panelName
);
} else {
updatedOpenPanels = [ ...openPanels, panelName ];
}
registry
.dispatch( preferencesStore )
.set( 'core', 'openPanels', updatedOpenPanels );
};
/**
* Returns an action object used to remove a panel from the editor.
*
* @param {string} panelName A string that identifies the panel to remove.
*
* @return {Object} Action object.
*/
export function removeEditorPanel( panelName ) {
return {
type: 'REMOVE_PANEL',
panelName,
};
}
/**
* Returns an action object used to open/close the inserter.
*
* @param {boolean|Object} value Whether the inserter should be
* opened (true) or closed (false).
* To specify an insertion point,
* use an object.
* @param {string} value.rootClientId The root client ID to insert at.
* @param {number} value.insertionIndex The index to insert at.
* @param {string} value.filterValue A query to filter the inserter results.
* @param {Function} value.onSelect A callback when an item is selected.
* @param {string} value.tab The tab to open in the inserter.
* @param {string} value.category The category to initialize in the inserter.
*
* @return {Object} Action object.
*/
export const setIsInserterOpened =
( value ) =>
( { dispatch, registry } ) => {
if (
typeof value === 'object' &&
value.hasOwnProperty( 'rootClientId' ) &&
value.hasOwnProperty( 'insertionIndex' )
) {
unlock( registry.dispatch( blockEditorStore ) ).setInsertionPoint( {
rootClientId: value.rootClientId,
index: value.insertionIndex,
} );
}
dispatch( {
type: 'SET_IS_INSERTER_OPENED',
value,
} );
};
/**
* Returns an action object used to open/close the list view.
*
* @param {boolean} isOpen A boolean representing whether the list view should be opened or closed.
* @return {Object} Action object.
*/
export function setIsListViewOpened( isOpen ) {
return {
type: 'SET_IS_LIST_VIEW_OPENED',
isOpen,
};
}
/**
* Action that toggles Distraction free mode.
* Distraction free mode expects there are no sidebars, as due to the
* z-index values set, you can't close sidebars.
*
* @param {Object} [options={}] Optional configuration object
* @param {boolean} [options.createNotice=true] Whether to create a notice
*/
export const toggleDistractionFree =
( { createNotice = true } = {} ) =>
( { dispatch, registry } ) => {
const isDistractionFree = registry
.select( preferencesStore )
.get( 'core', 'distractionFree' );
if ( isDistractionFree ) {
registry
.dispatch( preferencesStore )
.set( 'core', 'fixedToolbar', false );
}
if ( ! isDistractionFree ) {
registry.batch( () => {
registry
.dispatch( preferencesStore )
.set( 'core', 'fixedToolbar', true );
dispatch.setIsInserterOpened( false );
dispatch.setIsListViewOpened( false );
unlock(
registry.dispatch( blockEditorStore )
).resetZoomLevel();
} );
}
registry.batch( () => {
registry
.dispatch( preferencesStore )
.set( 'core', 'distractionFree', ! isDistractionFree );
if ( createNotice ) {
registry
.dispatch( noticesStore )
.createInfoNotice(
isDistractionFree
? __( 'Distraction free mode deactivated.' )
: __( 'Distraction free mode activated.' ),
{
id: 'core/editor/distraction-free-mode/notice',
type: 'snackbar',
actions: [
{
label: __( 'Undo' ),
onClick: () => {
registry.batch( () => {
registry
.dispatch( preferencesStore )
.set(
'core',
'fixedToolbar',
isDistractionFree
);
registry
.dispatch( preferencesStore )
.toggle(
'core',
'distractionFree'
);
} );
},
},
],
}
);
}
} );
};
/**
* Action that toggles the Spotlight Mode view option.
*/
export const toggleSpotlightMode =
() =>
( { registry } ) => {
registry.dispatch( preferencesStore ).toggle( 'core', 'focusMode' );
const isFocusMode = registry
.select( preferencesStore )
.get( 'core', 'focusMode' );
registry
.dispatch( noticesStore )
.createInfoNotice(
isFocusMode
? __( 'Spotlight mode activated.' )
: __( 'Spotlight mode deactivated.' ),
{
id: 'core/editor/toggle-spotlight-mode/notice',
type: 'snackbar',
actions: [
{
label: __( 'Undo' ),
onClick: () => {
registry
.dispatch( preferencesStore )
.toggle( 'core', 'focusMode' );
},
},
],
}
);
};
/**
* Action that toggles the Top Toolbar view option.
*/
export const toggleTopToolbar =
() =>
( { registry } ) => {
registry.dispatch( preferencesStore ).toggle( 'core', 'fixedToolbar' );
const isTopToolbar = registry
.select( preferencesStore )
.get( 'core', 'fixedToolbar' );
registry
.dispatch( noticesStore )
.createInfoNotice(
isTopToolbar
? __( 'Top toolbar activated.' )
: __( 'Top toolbar deactivated.' ),
{
id: 'core/editor/toggle-top-toolbar/notice',
type: 'snackbar',
actions: [
{
label: __( 'Undo' ),
onClick: () => {
registry
.dispatch( preferencesStore )
.toggle( 'core', 'fixedToolbar' );
},
},
],
}
);
};
/**
* Triggers an action used to switch editor mode.
*
* @param {string} mode The editor mode.
*/
export const switchEditorMode =
( mode ) =>
( { dispatch, registry } ) => {
registry.dispatch( preferencesStore ).set( 'core', 'editorMode', mode );
if ( mode !== 'visual' ) {
// Unselect blocks when we switch to a non visual mode.
registry.dispatch( blockEditorStore ).clearSelectedBlock();
// Exit zoom out state when switching to a non visual mode.
unlock( registry.dispatch( blockEditorStore ) ).resetZoomLevel();
}
if ( mode === 'visual' ) {
speak( __( 'Visual editor selected' ), 'assertive' );
} else if ( mode === 'text' ) {
const isDistractionFree = registry
.select( preferencesStore )
.get( 'core', 'distractionFree' );
if ( isDistractionFree ) {
dispatch.toggleDistractionFree();
}
speak( __( 'Code editor selected' ), 'assertive' );
}
};
/**
* Returns an action object used in signalling that the user opened the publish
* sidebar.
*
* @return {Object} Action object
*/
export function openPublishSidebar() {
return {
type: 'OPEN_PUBLISH_SIDEBAR',
};
}
/**
* Returns an action object used in signalling that the user closed the