Debian Codegraph @

extensions/VisualEditor/editcheck/modules/init.js

raw symbols SCIP
1 mw.editcheck = {
2 config: require( './config.json' ),
3 ecenable: !!( new URL( location.href ).searchParams.get( 'ecenable' ) || window.MWVE_FORCE_EDIT_CHECK_ENABLED )
4 };
5
6 require( './EditCheckContextItem.js' );
7 require( './EditCheckInspector.js' );
8 require( './EditCheckDialog.js' );
9 require( './EditCheckFactory.js' );
10 require( './EditCheckAction.js' );
11 require( './BaseEditCheck.js' );
12
13 // TODO: Load these checks behind feature flags
14 // require( './ConvertReferenceEditCheck.js' );
15 // require( './TextMatchEditCheck.js' );
16 require( './AddReferenceEditCheck.js' );
17
18 /**
19 * Return the content ranges (content branch node interiors) contained within a range
20 *
21 * For a content branch node entirely contained within the range, its entire interior
22 * range will be included. For a content branch node overlapping with the range boundary,
23 * only the covered part of its interior range will be included.
24 *
25 * @param {ve.dm.Document} documentModel The documentModel to search
26 * @param {ve.Range} range The range to include
27 * @param {boolean} covers Only include ranges which cover the whole of their node
28 * @return {ve.Range[]} The contained content ranges (content branch node interiors)
29 */
30 mw.editcheck.getContentRanges = function ( documentModel, range, covers ) {
31 const ranges = [];
32 documentModel.selectNodes( range, 'branches' ).forEach( ( spec ) => {
33 if (
34 spec.node.canContainContent() && (
35 !covers || (
36 !spec.range || // an empty range means the node is covered
37 spec.range.equalsSelection( spec.nodeRange )
38 )
39 )
40 ) {
41 ranges.push( spec.range || spec.nodeRange );
42 }
43 } );
44 return ranges;
45 };
46
47 mw.editcheck.hasAddedContentNeedingReference = function ( documentModel, includeReferencedContent ) {
48 // helper for ve.init.mw.ArticleTarget save-tagging, keep logic below in-sync with AddReferenceEditCheck.
49 // This is bypassing the normal "should this check apply?" logic for creation, so we need to manually
50 // apply the "only the main namespace" rule.
51 if ( mw.config.get( 'wgNamespaceNumber' ) !== mw.config.get( 'wgNamespaceIds' )[ '' ] ) {
52 return false;
53 }
54 const check = mw.editcheck.editCheckFactory.create( 'addReference', mw.editcheck.config.addReference );
55 return check.findAddedContent( documentModel, includeReferencedContent ).length > 0;
56 };
57
58 mw.editcheck.getModifiedRanges = function ( documentModel, coveredNodesOnly ) {
59 if ( !documentModel.completeHistory.getLength() ) {
60 return [];
61 }
62 const operations = documentModel.completeHistory.squash().transactions[ 0 ].operations;
63 const ranges = [];
64 let offset = 0;
65 const endOffset = documentModel.getDocumentRange().end;
66 operations.every( ( op ) => {
67 if ( op.type === 'retain' ) {
68 offset += op.length;
69 } else if ( op.type === 'replace' ) {
70 const insertedRange = new ve.Range( offset, offset + op.insert.length );
71 offset += op.insert.length;
72 // 1. Only trigger if the check is a pure insertion, with no adjacent content removed (T340088)
73 if ( op.remove.length === 0 ) {
74 ve.batchPush(
75 ranges,
76 // 2. Only fully inserted paragraphs (ranges that cover the whole node) (T345121)
77 mw.editcheck.getContentRanges( documentModel, insertedRange, coveredNodesOnly )
78 );
79 }
80 }
81 // Reached the end of the doc / start of internal list, stop searching
82 return offset < endOffset;
83 } );
84 return ranges;
85 };
86
87 mw.editcheck.rejections = [];
88
89 mw.editcheck.getRejectionReasons = function () {
90 return mw.editcheck.rejections;
91 };
92
93 mw.editcheck.refCheckShown = false;
94
95 if ( mw.config.get( 'wgVisualEditorConfig' ).editCheckTagging ) {
96 mw.hook( 've.activationComplete' ).add( () => {
97 const target = ve.init.target;
98
99 function getRefNodes() {
100 // The firstNodes list is a numerically indexed array of reference nodes in the document.
101 // The list is append only, and removed references are set to undefined in place.
102 // To check if a new reference is being published, we just need to know if a reference
103 // with an index beyond the initial list (initLength) is still set.
104 const internalList = target.getSurface().getModel().getDocument().getInternalList();
105 const group = internalList.getNodeGroup( 'mwReference/' );
106 return group ? group.firstNodes || [] : [];
107 }
108
109 const initLength = getRefNodes().length;
110 target.saveFields.vetags = function () {
111 const refNodes = getRefNodes();
112 const newLength = refNodes.length;
113 let newNodesInDoc = false;
114 for ( let i = initLength; i < newLength; i++ ) {
115 if ( refNodes[ i ] ) {
116 newNodesInDoc = true;
117 break;
118 }
119 }
120 const tags = [];
121 if ( newNodesInDoc ) {
122 tags.push( 'editcheck-newreference' );
123 }
124 if ( mw.editcheck.refCheckShown ) {
125 tags.push( 'editcheck-references-activated' );
126 }
127 return tags.join( ',' );
128 };
129 } );
130 mw.hook( 've.deactivationComplete' ).add( () => {
131 const target = ve.init.target;
132 delete target.saveFields.vetags;
133 } );
134 }
135
136 if ( mw.config.get( 'wgVisualEditorConfig' ).editCheck || mw.editcheck.ecenable ) {
137 let saveProcessDeferred;
138
139 mw.hook( 've.preSaveProcess' ).add( ( saveProcess, target ) => {
140 const surface = target.getSurface();
141
142 if ( surface.getMode() !== 'visual' ) {
143 // Some checks will entirely work in source mode for most cases.
144 // But others will fail spectacularly -- e.g. reference check
145 // isn't aware of <ref> tags and so will suggest that all content
146 // has references added. As such, disable in source mode for now.
147 return;
148 }
149
150 ve.track( 'counter.editcheck.preSaveChecksAvailable' );
151
152 // clear rejection-reasons between runs of the save process, so only the last one counts
153 mw.editcheck.rejections.length = 0;
154
155 let checks = mw.editcheck.editCheckFactory.createAllByListener( 'onBeforeSave', surface.getModel() );
156 if ( checks.length ) {
157 ve.track( 'counter.editcheck.preSaveChecksShown' );
158 mw.editcheck.refCheckShown = true;
159
160 const surfaceView = surface.getView();
161 const toolbar = target.getToolbar();
162 const reviewToolbar = new ve.ui.PositionedTargetToolbar( target, target.toolbarConfig );
163 reviewToolbar.setup( [
164 {
165 name: 'back',
166 type: 'bar',
167 include: [ 'editCheckBack' ]
168 },
169 // Placeholder toolbar groups
170 // TODO: Make a proper TitleTool?
171 {
172 name: 'title',
173 type: 'bar',
174 include: []
175 },
176 {
177 name: 'save',
178 // TODO: MobileArticleTarget should ignore 'align'
179 align: OO.ui.isMobile() ? 'before' : 'after',
180 type: 'bar',
181 include: [ 'showSaveDisabled' ]
182 }
183 ], surface );
184 reviewToolbar.$element.addClass( 've-ui-editCheck-toolbar' );
185
186 reviewToolbar.items[ 1 ].$element.removeClass( 'oo-ui-toolGroup-empty' );
187 reviewToolbar.items[ 1 ].$group.append(
188 $( '<span>' ).addClass( 've-ui-editCheck-toolbar-title' ).text( ve.msg( 'editcheck-dialog-title' ) )
189 );
190 if ( OO.ui.isMobile() ) {
191 reviewToolbar.$element.addClass( 've-init-mw-mobileArticleTarget-toolbar' );
192 }
193 target.toolbar.$element.before( reviewToolbar.$element );
194 target.toolbar = reviewToolbar;
195
196 saveProcessDeferred = ve.createDeferred();
197 const context = surface.getContext();
198
199 // TODO: Allow multiple checks to be shown when multicheck is enabled
200 checks = checks.slice( 0, 1 );
201
202 // eslint-disable-next-line no-shadow
203 const drawSelections = ( checks ) => {
204 const highlightNodes = [];
205 const selections = [];
206 checks.forEach( ( check ) => {
207 highlightNodes.push.apply( highlightNodes, surfaceView.getDocument().selectNodes( check.highlight.getSelection().getCoveringRange(), 'branches' ).map( ( spec ) => spec.node ) );
208 const selection = ve.ce.Selection.static.newFromModel( check.highlight.getSelection(), surfaceView );
209 selections.push( selection );
210 } );
211 // TODO: Make selections clickable when multicheck is enabled
212 surfaceView.drawSelections(
213 'editCheck',
214 checks.map( ( check ) => ve.ce.Selection.static.newFromModel( check.highlight.getSelection(), surfaceView ) )
215 );
216 surfaceView.setReviewMode( true, highlightNodes );
217 };
218
219 const contextDone = ( responseData, contextData ) => {
220 if ( !responseData ) {
221 // this is the back button
222 return saveProcessDeferred.resolve();
223 }
224 const selectionIndex = checks.indexOf( contextData.action );
225
226 if ( responseData.action !== 'reject' ) {
227 mw.notify( ve.msg( 'editcheck-dialog-addref-success-notify' ), { type: 'success' } );
228 } else if ( responseData.reason ) {
229 mw.editcheck.rejections.push( responseData.reason );
230 }
231 // TODO: Move on to the next issue, when multicheck is enabled
232 // checks = mw.editcheck.editCheckFactory.createAllByListener( 'onBeforeSave', surface.getModel() );
233 checks = [];
234
235 if ( checks.length ) {
236 context.removePersistentSource( 'editCheckReferences' );
237 setTimeout( () => {
238 // timeout needed to wait out the newly added content being focused
239 surface.getModel().setNullSelection();
240 drawSelections( checks );
241 setTimeout( () => {
242 // timeout needed to allow the context to reposition
243 showCheckContext( checks[ Math.min( selectionIndex, checks.length - 1 ) ] );
244 } );
245 }, 500 );
246 } else {
247 saveProcessDeferred.resolve( true );
248 }
249 };
250
251 // eslint-disable-next-line no-inner-declarations
252 function showCheckContext( check ) {
253 const fragment = check.highlight;
254
255 // Select the found content to correctly position the context on desktop
256 fragment.select();
257
258 context.addPersistentSource( {
259 embeddable: false,
260 data: {
261 action: check,
262 fragment: fragment,
263 callback: contextDone,
264 saveProcessDeferred: saveProcessDeferred
265 },
266 name: 'editCheckReferences'
267 } );
268
269 // Deactivate to prevent selection suppressing mobile context
270 surface.getView().deactivate();
271
272 // Once the context is positioned, clear the selection
273 setTimeout( () => {
274 surface.getModel().setNullSelection();
275 } );
276 }
277
278 drawSelections( checks );
279 toolbar.toggle( false );
280 target.onContainerScroll();
281
282 saveProcess.next( () => {
283 showCheckContext( checks[ 0 ] );
284
285 return saveProcessDeferred.promise().then( ( data ) => {
286 context.removePersistentSource( 'editCheckReferences' );
287
288 surfaceView.drawSelections( 'editCheck', [] );
289 surfaceView.setReviewMode( false );
290
291 reviewToolbar.$element.remove();
292 toolbar.toggle( true );
293 target.toolbar = toolbar;
294 target.onContainerScroll();
295
296 // Check the user inserted a citation
297 if ( data ) {
298 const delay = ve.createDeferred();
299 // If they inserted, wait 2 seconds on desktop before showing save dialog
300 setTimeout( () => {
301 ve.track( 'counter.editcheck.preSaveChecksCompleted' );
302 delay.resolve();
303 }, !OO.ui.isMobile() && data.action !== 'reject' ? 2000 : 0 );
304 return delay.promise();
305 } else {
306 ve.track( 'counter.editcheck.preSaveChecksAbandoned' );
307 return ve.createDeferred().reject().promise();
308 }
309 } );
310 } );
311 } else {
312 // Counterpart to earlier preSaveChecksShown, for use in tracking
313 // errors in check-generation:
314 ve.track( 'counter.editcheck.preSaveChecksNotShown' );
315 }
316 } );
317 mw.hook( 've.deactivationComplete' ).add( () => {
318 if ( saveProcessDeferred ) {
319 saveProcessDeferred.reject();
320 }
321 } );
322 }
323
324 ve.ui.EditCheckBack = function VeUiEditCheckBack() {
325 // Parent constructor
326 ve.ui.EditCheckBack.super.apply( this, arguments );
327
328 this.setDisabled( false );
329 };
330 OO.inheritClass( ve.ui.EditCheckBack, ve.ui.Tool );
331 ve.ui.EditCheckBack.static.name = 'editCheckBack';
332 ve.ui.EditCheckBack.static.icon = 'previous';
333 ve.ui.EditCheckBack.static.autoAddToCatchall = false;
334 ve.ui.EditCheckBack.static.autoAddToGroup = false;
335 ve.ui.EditCheckBack.static.title =
336 OO.ui.deferMsg( 'visualeditor-backbutton-tooltip' );
337 ve.ui.EditCheckBack.prototype.onSelect = function () {
338 const context = this.toolbar.getSurface().getContext();
339 if ( context.inspector ) {
340 context.inspector.close();
341 } else {
342 context.items[ 0 ].close();
343 }
344 this.setActive( false );
345 };
346 ve.ui.EditCheckBack.prototype.onUpdateState = function () {
347 this.setDisabled( false );
348 };
349 ve.ui.toolFactory.register( ve.ui.EditCheckBack );
350
351 ve.ui.EditCheckSaveDisabled = function VeUiEditCheckSaveDisabled() {
352 // Parent constructor
353 ve.ui.EditCheckSaveDisabled.super.apply( this, arguments );
354 };
355 OO.inheritClass( ve.ui.EditCheckSaveDisabled, ve.ui.MWSaveTool );
356 ve.ui.EditCheckSaveDisabled.static.name = 'showSaveDisabled';
357 ve.ui.EditCheckSaveDisabled.static.autoAddToCatchall = false;
358 ve.ui.EditCheckSaveDisabled.static.autoAddToGroup = false;
359 ve.ui.EditCheckSaveDisabled.prototype.onUpdateState = function () {
360 this.setDisabled( true );
361 };
362
363 ve.ui.toolFactory.register( ve.ui.EditCheckSaveDisabled );