Skip to content
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
8 changes: 8 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@
"require": "./internal/analytics-metadata/utils.js",
"default": "./mjs/internal/analytics-metadata/utils.js"
},
"./internal/table-role": {
"require": "./internal/table-role/index.js",
"default": "./mjs/internal/table-role/index.js"
},
"./internal/async-store": {
"require": "./internal/async-store/index.js",
"default": "./mjs/internal/async-store/index.js"
},
"./package.json": "./package.json"
},
"types": "./mjs/index.d.ts",
Expand Down
79 changes: 79 additions & 0 deletions src/internal/async-store/__tests__/async-store.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { act, renderHook } from './render-hook';
import AsyncStore, { useReaction, useSelector } from '../index.js';

describe('AsyncStore', () => {
it('notifies listeners when selected state is updated', () => {
const store = new AsyncStore({ a: 1, b: 2 });

let a = store.get().a;
store.subscribe(
state => state.a,
newState => {
a = newState.a;
}
);

store.set(state => ({ ...state, a: state.a + 1 }));
store.set(state => ({ ...state, b: state.b + 1 }));
store.set(state => ({ ...state, a: state.a + 1 }));

expect(store.get().a).toBe(3);
expect(store.get().b).toBe(3);
expect(a).toBe(3);
});

it('allows unsubscribing from updates', () => {
const store = new AsyncStore({ a: 1, b: 2 });

let a = store.get().a;
const unsubscribeA = store.subscribe(
state => state.a,
newState => {
a = newState.a;
}
);

store.set(state => ({ ...state, a: state.a + 1 }));
unsubscribeA();
store.set(state => ({ ...state, a: state.a + 1 }));

expect(store.get().a).toBe(3);
expect(a).toBe(2);
});

it('can be used with useReaction to describe effects', () => {
const store = new AsyncStore({ a: 1, b: 2 });

const aIncrements: number[] = [];
renderHook(() =>
useReaction(
store,
s => s.a,
a => {
aIncrements.push(a);
}
)
);

act(() => store.set(state => ({ ...state, a: state.a + 1 })));
act(() => store.set(state => ({ ...state, a: state.a + 1 })));

expect(aIncrements).toEqual([2, 3]);
});

it('can be used with useSelector to make state from selected properties', () => {
const store = new AsyncStore({ a: 1, b: 2 });

const { result } = renderHook(() => useSelector(store, s => s.a));
expect(result.current).toEqual(1);

act(() => store.set(state => ({ ...state, a: state.a + 1 })));
expect(result.current).toEqual(2);

act(() => store.set(state => ({ ...state, a: state.a + 1 })));
expect(result.current).toEqual(3);
});
});
29 changes: 29 additions & 0 deletions src/internal/async-store/__tests__/render-hook.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import React from 'react';
import { render } from '@testing-library/react';

export { act } from '@testing-library/react';

/**
* Minimal port of `renderHook` from @testing-library/react (native version needs v13+).
* Supports the no-options usage exercised by the async-store tests.
*/
export function renderHook<Result>(renderCallback: () => Result) {
const result = React.createRef<Result>() as React.MutableRefObject<Result>;

function TestComponent() {
const pendingResult = renderCallback();

React.useEffect(() => {
result.current = pendingResult;
});

return null;
}

const { rerender, unmount } = render(<TestComponent />);

return { result, rerender, unmount };
}
91 changes: 91 additions & 0 deletions src/internal/async-store/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { useLayoutEffect, useState } from 'react';
import { unstable_batchedUpdates } from 'react-dom';

import { usePrevious } from './use-previous.js';

type Selector<S, R> = (state: S) => R;
type Listener<S> = (state: S, prevState: S) => void;

export interface ReadonlyAsyncStore<S> {
get(): S;
subscribe<R>(selector: Selector<S, R>, listener: Listener<S>): () => void;
unsubscribe(listener: Listener<S>): void;
}

export default class AsyncStore<S> implements ReadonlyAsyncStore<S> {
_state: S;
_listeners: [Selector<S, unknown>, Listener<S>][] = [];

constructor(state: S) {
this._state = state;
}

get(): S {
return this._state;
}

set(cb: (state: S) => S): void {
const prevState = this._state;
const newState = cb(prevState);

this._state = newState;

unstable_batchedUpdates(() => {
for (const [selector, listener] of this._listeners) {
if (selector(prevState) !== selector(newState)) {
listener(newState, prevState);
}
}
});
}

subscribe<R>(selector: Selector<S, R>, listener: Listener<S>): () => void {
this._listeners.push([selector, listener]);

return () => this.unsubscribe(listener);
}

unsubscribe(listener: Listener<S>): void {
for (let index = 0; index < this._listeners.length; index++) {
const [, storedListener] = this._listeners[index];

if (storedListener === listener) {
this._listeners.splice(index, 1);
break;
}
}
}
}

export function useReaction<S, R>(store: ReadonlyAsyncStore<S>, selector: Selector<S, R>, effect: Listener<R>): void {
useLayoutEffect(
() => {
const unsubscribe = store.subscribe(selector, (newState, prevState) =>
effect(selector(newState), selector(prevState))
);
return unsubscribe;
},
// ignoring selector and effect as they are expected to stay constant
// eslint-disable-next-line react-hooks/exhaustive-deps
[store]
);
}

export function useSelector<S, R>(store: ReadonlyAsyncStore<S>, selector: Selector<S, R>): R {
const [state, setState] = useState<R>(selector(store.get()));

useReaction(store, selector, newState => {
setState(newState);
});

// When store changes we need the state to be updated synchronously to avoid inconsistencies.
const prevStore = usePrevious(store);
if (prevStore !== null && prevStore !== store) {
return selector(store.get());
}

return state;
}
15 changes: 15 additions & 0 deletions src/internal/async-store/use-previous.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { useEffect, useRef } from 'react';

/**
* This hook gives the value of any variable from the previous render invocation
*/
export const usePrevious = <T>(value: T) => {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { GridNavigationProcessor } from '../grid-navigation.js';

describe('GridNavigationProcessor', () => {
test('does not throw when not initialized', () => {
const navigation = new GridNavigationProcessor({
current: {
updateFocusTarget: () => {},
getFocusTarget: () => null,
isRegistered: () => false,
},
});
expect(() => navigation.getNextFocusTarget()).not.toThrow();
expect(() => navigation.isElementSuppressed(null)).not.toThrow();
expect(() => navigation.isElementSuppressed(document.createElement('div'))).not.toThrow();
expect(() => navigation.onRegisterFocusable(document.createElement('div'))).not.toThrow();
expect(() => navigation.onUnregisterActive()).not.toThrow();
expect(() => navigation.refresh()).not.toThrow();
expect(() => navigation.update({ pageSize: 10 })).not.toThrow();
expect(() => navigation.cleanup()).not.toThrow();
});
});
Loading
Loading