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

Stop longpress propagation? #221

Open
melMass opened this issue Jan 25, 2024 · 2 comments
Open

Stop longpress propagation? #221

melMass opened this issue Jan 25, 2024 · 2 comments

Comments

@melMass
Copy link

melMass commented Jan 25, 2024

Hi,

Great project, I just stumbled on it while looking for longpress action implementations.

I basically found 3 and had made one myself years ago, they all look relatively similar but none stop propagation of the mouseclick event.

I tried a few approach like stopImmediatePropagation and preventDefault but I'm probably doing it wrong.

As this repo seems the most up to date project to ship such an action it would be nice to fix it here.

What do you think?

Thanks

simplified reproduction

On release of longpress here, onclick is triggered

 <button
      on:click={() =>  console.log(`Tool Clicked`)}
      on:longpress={() => console.log(`Context Menu Triggered`); }
      use:longpress
      class="tool-icon"
    >
	ToolA
</button>
@melMass
Copy link
Author

melMass commented Jan 25, 2024

For completeness here is my version:

import type { Action } from "svelte/action";

interface Attributes {
  "on:long"?: (event: CustomEvent) => void;
  "on:long_released"?: (event: CustomEvent) => void;
}

export const longpress: Action<HTMLElement, number | undefined, Attributes> = (
  node: HTMLElement,
  ms = undefined
) => {
  const defaultMS = 500;
  ms = ms || defaultMS;
  let timeoutPtr: number;
  function handleMouseDown(e: MouseEvent) {
    e.stopImmediatePropagation();

    timeoutPtr = window.setTimeout(() => {
      node.dispatchEvent(new CustomEvent("long"));
    }, ms);
  }

  function handleMouseUp() {
    node.dispatchEvent(new CustomEvent("long_released"));
    window.clearTimeout(timeoutPtr);
  }
  node.addEventListener("mousedown", handleMouseDown);
  node.addEventListener("mouseup", handleMouseUp);

  return {
    update(newMs: number | undefined) {
      window.clearTimeout(timeoutPtr);
      ms = newMs || defaultMS;
    },
    destroy: () => {
      window.clearTimeout(timeoutPtr);
      node.removeEventListener("mousedown", handleMouseDown);
      node.removeEventListener("mouseup", handleMouseUp);
    },
  };
};

@techniq
Copy link
Owner

techniq commented Jan 26, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants