Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ui/ve.ui.Surface.js

raw symbols SCIP
1 /*!
2 * VisualEditor UserInterface Surface class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * A surface is a top-level object which contains both a surface model and a surface view.
9 *
10 * @class
11 * @abstract
12 * @extends OO.ui.Widget
13 *
14 * @constructor
15 * @param {ve.init.Target} target Target the surface belongs to
16 * @param {HTMLDocument|Array|ve.dm.ElementLinearData|ve.dm.Document|ve.dm.Surface} dataOrDocOrSurface Document data, document model, or surface model to edit
17 * @param {Object} [config] Configuration options
18 * @param {ve.dm.BranchNode} [config.attachedRoot] Node to surface, if ve.dm.Document passed in
19 * @param {string} config.mode Editing mode, either "visual" or "source"
20 * @param {jQuery} [config.$scrollContainer] The scroll container of the surface
21 * @param {jQuery} [config.$scrollListener] The scroll listener of the surface
22 * @param {jQuery} [config.$overlayContainer] Clipping container for local overlays, defaults to surface view
23 * @param {number} [config.overlayPadding] Padding beween local overlays and clipping container
24 * @param {ve.ui.CommandRegistry} [config.commandRegistry] Command registry to use
25 * @param {ve.ui.SequenceRegistry} [config.sequenceRegistry] Sequence registry to use
26 * @param {ve.ui.DataTransferHandlerFactory} [config.dataTransferHandlerFactory] Data transfer handler factory to use
27 * @param {string[]|null} [config.includeCommands] List of commands to include, null for all registered commands
28 * @param {string[]} [config.excludeCommands] List of commands to exclude
29 * @param {Object} [config.importRules={}] Import rules
30 * @param {boolean} [config.multiline=true] Multi-line surface
31 * @param {string} [config.placeholder] Placeholder text to display when the surface is empty
32 * @param {string} [config.readOnly=false] Surface is read-only
33 * @param {string} [config.nullSelectionOnBlur=true] Surface selection is set to null on blur
34 * @param {string} [config.inDialog=''] The name of the dialog this surface is in
35 * @param {boolean} [config.inTargetWidget=false] The surface is in a target widget
36 */
37 ve.ui.Surface = function VeUiSurface( target, dataOrDocOrSurface, config ) {
38 config = config || {};
39
40 // Parent constructor
41 ve.ui.Surface.super.call( this, config );
42
43 // Properties
44 this.target = target;
45 this.$scrollContainer = config.$scrollContainer || $( this.getClosestScrollableElementContainer() );
46 this.$scrollListener = config.$scrollListener || $( this.getElementWindow() );
47 this.inDialog = config.inDialog || '';
48 this.inTargetWidget = !!config.inTargetWidget;
49 this.mode = config.mode;
50
51 // The following classes are used here:
52 // * ve-ui-overlay-global-mobile
53 // * ve-ui-overlay-global-desktop
54 this.globalOverlay = new ve.ui.Overlay( { classes: [ 've-ui-overlay-global', 've-ui-overlay-global-' + ( OO.ui.isMobile() ? 'mobile' : 'desktop' ) ] } );
55 this.localOverlay = new ve.ui.Overlay( { classes: [ 've-ui-overlay-local' ] } );
56 this.$selections = $( '<div>' ).addClass( 've-ui-surface-selections' );
57 this.$blockers = $( '<div>' );
58 this.$controls = $( '<div>' );
59 this.$menus = $( '<div>' );
60 this.$placeholder = $( '<div>' ).addClass( 've-ui-surface-placeholder' );
61 this.commandRegistry = config.commandRegistry || ve.ui.commandRegistry;
62 this.sequenceRegistry = config.sequenceRegistry || ve.ui.sequenceRegistry;
63 this.dataTransferHandlerFactory = config.dataTransferHandlerFactory || ve.ui.dataTransferHandlerFactory;
64 this.commands = OO.simpleArrayDifference(
65 config.includeCommands || this.commandRegistry.getNames(), config.excludeCommands || []
66 );
67 this.triggerListener = new ve.TriggerListener( this.commands, this.commandRegistry );
68 if ( dataOrDocOrSurface instanceof ve.dm.Surface ) {
69 this.model = dataOrDocOrSurface;
70 } else {
71 let documentModel;
72 if ( dataOrDocOrSurface instanceof ve.dm.Document ) {
73 // ve.dm.Document
74 documentModel = dataOrDocOrSurface;
75 } else if ( dataOrDocOrSurface instanceof ve.dm.ElementLinearData || Array.isArray( dataOrDocOrSurface ) ) {
76 // LinearData or raw linear data
77 documentModel = new ve.dm.Document( dataOrDocOrSurface );
78 } else {
79 // HTMLDocument
80 documentModel = ve.dm.converter.getModelFromDom( dataOrDocOrSurface );
81 }
82 this.model = this.createModel( documentModel, config.attachedRoot );
83 }
84 this.view = this.createView( this.model );
85 this.dialogs = this.createDialogWindowManager();
86 this.importRules = config.importRules || {};
87 this.multiline = config.multiline !== false;
88 this.context = this.createContext( {
89 $popupContainer: config.$overlayContainer,
90 popupPadding: config.overlayPadding
91 } );
92 this.progresses = [];
93 this.showProgressDebounced = ve.debounce( this.showProgress.bind( this ) );
94 this.scrollSelectionIntoViewDebounced = ve.debounce( this.scrollSelectionIntoView.bind( this ), 500 );
95 this.debugBar = null;
96 this.placeholder = null;
97 this.placeholderVisible = false;
98 this.setPlaceholder( config.placeholder );
99 this.setReadOnly( !!config.readOnly );
100 this.nullSelectionOnBlur = config.nullSelectionOnBlur !== false;
101 this.completion = new ve.ui.CompletionWidget( this );
102
103 // Deprecated, use this.padding.top
104 this.toolbarHeight = 0;
105 this.padding = {
106 top: 0,
107 right: 0,
108 bottom: 0,
109 left: 0
110 };
111 // Intiailised on first use
112 this.toolbarDialogs = {};
113
114 // Events
115 this.getModel().connect( this, {
116 select: 'onModelSelect',
117 blur: 'onModelBlur',
118 focus: 'onModelFocus'
119 } );
120 this.getModel().getDocument().connect( this, { transact: 'onDocumentTransact' } );
121 this.getView().connect( this, {
122 position: 'onViewPosition',
123 activation: 'onViewActivation'
124 } );
125 this.getContext().connect( this, { resize: ve.debounce( this.onContextResize.bind( this ) ) } );
126
127 // Initialization
128 if ( OO.ui.isMobile() ) {
129 // Mobile context is almost fullscreen and must appear on top of other elements (T308716)
130 this.globalOverlay.$element.append( this.context.$element );
131 } else {
132 this.$menus.append( this.context.$element );
133 }
134 this.$menus.append( this.completion.$element );
135 this.$element
136 // The following classes are used here:
137 // * ve-ui-surface-visual
138 // * ve-ui-surface-source
139 .addClass( 've-ui-surface ve-ui-surface-' + this.mode )
140 .append( this.view.$element );
141 if ( this.mode === 'source' ) {
142 // Separate class to make it easier to override
143 this.getView().$element.add( this.$placeholder )
144 .addClass( 've-ui-surface-source-font' );
145 }
146 this.view.$element.after( this.localOverlay.$element );
147 this.localOverlay.$element.append( this.$selections, this.$blockers, this.$controls, this.$menus );
148 this.globalOverlay.$element.append( this.dialogs.$element );
149 };
150
151 /* Inheritance */
152
153 OO.inheritClass( ve.ui.Surface, OO.ui.Widget );
154
155 /* Events */
156
157 /**
158 * When a surface has been initialized
159 *
160 * @event ve.ui.Surface#ready
161 */
162
163 /**
164 * When a surface is destroyed.
165 *
166 * @event ve.ui.Surface#destroy
167 */
168
169 /**
170 * The surface was scrolled programmatically
171 * as a result of a native selection change
172 *
173 * @event ve.ui.Surface#scroll
174 */
175
176 /**
177 * The surface has been submitted by user action, e.g. Ctrl+Enter
178 *
179 * @event ve.ui.Surface#submit
180 */
181
182 /**
183 * The surface has been cancelled by user action, e.g. Escape
184 *
185 * @event ve.ui.Surface#cancel
186 */
187
188 /**
189 * The surface read-only state has changed
190 *
191 * @event ve.ui.Surface#readOnly
192 * @param {boolean} readOnly The surface is read-only
193 */
194
195 /* Methods */
196
197 /**
198 * Destroy the surface, releasing all memory and removing all DOM elements.
199 *
200 * @return {ve.ui.Surface}
201 * @chainable
202 * @fires ve.ui.Surface#destroy
203 */
204 ve.ui.Surface.prototype.destroy = function () {
205 // Destroy the ce.Surface, the ui.Context and window managers
206 this.context.destroy();
207 this.dialogs.destroy();
208 for ( const side in this.toolbarDialogs ) {
209 this.toolbarDialogs[ side ].destroy();
210 }
211 this.view.destroy();
212 if ( this.debugBar ) {
213 this.debugBar.destroy();
214 }
215
216 // Disconnect events
217 this.dialogs.disconnect( this );
218 this.context.getInspectors().disconnect( this );
219
220 // Remove DOM elements
221 this.$element.remove();
222 this.globalOverlay.$element.remove();
223
224 // Let others know we have been destroyed
225 this.emit( 'destroy' );
226
227 return this;
228 };
229
230 /**
231 * Initialize surface.
232 *
233 * This must be called after the surface has been attached to the DOM.
234 *
235 * @return {ve.ui.Surface}
236 * @chainable
237 * @fires ve.ui.Surface#ready
238 */
239 ve.ui.Surface.prototype.initialize = function () {
240 $( OO.ui.getTeleportTarget() ).append( this.globalOverlay.$element );
241
242 if ( ve.debug ) {
243 this.setupDebugBar();
244 }
245
246 // The following classes are used here:
247 // * ve-ui-surface-dir-ltr
248 // * ve-ui-surface-dir-rtl
249 this.$element.addClass( 've-ui-surface-dir-' + this.getDir() );
250
251 this.getView().initialize();
252 this.getModel().initialize();
253
254 this.emit( 'ready' );
255 return this;
256 };
257
258 /**
259 * Get the target the surface belongs to
260 *
261 * @return {ve.init.Target}
262 */
263 ve.ui.Surface.prototype.getTarget = function () {
264 return this.target;
265 };
266
267 /**
268 * Get the DOM representation of the surface's current state.
269 *
270 * @return {HTMLDocument|string} HTML document (visual mode) or text (source mode)
271 */
272 ve.ui.Surface.prototype.getDom = function () {
273 return this.getModel().getDom();
274 };
275
276 /**
277 * Get the HTML representation of the surface's current state.
278 *
279 * @return {string} HTML
280 */
281 ve.ui.Surface.prototype.getHtml = function () {
282 return this.getModel().getHtml();
283 };
284
285 /**
286 * Get the surface's editing mode
287 *
288 * @return {string} Editing mode
289 */
290 ve.ui.Surface.prototype.getMode = function () {
291 return this.mode;
292 };
293
294 /**
295 * Create a context.
296 *
297 * @param {Object} config Configuration options
298 * @return {ve.ui.LinearContext}
299 */
300 ve.ui.Surface.prototype.createContext = function ( config ) {
301 return OO.ui.isMobile() ? new ve.ui.MobileContext( this, config ) : new ve.ui.DesktopContext( this, config );
302 };
303
304 /**
305 * Create a dialog window manager.
306 *
307 * @return {ve.ui.WindowManager} Dialog window manager
308 */
309 ve.ui.Surface.prototype.createDialogWindowManager = function () {
310 return OO.ui.isMobile() ?
311 new ve.ui.MobileWindowManager( this, {
312 factory: ve.ui.windowFactory,
313 overlay: this.globalOverlay
314 } ) :
315 new ve.ui.SurfaceWindowManager( this, { factory: ve.ui.windowFactory } );
316 };
317
318 /**
319 * Create a surface model
320 *
321 * @param {ve.dm.Document} doc Document model
322 * @param {ve.dm.BranchNode} [attachedRoot] Node to surface
323 * @return {ve.dm.Surface} Surface model
324 */
325 ve.ui.Surface.prototype.createModel = function ( doc, attachedRoot ) {
326 return new ve.dm.Surface( doc, attachedRoot, { sourceMode: this.getMode() === 'source' } );
327 };
328
329 /**
330 * Create a surface view
331 *
332 * @param {ve.dm.Surface} model Surface model
333 * @return {ve.ce.Surface} Surface view
334 */
335 ve.ui.Surface.prototype.createView = function ( model ) {
336 return new ve.ce.Surface( model, this );
337 };
338
339 /**
340 * Set up the debug bar and insert it into the DOM.
341 */
342 ve.ui.Surface.prototype.setupDebugBar = function () {
343 this.debugBar = new ve.ui.DebugBar( this );
344 this.$element.append( this.debugBar.$element );
345 };
346
347 /**
348 * Get the bounding rectangle of the surface, relative to the viewport.
349 *
350 * @return {Object|null} Object with top, bottom, left, right, width and height properties.
351 * Null if the surface is not attached.
352 */
353 ve.ui.Surface.prototype.getBoundingClientRect = function () {
354 // We would use getBoundingClientRect(), but in iOS7 that's relative to the
355 // document rather than to the viewport
356 return this.$element[ 0 ].getClientRects()[ 0 ] || null;
357 };
358
359 /**
360 * Get vertical measurements of the visible area of the surface viewport
361 *
362 * @return {Object|null} Object with top, left, bottom, and height properties. Null if the surface is not attached.
363 */
364 ve.ui.Surface.prototype.getViewportDimensions = function () {
365 const rect = this.getBoundingClientRect();
366
367 if ( !rect ) {
368 return null;
369 }
370
371 const top = Math.max( this.getPadding().top - rect.top, 0 );
372 const bottom = $( this.getElementWindow() ).height() - rect.top;
373
374 return {
375 top: top,
376 left: rect.left,
377 bottom: bottom,
378 height: bottom - top
379 };
380 };
381
382 /**
383 * Get the surface model.
384 *
385 * @return {ve.dm.Surface} Surface model
386 */
387 ve.ui.Surface.prototype.getModel = function () {
388 return this.model;
389 };
390
391 /**
392 * Get the surface view.
393 *
394 * @return {ve.ce.Surface} Surface view
395 */
396 ve.ui.Surface.prototype.getView = function () {
397 return this.view;
398 };
399
400 /**
401 * Get the context menu.
402 *
403 * @return {ve.ui.LinearContext} Context user interface
404 */
405 ve.ui.Surface.prototype.getContext = function () {
406 return this.context;
407 };
408
409 /**
410 * Get dialogs window set.
411 *
412 * @return {ve.ui.WindowManager} Dialogs window set
413 */
414 ve.ui.Surface.prototype.getDialogs = function () {
415 return this.dialogs;
416 };
417
418 /**
419 * Get toolbar dialogs window set.
420 *
421 * @param {string} [position='side'] Get the toolbar dialogs window set for a specific position
422 * @return {ve.ui.WindowManager} Toolbar dialogs window set
423 */
424 ve.ui.Surface.prototype.getToolbarDialogs = function ( position ) {
425 position = position || 'side';
426 this.toolbarDialogs[ position ] = this.toolbarDialogs[ position ] ||
427 new ve.ui.ToolbarDialogWindowManager( this, {
428 factory: ve.ui.windowFactory,
429 modal: false
430 } );
431 return this.toolbarDialogs[ position ];
432 };
433
434 /**
435 * Get the local overlay.
436 *
437 * Local overlays are attached to the same frame as the surface.
438 *
439 * @return {ve.ui.Overlay} Local overlay
440 */
441 ve.ui.Surface.prototype.getLocalOverlay = function () {
442 return this.localOverlay;
443 };
444
445 /**
446 * Get the global overlay.
447 *
448 * Global overlays are attached to the top-most frame.
449 *
450 * @return {ve.ui.Overlay} Global overlay
451 */
452 ve.ui.Surface.prototype.getGlobalOverlay = function () {
453 return this.globalOverlay;
454 };
455
456 /**
457 * @inheritdoc
458 */
459 ve.ui.Surface.prototype.setDisabled = function ( disabled ) {
460 if ( disabled ) {
461 OO.ui.warnDeprecation( 'Surfaces can\'t be disabled, only set to readOnly' );
462 }
463 };
464
465 /**
466 * Set the read-only state of the surface
467 *
468 * @param {boolean} readOnly Make surface read-only
469 * @fires ve.ui.Surface#readOnly
470 */
471 ve.ui.Surface.prototype.setReadOnly = function ( readOnly ) {
472 this.readOnly = !!readOnly;
473 this.model.setReadOnly( readOnly );
474 this.view.setReadOnly( readOnly );
475 this.emit( 'readOnly', readOnly );
476 };
477
478 /**
479 * Check if the surface is read-only
480 *
481 * @return {boolean}
482 */
483 ve.ui.Surface.prototype.isReadOnly = function () {
484 return this.readOnly;
485 };
486
487 /**
488 * Give focus to the surface
489 */
490 ve.ui.Surface.prototype.focus = function () {
491 this.getView().focus();
492 };
493
494 /**
495 * Handle transact events from the document model
496 *
497 * @param {ve.dm.Transaction} Transaction
498 */
499 ve.ui.Surface.prototype.onDocumentTransact = function () {
500 if ( this.placeholder ) {
501 this.updatePlaceholder();
502 }
503 };
504
505 /**
506 * Handle select events from the model
507 */
508 ve.ui.Surface.prototype.onModelSelect = function () {
509 // eslint-disable-next-line no-bitwise
510 if ( this.getView().dragging ^ OO.ui.isMobile() ) {
511 // Allow native scroll behavior while dragging, as the start/end
512 // points are unreliable until we're finished. Without this, trying to
513 // drag a selection larger than a single screen will sometimes lock
514 // the viewport in place, as it tries to keep the wrong end of the
515 // selection on-screen.
516 // On mobile the dragging flag is essentially reversed in meaning, as
517 // it is set during mouse down, which happens when you are tapping
518 // to select, but when you drag selection handles no mousedown event
519 // occurs (or any event other 'selectionchange') so the flag is unset.
520 return;
521 }
522 const synchronizer = this.getModel().synchronizer;
523 // Don't scroll to this user's cursor due to another user's changes being applied
524 if ( !( synchronizer && synchronizer.applying ) ) {
525 this.scrollSelectionIntoViewDebounced();
526 }
527 };
528
529 /**
530 * Scroll the selection into view
531 *
532 * Called in response to selection events.
533 *
534 * This is done for all selections, even native ones, to account
535 * for the extra padding of the floating toolbar.
536 *
537 * @param {ve.dm.Selection} [selectionModel] Optional selection model, defaults to current selection
538 * @param {Object} [scrollConfig] Scroll config options, passed to ve.scrollIntoView
539 * @fires ve.ui.Surface#scroll
540 */
541 ve.ui.Surface.prototype.scrollSelectionIntoView = function ( selectionModel, scrollConfig ) {
542 selectionModel = selectionModel || this.getModel().getSelection();
543
544 const view = this.getView(),
545 selectionView = view.getSelection( selectionModel ),
546 isNative = selectionView.isNativeCursor();
547
548 // We only care about the focus end of the selection, the anchor never
549 // moves and should be allowed off screen.
550 let clientRect = selectionView.getSelectionFocusRect();
551 const surfaceRect = this.getBoundingClientRect();
552 if ( !clientRect || !surfaceRect ) {
553 return;
554 }
555
556 // We want viewport-relative coordinates, so we need to translate it
557 clientRect = ve.translateRect( clientRect, surfaceRect.left, surfaceRect.top );
558
559 const padding = ve.copy( this.getPadding() );
560
561 let animate = true;
562 if ( isNative ) {
563 animate = false;
564 if (
565 OO.ui.isMobile() &&
566 !selectionModel.isCollapsed()
567 ) {
568 const profile = $.client.profile();
569 // Assume that if the selection has been expanded, then a context menu is visible
570 // above the selection. We don't want this to obscure the toolbar so add on an
571 // estimate of its height.
572 // Previously we applied this fix to iOS, even though scrolling closed the context,
573 // because the user could touch the selection to re-open it. However sometime between
574 // iOS 12 and 12.3, scrolling stopped closing the context, but it doesn't move it either,
575 // so this fix became useless.
576 // Older versions of Android draw the context menu in the address bar and so
577 // don't need to be fixed.
578 if ( profile.name === 'android' && profile.versionNumber >= 6 ) {
579 padding.top += 60;
580 }
581 // Also assume there are selection handles below on Android. (T204718)
582 if ( profile.name === 'android' || profile.name === 'firefox' ) {
583 padding.bottom += 30;
584 }
585 }
586 } else {
587 // Don't attempt to scroll non-native selections into view if they
588 // are taller than the viewport (T305862).
589 const viewportDimensions = this.getViewportDimensions();
590 if ( clientRect.height > viewportDimensions.height ) {
591 return;
592 }
593 }
594
595 // Add some minimum padding so the selection doesn't touch the edge of the viewport
596 padding.top += 5;
597 padding.bottom += 5;
598 padding.left += 5;
599 padding.right += 5;
600
601 ve.scrollIntoView( clientRect, ve.extendObject( {
602 animate: animate,
603 scrollContainer: this.$scrollContainer[ 0 ],
604 padding: padding
605 }, scrollConfig ) ).then( () => {
606 if ( isNative ) {
607 // TODO: This event has only even been emitted for native selection
608 // scroll changes. Perhaps rename it.
609 this.emit( 'scroll' );
610 }
611 } );
612 };
613
614 // Deprecated alias
615 ve.ui.Surface.prototype.scrollCursorIntoView = ve.ui.Surface.prototype.scrollSelectionIntoView;
616
617 /**
618 * Set placeholder text
619 *
620 * @param {string} [placeholder] Placeholder text, clears placeholder if not set
621 */
622 ve.ui.Surface.prototype.setPlaceholder = function ( placeholder ) {
623 this.placeholder = placeholder;
624 if ( this.placeholder ) {
625 this.$placeholder.prependTo( this.$element );
626 this.updatePlaceholder();
627 const documentView = this.getView().getDocument();
628 this.$placeholder.prop( {
629 dir: documentView.getDir(),
630 lang: documentView.getLang()
631 } );
632 } else {
633 this.$placeholder.detach();
634 this.placeholderVisible = false;
635 this.getView().$element.css( 'min-height', '' );
636 }
637 this.getView().attachedRoot.$element.attr( 'aria-label', this.placeholder || null );
638 };
639
640 /**
641 * Update placeholder rendering
642 */
643 ve.ui.Surface.prototype.updatePlaceholder = function () {
644 const hasContent = this.getModel().getDocument().data.hasContent();
645
646 this.$placeholder.toggleClass( 'oo-ui-element-hidden', hasContent );
647 this.placeholderVisible = !hasContent;
648 if ( !hasContent ) {
649 // Use a clone of the first node in the document so the placeholder
650 // styling matches the text the users sees when they start typing
651 const firstNode = this.getView().attachedRoot.children[ 0 ];
652 let $wrapper;
653 if ( firstNode ) {
654 $wrapper = firstNode.$element.clone();
655 if ( ve.debug ) {
656 // In debug mode a background colour from the render animation may be present
657 $wrapper.removeAttr( 'style' );
658 }
659 } else {
660 $wrapper = $( '<p>' );
661 }
662 this.$placeholder.empty().append( $wrapper.text( this.placeholder ) );
663 } else {
664 this.getView().$element.css( 'min-height', '' );
665 }
666 };
667
668 /**
669 * Handle position events from the view
670 *
671 * @param {boolean} [wasSynchronizing]
672 */
673 ve.ui.Surface.prototype.onViewPosition = function ( wasSynchronizing ) {
674 const padding = {};
675 for ( const side in this.toolbarDialogs ) {
676 ve.extendObject( padding, this.toolbarDialogs[ side ].getSurfacePadding() );
677 }
678 if ( Object.keys( padding ).length ) {
679 this.setPadding( padding );
680 this.adjustVisiblePadding();
681 // Don't scroll to this user's cursor due to another user's changes being applied
682 if ( !wasSynchronizing ) {
683 this.scrollSelectionIntoView();
684 }
685 }
686 if ( this.placeholderVisible ) {
687 this.getView().$element.css( 'min-height', this.$placeholder.outerHeight() );
688 }
689 };
690
691 /**
692 * Get list of commands available on this surface.
693 *
694 * @return {string[]} Commands
695 */
696 ve.ui.Surface.prototype.getCommands = function () {
697 return this.commands;
698 };
699
700 /**
701 * Execute an action or command
702 *
703 * This is a compatability wrapper for executeCommandWithSource.
704 *
705 * @param {ve.ui.Trigger|string} triggerOrAction Trigger or symbolic name of action
706 * @param {string} [method] Action method name
707 * @param {...any} [args] Additional arguments for action
708 * @return {boolean} Action or command was executed
709 */
710 ve.ui.Surface.prototype.execute = function ( triggerOrAction, method, ...args ) {
711 return this.executeWithSource( triggerOrAction, method, false, ...args );
712 };
713
714 /**
715 * Execute an action or command
716 *
717 * @param {ve.ui.Trigger|string} triggerOrAction Trigger or symbolic name of action
718 * @param {string} [method] Action method name
719 * @param {string} [source] Action source, for logging
720 * @param {...any} [args] Additional arguments for action
721 * @return {boolean} Action or command was executed
722 */
723 ve.ui.Surface.prototype.executeWithSource = function ( triggerOrAction, method, source, ...args ) {
724 if ( triggerOrAction instanceof ve.ui.Trigger ) {
725 const command = this.triggerListener.getCommandByTrigger( triggerOrAction.toString() );
726 if ( command ) {
727 // Have command call execute with action arguments
728 return command.execute( this, false, source );
729 }
730 } else if ( typeof triggerOrAction === 'string' && typeof method === 'string' ) {
731 // Validate method
732 if ( ve.ui.actionFactory.doesActionSupportMethod( triggerOrAction, method ) ) {
733 // Create an action object and execute the method on it
734 const obj = ve.ui.actionFactory.create( triggerOrAction, this, source );
735 const ret = obj[ method ]( ...args );
736 return ret === undefined || !!ret;
737 }
738 }
739 return false;
740 };
741
742 /**
743 * Execute a command by name
744 *
745 * @param {string} commandName Command name
746 * @return {boolean} The command was executed
747 */
748 ve.ui.Surface.prototype.executeCommand = function ( commandName ) {
749 const command = this.commandRegistry.lookup( commandName );
750 if ( command ) {
751 return command.execute( this );
752 }
753 return false;
754 };
755
756 // Deprecated, use #setPadding
757 ve.ui.Surface.prototype.setToolbarHeight = function ( toolbarHeight ) {
758 this.setPadding( { top: toolbarHeight } );
759 };
760
761 /**
762 * @typedef {Object} Padding
763 * @memberof ve.ui.Surface
764 * @property {number} [top] Top padding
765 * @property {number} [right] Right padding
766 * @property {number} [bottom] Bottom padding
767 * @property {number} [left] Left padding
768 */
769
770 /**
771 * Set content area padding.
772 *
773 * When UI components obscure the surface (e.g. the toolbar),
774 * set the appropriate amount of padding here so that
775 * scroll-into-view calculations can be adjusted.
776 *
777 * @param {ve.ui.Surface.Padding} padding Padding object. Omit properties to leave unchanged.
778 */
779 ve.ui.Surface.prototype.setPadding = function ( padding ) {
780 ve.extendObject( this.padding, padding );
781 // Deprecated, use this.padding.top
782 this.toolbarHeight = this.padding.top;
783 };
784
785 /**
786 * Get the current content area padding
787 *
788 * Padding in this context means areas of the surface which are
789 * rendered but are obsured by some other UI element, e.g. a
790 * floating toolbar (but not a static toolbar).
791 *
792 * This can be used when deciding how to position other floating
793 * UI elements, e.g. to avoid rendering a context menu under
794 * a floating toolbar.
795 *
796 * @return {ve.ui.Surface.Padding}
797 */
798 ve.ui.Surface.prototype.getPadding = function () {
799 return this.padding;
800 };
801
802 /**
803 * Handle resize events from the context
804 */
805 ve.ui.Surface.prototype.onContextResize = function () {
806 const padding = this.context.getSurfacePadding();
807 if ( padding ) {
808 this.setPadding( padding );
809 this.adjustVisiblePadding();
810 this.scrollSelectionIntoView();
811 }
812 };
813
814 /**
815 * Handle surface model blur events
816 */
817 ve.ui.Surface.prototype.onModelBlur = function () {
818 this.adjustVisiblePadding();
819 };
820
821 /**
822 * Handle surface model focus events
823 */
824 ve.ui.Surface.prototype.onModelFocus = function () {
825 this.adjustVisiblePadding();
826 };
827
828 /**
829 * Handle surface view activation events
830 */
831 ve.ui.Surface.prototype.onViewActivation = function () {
832 this.adjustVisiblePadding();
833 };
834
835 /**
836 * Adjust visible padding on the surface to allow the whole document
837 * to be scrolled to.
838 */
839 ve.ui.Surface.prototype.adjustVisiblePadding = function () {
840 if ( OO.ui.isMobile() && !this.inTargetWidget ) {
841 const keyboardShown = this.getView().hasNativeCursorSelection();
842 let bottom;
843 if ( ve.init.platform.constructor.static.isIos() && keyboardShown ) {
844 // iOS needs a whole extra page of padding when the virtual keyboard is shown.
845 // Note: we keep this padding when surface is deactivated-but-shown-as-activated
846 // so that the view doesn't shift when e.g. opening a toolbar toolgroup popup.
847 bottom = $( window ).height() - this.getPadding().top;
848 } else {
849 // otherwise just add padding to account for the context
850 bottom = this.getPadding().bottom;
851 }
852 this.getView().$attachedRootNode.css( 'padding-bottom', bottom );
853 this.scrollSelectionIntoView();
854 }
855 };
856
857 /**
858 * Create a progress bar in the progress dialog
859 *
860 * @param {jQuery.Promise} progressCompletePromise Promise which resolves when the progress action is complete
861 * @param {jQuery|string|Function} label Progress bar label
862 * @param {boolean} nonCancellable Progress item can't be cancelled
863 * @return {jQuery.Promise} Promise which resolves with a progress bar widget and fails if cancelled
864 */
865 ve.ui.Surface.prototype.createProgress = function ( progressCompletePromise, label, nonCancellable ) {
866 const progressBarDeferred = ve.createDeferred();
867
868 this.progresses.push( {
869 label: label,
870 cancellable: !nonCancellable,
871 progressCompletePromise: progressCompletePromise,
872 progressBarDeferred: progressBarDeferred
873 } );
874
875 this.showProgressDebounced();
876
877 return progressBarDeferred.promise();
878 };
879
880 ve.ui.Surface.prototype.showProgress = function () {
881 const progresses = this.progresses;
882
883 this.dialogs.openWindow( 'progress', { progresses: progresses, $returnFocusTo: null } );
884 this.progresses = [];
885 };
886
887 /**
888 * Get sanitization rules for rich paste
889 *
890 * @return {Object} Import rules
891 */
892 ve.ui.Surface.prototype.getImportRules = function () {
893 return this.importRules;
894 };
895
896 /**
897 * Check if the surface is multi-line
898 *
899 * @return {boolean} Surface is multi-line
900 */
901 ve.ui.Surface.prototype.isMultiline = function () {
902 return this.multiline;
903 };
904
905 /**
906 * Surface 'dir' property (GUI/User-Level Direction)
907 *
908 * @return {string} 'ltr' or 'rtl'
909 */
910 ve.ui.Surface.prototype.getDir = function () {
911 return this.$element.css( 'direction' );
912 };
913
914 /**
915 * Get the name of the dialog this surface is in
916 *
917 * @return {string} The name of the dialog this surface is in
918 */
919 ve.ui.Surface.prototype.getInDialog = function () {
920 return this.inDialog;
921 };