Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@solid-primitives/event-listener

Package Overview
Dependencies
Maintainers
2
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@solid-primitives/event-listener - npm Package Compare versions

Comparing version 1.3.6 to 1.3.7

177

dist/index.d.ts

@@ -1,18 +0,19 @@

import { Accessor, JSX } from 'solid-js';
import { Fn, MaybeAccessor, Many } from '@solid-primitives/utils';
import { JSX, Accessor, Component } from 'solid-js';
import { Store } from 'solid-js/store';
declare type EventMapOf<T> = T extends Window ? WindowEventMap : T extends Document ? DocumentEventMap : T extends HTMLElement ? HTMLElementEventMap : T extends MediaQueryList ? MediaQueryListEventMap : {};
declare type EventMapOfMultiple<T> = T extends EventTarget ? EventMapOf<T> : T extends EventTarget[] ? EventMapOf<T[number]> : never;
declare type EventListenerProps<T extends EventTarget | EventTarget[], E extends Record<string, Event> = {}> = [
name: [{}, {}] extends [EventMapOfMultiple<T>, E] ? string : string & (keyof EventMapOfMultiple<T> | keyof E),
handler: EventListenerOrEventListenerObject | null,
options?: AddEventListenerOptions
declare type ClearListeners = Fn;
declare type TargetWithEventMap = Window | Document | HTMLElement | MediaQueryList;
declare type EventMapOf<Target> = Target extends Window ? WindowEventMap : Target extends Document ? DocumentEventMap : Target extends HTMLElement ? HTMLElementEventMap : Target extends MediaQueryList ? MediaQueryListEventMap : never;
declare type EventListenerDirectiveProps = [
name: string,
handler: (e: any) => void,
options?: AddEventListenerOptions | boolean
];
declare type CreateEventListenerReturn = [
add: (el: EventTarget) => void,
remove: (el: EventTarget) => void
];
declare type EventListenerMapDirectiveProps = [handlerMap: Record<string, (e: any) => void>, options?: AddEventListenerOptions | boolean] | Record<string, (e: any) => void>;
declare module "solid-js" {
namespace JSX {
interface Directives {
createEventListener: (ref: HTMLElement, props: Accessor<EventListenerProps<HTMLElement, {}>>) => [add: (target: EventTarget) => void, remove: (target: EventTarget) => void];
eventListener: EventListenerDirectiveProps;
eventListenerMap: EventListenerMapDirectiveProps;
}

@@ -22,26 +23,142 @@ }

declare type E = JSX.Element;
declare type CreateEventListenerFn = <EventMap extends Record<string, Event>, Target extends EventTarget | EventTarget[]>(target: Target, ...props: [Accessor<EventListenerProps<Target, EventMap>>] | EventListenerProps<Target, EventMap>) => CreateEventListenerReturn;
declare type EventListenerSignalReturns<Event> = [
lastEvent: Accessor<Event | undefined>,
clear: ClearListeners
];
/**
* Creates an event listener helper primitive.
* Creates an event listener, that will be automatically disposed on cleanup.
*
* @param target - ref to HTMLElement, EventTarget or Array thereof
* @param nameOrProps - name of the event or Accessor with the event props ([name, handler, options?])
* @param handler - if nameOrProps contains a name, you can specify the handler here
* @param options - if nameOrProps contains a name, you can specify event listener options
* @param eventName - name of the handled event
* @param handler - event handler
* @param options - addEventListener options
*
* @returns Function clearing all event listeners form targets
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
* @see https://github.com/davedbase/solid-primitives/tree/main/packages/event-listener#createEventListener
*
* @example
* ```tsx
* const [add, remove] = createEventListener(
* document.getElementById("mybutton"),
* "mouseDown",
* () => console.log("Click")
* );
* // or as a directive
* <MyButton use:createEventListener={() => ['click', () => console.log("Click")]}>Click!</MyButton>
* // you can provide your own event map type:
* createEventListener<{ myCustomEvent: Event }, Window>(window, 'myCustomEvent', () => console.log("yup!"));
* ```
* const clear = createEventListener(element, 'click', e => { ... }, { passive: true })
*/
declare const createEventListener: CreateEventListenerFn;
declare function createEventListener<Target extends TargetWithEventMap, EventMap extends EventMapOf<Target>, EventName extends keyof EventMap>(target: MaybeAccessor<Many<Target>>, eventName: MaybeAccessor<EventName>, handler: (event: EventMap[EventName]) => void, options?: MaybeAccessor<boolean | AddEventListenerOptions>): ClearListeners;
declare function createEventListener<EventMap extends Record<string, Event>, EventName extends keyof EventMap = keyof EventMap>(target: MaybeAccessor<Many<EventTarget>>, eventName: MaybeAccessor<EventName>, handler: (event: EventMap[EventName]) => void, options?: MaybeAccessor<boolean | AddEventListenerOptions>): ClearListeners;
/**
* Provides an reactive signal of last captured event.
*
* @param target - ref to HTMLElement, EventTarget or Array thereof
* @param eventName - name of the handled event
* @param options - addEventListener options
*
* @returns Signal of last captured event & function clearing all event listeners
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
* @see https://github.com/davedbase/solid-primitives/tree/main/packages/event-listener#createEventSignal
*
* @example
* const lastEvent = createEventSignal(el, 'click', { passive: true })
*
* createEffect(() => {
* console.log(lastEvent())
* })
*/
declare function createEventSignal<Target extends TargetWithEventMap, EventMap extends EventMapOf<Target>, EventName extends keyof EventMap>(target: MaybeAccessor<Many<Target>>, eventName: MaybeAccessor<EventName>, options?: MaybeAccessor<boolean | AddEventListenerOptions>): EventListenerSignalReturns<EventMap[EventName]>;
declare function createEventSignal<EventMap extends Record<string, Event>, EventName extends keyof EventMap = keyof EventMap>(target: MaybeAccessor<Many<EventTarget>>, eventName: MaybeAccessor<EventName>, options?: MaybeAccessor<boolean | AddEventListenerOptions>): EventListenerSignalReturns<EventMap[EventName]>;
/**
* Directive Usage. Creates an event listener, that will be automatically disposed on cleanup.
*
* @param props [eventName, eventHandler, options]
*
* @example
* <button use:eventListener={["click", () => {...}]}>Click me!</button>
*/
declare function eventListener(target: Element, props: Accessor<EventListenerDirectiveProps>): void;
export { CreateEventListenerReturn, E, EventListenerProps, EventMapOf, EventMapOfMultiple, createEventListener, createEventListener as default };
declare type EventHandlersMap<EventMap> = {
[EventName in keyof EventMap]: (event: EventMap[EventName]) => void;
};
declare type EventListnenerStoreReturns<E> = [lastEvents: Store<Partial<E>>, clear: ClearListeners];
/**
* A helpful primitive that listens to a map of events. Handle them by individual callbacks.
*
* @param target accessor or variable of multiple or single event targets
* @param handlersMap e.g. `{ mousemove: e => {}, click: e => {} }`
* @param options e.g. `{ passive: true }`
*
* @returns Function clearing all event listeners form targets
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
* @see https://github.com/davedbase/solid-primitives/tree/main/packages/event-listener#createEventListenerMap
*
* @example
* const clear = createEventListenerMap(element, {
* mousemove: mouseHandler,
* mouseenter: e => {},
* touchend: touchHandler
* });
*/
declare function createEventListenerMap<EventMap extends Record<string, Event>, UsedEvents extends keyof EventMap = keyof EventMap>(target: MaybeAccessor<Many<EventTarget>>, handlersMap: Partial<Pick<EventHandlersMap<EventMap>, UsedEvents>>, options?: MaybeAccessor<boolean | AddEventListenerOptions>): ClearListeners;
declare function createEventListenerMap<Target extends TargetWithEventMap, EventMap extends EventMapOf<Target>, HandlersMap extends Partial<EventHandlersMap<EventMap>>>(target: MaybeAccessor<Many<Target>>, handlersMap: HandlersMap, options?: MaybeAccessor<boolean | AddEventListenerOptions>): ClearListeners;
/**
* A helpful primitive that listens to target events and provides a reactive store with the latest captured events.
*
* @param target accessor or variable of multiple or single event targets
* @param options e.g. `{ passive: true }` *(can be omited)*
* @param eventNames names of events you want to listen to, e.g. `"mousemove", "touchend", "click"`
*
* @returns reactive store with the latest captured events & clear function
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
* @see https://github.com/davedbase/solid-primitives/tree/main/packages/event-listener#createEventStore
*
* @example
* const [lastEvents, clear] = createEventStore(el, "mousemove", "touchend", "click");
*
* createEffect(() => {
* console.log(lastEvents.mousemove.x)
* })
*/
declare function createEventStore<Target extends TargetWithEventMap, EventMap extends EventMapOf<Target>, UsedEvents extends keyof EventMap>(target: MaybeAccessor<Many<Target>>, ...eventNames: UsedEvents[]): EventListnenerStoreReturns<Pick<EventMap, UsedEvents>>;
declare function createEventStore<Target extends TargetWithEventMap, EventMap extends EventMapOf<Target>, UsedEvents extends keyof EventMap>(target: MaybeAccessor<Many<Target>>, options: MaybeAccessor<boolean | AddEventListenerOptions>, ...eventNames: UsedEvents[]): EventListnenerStoreReturns<Pick<EventMap, UsedEvents>>;
declare function createEventStore<EventMap extends Record<string, Event>, UsedEvents extends keyof EventMap = keyof EventMap>(target: MaybeAccessor<Many<EventTarget>>, ...eventNames: UsedEvents[]): EventListnenerStoreReturns<Pick<EventMap, UsedEvents>>;
declare function createEventStore<EventMap extends Record<string, Event>, UsedEvents extends keyof EventMap = keyof EventMap>(target: MaybeAccessor<Many<EventTarget>>, options: MaybeAccessor<boolean | AddEventListenerOptions>, ...eventNames: UsedEvents[]): EventListnenerStoreReturns<Pick<EventMap, UsedEvents>>;
/**
* Directive Usage. A helpful primitive that listens to provided events. Handle them by callbacks.
*
* @param props [handlerMap, options] | handlerMap
* - **handlerMap**: e.g. `{ mousemove: e => {}, click: e => {} }`
* - **options** e.g. `{ passive: true }`
*
* @example
* <div use:eventListenerMap={{
* mousemove: e => {},
* click: clickHandler,
* touchstart: () => {}
* }}></div>
*/
declare function eventListenerMap(target: Element, getProps: Accessor<EventListenerMapDirectiveProps>): void;
declare type EventAttributes<T> = {
[K in keyof JSX.DOMAttributes<T>]: `${K}` extends `on${string}` ? JSX.DOMAttributes<T>[K] : never;
};
/**
* Listen to the `window` DOM Events, using a component.
*
* @see https://github.com/davedbase/solid-primitives/tree/main/packages/event-listener#WindowEventListener
*
* @example
* <WindowEventListener onMouseMove={e => console.log(e.x, e.y)} />
*/
declare const WindowEventListener: Component<EventAttributes<null>>;
/**
* Listen to the `document` DOM Events, using a component.
*
* @see https://github.com/davedbase/solid-primitives/tree/main/packages/event-listener#DocumentEventListener
*
* @example
* <DocumentEventListener onMouseMove={e => console.log(e.x, e.y)} />
*/
declare const DocumentEventListener: Component<EventAttributes<null>>;
export { ClearListeners, DocumentEventListener, E, EventHandlersMap, EventListenerDirectiveProps, EventListenerMapDirectiveProps, EventListenerSignalReturns, EventListnenerStoreReturns, EventMapOf, TargetWithEventMap, WindowEventListener, createEventListener, createEventListenerMap, createEventSignal, createEventStore, eventListener, eventListenerMap };

@@ -1,35 +0,127 @@

// src/index.ts
// src/eventListener.ts
import {
access,
createCallbackStack,
isClient,
forEach
} from "@solid-primitives/utils";
import { createSignal } from "solid-js";
import { createEffect, onCleanup } from "solid-js";
var createEventListener = (target, ...propsArray) => {
const targets = Array.isArray(target) ? target : [target];
const props = typeof propsArray[0] === "function" ? propsArray[0] : () => propsArray;
const add = (target2) => {
targets.includes(target2) || targets.push(target2);
const [name, handler, options] = props();
if (name && handler !== void 0) {
target2.addEventListener.apply(target2, props());
}
};
const remove = (target2) => {
targets.forEach((t, index) => t === target2 && targets.splice(index, 1));
target2.removeEventListener.apply(target2, props());
};
targets.forEach(add);
createEffect((previousProps) => {
const currentProps = props();
if (previousProps !== currentProps) {
previousProps && targets.forEach((target2) => target2.removeEventListener.apply(target2, previousProps));
targets.forEach(add);
}
return currentProps;
}, props());
onCleanup(() => {
targets.forEach(remove);
function createEventListener(targets, eventName, handler, options) {
if (!isClient)
return () => {
};
const toCleanup = createCallbackStack();
createEffect(() => {
toCleanup.execute();
const _eventName = access(eventName);
const _options = access(options);
forEach(targets, (el) => {
if (!el)
return;
el.addEventListener(_eventName, handler, _options);
toCleanup.push(() => el.removeEventListener(_eventName, handler, _options));
});
});
return [add, remove];
onCleanup(toCleanup.execute);
return toCleanup.execute;
}
function createEventSignal(target, eventName, options) {
const [lastEvent, setLastEvent] = createSignal();
const clear = createEventListener(target, eventName, setLastEvent, options);
return [lastEvent, clear];
}
function eventListener(target, props) {
const toCleanup = createCallbackStack();
createEffect(() => {
toCleanup.execute();
const [eventName, handler, options] = props();
target.addEventListener(eventName, handler, options);
toCleanup.push(() => target.removeEventListener(eventName, handler, options));
});
onCleanup(toCleanup.execute);
}
// src/eventListenerMap.ts
import { entries, createCallbackStack as createCallbackStack2 } from "@solid-primitives/utils";
import { createEffect as createEffect2, createSignal as createSignal2, onCleanup as onCleanup2 } from "solid-js";
function createEventListenerMap(targets, handlersMap, options) {
const { push, execute } = createCallbackStack2();
entries(handlersMap).forEach(([eventName, handler]) => {
push(createEventListener(targets, eventName, (e) => handler == null ? void 0 : handler(e), options));
});
return execute;
}
function createEventStore(targets, ...rest) {
let options = void 0;
let names;
if (typeof rest[0] === "string")
names = rest;
else {
const [_options, ..._events] = rest;
options = _options;
names = _events;
}
const store = {};
const { push, execute } = createCallbackStack2();
names.forEach((eventName) => {
const [accessor, setter] = createSignal2();
Object.defineProperty(store, eventName, { get: accessor, set: setter, enumerable: true });
push(createEventListener(targets, eventName, setter, options));
});
return [store, execute];
}
function eventListenerMap(target, getProps) {
const toCleanup = createCallbackStack2();
createEffect2(() => {
toCleanup.execute();
let handlersMap;
let options;
const props = getProps();
if (Array.isArray(props)) {
handlersMap = props[0];
options = props[1];
} else
handlersMap = props;
entries(handlersMap).forEach(([eventName, handler]) => {
target.addEventListener(eventName, handler, options);
toCleanup.push(() => target.removeEventListener(eventName, handler, options));
});
});
onCleanup2(toCleanup.execute);
}
// src/components.ts
import { isClient as isClient2 } from "@solid-primitives/utils";
var forEachEventAttr = (props, fn) => {
Object.keys(props).forEach((attr) => {
if (!attr.startsWith("on"))
return;
const eventName = attr.substring(2).toLowerCase();
fn(eventName, attr);
});
};
var src_default = createEventListener;
var WindowEventListener = (props) => {
if (isClient2)
forEachEventAttr(props, (eventName, attr) => {
createEventListener(window, eventName, (e) => props[attr](e));
});
return void 0;
};
var DocumentEventListener = (props) => {
if (isClient2)
forEachEventAttr(props, (eventName, attr) => {
createEventListener(document, eventName, (e) => props[attr](e));
});
return void 0;
};
export {
DocumentEventListener,
WindowEventListener,
createEventListener,
src_default as default
createEventListenerMap,
createEventSignal,
createEventStore,
eventListener,
eventListenerMap
};

2

package.json
{
"name": "@solid-primitives/event-listener",
"version": "1.3.6",
"version": "1.3.7",
"description": "Primitive to manage creating event listeners.",

@@ -5,0 +5,0 @@ "author": "David Di Biase <dave.dibiase@gmail.com>",

@@ -334,2 +334,6 @@ # @solid-primitives/event-listener

1.3.7
Published recent major updates to latest tag.
</details>

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc