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
2 changes: 1 addition & 1 deletion docs/llms-full.txt
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,7 @@ MIT
A React checkout address form for Nigeria that accepts the 11-character NIPOST digital postcode (NDAPS), such as `FC-02-A09-DB-09`. It is built with [shadcn/ui](https://ui.shadcn.com) and [`ng-postcode-js`](https://www.npmjs.com/package/ng-postcode-js), and this folder is a Next.js app that uses it.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FAdeniyikayodee%2Fng-postcode%2Ftree%2Fmain%2Ftemplates%2Fnigerian-address-form&project-name=nigerian-address-form)
[![Open in v0](https://v0.app/chat-static/button.svg)](https://v0.dev/chat/api/open?url=https%3A%2F%2Fadeniyikayodee.github.io%2Fng-postcode%2Fr%2Fnigerian-address-form.json)
[![Open in v0](https://v0.app/chat-static/button.svg)](https://v0.app/chat/api/open?url=https%3A%2F%2Fadeniyikayodee.github.io%2Fng-postcode%2Fr%2Fnigerian-address-form.json)

## Add it to your project

Expand Down
8 changes: 1 addition & 7 deletions docs/r/nigerian-address-form.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,10 @@
"ng-postcode-js@^0.4.4",
"zod@^4.6.5"
],
"registryDependencies": [
"button",
"field",
"input",
"native-select"
],
"files": [
{
"path": "components/nigerian-address-form.tsx",
"content": "\"use client\";\n\nimport { type FocusEvent, type FormEvent, useRef, useState, useSyncExternalStore, useTransition } from \"react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from \"@/components/ui/field\";\nimport { Input } from \"@/components/ui/input\";\nimport { NativeSelect, NativeSelectOption } from \"@/components/ui/native-select\";\nimport {\n type Address,\n type AddressErrors,\n type AddressInput,\n addressSchema,\n checkPostcode,\n EXAMPLE,\n fieldErrors,\n STATES,\n} from \"@/lib/nigerian-address\";\n\ntype Props = {\n /** Return field errors to show them, such as a postcode the server refused. */\n onSubmit: (address: Address) => Promise<AddressErrors | void> | AddressErrors | void;\n postcodeRequired?: boolean;\n submitLabel?: string;\n};\n\ntype Name = keyof AddressInput;\n\nconst noop = () => () => {};\n\nexport function NigerianAddressForm({ onSubmit, postcodeRequired = false, submitLabel = \"Continue\" }: Props) {\n const form = useRef<HTMLFormElement>(null);\n const [errors, setErrors] = useState<AddressErrors>({});\n const [suggestion, setSuggestion] = useState<string>();\n const [failed, setFailed] = useState(false);\n const [pending, startTransition] = useTransition();\n // Until React runs, a click would submit the address as a plain GET.\n const ready = useSyncExternalStore(noop, () => true, () => false);\n\n function show(next: AddressErrors) {\n setErrors(next);\n const first = Object.keys(next)[0];\n if (first) form.current?.querySelector<HTMLElement>(`[name=\"${first}\"]`)?.focus();\n }\n\n function checkOnBlur(event: FocusEvent<HTMLInputElement>) {\n const input = event.currentTarget;\n if (!input.value.trim()) return;\n const check = checkPostcode(input.value);\n if (check.ok) {\n input.value = check.postcode;\n return;\n }\n setSuggestion(check.suggestion);\n setErrors((current) => ({ ...current, postcode: check.error }));\n }\n\n // Cleared on edit, not on blur: a message vanishing as the customer clicks\n // \"Place order\" moves the button out from under the pointer.\n function clearOnEdit(event: FormEvent<HTMLFormElement>) {\n const { name } = event.target as HTMLInputElement;\n if (name === \"postcode\") setSuggestion(undefined);\n setErrors((current) => {\n if (!(name in current)) return current;\n const { [name as Name]: _, ...rest } = current;\n return rest;\n });\n }\n\n function applySuggestion() {\n const input = form.current?.elements.namedItem(\"postcode\");\n if (input instanceof HTMLInputElement && suggestion) {\n input.value = suggestion;\n // The button that had focus is about to go away.\n input.focus();\n }\n setSuggestion(undefined);\n setErrors(({ postcode: _, ...rest }) => rest);\n }\n\n function submit(event: FormEvent<HTMLFormElement>) {\n event.preventDefault();\n setFailed(false);\n const result = addressSchema({ postcodeRequired }).safeParse(\n Object.fromEntries(new FormData(event.currentTarget)),\n );\n if (!result.success) return show(fieldErrors(result.error));\n setErrors({});\n startTransition(async () => {\n try {\n const refused = await onSubmit(result.data);\n if (refused) show(refused);\n } catch {\n setFailed(true);\n }\n });\n }\n\n function field(name: Name) {\n const error = errors[name];\n return {\n id: name,\n name,\n \"aria-invalid\": error ? true : undefined,\n \"aria-describedby\": error ? `${name}-error` : undefined,\n };\n }\n\n function error(name: Name) {\n const message = errors[name];\n if (!message) return null;\n // Keep the example code on one line.\n const [before, after] = message.split(EXAMPLE);\n return (\n <FieldError id={`${name}-error`}>\n {after === undefined ? message : <>{before}<span className=\"whitespace-nowrap\">{EXAMPLE}</span>{after}</>}\n </FieldError>\n );\n }\n\n return (\n <form ref={form} onSubmit={submit} onChange={clearOnEdit} noValidate aria-busy={pending}>\n <FieldGroup>\n <Field data-invalid={!!errors.name}>\n <FieldLabel htmlFor=\"name\">Full name</FieldLabel>\n <Input {...field(\"name\")} autoComplete=\"name\" />\n {error(\"name\")}\n </Field>\n <Field data-invalid={!!errors.phone}>\n <FieldLabel htmlFor=\"phone\">Phone number</FieldLabel>\n <Input {...field(\"phone\")} type=\"tel\" autoComplete=\"tel\" inputMode=\"tel\" placeholder=\"0803 123 4567\" />\n {error(\"phone\")}\n </Field>\n <Field data-invalid={!!errors.street}>\n <FieldLabel htmlFor=\"street\">Street address</FieldLabel>\n <Input {...field(\"street\")} autoComplete=\"street-address\" />\n {error(\"street\")}\n </Field>\n <Field data-invalid={!!errors.city}>\n <FieldLabel htmlFor=\"city\">Town or city</FieldLabel>\n <Input {...field(\"city\")} autoComplete=\"address-level2\" />\n {error(\"city\")}\n </Field>\n <Field data-invalid={!!errors.lga}>\n <FieldLabel htmlFor=\"lga\">Local government area (optional)</FieldLabel>\n <Input {...field(\"lga\")} />\n {error(\"lga\")}\n </Field>\n <Field data-invalid={!!errors.state}>\n <FieldLabel htmlFor=\"state\">State</FieldLabel>\n <NativeSelect {...field(\"state\")} autoComplete=\"address-level1\" defaultValue=\"\" className=\"w-full\">\n <NativeSelectOption value=\"\" disabled>\n Choose a state\n </NativeSelectOption>\n {STATES.map((state) => (\n <NativeSelectOption key={state} value={state}>\n {state}\n </NativeSelectOption>\n ))}\n </NativeSelect>\n {error(\"state\")}\n </Field>\n <Field data-invalid={!!errors.postcode}>\n <FieldLabel htmlFor=\"postcode\">Postcode{postcodeRequired ? \"\" : \" (optional)\"}</FieldLabel>\n <Input\n {...field(\"postcode\")}\n autoComplete=\"postal-code\"\n autoCapitalize=\"characters\"\n autoCorrect=\"off\"\n spellCheck={false}\n maxLength={24}\n placeholder={EXAMPLE}\n onBlur={checkOnBlur}\n />\n <FieldDescription>\n The 11-character NIPOST postcode. Find yours at{\" \"}\n <a href=\"https://postcode.gov.ng/find\" target=\"_blank\" rel=\"noreferrer\">\n postcode.gov.ng\n </a>\n .\n </FieldDescription>\n {error(\"postcode\")}\n {suggestion && (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"w-fit\" onClick={applySuggestion}>\n Use {suggestion}\n </Button>\n )}\n </Field>\n {failed && <FieldError>We could not send your address. Try again.</FieldError>}\n <Button type=\"submit\" disabled={!ready || pending}>\n {pending ? \"Sending…\" : submitLabel}\n </Button>\n </FieldGroup>\n </form>\n );\n}\n",
"content": "\"use client\";\n\nimport {\n type FocusEvent,\n type FormEvent,\n type ReactNode,\n useRef,\n useState,\n useSyncExternalStore,\n useTransition,\n} from \"react\";\nimport {\n type Address,\n type AddressErrors,\n type AddressInput,\n addressSchema,\n checkPostcode,\n EXAMPLE,\n fieldErrors,\n STATES,\n} from \"@/lib/nigerian-address\";\n\ntype Props = {\n /** Return field errors to show them, such as a postcode the server refused. Without it the form only validates. */\n onSubmit?: (address: Address) => Promise<AddressErrors | void> | AddressErrors | void;\n postcodeRequired?: boolean;\n submitLabel?: string;\n};\n\ntype Name = keyof AddressInput;\n\nconst noop = () => () => {};\n\n// Plain elements styled with the shadcn theme, so the form needs no other component\n// and installs the same in every shadcn style and in v0.\nconst control =\n \"h-9 w-full rounded-md border border-input bg-transparent px-3 text-base outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30\";\nconst button =\n \"inline-flex h-9 items-center justify-center rounded-md px-4 text-sm font-medium outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50\";\n\nexport function NigerianAddressForm({ onSubmit, postcodeRequired = false, submitLabel = \"Continue\" }: Props) {\n const form = useRef<HTMLFormElement>(null);\n const [errors, setErrors] = useState<AddressErrors>({});\n const [suggestion, setSuggestion] = useState<string>();\n const [failed, setFailed] = useState(false);\n const [pending, startTransition] = useTransition();\n // Until React runs, a click would submit the address as a plain GET.\n const ready = useSyncExternalStore(noop, () => true, () => false);\n\n function show(next: AddressErrors) {\n setErrors(next);\n const first = Object.keys(next)[0];\n if (first) form.current?.querySelector<HTMLElement>(`[name=\"${first}\"]`)?.focus();\n }\n\n function checkOnBlur(event: FocusEvent<HTMLInputElement>) {\n const input = event.currentTarget;\n if (!input.value.trim()) return;\n const check = checkPostcode(input.value);\n if (check.ok) {\n input.value = check.postcode;\n return;\n }\n setSuggestion(check.suggestion);\n setErrors((current) => ({ ...current, postcode: check.error }));\n }\n\n // Cleared on edit, not on blur: a message vanishing as the customer clicks\n // \"Place order\" moves the button out from under the pointer.\n function clearOnEdit(event: FormEvent<HTMLFormElement>) {\n const { name } = event.target as HTMLInputElement;\n if (name === \"postcode\") setSuggestion(undefined);\n setErrors((current) => {\n if (!(name in current)) return current;\n const { [name as Name]: _, ...rest } = current;\n return rest;\n });\n }\n\n function applySuggestion() {\n const input = form.current?.elements.namedItem(\"postcode\");\n if (input instanceof HTMLInputElement && suggestion) {\n input.value = suggestion;\n // The button that had focus is about to go away.\n input.focus();\n }\n setSuggestion(undefined);\n setErrors(({ postcode: _, ...rest }) => rest);\n }\n\n function submit(event: FormEvent<HTMLFormElement>) {\n event.preventDefault();\n setFailed(false);\n const result = addressSchema({ postcodeRequired }).safeParse(\n Object.fromEntries(new FormData(event.currentTarget)),\n );\n if (!result.success) return show(fieldErrors(result.error));\n setErrors({});\n startTransition(async () => {\n try {\n const refused = await onSubmit?.(result.data);\n if (refused) show(refused);\n } catch {\n setFailed(true);\n }\n });\n }\n\n function field(name: Name) {\n const error = errors[name];\n return {\n id: name,\n name,\n \"aria-invalid\": error ? true : undefined,\n \"aria-describedby\": error ? `${name}-error` : undefined,\n };\n }\n\n function error(name: Name) {\n const message = errors[name];\n if (!message) return null;\n // Keep the example code on one line.\n const [before, after] = message.split(EXAMPLE);\n return (\n <p id={`${name}-error`} role=\"alert\" className=\"text-sm text-destructive\">\n {after === undefined ? message : <>{before}<span className=\"whitespace-nowrap\">{EXAMPLE}</span>{after}</>}\n </p>\n );\n }\n\n function row(name: Name, label: string, input: ReactNode, extra?: ReactNode) {\n return (\n <div className=\"grid gap-2\">\n <label htmlFor={name} className=\"text-sm font-medium\">\n {label}\n </label>\n {input}\n {extra}\n {error(name)}\n </div>\n );\n }\n\n return (\n <form ref={form} onSubmit={submit} onChange={clearOnEdit} noValidate aria-busy={pending} className=\"grid gap-5\">\n {row(\"name\", \"Full name\", <input {...field(\"name\")} autoComplete=\"name\" className={control} />)}\n {row(\n \"phone\",\n \"Phone number\",\n <input {...field(\"phone\")} type=\"tel\" autoComplete=\"tel\" inputMode=\"tel\" placeholder=\"0803 123 4567\" className={control} />,\n )}\n {row(\"street\", \"Street address\", <input {...field(\"street\")} autoComplete=\"street-address\" className={control} />)}\n {row(\"city\", \"Town or city\", <input {...field(\"city\")} autoComplete=\"address-level2\" className={control} />)}\n {row(\"lga\", \"Local government area (optional)\", <input {...field(\"lga\")} className={control} />)}\n {row(\n \"state\",\n \"State\",\n <select {...field(\"state\")} autoComplete=\"address-level1\" defaultValue=\"\" className={control}>\n <option value=\"\" disabled>\n Choose a state\n </option>\n {STATES.map((state) => (\n <option key={state} value={state}>\n {state}\n </option>\n ))}\n </select>,\n )}\n {row(\n \"postcode\",\n `Postcode${postcodeRequired ? \"\" : \" (optional)\"}`,\n <input\n {...field(\"postcode\")}\n autoComplete=\"postal-code\"\n autoCapitalize=\"characters\"\n autoCorrect=\"off\"\n spellCheck={false}\n maxLength={24}\n placeholder={EXAMPLE}\n onBlur={checkOnBlur}\n className={control}\n />,\n <p className=\"text-sm text-muted-foreground\">\n The 11-character NIPOST postcode. Find yours at{\" \"}\n <a href=\"https://postcode.gov.ng/find\" target=\"_blank\" rel=\"noreferrer\" className=\"underline\">\n postcode.gov.ng\n </a>\n .\n </p>,\n )}\n {suggestion && (\n <button type=\"button\" onClick={applySuggestion} className={`${button} -mt-3 w-fit border border-input`}>\n Use {suggestion}\n </button>\n )}\n {failed && (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n We could not send your address. Try again.\n </p>\n )}\n <button type=\"submit\" disabled={!ready || pending} className={`${button} bg-primary text-primary-foreground`}>\n {pending ? \"Sending…\" : submitLabel}\n </button>\n </form>\n );\n}\n\nexport default NigerianAddressForm;\n",
"type": "registry:component"
},
{
Expand Down
27 changes: 21 additions & 6 deletions docs/r/registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,30 @@
"type": "registry:block",
"title": "Nigerian address form",
"description": "Checkout address form for Nigeria that accepts the 11-character NIPOST digital postcode (NDAPS), such as FC-02-A09-DB-09, checked offline with ng-postcode-js.",
"dependencies": ["ng-postcode-js@^0.4.4", "zod@^4.6.5"],
"registryDependencies": ["button", "field", "input", "native-select"],
"dependencies": [
"ng-postcode-js@^0.4.4",
"zod@^4.6.5"
],
"files": [
{ "path": "components/nigerian-address-form.tsx", "type": "registry:component" },
{ "path": "lib/nigerian-address.ts", "type": "registry:lib" },
{ "path": "lib/nipost.ts", "type": "registry:lib" }
{
"path": "components/nigerian-address-form.tsx",
"type": "registry:component"
},
{
"path": "lib/nigerian-address.ts",
"type": "registry:lib"
},
{
"path": "lib/nipost.ts",
"type": "registry:lib"
}
],
"docs": "Validate again on the server with addressSchema().safeParse. To confirm a code is assigned, call isAssigned from lib/nipost.ts with nipostClient(process.env.NG_POSTCODE_API_KEY).",
"categories": ["forms", "checkout", "address"]
"categories": [
"forms",
"checkout",
"address"
]
}
]
}
2 changes: 1 addition & 1 deletion templates/nigerian-address-form/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
A React checkout address form for Nigeria that accepts the 11-character NIPOST digital postcode (NDAPS), such as `FC-02-A09-DB-09`. It is built with [shadcn/ui](https://ui.shadcn.com) and [`ng-postcode-js`](https://www.npmjs.com/package/ng-postcode-js), and this folder is a Next.js app that uses it.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FAdeniyikayodee%2Fng-postcode%2Ftree%2Fmain%2Ftemplates%2Fnigerian-address-form&project-name=nigerian-address-form)
[![Open in v0](https://v0.app/chat-static/button.svg)](https://v0.dev/chat/api/open?url=https%3A%2F%2Fadeniyikayodee.github.io%2Fng-postcode%2Fr%2Fnigerian-address-form.json)
[![Open in v0](https://v0.app/chat-static/button.svg)](https://v0.app/chat/api/open?url=https%3A%2F%2Fadeniyikayodee.github.io%2Fng-postcode%2Fr%2Fnigerian-address-form.json)

## Add it to your project

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, expect, it, vi } from "vitest";
import { NigerianAddressForm } from "./nigerian-address-form";
import Default, { NigerianAddressForm } from "./nigerian-address-form";

afterEach(cleanup);

Expand Down Expand Up @@ -96,3 +96,10 @@ it("clears an error once the customer edits the field", async () => {
await user.tab();
expect(screen.getByRole("alert").textContent).toMatch(/A postcode has 11/);
});

it("works as a default import with no props", async () => {
render(<Default />);
const user = await fill("FC-02-A09-DB-09");
await user.click(screen.getByRole("button", { name: "Continue" }));
expect(screen.queryByRole("alert")).toBeNull();
});
Loading
Loading