Merge branch 'master' into patch_123
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Jason Miller · committed by GitHub · parents ec9122b, f0f36b0 · Browse files · 8 files·+168 added−68 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+168 added−68 removed
- tests:+72 added−26 removed
- other:+96 added−42 removed
Provenance
- Commit
53eb689- Tree
7d22727- Author
Jason Miller <developit@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
ec9122b- Parent 2
f0f36b0
8 files changed+168 added−68 removed
modified:src/index.ts+54 added-28 removed
12345656789101191012131415131617181920151621222318192425262122272829242530313233343536373833394041424344454647483 unmodified lines52535455455657585949506061626353646566676869596061707172737464657576777879804 unmodified lines8586878878899080919293949596868788979899100101102103104105106107108109110111112113114115116117export type EventType = string | symbol;
// An event handler can take an optional event argument// and should not return a valueexport type Handler<T = any> = (event?: T) => void;export type WildcardHandler = (type: EventType, event?: any) => void;export type Handler<T = unknown> = (event: T) => void;export type WildcardHandler<T = Record<string, unknown>> = ( type: keyof T, event: T[keyof T]) => void;
// An array of all currently registered event handlers for a typeexport type EventHandlerList = Array<Handler>;export type WildCardEventHandlerList = Array<WildcardHandler>;export type EventHandlerList<T = unknown> = Array<Handler<T>>;export type WildCardEventHandlerList<T = Record<string, unknown>> = Array<WildcardHandler<T>>;
// A map of event types and their corresponding event handlers.export type EventHandlerMap = Map<EventType, EventHandlerList | WildCardEventHandlerList>;export type EventHandlerMap<Events extends Record<EventType, unknown>> = Map< keyof Events | '*', EventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>>;
export interface Emitter { all: EventHandlerMap;export interface Emitter<Events extends Record<EventType, unknown>> { all: EventHandlerMap<Events>;
on<T = any>(type: EventType, handler: Handler<T>): void; on(type: '*', handler: WildcardHandler): void; on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void; on(type: '*', handler: WildcardHandler<Events>): void;
off<T = any>(type: EventType, handler?: Handler<T>): void; off(type: '*', handler: WildcardHandler): void; off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void; off(type: '*', handler: WildcardHandler<Events>): void;
emit<T = any>(type: EventType, event?: T): void; emit(type: '*', event?: any): void; emit<Key extends keyof Events>(type: Key, event: Events[Key]): void; emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;}
/** * Mitt: Tiny (~200b) functional event emitter / pubsub. * @name mitt * @returns {Mitt} */export default function mitt(all?: EventHandlerMap): Emitter {export default function mitt<Events extends Record<EventType, unknown>>( all?: EventHandlerMap<Events>): Emitter<Events> { type GenericEventHandler = | Handler<Events[keyof Events]> | WildcardHandler<Events>; all = all || new Map();
return {
3 unmodified lines all,
/** * Register an event handler for the given type. * @param {string|symbol} type Type of event to listen for, or `"*"` for all events * @param {string|symbol} type Type of event to listen for, or `'*'` for all events * @param {Function} handler Function to call in response to given event * @memberOf mitt */ on<T = any>(type: EventType, handler: Handler<T>) { const handlers = all.get(type); on<Key extends keyof Events>(type: Key, handler: GenericEventHandler) { const handlers: Array<GenericEventHandler> | undefined = all!.get(type); const added = handlers && handlers.push(handler); if (!added) { all.set(type, [handler]); all!.set(type, [handler] as EventHandlerList<Events[keyof Events]>); } },
/** * Remove an event handler for the given type. * If omit the `handler`, all event handlers of the given type are deleted. * @param {string|symbol} type Type of event to unregister `handler` from, or `"*"` * @param {Function} handler Handler function to remove * If `handler` is omitted, all handlers of the given type are removed. * @param {string|symbol} type Type of event to unregister `handler` from, or `'*'` * @param {Function} [handler] Handler function to remove * @memberOf mitt */ off<T = any>(type: EventType, handler?: Handler<T>) { const handlers = all.get(type); off<Key extends keyof Events>(type: Key, handler?: GenericEventHandler) { const handlers: Array<GenericEventHandler> | undefined = all!.get(type); if (handlers) { if (handler) { handlers.splice(handlers.indexOf(handler) >>> 0, 1); }4 unmodified lines },
/** * Invoke all handlers for the given type. * If present, `"*"` handlers are invoked after type-matched handlers. * If present, `'*'` handlers are invoked after type-matched handlers. * * Note: Manually firing "*" handlers is not supported. * Note: Manually firing '*' handlers is not supported. * * @param {string|symbol} type The event type to invoke * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler * @memberOf mitt */ emit<T = any>(type: EventType, evt: T) { ((all.get(type) || []) as EventHandlerList).slice().map((handler) => { handler(evt); }); ((all.get('*') || []) as WildCardEventHandlerList).slice().map((handler) => { handler(type, evt); }); emit<Key extends keyof Events>(type: Key, evt?: Events[Key]) { let handlers = all!.get(type); if (handlers) { (handlers as EventHandlerList<Events[keyof Events]>) .slice() .map((handler) => { handler(evt!); }); }
handlers = all!.get('*'); if (handlers) { (handlers as WildCardEventHandlerList<Events>) .slice() .map((handler) => { handler(type, evt!); }); } } };}modified:test/index_test.ts+17 added-6 removed
1-import mitt, { Emitter } from '..';1+import mitt, { Emitter, EventHandlerMap } from '..';2 import chai, { expect } from 'chai';3 import { spy } from 'sinon';4 import sinonChai from 'sinon-chai';5 chai.use(sinonChai);8 unmodified lines14 const map = new Map();15 const a = spy();16 const b = spy();17 map.set('foo', [a, b]);18- const events = mitt(map);18+ const events = mitt<{ foo: undefined }>(map);19 events.emit('foo');20 expect(a).to.have.been.calledOnce;21 expect(b).to.have.been.calledOnce;22 });23 });24 25 describe('mitt#', () => {26- let events, inst: Emitter;26+ const eventType = Symbol('eventType');27+ type Events = {28+ foo: unknown;29+ constructor: unknown;30+ FOO: unknown;31+ bar: unknown;32+ Bar: unknown;33+ 'baz:bat!': unknown;34+ 'baz:baT!': unknown;35+ Foo: unknown;36+ [eventType]: unknown;37+ };38+ let events: EventHandlerMap<Events>, inst: Emitter<Events>;39 28- beforeEach( () => {40+ beforeEach(() => {41 events = new Map();42 inst = mitt(events);43 });44 49 unmodified lines94 });95 96 it('can take symbols for event types', () => {97 const foo = () => {};86- const eventType = Symbol('eventType');98 inst.on(eventType, foo);99 expect(events.get(eventType)).to.deep.equal([foo]);100 });101 59 unmodified lines161 162 it('should invoke handler for type', () => {163 const event = { a: 'b' };164 154- inst.on('foo', (one, two?) => {165+ inst.on('foo', (one, two?: unknown) => {166 expect(one).to.deep.equal(event);167 expect(two).to.be.an('undefined');168 });169 32 unmodified linesmodified:test/test-types-compilation.ts+55 added-20 removed
12345567891011121314151617181920212282324251112262728293031151632333435363738394041204243442324454647484950272851525354555657585931603361626336373839404164656642676869707172737475767778/* eslint-disable @typescript-eslint/ban-ts-comment, @typescript-eslint/no-unused-vars */
import mitt from '..';
const emitter = mitt();interface SomeEventData { name: string;}
const emitter = mitt<{ foo: string; someEvent: SomeEventData; bar?: number;}>();
const barHandler = (x?: number) => {};const fooHandler = (x: string) => {};const wildcardHandler = ( _type: 'foo' | 'bar' | 'someEvent', _event: string | SomeEventData | number | undefined) => {};
/* * Check that if on is provided a generic, it only accepts handlers of that type * Check that 'on' args are inferred correctly */{ const badHandler = (x: number) => {}; const goodHandler = (x: string) => {}; // @ts-expect-error emitter.on('foo', barHandler); emitter.on('foo', fooHandler);
emitter.on('bar', barHandler); // @ts-expect-error emitter.on<string>('foo', badHandler); emitter.on<string>('foo', goodHandler); emitter.on('bar', fooHandler);
emitter.on('*', wildcardHandler); // fooHandler is ok, because ('foo' | 'bar' | 'someEvent') extends string emitter.on('*', fooHandler); // @ts-expect-error emitter.on('*', barHandler);}
/* * Check that if off is provided a generic, it only accepts handlers of that type * Check that 'off' args are inferred correctly */{ const badHandler = (x: number) => {}; const goodHandler = (x: string) => {}; // @ts-expect-error emitter.off('foo', barHandler); emitter.off('foo', fooHandler);
emitter.off('bar', barHandler); // @ts-expect-error emitter.off<string>('foo', badHandler); emitter.off<string>('foo', goodHandler); emitter.off('bar', fooHandler);
emitter.off('*', wildcardHandler); // fooHandler is ok, because ('foo' | 'bar' | 'someEvent') extends string emitter.off('*', fooHandler); // @ts-expect-error emitter.off('*', barHandler);}
/* * Check that if emitt is provided a generic, it only accepts event data of that type * Check that 'emit' args are inferred correctly */{ interface SomeEventData { name: string; } // @ts-expect-error emitter.emit<SomeEventData>('foo', 'NOT VALID'); emitter.emit<SomeEventData>('foo', { name: 'jack' }); // @ts-expect-error emitter.emit('someEvent', 'NOT VALID'); emitter.emit('someEvent', { name: 'jack' });}
// @ts-expect-error emitter.emit('foo'); // @ts-expect-error emitter.emit('foo', 1); emitter.emit('foo', 'string');
emitter.emit('bar'); emitter.emit('bar', 1); // @ts-expect-error emitter.emit('bar', 'string');}modified:.gitignore+1 added
4 unmodified lines5 /index.d.ts6 package-lock.json7 .DS_Store8 .idea9+.vscodeadded:LICENSE+21 added
1+MIT License2+3+Copyright (c) 2021 Jason Miller4+5+Permission is hereby granted, free of charge, to any person obtaining a copy6+of this software and associated documentation files (the "Software"), to deal7+in the Software without restriction, including without limitation the rights8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9+copies of the Software, and to permit persons to whom the Software is10+furnished to do so, subject to the following conditions:11+12+The above copyright notice and this permission notice shall be included in all13+copies or substantial portions of the Software.14+15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21+SOFTWARE.modified:package.json+5 added-5 removed
10 unmodified lines11 "typings": "index.d.ts",12 "scripts": {13 "test": "npm-run-all --silent typecheck lint mocha test-types",14 "mocha": "mocha test",15- "test-types": "tsc test/test-types-compilation.ts --noEmit",15+ "test-types": "tsc test/test-types-compilation.ts --noEmit --strict",16 "lint": "eslint src test --ext ts --ext js",17 "typecheck": "tsc --noEmit",18 "bundle": "microbundle",19 "build": "npm-run-all --silent clean -p bundle -s docs",13 unmodified lines33 "Jason Miller <jason@developit.ca>"34 ],35 "license": "MIT",36 "files": [37- "src",37 "dist",38 "index.d.ts"39 ],40 "mocha": {35 unmodified lines76 "jest/valid-expect": 0,77 "@typescript-eslint/no-explicit-any": 0,78 "@typescript-eslint/explicit-function-return-type": 0,79 "@typescript-eslint/explicit-module-boundary-types": 0,81- "@typescript-eslint/no-empty-function": 080+ "@typescript-eslint/no-empty-function": 0,81+ "@typescript-eslint/no-non-null-assertion": 082 }83 },84 "eslintIgnore": [85 "dist",17 unmodified lines103 "rimraf": "^3.0.2",104 "sinon": "^9.0.2",105 "sinon-chai": "^3.5.0",106 "ts-node": "^8.10.2",107- "typescript": "^3.9.3"107+ "typescript": "^3.9.7"108 }109-}109+}modified:README.md+13 added-5 removed
78 unmodified lines79 ```80 81 ### Typescript82 83+Set `"strict": true` in your tsconfig.json to get improved type inference for `mitt` instance methods.84+85 ```ts86 import mitt from 'mitt';87+88+type Events = {89+ foo: string90+ bar?: number91+}92+85-const emitter: mitt.Emitter = mitt();93+const emitter: mitt.Emitter<Events> = mitt<Events>();94 ```95 96 ## Examples & Demos97 35 unmodified lines133 Register an event handler for the given type.134 135 #### Parameters136 129-- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to listen for, or `"*"` for all events137+- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to listen for, or `'*'` for all events138 - `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Function to call in response to given event139 140 ### off141 1 unmodified line143 If omit the `handler`, all event handlers of the given type are deleted.144 145 #### Parameters146 139-- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to unregister `handler` from, or `"*"`147+- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to unregister `handler` from, or `'*'`148 - `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Handler function to remove149 150 ### emit151 152 Invoke all handlers for the given type.145-If present, `"*"` handlers are invoked after type-matched handlers.153+If present, `'*'` handlers are invoked after type-matched handlers.154 147-Note: Manually firing "\*" handlers is not supported.155+Note: Manually firing '\*' handlers is not supported.156 157 #### Parameters158 159 - `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** The event type to invoke29 unmodified linesmodified:tsconfig.json+2 added-4 removed
12345678991011121011{ "compileOnSave": false, "compilerOptions": { "strict": true, "noEmit": true, "declaration": true, "moduleResolution": "node", "esModuleInterop": true }, "include": [ "src/*.ts", "test/*.ts", ] "include": ["src/*.ts", "test/*.ts"]}