import { useEffect } from "react" import { customBlockDataSources } from "../bridge/sandboxClient.js" import type { UseDataSourceOptions, UseDataSourceResult } from "../types.js" import { useCustomBlockHost } from "./useHostState.js" /** * Reads from the data source mapped to the given semantic `key`. * * @param key - The semantic data-source key the block is wired to (e.g. `"people"`). * @param options - Optional live snapshot options. `limit` defaults to 20 and * is capped at 999. * * @example * const { items, isLoading, hasMore, error } = useDataSource("default", { limit: 25 }) */ export function useDataSource( key: string, options?: UseDataSourceOptions, ): UseDataSourceResult { const host = useCustomBlockHost() const limit = options?.limit const matchingDataSource = host.status === "initialized" ? host.dataSources.find(dataSource => dataSource.key === key) : undefined const isInitialized = host.status === "initialized" useEffect(() => { if (!isInitialized) { return } customBlockDataSources.query(key, { limit }) }, [matchingDataSource, isInitialized, key, limit]) const view = customBlockDataSources.getView(host, key) return { items: view.items, collectionSchema: view.collectionSchema, propertySchemasById: view.propertySchemasById, propertySchemasByKey: view.propertySchemasByKey, isLoading: view.isLoading, hasMore: view.hasMore, error: view.error, } }