Skip to content

Commit

Permalink
Extract the doLater() util and friends into their own file
Browse files Browse the repository at this point in the history
  • Loading branch information
sedwards2009 committed Jan 12, 2018
1 parent abbd4d2 commit 330bd18
Show file tree
Hide file tree
Showing 19 changed files with 177 additions and 155 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,4 @@ src/render_process/gui/FileTransferProgress.js
src/render_process/UploadProgressBar.js
src/render_process/PtyIpcBridge.js
src/pty/Pty.js
src/utils/DoLater.js
91 changes: 0 additions & 91 deletions src/render_process/DomUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,97 +294,6 @@ const inflightResentEvents = new Map<EventTarget, CustomEvent>();

//-------------------------------------------------------------------------

export interface LaterHandle {
cancel(): void;
}

let doLaterId: number = -1;
let laterList: Function[] = [];

function doLaterTimeoutHandler(): void {
doLaterId = -1;
const workingList = [...laterList];
laterList = [];
workingList.forEach( f => f() );
}

/**
* Schedule a function to be executed later.
*
* @param func the function to be executed later
* @param msec Optional time delay in ms. Default is 0.
* @return {LaterHandle} This object can be used to cancel the scheduled execution.
*/
export function doLater(func: Function, msec=0): LaterHandle {
laterList.push(func);
if (doLaterId === -1) {
doLaterId = window.setTimeout(doLaterTimeoutHandler, msec);
}
return { cancel: () => {
laterList = laterList.filter( f => f!== func );
} };
}

let doLaterFrameId: number = -1;
let laterFrameList: Function[] = [];

/**
* Schedule a function to run at the next animation frame.
*/
function doLaterFrameHandler(): void {
const workingList = [...laterFrameList];
laterFrameList = [];

window.cancelAnimationFrame(doLaterFrameId);
doLaterFrameId = -1;

workingList.forEach( f => f() );
}

export function doLaterFrame(func: Function): LaterHandle {
laterFrameList.push(func);
if (doLaterFrameId === -1) {
doLaterFrameId = window.requestAnimationFrame(doLaterFrameHandler);
}
return { cancel: () => {
laterFrameList = laterFrameList.filter( f => f!== func );
} };
}

//-------------------------------------------------------------------------
/**
* Run a function later, and debounce the trigger mechanism. Repeatable too.
*
* This is a reusable way of setting up callback to be called later after
* being triggered. Like `doLater()` it is possible to specify how long
* later, and as the name suggests this can be triggered multiple times
* but will only fire the callback once. After the callback has been
* run then it can be immediately reused.
*/
export class DebouncedDoLater {
private _laterHandle: LaterHandle = null;

constructor(private _callback: () => void, public delayMillis=0) {
}

trigger(): void {
if (this._laterHandle === null) {
this._laterHandle = doLater( () => {
this._laterHandle = null;
this._callback();
}, this.delayMillis);
}
}

cancel(): void {
if (this._laterHandle !== null) {
this._laterHandle.cancel();
this._laterHandle = null;
}
}
}
//-------------------------------------------------------------------------

/**
* Format a Uint8Array and mimetype as a data url.
*
Expand Down
5 changes: 3 additions & 2 deletions src/render_process/MainWeb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {CommandEntry, Commandable, EVENT_COMMAND_PALETTE_REQUEST, isCommandable,
from './CommandPaletteRequestTypes';
import * as config from '../Config';
import {ContextMenu} from './gui/ContextMenu';
import {doLater} from '../utils/DoLater';
import * as DomUtils from './DomUtils';
import {DropDown} from './gui/DropDown';
import {EmbeddedViewer} from './viewers/EmbeddedViewer';
Expand Down Expand Up @@ -588,7 +589,7 @@ function handleCommandPaletteRequest(ev: CustomEvent): void {
const path = ev.composedPath();
const requestCommandableStack: Commandable[] = <any> path.filter(el => isCommandable(el));

DomUtils.doLater( () => {
doLater( () => {
const commandableStack: Commandable[] = [...requestCommandableStack, {executeCommand, getCommandPaletteEntries}];

const firstCommandable = commandableStack[0];
Expand Down Expand Up @@ -660,7 +661,7 @@ function handleCommandPaletteSelected(ev: CustomEvent): void {
if (selectedId !== null) {
const commandIndex = Number.parseInt(selectedId);
const commandEntry = commandPaletteRequestEntries[commandIndex];
DomUtils.doLater( () => {
doLater( () => {
commandEntry.commandExecutor.executeCommand(commandEntry.id, commandEntry.commandArguments);
commandPaletteRequestSource = null;
commandPaletteRequestEntries = null;
Expand Down
6 changes: 4 additions & 2 deletions src/render_process/ResizeCanary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import {Disposable} from 'extraterm-extension-api';
import {WebComponent} from 'extraterm-web-component-decorators';

import * as DomUtils from './DomUtils';
import {doLater} from '../utils/DoLater';
import {Logger, getLogger} from '../logging/Logger';
import ElementResizeDetectorMaker = require('element-resize-detector');

Expand All @@ -20,7 +22,7 @@ export class ResizeCanary extends HTMLElement {

private _log: Logger = null;
private _erd: any; //ElementResizeDetector.Detector;
private _laterHandle: DomUtils.LaterHandle = null;
private _laterHandle: Disposable = null;
private _css: string = "";

setCss(css: string): void {
Expand All @@ -44,7 +46,7 @@ export class ResizeCanary extends HTMLElement {

this._erd.listenTo(container, (el: HTMLElement) => {
if (this._laterHandle === null) {
this._laterHandle = DomUtils.doLater( () => {
this._laterHandle = doLater( () => {
const event = new CustomEvent('resize', { detail: { } });
this.dispatchEvent(event);
this._laterHandle = null;
Expand Down
15 changes: 8 additions & 7 deletions src/render_process/Terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {Commandable, EVENT_COMMAND_PALETTE_REQUEST, CommandEntry, COMMAND_OPEN_C
import {Logger, getLogger} from '../logging/Logger';
import LogDecorator from '../logging/LogDecorator';
import * as DomUtils from './DomUtils';
import {doLater} from '../utils/DoLater';
import * as Term from './emulator/Term';
import * as TermApi from './emulator/TermApi';
import {ScrollBar} from './gui/ScrollBar';
Expand Down Expand Up @@ -191,14 +192,14 @@ export class EtTerminal extends ThemeableElementBase implements Commandable, Acc
private _themeCssPath: string = null;
private _mainStyleLoaded = false;
private _themeStyleLoaded = false;
private _resizePollHandle: DomUtils.LaterHandle = null;
private _resizePollHandle: Disposable = null;
private _elementAttached = false;
private _needsCompleteRefresh = true;

// This flag is needed to prevent the _enforceScrollbackLength() method from being run recursively
private _enforceScrollbackLengthGuard= false;

private _scheduleLaterHandle: DomUtils.LaterHandle = null;
private _scheduleLaterHandle: Disposable = null;
private _scheduleLaterQueue: Function[] = [];
private _stashedChildResizeTask: () => void = null;

Expand Down Expand Up @@ -402,7 +403,7 @@ export class EtTerminal extends ThemeableElementBase implements Commandable, Acc
// FIXME flow control.
});

DomUtils.doLater(() => {
doLater(() => {
pty.resize(this._columns, this._rows);
})
}
Expand Down Expand Up @@ -480,7 +481,7 @@ export class EtTerminal extends ThemeableElementBase implements Commandable, Acc
*/
destroy(): void {
if (this._resizePollHandle !== null) {
this._resizePollHandle.cancel();
this._resizePollHandle.dispose();
this._resizePollHandle = null;
}

Expand Down Expand Up @@ -703,15 +704,15 @@ export class EtTerminal extends ThemeableElementBase implements Commandable, Acc
});

if (ev.detail.originMouse) {
DomUtils.doLater( () => { this.copyToClipboard() } ); // FIXME This should be debounced slightly.
doLater( () => { this.copyToClipboard() } ); // FIXME This should be debounced slightly.
}
}

private _handleChildFocus(ev: FocusEvent): void {
// This needs to be done later otherwise it tickles a bug in
// Chrome/Blink and prevents drag and drop from working.
// https://bugs.chromium.org/p/chromium/issues/detail?id=726248
DomUtils.doLater( () => {
doLater( () => {
if (this._mode === Mode.DEFAULT) {
this.focus();
}
Expand Down Expand Up @@ -1497,7 +1498,7 @@ export class EtTerminal extends ThemeableElementBase implements Commandable, Acc
this._scheduleLaterQueue.push(func);

if (this._scheduleLaterHandle === null) {
this._scheduleLaterHandle = DomUtils.doLater( () => {
this._scheduleLaterHandle = doLater( () => {
this._scheduleLaterHandle = null;
const queue = this._scheduleLaterQueue;
this._scheduleLaterQueue = [];
Expand Down
21 changes: 10 additions & 11 deletions src/render_process/ViewerTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
*/

import * as fs from 'fs';
import {Disposable} from 'extraterm-extension-api';
import {WebComponent} from 'extraterm-web-component-decorators';

import {BulkFileHandle} from './bulk_file_handling/BulkFileHandle';
import {EVENT_COMMAND_PALETTE_REQUEST, COMMAND_OPEN_COMMAND_PALETTE, isCommandable,
Commandable, CommandEntry} from './CommandPaletteRequestTypes';
import {doLater} from '../utils/DoLater';
import * as DomUtils from './DomUtils';
import {EmbeddedViewer} from './viewers/EmbeddedViewer';
import {Logger, getLogger} from '../logging/Logger';
Expand Down Expand Up @@ -79,11 +81,11 @@ export class EtViewerTab extends ViewerElement implements Commandable,

private _mainStyleLoaded = false;
private _themeStyleLoaded = false;
private _resizePollHandle: DomUtils.LaterHandle = null;
private _resizePollHandle: Disposable = null;
private _elementAttached = false;
private _needsCompleteRefresh = true;

private _scheduleLaterHandle: DomUtils.LaterHandle = null;
private _scheduleLaterHandle: Disposable = null;
private _scheduledResize = false;

private _fontSizeAdjustment = 0;
Expand Down Expand Up @@ -174,7 +176,7 @@ export class EtViewerTab extends ViewerElement implements Commandable,

this.updateThemeCss();

DomUtils.doLater(this._processResize.bind(this));
doLater(this._processResize.bind(this));
}

disconnectedCallback(): void {
Expand All @@ -187,6 +189,10 @@ export class EtViewerTab extends ViewerElement implements Commandable,
if (element !== null) {
element.dispose();
}
if (this._resizePollHandle !== null) {
this._resizePollHandle.dispose();
this._resizePollHandle = null;
}
}

// FIXME delete
Expand All @@ -202,13 +208,6 @@ export class EtViewerTab extends ViewerElement implements Commandable,
this._tag = tag;
}

destroy(): void {
if (this._resizePollHandle !== null) {
this._resizePollHandle.cancel();
this._resizePollHandle = null;
}
}

focus(): void {
const element = this.getViewerElement();
if (element !== null) {
Expand Down Expand Up @@ -549,7 +548,7 @@ export class EtViewerTab extends ViewerElement implements Commandable,

private _handleBeforeSelectionChange(ev: CustomEvent): void {
if (ev.detail.originMouse) {
DomUtils.doLater( () => { this.copyToClipboard() } );
doLater( () => { this.copyToClipboard() } );
}
}

Expand Down
5 changes: 3 additions & 2 deletions src/render_process/gui/FileTransferProgress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Vue from 'vue';
import {WebComponent, Attribute, Observe} from 'extraterm-web-component-decorators';

import * as DomUtils from '../DomUtils';
import {DebouncedDoLater} from '../../utils/DoLater';
import {Logger, getLogger} from '../../logging/Logger';
import log from '../../logging/LogDecorator';
import {SimpleElementBase} from './SimpleElementBase';
Expand Down Expand Up @@ -122,14 +123,14 @@ export class FileTransferProgress extends SimpleElementBase implements Disposabl

private _log: Logger;
private _ui: FileTransferUI = null;
private _updateLater: DomUtils.DebouncedDoLater = null;
private _updateLater: DebouncedDoLater = null;
private _speedTracker: SpeedTracker = null;

constructor() {
super();
this._log = getLogger(FileTransferProgress.TAG_NAME, this);

this._updateLater = new DomUtils.DebouncedDoLater(this._updateLaterCallback.bind(this), 250);
this._updateLater = new DebouncedDoLater(this._updateLaterCallback.bind(this), 250);

this._ui = new FileTransferUI();
const component = this._ui.$mount();
Expand Down
6 changes: 4 additions & 2 deletions src/render_process/gui/ListPicker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import {Disposable} from 'extraterm-extension-api';
import {Attribute, Filter, Observe, WebComponent} from 'extraterm-web-component-decorators';

import {ThemeableElementBase} from '../ThemeableElementBase';
import * as ThemeTypes from '../../theme/Theme';
import * as DomUtils from '../DomUtils';
import {doLater} from '../../utils/DoLater';
import {PopDownDialog} from './PopDownDialog';
import {Logger, getLogger} from '../../logging/Logger';
import log from '../../logging/LogDecorator';
Expand All @@ -33,7 +35,7 @@ const ID_RESULTS = "ID_RESULTS";
private _selectedId: string = null;
private _filterEntries: (entries: T[], filterText: string) => T[];
private _formatEntries: (filteredEntries: T[], selectedId: string, filterInputValue: string) => string;
private _laterHandle: DomUtils.LaterHandle = null;
private _laterHandle: Disposable = null;
private _extraCssFiles: ThemeTypes.CssFile[] = [];

constructor() {
Expand Down Expand Up @@ -260,7 +262,7 @@ const ID_RESULTS = "ID_RESULTS";

private _okId(selectedId: string): void {
if (this._laterHandle === null) {
this._laterHandle = DomUtils.doLater( () => {
this._laterHandle = doLater( () => {
this._laterHandle = null;
const event = new CustomEvent("selected", { detail: {selected: selectedId } });
this.dispatchEvent(event);
Expand Down
2 changes: 0 additions & 2 deletions src/render_process/gui/PopDownDialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ export class PopDownDialog extends ThemeableElementBase {
static TAG_NAME = "ET-POPDOWNDIALOG";
static EVENT_CLOSE_REQUEST = "ET-POPDOWNDIALOG-CLOSE_REQUEST";

private _laterHandle: DomUtils.LaterHandle = null;

constructor() {
super();
const shadow = this.attachShadow({ mode: 'open', delegatesFocus: true });
Expand Down
6 changes: 4 additions & 2 deletions src/render_process/gui/PopDownListPicker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import {Disposable} from 'extraterm-extension-api';
import {Attribute, Observe, WebComponent} from 'extraterm-web-component-decorators';

import {doLater} from '../../utils/DoLater';
import {Logger, getLogger} from '../../logging/Logger';
import {ThemeableElementBase} from '../ThemeableElementBase';
import * as ThemeTypes from '../../theme/Theme';
Expand All @@ -31,7 +33,7 @@ export class PopDownListPicker<T extends { id: string; }> extends ThemeableEleme
private _entries: T[] = [];
private _filterEntries: (entries: T[], filterText: string) => T[];
private _formatEntries: (filteredEntries: T[], selectedId: string, filterInputValue: string) => string;
private _laterHandle: DomUtils.LaterHandle = null;
private _laterHandle: Disposable = null;
private _extraCssFiles: ThemeTypes.CssFile[] = [];

constructor() {
Expand Down Expand Up @@ -273,7 +275,7 @@ export class PopDownListPicker<T extends { id: string; }> extends ThemeableEleme

private _okId(selectedId: string): void {
if (this._laterHandle === null) {
this._laterHandle = DomUtils.doLater( () => {
this._laterHandle = doLater( () => {
this.close();
this._laterHandle = null;
const event = new CustomEvent("selected", { detail: {selected: selectedId } });
Expand Down
Loading

0 comments on commit 330bd18

Please sign in to comment.