This repository has been archived by the owner on Jun 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
converters.js
247 lines (211 loc) · 7.63 KB
/
converters.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/**
* @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module code-block/converters
*/
import {
rawSnippetTextToModelDocumentFragment,
getPropertyAssociation
} from './utils';
/**
* A model-to-view (both editing and data) converter for the `codeBlock` element.
*
* Sample input:
*
* <codeBlock language="javascript">foo();<softBreak></softBreak>bar();</codeBlock>
*
* Sample output (editing):
*
* <pre data-language="JavaScript"><code class="language-javascript">foo();<br />bar();</code></pre>
*
* Sample output (data, see {@link module:code-block/converters~modelToDataViewSoftBreakInsertion}):
*
* <pre><code class="language-javascript">foo();\nbar();</code></pre>
*
* @param {module:engine/model/model~Model} model
* @param {Array.<module:code-block/codeblock~CodeBlockLanguageDefinition>} languageDefs The normalized language
* configuration passed to the feature.
* @param {Boolean} [useLabels=false] When `true`, the `<pre>` element will get a `data-language` attribute with a
* human–readable label of the language. Used only in the editing.
* @returns {Function} Returns a conversion callback.
*/
export function modelToViewCodeBlockInsertion( model, languageDefs, useLabels = false ) {
// Language CSS classes:
//
// {
// php: 'language-php',
// python: 'language-python',
// javascript: 'js',
// ...
// }
const languagesToClasses = getPropertyAssociation( languageDefs, 'language', 'class' );
// Language labels:
//
// {
// php: 'PHP',
// python: 'Python',
// javascript: 'JavaScript',
// ...
// }
const languagesToLabels = getPropertyAssociation( languageDefs, 'language', 'label' );
return ( evt, data, conversionApi ) => {
const { writer, mapper, consumable } = conversionApi;
if ( !consumable.consume( data.item, 'insert' ) ) {
return;
}
const codeBlockLanguage = data.item.getAttribute( 'language' );
const targetViewPosition = mapper.toViewPosition( model.createPositionBefore( data.item ) );
const preAttributes = {};
// Attributes added only in the editing view.
if ( useLabels ) {
preAttributes[ 'data-language' ] = languagesToLabels[ codeBlockLanguage ];
preAttributes.spellcheck = 'false';
}
const pre = writer.createContainerElement( 'pre', preAttributes );
const code = writer.createContainerElement( 'code', {
class: languagesToClasses[ codeBlockLanguage ] || null
} );
writer.insert( writer.createPositionAt( pre, 0 ), code );
writer.insert( targetViewPosition, pre );
mapper.bindElements( data.item, code );
};
}
/**
* A model-to-data view converter for the new line (`softBreak`) separator.
*
* Sample input:
*
* <codeBlock ...>foo();<softBreak></softBreak>bar();</codeBlock>
*
* Sample output:
*
* <pre><code ...>foo();\nbar();</code></pre>
*
* @param {module:engine/model/model~Model} model
* @returns {Function} Returns a conversion callback.
*/
export function modelToDataViewSoftBreakInsertion( model ) {
return ( evt, data, conversionApi ) => {
if ( data.item.parent.name !== 'codeBlock' ) {
return;
}
const { writer, mapper, consumable } = conversionApi;
if ( !consumable.consume( data.item, 'insert' ) ) {
return;
}
const position = mapper.toViewPosition( model.createPositionBefore( data.item ) );
writer.insert( position, writer.createText( '\n' ) );
};
}
/**
* A view-to-model converter for `<pre>` with the `<code>` HTML.
*
* Sample input:
*
* <pre><code class="language-javascript">foo();\nbar();</code></pre>
*
* Sample output:
*
* <codeBlock language="javascript">foo();<softBreak></softBreak>bar();</codeBlock>
*
* @param {module:engine/controller/datacontroller~DataController} dataController
* @param {Array.<module:code-block/codeblock~CodeBlockLanguageDefinition>} languageDefs The normalized language
* configuration passed to the feature.
* @returns {Function} Returns a conversion callback.
*/
export function dataViewToModelCodeBlockInsertion( dataController, languageDefs ) {
// Language names associated with CSS classes:
//
// {
// 'language-php': 'php',
// 'language-python': 'python',
// js: 'javascript',
// ...
// }
const classesToLanguages = getPropertyAssociation( languageDefs, 'class', 'language' );
const defaultLanguageName = languageDefs[ 0 ].language;
return ( evt, data, conversionApi ) => {
const viewItem = data.viewItem;
const viewChild = viewItem.getChild( 0 );
if ( !viewChild || !viewChild.is( 'code' ) ) {
return;
}
const { consumable, writer } = conversionApi;
if ( !consumable.test( viewItem, { name: true } ) || !consumable.test( viewChild, { name: true } ) ) {
return;
}
const codeBlock = writer.createElement( 'codeBlock' );
const viewChildClasses = [ ...viewChild.getClassNames() ];
// As we're to associate each class with a model language, a lack of class (empty class) can be
// also associated with a language if the language definition was configured so. Pushing an empty
// string to make sure the association will work.
if ( !viewChildClasses.length ) {
viewChildClasses.push( '' );
}
// Figure out if any of the <code> element's class names is a valid programming
// language class. If so, use it on the model element (becomes the language of the entire block).
for ( const className of viewChildClasses ) {
const language = classesToLanguages[ className ];
if ( language ) {
writer.setAttribute( 'language', language, codeBlock );
break;
}
}
// If no language value was set, use the default language from the config.
if ( !codeBlock.hasAttribute( 'language' ) ) {
writer.setAttribute( 'language', defaultLanguageName, codeBlock );
}
const stringifiedElement = dataController.processor.toData( viewChild );
const textData = extractDataFromCodeElement( stringifiedElement );
const fragment = rawSnippetTextToModelDocumentFragment( writer, textData );
writer.append( fragment, codeBlock );
// Let's see if the codeBlock can be inserted the current modelCursor.
const splitResult = conversionApi.splitToAllowedParent( codeBlock, data.modelCursor );
// When there is no split result it means that we can't insert element to model tree,
// so let's skip it.
if ( !splitResult ) {
return;
}
// Insert element on allowed position.
writer.insert( codeBlock, splitResult.position );
consumable.consume( viewItem, { name: true } );
consumable.consume( viewChild, { name: true } );
const parts = conversionApi.getSplitParts( codeBlock );
// Set conversion result range.
data.modelRange = writer.createRange(
conversionApi.writer.createPositionBefore( codeBlock ),
conversionApi.writer.createPositionAfter( parts[ parts.length - 1 ] )
);
// If we had to split parent to insert our element then we want to continue conversion inside
// the split parent.
//
// before split:
//
// <allowed><notAllowed>[]</notAllowed></allowed>
//
// after split:
//
// <allowed>
// <notAllowed></notAllowed>
// <converted></converted>
// <notAllowed>[]</notAllowed>
// </allowed>
if ( splitResult.cursorParent ) {
data.modelCursor = writer.createPositionAt( splitResult.cursorParent, 0 );
} else {
// Otherwise just continue after the inserted element.
data.modelCursor = data.modelRange.end;
}
};
}
// Returns content of `<pre></pre>` with unescaped html inside.
//
// @param {String} stringifiedElement
function extractDataFromCodeElement( stringifiedElement ) {
const data = new RegExp( /^<code[^>]*>([\S\s]*)<\/code>$/ ).exec( stringifiedElement )[ 1 ];
return data
.replace( /</g, '<' )
.replace( />/g, '>' );
}