Debian Codegraph @

resources/codemirror.js

raw
1 const {
2 EditorState,
3 EditorView,
4 Extension,
5 Compartment,
6 KeyBinding,
7 ViewUpdate,
8 bracketMatching,
9 crosshairCursor,
10 defaultKeymap,
11 drawSelection,
12 highlightSpecialChars,
13 history,
14 historyKeymap,
15 keymap,
16 lineNumbers,
17 rectangularSelection,
18 redo
19 } = require( 'ext.CodeMirror.v6.lib' );
20 const CodeMirrorTextSelection = require( './codemirror.textSelection.js' );
21 const CodeMirrorSearch = require( './codemirror.search.js' );
22 const CodeMirrorGotoLine = require( './codemirror.gotoLine.js' );
23 require( './ext.CodeMirror.data.js' );
24
25 /**
26 * Interface for the CodeMirror editor.
27 *
28 * @example
29 * mw.loader.using( [
30 * 'ext.CodeMirror.v6',
31 * 'ext.CodeMirror.v6.mode.mediawiki'
32 * ] ).then( ( require ) => {
33 * const CodeMirror = require( 'ext.CodeMirror.v6' );
34 * const mediawikiLang = require( 'ext.CodeMirror.v6.mode.mediawiki' );
35 * const cm = new CodeMirror( myTextarea );
36 * cm.initialize( [ cm.defaultExtensions, mediawikiLang() ] );
37 * } );
38 */
39 class CodeMirror {
40 /**
41 * Instantiate a new CodeMirror instance.
42 *
43 * @param {HTMLTextAreaElement|jQuery|string|ve.ui.Surface} textarea Textarea to
44 * add syntax highlighting to.
45 * @constructor
46 */
47 constructor( textarea ) {
48 if ( textarea.constructor.name === 'VeUiMWWikitextSurface' ) {
49 /**
50 * The VisualEditor surface CodeMirror is bound to.
51 *
52 * @type {ve.ui.Surface}
53 */
54 this.surface = textarea;
55
56 // Let the content editable mimic the textarea.
57 // eslint-disable-next-line no-jquery/variable-pattern
58 textarea = this.surface.getView().$attachedRootNode;
59 }
60 /**
61 * The textarea that CodeMirror is bound to.
62 *
63 * @type {jQuery}
64 */
65 this.$textarea = $( textarea );
66 /**
67 * The editor user interface.
68 *
69 * @type {EditorView}
70 */
71 this.view = null;
72 /**
73 * The editor state.
74 *
75 * @type {EditorState}
76 */
77 this.state = null;
78 /**
79 * Whether the textarea is read-only.
80 *
81 * @type {boolean}
82 */
83 this.readOnly = this.surface ?
84 this.surface.getModel().isReadOnly() :
85 this.$textarea.prop( 'readonly' );
86 /**
87 * The [edit recovery]{@link https://www.mediawiki.org/wiki/Manual:Edit_Recovery} handler.
88 *
89 * @type {Function|null}
90 */
91 this.editRecoveryHandler = null;
92 /**
93 * jQuery.textSelection overrides for CodeMirror.
94 *
95 * @type {CodeMirrorTextSelection}
96 */
97 this.textSelection = null;
98 /**
99 * Compartment for the language direction Extension.
100 *
101 * @type {Compartment}
102 */
103 this.dirCompartment = new Compartment();
104 /**
105 * Compartment for the special characters Extension.
106 *
107 * @type {Compartment}
108 */
109 this.specialCharsCompartment = new Compartment();
110 }
111
112 /**
113 * Default extensions used by CodeMirror.
114 * Extensions here should be applicable to all theoretical uses of CodeMirror in MediaWiki.
115 *
116 * @see https://codemirror.net/docs/ref/#state.Extension
117 * @type {Extension|Extension[]}
118 * @stable to call
119 */
120 get defaultExtensions() {
121 const extensions = [
122 this.contentAttributesExtension,
123 this.phrasesExtension,
124 this.specialCharsCompartment.of( this.specialCharsExtension ),
125 this.heightExtension,
126 this.updateExtension,
127 this.bracketMatchingExtension,
128 this.dirExtension,
129 this.searchExtension,
130 EditorState.readOnly.of( this.readOnly ),
131 EditorView.domEventHandlers( {
132 blur: () => {
133 this.$textarea[ 0 ].dispatchEvent( new Event( 'blur' ) );
134 },
135 focus: () => {
136 this.$textarea[ 0 ].dispatchEvent( new Event( 'focus' ) );
137 }
138 } ),
139 EditorView.lineWrapping,
140 keymap.of( defaultKeymap ),
141 EditorState.allowMultipleSelections.of( true ),
142 drawSelection(),
143 rectangularSelection(),
144 crosshairCursor()
145 ];
146
147 // Add extensions relevant to editing (not read-only).
148 if ( !this.readOnly ) {
149 extensions.push( EditorView.updateListener.of( ( update ) => {
150 if ( update.docChanged && typeof this.editRecoveryHandler === 'function' ) {
151 this.editRecoveryHandler();
152 }
153 } ) );
154 extensions.push( history() );
155 extensions.push( keymap.of(
156 historyKeymap.concat( /** @type {KeyBinding} */ {
157 win: 'Ctrl-Shift-z',
158 run: redo,
159 preventDefault: true
160 } )
161 ) );
162 }
163
164 // Set to [] to disable everywhere, or null to enable everywhere
165 const namespaces = mw.config.get( 'extCodeMirrorConfig' ).lineNumberingNamespaces;
166 if ( !namespaces || namespaces.includes( mw.config.get( 'wgNamespaceNumber' ) ) ) {
167 extensions.push( lineNumbers() );
168 }
169
170 return extensions;
171 }
172
173 /**
174 * Extension for search and goto line functionality.
175 *
176 * @return {Extension|Extension[]}
177 */
178 get searchExtension() {
179 return [
180 new CodeMirrorSearch().extension,
181 new CodeMirrorGotoLine().extension
182 ];
183 }
184
185 /**
186 * This extension adds bracket matching to the CodeMirror editor.
187 *
188 * @return {Extension}
189 */
190 get bracketMatchingExtension() {
191 return bracketMatching( mw.config.get( 'wgPageContentModel' ) === 'wikitext' ?
192 {
193 // Also match CJK full-width brackets (T362992)
194 // This is only for wikitext as it can be confusing in programming languages.
195 brackets: '()[]{}()【】[]{}'
196 } : {}
197 );
198 }
199
200 /**
201 * This extension listens for changes in the CodeMirror editor and fires
202 * the `ext.CodeMirror.input` hook with the {@link ViewUpdate} object.
203 *
204 * @type {Extension}
205 * @fires CodeMirror~'ext.CodeMirror.input'
206 * @stable to call and override
207 */
208 get updateExtension() {
209 return EditorView.updateListener.of( ( update ) => {
210 if ( update.docChanged ) {
211 /**
212 * Called when document changes are made in CodeMirror.
213 * The native textarea is not necessarily updated yet.
214 *
215 * @event CodeMirror~'ext.CodeMirror.input'
216 * @param {ViewUpdate} update
217 * @stable to use
218 */
219 mw.hook( 'ext.CodeMirror.input' ).fire( update );
220 }
221 } );
222 }
223
224 /**
225 * This extension sets the height of the CodeMirror editor to match the textarea.
226 * Override this method to change the height of the editor.
227 *
228 * @type {Extension}
229 * @stable to call and override
230 */
231 get heightExtension() {
232 return EditorView.theme( {
233 '&': {
234 height: this.surface ? '100%' : `${ this.$textarea.outerHeight() }px`
235 },
236 '.cm-scroller': {
237 overflow: 'auto'
238 }
239 } );
240 }
241
242 /**
243 * This specifies which attributes get added to the `.cm-content` and `.cm-editor` elements.
244 * Subclasses are safe to override this method, but attributes here are considered vital.
245 *
246 * @see https://codemirror.net/docs/ref/#view.EditorView^contentAttributes
247 * @type {Extension}
248 * @stable to call and override
249 */
250 get contentAttributesExtension() {
251 const classList = [];
252 // T245568: Sync text editor font preferences with CodeMirror,
253 // but don't do this for the 2017 wikitext editor.
254 if ( !this.surface ) {
255 const fontClass = Array.from( this.$textarea[ 0 ].classList )
256 .find( ( style ) => style.startsWith( 'mw-editfont-' ) );
257 if ( fontClass ) {
258 classList.push( fontClass );
259 }
260 // Add colorblind mode if preference is set.
261 // This currently is only to be used for the MediaWiki markup language.
262 if (
263 mw.user.options.get( 'usecodemirror-colorblind' ) &&
264 mw.config.get( 'wgPageContentModel' ) === 'wikitext'
265 ) {
266 classList.push( 'cm-mw-colorblind-colors' );
267 }
268 }
269
270 return [
271 // .cm-content element (the contenteditable area)
272 EditorView.contentAttributes.of( {
273 // T259347: Use accesskey of the original textbox
274 accesskey: this.$textarea.attr( 'accesskey' ),
275 // Classes need to be on .cm-content to have precedence over .cm-scroller
276 class: classList.join( ' ' ),
277 spellcheck: 'true',
278 tabindex: this.$textarea.attr( 'tabindex' )
279 } ),
280 // .cm-editor element (contains the whole CodeMirror UI)
281 EditorView.editorAttributes.of( {
282 // Use language of the original textbox.
283 // These should be attributes of .cm-editor, not the .cm-content (T359589)
284 lang: this.$textarea.attr( 'lang' )
285 } ),
286 // The search panel should use the same direction as the interface language (T359611)
287 EditorView.theme( {
288 '.cm-panels': {
289 direction: document.dir
290 }
291 } )
292 ];
293 }
294
295 /**
296 * These are all potential messages used in a full-featured CodeMirror setup.
297 * We lump them all here and supply it as default extensions because it is only a small cost
298 * and we don't want localization to be overlooked by CodeMirror clients and subclasses.
299 *
300 * @see https://codemirror.net/examples/translate/
301 * @type {Extension}
302 * @stable to call. Instead of overriding, pass in an additional `EditorState.phrases.of()`
303 * when calling `initialize()`.
304 */
305 get phrasesExtension() {
306 return EditorState.phrases.of( {
307 'Control character': mw.msg( 'codemirror-control-character' )
308 } );
309 }
310
311 /**
312 * We give a small subset of special characters a tooltip explaining what they are.
313 * The messages and for what characters are defined here.
314 * Any character that does not have a message will instead use CM6 defaults,
315 * which is the localization of 'codemirror-control-character' followed by the Unicode number.
316 *
317 * @see https://codemirror.net/docs/ref/#view.highlightSpecialChars
318 * @type {Extension}
319 * @stable to call
320 */
321 get specialCharsExtension() {
322 // Keys are the decimal unicode number, values are the messages.
323 const messages = {
324 0: mw.msg( 'codemirror-special-char-null' ),
325 7: mw.msg( 'codemirror-special-char-bell' ),
326 8: mw.msg( 'codemirror-special-char-backspace' ),
327 10: mw.msg( 'codemirror-special-char-newline' ),
328 11: mw.msg( 'codemirror-special-char-vertical-tab' ),
329 13: mw.msg( 'codemirror-special-char-carriage-return' ),
330 27: mw.msg( 'codemirror-special-char-escape' ),
331 160: mw.msg( 'codemirror-special-char-nbsp' ),
332 8203: mw.msg( 'codemirror-special-char-zero-width-space' ),
333 8204: mw.msg( 'codemirror-special-char-zero-width-non-joiner' ),
334 8205: mw.msg( 'codemirror-special-char-zero-width-joiner' ),
335 8206: mw.msg( 'codemirror-special-char-left-to-right-mark' ),
336 8207: mw.msg( 'codemirror-special-char-right-to-left-mark' ),
337 8232: mw.msg( 'codemirror-special-char-line-separator' ),
338 8237: mw.msg( 'codemirror-special-char-left-to-right-override' ),
339 8238: mw.msg( 'codemirror-special-char-right-to-left-override' ),
340 8239: mw.msg( 'codemirror-special-char-narrow-nbsp' ),
341 8294: mw.msg( 'codemirror-special-char-left-to-right-isolate' ),
342 8295: mw.msg( 'codemirror-special-char-right-to-left-isolate' ),
343 8297: mw.msg( 'codemirror-special-char-pop-directional-isolate' ),
344 8233: mw.msg( 'codemirror-special-char-paragraph-separator' ),
345 65279: mw.msg( 'codemirror-special-char-zero-width-no-break-space' ),
346 65532: mw.msg( 'codemirror-special-char-object-replacement' )
347 };
348
349 return highlightSpecialChars( {
350 render: ( code, description, placeholder ) => {
351 description = messages[ code ] || mw.msg( 'codemirror-control-character', code );
352 const span = document.createElement( 'span' );
353 span.className = 'cm-specialChar';
354
355 // Special case non-breaking spaces (T181677).
356 if ( code === 160 || code === 8239 ) {
357 placeholder = '·';
358 span.className = 'cm-special-char-nbsp';
359 }
360
361 span.textContent = placeholder;
362 span.title = description;
363 span.setAttribute( 'aria-label', description );
364 return span;
365 },
366 // Highlight non-breaking spaces (T181677)
367 addSpecialChars: /[\u00a0\u202f]/g
368 } );
369 }
370
371 get dirExtension() {
372 return [
373 this.dirCompartment.of( EditorView.editorAttributes.of( {
374 // Use direction of the original textbox.
375 // These should be attributes of .cm-editor, not the .cm-content (T359589)
376 dir: this.$textarea.attr( 'dir' )
377 } ) ),
378 keymap.of( [ {
379 key: 'Mod-Shift-x',
380 run: ( view ) => {
381 const dir = this.$textarea.attr( 'dir' ) === 'rtl' ? 'ltr' : 'rtl';
382 this.$textarea.attr( 'dir', dir );
383 view.dispatch( {
384 effects: this.dirCompartment.reconfigure(
385 EditorView.editorAttributes.of( { dir } )
386 )
387 } );
388 return true;
389 }
390 } ] )
391 ];
392 }
393
394 /**
395 * Setup CodeMirror and add it to the DOM. This will hide the original textarea.
396 *
397 * @param {Extension|Extension[]} [extensions=this.defaultExtensions] Extensions to use.
398 * @fires CodeMirror~'ext.CodeMirror.initialize'
399 * @fires CodeMirror~'ext.CodeMirror.ready'
400 * @stable to call and override
401 */
402 initialize( extensions = this.defaultExtensions ) {
403 /**
404 * Called just before CodeMirror is initialized.
405 * This can be used to manipulate the DOM to suit CodeMirror
406 * (i.e. if you manipulate WikiEditor's DOM, you may need this).
407 *
408 * @event CodeMirror~'ext.CodeMirror.initialize'
409 * @param {jQuery} $textarea The textarea that CodeMirror is bound to.
410 * @stable to use
411 */
412 mw.hook( 'ext.CodeMirror.initialize' ).fire( this.$textarea );
413 mw.hook( 'editRecovery.loadEnd' ).add( ( data ) => {
414 this.editRecoveryHandler = data.fieldChangeHandler;
415 } );
416
417 // Set up the initial EditorState of CodeMirror with contents of the native textarea.
418 this.state = EditorState.create( {
419 doc: this.surface ?
420 this.surface.getDom() :
421 this.$textarea.textSelection( 'getContents' ),
422 extensions
423 } );
424
425 // Add CodeMirror view to the DOM.
426 this.addCodeMirrorToDom();
427
428 // Hide native textarea and sync CodeMirror contents upon submission.
429 if ( !this.surface ) {
430 this.$textarea.hide();
431 if ( this.$textarea[ 0 ].form ) {
432 this.$textarea[ 0 ].form.addEventListener( 'submit', () => {
433 this.$textarea.val( this.view.state.doc.toString() );
434 const scrollTop = document.getElementById( 'wpScrolltop' );
435 if ( scrollTop ) {
436 scrollTop.value = this.view.scrollDOM.scrollTop;
437 }
438 } );
439 }
440 }
441
442 // Register $.textSelection() on the .cm-editor element.
443 $( this.view.dom ).textSelection( 'register', this.cmTextSelection );
444 // Also override textSelection() functions for the "real" hidden textarea to route to
445 // CodeMirror. We unregister this when switching to normal textarea mode.
446 this.$textarea.textSelection( 'register', this.cmTextSelection );
447
448 /**
449 * Called just after CodeMirror is initialized.
450 *
451 * @event CodeMirror~'ext.CodeMirror.ready'
452 * @param {jQuery} $view The CodeMirror view.
453 * @stable to use
454 */
455 mw.hook( 'ext.CodeMirror.ready' ).fire( $( this.view.dom ) );
456 }
457
458 /**
459 * Instantiate the EditorView, adding the CodeMirror editor to the DOM.
460 * We use a dummy container to ensure that the editor will
461 * always be placed where the textarea is.
462 *
463 * @private
464 */
465 addCodeMirrorToDom() {
466 this.$textarea.wrap( '<div class="ext-codemirror-wrapper"></div>' );
467
468 this.view = new EditorView( {
469 state: this.state,
470 parent: this.surface ?
471 this.surface.getView().$element[ 0 ] :
472 this.$textarea.parent()[ 0 ]
473 } );
474 }
475
476 /**
477 * Destroy the CodeMirror instance and revert to the original textarea.
478 *
479 * @fires CodeMirror~'ext.CodeMirror.destroy'
480 * @stable to call and override
481 */
482 destroy() {
483 const scrollTop = this.view.scrollDOM.scrollTop;
484 const hasFocus = this.view.hasFocus;
485 const { from, to } = this.view.state.selection.ranges[ 0 ];
486 $( this.view.dom ).textSelection( 'unregister' );
487 this.$textarea.textSelection( 'unregister' );
488 this.$textarea.unwrap( '.ext-codemirror-wrapper' );
489 if ( !this.surface ) {
490 this.$textarea.val( this.view.state.doc.toString() );
491 }
492 this.view.destroy();
493 this.view = null;
494 this.$textarea.show();
495 if ( hasFocus ) {
496 this.$textarea.trigger( 'focus' );
497 }
498 this.$textarea.prop( 'selectionStart', Math.min( from, to ) )
499 .prop( 'selectionEnd', Math.max( to, from ) );
500 this.$textarea.scrollTop( scrollTop );
501 this.textSelection = null;
502
503 /**
504 * Called just after CodeMirror is destroyed and the original textarea is restored.
505 *
506 * @event CodeMirror~'ext.CodeMirror.destroy'
507 * @param {jQuery} $textarea The original textarea.
508 * @stable to use
509 */
510 mw.hook( 'ext.CodeMirror.destroy' ).fire( this.$textarea );
511 }
512
513 /**
514 * Log usage of CodeMirror.
515 *
516 * @param {Object} data
517 * @stable to call
518 * @internal
519 * @ignore
520 */
521 static logUsage( data ) {
522 /* eslint-disable camelcase */
523 const event = Object.assign( {
524 session_token: mw.user.sessionId(),
525 user_id: mw.user.getId()
526 }, data );
527 const editCountBucket = mw.config.get( 'wgUserEditCountBucket' );
528 if ( editCountBucket !== null ) {
529 event.user_edit_count_bucket = editCountBucket;
530 }
531 /* eslint-enable camelcase */
532 mw.track( 'event.CodeMirrorUsage', event );
533 }
534
535 /**
536 * Save CodeMirror enabled preference.
537 *
538 * @param {boolean} prefValue True, if CodeMirror should be enabled by default, otherwise false.
539 * @stable to call and override
540 */
541 static setCodeMirrorPreference( prefValue ) {
542 // Skip for unnamed users
543 if ( !mw.user.isNamed() ) {
544 return;
545 }
546 new mw.Api().saveOption( 'usecodemirror', prefValue ? 1 : 0 );
547 mw.user.options.set( 'usecodemirror', prefValue ? 1 : 0 );
548 }
549
550 /**
551 * jQuery.textSelection overrides for CodeMirror.
552 *
553 * @see jQuery.fn.textSelection
554 * @type {Object}
555 * @private
556 */
557 get cmTextSelection() {
558 if ( !this.textSelection ) {
559 this.textSelection = new CodeMirrorTextSelection( this.view );
560 }
561 return {
562 getContents: () => this.textSelection.getContents(),
563 setContents: ( content ) => this.textSelection.setContents( content ),
564 getCaretPosition: ( options ) => this.textSelection.getCaretPosition( options ),
565 scrollToCaretPosition: () => this.textSelection.scrollToCaretPosition(),
566 getSelection: () => this.textSelection.getSelection(),
567 setSelection: ( options ) => this.textSelection.setSelection( options ),
568 replaceSelection: ( value ) => this.textSelection.replaceSelection( value ),
569 encapsulateSelection: ( options ) => this.textSelection.encapsulateSelection( options )
570 };
571 }
572 }
573
574 module.exports = CodeMirror;