Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/status-matching.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bearstudio/ui-state": minor
---

Allow `getUiState` to take a status string so `.match().exhaustive()` works without a `set()` callback. A wide `string` is a type error, since it cannot be matched exhaustively.
24 changes: 12 additions & 12 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,23 @@ diverse, inclusive, and healthy community.
Examples of behavior that contributes to a positive environment for our
community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
- Focusing on what is best not just for us as individuals, but for the
overall community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or
- The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
- Other conduct which could reasonably be considered inappropriate in a
professional setting

## Enforcement Responsibilities
Expand Down Expand Up @@ -106,7 +106,7 @@ Violating these terms may lead to a permanent ban.
### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within
Expand All @@ -125,4 +125,4 @@ enforcement ladder](https://github.com/mozilla/diversity).

For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
https://www.contributor-covenant.org/translations.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ ui.match("pending", () => <>Loading...</>)
.exhaustive();
```

When the status is already known, pass it directly — no `set()` callback:

```tsx
getUiState(query.status)
.match("pending", () => <>Loading...</>)
.match("error", () => <>Error</>)
.match("success", () => <>Ready</>)
.exhaustive();
```

## 🪄 Fully customizable and type-safe

```tsx
Expand Down
10 changes: 10 additions & 0 deletions packages/ui-state/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ ui.match("pending", () => <>Loading...</>)
.exhaustive();
```

When the status is already known, pass it directly — no `set()` callback:

```tsx
getUiState(query.status)
.match("pending", () => <>Loading...</>)
.match("error", () => <>Error</>)
.match("success", () => <>Ready</>)
.exhaustive();
```

## 📃 License MIT

> Made with ❤️ by BearStudio Team
20 changes: 20 additions & 0 deletions packages/ui-state/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,26 @@ describe("getUiState", () => {
});
});

describe("from a status string", () => {
it("should create a UI state from a status string", () => {
const ui = getUiState("pending");

expect(ui.state.__status).toBe("pending");
});

it("should match and exhaustive from a status union", () => {
const status = "error" as "pending" | "error" | "success";

const result = getUiState(status)
.match("pending", () => "Loading")
.match("error", () => "Error")
.match("success", () => "OK")
.exhaustive();

expect(result).toBe("Error");
});
});

describe("is() method", () => {
it("should return true when status matches", () => {
const ui = getUiState((set) => set("pending"));
Expand Down
68 changes: 50 additions & 18 deletions packages/ui-state/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ type UiStateError<Message extends string> = null | {

type NonExhaustiveError<Message extends string = ""> = UiStateError<Message>;
type ExhaustiveError<Message extends string = ""> = UiStateError<Message>;
type ForbidWideString<S extends string> = string extends S
? ExhaustiveError<"`string` cannot be exhaustive. Use a string literal union.">
: S;

type Prettify<T> = { [K in keyof T]: T[K] } & {};

Expand All @@ -41,7 +44,7 @@ type GetUiStateSet = <
S extends AvailableStatus,
SData extends Record<string, unknown> | undefined = undefined,
>(
status: S,
status: ForbidWideString<S>,
data?: SData,
) => SetResult<S, SData>;

Expand All @@ -59,6 +62,21 @@ type MatchResult<Rest extends { __status: string }> = {
match: UiState<Rest>["match"];
});

type SplitStatus<S extends string> = S extends unknown
? { __status: S }
: never;

type UiStateFromInput<T> = [T] extends [(...args: never[]) => unknown]
? UiState<
Extract<
ReturnType<Extract<T, (...args: never[]) => unknown>>,
{ __status: AvailableStatus }
>
>
: [T] extends [string]
? UiState<SplitStatus<T>>
: never;

type UiState<T extends { __status: AvailableStatus }> = {
is: <S extends T["__status"]>(
status: S,
Expand All @@ -82,36 +100,29 @@ type UiState<T extends { __status: AvailableStatus }> = {
) => MatchResult<ExcludeStatus<T, S>>;
};

export const getUiState = <T extends { __status: AvailableStatus }>(
getState: (set: GetUiStateSet) => T,
const createUiState = <T extends { __status: AvailableStatus }>(
state: T,
): UiState<T> => {
const state = Object.freeze(
getState(((status, data = {} as ExplicitAny) => {
return {
__status: status,
...data,
};
}) as GetUiStateSet),
);
const frozenState = Object.freeze(state);

const isMatching = (status: T["__status"]): boolean =>
status === state.__status;
status === frozenState.__status;

const isMatchingArray = (status: Array<T["__status"]>): boolean =>
status.includes(state.__status);
status.includes(frozenState.__status);

const uiState: UiState<T> = {
state,
state: frozenState,
is: ((status: T["__status"]) => {
return state.__status === status;
return frozenState.__status === status;
}) as UiState<T>["is"],
when: (status, handler) => {
if (
typeof status === "string"
? isMatching(status)
: isMatchingArray(status)
) {
return handler(state as ExplicitAny);
return handler(frozenState as ExplicitAny);
}
return null;
},
Expand All @@ -125,9 +136,10 @@ export const getUiState = <T extends { __status: AvailableStatus }>(
: isMatchingArray(status))
) {
return {
exhaustive: () => handler(state as ExplicitAny) as React.ReactNode,
exhaustive: () =>
handler(frozenState as ExplicitAny) as React.ReactNode,
nonExhaustive: () =>
handler(state as ExplicitAny) as React.ReactNode,
handler(frozenState as ExplicitAny) as React.ReactNode,
match: (nextStatus: ExplicitAny, nextHandler: ExplicitAny) =>
uiState.match(nextStatus, nextHandler, true, () =>
handler(uiState.state as ExplicitAny),
Expand All @@ -146,3 +158,23 @@ export const getUiState = <T extends { __status: AvailableStatus }>(

return uiState;
};

export function getUiState<
T extends string | ((set: GetUiStateSet) => { __status: AvailableStatus }),
>(
statusOrGetState: T extends string ? ForbidWideString<T> : T,
): UiStateFromInput<T>;
export function getUiState(
statusOrGetState: ExplicitAny,
): UiState<{ __status: AvailableStatus }> {
if (typeof statusOrGetState === "string") {
return createUiState({ __status: statusOrGetState });
}

return createUiState(
statusOrGetState((status: AvailableStatus, data = {} as ExplicitAny) => ({
__status: status,
...data,
})),
);
}
45 changes: 45 additions & 0 deletions packages/ui-state/src/index.types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,48 @@ describe("getUiState empty payload vs data payload", () => {
});
});
});

describe("getUiState rejects a wide string", () => {
it("errors when getUiState() is called with a string", () => {
const status = "pending" as string;
// @ts-expect-error string cannot be exhaustive
const ui = getUiState(status);
expect(ui.state.__status).toBe("pending");
});

it("errors when set() is called with a string", () => {
const status = "pending" as string;
const ui = getUiState((set) =>
// @ts-expect-error string cannot be exhaustive
set(status),
);
expect(ui.state.__status).toBe("pending");
});
});

describe("getUiState from a status string", () => {
const status = "pending" as "pending" | "error" | "success";
const ui = getUiState(status);

it("splits a string union into a discriminated state", () => {
expectTypeOf(ui.state).toEqualTypeOf<
{ __status: "pending" } | { __status: "error" } | { __status: "success" }
>();
});

it("exhaustive() is not callable while statuses remain", () => {
const partial = ui.match("pending", () => null).match("error", () => null);
expectTypeOf(partial.exhaustive).not.toEqualTypeOf<() => ReactNode>();
// @ts-expect-error success is missing
partial.exhaustive();
});

it("exhaustive() is callable when the union is covered", () => {
const done = ui
.match("pending", () => "p")
.match("error", () => "e")
.match("success", () => "s");
expectTypeOf(done.exhaustive).toEqualTypeOf<() => ReactNode>();
expect(done.exhaustive()).toBe("p");
});
});
Loading