|
1 | 1 | import { __ } from '@wordpress/i18n'; |
2 | | -import { insert } from '@wordpress/rich-text'; |
| 2 | +import { applyFormat, insert, useAnchor } from '@wordpress/rich-text'; |
3 | 3 | import { RichTextShortcut } from '@wordpress/block-editor'; |
| 4 | +import { Popover } from '@wordpress/components'; |
4 | 5 |
|
5 | 6 | const name = 'core/non-breaking-space'; |
6 | 7 | const title = __( 'Non breaking space' ); |
7 | 8 |
|
| 9 | +function PopoverAnchor( { contentRef } ) { |
| 10 | + const popoverAnchor = useAnchor( { |
| 11 | + editableContentElement: contentRef.current, |
| 12 | + settings: nonBreakingSpace, |
| 13 | + } ); |
| 14 | + |
| 15 | + return ( |
| 16 | + <Popover anchor={ popoverAnchor }> |
| 17 | + <div style={ { whiteSpace: 'nowrap', padding: '4px' } }> |
| 18 | + { __( 'Non-breaking space' ) } |
| 19 | + </div> |
| 20 | + </Popover> |
| 21 | + ); |
| 22 | +} |
| 23 | + |
8 | 24 | export const nonBreakingSpace = { |
9 | 25 | name, |
10 | 26 | title, |
11 | | - tagName: 'nbsp', |
12 | | - className: null, |
13 | | - edit( { value, onChange } ) { |
| 27 | + tagName: 'span', |
| 28 | + className: 'non-breaking-space', |
| 29 | + edit( { value, onChange, contentRef } ) { |
14 | 30 | function addNonBreakingSpace() { |
15 | 31 | onChange( insert( value, '\u00a0' ) ); |
16 | 32 | } |
17 | 33 |
|
| 34 | + const selectedValue = |
| 35 | + value.start && value.end |
| 36 | + ? value.text.slice( value.start, value.end ) |
| 37 | + : null; |
| 38 | + |
18 | 39 | return ( |
19 | | - <RichTextShortcut |
20 | | - type="primaryShift" |
21 | | - character=" " |
22 | | - onUse={ addNonBreakingSpace } |
23 | | - /> |
| 40 | + <> |
| 41 | + <RichTextShortcut |
| 42 | + type="primaryShift" |
| 43 | + character=" " |
| 44 | + onUse={ addNonBreakingSpace } |
| 45 | + /> |
| 46 | + { selectedValue === '\u00a0' && ( |
| 47 | + <PopoverAnchor contentRef={ contentRef } /> |
| 48 | + ) } |
| 49 | + </> |
24 | 50 | ); |
25 | 51 | }, |
| 52 | + __experimentalCreatePrepareEditableTree() { |
| 53 | + return ( formats, text ) => { |
| 54 | + const NBSP = '\u00a0'; |
| 55 | + let record = { formats, text }; |
| 56 | + let index = -1; |
| 57 | + |
| 58 | + do { |
| 59 | + index = text.indexOf( NBSP, index + 1 ); |
| 60 | + if ( index !== -1 ) { |
| 61 | + record = applyFormat( |
| 62 | + record, |
| 63 | + { type: name }, |
| 64 | + index, |
| 65 | + index + 1 |
| 66 | + ); |
| 67 | + } |
| 68 | + } while ( index !== -1 ); |
| 69 | + |
| 70 | + return record.formats; |
| 71 | + }; |
| 72 | + }, |
26 | 73 | }; |
0 commit comments