defineEnum
Declare a list of statuses or categories once, with labels and colours, and use it on the server and in the UI.
Usage
app/shared/order.ts
import { defineEnum } from "manh/enum";
export const OrderStatus = defineEnum({
pending: ["Pending", "processing"],
done: ["Done", "success"],
cancelled: ["Cancelled", "default"],
});
export type OrderStatus = (typeof OrderStatus.values)[number];Put it in app/shared/ so both .tsx pages and .ts handlers can import it.
Signature
manh/enum
type EnumColor = "success" | "error" | "processing" | "warning" | "default" | (string & {});
function defineEnum<const T extends Record<string, readonly [label: string, color?: EnumColor]>>(def: T): {
readonly values: [K, ...K[]];
label(v: K | string | null | undefined): string;
color(v: K | string | null | undefined): EnumColor | undefined;
readonly valueEnum: Record<K, { text: string; status?: string; color?: string }>;
readonly options: Array<{ value: K; label: string }>;
is(v: unknown): v is K;
};
// K = the keys of defParameters
def: an object whose keys are the values stored in the database and whose values are[label, colour]. The colour is one ofsuccess,error,processing,warning,default(shown as a Badge) or any antdTagcolour ("blue","#1677ff"). The colour is optional.
Returns
A read-only object:
values: the array of keys, forz.enum(X.values)and loops.label(v): the label of a value. An unknown value comes back as a string.color(v): the colour of a value, orundefined.valueEnum: for thevalueEnumof aProTableorProDescriptionscolumn.options:[{ value, label }]forSelect,Segmented,Radio.is(v):truewhenvis a declared key.
Examples
Server:
app/orders/[id:int]/status/post.ts
import { z } from "@hono/zod-openapi";
import { OrderStatus } from "app/shared/order";
export const schema = { body: z.object({ to: z.enum(OrderStatus.values) }) };UI:
app/orders/order-columns.tsx
import { Tag } from "antd";
import { OrderStatus } from "app/shared/order";
export const statusColumn = { title: "Status", dataIndex: "status", valueEnum: OrderStatus.valueEnum };
export const StatusTag = ({ v }: { v: string }) => <Tag color={OrderStatus.color(v)}>{OrderStatus.label(v)}</Tag>;Change a label here and every screen, filter, schema and email follows. Don’t redeclare the same list in a page or a handler.
Next steps
- defineFlow: which status may move to which.
- The app/ folder:
app/shared, where enums shared by the UI and the server live.
Last updated