-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathformat.js
112 lines (101 loc) · 2.52 KB
/
format.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
/**
* External dependencies
*/
import { v4 as createId } from 'uuid';
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { formatListNumbered as icon } from '@wordpress/icons';
import { insertObject } from '@wordpress/rich-text';
import {
RichTextToolbarButton,
store as blockEditorStore,
} from '@wordpress/block-editor';
import { useSelect, useDispatch, useRegistry } from '@wordpress/data';
import { createBlock } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import { name } from './block.json';
export const formatName = 'core/footnote';
export const format = {
title: __( 'Footnote' ),
tagName: 'a',
className: 'fn',
attributes: {
id: 'id',
href: 'href',
'data-fn': 'data-fn',
},
contentEditable: false,
edit: function Edit( { value, onChange, isObjectActive } ) {
const registry = useRegistry();
const {
getSelectedBlockClientId,
getBlockRootClientId,
getBlockName,
getBlocks,
} = useSelect( blockEditorStore );
const { selectionChange, insertBlock } =
useDispatch( blockEditorStore );
function onClick() {
registry.batch( () => {
const id = createId();
const newValue = insertObject(
value,
{
type: formatName,
attributes: {
href: '#' + id,
id: `${ id }-link`,
'data-fn': id,
},
innerHTML: '*',
},
value.end,
value.end
);
newValue.start = newValue.end - 1;
onChange( newValue );
// BFS search to find the first footnote block.
let fnBlock = null;
{
const queue = [ ...getBlocks() ];
while ( queue.length ) {
const block = queue.shift();
if ( block.name === name ) {
fnBlock = block;
break;
}
queue.push( ...block.innerBlocks );
}
}
// Maybe this should all also be moved to the entity provider.
// When there is no footnotes block in the post, create one and
// insert it at the bottom.
if ( ! fnBlock ) {
const clientId = getSelectedBlockClientId();
let rootClientId = getBlockRootClientId( clientId );
while (
rootClientId &&
getBlockName( rootClientId ) !== 'core/post-content'
) {
rootClientId = getBlockRootClientId( rootClientId );
}
fnBlock = createBlock( name );
insertBlock( fnBlock, undefined, rootClientId );
}
selectionChange( fnBlock.clientId, id, 0, 0 );
} );
}
return (
<RichTextToolbarButton
icon={ icon }
title={ __( 'Footnote' ) }
onClick={ onClick }
isActive={ isObjectActive }
/>
);
},
};