Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add utility to handle profusion of clicks #9567

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/core/src/browser/core-preferences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,19 @@ export const corePreferenceSchema: PreferenceSchema = {
default: 'code',
description: 'Whether to interpret keypresses by the `code` of the physical key, or by the `keyCode` provided by the OS.'
},
'application.clickTime': {
type: 'number',
minimum: 0,
default: 500, // This is Windows' default.
description: 'The number of milliseconds within which a second click should trigger a double-click action'
}
}
};

export interface CoreConfiguration {
'application.confirmExit': 'never' | 'ifRequired' | 'always';
'application.clickTime': number;
'files.encoding': string
'keyboard.dispatch': 'code' | 'keyCode';
'workbench.list.openMode': 'singleClick' | 'doubleClick';
'workbench.commandPalette.history': number;
Expand All @@ -110,7 +118,6 @@ export interface CoreConfiguration {
'workbench.colorTheme': string;
'workbench.iconTheme': string | null;
'workbench.silentNotifications': boolean;
'files.encoding': string
'workbench.tree.renderIndentGuides': 'onHover' | 'none' | 'always';
}

Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/browser/frontend-application-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ import {
} from './quick-input';
import { QuickAccessContribution } from './quick-input/quick-access';
import { QuickCommandService } from './quick-input/quick-command-service';
import { ClickEventHandler, ClickEventHandlerFactory, ClickEventHandlerOptions } from './widgets/event-utils';

export { bindResourceProvider, bindMessageService, bindPreferenceService };

Expand Down Expand Up @@ -353,4 +354,11 @@ export const frontendApplicationModule = new ContainerModule((bind, unbind, isBo
bind(CredentialsService).to(CredentialsServiceImpl);

bind(ContributionFilterRegistry).to(ContributionFilterRegistryImpl).inSingletonScope();

bind(ClickEventHandler).toSelf();
bind(ClickEventHandlerFactory).toFactory(({ container }) => (options: ClickEventHandlerOptions) => {
const child = container.createChild();
child.bind(ClickEventHandlerOptions).toConstantValue(options);
return child.get(ClickEventHandler);
});
});
15 changes: 12 additions & 3 deletions packages/core/src/browser/tree/tree-widget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { TreeWidgetSelection } from './tree-widget-selection';
import { MaybePromise } from '../../common/types';
import { LabelProvider } from '../label-provider';
import { CorePreferences } from '../core-preferences';
import { ClickEventHandler, ClickEventHandlerFactory } from '../widgets/event-utils';

const debounce = require('lodash.debounce');

Expand Down Expand Up @@ -147,14 +148,14 @@ export namespace TreeWidget {
*/
readonly shiftKey: boolean;
}

}

@injectable()
export class TreeWidget extends ReactWidget implements StatefulWidget {

protected searchBox: SearchBox;
protected searchHighlights: Map<string, TreeDecoration.CaptionHighlight>;
protected nodeClickEventHandler: ClickEventHandler<React.MouseEvent>;

@inject(TreeDecoratorService)
protected readonly decoratorService: TreeDecoratorService;
Expand All @@ -174,6 +175,8 @@ export class TreeWidget extends ReactWidget implements StatefulWidget {
@inject(CorePreferences)
protected readonly corePreferences: CorePreferences;

@inject(ClickEventHandlerFactory) protected readonly clickEventHandlerFactory: ClickEventHandlerFactory;

protected shouldScrollToRow = true;

constructor(
Expand Down Expand Up @@ -237,7 +240,14 @@ export class TreeWidget extends ReactWidget implements StatefulWidget {
}),
]);
}
this.nodeClickEventHandler = this.clickEventHandlerFactory({
actions: [
(event: React.MouseEvent<HTMLElement>, node: TreeNode) => this.handleClickEvent(node, event),
(event: React.MouseEvent<HTMLElement>, node: TreeNode) => this.handleDblClickEvent(node, event),
]
});
this.toDispose.pushAll([
this.nodeClickEventHandler,
this.model,
this.model.onChanged(() => this.updateRows()),
this.model.onSelectionChanged(() => this.updateScrollToRow({ resize: false })),
Expand Down Expand Up @@ -889,8 +899,7 @@ export class TreeWidget extends ReactWidget implements StatefulWidget {
return {
className,
style,
onClick: event => this.handleClickEvent(node, event),
onDoubleClick: event => this.handleDblClickEvent(node, event),
onClick: event => this.nodeClickEventHandler.invoke(event, node),
onContextMenu: event => this.handleContextMenuEvent(node, event)
};
}
Expand Down
111 changes: 111 additions & 0 deletions packages/core/src/browser/widgets/event-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/********************************************************************************
* Copyright (C) 2021 Ericsson and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/

import { Disposable } from '../../common';
import { inject, injectable } from 'inversify';
import * as React from 'react';
import { CorePreferences } from '../core-preferences';
import { wait } from '../../common/promise-util';

export const isReactEvent = (event: MouseEvent | React.MouseEvent): event is React.MouseEvent => 'nativeEvent' in event;

interface MouseEventHandlerPlus<T extends MouseEvent | React.MouseEvent> {
(event: T, ...additionalArgs: unknown[]): unknown;
}

export interface ClickEventHandlerOptions<T extends MouseEvent | React.MouseEvent = MouseEvent> {
/**
* A function to invoke on every click, regardless of other conditions.
*/
immediateAction?: MouseEventHandlerPlus<T>;
/**
* Functions to invoke on a given number of clicks, and no more.
* E.g. the action at index 0 will be invoked on a single click if no additional click
* comes within a set interval.
*/
actions: MouseEventHandlerPlus<T>[];
}

export const ClickEventHandlerOptions = Symbol('ClickEventHandlerOptions');
export interface ClickEventHandlerFactory {
<T extends MouseEvent | React.MouseEvent>(options: ClickEventHandlerOptions<T>): ClickEventHandler<T>;
}
export const ClickEventHandlerFactory = Symbol('ClickEventHandlerFactory');

@injectable()
export class ClickEventHandler<T extends MouseEvent | React.MouseEvent> implements Disposable {

@inject(CorePreferences) readonly preferences: CorePreferences;
@inject(ClickEventHandlerOptions) protected readonly options: ClickEventHandlerOptions<T>;

protected disposed = false;

/**
* Setting `.canceled` to true will prevent the handler from running.
* Calling `.run()` will invoke the handler immediately and prevent future invocations.
*/
protected queuedInvocation: { event: T, canceled: boolean, run: () => unknown } | undefined;

async invoke(event: T, ...additionalArguments: unknown[]): Promise<void> {
if (this.disposed) {
return;
}
if (isReactEvent(event)) {
event.persist();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've read somewhere that this is a no-op in newer React versions. From my testing, I don't think we need it. (https://reactjs.org/docs/events.html).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like they say that that's the case as of React 17, but we're still on 16.14.0 according to our yarn.lock. Good to know, though, and something to look forward to :-).

}
const { immediateAction, actions } = this.options;
if (immediateAction) {
immediateAction(event, ...additionalArguments);
}
const { detail } = event;
const handler = actions[detail - 1];
if (!!handler) {
if (this.queuedInvocation && detail > this.queuedInvocation.event.detail) { // Click is on same thing as before. Cancel that invocation.
this.queuedInvocation.canceled = true;
} else if (this.queuedInvocation) { // Clicking somewhere else or OS timer has run out. Run handler for last invocation immediately.
this.queuedInvocation.run();
}
const thisCall = {
event,
canceled: false,
run(): void {
if (!this.canceled) {
this.canceled = true;
handler(event, ...additionalArguments);
}
}
};
this.queuedInvocation = thisCall;
// If detail == actions.length, it's the last defined handler.
// In that case, we run it immediately. If >, we don't reach this code.
if (detail < actions.length) {
await wait(this.preferences.get('application.clickTime', 500));
}
thisCall.run();
if (this.queuedInvocation === thisCall) {
this.queuedInvocation = undefined;
}
}
}

dispose(): void {
this.disposed = true;
if (this.queuedInvocation) {
this.queuedInvocation.canceled = true;
this.queuedInvocation = undefined;
}
}
}