@rebasepro/cms 0.29.2 → 0.30.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/components/CollectionTableBinding/fields/TableStorageUpload.js +1 -1
- package/dist/components/CollectionTableBinding/fields/TableStorageUpload.js.map +1 -1
- package/dist/components/EntityPreviewBinding.d.ts +20 -0
- package/dist/components/EntityPreviewBinding.js +121 -18
- package/dist/components/EntityPreviewBinding.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -1
- package/dist/mcp_view/bridge.d.ts +21 -1
- package/dist/mcp_view/bridge.js.map +1 -1
- package/dist/mcp_view/index.d.ts +7 -7
- package/dist/mcp_view/index.js +6 -1
- package/dist/mcp_view/index.js.map +1 -1
- package/dist/mcp_view/screen.d.ts +6 -4
- package/dist/mcp_view/screen.js +14 -42
- package/dist/mcp_view/screen.js.map +1 -1
- package/dist/mcp_view/tool_driver.d.ts +33 -0
- package/dist/mcp_view/tool_driver.js +186 -85
- package/dist/mcp_view/tool_driver.js.map +1 -1
- package/dist/mcp_view/write_review.d.ts +35 -0
- package/dist/mcp_view/write_review.js +144 -0
- package/dist/mcp_view/write_review.js.map +1 -0
- package/dist/preview/components/RelationPreview.js +7 -2
- package/dist/preview/components/RelationPreview.js.map +1 -1
- package/dist/saved_apps/SavedAppsView.d.ts +17 -0
- package/dist/saved_apps/SavedAppsView.js +167 -0
- package/dist/saved_apps/SavedAppsView.js.map +1 -0
- package/dist/saved_apps/admin_apps_client.d.ts +24 -0
- package/dist/saved_apps/admin_apps_client.js +46 -0
- package/dist/saved_apps/admin_apps_client.js.map +1 -0
- package/dist/saved_apps/saved_app_frame.d.ts +20 -0
- package/dist/saved_apps/saved_app_frame.js +143 -0
- package/dist/saved_apps/saved_app_frame.js.map +1 -0
- package/package.json +9 -9
|
@@ -156,7 +156,7 @@ function StorageUpload({ property, name, internalValue, setInternalValue, openPo
|
|
|
156
156
|
}
|
|
157
157
|
function TableStorageItemPreview({ propertyKey, property, value, size, entity }) {
|
|
158
158
|
return /* @__PURE__ */ jsx("div", {
|
|
159
|
-
className: "relative p-2 max-w-full",
|
|
159
|
+
className: "relative p-2 max-w-full shrink-0",
|
|
160
160
|
children: value && /* @__PURE__ */ jsx(ErrorBoundary, { children: /* @__PURE__ */ jsx(PropertyPreview, {
|
|
161
161
|
propertyKey,
|
|
162
162
|
value,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TableStorageUpload.js","names":[],"sources":["../../../../src/components/CollectionTableBinding/fields/TableStorageUpload.tsx"],"sourcesContent":["import type { ArrayProperty, StringProperty } from \"@rebasepro/types\";\nimport * as React from \"react\";\nimport { useMemo } from \"react\";\n\nimport { Entity, StorageConfig } from \"@rebasepro/types\";\nimport { PreviewSize } from \"../../../types\";\nimport { useDropzone } from \"react-dropzone\";\nimport { PropertyPreview } from \"../../../preview\";\nimport { ErrorBoundary } from \"@rebasepro/ui\";\nimport { cls, IconButton, PencilIcon, Typography } from \"@rebasepro/ui\";\nimport { useSnackbarController, useStorageSource, useTranslation, StorageFieldItem, useStorageUploadController, StorageSourceContext } from \"@rebasepro/app\";\nimport { getThumbnailMeasure } from \"../../../preview/util\";\nimport { StorageUploadProgress } from \"../../../form/components/StorageUploadProgress\";\nimport { useCollectionRegistryController } from \"../../../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { EntityTableCellActions } from \"../internal/EntityTableCellActions\";\n\nconst dropZoneClasses = \"max-w-full box-border relative pt-[2px] items-center border border-transparent outline-hidden rounded-md duration-200 ease-[cubic-bezier(0.4,0,0.2,1)] focus:border-primary\";\nconst activeDropClasses = \"pt-0 border-2 border-solid\"\nconst acceptDropClasses = \"transition-colors duration-200 ease-[cubic-bezier(0,0,0.2,1)] border-2 border-solid border-green-500 bg-green-50 dark:bg-green-900\"\nconst rejectDropClasses = \"transition-colors duration-200 ease-[cubic-bezier(0,0,0.2,1)] border-2 border-solid border-red-500 bg-red-50 dark:bg-red-900\"\n\n/**\n * Field that allows to upload files to Google Cloud Storage.\n *\n * This is one of the internal components that get mapped natively inside forms\n * and tables to the specified properties.\n * @group Form fields\n */\nexport function TableStorageUpload(props: {\n propertyKey: string;\n error: Error | undefined;\n disabled: boolean;\n value: string | string[] | null;\n updateValue: (newValue: (string | string[] | null)) => void;\n selected: boolean;\n focused: boolean;\n property: StringProperty | ArrayProperty;\n entity: Entity<Record<string, unknown>>;\n path: string;\n previewSize: PreviewSize;\n openPopup?: (cellRect?: DOMRect) => void;\n onBlur?: React.FocusEventHandler<HTMLInputElement | HTMLTextAreaElement>;\n}) {\n\n const {\n propertyKey,\n error,\n selected,\n openPopup,\n value,\n disabled,\n property,\n entity,\n path,\n previewSize,\n updateValue\n } = props;\n\n const storageSource = useStorageSource();\n const collectionSlug = useCollectionRegistryController().getCollection(path)?.slug;\n\n const {\n internalValue,\n setInternalValue,\n onFilesAdded,\n storage,\n onFileUploadComplete,\n storagePathBuilder,\n multipleFilesSupported,\n resolvedStorageSource\n } = useStorageUploadController({\n entityValues: entity.values,\n entityId: entity.id,\n path,\n collectionSlug,\n property: property as StringProperty,\n propertyKey,\n storageSource,\n onChange: updateValue,\n value,\n disabled\n });\n\n return (\n\n <StorageSourceContext.Provider value={resolvedStorageSource}>\n <StorageUpload\n internalValue={internalValue}\n setInternalValue={setInternalValue}\n name={propertyKey}\n disabled={disabled}\n autoFocus={false}\n openPopup={openPopup}\n error={error}\n selected={selected}\n property={property}\n onChange={updateValue}\n entity={entity}\n storagePathBuilder={storagePathBuilder}\n storage={storage}\n multipleFilesSupported={multipleFilesSupported}\n onFilesAdded={onFilesAdded}\n onFileUploadComplete={onFileUploadComplete}\n previewSize={previewSize}/>\n </StorageSourceContext.Provider>\n\n );\n}\n\ninterface StorageUploadProps {\n internalValue: StorageFieldItem[];\n setInternalValue: (v: StorageFieldItem[]) => void;\n name: string;\n error?: Error;\n property: StringProperty | ArrayProperty;\n onChange: (value: string | string[] | null) => void;\n multipleFilesSupported: boolean;\n autoFocus: boolean;\n selected: boolean;\n disabled: boolean;\n entity: Entity<Record<string, unknown>>;\n previewSize: PreviewSize;\n storage: StorageConfig;\n onFilesAdded: (acceptedFiles: File[]) => void;\n storagePathBuilder: (file: File) => string;\n openPopup?: (cellRect?: DOMRect) => void;\n onFileUploadComplete: (uploadedPath: string, entry: StorageFieldItem, fileMetadata?: Record<string, unknown>) => Promise<void>;\n}\n\nfunction StorageUpload({\n property,\n name,\n internalValue,\n setInternalValue,\n openPopup,\n entity,\n selected,\n error,\n onChange,\n multipleFilesSupported,\n previewSize: previewSizeInput,\n disabled,\n autoFocus,\n storage,\n onFilesAdded,\n onFileUploadComplete,\n storagePathBuilder\n}: StorageUploadProps) {\n\n const previewSize = previewSizeInput;\n if (multipleFilesSupported) {\n const arrayProperty = property as ArrayProperty;\n if (Array.isArray(arrayProperty.of)) {\n throw Error(\"Using array properties instead of single one in `of` in ArrayProperty\");\n }\n if (arrayProperty.of) {\n if (arrayProperty.of.type !== \"string\") {\n throw Error(\"Storage field using array must be of data type string\");\n }\n } else {\n throw Error(\"Storage field using array must be of data type string\");\n }\n }\n\n const metadata: Record<string, unknown> | undefined = storage?.metadata;\n const hasValue = Boolean(internalValue);\n\n const snackbarContext = useSnackbarController();\n const { t } = useTranslation();\n\n const {\n open,\n getRootProps,\n getInputProps,\n isDragActive,\n isDragAccept,\n isDragReject\n } = useDropzone({\n accept: storage.acceptedFiles ? storage.acceptedFiles.map(e => ({ [e]: [] })).reduce((a, b) => ({ ...a,\n...b }), {}) : undefined,\n disabled,\n maxSize: storage.maxSize,\n noClick: true,\n noKeyboard: true,\n onDrop: onFilesAdded,\n onDropRejected: (fileRejections, event) => {\n for (const fileRejection of fileRejections) {\n for (const error of fileRejection.errors) {\n console.error(\"Error uploading file: \", error);\n if (error.code === \"file-too-large\") {\n snackbarContext.open({\n type: \"error\",\n message: t(\"error_uploading_file_size\", { maxSize: String(storage.maxSize) })\n });\n } else if (error.code === \"file-invalid-type\") {\n snackbarContext.open({\n type: \"error\",\n message: t(\"error_uploading_file_type\")\n });\n }\n }\n }\n }\n }\n );\n\n const { ...rootProps } = getRootProps();\n\n const helpText = multipleFilesSupported\n ? t(\"drag_drop_files\")\n : t(\"drag_drop_file\");\n\n const renderProperty = multipleFilesSupported\n ? (property as ArrayProperty).of as StringProperty\n : property as StringProperty;\n\n const imageSize = useMemo(() => getThumbnailMeasure(previewSize), [previewSize]);\n const showError = !disabled && error;\n\n return (\n <div {...rootProps}\n className={cls(dropZoneClasses,\n \"relative w-full h-full flex\",\n `justify-${hasValue ? \"start\" : \"center\"}`,\n isDragActive ? activeDropClasses : \"\",\n isDragAccept ? acceptDropClasses : \"\",\n isDragReject ? rejectDropClasses : \"\"\n )}\n >\n\n <input autoFocus={autoFocus} {...getInputProps()}/>\n\n {internalValue.map((entry, index) => {\n let child;\n if (entry.storagePathOrDownloadUrl) {\n child = (\n <TableStorageItemPreview\n key={`storage_preview_${index}`}\n propertyKey={name}\n property={renderProperty}\n value={entry.storagePathOrDownloadUrl}\n entity={entity}\n size={previewSize}/>\n );\n } else if (entry.file) {\n child = (\n <StorageUploadProgress\n key={`storage_progress_${index}`}\n entry={entry}\n metadata={metadata}\n storagePath={storagePathBuilder(entry.file)}\n onFileUploadComplete={onFileUploadComplete}\n imageSize={imageSize}\n simple={true}\n />\n );\n }\n\n return child;\n })}\n\n {!internalValue && <div\n className=\"grow m-2 max-w-[200px]\"\n onClick={open}>\n <Typography\n className=\"text-surface-400 dark:text-surface-600\"\n variant={\"body2\"}\n align={\"center\"}>\n {helpText}\n </Typography>\n </div>}\n\n <EntityTableCellActions\n showError={showError}\n disabled={disabled}\n showExpandIcon={true}\n selected={selected}\n openPopup={!disabled ? openPopup : undefined}>\n <IconButton aria-label={t(\"edit\")}\n size={\"small\"}\n onClick={open}>\n <PencilIcon className={\"text-surface-500\"}/>\n </IconButton>\n </EntityTableCellActions>\n\n </div>\n );\n\n}\n\ninterface TableStorageItemPreviewProps {\n propertyKey: string;\n property: StringProperty;\n value: string,\n size: PreviewSize;\n entity: Entity<Record<string, unknown>>;\n}\n\nexport function TableStorageItemPreview({\n propertyKey,\n property,\n value,\n size,\n entity\n}: TableStorageItemPreviewProps) {\n\n return (\n <div\n className={\"relative p-2 max-w-full\"}\n >\n\n {value &&\n <ErrorBoundary>\n <PropertyPreview\n propertyKey={propertyKey}\n value={value}\n property={property}\n // entity={entity}\n size={size}/>\n </ErrorBoundary>\n }\n\n </div>\n );\n\n}\n"],"mappings":";;;;;;;;;;;AAgBA,IAAM,kBAAkB;AACxB,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;;;;;;;;AAS1B,SAAgB,mBAAmB,OAchC;CAEC,MAAM,EACF,aACA,OACA,UACA,WACA,OACA,UACA,UACA,QACA,MACA,aACA,gBACA;CAEJ,MAAM,gBAAgB,iBAAiB;CACvC,MAAM,iBAAiB,gCAAgC,CAAC,CAAC,cAAc,IAAI,CAAC,EAAE;CAE9E,MAAM,EACF,eACA,kBACA,cACA,SACA,sBACA,oBACA,wBACA,0BACA,2BAA2B;EAC3B,cAAc,OAAO;EACrB,UAAU,OAAO;EACjB;EACA;EACU;EACV;EACA;EACA,UAAU;EACV;EACA;CACJ,CAAC;CAED,OAEI,oBAAC,qBAAqB,UAAtB;EAA+B,OAAO;YAClC,oBAAC,eAAD;GACmB;GACG;GAClB,MAAM;GACI;GACV,WAAW;GACA;GACJ;GACG;GACA;GACV,UAAU;GACF;GACY;GACX;GACe;GACV;GACQ;GACT;EAAa,CAAA;CACH,CAAA;AAGvC;AAsBA,SAAS,cAAc,EACnB,UACA,MACA,eACA,kBACA,WACA,QACA,UACA,OACA,UACA,wBACA,aAAa,kBACb,UACA,WACA,SACA,cACA,sBACA,sBACmB;CAEnB,MAAM,cAAc;CACpB,IAAI,wBAAwB;EACxB,MAAM,gBAAgB;EACtB,IAAI,MAAM,QAAQ,cAAc,EAAE,GAC9B,MAAM,MAAM,uEAAuE;EAEvF,IAAI,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Ae,oBAAoB,IACnC,eAAe,oBAAoB,EACvC;YAPJ;GAUI,oBAAC,SAAD;IAAkB;IAAW,GAAI,cAAc;GAAG,CAAA;GAEjD,cAAc,KAAK,OAAO,UAAU;IACjC,IAAI;IACJ,IAAI,MAAM,0BACN,QACI,oBAAC,yBAAD;KAEI,aAAa;KACb,UAAU;KACV,OAAO,MAAM;KACL;KACR,MAAM;IAAa,GALd,mBAAmB,OAKL;SAExB,IAAI,MAAM,MACb,QACI,oBAAC,uBAAD;KAEW;KACG;KACV,aAAa,mBAAmB,MAAM,IAAI;KACpB;KACX;KACX,QAAQ;IACX,GAPQ,oBAAoB,OAO5B;IAIT,OAAO;GACX,CAAC;GAEA,CAAC,iBAAiB,oBAAC,OAAD;IACf,WAAU;IACV,SAAS;cACT,oBAAC,YAAD;KACI,WAAU;KACV,SAAS;KACT,OAAO;eACN;IACO,CAAA;GACX,CAAA;GAEL,oBAAC,wBAAD;IACe;IACD;IACV,gBAAgB;IACN;IACV,WAAW,CAAC,WAAW,YAAY,KAAA;cACnC,oBAAC,YAAD;KAAY,cAAY,EAAE,MAAM;KAC5B,MAAM;KACN,SAAS;eACT,oBAAC,YAAD,EAAY,WAAW,mBAAoB,CAAA;IACnC,CAAA;GACQ,CAAA;EAEvB;;AAGb;AAUA,SAAgB,wBAAwB,EACpC,aACA,UACA,OACA,MACA,UAC6B;CAE7B,OACI,oBAAC,OAAD;EACI,WAAW;YAGV,SACG,oBAAC,eAAD,EAAA,UACI,oBAAC,iBAAD;GACiB;GACN;GACG;GAEJ;EAAM,CAAA,EACL,CAAA;CAGlB,CAAA;AAGb"}
|
|
1
|
+
{"version":3,"file":"TableStorageUpload.js","names":[],"sources":["../../../../src/components/CollectionTableBinding/fields/TableStorageUpload.tsx"],"sourcesContent":["import type { ArrayProperty, StringProperty } from \"@rebasepro/types\";\nimport * as React from \"react\";\nimport { useMemo } from \"react\";\n\nimport { Entity, StorageConfig } from \"@rebasepro/types\";\nimport { PreviewSize } from \"../../../types\";\nimport { useDropzone } from \"react-dropzone\";\nimport { PropertyPreview } from \"../../../preview\";\nimport { ErrorBoundary } from \"@rebasepro/ui\";\nimport { cls, IconButton, PencilIcon, Typography } from \"@rebasepro/ui\";\nimport { useSnackbarController, useStorageSource, useTranslation, StorageFieldItem, useStorageUploadController, StorageSourceContext } from \"@rebasepro/app\";\nimport { getThumbnailMeasure } from \"../../../preview/util\";\nimport { StorageUploadProgress } from \"../../../form/components/StorageUploadProgress\";\nimport { useCollectionRegistryController } from \"../../../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { EntityTableCellActions } from \"../internal/EntityTableCellActions\";\n\nconst dropZoneClasses = \"max-w-full box-border relative pt-[2px] items-center border border-transparent outline-hidden rounded-md duration-200 ease-[cubic-bezier(0.4,0,0.2,1)] focus:border-primary\";\nconst activeDropClasses = \"pt-0 border-2 border-solid\"\nconst acceptDropClasses = \"transition-colors duration-200 ease-[cubic-bezier(0,0,0.2,1)] border-2 border-solid border-green-500 bg-green-50 dark:bg-green-900\"\nconst rejectDropClasses = \"transition-colors duration-200 ease-[cubic-bezier(0,0,0.2,1)] border-2 border-solid border-red-500 bg-red-50 dark:bg-red-900\"\n\n/**\n * Field that allows to upload files to Google Cloud Storage.\n *\n * This is one of the internal components that get mapped natively inside forms\n * and tables to the specified properties.\n * @group Form fields\n */\nexport function TableStorageUpload(props: {\n propertyKey: string;\n error: Error | undefined;\n disabled: boolean;\n value: string | string[] | null;\n updateValue: (newValue: (string | string[] | null)) => void;\n selected: boolean;\n focused: boolean;\n property: StringProperty | ArrayProperty;\n entity: Entity<Record<string, unknown>>;\n path: string;\n previewSize: PreviewSize;\n openPopup?: (cellRect?: DOMRect) => void;\n onBlur?: React.FocusEventHandler<HTMLInputElement | HTMLTextAreaElement>;\n}) {\n\n const {\n propertyKey,\n error,\n selected,\n openPopup,\n value,\n disabled,\n property,\n entity,\n path,\n previewSize,\n updateValue\n } = props;\n\n const storageSource = useStorageSource();\n const collectionSlug = useCollectionRegistryController().getCollection(path)?.slug;\n\n const {\n internalValue,\n setInternalValue,\n onFilesAdded,\n storage,\n onFileUploadComplete,\n storagePathBuilder,\n multipleFilesSupported,\n resolvedStorageSource\n } = useStorageUploadController({\n entityValues: entity.values,\n entityId: entity.id,\n path,\n collectionSlug,\n property: property as StringProperty,\n propertyKey,\n storageSource,\n onChange: updateValue,\n value,\n disabled\n });\n\n return (\n\n <StorageSourceContext.Provider value={resolvedStorageSource}>\n <StorageUpload\n internalValue={internalValue}\n setInternalValue={setInternalValue}\n name={propertyKey}\n disabled={disabled}\n autoFocus={false}\n openPopup={openPopup}\n error={error}\n selected={selected}\n property={property}\n onChange={updateValue}\n entity={entity}\n storagePathBuilder={storagePathBuilder}\n storage={storage}\n multipleFilesSupported={multipleFilesSupported}\n onFilesAdded={onFilesAdded}\n onFileUploadComplete={onFileUploadComplete}\n previewSize={previewSize}/>\n </StorageSourceContext.Provider>\n\n );\n}\n\ninterface StorageUploadProps {\n internalValue: StorageFieldItem[];\n setInternalValue: (v: StorageFieldItem[]) => void;\n name: string;\n error?: Error;\n property: StringProperty | ArrayProperty;\n onChange: (value: string | string[] | null) => void;\n multipleFilesSupported: boolean;\n autoFocus: boolean;\n selected: boolean;\n disabled: boolean;\n entity: Entity<Record<string, unknown>>;\n previewSize: PreviewSize;\n storage: StorageConfig;\n onFilesAdded: (acceptedFiles: File[]) => void;\n storagePathBuilder: (file: File) => string;\n openPopup?: (cellRect?: DOMRect) => void;\n onFileUploadComplete: (uploadedPath: string, entry: StorageFieldItem, fileMetadata?: Record<string, unknown>) => Promise<void>;\n}\n\nfunction StorageUpload({\n property,\n name,\n internalValue,\n setInternalValue,\n openPopup,\n entity,\n selected,\n error,\n onChange,\n multipleFilesSupported,\n previewSize: previewSizeInput,\n disabled,\n autoFocus,\n storage,\n onFilesAdded,\n onFileUploadComplete,\n storagePathBuilder\n}: StorageUploadProps) {\n\n const previewSize = previewSizeInput;\n if (multipleFilesSupported) {\n const arrayProperty = property as ArrayProperty;\n if (Array.isArray(arrayProperty.of)) {\n throw Error(\"Using array properties instead of single one in `of` in ArrayProperty\");\n }\n if (arrayProperty.of) {\n if (arrayProperty.of.type !== \"string\") {\n throw Error(\"Storage field using array must be of data type string\");\n }\n } else {\n throw Error(\"Storage field using array must be of data type string\");\n }\n }\n\n const metadata: Record<string, unknown> | undefined = storage?.metadata;\n const hasValue = Boolean(internalValue);\n\n const snackbarContext = useSnackbarController();\n const { t } = useTranslation();\n\n const {\n open,\n getRootProps,\n getInputProps,\n isDragActive,\n isDragAccept,\n isDragReject\n } = useDropzone({\n accept: storage.acceptedFiles ? storage.acceptedFiles.map(e => ({ [e]: [] })).reduce((a, b) => ({ ...a,\n...b }), {}) : undefined,\n disabled,\n maxSize: storage.maxSize,\n noClick: true,\n noKeyboard: true,\n onDrop: onFilesAdded,\n onDropRejected: (fileRejections, event) => {\n for (const fileRejection of fileRejections) {\n for (const error of fileRejection.errors) {\n console.error(\"Error uploading file: \", error);\n if (error.code === \"file-too-large\") {\n snackbarContext.open({\n type: \"error\",\n message: t(\"error_uploading_file_size\", { maxSize: String(storage.maxSize) })\n });\n } else if (error.code === \"file-invalid-type\") {\n snackbarContext.open({\n type: \"error\",\n message: t(\"error_uploading_file_type\")\n });\n }\n }\n }\n }\n }\n );\n\n const { ...rootProps } = getRootProps();\n\n const helpText = multipleFilesSupported\n ? t(\"drag_drop_files\")\n : t(\"drag_drop_file\");\n\n const renderProperty = multipleFilesSupported\n ? (property as ArrayProperty).of as StringProperty\n : property as StringProperty;\n\n const imageSize = useMemo(() => getThumbnailMeasure(previewSize), [previewSize]);\n const showError = !disabled && error;\n\n return (\n <div {...rootProps}\n className={cls(dropZoneClasses,\n \"relative w-full h-full flex\",\n `justify-${hasValue ? \"start\" : \"center\"}`,\n isDragActive ? activeDropClasses : \"\",\n isDragAccept ? acceptDropClasses : \"\",\n isDragReject ? rejectDropClasses : \"\"\n )}\n >\n\n <input autoFocus={autoFocus} {...getInputProps()}/>\n\n {internalValue.map((entry, index) => {\n let child;\n if (entry.storagePathOrDownloadUrl) {\n child = (\n <TableStorageItemPreview\n key={`storage_preview_${index}`}\n propertyKey={name}\n property={renderProperty}\n value={entry.storagePathOrDownloadUrl}\n entity={entity}\n size={previewSize}/>\n );\n } else if (entry.file) {\n child = (\n <StorageUploadProgress\n key={`storage_progress_${index}`}\n entry={entry}\n metadata={metadata}\n storagePath={storagePathBuilder(entry.file)}\n onFileUploadComplete={onFileUploadComplete}\n imageSize={imageSize}\n simple={true}\n />\n );\n }\n\n return child;\n })}\n\n {!internalValue && <div\n className=\"grow m-2 max-w-[200px]\"\n onClick={open}>\n <Typography\n className=\"text-surface-400 dark:text-surface-600\"\n variant={\"body2\"}\n align={\"center\"}>\n {helpText}\n </Typography>\n </div>}\n\n <EntityTableCellActions\n showError={showError}\n disabled={disabled}\n showExpandIcon={true}\n selected={selected}\n openPopup={!disabled ? openPopup : undefined}>\n <IconButton aria-label={t(\"edit\")}\n size={\"small\"}\n onClick={open}>\n <PencilIcon className={\"text-surface-500\"}/>\n </IconButton>\n </EntityTableCellActions>\n\n </div>\n );\n\n}\n\ninterface TableStorageItemPreviewProps {\n propertyKey: string;\n property: StringProperty;\n value: string,\n size: PreviewSize;\n entity: Entity<Record<string, unknown>>;\n}\n\nexport function TableStorageItemPreview({\n propertyKey,\n property,\n value,\n size,\n entity\n}: TableStorageItemPreviewProps) {\n\n // shrink-0: an image with a percentage max-height has no min-content width,\n // so a row of them in a narrow cell squeezes each one to a sliver. They\n // keep their size and the cell clips the ones that do not fit.\n return (\n <div\n className={\"relative p-2 max-w-full shrink-0\"}\n >\n\n {value &&\n <ErrorBoundary>\n <PropertyPreview\n propertyKey={propertyKey}\n value={value}\n property={property}\n // entity={entity}\n size={size}/>\n </ErrorBoundary>\n }\n\n </div>\n );\n\n}\n"],"mappings":";;;;;;;;;;;AAgBA,IAAM,kBAAkB;AACxB,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;;;;;;;;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AAO;GACX,CAAC;GAEA,CAAC,iBAAiB,oBAAC,OAAD;IACf,WAAU;IACV,SAAS;cACT,oBAAC,YAAD;KACI,WAAU;KACV,SAAS;KACT,OAAO;eACN;IACO,CAAA;GACX,CAAA;GAEL,oBAAC,wBAAD;IACe;IACD;IACV,gBAAgB;IACN;IACV,WAAW,CAAC,WAAW,YAAY,KAAA;cACnC,oBAAC,YAAD;KAAY,cAAY,EAAE,MAAM;KAC5B,MAAM;KACN,SAAS;eACT,oBAAC,YAAD,EAAY,WAAW,mBAAoB,CAAA;IACnC,CAAA;GACQ,CAAA;EAEvB;;AAGb;AAUA,SAAgB,wBAAwB,EACpC,aACA,UACA,OACA,MACA,UAC6B;CAK7B,OACI,oBAAC,OAAD;EACI,WAAW;YAGV,SACG,oBAAC,eAAD,EAAA,UACI,oBAAC,iBAAD;GACiB;GACN;GACG;GAEJ;EAAM,CAAA,EACL,CAAA;CAGlB,CAAA;AAGb"}
|
|
@@ -41,6 +41,26 @@ export type EntityPreviewBindingDataProps = {
|
|
|
41
41
|
* without any container wrapper. Used internally by EntityPreviewBinding.
|
|
42
42
|
*/
|
|
43
43
|
export declare function EntityPreviewBindingData({ actions, collection: collectionProp, previewKeys, size, includeId, onSidePanelClick, includeTitle, includeEntityLink, includeImage, layout, entity }: EntityPreviewBindingDataProps): React.JSX.Element;
|
|
44
|
+
/**
|
|
45
|
+
* A card that has not loaded yet, drawn as the card it will be: the image
|
|
46
|
+
* slot, a title, one placeholder per line the card will show and the open
|
|
47
|
+
* button's room. A single bar in a 48px box grew to the full card when the
|
|
48
|
+
* record arrived and pushed everything under it down.
|
|
49
|
+
*
|
|
50
|
+
* Which lines a card shows is known before its record is — they come from
|
|
51
|
+
* the collection, not the values — so the count is right whatever the
|
|
52
|
+
* collection declares. Each placeholder sits in the line's own wrapper with
|
|
53
|
+
* the line's own type, and an enum's is a chip, so a line is as tall
|
|
54
|
+
* loading as loaded without any height written down here.
|
|
55
|
+
*/
|
|
56
|
+
export declare function EntityPreviewBindingSkeleton({ collection, previewKeys, size, includeTitle, includeImage, includeEntityLink }: {
|
|
57
|
+
collection: AdminCollection;
|
|
58
|
+
previewKeys?: string[];
|
|
59
|
+
size?: "smallest" | "small" | "medium" | "large";
|
|
60
|
+
includeTitle?: boolean;
|
|
61
|
+
includeImage?: boolean;
|
|
62
|
+
includeEntityLink?: boolean;
|
|
63
|
+
}): React.JSX.Element;
|
|
44
64
|
export declare function EntityPreviewBindingWithId({ entityId, path, ...props }: Omit<EntityPreviewBindingProps, "entity"> & {
|
|
45
65
|
entityId: string | number;
|
|
46
66
|
path: string;
|
|
@@ -10,9 +10,9 @@ import { PropertyPreview } from "../preview/PropertyPreview.js";
|
|
|
10
10
|
import * as React$1 from "react";
|
|
11
11
|
import { useMemo } from "react";
|
|
12
12
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
13
|
-
import { ArrowRightToLineIcon, IconButton, Skeleton, Tooltip, Typography, cls, defaultBorderMixin } from "@rebasepro/ui";
|
|
14
|
-
import "@rebasepro/common";
|
|
15
|
-
import { ErrorView, IconForView, getEntityImagePreviewPropertyKey, useAnalyticsController, useAuthController, useCustomizationController } from "@rebasepro/app";
|
|
13
|
+
import { ArrowRightToLineIcon, Chip, IconButton, Skeleton, Tooltip, Typography, cls, defaultBorderMixin } from "@rebasepro/ui";
|
|
14
|
+
import { enumToObjectEntries } from "@rebasepro/common";
|
|
15
|
+
import { ErrorView, IconForView, buildEnumLabel, getEntityImagePreviewPropertyKey, useAnalyticsController, useAuthController, useCustomizationController } from "@rebasepro/app";
|
|
16
16
|
import { getValueInPath } from "@rebasepro/utils";
|
|
17
17
|
//#region src/components/EntityPreviewBinding.tsx
|
|
18
18
|
/**
|
|
@@ -20,28 +20,15 @@ import { getValueInPath } from "@rebasepro/utils";
|
|
|
20
20
|
* without any container wrapper. Used internally by EntityPreviewBinding.
|
|
21
21
|
*/
|
|
22
22
|
function EntityPreviewBindingData({ actions, collection: collectionProp, previewKeys, size = "medium", includeId = true, onSidePanelClick, includeTitle = true, includeEntityLink = true, includeImage = true, layout = "card", entity }) {
|
|
23
|
-
const authController = useAuthController();
|
|
24
23
|
const analyticsController = useAnalyticsController();
|
|
25
24
|
const sidePanelController = useSidePanel();
|
|
26
|
-
const customizationController = useCustomizationController();
|
|
27
25
|
const collectionRegistryController = useCollectionRegistryController();
|
|
28
26
|
const collection = collectionProp ?? collectionRegistryController.getCollection(entity.path);
|
|
29
27
|
const title = useEntityTitle({
|
|
30
28
|
collection,
|
|
31
29
|
entity
|
|
32
30
|
});
|
|
33
|
-
const
|
|
34
|
-
const listProperties = useMemo(() => {
|
|
35
|
-
if (!collection) return [];
|
|
36
|
-
if (statedKeys && statedKeys.length > 0) return statedKeys.filter((key) => getPropertyInPath$1(collection.properties, key));
|
|
37
|
-
const slotKeys = resolveCollectionSlotKeys(collection, authController, customizationController.propertyConfigs);
|
|
38
|
-
return [slotKeys.subtitleKey, slotKeys.statusKey].filter(Boolean);
|
|
39
|
-
}, [
|
|
40
|
-
statedKeys,
|
|
41
|
-
collection,
|
|
42
|
-
authController,
|
|
43
|
-
customizationController.propertyConfigs
|
|
44
|
-
]);
|
|
31
|
+
const { listProperties } = usePreviewCardKeys(collection, previewKeys);
|
|
45
32
|
if (!collection) return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(ErrorView, { error: `Collection not found: ${entity.path}` }) });
|
|
46
33
|
const titleProperty = includeTitle ? title.source?.key : void 0;
|
|
47
34
|
const imagePropertyKey = includeImage ? getEntityImagePreviewPropertyKey(collection) : void 0;
|
|
@@ -231,6 +218,122 @@ function EntityRowPreviewContent({ size, entity, collection, title, imagePropert
|
|
|
231
218
|
}) });
|
|
232
219
|
}
|
|
233
220
|
/**
|
|
221
|
+
* What a card says under its title, and the property its title would come
|
|
222
|
+
* from — one answer for the card and for the skeleton standing in for it, so
|
|
223
|
+
* the two always have the same lines.
|
|
224
|
+
*
|
|
225
|
+
* A stated list wins outright — `previewProperties` is the one place a
|
|
226
|
+
* developer says "show these", and nothing here is allowed to second-guess
|
|
227
|
+
* it. Failing that, the card fills the same slots as every other surface
|
|
228
|
+
* that renders one record in a row: a supporting line and a status. It used
|
|
229
|
+
* to take the first few properties in declaration order instead, which is
|
|
230
|
+
* how an author card ended up rendering an entire Markdown biography.
|
|
231
|
+
*/
|
|
232
|
+
function usePreviewCardKeys(collection, previewKeys) {
|
|
233
|
+
const authController = useAuthController();
|
|
234
|
+
const customizationController = useCustomizationController();
|
|
235
|
+
const statedKeys = previewKeys ?? collection?.previewProperties;
|
|
236
|
+
return useMemo(() => {
|
|
237
|
+
if (!collection) return {
|
|
238
|
+
listProperties: [],
|
|
239
|
+
titleKey: void 0
|
|
240
|
+
};
|
|
241
|
+
const slotKeys = resolveCollectionSlotKeys(collection, authController, customizationController.propertyConfigs);
|
|
242
|
+
return {
|
|
243
|
+
listProperties: statedKeys && statedKeys.length > 0 ? statedKeys.filter((key) => getPropertyInPath$1(collection.properties, key)) : [slotKeys.subtitleKey, slotKeys.statusKey].filter(Boolean),
|
|
244
|
+
titleKey: slotKeys.titleKey
|
|
245
|
+
};
|
|
246
|
+
}, [
|
|
247
|
+
statedKeys,
|
|
248
|
+
collection,
|
|
249
|
+
authController,
|
|
250
|
+
customizationController.propertyConfigs
|
|
251
|
+
]);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* A card that has not loaded yet, drawn as the card it will be: the image
|
|
255
|
+
* slot, a title, one placeholder per line the card will show and the open
|
|
256
|
+
* button's room. A single bar in a 48px box grew to the full card when the
|
|
257
|
+
* record arrived and pushed everything under it down.
|
|
258
|
+
*
|
|
259
|
+
* Which lines a card shows is known before its record is — they come from
|
|
260
|
+
* the collection, not the values — so the count is right whatever the
|
|
261
|
+
* collection declares. Each placeholder sits in the line's own wrapper with
|
|
262
|
+
* the line's own type, and an enum's is a chip, so a line is as tall
|
|
263
|
+
* loading as loaded without any height written down here.
|
|
264
|
+
*/
|
|
265
|
+
function EntityPreviewBindingSkeleton({ collection, previewKeys, size = "medium", includeTitle = true, includeImage = true, includeEntityLink = true }) {
|
|
266
|
+
const { listProperties, titleKey } = usePreviewCardKeys(collection, previewKeys);
|
|
267
|
+
const imagePropertyKey = includeImage ? getEntityImagePreviewPropertyKey(collection) : void 0;
|
|
268
|
+
const lines = listProperties.filter((key) => key !== (includeTitle ? titleKey : void 0) && key !== imagePropertyKey);
|
|
269
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
270
|
+
/* @__PURE__ */ jsx("div", {
|
|
271
|
+
className: cls("flex shrink-0 overflow-hidden", {
|
|
272
|
+
"w-6 h-6 mx-1 my-0.5": size === "small" || size === "smallest",
|
|
273
|
+
"w-8 h-8 ml-1 mr-2 m-2 self-start": size === "medium",
|
|
274
|
+
"w-10 h-10 ml-2 mr-2 m-2 self-start": size === "large"
|
|
275
|
+
}),
|
|
276
|
+
children: imagePropertyKey ? /* @__PURE__ */ jsx(Skeleton, { className: "w-full h-full" }) : /* @__PURE__ */ jsx(IconForView, {
|
|
277
|
+
collectionOrView: collection,
|
|
278
|
+
color: "primary",
|
|
279
|
+
size,
|
|
280
|
+
className: "m-auto"
|
|
281
|
+
})
|
|
282
|
+
}),
|
|
283
|
+
/* @__PURE__ */ jsxs("div", {
|
|
284
|
+
className: "flex flex-col grow w-full m-1 shrink min-w-0 text-text-primary dark:text-text-primary-dark flex-1 mr-2",
|
|
285
|
+
"aria-busy": true,
|
|
286
|
+
children: [includeTitle && /* @__PURE__ */ jsxs("div", {
|
|
287
|
+
className: "truncate my-0.5 text-sm font-medium",
|
|
288
|
+
children: ["", /* @__PURE__ */ jsx(Skeleton, {
|
|
289
|
+
className: "inline-block align-middle",
|
|
290
|
+
width: 160
|
|
291
|
+
})]
|
|
292
|
+
}), lines.map((key) => {
|
|
293
|
+
const property = getPropertyInPath$1(collection.properties, key);
|
|
294
|
+
if (!property) return null;
|
|
295
|
+
return /* @__PURE__ */ jsx("div", {
|
|
296
|
+
className: cls("truncate min-w-0 max-h-8 overflow-hidden", lines.length > 1 ? "my-0.5" : "my-0"),
|
|
297
|
+
children: /* @__PURE__ */ jsx(SkeletonCardLine, { property })
|
|
298
|
+
}, "ref_prev_" + key);
|
|
299
|
+
})]
|
|
300
|
+
}),
|
|
301
|
+
includeEntityLink && /* @__PURE__ */ jsx("div", {
|
|
302
|
+
className: "flex-shrink-0",
|
|
303
|
+
"aria-hidden": true,
|
|
304
|
+
children: /* @__PURE__ */ jsx(IconButton, {
|
|
305
|
+
size: "small",
|
|
306
|
+
"aria-label": "See details",
|
|
307
|
+
tabIndex: -1,
|
|
308
|
+
disabled: true,
|
|
309
|
+
className: cls("invisible", size !== "small" ? "self-start" : ""),
|
|
310
|
+
children: /* @__PURE__ */ jsx(ArrowRightToLineIcon, {})
|
|
311
|
+
})
|
|
312
|
+
})
|
|
313
|
+
] });
|
|
314
|
+
}
|
|
315
|
+
/** One card line, loading: a chip for an enum, as the loaded line draws it, else a bar in a line of text. */
|
|
316
|
+
function SkeletonCardLine({ property }) {
|
|
317
|
+
const enumValues = property.type === "string" || property.type === "number" ? property.enum : void 0;
|
|
318
|
+
if (enumValues) {
|
|
319
|
+
const [first] = enumToObjectEntries(enumValues);
|
|
320
|
+
return /* @__PURE__ */ jsx(Chip, {
|
|
321
|
+
size: "small",
|
|
322
|
+
children: /* @__PURE__ */ jsx("span", {
|
|
323
|
+
className: "invisible",
|
|
324
|
+
children: first ? buildEnumLabel(first) : "\xA0"
|
|
325
|
+
})
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
return /* @__PURE__ */ jsxs("span", {
|
|
329
|
+
className: "text-sm",
|
|
330
|
+
children: ["", /* @__PURE__ */ jsx(Skeleton, {
|
|
331
|
+
className: "inline-block align-middle",
|
|
332
|
+
width: 120
|
|
333
|
+
})]
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
234
337
|
* This view is used to display a preview of a entity.
|
|
235
338
|
* It is used by default in reference fields and whenever a reference is displayed.
|
|
236
339
|
*/
|
|
@@ -278,6 +381,6 @@ var EntityPreviewContainer = React$1.forwardRef(({ children, hover, onClick, siz
|
|
|
278
381
|
});
|
|
279
382
|
EntityPreviewContainer.displayName = "EntityPreviewContainer";
|
|
280
383
|
//#endregion
|
|
281
|
-
export { EntityPreviewBinding, EntityPreviewBindingData, EntityPreviewContainer };
|
|
384
|
+
export { EntityPreviewBinding, EntityPreviewBindingData, EntityPreviewBindingSkeleton, EntityPreviewContainer };
|
|
282
385
|
|
|
283
386
|
//# sourceMappingURL=EntityPreviewBinding.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EntityPreviewBinding.js","names":[],"sources":["../../src/components/EntityPreviewBinding.tsx"],"sourcesContent":["\nimport type { Property } from \"@rebasepro/types\";\nimport { hasEntityId } from \"@rebasepro/common\";\nimport * as React from \"react\";\nimport { useEffect, useMemo } from \"react\";\n\nimport { Entity } from \"@rebasepro/types\";\nimport type { PreviewSize } from \"../types/components/PropertyPreviewProps\";\nimport { getEntityImagePreviewPropertyKey } from \"@rebasepro/app\";\nimport {\n ArrowRightToLineIcon,\n cls,\n defaultBorderMixin,\n IconButton,\n Skeleton,\n Tooltip,\n Typography\n} from \"@rebasepro/ui\";\nimport { PropertyPreview, SkeletonPropertyComponent } from \"../preview\";\nimport {\n useAuthController,\n useCustomizationController,\n useData,\n ErrorView\n} from \"@rebasepro/app\";\nimport { useAnalyticsController } from \"@rebasepro/app\";\nimport { IconForView } from \"@rebasepro/app\";\nimport { getPropertyInPath } from \"../util/property_utils\";\nimport { resolveCollectionSlotKeys } from \"./CollectionViewBinding/usePreviewSlots\";\nimport { useEntityTitle } from \"../hooks/useEntityDisplay\";\nimport { getValueInPath } from \"@rebasepro/utils\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { useSidePanel } from \"../hooks/useSidePanel\";\nimport { EntityPreviewLayout, NestedEntityPreviewBoundary } from \"./EntityPreviewNesting\";\nimport { isEmptyPreviewValue } from \"../preview/util\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\n\nexport type EntityPreviewBindingProps = {\n size?: PreviewSize,\n actions?: React.ReactNode,\n collection?: AdminCollection,\n hover?: boolean;\n previewKeys?: string[],\n disabled?: boolean,\n entity: Entity<any>,\n includeId?: boolean,\n includeTitle?: boolean,\n includeEntityLink?: boolean,\n includeImage?: boolean,\n onClick?: (e: React.SyntheticEvent) => void;\n onSidePanelClick?: (entity: Entity) => void,\n};\n\nexport type EntityPreviewBindingDataProps = {\n size?: \"smallest\" | \"small\" | \"medium\" | \"large\",\n actions?: React.ReactNode,\n collection?: AdminCollection,\n previewKeys?: string[],\n entity: Entity<any>,\n onSidePanelClick?: (entity: Entity) => void,\n includeId?: boolean,\n includeTitle?: boolean,\n includeEntityLink?: boolean,\n includeImage?: boolean,\n /**\n * `row` draws the record as a line of a table row instead of a card: see\n * {@link EntityPreviewLayout}. No id, no open button — the title opens the\n * record — and only as many supporting lines as the row has room for.\n */\n layout?: EntityPreviewLayout,\n};\n\n/**\n * This component contains the main logic and content for displaying a entity preview,\n * without any container wrapper. Used internally by EntityPreviewBinding.\n */\nexport function EntityPreviewBindingData({\n actions,\n collection: collectionProp,\n previewKeys,\n size = \"medium\",\n includeId = true,\n onSidePanelClick,\n includeTitle = true,\n includeEntityLink = true,\n includeImage = true,\n layout = \"card\",\n entity\n}: EntityPreviewBindingDataProps) {\n\n const authController = useAuthController();\n const analyticsController = useAnalyticsController();\n const sidePanelController = useSidePanel();\n const customizationController = useCustomizationController();\n\n const collectionRegistryController = useCollectionRegistryController();\n\n const collection = collectionProp ?? collectionRegistryController.getCollection(entity.path);\n\n // Above the `!collection` return, because hooks are. `useEntityTitle`\n // tolerates a missing collection for exactly this reason.\n const title = useEntityTitle({\n collection,\n entity\n });\n\n // What the card says under the title.\n //\n // A stated list wins outright — `previewProperties` is the one place a\n // developer says \"show these\", and nothing here is allowed to second-guess\n // it. Failing that, the card fills the same slots as every other surface\n // that renders one record in a row: a supporting line and a status. It used\n // to take the first few properties in declaration order instead, which is\n // how an author card ended up rendering an entire Markdown biography.\n const statedKeys = previewKeys ?? (collection?.previewProperties as string[] | undefined);\n const listProperties = useMemo(() => {\n if (!collection) return [];\n if (statedKeys && statedKeys.length > 0) {\n return statedKeys.filter(key => getPropertyInPath(collection.properties, key));\n }\n const slotKeys = resolveCollectionSlotKeys(\n collection as AdminCollection<Record<string, unknown>>,\n authController,\n customizationController.propertyConfigs);\n return [slotKeys.subtitleKey, slotKeys.statusKey].filter(Boolean) as string[];\n }, [statedKeys, collection, authController, customizationController.propertyConfigs]);\n\n if (!collection) {\n return (\n <>\n <ErrorView error={`Collection not found: ${entity.path}`}/>\n </>\n );\n }\n\n const titleProperty = includeTitle ? title.source?.key : undefined;\n const imagePropertyKey = includeImage ? getEntityImagePreviewPropertyKey(collection) : undefined;\n const imageProperty = imagePropertyKey ? collection.properties[imagePropertyKey] : undefined;\n const ofProp = imageProperty && \"of\" in imageProperty ? imageProperty.of : undefined;\n const usedImageProperty = ofProp ? (Array.isArray(ofProp) ? ofProp[0] : ofProp) : imageProperty;\n const restProperties = listProperties.filter(p => p !== titleProperty && p !== imagePropertyKey);\n\n const openInSidePanel = () => {\n onSidePanelClick?.(entity);\n analyticsController.onAnalyticsEvent?.(\"entity_click_from_reference\", {\n path: entity.path,\n entityId: entity.id\n });\n sidePanelController.open({\n id: entity.id,\n path: entity.path,\n collection,\n updateUrl: true\n });\n };\n\n const imageValue = imagePropertyKey ? getValueInPath(entity.values, imagePropertyKey) : undefined;\n const usedImageValue = imageProperty !== undefined ? (\"of\" in imageProperty\n ? (((imageValue as unknown[]) ?? []).length > 0\n ? (imageValue as unknown[])[0] : undefined)\n : imageValue)\n : undefined;\n\n if (layout === \"row\")\n return <EntityRowPreviewContent size={size}\n entity={entity}\n collection={collection}\n title={title.value ?? String(entity.id)}\n imageProperty={usedImageProperty}\n imagePropertyKey={imagePropertyKey}\n imageValue={usedImageValue}\n supportingKeys={restProperties}\n onOpen={includeEntityLink ? openInSidePanel : undefined}/>;\n\n return (\n // Everything below renders *inside* this preview: a reference or\n // relation among the preview properties collapses to one line instead\n // of nesting another bordered card with its own id and action button.\n <NestedEntityPreviewBoundary>\n {/* `overflow-hidden`: the image slot is a fixed box, and a thumbnail\n that fails to load renders a \"file not found\" message sized for a\n full preview — which spilled across the title beside it. */}\n <div className={cls(\"flex shrink-0 overflow-hidden\", {\n \"w-6 h-6 mx-1 my-0.5\": size === \"small\" || size === \"smallest\",\n \"w-8 h-8 ml-1 mr-2 m-2 self-start\": size === \"medium\",\n \"w-10 h-10 ml-2 mr-2 m-2 self-start\": size === \"large\"\n })}>\n {usedImageProperty && usedImageValue ? <PropertyPreview property={usedImageProperty}\n propertyKey={imagePropertyKey as string}\n size={\"small\"}\n value={usedImageValue}/> : null}\n {(!usedImageProperty || !usedImageValue) ? <IconForView collectionOrView={collection}\n color={\"primary\"}\n size={size}\n className={\"m-auto\"}/> : null}\n </div>\n\n <div\n className={\"flex flex-col grow w-full m-1 shrink min-w-0 text-text-primary dark:text-text-primary-dark flex-1 mr-2\"}>\n\n {includeId && (\n entity\n ? <div className={\"block whitespace-nowrap overflow-hidden truncate\"}>\n <Typography variant={\"caption\"}\n color={\"disabled\"}\n className={\"font-mono\"}>\n {entity.id}\n </Typography>\n </div>\n : <Skeleton/>)}\n\n {/* A title that came from a property keeps that property's own\n rendering — an enum stays its coloured chip, a relation stays\n a link. A computed one is text, because that is all a\n resolver returns. */}\n {includeTitle && (titleProperty || title.value) && (\n <div\n className={\"truncate my-0.5 text-sm font-medium text-text-primary dark:text-text-primary-dark\"}>\n {!entity && titleProperty\n ? <SkeletonPropertyComponent\n property={getPropertyInPath(collection.properties, titleProperty) as Property}\n size={\"medium\"}/>\n : titleProperty\n ? <PropertyPreview\n propertyKey={titleProperty}\n value={title.source?.value}\n property={getPropertyInPath(collection.properties, titleProperty) as Property}\n size={\"medium\"}/>\n : title.value}\n </div>\n )}\n\n {restProperties && restProperties.map((key) => {\n const childProperty = getPropertyInPath(collection.properties, key);\n if (!childProperty) return null;\n\n const valueInPath = getValueInPath(entity.values, key);\n return (\n // `truncate` clamps a line of text; it does nothing to a\n // preview that renders blocks. Custom `admin.Preview`\n // components can render anything at all, so the height\n // is capped here as well — a card that loses the tail of\n // an unusual value beats a card the size of a document.\n <div key={\"ref_prev_\" + key}\n className={cls(\"truncate min-w-0 max-h-8 overflow-hidden\",\n restProperties.length > 1 ? \"my-0.5\" : \"my-0\")}>\n {\n entity\n ? <PropertyPreview\n propertyKey={key as string}\n value={valueInPath}\n property={childProperty as Property}\n size={\"small\"}/>\n : <SkeletonPropertyComponent\n property={childProperty as Property}\n size={\"small\"}/>\n }\n </div>\n );\n })}\n\n </div>\n\n {entity && includeEntityLink &&\n <div className=\"flex-shrink-0\">\n <Tooltip title={`See details for ${entity.id}`} className={\"shrink-0\"}>\n <IconButton aria-label={`See details for ${entity.id}`}\n size={\"small\"}\n className={size !== \"small\" ? \"self-start\" : \"\"}\n onClick={(e) => {\n e.stopPropagation();\n e.preventDefault();\n openInSidePanel();\n }}>\n <ArrowRightToLineIcon/>\n </IconButton>\n </Tooltip>\n </div>}\n\n {actions && <div className=\"flex-shrink-0\">{actions}</div>}\n </NestedEntityPreviewBoundary>\n );\n}\n\n/**\n * A record as a line of a table row: its image, a title that opens it, and the\n * supporting lines that fit — one at `medium`, two at `large`. Supporting\n * values that are empty are skipped rather than drawn as an empty bar, so the\n * line under a name is the first thing the record actually has to say.\n */\nfunction EntityRowPreviewContent({\n size,\n entity,\n collection,\n title,\n imageProperty,\n imagePropertyKey,\n imageValue,\n supportingKeys,\n onOpen\n}: {\n size: \"smallest\" | \"small\" | \"medium\" | \"large\";\n entity: Entity<Record<string, unknown>>;\n collection: AdminCollection;\n title: string;\n imageProperty?: Property;\n imagePropertyKey?: string;\n imageValue: unknown;\n supportingKeys: string[];\n onOpen?: () => void;\n}) {\n const maxLines = size === \"large\" ? 2 : 1;\n const lines = supportingKeys\n .map(key => ({\n key,\n property: getPropertyInPath(collection.properties, key),\n value: getValueInPath(entity.values, key)\n }))\n .filter((line): line is { key: string, property: Property, value: unknown } =>\n Boolean(line.property) && !isEmptyPreviewValue(line.value))\n .slice(0, maxLines);\n\n const titleNode = <span className={\"truncate\"}>{title}</span>;\n\n return (\n <NestedEntityPreviewBoundary>\n <div className={\"flex items-center gap-2.5 min-w-0 w-full text-left\"}>\n {imagePropertyKey && <div className={cls(\"flex shrink-0 items-center justify-center overflow-hidden rounded-md\",\n size === \"large\" ? \"w-10 h-10\" : \"w-8 h-8\")}>\n {imageProperty && imageValue\n ? <PropertyPreview property={imageProperty}\n propertyKey={imagePropertyKey}\n size={\"small\"}\n value={imageValue}/>\n : <IconForView collectionOrView={collection}\n color={\"primary\"}\n size={\"small\"}/>}\n </div>}\n <div className={\"flex flex-col min-w-0 flex-1\"}>\n <div className={\"flex min-w-0 text-sm font-medium text-text-primary dark:text-text-primary-dark\"}>\n {onOpen\n ? <Tooltip title={`See details for ${title}`} asChild={true}>\n <span role={\"button\"}\n tabIndex={0}\n className={\"inline-flex min-w-0 max-w-full cursor-pointer hover:underline underline-offset-2\"}\n // See InlineEntityPreview: a press does not\n // move the focus, or a table cell would\n // select itself mid-click.\n onMouseDown={(event) => event.preventDefault()}\n onClick={(event) => {\n event.preventDefault();\n event.stopPropagation();\n onOpen();\n }}\n onKeyDown={(event) => {\n if (event.key !== \"Enter\" && event.key !== \" \") return;\n event.preventDefault();\n event.stopPropagation();\n onOpen();\n }}>\n {titleNode}\n </span>\n </Tooltip>\n : titleNode}\n </div>\n {lines.map(({ key, property, value }) =>\n <div key={key}\n className={\"truncate min-w-0 max-h-5 overflow-hidden text-xs text-text-secondary dark:text-text-secondary-dark\"}>\n <PropertyPreview propertyKey={key}\n value={value}\n property={property}\n size={\"small\"}/>\n </div>)}\n </div>\n </div>\n </NestedEntityPreviewBoundary>\n );\n}\n\nexport function EntityPreviewBindingWithId({\n entityId,\n path,\n ...props\n}: Omit<EntityPreviewBindingProps, \"entity\"> & {\n entityId: string | number;\n path: string;\n databaseId?: string;\n}) {\n\n const [entity, setEntity] = React.useState<Entity | undefined>();\n const [dataLoading, setDataLoading] = React.useState(false);\n const dataClient = useData();\n\n useEffect(() => {\n let isMounted = true;\n if (!hasEntityId(entityId) || !path) {\n setEntity(undefined);\n return;\n }\n const fetchOne = async () => {\n setDataLoading(true);\n try {\n const fetchedEntity = await dataClient.collection(path).findById(entityId);\n if (isMounted) {\n setEntity(fetchedEntity);\n }\n } catch (error) {\n console.error(\"Error fetching entity:\", error);\n if (isMounted) {\n setEntity(undefined);\n }\n } finally {\n if (isMounted) {\n setDataLoading(false);\n }\n }\n }\n\n fetchOne();\n\n return () => {\n isMounted = false;\n }\n }, [entityId, path]);\n\n if (dataLoading && !entity) {\n return (\n <EntityPreviewContainer\n hover={props.hover}\n size={props.size}>\n <Skeleton/>\n </EntityPreviewContainer>\n );\n }\n\n if (!entity) {\n return (\n <EntityPreviewContainer\n hover={props.hover}\n size={props.size}>\n <div className={\"text-text-secondary dark:text-text-secondary-dark\"}>\n Entity not found\n </div>\n </EntityPreviewContainer>\n );\n }\n\n return <EntityPreviewBindingData\n {...props}\n entity={entity}/>;\n}\n\n/**\n * This view is used to display a preview of a entity.\n * It is used by default in reference fields and whenever a reference is displayed.\n */\nexport function EntityPreviewBinding({\n actions,\n disabled,\n hover,\n collection,\n previewKeys,\n onClick,\n size = \"medium\",\n includeId = true,\n includeTitle = true,\n includeEntityLink = true,\n includeImage = true,\n onSidePanelClick,\n entity\n}: EntityPreviewBindingProps) {\n\n return (\n <EntityPreviewContainer\n onClick={disabled ? undefined : onClick}\n hover={disabled ? undefined : hover}\n size={size}>\n <EntityPreviewBindingData\n actions={actions}\n collection={collection}\n previewKeys={previewKeys}\n size={size}\n includeId={includeId}\n includeTitle={includeTitle}\n includeEntityLink={includeEntityLink}\n includeImage={includeImage}\n onSidePanelClick={onSidePanelClick}\n entity={entity}\n />\n </EntityPreviewContainer>\n );\n}\n\nexport type EntityPreviewContainerProps = {\n children: React.ReactNode;\n hover?: boolean;\n fullwidth?: boolean;\n size?: PreviewSize;\n className?: string;\n style?: React.CSSProperties;\n onClick?: (e: React.SyntheticEvent) => void;\n};\n\nexport const EntityPreviewContainer = React.forwardRef<HTMLDivElement, EntityPreviewContainerProps>(({\n children,\n hover,\n onClick,\n size = \"medium\",\n style,\n className,\n fullwidth = true,\n ...props\n}, ref) => {\n return <div\n ref={ref}\n tabIndex={0}\n style={style}\n className={cls(\n \"bg-surface-card\",\n // On the shared 28/32/40/48 control scale. `44px` was between two\n // steps of it, so a reference in a form was 4px short of the field\n // next to it and their boxes never quite agreed.\n size === \"small\" ? \"min-h-[32px]\" : \"min-h-[48px]\",\n fullwidth ? \"w-full\" : \"\",\n \"items-center overflow-hidden\",\n hover ? \"hover:bg-surface-hover group-hover:bg-surface-hover\" : \"\",\n size === \"small\" ? \"p-1\" : \"px-2 py-1\",\n \"flex border rounded-lg\",\n onClick ? \"cursor-pointer\" : \"\",\n defaultBorderMixin,\n className)}\n role={onClick ? \"button\" : undefined}\n onClick={(event) => {\n if (onClick) {\n event.preventDefault();\n onClick(event);\n }\n }}\n onKeyDown={(event) => {\n if (onClick && (event.key === \"Enter\" || event.key === \" \")) {\n event.preventDefault();\n onClick(event);\n }\n }}\n {...props}>\n {children}\n </div>;\n});\n\nEntityPreviewContainer.displayName = \"EntityPreviewContainer\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4EA,SAAgB,yBAAyB,EACrC,SACA,YAAY,gBACZ,aACA,OAAO,UACP,YAAY,MACZ,kBACA,eAAe,MACf,oBAAoB,MACpB,eAAe,MACf,SAAS,QACT,UAC8B;CAE9B,MAAM,iBAAiB,kBAAkB;CACzC,MAAM,sBAAsB,uBAAuB;CACnD,MAAM,sBAAsB,aAAa;CACzC,MAAM,0BAA0B,2BAA2B;CAE3D,MAAM,+BAA+B,gCAAgC;CAErE,MAAM,aAAa,kBAAkB,6BAA6B,cAAc,OA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AAa,yBAAyB,QAAM,YAAyD,EACjG,UACA,OACA,SACA,OAAO,UACP,OACA,WACA,YAAY,MACZ,GAAG,SACJ,QAAQ;CACP,OAAO,oBAAC,OAAD;EACE;EACL,UAAU;EACH;EACP,WAAW,IACP,mBAIA,SAAS,UAAU,iBAAiB,gBACpC,YAAY,WAAW,IACvB,gCACA,QAAQ,wDAAwD,IAChE,SAAS,UAAU,QAAQ,aAC3B,0BACA,UAAU,mBAAmB,IAC7B,oBACA,SAAS;EACb,MAAM,UAAU,WAAW,KAAA;EAC3B,UAAU,UAAU;GAChB,IAAI,SAAS;IACT,MAAM,eAAe;IACrB,QAAQ,KAAK;GACjB;EACJ;EACA,YAAY,UAAU;GAClB,IAAI,YAAY,MAAM,QAAQ,WAAW,MAAM,QAAQ,MAAM;IACzD,MAAM,eAAe;IACrB,QAAQ,KAAK;GACjB;EACJ;EACA,GAAI;EACH;CACA,CAAA;AACT,CAAC;AAED,uBAAuB,cAAc"}
|
|
1
|
+
{"version":3,"file":"EntityPreviewBinding.js","names":[],"sources":["../../src/components/EntityPreviewBinding.tsx"],"sourcesContent":["\nimport type { Property } from \"@rebasepro/types\";\nimport { hasEntityId } from \"@rebasepro/common\";\nimport * as React from \"react\";\nimport { useEffect, useMemo } from \"react\";\n\nimport { Entity } from \"@rebasepro/types\";\nimport type { PreviewSize } from \"../types/components/PropertyPreviewProps\";\nimport { buildEnumLabel, getEntityImagePreviewPropertyKey } from \"@rebasepro/app\";\nimport { enumToObjectEntries } from \"@rebasepro/common\";\nimport {\n ArrowRightToLineIcon,\n Chip,\n cls,\n defaultBorderMixin,\n IconButton,\n Skeleton,\n Tooltip,\n Typography\n} from \"@rebasepro/ui\";\nimport { PropertyPreview, SkeletonPropertyComponent } from \"../preview\";\nimport {\n useAuthController,\n useCustomizationController,\n useData,\n ErrorView\n} from \"@rebasepro/app\";\nimport { useAnalyticsController } from \"@rebasepro/app\";\nimport { IconForView } from \"@rebasepro/app\";\nimport { getPropertyInPath } from \"../util/property_utils\";\nimport { resolveCollectionSlotKeys } from \"./CollectionViewBinding/usePreviewSlots\";\nimport { useEntityTitle } from \"../hooks/useEntityDisplay\";\nimport { getValueInPath } from \"@rebasepro/utils\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { useSidePanel } from \"../hooks/useSidePanel\";\nimport { EntityPreviewLayout, NestedEntityPreviewBoundary } from \"./EntityPreviewNesting\";\nimport { isEmptyPreviewValue } from \"../preview/util\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\n\nexport type EntityPreviewBindingProps = {\n size?: PreviewSize,\n actions?: React.ReactNode,\n collection?: AdminCollection,\n hover?: boolean;\n previewKeys?: string[],\n disabled?: boolean,\n entity: Entity<any>,\n includeId?: boolean,\n includeTitle?: boolean,\n includeEntityLink?: boolean,\n includeImage?: boolean,\n onClick?: (e: React.SyntheticEvent) => void;\n onSidePanelClick?: (entity: Entity) => void,\n};\n\nexport type EntityPreviewBindingDataProps = {\n size?: \"smallest\" | \"small\" | \"medium\" | \"large\",\n actions?: React.ReactNode,\n collection?: AdminCollection,\n previewKeys?: string[],\n entity: Entity<any>,\n onSidePanelClick?: (entity: Entity) => void,\n includeId?: boolean,\n includeTitle?: boolean,\n includeEntityLink?: boolean,\n includeImage?: boolean,\n /**\n * `row` draws the record as a line of a table row instead of a card: see\n * {@link EntityPreviewLayout}. No id, no open button — the title opens the\n * record — and only as many supporting lines as the row has room for.\n */\n layout?: EntityPreviewLayout,\n};\n\n/**\n * This component contains the main logic and content for displaying a entity preview,\n * without any container wrapper. Used internally by EntityPreviewBinding.\n */\nexport function EntityPreviewBindingData({\n actions,\n collection: collectionProp,\n previewKeys,\n size = \"medium\",\n includeId = true,\n onSidePanelClick,\n includeTitle = true,\n includeEntityLink = true,\n includeImage = true,\n layout = \"card\",\n entity\n}: EntityPreviewBindingDataProps) {\n\n const analyticsController = useAnalyticsController();\n const sidePanelController = useSidePanel();\n\n const collectionRegistryController = useCollectionRegistryController();\n\n const collection = collectionProp ?? collectionRegistryController.getCollection(entity.path);\n\n // Above the `!collection` return, because hooks are. `useEntityTitle`\n // tolerates a missing collection for exactly this reason.\n const title = useEntityTitle({\n collection,\n entity\n });\n\n // What the card says under the title: see `usePreviewCardKeys`.\n const { listProperties } = usePreviewCardKeys(collection, previewKeys);\n\n if (!collection) {\n return (\n <>\n <ErrorView error={`Collection not found: ${entity.path}`}/>\n </>\n );\n }\n\n const titleProperty = includeTitle ? title.source?.key : undefined;\n const imagePropertyKey = includeImage ? getEntityImagePreviewPropertyKey(collection) : undefined;\n const imageProperty = imagePropertyKey ? collection.properties[imagePropertyKey] : undefined;\n const ofProp = imageProperty && \"of\" in imageProperty ? imageProperty.of : undefined;\n const usedImageProperty = ofProp ? (Array.isArray(ofProp) ? ofProp[0] : ofProp) : imageProperty;\n const restProperties = listProperties.filter(p => p !== titleProperty && p !== imagePropertyKey);\n\n const openInSidePanel = () => {\n onSidePanelClick?.(entity);\n analyticsController.onAnalyticsEvent?.(\"entity_click_from_reference\", {\n path: entity.path,\n entityId: entity.id\n });\n sidePanelController.open({\n id: entity.id,\n path: entity.path,\n collection,\n updateUrl: true\n });\n };\n\n const imageValue = imagePropertyKey ? getValueInPath(entity.values, imagePropertyKey) : undefined;\n const usedImageValue = imageProperty !== undefined ? (\"of\" in imageProperty\n ? (((imageValue as unknown[]) ?? []).length > 0\n ? (imageValue as unknown[])[0] : undefined)\n : imageValue)\n : undefined;\n\n if (layout === \"row\")\n return <EntityRowPreviewContent size={size}\n entity={entity}\n collection={collection}\n title={title.value ?? String(entity.id)}\n imageProperty={usedImageProperty}\n imagePropertyKey={imagePropertyKey}\n imageValue={usedImageValue}\n supportingKeys={restProperties}\n onOpen={includeEntityLink ? openInSidePanel : undefined}/>;\n\n return (\n // Everything below renders *inside* this preview: a reference or\n // relation among the preview properties collapses to one line instead\n // of nesting another bordered card with its own id and action button.\n <NestedEntityPreviewBoundary>\n {/* `overflow-hidden`: the image slot is a fixed box, and a thumbnail\n that fails to load renders a \"file not found\" message sized for a\n full preview — which spilled across the title beside it. */}\n <div className={cls(\"flex shrink-0 overflow-hidden\", {\n \"w-6 h-6 mx-1 my-0.5\": size === \"small\" || size === \"smallest\",\n \"w-8 h-8 ml-1 mr-2 m-2 self-start\": size === \"medium\",\n \"w-10 h-10 ml-2 mr-2 m-2 self-start\": size === \"large\"\n })}>\n {usedImageProperty && usedImageValue ? <PropertyPreview property={usedImageProperty}\n propertyKey={imagePropertyKey as string}\n size={\"small\"}\n value={usedImageValue}/> : null}\n {(!usedImageProperty || !usedImageValue) ? <IconForView collectionOrView={collection}\n color={\"primary\"}\n size={size}\n className={\"m-auto\"}/> : null}\n </div>\n\n <div\n className={\"flex flex-col grow w-full m-1 shrink min-w-0 text-text-primary dark:text-text-primary-dark flex-1 mr-2\"}>\n\n {includeId && (\n entity\n ? <div className={\"block whitespace-nowrap overflow-hidden truncate\"}>\n <Typography variant={\"caption\"}\n color={\"disabled\"}\n className={\"font-mono\"}>\n {entity.id}\n </Typography>\n </div>\n : <Skeleton/>)}\n\n {/* A title that came from a property keeps that property's own\n rendering — an enum stays its coloured chip, a relation stays\n a link. A computed one is text, because that is all a\n resolver returns. */}\n {includeTitle && (titleProperty || title.value) && (\n <div\n className={\"truncate my-0.5 text-sm font-medium text-text-primary dark:text-text-primary-dark\"}>\n {!entity && titleProperty\n ? <SkeletonPropertyComponent\n property={getPropertyInPath(collection.properties, titleProperty) as Property}\n size={\"medium\"}/>\n : titleProperty\n ? <PropertyPreview\n propertyKey={titleProperty}\n value={title.source?.value}\n property={getPropertyInPath(collection.properties, titleProperty) as Property}\n size={\"medium\"}/>\n : title.value}\n </div>\n )}\n\n {restProperties && restProperties.map((key) => {\n const childProperty = getPropertyInPath(collection.properties, key);\n if (!childProperty) return null;\n\n const valueInPath = getValueInPath(entity.values, key);\n return (\n // `truncate` clamps a line of text; it does nothing to a\n // preview that renders blocks. Custom `admin.Preview`\n // components can render anything at all, so the height\n // is capped here as well — a card that loses the tail of\n // an unusual value beats a card the size of a document.\n <div key={\"ref_prev_\" + key}\n className={cls(\"truncate min-w-0 max-h-8 overflow-hidden\",\n restProperties.length > 1 ? \"my-0.5\" : \"my-0\")}>\n {\n entity\n ? <PropertyPreview\n propertyKey={key as string}\n value={valueInPath}\n property={childProperty as Property}\n size={\"small\"}/>\n : <SkeletonPropertyComponent\n property={childProperty as Property}\n size={\"small\"}/>\n }\n </div>\n );\n })}\n\n </div>\n\n {entity && includeEntityLink &&\n <div className=\"flex-shrink-0\">\n <Tooltip title={`See details for ${entity.id}`} className={\"shrink-0\"}>\n <IconButton aria-label={`See details for ${entity.id}`}\n size={\"small\"}\n className={size !== \"small\" ? \"self-start\" : \"\"}\n onClick={(e) => {\n e.stopPropagation();\n e.preventDefault();\n openInSidePanel();\n }}>\n <ArrowRightToLineIcon/>\n </IconButton>\n </Tooltip>\n </div>}\n\n {actions && <div className=\"flex-shrink-0\">{actions}</div>}\n </NestedEntityPreviewBoundary>\n );\n}\n\n/**\n * A record as a line of a table row: its image, a title that opens it, and the\n * supporting lines that fit — one at `medium`, two at `large`. Supporting\n * values that are empty are skipped rather than drawn as an empty bar, so the\n * line under a name is the first thing the record actually has to say.\n */\nfunction EntityRowPreviewContent({\n size,\n entity,\n collection,\n title,\n imageProperty,\n imagePropertyKey,\n imageValue,\n supportingKeys,\n onOpen\n}: {\n size: \"smallest\" | \"small\" | \"medium\" | \"large\";\n entity: Entity<Record<string, unknown>>;\n collection: AdminCollection;\n title: string;\n imageProperty?: Property;\n imagePropertyKey?: string;\n imageValue: unknown;\n supportingKeys: string[];\n onOpen?: () => void;\n}) {\n const maxLines = size === \"large\" ? 2 : 1;\n const lines = supportingKeys\n .map(key => ({\n key,\n property: getPropertyInPath(collection.properties, key),\n value: getValueInPath(entity.values, key)\n }))\n .filter((line): line is { key: string, property: Property, value: unknown } =>\n Boolean(line.property) && !isEmptyPreviewValue(line.value))\n .slice(0, maxLines);\n\n const titleNode = <span className={\"truncate\"}>{title}</span>;\n\n return (\n <NestedEntityPreviewBoundary>\n <div className={\"flex items-center gap-2.5 min-w-0 w-full text-left\"}>\n {imagePropertyKey && <div className={cls(\"flex shrink-0 items-center justify-center overflow-hidden rounded-md\",\n size === \"large\" ? \"w-10 h-10\" : \"w-8 h-8\")}>\n {imageProperty && imageValue\n ? <PropertyPreview property={imageProperty}\n propertyKey={imagePropertyKey}\n size={\"small\"}\n value={imageValue}/>\n : <IconForView collectionOrView={collection}\n color={\"primary\"}\n size={\"small\"}/>}\n </div>}\n <div className={\"flex flex-col min-w-0 flex-1\"}>\n <div className={\"flex min-w-0 text-sm font-medium text-text-primary dark:text-text-primary-dark\"}>\n {onOpen\n ? <Tooltip title={`See details for ${title}`} asChild={true}>\n <span role={\"button\"}\n tabIndex={0}\n className={\"inline-flex min-w-0 max-w-full cursor-pointer hover:underline underline-offset-2\"}\n // See InlineEntityPreview: a press does not\n // move the focus, or a table cell would\n // select itself mid-click.\n onMouseDown={(event) => event.preventDefault()}\n onClick={(event) => {\n event.preventDefault();\n event.stopPropagation();\n onOpen();\n }}\n onKeyDown={(event) => {\n if (event.key !== \"Enter\" && event.key !== \" \") return;\n event.preventDefault();\n event.stopPropagation();\n onOpen();\n }}>\n {titleNode}\n </span>\n </Tooltip>\n : titleNode}\n </div>\n {lines.map(({ key, property, value }) =>\n <div key={key}\n className={\"truncate min-w-0 max-h-5 overflow-hidden text-xs text-text-secondary dark:text-text-secondary-dark\"}>\n <PropertyPreview propertyKey={key}\n value={value}\n property={property}\n size={\"small\"}/>\n </div>)}\n </div>\n </div>\n </NestedEntityPreviewBoundary>\n );\n}\n\n/**\n * What a card says under its title, and the property its title would come\n * from — one answer for the card and for the skeleton standing in for it, so\n * the two always have the same lines.\n *\n * A stated list wins outright — `previewProperties` is the one place a\n * developer says \"show these\", and nothing here is allowed to second-guess\n * it. Failing that, the card fills the same slots as every other surface\n * that renders one record in a row: a supporting line and a status. It used\n * to take the first few properties in declaration order instead, which is\n * how an author card ended up rendering an entire Markdown biography.\n */\nfunction usePreviewCardKeys(collection: AdminCollection | undefined, previewKeys: string[] | undefined) {\n const authController = useAuthController();\n const customizationController = useCustomizationController();\n const statedKeys = previewKeys ?? (collection?.previewProperties as string[] | undefined);\n return useMemo(() => {\n if (!collection) return { listProperties: [], titleKey: undefined };\n const slotKeys = resolveCollectionSlotKeys(\n collection as AdminCollection<Record<string, unknown>>,\n authController,\n customizationController.propertyConfigs);\n const listProperties = statedKeys && statedKeys.length > 0\n ? statedKeys.filter(key => getPropertyInPath(collection.properties, key))\n : [slotKeys.subtitleKey, slotKeys.statusKey].filter(Boolean) as string[];\n return { listProperties, titleKey: slotKeys.titleKey };\n }, [statedKeys, collection, authController, customizationController.propertyConfigs]);\n}\n\n/**\n * A card that has not loaded yet, drawn as the card it will be: the image\n * slot, a title, one placeholder per line the card will show and the open\n * button's room. A single bar in a 48px box grew to the full card when the\n * record arrived and pushed everything under it down.\n *\n * Which lines a card shows is known before its record is — they come from\n * the collection, not the values — so the count is right whatever the\n * collection declares. Each placeholder sits in the line's own wrapper with\n * the line's own type, and an enum's is a chip, so a line is as tall\n * loading as loaded without any height written down here.\n */\nexport function EntityPreviewBindingSkeleton({\n collection,\n previewKeys,\n size = \"medium\",\n includeTitle = true,\n includeImage = true,\n includeEntityLink = true\n}: {\n collection: AdminCollection,\n previewKeys?: string[],\n size?: \"smallest\" | \"small\" | \"medium\" | \"large\",\n includeTitle?: boolean,\n includeImage?: boolean,\n includeEntityLink?: boolean\n}) {\n const { listProperties, titleKey } = usePreviewCardKeys(collection, previewKeys);\n const imagePropertyKey = includeImage ? getEntityImagePreviewPropertyKey(collection) : undefined;\n const lines = listProperties.filter(key => key !== (includeTitle ? titleKey : undefined) && key !== imagePropertyKey);\n\n return (\n <>\n <div className={cls(\"flex shrink-0 overflow-hidden\", {\n \"w-6 h-6 mx-1 my-0.5\": size === \"small\" || size === \"smallest\",\n \"w-8 h-8 ml-1 mr-2 m-2 self-start\": size === \"medium\",\n \"w-10 h-10 ml-2 mr-2 m-2 self-start\": size === \"large\"\n })}>\n {imagePropertyKey\n ? <Skeleton className={\"w-full h-full\"}/>\n : <IconForView collectionOrView={collection}\n color={\"primary\"}\n size={size}\n className={\"m-auto\"}/>}\n </div>\n\n <div className={\"flex flex-col grow w-full m-1 shrink min-w-0 text-text-primary dark:text-text-primary-dark flex-1 mr-2\"}\n aria-busy={true}>\n {includeTitle && (\n <div className={\"truncate my-0.5 text-sm font-medium\"}>\n {\"\\u200b\"}<Skeleton className={\"inline-block align-middle\"} width={160}/>\n </div>\n )}\n {lines.map(key => {\n const property = getPropertyInPath(collection.properties, key);\n if (!property) return null;\n return (\n <div key={\"ref_prev_\" + key}\n className={cls(\"truncate min-w-0 max-h-8 overflow-hidden\",\n lines.length > 1 ? \"my-0.5\" : \"my-0\")}>\n <SkeletonCardLine property={property as Property}/>\n </div>\n );\n })}\n </div>\n\n {includeEntityLink &&\n <div className=\"flex-shrink-0\" aria-hidden={true}>\n <IconButton size={\"small\"}\n aria-label=\"See details\"\n tabIndex={-1}\n disabled={true}\n className={cls(\"invisible\", size !== \"small\" ? \"self-start\" : \"\")}>\n <ArrowRightToLineIcon/>\n </IconButton>\n </div>}\n </>\n );\n}\n\n/** One card line, loading: a chip for an enum, as the loaded line draws it, else a bar in a line of text. */\nfunction SkeletonCardLine({ property }: { property: Property }) {\n const enumValues = (property.type === \"string\" || property.type === \"number\") ? property.enum : undefined;\n if (enumValues) {\n const [first] = enumToObjectEntries(enumValues);\n return (\n <Chip size={\"small\"}>\n <span className={\"invisible\"}>{first ? buildEnumLabel(first) : \"\\u00a0\"}</span>\n </Chip>\n );\n }\n return (\n <span className={\"text-sm\"}>\n {\"\\u200b\"}<Skeleton className={\"inline-block align-middle\"} width={120}/>\n </span>\n );\n}\n\nexport function EntityPreviewBindingWithId({\n entityId,\n path,\n ...props\n}: Omit<EntityPreviewBindingProps, \"entity\"> & {\n entityId: string | number;\n path: string;\n databaseId?: string;\n}) {\n\n const [entity, setEntity] = React.useState<Entity | undefined>();\n const [dataLoading, setDataLoading] = React.useState(false);\n const dataClient = useData();\n\n useEffect(() => {\n let isMounted = true;\n if (!hasEntityId(entityId) || !path) {\n setEntity(undefined);\n return;\n }\n const fetchOne = async () => {\n setDataLoading(true);\n try {\n const fetchedEntity = await dataClient.collection(path).findById(entityId);\n if (isMounted) {\n setEntity(fetchedEntity);\n }\n } catch (error) {\n console.error(\"Error fetching entity:\", error);\n if (isMounted) {\n setEntity(undefined);\n }\n } finally {\n if (isMounted) {\n setDataLoading(false);\n }\n }\n }\n\n fetchOne();\n\n return () => {\n isMounted = false;\n }\n }, [entityId, path]);\n\n if (dataLoading && !entity) {\n return (\n <EntityPreviewContainer\n hover={props.hover}\n size={props.size}>\n <Skeleton/>\n </EntityPreviewContainer>\n );\n }\n\n if (!entity) {\n return (\n <EntityPreviewContainer\n hover={props.hover}\n size={props.size}>\n <div className={\"text-text-secondary dark:text-text-secondary-dark\"}>\n Entity not found\n </div>\n </EntityPreviewContainer>\n );\n }\n\n return <EntityPreviewBindingData\n {...props}\n entity={entity}/>;\n}\n\n/**\n * This view is used to display a preview of a entity.\n * It is used by default in reference fields and whenever a reference is displayed.\n */\nexport function EntityPreviewBinding({\n actions,\n disabled,\n hover,\n collection,\n previewKeys,\n onClick,\n size = \"medium\",\n includeId = true,\n includeTitle = true,\n includeEntityLink = true,\n includeImage = true,\n onSidePanelClick,\n entity\n}: EntityPreviewBindingProps) {\n\n return (\n <EntityPreviewContainer\n onClick={disabled ? undefined : onClick}\n hover={disabled ? undefined : hover}\n size={size}>\n <EntityPreviewBindingData\n actions={actions}\n collection={collection}\n previewKeys={previewKeys}\n size={size}\n includeId={includeId}\n includeTitle={includeTitle}\n includeEntityLink={includeEntityLink}\n includeImage={includeImage}\n onSidePanelClick={onSidePanelClick}\n entity={entity}\n />\n </EntityPreviewContainer>\n );\n}\n\nexport type EntityPreviewContainerProps = {\n children: React.ReactNode;\n hover?: boolean;\n fullwidth?: boolean;\n size?: PreviewSize;\n className?: string;\n style?: React.CSSProperties;\n onClick?: (e: React.SyntheticEvent) => void;\n};\n\nexport const EntityPreviewContainer = React.forwardRef<HTMLDivElement, EntityPreviewContainerProps>(({\n children,\n hover,\n onClick,\n size = \"medium\",\n style,\n className,\n fullwidth = true,\n ...props\n}, ref) => {\n return <div\n ref={ref}\n tabIndex={0}\n style={style}\n className={cls(\n \"bg-surface-card\",\n // On the shared 28/32/40/48 control scale. `44px` was between two\n // steps of it, so a reference in a form was 4px short of the field\n // next to it and their boxes never quite agreed.\n size === \"small\" ? \"min-h-[32px]\" : \"min-h-[48px]\",\n fullwidth ? \"w-full\" : \"\",\n \"items-center overflow-hidden\",\n hover ? \"hover:bg-surface-hover group-hover:bg-surface-hover\" : \"\",\n size === \"small\" ? \"p-1\" : \"px-2 py-1\",\n \"flex border rounded-lg\",\n onClick ? \"cursor-pointer\" : \"\",\n defaultBorderMixin,\n className)}\n role={onClick ? \"button\" : undefined}\n onClick={(event) => {\n if (onClick) {\n event.preventDefault();\n onClick(event);\n }\n }}\n onKeyDown={(event) => {\n if (onClick && (event.key === \"Enter\" || event.key === \" \")) {\n event.preventDefault();\n onClick(event);\n }\n }}\n {...props}>\n {children}\n </div>;\n});\n\nEntityPreviewContainer.displayName = \"EntityPreviewContainer\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA8EA,SAAgB,yBAAyB,EACrC,SACA,YAAY,gBACZ,aACA,OAAO,UACP,YAAY,MACZ,kBACA,eAAe,MACf,oBAAoB,MACpB,eAAe,MACf,SAAS,QACT,UAC8B;CAE9B,MAAM,sBAAsB,uBAAuB;CACnD,MAAM,sBAAsB,aAAa;CAEzC,MAAM,+BAA+B,gCAAgC;CAErE,MAAM,aAAa,kBAAkB,6BAA6B,cAAc,OAAO,IAAI;CAI3F,MAAM,QAAQ,eAAe;EACzB;EACA;CACJ,CAAC;CAGD,MAAM,EAAE,mBAAmB,mBAAmB,YAAY,WAAW;CAErE,IAAI,CAAC,YACD,OACI,oB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;cAAc,QAAQ,eAAe,KAAK,IAAI;GAAe,CAAA;EAC5E,CAAA;CAEd;CACA,OACI,qBAAC,QAAD;EAAM,WAAW;YAAjB,CACK,KAAS,oBAAC,UAAD;GAAU,WAAW;GAA6B,OAAO;EAAK,CAAA,CACtE;;AAEd;;;;;AA+EA,SAAgB,qBAAqB,EACjC,SACA,UACA,OACA,YACA,aACA,SACA,OAAO,UACP,YAAY,MACZ,eAAe,MACf,oBAAoB,MACpB,eAAe,MACf,kBACA,UAC0B;CAE1B,OACI,oBAAC,wBAAD;EACI,SAAS,WAAW,KAAA,IAAY;EAChC,OAAO,WAAW,KAAA,IAAY;EACxB;YACN,oBAAC,0BAAD;GACa;GACG;GACC;GACP;GACK;GACG;GACK;GACL;GACI;GACV;EACX,CAAA;CACmB,CAAA;AAEhC;AAYA,IAAa,yBAAyB,QAAM,YAAyD,EACjG,UACA,OACA,SACA,OAAO,UACP,OACA,WACA,YAAY,MACZ,GAAG,SACJ,QAAQ;CACP,OAAO,oBAAC,OAAD;EACE;EACL,UAAU;EACH;EACP,WAAW,IACP,mBAIA,SAAS,UAAU,iBAAiB,gBACpC,YAAY,WAAW,IACvB,gCACA,QAAQ,wDAAwD,IAChE,SAAS,UAAU,QAAQ,aAC3B,0BACA,UAAU,mBAAmB,IAC7B,oBACA,SAAS;EACb,MAAM,UAAU,WAAW,KAAA;EAC3B,UAAU,UAAU;GAChB,IAAI,SAAS;IACT,MAAM,eAAe;IACrB,QAAQ,KAAK;GACjB;EACJ;EACA,YAAY,UAAU;GAClB,IAAI,YAAY,MAAM,QAAQ,WAAW,MAAM,QAAQ,MAAM;IACzD,MAAM,eAAe;IACrB,QAAQ,KAAK;GACjB;EACJ;EACA,GAAI;EACH;CACA,CAAA;AACT,CAAC;AAED,uBAAuB,cAAc"}
|
package/dist/index.d.ts
CHANGED
|
@@ -72,3 +72,5 @@ export type { DetailViewBindingProps } from "./components/DetailViewBinding.js";
|
|
|
72
72
|
export { NavigationCardBinding } from "./components/HomePage/NavigationCardBinding.js";
|
|
73
73
|
export { NavigationGroup } from "./components/HomePage/NavigationGroup.js";
|
|
74
74
|
export { FavouritesView } from "./components/HomePage/FavouritesView.js";
|
|
75
|
+
export { SavedAppsView, savedAppsView } from "./saved_apps/SavedAppsView.js";
|
|
76
|
+
export { SavedAppFrame, sandboxedViewDocument } from "./saved_apps/saved_app_frame.js";
|
package/dist/index.js
CHANGED
|
@@ -181,4 +181,6 @@ import { CollectionGenerationApiError, DEFAULT_COLLECTION_GENERATION_ENDPOINT, b
|
|
|
181
181
|
import { MissingReferenceWidget } from "./collection_editor/ui/MissingReferenceWidget.js";
|
|
182
182
|
import { getFullId, getFullIdPath, idToPropertiesPath, namespaceToPropertiesOrderPath, namespaceToPropertiesPath } from "./collection_editor/ui/collection_editor/util.js";
|
|
183
183
|
import { SmallNavigationCard } from "./components/HomePage/SmallNavigationCard.js";
|
|
184
|
-
|
|
184
|
+
import { SavedAppFrame, sandboxedViewDocument } from "./saved_apps/saved_app_frame.js";
|
|
185
|
+
import { SavedAppsView, savedAppsView } from "./saved_apps/SavedAppsView.js";
|
|
186
|
+
export { AdditionalFieldValue, AdminModeSyncer, AppBar, ArrayContainer, ArrayCustomShapedFieldBinding, ArrayEnumPreview, ArrayOfMapsPreview, ArrayOfReferencesFieldBinding, ArrayOfReferencesPreview, ArrayOfStorageComponentsPreview, ArrayOfStringsPreview, ArrayOneOfPreview, ArrayPropertyEnumPreview, ArrayPropertyPreview, BasicExportAction, BlockFieldBinding, BooleanFilterField, BooleanPreview, CollectionAddButton, CollectionCardViewBinding, CollectionFiltersButton, CollectionGenerationApiError, CollectionPanel, CollectionRegistryContext, CollectionRowActions, CollectionSearchBar, CollectionTableBinding, CollectionTableToolbar, CollectionToolbar, CollectionViewActions, CollectionViewBinding, CollectionViewModeToggle, CollectionsProvider, CreationResultDialog, CustomViewRoute, DEFAULT_COLLECTION_GENERATION_ENDPOINT, DEFAULT_FIELD_CONFIGS, DataNewPropertiesMapping, DatePreview, DateTimeFieldBinding, DateTimeFilterField, DefaultDrawer, DetailViewBinding, Drawer, DrawerExpansionContext, DrawerFooterActions, DrawerNavigationGroup, DrawerNavigationItem, EXPORT_PAGE_SIZE, EditViewBinding, EditorAIControllerProvider, EditorCollectionAction, EmptyValue, EntityCardBinding, EntityForm, EntityFormBinding, EntityFormPanel, EntityPreviewBinding, EntityTableCell, EntityViewBinding, EnumValuesChip, ExportCollectionAction, FavouritesView, FieldBlock, FieldCaption, FieldHelperText, FieldValue, FormField, FormRail, FormSections, Highlighted, IMPORT_BATCH_MAX_BYTES, IMPORT_BATCH_SIZE, ImagePreview, ImportCollectionAction, ImportConversionProblems, ImportDataPreview, ImportFileUpload, ImportNewPropertyFieldPreview, ImportSaveInProgress, InlineEntityListPreview, KeyValueFieldBinding, KeyValuePreview, LABEL_ICON_SIZE, LabelWithIcon, LiveSchemaError, MAX_EXPORT_ROWS, MAX_SELECTION_ROWS, MapFieldBinding, MapPropertyPreview, MarkdownEditorFieldBinding, MatchExplanation, MissingReferenceWidget, MultiSelectFieldBinding, NAVIGATION_DEFAULT_GROUP_NAME, NavigationCard, NavigationCardBinding, NavigationGroup, NavigationStateContext, NestedEntityPreviewBoundary, NumberPropertyPreview, PropertyConfigBadge, PropertyFieldBinding, PropertyKeyHint, PropertyPreview, PropertySelectEntry, PropertyTableCell, ReadOnlyFieldBinding, RebaseAuthGate, RebaseCMS, RebaseLayout, RebaseNavigation, RebaseRoute, RebaseRouteDefs, RebaseShell, RecordDetail, RecordForm, RecordMeta, ReferenceFieldBinding, ReferenceFilterField, ReferencePreview, ReferenceWidget, RelationFilterField, RelationPreview, RepeatFieldBinding, SELECTION_PAGE_SIZE, SavedAppFrame, SavedAppsView, Scaffold, SchemaChangeCancelled, SearchIconsView, SelectFieldBinding, SelectableTable, SelectableTableContext, SelectionMenu, SelectionTableBinding, SideDialogs, SidePanelControllerContext, SidePanelProvider, SkeletonPropertyComponent, SlotValue, SmallNavigationCard, StorageThumbnail, StorageThumbnailInternal, StorageUploadFieldBinding, StringNumberFilterField, StringPropertyPreview, SwitchFieldBinding, TagChips, TextFieldBinding, UrlComponentPreview, UrlContext, UserPreview, VectorFieldBinding, VirtualTableInput, addInitialSlash, asUnavailable, buildCollectionGenerationCallback, buildSidePanelsFromUrl, convertDataToEntity, convertFileToJson, convertImportData, copyEntityAction, createLiveSchemaClient, createStaticDataController, deleteEntityAction, detectCsvDelimiter, downloadBlob, downloadDataAsCsv, downloadEntitiesExport, editEntityAction, entityActionName, entryToCSVRow, escapeCsvFormula, extractTouchedValues, fetchAllEntitiesForExport, fieldLabel, flattenEntry, formatDatePreview, fromSerializableCollectionConfig, fromSerializableCollectionConfigs, fromSerializableProperties, fromSerializableProperty, getBracketNotation, getChanges, getCollectionBySlugWithin, getCollectionPathsCombinations, getDatePropertyMode, getDatePropertyTimezone, getDefaultFieldConfig, getDefaultFieldId, getDefaultPropertiesOrder, getEntityCSVExportableData, getEntityJsonExportableData, getEntityPreviewKeys, getEntityTitlePropertyKey, getEntityTitlePropertyKeyForEntity, getEntityViewWidth, getFieldConfig, getFieldId, getFullId, getFullIdPath, getIconForProperty, getIconForWidget, getInferenceType, getInitialEntityValues, getLastSegment, getParentLinkValues, getPropertiesWithPropertiesOrder, getPropertyInPath, getResolvedPropertyInPath, getTouchedPropertyValues, getUnappliedLocalChanges, getUserLabel, idToPropertiesPath, isEmptyPreviewValue, isReferenceProperty, isRelationProperty, isSchemaChangeCancelled, isSelfLabellingProperty, mapPropertiesToConfigs, mapPropertyToConfig, mappedColumnTarget, mergeEntityActions, namespaceToPropertiesOrderPath, namespaceToPropertiesPath, normalizeDeprecatedSidePanelProps, overlayEdit, parseCsvRows, parseCsvToObjects, processValueMapping, propertiesToColumns, removeEmptyContainers, removeInitialAndTrailingSlashes, removeInitialSlash, removeTrailingSlash, renderSkeletonCaptionText, renderSkeletonIcon, renderSkeletonImageThumbnail, renderSkeletonText, resetPasswordAction, resolveCollectionPathIds, resolveCollectionSlotKeys, resolveEntityAction, resolveEntityActionState, resolveEntityView, resolveNavigationFrom, resolveSelection, sandboxedViewDocument, sanitizeUrl, saveImportedEntities, savedAppsView, selectionQueryToFindParams, serializeSelectionQuery, slashDateOrdersByColumn, spanClass, toSerializableCollectionConfig, toSerializableProperties, toSerializableProperty, unescapeCsvFormula, unlinkEntityAction, useAdminContext, useApp, useBreadcrumbsController, useBuildCollectionRegistryController, useBuildNavigationStateController, useBuildSidePanel, useBuildUrlController, useChildViewSource, useClearRestoreValue, useCollectionDataController, useCollectionEditorController, useCollectionLargeLayout, useCollectionRegistryController, useCollectionSlotKeys, useCollectionsConfigController, useDateFnsLocale, useDrawerExpandedWhile, useDrawerExpansion, useEntitySlots, useEntityTitle, useHistory, useImagePlace, useImportConfig, useJsonCollectionsConfigController, useLiveSchemaEditing, useLocalCollectionsConfigController, useNavigationStateController, useProvidedEditorAIController, useResolvedCollections, useResolvedNavigationFrom, useResolvedUser, useResolvedViews, useSearchExplanation, useSelectionController, useSelectionDialog, useSideDialogContext, useSideDialogsController, useSidePanel, useToolbarLabels, useTopLevelNavigation, useUrlController, validateCollectionJson, zodToFormErrors };
|
|
@@ -34,11 +34,31 @@ export interface HostContext {
|
|
|
34
34
|
availableDisplayModes?: DisplayMode[];
|
|
35
35
|
locale?: string;
|
|
36
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* What the view needs of its channel: the call that opened it, the host's
|
|
39
|
+
* context, and the tools. {@link McpAppBridge} is the MCP Apps host's; a
|
|
40
|
+
* page that reaches the server another way (an artifact, through the
|
|
41
|
+
* viewer's connector) brings its own.
|
|
42
|
+
*/
|
|
43
|
+
export interface ViewBridge {
|
|
44
|
+
readonly hostContext: HostContext;
|
|
45
|
+
watchHostContext(watcher: (context: HostContext) => void): () => void;
|
|
46
|
+
ontoolinput: ((args: Record<string, unknown>) => void) | undefined;
|
|
47
|
+
ontoolresult: ((result: ToolResult) => void) | undefined;
|
|
48
|
+
connect(appInfo: {
|
|
49
|
+
name: string;
|
|
50
|
+
version: string;
|
|
51
|
+
}): Promise<void>;
|
|
52
|
+
callTool(name: string, args: Record<string, unknown>): Promise<ToolResult>;
|
|
53
|
+
updateModelContext(text: string): Promise<void>;
|
|
54
|
+
requestDisplayMode(mode: DisplayMode): Promise<DisplayMode | undefined>;
|
|
55
|
+
sizeChanged(height: number): void;
|
|
56
|
+
}
|
|
37
57
|
/** The host end of the channel: the parent window, in a host. */
|
|
38
58
|
export interface HostWindow {
|
|
39
59
|
postMessage(message: unknown, targetOrigin: string): void;
|
|
40
60
|
}
|
|
41
|
-
export declare class McpAppBridge {
|
|
61
|
+
export declare class McpAppBridge implements ViewBridge {
|
|
42
62
|
onhostcontext?: (context: HostContext) => void;
|
|
43
63
|
/** Everything the host has said about its context so far, each update merged in. */
|
|
44
64
|
hostContext: HostContext;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge.js","names":[],"sources":["../../src/mcp_view/bridge.ts"],"sourcesContent":["/**\n * The view's side of the MCP Apps protocol (`io.modelcontextprotocol/ui`,\n * revision 2026-01-26): JSON-RPC 2.0 over `postMessage` with the host window.\n *\n * Hand-written rather than taken from `@modelcontextprotocol/ext-apps`, whose\n * `App` carries the MCP SDK and zod — half a megabyte, in a document a host\n * downloads for every table it shows. A view needs a handful of messages:\n *\n * - `ui/initialize` → the host's context (theme, display mode), then\n * `ui/notifications/initialized`;\n * - the host's `ui/notifications/tool-input` and `…/tool-result`: the call\n * that opened this view, and its answer;\n * - `tools/call`, which the host relays to the MCP server with its own\n * credential — the view holds none;\n * - `ui/update-model-context`, to tell the model what the person did here;\n * - `ui/notifications/size-changed`, so the host sizes the iframe to fit;\n * - `ui/request-display-mode`, to open the view fullscreen where the host\n * offers it.\n */\n\nexport const APPS_PROTOCOL_VERSION = \"2026-01-26\";\n\nexport interface ToolResult {\n content?: Array<{ type: string; text?: string }>;\n structuredContent?: unknown;\n isError?: boolean;\n}\n\nexport type DisplayMode = \"inline\" | \"fullscreen\" | \"pip\";\n\n/** The modes this view can be shown in. Declared at the handshake. */\nconst VIEW_DISPLAY_MODES: DisplayMode[] = [\"inline\", \"fullscreen\"];\n\nexport interface HostContext {\n theme?: \"light\" | \"dark\";\n displayMode?: DisplayMode;\n /** The modes the host will show this view in; absent, only the one it is in. */\n availableDisplayModes?: DisplayMode[];\n locale?: string;\n}\n\ninterface Pending {\n resolve: (result: unknown) => void;\n reject: (error: Error) => void;\n}\n\ntype JsonRpcId = string | number;\n\n/** The host end of the channel: the parent window, in a host. */\nexport interface HostWindow {\n postMessage(message: unknown, targetOrigin: string): void;\n}\n\nexport class McpAppBridge {\n onhostcontext?: (context: HostContext) => void;\n\n /** Everything the host has said about its context so far, each update merged in. */\n hostContext: HostContext = {};\n private readonly contextWatchers = new Set<(context: HostContext) => void>();\n\n /** Called with the whole context now and on every change; returns the unsubscribe. */\n watchHostContext(watcher: (context: HostContext) => void): () => void {\n this.contextWatchers.add(watcher);\n watcher(this.hostContext);\n return () => {\n this.contextWatchers.delete(watcher);\n };\n }\n\n /**\n * The call that opened this view, and its answer. Kept, because the host\n * may send them before a handler is set — a React effect runs after the\n * first paint — and it sends each once.\n */\n toolInput?: Record<string, unknown>;\n toolResult?: ToolResult;\n private inputHandler?: (args: Record<string, unknown>) => void;\n private resultHandler?: (result: ToolResult) => void;\n\n set ontoolinput(handler: ((args: Record<string, unknown>) => void) | undefined) {\n this.inputHandler = handler;\n if (handler && this.toolInput) handler(this.toolInput);\n }\n\n set ontoolresult(handler: ((result: ToolResult) => void) | undefined) {\n this.resultHandler = handler;\n if (handler && this.toolResult) handler(this.toolResult);\n }\n\n private nextId = 1;\n private connected = false;\n private height?: number;\n private readonly pending = new Map<JsonRpcId, Pending>();\n private readonly host: HostWindow;\n\n /** `events` is where the host's messages arrive: this view's window. */\n constructor(host: HostWindow = window.parent, events: EventTarget = window) {\n this.host = host;\n events.addEventListener(\"message\", this.receive);\n }\n\n async connect(appInfo: { name: string; version: string }): Promise<void> {\n const result = await this.request(\"ui/initialize\", {\n appInfo,\n appCapabilities: { availableDisplayModes: VIEW_DISPLAY_MODES },\n protocolVersion: APPS_PROTOCOL_VERSION\n });\n if (isRecord(result) && isRecord(result.hostContext)) this.contextChanged(hostContextOf(result.hostContext));\n this.notify(\"ui/notifications/initialized\", {});\n this.connected = true;\n // A size measured before the handshake is held until now: nothing\n // but `ui/initialize` may reach the host before it.\n if (this.height !== undefined) this.notify(\"ui/notifications/size-changed\", { height: this.height });\n }\n\n /** A tool on this view's MCP server, called through the host. */\n async callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {\n const result = await this.request(\"tools/call\", { name, arguments: args });\n return isRecord(result) ? toolResultOf(result) : {};\n }\n\n /**\n * What the model should know about this view, sent with the person's next\n * message. Each call replaces the last.\n */\n async updateModelContext(text: string): Promise<void> {\n await this.request(\"ui/update-model-context\", { content: [{ type: \"text\", text }] });\n }\n\n /**\n * Ask the host to show this view in `mode`. The answer is the mode it is\n * in now, which may not be the one asked for.\n */\n async requestDisplayMode(mode: DisplayMode): Promise<DisplayMode | undefined> {\n const result = await this.request(\"ui/request-display-mode\", { mode });\n return isRecord(result) && isDisplayMode(result.mode) ? result.mode : undefined;\n }\n\n /** The document's height, for the host to size the iframe to. Sent when it changes. */\n sizeChanged(height: number): void {\n if (height === this.height) return;\n this.height = height;\n if (this.connected) this.notify(\"ui/notifications/size-changed\", { height });\n }\n\n private contextChanged(update: HostContext): void {\n this.hostContext = { ...this.hostContext, ...update };\n this.onhostcontext?.(update);\n for (const watcher of this.contextWatchers) watcher(this.hostContext);\n }\n\n private request(method: string, params: Record<string, unknown>): Promise<unknown> {\n const id = this.nextId++;\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n this.host.postMessage({ jsonrpc: \"2.0\", id, method, params }, \"*\");\n });\n }\n\n private notify(method: string, params: Record<string, unknown>): void {\n this.host.postMessage({ jsonrpc: \"2.0\", method, params }, \"*\");\n }\n\n private respond(id: JsonRpcId, result: Record<string, unknown>): void {\n this.host.postMessage({ jsonrpc: \"2.0\", id, result }, \"*\");\n }\n\n private readonly receive = (event: Event): void => {\n // Only the host speaks to this view. The sandbox gives the iframe an\n // opaque origin, so the window is the check, not the origin.\n if (!(event instanceof MessageEvent) || event.source !== this.host) return;\n const message: unknown = event.data;\n if (!isRecord(message) || message.jsonrpc !== \"2.0\") return;\n const id = typeof message.id === \"string\" || typeof message.id === \"number\" ? message.id : undefined;\n\n if (id !== undefined && (\"result\" in message || \"error\" in message)) {\n const pending = this.pending.get(id);\n if (!pending) return;\n this.pending.delete(id);\n if (isRecord(message.error)) pending.reject(new Error(String(message.error.message ?? \"The host refused the request.\")));\n else pending.resolve(message.result);\n return;\n }\n\n const params = isRecord(message.params) ? message.params : {};\n switch (message.method) {\n case \"ui/notifications/tool-input\":\n this.toolInput = isRecord(params.arguments) ? params.arguments : {};\n this.inputHandler?.(this.toolInput);\n return;\n case \"ui/notifications/tool-result\":\n this.toolResult = toolResultOf(params);\n this.resultHandler?.(this.toolResult);\n return;\n case \"ui/notifications/host-context-changed\":\n this.contextChanged(hostContextOf(params));\n return;\n // Requests the host may send. Nothing to clean up, nothing to report.\n case \"ui/resource-teardown\":\n case \"ping\":\n if (id !== undefined) this.respond(id, {});\n return;\n }\n };\n}\n\nfunction toolResultOf(value: Record<string, unknown>): ToolResult {\n return {\n content: Array.isArray(value.content)\n ? value.content.filter(isRecord).map(block => ({\n type: String(block.type),\n ...(typeof block.text === \"string\" && { text: block.text })\n }))\n : undefined,\n structuredContent: value.structuredContent,\n isError: value.isError === true\n };\n}\n\n/** The fields of the host's context this view reads. A partial update leaves the rest out. */\nfunction hostContextOf(value: Record<string, unknown>): HostContext {\n return {\n ...((value.theme === \"light\" || value.theme === \"dark\") && { theme: value.theme }),\n ...(isDisplayMode(value.displayMode) && { displayMode: value.displayMode }),\n ...(Array.isArray(value.availableDisplayModes) && {\n availableDisplayModes: value.availableDisplayModes.filter(isDisplayMode)\n }),\n ...(typeof value.locale === \"string\" && { locale: value.locale })\n };\n}\n\nfunction isDisplayMode(value: unknown): value is DisplayMode {\n return value === \"inline\" || value === \"fullscreen\" || value === \"pip\";\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,wBAAwB;;AAWrC,IAAM,qBAAoC,CAAC,UAAU,YAAY;AAsBjE,IAAa,eAAb,MAA0B;CACtB;;CAGA,cAA2B,CAAC;CAC5B,kCAAmC,IAAI,IAAoC;;CAG3E,iBAAiB,SAAqD;EAClE,KAAK,gBAAgB,IAAI,OAAO;EAChC,QAAQ,KAAK,WAAW;EACxB,aAAa;GACT,KAAK,gBAAgB,OAAO,OAAO;EACvC;CACJ;;;;;;CAOA;CACA;CACA;CACA;CAEA,IAAI,YAAY,SAAgE;EAC5E,KAAK,eAAe;EACpB,IAAI,WAAW,KAAK,WAAW,QAAQ,KAAK,SAAS;CACzD;CAEA,IAAI,aAAa,SAAqD;EAClE,KAAK,gBAAgB;EACrB,IAAI,WAAW,KAAK,YAAY,QAAQ,KAAK,UAAU;CAC3D;CAEA,SAAiB;CACjB,YAAoB;CACpB;CACA,0BAA2B,IAAI,IAAwB;CACvD;;CAGA,YAAY,OAAmB,OAAO,QAAQ,SAAsB,QAAQ;EACxE,KAAK,OAAO;EACZ,OAAO,iBAAiB,WAAW,KAAK,OAAO;CACnD;CAEA,MAAM,QAAQ,SAA2D;EACrE,MAAM,SAAS,MAAM,KAAK,QAAQ,iBAAiB;GAC/C;GACA,iBAAiB,EAAE,uBAAuB,mBAAmB;GAC7D,iBAAiB;EACrB,CAAC;EACD,IAAI,SAAS,MAAM,KAAK,SAAS,OAAO,WAAW,GAAG,KAAK,eAAe,cAAc,OAAO,WAAW,CAAC;EAC3G,KAAK,OAAO,gCAAgC,CAAC,CAAC;EAC9C,KAAK,YAAY;EAGjB,IAAI,KAAK,WAAW,KAAA,GAAW,KAAK,OAAO,iCAAiC,EAAE,QAAQ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AC7D,EAAE,IACA,KAAA;EACN,mBAAmB,MAAM;EACzB,SAAS,MAAM,YAAY;CAC/B;AACJ;;AAGA,SAAS,cAAc,OAA6C;CAChE,OAAO;EACH,IAAK,MAAM,UAAU,WAAW,MAAM,UAAU,WAAW,EAAE,OAAO,MAAM,MAAM;EAChF,GAAI,cAAc,MAAM,WAAW,KAAK,EAAE,aAAa,MAAM,YAAY;EACzE,GAAI,MAAM,QAAQ,MAAM,qBAAqB,KAAK,EAC9C,uBAAuB,MAAM,sBAAsB,OAAO,aAAa,EAC3E;EACA,GAAI,OAAO,MAAM,WAAW,YAAY,EAAE,QAAQ,MAAM,OAAO;CACnE;AACJ;AAEA,SAAS,cAAc,OAAsC;CACzD,OAAO,UAAU,YAAY,UAAU,gBAAgB,UAAU;AACrE;AAEA,SAAgB,SAAS,OAAkD;CACvE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC9E"}
|
|
1
|
+
{"version":3,"file":"bridge.js","names":[],"sources":["../../src/mcp_view/bridge.ts"],"sourcesContent":["/**\n * The view's side of the MCP Apps protocol (`io.modelcontextprotocol/ui`,\n * revision 2026-01-26): JSON-RPC 2.0 over `postMessage` with the host window.\n *\n * Hand-written rather than taken from `@modelcontextprotocol/ext-apps`, whose\n * `App` carries the MCP SDK and zod — half a megabyte, in a document a host\n * downloads for every table it shows. A view needs a handful of messages:\n *\n * - `ui/initialize` → the host's context (theme, display mode), then\n * `ui/notifications/initialized`;\n * - the host's `ui/notifications/tool-input` and `…/tool-result`: the call\n * that opened this view, and its answer;\n * - `tools/call`, which the host relays to the MCP server with its own\n * credential — the view holds none;\n * - `ui/update-model-context`, to tell the model what the person did here;\n * - `ui/notifications/size-changed`, so the host sizes the iframe to fit;\n * - `ui/request-display-mode`, to open the view fullscreen where the host\n * offers it.\n */\n\nexport const APPS_PROTOCOL_VERSION = \"2026-01-26\";\n\nexport interface ToolResult {\n content?: Array<{ type: string; text?: string }>;\n structuredContent?: unknown;\n isError?: boolean;\n}\n\nexport type DisplayMode = \"inline\" | \"fullscreen\" | \"pip\";\n\n/** The modes this view can be shown in. Declared at the handshake. */\nconst VIEW_DISPLAY_MODES: DisplayMode[] = [\"inline\", \"fullscreen\"];\n\nexport interface HostContext {\n theme?: \"light\" | \"dark\";\n displayMode?: DisplayMode;\n /** The modes the host will show this view in; absent, only the one it is in. */\n availableDisplayModes?: DisplayMode[];\n locale?: string;\n}\n\ninterface Pending {\n resolve: (result: unknown) => void;\n reject: (error: Error) => void;\n}\n\ntype JsonRpcId = string | number;\n\n/**\n * What the view needs of its channel: the call that opened it, the host's\n * context, and the tools. {@link McpAppBridge} is the MCP Apps host's; a\n * page that reaches the server another way (an artifact, through the\n * viewer's connector) brings its own.\n */\nexport interface ViewBridge {\n readonly hostContext: HostContext;\n watchHostContext(watcher: (context: HostContext) => void): () => void;\n ontoolinput: ((args: Record<string, unknown>) => void) | undefined;\n ontoolresult: ((result: ToolResult) => void) | undefined;\n connect(appInfo: { name: string; version: string }): Promise<void>;\n callTool(name: string, args: Record<string, unknown>): Promise<ToolResult>;\n updateModelContext(text: string): Promise<void>;\n requestDisplayMode(mode: DisplayMode): Promise<DisplayMode | undefined>;\n sizeChanged(height: number): void;\n}\n\n/** The host end of the channel: the parent window, in a host. */\nexport interface HostWindow {\n postMessage(message: unknown, targetOrigin: string): void;\n}\n\nexport class McpAppBridge implements ViewBridge {\n onhostcontext?: (context: HostContext) => void;\n\n /** Everything the host has said about its context so far, each update merged in. */\n hostContext: HostContext = {};\n private readonly contextWatchers = new Set<(context: HostContext) => void>();\n\n /** Called with the whole context now and on every change; returns the unsubscribe. */\n watchHostContext(watcher: (context: HostContext) => void): () => void {\n this.contextWatchers.add(watcher);\n watcher(this.hostContext);\n return () => {\n this.contextWatchers.delete(watcher);\n };\n }\n\n /**\n * The call that opened this view, and its answer. Kept, because the host\n * may send them before a handler is set — a React effect runs after the\n * first paint — and it sends each once.\n */\n toolInput?: Record<string, unknown>;\n toolResult?: ToolResult;\n private inputHandler?: (args: Record<string, unknown>) => void;\n private resultHandler?: (result: ToolResult) => void;\n\n set ontoolinput(handler: ((args: Record<string, unknown>) => void) | undefined) {\n this.inputHandler = handler;\n if (handler && this.toolInput) handler(this.toolInput);\n }\n\n set ontoolresult(handler: ((result: ToolResult) => void) | undefined) {\n this.resultHandler = handler;\n if (handler && this.toolResult) handler(this.toolResult);\n }\n\n private nextId = 1;\n private connected = false;\n private height?: number;\n private readonly pending = new Map<JsonRpcId, Pending>();\n private readonly host: HostWindow;\n\n /** `events` is where the host's messages arrive: this view's window. */\n constructor(host: HostWindow = window.parent, events: EventTarget = window) {\n this.host = host;\n events.addEventListener(\"message\", this.receive);\n }\n\n async connect(appInfo: { name: string; version: string }): Promise<void> {\n const result = await this.request(\"ui/initialize\", {\n appInfo,\n appCapabilities: { availableDisplayModes: VIEW_DISPLAY_MODES },\n protocolVersion: APPS_PROTOCOL_VERSION\n });\n if (isRecord(result) && isRecord(result.hostContext)) this.contextChanged(hostContextOf(result.hostContext));\n this.notify(\"ui/notifications/initialized\", {});\n this.connected = true;\n // A size measured before the handshake is held until now: nothing\n // but `ui/initialize` may reach the host before it.\n if (this.height !== undefined) this.notify(\"ui/notifications/size-changed\", { height: this.height });\n }\n\n /** A tool on this view's MCP server, called through the host. */\n async callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {\n const result = await this.request(\"tools/call\", { name, arguments: args });\n return isRecord(result) ? toolResultOf(result) : {};\n }\n\n /**\n * What the model should know about this view, sent with the person's next\n * message. Each call replaces the last.\n */\n async updateModelContext(text: string): Promise<void> {\n await this.request(\"ui/update-model-context\", { content: [{ type: \"text\", text }] });\n }\n\n /**\n * Ask the host to show this view in `mode`. The answer is the mode it is\n * in now, which may not be the one asked for.\n */\n async requestDisplayMode(mode: DisplayMode): Promise<DisplayMode | undefined> {\n const result = await this.request(\"ui/request-display-mode\", { mode });\n return isRecord(result) && isDisplayMode(result.mode) ? result.mode : undefined;\n }\n\n /** The document's height, for the host to size the iframe to. Sent when it changes. */\n sizeChanged(height: number): void {\n if (height === this.height) return;\n this.height = height;\n if (this.connected) this.notify(\"ui/notifications/size-changed\", { height });\n }\n\n private contextChanged(update: HostContext): void {\n this.hostContext = { ...this.hostContext, ...update };\n this.onhostcontext?.(update);\n for (const watcher of this.contextWatchers) watcher(this.hostContext);\n }\n\n private request(method: string, params: Record<string, unknown>): Promise<unknown> {\n const id = this.nextId++;\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n this.host.postMessage({ jsonrpc: \"2.0\", id, method, params }, \"*\");\n });\n }\n\n private notify(method: string, params: Record<string, unknown>): void {\n this.host.postMessage({ jsonrpc: \"2.0\", method, params }, \"*\");\n }\n\n private respond(id: JsonRpcId, result: Record<string, unknown>): void {\n this.host.postMessage({ jsonrpc: \"2.0\", id, result }, \"*\");\n }\n\n private readonly receive = (event: Event): void => {\n // Only the host speaks to this view. The sandbox gives the iframe an\n // opaque origin, so the window is the check, not the origin.\n if (!(event instanceof MessageEvent) || event.source !== this.host) return;\n const message: unknown = event.data;\n if (!isRecord(message) || message.jsonrpc !== \"2.0\") return;\n const id = typeof message.id === \"string\" || typeof message.id === \"number\" ? message.id : undefined;\n\n if (id !== undefined && (\"result\" in message || \"error\" in message)) {\n const pending = this.pending.get(id);\n if (!pending) return;\n this.pending.delete(id);\n if (isRecord(message.error)) pending.reject(new Error(String(message.error.message ?? \"The host refused the request.\")));\n else pending.resolve(message.result);\n return;\n }\n\n const params = isRecord(message.params) ? message.params : {};\n switch (message.method) {\n case \"ui/notifications/tool-input\":\n this.toolInput = isRecord(params.arguments) ? params.arguments : {};\n this.inputHandler?.(this.toolInput);\n return;\n case \"ui/notifications/tool-result\":\n this.toolResult = toolResultOf(params);\n this.resultHandler?.(this.toolResult);\n return;\n case \"ui/notifications/host-context-changed\":\n this.contextChanged(hostContextOf(params));\n return;\n // Requests the host may send. Nothing to clean up, nothing to report.\n case \"ui/resource-teardown\":\n case \"ping\":\n if (id !== undefined) this.respond(id, {});\n return;\n }\n };\n}\n\nfunction toolResultOf(value: Record<string, unknown>): ToolResult {\n return {\n content: Array.isArray(value.content)\n ? value.content.filter(isRecord).map(block => ({\n type: String(block.type),\n ...(typeof block.text === \"string\" && { text: block.text })\n }))\n : undefined,\n structuredContent: value.structuredContent,\n isError: value.isError === true\n };\n}\n\n/** The fields of the host's context this view reads. A partial update leaves the rest out. */\nfunction hostContextOf(value: Record<string, unknown>): HostContext {\n return {\n ...((value.theme === \"light\" || value.theme === \"dark\") && { theme: value.theme }),\n ...(isDisplayMode(value.displayMode) && { displayMode: value.displayMode }),\n ...(Array.isArray(value.availableDisplayModes) && {\n availableDisplayModes: value.availableDisplayModes.filter(isDisplayMode)\n }),\n ...(typeof value.locale === \"string\" && { locale: value.locale })\n };\n}\n\nfunction isDisplayMode(value: unknown): value is DisplayMode {\n return value === \"inline\" || value === \"fullscreen\" || value === \"pip\";\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,wBAAwB;;AAWrC,IAAM,qBAAoC,CAAC,UAAU,YAAY;AAwCjE,IAAa,eAAb,MAAgD;CAC5C;;CAGA,cAA2B,CAAC;CAC5B,kCAAmC,IAAI,IAAoC;;CAG3E,iBAAiB,SAAqD;EAClE,KAAK,gBAAgB,IAAI,OAAO;EAChC,QAAQ,KAAK,WAAW;EACxB,aAAa;GACT,KAAK,gBAAgB,OAAO,OAAO;EACvC;CACJ;;;;;;CAOA;CACA;CACA;CACA;CAEA,IAAI,YAAY,SAAgE;EAC5E,KAAK,eAAe;EACpB,IAAI,WAAW,KAAK,WAAW,QAAQ,KAAK,SAAS;CACzD;CAEA,IAAI,aAAa,SAAqD;EAClE,KAAK,gBAAgB;EACrB,IAAI,WAAW,KAAK,YAAY,QAAQ,KAAK,UAAU;CAC3D;CAEA,SAAiB;CACjB,YAAoB;C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