-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathposition.js
404 lines (359 loc) · 11.2 KB
/
position.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
/**
* External dependencies
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { __, _x, sprintf } from '@wordpress/i18n';
import { getBlockSupport, hasBlockSupport } from '@wordpress/blocks';
import {
BaseControl,
privateApis as componentsPrivateApis,
} from '@wordpress/components';
import { createHigherOrderComponent, useInstanceId } from '@wordpress/compose';
import { useSelect } from '@wordpress/data';
import { useMemo, Platform } from '@wordpress/element';
import { addFilter } from '@wordpress/hooks';
/**
* Internal dependencies
*/
import { useSettings } from '../components/use-settings';
import InspectorControls from '../components/inspector-controls';
import useBlockDisplayInformation from '../components/use-block-display-information';
import { cleanEmptyObject, useStyleOverride } from './utils';
import { unlock } from '../lock-unlock';
import { store as blockEditorStore } from '../store';
const { CustomSelectControl } = unlock( componentsPrivateApis );
const POSITION_SUPPORT_KEY = 'position';
const OPTION_CLASSNAME =
'block-editor-hooks__position-selection__select-control__option';
const DEFAULT_OPTION = {
key: 'default',
value: '',
name: __( 'Default' ),
className: OPTION_CLASSNAME,
};
const STICKY_OPTION = {
key: 'sticky',
value: 'sticky',
name: _x( 'Sticky', 'Name for the value of the CSS position property' ),
className: OPTION_CLASSNAME,
__experimentalHint: __(
'The block will stick to the top of the window instead of scrolling.'
),
};
const FIXED_OPTION = {
key: 'fixed',
value: 'fixed',
name: _x( 'Fixed', 'Name for the value of the CSS position property' ),
className: OPTION_CLASSNAME,
__experimentalHint: __(
'The block will not move when the page is scrolled.'
),
};
const POSITION_SIDES = [ 'top', 'right', 'bottom', 'left' ];
const VALID_POSITION_TYPES = [ 'sticky', 'fixed' ];
/**
* Get calculated position CSS.
*
* @param {Object} props Component props.
* @param {string} props.selector Selector to use.
* @param {Object} props.style Style object.
* @return {string} The generated CSS rules.
*/
export function getPositionCSS( { selector, style } ) {
let output = '';
const { type: positionType } = style?.position || {};
if ( ! VALID_POSITION_TYPES.includes( positionType ) ) {
return output;
}
output += `${ selector } {`;
output += `position: ${ positionType };`;
POSITION_SIDES.forEach( ( side ) => {
if ( style?.position?.[ side ] !== undefined ) {
output += `${ side }: ${ style.position[ side ] };`;
}
} );
if ( positionType === 'sticky' || positionType === 'fixed' ) {
// TODO: Replace hard-coded z-index value with a z-index preset approach in theme.json.
output += `z-index: 10`;
}
output += `}`;
return output;
}
/**
* Determines if there is sticky position support.
*
* @param {string|Object} blockType Block name or Block Type object.
*
* @return {boolean} Whether there is support.
*/
export function hasStickyPositionSupport( blockType ) {
const support = getBlockSupport( blockType, POSITION_SUPPORT_KEY );
return !! ( true === support || support?.sticky );
}
/**
* Determines if there is fixed position support.
*
* @param {string|Object} blockType Block name or Block Type object.
*
* @return {boolean} Whether there is support.
*/
export function hasFixedPositionSupport( blockType ) {
const support = getBlockSupport( blockType, POSITION_SUPPORT_KEY );
return !! ( true === support || support?.fixed );
}
/**
* Determines if there is position support.
*
* @param {string|Object} blockType Block name or Block Type object.
*
* @return {boolean} Whether there is support.
*/
export function hasPositionSupport( blockType ) {
const support = getBlockSupport( blockType, POSITION_SUPPORT_KEY );
return !! support;
}
/**
* Checks if there is a current value in the position block support attributes.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a position value set.
*/
export function hasPositionValue( props ) {
return props.attributes.style?.position?.type !== undefined;
}
/**
* Checks if the block is currently set to a sticky or fixed position.
* This check is helpful for determining how to position block toolbars or other elements.
*
* @param {Object} attributes Block attributes.
* @return {boolean} Whether or not the block is set to a sticky or fixed position.
*/
export function hasStickyOrFixedPositionValue( attributes ) {
const positionType = attributes.style?.position?.type;
return positionType === 'sticky' || positionType === 'fixed';
}
/**
* Resets the position block support attributes. This can be used when disabling
* the position support controls for a block via a `ToolsPanel`.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
export function resetPosition( { attributes = {}, setAttributes } ) {
const { style = {} } = attributes;
setAttributes( {
style: cleanEmptyObject( {
...style,
position: {
...style?.position,
type: undefined,
top: undefined,
right: undefined,
bottom: undefined,
left: undefined,
},
} ),
} );
}
/**
* Custom hook that checks if position settings have been disabled.
*
* @param {string} name The name of the block.
*
* @return {boolean} Whether padding setting is disabled.
*/
export function useIsPositionDisabled( { name: blockName } = {} ) {
const [ allowFixed, allowSticky ] = useSettings(
'position.fixed',
'position.sticky'
);
const isDisabled = ! allowFixed && ! allowSticky;
return ! hasPositionSupport( blockName ) || isDisabled;
}
/*
* Position controls rendered in an inspector control panel.
*
* @param {Object} props
*
* @return {Element} Position panel.
*/
export function PositionPanel( props ) {
const {
attributes: { style = {} },
clientId,
name: blockName,
setAttributes,
} = props;
const allowFixed = hasFixedPositionSupport( blockName );
const allowSticky = hasStickyPositionSupport( blockName );
const value = style?.position?.type;
const { firstParentClientId } = useSelect(
( select ) => {
const { getBlockParents } = select( blockEditorStore );
const parents = getBlockParents( clientId );
return { firstParentClientId: parents[ parents.length - 1 ] };
},
[ clientId ]
);
const blockInformation = useBlockDisplayInformation( firstParentClientId );
const stickyHelpText =
allowSticky && value === STICKY_OPTION.value && blockInformation
? sprintf(
/* translators: %s: the name of the parent block. */
__(
'The block will stick to the scrollable area of the parent %s block.'
),
blockInformation.title
)
: null;
const options = useMemo( () => {
const availableOptions = [ DEFAULT_OPTION ];
// Display options if they are allowed, or if a block already has a valid value set.
// This allows for a block to be switched off from a position type that is not allowed.
if ( allowSticky || value === STICKY_OPTION.value ) {
availableOptions.push( STICKY_OPTION );
}
if ( allowFixed || value === FIXED_OPTION.value ) {
availableOptions.push( FIXED_OPTION );
}
return availableOptions;
}, [ allowFixed, allowSticky, value ] );
const onChangeType = ( next ) => {
// For now, use a hard-coded `0px` value for the position.
// `0px` is preferred over `0` as it can be used in `calc()` functions.
// In the future, it could be useful to allow for an offset value.
const placementValue = '0px';
const newStyle = {
...style,
position: {
...style?.position,
type: next,
top:
next === 'sticky' || next === 'fixed'
? placementValue
: undefined,
},
};
setAttributes( {
style: cleanEmptyObject( newStyle ),
} );
};
const selectedOption = value
? options.find( ( option ) => option.value === value ) || DEFAULT_OPTION
: DEFAULT_OPTION;
// Only display position controls if there is at least one option to choose from.
return Platform.select( {
web:
options.length > 1 ? (
<InspectorControls group="position">
<BaseControl
className="block-editor-hooks__position-selection"
__nextHasNoMarginBottom
help={ stickyHelpText }
>
<CustomSelectControl
__nextUnconstrainedWidth
__next40pxDefaultSize
className="block-editor-hooks__position-selection__select-control"
label={ __( 'Position' ) }
hideLabelFromVision
describedBy={ sprintf(
// translators: %s: Currently selected position.
__( 'Currently selected position: %s' ),
selectedOption.name
) }
options={ options }
value={ selectedOption }
__experimentalShowSelectedHint
onChange={ ( { selectedItem } ) => {
onChangeType( selectedItem.value );
} }
size={ '__unstable-large' }
/>
</BaseControl>
</InspectorControls>
) : null,
native: null,
} );
}
/**
* Override the default edit UI to include position controls.
*
* @param {Function} BlockEdit Original component.
*
* @return {Function} Wrapped component.
*/
export const withPositionControls = createHigherOrderComponent(
( BlockEdit ) => ( props ) => {
const { name: blockName } = props;
const positionSupport = hasBlockSupport(
blockName,
POSITION_SUPPORT_KEY
);
const isPositionDisabled = useIsPositionDisabled( props );
const showPositionControls = positionSupport && ! isPositionDisabled;
return [
showPositionControls && (
<PositionPanel key="position" { ...props } />
),
<BlockEdit key="edit" { ...props } />,
];
},
'withPositionControls'
);
/**
* Override the default block element to add the position styles.
*
* @param {Function} BlockListBlock Original component.
*
* @return {Function} Wrapped component.
*/
export const withPositionStyles = createHigherOrderComponent(
( BlockListBlock ) => ( props ) => {
const { name, attributes } = props;
const hasPositionBlockSupport = hasBlockSupport(
name,
POSITION_SUPPORT_KEY
);
const isPositionDisabled = useIsPositionDisabled( props );
const allowPositionStyles =
hasPositionBlockSupport && ! isPositionDisabled;
const id = useInstanceId( BlockListBlock );
// Higher specificity to override defaults in editor UI.
const positionSelector = `.wp-container-${ id }.wp-container-${ id }`;
// Get CSS string for the current position values.
let css;
if ( allowPositionStyles ) {
css =
getPositionCSS( {
selector: positionSelector,
style: attributes?.style,
} ) || '';
}
// Attach a `wp-container-` id-based class name.
const className = classnames( props?.className, {
[ `wp-container-${ id }` ]: allowPositionStyles && !! css, // Only attach a container class if there is generated CSS to be attached.
[ `is-position-${ attributes?.style?.position?.type }` ]:
allowPositionStyles &&
!! css &&
!! attributes?.style?.position?.type,
} );
useStyleOverride( { css } );
return <BlockListBlock { ...props } className={ className } />;
},
'withPositionStyles'
);
addFilter(
'editor.BlockListBlock',
'core/editor/position/with-position-styles',
withPositionStyles
);
addFilter(
'editor.BlockEdit',
'core/editor/position/with-inspector-controls',
withPositionControls
);