Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ui/inspectors/ve.ui.AnnotationInspector.js

raw symbols SCIP
1 /*!
2 * VisualEditor UserInterface AnnotationInspector class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Inspector for working with content annotations.
9 *
10 * @class
11 * @abstract
12 * @extends ve.ui.FragmentInspector
13 *
14 * @constructor
15 * @param {Object} [config] Configuration options
16 */
17 ve.ui.AnnotationInspector = function VeUiAnnotationInspector() {
18 // Parent constructor
19 ve.ui.AnnotationInspector.super.apply( this, arguments );
20
21 // Properties
22 this.initialSelection = null;
23 this.initialAnnotation = null;
24 this.initialAnnotationIsCovering = false;
25 };
26
27 /* Inheritance */
28
29 OO.inheritClass( ve.ui.AnnotationInspector, ve.ui.FragmentInspector );
30
31 /**
32 * Annotation models this inspector can edit.
33 *
34 * @static
35 * @inheritable
36 * @property {Function[]}
37 */
38 ve.ui.AnnotationInspector.static.modelClasses = [];
39
40 /* Methods */
41
42 /**
43 * Check if form is empty, which if saved should result in removing the annotation.
44 *
45 * Only override this if the form provides the user a way to blank out primary information, allowing
46 * them to remove the annotation by clearing the form.
47 *
48 * @return {boolean} Form is empty
49 */
50 ve.ui.AnnotationInspector.prototype.shouldRemoveAnnotation = function () {
51 return false;
52 };
53
54 /**
55 * Work out whether the teardown process should replace the current text of the fragment.
56 *
57 * Default behavior is to only do so if nothing was selected initially, in which case we
58 * need *something* to apply the annotation to. If this returns true, getInsertionData had
59 * better produce something.
60 *
61 * @return {boolean} Whether to insert text on teardown
62 */
63 ve.ui.AnnotationInspector.prototype.shouldInsertText = function () {
64 return !this.isEditing();
65 };
66
67 /**
68 * Get data to insert if nothing was selected when the inspector opened.
69 *
70 * Defaults to using #getInsertionText.
71 *
72 * @return {string[]} Linear model content to insert
73 */
74 ve.ui.AnnotationInspector.prototype.getInsertionData = function () {
75 return this.getInsertionText().split( '' );
76 };
77
78 /**
79 * Get text to insert if nothing was selected when the inspector opened.
80 *
81 * @return {string} Text to insert
82 */
83 ve.ui.AnnotationInspector.prototype.getInsertionText = function () {
84 if ( this.sourceMode ) {
85 return OO.ui.resolveMsg( this.constructor.static.title );
86 }
87 return '';
88 };
89
90 /**
91 * Get the annotation object to apply.
92 *
93 * This method is called when the inspector is closing, and should return the annotation to apply
94 * to the text. If this method returns a falsey value like null, no annotation will be applied,
95 * but existing annotations won't be removed either.
96 *
97 * @abstract
98 * @return {ve.dm.Annotation} Annotation to apply
99 */
100 ve.ui.AnnotationInspector.prototype.getAnnotation = null;
101
102 /**
103 * Get an annotation object from a fragment.
104 *
105 * @abstract
106 * @param {ve.dm.SurfaceFragment} fragment Surface fragment
107 * @return {ve.dm.Annotation|null}
108 */
109 ve.ui.AnnotationInspector.prototype.getAnnotationFromFragment = null;
110
111 /**
112 * Get matching annotations within a fragment.
113 *
114 * @param {ve.dm.SurfaceFragment} fragment Fragment to get matching annotations within
115 * @param {boolean} [all] Get annotations which only cover some of the fragment
116 * @return {ve.dm.AnnotationSet} Matching annotations
117 */
118 ve.ui.AnnotationInspector.prototype.getMatchingAnnotations = function ( fragment, all ) {
119 const modelClasses = this.constructor.static.modelClasses;
120
121 return fragment.getAnnotations( all ).filter( ( annotation ) => ve.isInstanceOfAny( annotation, modelClasses ) );
122 };
123
124 // eslint-disable-next-line jsdoc/require-returns
125 /**
126 * @see ve.ui.FragmentWindow
127 */
128 ve.ui.AnnotationInspector.prototype.isEditing = function () {
129 // If initialSelection isn't set yet, default to assume we are editing,
130 // especially for the check in FragmentWindow#getSetupProcess
131 return !this.initialSelection || !this.initialSelection.isCollapsed();
132 };
133
134 /**
135 * Handle the inspector being setup.
136 *
137 * There are 4 scenarios:
138 *
139 * - Zero-length selection not near a word -> no change, text will be inserted on close
140 * - Zero-length selection inside or adjacent to a word -> expand selection to cover word
141 * - Selection covering non-annotated text -> trim selection to remove leading/trailing whitespace
142 * - Selection covering annotated text -> expand selection to cover annotation
143 *
144 * @param {Object} [data] Inspector opening data
145 * @param {boolean} [data.noExpand] Don't expand the selection when opening
146 * @return {OO.ui.Process}
147 */
148 ve.ui.AnnotationInspector.prototype.getSetupProcess = function ( data ) {
149 return ve.ui.AnnotationInspector.super.prototype.getSetupProcess.call( this, data )
150 .next( () => {
151 let fragment = this.getFragment(),
152 // Partial annotations will be expanded later
153 annotation = this.getMatchingAnnotations( fragment, true ).get( 0 );
154
155 const surfaceModel = fragment.getSurface();
156 surfaceModel.pushStaging();
157
158 // Only supports linear selections
159 if ( !( this.initialFragment && this.initialFragment.getSelection() instanceof ve.dm.LinearSelection ) ) {
160 return ve.createDeferred().reject().promise();
161 }
162
163 // Initialize range
164 if ( !annotation ) {
165 // No matching annotations found:
166 // If collapsed and at a content offset, try to expand the selection
167 if (
168 fragment.getSelection().isCollapsed() &&
169 fragment.getDocument().data.isContentOffset( fragment.getSelection().getRange().start )
170 ) {
171 // Expand to nearest word
172 if ( !data.noExpand ) {
173 fragment = fragment.expandLinearSelection( 'word' );
174 // If we expanded, check for matching annotations again
175 if ( !fragment.getSelection().isCollapsed() ) {
176 annotation = this.getMatchingAnnotations( fragment, true ).get( 0 );
177 }
178 }
179 // TODO: We should review how getMatchingAnnotation works in light of the fact
180 // that in the case of a collapsed range, the method falls back to retrieving
181 // insertion annotations.
182 } else {
183 // New expanded selection: trim whitespace
184 fragment = fragment.trimLinearSelection();
185 }
186
187 // Selection expanded, but still no annotation, create one from the selection
188 if ( !fragment.getSelection().isCollapsed() && !annotation ) {
189 this.isNew = true;
190 annotation = this.getAnnotationFromFragment( fragment );
191 if ( annotation ) {
192 fragment.annotateContent( 'set', annotation );
193 }
194 }
195 }
196
197 // Existing annotation only partially selection: expand to cover annotation
198 if ( annotation && !data.noExpand ) {
199 fragment = fragment.expandLinearSelection( 'annotation', annotation );
200 }
201
202 // Update selection
203 fragment.select();
204 this.initialSelection = fragment.getSelection();
205
206 // The initial annotation is the first matching annotation in the fragment
207 this.initialAnnotation = this.getMatchingAnnotations( fragment, true ).get( 0 );
208 const initialCoveringAnnotation = this.getMatchingAnnotations( fragment ).get( 0 );
209 // Fallback to a default annotation
210 if ( !this.initialAnnotation ) {
211 this.isNew = true;
212 this.initialAnnotation = this.getAnnotationFromFragment( fragment );
213 } else if (
214 initialCoveringAnnotation &&
215 initialCoveringAnnotation.compareTo( this.initialAnnotation )
216 ) {
217 // If the initial annotation doesn't cover the fragment, record this as we'll need
218 // to forcefully apply it to the rest of the fragment later
219 this.initialAnnotationIsCovering = true;
220 }
221
222 // Update fragment property
223 this.fragment = fragment;
224
225 // Duplicate calls from FragmentWindow#getSetupProcess after
226 // changing the fragment
227 this.actions.setMode( this.getMode() );
228 // isEditing is true when we are applying a new annotation because a
229 // stub is applied immediately, so use isNew instead
230 if ( this.isNew && this.isReadOnly() ) {
231 return ve.createDeferred().reject().promise();
232 }
233 }, this );
234 };
235
236 /**
237 * @inheritdoc
238 */
239 ve.ui.AnnotationInspector.prototype.getTeardownProcess = function ( data ) {
240 data = data || {};
241 return ve.ui.AnnotationInspector.super.prototype.getTeardownProcess.call( this, data )
242 .first( () => {
243 const annotation = this.getAnnotation(),
244 remove = data.action === 'done' && this.shouldRemoveAnnotation(),
245 surfaceModel = this.fragment.getSurface(),
246 surfaceView = this.manager.getSurface().getView(),
247 fragment = surfaceModel.getFragment( this.initialSelection, false ),
248 isEditing = this.isEditing(),
249 insertText = !remove && this.shouldInsertText();
250
251 let insertionAnnotation = false;
252 let replace = false;
253 let annotations;
254 let insertion;
255
256 const clear = () => {
257 // Clear all existing annotations
258 annotations = this.getMatchingAnnotations( fragment, true ).get();
259 for ( let i = 0, len = annotations.length; i < len; i++ ) {
260 fragment.annotateContent( 'clear', annotations[ i ] );
261 }
262 };
263
264 if ( remove ) {
265 surfaceModel.popStaging();
266 if ( !isEditing ) {
267 return;
268 }
269 clear();
270 } else {
271 if ( data.action !== 'done' ) {
272 surfaceModel.popStaging();
273 if ( this.initialFragment ) {
274 this.initialFragment.select();
275 }
276 return;
277 }
278 if ( annotation ) {
279 // Check if the initial annotation has changed, or didn't cover the whole fragment
280 // to begin with
281 if (
282 !this.initialAnnotationIsCovering ||
283 !this.initialAnnotation ||
284 !this.initialAnnotation.compareTo( annotation )
285 ) {
286 replace = true;
287 }
288 }
289 if ( replace || insertText ) {
290 surfaceModel.popStaging();
291 if ( insertText ) {
292 insertion = this.getInsertionData();
293 if ( insertion.length ) {
294 fragment.insertContent( insertion, true );
295 if ( !isEditing ) {
296 // Move cursor to the end of the inserted content, even if back button is used
297 this.initialFragment = fragment.collapseToEnd();
298 } else {
299 this.initialFragment = fragment;
300 }
301 }
302 }
303 // If we are setting a new annotation, clear any annotations the inspector may have
304 // applied up to this point. Otherwise keep them.
305 if ( replace ) {
306 clear();
307 // Apply new annotation
308 if ( fragment.getSelection().isCollapsed() ) {
309 insertionAnnotation = true;
310 } else {
311 fragment.annotateContent( 'set', annotation );
312 }
313 }
314 } else {
315 surfaceModel.applyStaging();
316 }
317 }
318
319 // HACK: ui.WindowAction unsets initialFragment in source mode,
320 // so we can't rely on it existing.
321 let selection;
322 if ( this.initialFragment && ( !data.action || insertText ) ) {
323 // Restore selection to what it was before we expanded it
324 selection = this.initialFragment.getSelection();
325 } else {
326 selection = fragment.getSelection();
327 }
328
329 if ( data.action ) {
330 // Place the selection after the inserted text. If the inserted content is actually an
331 // element and not text, keep it selected, so that the context menu for it appears.
332 if ( !( insertion && insertion.length && ve.dm.LinearData.static.isElementData( insertion[ 0 ] ) ) ) {
333 surfaceModel.setSelection( selection );
334 }
335 // Update active annotations from model as the document may be deactivated
336 surfaceView.updateActiveAnnotations( true );
337 // Update previousActiveAnnotations so the annotation stays active
338 // after re-activation
339 surfaceView.previousActiveAnnotations = surfaceView.activeAnnotations;
340 if ( OO.ui.isMobile() ) {
341 // Restore context-only view on mobile
342 surfaceView.deactivate( false, false, true );
343 } else {
344 // We can't rely on the selection being placed inside the annotation
345 // so force it based on the model annotations. T265166
346 surfaceView.selectAnnotation( ( annView ) => ve.isInstanceOfAny( annView.getModel(), this.constructor.static.modelClasses ) );
347 }
348 }
349
350 if ( insertionAnnotation ) {
351 surfaceModel.addInsertionAnnotations( annotation );
352 }
353 } )
354 .next( () => {
355 // Reset state
356 this.initialSelection = null;
357 this.initialAnnotation = null;
358 this.initialAnnotationIsCovering = false;
359 this.isNew = false;
360 } );
361 };