@rebasepro/cms 0.25.0-canary.ge06257e → 0.25.1

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.
Files changed (26) hide show
  1. package/dist/collection_editor/liveSchemaClient.d.ts +3 -3
  2. package/dist/collection_editor/liveSchemaClient.js.map +1 -1
  3. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js +52 -48
  4. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js.map +1 -1
  5. package/dist/collection_editor/ui/collection_editor/properties/DateTimePropertyField.js +22 -22
  6. package/dist/collection_editor/ui/collection_editor/properties/DateTimePropertyField.js.map +1 -1
  7. package/dist/collection_editor/ui/collection_editor/properties/NumberPropertyField.js +14 -14
  8. package/dist/collection_editor/ui/collection_editor/properties/NumberPropertyField.js.map +1 -1
  9. package/dist/collection_editor/ui/collection_editor/properties/StringPropertyField.js +24 -24
  10. package/dist/collection_editor/ui/collection_editor/properties/StringPropertyField.js.map +1 -1
  11. package/dist/components/CollectionTableBinding/internal/EntityTableCellActions.js +1 -1
  12. package/dist/components/CollectionTableBinding/internal/EntityTableCellActions.js.map +1 -1
  13. package/dist/components/DeleteEntityDialog.js +9 -9
  14. package/dist/components/DeleteEntityDialog.js.map +1 -1
  15. package/dist/components/PropertyConfigBadge.js +1 -1
  16. package/dist/components/PropertyConfigBadge.js.map +1 -1
  17. package/dist/components/ReferenceTable/SelectionTableBinding.js +4 -3
  18. package/dist/components/ReferenceTable/SelectionTableBinding.js.map +1 -1
  19. package/dist/components/RelationSelector.js +2 -2
  20. package/dist/components/RelationSelector.js.map +1 -1
  21. package/dist/components/app/Scaffold.js.map +1 -1
  22. package/dist/editor/editor.js +2 -2
  23. package/dist/editor/editor.js.map +1 -1
  24. package/dist/editor/extensions/drag-and-drop.js +1 -1
  25. package/dist/editor/extensions/drag-and-drop.js.map +1 -1
  26. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"RelationSelector.js","names":[],"sources":["../../src/components/RelationSelector.tsx"],"sourcesContent":["\nimport {\n ArrowRightToLineIcon,\n CheckIcon,\n ChevronDownIcon,\n Chip,\n CircularProgress,\n cls,\n defaultBorderMixin,\n fieldBackgroundDisabledMixin,\n fieldBackgroundHoverMixin,\n fieldBackgroundInvisibleMixin,\n fieldBackgroundMixin,\n focusedDisabled,\n IconButton,\n iconSize,\n PlusIcon,\n PopoverPrimitive,\n SearchIcon,\n Separator,\n Tooltip,\n usePortalContainer,\n XIcon\n} from \"@rebasepro/ui\";\nimport * as React from \"react\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { Command as CommandPrimitive } from \"cmdk\";\nimport { Entity, EntityRelation, FilterValues, Relation, getCollectionDataPath } from \"@rebasepro/types\";\nimport { EntityPreviewBindingData } from \"./EntityPreviewBinding\";\nimport { PickerTrigger } from \"./PickerTrigger\";\nimport { getTitlePropertyKey, useData, usePermissions, useRelationSelector, useTranslation } from \"@rebasepro/app\";\nimport { useSidePanel } from \"../hooks/useSidePanel\";\nimport { normalizeToEntityRelation } from \"@rebasepro/common\";\nimport { findEntitiesByIds } from \"../util/find_entities_by_ids\";\n\n/** Whether an authored relation yields many rows. Derived from its kind. */\nfunction relationCardinality(relation: { kind?: string; cardinality?: string } | undefined): \"one\" | \"many\" | undefined {\n if (!relation) return undefined;\n if (relation.kind === \"via\") return relation.cardinality as \"one\" | \"many\" | undefined;\n if (relation.kind === \"hasMany\" || relation.kind === \"manyToMany\") return \"many\";\n if (relation.kind === \"belongsTo\" || relation.kind === \"hasOne\") return \"one\";\n return relation.cardinality as \"one\" | \"many\" | undefined;\n}\n\n\nexport interface RelationItem {\n id: string | number;\n label: string;\n description?: string;\n data?: Entity;\n relation: EntityRelation;\n}\n\nexport interface RelationSelectorProps {\n className?: string;\n name?: string;\n id?: string;\n value?: EntityRelation | EntityRelation[] | null;\n /** Callback returning selected EntityRelation(s) */\n\n onValueChange?: (updatedValue: EntityRelation | EntityRelation[] | undefined) => void;\n placeholder?: React.ReactNode;\n /**\n * `large` is the form's size and is on the shared 28/32/40/48 control\n * scale, so a relation picker lines up with the text field beside it.\n *\n * `small` and `medium` predate that scale (42 and 56) and are kept as they\n * are because the filter row is built around them. A table cell passes\n * `triggerContent` instead, and has no size of its own.\n */\n size?: \"small\" | \"medium\" | \"large\";\n useChips?: boolean;\n disabled?: boolean;\n invisible?: boolean;\n\n relation: Relation;\n /**\n * Whether the selector picks many rows or one.\n *\n * Defaults to what the relation implies — a `hasMany` or `manyToMany`\n * picks many — which is right wherever the selector *edits* the relation,\n * because there the cardinality is the shape of the stored value.\n *\n * A filter is the case where it is not. `tags == <one tag>` asks a single\n * question about a to-many link, and the operator is what decides how many\n * values it takes. Deriving multiplicity from the relation there meant a\n * to-many relation could only ever emit a list, so the filter field had to\n * hide every single-value operator to avoid handing `==` an array.\n */\n multiple?: boolean;\n fixedFilter?: FilterValues<string>;\n pageSize?: number;\n emptyPlaceholder?: string;\n searchPlaceholder?: string;\n /** Shown in the open list when a search matched nothing. */\n noResultsText?: string;\n /**\n * Shown on the closed trigger when nothing is selected. Says only that the\n * field is empty — see the note by `resolvedPlaceholder` for why it cannot\n * say whether there is anything to pick.\n */\n emptyText?: string;\n /**\n * Shown in the open list when the target collection turned out to hold no\n * rows at all, as opposed to a search simply not matching. Defaults to a\n * sentence naming the target collection.\n */\n emptyCollectionText?: string;\n loadingText?: string;\n /**\n * Whether the list is open, for a caller that opens it from outside the\n * trigger — a table cell's opener. Every open and close the selector\n * makes itself is reported through `onOpenChange`, controlled or not.\n */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /**\n * Replaces everything the trigger draws — the value, the box, its padding\n * and the chevron — with this node. For a caller that frames the picker\n * itself: a table cell passes the preview it shows at rest, so the cell\n * looks the same whether the picker is mounted, closed or open.\n */\n triggerContent?: React.ReactNode;\n /**\n * Positions the list against this element instead of the trigger. A\n * table cell passes itself: the trigger inside it can be taller than the\n * cell that clips it, and the list belongs under what can be seen.\n */\n anchorRef?: React.RefObject<HTMLElement | null>;\n /**\n * Whether the open list offers to create a row in the target collection.\n * Defaults to `true`. The offer is shown only when the user could actually\n * insert into that collection — the same permission check the selection\n * dialog's \"Add\" button makes — so turning this off is for the cases where\n * creating is possible but not wanted, like a filter.\n */\n allowCreate?: boolean;\n}\n\nexport const RelationSelector = React.forwardRef<\n HTMLElement,\n RelationSelectorProps\n>(\n (\n {\n value,\n size = \"medium\",\n onValueChange,\n invisible,\n disabled,\n placeholder,\n useChips = true,\n className,\n relation,\n multiple: multipleOverride,\n fixedFilter,\n pageSize,\n emptyPlaceholder,\n searchPlaceholder = \"Search...\",\n noResultsText = \"No matches.\",\n emptyText = \"Select…\",\n emptyCollectionText,\n loadingText = \"Loading...\",\n allowCreate = true,\n open: openProp,\n onOpenChange,\n triggerContent,\n anchorRef\n },\n ref\n ) => {\n\n const collection = relation.target();\n const dataPath = getCollectionDataPath(collection);\n const dataClient = useData();\n const sidePanelController = useSidePanel();\n const { canCreate } = usePermissions();\n const { t } = useTranslation();\n const contextPortalContainer = usePortalContainer();\n const multiple = multipleOverride ?? relationCardinality(relation) === \"many\";\n\n const [isPopoverOpen, setIsPopoverOpenState] = useState(false);\n const isPopoverOpenRef = useRef(false);\n // The list is only worth fetching once the picker has been opened. A\n // table cell mounts one of these per row, and the selected value is\n // resolved by its own effect below, not from the list. Latches on the\n // first open so a closed popover keeps its results.\n const [listRequested, setListRequested] = useState(false);\n const [selectedItems, setSelectedItems] = useState<RelationItem[]>([]);\n const [isLoadingSelectedItems, setIsLoadingSelectedItems] = useState(false);\n const [searchString, setSearchString] = useState<string>(\"\");\n\n // Track IDs that were set via local user interaction (onItemClick / handleClear / handleRemoveItem).\n // When an incoming value change matches these IDs exactly, we skip async re-resolution.\n const localSelectionIdsRef = useRef<string | null>(null);\n // Entity of selected IDs captured when the popover opens.\n // Used to sort the dropdown list so selected items appear at the top.\n // Stays stable for the entire popover session so items don't jump around.\n const pinnedIdsRef = useRef<Set<string> | null>(null);\n\n const selectedItemsForPinRef = useRef<RelationItem[]>([]);\n selectedItemsForPinRef.current = selectedItems;\n const onOpenChangeRef = useRef(onOpenChange);\n onOpenChangeRef.current = onOpenChange;\n\n // Every open and close goes through here. Opening pins the current\n // selection to the top of the list for as long as it stays open, and\n // is what first requests the list at all.\n const setPopoverOpen = useCallback((next: boolean, notify = true) => {\n if (next) {\n // From the value as well as the resolved items: a picker a\n // table cell mounts already open has not resolved them yet.\n pinnedIdsRef.current = new Set([\n ...selectedItemsForPinRef.current.map(i => String(i.id)),\n ...relationsArrayRef.current.map(rel =>\n String(typeof rel === \"string\" || typeof rel === \"number\" ? rel : rel.id))\n ]);\n setListRequested(true);\n } else {\n pinnedIdsRef.current = null;\n }\n const changed = isPopoverOpenRef.current !== next;\n isPopoverOpenRef.current = next;\n setIsPopoverOpenState(next);\n if (changed && notify) onOpenChangeRef.current?.(next);\n }, []);\n\n useEffect(() => {\n if (openProp === undefined || openProp === isPopoverOpenRef.current) return;\n if (openProp && disabled) {\n onOpenChangeRef.current?.(false);\n return;\n }\n setPopoverOpen(openProp, false);\n }, [openProp, disabled, setPopoverOpen]);\n\n const {\n items: availableItems,\n isLoading,\n hasMore,\n search,\n loadMore,\n entityToRelationItem\n } = useRelationSelector({\n path: dataPath,\n collection,\n fixedFilter,\n pageSize,\n enabled: listRequested\n });\n\n const scrollContainerRef = useRef<HTMLDivElement>(null);\n const sentinelRef = useRef<HTMLDivElement>(null);\n const observerRef = useRef<IntersectionObserver | null>(null);\n const localTriggerRef = useRef<HTMLElement | null>(null);\n\n const handleButtonRef = useCallback((node: HTMLElement | null) => {\n localTriggerRef.current = node;\n if (typeof ref === \"function\") {\n ref(node);\n } else if (ref) {\n ref.current = node;\n }\n }, [ref]);\n const contentRef = useRef<HTMLDivElement | null>(null);\n const searchInputRef = useRef<HTMLInputElement | null>(null);\n\n // Keep stable refs for dependencies used in the value-resolution effect\n // so the effect only re-fires when the actual `value` identity changes.\n const dataClientRef = useRef(dataClient);\n dataClientRef.current = dataClient;\n const entityToRelationItemRef = useRef(entityToRelationItem);\n entityToRelationItemRef.current = entityToRelationItem;\n const collectionSlugRef = useRef(collection.slug);\n collectionSlugRef.current = collection.slug;\n const collectionRef = useRef(collection);\n collectionRef.current = collection;\n\n // Stable ref to track which IDs we've already resolved\n const resolvedIdsRef = useRef<string>(\"\");\n // Track whether we have resolved items (used for skip guard without adding to deps)\n const hasResolvedItemsRef = useRef(false);\n\n const selectedItemsRef = useRef(selectedItems);\n selectedItemsRef.current = selectedItems;\n\n // Normalize incoming values — plain { __type: \"relation\" } objects\n // from the server are converted to proper EntityRelation instances.\n const rawArray = !value ? [] : Array.isArray(value) ? value : [value];\n const relationsArray = rawArray.map(rel => {\n if (typeof rel === \"string\" || typeof rel === \"number\") return rel;\n return normalizeToEntityRelation(rel) ?? rel;\n });\n\n // Build a fingerprint of the incoming value's IDs\n const incomingIds = relationsArray\n .map(rel => {\n const isPrimitive = typeof rel === \"string\" || typeof rel === \"number\";\n return String(isPrimitive ? rel : (rel as EntityRelation).id);\n })\n .sort()\n .join(\",\");\n\n // CheckIcon if every relation already has embedded data\n const allHaveData = relationsArray.length > 0 && relationsArray.every(rel => {\n if (typeof rel === \"string\" || typeof rel === \"number\") return false;\n return !!(rel as EntityRelation)?.data;\n });\n\n const relationsArrayRef = useRef(relationsArray);\n relationsArrayRef.current = relationsArray;\n\n useEffect(() => {\n let active = true;\n const currentRelationsArray = relationsArrayRef.current;\n\n // If the IDs haven't changed and we already resolved them, skip entirely\n if (incomingIds === resolvedIdsRef.current && (allHaveData || hasResolvedItemsRef.current)) {\n return;\n }\n\n // FAST PATH: If the incoming IDs match what we just set locally via user interaction,\n // our selectedItems already have the correct data — no re-resolution needed.\n //\n // The fingerprint answers for one echo only, and is dropped on the\n // first incoming value whether it matches or not. Kept, it also\n // matched a *later* return to the same ids — pick A, discard to B,\n // undo back to A — and the chip went on showing B.\n const localSelectionIds = localSelectionIdsRef.current;\n localSelectionIdsRef.current = null;\n if (localSelectionIds !== null && incomingIds === localSelectionIds) {\n resolvedIdsRef.current = incomingIds;\n hasResolvedItemsRef.current = true;\n // Do NOT call setSelectedItems or setIsLoadingSelectedItems — they are already correct.\n return;\n }\n\n const currentSelected = selectedItemsRef.current;\n const currentSelectedMap = new Map(currentSelected.map(item => [String(item.id), item]));\n\n let allCovered = true;\n const newResolvedItems: RelationItem[] = [];\n const toRelationItem = entityToRelationItemRef.current;\n const slug = collectionSlugRef.current;\n\n for (const rel of currentRelationsArray) {\n const isPrimitive = typeof rel === \"string\" || typeof rel === \"number\";\n const relId = String(isPrimitive ? rel : (rel as EntityRelation).id);\n const hasEmbeddedData = !isPrimitive && !!(rel as EntityRelation).data;\n\n if (hasEmbeddedData) {\n const r = rel as EntityRelation;\n // admin wire format embeds relation data as { id, path, values }\n newResolvedItems.push(toRelationItem(r.data as unknown as Entity, r));\n } else if (currentSelectedMap.has(relId)) {\n // We already have it in currentSelected\n const existingItem = currentSelectedMap.get(relId)!;\n newResolvedItems.push(existingItem);\n } else {\n allCovered = false;\n break;\n }\n }\n\n // FAST PATH: We have all necessary data embedded or in local cache\n if (allCovered) {\n setSelectedItems(newResolvedItems);\n hasResolvedItemsRef.current = true;\n resolvedIdsRef.current = incomingIds;\n setIsLoadingSelectedItems(false);\n return;\n }\n\n // SLOW PATH: fetch missing data — but don't show loading if popover is open\n // (user is actively interacting; showing a spinner is disruptive)\n if (!isPopoverOpenRef.current) {\n setIsLoadingSelectedItems(true);\n }\n const client = dataClientRef.current;\n const target = collectionRef.current;\n\n // The ids nothing above resolves, by the path they are read at:\n // one request per path (per 1,000 ids), not one per id.\n const unresolved = new Map<string, (string | number)[]>();\n for (const rel of currentRelationsArray) {\n const isPrimitive = typeof rel === \"string\" || typeof rel === \"number\";\n const relId = isPrimitive ? rel : (rel as EntityRelation).id;\n if (!isPrimitive && (rel as EntityRelation).data) continue;\n if (currentSelectedMap.has(String(relId))) continue;\n const path = isPrimitive ? slug : (rel as EntityRelation).path;\n unresolved.set(path, [...(unresolved.get(path) ?? []), relId]);\n }\n\n Promise.all(\n [...unresolved].map(async ([path, ids]): Promise<[string, Map<string, Entity>]> => {\n try {\n return [path, await findEntitiesByIds(client.collection(path), target, ids)];\n } catch (e) {\n console.warn(\"RelationSelector: could not fetch the entities for relations\", path, ids, e);\n return [path, new Map()];\n }\n })\n ).then(read => {\n const readByPath = new Map(read);\n return currentRelationsArray.map((rel) => {\n const isPrimitive = typeof rel === \"string\" || typeof rel === \"number\";\n const relId = isPrimitive ? rel : (rel as EntityRelation).id;\n const path = isPrimitive ? slug : (rel as EntityRelation).path;\n const relation = isPrimitive ? new EntityRelation(relId, path) : rel as EntityRelation;\n\n if (!isPrimitive && (rel as EntityRelation).data) {\n // admin wire format embeds relation data as { id, path, values }\n return toRelationItem((rel as EntityRelation).data as unknown as Entity, relation);\n }\n if (currentSelectedMap.has(String(relId))) {\n return currentSelectedMap.get(String(relId))!;\n }\n const entity = readByPath.get(path)?.get(String(relId));\n if (entity) return toRelationItem(entity, relation);\n return { id: relId,\nlabel: String(relId),\nrelation } as RelationItem;\n });\n }).then(resolved => {\n if (active) {\n setSelectedItems(resolved);\n setIsLoadingSelectedItems(false);\n hasResolvedItemsRef.current = true;\n resolvedIdsRef.current = incomingIds;\n }\n });\n\n return () => {\n active = false;\n };\n }, [incomingIds, allHaveData]);\n\n const sentinelCallbackRef = useCallback((node: HTMLDivElement | null) => {\n if (observerRef.current) {\n observerRef.current.disconnect();\n observerRef.current = null;\n }\n if (sentinelRef.current !== node) {\n (sentinelRef as React.MutableRefObject<HTMLDivElement | null>).current = node;\n }\n if (!node || !hasMore || isLoading || !loadMore) return;\n const observer = new IntersectionObserver(\n (entries) => {\n const entry = entries[0];\n if (entry.isIntersecting && hasMore && !isLoading) loadMore();\n },\n {\n root: scrollContainerRef.current,\n rootMargin: \"20px\",\n threshold: 0\n }\n );\n observer.observe(node);\n observerRef.current = observer;\n }, [hasMore, isLoading, loadMore]);\n\n useEffect(() => () => {\n if (observerRef.current) observerRef.current.disconnect();\n }, []);\n\n // Enhanced scroll event listener specifically for dialog contexts\n useEffect(() => {\n const scrollContainer = scrollContainerRef.current;\n if (!scrollContainer || !hasMore || isLoading || !isPopoverOpen) return;\n\n const handleScroll = () => {\n const { scrollTop, scrollHeight, clientHeight } = scrollContainer;\n const isNearBottom = scrollTop + clientHeight >= scrollHeight - 100;\n\n if (isNearBottom && hasMore && !isLoading) {\n loadMore();\n }\n };\n\n // Add scroll listener directly to the container\n scrollContainer.addEventListener(\"scroll\", handleScroll, { passive: true });\n\n return () => {\n scrollContainer.removeEventListener(\"scroll\", handleScroll);\n };\n }, [hasMore, isLoading, loadMore, isPopoverOpen]);\n\n const handleSearchChange = useCallback((newSearchString: string) => {\n setSearchString(newSearchString);\n search(newSearchString);\n }, [search]);\n\n const emitValueChange = useCallback((selected: RelationItem[]) => {\n if (multiple) onValueChange?.(selected.length ? selected.map(i => i.relation) : undefined);\n else onValueChange?.(selected[0]?.relation);\n }, [onValueChange, multiple]);\n\n // The picker can hand its selection over long after the render that\n // built the callback — a row created in the side panel arrives whenever\n // the person saves it — so the emitter is read from a ref rather than\n // captured.\n const emitValueChangeRef = useRef(emitValueChange);\n emitValueChangeRef.current = emitValueChange;\n\n // Helper: compute the \"IDs fingerprint\" for a set of RelationItems\n // so we can mark it in localSelectionIdsRef and skip re-resolution.\n const computeSelectionFingerprint = useCallback((items: RelationItem[]): string => {\n return items.map(i => String(i.id)).sort().join(\",\");\n }, []);\n\n const onItemClick = useCallback((item: RelationItem) => {\n let newSelected: RelationItem[];\n if (multiple) {\n const isSelected = selectedItems.some(v => String(v.id) === String(item.id));\n newSelected = isSelected\n ? selectedItems.filter(v => String(v.id) !== String(item.id))\n : [...selectedItems, item];\n } else {\n newSelected = [item];\n setPopoverOpen(false);\n }\n setSelectedItems(newSelected);\n // Mark this fingerprint so the resolution effect skips async work\n // when the parent echoes the same IDs back via props.\n localSelectionIdsRef.current = computeSelectionFingerprint(newSelected);\n emitValueChange(newSelected);\n }, [multiple, selectedItems, emitValueChange, computeSelectionFingerprint, setPopoverOpen]);\n\n const handleClear = useCallback(() => {\n setSelectedItems([]);\n localSelectionIdsRef.current = \"\";\n onValueChange?.(undefined);\n }, [onValueChange]);\n\n const handleRemoveItem = useCallback((itemToRemove: RelationItem) => {\n const newSelected = selectedItems.filter(v => String(v.id) !== String(itemToRemove.id));\n setSelectedItems(newSelected);\n localSelectionIdsRef.current = computeSelectionFingerprint(newSelected);\n emitValueChange(newSelected);\n }, [selectedItems, emitValueChange, computeSelectionFingerprint]);\n\n const handleRootOpenChange = useCallback((next: boolean) => {\n if (disabled) return;\n // We control open manually; only allow opening attempts from Radix (e.g. trigger press)\n if (next) setPopoverOpen(true);\n // Ignore close attempts here; outside click/Escape handled manually; single select closes explicitly on selection.\n }, [disabled, setPopoverOpen]);\n\n // Outside click + Escape handling (simple and reliable)\n useEffect(() => {\n if (!isPopoverOpen) return;\n\n function handlePointerDown(ev: MouseEvent) {\n const target = ev.target as Node;\n const triggerEl = localTriggerRef.current;\n const contentEl = contentRef.current;\n if (triggerEl?.contains(target)) return;\n if (contentEl?.contains(target)) return;\n // Outside\n setPopoverOpen(false);\n }\n\n // A layer of its own, so capture phase — and it claims the Escape\n // it acts on, so the record view underneath leaves the record open.\n function handleKey(ev: KeyboardEvent) {\n if (ev.key !== \"Escape\") return;\n ev.preventDefault();\n setPopoverOpen(false);\n }\n\n document.addEventListener(\"mousedown\", handlePointerDown, true);\n document.addEventListener(\"keydown\", handleKey, true);\n return () => {\n document.removeEventListener(\"mousedown\", handlePointerDown, true);\n document.removeEventListener(\"keydown\", handleKey, true);\n };\n }, [isPopoverOpen, setPopoverOpen]);\n\n const closePopover = useCallback(() => setPopoverOpen(false), [setPopoverOpen]);\n\n const toggleOpen = useCallback(() => {\n if (disabled) return;\n setPopoverOpen(!isPopoverOpenRef.current);\n }, [disabled, setPopoverOpen]);\n\n // Pointing at a row that does not exist yet.\n //\n // Until now the only way out of that was to abandon the form, go to the\n // other collection, create the row, come back and start again — and on\n // a new record that meant losing everything typed so far. The side\n // panel already stacks (the selection dialog creates from inside itself\n // this way), so the picker can open a create form over the form it\n // belongs to and select what comes back.\n const canCreateTarget = allowCreate && canCreate(collection, dataPath);\n\n // A search that matched nothing is the name the person was looking for,\n // so it seeds the new row. Only when the title lands on a plain string\n // property: putting free text into an enum, a relation or a computed\n // property would be worse than not prefilling at all.\n const buildDefaultValues = useCallback((searchText: string): Record<string, unknown> | undefined => {\n const trimmed = searchText.trim();\n if (!trimmed) return undefined;\n const titleKey = getTitlePropertyKey(collection);\n if (!titleKey || titleKey.includes(\".\")) return undefined;\n const titleProperty = collection.properties?.[titleKey];\n // A property builder is a function, and it decides its own value.\n if (!titleProperty || typeof titleProperty === \"function\") return undefined;\n if (titleProperty.type !== \"string\" || titleProperty.enum) return undefined;\n return { [titleKey]: trimmed };\n }, [collection]);\n\n const handleCreateNew = useCallback(() => {\n const defaultValues = buildDefaultValues(searchString);\n closePopover();\n sidePanelController.open({\n path: dataPath,\n collection,\n // No URL. This panel is a detour inside the form you are\n // filling in, not somewhere you navigated to, and its address\n // would restore nothing anyway — a record that does not exist\n // yet has none.\n //\n // Pushing one made closing it a *pathname* change, which is\n // exactly what the unsaved-changes blocker watches\n // (`useUnsavedChangesDialog`). So saving the new row raced the\n // panel clearing its own dirty flag, and often enough lost:\n // \"There are unsaved changes\" over a record that had just been\n // saved, with the URL stranded on the target collection. Worst\n // of all in the case this feature exists for — the outer form\n // has content in it, which is the whole reason not to leave.\n updateUrl: false,\n // Saving is the whole point of the detour; the panel goes away\n // and the picker is left holding the row it made.\n closeOnSave: true,\n defaultValues,\n onUpdate: ({ entity }) => {\n if (!entity) return;\n const item = entityToRelationItemRef.current(entity, new EntityRelation(entity.id, dataPath));\n const current = selectedItemsRef.current;\n const newSelected = multiple\n ? [...current.filter(i => String(i.id) !== String(item.id)), item]\n : [item];\n setSelectedItems(newSelected);\n // Same bookkeeping `onItemClick` does: mark the fingerprint\n // so the resolution effect does not re-fetch the row we\n // already hold when the form echoes the value back.\n localSelectionIdsRef.current = newSelected.map(i => String(i.id)).sort().join(\",\");\n emitValueChangeRef.current(newSelected);\n }\n });\n }, [buildDefaultValues, searchString, closePopover, sidePanelController, dataPath, collection, multiple]);\n\n // Text, not `EmptyValue`. That component draws a small grey rounded bar\n // with no text in it, which is the same shape the `Skeleton` component\n // uses while data is in flight — so a relation you simply had not filled\n // in was indistinguishable from one that was still loading, and an empty\n // Author or Tags field read as permanently stuck. It also left the trigger\n // button with no accessible name, since the bar contains no text at all.\n //\n // This says \"not filled in\" rather than \"nothing to choose from\": which of\n // those it is cannot be known here. The list is deliberately not fetched\n // until the picker is first opened (`enabled: listRequested`, guarded by\n // relation_cell_picker_gating.test.tsx, because a table renders one of\n // these per row), so before that `availableItems` is empty because nobody\n // asked, not because the target collection is. The genuine \"nothing to\n // pick yet\" state is reported inside the popover below, where the fetch\n // has actually happened.\n const resolvedPlaceholder = placeholder || emptyPlaceholder || emptyText;\n\n // Whatever dialog, side dialog or sheet we are inside offers as its\n // portal host, falling back to `document.body`. This is not cosmetic:\n // those are modal, and a modal locks scrolling everywhere outside its\n // own content — a list portaled to the body opens and then refuses to\n // scroll, because every wheel event over it is cancelled.\n const portalContainer = (contextPortalContainer ?? (typeof document !== \"undefined\" ? document.body : undefined)) ?? undefined;\n\n return (\n <>\n <PopoverPrimitive.Root open={isPopoverOpen} onOpenChange={handleRootOpenChange} modal={false}>\n <PickerTrigger anchorRef={anchorRef}>\n {triggerContent !== undefined\n // Bare: the caller frames it. No box, no padding,\n // no height of its own — the node it passed,\n // exactly where it would be anyway. A `div`, not a\n // `button`: what it wraps can hold buttons of its\n // own (a record card's open button, at tall rows).\n ? <div\n ref={handleButtonRef}\n role=\"button\"\n tabIndex={disabled ? -1 : 0}\n aria-disabled={disabled || undefined}\n aria-haspopup=\"listbox\"\n aria-expanded={isPopoverOpen}\n data-relation-selector-trigger\n onClick={toggleOpen}\n // A record's title in the value opens that\n // record, and the list has no business staying\n // open over it.\n onClickCapture={(event) => {\n const target = event.target;\n if (!(target instanceof Element) || !isPopoverOpenRef.current) return;\n const interactive = target.closest(\"a, button, [role=\\\"button\\\"]\");\n if (interactive && interactive !== event.currentTarget) setPopoverOpen(false);\n }}\n onKeyDown={(event) => {\n if (event.key !== \"Enter\" && event.key !== \" \") return;\n event.preventDefault();\n toggleOpen();\n }}\n className={cls(\"w-full select-none text-left text-sm relative flex items-center outline-none\", className)}>\n {triggerContent}\n </div>\n : <button\n ref={handleButtonRef}\n type=\"button\"\n aria-haspopup=\"listbox\"\n aria-expanded={isPopoverOpen}\n data-relation-selector-trigger\n disabled={disabled}\n onClick={toggleOpen}\n className={cls(\n {\n \"min-h-[42px] py-1 px-2\": size === \"small\",\n \"min-h-[56px] py-2 px-4\": size === \"medium\",\n \"min-h-[48px] py-1 px-4\": size === \"large\"\n },\n // `rounded-lg` like every other field box —\n // `rounded-md` made this the one control in a\n // row with a different corner.\n \"w-full select-none rounded-lg text-sm relative flex items-center\",\n invisible ? fieldBackgroundInvisibleMixin : fieldBackgroundMixin,\n disabled ? fieldBackgroundDisabledMixin : fieldBackgroundHoverMixin,\n className\n )}\n >\n <div className=\"flex justify-between items-center w-full\">\n {isLoadingSelectedItems ? (\n <div className=\"flex items-center gap-2\">\n <CircularProgress size=\"smallest\"/>\n <span className=\"text-sm text-text-secondary dark:text-text-secondary-dark\">{loadingText}</span>\n </div>\n ) : selectedItems.length > 0 ? (\n <div\n className=\"flex flex-wrap items-center gap-1.5 text-start flex-1 min-w-0 mr-2\">\n {selectedItems.map((item) => {\n if (!useChips || !multiple) {\n return (\n <div key={String(item.id)}\n className=\"flex flex-row items-center gap-1 truncate\">\n {item.data ? (\n <EntityPreviewBindingData size={\"medium\"}\n entity={item.data}\n includeEntityLink={false}\n includeId={false}\n onSidePanelClick={closePopover}\n />\n ) : (\n <span className=\"text-sm truncate\">{item.label}</span>\n )}\n </div>\n );\n }\n return (\n <Chip\n size={\"small\"}\n key={String(item.id)}\n className={cls(\"flex flex-row items-center gap-1 truncate\")}\n >\n {item.data ? (\n <EntityPreviewBindingData size={\"smallest\"} entity={item.data}\n includeEntityLink={false}\n includeId={false}/>\n ) : (\n <span className=\"text-sm truncate\">{item.label}</span>\n )}\n <XIcon\n size={iconSize.smallest}\n onClick={(event) => {\n event.stopPropagation();\n handleRemoveItem(item);\n }}\n />\n </Chip>\n );\n })}\n </div>\n ) :\n (\n <span className=\"text-sm text-text-secondary dark:text-text-secondary-dark\">\n {resolvedPlaceholder}\n </span>\n )}\n\n <div className=\"flex items-center flex-shrink-0\">\n {!multiple && selectedItems.length === 1 && selectedItems[0]?.data && (\n <Tooltip title={`Open ${selectedItems[0].label}`}>\n <IconButton aria-label={`Open ${selectedItems[0].label}`}\n component={\"div\"}\n size={\"small\"}\n className=\"opacity-60 hover:opacity-100\"\n onClick={(e) => {\n e.stopPropagation();\n e.preventDefault();\n const entity = selectedItems[0].data!;\n setPopoverOpen(false);\n sidePanelController.open({\n entityId: entity.id,\n path: entity.path,\n collection,\n updateUrl: true\n });\n }}>\n <ArrowRightToLineIcon size={iconSize.small}/>\n </IconButton>\n </Tooltip>\n )}\n <ChevronDownIcon\n size={size === \"small\" ? iconSize.small : iconSize.medium}\n className={cls(\"transition\", isPopoverOpen ? \"rotate-180\" : \"\")}\n />\n </div>\n </div>\n\n </button>}\n </PickerTrigger>\n <PopoverPrimitive.Portal container={portalContainer}>\n <PopoverPrimitive.Content\n ref={contentRef}\n data-relation-selector-content\n className={cls(\"z-50 overflow-hidden border bg-surface-card rounded-lg min-w-72\", defaultBorderMixin)}\n align=\"start\"\n sideOffset={8}\n side=\"bottom\"\n avoidCollisions={true}\n collisionPadding={16}\n // Allow default auto focus (we manually refocus anyway)\n onOpenAutoFocus={(_e) => { /* leave default or custom manual focus */\n }}\n onCloseAutoFocus={(e) => {\n e.preventDefault();\n }}\n style={{ width: \"var(--radix-popover-trigger-width)\" }}\n >\n <CommandPrimitive shouldFilter={false}>\n <div className=\"flex flex-row items-center\">\n <div className=\"relative flex-1\">\n <SearchIcon\n className=\"absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary dark:text-text-secondary-dark\"\n size={iconSize.smallest}/>\n <CommandPrimitive.Input\n ref={searchInputRef}\n className={cls(\n focusedDisabled,\n \"bg-transparent outline-hidden flex-1 h-full w-full pl-10 pr-4 py-3 text-text-primary dark:text-text-primary-dark placeholder:text-text-secondary dark:placeholder:text-text-secondary-dark\"\n )}\n placeholder={searchPlaceholder}\n value={searchString}\n onValueChange={handleSearchChange}\n />\n </div>\n {isLoading && (\n <div className=\"flex items-center justify-center px-3\">\n <CircularProgress size=\"smallest\"/>\n </div>\n )}\n {selectedItems.length > 0 && (\n <div\n onClick={handleClear}\n className=\"text-sm justify-center cursor-pointer py-3 px-4 text-text-secondary dark:text-text-secondary-dark hover:text-text-primary dark:hover:text-text-primary-dark\"\n >\n Clear\n </div>\n )}\n </div>\n <Separator orientation=\"horizontal\" className=\"my-0\"/>\n <CommandPrimitive.List\n ref={scrollContainerRef}\n style={{\n maxHeight: \"40vh\",\n overflowY: \"auto\"\n }}\n >\n {isLoading && availableItems.length === 0 && (\n <div className=\"flex items-center justify-center py-6\">\n <CircularProgress size=\"small\"/>\n <span\n className=\"ml-2 text-sm text-text-secondary dark:text-text-secondary-dark\">{loadingText}</span>\n </div>\n )}\n {/* Two different nothings, which used to share one\n message (\"No relations found.\") even though the\n fix for each is the opposite: clear the search, or\n go and create the first row. With the fetch done,\n the search string is what tells them apart. */}\n {!isLoading && availableItems.length === 0 && (\n <CommandPrimitive.Empty\n className=\"px-4 py-6 text-center text-text-secondary dark:text-text-secondary-dark\">\n {searchString\n ? noResultsText\n : (emptyCollectionText ?? `No ${collection.name ?? \"entries\"} yet.`)}\n </CommandPrimitive.Empty>\n )}\n <CommandPrimitive.Group>\n {(() => {\n // Sort items so that initially-selected (pinned) items appear first.\n // We use the entity taken when the popover opened so items don't\n // jump around as the user checks/unchecks.\n const pinned = pinnedIdsRef.current;\n const sortedItems = pinned && pinned.size > 0\n ? [...availableItems].sort((a, b) => {\n const aP = pinned.has(String(a.id)) ? 0 : 1;\n const bP = pinned.has(String(b.id)) ? 0 : 1;\n return aP - bP;\n })\n : availableItems;\n return sortedItems;\n })().map((item) => {\n const isSelected = selectedItems.some(v => String(v.id) === String(item.id));\n return (\n <CommandPrimitive.Item\n key={String(item.id)}\n value={String(item.id)}\n onMouseDown={(e) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n onSelect={() => onItemClick(item)}\n className={cls(\n \"flex flex-row items-center gap-1.5 m-1 p-1 rounded-xs cursor-pointer ring-offset-transparent\",\n isSelected && \"bg-surface-active\",\n \"aria-selected:outline-hidden aria-selected:bg-surface-active\"\n )}\n >\n {multiple && (<InnerCheckBox checked={isSelected}/>)}\n {item.data ? (\n <div\n className=\"flex flex-row items-center gap-2 min-w-0 w-full\">\n <EntityPreviewBindingData\n size={multiple ? \"smallest\" : \"medium\"}\n entity={item.data}\n includeId={false}\n includeEntityLink={true}\n />\n </div>\n ) : (\n <div>\n <div\n className=\"text-sm font-medium text-text-primary dark:text-text-primary-dark\">{item.label}</div>\n {item.description && (\n <div\n className=\"text-xs text-text-secondary dark:text-text-secondary-dark\">{item.description}</div>\n )}\n </div>\n )}\n </CommandPrimitive.Item>\n );\n })}\n {availableItems.length > 0 && hasMore && (\n <div ref={sentinelCallbackRef} className=\"h-1 w-full\"\n style={{ visibility: \"hidden\" }}/>\n )}\n {isLoading && availableItems.length > 0 && (\n <div className=\"flex items-center justify-center py-4\">\n <CircularProgress size=\"smallest\"/>\n <span\n className=\"ml-2 text-xs text-text-secondary dark:text-text-secondary-dark\">Loading...</span>\n </div>\n )}\n </CommandPrimitive.Group>\n </CommandPrimitive.List>\n {canCreateTarget && <>\n <Separator orientation=\"horizontal\" className=\"my-0\"/>\n {/* Outside the scrolling list on purpose: it\n is most wanted exactly when the list is\n long and nothing in it matched. */}\n <button\n type=\"button\"\n data-relation-selector-create\n onMouseDown={(e) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n onClick={handleCreateNew}\n className={cls(\n \"w-full flex flex-row items-center gap-2 px-4 py-3 text-sm text-left\",\n \"text-primary hover:bg-surface-hover\"\n )}>\n <PlusIcon size={iconSize.smallest}/>\n <span className=\"truncate\">\n {searchString.trim()\n ? t(\"add_named\", { name: searchString.trim() })\n : t(\"add_specific\", { name: collection.singularName ?? collection.name })}\n </span>\n </button>\n </>}\n </CommandPrimitive>\n </PopoverPrimitive.Content>\n </PopoverPrimitive.Portal>\n </PopoverPrimitive.Root>\n </>\n );\n }\n);\n\nRelationSelector.displayName = \"RelationSelector\";\n\nfunction InnerCheckBox({ checked }: { checked: boolean }) {\n return (\n <div className={cls(\n \"p-2 w-8 h-8 inline-flex items-center justify-center text-sm font-medium focus:outline-hidden transition-colors ease-in-out duration-150\"\n )}>\n <div\n className={cls(\n \"border-2 relative transition-colors ease-in-out duration-150 w-4 h-4 rounded-xs flex items-center justify-center\",\n checked ? \"bg-primary text-surface-accent-100 dark:text-surface-accent-900 border-transparent\" : \"bg-surface-card border-surface-accent-800 dark:border-surface-accent-500\"\n )}\n >\n {checked && <CheckIcon size={iconSize.smallest} className=\"absolute\"/>}\n </div>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAoCA,SAAS,oBAAoB,UAA2F;CACpH,IAAI,CAAC,UAAU,OAAO,KAAA;CACtB,IAAI,SAAS,SAAS,OAAO,OAAO,SAAS;CAC7C,IAAI,SAAS,SAAS,aAAa,SAAS,SAAS,cAAc,OAAO;CAC1E,IAAI,SAAS,SAAS,eAAe,SAAS,SAAS,UAAU,OAAO;CACxE,OAAO,SAAS;AACpB;AAiGA,IAAa,mBAAmB,QAAM,YAK9B,EACI,OACA,OAAO,UACP,eACA,WACA,UACA,aACA,WAAW,MACX,WACA,UACA,UAAU,kBACV,aACA,UACA,kBACA,oBAAoB,aACpB,gBAAgB,eAChB,YAAY,WACZ,qBACA,cAAc,cACd,cAAc,MACd,MAAM,UACN,cACA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;WACI,WAAU;qBAAiE;UAAgB,CAAA,CAC9F;;QAEW,EAAA,CAAA;OACL;;MACtB,mBAAmB,qBAAA,UAAA,EAAA,UAAA,CAChB,oBAAC,WAAD;OAAW,aAAY;OAAa,WAAU;MAAO,CAAA,GAIrD,qBAAC,UAAD;OACI,MAAK;OACL,iCAAA;OACA,cAAc,MAAM;QAChB,EAAE,eAAe;QACjB,EAAE,gBAAgB;OACtB;OACA,SAAS;OACT,WAAW,IACP,uEACA,qCACJ;iBAXJ,CAYI,oBAAC,UAAD,EAAU,MAAM,SAAS,SAAU,CAAA,GACnC,oBAAC,QAAD;QAAM,WAAU;kBACX,aAAa,KAAK,IACb,EAAE,aAAa,EAAE,MAAM,aAAa,KAAK,EAAE,CAAC,IAC5C,EAAE,gBAAgB,EAAE,MAAM,WAAW,gBAAgB,WAAW,KAAK,CAAC;OAC1E,CAAA,CACF;QACV,EAAA,CAAA;KACY;;GACI,CAAA;EACL,CAAA,CACN;IACzB,CAAA;AAEV,CACJ;AAEA,iBAAiB,cAAc;AAE/B,SAAS,cAAc,EAAE,WAAiC;CACtD,OACI,oBAAC,OAAD;EAAK,WAAW,IACZ,yIACJ;YACI,oBAAC,OAAD;GACI,WAAW,IACP,oHACA,UAAU,uFAAuF,0EACrG;aAEC,WAAW,oBAAC,WAAD;IAAW,MAAM,SAAS;IAAU,WAAU;GAAW,CAAA;EACpE,CAAA;CACJ,CAAA;AAEb"}
1
+ {"version":3,"file":"RelationSelector.js","names":[],"sources":["../../src/components/RelationSelector.tsx"],"sourcesContent":["\nimport {\n ArrowRightToLineIcon,\n CheckIcon,\n ChevronDownIcon,\n Chip,\n CircularProgress,\n cls,\n defaultBorderMixin,\n fieldBackgroundDisabledMixin,\n fieldBackgroundHoverMixin,\n fieldBackgroundInvisibleMixin,\n fieldBackgroundMixin,\n focusedDisabled,\n IconButton,\n iconSize,\n PlusIcon,\n PopoverPrimitive,\n SearchIcon,\n Separator,\n Tooltip,\n usePortalContainer,\n XIcon\n} from \"@rebasepro/ui\";\nimport * as React from \"react\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { Command as CommandPrimitive } from \"cmdk\";\nimport { Entity, EntityRelation, FilterValues, Relation, getCollectionDataPath } from \"@rebasepro/types\";\nimport { EntityPreviewBindingData } from \"./EntityPreviewBinding\";\nimport { PickerTrigger } from \"./PickerTrigger\";\nimport { getTitlePropertyKey, useData, usePermissions, useRelationSelector, useTranslation } from \"@rebasepro/app\";\nimport { useSidePanel } from \"../hooks/useSidePanel\";\nimport { normalizeToEntityRelation } from \"@rebasepro/common\";\nimport { findEntitiesByIds } from \"../util/find_entities_by_ids\";\n\n/** Whether an authored relation yields many rows. Derived from its kind. */\nfunction relationCardinality(relation: { kind?: string; cardinality?: string } | undefined): \"one\" | \"many\" | undefined {\n if (!relation) return undefined;\n if (relation.kind === \"via\") return relation.cardinality as \"one\" | \"many\" | undefined;\n if (relation.kind === \"hasMany\" || relation.kind === \"manyToMany\") return \"many\";\n if (relation.kind === \"belongsTo\" || relation.kind === \"hasOne\") return \"one\";\n return relation.cardinality as \"one\" | \"many\" | undefined;\n}\n\n\nexport interface RelationItem {\n id: string | number;\n label: string;\n description?: string;\n data?: Entity;\n relation: EntityRelation;\n}\n\nexport interface RelationSelectorProps {\n className?: string;\n name?: string;\n id?: string;\n value?: EntityRelation | EntityRelation[] | null;\n /** Callback returning selected EntityRelation(s) */\n\n onValueChange?: (updatedValue: EntityRelation | EntityRelation[] | undefined) => void;\n placeholder?: React.ReactNode;\n /**\n * `large` is the form's size and is on the shared 28/32/40/48 control\n * scale, so a relation picker lines up with the text field beside it.\n *\n * `small` and `medium` predate that scale (42 and 56) and are kept as they\n * are because the filter row is built around them. A table cell passes\n * `triggerContent` instead, and has no size of its own.\n */\n size?: \"small\" | \"medium\" | \"large\";\n useChips?: boolean;\n disabled?: boolean;\n invisible?: boolean;\n\n relation: Relation;\n /**\n * Whether the selector picks many rows or one.\n *\n * Defaults to what the relation implies — a `hasMany` or `manyToMany`\n * picks many — which is right wherever the selector *edits* the relation,\n * because there the cardinality is the shape of the stored value.\n *\n * A filter is the case where it is not. `tags == <one tag>` asks a single\n * question about a to-many link, and the operator is what decides how many\n * values it takes. Deriving multiplicity from the relation there meant a\n * to-many relation could only ever emit a list, so the filter field had to\n * hide every single-value operator to avoid handing `==` an array.\n */\n multiple?: boolean;\n fixedFilter?: FilterValues<string>;\n pageSize?: number;\n emptyPlaceholder?: string;\n searchPlaceholder?: string;\n /** Shown in the open list when a search matched nothing. */\n noResultsText?: string;\n /**\n * Shown on the closed trigger when nothing is selected. Says only that the\n * field is empty — see the note by `resolvedPlaceholder` for why it cannot\n * say whether there is anything to pick.\n */\n emptyText?: string;\n /**\n * Shown in the open list when the target collection turned out to hold no\n * rows at all, as opposed to a search simply not matching. Defaults to a\n * sentence naming the target collection.\n */\n emptyCollectionText?: string;\n loadingText?: string;\n /**\n * Whether the list is open, for a caller that opens it from outside the\n * trigger — a table cell's opener. Every open and close the selector\n * makes itself is reported through `onOpenChange`, controlled or not.\n */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /**\n * Replaces everything the trigger draws — the value, the box, its padding\n * and the chevron — with this node. For a caller that frames the picker\n * itself: a table cell passes the preview it shows at rest, so the cell\n * looks the same whether the picker is mounted, closed or open.\n */\n triggerContent?: React.ReactNode;\n /**\n * Positions the list against this element instead of the trigger. A\n * table cell passes itself: the trigger inside it can be taller than the\n * cell that clips it, and the list belongs under what can be seen.\n */\n anchorRef?: React.RefObject<HTMLElement | null>;\n /**\n * Whether the open list offers to create a row in the target collection.\n * Defaults to `true`. The offer is shown only when the user could actually\n * insert into that collection — the same permission check the selection\n * dialog's \"Add\" button makes — so turning this off is for the cases where\n * creating is possible but not wanted, like a filter.\n */\n allowCreate?: boolean;\n}\n\nexport const RelationSelector = React.forwardRef<\n HTMLElement,\n RelationSelectorProps\n>(\n (\n {\n value,\n size = \"medium\",\n onValueChange,\n invisible,\n disabled,\n placeholder,\n useChips = true,\n className,\n relation,\n multiple: multipleOverride,\n fixedFilter,\n pageSize,\n emptyPlaceholder,\n searchPlaceholder = \"Search...\",\n noResultsText = \"No matches.\",\n emptyText = \"Select…\",\n emptyCollectionText,\n loadingText = \"Loading...\",\n allowCreate = true,\n open: openProp,\n onOpenChange,\n triggerContent,\n anchorRef\n },\n ref\n ) => {\n\n const collection = relation.target();\n const dataPath = getCollectionDataPath(collection);\n const dataClient = useData();\n const sidePanelController = useSidePanel();\n const { canCreate } = usePermissions();\n const { t } = useTranslation();\n const contextPortalContainer = usePortalContainer();\n const multiple = multipleOverride ?? relationCardinality(relation) === \"many\";\n\n const [isPopoverOpen, setIsPopoverOpenState] = useState(false);\n const isPopoverOpenRef = useRef(false);\n // The list is only worth fetching once the picker has been opened. A\n // table cell mounts one of these per row, and the selected value is\n // resolved by its own effect below, not from the list. Latches on the\n // first open so a closed popover keeps its results.\n const [listRequested, setListRequested] = useState(false);\n const [selectedItems, setSelectedItems] = useState<RelationItem[]>([]);\n const [isLoadingSelectedItems, setIsLoadingSelectedItems] = useState(false);\n const [searchString, setSearchString] = useState<string>(\"\");\n\n // Track IDs that were set via local user interaction (onItemClick / handleClear / handleRemoveItem).\n // When an incoming value change matches these IDs exactly, we skip async re-resolution.\n const localSelectionIdsRef = useRef<string | null>(null);\n // Entity of selected IDs captured when the popover opens.\n // Used to sort the dropdown list so selected items appear at the top.\n // Stays stable for the entire popover session so items don't jump around.\n const pinnedIdsRef = useRef<Set<string> | null>(null);\n\n const selectedItemsForPinRef = useRef<RelationItem[]>([]);\n selectedItemsForPinRef.current = selectedItems;\n const onOpenChangeRef = useRef(onOpenChange);\n onOpenChangeRef.current = onOpenChange;\n\n // Every open and close goes through here. Opening pins the current\n // selection to the top of the list for as long as it stays open, and\n // is what first requests the list at all.\n const setPopoverOpen = useCallback((next: boolean, notify = true) => {\n if (next) {\n // From the value as well as the resolved items: a picker a\n // table cell mounts already open has not resolved them yet.\n pinnedIdsRef.current = new Set([\n ...selectedItemsForPinRef.current.map(i => String(i.id)),\n ...relationsArrayRef.current.map(rel =>\n String(typeof rel === \"string\" || typeof rel === \"number\" ? rel : rel.id))\n ]);\n setListRequested(true);\n } else {\n pinnedIdsRef.current = null;\n }\n const changed = isPopoverOpenRef.current !== next;\n isPopoverOpenRef.current = next;\n setIsPopoverOpenState(next);\n if (changed && notify) onOpenChangeRef.current?.(next);\n }, []);\n\n useEffect(() => {\n if (openProp === undefined || openProp === isPopoverOpenRef.current) return;\n if (openProp && disabled) {\n onOpenChangeRef.current?.(false);\n return;\n }\n setPopoverOpen(openProp, false);\n }, [openProp, disabled, setPopoverOpen]);\n\n const {\n items: availableItems,\n isLoading,\n hasMore,\n search,\n loadMore,\n entityToRelationItem\n } = useRelationSelector({\n path: dataPath,\n collection,\n fixedFilter,\n pageSize,\n enabled: listRequested\n });\n\n const scrollContainerRef = useRef<HTMLDivElement>(null);\n const sentinelRef = useRef<HTMLDivElement>(null);\n const observerRef = useRef<IntersectionObserver | null>(null);\n const localTriggerRef = useRef<HTMLElement | null>(null);\n\n const handleButtonRef = useCallback((node: HTMLElement | null) => {\n localTriggerRef.current = node;\n if (typeof ref === \"function\") {\n ref(node);\n } else if (ref) {\n ref.current = node;\n }\n }, [ref]);\n const contentRef = useRef<HTMLDivElement | null>(null);\n const searchInputRef = useRef<HTMLInputElement | null>(null);\n\n // Keep stable refs for dependencies used in the value-resolution effect\n // so the effect only re-fires when the actual `value` identity changes.\n const dataClientRef = useRef(dataClient);\n dataClientRef.current = dataClient;\n const entityToRelationItemRef = useRef(entityToRelationItem);\n entityToRelationItemRef.current = entityToRelationItem;\n const collectionSlugRef = useRef(collection.slug);\n collectionSlugRef.current = collection.slug;\n const collectionRef = useRef(collection);\n collectionRef.current = collection;\n\n // Stable ref to track which IDs we've already resolved\n const resolvedIdsRef = useRef<string>(\"\");\n // Track whether we have resolved items (used for skip guard without adding to deps)\n const hasResolvedItemsRef = useRef(false);\n\n const selectedItemsRef = useRef(selectedItems);\n selectedItemsRef.current = selectedItems;\n\n // Normalize incoming values — plain { __type: \"relation\" } objects\n // from the server are converted to proper EntityRelation instances.\n const rawArray = !value ? [] : Array.isArray(value) ? value : [value];\n const relationsArray = rawArray.map(rel => {\n if (typeof rel === \"string\" || typeof rel === \"number\") return rel;\n return normalizeToEntityRelation(rel) ?? rel;\n });\n\n // Build a fingerprint of the incoming value's IDs\n const incomingIds = relationsArray\n .map(rel => {\n const isPrimitive = typeof rel === \"string\" || typeof rel === \"number\";\n return String(isPrimitive ? rel : (rel as EntityRelation).id);\n })\n .sort()\n .join(\",\");\n\n // CheckIcon if every relation already has embedded data\n const allHaveData = relationsArray.length > 0 && relationsArray.every(rel => {\n if (typeof rel === \"string\" || typeof rel === \"number\") return false;\n return !!(rel as EntityRelation)?.data;\n });\n\n const relationsArrayRef = useRef(relationsArray);\n relationsArrayRef.current = relationsArray;\n\n useEffect(() => {\n let active = true;\n const currentRelationsArray = relationsArrayRef.current;\n\n // If the IDs haven't changed and we already resolved them, skip entirely\n if (incomingIds === resolvedIdsRef.current && (allHaveData || hasResolvedItemsRef.current)) {\n return;\n }\n\n // FAST PATH: If the incoming IDs match what we just set locally via user interaction,\n // our selectedItems already have the correct data — no re-resolution needed.\n //\n // The fingerprint answers for one echo only, and is dropped on the\n // first incoming value whether it matches or not. Kept, it also\n // matched a *later* return to the same ids — pick A, discard to B,\n // undo back to A — and the chip went on showing B.\n const localSelectionIds = localSelectionIdsRef.current;\n localSelectionIdsRef.current = null;\n if (localSelectionIds !== null && incomingIds === localSelectionIds) {\n resolvedIdsRef.current = incomingIds;\n hasResolvedItemsRef.current = true;\n // Do NOT call setSelectedItems or setIsLoadingSelectedItems — they are already correct.\n return;\n }\n\n const currentSelected = selectedItemsRef.current;\n const currentSelectedMap = new Map(currentSelected.map(item => [String(item.id), item]));\n\n let allCovered = true;\n const newResolvedItems: RelationItem[] = [];\n const toRelationItem = entityToRelationItemRef.current;\n const slug = collectionSlugRef.current;\n\n for (const rel of currentRelationsArray) {\n const isPrimitive = typeof rel === \"string\" || typeof rel === \"number\";\n const relId = String(isPrimitive ? rel : (rel as EntityRelation).id);\n const hasEmbeddedData = !isPrimitive && !!(rel as EntityRelation).data;\n\n if (hasEmbeddedData) {\n const r = rel as EntityRelation;\n // admin wire format embeds relation data as { id, path, values }\n newResolvedItems.push(toRelationItem(r.data as unknown as Entity, r));\n } else if (currentSelectedMap.has(relId)) {\n // We already have it in currentSelected\n const existingItem = currentSelectedMap.get(relId)!;\n newResolvedItems.push(existingItem);\n } else {\n allCovered = false;\n break;\n }\n }\n\n // FAST PATH: We have all necessary data embedded or in local cache\n if (allCovered) {\n setSelectedItems(newResolvedItems);\n hasResolvedItemsRef.current = true;\n resolvedIdsRef.current = incomingIds;\n setIsLoadingSelectedItems(false);\n return;\n }\n\n // SLOW PATH: fetch missing data — but don't show loading if popover is open\n // (user is actively interacting; showing a spinner is disruptive)\n if (!isPopoverOpenRef.current) {\n setIsLoadingSelectedItems(true);\n }\n const client = dataClientRef.current;\n const target = collectionRef.current;\n\n // The ids nothing above resolves, by the path they are read at:\n // one request per path (per 1,000 ids), not one per id.\n const unresolved = new Map<string, (string | number)[]>();\n for (const rel of currentRelationsArray) {\n const isPrimitive = typeof rel === \"string\" || typeof rel === \"number\";\n const relId = isPrimitive ? rel : (rel as EntityRelation).id;\n if (!isPrimitive && (rel as EntityRelation).data) continue;\n if (currentSelectedMap.has(String(relId))) continue;\n const path = isPrimitive ? slug : (rel as EntityRelation).path;\n unresolved.set(path, [...(unresolved.get(path) ?? []), relId]);\n }\n\n Promise.all(\n [...unresolved].map(async ([path, ids]): Promise<[string, Map<string, Entity>]> => {\n try {\n return [path, await findEntitiesByIds(client.collection(path), target, ids)];\n } catch (e) {\n console.warn(\"RelationSelector: could not fetch the entities for relations\", path, ids, e);\n return [path, new Map()];\n }\n })\n ).then(read => {\n const readByPath = new Map(read);\n return currentRelationsArray.map((rel) => {\n const isPrimitive = typeof rel === \"string\" || typeof rel === \"number\";\n const relId = isPrimitive ? rel : (rel as EntityRelation).id;\n const path = isPrimitive ? slug : (rel as EntityRelation).path;\n const relation = isPrimitive ? new EntityRelation(relId, path) : rel as EntityRelation;\n\n if (!isPrimitive && (rel as EntityRelation).data) {\n // admin wire format embeds relation data as { id, path, values }\n return toRelationItem((rel as EntityRelation).data as unknown as Entity, relation);\n }\n if (currentSelectedMap.has(String(relId))) {\n return currentSelectedMap.get(String(relId))!;\n }\n const entity = readByPath.get(path)?.get(String(relId));\n if (entity) return toRelationItem(entity, relation);\n return { id: relId,\nlabel: String(relId),\nrelation } as RelationItem;\n });\n }).then(resolved => {\n if (active) {\n setSelectedItems(resolved);\n setIsLoadingSelectedItems(false);\n hasResolvedItemsRef.current = true;\n resolvedIdsRef.current = incomingIds;\n }\n });\n\n return () => {\n active = false;\n };\n }, [incomingIds, allHaveData]);\n\n const sentinelCallbackRef = useCallback((node: HTMLDivElement | null) => {\n if (observerRef.current) {\n observerRef.current.disconnect();\n observerRef.current = null;\n }\n if (sentinelRef.current !== node) {\n (sentinelRef as React.MutableRefObject<HTMLDivElement | null>).current = node;\n }\n if (!node || !hasMore || isLoading || !loadMore) return;\n const observer = new IntersectionObserver(\n (entries) => {\n const entry = entries[0];\n if (entry.isIntersecting && hasMore && !isLoading) loadMore();\n },\n {\n root: scrollContainerRef.current,\n rootMargin: \"20px\",\n threshold: 0\n }\n );\n observer.observe(node);\n observerRef.current = observer;\n }, [hasMore, isLoading, loadMore]);\n\n useEffect(() => () => {\n if (observerRef.current) observerRef.current.disconnect();\n }, []);\n\n // Enhanced scroll event listener specifically for dialog contexts\n useEffect(() => {\n const scrollContainer = scrollContainerRef.current;\n if (!scrollContainer || !hasMore || isLoading || !isPopoverOpen) return;\n\n const handleScroll = () => {\n const { scrollTop, scrollHeight, clientHeight } = scrollContainer;\n const isNearBottom = scrollTop + clientHeight >= scrollHeight - 100;\n\n if (isNearBottom && hasMore && !isLoading) {\n loadMore();\n }\n };\n\n // Add scroll listener directly to the container\n scrollContainer.addEventListener(\"scroll\", handleScroll, { passive: true });\n\n return () => {\n scrollContainer.removeEventListener(\"scroll\", handleScroll);\n };\n }, [hasMore, isLoading, loadMore, isPopoverOpen]);\n\n const handleSearchChange = useCallback((newSearchString: string) => {\n setSearchString(newSearchString);\n search(newSearchString);\n }, [search]);\n\n const emitValueChange = useCallback((selected: RelationItem[]) => {\n if (multiple) onValueChange?.(selected.length ? selected.map(i => i.relation) : undefined);\n else onValueChange?.(selected[0]?.relation);\n }, [onValueChange, multiple]);\n\n // The picker can hand its selection over long after the render that\n // built the callback — a row created in the side panel arrives whenever\n // the person saves it — so the emitter is read from a ref rather than\n // captured.\n const emitValueChangeRef = useRef(emitValueChange);\n emitValueChangeRef.current = emitValueChange;\n\n // Helper: compute the \"IDs fingerprint\" for a set of RelationItems\n // so we can mark it in localSelectionIdsRef and skip re-resolution.\n const computeSelectionFingerprint = useCallback((items: RelationItem[]): string => {\n return items.map(i => String(i.id)).sort().join(\",\");\n }, []);\n\n const onItemClick = useCallback((item: RelationItem) => {\n let newSelected: RelationItem[];\n if (multiple) {\n const isSelected = selectedItems.some(v => String(v.id) === String(item.id));\n newSelected = isSelected\n ? selectedItems.filter(v => String(v.id) !== String(item.id))\n : [...selectedItems, item];\n } else {\n newSelected = [item];\n setPopoverOpen(false);\n }\n setSelectedItems(newSelected);\n // Mark this fingerprint so the resolution effect skips async work\n // when the parent echoes the same IDs back via props.\n localSelectionIdsRef.current = computeSelectionFingerprint(newSelected);\n emitValueChange(newSelected);\n }, [multiple, selectedItems, emitValueChange, computeSelectionFingerprint, setPopoverOpen]);\n\n const handleClear = useCallback(() => {\n setSelectedItems([]);\n localSelectionIdsRef.current = \"\";\n onValueChange?.(undefined);\n }, [onValueChange]);\n\n const handleRemoveItem = useCallback((itemToRemove: RelationItem) => {\n const newSelected = selectedItems.filter(v => String(v.id) !== String(itemToRemove.id));\n setSelectedItems(newSelected);\n localSelectionIdsRef.current = computeSelectionFingerprint(newSelected);\n emitValueChange(newSelected);\n }, [selectedItems, emitValueChange, computeSelectionFingerprint]);\n\n const handleRootOpenChange = useCallback((next: boolean) => {\n if (disabled) return;\n // We control open manually; only allow opening attempts from Radix (e.g. trigger press)\n if (next) setPopoverOpen(true);\n // Ignore close attempts here; outside click/Escape handled manually; single select closes explicitly on selection.\n }, [disabled, setPopoverOpen]);\n\n // Outside click + Escape handling (simple and reliable)\n useEffect(() => {\n if (!isPopoverOpen) return;\n\n function handlePointerDown(ev: MouseEvent) {\n const target = ev.target as Node;\n const triggerEl = localTriggerRef.current;\n const contentEl = contentRef.current;\n if (triggerEl?.contains(target)) return;\n if (contentEl?.contains(target)) return;\n // Outside\n setPopoverOpen(false);\n }\n\n // A layer of its own, so capture phase — and it claims the Escape\n // it acts on, so the record view underneath leaves the record open.\n function handleKey(ev: KeyboardEvent) {\n if (ev.key !== \"Escape\") return;\n ev.preventDefault();\n setPopoverOpen(false);\n }\n\n document.addEventListener(\"mousedown\", handlePointerDown, true);\n document.addEventListener(\"keydown\", handleKey, true);\n return () => {\n document.removeEventListener(\"mousedown\", handlePointerDown, true);\n document.removeEventListener(\"keydown\", handleKey, true);\n };\n }, [isPopoverOpen, setPopoverOpen]);\n\n const closePopover = useCallback(() => setPopoverOpen(false), [setPopoverOpen]);\n\n const toggleOpen = useCallback(() => {\n if (disabled) return;\n setPopoverOpen(!isPopoverOpenRef.current);\n }, [disabled, setPopoverOpen]);\n\n // Pointing at a row that does not exist yet.\n //\n // Until now the only way out of that was to abandon the form, go to the\n // other collection, create the row, come back and start again — and on\n // a new record that meant losing everything typed so far. The side\n // panel already stacks (the selection dialog creates from inside itself\n // this way), so the picker can open a create form over the form it\n // belongs to and select what comes back.\n const canCreateTarget = allowCreate && canCreate(collection, dataPath);\n\n // A search that matched nothing is the name the person was looking for,\n // so it seeds the new row. Only when the title lands on a plain string\n // property: putting free text into an enum, a relation or a computed\n // property would be worse than not prefilling at all.\n const buildDefaultValues = useCallback((searchText: string): Record<string, unknown> | undefined => {\n const trimmed = searchText.trim();\n if (!trimmed) return undefined;\n const titleKey = getTitlePropertyKey(collection);\n if (!titleKey || titleKey.includes(\".\")) return undefined;\n const titleProperty = collection.properties?.[titleKey];\n // A property builder is a function, and it decides its own value.\n if (!titleProperty || typeof titleProperty === \"function\") return undefined;\n if (titleProperty.type !== \"string\" || titleProperty.enum) return undefined;\n return { [titleKey]: trimmed };\n }, [collection]);\n\n const handleCreateNew = useCallback(() => {\n const defaultValues = buildDefaultValues(searchString);\n closePopover();\n sidePanelController.open({\n path: dataPath,\n collection,\n // No URL. This panel is a detour inside the form you are\n // filling in, not somewhere you navigated to, and its address\n // would restore nothing anyway — a record that does not exist\n // yet has none.\n //\n // Pushing one made closing it a *pathname* change, which is\n // exactly what the unsaved-changes blocker watches\n // (`useUnsavedChangesDialog`). So saving the new row raced the\n // panel clearing its own dirty flag, and often enough lost:\n // \"There are unsaved changes\" over a record that had just been\n // saved, with the URL stranded on the target collection. Worst\n // of all in the case this feature exists for — the outer form\n // has content in it, which is the whole reason not to leave.\n updateUrl: false,\n // Saving is the whole point of the detour; the panel goes away\n // and the picker is left holding the row it made.\n closeOnSave: true,\n defaultValues,\n onUpdate: ({ entity }) => {\n if (!entity) return;\n const item = entityToRelationItemRef.current(entity, new EntityRelation(entity.id, dataPath));\n const current = selectedItemsRef.current;\n const newSelected = multiple\n ? [...current.filter(i => String(i.id) !== String(item.id)), item]\n : [item];\n setSelectedItems(newSelected);\n // Same bookkeeping `onItemClick` does: mark the fingerprint\n // so the resolution effect does not re-fetch the row we\n // already hold when the form echoes the value back.\n localSelectionIdsRef.current = newSelected.map(i => String(i.id)).sort().join(\",\");\n emitValueChangeRef.current(newSelected);\n }\n });\n }, [buildDefaultValues, searchString, closePopover, sidePanelController, dataPath, collection, multiple]);\n\n // Text, not `EmptyValue`. That component draws a small grey rounded bar\n // with no text in it, which is the same shape the `Skeleton` component\n // uses while data is in flight — so a relation you simply had not filled\n // in was indistinguishable from one that was still loading, and an empty\n // Author or Tags field read as permanently stuck. It also left the trigger\n // button with no accessible name, since the bar contains no text at all.\n //\n // This says \"not filled in\" rather than \"nothing to choose from\": which of\n // those it is cannot be known here. The list is deliberately not fetched\n // until the picker is first opened (`enabled: listRequested`, guarded by\n // relation_cell_picker_gating.test.tsx, because a table renders one of\n // these per row), so before that `availableItems` is empty because nobody\n // asked, not because the target collection is. The genuine \"nothing to\n // pick yet\" state is reported inside the popover below, where the fetch\n // has actually happened.\n const resolvedPlaceholder = placeholder || emptyPlaceholder || emptyText;\n\n // Whatever dialog, side dialog or sheet we are inside offers as its\n // portal host, falling back to `document.body`. This is not cosmetic:\n // those are modal, and a modal locks scrolling everywhere outside its\n // own content — a list portaled to the body opens and then refuses to\n // scroll, because every wheel event over it is cancelled.\n const portalContainer = (contextPortalContainer ?? (typeof document !== \"undefined\" ? document.body : undefined)) ?? undefined;\n\n return (\n <>\n <PopoverPrimitive.Root open={isPopoverOpen} onOpenChange={handleRootOpenChange} modal={false}>\n <PickerTrigger anchorRef={anchorRef}>\n {triggerContent !== undefined\n // Bare: the caller frames it. No box, no padding,\n // no height of its own — the node it passed,\n // exactly where it would be anyway. A `div`, not a\n // `button`: what it wraps can hold buttons of its\n // own (a record card's open button, at tall rows).\n ? <div\n ref={handleButtonRef}\n role=\"button\"\n tabIndex={disabled ? -1 : 0}\n aria-disabled={disabled || undefined}\n aria-haspopup=\"listbox\"\n aria-expanded={isPopoverOpen}\n data-relation-selector-trigger\n onClick={toggleOpen}\n // A record's title in the value opens that\n // record, and the list has no business staying\n // open over it.\n onClickCapture={(event) => {\n const target = event.target;\n if (!(target instanceof Element) || !isPopoverOpenRef.current) return;\n const interactive = target.closest(\"a, button, [role=\\\"button\\\"]\");\n if (interactive && interactive !== event.currentTarget) setPopoverOpen(false);\n }}\n onKeyDown={(event) => {\n if (event.key !== \"Enter\" && event.key !== \" \") return;\n event.preventDefault();\n toggleOpen();\n }}\n className={cls(\"w-full select-none text-left text-sm relative flex items-center outline-none\", className)}>\n {triggerContent}\n </div>\n : <button\n ref={handleButtonRef}\n type=\"button\"\n aria-haspopup=\"listbox\"\n aria-expanded={isPopoverOpen}\n data-relation-selector-trigger\n disabled={disabled}\n onClick={toggleOpen}\n className={cls(\n {\n \"min-h-[42px] py-1 px-2\": size === \"small\",\n \"min-h-[56px] py-2 px-4\": size === \"medium\",\n \"min-h-[48px] py-1 px-4\": size === \"large\"\n },\n // `rounded-lg` like every other field box —\n // `rounded-md` made this the one control in a\n // row with a different corner.\n \"w-full select-none rounded-lg text-sm relative flex items-center\",\n invisible ? fieldBackgroundInvisibleMixin : fieldBackgroundMixin,\n disabled ? fieldBackgroundDisabledMixin : fieldBackgroundHoverMixin,\n className\n )}\n >\n <div className=\"flex justify-between items-center w-full\">\n {isLoadingSelectedItems ? (\n <div className=\"flex items-center gap-2\">\n <CircularProgress size=\"smallest\"/>\n <span className=\"text-sm text-text-secondary dark:text-text-secondary-dark\">{loadingText}</span>\n </div>\n ) : selectedItems.length > 0 ? (\n <div\n className=\"flex flex-wrap items-center gap-1.5 text-start flex-1 min-w-0 mr-2\">\n {selectedItems.map((item) => {\n if (!useChips || !multiple) {\n return (\n <div key={String(item.id)}\n className=\"flex flex-row items-center gap-1 truncate\">\n {item.data ? (\n <EntityPreviewBindingData size={\"medium\"}\n entity={item.data}\n includeEntityLink={false}\n includeId={false}\n onSidePanelClick={closePopover}\n />\n ) : (\n <span className=\"text-sm truncate\">{item.label}</span>\n )}\n </div>\n );\n }\n return (\n <Chip\n size={\"small\"}\n key={String(item.id)}\n className={cls(\"flex flex-row items-center gap-1 truncate\")}\n >\n {item.data ? (\n <EntityPreviewBindingData size={\"smallest\"} entity={item.data}\n includeEntityLink={false}\n includeId={false}/>\n ) : (\n <span className=\"text-sm truncate\">{item.label}</span>\n )}\n <XIcon\n size={iconSize.smallest}\n onClick={(event) => {\n event.stopPropagation();\n handleRemoveItem(item);\n }}\n />\n </Chip>\n );\n })}\n </div>\n ) :\n (\n <span className=\"text-sm text-text-secondary dark:text-text-secondary-dark\">\n {resolvedPlaceholder}\n </span>\n )}\n\n <div className=\"flex items-center flex-shrink-0\">\n {!multiple && selectedItems.length === 1 && selectedItems[0]?.data && (\n <Tooltip title={t(\"relation_open_record\", { label: selectedItems[0].label })}>\n <IconButton aria-label={t(\"relation_open_record\", { label: selectedItems[0].label })}\n component={\"div\"}\n size={\"small\"}\n className=\"opacity-60 hover:opacity-100\"\n onClick={(e) => {\n e.stopPropagation();\n e.preventDefault();\n const entity = selectedItems[0].data!;\n setPopoverOpen(false);\n sidePanelController.open({\n entityId: entity.id,\n path: entity.path,\n collection,\n updateUrl: true\n });\n }}>\n <ArrowRightToLineIcon size={iconSize.small}/>\n </IconButton>\n </Tooltip>\n )}\n <ChevronDownIcon\n size={size === \"small\" ? iconSize.small : iconSize.medium}\n className={cls(\"transition\", isPopoverOpen ? \"rotate-180\" : \"\")}\n />\n </div>\n </div>\n\n </button>}\n </PickerTrigger>\n <PopoverPrimitive.Portal container={portalContainer}>\n <PopoverPrimitive.Content\n ref={contentRef}\n data-relation-selector-content\n className={cls(\"z-50 overflow-hidden border bg-surface-card rounded-lg min-w-72\", defaultBorderMixin)}\n align=\"start\"\n sideOffset={8}\n side=\"bottom\"\n avoidCollisions={true}\n collisionPadding={16}\n // Allow default auto focus (we manually refocus anyway)\n onOpenAutoFocus={(_e) => { /* leave default or custom manual focus */\n }}\n onCloseAutoFocus={(e) => {\n e.preventDefault();\n }}\n style={{ width: \"var(--radix-popover-trigger-width)\" }}\n >\n <CommandPrimitive shouldFilter={false}>\n <div className=\"flex flex-row items-center\">\n <div className=\"relative flex-1\">\n <SearchIcon\n className=\"absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary dark:text-text-secondary-dark\"\n size={iconSize.smallest}/>\n <CommandPrimitive.Input\n ref={searchInputRef}\n className={cls(\n focusedDisabled,\n \"bg-transparent outline-hidden flex-1 h-full w-full pl-10 pr-4 py-3 text-text-primary dark:text-text-primary-dark placeholder:text-text-secondary dark:placeholder:text-text-secondary-dark\"\n )}\n placeholder={searchPlaceholder}\n value={searchString}\n onValueChange={handleSearchChange}\n />\n </div>\n {isLoading && (\n <div className=\"flex items-center justify-center px-3\">\n <CircularProgress size=\"smallest\"/>\n </div>\n )}\n {selectedItems.length > 0 && (\n <div\n onClick={handleClear}\n className=\"text-sm justify-center cursor-pointer py-3 px-4 text-text-secondary dark:text-text-secondary-dark hover:text-text-primary dark:hover:text-text-primary-dark\"\n >\n Clear\n </div>\n )}\n </div>\n <Separator orientation=\"horizontal\" className=\"my-0\"/>\n <CommandPrimitive.List\n ref={scrollContainerRef}\n style={{\n maxHeight: \"40vh\",\n overflowY: \"auto\"\n }}\n >\n {isLoading && availableItems.length === 0 && (\n <div className=\"flex items-center justify-center py-6\">\n <CircularProgress size=\"small\"/>\n <span\n className=\"ml-2 text-sm text-text-secondary dark:text-text-secondary-dark\">{loadingText}</span>\n </div>\n )}\n {/* Two different nothings, which used to share one\n message (\"No relations found.\") even though the\n fix for each is the opposite: clear the search, or\n go and create the first row. With the fetch done,\n the search string is what tells them apart. */}\n {!isLoading && availableItems.length === 0 && (\n <CommandPrimitive.Empty\n className=\"px-4 py-6 text-center text-text-secondary dark:text-text-secondary-dark\">\n {searchString\n ? noResultsText\n : (emptyCollectionText ?? `No ${collection.name ?? \"entries\"} yet.`)}\n </CommandPrimitive.Empty>\n )}\n <CommandPrimitive.Group>\n {(() => {\n // Sort items so that initially-selected (pinned) items appear first.\n // We use the entity taken when the popover opened so items don't\n // jump around as the user checks/unchecks.\n const pinned = pinnedIdsRef.current;\n const sortedItems = pinned && pinned.size > 0\n ? [...availableItems].sort((a, b) => {\n const aP = pinned.has(String(a.id)) ? 0 : 1;\n const bP = pinned.has(String(b.id)) ? 0 : 1;\n return aP - bP;\n })\n : availableItems;\n return sortedItems;\n })().map((item) => {\n const isSelected = selectedItems.some(v => String(v.id) === String(item.id));\n return (\n <CommandPrimitive.Item\n key={String(item.id)}\n value={String(item.id)}\n onMouseDown={(e) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n onSelect={() => onItemClick(item)}\n className={cls(\n \"flex flex-row items-center gap-1.5 m-1 p-1 rounded-xs cursor-pointer ring-offset-transparent\",\n isSelected && \"bg-surface-active\",\n \"aria-selected:outline-hidden aria-selected:bg-surface-active\"\n )}\n >\n {multiple && (<InnerCheckBox checked={isSelected}/>)}\n {item.data ? (\n <div\n className=\"flex flex-row items-center gap-2 min-w-0 w-full\">\n <EntityPreviewBindingData\n size={multiple ? \"smallest\" : \"medium\"}\n entity={item.data}\n includeId={false}\n includeEntityLink={true}\n />\n </div>\n ) : (\n <div>\n <div\n className=\"text-sm font-medium text-text-primary dark:text-text-primary-dark\">{item.label}</div>\n {item.description && (\n <div\n className=\"text-xs text-text-secondary dark:text-text-secondary-dark\">{item.description}</div>\n )}\n </div>\n )}\n </CommandPrimitive.Item>\n );\n })}\n {availableItems.length > 0 && hasMore && (\n <div ref={sentinelCallbackRef} className=\"h-1 w-full\"\n style={{ visibility: \"hidden\" }}/>\n )}\n {isLoading && availableItems.length > 0 && (\n <div className=\"flex items-center justify-center py-4\">\n <CircularProgress size=\"smallest\"/>\n <span\n className=\"ml-2 text-xs text-text-secondary dark:text-text-secondary-dark\">Loading...</span>\n </div>\n )}\n </CommandPrimitive.Group>\n </CommandPrimitive.List>\n {canCreateTarget && <>\n <Separator orientation=\"horizontal\" className=\"my-0\"/>\n {/* Outside the scrolling list on purpose: it\n is most wanted exactly when the list is\n long and nothing in it matched. */}\n <button\n type=\"button\"\n data-relation-selector-create\n onMouseDown={(e) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n onClick={handleCreateNew}\n className={cls(\n \"w-full flex flex-row items-center gap-2 px-4 py-3 text-sm text-left\",\n \"text-primary hover:bg-surface-hover\"\n )}>\n <PlusIcon size={iconSize.smallest}/>\n <span className=\"truncate\">\n {searchString.trim()\n ? t(\"add_named\", { name: searchString.trim() })\n : t(\"add_specific\", { name: collection.singularName ?? collection.name })}\n </span>\n </button>\n </>}\n </CommandPrimitive>\n </PopoverPrimitive.Content>\n </PopoverPrimitive.Portal>\n </PopoverPrimitive.Root>\n </>\n );\n }\n);\n\nRelationSelector.displayName = \"RelationSelector\";\n\nfunction InnerCheckBox({ checked }: { checked: boolean }) {\n return (\n <div className={cls(\n \"p-2 w-8 h-8 inline-flex items-center justify-center text-sm font-medium focus:outline-hidden transition-colors ease-in-out duration-150\"\n )}>\n <div\n className={cls(\n \"border-2 relative transition-colors ease-in-out duration-150 w-4 h-4 rounded-xs flex items-center justify-center\",\n checked ? \"bg-primary text-surface-accent-100 dark:text-surface-accent-900 border-transparent\" : \"bg-surface-card border-surface-accent-800 dark:border-surface-accent-500\"\n )}\n >\n {checked && <CheckIcon size={iconSize.smallest} className=\"absolute\"/>}\n </div>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAoCA,SAAS,oBAAoB,UAA2F;CACpH,IAAI,CAAC,UAAU,OAAO,KAAA;CACtB,IAAI,SAAS,SAAS,OAAO,OAAO,SAAS;CAC7C,IAAI,SAAS,SAAS,aAAa,SAAS,SAAS,cAAc,OAAO;CAC1E,IAAI,SAAS,SAAS,eAAe,SAAS,SAAS,UAAU,OAAO;CACxE,OAAO,SAAS;AACpB;AAiGA,IAAa,mBAAmB,QAAM,YAK9B,EACI,OACA,OAAO,UACP,eACA,WACA,UACA,aACA,WAAW,MACX,WACA,UACA,UAAU,kBACV,aACA,UACA,kBACA,oBAAoB,aACpB,gBAAgB,eAChB,YAAY,WACZ,qBACA,cAAc,cACd,cAAc,MACd,MAAM,UACN,cACA,gBACA,aAEJ,QACC;CAED,MAAM,aAAa,SAAS,OAAO;CACnC,MAAM,WAAW,sBAAsB,UAAU;CACjD,MAAM,aAAa,QAAQ;CAC3B,MAAM,sBAAsB,aAAa;CACzC,MAAM,EAAE,cAAc,eAAe;CACrC,MAAM,EAAE,MAAM,eAAe;CAC7B,MAAM,yBAAyB,mBAAmB;CAClD,MAAM,WAAW,oBAAoB,oBAAoB,QAAQ,MAAM;CAEvE,MAAM,CAAC,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AAE,eAAe;QACjB,EAAE,gBAAgB;OACtB;OACA,SAAS;OACT,WAAW,IACP,uEACA,qCACJ;iBAXJ,CAYI,oBAAC,UAAD,EAAU,MAAM,SAAS,SAAU,CAAA,GACnC,oBAAC,QAAD;QAAM,WAAU;kBACX,aAAa,KAAK,IACb,EAAE,aAAa,EAAE,MAAM,aAAa,KAAK,EAAE,CAAC,IAC5C,EAAE,gBAAgB,EAAE,MAAM,WAAW,gBAAgB,WAAW,KAAK,CAAC;OAC1E,CAAA,CACF;QACV,EAAA,CAAA;KACY;;GACI,CAAA;EACL,CAAA,CACN;IACzB,CAAA;AAEV,CACJ;AAEA,iBAAiB,cAAc;AAE/B,SAAS,cAAc,EAAE,WAAiC;CACtD,OACI,oBAAC,OAAD;EAAK,WAAW,IACZ,yIACJ;YACI,oBAAC,OAAD;GACI,WAAW,IACP,oHACA,UAAU,uFAAuF,0EACrG;aAEC,WAAW,oBAAC,WAAD;IAAW,MAAM,SAAS;IAAU,WAAU;GAAW,CAAA;EACpE,CAAA;CACJ,CAAA;AAEb"}
@@ -1 +1 @@
1
- {"version":3,"file":"Scaffold.js","names":[],"sources":["../../../src/components/app/Scaffold.tsx"],"sourcesContent":["import React, { PropsWithChildren, useCallback, useMemo } from \"react\";\nimport { cls, defaultBorderMixin, IconButton, Sheet, Tooltip } from \"@rebasepro/ui\";\nimport { ChevronLeftIcon, ErrorBoundary, MenuIcon } from \"@rebasepro/ui\";\nimport { deepEqual as equal } from \"fast-equals\"\n\nimport { ConnectionLostBanner, useLargeLayout, useTranslation } from \"@rebasepro/app\";\nimport { useUrlController } from \"../../hooks/navigation/contexts/UrlContext\";\nimport { AppContext } from \"./useApp\";\n\nexport const DRAWER_WIDTH = 280;\n\n/**\n * Namespaced by base path: two admins served from one origin are two different\n * navigations, and a single key would have them overwrite each other's drawer.\n */\nexport function drawerOpenStorageKey(basePath: string | undefined) {\n return `rebase-drawer-open:${basePath || \"/\"}`;\n}\n\n/** `null` when the user has never toggled the drawer, or storage is unavailable. */\nfunction readStoredDrawerOpen(key: string): boolean | null {\n if (typeof window === \"undefined\") return null;\n try {\n const stored = window.localStorage.getItem(key);\n return stored === null ? null : stored === \"true\";\n } catch (e) {\n // Storage can be blocked: private mode, sandboxed iframe, cookie policy.\n return null;\n }\n}\n\nfunction writeStoredDrawerOpen(key: string, open: boolean) {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.setItem(key, String(open));\n } catch (e) {\n // Same as above: a drawer that forgets is better than a crash.\n }\n}\n\n/**\n * @group Core\n */\nexport interface ScaffoldProps {\n\n /**\n * Expand the collapsed drawer while the pointer is over it. On by default —\n * pass `false` to keep the rail a rail until the user clicks the toggle.\n */\n autoOpenDrawer?: boolean;\n\n /**\n * Start with the drawer expanded rather than collapsed to icons.\n *\n * Distinct from {@link autoOpenDrawer}, which is a hover behaviour: this one\n * only seeds the very first visit. Once the user toggles the drawer, that\n * choice is stored in `localStorage` and wins over this prop on every load.\n *\n * Ignored on small layouts, where an expanded drawer covers the content it is\n * meant to navigate.\n */\n defaultDrawerOpen?: boolean;\n\n /**\n * Logo to be displayed in the top bar and drawer.\n * Note that this has no effect if you are using a custom AppBar or Drawer.\n */\n logo?: string;\n\n /**\n * If true, the main content will be padded in large layouts. Defaults to true.\n */\n padding?: boolean;\n\n className?: string;\n\n style?: React.CSSProperties;\n}\n\n/**\n * This view acts as a scaffold for Rebase.\n *\n * It is in charge of displaying the navigation drawer, top bar and main\n * collection views.\n * This component needs a parent {@link Rebase}\n *\n * @param props\n\n * @group Core\n */\nexport const Scaffold = React.memo<PropsWithChildren<ScaffoldProps>>(\n function Scaffold(props: PropsWithChildren<ScaffoldProps>) {\n\n const {\n children,\n autoOpenDrawer = true,\n defaultDrawerOpen = false,\n logo,\n className,\n style,\n padding = true\n } = props;\n\n // `toArray` keeps strings and numbers, and those have no `.type` at all.\n // Reading `child.type.componentType` off one threw a TypeError from\n // inside the layout, which is a bewildering way to be told that a stray\n // text node — a conditional that rendered `\"\"`, a template string —\n // reached the Scaffold. Anything that is not an element is just \"other\".\n const slotOf = (child: React.ReactNode): string | undefined =>\n React.isValidElement(child)\n ? (child.type as { componentType?: string })?.componentType\n : undefined;\n\n const childArray = React.Children.toArray(children);\n const drawerChildren = childArray.filter((child) => slotOf(child) === \"Drawer\");\n if (drawerChildren.length > 1) {\n throw Error(\"Only one Drawer component is allowed in Scaffold\");\n }\n const appBarChildren = childArray.filter((child) => slotOf(child) === \"AppBar\");\n if (appBarChildren.length > 1) {\n throw Error(\"Only one AppBar component is allowed in Scaffold\");\n }\n const otherChildren = childArray\n .filter((child) => slotOf(child) !== \"Drawer\" && slotOf(child) !== \"AppBar\");\n const includeDrawer = drawerChildren.length > 0;\n const largeLayout = useLargeLayout();\n\n const storageKey = drawerOpenStorageKey(useUrlController().basePath);\n\n // Seeded once, deliberately: a `useEffect` syncing this to the prop would\n // re-expand the drawer under a user who had just collapsed it.\n const [drawerOpen, setDrawerOpenState] = React.useState(defaultDrawerOpen && largeLayout);\n const [onHover, setOnHover] = React.useState(false);\n\n // The stored choice is a client-only fact, so it is applied after the first\n // render rather than seeded into it: reading storage while rendering would\n // make the client disagree with server-rendered HTML. A layout effect runs\n // before paint, so the drawer still arrives in its remembered state.\n // `defaultDrawerOpen` seeds the very first visit and is ignored after that.\n React.useLayoutEffect(() => {\n const stored = readStoredDrawerOpen(storageKey);\n if (stored === null) return;\n setDrawerOpenState(stored && largeLayout);\n // Deliberately not re-run on `largeLayout`: crossing the breakpoint is\n // the effect below, and re-running here would undo a user's toggle.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [storageKey]);\n\n // One piece of state drives two different things: the expanded rail on\n // large layouts, and the modal sheet on small ones. Carrying an expanded\n // rail across the breakpoint would drop that sheet, overlay and all, over\n // the content — so the crossing resets it, and widening again restores\n // whatever the user last chose.\n const wasLargeLayout = React.useRef(largeLayout);\n React.useEffect(() => {\n if (wasLargeLayout.current === largeLayout) return;\n wasLargeLayout.current = largeLayout;\n setDrawerOpenState(largeLayout ? (readStoredDrawerOpen(storageKey) ?? defaultDrawerOpen) : false);\n }, [largeLayout, defaultDrawerOpen, storageKey]);\n\n const setDrawerOpen = useCallback((open: boolean) => {\n setDrawerOpenState(open);\n // Small layouts render the drawer as a modal sheet. Remembering that\n // one would greet the next load with an overlay over the content.\n if (!largeLayout) return;\n writeStoredDrawerOpen(storageKey, open);\n }, [largeLayout, storageKey]);\n\n // The pointer has left, but a popover the drawer opened is still up, so the\n // collapse is owed rather than cancelled. See `setOnHoverFalse`.\n const collapseWhenPopoverCloses = React.useRef(false);\n\n const setOnHoverTrue = useCallback(() => {\n // Hover expansion is the default; `autoOpenDrawer={false}` opts out for\n // admins that want the rail to stay a rail until the toggle is clicked.\n if (!autoOpenDrawer) return;\n collapseWhenPopoverCloses.current = false;\n setOnHover(true);\n }, [autoOpenDrawer]);\n const setOnHoverFalse = useCallback(() => {\n // Don't collapse the drawer out from under an open popover/dropdown —\n // its content is portalled outside the drawer, so reaching for it reads\n // as a mouseleave. The collapse is owed until that popover closes.\n if (document.querySelector(\"[data-radix-popper-content-wrapper]\")) {\n collapseWhenPopoverCloses.current = true;\n return;\n }\n collapseWhenPopoverCloses.current = false;\n setOnHover(false);\n }, []);\n\n // Nothing fires a second mouseleave when the popover finally closes, so the\n // owed collapse has to be noticed rather than waited for. Only mounted\n // while the drawer is actually floating open.\n React.useEffect(() => {\n if (!onHover) return;\n const collapseIfOwed = () => {\n if (!collapseWhenPopoverCloses.current) return;\n if (document.querySelector(\"[data-radix-popper-content-wrapper]\")) return;\n collapseWhenPopoverCloses.current = false;\n setOnHover(false);\n };\n const observer = new MutationObserver(collapseIfOwed);\n observer.observe(document.body, {\n childList: true,\n subtree: true\n });\n return () => observer.disconnect();\n }, [onHover]);\n\n const handleDrawerOpen = useCallback(() => {\n setDrawerOpen(true);\n }, [setDrawerOpen]);\n\n const handleDrawerClose = useCallback(() => {\n setDrawerOpen(false);\n }, [setDrawerOpen]);\n\n const computedDrawerOpen: boolean = drawerOpen;\n const computedDrawerHovered = Boolean(largeLayout && onHover);\n\n const hasAppBar = Boolean(appBarChildren.length > 0);\n const appContextValue = useMemo(() => ({\n hasDrawer: Boolean(includeDrawer),\n drawerOpen: computedDrawerOpen,\n drawerHovered: computedDrawerHovered,\n openDrawer: handleDrawerOpen,\n closeDrawer: handleDrawerClose,\n closeHover: setOnHoverFalse,\n logo\n }), [includeDrawer, computedDrawerOpen, computedDrawerHovered, handleDrawerOpen, handleDrawerClose, setOnHoverFalse, logo]);\n\n return (\n <AppContext.Provider value={appContextValue}>\n <div\n className={cls(\"flex h-screen w-screen overflow-hidden\",\n \"bg-surface-frame\",\n \"text-surface-900 dark:text-white\", className)}\n style={{\n paddingTop: \"env(safe-area-inset-top)\",\n paddingLeft: \"env(safe-area-inset-left)\",\n paddingRight: \"env(safe-area-inset-right)\",\n paddingBottom: \"env(safe-area-inset-bottom)\",\n height: \"100dvh\",\n ...style\n }}>\n {appBarChildren}\n\n <DrawerWrapper\n displayed={includeDrawer}\n onMouseEnter={setOnHoverTrue}\n onMouseMove={setOnHoverTrue}\n onMouseLeave={setOnHoverFalse}\n open={drawerOpen}\n hovered={onHover}\n setDrawerOpen={setDrawerOpen}>\n {includeDrawer && drawerChildren}\n </DrawerWrapper>\n\n <main\n className=\"flex flex-col grow overflow-auto\">\n\n {hasAppBar && <DrawerHeader/>}\n\n {/* Above the sheet, so it is there on every screen: while\n the realtime connection is down, every live view is\n showing what it last received. */}\n <ConnectionLostBanner className={cls(\"px-2 pt-1\", {\n \"lg:pt-0 lg:pb-2\": padding,\n \"lg:pt-2\": !hasAppBar && padding\n })}/>\n\n <div\n // The sheet is one lightness step above the frame AND carries a\n // plain hairline on its edge. The step alone (#0a0a0a to #131313,\n // #f0f0f2 to #f9f9fa) is about 3 L* on both themes, under what a\n // dimmed screen renders, and the first pass of this system removed\n // the line on the theory that the step would do its work; the\n // frame and the sheet then read as one black. The reference's own\n // content sheet carries this line. Only in the inset `lg` layout:\n // edge-to-edge on small screens, a border draws at the viewport.\n className={cls(\"bg-surface-sheet\", \"grow overflow-auto m-0\", \"lg:border lg:border-hairline\", {\n \"mt-1 lg:m-0 lg:mx-2 lg:mb-2 lg:rounded-xl\": padding,\n // No app bar means no DrawerHeader spacer above, so inset the\n // panel by the same amount as its sides and bottom.\n // Must come after the padding classes, which reset lg margins.\n \"lg:mt-2\": !hasAppBar && padding,\n \"lg:mt-4\": !hasAppBar && !padding\n })}>\n\n <ErrorBoundary>\n {otherChildren}\n </ErrorBoundary>\n\n </div>\n </main>\n </div>\n </AppContext.Provider>\n );\n },\n equal\n)\n\nconst DrawerHeader = () => {\n return (\n <div className=\"flex flex-col min-h-14\"></div>\n );\n};\n\nfunction DrawerWrapper(props: {\n children: React.ReactNode,\n displayed: boolean,\n open: boolean,\n logo?: string,\n hovered: boolean,\n setDrawerOpen: (open: boolean) => void,\n onMouseEnter: () => void,\n onMouseMove: () => void,\n onMouseLeave: () => void\n}) {\n\n const layoutWidth = !props.displayed ? 0 : (props.open ? DRAWER_WIDTH : 72);\n const visualWidth = !props.displayed ? 0 : ((props.open || props.hovered) ? DRAWER_WIDTH : 72);\n\n const isFloating = props.hovered && !props.open;\n const { t } = useTranslation();\n\n // The drawer is part of the frame, on both themes. When it floats over the\n // sheet it needs an edge, because a frame-coloured panel over the sheet is\n // an object at that moment; docked, it is a region and gets none.\n const innerDrawer = <div\n className={cls(\"h-full overflow-hidden bg-surface-frame\", defaultBorderMixin,\n isFloating ? \"absolute top-0 left-0 bottom-0 z-50 shadow-lg border-r\" : \"relative\")}\n style={{\n width: visualWidth,\n transition: \"left 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, opacity 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, width 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms\"\n }}\n >\n\n <div className={\"flex flex-col h-full\"}>\n {props.children}\n </div>\n\n </div>;\n\n const largeLayout = useLargeLayout();\n if (!largeLayout) {\n if (!props.displayed)\n return null;\n return <>\n <IconButton\n aria-label={t(\"open_menu\")}\n onClick={() => props.setDrawerOpen(true)}\n className=\"absolute sm:top-2 sm:left-4 top-1 left-2\"\n >\n <MenuIcon/>\n </IconButton>\n <Sheet side={\"left\"}\n transparent={true}\n open={props.open}\n onOpenChange={props.setDrawerOpen}\n title={t(\"navigation_drawer\")}\n overlayClassName={\"bg-surface-scrim\"}\n >\n {innerDrawer}\n </Sheet>\n </>;\n }\n\n return (\n <div\n className=\"z-20 relative flex-shrink-0 overflow-visible\"\n onMouseEnter={props.onMouseEnter}\n onMouseMove={props.onMouseMove}\n onMouseLeave={props.onMouseLeave}\n style={{\n width: layoutWidth,\n minWidth: layoutWidth,\n transition: \"left 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, opacity 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, width 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms\"\n }}>\n\n {innerDrawer}\n\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;AAeA,SAAgB,qBAAqB,UAA8B;CAC/D,OAAO,sBAAsB,YAAY;AAC7C;;AAGA,SAAS,qBAAqB,KAA6B;CACvD,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,IAAI;EACA,MAAM,SAAS,OAAO,aAAa,QAAQ,GAAG;EAC9C,OAAO,WAAW,OAAO,OAAO,WAAW;CAC/C,SAAS,GAAG;EAER,OAAO;CACX;AACJ;AAEA,SAAS,sBAAsB,KAAa,MAAe;CACvD,IAAI,OAAO,WAAW,aAAa;CACnC,IAAI;EACA,OAAO,aAAa,QAAQ,KAAK,OAAO,IAAI,CAAC;CACjD,SAAS,GAAG,CAEZ;AACJ;;;;;;;;;;;;AAoDA,IAAa,WAAW,MAAM,KAC1B,SAAS,SAAS,OAAyC;CAEvD,MAAM,EACF,UACA,iBAAiB,MACjB,oBAAoB,OACpB,MACA,WACA,OACA,UAAU,SACV;CAOJ,MAAM,UAAU,UACZ,MAAM,eAAe,KAAK,IACnB,MAAM,MAAqC,gB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,MAAM;GACT,aAAa;GACb,MAAM,MAAM;GACZ,cAAc,MAAM;GACpB,OAAO,EAAE,mBAAmB;GAC5B,kBAAkB;aAEjB;EACE,CAAA,CACT,EAAA,CAAA;CACN;CAEA,OACI,oBAAC,OAAD;EACI,WAAU;EACV,cAAc,MAAM;EACpB,aAAa,MAAM;EACnB,cAAc,MAAM;EACpB,OAAO;GACH,OAAO;GACP,UAAU;GACV,YAAY;EAChB;YAEC;CAEA,CAAA;AAEb"}
1
+ {"version":3,"file":"Scaffold.js","names":[],"sources":["../../../src/components/app/Scaffold.tsx"],"sourcesContent":["import React, { PropsWithChildren, useCallback, useMemo } from \"react\";\nimport { cls, defaultBorderMixin, IconButton, Sheet, Tooltip } from \"@rebasepro/ui\";\nimport { ChevronLeftIcon, ErrorBoundary, MenuIcon } from \"@rebasepro/ui\";\nimport { deepEqual as equal } from \"fast-equals\"\n\nimport { ConnectionLostBanner, useLargeLayout, useTranslation } from \"@rebasepro/app\";\nimport { useUrlController } from \"../../hooks/navigation/contexts/UrlContext\";\nimport { AppContext } from \"./useApp\";\n\nexport const DRAWER_WIDTH = 280;\n\n/**\n * Namespaced by base path: two admins served from one origin are two different\n * navigations, and a single key would have them overwrite each other's drawer.\n */\nexport function drawerOpenStorageKey(basePath: string | undefined) {\n return `rebase-drawer-open:${basePath || \"/\"}`;\n}\n\n/** `null` when the user has never toggled the drawer, or storage is unavailable. */\nfunction readStoredDrawerOpen(key: string): boolean | null {\n if (typeof window === \"undefined\") return null;\n try {\n const stored = window.localStorage.getItem(key);\n return stored === null ? null : stored === \"true\";\n } catch (e) {\n // Storage can be blocked: private mode, sandboxed iframe, cookie policy.\n return null;\n }\n}\n\nfunction writeStoredDrawerOpen(key: string, open: boolean) {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.setItem(key, String(open));\n } catch (e) {\n // Same as above: a drawer that forgets is better than a crash.\n }\n}\n\n/**\n * @group Core\n */\nexport interface ScaffoldProps {\n\n /**\n * Expand the collapsed drawer while the pointer is over it. On by default —\n * pass `false` to keep the rail a rail until the user clicks the toggle.\n */\n autoOpenDrawer?: boolean;\n\n /**\n * Start with the drawer expanded rather than collapsed to icons.\n *\n * Distinct from {@link autoOpenDrawer}, which is a hover behaviour: this one\n * only seeds the very first visit. Once the user toggles the drawer, that\n * choice is stored in `localStorage` and wins over this prop on every load.\n *\n * Ignored on small layouts, where an expanded drawer covers the content it is\n * meant to navigate.\n */\n defaultDrawerOpen?: boolean;\n\n /**\n * Logo to be displayed in the top bar and drawer.\n * Note that this has no effect if you are using a custom AppBar or Drawer.\n */\n logo?: string;\n\n /**\n * If true, the main content will be padded in large layouts. Defaults to true.\n */\n padding?: boolean;\n\n className?: string;\n\n style?: React.CSSProperties;\n}\n\n/**\n * This view acts as a scaffold for Rebase.\n *\n * It is in charge of displaying the navigation drawer, top bar and main\n * collection views.\n * This component needs a parent {@link Rebase}\n *\n * @param props\n\n * @group Core\n */\nexport const Scaffold = React.memo<PropsWithChildren<ScaffoldProps>>(\n function Scaffold(props: PropsWithChildren<ScaffoldProps>) {\n\n const {\n children,\n autoOpenDrawer = true,\n defaultDrawerOpen = false,\n logo,\n className,\n style,\n padding = true\n } = props;\n\n // `toArray` keeps strings and numbers, and those have no `.type` at all.\n // Reading `child.type.componentType` off one threw a TypeError from\n // inside the layout, which is a bewildering way to be told that a stray\n // text node — a conditional that rendered `\"\"`, a template string —\n // reached the Scaffold. Anything that is not an element is just \"other\".\n const slotOf = (child: React.ReactNode): string | undefined =>\n React.isValidElement(child)\n ? (child.type as { componentType?: string })?.componentType\n : undefined;\n\n const childArray = React.Children.toArray(children);\n const drawerChildren = childArray.filter((child) => slotOf(child) === \"Drawer\");\n if (drawerChildren.length > 1) {\n throw Error(\"Only one Drawer component is allowed in Scaffold\");\n }\n const appBarChildren = childArray.filter((child) => slotOf(child) === \"AppBar\");\n if (appBarChildren.length > 1) {\n throw Error(\"Only one AppBar component is allowed in Scaffold\");\n }\n const otherChildren = childArray\n .filter((child) => slotOf(child) !== \"Drawer\" && slotOf(child) !== \"AppBar\");\n const includeDrawer = drawerChildren.length > 0;\n const largeLayout = useLargeLayout();\n\n const storageKey = drawerOpenStorageKey(useUrlController().basePath);\n\n // Seeded once, deliberately: a `useEffect` syncing this to the prop would\n // re-expand the drawer under a user who had just collapsed it.\n const [drawerOpen, setDrawerOpenState] = React.useState(defaultDrawerOpen && largeLayout);\n const [onHover, setOnHover] = React.useState(false);\n\n // The stored choice is a client-only fact, so it is applied after the first\n // render rather than seeded into it: reading storage while rendering would\n // make the client disagree with server-rendered HTML. A layout effect runs\n // before paint, so the drawer still arrives in its remembered state.\n // `defaultDrawerOpen` seeds the very first visit and is ignored after that.\n React.useLayoutEffect(() => {\n const stored = readStoredDrawerOpen(storageKey);\n if (stored === null) return;\n setDrawerOpenState(stored && largeLayout);\n // Deliberately not re-run on `largeLayout`: crossing the breakpoint is\n // the effect below, and re-running here would undo a user's toggle.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [storageKey]);\n\n // One piece of state drives two different things: the expanded rail on\n // large layouts, and the modal sheet on small ones. Carrying an expanded\n // rail across the breakpoint would drop that sheet, overlay and all, over\n // the content — so the crossing resets it, and widening again restores\n // whatever the user last chose.\n const wasLargeLayout = React.useRef(largeLayout);\n React.useEffect(() => {\n if (wasLargeLayout.current === largeLayout) return;\n wasLargeLayout.current = largeLayout;\n setDrawerOpenState(largeLayout ? (readStoredDrawerOpen(storageKey) ?? defaultDrawerOpen) : false);\n }, [largeLayout, defaultDrawerOpen, storageKey]);\n\n const setDrawerOpen = useCallback((open: boolean) => {\n setDrawerOpenState(open);\n // Small layouts render the drawer as a modal sheet. Remembering that\n // one would greet the next load with an overlay over the content.\n if (!largeLayout) return;\n writeStoredDrawerOpen(storageKey, open);\n }, [largeLayout, storageKey]);\n\n // The pointer has left, but a popover the drawer opened is still up, so the\n // collapse is owed rather than cancelled. See `setOnHoverFalse`.\n const collapseWhenPopoverCloses = React.useRef(false);\n\n const setOnHoverTrue = useCallback(() => {\n // Hover expansion is the default; `autoOpenDrawer={false}` opts out for\n // admins that want the rail to stay a rail until the toggle is clicked.\n if (!autoOpenDrawer) return;\n collapseWhenPopoverCloses.current = false;\n setOnHover(true);\n }, [autoOpenDrawer]);\n const setOnHoverFalse = useCallback(() => {\n // Don't collapse the drawer out from under an open popover/dropdown —\n // its content is portalled outside the drawer, so reaching for it reads\n // as a mouseleave. The collapse is owed until that popover closes.\n if (document.querySelector(\"[data-radix-popper-content-wrapper]\")) {\n collapseWhenPopoverCloses.current = true;\n return;\n }\n collapseWhenPopoverCloses.current = false;\n setOnHover(false);\n }, []);\n\n // Nothing fires a second mouseleave when the popover finally closes, so the\n // owed collapse has to be noticed rather than waited for. Only mounted\n // while the drawer is actually floating open.\n React.useEffect(() => {\n if (!onHover) return;\n const collapseIfOwed = () => {\n if (!collapseWhenPopoverCloses.current) return;\n if (document.querySelector(\"[data-radix-popper-content-wrapper]\")) return;\n collapseWhenPopoverCloses.current = false;\n setOnHover(false);\n };\n const observer = new MutationObserver(collapseIfOwed);\n observer.observe(document.body, {\n childList: true,\n subtree: true\n });\n return () => observer.disconnect();\n }, [onHover]);\n\n const handleDrawerOpen = useCallback(() => {\n setDrawerOpen(true);\n }, [setDrawerOpen]);\n\n const handleDrawerClose = useCallback(() => {\n setDrawerOpen(false);\n }, [setDrawerOpen]);\n\n const computedDrawerOpen: boolean = drawerOpen;\n const computedDrawerHovered = Boolean(largeLayout && onHover);\n\n const hasAppBar = Boolean(appBarChildren.length > 0);\n const appContextValue = useMemo(() => ({\n hasDrawer: Boolean(includeDrawer),\n drawerOpen: computedDrawerOpen,\n drawerHovered: computedDrawerHovered,\n openDrawer: handleDrawerOpen,\n closeDrawer: handleDrawerClose,\n closeHover: setOnHoverFalse,\n logo\n }), [includeDrawer, computedDrawerOpen, computedDrawerHovered, handleDrawerOpen, handleDrawerClose, setOnHoverFalse, logo]);\n\n return (\n <AppContext.Provider value={appContextValue}>\n <div\n className={cls(\"flex h-screen w-screen overflow-hidden\",\n \"bg-surface-frame\",\n \"text-surface-900 dark:text-white\", className)}\n style={{\n paddingTop: \"env(safe-area-inset-top)\",\n paddingLeft: \"env(safe-area-inset-left)\",\n paddingRight: \"env(safe-area-inset-right)\",\n paddingBottom: \"env(safe-area-inset-bottom)\",\n height: \"100dvh\",\n ...style\n }}>\n {appBarChildren}\n\n <DrawerWrapper\n displayed={includeDrawer}\n onMouseEnter={setOnHoverTrue}\n onMouseMove={setOnHoverTrue}\n onMouseLeave={setOnHoverFalse}\n open={drawerOpen}\n hovered={onHover}\n setDrawerOpen={setDrawerOpen}>\n {includeDrawer && drawerChildren}\n </DrawerWrapper>\n\n <main\n className=\"flex flex-col grow overflow-auto\">\n\n {hasAppBar && <DrawerHeader/>}\n\n {/* Above the sheet, so it is there on every screen: while\n the realtime connection is down, every live view is\n showing what it last received. */}\n <ConnectionLostBanner className={cls(\"px-2 pt-1\", {\n \"lg:pt-0 lg:pb-2\": padding,\n \"lg:pt-2\": !hasAppBar && padding\n })}/>\n\n <div\n // The sheet is one lightness step above the frame AND carries a\n // plain hairline on its edge. The step alone (#090a0c to #111316,\n // #eff0f3 to #f8f9fa) is about 3 L* on both themes, under what a\n // dimmed screen renders, and the first pass of this system removed\n // the line on the theory that the step would do its work; the\n // frame and the sheet then read as one black. The reference's own\n // content sheet carries this line. Only in the inset `lg` layout:\n // edge-to-edge on small screens, a border draws at the viewport.\n className={cls(\"bg-surface-sheet\", \"grow overflow-auto m-0\", \"lg:border lg:border-hairline\", {\n \"mt-1 lg:m-0 lg:mx-2 lg:mb-2 lg:rounded-xl\": padding,\n // No app bar means no DrawerHeader spacer above, so inset the\n // panel by the same amount as its sides and bottom.\n // Must come after the padding classes, which reset lg margins.\n \"lg:mt-2\": !hasAppBar && padding,\n \"lg:mt-4\": !hasAppBar && !padding\n })}>\n\n <ErrorBoundary>\n {otherChildren}\n </ErrorBoundary>\n\n </div>\n </main>\n </div>\n </AppContext.Provider>\n );\n },\n equal\n)\n\nconst DrawerHeader = () => {\n return (\n <div className=\"flex flex-col min-h-14\"></div>\n );\n};\n\nfunction DrawerWrapper(props: {\n children: React.ReactNode,\n displayed: boolean,\n open: boolean,\n logo?: string,\n hovered: boolean,\n setDrawerOpen: (open: boolean) => void,\n onMouseEnter: () => void,\n onMouseMove: () => void,\n onMouseLeave: () => void\n}) {\n\n const layoutWidth = !props.displayed ? 0 : (props.open ? DRAWER_WIDTH : 72);\n const visualWidth = !props.displayed ? 0 : ((props.open || props.hovered) ? DRAWER_WIDTH : 72);\n\n const isFloating = props.hovered && !props.open;\n const { t } = useTranslation();\n\n // The drawer is part of the frame, on both themes. When it floats over the\n // sheet it needs an edge, because a frame-coloured panel over the sheet is\n // an object at that moment; docked, it is a region and gets none.\n const innerDrawer = <div\n className={cls(\"h-full overflow-hidden bg-surface-frame\", defaultBorderMixin,\n isFloating ? \"absolute top-0 left-0 bottom-0 z-50 shadow-lg border-r\" : \"relative\")}\n style={{\n width: visualWidth,\n transition: \"left 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, opacity 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, width 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms\"\n }}\n >\n\n <div className={\"flex flex-col h-full\"}>\n {props.children}\n </div>\n\n </div>;\n\n const largeLayout = useLargeLayout();\n if (!largeLayout) {\n if (!props.displayed)\n return null;\n return <>\n <IconButton\n aria-label={t(\"open_menu\")}\n onClick={() => props.setDrawerOpen(true)}\n className=\"absolute sm:top-2 sm:left-4 top-1 left-2\"\n >\n <MenuIcon/>\n </IconButton>\n <Sheet side={\"left\"}\n transparent={true}\n open={props.open}\n onOpenChange={props.setDrawerOpen}\n title={t(\"navigation_drawer\")}\n overlayClassName={\"bg-surface-scrim\"}\n >\n {innerDrawer}\n </Sheet>\n </>;\n }\n\n return (\n <div\n className=\"z-20 relative flex-shrink-0 overflow-visible\"\n onMouseEnter={props.onMouseEnter}\n onMouseMove={props.onMouseMove}\n onMouseLeave={props.onMouseLeave}\n style={{\n width: layoutWidth,\n minWidth: layoutWidth,\n transition: \"left 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, opacity 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, width 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms\"\n }}>\n\n {innerDrawer}\n\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;AAeA,SAAgB,qBAAqB,UAA8B;CAC/D,OAAO,sBAAsB,YAAY;AAC7C;;AAGA,SAAS,qBAAqB,KAA6B;CACvD,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,IAAI;EACA,MAAM,SAAS,OAAO,aAAa,QAAQ,GAAG;EAC9C,OAAO,WAAW,OAAO,OAAO,WAAW;CAC/C,SAAS,GAAG;EAER,OAAO;CACX;AACJ;AAEA,SAAS,sBAAsB,KAAa,MAAe;CACvD,IAAI,OAAO,WAAW,aAAa;CACnC,IAAI;EACA,OAAO,aAAa,QAAQ,KAAK,OAAO,IAAI,CAAC;CACjD,SAAS,GAAG,CAEZ;AACJ;;;;;;;;;;;;AAoDA,IAAa,WAAW,MAAM,KAC1B,SAAS,SAAS,OAAyC;CAEvD,MAAM,EACF,UACA,iBAAiB,MACjB,oBAAoB,OACpB,MACA,WACA,OACA,UAAU,SACV;CAOJ,MAAM,UAAU,UACZ,MAAM,eAAe,KAAK,IACnB,MAAM,MAAqC,gBAC5C,KAAA;CAEV,MAAM,aAAa,MAAM,SAAS,QAAQ,QAAQ;CAClD,MAAM,iBAAiB,WAAW,QAAQ,UAAU,OAAO,KAAK,MAAM,QAAQ;CAC9E,IAAI,eAAe,SAAS,GACxB,MAAM,MAAM,kDAAkD;CAElE,MAAM,iBAAiB,WAAW,QAAQ,UAAU,OAAO,KAAK,MAAM,QAAQ;CAC9E,IAAI,eAAe,SAAS,GACxB,MAAM,MAAM,kDAAkD;CAElE,MAAM,gBAAgB,WACjB,QAAQ,UAAU,OAAO,KAAK,MAAM,YAAY,OAAO,KAAK,MAAM,QAA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skList"] li > label input[type="checkbox"] {
280
280
  background-color: rgb(30 41 59);
281
- border: 2px solid #666;
281
+ border: 2px solid #62676e;
282
282
  }
283
283
  [data-theme="dark"] ul[data-type="taskList"] li > label input[type="checkbox"]:hover { background-color: rgb(51 65 85); }
284
284
  [data-theme="dark"] ul[data-type="taskList"] li > label input[type="checkbox"]:active { background-color: rgb(71 85 105); }
@@ -292,7 +292,7 @@ ul[data-type="taskList"] li > label input[type="checkbox"] {
292
292
  height: 1.2em;
293
293
  position: relative;
294
294
  top: 5px;
295
- border: 2px solid #777;
295
+ border: 2px solid #72787f;
296
296
  border-radius: 0.25em;
297
297
  margin-right: 0.3rem;
298
298
  display: grid;
@@ -1 +1 @@
1
- {"version":3,"file":"editor.js","names":[],"sources":["../../src/editor/editor.tsx"],"sourcesContent":["\"use client\";\nimport React, { useEffect, useState, useRef, useMemo } from \"react\";\nimport { EditorState, Selection } from \"prosemirror-state\";\nimport { cls, defaultBorderMixin, Separator, TextareaAutosize, useInjectStyles } from \"@rebasepro/ui\";\nimport { useTranslation } from \"@rebasepro/app\";\nimport { EditorBubble, ImageBubble, SlashCommandMenu, TableBubble, type JSONContent } from \"./components\";\nimport { NodeSelector } from \"./selectors/node-selector\";\nimport { LinkSelector } from \"./selectors/link-selector\";\nimport { TextButtons } from \"./selectors/text-buttons\";\nimport { removeClassesFromJson } from \"./utils/remove_classes\";\nimport { parser, serializer } from \"./markdown\";\nimport { EditorAIController } from \"./types\";\nimport { useProseMirror } from \"./hooks/useProseMirror\";\nimport { ProseMirrorContext } from \"./hooks/useProseMirrorContext\";\nimport { highlightCommands } from \"./extensions/HighlightDecorationExtension\";\nimport { schema } from \"./schema\";\n\nexport type CustomEditorComponent = {\n name: string,\n component: React.FC\n};\n\nexport type RichTextEditorTextSize = \"sm\" | \"base\" | \"lg\";\n\n\nexport type RichTextEditorProps = {\n content?: JSONContent | string,\n onMarkdownContentChange?: (content: string) => void,\n onJsonContentChange?: (content: JSONContent | null) => void,\n onHtmlContentChange?: (content: string) => void,\n handleImageUpload: (file: File) => Promise<string>,\n /**\n * Turns an image's stored `src` into a URL to show. `handleImageUpload`\n * returns a `rebase-storage:` reference to keep in the text — a private\n * object's URL expires — and the editor asks this for a URL to display it.\n */\n resolveImageSrc?: (src: string) => Promise<string | null | undefined>,\n version?: number,\n textSize?: RichTextEditorTextSize,\n highlight?: { from: number, to: number },\n aiController?: EditorAIController,\n customComponents?: CustomEditorComponent[];\n disabled?: boolean;\n};\n\n\nconst proseClasses = {\n \"sm\": \"prose-sm\",\n \"base\": \"prose-base\",\n \"lg\": \"prose-lg\"\n}\n\nexport const RichTextEditor = ({\n content,\n onJsonContentChange,\n onHtmlContentChange,\n onMarkdownContentChange,\n version,\n textSize = \"base\",\n highlight,\n handleImageUpload,\n resolveImageSrc,\n aiController,\n disabled\n}: RichTextEditorProps) => {\n\n const { t } = useTranslation();\n\n const [openNode, setOpenNode] = useState(false);\n const [openLink, setOpenLink] = useState(false);\n\n const [isMarkdownMode, setIsMarkdownMode] = useState(false);\n const [internalMarkdown, setInternalMarkdown] = useState<string>(\"\");\n\n useEffect(() => {\n if (!isMarkdownMode) return;\n const timeout = setTimeout(() => {\n if (callbacksRef.current.onMarkdownContentChange) {\n callbacksRef.current.onMarkdownContentChange(internalMarkdown);\n }\n }, 250);\n return () => clearTimeout(timeout);\n }, [internalMarkdown, isMarkdownMode]);\n\n const handleToggleMarkdown = () => {\n if (!isMarkdownMode) {\n if (view) {\n setInternalMarkdown(serializer.serialize(view.state.doc));\n }\n setIsMarkdownMode(true);\n } else {\n if (view) {\n const newDoc = parser.parse(internalMarkdown);\n if (newDoc) {\n const tr = view.state.tr.replaceWith(0, view.state.doc.content.size, newDoc.content);\n view.dispatch(tr);\n }\n }\n setIsMarkdownMode(false);\n }\n };\n\n const handleMarkdownChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n setInternalMarkdown(e.target.value);\n };\n\n const handleMarkdownBlur = () => {\n const { onMarkdownContentChange, onJsonContentChange } = callbacksRef.current;\n if (onMarkdownContentChange) {\n onMarkdownContentChange(internalMarkdown);\n }\n if (onJsonContentChange) {\n try {\n const newDoc = parser.parse(internalMarkdown);\n if (newDoc) {\n onJsonContentChange(removeClassesFromJson(newDoc.toJSON()) as JSONContent);\n }\n } catch (e) {\n console.warn(\"Could not parse markdown to JSON\", e);\n }\n }\n };\n\n useInjectStyles(\"Editor\", cssStyles);\n\n const callbacksRef = useRef({ onMarkdownContentChange,\nonJsonContentChange });\n useEffect(() => {\n callbacksRef.current = { onMarkdownContentChange,\nonJsonContentChange };\n }, [onMarkdownContentChange, onJsonContentChange]);\n\n const flushChanges = (currentState: EditorState) => {\n const { onMarkdownContentChange, onJsonContentChange } = callbacksRef.current;\n if (onMarkdownContentChange) {\n try {\n const markdown = serializer.serialize(currentState.doc);\n onMarkdownContentChange(markdown);\n } catch (e) {\n console.warn(\"[RichTextEditor] Could not serialize editor state to markdown:\", e);\n }\n }\n if (onJsonContentChange) {\n const jsonContent = removeClassesFromJson(currentState.doc.toJSON()) as JSONContent;\n onJsonContentChange(jsonContent);\n }\n };\n\n const { state, view, editorRef } = useProseMirror({\n initialContent: content,\n editable: !disabled,\n handleImageUpload,\n resolveImageSrc\n });\n\n // When `version` changes externally (e.g. form discard/reset), re-parse the\n // `content` prop and replace the ProseMirror document so the editor reflects\n // the reverted value.\n const versionRef = useRef(version);\n useEffect(() => {\n if (versionRef.current === version) return; // skip initial render\n versionRef.current = version;\n if (!view) return;\n try {\n const newDoc = typeof content === \"string\"\n ? parser.parse(content ?? \"\")\n : content\n ? schema.nodeFromJSON(content)\n : schema.node(\"doc\", null, [schema.node(\"paragraph\")]);\n if (newDoc) {\n const tr = view.state.tr.replaceWith(0, view.state.doc.content.size, newDoc.content);\n view.dispatch(tr);\n }\n } catch (e) {\n console.warn(\"[RichTextEditor] Could not reset editor content:\", e);\n }\n // Also reset raw-markdown textarea if the user is in source mode\n if (isMarkdownMode) {\n setInternalMarkdown(typeof content === \"string\" ? content : \"\");\n }\n // Reset the settling window so the replacement dispatch above is NOT\n // treated as a user edit (which would fire onChange back to the form).\n mountTimeRef.current = Date.now();\n hasUserEditedRef.current = false;\n }, [version]);\n\n const doc = state?.doc;\n // Use a time-based settling window instead of a single-skip flag.\n // The trailingNodePlugin fires appendTransaction on mount (adding a trailing\n // paragraph), which creates a second doc change after the initial parse.\n // A single-skip flag misses that second change. Instead, we skip ALL doc\n // changes within the first 500ms after the view is created.\n const mountTimeRef = useRef(Date.now());\n const hasUserEditedRef = useRef(false);\n useEffect(() => {\n if (!state) return;\n // Skip all doc changes during the initial settling window (500ms).\n // This covers both the initial parse AND the trailingNodePlugin's\n // appendTransaction that adds a trailing paragraph.\n const elapsed = Date.now() - mountTimeRef.current;\n if (elapsed < 500 && !hasUserEditedRef.current) {\n return;\n }\n hasUserEditedRef.current = true;\n const timeout = setTimeout(() => {\n flushChanges(state);\n }, 250);\n return () => clearTimeout(timeout);\n }, [doc]);\n\n useEffect(() => {\n if (!view) return;\n const dom = view.dom;\n const handleBlur = () => {\n // Don't flush during the initial settling window — the editor\n // hasn't been interacted with yet, and the serialized output\n // may differ from the input due to parse→serialize normalization.\n if (!hasUserEditedRef.current) {\n const elapsed = Date.now() - mountTimeRef.current;\n if (elapsed < 500) return;\n }\n flushChanges(view.state);\n };\n dom.addEventListener(\"blur\", handleBlur);\n return () => dom.removeEventListener(\"blur\", handleBlur);\n }, [view]);\n\n\n useEffect(() => {\n if (view) {\n if (highlight) {\n highlightCommands.toggleAutocompleteHighlight(highlight)(view.state, view.dispatch);\n } else {\n highlightCommands.removeAutocompleteHighlight()(view.state, view.dispatch);\n }\n }\n }, [highlight?.from, highlight?.to]);\n\n const proseClass = proseClasses[textSize];\n\n\n return (\n <div className=\"relative min-h-[200px] w-full flex flex-col\">\n <button\n type=\"button\"\n onClick={handleToggleMarkdown}\n title={isMarkdownMode ? \"Switch to Visual Editor\" : \"Switch to Markdown\"}\n className=\"absolute top-2 right-2 z-10 px-2 py-1 text-xs font-medium text-surface-400 hover:text-surface-700 dark:text-surface-600 dark:hover:text-surface-300 transition-colors opacity-50 hover:opacity-100 bg-transparent rounded\"\n >\n {isMarkdownMode ? \"Visual\" : \"Markdown\"}\n </button>\n\n <ProseMirrorContext.Provider value={useMemo(() => ({ state,\nview }), [state, view])}>\n\n <div style={{ display: isMarkdownMode ? \"none\" : \"flex\" }} className=\"flex-1 flex flex-col\">\n <div\n ref={editorRef}\n onClick={(e) => {\n // If the click landed on the wrapper padding (not on the ProseMirror\n // content), focus the editor and place the cursor at the nearest position.\n if (view && e.target === e.currentTarget) {\n view.focus();\n // Place cursor at end of the document\n const end = view.state.doc.content.size;\n const tr = view.state.tr.setSelection(\n Selection.near(view.state.doc.resolve(end), -1)\n );\n view.dispatch(tr);\n }\n }}\n className={cls(\"relative prose dark:prose-invert cursor-text flex-1\", proseClass, \"prose-headings:font-title prose-headings:font-normal prose-strong:font-semibold prose-code:font-normal prose-blockquote:font-normal prose-a:font-normal font-default focus:outline-none max-w-full py-4\")}\n />\n\n {view && (\n <>\n <EditorBubble\n options={{\n placement: \"top\",\n offset: 6\n }}\n className={cls(\"flex w-fit max-w-[90vw] h-10 overflow-hidden rounded border bg-surface-card shadow\", defaultBorderMixin)}\n >\n <NodeSelector portalContainer={editorRef.current} open={openNode} onOpenChange={setOpenNode}/>\n <Separator orientation=\"vertical\"/>\n <LinkSelector open={openLink} onOpenChange={setOpenLink}/>\n <Separator orientation=\"vertical\"/>\n <TextButtons/>\n </EditorBubble>\n\n <ImageBubble\n options={{\n placement: \"bottom\",\n offset: 6\n }}\n />\n <TableBubble/>\n </>\n )}\n\n <SlashCommandMenu upload={handleImageUpload} aiController={aiController}/>\n </div>\n\n {isMarkdownMode && (\n <TextareaAutosize\n value={internalMarkdown}\n onChange={handleMarkdownChange}\n onBlur={handleMarkdownBlur}\n className={cls(\n \"w-full h-full min-h-[200px] px-12 py-4 bg-transparent resize-none font-mono focus:ring-0\",\n proseClass\n )}\n style={{\n tabSize: 4,\n outline: \"none\",\n border: \"none\",\n boxShadow: \"none\"\n }}\n />\n )}\n\n </ProseMirrorContext.Provider>\n </div>\n );\n};\n\n\nconst cssStyles = `\n.ProseMirror {\n box-shadow: none !important;\n padding-left: 2rem;\n padding-right: 2rem;\n min-height: 100%;\n /* What prosemirror-view's style/prosemirror.css sets on its root: the\n document's spaces are read back from the DOM, so they must not collapse. */\n word-wrap: break-word;\n white-space: pre-wrap;\n white-space: break-spaces;\n font-variant-ligatures: none;\n font-feature-settings: \"liga\" 0;\n}\n.ProseMirror pre {\n white-space: pre-wrap;\n}\n.ProseMirror .is-editor-empty:first-child::before {\n content: attr(data-placeholder);\n float: left;\n color: rgb(100 116 139); /* 500 */\n pointer-events: none;\n height: 0;\n}\n.ProseMirror .is-empty::before {\n content: attr(data-placeholder);\n float: left;\n color: rgb(100 116 139); /* 500 */\n pointer-events: none;\n height: 0;\n}\n\n[data-theme=\"dark\"] .ProseMirror .is-empty::before {\n color: rgb(100 116 139); /* 500 */\n}\n\n.is-empty {\n cursor: text;\n color: rgb(100 116 139); /* 500 */\n}\n\n.ProseMirror img {\n transition: filter 0.1s ease-in-out;\n}\n.ProseMirror img:hover {\n cursor: pointer;\n filter: brightness(90%);\n}\n.ProseMirror img.ProseMirror-selectednode {\n filter: brightness(90%);\n box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000) !important;\n}\n\nul[data-type=\"taskList\"] li > label {\n margin-right: 0.2rem;\n user-select: none;\n}\n@media screen and (max-width: 768px) {\n ul[data-type=\"taskList\"] li > label {\n margin-right: 0.5rem;\n }\n}\n[data-theme=\"dark\"] ul[data-type=\"taskList\"] li > label input[type=\"checkbox\"] {\n background-color: rgb(30 41 59);\n border: 2px solid #666;\n}\n[data-theme=\"dark\"] ul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]:hover { background-color: rgb(51 65 85); }\n[data-theme=\"dark\"] ul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]:active { background-color: rgb(71 85 105); }\nul[data-type=\"taskList\"] li > label input[type=\"checkbox\"] {\n -webkit-appearance: none;\n appearance: none;\n background-color: white;\n margin: 0;\n cursor: pointer;\n width: 1.2em;\n height: 1.2em;\n position: relative;\n top: 5px;\n border: 2px solid #777;\n border-radius: 0.25em;\n margin-right: 0.3rem;\n display: grid;\n place-content: center;\n}\nul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]:hover { background-color: rgb(241 245 249); }\nul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]:active { background-color: rgb(226 232 240); }\nul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]::before {\n content: \"\";\n width: 0.65em;\n height: 0.65em;\n transform: scale(0);\n transition: 120ms transform ease-in-out;\n box-shadow: inset 1em 1em;\n transform-origin: center;\n clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%);\n}\nul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]:checked::before { transform: scale(1); }\n\n[data-theme=\"dark\"] ul[data-type=\"taskList\"] li[data-checked=\"true\"] > div > p {\n color: rgb(226 232 240);\n text-decoration: line-through;\n text-decoration-thickness: 2px;\n}\nul[data-type=\"taskList\"] li[data-checked=\"true\"] > div > p {\n color: rgb(51 65 85);\n text-decoration: line-through;\n text-decoration-thickness: 2px;\n}\n.tippy-box { max-width: 400px !important; }\n\n.ProseMirror:not(.dragging) .ProseMirror-selectednode {\n background-color: rgb(219 234 254);\n transition: background-color 0.2s;\n box-shadow: none;\n}\n[data-theme=\"dark\"] .ProseMirror:not(.dragging) .ProseMirror-selectednode {\n background-color: rgb(51 65 85);\n}\n.prose-base table p { margin: 0; }\n\n.drag-handle {\n position: absolute;\n opacity: 1;\n transition: opacity ease-in 0.2s;\n border-radius: 0.25rem;\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10' style='fill: rgba(128, 128, 128, 0.9)'%3E%3Cpath d='M3,2 C2.44771525,2 2,1.55228475 2,1 C2,0.44771525 2.44771525,0 3,0 C3.55228475,0 4,0.44771525 4,1 C4,1.55228475 3.55228475,2 3,2 Z M3,6 C2.44771525,6 2,5.55228475 2,5 C2,4.44771525 2.44771525,4 3,4 C3.55228475,4 4,4.44771525 4,5 C4,5.55228475 3.55228475,6 3,6 Z M3,10 C2.44771525,10 2,9.55228475 2,9 C2,8.44771525 2.44771525,8 3,8 C3.55228475,8 4,8.44771525 4,9 C4,9.55228475 3.55228475,10 3,10 Z M7,2 C6.44771525,2 6,1.55228475 6,1 C6,0.44771525 6.44771525,0 7,0 C7.55228475,0 8,0.44771525 8,1 C8,1.55228475 7.55228475,2 7,2 Z M7,6 C6.44771525,6 6,5.55228475 6,5 C6,4.44771525 6.44771525,4 7,4 C7.55228475,4 8,4.44771525 8,5 C8,5.55228475 7.55228475,6 7,6 Z M7,10 C6.44771525,10 6,9.55228475 6,9 C6,8.44771525 6.44771525,8 7,8 C7,8.44771525 7,9 7,9 C7,9.55228475 7,10 7,10 Z'%3E%3C/path%3E%3C/svg%3E\");\n background-size: calc(0.5em + 0.375rem) calc(0.5em + 0.375rem);\n background-repeat: no-repeat;\n background-position: center;\n width: 1.2rem;\n height: 1.5rem;\n z-index: 100;\n cursor: grab;\n}\n.drag-handle::before {\n content: '';\n position: absolute;\n top: -10px;\n bottom: -10px;\n left: -20px; \n right: 0px;\n z-index: -1;\n}\n.drag-handle:hover { background-color: rgb(241 245 249); transition: background-color 0.2s; }\n.drag-handle:active { background-color: rgb(226 232 240); transition: background-color 0.2s; }\n.drag-handle.hide { opacity: 0; pointer-events: none; }\n@media screen and (max-width: 600px) { .drag-handle { display: none; pointer-events: none; } }\n[data-theme=\"dark\"] .drag-handle:hover { background-color: rgb(51 65 85); }\n[data-theme=\"dark\"] .drag-handle:active { background-color: rgb(51 65 85); }\n.prosemirror-dropcursor-block {\n background-color: var(--color-surface-accent-600);\n}\n[data-theme=\"dark\"] .prosemirror-dropcursor-block {\n background-color: var(--color-surface-accent-300);\n}\n\n.ProseMirror table {\n border-collapse: separate;\n border-spacing: 0;\n table-layout: fixed;\n width: 100%;\n margin: 1em 0;\n overflow: hidden;\n border-radius: 0.375rem;\n border: 1px solid #e5e7eb;\n}\n[data-theme=\"dark\"] .ProseMirror table {\n border-color: #374151;\n}\n\n.ProseMirror td, .ProseMirror th {\n min-width: 1em;\n padding: 8px 10px;\n vertical-align: top;\n box-sizing: border-box;\n position: relative;\n border-right: 1px solid #e5e7eb;\n border-bottom: 1px solid #e5e7eb;\n}\n[data-theme=\"dark\"] .ProseMirror td, [data-theme=\"dark\"] .ProseMirror th {\n border-right-color: #374151;\n border-bottom-color: #374151;\n}\n\n.ProseMirror tr:last-child td, .ProseMirror tr:last-child th {\n border-bottom: none;\n}\n.ProseMirror th:last-child, .ProseMirror td:last-child {\n border-right: none;\n}\n\n.ProseMirror td {\n background-color: transparent;\n}\n\n.ProseMirror th {\n font-weight: 600;\n text-align: left;\n background-color: #f3f4f6;\n color: #374151;\n}\n[data-theme=\"dark\"] .ProseMirror td {\n background-color: transparent;\n}\n[data-theme=\"dark\"] .ProseMirror th {\n background-color: rgba(255, 255, 255, 0.05);\n color: #d1d5db;\n}\n`;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA8CA,IAAM,eAAe;CACnB,MAAM;CACN,QAAQ;CACR,MAAM;AACR;AAEA,IAAa,kBAAkB,EAC7B,SACA,qBACA,qBACA,yBACA,SACA,WAAW,QACX,WACA,mBACA,iBACA,cACA,eACyB;CAEzB,MAAM,EAAE,MAAM,eAAe;CAE7B,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAC9C,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAE9C,MAAM,CAAC,gBAAgB,qBAAqB,SAAS,KAAK;CAC1D,MAAM,CAAC,kBAAkB,uBAAuB,SAAiB,EAAE;CAEnE,gBAAgB;EACd,IAAI,CAAC,gBAAgB;EACrB,MAAM,UAAU,iBAAiB;GAC/B,IAAI,aAAa,QAAQ,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D;SAAc,iBAAiB,UAAU;SAAS,MAAM;SAAU,cAAc;QAAa,CAAA;QAC7F,oBAAC,WAAD,EAAW,aAAY,WAAW,CAAA;QAClC,oBAAC,cAAD;SAAc,MAAM;SAAU,cAAc;QAAa,CAAA;QACzD,oBAAC,WAAD,EAAW,aAAY,WAAW,CAAA;QAClC,oBAAC,aAAD,CAAa,CAAA;OACD;;MAEd,oBAAC,aAAD,EACG,SAAS;OACR,WAAW;OACX,QAAQ;MACV,EACD,CAAA;MACD,oBAAC,aAAD,CAAa,CAAA;KACb,EAAA,CAAA;KAGJ,oBAAC,kBAAD;MAAkB,QAAQ;MAAiC;KAAc,CAAA;IACpE;OAEJ,kBACC,oBAAC,kBAAD;IACE,OAAO;IACP,UAAU;IACV,QAAQ;IACR,WAAW,IACT,4FACA,UACF;IACA,OAAO;KACL,SAAS;KACT,SAAS;KACT,QAAQ;KACR,WAAW;IACb;GACD,CAAA,CAGwB;IAC1B;;AAET;AAGA,IAAM,YAAY"}
1
+ {"version":3,"file":"editor.js","names":[],"sources":["../../src/editor/editor.tsx"],"sourcesContent":["\"use client\";\nimport React, { useEffect, useState, useRef, useMemo } from \"react\";\nimport { EditorState, Selection } from \"prosemirror-state\";\nimport { cls, defaultBorderMixin, Separator, TextareaAutosize, useInjectStyles } from \"@rebasepro/ui\";\nimport { useTranslation } from \"@rebasepro/app\";\nimport { EditorBubble, ImageBubble, SlashCommandMenu, TableBubble, type JSONContent } from \"./components\";\nimport { NodeSelector } from \"./selectors/node-selector\";\nimport { LinkSelector } from \"./selectors/link-selector\";\nimport { TextButtons } from \"./selectors/text-buttons\";\nimport { removeClassesFromJson } from \"./utils/remove_classes\";\nimport { parser, serializer } from \"./markdown\";\nimport { EditorAIController } from \"./types\";\nimport { useProseMirror } from \"./hooks/useProseMirror\";\nimport { ProseMirrorContext } from \"./hooks/useProseMirrorContext\";\nimport { highlightCommands } from \"./extensions/HighlightDecorationExtension\";\nimport { schema } from \"./schema\";\n\nexport type CustomEditorComponent = {\n name: string,\n component: React.FC\n};\n\nexport type RichTextEditorTextSize = \"sm\" | \"base\" | \"lg\";\n\n\nexport type RichTextEditorProps = {\n content?: JSONContent | string,\n onMarkdownContentChange?: (content: string) => void,\n onJsonContentChange?: (content: JSONContent | null) => void,\n onHtmlContentChange?: (content: string) => void,\n handleImageUpload: (file: File) => Promise<string>,\n /**\n * Turns an image's stored `src` into a URL to show. `handleImageUpload`\n * returns a `rebase-storage:` reference to keep in the text — a private\n * object's URL expires — and the editor asks this for a URL to display it.\n */\n resolveImageSrc?: (src: string) => Promise<string | null | undefined>,\n version?: number,\n textSize?: RichTextEditorTextSize,\n highlight?: { from: number, to: number },\n aiController?: EditorAIController,\n customComponents?: CustomEditorComponent[];\n disabled?: boolean;\n};\n\n\nconst proseClasses = {\n \"sm\": \"prose-sm\",\n \"base\": \"prose-base\",\n \"lg\": \"prose-lg\"\n}\n\nexport const RichTextEditor = ({\n content,\n onJsonContentChange,\n onHtmlContentChange,\n onMarkdownContentChange,\n version,\n textSize = \"base\",\n highlight,\n handleImageUpload,\n resolveImageSrc,\n aiController,\n disabled\n}: RichTextEditorProps) => {\n\n const { t } = useTranslation();\n\n const [openNode, setOpenNode] = useState(false);\n const [openLink, setOpenLink] = useState(false);\n\n const [isMarkdownMode, setIsMarkdownMode] = useState(false);\n const [internalMarkdown, setInternalMarkdown] = useState<string>(\"\");\n\n useEffect(() => {\n if (!isMarkdownMode) return;\n const timeout = setTimeout(() => {\n if (callbacksRef.current.onMarkdownContentChange) {\n callbacksRef.current.onMarkdownContentChange(internalMarkdown);\n }\n }, 250);\n return () => clearTimeout(timeout);\n }, [internalMarkdown, isMarkdownMode]);\n\n const handleToggleMarkdown = () => {\n if (!isMarkdownMode) {\n if (view) {\n setInternalMarkdown(serializer.serialize(view.state.doc));\n }\n setIsMarkdownMode(true);\n } else {\n if (view) {\n const newDoc = parser.parse(internalMarkdown);\n if (newDoc) {\n const tr = view.state.tr.replaceWith(0, view.state.doc.content.size, newDoc.content);\n view.dispatch(tr);\n }\n }\n setIsMarkdownMode(false);\n }\n };\n\n const handleMarkdownChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n setInternalMarkdown(e.target.value);\n };\n\n const handleMarkdownBlur = () => {\n const { onMarkdownContentChange, onJsonContentChange } = callbacksRef.current;\n if (onMarkdownContentChange) {\n onMarkdownContentChange(internalMarkdown);\n }\n if (onJsonContentChange) {\n try {\n const newDoc = parser.parse(internalMarkdown);\n if (newDoc) {\n onJsonContentChange(removeClassesFromJson(newDoc.toJSON()) as JSONContent);\n }\n } catch (e) {\n console.warn(\"Could not parse markdown to JSON\", e);\n }\n }\n };\n\n useInjectStyles(\"Editor\", cssStyles);\n\n const callbacksRef = useRef({ onMarkdownContentChange,\nonJsonContentChange });\n useEffect(() => {\n callbacksRef.current = { onMarkdownContentChange,\nonJsonContentChange };\n }, [onMarkdownContentChange, onJsonContentChange]);\n\n const flushChanges = (currentState: EditorState) => {\n const { onMarkdownContentChange, onJsonContentChange } = callbacksRef.current;\n if (onMarkdownContentChange) {\n try {\n const markdown = serializer.serialize(currentState.doc);\n onMarkdownContentChange(markdown);\n } catch (e) {\n console.warn(\"[RichTextEditor] Could not serialize editor state to markdown:\", e);\n }\n }\n if (onJsonContentChange) {\n const jsonContent = removeClassesFromJson(currentState.doc.toJSON()) as JSONContent;\n onJsonContentChange(jsonContent);\n }\n };\n\n const { state, view, editorRef } = useProseMirror({\n initialContent: content,\n editable: !disabled,\n handleImageUpload,\n resolveImageSrc\n });\n\n // When `version` changes externally (e.g. form discard/reset), re-parse the\n // `content` prop and replace the ProseMirror document so the editor reflects\n // the reverted value.\n const versionRef = useRef(version);\n useEffect(() => {\n if (versionRef.current === version) return; // skip initial render\n versionRef.current = version;\n if (!view) return;\n try {\n const newDoc = typeof content === \"string\"\n ? parser.parse(content ?? \"\")\n : content\n ? schema.nodeFromJSON(content)\n : schema.node(\"doc\", null, [schema.node(\"paragraph\")]);\n if (newDoc) {\n const tr = view.state.tr.replaceWith(0, view.state.doc.content.size, newDoc.content);\n view.dispatch(tr);\n }\n } catch (e) {\n console.warn(\"[RichTextEditor] Could not reset editor content:\", e);\n }\n // Also reset raw-markdown textarea if the user is in source mode\n if (isMarkdownMode) {\n setInternalMarkdown(typeof content === \"string\" ? content : \"\");\n }\n // Reset the settling window so the replacement dispatch above is NOT\n // treated as a user edit (which would fire onChange back to the form).\n mountTimeRef.current = Date.now();\n hasUserEditedRef.current = false;\n }, [version]);\n\n const doc = state?.doc;\n // Use a time-based settling window instead of a single-skip flag.\n // The trailingNodePlugin fires appendTransaction on mount (adding a trailing\n // paragraph), which creates a second doc change after the initial parse.\n // A single-skip flag misses that second change. Instead, we skip ALL doc\n // changes within the first 500ms after the view is created.\n const mountTimeRef = useRef(Date.now());\n const hasUserEditedRef = useRef(false);\n useEffect(() => {\n if (!state) return;\n // Skip all doc changes during the initial settling window (500ms).\n // This covers both the initial parse AND the trailingNodePlugin's\n // appendTransaction that adds a trailing paragraph.\n const elapsed = Date.now() - mountTimeRef.current;\n if (elapsed < 500 && !hasUserEditedRef.current) {\n return;\n }\n hasUserEditedRef.current = true;\n const timeout = setTimeout(() => {\n flushChanges(state);\n }, 250);\n return () => clearTimeout(timeout);\n }, [doc]);\n\n useEffect(() => {\n if (!view) return;\n const dom = view.dom;\n const handleBlur = () => {\n // Don't flush during the initial settling window — the editor\n // hasn't been interacted with yet, and the serialized output\n // may differ from the input due to parse→serialize normalization.\n if (!hasUserEditedRef.current) {\n const elapsed = Date.now() - mountTimeRef.current;\n if (elapsed < 500) return;\n }\n flushChanges(view.state);\n };\n dom.addEventListener(\"blur\", handleBlur);\n return () => dom.removeEventListener(\"blur\", handleBlur);\n }, [view]);\n\n\n useEffect(() => {\n if (view) {\n if (highlight) {\n highlightCommands.toggleAutocompleteHighlight(highlight)(view.state, view.dispatch);\n } else {\n highlightCommands.removeAutocompleteHighlight()(view.state, view.dispatch);\n }\n }\n }, [highlight?.from, highlight?.to]);\n\n const proseClass = proseClasses[textSize];\n\n\n return (\n <div className=\"relative min-h-[200px] w-full flex flex-col\">\n <button\n type=\"button\"\n onClick={handleToggleMarkdown}\n title={isMarkdownMode ? \"Switch to Visual Editor\" : \"Switch to Markdown\"}\n className=\"absolute top-2 right-2 z-10 px-2 py-1 text-xs font-medium text-surface-400 hover:text-surface-700 dark:text-surface-600 dark:hover:text-surface-300 transition-colors opacity-50 hover:opacity-100 bg-transparent rounded\"\n >\n {isMarkdownMode ? \"Visual\" : \"Markdown\"}\n </button>\n\n <ProseMirrorContext.Provider value={useMemo(() => ({ state,\nview }), [state, view])}>\n\n <div style={{ display: isMarkdownMode ? \"none\" : \"flex\" }} className=\"flex-1 flex flex-col\">\n <div\n ref={editorRef}\n onClick={(e) => {\n // If the click landed on the wrapper padding (not on the ProseMirror\n // content), focus the editor and place the cursor at the nearest position.\n if (view && e.target === e.currentTarget) {\n view.focus();\n // Place cursor at end of the document\n const end = view.state.doc.content.size;\n const tr = view.state.tr.setSelection(\n Selection.near(view.state.doc.resolve(end), -1)\n );\n view.dispatch(tr);\n }\n }}\n className={cls(\"relative prose dark:prose-invert cursor-text flex-1\", proseClass, \"prose-headings:font-title prose-headings:font-normal prose-strong:font-semibold prose-code:font-normal prose-blockquote:font-normal prose-a:font-normal font-default focus:outline-none max-w-full py-4\")}\n />\n\n {view && (\n <>\n <EditorBubble\n options={{\n placement: \"top\",\n offset: 6\n }}\n className={cls(\"flex w-fit max-w-[90vw] h-10 overflow-hidden rounded border bg-surface-card shadow\", defaultBorderMixin)}\n >\n <NodeSelector portalContainer={editorRef.current} open={openNode} onOpenChange={setOpenNode}/>\n <Separator orientation=\"vertical\"/>\n <LinkSelector open={openLink} onOpenChange={setOpenLink}/>\n <Separator orientation=\"vertical\"/>\n <TextButtons/>\n </EditorBubble>\n\n <ImageBubble\n options={{\n placement: \"bottom\",\n offset: 6\n }}\n />\n <TableBubble/>\n </>\n )}\n\n <SlashCommandMenu upload={handleImageUpload} aiController={aiController}/>\n </div>\n\n {isMarkdownMode && (\n <TextareaAutosize\n value={internalMarkdown}\n onChange={handleMarkdownChange}\n onBlur={handleMarkdownBlur}\n className={cls(\n \"w-full h-full min-h-[200px] px-12 py-4 bg-transparent resize-none font-mono focus:ring-0\",\n proseClass\n )}\n style={{\n tabSize: 4,\n outline: \"none\",\n border: \"none\",\n boxShadow: \"none\"\n }}\n />\n )}\n\n </ProseMirrorContext.Provider>\n </div>\n );\n};\n\n\nconst cssStyles = `\n.ProseMirror {\n box-shadow: none !important;\n padding-left: 2rem;\n padding-right: 2rem;\n min-height: 100%;\n /* What prosemirror-view's style/prosemirror.css sets on its root: the\n document's spaces are read back from the DOM, so they must not collapse. */\n word-wrap: break-word;\n white-space: pre-wrap;\n white-space: break-spaces;\n font-variant-ligatures: none;\n font-feature-settings: \"liga\" 0;\n}\n.ProseMirror pre {\n white-space: pre-wrap;\n}\n.ProseMirror .is-editor-empty:first-child::before {\n content: attr(data-placeholder);\n float: left;\n color: rgb(100 116 139); /* 500 */\n pointer-events: none;\n height: 0;\n}\n.ProseMirror .is-empty::before {\n content: attr(data-placeholder);\n float: left;\n color: rgb(100 116 139); /* 500 */\n pointer-events: none;\n height: 0;\n}\n\n[data-theme=\"dark\"] .ProseMirror .is-empty::before {\n color: rgb(100 116 139); /* 500 */\n}\n\n.is-empty {\n cursor: text;\n color: rgb(100 116 139); /* 500 */\n}\n\n.ProseMirror img {\n transition: filter 0.1s ease-in-out;\n}\n.ProseMirror img:hover {\n cursor: pointer;\n filter: brightness(90%);\n}\n.ProseMirror img.ProseMirror-selectednode {\n filter: brightness(90%);\n box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000) !important;\n}\n\nul[data-type=\"taskList\"] li > label {\n margin-right: 0.2rem;\n user-select: none;\n}\n@media screen and (max-width: 768px) {\n ul[data-type=\"taskList\"] li > label {\n margin-right: 0.5rem;\n }\n}\n[data-theme=\"dark\"] ul[data-type=\"taskList\"] li > label input[type=\"checkbox\"] {\n background-color: rgb(30 41 59);\n border: 2px solid #62676e;\n}\n[data-theme=\"dark\"] ul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]:hover { background-color: rgb(51 65 85); }\n[data-theme=\"dark\"] ul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]:active { background-color: rgb(71 85 105); }\nul[data-type=\"taskList\"] li > label input[type=\"checkbox\"] {\n -webkit-appearance: none;\n appearance: none;\n background-color: white;\n margin: 0;\n cursor: pointer;\n width: 1.2em;\n height: 1.2em;\n position: relative;\n top: 5px;\n border: 2px solid #72787f;\n border-radius: 0.25em;\n margin-right: 0.3rem;\n display: grid;\n place-content: center;\n}\nul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]:hover { background-color: rgb(241 245 249); }\nul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]:active { background-color: rgb(226 232 240); }\nul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]::before {\n content: \"\";\n width: 0.65em;\n height: 0.65em;\n transform: scale(0);\n transition: 120ms transform ease-in-out;\n box-shadow: inset 1em 1em;\n transform-origin: center;\n clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%);\n}\nul[data-type=\"taskList\"] li > label input[type=\"checkbox\"]:checked::before { transform: scale(1); }\n\n[data-theme=\"dark\"] ul[data-type=\"taskList\"] li[data-checked=\"true\"] > div > p {\n color: rgb(226 232 240);\n text-decoration: line-through;\n text-decoration-thickness: 2px;\n}\nul[data-type=\"taskList\"] li[data-checked=\"true\"] > div > p {\n color: rgb(51 65 85);\n text-decoration: line-through;\n text-decoration-thickness: 2px;\n}\n.tippy-box { max-width: 400px !important; }\n\n.ProseMirror:not(.dragging) .ProseMirror-selectednode {\n background-color: rgb(219 234 254);\n transition: background-color 0.2s;\n box-shadow: none;\n}\n[data-theme=\"dark\"] .ProseMirror:not(.dragging) .ProseMirror-selectednode {\n background-color: rgb(51 65 85);\n}\n.prose-base table p { margin: 0; }\n\n.drag-handle {\n position: absolute;\n opacity: 1;\n transition: opacity ease-in 0.2s;\n border-radius: 0.25rem;\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10' style='fill: rgba(128, 128, 128, 0.9)'%3E%3Cpath d='M3,2 C2.44771525,2 2,1.55228475 2,1 C2,0.44771525 2.44771525,0 3,0 C3.55228475,0 4,0.44771525 4,1 C4,1.55228475 3.55228475,2 3,2 Z M3,6 C2.44771525,6 2,5.55228475 2,5 C2,4.44771525 2.44771525,4 3,4 C3.55228475,4 4,4.44771525 4,5 C4,5.55228475 3.55228475,6 3,6 Z M3,10 C2.44771525,10 2,9.55228475 2,9 C2,8.44771525 2.44771525,8 3,8 C3.55228475,8 4,8.44771525 4,9 C4,9.55228475 3.55228475,10 3,10 Z M7,2 C6.44771525,2 6,1.55228475 6,1 C6,0.44771525 6.44771525,0 7,0 C7.55228475,0 8,0.44771525 8,1 C8,1.55228475 7.55228475,2 7,2 Z M7,6 C6.44771525,6 6,5.55228475 6,5 C6,4.44771525 6.44771525,4 7,4 C7.55228475,4 8,4.44771525 8,5 C8,5.55228475 7.55228475,6 7,6 Z M7,10 C6.44771525,10 6,9.55228475 6,9 C6,8.44771525 6.44771525,8 7,8 C7,8.44771525 7,9 7,9 C7,9.55228475 7,10 7,10 Z'%3E%3C/path%3E%3C/svg%3E\");\n background-size: calc(0.5em + 0.375rem) calc(0.5em + 0.375rem);\n background-repeat: no-repeat;\n background-position: center;\n width: 1.2rem;\n height: 1.5rem;\n z-index: 100;\n cursor: grab;\n}\n.drag-handle::before {\n content: '';\n position: absolute;\n top: -10px;\n bottom: -10px;\n left: -20px; \n right: 0px;\n z-index: -1;\n}\n.drag-handle:hover { background-color: rgb(241 245 249); transition: background-color 0.2s; }\n.drag-handle:active { background-color: rgb(226 232 240); transition: background-color 0.2s; }\n.drag-handle.hide { opacity: 0; pointer-events: none; }\n@media screen and (max-width: 600px) { .drag-handle { display: none; pointer-events: none; } }\n[data-theme=\"dark\"] .drag-handle:hover { background-color: rgb(51 65 85); }\n[data-theme=\"dark\"] .drag-handle:active { background-color: rgb(51 65 85); }\n.prosemirror-dropcursor-block {\n background-color: var(--color-surface-accent-600);\n}\n[data-theme=\"dark\"] .prosemirror-dropcursor-block {\n background-color: var(--color-surface-accent-300);\n}\n\n.ProseMirror table {\n border-collapse: separate;\n border-spacing: 0;\n table-layout: fixed;\n width: 100%;\n margin: 1em 0;\n overflow: hidden;\n border-radius: 0.375rem;\n border: 1px solid #e5e7eb;\n}\n[data-theme=\"dark\"] .ProseMirror table {\n border-color: #374151;\n}\n\n.ProseMirror td, .ProseMirror th {\n min-width: 1em;\n padding: 8px 10px;\n vertical-align: top;\n box-sizing: border-box;\n position: relative;\n border-right: 1px solid #e5e7eb;\n border-bottom: 1px solid #e5e7eb;\n}\n[data-theme=\"dark\"] .ProseMirror td, [data-theme=\"dark\"] .ProseMirror th {\n border-right-color: #374151;\n border-bottom-color: #374151;\n}\n\n.ProseMirror tr:last-child td, .ProseMirror tr:last-child th {\n border-bottom: none;\n}\n.ProseMirror th:last-child, .ProseMirror td:last-child {\n border-right: none;\n}\n\n.ProseMirror td {\n background-color: transparent;\n}\n\n.ProseMirror th {\n font-weight: 600;\n text-align: left;\n background-color: #f3f4f6;\n color: #374151;\n}\n[data-theme=\"dark\"] .ProseMirror td {\n background-color: transparent;\n}\n[data-theme=\"dark\"] .ProseMirror th {\n background-color: rgba(255, 255, 255, 0.05);\n color: #d1d5db;\n}\n`;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA8CA,IAAM,eAAe;CACnB,MAAM;CACN,QAAQ;CACR,MAAM;AACR;AAEA,IAAa,kBAAkB,EAC7B,SACA,qBACA,qBACA,yBACA,SACA,WAAW,QACX,WACA,mBACA,iBACA,cACA,eACyB;CAEzB,MAAM,EAAE,MAAM,eAAe;CAE7B,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAC9C,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAE9C,M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