@rebasepro/cms 0.25.1 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.js +1 -1
- package/dist/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.d.ts +7 -1
- package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js +9 -2
- package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js.map +1 -1
- package/dist/collection_editor/useLiveSchemaEditing.js +4 -1
- package/dist/collection_editor/useLiveSchemaEditing.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/TableReferenceField.js +1 -1
- package/dist/components/CollectionTableBinding/fields/TableReferenceField.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.d.ts +1 -2
- package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/EntityTableCell.d.ts +1 -2
- package/dist/components/CollectionTableBinding/internal/EntityTableCell.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewActions.js +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewActions.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewBinding.js +2 -28
- package/dist/components/CollectionViewBinding/CollectionViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.d.ts +12 -0
- package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.js +33 -0
- package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.js.map +1 -0
- package/dist/components/CollectionsScopeContext.d.ts +5 -1
- package/dist/components/CollectionsScopeContext.js +10 -2
- package/dist/components/CollectionsScopeContext.js.map +1 -1
- package/dist/components/DefaultAppBar.js +2 -1
- package/dist/components/DefaultAppBar.js.map +1 -1
- package/dist/components/DefaultDrawer.js +19 -6
- package/dist/components/DefaultDrawer.js.map +1 -1
- package/dist/components/DefaultMissingReference.d.ts +8 -0
- package/dist/components/DefaultMissingReference.js +13 -0
- package/dist/components/DefaultMissingReference.js.map +1 -0
- package/dist/components/EntityFormPanel.d.ts +7 -2
- package/dist/components/EntityFormPanel.js +72 -29
- package/dist/components/EntityFormPanel.js.map +1 -1
- package/dist/components/HomePage/ContentHomePage.js +7 -5
- package/dist/components/HomePage/ContentHomePage.js.map +1 -1
- package/dist/components/HomePage/HomePageDnD.js +3 -1
- package/dist/components/HomePage/HomePageDnD.js.map +1 -1
- package/dist/components/HomePage/SmallNavigationCard.js +25 -0
- package/dist/components/HomePage/SmallNavigationCard.js.map +1 -0
- package/dist/components/RebaseAuthGate.js +3 -2
- package/dist/components/RebaseAuthGate.js.map +1 -1
- package/dist/components/RebaseLayout.d.ts +4 -1
- package/dist/components/RebaseLayout.js +7 -1
- package/dist/components/RebaseLayout.js.map +1 -1
- package/dist/components/RebaseShell.d.ts +4 -1
- package/dist/components/RebaseShell.js.map +1 -1
- package/dist/components/SideDialogs.js +10 -4
- package/dist/components/SideDialogs.js.map +1 -1
- package/dist/components/app/Scaffold.js +5 -1
- package/dist/components/app/Scaffold.js.map +1 -1
- package/dist/components/field_configs.js +1 -1
- package/dist/components/history/EntityHistoryView.js +6 -4
- package/dist/components/history/EntityHistoryView.js.map +1 -1
- package/dist/components/history/LastEditedByIndicator.d.ts +2 -1
- package/dist/data_export/export/export.d.ts +2 -13
- package/dist/data_export/export/export.js +1 -36
- package/dist/data_export/export/export.js.map +1 -1
- package/dist/form/EntityForm.d.ts +1 -1
- package/dist/form/EntityForm.js +17 -13
- package/dist/form/EntityForm.js.map +1 -1
- package/dist/form/EntityFormBinding.d.ts +1 -1
- package/dist/form/EntityFormBinding.js +42 -4
- package/dist/form/EntityFormBinding.js.map +1 -1
- package/dist/form/PropertyFieldBinding.js +1 -1
- package/dist/form/components/FieldBlock.d.ts +8 -1
- package/dist/form/components/FieldBlock.js +16 -2
- package/dist/form/components/FieldBlock.js.map +1 -1
- package/dist/form/components/FormSections.js +1 -1
- package/dist/form/components/FormSections.js.map +1 -1
- package/dist/form/components/LabelWithIcon.js +5 -2
- package/dist/form/components/LabelWithIcon.js.map +1 -1
- package/dist/form/field_bindings/DateTimeFieldBinding.js +2 -1
- package/dist/form/field_bindings/DateTimeFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/ReadOnlyFieldBinding.js +28 -1
- package/dist/form/field_bindings/ReadOnlyFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/RelationFieldBinding.js +7 -3
- package/dist/form/field_bindings/RelationFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/SelectFieldBinding.js +63 -42
- package/dist/form/field_bindings/SelectFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/SwitchFieldBinding.js +2 -1
- package/dist/form/field_bindings/SwitchFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/TextFieldBinding.js +8 -6
- package/dist/form/field_bindings/TextFieldBinding.js.map +1 -1
- package/dist/form/form_utils.d.ts +18 -1
- package/dist/form/form_utils.js +38 -2
- package/dist/form/form_utils.js.map +1 -1
- package/dist/form/index.d.ts +1 -1
- package/dist/form/label_placement.d.ts +23 -0
- package/dist/form/label_placement.js +71 -0
- package/dist/form/label_placement.js.map +1 -0
- package/dist/form/resolve_form_properties.d.ts +35 -3
- package/dist/form/resolve_form_properties.js +67 -6
- package/dist/form/resolve_form_properties.js.map +1 -1
- package/dist/hooks/useHistory.d.ts +5 -0
- package/dist/hooks/useHistory.js +22 -6
- package/dist/hooks/useHistory.js.map +1 -1
- package/dist/index.d.ts +50 -0
- package/dist/index.js +34 -7
- package/dist/preview/components/ReferencePreview.js +1 -1
- package/dist/preview/components/ReferencePreview.js.map +1 -1
- package/dist/preview/components/RelationPreview.js +1 -1
- package/dist/preview/components/RelationPreview.js.map +1 -1
- package/dist/types/components/EntityFormProps.d.ts +11 -0
- package/package.json +11 -10
- package/recipes/README.md +131 -0
- package/recipes/bulk-set-status.tsx +62 -0
- package/recipes/calendar-view.tsx +123 -0
- package/recipes/custom-login.tsx +60 -0
- package/recipes/my-preferences.tsx +68 -0
- package/recipes/orders-dashboard.tsx +125 -0
- package/recipes/site-settings.tsx +63 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"export.js","names":[],"sources":["../../../src/data_export/export/export.ts"],"sourcesContent":["import { Entity, EntityReference, EntityRelation, Properties, Property } from \"@rebasepro/types\";\nimport { type ArrayValuesCount, getArrayValuesCount, getValueInPath } from \"@rebasepro/utils\";\n\ninterface Header {\n key: string;\n label: string;\n}\n\nexport interface DownloadEntitiesExportParams<M extends Record<string, unknown>> {\n data: Entity<M>[];\n additionalData: Record<string, unknown>[] | undefined;\n properties: Properties;\n propertiesOrder: string[] | undefined;\n name: string;\n flattenArrays: boolean;\n additionalHeaders: string[] | undefined;\n exportType: \"csv\" | \"json\";\n dateExportType: \"timestamp\" | \"string\";\n}\n\nexport function downloadEntitiesExport<M extends Record<string, unknown>>({\n data,\n additionalData,\n properties,\n propertiesOrder,\n name,\n flattenArrays,\n additionalHeaders,\n exportType,\n dateExportType\n}: DownloadEntitiesExportParams<M>\n) {\n\n console.debug(\"Downloading export\", {\n dataLength: data.length,\n properties,\n exportType,\n dateExportType\n });\n\n if (exportType === \"csv\") {\n const writer = createCsvExportWriter({\n properties,\n propertiesOrder,\n additionalHeaders,\n flattenArrays,\n dateExportType\n });\n writer.addPage(data, additionalData);\n downloadBlob(writer.finish(), `${name}.csv`, \"text/csv\");\n } else {\n const exportableData = getEntityJsonExportableData(data, additionalData, properties, dateExportType);\n const json = JSON.stringify(exportableData, null, 2);\n downloadBlob([json], `${name}.json`, \"application/json\");\n }\n}\n\nexport function getEntityCSVExportableData(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n headers: Header[],\n dateExportType: \"timestamp\" | \"string\"\n) {\n return mergeExportRows(data, additionalData, properties, \"csv\", dateExportType)\n .map((entry) => headers.map((header) => getValueInPath(entry, header.key)));\n}\n\nexport function getEntityJsonExportableData(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n dateExportType: \"timestamp\" | \"string\"\n) {\n return mergeExportRows(data, additionalData, properties, \"json\", dateExportType);\n}\n\n/**\n * Each entity as the record its export row is read from: `id`, the processed\n * values, then `additionalData[i]` over them. An `additionalData` longer than\n * `data` adds rows of its own.\n */\nfunction mergeExportRows(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n): Record<string, unknown>[] {\n\n const mergedData: Record<string, unknown>[] = data.map(e => ({\n id: e.id,\n ...processValuesForExport(e.values, properties, exportType, dateExportType)\n }));\n\n if (additionalData) {\n additionalData.forEach((additional, index) => {\n mergedData[index] = { ...mergedData[index],\n...additional };\n });\n }\n\n return mergedData;\n}\n\n/**\n * The columns of an export, in groups: the `id`, then one group per property\n * in `propertiesOrder`, then one per additional header. A property's group is\n * the one that becomes a column per array item (`tags[0]`, `tags[1]`, …) when\n * arrays are flattened and some row holds more than one.\n */\ninterface ExportHeaderGroup {\n /** The property's key, for a property's group. */\n key?: string;\n property?: Property;\n /** The group's columns while its array is not expanded. */\n headers: Header[];\n}\n\nfunction getExportHeaderGroups(properties: Properties,\n propertiesOrder: string[] | undefined,\n additionalHeaders: string[] | undefined): ExportHeaderGroup[] {\n\n const groups: ExportHeaderGroup[] = [{ headers: [{ label: \"id\", key: \"id\" }] }];\n for (const childKey of propertiesOrder ?? Object.keys(properties)) {\n // The first column already is the id. A collection that declares its\n // key as a property named `id` wrote it twice, and the import refuses\n // a file with a duplicate header.\n if (childKey === \"id\") continue;\n const property = properties[childKey];\n if (!property) {\n console.warn(\"Property not found\", childKey, properties);\n continue;\n }\n groups.push({ key: childKey, property: property as Property, headers: getHeaders(property as Property, childKey, \"\") });\n }\n if (additionalHeaders) {\n groups.push(...additionalHeaders.map(h => ({ headers: [{ label: h, key: h }] })));\n }\n return groups;\n}\n\n/** How many columns per item the group's array spreads into, or 0 when it does not. */\nfunction expandedItemCount(group: ExportHeaderGroup, arrayValuesCount: ArrayValuesCount): number {\n if (group.key === undefined) return 0;\n const count = arrayValuesCount[group.key];\n return count > 1 ? count : 0;\n}\n\n/** The group's columns for array item `index`. */\nfunction itemHeaders(group: ExportHeaderGroup, index: number): Header[] {\n return getHeaders(group.property as Property, `${group.key}[${index}]`, \"\");\n}\n\nfunction headersOf(groups: ExportHeaderGroup[], arrayValuesCount: ArrayValuesCount): Header[] {\n return groups.flatMap((group) => {\n const count = expandedItemCount(group, arrayValuesCount);\n return count > 0\n ? Array.from({ length: count }, (_, i) => itemHeaders(group, i)).flat()\n : group.headers;\n });\n}\n\nfunction rowCells(entry: Record<string, unknown>, headers: Header[]): string[] {\n return headers.map((header) => toCSVCell(getValueInPath(entry, header.key)));\n}\n\nexport interface CsvExportWriterParams {\n properties: Properties;\n propertiesOrder: string[] | undefined;\n additionalHeaders: string[] | undefined;\n flattenArrays: boolean;\n dateExportType: \"timestamp\" | \"string\";\n}\n\n/**\n * Writes a CSV export one page of entities at a time.\n *\n * An export used to hold every entity it read, then a copy of every row, then\n * an array of cells per row, then the row strings — about 211 MB at its peak\n * for 100,000 rows × 20 columns, for a 32 MB file. Each page is now turned\n * into its CSV text as it arrives and its entities are let go; what is held\n * is the text itself.\n *\n * The file is the one the in-memory export wrote, byte for byte. What makes\n * that work across pages is `flattenArrays`: the columns an array spreads into\n * (`tags[0]` … `tags[n-1]`) depend on the longest array in *any* row, which\n * an early page cannot know. So a page is written with the columns known when\n * it arrives, and a row also keeps the cells of any array items those columns\n * leave out. At the end, a page written with fewer columns than the file has\n * is re-cut: its cells copied, and an array's swapped for, or extended with,\n * the kept item cells (or empty ones). Usually the longest array is met in the\n * first page and nothing is re-cut. A property key with `.` or `[` in it\n * resolves through other properties when spread, so an export with one keeps\n * its rows' records and writes them at the end, as before.\n */\nexport interface CsvExportWriter {\n /** One page of entities, with their additional-column values index for index. */\n addPage(data: Entity<Record<string, unknown>>[], additionalData?: Record<string, unknown>[]): void;\n /** The whole file, header row first. Once: the pages are handed over. */\n finish(): BlobPart[];\n}\n\n/**\n * A row's cells for the items of one array that its page's columns leave out,\n * kept in case the file has columns for them. The cells of items `0…n-1` in\n * one string, for an array its page did not spread; otherwise one string per\n * item, a hole where an item is not kept or its cells are all empty.\n */\ntype RowItemCells = string | (string | undefined)[];\n\ninterface CsvExportPage {\n /** The rows, `\\r\\n` after each. */\n text: string;\n rows: number;\n /** Per group, the items its array was spread into on this page; 0 when not spread. */\n spread: number[];\n /** By `row * groups + group`, for the rows that hold items `spread` leaves out. */\n items?: (RowItemCells | undefined)[];\n /** The rows' records, when the export cannot be re-cut (see the writer). */\n entries?: Record<string, unknown>[];\n}\n\nexport function createCsvExportWriter({\n properties,\n propertiesOrder,\n additionalHeaders,\n flattenArrays,\n dateExportType\n}: CsvExportWriterParams): CsvExportWriter {\n\n const groups = getExportHeaderGroups(properties, propertiesOrder, additionalHeaders);\n // The columns of item `i` of each group, built once per item, not per row.\n const itemHeaderCache: Header[][][] = groups.map(() => []);\n const headersOfItem = (groupIndex: number, index: number): Header[] =>\n itemHeaderCache[groupIndex][index] ??= itemHeaders(groups[groupIndex], index);\n // Cells per item; a group with none (a map with no properties) spreads\n // into no columns at all.\n const itemWidths = groups.map((group, groupIndex) => group.key === undefined ? 0 : headersOfItem(groupIndex, 0).length);\n const arrayValuesCount: ArrayValuesCount = {};\n // A key the spread column's path would read through some other property.\n const keepEntries = flattenArrays && groups.some((group) => group.key !== undefined && /[.[\\]]/.test(group.key));\n const pages: CsvExportPage[] = [];\n\n return {\n addPage(data, additionalData) {\n if (flattenArrays) {\n // Merged by maximum, which is what one pass over every row\n // computes.\n for (const [key, count] of Object.entries(getArrayValuesCount(data.map(d => d.values)))) {\n arrayValuesCount[key] = Math.max(arrayValuesCount[key] || 0, count);\n }\n }\n const spread = groups.map((group) => expandedItemCount(group, arrayValuesCount));\n const entries = mergeExportRows(data, additionalData, properties, \"csv\", dateExportType);\n if (keepEntries) {\n pages.push({ text: \"\", rows: entries.length, spread, entries });\n return;\n }\n const headers = headersOf(groups, arrayValuesCount);\n const lines: string[] = [];\n let items: CsvExportPage[\"items\"];\n entries.forEach((entry, row) => {\n lines.push(rowCells(entry, headers).join(\",\") + \"\\r\\n\");\n if (!flattenArrays) return;\n const bracketed = bracketedKeyIndices(entry);\n groups.forEach((group, groupIndex) => {\n if (group.key === undefined || itemWidths[groupIndex] === 0) return;\n const written = spread[groupIndex];\n const indices = itemIndicesWithValues(entry, group.key, bracketed)\n .filter((index) => index >= written);\n if (indices.length === 0) return;\n const value = entry[group.key];\n let cells: RowItemCells;\n if (written === 0 && Array.isArray(value) && indices.length === value.length) {\n cells = value.map((_, index) => rowCells(entry, headersOfItem(groupIndex, index)).join(\",\")).join(\",\");\n } else {\n cells = [];\n for (const index of indices) {\n cells[index] = rowCells(entry, headersOfItem(groupIndex, index)).join(\",\");\n }\n }\n (items ??= [])[row * groups.length + groupIndex] = cells;\n });\n });\n pages.push({ text: lines.join(\"\"), rows: entries.length, spread, items });\n },\n\n finish() {\n const counts = flattenArrays ? arrayValuesCount : {};\n const headers = headersOf(groups, counts);\n const parts: BlobPart[] = [entryToCSVRow(headers.map(h => h.label))];\n const spread = groups.map((group) => expandedItemCount(group, counts));\n\n // Handed over a page at a time, so a re-cut page and the text it\n // was cut from are not both held for the whole file.\n for (let page = pages.shift(); page; page = pages.shift()) {\n if (page.entries) {\n parts.push(page.entries.map((entry) => rowCells(entry, headers).join(\",\") + \"\\r\\n\").join(\"\"));\n } else if (page.spread.every((count, groupIndex) => count === spread[groupIndex])) {\n parts.push(page.text);\n } else {\n parts.push(recutPage(page, groups, spread, itemWidths));\n }\n }\n return parts;\n }\n };\n}\n\n/**\n * The record's own keys spelled `key[i]…`, by `key`: `getValueInPath` reads\n * one of those for the cell `key[i]` before anything else. Almost never there.\n */\nfunction bracketedKeyIndices(entry: Record<string, unknown>): Map<string, number[]> | undefined {\n let found: Map<string, number[]> | undefined;\n for (const own of Object.keys(entry)) {\n if (!own.includes(\"[\")) continue;\n const match = /^(.*?)\\[(\\d+)\\]/.exec(own);\n if (!match) continue;\n found ??= new Map();\n const indices = found.get(match[1]) ?? [];\n indices.push(Number(match[2]));\n found.set(match[1], indices);\n }\n return found;\n}\n\nconst NO_INDICES: number[] = [];\n\n/**\n * The array items of `entry[key]` whose spread cells may not all be empty —\n * every other item's are, as `getValueInPath` reads `key[i]` and\n * `key[i].child`: an array's own items, an object's own integer-named keys\n * (read as `key[i]` too), and a key of the record spelled `key[i]…` itself.\n * Over-including is harmless; the cells are computed, not assumed.\n */\nfunction itemIndicesWithValues(entry: Record<string, unknown>,\n key: string,\n bracketed: Map<string, number[]> | undefined): number[] {\n const value = entry[key];\n const extra = bracketed?.get(key);\n if (!extra) {\n // The common cases, without building a set per cell.\n if (Array.isArray(value)) return value.map((_, i) => i);\n if (value === null || typeof value !== \"object\") return NO_INDICES;\n }\n const indices = new Set<number>();\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) indices.add(i);\n } else if (value !== null && typeof value === \"object\") {\n for (const own of Object.getOwnPropertyNames(value)) {\n const match = /^(\\d+)(?:$|[.[])/.exec(own);\n if (match) indices.add(Number(match[1]));\n }\n }\n extra?.forEach((index) => indices.add(index));\n return [...indices];\n}\n\n/**\n * A page written with fewer columns than the file has, cut back into cells\n * and written again: each array the file spreads further than the page did\n * gets its kept item cells, or empty ones.\n */\nfunction recutPage(page: CsvExportPage, groups: ExportHeaderGroup[], spread: number[], itemWidths: number[]): string {\n const text = page.text;\n const out: string[] = [];\n let pos = 0;\n for (let row = 0; row < page.rows; row++) {\n const cells: string[] = [];\n let first = true;\n groups.forEach((group, groupIndex) => {\n const written = page.spread[groupIndex];\n const itemWidth = itemWidths[groupIndex];\n const width = written > 0 ? written * itemWidth : group.headers.length;\n const groupCells: string[] = [];\n for (let c = 0; c < width; c++) {\n if (!first) pos++; // the comma before every cell but the row's first\n first = false;\n const end = csvCellEnd(text, pos);\n groupCells.push(text.slice(pos, end));\n pos = end;\n }\n const count = spread[groupIndex];\n if (count === written) {\n cells.push(...groupCells);\n return;\n }\n // Spread further than the page was: the items it wrote stay.\n if (written > 0) cells.push(...groupCells);\n const items = page.items?.[row * groups.length + groupIndex];\n const dense = typeof items === \"string\" ? splitCsvCells(items) : undefined;\n for (let i = written; i < count; i++) {\n const itemCells = dense\n ? dense.slice(i * itemWidth, (i + 1) * itemWidth)\n : (typeof items === \"object\" && items[i] !== undefined ? splitCsvCells(items[i] as string) : []);\n for (let c = 0; c < itemWidth; c++) cells.push(itemCells[c] ?? \"\");\n }\n });\n pos += 2; // \"\\r\\n\"\n out.push(cells.join(\",\") + \"\\r\\n\");\n }\n return out.join(\"\");\n}\n\n/** The cells of a run of them joined with commas, as `toCSVCell` wrote them. */\nfunction splitCsvCells(text: string): string[] {\n const cells: string[] = [];\n let pos = 0;\n for (; ;) {\n const end = csvCellEnd(text, pos);\n cells.push(text.slice(pos, end));\n if (end >= text.length) return cells;\n pos = end + 1;\n }\n}\n\n/**\n * Where the cell starting at `start` ends. Every cell `toCSVCell` writes is\n * either empty or quoted with its own quotes doubled, so the next lone quote\n * closes it.\n */\nfunction csvCellEnd(text: string, start: number): number {\n if (text.charCodeAt(start) !== 34 /* \" */) return start;\n let i = start + 1;\n for (; ;) {\n const quote = text.indexOf(\"\\\"\", i);\n if (quote < 0) return text.length;\n if (text.charCodeAt(quote + 1) === 34) {\n i = quote + 2;\n } else {\n return quote + 1;\n }\n }\n}\n\n/**\n * Get headers for property. There could be more than one header per property\n * @param property\n * @param propertyKey\n * @param prefix\n */\nfunction getHeaders(property: Property, propertyKey: string, prefix = \"\"): Header[] {\n const currentKey = prefix ? `${prefix}.${propertyKey}` : propertyKey;\n if (property.type === \"map\" && property.properties) {\n return Object.entries(property.properties)\n .map(([childKey, p]) => getHeaders(p, childKey, currentKey))\n .flat();\n } else {\n return [{\n label: currentKey,\n key: currentKey\n }];\n }\n}\n\n/**\n * Read whatever a `date` column actually arrived as into a `Date`.\n *\n * The driver/WebSocket path revives `{ __type: \"date\" }` into a `Date`; the REST\n * path — which is the one the admin is on — leaves an ISO string, and an epoch\n * number is what a re-imported export carries. Returns `undefined` for anything\n * that is not a date, so the caller can pass the raw value through.\n */\nfunction toExportableDate(inputValue: unknown): Date | undefined {\n if (inputValue instanceof Date) return Number.isNaN(inputValue.getTime()) ? undefined : inputValue;\n if (typeof inputValue === \"number\" && Number.isFinite(inputValue)) return new Date(inputValue);\n if (typeof inputValue === \"string\" && inputValue.trim() !== \"\") {\n const parsed = new Date(inputValue);\n return Number.isNaN(parsed.getTime()) ? undefined : parsed;\n }\n return undefined;\n}\n\n/**\n * The id a relation value points at, for a relation property's value — an\n * `EntityRelation`, or the same thing still in its `{ __type: \"relation\" }`\n * wire form. `undefined` for anything else, so a bare foreign key passes\n * through as the id it already is.\n */\nfunction relationIdForExport(value: unknown): string | number | undefined {\n if (value instanceof EntityRelation) return value.id;\n if (typeof value === \"object\" && value !== null\n && \"__type\" in value && value.__type === \"relation\"\n && \"id\" in value && (typeof value.id === \"string\" || typeof value.id === \"number\")) {\n return value.id;\n }\n return undefined;\n}\n\nfunction processValueForExport(inputValue: unknown,\n property: Property,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n): unknown {\n\n let value: unknown;\n if (property.type === \"relation\") {\n // A relation is exported as the id it points at — what the import\n // writes back — rather than the view-model object the admin holds,\n // which a CSV cell printed as `[object Object]`. To-many relations\n // are arrays of them.\n const toId = (item: unknown) => relationIdForExport(item) ?? item;\n value = Array.isArray(inputValue) ? inputValue.map(toId) : toId(inputValue);\n } else if (property.type === \"map\" && property.properties) {\n value = processValuesForExport(inputValue as Record<string, unknown>, property.properties as Properties, exportType, dateExportType);\n } else if (property.type === \"array\") {\n if (property.of && Array.isArray(inputValue)) {\n if (Array.isArray(property.of)) {\n value = property.of.map((p, i) => processValueForExport(inputValue[i], p, exportType, dateExportType));\n } else if (property.of.type === \"map\") {\n value = exportType === \"csv\"\n ? inputValue.map((e) => JSON.stringify(e))\n : inputValue.map((e) => processValueForExport(e, property.of as Property, exportType, dateExportType));\n ;\n } else {\n value = inputValue.map((e) => processValueForExport(e, property.of as Property, exportType, dateExportType));\n }\n } else {\n value = inputValue;\n }\n } else if (property.type === \"reference\" && inputValue && typeof inputValue === \"object\" && \"isEntityReference\" in inputValue && typeof (inputValue as EntityReference).isEntityReference === \"function\" && (inputValue as EntityReference).isEntityReference()) {\n const ref = inputValue ? inputValue as EntityReference : undefined;\n value = ref ? ref.fullPath : null;\n } else if (property.type === \"date\") {\n // Not `instanceof Date`: the admin reads over REST, and the REST row\n // pipeline hands dates back as the database wrote them — a string. That\n // made this branch dead on every live export, so both radio options\n // produced identical files. Normalise here, where the declared type says\n // the column is a date, and leave anything unparseable untouched rather\n // than exporting an invalid date as `null`.\n const date = toExportableDate(inputValue);\n value = date\n ? (dateExportType === \"timestamp\" ? date.getTime() : date.toISOString())\n : inputValue;\n } else {\n value = inputValue;\n }\n\n return value;\n}\n\nfunction processValuesForExport<M extends Record<string, unknown>>\n (inputValues: Record<string, unknown>,\n properties: Properties,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n ): Record<string, unknown> {\n // One accumulator. Merging `{ [key]: value }` objects pairwise copied the\n // whole row once per property — the square of the property count, per row.\n const result: Record<string, unknown> = { ...inputValues };\n for (const [key, property] of Object.entries(properties)) {\n const inputValue = inputValues && (inputValues)[key];\n const updatedValue = processValueForExport(inputValue, property as Property, exportType, dateExportType);\n if (updatedValue === undefined) continue;\n if (key === \"__proto__\") {\n // An own property, as the object spread made it, not the prototype.\n Object.defineProperty(result, key, { value: updatedValue, enumerable: true, writable: true, configurable: true });\n } else {\n result[key] = updatedValue;\n }\n }\n return result;\n}\n\n/**\n * Characters that make a spreadsheet read a cell as a formula rather than text.\n *\n * Quoting is CSV *escaping* and is not enough: Excel, LibreOffice Calc and\n * Sheets strip the CSV quoting at parse time and then evaluate a cell whose\n * first character is one of these — `=HYPERLINK(…)` exfiltrates neighbouring\n * cells on click, `=cmd|'…'!A0` is worse.\n */\nconst FORMULA_TRIGGERS = [\"=\", \"+\", \"-\", \"@\", \"\\t\", \"\\r\"];\n\n/**\n * Neutralise a cell that a spreadsheet would otherwise evaluate, by prefixing a\n * single quote — the standard OWASP mitigation. The apostrophe is consumed by\n * the spreadsheet as \"treat the rest as text\", so the value reads back intact.\n */\nexport function escapeCsvFormula(value: string): string {\n const first = value.charAt(0);\n if (!FORMULA_TRIGGERS.includes(first)) return value;\n // A signed number is not a formula, and prefixing it would turn every\n // negative amount in the file into text. `-1+1` is still neutralised,\n // because it is not a number.\n if ((first === \"-\" || first === \"+\") && value.trim() !== \"\" && Number.isFinite(Number(value))) return value;\n return \"'\" + value;\n}\n\n/**\n * The inverse of {@link escapeCsvFormula}, for a file read back in: a cell that\n * is an apostrophe followed by a formula trigger loses the apostrophe, as it\n * does when a spreadsheet reads it. Any other apostrophe is text.\n */\nexport function unescapeCsvFormula(value: string): string {\n return value.charAt(0) === \"'\" && FORMULA_TRIGGERS.includes(value.charAt(1))\n ? value.slice(1)\n : value;\n}\n\nfunction toCSVCell(v: unknown): string {\n if (v === null || v === undefined) return \"\";\n // An array or object (a geopoint, a value no property declares) is written\n // as its JSON: `String()` of an object is `[object Object]`. Date\n // properties are normalised before they get here.\n const s = Array.isArray(v) || (typeof v === \"object\" && !(v instanceof Date))\n ? JSON.stringify(v)\n : String(v);\n return \"\\\"\" + escapeCsvFormula(s).replaceAll(\"\\\"\", \"\\\"\\\"\") + \"\\\"\";\n}\n\nexport function entryToCSVRow(entry: unknown[]) {\n return entry\n .map(toCSVCell)\n .join(\",\") + \"\\r\\n\";\n}\n\nexport function downloadBlob(content: BlobPart[], filename: string, contentType: string) {\n const blob = new Blob(content, { type: contentType });\n const url = URL.createObjectURL(blob);\n const pom = document.createElement(\"a\");\n pom.href = url;\n pom.setAttribute(\"download\", filename);\n pom.click();\n // Unrevoked, the URL kept the whole file in memory until the tab closed —\n // one more copy per export. The download holds its own reference once it\n // has started; the delay covers browsers that start it a moment after\n // `click()` returns.\n setTimeout(() => URL.revokeObjectURL(url), BLOB_URL_LIFETIME_MS);\n}\n\n/** How long an export's object URL outlives the click that downloads it. */\nconst BLOB_URL_LIFETIME_MS = 10_000;\n\nexport function downloadDataAsCsv(data: object[], name: string) {\n if (data.length === 0) return;\n\n const headers = Object.keys(data[0]);\n const csvContent = [\n headers.join(\",\"),\n ...data.map(row => headers.map(header => toCSVCell((row as Record<string, unknown>)[header])).join(\",\"))\n ].join(\"\\r\\n\");\n\n downloadBlob([csvContent], `${name}.csv`, \"text/csv\");\n}\n"],"mappings":";;;AAoBA,SAAgB,uBAA0D,EACtE,MACA,gBACA,YACA,iBACA,MACA,eACA,mBACA,YACA,kBAEF;CAEE,QAAQ,MAAM,sBAAsB;EAChC,YAAY,KAAK;EACjB;EACA;EACA;CACJ,CAAC;CAED,IAAI,eAAe,OAAO;EACtB,MAAM,SAAS,sBAAsB;GACjC;GACA;GACA;GACA;GACA;EACJ,CAAC;EACD,OAAO,QAAQ,MAAM,cAAc;EACnC,aAAa,OAAO,OAAO,GAAG,GAAG,KAAK,OAAO,UAAU;CAC3D,OAAO;EACH,MAAM,iBAAiB,4BAA4B,MAAM,gBAAgB,YAAY,cAAc;EAEnG,aAAa,CADA,KAAK,UAAU,gBAAgB,MAAM,CACpC,CAAI,GAAG,GAAG,KAAK,QAAQ,kBAAkB;CAC3D;AACJ;AAEA,SAAgB,2BAA2B,MACvC,gBACA,YACA,SACA,gBACF;CACE,OAAO,gBAAgB,MAAM,gBAAgB,YAAY,OAAO,cAAc,CAAC,CAC1E,KAAK,UAAU,QAAQ,KAAK,WAAW,eAAe,OAAO,OAAO,GAAG,CAAC,CAAC;AAClF;AAEA,SAAgB,4BAA4B,MACxC,gBACA,YACA,gBACF;CACE,OAAO,gBA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CAAC,IACb;AACV;AAEA,SAAS,UAAU,GAAoB;CACnC,IAAI,MAAM,QAAQ,MAAM,KAAA,GAAW,OAAO;CAO1C,OAAO,OAAO,iBAHJ,MAAM,QAAQ,CAAC,KAAM,OAAO,MAAM,YAAY,EAAE,aAAa,QACjE,KAAK,UAAU,CAAC,IAChB,OAAO,CAAC,CACkB,CAAC,CAAC,WAAW,MAAM,MAAM,IAAI;AACjE;AAEA,SAAgB,cAAc,OAAkB;CAC5C,OAAO,MACF,IAAI,SAAS,CAAC,CACd,KAAK,GAAG,IAAI;AACrB;AAEA,SAAgB,aAAa,SAAqB,UAAkB,aAAqB;CACrF,MAAM,OAAO,IAAI,KAAK,SAAS,EAAE,MAAM,YAAY,CAAC;CACpD,MAAM,MAAM,IAAI,gBAAgB,IAAI;CACpC,MAAM,MAAM,SAAS,cAAc,GAAG;CACtC,IAAI,OAAO;CACX,IAAI,aAAa,YAAY,QAAQ;CACrC,IAAI,MAAM;CAKV,iBAAiB,IAAI,gBAAgB,GAAG,GAAG,oBAAoB;AACnE;;AAGA,IAAM,uBAAuB;AAE7B,SAAgB,kBAAkB,MAAgB,MAAc;CAC5D,IAAI,KAAK,WAAW,GAAG;CAEvB,MAAM,UAAU,OAAO,KAAK,KAAK,EAAE;CAMnC,aAAa,CALM,CACf,QAAQ,KAAK,GAAG,GAChB,GAAG,KAAK,KAAI,QAAO,QAAQ,KAAI,WAAU,UAAW,IAAgC,OAAO,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAC3G,CAAC,CAAC,KAAK,MAEO,CAAU,GAAG,GAAG,KAAK,OAAO,UAAU;AACxD"}
|
|
1
|
+
{"version":3,"file":"export.js","names":[],"sources":["../../../src/data_export/export/export.ts"],"sourcesContent":["import { Entity, EntityReference, EntityRelation, Properties, Property } from \"@rebasepro/types\";\nimport { type ArrayValuesCount, escapeCsvFormula, getArrayValuesCount, getValueInPath, unescapeCsvFormula } from \"@rebasepro/utils\";\n\ninterface Header {\n key: string;\n label: string;\n}\n\nexport interface DownloadEntitiesExportParams<M extends Record<string, unknown>> {\n data: Entity<M>[];\n additionalData: Record<string, unknown>[] | undefined;\n properties: Properties;\n propertiesOrder: string[] | undefined;\n name: string;\n flattenArrays: boolean;\n additionalHeaders: string[] | undefined;\n exportType: \"csv\" | \"json\";\n dateExportType: \"timestamp\" | \"string\";\n}\n\nexport function downloadEntitiesExport<M extends Record<string, unknown>>({\n data,\n additionalData,\n properties,\n propertiesOrder,\n name,\n flattenArrays,\n additionalHeaders,\n exportType,\n dateExportType\n}: DownloadEntitiesExportParams<M>\n) {\n\n console.debug(\"Downloading export\", {\n dataLength: data.length,\n properties,\n exportType,\n dateExportType\n });\n\n if (exportType === \"csv\") {\n const writer = createCsvExportWriter({\n properties,\n propertiesOrder,\n additionalHeaders,\n flattenArrays,\n dateExportType\n });\n writer.addPage(data, additionalData);\n downloadBlob(writer.finish(), `${name}.csv`, \"text/csv\");\n } else {\n const exportableData = getEntityJsonExportableData(data, additionalData, properties, dateExportType);\n const json = JSON.stringify(exportableData, null, 2);\n downloadBlob([json], `${name}.json`, \"application/json\");\n }\n}\n\nexport function getEntityCSVExportableData(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n headers: Header[],\n dateExportType: \"timestamp\" | \"string\"\n) {\n return mergeExportRows(data, additionalData, properties, \"csv\", dateExportType)\n .map((entry) => headers.map((header) => getValueInPath(entry, header.key)));\n}\n\nexport function getEntityJsonExportableData(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n dateExportType: \"timestamp\" | \"string\"\n) {\n return mergeExportRows(data, additionalData, properties, \"json\", dateExportType);\n}\n\n/**\n * Each entity as the record its export row is read from: `id`, the processed\n * values, then `additionalData[i]` over them. An `additionalData` longer than\n * `data` adds rows of its own.\n */\nfunction mergeExportRows(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n): Record<string, unknown>[] {\n\n const mergedData: Record<string, unknown>[] = data.map(e => ({\n id: e.id,\n ...processValuesForExport(e.values, properties, exportType, dateExportType)\n }));\n\n if (additionalData) {\n additionalData.forEach((additional, index) => {\n mergedData[index] = { ...mergedData[index],\n...additional };\n });\n }\n\n return mergedData;\n}\n\n/**\n * The columns of an export, in groups: the `id`, then one group per property\n * in `propertiesOrder`, then one per additional header. A property's group is\n * the one that becomes a column per array item (`tags[0]`, `tags[1]`, …) when\n * arrays are flattened and some row holds more than one.\n */\ninterface ExportHeaderGroup {\n /** The property's key, for a property's group. */\n key?: string;\n property?: Property;\n /** The group's columns while its array is not expanded. */\n headers: Header[];\n}\n\nfunction getExportHeaderGroups(properties: Properties,\n propertiesOrder: string[] | undefined,\n additionalHeaders: string[] | undefined): ExportHeaderGroup[] {\n\n const groups: ExportHeaderGroup[] = [{ headers: [{ label: \"id\", key: \"id\" }] }];\n for (const childKey of propertiesOrder ?? Object.keys(properties)) {\n // The first column already is the id. A collection that declares its\n // key as a property named `id` wrote it twice, and the import refuses\n // a file with a duplicate header.\n if (childKey === \"id\") continue;\n const property = properties[childKey];\n if (!property) {\n console.warn(\"Property not found\", childKey, properties);\n continue;\n }\n groups.push({ key: childKey, property: property as Property, headers: getHeaders(property as Property, childKey, \"\") });\n }\n if (additionalHeaders) {\n groups.push(...additionalHeaders.map(h => ({ headers: [{ label: h, key: h }] })));\n }\n return groups;\n}\n\n/** How many columns per item the group's array spreads into, or 0 when it does not. */\nfunction expandedItemCount(group: ExportHeaderGroup, arrayValuesCount: ArrayValuesCount): number {\n if (group.key === undefined) return 0;\n const count = arrayValuesCount[group.key];\n return count > 1 ? count : 0;\n}\n\n/** The group's columns for array item `index`. */\nfunction itemHeaders(group: ExportHeaderGroup, index: number): Header[] {\n return getHeaders(group.property as Property, `${group.key}[${index}]`, \"\");\n}\n\nfunction headersOf(groups: ExportHeaderGroup[], arrayValuesCount: ArrayValuesCount): Header[] {\n return groups.flatMap((group) => {\n const count = expandedItemCount(group, arrayValuesCount);\n return count > 0\n ? Array.from({ length: count }, (_, i) => itemHeaders(group, i)).flat()\n : group.headers;\n });\n}\n\nfunction rowCells(entry: Record<string, unknown>, headers: Header[]): string[] {\n return headers.map((header) => toCSVCell(getValueInPath(entry, header.key)));\n}\n\nexport interface CsvExportWriterParams {\n properties: Properties;\n propertiesOrder: string[] | undefined;\n additionalHeaders: string[] | undefined;\n flattenArrays: boolean;\n dateExportType: \"timestamp\" | \"string\";\n}\n\n/**\n * Writes a CSV export one page of entities at a time.\n *\n * An export used to hold every entity it read, then a copy of every row, then\n * an array of cells per row, then the row strings — about 211 MB at its peak\n * for 100,000 rows × 20 columns, for a 32 MB file. Each page is now turned\n * into its CSV text as it arrives and its entities are let go; what is held\n * is the text itself.\n *\n * The file is the one the in-memory export wrote, byte for byte. What makes\n * that work across pages is `flattenArrays`: the columns an array spreads into\n * (`tags[0]` … `tags[n-1]`) depend on the longest array in *any* row, which\n * an early page cannot know. So a page is written with the columns known when\n * it arrives, and a row also keeps the cells of any array items those columns\n * leave out. At the end, a page written with fewer columns than the file has\n * is re-cut: its cells copied, and an array's swapped for, or extended with,\n * the kept item cells (or empty ones). Usually the longest array is met in the\n * first page and nothing is re-cut. A property key with `.` or `[` in it\n * resolves through other properties when spread, so an export with one keeps\n * its rows' records and writes them at the end, as before.\n */\nexport interface CsvExportWriter {\n /** One page of entities, with their additional-column values index for index. */\n addPage(data: Entity<Record<string, unknown>>[], additionalData?: Record<string, unknown>[]): void;\n /** The whole file, header row first. Once: the pages are handed over. */\n finish(): BlobPart[];\n}\n\n/**\n * A row's cells for the items of one array that its page's columns leave out,\n * kept in case the file has columns for them. The cells of items `0…n-1` in\n * one string, for an array its page did not spread; otherwise one string per\n * item, a hole where an item is not kept or its cells are all empty.\n */\ntype RowItemCells = string | (string | undefined)[];\n\ninterface CsvExportPage {\n /** The rows, `\\r\\n` after each. */\n text: string;\n rows: number;\n /** Per group, the items its array was spread into on this page; 0 when not spread. */\n spread: number[];\n /** By `row * groups + group`, for the rows that hold items `spread` leaves out. */\n items?: (RowItemCells | undefined)[];\n /** The rows' records, when the export cannot be re-cut (see the writer). */\n entries?: Record<string, unknown>[];\n}\n\nexport function createCsvExportWriter({\n properties,\n propertiesOrder,\n additionalHeaders,\n flattenArrays,\n dateExportType\n}: CsvExportWriterParams): CsvExportWriter {\n\n const groups = getExportHeaderGroups(properties, propertiesOrder, additionalHeaders);\n // The columns of item `i` of each group, built once per item, not per row.\n const itemHeaderCache: Header[][][] = groups.map(() => []);\n const headersOfItem = (groupIndex: number, index: number): Header[] =>\n itemHeaderCache[groupIndex][index] ??= itemHeaders(groups[groupIndex], index);\n // Cells per item; a group with none (a map with no properties) spreads\n // into no columns at all.\n const itemWidths = groups.map((group, groupIndex) => group.key === undefined ? 0 : headersOfItem(groupIndex, 0).length);\n const arrayValuesCount: ArrayValuesCount = {};\n // A key the spread column's path would read through some other property.\n const keepEntries = flattenArrays && groups.some((group) => group.key !== undefined && /[.[\\]]/.test(group.key));\n const pages: CsvExportPage[] = [];\n\n return {\n addPage(data, additionalData) {\n if (flattenArrays) {\n // Merged by maximum, which is what one pass over every row\n // computes.\n for (const [key, count] of Object.entries(getArrayValuesCount(data.map(d => d.values)))) {\n arrayValuesCount[key] = Math.max(arrayValuesCount[key] || 0, count);\n }\n }\n const spread = groups.map((group) => expandedItemCount(group, arrayValuesCount));\n const entries = mergeExportRows(data, additionalData, properties, \"csv\", dateExportType);\n if (keepEntries) {\n pages.push({ text: \"\", rows: entries.length, spread, entries });\n return;\n }\n const headers = headersOf(groups, arrayValuesCount);\n const lines: string[] = [];\n let items: CsvExportPage[\"items\"];\n entries.forEach((entry, row) => {\n lines.push(rowCells(entry, headers).join(\",\") + \"\\r\\n\");\n if (!flattenArrays) return;\n const bracketed = bracketedKeyIndices(entry);\n groups.forEach((group, groupIndex) => {\n if (group.key === undefined || itemWidths[groupIndex] === 0) return;\n const written = spread[groupIndex];\n const indices = itemIndicesWithValues(entry, group.key, bracketed)\n .filter((index) => index >= written);\n if (indices.length === 0) return;\n const value = entry[group.key];\n let cells: RowItemCells;\n if (written === 0 && Array.isArray(value) && indices.length === value.length) {\n cells = value.map((_, index) => rowCells(entry, headersOfItem(groupIndex, index)).join(\",\")).join(\",\");\n } else {\n cells = [];\n for (const index of indices) {\n cells[index] = rowCells(entry, headersOfItem(groupIndex, index)).join(\",\");\n }\n }\n (items ??= [])[row * groups.length + groupIndex] = cells;\n });\n });\n pages.push({ text: lines.join(\"\"), rows: entries.length, spread, items });\n },\n\n finish() {\n const counts = flattenArrays ? arrayValuesCount : {};\n const headers = headersOf(groups, counts);\n const parts: BlobPart[] = [entryToCSVRow(headers.map(h => h.label))];\n const spread = groups.map((group) => expandedItemCount(group, counts));\n\n // Handed over a page at a time, so a re-cut page and the text it\n // was cut from are not both held for the whole file.\n for (let page = pages.shift(); page; page = pages.shift()) {\n if (page.entries) {\n parts.push(page.entries.map((entry) => rowCells(entry, headers).join(\",\") + \"\\r\\n\").join(\"\"));\n } else if (page.spread.every((count, groupIndex) => count === spread[groupIndex])) {\n parts.push(page.text);\n } else {\n parts.push(recutPage(page, groups, spread, itemWidths));\n }\n }\n return parts;\n }\n };\n}\n\n/**\n * The record's own keys spelled `key[i]…`, by `key`: `getValueInPath` reads\n * one of those for the cell `key[i]` before anything else. Almost never there.\n */\nfunction bracketedKeyIndices(entry: Record<string, unknown>): Map<string, number[]> | undefined {\n let found: Map<string, number[]> | undefined;\n for (const own of Object.keys(entry)) {\n if (!own.includes(\"[\")) continue;\n const match = /^(.*?)\\[(\\d+)\\]/.exec(own);\n if (!match) continue;\n found ??= new Map();\n const indices = found.get(match[1]) ?? [];\n indices.push(Number(match[2]));\n found.set(match[1], indices);\n }\n return found;\n}\n\nconst NO_INDICES: number[] = [];\n\n/**\n * The array items of `entry[key]` whose spread cells may not all be empty —\n * every other item's are, as `getValueInPath` reads `key[i]` and\n * `key[i].child`: an array's own items, an object's own integer-named keys\n * (read as `key[i]` too), and a key of the record spelled `key[i]…` itself.\n * Over-including is harmless; the cells are computed, not assumed.\n */\nfunction itemIndicesWithValues(entry: Record<string, unknown>,\n key: string,\n bracketed: Map<string, number[]> | undefined): number[] {\n const value = entry[key];\n const extra = bracketed?.get(key);\n if (!extra) {\n // The common cases, without building a set per cell.\n if (Array.isArray(value)) return value.map((_, i) => i);\n if (value === null || typeof value !== \"object\") return NO_INDICES;\n }\n const indices = new Set<number>();\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) indices.add(i);\n } else if (value !== null && typeof value === \"object\") {\n for (const own of Object.getOwnPropertyNames(value)) {\n const match = /^(\\d+)(?:$|[.[])/.exec(own);\n if (match) indices.add(Number(match[1]));\n }\n }\n extra?.forEach((index) => indices.add(index));\n return [...indices];\n}\n\n/**\n * A page written with fewer columns than the file has, cut back into cells\n * and written again: each array the file spreads further than the page did\n * gets its kept item cells, or empty ones.\n */\nfunction recutPage(page: CsvExportPage, groups: ExportHeaderGroup[], spread: number[], itemWidths: number[]): string {\n const text = page.text;\n const out: string[] = [];\n let pos = 0;\n for (let row = 0; row < page.rows; row++) {\n const cells: string[] = [];\n let first = true;\n groups.forEach((group, groupIndex) => {\n const written = page.spread[groupIndex];\n const itemWidth = itemWidths[groupIndex];\n const width = written > 0 ? written * itemWidth : group.headers.length;\n const groupCells: string[] = [];\n for (let c = 0; c < width; c++) {\n if (!first) pos++; // the comma before every cell but the row's first\n first = false;\n const end = csvCellEnd(text, pos);\n groupCells.push(text.slice(pos, end));\n pos = end;\n }\n const count = spread[groupIndex];\n if (count === written) {\n cells.push(...groupCells);\n return;\n }\n // Spread further than the page was: the items it wrote stay.\n if (written > 0) cells.push(...groupCells);\n const items = page.items?.[row * groups.length + groupIndex];\n const dense = typeof items === \"string\" ? splitCsvCells(items) : undefined;\n for (let i = written; i < count; i++) {\n const itemCells = dense\n ? dense.slice(i * itemWidth, (i + 1) * itemWidth)\n : (typeof items === \"object\" && items[i] !== undefined ? splitCsvCells(items[i] as string) : []);\n for (let c = 0; c < itemWidth; c++) cells.push(itemCells[c] ?? \"\");\n }\n });\n pos += 2; // \"\\r\\n\"\n out.push(cells.join(\",\") + \"\\r\\n\");\n }\n return out.join(\"\");\n}\n\n/** The cells of a run of them joined with commas, as `toCSVCell` wrote them. */\nfunction splitCsvCells(text: string): string[] {\n const cells: string[] = [];\n let pos = 0;\n for (; ;) {\n const end = csvCellEnd(text, pos);\n cells.push(text.slice(pos, end));\n if (end >= text.length) return cells;\n pos = end + 1;\n }\n}\n\n/**\n * Where the cell starting at `start` ends. Every cell `toCSVCell` writes is\n * either empty or quoted with its own quotes doubled, so the next lone quote\n * closes it.\n */\nfunction csvCellEnd(text: string, start: number): number {\n if (text.charCodeAt(start) !== 34 /* \" */) return start;\n let i = start + 1;\n for (; ;) {\n const quote = text.indexOf(\"\\\"\", i);\n if (quote < 0) return text.length;\n if (text.charCodeAt(quote + 1) === 34) {\n i = quote + 2;\n } else {\n return quote + 1;\n }\n }\n}\n\n/**\n * Get headers for property. There could be more than one header per property\n * @param property\n * @param propertyKey\n * @param prefix\n */\nfunction getHeaders(property: Property, propertyKey: string, prefix = \"\"): Header[] {\n const currentKey = prefix ? `${prefix}.${propertyKey}` : propertyKey;\n if (property.type === \"map\" && property.properties) {\n return Object.entries(property.properties)\n .map(([childKey, p]) => getHeaders(p, childKey, currentKey))\n .flat();\n } else {\n return [{\n label: currentKey,\n key: currentKey\n }];\n }\n}\n\n/**\n * Read whatever a `date` column actually arrived as into a `Date`.\n *\n * The driver/WebSocket path revives `{ __type: \"date\" }` into a `Date`; the REST\n * path — which is the one the admin is on — leaves an ISO string, and an epoch\n * number is what a re-imported export carries. Returns `undefined` for anything\n * that is not a date, so the caller can pass the raw value through.\n */\nfunction toExportableDate(inputValue: unknown): Date | undefined {\n if (inputValue instanceof Date) return Number.isNaN(inputValue.getTime()) ? undefined : inputValue;\n if (typeof inputValue === \"number\" && Number.isFinite(inputValue)) return new Date(inputValue);\n if (typeof inputValue === \"string\" && inputValue.trim() !== \"\") {\n const parsed = new Date(inputValue);\n return Number.isNaN(parsed.getTime()) ? undefined : parsed;\n }\n return undefined;\n}\n\n/**\n * The id a relation value points at, for a relation property's value — an\n * `EntityRelation`, or the same thing still in its `{ __type: \"relation\" }`\n * wire form. `undefined` for anything else, so a bare foreign key passes\n * through as the id it already is.\n */\nfunction relationIdForExport(value: unknown): string | number | undefined {\n if (value instanceof EntityRelation) return value.id;\n if (typeof value === \"object\" && value !== null\n && \"__type\" in value && value.__type === \"relation\"\n && \"id\" in value && (typeof value.id === \"string\" || typeof value.id === \"number\")) {\n return value.id;\n }\n return undefined;\n}\n\nfunction processValueForExport(inputValue: unknown,\n property: Property,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n): unknown {\n\n let value: unknown;\n if (property.type === \"relation\") {\n // A relation is exported as the id it points at — what the import\n // writes back — rather than the view-model object the admin holds,\n // which a CSV cell printed as `[object Object]`. To-many relations\n // are arrays of them.\n const toId = (item: unknown) => relationIdForExport(item) ?? item;\n value = Array.isArray(inputValue) ? inputValue.map(toId) : toId(inputValue);\n } else if (property.type === \"map\" && property.properties) {\n value = processValuesForExport(inputValue as Record<string, unknown>, property.properties as Properties, exportType, dateExportType);\n } else if (property.type === \"array\") {\n if (property.of && Array.isArray(inputValue)) {\n if (Array.isArray(property.of)) {\n value = property.of.map((p, i) => processValueForExport(inputValue[i], p, exportType, dateExportType));\n } else if (property.of.type === \"map\") {\n value = exportType === \"csv\"\n ? inputValue.map((e) => JSON.stringify(e))\n : inputValue.map((e) => processValueForExport(e, property.of as Property, exportType, dateExportType));\n ;\n } else {\n value = inputValue.map((e) => processValueForExport(e, property.of as Property, exportType, dateExportType));\n }\n } else {\n value = inputValue;\n }\n } else if (property.type === \"reference\" && inputValue && typeof inputValue === \"object\" && \"isEntityReference\" in inputValue && typeof (inputValue as EntityReference).isEntityReference === \"function\" && (inputValue as EntityReference).isEntityReference()) {\n const ref = inputValue ? inputValue as EntityReference : undefined;\n value = ref ? ref.fullPath : null;\n } else if (property.type === \"date\") {\n // Not `instanceof Date`: the admin reads over REST, and the REST row\n // pipeline hands dates back as the database wrote them — a string. That\n // made this branch dead on every live export, so both radio options\n // produced identical files. Normalise here, where the declared type says\n // the column is a date, and leave anything unparseable untouched rather\n // than exporting an invalid date as `null`.\n const date = toExportableDate(inputValue);\n value = date\n ? (dateExportType === \"timestamp\" ? date.getTime() : date.toISOString())\n : inputValue;\n } else {\n value = inputValue;\n }\n\n return value;\n}\n\nfunction processValuesForExport<M extends Record<string, unknown>>\n (inputValues: Record<string, unknown>,\n properties: Properties,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n ): Record<string, unknown> {\n // One accumulator. Merging `{ [key]: value }` objects pairwise copied the\n // whole row once per property — the square of the property count, per row.\n const result: Record<string, unknown> = { ...inputValues };\n for (const [key, property] of Object.entries(properties)) {\n const inputValue = inputValues && (inputValues)[key];\n const updatedValue = processValueForExport(inputValue, property as Property, exportType, dateExportType);\n if (updatedValue === undefined) continue;\n if (key === \"__proto__\") {\n // An own property, as the object spread made it, not the prototype.\n Object.defineProperty(result, key, { value: updatedValue, enumerable: true, writable: true, configurable: true });\n } else {\n result[key] = updatedValue;\n }\n }\n return result;\n}\n\n// One rule for every CSV the product writes — here, the SQL console's export\n// and the server's streamed download: `@rebasepro/utils`' csv helpers.\nexport { escapeCsvFormula, unescapeCsvFormula };\n\nfunction toCSVCell(v: unknown): string {\n if (v === null || v === undefined) return \"\";\n // An array or object (a geopoint, a value no property declares) is written\n // as its JSON: `String()` of an object is `[object Object]`. Date\n // properties are normalised before they get here.\n const s = Array.isArray(v) || (typeof v === \"object\" && !(v instanceof Date))\n ? JSON.stringify(v)\n : String(v);\n return \"\\\"\" + escapeCsvFormula(s).replaceAll(\"\\\"\", \"\\\"\\\"\") + \"\\\"\";\n}\n\nexport function entryToCSVRow(entry: unknown[]) {\n return entry\n .map(toCSVCell)\n .join(\",\") + \"\\r\\n\";\n}\n\nexport function downloadBlob(content: BlobPart[], filename: string, contentType: string) {\n const blob = new Blob(content, { type: contentType });\n const url = URL.createObjectURL(blob);\n const pom = document.createElement(\"a\");\n pom.href = url;\n pom.setAttribute(\"download\", filename);\n pom.click();\n // Unrevoked, the URL kept the whole file in memory until the tab closed —\n // one more copy per export. The download holds its own reference once it\n // has started; the delay covers browsers that start it a moment after\n // `click()` returns.\n setTimeout(() => URL.revokeObjectURL(url), BLOB_URL_LIFETIME_MS);\n}\n\n/** How long an export's object URL outlives the click that downloads it. */\nconst BLOB_URL_LIFETIME_MS = 10_000;\n\nexport function downloadDataAsCsv(data: object[], name: string) {\n if (data.length === 0) return;\n\n const headers = Object.keys(data[0]);\n const csvContent = [\n headers.join(\",\"),\n ...data.map(row => headers.map(header => toCSVCell((row as Record<string, unknown>)[header])).join(\",\"))\n ].join(\"\\r\\n\");\n\n downloadBlob([csvContent], `${name}.csv`, \"text/csv\");\n}\n"],"mappings":";;;AAoBA,SAAgB,uBAA0D,EACtE,MACA,gBACA,YACA,iBACA,MACA,eACA,mBACA,YACA,kBAEF;CAEE,QAAQ,MAAM,sBAAsB;EAChC,YAAY,KAAK;EACjB;EACA;EACA;CACJ,CAAC;CAED,IAAI,eAAe,OAAO;EACtB,MAAM,SAAS,sBAAsB;GACjC;GACA;GACA;GACA;GACA;EACJ,CAAC;EACD,OAAO,QAAQ,MAAM,cAAc;EACnC,aAAa,OAAO,OAAO,GAAG,GAAG,KAAK,OAAO,UAAU;CAC3D,OAAO;EACH,MAAM,iBAAiB,4BAA4B,MAAM,gBAAgB,YAAY,cAAc;EAEnG,aAAa,CADA,KAAK,UAAU,gBAAgB,MAAM,CACpC,CAAI,GAAG,GAAG,KAAK,QAAQ,kBAAkB;CAC3D;AACJ;AAEA,SAAgB,2BAA2B,MACvC,gBACA,YACA,SACA,gBACF;CACE,OAAO,gBAAgB,MAAM,gBAAgB,YAAY,OAAO,cAAc,CAAC,CAC1E,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IAAI;AACrB;AAEA,SAAgB,aAAa,SAAqB,UAAkB,aAAqB;CACrF,MAAM,OAAO,IAAI,KAAK,SAAS,EAAE,MAAM,YAAY,CAAC;CACpD,MAAM,MAAM,IAAI,gBAAgB,IAAI;CACpC,MAAM,MAAM,SAAS,cAAc,GAAG;CACtC,IAAI,OAAO;CACX,IAAI,aAAa,YAAY,QAAQ;CACrC,IAAI,MAAM;CAKV,iBAAiB,IAAI,gBAAgB,GAAG,GAAG,oBAAoB;AACnE;;AAGA,IAAM,uBAAuB;AAE7B,SAAgB,kBAAkB,MAAgB,MAAc;CAC5D,IAAI,KAAK,WAAW,GAAG;CAEvB,MAAM,UAAU,OAAO,KAAK,KAAK,EAAE;CAMnC,aAAa,CALM,CACf,QAAQ,KAAK,GAAG,GAChB,GAAG,KAAK,KAAI,QAAO,QAAQ,KAAI,WAAU,UAAW,IAAgC,OAAO,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAC3G,CAAC,CAAC,KAAK,MAEO,CAAU,GAAG,GAAG,KAAK,OAAO,UAAU;AACxD"}
|
|
@@ -9,4 +9,4 @@ import type { EntityFormProps } from "../types/components/EntityFormProps.js";
|
|
|
9
9
|
*
|
|
10
10
|
* @group Components
|
|
11
11
|
*/
|
|
12
|
-
export declare function EntityForm<M extends Record<string, unknown>>({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode, formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent, showDefaultActions, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }: EntityFormProps<M>): React.JSX.Element;
|
|
12
|
+
export declare function EntityForm<M extends Record<string, unknown>>({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode, formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent, showDefaultActions, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, lockedPropertyKeys, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }: EntityFormProps<M>): React.JSX.Element;
|
package/dist/form/EntityForm.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { FieldBlock, isSelfLabellingProperty, spanClass } from "./components/FieldBlock.js";
|
|
2
|
+
import { labelsInsideControl } from "./label_placement.js";
|
|
2
3
|
import { AdditionalFieldValue } from "../components/AdditionalFieldValue.js";
|
|
3
4
|
import { FormRail, RecordMeta } from "./components/FormRail.js";
|
|
4
5
|
import { FormSections } from "./components/FormSections.js";
|
|
5
6
|
import { useRailVisible } from "./components/useRailVisible.js";
|
|
6
|
-
import { resolveFormProperty, resolvePropertiesForValidation } from "./resolve_form_properties.js";
|
|
7
|
+
import { formViewer, resolveFormProperty, resolvePropertiesForValidation, withoutUnwritableDefaults } from "./resolve_form_properties.js";
|
|
7
8
|
import { FormUploadsContext, createFormUploadTracker } from "./form_uploads.js";
|
|
8
9
|
import { applyValueTransforms, getEntitySchema, uniqueValueErrors } from "./validation.js";
|
|
9
10
|
import { PropertyFieldBinding } from "./PropertyFieldBinding.js";
|
|
@@ -17,7 +18,7 @@ import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "rea
|
|
|
17
18
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
18
19
|
import { deepEqual } from "fast-equals";
|
|
19
20
|
import { Alert, AlignLeftIcon, Button, CircularProgressCenter, Dialog, DialogActions, DialogContent, DialogTitle, ErrorBoundary, Typography, cls, defaultBorderMixin, isKeyHandled, paperMixin, useDebouncedCallback } from "@rebasepro/ui";
|
|
20
|
-
import { getCopyValues, getDefaultValuesFor } from "@rebasepro/common";
|
|
21
|
+
import { effectiveAccess, getCopyValues, getDefaultValuesFor } from "@rebasepro/common";
|
|
21
22
|
import { flattenKeys, getFormFieldKeys, isDisabled, isHidden, isReadOnly, resolveFormLayout, useAuthController, useCustomizationController, useRebaseContext, useTranslation } from "@rebasepro/app";
|
|
22
23
|
import { Formex, useCreateFormex } from "@rebasepro/forms";
|
|
23
24
|
//#region src/form/EntityForm.tsx
|
|
@@ -30,10 +31,11 @@ import { Formex, useCreateFormex } from "@rebasepro/forms";
|
|
|
30
31
|
*
|
|
31
32
|
* @group Components
|
|
32
33
|
*/
|
|
33
|
-
function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode = "full_screen", formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent = EntityFormActions, showDefaultActions = true, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }) {
|
|
34
|
+
function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode = "full_screen", formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent = EntityFormActions, showDefaultActions = true, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, lockedPropertyKeys, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }) {
|
|
34
35
|
const navigateBack = useCallback(() => {
|
|
35
36
|
if (navigateBackProp) navigateBackProp();
|
|
36
37
|
}, [navigateBackProp]);
|
|
38
|
+
const authController = useAuthController();
|
|
37
39
|
const [status, setStatus] = useState(initialStatus);
|
|
38
40
|
const updateStatus = (status) => {
|
|
39
41
|
setStatus(status);
|
|
@@ -228,7 +230,7 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
|
|
|
228
230
|
const lastSavedValues = useRef(baseInitialValues);
|
|
229
231
|
const save = async (values) => {
|
|
230
232
|
const writtenValues = applyValueTransforms(values, collection.properties);
|
|
231
|
-
const valuesToSave = status === "existing" ? getChangedProperties(writtenValues, entity?.values || {}) : status === "new" ? withoutUnsetNulls(writtenValues, baseInitialValues) : writtenValues;
|
|
233
|
+
const valuesToSave = status === "existing" ? getChangedProperties(writtenValues, entity?.values || {}) : withoutUnwritableDefaults(status === "new" ? withoutUnsetNulls(writtenValues, baseInitialValues) : writtenValues, baseInitialValues, collection.properties, formViewer(authController));
|
|
232
234
|
if (status === "existing" && Object.keys(valuesToSave).length === 0 && entity) return Promise.resolve(entity);
|
|
233
235
|
lastSavedValues.current = values;
|
|
234
236
|
if (!onSubmitProp) return;
|
|
@@ -343,7 +345,6 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
|
|
|
343
345
|
if (uniqueFieldValidatorProp) return uniqueFieldValidatorProp;
|
|
344
346
|
return defaultUniqueFieldValidator;
|
|
345
347
|
}, [uniqueFieldValidatorProp, defaultUniqueFieldValidator]);
|
|
346
|
-
const authController = useAuthController();
|
|
347
348
|
const customizationController = useCustomizationController();
|
|
348
349
|
const { t } = useTranslation();
|
|
349
350
|
async function validationErrorsFor(values) {
|
|
@@ -448,18 +449,19 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
|
|
|
448
449
|
if (status !== "new" && status !== "copy") return void 0;
|
|
449
450
|
return [...layout.sections.flatMap((s) => s.fields), ...layout.sidebar].find((field) => {
|
|
450
451
|
const property = collection.properties?.[field.key];
|
|
451
|
-
return property ? !isFieldDisabled(property) : false;
|
|
452
|
+
return property ? !isFieldDisabled(field.key, property) : false;
|
|
452
453
|
})?.key;
|
|
453
454
|
}, [
|
|
454
455
|
layout,
|
|
455
456
|
collection,
|
|
456
457
|
status,
|
|
457
|
-
disabledProp
|
|
458
|
+
disabledProp,
|
|
459
|
+
lockedPropertyKeys
|
|
458
460
|
]);
|
|
459
|
-
function isFieldDisabled(property) {
|
|
461
|
+
function isFieldDisabled(key, property) {
|
|
460
462
|
const isNew = status === "new" || status === "copy";
|
|
461
463
|
const isIdAndAuto = (property.type === "string" || property.type === "number") && "isId" in property && typeof property.isId === "string" && property.isId !== "manual";
|
|
462
|
-
return Boolean(disabledProp || !autoSave && formex.isSubmitting || isReadOnly(property) || isDisabled(property) || !isNew && "isId" in property && Boolean(property.isId) || isNew && isIdAndAuto);
|
|
464
|
+
return Boolean(disabledProp || !autoSave && formex.isSubmitting || isReadOnly(property) || isDisabled(property) || !isNew && "isId" in property && Boolean(property.isId) || isNew && isIdAndAuto || isNew && lockedPropertyKeys?.includes(key));
|
|
463
465
|
}
|
|
464
466
|
const renderField = (field) => {
|
|
465
467
|
if (field.additional) {
|
|
@@ -497,7 +499,7 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
|
|
|
497
499
|
console.warn(`Property ${field.key} not found in collection ${collection.name} in properties or additional fields. Skipping.`);
|
|
498
500
|
return null;
|
|
499
501
|
}
|
|
500
|
-
if (property.conditions?.hidden) {
|
|
502
|
+
if (property.conditions?.hidden || effectiveAccess(property)) {
|
|
501
503
|
const shown = resolveFormProperty({
|
|
502
504
|
propertyKey: field.key,
|
|
503
505
|
property,
|
|
@@ -512,14 +514,15 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
|
|
|
512
514
|
if (!shown || isHidden(shown)) return null;
|
|
513
515
|
}
|
|
514
516
|
const underlyingValueHasChanged = field.key in underlyingChanges && !deepEqual(formex.values[field.key], underlyingChanges[field.key]);
|
|
515
|
-
const disabled = isFieldDisabled(property);
|
|
517
|
+
const disabled = isFieldDisabled(field.key, property);
|
|
516
518
|
const selfLabelling = isSelfLabellingProperty(property);
|
|
519
|
+
const labelInside = !selfLabelling && labelsInsideControl(property, customizationController.propertyConfigs);
|
|
517
520
|
const cmsFormFieldProps = {
|
|
518
521
|
propertyKey: field.key,
|
|
519
522
|
disabled,
|
|
520
523
|
property,
|
|
521
524
|
includeDescription: false,
|
|
522
|
-
hideLabel: !selfLabelling,
|
|
525
|
+
hideLabel: !selfLabelling && !labelInside,
|
|
523
526
|
underlyingValueHasChanged: underlyingValueHasChanged && !autoSave,
|
|
524
527
|
context: fieldContext,
|
|
525
528
|
partOfArray: false,
|
|
@@ -532,7 +535,8 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
|
|
|
532
535
|
children: /* @__PURE__ */ jsx(FieldBlock, {
|
|
533
536
|
propertyKey: field.key,
|
|
534
537
|
property,
|
|
535
|
-
showLabel: !selfLabelling,
|
|
538
|
+
showLabel: !selfLabelling && !labelInside,
|
|
539
|
+
labelInside,
|
|
536
540
|
children: /* @__PURE__ */ jsx(PropertyFieldBinding, { ...cmsFormFieldProps })
|
|
537
541
|
})
|
|
538
542
|
}, `field_${field.key}`);
|