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!: Add support for custom isEqual #59

Merged
merged 9 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
20 changes: 10 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"react-dom": ">=16.0 <18.0",
"replicache": "^13.0.0",
"snowpack": "^3.8.8",
"typescript": "^4.4.3"
"typescript": "^5.2.2"
},
"files": [
"out/index.js",
Expand Down
171 changes: 165 additions & 6 deletions src/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import {expect} from '@esm-bundle/chai';
import {resolver} from '@rocicorp/resolver';
import React from 'react';
import {render} from 'react-dom';
import type {JSONValue} from 'replicache';
import type {JSONValue, ReadTransaction} from 'replicache';
import {Replicache, TEST_LICENSE_KEY, WriteTransaction} from 'replicache';
import {useSubscribe} from './index';
import {Subscribable, useSubscribe} from './index';

function sleep(ms: number | undefined): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
Expand All @@ -19,7 +19,7 @@ test('null/undefined replicache', async () => {
resolve();
return 'hello';
},
def,
{default: def},
);
return <div>{subResult}</div>;
}
Expand Down Expand Up @@ -77,7 +77,7 @@ test('Batching of subscriptions', async () => {
rep,
// TODO: Use type param to get when new Replicache is released.
async tx => (await tx.get('a')) as string | undefined,
null,
{default: null},
);
renderLog.push('render A', dataA);
return <B rep={rep} dataA={dataA} />;
Expand All @@ -87,7 +87,7 @@ test('Batching of subscriptions', async () => {
const dataB = useSubscribe(
rep,
async tx => (await tx.get('b')) as string | undefined,
null,
{default: null},
);
renderLog.push('render B', dataA, dataB);
return (
Expand Down Expand Up @@ -127,7 +127,7 @@ test('returning undefined', async () => {
resolve();
return undefined;
},
def,
{default: def},
);
return <div>{subResult}</div>;
}
Expand Down Expand Up @@ -204,3 +204,162 @@ test('changing subscribable instances', async () => {
await rep1.close();
await rep2.close();
});

test('using isEqual', async () => {
const {promise, resolve} = resolver();

const sentinel = Symbol();

class FakeReplicache implements Subscribable<ReadTransaction> {
subscribe<Data>(
query: (tx: ReadTransaction) => Promise<Data>,
{
onData,
isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b),
}: {
onData: (data: Data) => void;
isEqual?: ((a: Data, b: Data) => boolean) | undefined;
},
): () => void {
const data = query({} as ReadTransaction);
let previous: Data | typeof sentinel = sentinel;
void data.then(data => {
if (previous === sentinel || isEqual(previous, data)) {
previous = data;
return onData(data);
}
});

return () => undefined;
}
}

function A({
rep,
def,
}: {
rep: FakeReplicache | null | undefined;
def: string;
}) {
const subResult = useSubscribe(
rep,
async () => {
resolve();
return 123n;
},
{
isEqual(a, b) {
return a === b;
},
default: def,
},
);
return (
<div>
{typeof subResult}, {String(subResult)}
</div>
);
}

const div = document.createElement('div');

render(<A key="a" rep={null} def="a" />, div);
expect(div.textContent).to.equal('string, a');

render(<A key="b" rep={undefined} def="b" />, div);
expect(div.textContent).to.equal('string, b');

const rep = new FakeReplicache();

render(<A key="c" rep={rep} def="c" />, div);
expect(div.textContent).to.equal('string, c');
await promise;
await sleep(1);
expect(div.textContent).to.equal('bigint, 123');
});

test.skip('using isEqual [type checking]', async () => {
const use = (...args: unknown[]) => args;

// eslint-disable-next-line @typescript-eslint/no-unused-vars
function expectType<T>(_expression: T) {
// intentionally empty
}

class FakeReplicache<Tx> implements Subscribable<Tx> {
subscribe<Data>(
query: (tx: Tx) => Promise<Data>,
options: {
onData: (data: Data) => void;
isEqual?: ((a: Data, b: Data) => boolean) | undefined;
},
): () => void {
use(query, options);
return () => undefined;
}
}

{
const s = useSubscribe(
new FakeReplicache<ReadTransaction>(),
tx => {
use(tx);
return Promise.resolve(123n);
},
{isEqual: (a, b) => a === b},
);
expectType<bigint | undefined>(s);
}

{
// This is invalid because the return type is not json
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I realized this kind of advanced type checking could be put into replicache/reflect too.

I don't think it makes sense to have advanced type check here but not in replicache/reflect.

// @ts-expect-error index.ts(61, 3): An argument for 'options' was not provided.
const s = useSubscribe(new FakeReplicache<ReadTransaction>(), tx => {
use(tx);
return Promise.resolve(123n);
});
use(s);
}

{
// default not passed so it is undefined
const s = useSubscribe(new FakeReplicache<ReadTransaction>(), tx => {
use(tx);
return Promise.resolve(123);
});
expectType<123 | undefined>(s);
}

{
const s = useSubscribe(
new FakeReplicache<ReadTransaction>(),
tx => {
use(tx);
return Promise.resolve(true);
},
{default: 456},
);
expectType<boolean | number>(s);
}

{
const s: bigint | 'abc' = useSubscribe(
new FakeReplicache<ReadTransaction>(),
tx => {
use(tx);
return Promise.resolve(123n);
},
{isEqual: (a, b) => a === b, default: 'abc'},
);
expectType<bigint | 'abc'>(s);
}

{
// @ts-expect-error Type 'Promise<bigint>' is not assignable to type 'Promise<ReadonlyJSONValue>'.ts(2345)
const s = useSubscribe(new FakeReplicache<ReadTransaction>(), tx => {
use(tx);
return Promise.resolve(123n);
});
use(s);
}
});
57 changes: 44 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import {useEffect, useState} from 'react';
import {DependencyList, useEffect, useState} from 'react';
import {unstable_batchedUpdates} from 'react-dom';
import {ReadonlyJSONValue} from 'replicache';

export type Subscribable<Tx, Data> = {
subscribe: (
export type Subscribable<Tx> = {
subscribe<Data>(
query: (tx: Tx) => Promise<Data>,
{onData}: {onData: (data: Data) => void},
) => () => void;
options: {
onData: (data: Data) => void;
isEqual?: ((a: Data, b: Data) => boolean) | undefined;
},
): () => void;
};

// We wrap all the callbacks in a `unstable_batchedUpdates` call to ensure that
Expand All @@ -27,12 +31,38 @@ function doCallback() {

export type RemoveUndefined<T> = T extends undefined ? never : T;

export function useSubscribe<Tx, Data, QueryRet extends Data, Default>(
r: Subscribable<Tx, Data> | null | undefined,
export type UseSubscribeOptions<QueryRet, Default> = {
/** Default can already be undefined since it is an unbounded type parameter. */
default?: Default;
dependencies?: DependencyList | undefined;
isEqual?: ((a: QueryRet, b: QueryRet) => boolean) | undefined;
};

export type UseSubscribeOptionsNoIsEqual<QueryRet, Default> = Omit<
UseSubscribeOptions<QueryRet, Default>,
'isEqual'
>;

export function useSubscribe<Tx, QueryRet, Default = undefined>(
r: Subscribable<Tx> | null | undefined,
query: (tx: Tx) => Promise<QueryRet>,
options: UseSubscribeOptions<QueryRet, Default>,
): RemoveUndefined<QueryRet> | Default;
export function useSubscribe<Tx, QueryRet extends ReadonlyJSONValue, undefined>(
r: Subscribable<Tx> | null | undefined,
query: (tx: Tx) => Promise<QueryRet>,
): RemoveUndefined<QueryRet> | undefined;
export function useSubscribe<Tx, QueryRet extends ReadonlyJSONValue, Default>(
r: Subscribable<Tx> | null | undefined,
query: (tx: Tx) => Promise<QueryRet>,
options: UseSubscribeOptionsNoIsEqual<QueryRet, Default> | undefined,
): RemoveUndefined<QueryRet> | Default;
export function useSubscribe<Tx, QueryRet, Default>(
r: Subscribable<Tx> | null | undefined,
query: (tx: Tx) => Promise<QueryRet>,
def: Default,
deps: Array<unknown> = [],
) {
options: UseSubscribeOptions<QueryRet, Default> = {},
): RemoveUndefined<QueryRet> | Default {
const {default: def, dependencies = [], isEqual} = options;
const [snapshot, setSnapshot] = useState<QueryRet | undefined>(undefined);
useEffect(() => {
if (!r) {
Expand All @@ -43,12 +73,13 @@ export function useSubscribe<Tx, Data, QueryRet extends Data, Default>(
onData: data => {
// This is safe because we know that subscribe in fact can only return
// `R` (the return type of query or def).
callbacks.push(() => setSnapshot(data as QueryRet));
callbacks.push(() => setSnapshot(data));
if (!hasPendingCallback) {
void Promise.resolve().then(doCallback);
hasPendingCallback = true;
}
},
isEqual,
});

return () => {
Expand All @@ -61,9 +92,9 @@ export function useSubscribe<Tx, Data, QueryRet extends Data, Default>(
// Also note that if this ever changes, it's a breaking change and should
// be documented, as if callers pass an object/array/func literal, changing
// this will cause a render loop that would be hard to debug.
}, [r, ...deps]);
}, [r, ...dependencies]);
if (snapshot === undefined) {
return def;
return def as Default;
}
// This RemoveUndefined is just here to make the return type easier to read.
// It should be exactly equivalent to what the type would be without this.
Expand Down
7 changes: 3 additions & 4 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"jsx": "react",
"target": "ES2018",
"target": "ES2020",
"isolatedModules": true,

"strict": true,
Expand All @@ -11,13 +11,12 @@
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,

"importsNotUsedAsValues": "error",

"declaration": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"allowJs": true,
"lib": ["dom", "esnext"]
"lib": ["dom", "esnext"],
"skipLibCheck": true
},
"include": ["src/**/*.ts", "src/**/*.tsx"],
"exclude": ["node_modules", "dist/**/*", "build/**/*"]
Expand Down