Skip to content

Add type declarations #267

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

Merged
merged 44 commits into from
Aug 12, 2023
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
7d8ed5c
Generate `Onyx` and `withOnyx` declaration files
fabioh8010 Jun 27, 2023
d10db07
Create `Logger` declaration file
fabioh8010 Jun 27, 2023
98ac024
Improve basic `Onyx` method declarations
fabioh8010 Jun 27, 2023
e0b50fd
Ignore .d.ts files during linting
fabioh8010 Jun 27, 2023
65f0cf3
Add "types" entry in package.json
fabioh8010 Jun 28, 2023
2eb85e6
Initial implementation of generic keys
fabioh8010 Jun 28, 2023
64a1d1a
Improve typings for Onyx methods
fabioh8010 Jun 29, 2023
dbfbd8c
Improve custom type approach
fabioh8010 Jun 30, 2023
78a766c
Address reviews suggestions and improve several types
fabioh8010 Jun 30, 2023
e389d32
Minor fixes
fabioh8010 Jul 3, 2023
cd1807b
Improve merge() and updated() typings
fabioh8010 Jul 4, 2023
533dfdf
Improves mergeCollection() typings
fabioh8010 Jul 4, 2023
5cce58e
Add type to withOnyxInstance property on connect()
fabioh8010 Jul 4, 2023
d42ea7e
Change callback type based on waitForCollectionCallback on connect()
fabioh8010 Jul 4, 2023
0b487d5
Improve connect() typing
fabioh8010 Jul 4, 2023
b0a0321
First version of withOnyx HOC typing
fabioh8010 Jul 10, 2023
c5b36a8
Fix withOnyx key type and improve all typings
fabioh8010 Jul 12, 2023
af68220
Use a separate type for collection keys
fabioh8010 Jul 13, 2023
7b3492a
Fix update() mergeCollection object
fabioh8010 Jul 13, 2023
7944e13
Improve connect() type for collection keys
fabioh8010 Jul 13, 2023
2592b36
Fix Selector type for unknown values
fabioh8010 Jul 13, 2023
02f0c1e
General improvements on HOC typings
fabioh8010 Jul 17, 2023
a25920a
Minor fix in getAllKeys() type
fabioh8010 Jul 18, 2023
e0ebe55
Address review comments
fabioh8010 Jul 19, 2023
6103f73
Address review comments
fabioh8010 Jul 25, 2023
32abd45
Remove string selectors and fix safeEvictionKeys
fabioh8010 Jul 26, 2023
6ec2d95
First attempt of GetOnyxValue
fabioh8010 Jul 26, 2023
38e8eed
Merge branch 'main' into feature/type-declarations
fabioh8010 Jul 26, 2023
30b2dc4
Add type declarations for new Onyx methods
fabioh8010 Jul 26, 2023
4332d2f
Add comments to some draft types
fabioh8010 Jul 26, 2023
343d7d9
Second attempt to solve collection key issue
fabioh8010 Jul 27, 2023
949b48e
Add JSDoc comments for several types
fabioh8010 Jul 27, 2023
3a101df
Clean up typings and add more JSDoc comments
fabioh8010 Jul 28, 2023
f06ce38
Merge remote-tracking branch 'origin/main' into feature/type-declarat…
fabioh8010 Jul 31, 2023
826ee48
Address review comments
fabioh8010 Jul 31, 2023
834bf1d
Address review comments
fabioh8010 Aug 1, 2023
3eaf539
Replace MergeBy with Merge from type-fest and remove unused exports
fabioh8010 Aug 2, 2023
6215c2f
Add examples for OnyxEntry and OnyxCollectionEntries types
fabioh8010 Aug 2, 2023
c5fc96e
Change KeyValueMapping type to automatically consider collection keys…
fabioh8010 Aug 2, 2023
521426f
Address review comments
fabioh8010 Aug 3, 2023
d632845
First test with new OnyxUpdate approach
fabioh8010 Aug 4, 2023
eae275b
Remove unused code
fabioh8010 Aug 4, 2023
86aa549
Export OnyxUpdate type
fabioh8010 Aug 4, 2023
500d228
Address review comments
fabioh8010 Aug 8, 2023
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 @@
*.d.ts
13 changes: 13 additions & 0 deletions lib/Logger.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
declare type LogData = {
message: string;
level: 'alert' | 'info';
};

/**
* Register the logging callback
*
* @param callback
*/
declare function registerLogger(callback: (data: LogData) => void): void;

export {registerLogger};
294 changes: 294 additions & 0 deletions lib/Onyx.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,294 @@
import {Component} from 'react';
import {PartialDeep} from 'type-fest';
import {CustomTypeOptions} from '.';
import * as Logger from './Logger';

type MergeBy<T, K> = Omit<T, keyof K> & K;
type DeepRecord<K extends string | number | symbol, T> = {[key: string]: T | DeepRecord<K, T>};
type DeepKeyOf<T> = T extends object
? {
[K in keyof T & (string | number)]: T[K] extends Record<string, unknown> ? `${K}.${DeepKeyOf<T[K]>}` | K : K;
}[keyof T & (string | number)]
: T;

type TypeOptions = MergeBy<
{
keys: string;
values: Record<string, unknown>;
},
CustomTypeOptions
>;

type Key = TypeOptions['keys'];
type Value = TypeOptions['values'];

type KeyValueMap = {
[K in Key]: Value[K];
};

type BaseConnectOptions<K extends Key> = {
key: K;
statePropertyName?: string;
withOnyxInstance?: Component;
initWithStoredValues?: boolean;
selector?: Value[K] extends object ? ((value: Value[K] | null) => PartialDeep<Value[K]> | null) | DeepKeyOf<Value[K]> : never;
};

declare type ConnectOptions<K extends Key> = BaseConnectOptions<K> &
(
| {
callback?: (value: Record<string, Value[K]> | null, key?: K) => void;
waitForCollectionCallback: true;
}
| {
callback?: (value: Value[K] | null, key?: K) => void;
waitForCollectionCallback?: false;
}
);

declare type MergeCollection<K extends Key, Map, Value> = {
[MapK in keyof Map]: MapK extends `${K}${string}`
? MapK extends `${K}`
? never // forbids empty id
: Value
: never;
};

declare type UpdateOperation<K extends Key> =
| {
onyxMethod: 'set';
key: K;
value: Value[K];
}
| {
onyxMethod: 'merge';
key: K;
value: PartialDeep<Value[K]>;
}
| {
onyxMethod: 'mergeCollection'; // TODO: Finish this.
key: K;
value: PartialDeep<Value[K]>;
};

declare type UpdateOperations<KList extends Key[]> = {
[K in keyof KList]: UpdateOperation<KList[K]>;
};

declare type InitOptions = {
keys?: DeepRecord<string, string>;
initialKeyStates?: Partial<KeyValueMap>;
safeEvictionKeys?: Key[];
maxCachedKeysCount?: number;
captureMetrics?: boolean;
shouldSyncMultipleInstances?: boolean;
debugSetState?: boolean;
};

declare const METHOD: {
readonly SET: string;
readonly MERGE: string;
readonly MERGE_COLLECTION: string;
readonly CLEAR: string;
};

/**
* Returns current key names stored in persisted storage
*/
declare function getAllKeys<K extends Key>(): Promise<K[]>;

/**
* Checks to see if this key has been flagged as
* safe for removal.
*
* @param testKey
*/
declare function isSafeEvictionKey<K extends Key>(testKey: K): boolean;

/**
* Removes a key previously added to this list
* which will enable it to be deleted again.
*
* @param key
* @param connectionID
*/
declare function removeFromEvictionBlockList<K extends Key>(key: K, connectionID: number): void;

/**
* Keys added to this list can never be deleted.
*
* @param key
* @param connectionID
*/
declare function addToEvictionBlockList<K extends Key>(key: K, connectionID: number): void;

/**
* Subscribes a react component's state directly to a store key
*
* @example
* const connectionID = Onyx.connect({
* key: ONYXKEYS.SESSION,
* callback: onSessionChange,
* });
*
* @param mapping the mapping information to connect Onyx to the components state
* @param mapping.key ONYXKEY to subscribe to
* @param [mapping.statePropertyName] the name of the property in the state to connect the data to
* @param {Object} [mapping.withOnyxInstance] whose setState() method will be called with any changed data
* This is used by React components to connect to Onyx
* @param [mapping.callback] a method that will be called with changed data
* This is used by any non-React code to connect to Onyx
* @param [mapping.initWithStoredValues] If set to false, then no data will be prefilled into the
* component
* @param [mapping.waitForCollectionCallback] If set to true, it will return the entire collection to the callback as a single object
* @param {String|Function} [mapping.selector] THIS PARAM IS ONLY USED WITH withOnyx(). If included, this will be used to subscribe to a subset of an Onyx key's data.
* If the selector is a string, the selector is passed to lodashGet on the sourceData. If the selector is a function, the sourceData and withOnyx state are
* passed to the selector and should return the simplified data. Using this setting on `withOnyx` can have very positive performance benefits because the component
* will only re-render when the subset of data changes. Otherwise, any change of data on any property would normally cause the component to re-render (and that can
* be expensive from a performance standpoint).
* @returns an ID to use when calling disconnect
*/
declare function connect<K extends Key>(mapping: ConnectOptions<K>): number;

/**
* Remove the listener for a react component
* @example
* Onyx.disconnect(connectionID);
*
* @param connectionID unique id returned by call to Onyx.connect()
* @param [keyToRemoveFromEvictionBlocklist]
*/
declare function disconnect<K extends Key>(connectionID: number, keyToRemoveFromEvictionBlocklist?: K): void;

/**
* Write a value to our store with the given key
*
* @param key ONYXKEY to set
* @param value value to store
*/
declare function set<K extends Key>(key: K, value: Value[K] | null): Promise<void>;

/**
* Sets multiple keys and values
*
* @example Onyx.multiSet({'key1': 'a', 'key2': 'b'});
*
* @param data object keyed by ONYXKEYS and the values to set
*/
declare function multiSet(data: Partial<KeyValueMap>): Promise<void>;

/**
* Merge a new value into an existing value at a key.
*
* The types of values that can be merged are `Object` and `Array`. To set another type of value use `Onyx.set()`. Merge
* behavior uses lodash/merge under the hood for `Object` and simple concatenation for `Array`. However, it's important
* to note that if you have an array value property on an `Object` that the default behavior of lodash/merge is not to
* concatenate. See here: https://github.com/lodash/lodash/issues/2872
*
* Calls to `Onyx.merge()` are batched so that any calls performed in a single tick will stack in a queue and get
* applied in the order they were called. Note: `Onyx.set()` calls do not work this way so use caution when mixing
* `Onyx.merge()` and `Onyx.set()`.
*
* @example
* Onyx.merge(ONYXKEYS.EMPLOYEE_LIST, ['Joe']); // -> ['Joe']
* Onyx.merge(ONYXKEYS.EMPLOYEE_LIST, ['Jack']); // -> ['Joe', 'Jack']
* Onyx.merge(ONYXKEYS.POLICY, {id: 1}); // -> {id: 1}
* Onyx.merge(ONYXKEYS.POLICY, {name: 'My Workspace'}); // -> {id: 1, name: 'My Workspace'}
*
* @param key ONYXKEYS key
* @param value Object or Array value to merge
*/
declare function merge<K extends Key>(key: K, value: PartialDeep<Value[K]>): Promise<void>;

/**
* Clear out all the data in the store
*
* Note that calling Onyx.clear() and then Onyx.set() on a key with a default
* key state may store an unexpected value in Storage.
*
* E.g.
* Onyx.clear();
* Onyx.set(ONYXKEYS.DEFAULT_KEY, 'default');
* Storage.getItem(ONYXKEYS.DEFAULT_KEY)
* .then((storedValue) => console.log(storedValue));
* null is logged instead of the expected 'default'
*
* Onyx.set() might call Storage.setItem() before Onyx.clear() calls
* Storage.setItem(). Use Onyx.merge() instead if possible. Onyx.merge() calls
* Onyx.get(key) before calling Storage.setItem() via Onyx.set().
* Storage.setItem() from Onyx.clear() will have already finished and the merged
* value will be saved to storage after the default value.
*
* @param keysToPreserve is a list of ONYXKEYS that should not be cleared with the rest of the data
*/
declare function clear(keysToPreserve?: Key[]): Promise<void>;

/**
* Merges a collection based on their keys
*
* @example
*
* Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, {
* [`${ONYXKEYS.COLLECTION.REPORT}1`]: report1,
* [`${ONYXKEYS.COLLECTION.REPORT}2`]: report2,
* });
*
* @param collectionKey e.g. `ONYXKEYS.COLLECTION.REPORT`
* @param collection Object collection keyed by individual collection member keys and values
*/
declare function mergeCollection<K extends Key, T>(collectionKey: K, collection: MergeCollection<K, T, PartialDeep<Value[K]>>): Promise<void>;

/**
* Insert API responses and lifecycle data into Onyx
*
* @param data An array of objects with shape {onyxMethod: oneOf('set', 'merge', 'mergeCollection'), key: string, value: *}
* @returns resolves when all operations are complete
*/
declare function update<KList extends Key[]>(data: UpdateOperations<[...KList]>): Promise<void>;

/**
* Initialize the store with actions and listening for storage events
*
* @param [options={}] config object
* @param [options.keys={}] `ONYXKEYS` constants object
* @param [options.initialKeyStates={}] initial data to set when `init()` and `clear()` is called
* @param [options.safeEvictionKeys=[]] This is an array of keys
* (individual or collection patterns) that when provided to Onyx are flagged
* as "safe" for removal. Any components subscribing to these keys must also
* implement a canEvict option. See the README for more info.
* @param [options.maxCachedKeysCount=55] Sets how many recent keys should we try to keep in cache
* Setting this to 0 would practically mean no cache
* We try to free cache when we connect to a safe eviction key
* @param [options.captureMetrics] Enables Onyx benchmarking and exposes the get/print/reset functions
* @param [options.shouldSyncMultipleInstances] Auto synchronize storage events between multiple instances
* of Onyx running in different tabs/windows. Defaults to true for platforms that support local storage (web/desktop)
* @param [options.debugSetState] Enables debugging setState() calls to connected components.
* @example
* Onyx.init({
* keys: ONYXKEYS,
* initialKeyStates: {
* [ONYXKEYS.SESSION]: {loading: false},
* },
* });
*/
declare function init(config?: InitOptions): void;

declare const Onyx: {
connect: typeof connect;
disconnect: typeof disconnect;
set: typeof set;
multiSet: typeof multiSet;
merge: typeof merge;
mergeCollection: typeof mergeCollection;
update: typeof update;
clear: typeof clear;
getAllKeys: typeof getAllKeys;
init: typeof init;
registerLogger: typeof Logger.registerLogger;
addToEvictionBlockList: typeof addToEvictionBlockList;
removeFromEvictionBlockList: typeof removeFromEvictionBlockList;
isSafeEvictionKey: typeof isSafeEvictionKey;
METHOD: typeof METHOD;
};

export default Onyx;
7 changes: 7 additions & 0 deletions lib/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import Onyx from './Onyx';
import withOnyx from './withOnyx';

interface CustomTypeOptions {}

export default Onyx;
export {CustomTypeOptions, withOnyx};
2 changes: 2 additions & 0 deletions lib/withOnyx.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export default function (mapOnyxToState: any): (WrappedComponent: any) => any;
//# sourceMappingURL=withOnyx.d.ts.map
Loading