UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

47 lines (45 loc) • 2.13 kB
import { assert } from "./assertions.js"; //#region src/record-url.ts /** Comes between the name and the id. The name part never holds it, so the id is all that follows its first match. */ const SEPARATOR = "--"; /** The longest name part, so a long name still gives a short address. */ const MAX_NAME_LENGTH = 60; /** * A record page's path segment: the record's name and its id, such as * `belem-coast-cruiser--2d0grM08PZDtDs`. A link then shows what it opens, and * search results show a readable address. `name` is the value of the record's * name field. When it is not text, or has no letters or digits, the segment is the id. * * The route keeps one parameter for it. Read the id back with {@link recordIdFromSlug}. * * @example * <Link to="/bikes/$bikeId" params={{ bikeId: recordSlug(bike.id, bike.fields.name) }}> */ function recordSlug(id, name) { assert(id !== "", "a record id must not be empty"); const words = (typeof name === "string" ? name : "").normalize("NFKD").replace(/(\p{Script=Latin})\p{M}+/gu, "$1").normalize("NFC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu, "-"); const slug = Array.from(words).slice(0, MAX_NAME_LENGTH).join("").replace(/^-+|-+$/g, ""); if (slug !== "") return `${slug}${SEPARATOR}${id}`; return id.includes(SEPARATOR) ? `record${SEPARATOR}${id}` : id; } /** * The record id in a path segment that {@link recordSlug} made. A segment with * no name part is the id itself, so a link with a plain id still opens the page. * * @example * loader: async ({ params }) => { * const bike = await loadBike({ data: recordIdFromSlug(params.bikeId) }) * if (bike === null) throw notFound() * const slug = recordSlug(bike.id, bike.fields.name) * // One address per record: an old name or a plain id moves to the current one. * if (params.bikeId !== slug) throw redirect({ to: "/bikes/$bikeId", params: { bikeId: slug }, statusCode: 301 }) * return bike * } */ function recordIdFromSlug(segment) { const at = segment.indexOf(SEPARATOR); const id = at === -1 ? "" : segment.slice(at + 2); return id === "" ? segment : id; } //#endregion export { recordIdFromSlug, recordSlug };