forked from xwp/code-syntax-block
-
Notifications
You must be signed in to change notification settings - Fork 0
/
code-syntax.js
95 lines (82 loc) · 2.18 KB
/
code-syntax.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
/**
* Code Syntax Highlighting Block
* A gutenberg block that allows inserting code with syntax highlighting.
*/
/**
* WordPress dependencies
*/
const { addFilter } = wp.hooks;
const el = wp.element.createElement;
const { PlainText, InspectorControls } = wp.editor;
const { SelectControl } = wp.components;
const editorStyle = { fontFamily: 'sans-serif', fontSize: '10px', color: '#999999', textAlign: 'right' };
let langs = {};
for ( let lang in prismLanguages ) {
if ( ! prismLanguages.hasOwnProperty( lang ) ) { continue; }
if ( typeof prismLanguages[lang].title !== 'undefined' ) {
langs[lang] = prismLanguages[lang].title;
}
}
const addSyntaxToCodeBlock = settings => {
if ( settings.name !== 'core/code' ) {
return settings;
}
const newCodeBlockSettings = {
...settings,
attributes: {
...settings.attributes,
language: {
type: 'string',
selector: 'code',
source: 'attribute',
attribute: 'lang'
}
},
edit({ attributes, setAttributes, isSelected, className }) {
const updateLanguage = language => {
setAttributes({ language });
};
return [
el( InspectorControls, { key: 'controls' },
el( SelectControl, {
label: "Language",
value: attributes.language,
options: [ {
label: 'Select code language',
value: '',
}].concat (
Object.keys( langs ).map( ( lang ) => (
{ label: langs[lang], value: lang }
) )
),
onChange: updateLanguage,
} )
),
el( 'div', { key: 'editor-wrapper', className: className },
el( PlainText, {
value: attributes.content,
onChange: ( content ) => setAttributes({ content }),
placeholder: 'Write code…',
ariaLabel: 'Code',
}),
el( 'div', { style: editorStyle }, langs[ attributes.language ] )
)
];
},
save({ attributes }) {
const cls = ( attributes.language ) ? 'language-' + attributes.language : '';
return el(
'pre',
{},
el( 'code', { lang: attributes.language, className: cls }, attributes.content )
);
}
};
return newCodeBlockSettings;
};
// Register Filter
addFilter(
'blocks.registerBlockType',
'mkaz/code-syntax-block',
addSyntaxToCodeBlock
);