Debian Codegraph @

resources/legacy/ext.CodeMirror.WikiEditor.js

raw
1 function init() {
2 const extCodeMirror = require( 'ext.CodeMirror' );
3 let codeMirror, $textbox1, realtimePreviewHandler;
4
5 let useCodeMirror = mw.user.options.get( 'usecodemirror' ) > 0;
6
7 const originHooksTextarea = $.valHooks.textarea;
8 // define jQuery hook for searching and replacing text using JS if CodeMirror is enabled, see Bug: T108711
9 $.valHooks.textarea = {
10 get: function ( elem ) {
11 if ( elem.id === 'wpTextbox1' && codeMirror ) {
12 return codeMirror.doc.getValue();
13 } else if ( originHooksTextarea ) {
14 return originHooksTextarea.get( elem );
15 }
16 return elem.value;
17 },
18 set: function ( elem, value ) {
19 if ( elem.id === 'wpTextbox1' && codeMirror ) {
20 return codeMirror.doc.setValue( value );
21 } else if ( originHooksTextarea ) {
22 return originHooksTextarea.set( elem, value );
23 }
24 elem.value = value;
25 }
26 };
27
28 // jQuery.textSelection overrides for CodeMirror.
29 // See jQuery.textSelection.js for method documentation
30 const cmTextSelection = {
31 getContents: function () {
32 return codeMirror.doc.getValue();
33 },
34 setContents: function ( content ) {
35 codeMirror.doc.setValue( content );
36 return this;
37 },
38 getSelection: function () {
39 return codeMirror.doc.getSelection();
40 },
41 setSelection: function ( options ) {
42 codeMirror.doc.setSelection(
43 codeMirror.doc.posFromIndex( options.start ),
44 codeMirror.doc.posFromIndex( options.end )
45 );
46 codeMirror.focus();
47 return this;
48 },
49 replaceSelection: function ( value ) {
50 codeMirror.doc.replaceSelection( value );
51 return this;
52 },
53 getCaretPosition: function ( options ) {
54 const caretPos = codeMirror.doc.indexFromPos( codeMirror.doc.getCursor( true ) ),
55 endPos = codeMirror.doc.indexFromPos( codeMirror.doc.getCursor( false ) );
56 if ( options.startAndEnd ) {
57 return [ caretPos, endPos ];
58 }
59 return caretPos;
60 },
61 scrollToCaretPosition: function () {
62 codeMirror.scrollIntoView( null );
63 return this;
64 }
65 };
66
67 /**
68 * Save CodeMirror enabled pref.
69 *
70 * @param {boolean} prefValue True, if CodeMirror should be enabled by default, otherwise false.
71 */
72 function setCodeEditorPreference( prefValue ) {
73 useCodeMirror = prefValue; // Save state for function updateToolbarButton()
74 extCodeMirror.setCodeEditorPreference( prefValue );
75 }
76
77 /**
78 * @return {boolean}
79 */
80 function isLineNumbering() {
81 // T285660: Backspace related bug on Android browsers as of 2021
82 if ( /Android\b/.test( navigator.userAgent ) ) {
83 return false;
84 }
85
86 const namespaces = mw.config.get( 'wgCodeMirrorLineNumberingNamespaces' );
87 // Set to [] to disable everywhere, or null to enable everywhere
88 return !namespaces ||
89 namespaces.indexOf( mw.config.get( 'wgNamespaceNumber' ) ) !== -1;
90 }
91
92 // Keep these modules in sync with MediaWiki\Extension\CodeMirror\Hooks.php
93 const codeMirrorCoreModules = [
94 'ext.CodeMirror.lib',
95 'ext.CodeMirror.mode.mediawiki'
96 ];
97
98 /**
99 * Set the size of the CodeMirror element,
100 * and react to changes coming from WikiEditor (including Realtime Preview if its enabled).
101 */
102 function setupSizing() {
103 const $codeMirror = $( codeMirror.getWrapperElement() );
104
105 // Only add resizing corner if realtime preview is enabled,
106 // because that feature provides height resizing (even when preview isn't used).
107 if ( mw.loader.getState( 'ext.wikiEditor.realtimepreview' ) === 'ready' ) {
108 codeMirror.setSize( '100%', $textbox1.parent().height() );
109 }
110 const $resizableHandle = $codeMirror.find( '.ui-resizable-handle' );
111 mw.hook( 'ext.WikiEditor.realtimepreview.enable' ).add( ( realtimePreview ) => {
112 // CodeMirror may have been turned on and then off again before realtimepreview is enabled, in which case it will be null.
113 if ( !codeMirror ) {
114 return;
115 }
116 // Get rid of the corner resize handle, because realtimepreview provides its own.
117 $resizableHandle.hide();
118 // Add listener for CodeMirror changes.
119 realtimePreviewHandler = realtimePreview.getEventHandler().bind( realtimePreview );
120 codeMirror.on( 'change', realtimePreviewHandler );
121 // Fix the width and height of the CodeMirror area.
122 codeMirror.setSize( '100%', realtimePreview.twoPaneLayout.$element.height() );
123 } );
124 mw.hook( 'ext.WikiEditor.realtimepreview.resize' ).add( ( resizingBar ) => {
125 // CodeMirror may have been turned off after realtimepreview was opened, in which case it will be null.
126 if ( !codeMirror ) {
127 return;
128 }
129 // Keep in sync with the height of the pane.
130 codeMirror.setSize( '100%', resizingBar.getResizedPane().height() );
131 } );
132 mw.hook( 'ext.WikiEditor.realtimepreview.disable' ).add( () => {
133 // Re-show the corner resize handle.
134 $resizableHandle.show();
135 // CodeMirror may have been turned off after realtimepreview was opened, in which case it will be null.
136 if ( !codeMirror ) {
137 return;
138 }
139 codeMirror.refresh(); // T305333
140 codeMirror.off( 'change', realtimePreviewHandler );
141 } );
142 }
143
144 /**
145 * Replaces the default textarea with CodeMirror
146 */
147 function enableCodeMirror() {
148 const config = mw.config.get( 'extCodeMirrorConfig' );
149 mw.loader.using( codeMirrorCoreModules.concat( config.pluginModules ), () => {
150 const selectionStart = $textbox1.prop( 'selectionStart' ),
151 selectionEnd = $textbox1.prop( 'selectionEnd' ),
152 scrollTop = $textbox1.scrollTop(),
153 hasFocus = $textbox1.is( ':focus' );
154
155 // If CodeMirror is already loaded or wikEd gadget is enabled, abort. See T178348.
156 // FIXME: Would be good to replace the wikEd check with something more generic.
157 if ( codeMirror || mw.user.options.get( 'gadget-wikEd' ) > 0 ) {
158 return;
159 }
160
161 // T174055: Do not redefine the browser history navigation keys (T175378: for PC only)
162 CodeMirror.keyMap.pcDefault[ 'Alt-Left' ] = false;
163 CodeMirror.keyMap.pcDefault[ 'Alt-Right' ] = false;
164
165 const cmOptions = {
166 mwConfig: config,
167 // styleActiveLine: true, // disabled since Bug: T162204, maybe should be optional
168 lineWrapping: true,
169 lineNumbers: isLineNumbering(),
170 readOnly: $textbox1[ 0 ].readOnly,
171 // select mediawiki as text input mode
172 mode: 'text/mediawiki',
173 extraKeys: {
174 Tab: false,
175 'Shift-Tab': false,
176 // T174514: Move the cursor at the beginning/end of the current wrapped line
177 Home: 'goLineLeft',
178 End: 'goLineRight'
179 },
180 inputStyle: 'contenteditable',
181 spellcheck: true,
182 viewportMargin: Infinity
183 };
184
185 cmOptions.matchBrackets = {
186 highlightNonMatching: false,
187 maxHighlightLineLength: 10000
188 };
189
190 codeMirror = CodeMirror.fromTextArea( $textbox1[ 0 ], cmOptions );
191 const $codeMirror = $( codeMirror.getWrapperElement() );
192
193 codeMirror.on( 'focus', () => {
194 $textbox1[ 0 ].dispatchEvent( new Event( 'focus' ) );
195 } );
196 codeMirror.on( 'blur', () => {
197 $textbox1[ 0 ].dispatchEvent( new Event( 'blur' ) );
198 } );
199 mw.hook( 'editRecovery.loadEnd' ).add( ( data ) => {
200 codeMirror.on( 'change', data.fieldChangeHandler );
201 } );
202
203 // Allow textSelection() functions to work with CodeMirror editing field.
204 $codeMirror.textSelection( 'register', cmTextSelection );
205 // Also override textSelection() functions for the "real" hidden textarea to route to CodeMirror.
206 // We unregister this when switching to normal textarea mode.
207 $textbox1.textSelection( 'register', cmTextSelection );
208
209 setupSizing( $textbox1, codeMirror );
210
211 if ( hasFocus ) {
212 codeMirror.focus();
213 }
214 codeMirror.doc.setSelection( codeMirror.doc.posFromIndex( selectionEnd ), codeMirror.doc.posFromIndex( selectionStart ) );
215 codeMirror.scrollTo( null, scrollTop );
216
217 // HACK: <textarea> font size varies by browser (chrome/FF/IE)
218 $codeMirror.css( {
219 'font-size': $textbox1.css( 'font-size' ),
220 'line-height': $textbox1.css( 'line-height' )
221 } );
222
223 // use direction and language of the original textbox
224 $codeMirror.attr( {
225 dir: $textbox1.attr( 'dir' ),
226 lang: $textbox1.attr( 'lang' )
227 } );
228
229 $( codeMirror.getInputField() )
230 // T259347: Use accesskey of the original textbox
231 .attr( 'accesskey', $textbox1.attr( 'accesskey' ) )
232 // T194102: UniversalLanguageSelector integration is buggy, disabling it completely
233 .addClass( 'noime' );
234
235 if ( mw.user.options.get( 'usecodemirror-colorblind' ) ) {
236 $codeMirror.addClass( 'cm-mw-colorblind-colors' );
237 }
238
239 // T305333: Reload CodeMirror to fix a cursor caret issue.
240 codeMirror.refresh();
241
242 mw.hook( 'ext.CodeMirror.switch' ).fire( true, $codeMirror );
243 } );
244 }
245
246 /**
247 * Updates CodeMirror button on the toolbar according to the current state (on/off)
248 */
249 function updateToolbarButton() {
250 // eslint-disable-next-line no-jquery/no-global-selector
251 const $button = $( '#mw-editbutton-codemirror' );
252
253 $button.toggleClass( 'mw-editbutton-codemirror-active', !!useCodeMirror );
254
255 // WikiEditor2010 OOUI ToggleButtonWidget
256 if ( $button.data( 'setActive' ) ) {
257 $button.data( 'setActive' )( !!useCodeMirror );
258 }
259 }
260
261 /**
262 * Enables or disables CodeMirror
263 */
264 function switchCodeMirror() {
265 let selectionObj, selectionStart, selectionEnd, scrollTop, hasFocus, $codeMirror;
266
267 if ( codeMirror ) {
268 scrollTop = codeMirror.getScrollInfo().top;
269 selectionObj = codeMirror.doc.listSelections()[ 0 ];
270 selectionStart = codeMirror.doc.indexFromPos( selectionObj.head );
271 selectionEnd = codeMirror.doc.indexFromPos( selectionObj.anchor );
272 hasFocus = codeMirror.hasFocus();
273 $codeMirror = $( codeMirror.getWrapperElement() );
274 setCodeEditorPreference( false );
275 $codeMirror.textSelection( 'unregister' );
276 $textbox1.textSelection( 'unregister' );
277 codeMirror.toTextArea();
278 codeMirror = null;
279 if ( hasFocus ) {
280 $textbox1.trigger( 'focus' );
281 }
282 $textbox1.prop( 'selectionStart', selectionStart );
283 $textbox1.prop( 'selectionEnd', selectionEnd );
284 $textbox1.scrollTop( scrollTop );
285
286 mw.hook( 'ext.CodeMirror.switch' ).fire( false, $textbox1 );
287 } else {
288 enableCodeMirror();
289 setCodeEditorPreference( true );
290 }
291 updateToolbarButton();
292
293 extCodeMirror.logUsage( {
294 editor: 'wikitext',
295 enabled: codeMirror !== null,
296 toggled: true,
297 // eslint-disable-next-line no-jquery/no-global-selector,camelcase
298 edit_start_ts_ms: parseInt( $( 'input[name="wpStarttime"]' ).val() ) * 1000 || 0
299 } );
300 }
301
302 /**
303 * Adds the CodeMirror button to WikiEditor
304 */
305 function addCodeMirrorToWikiEditor() {
306 const context = $textbox1.data( 'wikiEditor-context' ),
307 toolbar = context && context.modules && context.modules.toolbar;
308
309 // Guard against something having removed WikiEditor (T271457)
310 if ( !toolbar ) {
311 return;
312 }
313
314 $textbox1.wikiEditor(
315 'addToToolbar',
316 {
317 section: 'main',
318 groups: {
319 codemirror: {
320 tools: {
321 CodeMirror: {
322 label: mw.msg( 'codemirror-toggle-label' ),
323 type: 'toggle',
324 oouiIcon: 'highlight',
325 action: {
326 type: 'callback',
327 execute: function () {
328 switchCodeMirror();
329 }
330 }
331 }
332 }
333 }
334 }
335 }
336 );
337
338 const $codeMirrorButton = toolbar.$toolbar.find( '.tool[rel=CodeMirror]' );
339 $codeMirrorButton
340 .attr( 'id', 'mw-editbutton-codemirror' );
341
342 if ( useCodeMirror ) {
343 enableCodeMirror();
344 }
345 updateToolbarButton();
346
347 extCodeMirror.logUsage( {
348 editor: 'wikitext',
349 enabled: useCodeMirror,
350 toggled: false,
351 // eslint-disable-next-line no-jquery/no-global-selector,camelcase
352 edit_start_ts_ms: parseInt( $( 'input[name="wpStarttime"]' ).val() ) * 1000 || 0
353 } );
354 }
355
356 // Add CodeMirror button to the enhanced editing toolbar.
357 mw.hook( 'wikiEditor.toolbarReady' ).add( ( $textarea ) => {
358 $textbox1 = $textarea;
359 addCodeMirrorToWikiEditor();
360 } );
361
362 // Synchronize textarea with CodeMirror before leaving
363 window.addEventListener( 'beforeunload', () => {
364 if ( codeMirror ) {
365 codeMirror.save();
366 }
367 } );
368 }
369
370 if ( mw.loader.getState( 'ext.wikiEditor' ) ) {
371 init();
372 }