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

Add event sore #1

Merged
merged 6 commits into from
Apr 4, 2024
Merged
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 .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.eslintrc.cjs
2 changes: 2 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ module.exports = {
'standard-with-typescript',
'plugin:react/recommended',
'plugin:storybook/recommended',
'prettier',
],
plugins: ['prettier'],
overrides: [],
parserOptions: {
ecmaVersion: 'latest',
Expand Down
Binary file modified .yarn/install-state.gz
Binary file not shown.
15 changes: 1 addition & 14 deletions lib/classic-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,6 @@ interface StoreBuilder<T> {
getValue: () => T
}

const createStore = <T>(initialState: T) => {
let storeInstance: BehaviorSubject<T> | null = null;

return () => {
if (storeInstance === null) {
storeInstance = new BehaviorSubject<T>(initialState);
}
return storeInstance;
};
};

const isDefaultState = <T>(
defaultState: DefaultState<T>
): defaultState is T => {
Expand All @@ -52,9 +41,7 @@ export const buildClassicStore = async <T>(
? defaultState
: await defaultState.hydrator();

const getStoreInstance = createStore(initialState);

const store = getStoreInstance();
const store = new BehaviorSubject<T>(initialState);

const update: Updater<T> = (updater) => {
store.next(updater(store.getValue()));
Expand Down
3 changes: 3 additions & 0 deletions lib/dao.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { createEventStore } from '.';

export const wuji = createEventStore;
169 changes: 169 additions & 0 deletions lib/event-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import { BehaviorSubject, type Observable } from 'rxjs';
import {
distinctUntilChanged,
filter,
map,
scan,
startWith,
tap,
} from 'rxjs/operators';
import {
type GetValueType,
type NestedEvent,
type PropertyPath,
type SystemEvent,
} from './types';
import { set, get } from 'lodash/fp';

import { useCallback, useEffect, useState } from 'react';

export function createEventStore<T extends object>(
initialState: T,
options?: {
debug?: boolean;
hydrator: () => Promise<T>;
persist?: (state: T) => Promise<void>;
},
) {
const debug = options?.debug === true ? options.debug : false;
const globalEventStore = new BehaviorSubject<NestedEvent<T> | SystemEvent<T>>(
{
type: '@@INIT',
payload: initialState,
},
);
const publish = <
TType extends PropertyPath<T>,
TPayload extends GetValueType<T, TType>,
>(
type: TType,
payload: TPayload,
) => {
// eslint-disable-next-line
const event = { type, payload } as NestedEvent<T>;
globalEventStore.next(event);
};

const getPropertyObservable = <K extends PropertyPath<T>>(
eventType: K,
): Observable<GetValueType<T, K>> => {
return globalEventStore.pipe(
filter((event) => event.type.startsWith(eventType)),
map((event) => event.payload as GetValueType<T, K>),
scan((__, curr) => curr),
distinctUntilChanged(),
);
};

const getHydrationObservable$ = (): Observable<T> => {
return globalEventStore.pipe(
filter((event) => event.type === '@@HYDRATED'),
map((event) => event.payload as T),
scan((__, curr) => curr),
distinctUntilChanged(),
);
};

const state$ = new BehaviorSubject<T>(initialState);

globalEventStore
.pipe(
tap((event) => {
if (debug) {
console.info(event);
}
}),
scan((state, event) => {
if (event.type === '@@INIT' || event.type === '@@HYDRATED') {
return event.payload as T;
}
return set(event.type, event.payload, state);
}, initialState),
tap((state) => {
if (debug) {
console.info('State after update', state);
}
}),
startWith(initialState),
)
.subscribe(state$);

options
?.hydrator?.()
.then((payload) => {
globalEventStore.next({ type: '@@HYDRATED', payload });
})
.catch((error) => {
console.error('Failed to hydrate store', error);
});

state$.subscribe({ next: options?.persist });

const useStoreValue = <K extends PropertyPath<T>>(
type: K,
): [GetValueType<T, K>, (payload: GetValueType<T, K>) => void] => {
const defaultValue: GetValueType<T, K> = get(type, state$.getValue());
const [value, setValue] = useState<GetValueType<T, K>>(defaultValue);
const handleUpdate = useCallback((payload: GetValueType<T, K>) => {
publish(type, payload);
}, []);

useEffect(() => {
const subscription = getHydrationObservable$().subscribe({
next: (nextState) => {
setValue(get(type, nextState) as GetValueType<T, K>);
},
});

return () => {
subscription.unsubscribe();
};
}, []);

useEffect(() => {
const subscription = getPropertyObservable(type).subscribe({
next: (value) => {
setValue(value);
},
});
return () => {
subscription.unsubscribe();
};
}, []);

return [value, handleUpdate];
};
const useHydrateStore = () => {
return (payload: T) => {
globalEventStore.next({ type: '@@HYDRATED', payload });
};
};
const useIsHydrated = () => {
const [isHydrated, setIsHydrated] = useState(false);
useEffect(() => {
const subscription = getHydrationObservable$().subscribe({
next: () => {
setIsHydrated(true);
},
});

return () => {
subscription.unsubscribe();
};
}, []);
return isHydrated;
};
const systemEvents$ = globalEventStore.pipe(
filter((event) => event.type.startsWith('@@')),
);

return {
useStoreValue,
useHydrateStore,
useIsHydrated,
publish,
getPropertyObservable,
state$,
systemEvents$,
};
}
2 changes: 2 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export * from './classic-store';
export * from './event-store';
export * from './dao';
28 changes: 28 additions & 0 deletions lib/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export type PropertyPath<T> = {
[K in keyof T]: K extends string
? T[K] extends object
? `${K}.${PropertyPath<T[K]>}` | K
: K
: never;
}[keyof T];

export type GetValueType<
T,
Path extends PropertyPath<T>,
> = Path extends `${infer Key}.${infer Rest}`
? Key extends keyof T
? Rest extends PropertyPath<T[Key]>
? GetValueType<T[Key], Rest>
: never
: never
: Path extends keyof T
? T[Path]
: never;

export interface NestedEvent<T> {
type: PropertyPath<T>
payload: GetValueType<T, PropertyPath<T>>
}
export type SystemEvent<T> =
| { type: '@@INIT', payload: T }
| { type: '@@HYDRATED', payload: T };
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,13 @@
"@storybook/react-vite": "^7.6.17",
"@storybook/test": "^7.6.17",
"@storybook/testing-library": "^0.2.2",
"@types/lodash.set": "^4",
"@types/node": "^20.11.20",
"@typescript-eslint/eslint-plugin": "^6.4.0",
"@typescript-eslint/parser": "^7.0.2",
"@vitest/ui": "^1.3.1",
"eslint": "^8.0.1",
"eslint-config-prettier": "^9.1.0",
"eslint-config-standard-with-typescript": "^43.0.1",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-n": "^15.0.0 || ^16.0.0 ",
Expand All @@ -65,6 +67,7 @@
},
"packageManager": "[email protected]",
"dependencies": {
"lodash.set": "^4.3.2",
"rxjs": "^7.8.1"
}
}
23 changes: 23 additions & 0 deletions stories/event-store.stories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { Meta, StoryObj } from '@storybook/react';
import { Root } from './event-store/Root';

// More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export
const meta = {
title: 'Dantian/Event Store',
component: Root,
parameters: {
layout: 'centered',
},

tags: ['autodocs'],

argTypes: {},
} satisfies Meta<typeof Root>;

export default meta;
type Story = StoryObj<typeof meta>;

// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Primary: Story = {
args: {},
};
19 changes: 19 additions & 0 deletions stories/event-store/Root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Flex } from '@radix-ui/themes';

import React from 'react';
import { state$, useStoreValue } from './store';

export const Root = () => {
const [name] = useStoreValue('user.name');
return (
<Flex direction="column" gap="2">
<Flex direction="row" gap="2" align={'center'}>
State: <pre>{JSON.stringify(state$.getValue())}</pre>
</Flex>

<Flex direction="row" gap="2" align={'center'}>
User name: {name}
</Flex>
</Flex>
);
};
9 changes: 9 additions & 0 deletions stories/event-store/state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
interface State {
user: {
name: string;
address: {
city: string;
street: string;
};
};
}
28 changes: 28 additions & 0 deletions stories/event-store/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { wuji } from '../../lib';

export const { state$, useStoreValue, useHydrateStore, useIsHydrated } =
wuji<State>(
{
user: { address: { city: 'n/a', street: 'n/a' }, name: 'n/a' },
},
{
hydrator: () => {
return new Promise((resolve) => {
setTimeout(
() =>
resolve({
user: {
address: {
city: 'Aubonne',
street: 'Chemin du Mont-Blanc 16',
},
name: 'Julius',
},
}),
3000,
);
});
},
debug: true,
},
);
Loading
Loading