/
index.js
62 lines (52 loc) · 1.4 KB
/
index.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
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { toggleFormat, remove, applyFormat } from '@wordpress/rich-text';
import { RichTextToolbarButton } from '@wordpress/block-editor';
import { code as codeIcon } from '@wordpress/icons';
const name = 'core/code';
const title = __( 'Inline Code' );
export const code = {
name,
title,
tagName: 'code',
className: null,
__unstableInputRule( value ) {
const BACKTICK = '`';
const { start, text } = value;
const characterBefore = text.slice( start - 1, start );
// Quick check the text for the necessary character.
if ( characterBefore !== BACKTICK ) {
return value;
}
const textBefore = text.slice( 0, start - 1 );
const indexBefore = textBefore.lastIndexOf( BACKTICK );
if ( indexBefore === -1 ) {
return value;
}
const startIndex = indexBefore;
const endIndex = start - 2;
if ( startIndex === endIndex ) {
return value;
}
value = remove( value, startIndex, startIndex + 1 );
value = remove( value, endIndex, endIndex + 1 );
value = applyFormat( value, { type: name }, startIndex, endIndex );
return value;
},
edit( { value, onChange, onFocus, isActive } ) {
function onClick() {
onChange( toggleFormat( value, { type: name } ) );
onFocus();
}
return (
<RichTextToolbarButton
icon={ codeIcon }
title={ title }
onClick={ onClick }
isActive={ isActive }
/>
);
},
};