@rebasepro/plugin-data-enhancement 0.0.1-canary.f81da60 → 0.1.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/core/src/components/BootstrapAdminBanner.d.ts +4 -0
- package/dist/core/src/components/LoginView/LoginView.d.ts +22 -0
- package/dist/core/src/components/index.d.ts +1 -0
- package/dist/core/src/hooks/index.d.ts +1 -0
- package/dist/core/src/hooks/useCollapsedGroups.d.ts +16 -1
- package/dist/core/src/hooks/useResolvedComponent.d.ts +47 -0
- package/dist/index.es.js +8 -7
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +8 -7
- package/dist/index.umd.js.map +1 -1
- package/dist/types/src/controllers/auth.d.ts +8 -2
- package/dist/types/src/controllers/client.d.ts +13 -0
- package/dist/types/src/controllers/navigation.d.ts +18 -6
- package/dist/types/src/controllers/registry.d.ts +9 -1
- package/dist/types/src/controllers/side_entity_controller.d.ts +7 -0
- package/dist/types/src/rebase_context.d.ts +17 -0
- package/dist/types/src/types/collections.d.ts +20 -1
- package/dist/types/src/types/component_ref.d.ts +47 -0
- package/dist/types/src/types/entity_views.d.ts +2 -1
- package/dist/types/src/types/index.d.ts +1 -0
- package/dist/types/src/types/properties.d.ts +15 -3
- package/dist/types/src/types/translations.d.ts +2 -0
- package/dist/ui/src/components/SearchBar.d.ts +5 -1
- package/package.json +7 -7
- package/src/components/FormEnhanceAction.tsx +8 -7
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/utils/values.ts","../src/api.ts","../src/utils/suggestions.ts","../src/utils/properties.ts","../src/editor/useEditorAIController.tsx","../src/components/DataEnhancementControllerProvider.tsx","../src/components/FormEnhanceAction.tsx","../src/useDataEnhancementPlugin.tsx"],"sourcesContent":["export function flatMapEntityValues<M extends object>(values: M, path = \"\"): object {\n if (!values) return {};\n return Object.entries(values).flatMap(([key, value]) => {\n const currentPath = path ? `${path}.${key}` : key;\n if (typeof value === \"object\") {\n return flatMapEntityValues(value, currentPath);\n } else {\n return { [currentPath]: value };\n }\n }).reduce((acc, curr) => ({ ...acc,\n...curr }), {})\n}\n","import {\n DataEnhancementRequest,\n EnhancedDataResult,\n InputEntity,\n InputProperty,\n SamplePromptsResult\n} from \"./types/data_enhancement_controller\";\nimport { EntityValues } from \"@rebasepro/types\";\nimport { flatMapEntityValues } from \"./utils/values\";\n\n// const DEFAULT_SERVER = \"http://localhost:5001/rebase-dev-2da42/europe-west3/api\"; // Local\n\nconst DEFAULT_SERVER = \"https://api.rebase.pro\";\n\nexport async function enhanceDataAPIStream<M extends Record<string, unknown>>(props: {\n apiKey: string,\n entityId?: string | number,\n entityName: string,\n entityDescription?: string,\n propertyKey?: string,\n propertyInstructions?: string;\n values: EntityValues<M>,\n path: string,\n properties: Record<string, InputProperty>,\n\n instructions?: string,\n firebaseToken: string,\n onUpdate: (suggestions: Record<string, any>) => void;\n onUpdateDelta: (propertyKey: string, partialValue: any) => void;\n onError: (error: Error) => void;\n onEnd: (result: EnhancedDataResult) => void;\n host?: string;\n}) {\n\n const flatValues = flatMapEntityValues(props.values);\n\n const properties = props.properties;\n\n const inputEntity: InputEntity = {\n entityId: props.entityId,\n values: flatValues\n }\n\n const request: DataEnhancementRequest = {\n inputEntity,\n properties,\n entityName: props.entityName,\n entityDescription: props.entityDescription,\n propertyKey: props.propertyKey,\n propertyInstructions: props.propertyInstructions,\n instructions: props.instructions\n };\n\n console.debug(\"enhanceDataAPIStream\", request);\n\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/enhance_stream/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`,\n \"x-de-api-key\": `Basic ${props.apiKey}`\n // \"x-de-version\": version\n },\n body: JSON.stringify(request)\n })\n .then(async (res) => {\n if (!res.ok) {\n console.error(\"enhanceDataAPIStream error\", res)\n throw await res.json();\n }\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"No reader\");\n }\n\n for await (const chunk of readChunks(reader)) {\n const str = new TextDecoder().decode(chunk);\n try {\n str.split(\"&$# \").forEach((s) => {\n if (s && s.length > 0) {\n const data = JSON.parse(s.trim());\n if (data.type === \"suggestion_delta\")\n props.onUpdateDelta(data.data.propertyKey, data.data.partialValue);\n else if (data.type === \"suggestion\")\n props.onUpdate(data.data);\n else if (data.type === \"result\")\n props.onEnd(data.data);\n }\n });\n } catch (e: any) {\n console.error(\"str\", str);\n console.error(\"Error parsing stream\", e);\n props.onError(e);\n }\n }\n\n });\n\n}\n\nfunction readChunks(reader: ReadableStreamDefaultReader) {\n return {\n async *[Symbol.asyncIterator]() {\n let readResult = await reader.read();\n while (!readResult.done) {\n yield readResult.value;\n readResult = await reader.read();\n }\n }\n };\n}\n\nexport async function fetchEntityPromptSuggestion<M extends object>(props: {\n input?: string,\n entityName: string,\n firebaseToken: string,\n apiKey: string,\n host?: string\n}): Promise<SamplePromptsResult> {\n\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/prompt_autocomplete/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`,\n \"x-de-api-key\": `Basic ${props.apiKey}`\n },\n body: JSON.stringify({\n entityName: props.entityName,\n input: props.input ?? null\n })\n })\n .then(async (res) => {\n const data = await res.json();\n if (!res.ok) {\n console.error(\"fetchEntityPromptSuggestion\", data);\n throw Error(data.message);\n }\n return {\n prompts: data.data.prompts.map((e: string) => ({\n prompt: e,\n type: \"sample\"\n }))\n };\n });\n\n}\n\nexport async function autocompleteStream(props: {\n firebaseToken: string,\n textBefore?: string,\n textAfter: string,\n host?: string;\n onUpdate: (delta: string) => void;\n}) {\n\n let result = \"\";\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/autocomplete/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`\n // \"x-de-version\": version\n },\n body: JSON.stringify({\n textBefore: props.textBefore,\n textAfter: props.textAfter\n })\n })\n .then(async (res) => {\n if (!res.ok) {\n console.error(\"enhanceDataAPIStream error\", res)\n throw await res.json();\n }\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"No reader\");\n }\n\n for await (const chunk of readChunks(reader)) {\n const str = new TextDecoder().decode(chunk);\n result += str;\n console.debug(\"Autocomplete update:\", str);\n props.onUpdate(str);\n }\n\n }).then(() => {\n console.debug(\"Autocomplete result:\", result);\n return result;\n });\n\n}\n","export function getAppendableSuggestion(suggestion: string | number | undefined, value: any): string | undefined {\n const suggestionIncludesValue = typeof suggestion === \"string\" && typeof value === \"string\" && suggestion.toLowerCase().trim().startsWith(value.toLowerCase().trim());\n return (typeof value === \"string\" && suggestionIncludesValue)\n ? suggestion.substring(suggestion.toLowerCase().trim().indexOf(value.toLowerCase().trim()) + value.trim().length)\n : undefined;\n}\n","import { getFieldId } from \"@rebasepro/admin\";\nimport { EnumValues, Properties, Property } from \"@rebasepro/types\";\nimport { isPropertyBuilder } from \"@rebasepro/common\";\nimport { InputProperty } from \"../types/data_enhancement_controller\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nexport function getSimplifiedProperties<M extends Record<string, any>>(properties: Properties, values: M, path = \"\"): Record<string, InputProperty> {\n if (!properties) return {};\n return Object.entries(properties)\n .map(([key, property]) => {\n if (isPropertyBuilder(property)) return {};\n const fullKey = path ? `${path}.${key}` : key;\n const valueInPath = getValueInPath(values, fullKey);\n return getSimplifiedProperty(property, fullKey, valueInPath)\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n}\n\nfunction getSimpleProperty(property: Property): InputProperty {\n const fieldId = getFieldId(property);\n if (!fieldId) {\n console.error(\"No fieldId found for property\", property);\n throw new Error(\"Field id not found\");\n }\n return {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: fieldId,\n enum: \"enum\" in property && property.enum\n ? getSimpleEnumValues(property.enum)\n : undefined,\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)\n };\n}\n\nfunction getSimplifiedProperty(property: Property, path: string, value?: any): Record<string, InputProperty> {\n if (isPropertyBuilder(property)) return {};\n if (property.type === \"array\") {\n\n if (property.of && !Array.isArray(property.of) && !isPropertyBuilder(property.of)) {\n const arrayParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"repeat\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),\n of: getSimpleProperty(property.of as Property)\n };\n\n const result = { [path]: arrayParentProperty };\n // if (Array.isArray(value)) {\n // result = {\n // ...result,\n // ...value\n // .map((v, i) => getSimplifiedProperty(property.of, `${path}.${i}`, v))\n // .reduce((a, b) => ({ ...a, ...b }), {})\n // };\n // }\n //\n // const existingValuesCount = Array.isArray(value) ? value.length : 0;\n //\n // const newValuesCount = property.of && !isPropertyBuilder<any, any>(property.of) && (property.of as Property).type === \"map\" ? 1 : 3;\n // result = {\n // ...result,\n // // ...Array.from(Array(newValuesCount))\n // // .map((v, i) => getSimplifiedProperty(property.of, `${path}.${i + existingValuesCount}`, v))\n // // .reduce((a, b) => ({ ...a, ...b }), {})\n // }\n\n return result;\n } else if (property.oneOf) {\n\n const arrayParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"block\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),\n oneOf: {\n typeField: property.oneOf.typeField,\n valueField: property.oneOf.valueField,\n properties: Object.entries(property.oneOf.properties)\n .map(([key, prop]) => ({ [key]: getSimpleProperty(prop) }))\n .reduce((a, b) => ({ ...a,\n...b }), {})\n }\n };\n\n if (!Array.isArray(value)) {\n return { [path]: arrayParentProperty };\n }\n\n return value.map((v, i) => {\n if (v == null) return {};\n const typeKey = property.oneOf!.typeField ?? \"type\";\n const oneOfType = v[typeKey];\n const valueKey = property.oneOf!.valueField ?? \"value\";\n const oneOfValue = v[valueKey];\n const childProperty = property.oneOf!.properties[oneOfType];\n if (childProperty === undefined) {\n console.error(`No property found for type ${oneOfType}`, property.oneOf!.properties);\n return {};\n }\n const simplifiedProperty = getSimplifiedProperty(childProperty, `${path}.${i}.${valueKey}`, oneOfValue);\n return {\n [`${path}.${i}.${typeKey}`]: oneOfType,\n ...simplifiedProperty\n };\n }).reduce((a, b) => ({ ...a,\n...b }), { [path]: arrayParentProperty });\n }\n } else if (property.type === \"map\") {\n if (property.properties) {\n const mapProperties: Record<string, InputProperty> = Object.entries(property.properties)\n .map(([key, childProperty]) => {\n const childValue = value?.[key];\n return getSimplifiedProperty(childProperty, key, childValue);\n })\n .map(o => attachPathToKeys(o, path))\n .reduce((a, b) => ({ ...a,\n...b }), {});\n\n if (Object.keys(mapProperties).length === 0) return {};\n const mapParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"group\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)\n };\n return {\n [path]: mapParentProperty,\n ...mapProperties\n } as Record<string, InputProperty>;\n }\n } else {\n const fieldId = getFieldId(property);\n if (!fieldId) {\n console.warn(`No fieldId found for property ${path} with type ${property.type}`);\n return {};\n }\n return {\n [path]: getSimpleProperty(property)\n };\n }\n return {};\n}\n\n// attach a path to every key in an object\nfunction attachPathToKeys(obj: Record<string, any>, path = \"\"): Record<string, any> {\n return Object.entries(obj)\n .map(([key, value]) => {\n const fullKey = path ? `${path}.${key}` : key;\n return { [fullKey]: value };\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n}\n\nfunction getSimpleEnumValues(enumValues: EnumValues): string[] {\n if (Array.isArray(enumValues))\n return enumValues.map(v => String(v.id));\n if (typeof enumValues === \"object\")\n return Object.keys(enumValues);\n throw Error(\"getSimpleEnumValues: Invalid enumValues\");\n}\n","import { autocompleteStream } from \"../api\";\nimport { EditorAIController } from \"@rebasepro/admin\";\n\nexport function useEditorAIController({ getAuthToken }: { getAuthToken?: () => Promise<string> }): EditorAIController {\n const autocomplete = async (textBefore: string, textAfter: string, onUpdate: (delta: string) => void) => {\n if (!getAuthToken) {\n throw new Error(\"Firebase token is required\");\n }\n const firebaseToken = await getAuthToken();\n return autocompleteStream({\n firebaseToken,\n textBefore,\n textAfter,\n onUpdate\n });\n }\n\n return {\n autocomplete\n };\n}\n\n// async function * generateLoremIpsum(): AsyncGenerator<string> {\n// const loremIpsum = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\\n# Heading\\n\\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\";\n//\n// const words = loremIpsum.split(\" \");\n//\n// for (const word of words) {\n// yield word;\n// await new Promise(resolve => setTimeout(resolve, 100));\n// }\n// }\n//\n// const generator = generateLoremIpsum();\n// for await (const word of generator) {\n//\n// }\n","import React, { PropsWithChildren, useCallback, useContext, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport {\n DataEnhancementController,\n EnhancedDataResult,\n EnhanceParams,\n InputProperty\n} from \"../types/data_enhancement_controller\";\nimport {\n useAuthController,\n useCustomizationController,\n useSnackbarController\n} from \"@rebasepro/core\";\nimport { useUrlController } from \"@rebasepro/admin\";\nimport { DataDriver, Entity, EntityCollection, PluginFormActionProps } from \"@rebasepro/types\";\nimport { enhanceDataAPIStream, fetchEntityPromptSuggestion } from \"../api\";\nimport { getAppendableSuggestion } from \"../utils/suggestions\";\nimport { getSimplifiedProperties } from \"../utils/properties\";\nimport { useEditorAIController } from \"../editor/useEditorAIController\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nexport const DataEnhancementControllerContext = React.createContext<DataEnhancementController>(null! as DataEnhancementController);\n\nexport type DataEnhancementControllerProviderProps = {\n\n apiKey: string;\n\n getConfigForPath?: (props: {\n path: string,\n collection: EntityCollection\n }) => boolean;\n\n host?: string;\n}\n\nexport const useDataEnhancementController = (): DataEnhancementController => useContext(DataEnhancementControllerContext);\n\nfunction getPropertyFromKey(properties: Record<string, InputProperty>, propertyKey: string) {\n if (propertyKey in properties) {\n return properties[propertyKey];\n } else {\n //split the property key\n const split = propertyKey.split(\".\");\n if (split.length === 1) {\n return undefined;\n }\n const parentKey = split.slice(0, split.length - 1).join(\".\");\n return getPropertyFromKey(properties, parentKey);\n\n }\n}\n\nexport function DataEnhancementControllerProvider({\n apiKey,\n getConfigForPath,\n children,\n host,\n path,\n collection,\n formContext\n}: PropsWithChildren<DataEnhancementControllerProviderProps & PluginFormActionProps<any>>) {\n\n const [enabled, setEnabled] = useState(false);\n const [suggestions, setSuggestions] = useState<Record<string, string | number>>({});\n const [loadingSuggestions, setLoadingSuggestions] = useState<string[]>([]);\n\n const enhancingInProgress = useRef(false);\n\n const authController = useAuthController();\n const snackbarController = useSnackbarController();\n\n\n const properties = useMemo(() => getSimplifiedProperties(collection.properties, formContext?.values ?? {}), [formContext?.values]);\n // const preEnhanceValuesRef = React.useRef(formContext?.values ?? {});\n const valuesRef = React.useRef(formContext?.values ?? {});\n useEffect(() => {\n if (!enhancingInProgress.current)\n valuesRef.current = formContext?.values ?? {};\n }, [formContext?.values]);\n\n const allowReferenceDataSelection = false;\n\n const updateConfig = useCallback(async () => {\n if (!getConfigForPath) return;\n const config = getConfigForPath({\n path,\n collection\n });\n if (config) {\n setEnabled(true);\n }\n }, [collection, getConfigForPath, path]);\n\n useEffect(() => {\n if (!getConfigForPath) {\n setEnabled(true);\n } else {\n updateConfig();\n }\n\n }, [getConfigForPath, updateConfig]);\n\n\n const urlController = useUrlController();\n\n const clearSuggestion = useCallback((propertyKey: string) => {\n setSuggestions((prev) => {\n //remove propertyKey from prev\n const {\n [propertyKey]: _,\n ...rest\n } = prev;\n return rest;\n });\n }, []);\n\n const appendValueDelta = useCallback((propertyKey: string, delta: string) => {\n\n const property = getPropertyFromKey(properties, propertyKey);\n if (delta === null || property?.disabled) {\n return;\n }\n\n // clearSuggestion(propertyKey);\n const value = getValueInPath(valuesRef.current, propertyKey);\n\n const currentValue = value ? (value as string) + \"\" : \"\";\n const updatedValue = currentValue + delta;\n // if (currentValue.length === 0) updatedValue = updatedValue.trimStart();\n valuesRef.current = {\n ...valuesRef.current,\n [propertyKey]: updatedValue\n };\n formContext?.setFieldValue(propertyKey, updatedValue, false);\n setSuggestions(prev => ({\n ...prev,\n [propertyKey]: (prev[propertyKey] ?? \"\") + delta\n }));\n }, [properties, formContext]);\n\n const updateSuggestedValues = useCallback((currentValues: object, updatedValues: Record<string, string | number>, replaceValues: boolean) => {\n\n setLoadingSuggestions((prev) => {\n return prev.filter(p => !Object.keys(updatedValues).includes(p));\n });\n\n Object.entries(updatedValues).forEach(([propertyKey, suggestion]) => {\n\n const value = getValueInPath(currentValues, propertyKey);\n const property = getPropertyFromKey(properties, propertyKey);\n\n if (!property || suggestion === null || property?.disabled) {\n return;\n }\n\n if (typeof suggestion === \"number\") {\n formContext?.setFieldValue(propertyKey, suggestion);\n return;\n }\n\n if (replaceValues) {\n formContext?.setFieldValue(propertyKey, suggestion);\n return;\n }\n\n const appendableValue = getAppendableSuggestion(suggestion, value);\n\n const currentValue = value ? (value as string) + \"\" : \"\";\n if (appendableValue) {\n formContext?.setFieldValue(propertyKey, suggestion);\n } else {\n const multiline = property?.fieldConfigId === \"multiline\" || property?.fieldConfigId === \"markdown\";\n const trimmedValue = currentValue.trimEnd();\n if (multiline && (trimmedValue.endsWith(\".\") || trimmedValue.endsWith(\"?\") || trimmedValue.endsWith(\"!\") || trimmedValue.endsWith(\":\"))) {\n formContext?.setFieldValue(propertyKey, trimmedValue + \"\\n\\n\" + (suggestion as string).trimStart());\n } else {\n formContext?.setFieldValue(propertyKey, trimmedValue + (trimmedValue.length > 0 ? \" \" : \"\") + (suggestion as string));\n }\n }\n });\n\n setSuggestions(prev => ({\n ...prev,\n ...Object.keys(updatedValues)\n .reduce((acc, key) => {\n const value = getValueInPath(formContext?.values, key);\n const suggestion = updatedValues[key];\n return {\n ...acc,\n [key]: getAppendableSuggestion(suggestion, value) ?? suggestion\n };\n }, {})\n }));\n }, [properties, formContext]);\n\n const displayNeededSubscriptionSnackbar = useCallback((projectId: any) => {\n snackbarController.open({\n type: \"warning\",\n message: \"A valid subscription is needed in order to use this function.\",\n autoHideDuration: 4000\n });\n }, [snackbarController]);\n\n const editorAIController = useEditorAIController({ getAuthToken: authController.getAuthToken });\n\n const clearAllSuggestions = useCallback(() => {\n setSuggestions({});\n }, []);\n\n const enhance = useCallback(async (props: EnhanceParams<any>): Promise<EnhancedDataResult | null> => {\n\n if (!authController.user) {\n snackbarController.open({\n type: \"warning\",\n message: \"You need to be logged in to enhance data\"\n });\n return Promise.reject(new Error(\"Not logged in\"));\n }\n\n const resolvedPath = urlController.resolveDatabasePathsFrom(path);\n const firebaseToken = await authController.getAuthToken();\n\n if (props.propertyKey) {\n clearSuggestion(props.propertyKey)\n } else {\n clearAllSuggestions();\n }\n\n setLoadingSuggestions((prev) => [...prev, ...(props.propertyKey ? [props.propertyKey] : Object.keys(properties))]);\n enhancingInProgress.current = true;\n\n const currentValues = valuesRef.current ?? {};\n\n return new Promise((resolve, reject) => {\n function onError(e: any) {\n setLoadingSuggestions([]);\n if (e.code === \"payment-required\") {\n const projectId = e.data.projectId;\n displayNeededSubscriptionSnackbar(projectId);\n } else {\n console.error(\"Enhance error\", e);\n }\n reject(e);\n enhancingInProgress.current = false;\n }\n\n try {\n enhanceDataAPIStream({\n ...props,\n host,\n apiKey,\n properties,\n path: resolvedPath,\n entityName: collection.singularName ?? collection.name,\n entityDescription: collection.description,\n\n firebaseToken,\n onUpdate: (suggestions) => {\n console.debug(\"de onUpdate\", suggestions);\n updateSuggestedValues(currentValues, suggestions, props.replaceValues ?? false);\n },\n onUpdateDelta: (propertyKey: string, partialValue: string) => {\n // console.debug(\"de delta\", propertyKey, partialValue);\n appendValueDelta(propertyKey, partialValue);\n },\n onError,\n onEnd: (result) => {\n console.debug(\"de onEnd\", result);\n if (result.errors) {\n result.errors.forEach((error) => {\n snackbarController.open({\n type: \"warning\",\n message: error\n })\n });\n }\n if (Object.keys(result.suggestions).length === 0) {\n snackbarController.open({\n type: \"info\",\n autoHideDuration: 1800,\n message: \"No fields were updated\"\n })\n }\n setLoadingSuggestions([]);\n resolve(result);\n enhancingInProgress.current = false;\n }\n }).catch(onError);\n } catch (e: any) {\n onError(e);\n }\n });\n }, [\n authController, urlController, path, clearSuggestion, clearAllSuggestions,\n properties, host, apiKey, collection, updateSuggestedValues, appendValueDelta, displayNeededSubscriptionSnackbar, snackbarController\n ]);\n\n const getSamplePrompts = useCallback(async (entityName: string, input?: string) => {\n const firebaseToken = await authController.getAuthToken()\n return fetchEntityPromptSuggestion({\n host,\n entityName,\n firebaseToken,\n apiKey,\n input\n });\n }, [apiKey, authController.getAuthToken, host]);\n\n const dataEnhancementController: DataEnhancementController = useMemo(() => ({\n enabled,\n suggestions,\n clearSuggestion,\n enhance,\n allowReferenceDataSelection,\n clearAllSuggestions,\n getSamplePrompts,\n loadingSuggestions,\n editorAIController\n }), [\n enabled,\n suggestions,\n clearSuggestion,\n enhance,\n allowReferenceDataSelection,\n clearAllSuggestions,\n getSamplePrompts,\n loadingSuggestions,\n editorAIController\n ]);\n\n return (\n <DataEnhancementControllerContext.Provider\n value={dataEnhancementController}>\n {children}\n </DataEnhancementControllerContext.Provider>\n );\n}\n\n\n","\nimport React, { useCallback, useDeferredValue, useEffect, useRef } from \"react\";\n\nimport { Button, CircularProgress, cls, focusedDisabled, IconButton, Menu, MenuItem, Separator, TextareaAutosize , iconSize } from \"@rebasepro/ui\";\nimport { XIcon, SendIcon } from \"lucide-react\";\nimport {\n AIIcon,\n useLargeLayout\n} from \"@rebasepro/core\";\nimport { EntityStatus, PluginFormActionProps, Properties, Property } from \"@rebasepro/types\";\nimport { isPropertyBuilder, stripCollectionPath } from \"@rebasepro/common\";\nimport { useDataEnhancementController } from \"./DataEnhancementControllerProvider\";\nimport { SamplePrompt } from \"../types/data_enhancement_controller\";\n\nexport function FormEnhanceAction({\n entityId,\n path,\n status,\n collection,\n formContext,\n openEntityMode\n}: PluginFormActionProps) {\n\n const largeLayout = useLargeLayout();\n\n const storageKey = createLocalStorageKey(path, status);\n\n const [loading, setLoading] = React.useState(false);\n const dataEnhancementController = useDataEnhancementController();\n\n const [samplePrompts, setSamplePrompts] = React.useState<SamplePrompt[] | undefined>(undefined);\n const [instructions, setInstructions] = React.useState<string>(\"\");\n\n const {\n suggestions,\n getSamplePrompts\n } = dataEnhancementController;\n\n const loadingPrompts = useRef(false);\n const updateSuggestedPrompts = useCallback(async function updateSuggestedPrompts(instructions?: string) {\n if (loadingPrompts.current) return;\n loadingPrompts.current = true;\n const prompts = status === \"new\"\n ? (await getSamplePrompts(collection.singularName ?? collection.name, instructions)).prompts\n : getPromptsForExistingEntities(collection.properties);\n\n const recentPromptsFromStorage = getRecentPromptsFromStorage(storageKey);\n const recentPrompts = recentPromptsFromStorage.map(prompt => prompt.prompt);\n setSamplePrompts([...recentPromptsFromStorage, ...prompts.filter(p => !recentPrompts.includes(p.prompt))].slice(0, 5));\n loadingPrompts.current = false;\n },\n [collection.name, collection.singularName, getSamplePrompts, status]);\n\n const deferredValues = useDeferredValue(formContext?.values);\n // const enoughData = countStringCharacters(deferredValues, collection.properties) > 20;\n\n useEffect(() => {\n if (!samplePrompts) {\n setSamplePrompts(getRecentPromptsFromStorage(storageKey));\n updateSuggestedPrompts().then();\n }\n }, [samplePrompts, storageKey, updateSuggestedPrompts, instructions, status]);\n\n useEffect(() => {\n updateSuggestedPrompts().then();\n }, [status]);\n\n const enhance = (prompt?: string) => {\n if (!formContext?.values) return;\n setLoading(true);\n if (prompt) {\n addRecentPrompt(storageKey, prompt);\n setSamplePrompts([{\n prompt,\n type: \"recent\"\n }, ...(samplePrompts ?? []).slice(0, 5)]);\n }\n return dataEnhancementController.enhance({\n entityId,\n values: formContext!.values,\n instructions: prompt,\n replaceValues: true\n }).finally(() => {\n setLoading(false);\n });\n };\n\n if (!dataEnhancementController?.enabled)\n return null;\n\n const hasSuggestions = Object.values(suggestions).filter(Boolean).length > 0;\n\n const disabledSuggestionActions = !hasSuggestions;\n const promptSuggestionsEnabled = (samplePrompts ?? []).length > 0 && instructions.length === 0;\n\n // const noIdSet = !formContext?.entityId;\n\n function submit() {\n enhance(instructions);\n }\n\n return (\n <Menu\n align={\"end\"}\n sideOffset={8}\n className={\"max-w-[100vw]\"}\n trigger={<Button variant={\"filled\"}\n color={\"neutral\"}\n fullWidth={largeLayout && openEntityMode === \"full_screen\"}\n size={\"small\"}\n disabled={loading}>\n {!loading && <AIIcon size={\"small\"}/>}\n {loading && <CircularProgress size={\"small\"}/>}\n Autofill\n </Button>}>\n\n <MenuItem className={\"py-4\"}\n onClick={() => {\n enhance();\n }}>\n <AIIcon size={\"small\"}/>\n Autofill based on the current content\n </MenuItem>\n\n <Separator orientation={\"horizontal\"} className={\"mt-2\"}/>\n\n {samplePrompts?.map((samplePrompt, index) => {\n return <MenuItem\n key={index + \"_\" + samplePrompt.prompt}\n onClick={() => {\n setInstructions(samplePrompt.prompt);\n enhance(samplePrompt.prompt);\n }}\n >\n <div className={\"pl-9 grow text-text-secondary dark:text-text-secondary-dark\"}>\n {samplePrompt.prompt}\n </div>\n\n {samplePrompt.type === \"recent\" && <IconButton\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n removeRecentPrompt(storageKey, samplePrompt.prompt);\n setSamplePrompts((samplePrompts ?? []).filter(p => p.prompt !== samplePrompt.prompt));\n }}\n size={\"smallest\"}\n >\n <XIcon size={iconSize.smallest}/>\n </IconButton>\n }\n </MenuItem>;\n })}\n\n <Separator orientation={\"horizontal\"}/>\n\n <div\n className={cls(\n \"my-2 w-[500px] max-w-full flex items-start text-surface-700 dark:text-surface-200\"\n )}>\n\n <TextareaAutosize\n className={cls(\"p-4 rounded-lg resize-none bg-surface-100 dark:bg-surface-950 mx-2 w-full grow outline-hidden max-h-[300px] overflow-auto\", focusedDisabled)}\n value={instructions}\n autoFocus={status === \"new\"}\n disabled={loading}\n onFocus={(event) => {\n event.stopPropagation();\n }}\n placeholder={\"...or provide instructions\"}\n onKeyDown={(e) => {\n e.stopPropagation();\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault();\n submit();\n }\n\n }}\n onChange={(e) => {\n setInstructions(e.target.value);\n }}\n />\n\n <IconButton\n size={\"small\"}\n onClick={() => {\n setInstructions(\"\");\n }}\n color={!instructions ? \"primary\" : undefined}\n disabled={loading || !instructions}>\n <XIcon size={iconSize.small}/>\n </IconButton>\n\n <IconButton\n onClick={() => enhance(instructions)}\n size={\"small\"}\n color={!instructions ? \"primary\" : undefined}\n disabled={loading || !instructions}>\n {loading &&\n <CircularProgress size={\"smallest\"}/>}\n {!loading &&\n <SendIcon color={\"primary\"}/>}\n </IconButton>\n\n </div>\n\n </Menu>\n );\n}\n\nexport interface EnhanceDialogProps {\n open: boolean;\n onClose: () => void;\n selectReferences: () => void;\n loading: boolean;\n enhance: (instructions: string) => void;\n samplePrompts?: string[];\n}\n\nfunction getPromptsForExistingEntities(properties: Properties): SamplePrompt[] {\n\n const multilineProperties = Object.values(properties).filter((p: Property) => {\n if (isPropertyBuilder(p)) {\n return false;\n }\n return p.type === \"string\" && (p.ui?.markdown || p.ui?.multiline);\n });\n\n const multilinePrompt: Property | undefined = multilineProperties.length > 0\n ? multilineProperties[Math.floor(Math.random() * multilineProperties.length)] as Property\n : undefined;\n\n const prompts = [\n \"Fill the missing fields\",\n \"Translate the missing content\"\n ];\n if (multilinePrompt) {\n prompts.push(`Add 2 paragraphs to '${multilinePrompt.name}'`);\n }\n return prompts.map(p => ({\n prompt: p,\n type: \"sample\"\n }));\n}\n\nconst createLocalStorageKey = (path: string, status: EntityStatus) => {\n const statusString = status === \"new\" ? \"new\" : \"existing\";\n return `data_enhancement::${statusString}::${stripCollectionPath(path)}`;\n};\n\nconst getRecentPromptsFromStorage = (storageKey: string): SamplePrompt[] => {\n const item = localStorage.getItem(storageKey);\n return item ? JSON.parse(item).map((e: string) => ({\n prompt: e,\n type: \"recent\"\n })) : [];\n};\n\nconst addRecentPrompt = (storageKey: string, prompt: string) => {\n if (!prompt || prompt.trim().length === 0) {\n return;\n }\n const recentPrompts = getRecentPromptsFromStorage(storageKey);\n localStorage.setItem(storageKey, JSON.stringify([prompt, ...recentPrompts\n .map(e => e.prompt)\n .filter(e => e !== prompt)\n .slice(0, 5)]));\n};\n\nconst removeRecentPrompt = (storageKey: string, prompt: string) => {\n localStorage.setItem(storageKey, JSON.stringify(getRecentPromptsFromStorage(storageKey)\n .map(e => e.prompt)\n .filter(e => e !== prompt)));\n};\n","import React from \"react\";\n\nimport { EntityCollection, RebasePlugin, User } from \"@rebasepro/types\";\nimport { DataEnhancementControllerProvider } from \"./components/DataEnhancementControllerProvider\";\nimport { FormEnhanceAction } from \"./components/FormEnhanceAction\";\n\nconst DEFAULT_API_KEY = \"fcms-U9jdDii0xXWSDC34asfrf54lbkFJBfKfRWcEDEwdc4V5wDWEDF\";\n\nexport interface DataEnhancementPluginProps {\n\n apiKey?: string;\n\n /**\n * Use this function to determine if the data enhancement plugin should be enabled for a given path.\n * If this function is not provided, the plugin will be enabled for all paths.\n * If the function returns false, the plugin will be disabled for the given path.\n * You can also return a configuration object to override the default configuration.\n *\n * @param path\n * @param collection\n */\n getConfigForPath?: (props: {\n path: string,\n collection: EntityCollection,\n user: User | null\n }) => boolean;\n\n /**\n * Host to use for the data enhancement API.\n * This prop is only use in development mode.\n */\n host?: string;\n}\n\n/**\n * Use this hook to initialise the data enhancement plugin.\n * This is likely the only hook you will need to use.\n * @param props\n */\nexport function useDataEnhancementPlugin(props?: DataEnhancementPluginProps): RebasePlugin {\n\n const apiKey = props?.apiKey ?? DEFAULT_API_KEY;\n const getConfigForPath = props?.getConfigForPath;\n\n return React.useMemo(() => ({\n key: \"data_enhancement\",\n slots: [\n {\n slot: \"form.actions\",\n Component: FormEnhanceAction,\n order: 40\n }\n ],\n providers: [\n {\n scope: \"form\" as const,\n Component: DataEnhancementControllerProvider as React.ComponentType<any>,\n props: {\n apiKey,\n getConfigForPath,\n host: props?.host\n }\n }\n ]\n }), [apiKey, getConfigForPath, props?.host]);\n}\n"],"names":["flatMapEntityValues","values","path","Object","entries","flatMap","key","value","currentPath","reduce","acc","curr","DEFAULT_SERVER","enhanceDataAPIStream","props","flatValues","properties","inputEntity","entityId","request","entityName","entityDescription","propertyKey","propertyInstructions","instructions","console","debug","fetch","host","method","headers","Authorization","firebaseToken","apiKey","body","JSON","stringify","then","res","ok","error","json","reader","getReader","Error","chunk","readChunks","str","TextDecoder","decode","split","forEach","s","length","data","parse","trim","type","onUpdateDelta","partialValue","onUpdate","onEnd","e","onError","Symbol","asyncIterator","readResult","read","done","fetchEntityPromptSuggestion","input","message","prompts","map","prompt","autocompleteStream","result","textBefore","textAfter","getAppendableSuggestion","suggestion","suggestionIncludesValue","toLowerCase","startsWith","substring","indexOf","undefined","getSimplifiedProperties","property","isPropertyBuilder","fullKey","valueInPath","getValueInPath","getSimplifiedProperty","a","b","getSimpleProperty","fieldId","getFieldId","name","description","fieldConfigId","enum","getSimpleEnumValues","disabled","Boolean","ui","readOnly","of","Array","isArray","arrayParentProperty","oneOf","typeField","valueField","prop","v","i","typeKey","oneOfType","valueKey","oneOfValue","childProperty","simplifiedProperty","mapProperties","childValue","o","attachPathToKeys","keys","mapParentProperty","warn","obj","enumValues","String","id","useEditorAIController","getAuthToken","autocomplete","DataEnhancementControllerContext","React","createContext","useDataEnhancementController","useContext","getPropertyFromKey","parentKey","slice","join","DataEnhancementControllerProvider","getConfigForPath","children","collection","formContext","enabled","setEnabled","useState","suggestions","setSuggestions","loadingSuggestions","setLoadingSuggestions","enhancingInProgress","useRef","authController","useAuthController","snackbarController","useSnackbarController","useMemo","valuesRef","useEffect","current","allowReferenceDataSelection","updateConfig","useCallback","config","urlController","useUrlController","clearSuggestion","prev","_","rest","appendValueDelta","delta","currentValue","updatedValue","setFieldValue","updateSuggestedValues","currentValues","updatedValues","replaceValues","filter","p","includes","appendableValue","multiline","trimmedValue","trimEnd","endsWith","trimStart","displayNeededSubscriptionSnackbar","projectId","open","autoHideDuration","editorAIController","clearAllSuggestions","enhance","user","Promise","reject","resolvedPath","resolveDatabasePathsFrom","resolve","code","singularName","errors","catch","getSamplePrompts","dataEnhancementController","FormEnhanceAction","status","openEntityMode","largeLayout","useLargeLayout","storageKey","createLocalStorageKey","loading","setLoading","samplePrompts","setSamplePrompts","setInstructions","loadingPrompts","updateSuggestedPrompts","getPromptsForExistingEntities","recentPromptsFromStorage","getRecentPromptsFromStorage","recentPrompts","useDeferredValue","addRecentPrompt","finally","submit","jsxs","Menu","Button","jsx","AIIcon","CircularProgress","MenuItem","Separator","samplePrompt","index","IconButton","preventDefault","stopPropagation","removeRecentPrompt","XIcon","iconSize","smallest","cls","TextareaAutosize","focusedDisabled","event","shiftKey","target","small","SendIcon","multilineProperties","markdown","multilinePrompt","Math","floor","random","push","statusString","stripCollectionPath","item","localStorage","getItem","setItem","DEFAULT_API_KEY","useDataEnhancementPlugin","$","_c","t0","t1","for","slot","Component","order","t2","t3","slots","providers","scope"],"mappings":";;;;AAAO,WAASA,oBAAsCC,QAAWC,OAAO,IAAY;AAChF,QAAI,CAACD,OAAQ,QAAO,CAAA;AACpB,WAAOE,OAAOC,QAAQH,MAAM,EAAEI,QAAQ,CAAC,CAACC,KAAKC,KAAK,MAAM;AACpD,YAAMC,cAAcN,OAAO,GAAGA,IAAI,IAAII,GAAG,KAAKA;AAC9C,UAAI,OAAOC,UAAU,UAAU;AAC3B,eAAOP,oBAAoBO,OAAOC,WAAW;AAAA,MACjD,OAAO;AACH,eAAO;AAAA,UAAE,CAACA,WAAW,GAAGD;AAAAA,QAAAA;AAAAA,MAC5B;AAAA,IACJ,CAAC,EAAEE,OAAO,CAACC,KAAKC,UAAU;AAAA,MAAE,GAAGD;AAAAA,MACnC,GAAGC;AAAAA,IAAAA,IAAS,CAAA,CAAE;AAAA,EACd;ACCA,QAAMC,iBAAiB;AAEv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;AAAA,EACnC;AC1QA,QAAM0M,kBAAkB;AAiCjB,WAAAC,yBAAAvQ,OAAA;AAAA,UAAAwQ,IAAAC,qBAAAA,EAAA,CAAA;AAEH,UAAAtP,SAAenB,OAAKmB,UAAAmP;AACpB,UAAAhI,mBAAyBtI,OAAKsI;AAsBCtI,WAAKc;AAAA,QAAA4P;AAAA,QAAAC;AAAA,QAAAH,EAAA,CAAA,MAAAtN,uBAAA0N,IAAA,2BAAA,GAAA;AAlBzBD,WAAA,CAAA;AAAA,QAAAE,MAEO;AAAA,QAAcC,WAAApE;AAAAA,QAAAqE,OAAA;AAAA,MAAA,CAAA;AAI3BP,aAAAG;AAAAA,IAAA,OAAA;AAAAA,WAAAH,EAAA,CAAA;AAAA,IAAA;AAQiB,UAAAQ,KAAAhR,OAAKc;AAAM,QAAAmQ;AAAA,QAAAT,EAAA,CAAA,MAAArP,UAAAqP,SAAAlI,oBAAAkI,EAAA,CAAA,MAAAQ,IAAA;AAhBLC,WAAA;AAAA,QAAAzR,KACnB;AAAA,QAAkB0R,OAChBP;AAAAA,QAMNQ,WAAA,CAAA;AAAA,UAAAC,OAGc;AAAA,UAAeN,WAAAzI;AAAAA,UACkDrI,OAAA;AAAA,YAAAmB;AAAAA,YAAAmH;AAAAA,YAAAxH,MAI9DkQ;AAAAA,UAAAA;AAAAA,QAAW,CAAA;AAAA,MAAA;AAIhCR,aAAArP;AAAAqP,aAAAlI;AAAAkI,aAAAQ;AAAAR,aAAAS;AAAAA,IAAA,OAAA;AAAAA,WAAAT,EAAA,CAAA;AAAA,IAAA;AAAAE,SApB2BO;AAoB3B,WApBMP;AAAAA,EAoBqC;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/utils/values.ts","../src/api.ts","../src/utils/suggestions.ts","../src/utils/properties.ts","../src/editor/useEditorAIController.tsx","../src/components/DataEnhancementControllerProvider.tsx","../src/components/FormEnhanceAction.tsx","../src/useDataEnhancementPlugin.tsx"],"sourcesContent":["export function flatMapEntityValues<M extends object>(values: M, path = \"\"): object {\n if (!values) return {};\n return Object.entries(values).flatMap(([key, value]) => {\n const currentPath = path ? `${path}.${key}` : key;\n if (typeof value === \"object\") {\n return flatMapEntityValues(value, currentPath);\n } else {\n return { [currentPath]: value };\n }\n }).reduce((acc, curr) => ({ ...acc,\n...curr }), {})\n}\n","import {\n DataEnhancementRequest,\n EnhancedDataResult,\n InputEntity,\n InputProperty,\n SamplePromptsResult\n} from \"./types/data_enhancement_controller\";\nimport { EntityValues } from \"@rebasepro/types\";\nimport { flatMapEntityValues } from \"./utils/values\";\n\n// const DEFAULT_SERVER = \"http://localhost:5001/rebase-dev-2da42/europe-west3/api\"; // Local\n\nconst DEFAULT_SERVER = \"https://api.rebase.pro\";\n\nexport async function enhanceDataAPIStream<M extends Record<string, unknown>>(props: {\n apiKey: string,\n entityId?: string | number,\n entityName: string,\n entityDescription?: string,\n propertyKey?: string,\n propertyInstructions?: string;\n values: EntityValues<M>,\n path: string,\n properties: Record<string, InputProperty>,\n\n instructions?: string,\n firebaseToken: string,\n onUpdate: (suggestions: Record<string, any>) => void;\n onUpdateDelta: (propertyKey: string, partialValue: any) => void;\n onError: (error: Error) => void;\n onEnd: (result: EnhancedDataResult) => void;\n host?: string;\n}) {\n\n const flatValues = flatMapEntityValues(props.values);\n\n const properties = props.properties;\n\n const inputEntity: InputEntity = {\n entityId: props.entityId,\n values: flatValues\n }\n\n const request: DataEnhancementRequest = {\n inputEntity,\n properties,\n entityName: props.entityName,\n entityDescription: props.entityDescription,\n propertyKey: props.propertyKey,\n propertyInstructions: props.propertyInstructions,\n instructions: props.instructions\n };\n\n console.debug(\"enhanceDataAPIStream\", request);\n\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/enhance_stream/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`,\n \"x-de-api-key\": `Basic ${props.apiKey}`\n // \"x-de-version\": version\n },\n body: JSON.stringify(request)\n })\n .then(async (res) => {\n if (!res.ok) {\n console.error(\"enhanceDataAPIStream error\", res)\n throw await res.json();\n }\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"No reader\");\n }\n\n for await (const chunk of readChunks(reader)) {\n const str = new TextDecoder().decode(chunk);\n try {\n str.split(\"&$# \").forEach((s) => {\n if (s && s.length > 0) {\n const data = JSON.parse(s.trim());\n if (data.type === \"suggestion_delta\")\n props.onUpdateDelta(data.data.propertyKey, data.data.partialValue);\n else if (data.type === \"suggestion\")\n props.onUpdate(data.data);\n else if (data.type === \"result\")\n props.onEnd(data.data);\n }\n });\n } catch (e: any) {\n console.error(\"str\", str);\n console.error(\"Error parsing stream\", e);\n props.onError(e);\n }\n }\n\n });\n\n}\n\nfunction readChunks(reader: ReadableStreamDefaultReader) {\n return {\n async *[Symbol.asyncIterator]() {\n let readResult = await reader.read();\n while (!readResult.done) {\n yield readResult.value;\n readResult = await reader.read();\n }\n }\n };\n}\n\nexport async function fetchEntityPromptSuggestion<M extends object>(props: {\n input?: string,\n entityName: string,\n firebaseToken: string,\n apiKey: string,\n host?: string\n}): Promise<SamplePromptsResult> {\n\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/prompt_autocomplete/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`,\n \"x-de-api-key\": `Basic ${props.apiKey}`\n },\n body: JSON.stringify({\n entityName: props.entityName,\n input: props.input ?? null\n })\n })\n .then(async (res) => {\n const data = await res.json();\n if (!res.ok) {\n console.error(\"fetchEntityPromptSuggestion\", data);\n throw Error(data.message);\n }\n return {\n prompts: data.data.prompts.map((e: string) => ({\n prompt: e,\n type: \"sample\"\n }))\n };\n });\n\n}\n\nexport async function autocompleteStream(props: {\n firebaseToken: string,\n textBefore?: string,\n textAfter: string,\n host?: string;\n onUpdate: (delta: string) => void;\n}) {\n\n let result = \"\";\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/autocomplete/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`\n // \"x-de-version\": version\n },\n body: JSON.stringify({\n textBefore: props.textBefore,\n textAfter: props.textAfter\n })\n })\n .then(async (res) => {\n if (!res.ok) {\n console.error(\"enhanceDataAPIStream error\", res)\n throw await res.json();\n }\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"No reader\");\n }\n\n for await (const chunk of readChunks(reader)) {\n const str = new TextDecoder().decode(chunk);\n result += str;\n console.debug(\"Autocomplete update:\", str);\n props.onUpdate(str);\n }\n\n }).then(() => {\n console.debug(\"Autocomplete result:\", result);\n return result;\n });\n\n}\n","export function getAppendableSuggestion(suggestion: string | number | undefined, value: any): string | undefined {\n const suggestionIncludesValue = typeof suggestion === \"string\" && typeof value === \"string\" && suggestion.toLowerCase().trim().startsWith(value.toLowerCase().trim());\n return (typeof value === \"string\" && suggestionIncludesValue)\n ? suggestion.substring(suggestion.toLowerCase().trim().indexOf(value.toLowerCase().trim()) + value.trim().length)\n : undefined;\n}\n","import { getFieldId } from \"@rebasepro/admin\";\nimport { EnumValues, Properties, Property } from \"@rebasepro/types\";\nimport { isPropertyBuilder } from \"@rebasepro/common\";\nimport { InputProperty } from \"../types/data_enhancement_controller\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nexport function getSimplifiedProperties<M extends Record<string, any>>(properties: Properties, values: M, path = \"\"): Record<string, InputProperty> {\n if (!properties) return {};\n return Object.entries(properties)\n .map(([key, property]) => {\n if (isPropertyBuilder(property)) return {};\n const fullKey = path ? `${path}.${key}` : key;\n const valueInPath = getValueInPath(values, fullKey);\n return getSimplifiedProperty(property, fullKey, valueInPath)\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n}\n\nfunction getSimpleProperty(property: Property): InputProperty {\n const fieldId = getFieldId(property);\n if (!fieldId) {\n console.error(\"No fieldId found for property\", property);\n throw new Error(\"Field id not found\");\n }\n return {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: fieldId,\n enum: \"enum\" in property && property.enum\n ? getSimpleEnumValues(property.enum)\n : undefined,\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)\n };\n}\n\nfunction getSimplifiedProperty(property: Property, path: string, value?: any): Record<string, InputProperty> {\n if (isPropertyBuilder(property)) return {};\n if (property.type === \"array\") {\n\n if (property.of && !Array.isArray(property.of) && !isPropertyBuilder(property.of)) {\n const arrayParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"repeat\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),\n of: getSimpleProperty(property.of as Property)\n };\n\n const result = { [path]: arrayParentProperty };\n // if (Array.isArray(value)) {\n // result = {\n // ...result,\n // ...value\n // .map((v, i) => getSimplifiedProperty(property.of, `${path}.${i}`, v))\n // .reduce((a, b) => ({ ...a, ...b }), {})\n // };\n // }\n //\n // const existingValuesCount = Array.isArray(value) ? value.length : 0;\n //\n // const newValuesCount = property.of && !isPropertyBuilder<any, any>(property.of) && (property.of as Property).type === \"map\" ? 1 : 3;\n // result = {\n // ...result,\n // // ...Array.from(Array(newValuesCount))\n // // .map((v, i) => getSimplifiedProperty(property.of, `${path}.${i + existingValuesCount}`, v))\n // // .reduce((a, b) => ({ ...a, ...b }), {})\n // }\n\n return result;\n } else if (property.oneOf) {\n\n const arrayParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"block\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),\n oneOf: {\n typeField: property.oneOf.typeField,\n valueField: property.oneOf.valueField,\n properties: Object.entries(property.oneOf.properties)\n .map(([key, prop]) => ({ [key]: getSimpleProperty(prop) }))\n .reduce((a, b) => ({ ...a,\n...b }), {})\n }\n };\n\n if (!Array.isArray(value)) {\n return { [path]: arrayParentProperty };\n }\n\n return value.map((v, i) => {\n if (v == null) return {};\n const typeKey = property.oneOf!.typeField ?? \"type\";\n const oneOfType = v[typeKey];\n const valueKey = property.oneOf!.valueField ?? \"value\";\n const oneOfValue = v[valueKey];\n const childProperty = property.oneOf!.properties[oneOfType];\n if (childProperty === undefined) {\n console.error(`No property found for type ${oneOfType}`, property.oneOf!.properties);\n return {};\n }\n const simplifiedProperty = getSimplifiedProperty(childProperty, `${path}.${i}.${valueKey}`, oneOfValue);\n return {\n [`${path}.${i}.${typeKey}`]: oneOfType,\n ...simplifiedProperty\n };\n }).reduce((a, b) => ({ ...a,\n...b }), { [path]: arrayParentProperty });\n }\n } else if (property.type === \"map\") {\n if (property.properties) {\n const mapProperties: Record<string, InputProperty> = Object.entries(property.properties)\n .map(([key, childProperty]) => {\n const childValue = value?.[key];\n return getSimplifiedProperty(childProperty, key, childValue);\n })\n .map(o => attachPathToKeys(o, path))\n .reduce((a, b) => ({ ...a,\n...b }), {});\n\n if (Object.keys(mapProperties).length === 0) return {};\n const mapParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"group\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)\n };\n return {\n [path]: mapParentProperty,\n ...mapProperties\n } as Record<string, InputProperty>;\n }\n } else {\n const fieldId = getFieldId(property);\n if (!fieldId) {\n console.warn(`No fieldId found for property ${path} with type ${property.type}`);\n return {};\n }\n return {\n [path]: getSimpleProperty(property)\n };\n }\n return {};\n}\n\n// attach a path to every key in an object\nfunction attachPathToKeys(obj: Record<string, any>, path = \"\"): Record<string, any> {\n return Object.entries(obj)\n .map(([key, value]) => {\n const fullKey = path ? `${path}.${key}` : key;\n return { [fullKey]: value };\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n}\n\nfunction getSimpleEnumValues(enumValues: EnumValues): string[] {\n if (Array.isArray(enumValues))\n return enumValues.map(v => String(v.id));\n if (typeof enumValues === \"object\")\n return Object.keys(enumValues);\n throw Error(\"getSimpleEnumValues: Invalid enumValues\");\n}\n","import { autocompleteStream } from \"../api\";\nimport { EditorAIController } from \"@rebasepro/admin\";\n\nexport function useEditorAIController({ getAuthToken }: { getAuthToken?: () => Promise<string> }): EditorAIController {\n const autocomplete = async (textBefore: string, textAfter: string, onUpdate: (delta: string) => void) => {\n if (!getAuthToken) {\n throw new Error(\"Firebase token is required\");\n }\n const firebaseToken = await getAuthToken();\n return autocompleteStream({\n firebaseToken,\n textBefore,\n textAfter,\n onUpdate\n });\n }\n\n return {\n autocomplete\n };\n}\n\n// async function * generateLoremIpsum(): AsyncGenerator<string> {\n// const loremIpsum = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\\n# Heading\\n\\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\";\n//\n// const words = loremIpsum.split(\" \");\n//\n// for (const word of words) {\n// yield word;\n// await new Promise(resolve => setTimeout(resolve, 100));\n// }\n// }\n//\n// const generator = generateLoremIpsum();\n// for await (const word of generator) {\n//\n// }\n","import React, { PropsWithChildren, useCallback, useContext, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport {\n DataEnhancementController,\n EnhancedDataResult,\n EnhanceParams,\n InputProperty\n} from \"../types/data_enhancement_controller\";\nimport {\n useAuthController,\n useCustomizationController,\n useSnackbarController\n} from \"@rebasepro/core\";\nimport { useUrlController } from \"@rebasepro/admin\";\nimport { DataDriver, Entity, EntityCollection, PluginFormActionProps } from \"@rebasepro/types\";\nimport { enhanceDataAPIStream, fetchEntityPromptSuggestion } from \"../api\";\nimport { getAppendableSuggestion } from \"../utils/suggestions\";\nimport { getSimplifiedProperties } from \"../utils/properties\";\nimport { useEditorAIController } from \"../editor/useEditorAIController\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nexport const DataEnhancementControllerContext = React.createContext<DataEnhancementController>(null! as DataEnhancementController);\n\nexport type DataEnhancementControllerProviderProps = {\n\n apiKey: string;\n\n getConfigForPath?: (props: {\n path: string,\n collection: EntityCollection\n }) => boolean;\n\n host?: string;\n}\n\nexport const useDataEnhancementController = (): DataEnhancementController => useContext(DataEnhancementControllerContext);\n\nfunction getPropertyFromKey(properties: Record<string, InputProperty>, propertyKey: string) {\n if (propertyKey in properties) {\n return properties[propertyKey];\n } else {\n //split the property key\n const split = propertyKey.split(\".\");\n if (split.length === 1) {\n return undefined;\n }\n const parentKey = split.slice(0, split.length - 1).join(\".\");\n return getPropertyFromKey(properties, parentKey);\n\n }\n}\n\nexport function DataEnhancementControllerProvider({\n apiKey,\n getConfigForPath,\n children,\n host,\n path,\n collection,\n formContext\n}: PropsWithChildren<DataEnhancementControllerProviderProps & PluginFormActionProps<any>>) {\n\n const [enabled, setEnabled] = useState(false);\n const [suggestions, setSuggestions] = useState<Record<string, string | number>>({});\n const [loadingSuggestions, setLoadingSuggestions] = useState<string[]>([]);\n\n const enhancingInProgress = useRef(false);\n\n const authController = useAuthController();\n const snackbarController = useSnackbarController();\n\n\n const properties = useMemo(() => getSimplifiedProperties(collection.properties, formContext?.values ?? {}), [formContext?.values]);\n // const preEnhanceValuesRef = React.useRef(formContext?.values ?? {});\n const valuesRef = React.useRef(formContext?.values ?? {});\n useEffect(() => {\n if (!enhancingInProgress.current)\n valuesRef.current = formContext?.values ?? {};\n }, [formContext?.values]);\n\n const allowReferenceDataSelection = false;\n\n const updateConfig = useCallback(async () => {\n if (!getConfigForPath) return;\n const config = getConfigForPath({\n path,\n collection\n });\n if (config) {\n setEnabled(true);\n }\n }, [collection, getConfigForPath, path]);\n\n useEffect(() => {\n if (!getConfigForPath) {\n setEnabled(true);\n } else {\n updateConfig();\n }\n\n }, [getConfigForPath, updateConfig]);\n\n\n const urlController = useUrlController();\n\n const clearSuggestion = useCallback((propertyKey: string) => {\n setSuggestions((prev) => {\n //remove propertyKey from prev\n const {\n [propertyKey]: _,\n ...rest\n } = prev;\n return rest;\n });\n }, []);\n\n const appendValueDelta = useCallback((propertyKey: string, delta: string) => {\n\n const property = getPropertyFromKey(properties, propertyKey);\n if (delta === null || property?.disabled) {\n return;\n }\n\n // clearSuggestion(propertyKey);\n const value = getValueInPath(valuesRef.current, propertyKey);\n\n const currentValue = value ? (value as string) + \"\" : \"\";\n const updatedValue = currentValue + delta;\n // if (currentValue.length === 0) updatedValue = updatedValue.trimStart();\n valuesRef.current = {\n ...valuesRef.current,\n [propertyKey]: updatedValue\n };\n formContext?.setFieldValue(propertyKey, updatedValue, false);\n setSuggestions(prev => ({\n ...prev,\n [propertyKey]: (prev[propertyKey] ?? \"\") + delta\n }));\n }, [properties, formContext]);\n\n const updateSuggestedValues = useCallback((currentValues: object, updatedValues: Record<string, string | number>, replaceValues: boolean) => {\n\n setLoadingSuggestions((prev) => {\n return prev.filter(p => !Object.keys(updatedValues).includes(p));\n });\n\n Object.entries(updatedValues).forEach(([propertyKey, suggestion]) => {\n\n const value = getValueInPath(currentValues, propertyKey);\n const property = getPropertyFromKey(properties, propertyKey);\n\n if (!property || suggestion === null || property?.disabled) {\n return;\n }\n\n if (typeof suggestion === \"number\") {\n formContext?.setFieldValue(propertyKey, suggestion);\n return;\n }\n\n if (replaceValues) {\n formContext?.setFieldValue(propertyKey, suggestion);\n return;\n }\n\n const appendableValue = getAppendableSuggestion(suggestion, value);\n\n const currentValue = value ? (value as string) + \"\" : \"\";\n if (appendableValue) {\n formContext?.setFieldValue(propertyKey, suggestion);\n } else {\n const multiline = property?.fieldConfigId === \"multiline\" || property?.fieldConfigId === \"markdown\";\n const trimmedValue = currentValue.trimEnd();\n if (multiline && (trimmedValue.endsWith(\".\") || trimmedValue.endsWith(\"?\") || trimmedValue.endsWith(\"!\") || trimmedValue.endsWith(\":\"))) {\n formContext?.setFieldValue(propertyKey, trimmedValue + \"\\n\\n\" + (suggestion as string).trimStart());\n } else {\n formContext?.setFieldValue(propertyKey, trimmedValue + (trimmedValue.length > 0 ? \" \" : \"\") + (suggestion as string));\n }\n }\n });\n\n setSuggestions(prev => ({\n ...prev,\n ...Object.keys(updatedValues)\n .reduce((acc, key) => {\n const value = getValueInPath(formContext?.values, key);\n const suggestion = updatedValues[key];\n return {\n ...acc,\n [key]: getAppendableSuggestion(suggestion, value) ?? suggestion\n };\n }, {})\n }));\n }, [properties, formContext]);\n\n const displayNeededSubscriptionSnackbar = useCallback((projectId: any) => {\n snackbarController.open({\n type: \"warning\",\n message: \"A valid subscription is needed in order to use this function.\",\n autoHideDuration: 4000\n });\n }, [snackbarController]);\n\n const editorAIController = useEditorAIController({ getAuthToken: authController.getAuthToken });\n\n const clearAllSuggestions = useCallback(() => {\n setSuggestions({});\n }, []);\n\n const enhance = useCallback(async (props: EnhanceParams<any>): Promise<EnhancedDataResult | null> => {\n\n if (!authController.user) {\n snackbarController.open({\n type: \"warning\",\n message: \"You need to be logged in to enhance data\"\n });\n return Promise.reject(new Error(\"Not logged in\"));\n }\n\n const resolvedPath = urlController.resolveDatabasePathsFrom(path);\n const firebaseToken = await authController.getAuthToken();\n\n if (props.propertyKey) {\n clearSuggestion(props.propertyKey)\n } else {\n clearAllSuggestions();\n }\n\n setLoadingSuggestions((prev) => [...prev, ...(props.propertyKey ? [props.propertyKey] : Object.keys(properties))]);\n enhancingInProgress.current = true;\n\n const currentValues = valuesRef.current ?? {};\n\n return new Promise((resolve, reject) => {\n function onError(e: any) {\n setLoadingSuggestions([]);\n if (e.code === \"payment-required\") {\n const projectId = e.data.projectId;\n displayNeededSubscriptionSnackbar(projectId);\n } else {\n console.error(\"Enhance error\", e);\n }\n reject(e);\n enhancingInProgress.current = false;\n }\n\n try {\n enhanceDataAPIStream({\n ...props,\n host,\n apiKey,\n properties,\n path: resolvedPath,\n entityName: collection.singularName ?? collection.name,\n entityDescription: collection.description,\n\n firebaseToken,\n onUpdate: (suggestions) => {\n console.debug(\"de onUpdate\", suggestions);\n updateSuggestedValues(currentValues, suggestions, props.replaceValues ?? false);\n },\n onUpdateDelta: (propertyKey: string, partialValue: string) => {\n // console.debug(\"de delta\", propertyKey, partialValue);\n appendValueDelta(propertyKey, partialValue);\n },\n onError,\n onEnd: (result) => {\n console.debug(\"de onEnd\", result);\n if (result.errors) {\n result.errors.forEach((error) => {\n snackbarController.open({\n type: \"warning\",\n message: error\n })\n });\n }\n if (Object.keys(result.suggestions).length === 0) {\n snackbarController.open({\n type: \"info\",\n autoHideDuration: 1800,\n message: \"No fields were updated\"\n })\n }\n setLoadingSuggestions([]);\n resolve(result);\n enhancingInProgress.current = false;\n }\n }).catch(onError);\n } catch (e: any) {\n onError(e);\n }\n });\n }, [\n authController, urlController, path, clearSuggestion, clearAllSuggestions,\n properties, host, apiKey, collection, updateSuggestedValues, appendValueDelta, displayNeededSubscriptionSnackbar, snackbarController\n ]);\n\n const getSamplePrompts = useCallback(async (entityName: string, input?: string) => {\n const firebaseToken = await authController.getAuthToken()\n return fetchEntityPromptSuggestion({\n host,\n entityName,\n firebaseToken,\n apiKey,\n input\n });\n }, [apiKey, authController.getAuthToken, host]);\n\n const dataEnhancementController: DataEnhancementController = useMemo(() => ({\n enabled,\n suggestions,\n clearSuggestion,\n enhance,\n allowReferenceDataSelection,\n clearAllSuggestions,\n getSamplePrompts,\n loadingSuggestions,\n editorAIController\n }), [\n enabled,\n suggestions,\n clearSuggestion,\n enhance,\n allowReferenceDataSelection,\n clearAllSuggestions,\n getSamplePrompts,\n loadingSuggestions,\n editorAIController\n ]);\n\n return (\n <DataEnhancementControllerContext.Provider\n value={dataEnhancementController}>\n {children}\n </DataEnhancementControllerContext.Provider>\n );\n}\n\n\n","\nimport React, { useCallback, useDeferredValue, useEffect, useRef } from \"react\";\n\nimport { Button, CircularProgress, cls, focusedDisabled, IconButton, Menu, MenuItem, Separator, TextareaAutosize , iconSize } from \"@rebasepro/ui\";\nimport { XIcon, SendIcon } from \"lucide-react\";\nimport {\n AIIcon,\n useLargeLayout\n} from \"@rebasepro/core\";\nimport { EntityStatus, PluginFormActionProps, Properties, Property } from \"@rebasepro/types\";\nimport { isPropertyBuilder, stripCollectionPath } from \"@rebasepro/common\";\nimport { useDataEnhancementController } from \"./DataEnhancementControllerProvider\";\nimport { SamplePrompt } from \"../types/data_enhancement_controller\";\n\nexport function FormEnhanceAction({\n entityId,\n path,\n status,\n collection,\n formContext,\n openEntityMode\n}: PluginFormActionProps) {\n\n const largeLayout = useLargeLayout();\n\n const storageKey = createLocalStorageKey(path, status);\n\n const [loading, setLoading] = React.useState(false);\n const dataEnhancementController = useDataEnhancementController();\n\n const [samplePrompts, setSamplePrompts] = React.useState<SamplePrompt[] | undefined>(undefined);\n const [instructions, setInstructions] = React.useState<string>(\"\");\n\n const getSamplePrompts = dataEnhancementController?.getSamplePrompts;\n\n const loadingPrompts = useRef(false);\n const updateSuggestedPrompts = useCallback(async function updateSuggestedPrompts(instructions?: string) {\n if (!getSamplePrompts) return;\n if (loadingPrompts.current) return;\n loadingPrompts.current = true;\n const prompts = status === \"new\"\n ? (await getSamplePrompts(collection.singularName ?? collection.name, instructions)).prompts\n : getPromptsForExistingEntities(collection.properties);\n\n const recentPromptsFromStorage = getRecentPromptsFromStorage(storageKey);\n const recentPrompts = recentPromptsFromStorage.map(prompt => prompt.prompt);\n setSamplePrompts([...recentPromptsFromStorage, ...prompts.filter(p => !recentPrompts.includes(p.prompt))].slice(0, 5));\n loadingPrompts.current = false;\n },\n [collection.name, collection.singularName, getSamplePrompts, status]);\n\n const deferredValues = useDeferredValue(formContext?.values);\n // const enoughData = countStringCharacters(deferredValues, collection.properties) > 20;\n\n useEffect(() => {\n if (!dataEnhancementController) return;\n if (!samplePrompts) {\n setSamplePrompts(getRecentPromptsFromStorage(storageKey));\n updateSuggestedPrompts().then();\n }\n }, [dataEnhancementController, samplePrompts, storageKey, updateSuggestedPrompts, instructions, status]);\n\n useEffect(() => {\n if (!dataEnhancementController) return;\n updateSuggestedPrompts().then();\n }, [dataEnhancementController, status]);\n\n const enhance = (prompt?: string) => {\n if (!dataEnhancementController || !formContext?.values) return;\n setLoading(true);\n if (prompt) {\n addRecentPrompt(storageKey, prompt);\n setSamplePrompts([{\n prompt,\n type: \"recent\"\n }, ...(samplePrompts ?? []).slice(0, 5)]);\n }\n return dataEnhancementController.enhance({\n entityId,\n values: formContext!.values,\n instructions: prompt,\n replaceValues: true\n }).finally(() => {\n setLoading(false);\n });\n };\n\n if (!dataEnhancementController?.enabled)\n return null;\n\n const suggestions = dataEnhancementController.suggestions;\n const hasSuggestions = Object.values(suggestions).filter(Boolean).length > 0;\n\n const disabledSuggestionActions = !hasSuggestions;\n const promptSuggestionsEnabled = (samplePrompts ?? []).length > 0 && instructions.length === 0;\n\n // const noIdSet = !formContext?.entityId;\n\n function submit() {\n enhance(instructions);\n }\n\n return (\n <Menu\n align={\"end\"}\n sideOffset={8}\n className={\"max-w-[100vw]\"}\n trigger={<Button variant={\"filled\"}\n color={\"neutral\"}\n fullWidth={largeLayout && openEntityMode === \"full_screen\"}\n size={\"small\"}\n disabled={loading}>\n {!loading && <AIIcon size={\"small\"}/>}\n {loading && <CircularProgress size={\"small\"}/>}\n Autofill\n </Button>}>\n\n <MenuItem className={\"py-4\"}\n onClick={() => {\n enhance();\n }}>\n <AIIcon size={\"small\"}/>\n Autofill based on the current content\n </MenuItem>\n\n <Separator orientation={\"horizontal\"} className={\"mt-2\"}/>\n\n {samplePrompts?.map((samplePrompt, index) => {\n return <MenuItem\n key={index + \"_\" + samplePrompt.prompt}\n onClick={() => {\n setInstructions(samplePrompt.prompt);\n enhance(samplePrompt.prompt);\n }}\n >\n <div className={\"pl-9 grow text-text-secondary dark:text-text-secondary-dark\"}>\n {samplePrompt.prompt}\n </div>\n\n {samplePrompt.type === \"recent\" && <IconButton\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n removeRecentPrompt(storageKey, samplePrompt.prompt);\n setSamplePrompts((samplePrompts ?? []).filter(p => p.prompt !== samplePrompt.prompt));\n }}\n size={\"smallest\"}\n >\n <XIcon size={iconSize.smallest}/>\n </IconButton>\n }\n </MenuItem>;\n })}\n\n <Separator orientation={\"horizontal\"}/>\n\n <div\n className={cls(\n \"my-2 w-[500px] max-w-full flex items-start text-surface-700 dark:text-surface-200\"\n )}>\n\n <TextareaAutosize\n className={cls(\"p-4 rounded-lg resize-none bg-surface-100 dark:bg-surface-950 mx-2 w-full grow outline-hidden max-h-[300px] overflow-auto\", focusedDisabled)}\n value={instructions}\n autoFocus={status === \"new\"}\n disabled={loading}\n onFocus={(event) => {\n event.stopPropagation();\n }}\n placeholder={\"...or provide instructions\"}\n onKeyDown={(e) => {\n e.stopPropagation();\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault();\n submit();\n }\n\n }}\n onChange={(e) => {\n setInstructions(e.target.value);\n }}\n />\n\n <IconButton\n size={\"small\"}\n onClick={() => {\n setInstructions(\"\");\n }}\n color={!instructions ? \"primary\" : undefined}\n disabled={loading || !instructions}>\n <XIcon size={iconSize.small}/>\n </IconButton>\n\n <IconButton\n onClick={() => enhance(instructions)}\n size={\"small\"}\n color={!instructions ? \"primary\" : undefined}\n disabled={loading || !instructions}>\n {loading &&\n <CircularProgress size={\"smallest\"}/>}\n {!loading &&\n <SendIcon color={\"primary\"}/>}\n </IconButton>\n\n </div>\n\n </Menu>\n );\n}\n\nexport interface EnhanceDialogProps {\n open: boolean;\n onClose: () => void;\n selectReferences: () => void;\n loading: boolean;\n enhance: (instructions: string) => void;\n samplePrompts?: string[];\n}\n\nfunction getPromptsForExistingEntities(properties: Properties): SamplePrompt[] {\n\n const multilineProperties = Object.values(properties).filter((p: Property) => {\n if (isPropertyBuilder(p)) {\n return false;\n }\n return p.type === \"string\" && (p.ui?.markdown || p.ui?.multiline);\n });\n\n const multilinePrompt: Property | undefined = multilineProperties.length > 0\n ? multilineProperties[Math.floor(Math.random() * multilineProperties.length)] as Property\n : undefined;\n\n const prompts = [\n \"Fill the missing fields\",\n \"Translate the missing content\"\n ];\n if (multilinePrompt) {\n prompts.push(`Add 2 paragraphs to '${multilinePrompt.name}'`);\n }\n return prompts.map(p => ({\n prompt: p,\n type: \"sample\"\n }));\n}\n\nconst createLocalStorageKey = (path: string, status: EntityStatus) => {\n const statusString = status === \"new\" ? \"new\" : \"existing\";\n return `data_enhancement::${statusString}::${stripCollectionPath(path)}`;\n};\n\nconst getRecentPromptsFromStorage = (storageKey: string): SamplePrompt[] => {\n const item = localStorage.getItem(storageKey);\n return item ? JSON.parse(item).map((e: string) => ({\n prompt: e,\n type: \"recent\"\n })) : [];\n};\n\nconst addRecentPrompt = (storageKey: string, prompt: string) => {\n if (!prompt || prompt.trim().length === 0) {\n return;\n }\n const recentPrompts = getRecentPromptsFromStorage(storageKey);\n localStorage.setItem(storageKey, JSON.stringify([prompt, ...recentPrompts\n .map(e => e.prompt)\n .filter(e => e !== prompt)\n .slice(0, 5)]));\n};\n\nconst removeRecentPrompt = (storageKey: string, prompt: string) => {\n localStorage.setItem(storageKey, JSON.stringify(getRecentPromptsFromStorage(storageKey)\n .map(e => e.prompt)\n .filter(e => e !== prompt)));\n};\n","import React from \"react\";\n\nimport { EntityCollection, RebasePlugin, User } from \"@rebasepro/types\";\nimport { DataEnhancementControllerProvider } from \"./components/DataEnhancementControllerProvider\";\nimport { FormEnhanceAction } from \"./components/FormEnhanceAction\";\n\nconst DEFAULT_API_KEY = \"fcms-U9jdDii0xXWSDC34asfrf54lbkFJBfKfRWcEDEwdc4V5wDWEDF\";\n\nexport interface DataEnhancementPluginProps {\n\n apiKey?: string;\n\n /**\n * Use this function to determine if the data enhancement plugin should be enabled for a given path.\n * If this function is not provided, the plugin will be enabled for all paths.\n * If the function returns false, the plugin will be disabled for the given path.\n * You can also return a configuration object to override the default configuration.\n *\n * @param path\n * @param collection\n */\n getConfigForPath?: (props: {\n path: string,\n collection: EntityCollection,\n user: User | null\n }) => boolean;\n\n /**\n * Host to use for the data enhancement API.\n * This prop is only use in development mode.\n */\n host?: string;\n}\n\n/**\n * Use this hook to initialise the data enhancement plugin.\n * This is likely the only hook you will need to use.\n * @param props\n */\nexport function useDataEnhancementPlugin(props?: DataEnhancementPluginProps): RebasePlugin {\n\n const apiKey = props?.apiKey ?? DEFAULT_API_KEY;\n const getConfigForPath = props?.getConfigForPath;\n\n return React.useMemo(() => ({\n key: \"data_enhancement\",\n slots: [\n {\n slot: \"form.actions\",\n Component: FormEnhanceAction,\n order: 40\n }\n ],\n providers: [\n {\n scope: \"form\" as const,\n Component: DataEnhancementControllerProvider as React.ComponentType<any>,\n props: {\n apiKey,\n getConfigForPath,\n host: props?.host\n }\n }\n ]\n }), [apiKey, getConfigForPath, props?.host]);\n}\n"],"names":["flatMapEntityValues","values","path","Object","entries","flatMap","key","value","currentPath","reduce","acc","curr","DEFAULT_SERVER","enhanceDataAPIStream","props","flatValues","properties","inputEntity","entityId","request","entityName","entityDescription","propertyKey","propertyInstructions","instructions","console","debug","fetch","host","method","headers","Authorization","firebaseToken","apiKey","body","JSON","stringify","then","res","ok","error","json","reader","getReader","Error","chunk","readChunks","str","TextDecoder","decode","split","forEach","s","length","data","parse","trim","type","onUpdateDelta","partialValue","onUpdate","onEnd","e","onError","Symbol","asyncIterator","readResult","read","done","fetchEntityPromptSuggestion","input","message","prompts","map","prompt","autocompleteStream","result","textBefore","textAfter","getAppendableSuggestion","suggestion","suggestionIncludesValue","toLowerCase","startsWith","substring","indexOf","undefined","getSimplifiedProperties","property","isPropertyBuilder","fullKey","valueInPath","getValueInPath","getSimplifiedProperty","a","b","getSimpleProperty","fieldId","getFieldId","name","description","fieldConfigId","enum","getSimpleEnumValues","disabled","Boolean","ui","readOnly","of","Array","isArray","arrayParentProperty","oneOf","typeField","valueField","prop","v","i","typeKey","oneOfType","valueKey","oneOfValue","childProperty","simplifiedProperty","mapProperties","childValue","o","attachPathToKeys","keys","mapParentProperty","warn","obj","enumValues","String","id","useEditorAIController","getAuthToken","autocomplete","DataEnhancementControllerContext","React","createContext","useDataEnhancementController","useContext","getPropertyFromKey","parentKey","slice","join","DataEnhancementControllerProvider","getConfigForPath","children","collection","formContext","enabled","setEnabled","useState","suggestions","setSuggestions","loadingSuggestions","setLoadingSuggestions","enhancingInProgress","useRef","authController","useAuthController","snackbarController","useSnackbarController","useMemo","valuesRef","useEffect","current","allowReferenceDataSelection","updateConfig","useCallback","config","urlController","useUrlController","clearSuggestion","prev","_","rest","appendValueDelta","delta","currentValue","updatedValue","setFieldValue","updateSuggestedValues","currentValues","updatedValues","replaceValues","filter","p","includes","appendableValue","multiline","trimmedValue","trimEnd","endsWith","trimStart","displayNeededSubscriptionSnackbar","projectId","open","autoHideDuration","editorAIController","clearAllSuggestions","enhance","user","Promise","reject","resolvedPath","resolveDatabasePathsFrom","resolve","code","singularName","errors","catch","getSamplePrompts","dataEnhancementController","FormEnhanceAction","status","openEntityMode","largeLayout","useLargeLayout","storageKey","createLocalStorageKey","loading","setLoading","samplePrompts","setSamplePrompts","setInstructions","loadingPrompts","updateSuggestedPrompts","getPromptsForExistingEntities","recentPromptsFromStorage","getRecentPromptsFromStorage","recentPrompts","useDeferredValue","addRecentPrompt","finally","submit","jsxs","Menu","Button","jsx","AIIcon","CircularProgress","MenuItem","Separator","samplePrompt","index","IconButton","preventDefault","stopPropagation","removeRecentPrompt","XIcon","iconSize","smallest","cls","TextareaAutosize","focusedDisabled","event","shiftKey","target","small","SendIcon","multilineProperties","markdown","multilinePrompt","Math","floor","random","push","statusString","stripCollectionPath","item","localStorage","getItem","setItem","DEFAULT_API_KEY","useDataEnhancementPlugin","$","_c","t0","t1","for","slot","Component","order","t2","t3","slots","providers","scope"],"mappings":";;;;AAAO,WAASA,oBAAsCC,QAAWC,OAAO,IAAY;AAChF,QAAI,CAACD,OAAQ,QAAO,CAAA;AACpB,WAAOE,OAAOC,QAAQH,MAAM,EAAEI,QAAQ,CAAC,CAACC,KAAKC,KAAK,MAAM;AACpD,YAAMC,cAAcN,OAAO,GAAGA,IAAI,IAAII,GAAG,KAAKA;AAC9C,UAAI,OAAOC,UAAU,UAAU;AAC3B,eAAOP,oBAAoBO,OAAOC,WAAW;AAAA,MACjD,OAAO;AACH,eAAO;AAAA,UAAE,CAACA,WAAW,GAA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,IAAA,OAAA;AAAAA,WAAAT,EAAA,CAAA;AAAA,IAAA;AAAAE,SApB2BO;AAoB3B,WApBMP;AAAAA,EAoBqC;;;;;"}
|
|
@@ -80,8 +80,14 @@ export type AuthController<USER extends User = User, ExtraData = unknown> = {
|
|
|
80
80
|
export interface AuthControllerExtended<USER extends User = User, ExtraData = unknown> extends AuthController<USER, ExtraData> {
|
|
81
81
|
/** Login with email and password */
|
|
82
82
|
emailPasswordLogin?(email: string, password: string): Promise<void>;
|
|
83
|
-
/** Login with a Google token
|
|
84
|
-
googleLogin
|
|
83
|
+
/** Login with a Google token or authorization code */
|
|
84
|
+
googleLogin?: {
|
|
85
|
+
(token: string, tokenType?: "idToken" | "accessToken"): Promise<void>;
|
|
86
|
+
(payload: {
|
|
87
|
+
code: string;
|
|
88
|
+
redirectUri: string;
|
|
89
|
+
}): Promise<void>;
|
|
90
|
+
};
|
|
85
91
|
/** Register a new user */
|
|
86
92
|
register?(email: string, password: string, displayName?: string): Promise<void>;
|
|
87
93
|
/** Skip login (for anonymous access if enabled) */
|
|
@@ -167,4 +167,17 @@ export interface RebaseClient<DB = unknown> {
|
|
|
167
167
|
email?: EmailService;
|
|
168
168
|
/** Admin API for user and role management */
|
|
169
169
|
admin?: AdminAPI;
|
|
170
|
+
/**
|
|
171
|
+
* The base HTTP URL of the backend server.
|
|
172
|
+
* Exposed by the SDK client (`@rebasepro/client`) and used to auto-derive
|
|
173
|
+
* the `ApiConfigProvider` URL.
|
|
174
|
+
*/
|
|
175
|
+
baseUrl?: string;
|
|
176
|
+
/**
|
|
177
|
+
* WebSocket client for realtime subscriptions and admin capabilities.
|
|
178
|
+
* Exposed by the SDK client (`@rebasepro/client`). The shape is intentionally
|
|
179
|
+
* left as `unknown` in the base interface — callers should narrow via feature
|
|
180
|
+
* detection (e.g. `typeof ws.executeSql === "function"`).
|
|
181
|
+
*/
|
|
182
|
+
ws?: unknown;
|
|
170
183
|
}
|
|
@@ -144,17 +144,18 @@ export interface AppView {
|
|
|
144
144
|
* It will still be accessible if you reach the specified path
|
|
145
145
|
*/
|
|
146
146
|
hideFromNavigation?: boolean;
|
|
147
|
+
/**
|
|
148
|
+
* Navigation group for this view.
|
|
149
|
+
* Views sharing the same group name will be visually grouped
|
|
150
|
+
* together in the drawer and home page. If not set, the view
|
|
151
|
+
* falls into the default "Views" group.
|
|
152
|
+
*/
|
|
153
|
+
group?: string;
|
|
147
154
|
/**
|
|
148
155
|
* Component to be rendered. This can be any React component, and can use
|
|
149
156
|
* any of the provided hooks
|
|
150
157
|
*/
|
|
151
158
|
view: React.ReactNode;
|
|
152
|
-
/**
|
|
153
|
-
* Optional field used to group top level navigation entries under a
|
|
154
|
-
* navigation view.
|
|
155
|
-
* This prop is ignored for admin views.
|
|
156
|
-
*/
|
|
157
|
-
group?: string;
|
|
158
159
|
/**
|
|
159
160
|
* If true, a wildcard route (slug/*) is automatically registered
|
|
160
161
|
* alongside the base route, enabling nested navigation within this view.
|
|
@@ -193,6 +194,17 @@ export interface NavigationGroupMapping {
|
|
|
193
194
|
* List of collection ids or view paths that belong to this group.
|
|
194
195
|
*/
|
|
195
196
|
entries: string[];
|
|
197
|
+
/**
|
|
198
|
+
* Configure which groups start collapsed.
|
|
199
|
+
* Set to `true` to collapse in both drawer and home page,
|
|
200
|
+
* or use an object to control each independently.
|
|
201
|
+
*
|
|
202
|
+
* @defaultValue false (expanded)
|
|
203
|
+
*/
|
|
204
|
+
collapsedByDefault?: boolean | {
|
|
205
|
+
drawer?: boolean;
|
|
206
|
+
home?: boolean;
|
|
207
|
+
};
|
|
196
208
|
}
|
|
197
209
|
export interface NavigationEntry {
|
|
198
210
|
id: string;
|
|
@@ -3,7 +3,7 @@ import type { EntityCollection } from "../types/collections";
|
|
|
3
3
|
import type { EntityCollectionsBuilder } from "../types/builders";
|
|
4
4
|
import type { EntityCustomView } from "../types/entity_views";
|
|
5
5
|
import type { EntityAction } from "../types/entity_actions";
|
|
6
|
-
import type { AppView } from "./navigation";
|
|
6
|
+
import type { AppView, NavigationGroupMapping } from "./navigation";
|
|
7
7
|
/**
|
|
8
8
|
* Options to enable the built-in collection editor.
|
|
9
9
|
* When provided to `<RebaseCMS>`, the editor is auto-wired as a native feature.
|
|
@@ -25,6 +25,14 @@ export interface RebaseCMSConfig<EC extends EntityCollection = any> {
|
|
|
25
25
|
entityViews?: EntityCustomView<any>[];
|
|
26
26
|
entityActions?: EntityAction[];
|
|
27
27
|
plugins?: any[];
|
|
28
|
+
/**
|
|
29
|
+
* Centralized configuration for how collections and views are grouped
|
|
30
|
+
* in the navigation sidebar and home page.
|
|
31
|
+
* Each mapping defines a named group and the collection/view slugs
|
|
32
|
+
* that belong to it. The array order determines group display order.
|
|
33
|
+
* Entry order within each group determines card order.
|
|
34
|
+
*/
|
|
35
|
+
navigationGroupMappings?: NavigationGroupMapping[];
|
|
28
36
|
/**
|
|
29
37
|
* Enable the built-in visual collection/schema editor.
|
|
30
38
|
* Pass `true` for zero-config, or an options object for fine-grained control.
|
|
@@ -62,6 +62,13 @@ export interface EntitySidePanelProps<M extends Record<string, unknown> = Record
|
|
|
62
62
|
* Allow the user to open the entity fullscreen
|
|
63
63
|
*/
|
|
64
64
|
allowFullScreen?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Pre-populate the form with these values when creating a new entity.
|
|
67
|
+
* Only applied when `entityId` is not set (i.e. the form is in "new" mode).
|
|
68
|
+
* Useful for actions that fetch data from an external source (e.g. a URL)
|
|
69
|
+
* and want to pre-fill the document before the user saves.
|
|
70
|
+
*/
|
|
71
|
+
defaultValues?: Partial<M>;
|
|
65
72
|
}
|
|
66
73
|
/**
|
|
67
74
|
* Controller to open the side dialog displaying entity forms
|
|
@@ -3,6 +3,7 @@ import type { AuthController } from "./controllers/auth";
|
|
|
3
3
|
import type { StorageSource } from "./controllers/storage";
|
|
4
4
|
import type { UserConfigurationPersistence } from "./controllers/local_config_persistence";
|
|
5
5
|
import type { DatabaseAdmin } from "./types/backend";
|
|
6
|
+
import type { RebaseClient } from "./controllers/client";
|
|
6
7
|
import type { RebaseData } from "./controllers/data";
|
|
7
8
|
import type { User } from "./users";
|
|
8
9
|
import type { UserManagementDelegate } from "./types/user_management_delegate";
|
|
@@ -12,6 +13,22 @@ import type { UserManagementDelegate } from "./types/user_management_delegate";
|
|
|
12
13
|
* @group Hooks and utilities
|
|
13
14
|
*/
|
|
14
15
|
export type RebaseCallContext<USER extends User = User> = {
|
|
16
|
+
/**
|
|
17
|
+
* The Rebase client instance.
|
|
18
|
+
* Available in all entity callbacks (beforeSave, afterSave, afterRead,
|
|
19
|
+
* beforeDelete, afterDelete) and in CollectionActionsProps via context.
|
|
20
|
+
* Use it to call backend functions, access data, storage, etc.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* // In a beforeSave callback:
|
|
24
|
+
* const result = await context.client.functions.invoke('my-function', { ... });
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* // In a CollectionAction component:
|
|
28
|
+
* const { client } = props.context;
|
|
29
|
+
* const result = await client.functions.invoke('extract-job', { url });
|
|
30
|
+
*/
|
|
31
|
+
client: RebaseClient<any>;
|
|
15
32
|
/**
|
|
16
33
|
* Unified data access — `context.data.products.create(...)`.
|
|
17
34
|
* Access any collection as a dynamic property.
|
|
@@ -9,6 +9,7 @@ import type { RebaseContext } from "../rebase_context";
|
|
|
9
9
|
import type { Relation } from "./relations";
|
|
10
10
|
import type { EntityCustomView } from "./entity_views";
|
|
11
11
|
import type { EntityAction } from "./entity_actions";
|
|
12
|
+
import type { ComponentRef } from "./component_ref";
|
|
12
13
|
/**
|
|
13
14
|
* Base interface containing all driver-agnostic collection properties.
|
|
14
15
|
* Use {@link PostgresCollection} or {@link FirebaseCollection} for
|
|
@@ -86,6 +87,9 @@ export interface BaseEntityCollection<M extends Record<string, unknown> = Record
|
|
|
86
87
|
icon?: string | React.ReactNode;
|
|
87
88
|
/**
|
|
88
89
|
* Navigation group for this collection.
|
|
90
|
+
* Collections sharing the same group name will be visually grouped
|
|
91
|
+
* together in the drawer and home page. If not set, the collection
|
|
92
|
+
* falls into the default "Views" group.
|
|
89
93
|
*/
|
|
90
94
|
group?: string;
|
|
91
95
|
/**
|
|
@@ -301,7 +305,7 @@ export interface BaseEntityCollection<M extends Record<string, unknown> = Record
|
|
|
301
305
|
/**
|
|
302
306
|
* Builder for the collection actions rendered in the toolbar
|
|
303
307
|
*/
|
|
304
|
-
Actions?:
|
|
308
|
+
Actions?: ComponentRef<CollectionActionsProps>[];
|
|
305
309
|
}
|
|
306
310
|
/**
|
|
307
311
|
* A collection backed by PostgreSQL (or any SQL database).
|
|
@@ -482,6 +486,21 @@ export interface CollectionActionsProps<M extends Record<string, unknown> = Reco
|
|
|
482
486
|
* undefined means the count is still loading.
|
|
483
487
|
*/
|
|
484
488
|
collectionEntitiesCount?: number;
|
|
489
|
+
/**
|
|
490
|
+
* Programmatically open the new-document form for this collection,
|
|
491
|
+
* optionally pre-populating it with initial field values.
|
|
492
|
+
* The form opens in the same mode configured for the collection
|
|
493
|
+
* (side panel, full screen, or split).
|
|
494
|
+
*
|
|
495
|
+
* This is the primary hook for workflows that need to create a document
|
|
496
|
+
* from external data — e.g. fetching content from a URL, importing from
|
|
497
|
+
* a third-party API, or duplicating from another system.
|
|
498
|
+
*
|
|
499
|
+
* @example
|
|
500
|
+
* // Inside a custom CollectionAction component:
|
|
501
|
+
* openNewDocument({ title: "Fetched title", body: "..." });
|
|
502
|
+
*/
|
|
503
|
+
openNewDocument: (defaultValues?: Record<string, unknown>) => void;
|
|
485
504
|
}
|
|
486
505
|
/**
|
|
487
506
|
* Use this controller to retrieve the selected entities or modify them in
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type React from "react";
|
|
2
|
+
/**
|
|
3
|
+
* Internal marker for a lazily-loaded component reference.
|
|
4
|
+
* Created by the Vite transform plugin when converting string paths
|
|
5
|
+
* to deferred `import()` calls. Users should NOT create these manually.
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
export interface LazyComponentRef<P = unknown> {
|
|
10
|
+
readonly __rebaseLazy: true;
|
|
11
|
+
readonly load: () => Promise<{
|
|
12
|
+
default: React.ComponentType<P>;
|
|
13
|
+
}>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A reference to a React component that can be provided in three forms:
|
|
17
|
+
*
|
|
18
|
+
* 1. **String path** (recommended for collection configs):
|
|
19
|
+
* ```ts
|
|
20
|
+
* Field: "../../frontend/src/components/MyField"
|
|
21
|
+
* ```
|
|
22
|
+
* The Vite plugin transforms this into a `LazyComponentRef` at build time.
|
|
23
|
+
* On the backend, the string stays inert and is never evaluated.
|
|
24
|
+
*
|
|
25
|
+
* 2. **Lazy import function**:
|
|
26
|
+
* ```ts
|
|
27
|
+
* Field: () => import("../../frontend/src/components/MyField")
|
|
28
|
+
* ```
|
|
29
|
+
* Standard ES dynamic import. Backend never calls the function.
|
|
30
|
+
*
|
|
31
|
+
* 3. **Direct component reference** (use only in frontend-only code):
|
|
32
|
+
* ```ts
|
|
33
|
+
* Field: MyFieldComponent
|
|
34
|
+
* ```
|
|
35
|
+
* Importing a component at the top level will pull React into the
|
|
36
|
+
* backend runtime — only safe in code that the backend never imports.
|
|
37
|
+
*
|
|
38
|
+
* @group Types
|
|
39
|
+
*/
|
|
40
|
+
export type ComponentRef<P = unknown> = React.ComponentType<P> | LazyComponentRef<P> | (() => Promise<{
|
|
41
|
+
default: React.ComponentType<P>;
|
|
42
|
+
}>) | string;
|
|
43
|
+
/**
|
|
44
|
+
* Type guard: checks if a value is a `LazyComponentRef` produced by the
|
|
45
|
+
* Vite transform plugin.
|
|
46
|
+
*/
|
|
47
|
+
export declare function isLazyComponentRef<P = unknown>(ref: unknown): ref is LazyComponentRef<P>;
|
|
@@ -2,6 +2,7 @@ import React from "react";
|
|
|
2
2
|
import type { Entity, EntityValues } from "./entities";
|
|
3
3
|
import type { EntityCollection } from "./collections";
|
|
4
4
|
import type { FormexController } from "./formex";
|
|
5
|
+
import type { ComponentRef } from "./component_ref";
|
|
5
6
|
/**
|
|
6
7
|
* Context passed to custom fields and entity views.
|
|
7
8
|
* @group Form custom fields
|
|
@@ -46,7 +47,7 @@ export type EntityCustomView<M extends Record<string, unknown> = Record<string,
|
|
|
46
47
|
name: string;
|
|
47
48
|
tabComponent?: React.ReactNode;
|
|
48
49
|
includeActions?: boolean | "bottom";
|
|
49
|
-
Builder?:
|
|
50
|
+
Builder?: ComponentRef<EntityCustomViewParams<M>>;
|
|
50
51
|
position?: "start" | "end";
|
|
51
52
|
};
|
|
52
53
|
export interface EntityCustomViewParams<M extends Record<string, unknown> = Record<string, unknown>> {
|