Skip to content

Commit 5ede2fa

Browse files
authored
Merge pull request #7 from srav001/0.1.4
0.1.4
2 parents 05294a2 + fc52607 commit 5ede2fa

File tree

9 files changed

+650
-79
lines changed

9 files changed

+650
-79
lines changed

.prettierrc

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
{
2-
"useTabs": true,
3-
"tabWidth": 4,
4-
"singleQuote": true,
5-
"trailingComma": "none",
6-
"printWidth": 120,
7-
"plugins": ["prettier-plugin-organize-imports", "prettier-plugin-svelte"],
8-
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
2+
"useTabs": true,
3+
"tabWidth": 4,
4+
"singleQuote": true,
5+
"trailingComma": "none",
6+
"printWidth": 120,
7+
"plugins": ["prettier-plugin-organize-imports", "prettier-plugin-svelte"],
8+
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
99
}

DOCS/doc1.md

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Documentation for Store Creation and Caching Functions
2+
3+
This documentation provides a comprehensive overview of the TypeScript functions designed for creating stores and handling their caching. These functions are part of a larger system that manages state across an application. Below, you will find detailed descriptions, usage examples, and explanations of the parameters and return types for each function.
4+
5+
## Functions Overview
6+
7+
- **createStore**: Creates a primitive store with a specified name and initial state, with optional caching.
8+
- **createState**: A helper function that initializes the store state and handles caching based on provided options.
9+
- **handleCacheOfNewStore**: Manages the caching logic for a new store, including setting and retrieving cache data.
10+
11+
### createStore
12+
13+
Creates a primitive store with a specified name and initial state. It optionally configures caching for the store if specified in the options.
14+
15+
#### Parameters
16+
17+
- `storeName` (string): The name of the store being created. This name must be unique across the application.
18+
- `storeState` (InferedState): The initial state or value that will be stored in the created store. This is the data that the store will manage and provide access to.
19+
- `options` (StoreOptions, optional): Additional configuration options for creating the store. This may include settings for caching.
20+
21+
#### Returns
22+
23+
- `PrimitiveStore<InferedState>`: An object representing the created store. It includes the store name and a getter function for the store value.
24+
25+
#### Usage Example
26+
27+
```typescript
28+
const userStore = createStore('user', { name: 'John Doe', age: 30 });
29+
console.log(userStore.name); // Output: 'user'
30+
console.log(userStore.value); // Output: { name: 'John Doe', age: 30 }
31+
```
32+
33+
### createState
34+
35+
A helper function that initializes the store state and optionally handles caching based on the provided options. It is used internally by `createStore`.
36+
37+
#### Parameters
38+
39+
- `storeName` (string): The name of the store being created.
40+
- `storeState` (T): The initial state of the store.
41+
- `options` (StoreOptions, optional): Configuration options for the store, potentially including caching settings.
42+
43+
#### Usage Example
44+
45+
This function is used internally by `createStore` and is not intended to be called directly in most cases.
46+
47+
### handleCacheOfNewStore
48+
49+
Manages the caching logic for a new store, including setting and retrieving cache data based on the provided options.
50+
51+
#### Parameters
52+
53+
- `storeName` (string): The name of the store for which caching is being handled.
54+
- `storeState` (T): The initial state of the store.
55+
- `options` (StoreOptions): Configuration options for the store, including caching settings.
56+
57+
#### Usage Example
58+
59+
This function is used internally by `createState` when caching options are provided and is not intended to be called directly in most cases.
60+
61+
## Additional Notes
62+
63+
- The `StoreOptions` type should be defined elsewhere in your codebase, detailing the structure for caching options and any other store configuration settings.
64+
- The `_stores` object and `cacheModule` are assumed to be part of the larger application context, managing the state and caching logic respectively.
65+
- Error handling is implemented to ensure unique store names and the presence of required parameters.
66+
67+
By utilizing these functions, developers can efficiently manage application state with the added benefit of caching, enhancing performance and user experience.

DOCS/doc2.md

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# TypeScript Documentation
2+
3+
This documentation provides a comprehensive overview of a TypeScript module designed for state management with caching capabilities. The module introduces several key functions: `get`, `update`, `subscribe`, and `clearCache`, each serving a unique purpose in managing and interacting with state stores.
4+
5+
## Table of Contents
6+
7+
- [PrimitiveStore Type](#primitivestore-type)
8+
- [Getter Function](#getter-function)
9+
- [Updater Function](#updater-function)
10+
- [Subscriber Type](#subscriber-type)
11+
- [Subscribe Function](#subscribe-function)
12+
- [ClearCache Function](#clearcache-function)
13+
14+
### PrimitiveStore Type
15+
16+
Before diving into the functions, it's essential to understand the `PrimitiveStore<T>` type, which is a generic type representing a store that holds a value of type `T`. This type is crucial for the operation of the provided functions.
17+
18+
### Getter Function
19+
20+
```typescript
21+
function get<T, U>(store: PrimitiveStore<T>, derivation: (state: T) => U): Getter<U>
22+
```
23+
24+
The `get` function is designed to create a getter function from a store and a derivation function. It applies the derivation function to the store's value, returning a new value of type `U`.
25+
26+
- **Parameters:**
27+
- `store`: An instance of `PrimitiveStore<T>`.
28+
- `derivation`: A function that takes the current state of type `T` and returns a value of type `U`.
29+
30+
- **Returns:** A `Getter<U>` function that, when called, returns a value of type `U`.
31+
32+
### Updater Function
33+
34+
```typescript
35+
function update<T, U, C = unknown>(store: PrimitiveStore<T>, mutator: (state: T, payload: C) => U): Updater<C>
36+
```
37+
38+
The `update` function updates the store's value using a mutator function and a payload. It also handles caching if applicable.
39+
40+
- **Parameters:**
41+
- `store`: A `PrimitiveStore<T>` object.
42+
- `mutator`: A function that updates the state of the store based on the provided payload.
43+
44+
- **Returns:** An `Updater<C>` function that takes a payload of type `C`.
45+
46+
### Subscriber Type
47+
48+
```typescript
49+
type Subscriber<T, U = unknown> = (state: T) => U;
50+
type Subscribers<T> = Subscriber<T, unknown>[];
51+
```
52+
53+
Subscribers are functions that subscribe to changes in the store's state, reacting to updates.
54+
55+
### Subscribe Function
56+
57+
```typescript
58+
function subscribe<T, U extends Subscribers<T>>(store: PrimitiveStore<T>, subscribers: [...U], effect: (states: MapSources<U, T>) => void): () => void
59+
```
60+
61+
The `subscribe` function allows subscribing to a primitive store with specified subscribers and an effect to be executed.
62+
63+
- **Parameters:**
64+
- `store`: A `PrimitiveStore<T>`.
65+
- `subscribers`: An array of subscriber functions.
66+
- `effect`: A function that performs an action based on the states provided.
67+
68+
- **Returns:** A cleanup function to unsubscribe the effect.
69+
70+
### ClearCache Function
71+
72+
```typescript
73+
function clearCache(storeName: string): void
74+
```
75+
76+
The `clearCache` function clears the cache for a specific store if it exists.
77+
78+
- **Parameters:**
79+
- `storeName`: The name of the store to clear from the cache.
80+
81+
This module provides a robust solution for managing state in TypeScript applications, with features like caching and subscription to state changes, enhancing performance and reactivity.

DOCS/doc3.md

+153
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
## ❗️ In Development ❗️
2+
3+
The project is still in development. Hoping to release it right before Svelte 5 release. You can find usable examples in `src/routes/+page.svelte`.
4+
5+
# katai
6+
7+
Kaṭai (meaning store in Tamil) is a simple and lightweight store implementation for Svelte 5.
8+
9+
The basics of Katai is a few primitives that can be used to build any type of store. You can also build the store type you need with the help of these primitives. We also provide a few pre-built variations to choose from the Stores options. Whichever feels the most suitable can be used.
10+
11+
We do not wish to restrict you to a particular pattern for all your stores. You can copy the one of the current stores implementation as a base and build from on top it.
12+
13+
## Primitives
14+
15+
### createStore
16+
17+
The function `createStore` creates a primitive store with a specified name and initial state.
18+
19+
- @param {string} storeName - The `storeName` parameter is a string that represents the name of the store being created. It is a required parameter for creating a new store.
20+
- @param {InferedState} storeState - The `storeState` parameter in the `createStore` function represents the initial state or value that will be stored in the created store. It is the data that the store will manage and provide access to.
21+
- @param {StoreOptions} [options] - The `options` parameter in the `createStore` function is an optional parameter that allows you to provide additional configuration options for creating the store. It is of type `StoreOptions`, which likely contains properties or settings that can be used to customize the behavior of the store creation process like adding cache adapters.
22+
- @returns A PrimitiveStore object with the store name and a getter function for the store value.
23+
24+
#### EXAMPLE
25+
26+
```ts
27+
export const counterCoreStore = createStore('test', {
28+
counter: 0
29+
});
30+
31+
// Returns
32+
PrimitiveStore<{
33+
counter: number;
34+
}>;
35+
```
36+
37+
### get
38+
39+
The `get` function takes a store and a derivation function, and returns a getter function that applies the derivation function to the store's value.
40+
41+
- @param store - `PrimitiveStore<T>` is a generic type representing a store that holds a value of type `T`. It seems like the `store` parameter is expected to be an instance of this `PrimitiveStore` type.
42+
- @param derivation - The `derivation` parameter is a function that takes the current state of type `T` as input and returns a value of type `U`. It is used to derive a new value based on the current state stored in the `PrimitiveStore`.
43+
- @returns A `Getter<U>` function is being returned. This function takes no arguments and returns a value of type `U`. The value returned is the result of applying the `derivation` function to the `store.value`.
44+
45+
### update
46+
47+
The function `update` takes a store, a mutator function, and a payload, and updates the store's value using the mutator function while handling caching if applicable.
48+
49+
- @param store - The `store` parameter is a PrimitiveStore object that holds a value of type T.
50+
- @param mutator - The `mutator` parameter is a function that takes the current state of the store (`T`) and a payload of type `C`, and returns a new state of type `U`. It is used to update the state of the store based on the provided payload.
51+
- @returns The `update` function returns an `Updater` function that takes a value of type `C` as an argument.
52+
53+
### subscribe
54+
55+
The `subscribe` function allows for subscribing to a primitive store with specified subscribers and an effect to be executed.
56+
57+
- @param store - The `store` parameter is a PrimitiveStore that holds the state of type T.
58+
- @param subscribers - Subscribers are functions that subscribe to changes in the store's state. They are typically used to extract specific pieces of state from the store and react to changes in those pieces of state.
59+
- @param effect - The `effect` parameter in the `subscribe` function is a function that takes a `MapSources` object as its argument and performs some action based on the states provided in the `MapSources` object.
60+
- @returns The `subscribe` function returns a cleanup function that can be used to unsubscribe the effect and remove it from the list of subscribers.
61+
62+
#### EXAMPLE
63+
64+
```ts
65+
export const test = createStore('test', {
66+
counter: 0
67+
});
68+
69+
type StoreType = (typeof test)['value'];
70+
71+
export const testStore = {
72+
get $value() {
73+
return test.value;
74+
},
75+
get: <U extends unknown>(derivation: (val: StoreType) => U) => get(test, () => derivation(test.value)),
76+
subscribe: <T extends Subscribers<StoreType>>(states: [...T], effect: (states: MapSources<T, StoreType>) => void) =>
77+
subscribe(test, states, effect)
78+
};
79+
80+
testStore.subscribe([(state) => state.counter], ([value]) => {
81+
console.log('counter', value);
82+
});
83+
84+
const interval = setInterval(() => {
85+
testStore.$value.counter = testStore.$value.counter + 1;
86+
}, 2000);
87+
88+
// cleanup
89+
onDestroy(() => {
90+
clearInterval(interval);
91+
});
92+
```
93+
94+
## Stores
95+
96+
### Basic Store
97+
98+
The function `createBasicStore` creates a basic store with state, getters, and actions based on the provided options.
99+
100+
- @param {string} storeName - The `storeName` parameter is a string that represents the name of the store being created.
101+
- @param options - The `options` parameter in the `createBasicStore` function is an object that contains the following properties:
102+
- @param {StoreOptions} [settings] - The `settings` parameter in the `createBasicStore` function is an optional parameter of type `StoreOptions`. It allows you to provide additional settings or configurations for the store creation process. These settings can include options such as the store's persistence mechanism using cache adapters.
103+
- @returns The `createBasicStore` function returns an object of type `BasicStore<S, G, A>`, which includes the state, getters, actions, and additional methods like `clearCache` and `subscribe`.
104+
105+
#### EXAMPLE
106+
107+
```ts
108+
const newStore = createBasicStore('tester', {
109+
state: {
110+
counter: 0,
111+
count: 0
112+
},
113+
getters: {
114+
getCounter: (state) => state.counter,
115+
getCount: (state) => String(state.count)
116+
},
117+
actions: {
118+
updateCounter: (state, payload: number) => {
119+
state.counter += payload;
120+
},
121+
updateCount: (state, payload: number) => {
122+
state.count += payload;
123+
}
124+
}
125+
});
126+
127+
const interval = setInterval(() => {
128+
newStore.updateCounter(1);
129+
}, 2000);
130+
131+
// cleanup
132+
onDestroy(() => {
133+
clearInterval(interval);
134+
});
135+
136+
newStore.subscribe([(state) => state.counter], (states) => {
137+
console.log('newStore', states[0]);
138+
});
139+
```
140+
141+
### Writable Store
142+
143+
The `createWritable` function creates a writable store with initial value and provides methods for getting, setting, updating, subscribing to changes, and clearing cache.
144+
145+
- @param {T} initalValue - The `initalValue` parameter is the initial value that will be stored in the writable store. It should be an object of type `T`, which extends `Record<string, any>`. This initial value will be used as the starting value for the store.
146+
- @param storeName - The `storeName` parameter is a string that represents the name of the store where the data will be stored. If no `storeName` is provided, a random string will be generated for the store name.
147+
- @param {StoreOptions} [storeOptions] - The `storeOptions` parameter in the `createWritable` function is an optional parameter that allows you to specify additional options for the store creation. These options can include configuration settings or options specific to the underlying store implementation. If provided, these options will be used when creating the store using the `create
148+
- @returns An object is being returned with the following properties:
149+
- - get: a function that retrieves the current value from the store
150+
- - set: a function that updates the value in the store
151+
- - update: a function that takes a callback to update the value in the store
152+
- - subscribe: a function that subscribes to changes in the store and calls a subscriber function
153+
- - clearCache: a function that

DOCS/doc4.md

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Documentation for `createBasicStore` Function
2+
3+
The `createBasicStore` function is designed to create a basic store structure in TypeScript, facilitating state management in applications. This function is part of a larger library that provides utilities for creating, managing, and interacting with stores. Below is a detailed documentation of the `createBasicStore` function, including its parameters, return type, and usage examples.
4+
5+
## Function Signature
6+
7+
```typescript
8+
function createBasicStore<S extends State, G extends Getters<S>, A extends Actions<S>>(
9+
storeName: string,
10+
options: Store<S, G, A>,
11+
settings?: StoreOptions
12+
): BasicStore<S, G, A>;
13+
```
14+
15+
### Parameters
16+
17+
- `storeName: string`: A string that represents the name of the store being created. This name is used internally for identification and possibly for caching purposes.
18+
19+
- `options: Store<S, G, A>`: An object that specifies the initial state, getters, and actions for the store. The `options` object must conform to the `Store` type, which is a generic type parameterized by the state `S`, getters `G`, and actions `A`.
20+
21+
- `state: S`: The initial state of the store. It is a record type with keys as `string` or `number` and values of any type.
22+
- `getters: G`: An object containing getter functions. Each getter function takes the current state as an argument and returns a computed value based on that state.
23+
- `actions: A`: An object containing action functions. Each action function is responsible for updating the state based on the given payload.
24+
25+
- `settings?: StoreOptions` (Optional): An optional parameter that allows providing additional settings or configurations for the store creation process. These settings can include options such as the store's persistence mechanism using cache adapters.
26+
27+
### Return Type
28+
29+
- `BasicStore<S, G, A>`: The function returns an object of type `BasicStore<S, G, A>`, which includes the state, getters, actions, and additional methods like `clearCache` and `subscribe`. This object provides a simplified interface for interacting with the store, including performing state updates and subscribing to state changes.
30+
31+
### Additional Methods
32+
33+
- `clearCache`: A method that clears the cache associated with the store. Useful for resetting the store's state in scenarios involving caching.
34+
35+
- `subscribe`: A method that allows subscribing to state changes. It takes a set of subscribers and an effect function, which is called whenever the subscribed state changes.
36+
37+
## Usage Example
38+
39+
```typescript
40+
// Define the initial state, getters, and actions for a simple counter store.
41+
const counterOptions = {
42+
state: { count: 0 },
43+
getters: {
44+
doubleCount: (state) => state.count * 2,
45+
},
46+
actions: {
47+
increment: (state) => ({ count: state.count + 1 }),
48+
decrement: (state) => ({ count: state.count - 1 }),
49+
},
50+
};
51+
52+
// Create the counter store.
53+
const counterStore = createBasicStore('counterStore', counterOptions);
54+
55+
// Use the store's methods.
56+
console.log(counterStore.doubleCount()); // Output: 0 (double of initial count)
57+
counterStore.increment();
58+
console.log(counterStore.doubleCount()); // Output: 2 (double of updated count)
59+
```
60+
61+
This example demonstrates how to create a basic store for managing a counter's state, including incrementing and decrementing actions, and a getter for computing the double of the current count.

0 commit comments

Comments
 (0)