Skip to content
This repository has been archived by the owner on Dec 14, 2023. It is now read-only.

Commit

Permalink
ui/react: extract updater constructors
Browse files Browse the repository at this point in the history
  • Loading branch information
denis-sokolov committed Mar 2, 2021
1 parent 24c0953 commit 179f9d2
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 37 deletions.
39 changes: 2 additions & 37 deletions src/ui/react/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,14 @@
import type { DebugConfig, FullDB } from "../../../core";
import type { ReactType } from "../types";
import type {
Changer,
MassUpdater,
MassUpdaterInternal,
Updater,
UpdaterInternal,
} from "./types";
import { makeMassUpdater, makeUpdater } from "./updater";
import type { Changer, MassUpdater } from "./types";

export type { MassUpdater, Updater } from "./types";

function flat<T>(list: T[][]): T[] {
return list.reduce((a, b) => a.concat(b));
}

function makeMassUpdater<Domain, K extends keyof Domain>(
db: FullDB<Domain>
): MassUpdater<Domain, K> {
const updater: MassUpdaterInternal<Domain, K> = function (
_options,
kind,
id,
delta
) {
db.update(kind, id, delta);
};
return (a: any, b: any, c: any, d?: any) =>
d ? updater(a, b, c, d) : updater({}, a, b, c);
}

function makeUpdater<Domain, K extends keyof Domain>(
massUpdater: MassUpdater<Domain, K>,
kind: K,
id: string
): Updater<Domain[K]> {
const updater: UpdaterInternal<Domain[K]> = function (options, delta) {
massUpdater(options, kind, id, delta);
};
return ((a: any, b?: any) => {
if (typeof a === "string")
return updater({}, (prev) => ({ ...prev, [a]: b }));
updater(b ? a : {}, b || a);
}) as any;
}

export function makeHooks<Domain>(params: {
React: ReactType;
useTryDB: () => FullDB<Domain> | "missing-provider";
Expand Down
37 changes: 37 additions & 0 deletions src/ui/react/hooks/updater.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { FullDB } from "../../../core";
import type {
MassUpdater,
MassUpdaterInternal,
Updater,
UpdaterInternal,
} from "./types";

export function makeMassUpdater<Domain, K extends keyof Domain>(
db: FullDB<Domain>
): MassUpdater<Domain, K> {
const updater: MassUpdaterInternal<Domain, K> = function (
_options,
kind,
id,
delta
) {
db.update(kind, id, delta);
};
return (a: any, b: any, c: any, d?: any) =>
d ? updater(a, b, c, d) : updater({}, a, b, c);
}

export function makeUpdater<Domain, K extends keyof Domain>(
massUpdater: MassUpdater<Domain, K>,
kind: K,
id: string
): Updater<Domain[K]> {
const updater: UpdaterInternal<Domain[K]> = function (options, delta) {
massUpdater(options, kind, id, delta);
};
return ((a: any, b?: any) => {
if (typeof a === "string")
return updater({}, (prev) => ({ ...prev, [a]: b }));
updater(b ? a : {}, b || a);
}) as any;
}

0 comments on commit 179f9d2

Please sign in to comment.