-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathedit.js
More file actions
480 lines (449 loc) · 13.5 KB
/
edit.js
File metadata and controls
480 lines (449 loc) · 13.5 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
/**
* External dependencies.
*/
import { v4 as uuidv4 } from 'uuid';
/**
* WordPress dependencies.
*/
import {
BlockControls,
InnerBlocks,
useBlockProps,
InspectorControls,
InspectorAdvancedControls,
PanelColorSettings,
RichText,
} from '@wordpress/block-editor';
import {
BoxControl,
PanelBody,
ToolbarButton,
RangeControl,
// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
__experimentalToggleGroupControl as ToggleGroupControl,
// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
__experimentalToggleGroupControlOption as ToggleGroupControlOption,
ToolbarGroup,
ToggleControl,
SelectControl,
} from '@wordpress/components';
import { __, sprintf } from '@wordpress/i18n';
import { useState, useEffect } from '@wordpress/element';
import { dispatch, select, useSelect } from '@wordpress/data';
/**
* Internal dependencies.
*/
import { useIsBlockOrDescendantSelected } from './helpers';
/**
* Edit component for the GatherPress Dropdown block.
*
* This component is used in the WordPress editor to manage the editable interface
* for the GatherPress Dropdown block. It allows users to configure the block's
* attributes and settings directly within the editor.
*
* @since 1.0.0
*
* @param {Object} props The props object passed to the component.
* @param {Object} props.attributes The attributes for the block.
* @param {Function} props.setAttributes A function to update block attributes.
* @param {string} props.clientId The unique identifier for the block instance.
*
* @return {JSX.Element} The rendered edit interface for the block.
*/
const Edit = ( { attributes, setAttributes, clientId } ) => {
const blockProps = useBlockProps();
const [ isExpanded, setIsExpanded ] = useState( false );
const {
actAsSelect,
dropdownBorderColor,
dropdownBorderRadius,
dropdownBorderThickness,
dropdownId,
dropdownWidth,
dropdownZIndex,
itemBgColor,
itemDividerColor,
itemDividerThickness,
itemHoverBgColor,
itemHoverTextColor,
itemPadding,
itemTextColor,
label,
labelTextColor,
openOn,
selectedIndex,
} = attributes;
const innerBlocks = useSelect(
( blockEditorSelect ) =>
blockEditorSelect( 'core/block-editor' ).getBlock( clientId )
?.innerBlocks || [],
[ clientId ],
);
// Track if dropdown or its children are selected for auto-close behavior.
const isDropdownOrChildSelected = useIsBlockOrDescendantSelected( clientId );
// Get the currently selected block ID.
const selectedBlockId = useSelect(
( blockEditorSelect ) =>
blockEditorSelect( 'core/block-editor' ).getSelectedBlockClientId(),
[]
);
// Auto-expand dropdown when a child block is selected (e.g., from List View)
// and auto-close when clicking outside the dropdown tree.
useEffect( () => {
if ( isDropdownOrChildSelected && selectedBlockId !== clientId ) {
// A child block is selected (not the dropdown itself), expand.
setIsExpanded( true );
} else if ( ! isDropdownOrChildSelected && isExpanded ) {
// Nothing in the dropdown tree is selected, close.
setIsExpanded( false );
}
}, [ isDropdownOrChildSelected, selectedBlockId, clientId, isExpanded ] );
// Generate a persistent unique ID for the dropdown if not already set.
useEffect( () => {
if ( ! dropdownId ) {
const newDropdownId = `dropdown-${ uuidv4() }`;
setAttributes( { dropdownId: newDropdownId } );
}
}, [ dropdownId, setAttributes ] );
// Update `metadata.name` with the label value for the List View.
useEffect( () => {
const currentLabel = label || __( 'Dropdown', 'gatherpress' );
const currentMetadata =
select( 'core/block-editor' ).getBlockAttributes( clientId )
?.metadata || {};
// Only update if the metadata name differs from the current label.
if ( currentMetadata.name !== currentLabel ) {
dispatch( 'core/block-editor' ).updateBlockAttributes( clientId, {
metadata: { ...currentMetadata, name: currentLabel },
} );
}
}, [ label, clientId ] );
useEffect( () => {
// Ensure this effect only runs when `actAsSelect` is enabled.
if ( ! actAsSelect ) {
return;
}
// Validate innerBlocks exists and has items
if ( ! Array.isArray( innerBlocks ) || ! innerBlocks.length ) {
return;
}
// Validate selectedIndex is within bounds
if ( 0 > selectedIndex || selectedIndex >= innerBlocks.length ) {
return;
}
const selectedBlock = innerBlocks[ selectedIndex ];
const selectedBlockText = selectedBlock?.attributes?.text || '';
// Parse and extract plain text to remove any markup.
const plainTextLabel = new DOMParser()
.parseFromString( selectedBlockText, 'text/html' )
.body.textContent.trim();
// Update the label if it differs from the current one.
if ( plainTextLabel && plainTextLabel !== label ) {
setAttributes( { label: plainTextLabel } );
}
}, [ actAsSelect, selectedIndex, innerBlocks, label, setAttributes ] );
useEffect( () => {
// Only run if actAsSelect is enabled and there are inner blocks
if ( ! actAsSelect || ! innerBlocks.length ) {
return;
}
// Check if selectedIndex is valid
if ( 0 > selectedIndex || selectedIndex >= innerBlocks.length ) {
return;
}
const selectedBlockText =
innerBlocks[ selectedIndex ]?.attributes?.text || '';
// Parse the selected block's text to remove any HTML markup.
const plainTextLabel = new DOMParser()
.parseFromString( selectedBlockText, 'text/html' )
.body.textContent.trim();
const newLabel =
plainTextLabel ||
__( 'Item', 'gatherpress' ) + ` ${ selectedIndex + 1 }`;
// Only update if the label has changed
if ( newLabel !== label ) {
setAttributes( { label: newLabel } );
}
}, [ innerBlocks, actAsSelect, selectedIndex, label, setAttributes ] );
const dropdownStyles = `
#${ dropdownId } .wp-block-gatherpress-dropdown-item {
padding: ${ parseInt( itemPadding?.top || 0, 10 ) }px
${ parseInt( itemPadding?.right || 0, 10 ) }px
${ parseInt( itemPadding?.bottom || 0, 10 ) }px
${ parseInt( itemPadding?.left || 0, 10 ) }px;
color: ${ itemTextColor || 'inherit' };
background-color: ${ itemBgColor || 'transparent' };
}
#${ dropdownId } .wp-block-gatherpress-dropdown-item:hover {
color: ${ itemHoverTextColor || 'inherit' };
background-color: ${ itemHoverBgColor || 'transparent' };
}
#${ dropdownId } .wp-block-gatherpress-dropdown-item:not(:first-child) {
border-top: ${ itemDividerThickness || 1 }px solid ${ itemDividerColor || 'transparent' };
}
`;
// Toggle dropdown visibility.
const handleToggle = () => {
setIsExpanded( ( prev ) => ! prev );
};
return (
<div { ...blockProps }>
<InspectorControls>
<PanelBody
title={ __( 'Dropdown Settings', 'gatherpress' ) }
initialOpen={ true }
>
<RangeControl
label={ __( 'Dropdown Z-Index', 'gatherpress' ) }
value={ dropdownZIndex }
onChange={ ( value ) =>
setAttributes( { dropdownZIndex: value } )
}
min={ 0 }
max={ 9999 }
/>
<RangeControl
label={ __( 'Dropdown Width', 'gatherpress' ) }
value={ parseInt( dropdownWidth, 10 ) }
onChange={ ( value ) =>
setAttributes( { dropdownWidth: value } )
}
min={ 100 }
max={ 300 }
/>
<RangeControl
label={ __( 'Dropdown Border Thickness', 'gatherpress' ) }
value={ dropdownBorderThickness || 1 }
onChange={ ( value ) =>
setAttributes( { dropdownBorderThickness: value } )
}
min={ 0 }
max={ 20 }
/>
<RangeControl
label={ __( 'Dropdown Border Radius', 'gatherpress' ) }
value={ dropdownBorderRadius }
onChange={ ( value ) =>
setAttributes( { dropdownBorderRadius: value } )
}
min={ 0 }
max={ 50 }
/>
<BoxControl
label={ __( 'Item Padding', 'gatherpress' ) }
values={ itemPadding || 8 }
onChange={ ( value ) =>
setAttributes( { itemPadding: value } )
}
/>
<RangeControl
label={ __( 'Item Divider Thickness', 'gatherpress' ) }
value={ itemDividerThickness || 1 }
onChange={ ( value ) =>
setAttributes( { itemDividerThickness: value } )
}
min={ 0 }
max={ 10 }
/>
</PanelBody>
<PanelColorSettings
title={ __( 'Label Colors', 'gatherpress' ) }
colorSettings={ [
{
value: labelTextColor,
onChange: ( value ) =>
setAttributes( { labelTextColor: value } ),
label: __( 'Label Text Color', 'gatherpress' ),
},
] }
/>
<PanelColorSettings
title={ __( 'Dropdown Colors', 'gatherpress' ) }
colorSettings={ [
{
value: dropdownBorderColor,
onChange: ( value ) =>
setAttributes( { dropdownBorderColor: value } ),
label: __( 'Dropdown Border Color', 'gatherpress' ),
},
] }
/>
<PanelColorSettings
title={ __( 'Item Colors', 'gatherpress' ) }
colorSettings={ [
{
value: itemTextColor,
onChange: ( value ) =>
setAttributes( { itemTextColor: value } ),
label: __( 'Item Text Color', 'gatherpress' ),
},
{
value: itemBgColor,
onChange: ( value ) =>
setAttributes( { itemBgColor: value } ),
label: __( 'Item Background Color', 'gatherpress' ),
},
{
value: itemHoverTextColor,
onChange: ( value ) =>
setAttributes( { itemHoverTextColor: value } ),
label: __( 'Item Hover Text Color', 'gatherpress' ),
},
{
value: itemHoverBgColor,
onChange: ( value ) =>
setAttributes( { itemHoverBgColor: value } ),
label: __(
'Item Hover Background Color',
'gatherpress',
),
},
{
value: itemDividerColor,
onChange: ( newColor ) =>
setAttributes( { itemDividerColor: newColor } ),
label: __( 'Item Divider Color', 'gatherpress' ),
},
] }
/>
</InspectorControls>
<InspectorAdvancedControls>
<ToggleGroupControl
label={ __( 'Open on', 'gatherpress' ) }
value={ openOn }
isBlock
__nextHasNoMarginBottom
__next40pxDefaultSize
onChange={ ( value ) => setAttributes( { openOn: value } ) }
>
<ToggleGroupControlOption
value="click"
label={ __( 'Click', 'gatherpress' ) }
/>
<ToggleGroupControlOption
value="hover"
label={ __( 'Hover', 'gatherpress' ) }
/>
</ToggleGroupControl>
{ 0 < innerBlocks.length && (
<>
<ToggleControl
label={ __( 'Enable Select Mode', 'gatherpress' ) }
help={ __(
'When enabled, clicking on an item will set it as the dropdown label, and the selected item will be disabled until another is chosen.',
'gatherpress',
) }
checked={ actAsSelect }
onChange={ ( value ) =>
setAttributes( { actAsSelect: value } )
}
/>
{ actAsSelect && (
<SelectControl
label={ __(
'Default Selected Item',
'gatherpress',
) }
help={ __(
'This item will be selected by default when the dropdown is displayed.',
'gatherpress',
) }
value={ selectedIndex }
options={ innerBlocks.map( ( block, index ) => {
// Parse and extract plain text to remove markup.
const plainTextLabel = new DOMParser()
.parseFromString(
block.attributes.text || '',
'text/html',
)
.body.textContent.trim();
/* translators: %d is the index of the item. */
const labelTemplate = __(
'Item %d',
'gatherpress',
);
return {
label:
plainTextLabel ||
sprintf( labelTemplate, index + 1 ),
value: index,
};
} ) }
onChange={ ( value ) =>
setAttributes( {
selectedIndex: parseInt( value, 10 ),
} )
}
/>
) }
</>
) }
</InspectorAdvancedControls>
<BlockControls>
<ToolbarGroup>
<ToolbarButton
icon={ isExpanded ? 'no-alt' : 'plus' }
onClick={ handleToggle }
label={
isExpanded
? __( 'Close Dropdown', 'gatherpress' )
: __( 'Open Dropdown', 'gatherpress' )
}
/>
</ToolbarGroup>
</BlockControls>
{ actAsSelect ? (
// Use plain anchor when actAsSelect is enabled.
// eslint-disable-next-line jsx-a11y/anchor-is-valid
<a
href="#"
role="button"
aria-expanded={ isExpanded }
aria-controls={ dropdownId }
tabIndex={ 0 }
className="wp-block-gatherpress-dropdown__trigger"
style={ {
color: labelTextColor,
} }
>
{ label }
</a>
) : (
// Use RichText when actAsSelect is disabled.
<RichText
tagName="a"
href="#"
role="button"
aria-expanded={ isExpanded }
aria-controls={ dropdownId }
tabIndex={ 0 }
className="wp-block-gatherpress-dropdown__trigger"
value={ label }
onChange={ ( value ) => {
setAttributes( { label: value } );
} }
allowedFormats={ [] }
placeholder={ __( 'Dropdown Label…', 'gatherpress' ) }
style={ {
color: labelTextColor,
} }
/>
) }
<style>{ dropdownStyles }</style>
<div
id={ dropdownId }
className="wp-block-gatherpress-dropdown__menu"
style={ {
display: isExpanded ? 'block' : 'none',
backgroundColor: itemBgColor,
border: `${ dropdownBorderThickness || 1 }px solid ${ dropdownBorderColor || '#000000' }`,
borderRadius: `${ dropdownBorderRadius || 0 }px`,
width: dropdownWidth,
} }
>
<InnerBlocks allowedBlocks={ [ 'gatherpress/dropdown-item' ] } />
</div>
</div>
);
};
export default Edit;