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.

140 lines (138 loc) • 6.35 kB
import { formatDate, formatDateTime, formatNumber } from "../formatting.js"; //#region src/fields/format.ts let registry = {}; /** * Makes the app's fields known to `fieldShape` and `formatValue`. The generated `src/softr-fields.ts` * calls it once as a side effect of being imported; the root route imports that file. */ function registerSoftrFields(fields) { registry = { ...registry, ...fields }; } /** * The shape of a field a query reads, by the alias the query holds it under. Throws when the app has * not registered its fields: the generated `src/softr-fields.ts` is not imported. */ function fieldShape(query, alias) { const fieldId = query.fields[alias]; if (fieldId === void 0) throw new Error(`The query has no field "${alias}"; it reads ${Object.keys(query.fields).join(", ")}.`); const shape = registry[query.datasourceId]?.[fieldId]; if (shape === void 0) throw new Error(`No shape is registered for field ${fieldId} of datasource ${query.datasourceId}. Import the generated src/softr-fields.ts once, in the root route, and run the SDK's codegen after a schema change.`); return shape; } /** * A value a query read, as the text a page shows it as, by the field's own type and options: money with * its symbol, a date in the app's format, a choice or a linked record by its label, a rating out of its * scale, a duration in hours and minutes, a checkbox as Yes or No. '' for a value the record does not * hold. Several values read joined by a comma. */ function formatValue(query, alias, value, formatting) { return formatField(fieldShape(query, alias), value, formatting); } /** `formatValue` for a shape in hand, such as one from `src/softr-fields.ts` or a `returnedField`. */ function formatField(shape, value, formatting) { if (value === null || value === void 0) return ""; if (Array.isArray(value)) return value.map((entry) => formatField({ ...shape, allowMultipleEntries: false }, entry, formatting)).filter((text$1) => text$1 !== "").join(", "); const returned = computedReturns(shape); if (returned !== null) return formatField(returned, value, formatting); const options = shape.options ?? {}; switch (shape.type) { case "CHECKBOX": return value === true ? "Yes" : "No"; case "NUMBER": case "COUNT": case "PROGRESS": return typeof value === "number" ? formatNumber(value, formatting, digits(precisionOf(options))) : text(value); case "AUTONUMBER": return text(value); case "CURRENCY": { if (typeof value !== "number") return text(value); const code = options.isoCode; const precision = precisionOf(options) ?? 2; const cents = { minimumFractionDigits: Number.isInteger(value) ? 0 : precision, maximumFractionDigits: precision }; if (typeof code === "string" && /^[A-Z]{3}$/.test(code)) return formatNumber(value, formatting, { style: "currency", currency: code, ...cents }); const amount = formatNumber(value, formatting, cents); const symbol = typeof options.customSymbol === "string" ? options.customSymbol : ""; if (symbol === "") return amount; return options.symbolOrCodePosition === "AFTER" ? `${amount} ${symbol}` : `${symbol}${amount}`; } case "PERCENT": return typeof value === "number" ? `${formatNumber(value, formatting, digits(precisionOf(options)))}%` : text(value); case "RATING": return typeof value === "number" ? `${value}/${numberOption(options, "max") ?? 5}` : text(value); case "DURATION": return typeof value === "number" ? formatDuration(value) : text(value); case "DATE": case "DATETIME": return isDateValue(value) ? formatDateTime(value, formatting, { dateStyle: "medium" }) : text(value); case "CREATED_AT": case "UPDATED_AT": if (!isDateValue(value)) return text(value); return options.precision === "DATE" ? formatDate(value, formatting, { dateStyle: "medium" }) : formatDateTime(value, formatting, { dateStyle: "medium" }); case "DATE_RANGE": { const range = value; return [isDateValue(range.from) ? formatDateTime(range.from, formatting, { dateStyle: "medium" }) : "", isDateValue(range.to) ? formatDateTime(range.to, formatting, { dateStyle: "medium" }) : ""].filter((part) => part !== "").join(" – "); } case "USER": { const person = value; return text(person.name ?? person.email); } case "ATTACHMENT": { const file = value; return typeof file.filename === "string" && file.filename !== "" ? file.filename : "File"; } default: if (typeof value === "object" && "label" in value) return text(value.label); return text(value); } } /** The shape a FORMULA, LOOKUP or ROLLUP reads as, when its options say; null for any other field. */ function computedReturns(shape) { if (shape.type !== "FORMULA" && shape.type !== "LOOKUP" && shape.type !== "ROLLUP") return null; const returned = shape.options?.returnedField; if (typeof returned !== "object" || returned === null || !("type" in returned) || typeof returned.type !== "string") return null; const options = "options" in returned && typeof returned.options === "object" ? returned.options : null; return { type: returned.type, options }; } function text(value) { return value === null || value === void 0 ? "" : String(value); } function isDateValue(value) { return typeof value === "string" && value !== "" || typeof value === "number" || value instanceof Date; } function numberOption(options, key) { const value = options[key]; return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0; } function precisionOf(options) { return numberOption(options, "precision"); } function digits(precision) { return precision === void 0 ? void 0 : { minimumFractionDigits: precision, maximumFractionDigits: precision }; } /** A duration, which the datasource holds in milliseconds, as hours and minutes; seconds only under an hour. */ function formatDuration(milliseconds) { const total = Math.round(milliseconds / 1e3); const hours = Math.floor(total / 3600); const minutes = Math.floor(total % 3600 / 60); const rest = total % 60; const parts = [ hours > 0 ? `${hours}h` : "", minutes > 0 ? `${minutes}m` : "", hours === 0 && rest > 0 ? `${rest}s` : "" ].filter((part) => part !== ""); return parts.length === 0 ? "0m" : parts.join(" "); } //#endregion export { fieldShape, formatDuration, formatField, formatValue, registerSoftrFields };