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

feat: implement plugable map combined with event emitter #403

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"@file-services/types": "^7.2.5",
"@types/chai": "^4.3.5",
"@types/chai-as-promised": "^7.1.5",
"@types/react": "^17.0.39",
"@types/glob": "^8.1.0",
"@types/make-fetch-happen": "^10.0.1",
"@types/mocha": "^10.0.1",
Expand Down
21 changes: 21 additions & 0 deletions packages/plugable/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Wix.com

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.
295 changes: 295 additions & 0 deletions packages/plugable/README.md

Large diffs are not rendered by default.

24 changes: 24 additions & 0 deletions packages/plugable/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "@wixc3/plugable",
"version": "1.0.1",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"scripts": {
"test": "mocha \"dist/cjs/test/**/*.unit.js\""
},
"peerDependencies": {
"react": "^17.0.2"
},
"files": [
"dist",
"src",
"!dist/test",
"!dist/tsconfig.tsbuildinfo"
],
"license": "MIT",
"author": "Wix.com",
"repository": "[email protected]:wixplosives/core3-utils.git",
"publishConfig": {
"access": "public"
}
}
1 change: 1 addition & 0 deletions packages/plugable/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './plugable';
24 changes: 24 additions & 0 deletions packages/plugable/src/plugable-react.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { createContext, useContext, useEffect, useState } from 'react';
import type { Plugable, Key } from './types';
import { on, get } from './plugable';

export const PlugableContext = createContext<Plugable | undefined>(undefined);

export function usePlugable() {
const plugable = useContext(PlugableContext);
if (!plugable) {
throw new Error('PlugableContext is not initialized');
}
return plugable;
}

function toggle(v: boolean) {
return !v;
}

export function usePlugableValue<T>(key: Key<T>): T | undefined {
const [_, setState] = useState(true);
const map = usePlugable();
useEffect(() => on(map, key, () => setState(toggle)), [key]);
return get(map, key);
}
101 changes: 101 additions & 0 deletions packages/plugable/src/plugable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { type Plugable, type Key, internals, PlugableInternals, Val, PlugableApi } from './types';

const proto: PlugableApi = {
createKey<V extends NonNullable<unknown> = never>(debugName?: string): Key<V> {
return createKey(debugName);
},
getThrow<Value>(this: Plugable, key: Key<Value>): Value {
return getThrow(this, key);
},
get<Value>(this: Plugable, key: Key<Value>): Value | undefined {
return get(this, key);
},
set<Value>(
this: Plugable,
key: Key<Value>,
value: Value,
isEqual?: (previous: Value | undefined, value: Value) => boolean
) {
set(this, key, value, isEqual);
},
on<K extends Key>(this: Plugable, key: K, listener: (value: Val<K>) => void) {
return on(this, key, listener);
},
};

export function createPlugable(): Plugable {
const rec = Object.create(proto) as Plugable;
rec[internals] = {
parent: undefined,
listeners: new Map(),
handlerToRec: new WeakMap(),
};
return rec;
}

export function inheritPlugable(rec: Plugable): Plugable {
const inherited = Object.create(rec) as Plugable;
inherited[internals] = Object.create(rec[internals]) as PlugableInternals;
inherited[internals].parent = rec;
return inherited;
}

export function createKey<V extends NonNullable<unknown> = never>(debugName?: string): Key<V> {
return Symbol(debugName) as Key<V>;
}

export function getThrow<Value>(rec: Plugable, key: Key<Value>): Value {
barak007 marked this conversation as resolved.
Show resolved Hide resolved
const value = get(rec, key);
if (value === undefined || value === null) {
throw new Error(`missing value for key ${String(key)}`);
}
return value;
}

export function get<Value>(rec: Plugable, key: Key<Value>): Value | undefined {
return (rec as Record<Key<Value>, Value>)[key];
}

export function set<Value>(rec: Plugable, key: Key<Value>, value: Value, isEqual = tripleEqual<Value>): void {
if (!isEqual(get(rec, key), value)) {
(rec as Record<Key<Value>, Value>)[key] = value;
dispatch(rec, key, value);
}
}

export function on<K extends Key>(rec: Plugable, key: K, listener: (value: Val<K>) => void): () => void {
const { listeners, handlerToRec } = rec[internals];
let handlers = listeners.get(key);
if (!handlers) {
handlers = new Set();
listeners.set(key, handlers);
}
handlers.add(listener);
handlerToRec.set(listener, rec);
return () => {
handlers?.delete(listener);
};
}

function tripleEqual<T>(previous: T | undefined, value: T): boolean {
return previous === value;
}

function dispatch<T>(rec: Plugable, key: Key<T>, value: T): void {
const { listeners, handlerToRec } = rec[internals];
listeners.get(key)?.forEach((listener) => shouldDispatch(rec, handlerToRec.get(listener), key) && listener(value));
}

function hasOwn(obj: unknown, key: string | symbol): boolean {
return Object.prototype.hasOwnProperty.call(obj, key);
}

function shouldDispatch(dispatcherRec: Plugable, handlerRec: Plugable | undefined, key: string | symbol): boolean {
if (dispatcherRec === handlerRec) {
return true;
} else if (handlerRec && !hasOwn(handlerRec, key)) {
return shouldDispatch(dispatcherRec, handlerRec[internals].parent, key);
} else {
return false;
}
}
177 changes: 177 additions & 0 deletions packages/plugable/src/test/test.unit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import { createPlugable, createKey, inheritPlugable, set, get, on, getThrow } from '../plugable';
chai.use(chaiAsPromised);

describe('Plugable', () => {
it('set and get', () => {
const rec = createPlugable();
const key = createKey<string>();

set(rec, key, 'hello');
expect(get(rec, key)).to.equal('hello');
});

it('getThrow', () => {
const rec = createPlugable();
const key = createKey<string>();

expect(() => {
getThrow(rec, key);
}).to.throw(`missing value for key`);

set(rec, key, 'hello');
expect(get(rec, key)).to.equal('hello');
});

it('emit on set', () => {
const rec = createPlugable();
const key = createKey<string>();
const res = new Array<string>();

on(rec, key, res.push.bind(res));
set(rec, key, 'hello');

expect(res[0]).to.equal('hello');
});

it('same value does not trigger event', () => {
const rec = createPlugable();
const key = createKey<string>();
const res = new Array<string>();

on(rec, key, res.push.bind(res));
set(rec, key, 'hello');
set(rec, key, 'hello');
expect(res[0]).to.equal('hello');
expect(res).to.have.length(1);
});

it('remove listener', () => {
const rec = createPlugable();
const key = createKey<string>();
const res = new Array<string>();

const off = on(rec, key, res.push.bind(res));
set(rec, key, 'hello');
off();
set(rec, key, 'world');
expect(res).to.have.length(1);
});

it('multiple listeners', () => {
const rec = createPlugable();
const key = createKey<string>();
const resA = new Array<string>();
const resB = new Array<string>();

const offA = on(rec, key, resA.push.bind(resA));
const offB = on(rec, key, resB.push.bind(resB));
set(rec, key, 'hello');
offA();
set(rec, key, 'world');

expect(resA).to.have.length(1);
expect(resB).to.have.length(2);

offB();

set(rec, key, 'goodbye');

expect(resA).to.have.length(1);
expect(resB).to.have.length(2);
});

it('emit on child when set', () => {
const parent = createPlugable();
const child = inheritPlugable(parent);
const key = createKey<string>();
const res = new Array<string>();

on(child, key, res.push.bind(res));
set(child, key, 'hello');

expect(res[0]).to.equal('hello');
});

it('child does not affect parent', () => {
const parent = createPlugable();
const child = inheritPlugable(parent);
const key = createKey<string>();
const res = new Array<string>();

on(parent, key, res.push.bind(res));
set(child, key, 'hello');

expect(res).to.eql([]);
expect(get(parent, key)).to.equal(undefined);
});

it('emit on child when set on parent (no child override)', () => {
const parent = createPlugable();
const child = inheritPlugable(parent);
const key = createKey<string>();
const res = new Array<string>();

on(child, key, res.push.bind(res));
set(parent, key, 'hello');

expect(res[0]).to.equal('hello');
});

it('no emit on child when set on parent (when there is override)', () => {
const parent = createPlugable();
const child = inheritPlugable(parent);
const key = createKey<string>();
const res = new Array<string>();

set(child, key, 'world');
on(child, key, res.push.bind(res));
set(parent, key, 'hello');

expect(res).to.be.empty;
});

it('no emit on grandChild when set on parent (when there is override on child)', () => {
const parent = createPlugable();
const child = inheritPlugable(parent);
const grandChild = inheritPlugable(child);
const key = createKey<string>();
const res = new Array<string>();

set(child, key, 'world');
on(grandChild, key, res.push.bind(res));
set(parent, key, 'hello');

expect(res).to.be.empty;

const value = get(grandChild, key);
expect(value).to.equal('world');
});

it('emit on grandChild when set on parent (when there is no override on child)', () => {
const parent = createPlugable();
const child = inheritPlugable(parent);
const grandChild = inheritPlugable(child);
const key = createKey<string>();
const res = new Array<string>();

on(grandChild, key, res.push.bind(res));
set(parent, key, 'hello');

expect(res[0]).to.equal('hello');
});
Copy link
Contributor

Choose a reason for hiding this comment

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

missing tests:

  • inherited record doesn't effect the origin
  • call return value of on() to stop listening
  • listen with multiple listeners (check that removing 1 doesn't change the others)

});

describe('Plugable (prototype api)', () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

what is this test for? seems like you test the API in the previous tests.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This is related all the other tests checking the non prototype api.
at this point I'm not sure which one is preferred WDYT?

it('set and get and on', () => {
const rec = createPlugable();
const key = createKey<string>();
const res = new Array<string>();

rec.on(key, res.push.bind(res));
rec.set(key, 'hello');
expect(rec.get(key)).to.equal('hello');
expect(res[0]).to.equal('hello');
});
});
9 changes: 9 additions & 0 deletions packages/plugable/src/tsconfig.esm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../dist/esm",
"module": "esnext",
"types": ["mocha"]
},
"references": []
}
8 changes: 8 additions & 0 deletions packages/plugable/src/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"outDir": "../dist/cjs",
"types": ["mocha"]
},
"references": []
}
Loading