Debian Codegraph @

resources/legacy/modules/ve-cm/ve.ui.CodeMirrorAction.js

raw
1 /*!
2 * VisualEditor UserInterface CodeMirrorAction class.
3 */
4
5 /**
6 * CodeMirror action
7 *
8 * @class
9 * @extends ve.ui.Action
10 * @constructor
11 * @param {ve.ui.Surface} surface Surface to act on
12 */
13 ve.ui.CodeMirrorAction = function VeUiCodeMirrorAction() {
14 // Parent constructor
15 ve.ui.CodeMirrorAction.super.apply( this, arguments );
16 };
17
18 /* Inheritance */
19
20 OO.inheritClass( ve.ui.CodeMirrorAction, ve.ui.Action );
21
22 /* Static Properties */
23
24 ve.ui.CodeMirrorAction.static.name = 'codeMirror';
25
26 /**
27 * @inheritdoc
28 */
29 ve.ui.CodeMirrorAction.static.methods = [ 'toggle' ];
30
31 /* Methods */
32
33 /**
34 * @return {boolean}
35 */
36 ve.ui.CodeMirrorAction.static.isLineNumbering = function () {
37 // T285660: Backspace related bug on Android browsers as of 2021
38 if ( /Android\b/.test( navigator.userAgent ) ) {
39 return false;
40 }
41
42 const namespaces = mw.config.get( 'wgCodeMirrorLineNumberingNamespaces' );
43 // Set to [] to disable everywhere, or null to enable everywhere
44 return !namespaces ||
45 namespaces.indexOf( mw.config.get( 'wgNamespaceNumber' ) ) !== -1;
46 };
47
48 /**
49 * @method
50 * @param {boolean} [enable] State to force toggle to, inverts current state if undefined
51 * @return {boolean} Action was executed
52 */
53 ve.ui.CodeMirrorAction.prototype.toggle = function ( enable ) {
54 const surface = this.surface,
55 surfaceView = surface.getView(),
56 doc = surface.getModel().getDocument();
57
58 if ( !surface.mirror && enable !== false ) {
59 surface.mirror = true;
60 mw.loader.using( [
61 'ext.CodeMirror.lib',
62 'ext.CodeMirror.mode.mediawiki',
63 'jquery.client'
64 ] ).then( () => {
65 const config = mw.config.get( 'extCodeMirrorConfig' );
66
67 if ( !surface.mirror ) {
68 // Action was toggled to false since promise started
69 return;
70 }
71 mw.loader.using( config.pluginModules, () => {
72 if ( !surface.mirror ) {
73 // Action was toggled to false since promise started
74 return;
75 }
76 const tabSizeValue = surfaceView.documentView.documentNode.$element.css( 'tab-size' );
77 const cmOptions = {
78 value: surface.getDom(),
79 mwConfig: config,
80 readOnly: 'nocursor',
81 lineWrapping: true,
82 scrollbarStyle: 'null',
83 specialChars: /^$/,
84 viewportMargin: 5,
85 tabSize: tabSizeValue ? +tabSizeValue : 8,
86 // select mediawiki as text input mode
87 mode: 'text/mediawiki',
88 extraKeys: {
89 Tab: false,
90 'Shift-Tab': false
91 }
92 };
93
94 cmOptions.matchBrackets = {
95 highlightNonMatching: false,
96 maxHighlightLineLength: 10000
97 };
98
99 if ( ve.ui.CodeMirrorAction.static.isLineNumbering() ) {
100 Object.assign( cmOptions, {
101 // Set up a special "padding" gutter to create space between the line numbers
102 // and page content. The first column name is a magic constant which causes
103 // the built-in line number gutter to appear in the desired, leftmost position.
104 gutters: [
105 'CodeMirror-linenumbers',
106 'CodeMirror-linenumber-padding'
107 ],
108 lineNumbers: true
109 } );
110 }
111
112 surface.mirror = CodeMirror( surfaceView.$element[ 0 ], cmOptions );
113
114 // The VE/CM overlay technique only works with monospace fonts (as we use width-changing bold as a highlight)
115 // so revert any editfont user preference
116 surfaceView.$element.removeClass( 'mw-editfont-sans-serif mw-editfont-serif' ).addClass( 'mw-editfont-monospace' );
117
118 if ( mw.user.options.get( 'usecodemirror-colorblind' ) ) {
119 surfaceView.$element.addClass( 'cm-mw-colorblind-colors' );
120 }
121
122 const profile = $.client.profile();
123 const supportsTransparentText = 'WebkitTextFillColor' in document.body.style &&
124 // Disable on Firefox+OSX (T175223)
125 !( profile.layout === 'gecko' && profile.platform === 'mac' );
126
127 surfaceView.$documentNode.addClass(
128 supportsTransparentText ?
129 've-ce-documentNode-codeEditor-webkit-hide' :
130 've-ce-documentNode-codeEditor-hide'
131 );
132
133 if ( cmOptions.lineNumbers ) {
134 // Transfer gutter width to VE overlay.
135 const updateGutter = ( cmDisplay ) => {
136 surfaceView.$documentNode.css( 'margin-left', cmDisplay.gutters.offsetWidth );
137 };
138 CodeMirror.on( surface.mirror.display, 'updateGutter', updateGutter );
139 updateGutter( surface.mirror.display );
140 }
141
142 /* Events */
143
144 // As the action is regenerated each time, we need to store bound listeners
145 // in the mirror for later disconnection.
146 surface.mirror.veTransactionListener = this.onDocumentPrecommit.bind( this );
147 surface.mirror.veLangChangeListener = this.onLangChange.bind( this );
148 surface.mirror.veSelectListener = this.onSelect.bind( this );
149
150 doc.on( 'precommit', surface.mirror.veTransactionListener );
151 surfaceView.getDocument().on( 'langChange', surface.mirror.veLangChangeListener );
152 surface.getModel().on( 'select', surface.mirror.veSelectListener );
153
154 this.onLangChange();
155
156 ve.init.target.once( 'surfaceReady', () => {
157 if ( surface.mirror ) {
158 surface.mirror.refresh();
159 }
160 } );
161 } );
162 } );
163 } else if ( surface.mirror && enable !== true ) {
164 if ( surface.mirror !== true ) {
165 doc.off( 'precommit', surface.mirror.veTransactionListener );
166 surfaceView.getDocument().off( 'langChange', surface.mirror.veLangChangeListener );
167 surface.getModel().off( 'select', surface.mirror.veSelectListener );
168
169 // Restore edit-font
170 // eslint-disable-next-line mediawiki/class-doc
171 surfaceView.$element.removeClass( 'mw-editfont-monospace' ).addClass( 'mw-editfont-' + mw.user.options.get( 'editfont' ) );
172
173 surfaceView.$documentNode.removeClass(
174 've-ce-documentNode-codeEditor-webkit-hide ve-ce-documentNode-codeEditor-hide'
175 );
176 // Reset gutter.
177 surfaceView.$documentNode.css( 'margin-left', '' );
178
179 const mirrorElement = surface.mirror.getWrapperElement();
180 mirrorElement.parentNode.removeChild( mirrorElement );
181 }
182
183 surface.mirror = null;
184 }
185
186 return true;
187 };
188
189 /**
190 * Handle select events from the surface model
191 *
192 * @param {ve.dm.Selection} selection
193 */
194 ve.ui.CodeMirrorAction.prototype.onSelect = function ( selection ) {
195 const range = selection.getCoveringRange();
196
197 // Do not re-trigger bracket matching as long as something is selected
198 if ( !range || !range.isCollapsed() ) {
199 return;
200 }
201
202 this.surface.mirror.setSelection( this.getPosFromOffset( range.from ) );
203 };
204
205 /**
206 * Handle langChange events from the document view
207 */
208 ve.ui.CodeMirrorAction.prototype.onLangChange = function () {
209 const surface = this.surface,
210 doc = surface.getView().getDocument(),
211 dir = doc.getDir(), lang = doc.getLang();
212
213 surface.mirror.setOption( 'direction', dir );
214
215 // Set the wrapper to the appropriate language (T341342)
216 surface.mirror.getWrapperElement().setAttribute( 'lang', lang );
217 };
218
219 /**
220 * Handle precommit events from the document.
221 *
222 * The document is still in it's 'old' state before the transaction
223 * has been applied at this point.
224 *
225 * @param {ve.dm.Transaction} tx
226 */
227 ve.ui.CodeMirrorAction.prototype.onDocumentPrecommit = function ( tx ) {
228 const replacements = [],
229 store = this.surface.getModel().getDocument().getStore(),
230 mirror = this.surface.mirror;
231
232 let offset = 0;
233 tx.operations.forEach( ( op ) => {
234 if ( op.type === 'retain' ) {
235 offset += op.length;
236 } else if ( op.type === 'replace' ) {
237 replacements.push( {
238 start: this.getPosFromOffset( offset ),
239 // Don't bother recalculating end offset if not a removal, replaceRange works with just one arg
240 end: op.remove.length ? this.getPosFromOffset( offset + op.remove.length ) : undefined,
241 data: new ve.dm.ElementLinearData( store, op.insert ).getSourceText()
242 } );
243 offset += op.remove.length;
244 }
245 } );
246
247 // Apply replacements in reverse to avoid having to shift offsets
248 for ( let i = replacements.length - 1; i >= 0; i-- ) {
249 mirror.replaceRange(
250 replacements[ i ].data,
251 replacements[ i ].start,
252 replacements[ i ].end
253 );
254 }
255
256 // HACK: The absolutely positioned CodeMirror doesn't calculate the viewport
257 // correctly when expanding from less than the viewport height. (T185184)
258 if ( mirror.display.sizer.style.minHeight !== this.lastHeight ) {
259 mirror.refresh();
260 this.lastHeight = mirror.display.sizer.style.minHeight;
261 }
262 };
263
264 /**
265 * Convert a VE offset to a 2D CodeMirror position
266 *
267 * @param {number} veOffset VE linear model offset
268 * @return {Object} Code mirror position, containing 'line' and 'ch' numbers
269 */
270 ve.ui.CodeMirrorAction.prototype.getPosFromOffset = function ( veOffset ) {
271 return this.surface.mirror.posFromIndex(
272 this.surface.getModel().getSourceOffsetFromOffset( veOffset )
273 );
274 };
275
276 /* Registration */
277
278 {
279 // eslint-disable-next-line no-jquery/no-global-selector
280 const contentDir = $( '.mw-body-content .mw-parser-output' ).attr( 'dir' ) ||
281 // New pages will use wgPageContentLanguage which is set on the html element.
282 document.documentElement.dir;
283
284 if ( contentDir === 'ltr' ) {
285 ve.ui.actionFactory.register( ve.ui.CodeMirrorAction );
286 }
287 }