Skip to content

Instantly share code, notes, and snippets.

@claviska
Last active February 7, 2022 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save claviska/fb7a811668f39fa821bb6599a490ffcf to your computer and use it in GitHub Desktop.
Save claviska/fb7a811668f39fa821bb6599a490ffcf to your computer and use it in GitHub Desktop.
A Reactive Controller for detecting "click presses."
import type { ReactiveController, ReactiveControllerHost } from 'lit';
export interface ClickPressOptions {
/**
* An optional selector to designate an element in shadow root where listeners will be attached. If unset, the host
* element will be used.
*/
selector: string;
/**
* The time in milliseconds to wait after the first press and before the interval will start counting. Useful for
* simulating a click press in the same way many keyboards work when a key is held down.
*/
delayAfterFirstPress: number;
/** The time in milliseconds to wait before initiating another press. Defaults to 250. */
interval: number;
/**
* Called when pressed and called again every interval while the control remains pressed. The event will initially be
* the mousedown event that initiated the press. Subsequent events will be the most recent mousemove event, or the
* original mousedown event if the cursor hasn't moved.
*/
press: (event: MouseEvent) => unknown;
/**
* Called when the press is finally released. The event will be a mouseup event or a mouseleave event if the cursor
* exited the target element during a press.
*/
release: (event: MouseEvent) => unknown;
}
export class ClickPressController implements ReactiveController {
host: ReactiveControllerHost & Element;
options: Partial<ClickPressOptions>;
target: Element;
firstPressTimeout: number;
nextInterval: number;
lastMoveEvent: MouseEvent | undefined;
constructor(host: ReactiveControllerHost & Element, options: Partial<ClickPressOptions>) {
(this.host = host).addController(this);
this.options = options;
this.handleMove = this.handleMove.bind(this);
this.handlePress = this.handlePress.bind(this);
this.handleExit = this.handleExit.bind(this);
this.handleRelease = this.handleRelease.bind(this);
}
hostConnected() {
this.host.updateComplete.then(() => {
if (this.options.selector) {
try {
const target = this.host.shadowRoot!.querySelector(this.options.selector);
if (target === null) {
throw new Error(`No target found using the "${this.options.selector}" query selector.`);
}
this.target = target;
} catch {
throw new Error(`Invalid query selector "${this.options.selector}" in ClickPressController.`);
}
} else {
this.target = this.host;
}
this.target.addEventListener('mousedown', this.handlePress);
this.target.addEventListener('touchstart', this.handlePress);
});
}
hostDisconnected() {
this.target.removeEventListener('mousedown', this.handlePress);
this.target.removeEventListener('touchstart', this.handlePress);
this.removePressedListeners();
}
private handlePress(event: MouseEvent) {
this.addPressedListeners();
// First press
if (this.options.press) {
this.options.press(event);
}
// Interval presses (after first press delay)
this.firstPressTimeout = window.setTimeout(() => {
this.nextInterval = window.setInterval(() => {
if (this.options.press) {
this.options.press(this.lastMoveEvent ?? event);
}
}, this.options.interval ?? 250);
}, this.options.delayAfterFirstPress ?? 0);
}
private handleExit(event: MouseEvent) {
// If the mouse leaves the target element, trigger a release
this.handleRelease(event);
}
private handleMove(event: MouseEvent) {
// Remember the last mouse move event so we can send it along in the next interval.
this.lastMoveEvent = event;
}
private handleRelease(event: MouseEvent) {
this.removePressedListeners();
window.clearTimeout(this.firstPressTimeout);
window.clearInterval(this.nextInterval);
this.lastMoveEvent = undefined;
// Release
if (this.options.release) {
this.options.release(event);
}
}
private addPressedListeners() {
this.target.addEventListener('mouseleave', this.handleExit);
document.addEventListener('mousemove', this.handleMove);
document.addEventListener('mouseup', this.handleRelease);
document.addEventListener('touchend', this.handleRelease);
document.addEventListener('touchmove', this.handleExit);
}
private removePressedListeners() {
this.target.removeEventListener('mouseleave', this.handleExit);
document.removeEventListener('mousemove', this.handleMove);
document.removeEventListener('mouseup', this.handleRelease);
document.removeEventListener('touchend', this.handleRelease);
document.removeEventListener('touchmove', this.handleExit);
}
}

Copyright (c) 2020 A Beautiful Site, LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Click Press Reactive Controller

Allows you to easily listen for "click presses" on arbitrary elements in your component. A click press is when the users holds the click for longer than normal. With this controller, you can run a callback at a set interval until the click is released.

What is a Reactive Controller?

Reactive Controllers let you abstract and reuse code in components. They were designed for Lit, but are generic enough to be easily adapted for other libraries.

Learn more: https://lit.dev/docs/composition/controllers/

Usage

import { LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';
import { ClickPressController } from './click-press-controller';

@customElement('my-element')
class MyElement extends LitElement {
  // ...

  private readonly clickPressController = new ClickPressController(this, {
    selector: '.button', // optional selector to listen for presses (if unset, the host element will be used)
    interval: 250, // how frequently the press will repeat in milliseconds
    delayAfterFirstPress: 250, // optional delay in milliseconds to wait after the first press
    press: event => console.log('pressed'), // runs when pressed, and again on each interval until release
    release: event => console.log('released') // runs when released
  });

  // ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment