-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathpatterns.js
78 lines (62 loc) · 1.82 KB
/
patterns.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
/**
* WordPress dependencies
*/
import { getBlockTransforms, findTransform } from '@wordpress/blocks';
import {
remove,
applyFormat,
getTextContent,
slice,
} from '@wordpress/rich-text';
export function getPatterns( { onReplace, valueToFormat } ) {
const prefixTransforms = getBlockTransforms( 'from' )
.filter( ( { type } ) => type === 'prefix' );
return [
( record ) => {
if ( ! onReplace ) {
return record;
}
const { start } = record;
const text = getTextContent( record );
const characterBefore = text.slice( start - 1, start );
if ( ! /\s/.test( characterBefore ) ) {
return record;
}
const trimmedTextBefore = text.slice( 0, start ).trim();
const transformation = findTransform( prefixTransforms, ( { prefix } ) => {
return trimmedTextBefore === prefix;
} );
if ( ! transformation ) {
return record;
}
const content = valueToFormat( slice( record, start, text.length ) );
const block = transformation.transform( content );
onReplace( [ block ] );
return record;
},
( record ) => {
const BACKTICK = '`';
const { start } = record;
const text = getTextContent( record );
const characterBefore = text.slice( start - 1, start );
// Quick check the text for the necessary character.
if ( characterBefore !== BACKTICK ) {
return record;
}
const textBefore = text.slice( 0, start - 1 );
const indexBefore = textBefore.lastIndexOf( BACKTICK );
if ( indexBefore === -1 ) {
return record;
}
const startIndex = indexBefore;
const endIndex = start - 2;
if ( startIndex === endIndex ) {
return record;
}
record = remove( record, startIndex, startIndex + 1 );
record = remove( record, endIndex, endIndex + 1 );
record = applyFormat( record, { type: 'code' }, startIndex, endIndex );
return record;
},
];
}