tempest-react-sdk 0.66.0 → 0.67.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/BottomSheet/BottomSheet.cjs +1 -1
- package/dist/components/BottomSheet/BottomSheet.cjs.map +1 -1
- package/dist/components/BottomSheet/BottomSheet.js +31 -40
- package/dist/components/BottomSheet/BottomSheet.js.map +1 -1
- package/dist/components/Combobox/Combobox.cjs +1 -1
- package/dist/components/Combobox/Combobox.cjs.map +1 -1
- package/dist/components/Combobox/Combobox.js +94 -73
- package/dist/components/Combobox/Combobox.js.map +1 -1
- package/dist/components/Combobox/Combobox.module.cjs +1 -1
- package/dist/components/Combobox/Combobox.module.cjs.map +1 -1
- package/dist/components/Combobox/Combobox.module.js +4 -3
- package/dist/components/Combobox/Combobox.module.js.map +1 -1
- package/dist/components/ContextMenu/ContextMenu.cjs +1 -1
- package/dist/components/ContextMenu/ContextMenu.cjs.map +1 -1
- package/dist/components/ContextMenu/ContextMenu.js +80 -83
- package/dist/components/ContextMenu/ContextMenu.js.map +1 -1
- package/dist/components/Drawer/Drawer.cjs +1 -1
- package/dist/components/Drawer/Drawer.cjs.map +1 -1
- package/dist/components/Drawer/Drawer.js +43 -46
- package/dist/components/Drawer/Drawer.js.map +1 -1
- package/dist/components/DropdownMenu/DropdownMenu.cjs +1 -1
- package/dist/components/DropdownMenu/DropdownMenu.cjs.map +1 -1
- package/dist/components/DropdownMenu/DropdownMenu.js +129 -105
- package/dist/components/DropdownMenu/DropdownMenu.js.map +1 -1
- package/dist/components/DropdownMenu/DropdownMenu.module.cjs +1 -1
- package/dist/components/DropdownMenu/DropdownMenu.module.cjs.map +1 -1
- package/dist/components/DropdownMenu/DropdownMenu.module.js +12 -11
- package/dist/components/DropdownMenu/DropdownMenu.module.js.map +1 -1
- package/dist/components/HoverCard/HoverCard.cjs +1 -1
- package/dist/components/HoverCard/HoverCard.cjs.map +1 -1
- package/dist/components/HoverCard/HoverCard.js +54 -29
- package/dist/components/HoverCard/HoverCard.js.map +1 -1
- package/dist/components/HoverCard/HoverCard.module.cjs +1 -1
- package/dist/components/HoverCard/HoverCard.module.cjs.map +1 -1
- package/dist/components/HoverCard/HoverCard.module.js +4 -3
- package/dist/components/HoverCard/HoverCard.module.js.map +1 -1
- package/dist/components/Lightbox/Lightbox.cjs +1 -1
- package/dist/components/Lightbox/Lightbox.cjs.map +1 -1
- package/dist/components/Lightbox/Lightbox.js +86 -89
- package/dist/components/Lightbox/Lightbox.js.map +1 -1
- package/dist/components/Menubar/Menubar.cjs +1 -1
- package/dist/components/Menubar/Menubar.cjs.map +1 -1
- package/dist/components/Menubar/Menubar.js +86 -65
- package/dist/components/Menubar/Menubar.js.map +1 -1
- package/dist/components/Menubar/Menubar.module.cjs +1 -1
- package/dist/components/Menubar/Menubar.module.cjs.map +1 -1
- package/dist/components/Menubar/Menubar.module.js +4 -3
- package/dist/components/Menubar/Menubar.module.js.map +1 -1
- package/dist/components/Modal/Modal.cjs +1 -1
- package/dist/components/Modal/Modal.cjs.map +1 -1
- package/dist/components/Modal/Modal.js +44 -51
- package/dist/components/Modal/Modal.js.map +1 -1
- package/dist/components/MultiSelect/MultiSelect.cjs +1 -1
- package/dist/components/MultiSelect/MultiSelect.cjs.map +1 -1
- package/dist/components/MultiSelect/MultiSelect.js +113 -96
- package/dist/components/MultiSelect/MultiSelect.js.map +1 -1
- package/dist/components/MultiSelect/MultiSelect.module.cjs +1 -1
- package/dist/components/MultiSelect/MultiSelect.module.cjs.map +1 -1
- package/dist/components/MultiSelect/MultiSelect.module.js +4 -3
- package/dist/components/MultiSelect/MultiSelect.module.js.map +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.cjs +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.cjs.map +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.js +83 -61
- package/dist/components/NavigationMenu/NavigationMenu.js.map +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.module.cjs +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.module.cjs.map +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.module.js +4 -3
- package/dist/components/NavigationMenu/NavigationMenu.module.js.map +1 -1
- package/dist/components/Popover/Popover.cjs +1 -1
- package/dist/components/Popover/Popover.cjs.map +1 -1
- package/dist/components/Popover/Popover.js +57 -36
- package/dist/components/Popover/Popover.js.map +1 -1
- package/dist/components/Popover/Popover.module.cjs +1 -1
- package/dist/components/Popover/Popover.module.cjs.map +1 -1
- package/dist/components/Popover/Popover.module.js +7 -6
- package/dist/components/Popover/Popover.module.js.map +1 -1
- package/dist/components/Portal/anchor-position.cjs +2 -0
- package/dist/components/Portal/anchor-position.cjs.map +1 -0
- package/dist/components/Portal/anchor-position.js +99 -0
- package/dist/components/Portal/anchor-position.js.map +1 -0
- package/dist/components/Portal/escape-layer.cjs +2 -0
- package/dist/components/Portal/escape-layer.cjs.map +1 -0
- package/dist/components/Portal/escape-layer.js +30 -0
- package/dist/components/Portal/escape-layer.js.map +1 -0
- package/dist/components/Portal/tab-bridge.cjs +2 -0
- package/dist/components/Portal/tab-bridge.cjs.map +1 -0
- package/dist/components/Portal/tab-bridge.js +39 -0
- package/dist/components/Portal/tab-bridge.js.map +1 -0
- package/dist/components/Tooltip/Tooltip.cjs +1 -1
- package/dist/components/Tooltip/Tooltip.cjs.map +1 -1
- package/dist/components/Tooltip/Tooltip.js +43 -29
- package/dist/components/Tooltip/Tooltip.js.map +1 -1
- package/dist/components/Tooltip/Tooltip.module.cjs +1 -1
- package/dist/components/Tooltip/Tooltip.module.cjs.map +1 -1
- package/dist/components/Tooltip/Tooltip.module.js +4 -3
- package/dist/components/Tooltip/Tooltip.module.js.map +1 -1
- package/dist/hooks/use-focus-trap.cjs +1 -1
- package/dist/hooks/use-focus-trap.cjs.map +1 -1
- package/dist/hooks/use-focus-trap.js +2 -2
- package/dist/hooks/use-focus-trap.js.map +1 -1
- package/dist/hooks/use-sortable.cjs +1 -1
- package/dist/hooks/use-sortable.cjs.map +1 -1
- package/dist/hooks/use-sortable.js +3 -3
- package/dist/hooks/use-sortable.js.map +1 -1
- package/dist/http/describe-api-error.cjs +1 -1
- package/dist/http/describe-api-error.cjs.map +1 -1
- package/dist/http/describe-api-error.js +4 -2
- package/dist/http/describe-api-error.js.map +1 -1
- package/dist/styles/actions.css +3 -0
- package/dist/styles/advanced.css +1 -0
- package/dist/styles/component/Combobox.css +1 -0
- package/dist/styles/component/DropdownMenu.css +1 -0
- package/dist/styles/component/HoverCard.css +1 -0
- package/dist/styles/component/Menubar.css +1 -0
- package/dist/styles/component/MultiSelect.css +1 -0
- package/dist/styles/component/NavigationMenu.css +1 -0
- package/dist/styles/component/Popover.css +1 -0
- package/dist/styles/component/Tooltip.css +1 -0
- package/dist/styles/forms.css +2 -0
- package/dist/styles/navigation.css +2 -0
- package/dist/styles.css +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +147 -13
- package/dist/tempest-react-sdk.js +134 -134
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-sortable.cjs","names":[],"sources":["../../src/hooks/use-sortable.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, hook-lines — drag-and-drop with a keyboard path that\n * has to produce the same moves as the pointer path: pointer capture, auto-scroll\n * near the edges, the drop-index maths and the live-region announcements all read\n * one drag state. Two hooks would mean two copies of the index arithmetic, and the\n * two paths silently disagreeing is the bug this exists to prevent.\n */\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from \"react\";\n\n/** Where a dragged item would land if dropped now. */\nexport interface SortableDropTarget {\n /** Index the item started at, within its own group. */\n from: number;\n /** Index it would move to, within the destination group. */\n to: number;\n /**\n * Group the item started in — a Kanban column, for instance. `undefined` for a\n * plain single-list sortable.\n */\n fromGroup?: string;\n /** Destination group. Equal to `fromGroup` when the move stays in one group. */\n toGroup?: string;\n}\n\n/** Props to spread on each sortable item. */\nexport interface SortableItemProps {\n /** Marks the item for hit-testing. */\n \"data-sortable-index\": number;\n /** Group the item belongs to, when the sortable spans several lists. */\n \"data-sortable-group\"?: string;\n /** `true` while this item is the one being moved. */\n \"data-sortable-active\"?: boolean;\n /** Grab handle wiring: starts a pointer drag. */\n onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;\n /** Keyboard reordering — see {@link UseSortableResult}. */\n onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => void;\n /** Puts the item in the tab order so the keyboard path is reachable. */\n tabIndex: number;\n role: \"option\";\n \"aria-roledescription\": string;\n \"aria-selected\": boolean;\n}\n\nexport interface UseSortableOptions {\n /**\n * How many items are in the sortable. Changing it cancels an in-flight drag.\n *\n * With groups, pass the **total** across groups: the number only has to change\n * whenever the indices the drag was based on stop being valid.\n */\n itemCount: number;\n /**\n * Called once, when a move is committed — on pointer release or on a keyboard\n * move. Never called mid-drag, so a controlled list re-renders once instead of\n * on every pointer frame.\n */\n onReorder: (target: SortableDropTarget) => void;\n /** Blocks all interaction. */\n disabled?: boolean;\n /**\n * Description announced for each item, so a screen reader user learns the\n * keyboard contract. Default is in English — override it to localize.\n */\n roleDescription?: string;\n}\n\nexport interface UseSortableResult {\n /** Index being dragged, or `null` when idle. */\n activeIndex: number | null;\n /** Index the item would land on, or `null` when idle. */\n overIndex: number | null;\n /** Group the dragged item came from, when using groups. */\n activeGroup?: string;\n /** Group the item is currently over, when using groups. */\n overGroup?: string;\n /**\n * Spread on each item. Pass `group` when the sortable spans several lists (a\n * Kanban column id), so a drop can land in a different group.\n */\n getItemProps: (index: number, group?: string) => SortableItemProps;\n /**\n * Spread on an **empty** group's drop area, so an item can be moved into a\n * column that has no cards yet — hit-testing works off item rects, and a group\n * with no items has none.\n */\n getEmptyGroupProps: (group: string) => {\n \"data-sortable-group\": string;\n \"data-sortable-empty\": true;\n };\n /** Spread on the list container (`role=\"listbox\"` + a label of your own). */\n getListProps: () => { role: \"listbox\"; \"aria-orientation\": \"vertical\" };\n /** Abort the current drag without reordering. */\n cancel: () => void;\n /**\n * Callback ref for the element that contains the sortable items — hit-testing\n * searches inside it.\n *\n * Named `setContainer` rather than `ref` because it is a **callback**, not a ref\n * object: `ref={sortable.setContainer}`. The old name also read as a readable\n * ref to the React Compiler rules, which flagged every consumer.\n */\n setContainer: (node: HTMLElement | null) => void;\n}\n\n/** Reorder helper: move `from` to `to`, returning a new array. */\nexport function moveItem<T>(items: T[], from: number, to: number): T[] {\n if (from === to || from < 0 || to < 0 || from >= items.length || to >= items.length) {\n return items;\n }\n const next = items.slice();\n const [moved] = next.splice(from, 1);\n next.splice(to, 0, moved);\n return next;\n}\n\n/** A hit-test result: the item (or empty group) under the pointer. */\ninterface HitTarget {\n index: number;\n group?: string;\n}\n\n/**\n * Find the sortable slot under a viewport point.\n *\n * Items are tried first; an empty group's drop area is only considered when no item\n * matched, since an empty column is a fallback target rather than a competing one.\n */\nfunction targetAtPoint(container: HTMLElement | null, x: number, y: number): HitTarget | null {\n if (!container) return null;\n const inside = (element: HTMLElement): boolean => {\n const rect = element.getBoundingClientRect();\n return y >= rect.top && y <= rect.bottom && x >= rect.left && x <= rect.right;\n };\n\n for (const item of Array.from(\n container.querySelectorAll<HTMLElement>(\"[data-sortable-index]\"),\n )) {\n if (!inside(item)) continue;\n const index = Number(item.dataset.sortableIndex);\n if (Number.isNaN(index)) return null;\n return { index, group: item.dataset.sortableGroup };\n }\n\n for (const empty of Array.from(\n container.querySelectorAll<HTMLElement>(\"[data-sortable-empty]\"),\n )) {\n if (inside(empty)) return { index: 0, group: empty.dataset.sortableGroup };\n }\n\n return null;\n}\n\n/**\n * Drag-to-reorder for a list, with a **keyboard path of equal standing**.\n *\n * Pointer events cover mouse, touch and stylus through one code path, and pointer\n * capture keeps the drag alive when the pointer leaves the item. `Space` picks an\n * item up, the arrows move it, `Space`/`Enter` drops it and `Escape` cancels —\n * because a reorder that only works by dragging excludes keyboard users\n * completely, which is where most drag-and-drop implementations fail.\n *\n * The hook owns interaction only: it never mutates your data. `onReorder` fires\n * once per committed move and you apply it, typically with {@link moveItem}. That\n * keeps the list a controlled value and avoids a re-render per pointer frame.\n *\n * Hit-testing reads the live DOM rects of `[data-sortable-index]` children rather\n * than assuming a fixed row height, so it works with rows of different sizes.\n *\n * A change in `itemCount` cancels an in-flight drag: the list no longer has the\n * indices the drag was based on, and committing anyway would move the wrong row.\n *\n * Note for consumers: the indices and groups are exposed as **state** (so rendering\n * from them is reactive) and mirrored into refs only so the window-level `pointerup`\n * listener can read both synchronously. Because the handlers returned by\n * `getItemProps` close over those mirrors, the React Compiler `refs` rule reports\n * the *call site* — a component spreading these props may need a file-level\n * exemption, as `Kanban` documents.\n *\n * @example\n * ```tsx\n * const [items, setItems] = useState([\"Alfa\", \"Bravo\", \"Charlie\"]);\n * const sortable = useSortable({\n * itemCount: items.length,\n * onReorder: ({ from, to }) => setItems((current) => moveItem(current, from, to)),\n * });\n *\n * <ul {...sortable.getListProps()} aria-label=\"Prioridade\" ref={sortable.setContainer}>\n * {items.map((item, index) => (\n * <li key={item} {...sortable.getItemProps(index)}>\n * {item}\n * </li>\n * ))}\n * </ul>\n * ```\n */\nexport function useSortable(options: UseSortableOptions): UseSortableResult {\n const { itemCount, onReorder, disabled = false, roleDescription = \"Sortable item\" } = options;\n\n const [activeIndex, setActiveIndexState] = useState<number | null>(null);\n const [overIndex, setOverIndexState] = useState<number | null>(null);\n const containerRef = useRef<HTMLElement | null>(null);\n const onReorderRef = useRef(onReorder);\n\n /**\n * Mirrors of the two indices.\n *\n * The window-level `pointerup` listener has to read both values *synchronously*\n * to know what to commit, and a state setter only exposes one of them. Mirroring\n * into refs keeps the commit readable instead of nesting setters to smuggle the\n * other value out.\n */\n const activeRef = useRef<number | null>(null);\n const overRef = useRef<number | null>(null);\n const [activeGroup, setActiveGroupState] = useState<string | undefined>(undefined);\n const [overGroup, setOverGroupState] = useState<string | undefined>(undefined);\n const activeGroupRef = useRef<string | undefined>(undefined);\n const overGroupRef = useRef<string | undefined>(undefined);\n\n const setActiveGroup = useCallback((value: string | undefined): void => {\n activeGroupRef.current = value;\n setActiveGroupState(value);\n }, []);\n\n const setOverGroup = useCallback((value: string | undefined): void => {\n overGroupRef.current = value;\n setOverGroupState(value);\n }, []);\n\n const setActiveIndex = useCallback((value: number | null): void => {\n activeRef.current = value;\n setActiveIndexState(value);\n }, []);\n\n const setOverIndex = useCallback((value: number | null): void => {\n overRef.current = value;\n setOverIndexState(value);\n }, []);\n\n useEffect(() => {\n onReorderRef.current = onReorder;\n }, [onReorder]);\n\n const reset = useCallback((): void => {\n setActiveGroup(undefined);\n setOverGroup(undefined);\n setActiveIndex(null);\n setOverIndex(null);\n }, [setActiveGroup, setActiveIndex, setOverGroup, setOverIndex]);\n\n useEffect(() => {\n reset();\n }, [itemCount, reset]);\n\n /**\n * Report a committed move and go back to idle.\n *\n * The groups are **arguments**, not reads of the mirror refs: `commit` ends up\n * inside the props returned by `getItemProps`, which render calls, and a ref read\n * anywhere in that closure chain is a render-time ref access. The pointer\n * listener reads the mirrors itself — it is an event handler, where reading is\n * fine — and hands the values over.\n *\n * A move that changes group counts even at the same index (the card lands in\n * another column), so only a same-group, same-index drop is \"nothing happened\".\n */\n const commit = useCallback(\n (from: number, to: number, fromGroup?: string, toGroup?: string): void => {\n if (from !== to || fromGroup !== toGroup) {\n onReorderRef.current({ from, to, fromGroup, toGroup });\n }\n reset();\n },\n [reset],\n );\n\n const setContainer = useCallback((node: HTMLElement | null): void => {\n containerRef.current = node;\n }, []);\n\n const handlePointerDown = useCallback(\n (index: number, group: string | undefined, event: ReactPointerEvent<HTMLElement>): void => {\n if (disabled) return;\n event.currentTarget.setPointerCapture?.(event.pointerId);\n setActiveGroup(group);\n setOverGroup(group);\n setActiveIndex(index);\n setOverIndex(index);\n },\n [disabled, setActiveGroup, setActiveIndex, setOverGroup, setOverIndex],\n );\n\n useEffect(() => {\n if (activeIndex === null) return;\n\n function onPointerMove(event: PointerEvent): void {\n const target = targetAtPoint(containerRef.current, event.clientX, event.clientY);\n if (!target) return;\n setOverGroup(target.group);\n setOverIndex(target.index);\n }\n\n function onPointerUp(): void {\n const from = activeRef.current;\n const to = overRef.current;\n if (from !== null && to !== null) {\n commit(from, to, activeGroupRef.current, overGroupRef.current);\n } else {\n reset();\n }\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n if (event.key === \"Escape\") reset();\n }\n\n window.addEventListener(\"pointermove\", onPointerMove);\n window.addEventListener(\"pointerup\", onPointerUp);\n window.addEventListener(\"pointercancel\", reset);\n window.addEventListener(\"keydown\", onKeyDown);\n return () => {\n window.removeEventListener(\"pointermove\", onPointerMove);\n window.removeEventListener(\"pointerup\", onPointerUp);\n window.removeEventListener(\"pointercancel\", reset);\n window.removeEventListener(\"keydown\", onKeyDown);\n };\n }, [activeIndex, commit, reset, setOverGroup, setOverIndex]);\n\n const handleKeyDown = useCallback(\n (\n index: number,\n group: string | undefined,\n event: ReactKeyboardEvent<HTMLElement>,\n ): void => {\n if (disabled) return;\n const picked = activeIndex !== null;\n\n switch (event.key) {\n case \" \":\n case \"Enter\":\n event.preventDefault();\n if (!picked) {\n setActiveGroup(group);\n setOverGroup(group);\n setActiveIndex(index);\n setOverIndex(index);\n } else if (overIndex !== null) {\n commit(activeIndex, overIndex, activeGroup, overGroup);\n }\n break;\n case \"ArrowDown\":\n case \"ArrowRight\": {\n if (!picked) return;\n event.preventDefault();\n if (overRef.current !== null) {\n setOverIndex(Math.min(overRef.current + 1, itemCount - 1));\n }\n break;\n }\n case \"ArrowUp\":\n case \"ArrowLeft\": {\n if (!picked) return;\n event.preventDefault();\n if (overRef.current !== null) {\n setOverIndex(Math.max(overRef.current - 1, 0));\n }\n break;\n }\n case \"Escape\":\n if (!picked) return;\n event.preventDefault();\n reset();\n break;\n default:\n break;\n }\n },\n [\n activeGroup,\n activeIndex,\n commit,\n overGroup,\n disabled,\n itemCount,\n overIndex,\n reset,\n setActiveGroup,\n setActiveIndex,\n setOverGroup,\n setOverIndex,\n ],\n );\n\n const getItemProps = useCallback(\n (index: number, group?: string): SortableItemProps => ({\n \"data-sortable-index\": index,\n \"data-sortable-group\": group,\n \"data-sortable-active\": (activeIndex === index && activeGroup === group) || undefined,\n onPointerDown: (event) => handlePointerDown(index, group, event),\n onKeyDown: (event) => handleKeyDown(index, group, event),\n tabIndex: disabled ? -1 : 0,\n role: \"option\",\n \"aria-roledescription\": roleDescription,\n \"aria-selected\": activeIndex === index && activeGroup === group,\n }),\n [activeGroup, activeIndex, disabled, handleKeyDown, handlePointerDown, roleDescription],\n );\n\n const getEmptyGroupProps = useCallback(\n (group: string) => ({ \"data-sortable-group\": group, \"data-sortable-empty\": true as const }),\n [],\n );\n\n const getListProps = useCallback(\n () => ({ role: \"listbox\" as const, \"aria-orientation\": \"vertical\" as const }),\n [],\n );\n\n return {\n activeIndex,\n overIndex,\n activeGroup,\n overGroup,\n getItemProps,\n getEmptyGroupProps,\n getListProps,\n cancel: reset,\n setContainer,\n };\n}\n"],"mappings":"uBA0GA,SAAgB,EAAY,EAAY,EAAc,EAAiB,CACnE,GAAI,IAAS,GAAM,EAAO,GAAK,EAAK,GAAK,GAAQ,EAAM,QAAU,GAAM,EAAM,OACzE,OAAO,EAEX,IAAM,EAAO,EAAM,MAAM,EACnB,CAAC,GAAS,EAAK,OAAO,EAAM,CAAC,EAEnC,OADA,EAAK,OAAO,EAAI,EAAG,CAAK,EACjB,CACX,CAcA,SAAS,EAAc,EAA+B,EAAW,EAA6B,CAC1F,GAAI,CAAC,EAAW,OAAO,KACvB,IAAM,EAAU,GAAkC,CAC9C,IAAM,EAAO,EAAQ,sBAAsB,EAC3C,OAAO,GAAK,EAAK,KAAO,GAAK,EAAK,QAAU,GAAK,EAAK,MAAQ,GAAK,EAAK,KAC5E,EAEA,IAAK,IAAM,KAAQ,MAAM,KACrB,EAAU,iBAA8B,uBAAuB,CACnE,EAAG,CACC,GAAI,CAAC,EAAO,CAAI,EAAG,SACnB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,YACA,cACA,YACA,cAAA,EA9BiB,EAAA,YAAA,EAChB,EAAe,KAAuC,CACnD,sBAAuB,EACvB,sBAAuB,EACvB,uBAAyB,IAAgB,GAAS,IAAgB,GAAU,IAAA,GAC5E,cAAgB,GAAU,EAAkB,EAAO,EAAO,CAAK,EAC/D,UAAY,GAAU,EAAc,EAAO,EAAO,CAAK,EACvD,SAAU,EAAW,GAAK,EAC1B,KAAM,SACN,uBAAwB,EACxB,gBAAiB,IAAgB,GAAS,IAAgB,CAC9D,GACA,CAAC,EAAa,EAAa,EAAU,EAAe,EAAmB,CAAe,CAkBtF,EACA,oBAAA,EAhBuB,EAAA,YAAA,CACtB,IAAmB,CAAE,sBAAuB,EAAO,sBAAuB,EAAc,GACzF,CAAC,CAcD,EACA,cAAA,EAZiB,EAAA,YAAA,MACV,CAAE,KAAM,UAAoB,mBAAoB,UAAoB,GAC3E,CAAC,CAUD,EACA,OAAQ,EACR,cACJ,CACJ"}
|
|
1
|
+
{"version":3,"file":"use-sortable.cjs","names":[],"sources":["../../src/hooks/use-sortable.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, hook-lines — drag-and-drop with a keyboard path that\n * has to produce the same moves as the pointer path: pointer capture, auto-scroll\n * near the edges, the drop-index maths and the live-region announcements all read\n * one drag state. Two hooks would mean two copies of the index arithmetic, and the\n * two paths silently disagreeing is the bug this exists to prevent.\n */\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from \"react\";\n\n/** Where a dragged item would land if dropped now. */\nexport interface SortableDropTarget {\n /** Index the item started at, within its own group. */\n from: number;\n /** Index it would move to, within the destination group. */\n to: number;\n /**\n * Group the item started in — a Kanban column, for instance. `undefined` for a\n * plain single-list sortable.\n */\n fromGroup?: string;\n /** Destination group. Equal to `fromGroup` when the move stays in one group. */\n toGroup?: string;\n}\n\n/** Props to spread on each sortable item. */\nexport interface SortableItemProps {\n /** Marks the item for hit-testing. */\n \"data-sortable-index\": number;\n /** Group the item belongs to, when the sortable spans several lists. */\n \"data-sortable-group\"?: string;\n /** `true` while this item is the one being moved. */\n \"data-sortable-active\"?: boolean;\n /** Grab handle wiring: starts a pointer drag. */\n onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;\n /** Keyboard reordering — see {@link UseSortableResult}. */\n onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => void;\n /** Puts the item in the tab order so the keyboard path is reachable. */\n tabIndex: number;\n role: \"option\";\n \"aria-roledescription\": string;\n \"aria-selected\": boolean;\n}\n\nexport interface UseSortableOptions {\n /**\n * How many items are in the sortable. Changing it cancels an in-flight drag.\n *\n * With groups, pass the **total** across groups: the number only has to change\n * whenever the indices the drag was based on stop being valid.\n */\n itemCount: number;\n /**\n * Called once, when a move is committed — on pointer release or on a keyboard\n * move. Never called mid-drag, so a controlled list re-renders once instead of\n * on every pointer frame.\n */\n onReorder: (target: SortableDropTarget) => void;\n /** Blocks all interaction. */\n disabled?: boolean;\n /**\n * Description announced for each item, so a screen reader user learns the\n * keyboard contract. Default is in English — override it to localize.\n */\n roleDescription?: string;\n}\n\nexport interface UseSortableResult {\n /** Index being dragged, or `null` when idle. */\n activeIndex: number | null;\n /** Index the item would land on, or `null` when idle. */\n overIndex: number | null;\n /** Group the dragged item came from, when using groups. */\n activeGroup?: string;\n /** Group the item is currently over, when using groups. */\n overGroup?: string;\n /**\n * Spread on each item. Pass `group` when the sortable spans several lists (a\n * Kanban column id), so a drop can land in a different group.\n */\n getItemProps: (index: number, group?: string) => SortableItemProps;\n /**\n * Spread on an **empty** group's drop area, so an item can be moved into a\n * column that has no cards yet — hit-testing works off item rects, and a group\n * with no items has none.\n */\n getEmptyGroupProps: (group: string) => {\n \"data-sortable-group\": string;\n \"data-sortable-empty\": true;\n };\n /** Spread on the list container (`role=\"listbox\"` + a label of your own). */\n getListProps: () => { role: \"listbox\"; \"aria-orientation\": \"vertical\" };\n /** Abort the current drag without reordering. */\n cancel: () => void;\n /**\n * Callback ref for the element that contains the sortable items — hit-testing\n * searches inside it.\n *\n * Named `setContainer` rather than `ref` because it is a **callback**, not a ref\n * object: `ref={sortable.setContainer}`. The old name also read as a readable\n * ref to the React Compiler rules, which flagged every consumer.\n */\n setContainer: (node: HTMLElement | null) => void;\n}\n\n/** Reorder helper: move `from` to `to`, returning a new array. */\nexport function moveItem<T>(items: T[], from: number, to: number): T[] {\n if (from === to || from < 0 || to < 0 || from >= items.length || to >= items.length) {\n return items;\n }\n const next = items.slice();\n const [moved] = next.splice(from, 1);\n next.splice(to, 0, moved);\n return next;\n}\n\n/** A hit-test result: the item (or empty group) under the pointer. */\ninterface HitTarget {\n index: number;\n group?: string;\n}\n\n/**\n * Find the sortable slot under a viewport point.\n *\n * Items are tried first; an empty group's drop area is only considered when no item\n * matched, since an empty column is a fallback target rather than a competing one.\n */\nfunction targetAtPoint(container: HTMLElement | null, x: number, y: number): HitTarget | null {\n if (!container) return null;\n const inside = (element: HTMLElement): boolean => {\n const rect = element.getBoundingClientRect();\n return y >= rect.top && y <= rect.bottom && x >= rect.left && x <= rect.right;\n };\n\n for (const item of Array.from(\n container.querySelectorAll<HTMLElement>(\"[data-sortable-index]\"),\n )) {\n if (!inside(item)) continue;\n const index = Number(item.dataset.sortableIndex);\n if (Number.isNaN(index)) return null;\n return { index, group: item.dataset.sortableGroup };\n }\n\n for (const empty of Array.from(\n container.querySelectorAll<HTMLElement>(\"[data-sortable-empty]\"),\n )) {\n if (inside(empty)) return { index: 0, group: empty.dataset.sortableGroup };\n }\n\n return null;\n}\n\n/**\n * Drag-to-reorder for a list, with a **keyboard path of equal standing**.\n *\n * Pointer events cover mouse, touch and stylus through one code path, and pointer\n * capture keeps the drag alive when the pointer leaves the item. `Space` picks an\n * item up, the arrows move it, `Space`/`Enter` drops it and `Escape` cancels —\n * because a reorder that only works by dragging excludes keyboard users\n * completely, which is where most drag-and-drop implementations fail.\n *\n * The hook owns interaction only: it never mutates your data. `onReorder` fires\n * once per committed move and you apply it, typically with {@link moveItem}. That\n * keeps the list a controlled value and avoids a re-render per pointer frame.\n *\n * Hit-testing reads the live DOM rects of `[data-sortable-index]` children rather\n * than assuming a fixed row height, so it works with rows of different sizes.\n *\n * A change in `itemCount` cancels an in-flight drag: the list no longer has the\n * indices the drag was based on, and committing anyway would move the wrong row.\n *\n * Note for consumers: the indices and groups are exposed as **state** (so rendering\n * from them is reactive) and mirrored into refs only so the window-level `pointerup`\n * listener can read both synchronously. Because the handlers returned by\n * `getItemProps` close over those mirrors, the React Compiler `refs` rule reports\n * the *call site* — a component spreading these props may need a file-level\n * exemption, as `Kanban` documents.\n *\n * @example\n * ```tsx\n * const [items, setItems] = useState([\"Alfa\", \"Bravo\", \"Charlie\"]);\n * const sortable = useSortable({\n * itemCount: items.length,\n * onReorder: ({ from, to }) => setItems((current) => moveItem(current, from, to)),\n * });\n *\n * <ul {...sortable.getListProps()} aria-label=\"Prioridade\" ref={sortable.setContainer}>\n * {items.map((item, index) => (\n * <li key={item} {...sortable.getItemProps(index)}>\n * {item}\n * </li>\n * ))}\n * </ul>\n * ```\n */\nexport function useSortable(options: UseSortableOptions): UseSortableResult {\n const { itemCount, onReorder, disabled = false, roleDescription = \"Sortable item\" } = options;\n\n const [activeIndex, setActiveIndexState] = useState<number | null>(null);\n const [overIndex, setOverIndexState] = useState<number | null>(null);\n const containerRef = useRef<HTMLElement | null>(null);\n const onReorderRef = useRef(onReorder);\n\n /**\n * Mirrors of the two indices.\n *\n * The window-level `pointerup` listener has to read both values *synchronously*\n * to know what to commit, and a state setter only exposes one of them. Mirroring\n * into refs keeps the commit readable instead of nesting setters to smuggle the\n * other value out.\n */\n const activeRef = useRef<number | null>(null);\n const overRef = useRef<number | null>(null);\n const [activeGroup, setActiveGroupState] = useState<string | undefined>(undefined);\n const [overGroup, setOverGroupState] = useState<string | undefined>(undefined);\n const activeGroupRef = useRef<string | undefined>(undefined);\n const overGroupRef = useRef<string | undefined>(undefined);\n\n const setActiveGroup = useCallback((value: string | undefined): void => {\n activeGroupRef.current = value;\n setActiveGroupState(value);\n }, []);\n\n const setOverGroup = useCallback((value: string | undefined): void => {\n overGroupRef.current = value;\n setOverGroupState(value);\n }, []);\n\n const setActiveIndex = useCallback((value: number | null): void => {\n activeRef.current = value;\n setActiveIndexState(value);\n }, []);\n\n const setOverIndex = useCallback((value: number | null): void => {\n overRef.current = value;\n setOverIndexState(value);\n }, []);\n\n useEffect(() => {\n onReorderRef.current = onReorder;\n }, [onReorder]);\n\n const reset = useCallback((): void => {\n setActiveGroup(undefined);\n setOverGroup(undefined);\n setActiveIndex(null);\n setOverIndex(null);\n }, [setActiveGroup, setActiveIndex, setOverGroup, setOverIndex]);\n\n useEffect(() => {\n reset();\n }, [itemCount, reset]);\n\n /**\n * Report a committed move and go back to idle.\n *\n * The groups are **arguments**, not reads of the mirror refs: `commit` ends up\n * inside the props returned by `getItemProps`, which render calls, and a ref read\n * anywhere in that closure chain is a render-time ref access. The pointer\n * listener reads the mirrors itself — it is an event handler, where reading is\n * fine — and hands the values over.\n *\n * A move that changes group counts even at the same index (the card lands in\n * another column), so only a same-group, same-index drop is \"nothing happened\".\n */\n const commit = useCallback(\n (from: number, to: number, fromGroup?: string, toGroup?: string): void => {\n if (from !== to || fromGroup !== toGroup) {\n onReorderRef.current({ from, to, fromGroup, toGroup });\n }\n reset();\n },\n [reset],\n );\n\n const setContainer = useCallback((node: HTMLElement | null): void => {\n containerRef.current = node;\n }, []);\n\n const handlePointerDown = useCallback(\n (index: number, group: string | undefined, event: ReactPointerEvent<HTMLElement>): void => {\n if (disabled) return;\n event.currentTarget.setPointerCapture?.(event.pointerId);\n setActiveGroup(group);\n setOverGroup(group);\n setActiveIndex(index);\n setOverIndex(index);\n },\n [disabled, setActiveGroup, setActiveIndex, setOverGroup, setOverIndex],\n );\n\n useEffect(() => {\n if (activeIndex === null) return;\n\n function onPointerMove(event: PointerEvent): void {\n const target = targetAtPoint(containerRef.current, event.clientX, event.clientY);\n if (!target) return;\n setOverGroup(target.group);\n setOverIndex(target.index);\n }\n\n function onPointerUp(): void {\n const from = activeRef.current;\n const to = overRef.current;\n if (from !== null && to !== null) {\n commit(from, to, activeGroupRef.current, overGroupRef.current);\n } else {\n reset();\n }\n }\n\n /**\n * Cancel the drag on `Escape`.\n *\n * Listened in the capture phase and marked consumed: the overlays' shared\n * `Escape` listener sits on `window` in the bubble phase, so a list sorted\n * inside a `Modal` would otherwise close the modal mid-drag instead of\n * just dropping the item back.\n */\n function onKeyDown(event: KeyboardEvent): void {\n if (event.key !== \"Escape\") return;\n event.preventDefault();\n reset();\n }\n\n window.addEventListener(\"pointermove\", onPointerMove);\n window.addEventListener(\"pointerup\", onPointerUp);\n window.addEventListener(\"pointercancel\", reset);\n window.addEventListener(\"keydown\", onKeyDown, true);\n return () => {\n window.removeEventListener(\"pointermove\", onPointerMove);\n window.removeEventListener(\"pointerup\", onPointerUp);\n window.removeEventListener(\"pointercancel\", reset);\n window.removeEventListener(\"keydown\", onKeyDown, true);\n };\n }, [activeIndex, commit, reset, setOverGroup, setOverIndex]);\n\n const handleKeyDown = useCallback(\n (\n index: number,\n group: string | undefined,\n event: ReactKeyboardEvent<HTMLElement>,\n ): void => {\n if (disabled) return;\n const picked = activeIndex !== null;\n\n switch (event.key) {\n case \" \":\n case \"Enter\":\n event.preventDefault();\n if (!picked) {\n setActiveGroup(group);\n setOverGroup(group);\n setActiveIndex(index);\n setOverIndex(index);\n } else if (overIndex !== null) {\n commit(activeIndex, overIndex, activeGroup, overGroup);\n }\n break;\n case \"ArrowDown\":\n case \"ArrowRight\": {\n if (!picked) return;\n event.preventDefault();\n if (overRef.current !== null) {\n setOverIndex(Math.min(overRef.current + 1, itemCount - 1));\n }\n break;\n }\n case \"ArrowUp\":\n case \"ArrowLeft\": {\n if (!picked) return;\n event.preventDefault();\n if (overRef.current !== null) {\n setOverIndex(Math.max(overRef.current - 1, 0));\n }\n break;\n }\n case \"Escape\":\n if (!picked) return;\n event.preventDefault();\n reset();\n break;\n default:\n break;\n }\n },\n [\n activeGroup,\n activeIndex,\n commit,\n overGroup,\n disabled,\n itemCount,\n overIndex,\n reset,\n setActiveGroup,\n setActiveIndex,\n setOverGroup,\n setOverIndex,\n ],\n );\n\n const getItemProps = useCallback(\n (index: number, group?: string): SortableItemProps => ({\n \"data-sortable-index\": index,\n \"data-sortable-group\": group,\n \"data-sortable-active\": (activeIndex === index && activeGroup === group) || undefined,\n onPointerDown: (event) => handlePointerDown(index, group, event),\n onKeyDown: (event) => handleKeyDown(index, group, event),\n tabIndex: disabled ? -1 : 0,\n role: \"option\",\n \"aria-roledescription\": roleDescription,\n \"aria-selected\": activeIndex === index && activeGroup === group,\n }),\n [activeGroup, activeIndex, disabled, handleKeyDown, handlePointerDown, roleDescription],\n );\n\n const getEmptyGroupProps = useCallback(\n (group: string) => ({ \"data-sortable-group\": group, \"data-sortable-empty\": true as const }),\n [],\n );\n\n const getListProps = useCallback(\n () => ({ role: \"listbox\" as const, \"aria-orientation\": \"vertical\" as const }),\n [],\n );\n\n return {\n activeIndex,\n overIndex,\n activeGroup,\n overGroup,\n getItemProps,\n getEmptyGroupProps,\n getListProps,\n cancel: reset,\n setContainer,\n };\n}\n"],"mappings":"uBA0GA,SAAgB,EAAY,EAAY,EAAc,EAAiB,CACnE,GAAI,IAAS,GAAM,EAAO,GAAK,EAAK,GAAK,GAAQ,EAAM,QAAU,GAAM,EAAM,OACzE,OAAO,EAEX,IAAM,EAAO,EAAM,MAAM,EACnB,CAAC,GAAS,EAAK,OAAO,EAAM,CAAC,EAEnC,OADA,EAAK,OAAO,EAAI,EAAG,CAAK,EACjB,CACX,CAcA,SAAS,EAAc,EAA+B,EAAW,EAA6B,CAC1F,GAAI,CAAC,EAAW,OAAO,KACvB,IAAM,EAAU,GAAkC,CAC9C,IAAM,EAAO,EAAQ,sBAAsB,EAC3C,OAAO,GAAK,EAAK,KAAO,GAAK,EAAK,QAAU,GAAK,EAAK,MAAQ,GAAK,EAAK,KAC5E,EAEA,IAA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AAM,eAAe,EACrB,EAAM,CAId,CACJ,EACA,CACI,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACJ,CACJ,EA2BA,MAAO,CACH,cACA,YACA,cACA,YACA,cAAA,EA9BiB,EAAA,YAAA,EAChB,EAAe,KAAuC,CACnD,sBAAuB,EACvB,sBAAuB,EACvB,uBAAyB,IAAgB,GAAS,IAAgB,GAAU,IAAA,GAC5E,cAAgB,GAAU,EAAkB,EAAO,EAAO,CAAK,EAC/D,UAAY,GAAU,EAAc,EAAO,EAAO,CAAK,EACvD,SAAU,EAAW,GAAK,EAC1B,KAAM,SACN,uBAAwB,EACxB,gBAAiB,IAAgB,GAAS,IAAgB,CAC9D,GACA,CAAC,EAAa,EAAa,EAAU,EAAe,EAAmB,CAAe,CAkBtF,EACA,oBAAA,EAhBuB,EAAA,YAAA,CACtB,IAAmB,CAAE,sBAAuB,EAAO,sBAAuB,EAAc,GACzF,CAAC,CAcD,EACA,cAAA,EAZiB,EAAA,YAAA,MACV,CAAE,KAAM,UAAoB,mBAAoB,UAAoB,GAC3E,CAAC,CAUD,EACA,OAAQ,EACR,cACJ,CACJ"}
|
|
@@ -78,10 +78,10 @@ function o(i) {
|
|
|
78
78
|
e !== null && t !== null ? k(e, t, S.current, C.current) : O();
|
|
79
79
|
}
|
|
80
80
|
function n(e) {
|
|
81
|
-
e.key === "Escape" && O();
|
|
81
|
+
e.key === "Escape" && (e.preventDefault(), O());
|
|
82
82
|
}
|
|
83
|
-
return window.addEventListener("pointermove", e), window.addEventListener("pointerup", t), window.addEventListener("pointercancel", O), window.addEventListener("keydown", n), () => {
|
|
84
|
-
window.removeEventListener("pointermove", e), window.removeEventListener("pointerup", t), window.removeEventListener("pointercancel", O), window.removeEventListener("keydown", n);
|
|
83
|
+
return window.addEventListener("pointermove", e), window.addEventListener("pointerup", t), window.addEventListener("pointercancel", O), window.addEventListener("keydown", n, !0), () => {
|
|
84
|
+
window.removeEventListener("pointermove", e), window.removeEventListener("pointerup", t), window.removeEventListener("pointercancel", O), window.removeEventListener("keydown", n, !0);
|
|
85
85
|
};
|
|
86
86
|
}, [
|
|
87
87
|
u,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-sortable.js","names":[],"sources":["../../src/hooks/use-sortable.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, hook-lines — drag-and-drop with a keyboard path that\n * has to produce the same moves as the pointer path: pointer capture, auto-scroll\n * near the edges, the drop-index maths and the live-region announcements all read\n * one drag state. Two hooks would mean two copies of the index arithmetic, and the\n * two paths silently disagreeing is the bug this exists to prevent.\n */\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from \"react\";\n\n/** Where a dragged item would land if dropped now. */\nexport interface SortableDropTarget {\n /** Index the item started at, within its own group. */\n from: number;\n /** Index it would move to, within the destination group. */\n to: number;\n /**\n * Group the item started in — a Kanban column, for instance. `undefined` for a\n * plain single-list sortable.\n */\n fromGroup?: string;\n /** Destination group. Equal to `fromGroup` when the move stays in one group. */\n toGroup?: string;\n}\n\n/** Props to spread on each sortable item. */\nexport interface SortableItemProps {\n /** Marks the item for hit-testing. */\n \"data-sortable-index\": number;\n /** Group the item belongs to, when the sortable spans several lists. */\n \"data-sortable-group\"?: string;\n /** `true` while this item is the one being moved. */\n \"data-sortable-active\"?: boolean;\n /** Grab handle wiring: starts a pointer drag. */\n onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;\n /** Keyboard reordering — see {@link UseSortableResult}. */\n onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => void;\n /** Puts the item in the tab order so the keyboard path is reachable. */\n tabIndex: number;\n role: \"option\";\n \"aria-roledescription\": string;\n \"aria-selected\": boolean;\n}\n\nexport interface UseSortableOptions {\n /**\n * How many items are in the sortable. Changing it cancels an in-flight drag.\n *\n * With groups, pass the **total** across groups: the number only has to change\n * whenever the indices the drag was based on stop being valid.\n */\n itemCount: number;\n /**\n * Called once, when a move is committed — on pointer release or on a keyboard\n * move. Never called mid-drag, so a controlled list re-renders once instead of\n * on every pointer frame.\n */\n onReorder: (target: SortableDropTarget) => void;\n /** Blocks all interaction. */\n disabled?: boolean;\n /**\n * Description announced for each item, so a screen reader user learns the\n * keyboard contract. Default is in English — override it to localize.\n */\n roleDescription?: string;\n}\n\nexport interface UseSortableResult {\n /** Index being dragged, or `null` when idle. */\n activeIndex: number | null;\n /** Index the item would land on, or `null` when idle. */\n overIndex: number | null;\n /** Group the dragged item came from, when using groups. */\n activeGroup?: string;\n /** Group the item is currently over, when using groups. */\n overGroup?: string;\n /**\n * Spread on each item. Pass `group` when the sortable spans several lists (a\n * Kanban column id), so a drop can land in a different group.\n */\n getItemProps: (index: number, group?: string) => SortableItemProps;\n /**\n * Spread on an **empty** group's drop area, so an item can be moved into a\n * column that has no cards yet — hit-testing works off item rects, and a group\n * with no items has none.\n */\n getEmptyGroupProps: (group: string) => {\n \"data-sortable-group\": string;\n \"data-sortable-empty\": true;\n };\n /** Spread on the list container (`role=\"listbox\"` + a label of your own). */\n getListProps: () => { role: \"listbox\"; \"aria-orientation\": \"vertical\" };\n /** Abort the current drag without reordering. */\n cancel: () => void;\n /**\n * Callback ref for the element that contains the sortable items — hit-testing\n * searches inside it.\n *\n * Named `setContainer` rather than `ref` because it is a **callback**, not a ref\n * object: `ref={sortable.setContainer}`. The old name also read as a readable\n * ref to the React Compiler rules, which flagged every consumer.\n */\n setContainer: (node: HTMLElement | null) => void;\n}\n\n/** Reorder helper: move `from` to `to`, returning a new array. */\nexport function moveItem<T>(items: T[], from: number, to: number): T[] {\n if (from === to || from < 0 || to < 0 || from >= items.length || to >= items.length) {\n return items;\n }\n const next = items.slice();\n const [moved] = next.splice(from, 1);\n next.splice(to, 0, moved);\n return next;\n}\n\n/** A hit-test result: the item (or empty group) under the pointer. */\ninterface HitTarget {\n index: number;\n group?: string;\n}\n\n/**\n * Find the sortable slot under a viewport point.\n *\n * Items are tried first; an empty group's drop area is only considered when no item\n * matched, since an empty column is a fallback target rather than a competing one.\n */\nfunction targetAtPoint(container: HTMLElement | null, x: number, y: number): HitTarget | null {\n if (!container) return null;\n const inside = (element: HTMLElement): boolean => {\n const rect = element.getBoundingClientRect();\n return y >= rect.top && y <= rect.bottom && x >= rect.left && x <= rect.right;\n };\n\n for (const item of Array.from(\n container.querySelectorAll<HTMLElement>(\"[data-sortable-index]\"),\n )) {\n if (!inside(item)) continue;\n const index = Number(item.dataset.sortableIndex);\n if (Number.isNaN(index)) return null;\n return { index, group: item.dataset.sortableGroup };\n }\n\n for (const empty of Array.from(\n container.querySelectorAll<HTMLElement>(\"[data-sortable-empty]\"),\n )) {\n if (inside(empty)) return { index: 0, group: empty.dataset.sortableGroup };\n }\n\n return null;\n}\n\n/**\n * Drag-to-reorder for a list, with a **keyboard path of equal standing**.\n *\n * Pointer events cover mouse, touch and stylus through one code path, and pointer\n * capture keeps the drag alive when the pointer leaves the item. `Space` picks an\n * item up, the arrows move it, `Space`/`Enter` drops it and `Escape` cancels —\n * because a reorder that only works by dragging excludes keyboard users\n * completely, which is where most drag-and-drop implementations fail.\n *\n * The hook owns interaction only: it never mutates your data. `onReorder` fires\n * once per committed move and you apply it, typically with {@link moveItem}. That\n * keeps the list a controlled value and avoids a re-render per pointer frame.\n *\n * Hit-testing reads the live DOM rects of `[data-sortable-index]` children rather\n * than assuming a fixed row height, so it works with rows of different sizes.\n *\n * A change in `itemCount` cancels an in-flight drag: the list no longer has the\n * indices the drag was based on, and committing anyway would move the wrong row.\n *\n * Note for consumers: the indices and groups are exposed as **state** (so rendering\n * from them is reactive) and mirrored into refs only so the window-level `pointerup`\n * listener can read both synchronously. Because the handlers returned by\n * `getItemProps` close over those mirrors, the React Compiler `refs` rule reports\n * the *call site* — a component spreading these props may need a file-level\n * exemption, as `Kanban` documents.\n *\n * @example\n * ```tsx\n * const [items, setItems] = useState([\"Alfa\", \"Bravo\", \"Charlie\"]);\n * const sortable = useSortable({\n * itemCount: items.length,\n * onReorder: ({ from, to }) => setItems((current) => moveItem(current, from, to)),\n * });\n *\n * <ul {...sortable.getListProps()} aria-label=\"Prioridade\" ref={sortable.setContainer}>\n * {items.map((item, index) => (\n * <li key={item} {...sortable.getItemProps(index)}>\n * {item}\n * </li>\n * ))}\n * </ul>\n * ```\n */\nexport function useSortable(options: UseSortableOptions): UseSortableResult {\n const { itemCount, onReorder, disabled = false, roleDescription = \"Sortable item\" } = options;\n\n const [activeIndex, setActiveIndexState] = useState<number | null>(null);\n const [overIndex, setOverIndexState] = useState<number | null>(null);\n const containerRef = useRef<HTMLElement | null>(null);\n const onReorderRef = useRef(onReorder);\n\n /**\n * Mirrors of the two indices.\n *\n * The window-level `pointerup` listener has to read both values *synchronously*\n * to know what to commit, and a state setter only exposes one of them. Mirroring\n * into refs keeps the commit readable instead of nesting setters to smuggle the\n * other value out.\n */\n const activeRef = useRef<number | null>(null);\n const overRef = useRef<number | null>(null);\n const [activeGroup, setActiveGroupState] = useState<string | undefined>(undefined);\n const [overGroup, setOverGroupState] = useState<string | undefined>(undefined);\n const activeGroupRef = useRef<string | undefined>(undefined);\n const overGroupRef = useRef<string | undefined>(undefined);\n\n const setActiveGroup = useCallback((value: string | undefined): void => {\n activeGroupRef.current = value;\n setActiveGroupState(value);\n }, []);\n\n const setOverGroup = useCallback((value: string | undefined): void => {\n overGroupRef.current = value;\n setOverGroupState(value);\n }, []);\n\n const setActiveIndex = useCallback((value: number | null): void => {\n activeRef.current = value;\n setActiveIndexState(value);\n }, []);\n\n const setOverIndex = useCallback((value: number | null): void => {\n overRef.current = value;\n setOverIndexState(value);\n }, []);\n\n useEffect(() => {\n onReorderRef.current = onReorder;\n }, [onReorder]);\n\n const reset = useCallback((): void => {\n setActiveGroup(undefined);\n setOverGroup(undefined);\n setActiveIndex(null);\n setOverIndex(null);\n }, [setActiveGroup, setActiveIndex, setOverGroup, setOverIndex]);\n\n useEffect(() => {\n reset();\n }, [itemCount, reset]);\n\n /**\n * Report a committed move and go back to idle.\n *\n * The groups are **arguments**, not reads of the mirror refs: `commit` ends up\n * inside the props returned by `getItemProps`, which render calls, and a ref read\n * anywhere in that closure chain is a render-time ref access. The pointer\n * listener reads the mirrors itself — it is an event handler, where reading is\n * fine — and hands the values over.\n *\n * A move that changes group counts even at the same index (the card lands in\n * another column), so only a same-group, same-index drop is \"nothing happened\".\n */\n const commit = useCallback(\n (from: number, to: number, fromGroup?: string, toGroup?: string): void => {\n if (from !== to || fromGroup !== toGroup) {\n onReorderRef.current({ from, to, fromGroup, toGroup });\n }\n reset();\n },\n [reset],\n );\n\n const setContainer = useCallback((node: HTMLElement | null): void => {\n containerRef.current = node;\n }, []);\n\n const handlePointerDown = useCallback(\n (index: number, group: string | undefined, event: ReactPointerEvent<HTMLElement>): void => {\n if (disabled) return;\n event.currentTarget.setPointerCapture?.(event.pointerId);\n setActiveGroup(group);\n setOverGroup(group);\n setActiveIndex(index);\n setOverIndex(index);\n },\n [disabled, setActiveGroup, setActiveIndex, setOverGroup, setOverIndex],\n );\n\n useEffect(() => {\n if (activeIndex === null) return;\n\n function onPointerMove(event: PointerEvent): void {\n const target = targetAtPoint(containerRef.current, event.clientX, event.clientY);\n if (!target) return;\n setOverGroup(target.group);\n setOverIndex(target.index);\n }\n\n function onPointerUp(): void {\n const from = activeRef.current;\n const to = overRef.current;\n if (from !== null && to !== null) {\n commit(from, to, activeGroupRef.current, overGroupRef.current);\n } else {\n reset();\n }\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n if (event.key === \"Escape\") reset();\n }\n\n window.addEventListener(\"pointermove\", onPointerMove);\n window.addEventListener(\"pointerup\", onPointerUp);\n window.addEventListener(\"pointercancel\", reset);\n window.addEventListener(\"keydown\", onKeyDown);\n return () => {\n window.removeEventListener(\"pointermove\", onPointerMove);\n window.removeEventListener(\"pointerup\", onPointerUp);\n window.removeEventListener(\"pointercancel\", reset);\n window.removeEventListener(\"keydown\", onKeyDown);\n };\n }, [activeIndex, commit, reset, setOverGroup, setOverIndex]);\n\n const handleKeyDown = useCallback(\n (\n index: number,\n group: string | undefined,\n event: ReactKeyboardEvent<HTMLElement>,\n ): void => {\n if (disabled) return;\n const picked = activeIndex !== null;\n\n switch (event.key) {\n case \" \":\n case \"Enter\":\n event.preventDefault();\n if (!picked) {\n setActiveGroup(group);\n setOverGroup(group);\n setActiveIndex(index);\n setOverIndex(index);\n } else if (overIndex !== null) {\n commit(activeIndex, overIndex, activeGroup, overGroup);\n }\n break;\n case \"ArrowDown\":\n case \"ArrowRight\": {\n if (!picked) return;\n event.preventDefault();\n if (overRef.current !== null) {\n setOverIndex(Math.min(overRef.current + 1, itemCount - 1));\n }\n break;\n }\n case \"ArrowUp\":\n case \"ArrowLeft\": {\n if (!picked) return;\n event.preventDefault();\n if (overRef.current !== null) {\n setOverIndex(Math.max(overRef.current - 1, 0));\n }\n break;\n }\n case \"Escape\":\n if (!picked) return;\n event.preventDefault();\n reset();\n break;\n default:\n break;\n }\n },\n [\n activeGroup,\n activeIndex,\n commit,\n overGroup,\n disabled,\n itemCount,\n overIndex,\n reset,\n setActiveGroup,\n setActiveIndex,\n setOverGroup,\n setOverIndex,\n ],\n );\n\n const getItemProps = useCallback(\n (index: number, group?: string): SortableItemProps => ({\n \"data-sortable-index\": index,\n \"data-sortable-group\": group,\n \"data-sortable-active\": (activeIndex === index && activeGroup === group) || undefined,\n onPointerDown: (event) => handlePointerDown(index, group, event),\n onKeyDown: (event) => handleKeyDown(index, group, event),\n tabIndex: disabled ? -1 : 0,\n role: \"option\",\n \"aria-roledescription\": roleDescription,\n \"aria-selected\": activeIndex === index && activeGroup === group,\n }),\n [activeGroup, activeIndex, disabled, handleKeyDown, handlePointerDown, roleDescription],\n );\n\n const getEmptyGroupProps = useCallback(\n (group: string) => ({ \"data-sortable-group\": group, \"data-sortable-empty\": true as const }),\n [],\n );\n\n const getListProps = useCallback(\n () => ({ role: \"listbox\" as const, \"aria-orientation\": \"vertical\" as const }),\n [],\n );\n\n return {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EAAQ,UAAU,GAAG,IAAY,CAAC,CAAC;IAE7D;GAEJ,KAAK;GACL,KAAK;IACD,IAAI,CAAC,GAAQ;IAEb,AADA,EAAM,eAAe,GACjB,EAAQ,YAAY,QACpB,EAAa,KAAK,IAAI,EAAQ,UAAU,GAAG,CAAC,CAAC;IAEjD;GAEJ,KAAK;IACD,IAAI,CAAC,GAAQ;IAEb,AADA,EAAM,eAAe,GACrB,EAAM;EAId;CACJ,GACA;EACI;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CACJ;CA2BA,OAAO;EACH;EACA;EACA;EACA;EACA,cA9BiB,GAChB,GAAe,OAAuC;GACnD,uBAAuB;GACvB,uBAAuB;GACvB,wBAAyB,MAAgB,KAAS,MAAgB,KAAU,KAAA;GAC5E,gBAAgB,MAAU,EAAkB,GAAO,GAAO,CAAK;GAC/D,YAAY,MAAU,EAAc,GAAO,GAAO,CAAK;GACvD,UAAU,IAAW,KAAK;GAC1B,MAAM;GACN,wBAAwB;GACxB,iBAAiB,MAAgB,KAAS,MAAgB;EAC9D,IACA;GAAC;GAAa;GAAa;GAAU;GAAe;GAAmB;EAAe,CAkBtF;EACA,oBAhBuB,GACtB,OAAmB;GAAE,uBAAuB;GAAO,uBAAuB;EAAc,IACzF,CAAC,CAcD;EACA,cAZiB,SACV;GAAE,MAAM;GAAoB,oBAAoB;EAAoB,IAC3E,CAAC,CAUD;EACA,QAAQ;EACR;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"use-sortable.js","names":[],"sources":["../../src/hooks/use-sortable.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, hook-lines — drag-and-drop with a keyboard path that\n * has to produce the same moves as the pointer path: pointer capture, auto-scroll\n * near the edges, the drop-index maths and the live-region announcements all read\n * one drag state. Two hooks would mean two copies of the index arithmetic, and the\n * two paths silently disagreeing is the bug this exists to prevent.\n */\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from \"react\";\n\n/** Where a dragged item would land if dropped now. */\nexport interface SortableDropTarget {\n /** Index the item started at, within its own group. */\n from: number;\n /** Index it would move to, within the destination group. */\n to: number;\n /**\n * Group the item started in — a Kanban column, for instance. `undefined` for a\n * plain single-list sortable.\n */\n fromGroup?: string;\n /** Destination group. Equal to `fromGroup` when the move stays in one group. */\n toGroup?: string;\n}\n\n/** Props to spread on each sortable item. */\nexport interface SortableItemProps {\n /** Marks the item for hit-testing. */\n \"data-sortable-index\": number;\n /** Group the item belongs to, when the sortable spans several lists. */\n \"data-sortable-group\"?: string;\n /** `true` while this item is the one being moved. */\n \"data-sortable-active\"?: boolean;\n /** Grab handle wiring: starts a pointer drag. */\n onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;\n /** Keyboard reordering — see {@link UseSortableResult}. */\n onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => void;\n /** Puts the item in the tab order so the keyboard path is reachable. */\n tabIndex: number;\n role: \"option\";\n \"aria-roledescription\": string;\n \"aria-selected\": boolean;\n}\n\nexport interface UseSortableOptions {\n /**\n * How many items are in the sortable. Changing it cancels an in-flight drag.\n *\n * With groups, pass the **total** across groups: the number only has to change\n * whenever the indices the drag was based on stop being valid.\n */\n itemCount: number;\n /**\n * Called once, when a move is committed — on pointer release or on a keyboard\n * move. Never called mid-drag, so a controlled list re-renders once instead of\n * on every pointer frame.\n */\n onReorder: (target: SortableDropTarget) => void;\n /** Blocks all interaction. */\n disabled?: boolean;\n /**\n * Description announced for each item, so a screen reader user learns the\n * keyboard contract. Default is in English — override it to localize.\n */\n roleDescription?: string;\n}\n\nexport interface UseSortableResult {\n /** Index being dragged, or `null` when idle. */\n activeIndex: number | null;\n /** Index the item would land on, or `null` when idle. */\n overIndex: number | null;\n /** Group the dragged item came from, when using groups. */\n activeGroup?: string;\n /** Group the item is currently over, when using groups. */\n overGroup?: string;\n /**\n * Spread on each item. Pass `group` when the sortable spans several lists (a\n * Kanban column id), so a drop can land in a different group.\n */\n getItemProps: (index: number, group?: string) => SortableItemProps;\n /**\n * Spread on an **empty** group's drop area, so an item can be moved into a\n * column that has no cards yet — hit-testing works off item rects, and a group\n * with no items has none.\n */\n getEmptyGroupProps: (group: string) => {\n \"data-sortable-group\": string;\n \"data-sortable-empty\": true;\n };\n /** Spread on the list container (`role=\"listbox\"` + a label of your own). */\n getListProps: () => { role: \"listbox\"; \"aria-orientation\": \"vertical\" };\n /** Abort the current drag without reordering. */\n cancel: () => void;\n /**\n * Callback ref for the element that contains the sortable items — hit-testing\n * searches inside it.\n *\n * Named `setContainer` rather than `ref` because it is a **callback**, not a ref\n * object: `ref={sortable.setContainer}`. The old name also read as a readable\n * ref to the React Compiler rules, which flagged every consumer.\n */\n setContainer: (node: HTMLElement | null) => void;\n}\n\n/** Reorder helper: move `from` to `to`, returning a new array. */\nexport function moveItem<T>(items: T[], from: number, to: number): T[] {\n if (from === to || from < 0 || to < 0 || from >= items.length || to >= items.length) {\n return items;\n }\n const next = items.slice();\n const [moved] = next.splice(from, 1);\n next.splice(to, 0, moved);\n return next;\n}\n\n/** A hit-test result: the item (or empty group) under the pointer. */\ninterface HitTarget {\n index: number;\n group?: string;\n}\n\n/**\n * Find the sortable slot under a viewport point.\n *\n * Items are tried first; an empty group's drop area is only considered when no item\n * matched, since an empty column is a fallback target rather than a competing one.\n */\nfunction targetAtPoint(container: HTMLElement | null, x: number, y: number): HitTarget | null {\n if (!container) return null;\n const inside = (element: HTMLElement): boolean => {\n const rect = element.getBoundingClientRect();\n return y >= rect.top && y <= rect.bottom && x >= rect.left && x <= rect.right;\n };\n\n for (const item of Array.from(\n container.querySelectorAll<HTMLElement>(\"[data-sortable-index]\"),\n )) {\n if (!inside(item)) continue;\n const index = Number(item.dataset.sortableIndex);\n if (Number.isNaN(index)) return null;\n return { index, group: item.dataset.sortableGroup };\n }\n\n for (const empty of Array.from(\n container.querySelectorAll<HTMLElement>(\"[data-sortable-empty]\"),\n )) {\n if (inside(empty)) return { index: 0, group: empty.dataset.sortableGroup };\n }\n\n return null;\n}\n\n/**\n * Drag-to-reorder for a list, with a **keyboard path of equal standing**.\n *\n * Pointer events cover mouse, touch and stylus through one code path, and pointer\n * capture keeps the drag alive when the pointer leaves the item. `Space` picks an\n * item up, the arrows move it, `Space`/`Enter` drops it and `Escape` cancels —\n * because a reorder that only works by dragging excludes keyboard users\n * completely, which is where most drag-and-drop implementations fail.\n *\n * The hook owns interaction only: it never mutates your data. `onReorder` fires\n * once per committed move and you apply it, typically with {@link moveItem}. That\n * keeps the list a controlled value and avoids a re-render per pointer frame.\n *\n * Hit-testing reads the live DOM rects of `[data-sortable-index]` children rather\n * than assuming a fixed row height, so it works with rows of different sizes.\n *\n * A change in `itemCount` cancels an in-flight drag: the list no longer has the\n * indices the drag was based on, and committing anyway would move the wrong row.\n *\n * Note for consumers: the indices and groups are exposed as **state** (so rendering\n * from them is reactive) and mirrored into refs only so the window-level `pointerup`\n * listener can read both synchronously. Because the handlers returned by\n * `getItemProps` close over those mirrors, the React Compiler `refs` rule reports\n * the *call site* — a component spreading these props may need a file-level\n * exemption, as `Kanban` documents.\n *\n * @example\n * ```tsx\n * const [items, setItems] = useState([\"Alfa\", \"Bravo\", \"Charlie\"]);\n * const sortable = useSortable({\n * itemCount: items.length,\n * onReorder: ({ from, to }) => setItems((current) => moveItem(current, from, to)),\n * });\n *\n * <ul {...sortable.getListProps()} aria-label=\"Prioridade\" ref={sortable.setContainer}>\n * {items.map((item, index) => (\n * <li key={item} {...sortable.getItemProps(index)}>\n * {item}\n * </li>\n * ))}\n * </ul>\n * ```\n */\nexport function useSortable(options: UseSortableOptions): UseSortableResult {\n const { itemCount, onReorder, disabled = false, roleDescription = \"Sortable item\" } = options;\n\n const [activeIndex, setActiveIndexState] = useState<number | null>(null);\n const [overIndex, setOverIndexState] = useState<number | null>(null);\n const containerRef = useRef<HTMLElement | null>(null);\n const onReorderRef = useRef(onReorder);\n\n /**\n * Mirrors of the two indices.\n *\n * The window-level `pointerup` listener has to read both values *synchronously*\n * to know what to commit, and a state setter only exposes one of them. Mirroring\n * into refs keeps the commit readable instead of nesting setters to smuggle the\n * other value out.\n */\n const activeRef = useRef<number | null>(null);\n const overRef = useRef<number | null>(null);\n const [activeGroup, setActiveGroupState] = useState<string | undefined>(undefined);\n const [overGroup, setOverGroupState] = useState<string | undefined>(undefined);\n const activeGroupRef = useRef<string | undefined>(undefined);\n const overGroupRef = useRef<string | undefined>(undefined);\n\n const setActiveGroup = useCallback((value: string | undefined): void => {\n activeGroupRef.current = value;\n setActiveGroupState(value);\n }, []);\n\n const setOverGroup = useCallback((value: string | undefined): void => {\n overGroupRef.current = value;\n setOverGroupState(value);\n }, []);\n\n const setActiveIndex = useCallback((value: number | null): void => {\n activeRef.current = value;\n setActiveIndexState(value);\n }, []);\n\n const setOverIndex = useCallback((value: number | null): void => {\n overRef.current = value;\n setOverIndexState(value);\n }, []);\n\n useEffect(() => {\n onReorderRef.current = onReorder;\n }, [onReorder]);\n\n const reset = useCallback((): void => {\n setActiveGroup(undefined);\n setOverGroup(undefined);\n setActiveIndex(null);\n setOverIndex(null);\n }, [setActiveGroup, setActiveIndex, setOverGroup, setOverIndex]);\n\n useEffect(() => {\n reset();\n }, [itemCount, reset]);\n\n /**\n * Report a committed move and go back to idle.\n *\n * The groups are **arguments**, not reads of the mirror refs: `commit` ends up\n * inside the props returned by `getItemProps`, which render calls, and a ref read\n * anywhere in that closure chain is a render-time ref access. The pointer\n * listener reads the mirrors itself — it is an event handler, where reading is\n * fine — and hands the values over.\n *\n * A move that changes group counts even at the same index (the card lands in\n * another column), so only a same-group, same-index drop is \"nothing happened\".\n */\n const commit = useCallback(\n (from: number, to: number, fromGroup?: string, toGroup?: string): void => {\n if (from !== to || fromGroup !== toGroup) {\n onReorderRef.current({ from, to, fromGroup, toGroup });\n }\n reset();\n },\n [reset],\n );\n\n const setContainer = useCallback((node: HTMLElement | null): void => {\n containerRef.current = node;\n }, []);\n\n const handlePointerDown = useCallback(\n (index: number, group: string | undefined, event: ReactPointerEvent<HTMLElement>): void => {\n if (disabled) return;\n event.currentTarget.setPointerCapture?.(event.pointerId);\n setActiveGroup(group);\n setOverGroup(group);\n setActiveIndex(index);\n setOverIndex(index);\n },\n [disabled, setActiveGroup, setActiveIndex, setOverGroup, setOverIndex],\n );\n\n useEffect(() => {\n if (activeIndex === null) return;\n\n function onPointerMove(event: PointerEvent): void {\n const target = targetAtPoint(containerRef.current, event.clientX, event.clientY);\n if (!target) return;\n setOverGroup(target.group);\n setOverIndex(target.index);\n }\n\n function onPointerUp(): void {\n const from = activeRef.current;\n const to = overRef.current;\n if (from !== null && to !== null) {\n commit(from, to, activeGroupRef.current, overGroupRef.current);\n } else {\n reset();\n }\n }\n\n /**\n * Cancel the drag on `Escape`.\n *\n * Listened in the capture phase and marked consumed: the overlays' shared\n * `Escape` listener sits on `window` in the bubble phase, so a list sorted\n * inside a `Modal` would otherwise close the modal mid-drag instead of\n * just dropping the item back.\n */\n function onKeyDown(event: KeyboardEvent): void {\n if (event.key !== \"Escape\") return;\n event.preventDefault();\n reset();\n }\n\n window.addEventListener(\"pointermove\", onPointerMove);\n window.addEventListener(\"pointerup\", onPointerUp);\n window.addEventListener(\"pointercancel\", reset);\n window.addEventListener(\"keydown\", onKeyDown, true);\n return () => {\n window.removeEventListener(\"pointermove\", onPointerMove);\n window.removeEventListener(\"pointerup\", onPointerUp);\n window.removeEventListener(\"pointercancel\", reset);\n window.removeEventListener(\"keydown\", onKeyDown, true);\n };\n }, [activeIndex, commit, reset, setOverGroup, setOverIndex]);\n\n const handleKeyDown = useCallback(\n (\n index: number,\n group: string | undefined,\n event: ReactKeyboardEvent<HTMLElement>,\n ): void => {\n if (disabled) return;\n const picked = activeIndex !== null;\n\n switch (event.key) {\n case \" \":\n case \"Enter\":\n event.preventDefault();\n if (!picked) {\n setActiveGroup(group);\n setOverGroup(group);\n setActiveIndex(index);\n setOverIndex(index);\n } else if (overIndex !== null) {\n commit(activeIndex, overIndex, activeGroup, overGroup);\n }\n break;\n case \"ArrowDown\":\n case \"ArrowRight\": {\n if (!picked) return;\n event.preventDefault();\n if (overRef.current !== null) {\n setOverIndex(Math.min(overRef.current + 1, itemCount - 1));\n }\n break;\n }\n case \"ArrowUp\":\n case \"ArrowLeft\": {\n if (!picked) return;\n event.preventDefault();\n if (overRef.current !== null) {\n setOverIndex(Math.max(overRef.current - 1, 0));\n }\n break;\n }\n case \"Escape\":\n if (!picked) return;\n event.preventDefault();\n reset();\n break;\n default:\n break;\n }\n },\n [\n activeGroup,\n activeIndex,\n commit,\n overGroup,\n disabled,\n itemCount,\n overIndex,\n reset,\n setActiveGroup,\n setActiveIndex,\n setOverGroup,\n setOverIndex,\n ],\n );\n\n const getItemProps = useCallback(\n (index: number, group?: string): SortableItemProps => ({\n \"data-sortable-index\": index,\n \"data-sortable-group\": group,\n \"data-sortable-active\": (activeIndex === index && activeGroup === group) || undefined,\n onPointerDown: (event) => handlePointerDown(index, group, event),\n onKeyDown: (event) => handleKeyDown(index, group, event),\n tabIndex: disabled ? -1 : 0,\n role: \"option\",\n \"aria-roledescription\": roleDescription,\n \"aria-selected\": activeIndex === index && activeGroup === group,\n }),\n [activeGroup, activeIndex, disabled, handleKeyDown, handlePointerDown, roleDescription],\n );\n\n const getEmptyGroupProps = useCallback(\n (group: string) => ({ \"data-sortable-group\": group, \"data-sortable-empty\": true as const }),\n [],\n );\n\n const getListProps = useCallback(\n () => ({ role: \"listbox\" as const, \"aria-orientation\": \"vertical\" as const }),\n [],\n );\n\n return {\n activeIndex,\n overIndex,\n activeGroup,\n overGroup,\n getItemProps,\n getEmptyGroupProps,\n getListProps,\n cancel: reset,\n setContainer,\n };\n}\n"],"mappings":";;AA0GA,SAAgB,EAAY,GAAY,GAAc,GAAiB;CACnE,IAAI,MAAS,KAAM,IAAO,KAAK,IAAK,KAAK,KAAQ,EAAM,UAAU,KAAM,EAAM,QACzE,OAAO;CAEX,IAAM,IAAO,EAAM,MAAM,G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eAAe,GACrB,EAAM;EAId;CACJ,GACA;EACI;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CACJ;CA2BA,OAAO;EACH;EACA;EACA;EACA;EACA,cA9BiB,GAChB,GAAe,OAAuC;GACnD,uBAAuB;GACvB,uBAAuB;GACvB,wBAAyB,MAAgB,KAAS,MAAgB,KAAU,KAAA;GAC5E,gBAAgB,MAAU,EAAkB,GAAO,GAAO,CAAK;GAC/D,YAAY,MAAU,EAAc,GAAO,GAAO,CAAK;GACvD,UAAU,IAAW,KAAK;GAC1B,MAAM;GACN,wBAAwB;GACxB,iBAAiB,MAAgB,KAAS,MAAgB;EAC9D,IACA;GAAC;GAAa;GAAa;GAAU;GAAe;GAAmB;EAAe,CAkBtF;EACA,oBAhBuB,GACtB,OAAmB;GAAE,uBAAuB;GAAO,uBAAuB;EAAc,IACzF,CAAC,CAcD;EACA,cAZiB,SACV;GAAE,MAAM;GAAoB,oBAAoB;EAAoB,IAC3E,CAAC,CAUD;EACA,QAAQ;EACR;CACJ;AACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs");var t={offline:`Sem conexão com o servidor. Verifique sua internet e tente de novo.`,validation:`Confira os campos destacados e tente de novo.`},n=`tempest.error.offline`,r=`tempest.error.validation`;function i(){return typeof navigator<`u`&&navigator.onLine===!1}function a(t,n,r){if(n===``||n===e.syntheticDetail(r))return!1;let i=Object.values(t);return i.length===1&&i[0].trim()===n}function o(n,r,o){let s=o?.offline??t.offline;if(e.isApiError(n)){let i=n.code===void 0?void 0:o?.codes?.[n.code];if(i!==void 0)return i;if(n.status===0)return s;let
|
|
1
|
+
const e=require("./errors.cjs");var t={offline:`Sem conexão com o servidor. Verifique sua internet e tente de novo.`,validation:`Confira os campos destacados e tente de novo.`},n=`tempest.error.offline`,r=`tempest.error.validation`;function i(){return typeof navigator<`u`&&navigator.onLine===!1}function a(t,n,r){if(n===``||n===e.syntheticDetail(r))return!1;let i=Object.values(t);return i.length===1&&i[0].trim()===n}function o(n,r,o){let s=o?.offline??t.offline;if(e.isApiError(n)){let i=n.code===void 0?void 0:o?.codes?.[n.code];if(i!==void 0)return i;let c=o?.statuses?.[n.status];if(c!==void 0)return c;if(n.status===0)return s;let l=n.detail.trim();return n.fields&&Object.keys(n.fields).length>0?o?.useDetail!==!1&&a(n.fields,l,n.status)?l:o?.validation??t.validation:o?.useDetail!==!1&&l!==``&&l!==e.syntheticDetail(n.status)?l:`${r} (HTTP ${n.status})`}return i()?s:r}exports.API_ERROR_OFFLINE_KEY=n,exports.API_ERROR_VALIDATION_KEY=r,exports.DEFAULT_API_ERROR_STRINGS=t,exports.describeApiError=o;
|
|
2
2
|
//# sourceMappingURL=describe-api-error.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"describe-api-error.cjs","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError, syntheticDetail } from \"./errors\";\n\n/** The fixed sentences {@link describeApiError} may need. */\nexport interface ApiErrorStrings {\n /** Shown when the request never reached the server. */\n offline: string;\n /**\n * Shown when the backend rejected the payload field by field.\n *\n * The per-field messages are on `error.fields`, to be attached to the inputs\n * themselves; this sentence is what the toast says.\n *\n * It does not apply to the one rejection that named a single field with a\n * finished sentence — there the server's own `detail` is shown instead, since\n * it is the same string `fields` carries. Pass `useDetail: false` to force\n * this sentence in that case too.\n */\n validation: string;\n}\n\n/**\n * PT-BR defaults, used when no strings are supplied and no catalog answers.\n *\n * The SDK's copy is pt-BR everywhere else (`FilterBar`, `DataTable`, `Chat`), so\n * the default here matches rather than introducing an English string that only\n * shows up on a network failure.\n */\nexport const DEFAULT_API_ERROR_STRINGS: ApiErrorStrings = {\n offline: \"Sem conexão com o servidor. Verifique sua internet e tente de novo.\",\n validation: \"Confira os campos destacados e tente de novo.\",\n};\n\n/**\n * Translation key the {@link useDescribeApiError} hook looks up.\n *\n * A catalog that does not define it falls back to\n * {@link DEFAULT_API_ERROR_STRINGS}, because `t` returns the key itself when the\n * lookup misses and printing `tempest.error.offline` at the user would be worse\n * than printing pt-BR at them.\n */\nexport const API_ERROR_OFFLINE_KEY = \"tempest.error.offline\";\n\n/**\n * Translation key for the validation sentence, looked up the same way as\n * {@link API_ERROR_OFFLINE_KEY}.\n */\nexport const API_ERROR_VALIDATION_KEY = \"tempest.error.validation\";\n\n/**\n * Everything {@link describeApiError} accepts beyond the error and the fallback.\n *\n * Extends the fixed sentences rather than sitting beside them, so a caller that\n * already passed `{ offline, validation }` keeps compiling untouched.\n */\nexport interface DescribeApiErrorOptions extends Partial<ApiErrorStrings> {\n /**\n * Maps the backend's programmatic `code` to a sentence in your language.\n *\n * The client already surfaces `code` on `ApiError`, but without this every\n * app writes the same `switch` over it. A hit here wins over every other\n * step: it is the only sentence written for that exact case, by someone who\n * knew both the backend contract and the screen it lands on.\n */\n codes?: Readonly<Record<string, string>>;\n /**\n * Whether the backend's `detail` may be shown when no `code` matched.\n * Default `true`.\n *\n * Set it to `false` when `detail` is written for developers rather than\n * users, or when it could echo internals — the result is then always either\n * a sentence you wrote or the fallback.\n */\n useDetail?: boolean;\n}\n\n/**\n * Whether the browser currently reports itself as offline.\n *\n * `fetch` rejects a network failure with a plain `TypeError` whose message\n * differs per browser (\"Failed to fetch\", \"NetworkError when attempting to fetch\n * resource.\", \"Load failed\"), so sniffing the message is not portable. The online\n * flag is, and it is the signal that matters for the sentence being chosen.\n *\n * @returns `true` only when the environment positively says it is offline.\n */\nfunction browserIsOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/**\n * Whether `fields` is the flattened single-field envelope, carrying `detail`.\n *\n * The check is identity rather than shape-sniffing. `collectFields` has exactly\n * two sources: FastAPI's `detail` **list**, whose entries are the per-issue\n * messages, and the flattened envelope, whose one entry is built from the same\n * string that becomes `ApiError.detail`. So one entry equal to `detail` can only\n * have come from the second, and returning `detail` there shows the string the\n * form is already about to attach to that input.\n *\n * @param fields - The error's field messages.\n * @param detail - `error.detail`, already trimmed.\n * @param status - The HTTP status, to recognise the synthetic `Erro <status>`\n * that stands in when the body carried no message at all.\n * @returns Whether `detail` is safe to show as the sentence.\n */\nfunction singleFieldSentence(\n fields: Record<string, string>,\n detail: string,\n status: number,\n): boolean {\n if (detail === \"\" || detail === syntheticDetail(status)) return false;\n const messages = Object.values(fields);\n return messages.length === 1 && messages[0].trim() === detail;\n}\n\n/**\n * Turn any caught value into a sentence worth showing.\n *\n * The funnel, in order:\n *\n * 0. `codes[error.code]` — the sentence you wrote for that exact backend case.\n * Checked first because nothing the funnel derives can beat it, and because a\n * request that never landed carries no `code` for it to shadow.\n * 1. A request that never reached the server — `status === 0`, or a non-API\n * error thrown while the browser reports itself offline — produces the\n * offline sentence. This is the step apps skip, and skipping it renders\n * \"erro 0\" or a raw `TypeError` at the user.\n * 2. A validation rejection — `error.fields` is set — produces the validation\n * sentence, **not** `detail`. On a FastAPI `422` the `detail` line is assembled\n * from the backend's field paths and the validator's own wording\n * (`\"items.0.price: Input should be greater than 0\"`), which is right for a\n * log and wrong for a person: it is half English in a pt-BR screen and it\n * names internals. The per-field messages stay on `fields`, where a form can\n * attach them to the inputs that failed.\n *\n * **Unless the rejection named exactly one field and its message is\n * `detail` itself**, in which case `detail` is returned. That is not a guess\n * about the text: `collectFields` fills a single entry from `detail` only for\n * the flattened envelope a `tempest-fastapi-sdk` backend sends, where the\n * server wrote one finished sentence about one field (`\"CPF ou CNPJ\n * inválido\"`). Returning it shows the same string that is already on\n * `fields`, so nothing is invented and nothing is lost. The assembled FastAPI\n * line never reaches this branch, because it comes from the `detail` **list**\n * and its entries are the per-issue messages, not `detail`.\n *\n * This is a fix, not a preference. Before `namedField` shipped in 0.54.0,\n * `fields` was empty against that backend and the sentence reached the user\n * through step 3; filling `fields` silently replaced it with \"Confira os\n * campos destacados\", which presumes a screen that highlights fields — and\n * no app highlighted anything on the day of the bump.\n *\n * `useDetail: false` still suppresses it, and is the way to force the fixed\n * sentence for a backend whose text is written for developers. `validation`\n * does **not** override it, and that is on purpose: its own contract is the\n * sentence for a payload rejected *field by field*, which one field carrying\n * one finished sentence is not — and `useDescribeApiError` always passes\n * `validation`, so treating it as an override would mean the branch never ran\n * for any component, which is every caller that matters here.\n * 3. The backend's own `detail`, which is the most specific thing available and\n * is already written for a person — unless `useDetail: false` says that text\n * is for developers.\n * 4. `fallback`, with `(HTTP <status>)` appended when a status is known, so the\n * screenshot in the support ticket carries the one fact a developer needs.\n *\n * Pure on purpose: it works in an interceptor, in a logger and anywhere outside\n * the React tree. {@link useDescribeApiError} is the same funnel with the\n * sentences resolved through `I18nProvider`.\n *\n * @example\n * catch (error) {\n * toast(describeApiError(error, \"Não foi possível salvar o pedido\"));\n * }\n *\n * @example\n * catch (error) {\n * toast(\n * describeApiError(error, \"Não foi possível se candidatar\", {\n * codes: {\n * SERVICE_FULL: \"Este serviço atingiu o limite de vagas.\",\n * CANDIDATE_ALREADY_EXISTS: \"Você já se candidatou a este serviço.\",\n * },\n * useDetail: false,\n * }),\n * );\n * }\n *\n * @param error - The caught value, of any shape.\n * @param fallback - What to say when the error carries nothing better.\n * @param options - A `codes` catalog, `useDetail`, and overrides for the fixed\n * sentences.\n * @returns A sentence to show the user.\n */\nexport function describeApiError(\n error: unknown,\n fallback: string,\n options?: DescribeApiErrorOptions,\n): string {\n const offline = options?.offline ?? DEFAULT_API_ERROR_STRINGS.offline;\n\n if (isApiError(error)) {\n const mapped = error.code === undefined ? undefined : options?.codes?.[error.code];\n if (mapped !== undefined) return mapped;\n if (error.status === 0) return offline;\n const detail = error.detail.trim();\n if (error.fields && Object.keys(error.fields).length > 0) {\n if (\n options?.useDetail !== false &&\n singleFieldSentence(error.fields, detail, error.status)\n ) {\n return detail;\n }\n return options?.validation ?? DEFAULT_API_ERROR_STRINGS.validation;\n }\n if (\n options?.useDetail !== false &&\n detail !== \"\" &&\n detail !== syntheticDetail(error.status)\n ) {\n return detail;\n }\n return `${fallback} (HTTP ${error.status})`;\n }\n\n if (browserIsOffline()) return offline;\n\n return fallback;\n}\n"],"mappings":"gCAgCA,IAAa,EAA6C,CACtD,QAAS,sEACT,WAAY,+CAChB,EAUa,EAAwB,wBAMxB,EAA2B,2BAuCxC,SAAS,GAA4B,CACjC,OAAO,OAAO,UAAc,KAAe,UAAU,SAAW,EACpE,CAkBA,SAAS,EACL,EACA,EACA,EACO,CACP,GAAI,IAAW,IAAM,IAAW,EAAA,gBAAgB,CAAM,EAAG,MAAO,GAChE,IAAM,EAAW,OAAO,OAAO,CAAM,EACrC,OAAO,EAAS,SAAW,GAAK,EAAS,EAAE,CAAC,KAAK,IAAM,CAC3D,CA+EA,SAAgB,EACZ,EACA,EACA,EACM,CACN,IAAM,EAAU,GAAS,SAAW,EAA0B,QAE9D,GAAI,EAAA,WAAW,CAAK,EAAG,CACnB,IAAM,EAAS,EAAM,OAAS,IAAA,GAAY,IAAA,GAAY,GAAS,QAAQ,EAAM,MAC7E,GAAI,IAAW,IAAA,GAAW,OAAO,EACjC,GAAI,EAAM,SAAW,EAAG,OAAO,EAC/B,IAAM,EAAS,EAAM,OAAO,KAAK,EAiBjC,OAhBI,EAAM,QAAU,OAAO,KAAK,EAAM,MAAM,CAAC,CAAC,OAAS,EAE/C,GAAS,YAAc,IACvB,EAAoB,EAAM,OAAQ,EAAQ,EAAM,MAAM,EAE/C,EAEJ,GAAS,YAAc,EAA0B,WAGxD,GAAS,YAAc,IACvB,IAAW,IACX,IAAW,EAAA,gBAAgB,EAAM,MAAM,EAEhC,EAEJ,GAAG,EAAS,SAAS,EAAM,OAAO,EAC7C,CAIA,OAFI,EAAiB,EAAU,EAExB,CACX"}
|
|
1
|
+
{"version":3,"file":"describe-api-error.cjs","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError, syntheticDetail } from \"./errors\";\n\n/** The fixed sentences {@link describeApiError} may need. */\nexport interface ApiErrorStrings {\n /** Shown when the request never reached the server. */\n offline: string;\n /**\n * Shown when the backend rejected the payload field by field.\n *\n * The per-field messages are on `error.fields`, to be attached to the inputs\n * themselves; this sentence is what the toast says.\n *\n * It does not apply to the one rejection that named a single field with a\n * finished sentence — there the server's own `detail` is shown instead, since\n * it is the same string `fields` carries. Pass `useDetail: false` to force\n * this sentence in that case too.\n */\n validation: string;\n}\n\n/**\n * PT-BR defaults, used when no strings are supplied and no catalog answers.\n *\n * The SDK's copy is pt-BR everywhere else (`FilterBar`, `DataTable`, `Chat`), so\n * the default here matches rather than introducing an English string that only\n * shows up on a network failure.\n */\nexport const DEFAULT_API_ERROR_STRINGS: ApiErrorStrings = {\n offline: \"Sem conexão com o servidor. Verifique sua internet e tente de novo.\",\n validation: \"Confira os campos destacados e tente de novo.\",\n};\n\n/**\n * Translation key the {@link useDescribeApiError} hook looks up.\n *\n * A catalog that does not define it falls back to\n * {@link DEFAULT_API_ERROR_STRINGS}, because `t` returns the key itself when the\n * lookup misses and printing `tempest.error.offline` at the user would be worse\n * than printing pt-BR at them.\n */\nexport const API_ERROR_OFFLINE_KEY = \"tempest.error.offline\";\n\n/**\n * Translation key for the validation sentence, looked up the same way as\n * {@link API_ERROR_OFFLINE_KEY}.\n */\nexport const API_ERROR_VALIDATION_KEY = \"tempest.error.validation\";\n\n/**\n * Everything {@link describeApiError} accepts beyond the error and the fallback.\n *\n * Extends the fixed sentences rather than sitting beside them, so a caller that\n * already passed `{ offline, validation }` keeps compiling untouched.\n */\nexport interface DescribeApiErrorOptions extends Partial<ApiErrorStrings> {\n /**\n * Maps the backend's programmatic `code` to a sentence in your language.\n *\n * The client already surfaces `code` on `ApiError`, but without this every\n * app writes the same `switch` over it. A hit here wins over every other\n * step: it is the only sentence written for that exact case, by someone who\n * knew both the backend contract and the screen it lands on.\n */\n codes?: Readonly<Record<string, string>>;\n /**\n * Maps an HTTP status to a sentence, for the failures that arrive with no\n * useful body.\n *\n * `codes` covers the cases the backend named; this covers the ones it did\n * not. The reference case is the `403` of an admin-only route: the body\n * carries a generic `detail` (or none), so the funnel fell through to the\n * fallback and an administrator read \"Não foi possível carregar\" when the\n * fact that answers their question is \"esta listagem é só para\n * administradores\".\n *\n * Checked after `codes` and **before** the backend's `detail`: a generic\n * sentence emitted by the framework is worse than the one the app wrote for\n * that status. `useDetail: false` remains the way to suppress `detail`\n * entirely.\n *\n * A `0` key is honoured like any other, ahead of the offline sentence —\n * `statuses` is the caller's explicit map, and the fixed `offline` string is\n * already the way to reword that case. Status `0` covers a request that\n * never landed **and** one abandoned by the client timeout, so an app that\n * maps it is taking both.\n */\n statuses?: Readonly<Record<number, string>>;\n /**\n * Whether the backend's `detail` may be shown when no `code` matched.\n * Default `true`.\n *\n * Set it to `false` when `detail` is written for developers rather than\n * users, or when it could echo internals — the result is then always either\n * a sentence you wrote or the fallback.\n */\n useDetail?: boolean;\n}\n\n/**\n * Whether the browser currently reports itself as offline.\n *\n * `fetch` rejects a network failure with a plain `TypeError` whose message\n * differs per browser (\"Failed to fetch\", \"NetworkError when attempting to fetch\n * resource.\", \"Load failed\"), so sniffing the message is not portable. The online\n * flag is, and it is the signal that matters for the sentence being chosen.\n *\n * @returns `true` only when the environment positively says it is offline.\n */\nfunction browserIsOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/**\n * Whether `fields` is the flattened single-field envelope, carrying `detail`.\n *\n * The check is identity rather than shape-sniffing. `collectFields` has exactly\n * two sources: FastAPI's `detail` **list**, whose entries are the per-issue\n * messages, and the flattened envelope, whose one entry is built from the same\n * string that becomes `ApiError.detail`. So one entry equal to `detail` can only\n * have come from the second, and returning `detail` there shows the string the\n * form is already about to attach to that input.\n *\n * @param fields - The error's field messages.\n * @param detail - `error.detail`, already trimmed.\n * @param status - The HTTP status, to recognise the synthetic `Erro <status>`\n * that stands in when the body carried no message at all.\n * @returns Whether `detail` is safe to show as the sentence.\n */\nfunction singleFieldSentence(\n fields: Record<string, string>,\n detail: string,\n status: number,\n): boolean {\n if (detail === \"\" || detail === syntheticDetail(status)) return false;\n const messages = Object.values(fields);\n return messages.length === 1 && messages[0].trim() === detail;\n}\n\n/**\n * Turn any caught value into a sentence worth showing.\n *\n * The funnel, in order:\n *\n * 0. `codes[error.code]` — the sentence you wrote for that exact backend case.\n * Checked first because nothing the funnel derives can beat it, and because a\n * request that never landed carries no `code` for it to shadow.\n * 0.5. `statuses[error.status]` — the sentence for a whole class of failure,\n * for the errors that arrive with no useful body. It beats the backend's\n * `detail`, because a generic line emitted by the framework is worse than the\n * one the app wrote for that status, and it beats the offline sentence when\n * the caller maps `0` explicitly.\n * 1. A request that never reached the server — `status === 0`, or a non-API\n * error thrown while the browser reports itself offline — produces the\n * offline sentence. This is the step apps skip, and skipping it renders\n * \"erro 0\" or a raw `TypeError` at the user.\n * 2. A validation rejection — `error.fields` is set — produces the validation\n * sentence, **not** `detail`. On a FastAPI `422` the `detail` line is assembled\n * from the backend's field paths and the validator's own wording\n * (`\"items.0.price: Input should be greater than 0\"`), which is right for a\n * log and wrong for a person: it is half English in a pt-BR screen and it\n * names internals. The per-field messages stay on `fields`, where a form can\n * attach them to the inputs that failed.\n *\n * **Unless the rejection named exactly one field and its message is\n * `detail` itself**, in which case `detail` is returned. That is not a guess\n * about the text: `collectFields` fills a single entry from `detail` only for\n * the flattened envelope a `tempest-fastapi-sdk` backend sends, where the\n * server wrote one finished sentence about one field (`\"CPF ou CNPJ\n * inválido\"`). Returning it shows the same string that is already on\n * `fields`, so nothing is invented and nothing is lost. The assembled FastAPI\n * line never reaches this branch, because it comes from the `detail` **list**\n * and its entries are the per-issue messages, not `detail`.\n *\n * This is a fix, not a preference. Before `namedField` shipped in 0.54.0,\n * `fields` was empty against that backend and the sentence reached the user\n * through step 3; filling `fields` silently replaced it with \"Confira os\n * campos destacados\", which presumes a screen that highlights fields — and\n * no app highlighted anything on the day of the bump.\n *\n * `useDetail: false` still suppresses it, and is the way to force the fixed\n * sentence for a backend whose text is written for developers. `validation`\n * does **not** override it, and that is on purpose: its own contract is the\n * sentence for a payload rejected *field by field*, which one field carrying\n * one finished sentence is not — and `useDescribeApiError` always passes\n * `validation`, so treating it as an override would mean the branch never ran\n * for any component, which is every caller that matters here.\n * 3. The backend's own `detail`, which is the most specific thing available and\n * is already written for a person — unless `useDetail: false` says that text\n * is for developers.\n * 4. `fallback`, with `(HTTP <status>)` appended when a status is known, so the\n * screenshot in the support ticket carries the one fact a developer needs.\n *\n * Pure on purpose: it works in an interceptor, in a logger and anywhere outside\n * the React tree. {@link useDescribeApiError} is the same funnel with the\n * sentences resolved through `I18nProvider`.\n *\n * @example\n * catch (error) {\n * toast(describeApiError(error, \"Não foi possível salvar o pedido\"));\n * }\n *\n * @example\n * catch (error) {\n * toast(\n * describeApiError(error, \"Não foi possível se candidatar\", {\n * codes: {\n * SERVICE_FULL: \"Este serviço atingiu o limite de vagas.\",\n * CANDIDATE_ALREADY_EXISTS: \"Você já se candidatou a este serviço.\",\n * },\n * useDetail: false,\n * }),\n * );\n * }\n *\n * @param error - The caught value, of any shape.\n * @param fallback - What to say when the error carries nothing better.\n * @param options - A `codes` catalog, `useDetail`, and overrides for the fixed\n * sentences.\n * @returns A sentence to show the user.\n */\nexport function describeApiError(\n error: unknown,\n fallback: string,\n options?: DescribeApiErrorOptions,\n): string {\n const offline = options?.offline ?? DEFAULT_API_ERROR_STRINGS.offline;\n\n if (isApiError(error)) {\n const mapped = error.code === undefined ? undefined : options?.codes?.[error.code];\n if (mapped !== undefined) return mapped;\n const byStatus = options?.statuses?.[error.status];\n if (byStatus !== undefined) return byStatus;\n if (error.status === 0) return offline;\n const detail = error.detail.trim();\n if (error.fields && Object.keys(error.fields).length > 0) {\n if (\n options?.useDetail !== false &&\n singleFieldSentence(error.fields, detail, error.status)\n ) {\n return detail;\n }\n return options?.validation ?? DEFAULT_API_ERROR_STRINGS.validation;\n }\n if (\n options?.useDetail !== false &&\n detail !== \"\" &&\n detail !== syntheticDetail(error.status)\n ) {\n return detail;\n }\n return `${fallback} (HTTP ${error.status})`;\n }\n\n if (browserIsOffline()) return offline;\n\n return fallback;\n}\n"],"mappings":"gCAgCA,IAAa,EAA6C,CACtD,QAAS,sEACT,WAAY,+CAChB,EAUa,EAAwB,wBAMxB,EAA2B,2BA8DxC,SAAS,GAA4B,CACjC,OAAO,OAAO,UAAc,KAAe,UAAU,SAAW,EACpE,CAkBA,SAAS,EACL,EACA,EACA,EACO,CACP,GAAI,IAAW,IAAM,IAAW,EAAA,gBAAgB,CAAM,EAAG,MAAO,GAChE,IAAM,EAAW,OAAO,OAAO,CAAM,EACrC,OAAO,EAAS,SAAW,GAAK,EAAS,EAAE,CAAC,KAAK,IAAM,CAC3D,CAoFA,SAAgB,EACZ,EACA,EACA,EACM,CACN,IAAM,EAAU,GAAS,SAAW,EAA0B,QAE9D,GAAI,EAAA,WAAW,CAAK,EAAG,CACnB,IAAM,EAAS,EAAM,OAAS,IAAA,GAAY,IAAA,GAAY,GAAS,QAAQ,EAAM,MAC7E,GAAI,IAAW,IAAA,GAAW,OAAO,EACjC,IAAM,EAAW,GAAS,WAAW,EAAM,QAC3C,GAAI,IAAa,IAAA,GAAW,OAAO,EACnC,GAAI,EAAM,SAAW,EAAG,OAAO,EAC/B,IAAM,EAAS,EAAM,OAAO,KAAK,EAiBjC,OAhBI,EAAM,QAAU,OAAO,KAAK,EAAM,MAAM,CAAC,CAAC,OAAS,EAE/C,GAAS,YAAc,IACvB,EAAoB,EAAM,OAAQ,EAAQ,EAAM,MAAM,EAE/C,EAEJ,GAAS,YAAc,EAA0B,WAGxD,GAAS,YAAc,IACvB,IAAW,IACX,IAAW,EAAA,gBAAgB,EAAM,MAAM,EAEhC,EAEJ,GAAG,EAAS,SAAS,EAAM,OAAO,EAC7C,CAIA,OAFI,EAAiB,EAAU,EAExB,CACX"}
|
|
@@ -17,9 +17,11 @@ function s(r, i, s) {
|
|
|
17
17
|
if (e(r)) {
|
|
18
18
|
let e = r.code === void 0 ? void 0 : s?.codes?.[r.code];
|
|
19
19
|
if (e !== void 0) return e;
|
|
20
|
+
let a = s?.statuses?.[r.status];
|
|
21
|
+
if (a !== void 0) return a;
|
|
20
22
|
if (r.status === 0) return c;
|
|
21
|
-
let
|
|
22
|
-
return r.fields && Object.keys(r.fields).length > 0 ? s?.useDetail !== !1 && o(r.fields,
|
|
23
|
+
let l = r.detail.trim();
|
|
24
|
+
return r.fields && Object.keys(r.fields).length > 0 ? s?.useDetail !== !1 && o(r.fields, l, r.status) ? l : s?.validation ?? n.validation : s?.useDetail !== !1 && l !== "" && l !== t(r.status) ? l : `${i} (HTTP ${r.status})`;
|
|
23
25
|
}
|
|
24
26
|
return a() ? c : i;
|
|
25
27
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"describe-api-error.js","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError, syntheticDetail } from \"./errors\";\n\n/** The fixed sentences {@link describeApiError} may need. */\nexport interface ApiErrorStrings {\n /** Shown when the request never reached the server. */\n offline: string;\n /**\n * Shown when the backend rejected the payload field by field.\n *\n * The per-field messages are on `error.fields`, to be attached to the inputs\n * themselves; this sentence is what the toast says.\n *\n * It does not apply to the one rejection that named a single field with a\n * finished sentence — there the server's own `detail` is shown instead, since\n * it is the same string `fields` carries. Pass `useDetail: false` to force\n * this sentence in that case too.\n */\n validation: string;\n}\n\n/**\n * PT-BR defaults, used when no strings are supplied and no catalog answers.\n *\n * The SDK's copy is pt-BR everywhere else (`FilterBar`, `DataTable`, `Chat`), so\n * the default here matches rather than introducing an English string that only\n * shows up on a network failure.\n */\nexport const DEFAULT_API_ERROR_STRINGS: ApiErrorStrings = {\n offline: \"Sem conexão com o servidor. Verifique sua internet e tente de novo.\",\n validation: \"Confira os campos destacados e tente de novo.\",\n};\n\n/**\n * Translation key the {@link useDescribeApiError} hook looks up.\n *\n * A catalog that does not define it falls back to\n * {@link DEFAULT_API_ERROR_STRINGS}, because `t` returns the key itself when the\n * lookup misses and printing `tempest.error.offline` at the user would be worse\n * than printing pt-BR at them.\n */\nexport const API_ERROR_OFFLINE_KEY = \"tempest.error.offline\";\n\n/**\n * Translation key for the validation sentence, looked up the same way as\n * {@link API_ERROR_OFFLINE_KEY}.\n */\nexport const API_ERROR_VALIDATION_KEY = \"tempest.error.validation\";\n\n/**\n * Everything {@link describeApiError} accepts beyond the error and the fallback.\n *\n * Extends the fixed sentences rather than sitting beside them, so a caller that\n * already passed `{ offline, validation }` keeps compiling untouched.\n */\nexport interface DescribeApiErrorOptions extends Partial<ApiErrorStrings> {\n /**\n * Maps the backend's programmatic `code` to a sentence in your language.\n *\n * The client already surfaces `code` on `ApiError`, but without this every\n * app writes the same `switch` over it. A hit here wins over every other\n * step: it is the only sentence written for that exact case, by someone who\n * knew both the backend contract and the screen it lands on.\n */\n codes?: Readonly<Record<string, string>>;\n /**\n * Whether the backend's `detail` may be shown when no `code` matched.\n * Default `true`.\n *\n * Set it to `false` when `detail` is written for developers rather than\n * users, or when it could echo internals — the result is then always either\n * a sentence you wrote or the fallback.\n */\n useDetail?: boolean;\n}\n\n/**\n * Whether the browser currently reports itself as offline.\n *\n * `fetch` rejects a network failure with a plain `TypeError` whose message\n * differs per browser (\"Failed to fetch\", \"NetworkError when attempting to fetch\n * resource.\", \"Load failed\"), so sniffing the message is not portable. The online\n * flag is, and it is the signal that matters for the sentence being chosen.\n *\n * @returns `true` only when the environment positively says it is offline.\n */\nfunction browserIsOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/**\n * Whether `fields` is the flattened single-field envelope, carrying `detail`.\n *\n * The check is identity rather than shape-sniffing. `collectFields` has exactly\n * two sources: FastAPI's `detail` **list**, whose entries are the per-issue\n * messages, and the flattened envelope, whose one entry is built from the same\n * string that becomes `ApiError.detail`. So one entry equal to `detail` can only\n * have come from the second, and returning `detail` there shows the string the\n * form is already about to attach to that input.\n *\n * @param fields - The error's field messages.\n * @param detail - `error.detail`, already trimmed.\n * @param status - The HTTP status, to recognise the synthetic `Erro <status>`\n * that stands in when the body carried no message at all.\n * @returns Whether `detail` is safe to show as the sentence.\n */\nfunction singleFieldSentence(\n fields: Record<string, string>,\n detail: string,\n status: number,\n): boolean {\n if (detail === \"\" || detail === syntheticDetail(status)) return false;\n const messages = Object.values(fields);\n return messages.length === 1 && messages[0].trim() === detail;\n}\n\n/**\n * Turn any caught value into a sentence worth showing.\n *\n * The funnel, in order:\n *\n * 0. `codes[error.code]` — the sentence you wrote for that exact backend case.\n * Checked first because nothing the funnel derives can beat it, and because a\n * request that never landed carries no `code` for it to shadow.\n * 1. A request that never reached the server — `status === 0`, or a non-API\n * error thrown while the browser reports itself offline — produces the\n * offline sentence. This is the step apps skip, and skipping it renders\n * \"erro 0\" or a raw `TypeError` at the user.\n * 2. A validation rejection — `error.fields` is set — produces the validation\n * sentence, **not** `detail`. On a FastAPI `422` the `detail` line is assembled\n * from the backend's field paths and the validator's own wording\n * (`\"items.0.price: Input should be greater than 0\"`), which is right for a\n * log and wrong for a person: it is half English in a pt-BR screen and it\n * names internals. The per-field messages stay on `fields`, where a form can\n * attach them to the inputs that failed.\n *\n * **Unless the rejection named exactly one field and its message is\n * `detail` itself**, in which case `detail` is returned. That is not a guess\n * about the text: `collectFields` fills a single entry from `detail` only for\n * the flattened envelope a `tempest-fastapi-sdk` backend sends, where the\n * server wrote one finished sentence about one field (`\"CPF ou CNPJ\n * inválido\"`). Returning it shows the same string that is already on\n * `fields`, so nothing is invented and nothing is lost. The assembled FastAPI\n * line never reaches this branch, because it comes from the `detail` **list**\n * and its entries are the per-issue messages, not `detail`.\n *\n * This is a fix, not a preference. Before `namedField` shipped in 0.54.0,\n * `fields` was empty against that backend and the sentence reached the user\n * through step 3; filling `fields` silently replaced it with \"Confira os\n * campos destacados\", which presumes a screen that highlights fields — and\n * no app highlighted anything on the day of the bump.\n *\n * `useDetail: false` still suppresses it, and is the way to force the fixed\n * sentence for a backend whose text is written for developers. `validation`\n * does **not** override it, and that is on purpose: its own contract is the\n * sentence for a payload rejected *field by field*, which one field carrying\n * one finished sentence is not — and `useDescribeApiError` always passes\n * `validation`, so treating it as an override would mean the branch never ran\n * for any component, which is every caller that matters here.\n * 3. The backend's own `detail`, which is the most specific thing available and\n * is already written for a person — unless `useDetail: false` says that text\n * is for developers.\n * 4. `fallback`, with `(HTTP <status>)` appended when a status is known, so the\n * screenshot in the support ticket carries the one fact a developer needs.\n *\n * Pure on purpose: it works in an interceptor, in a logger and anywhere outside\n * the React tree. {@link useDescribeApiError} is the same funnel with the\n * sentences resolved through `I18nProvider`.\n *\n * @example\n * catch (error) {\n * toast(describeApiError(error, \"Não foi possível salvar o pedido\"));\n * }\n *\n * @example\n * catch (error) {\n * toast(\n * describeApiError(error, \"Não foi possível se candidatar\", {\n * codes: {\n * SERVICE_FULL: \"Este serviço atingiu o limite de vagas.\",\n * CANDIDATE_ALREADY_EXISTS: \"Você já se candidatou a este serviço.\",\n * },\n * useDetail: false,\n * }),\n * );\n * }\n *\n * @param error - The caught value, of any shape.\n * @param fallback - What to say when the error carries nothing better.\n * @param options - A `codes` catalog, `useDetail`, and overrides for the fixed\n * sentences.\n * @returns A sentence to show the user.\n */\nexport function describeApiError(\n error: unknown,\n fallback: string,\n options?: DescribeApiErrorOptions,\n): string {\n const offline = options?.offline ?? DEFAULT_API_ERROR_STRINGS.offline;\n\n if (isApiError(error)) {\n const mapped = error.code === undefined ? undefined : options?.codes?.[error.code];\n if (mapped !== undefined) return mapped;\n if (error.status === 0) return offline;\n const detail = error.detail.trim();\n if (error.fields && Object.keys(error.fields).length > 0) {\n if (\n options?.useDetail !== false &&\n singleFieldSentence(error.fields, detail, error.status)\n ) {\n return detail;\n }\n return options?.validation ?? DEFAULT_API_ERROR_STRINGS.validation;\n }\n if (\n options?.useDetail !== false &&\n detail !== \"\" &&\n detail !== syntheticDetail(error.status)\n ) {\n return detail;\n }\n return `${fallback} (HTTP ${error.status})`;\n }\n\n if (browserIsOffline()) return offline;\n\n return fallback;\n}\n"],"mappings":";;AAgCA,IAAa,IAA6C;CACtD,SAAS;CACT,YAAY;AAChB,GAUa,IAAwB,yBAMxB,IAA2B;AAuCxC,SAAS,IAA4B;CACjC,OAAO,OAAO,YAAc,OAAe,UAAU,WAAW;AACpE;AAkBA,SAAS,EACL,GACA,GACA,GACO;CACP,IAAI,MAAW,MAAM,MAAW,EAAgB,CAAM,GAAG,OAAO;CAChE,IAAM,IAAW,OAAO,OAAO,CAAM;CACrC,OAAO,EAAS,WAAW,KAAK,EAAS,EAAE,CAAC,KAAK,MAAM;AAC3D;AA+EA,SAAgB,EACZ,GACA,GACA,GACM;CACN,IAAM,IAAU,GAAS,WAAW,EAA0B;CAE9D,IAAI,EAAW,CAAK,GAAG;EACnB,IAAM,IAAS,EAAM,SAAS,KAAA,IAAY,KAAA,IAAY,GAAS,QAAQ,EAAM;EAC7E,IAAI,MAAW,KAAA,GAAW,OAAO;EACjC,IAAI,EAAM,WAAW,GAAG,OAAO;EAC/B,IAAM,IAAS,EAAM,OAAO,KAAK;EAiBjC,OAhBI,EAAM,UAAU,OAAO,KAAK,EAAM,MAAM,CAAC,CAAC,SAAS,IAE/C,GAAS,cAAc,MACvB,EAAoB,EAAM,QAAQ,GAAQ,EAAM,MAAM,IAE/C,IAEJ,GAAS,cAAc,EAA0B,aAGxD,GAAS,cAAc,MACvB,MAAW,MACX,MAAW,EAAgB,EAAM,MAAM,IAEhC,IAEJ,GAAG,EAAS,SAAS,EAAM,OAAO;CAC7C;CAIA,OAFI,EAAiB,IAAU,IAExB;AACX"}
|
|
1
|
+
{"version":3,"file":"describe-api-error.js","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError, syntheticDetail } from \"./errors\";\n\n/** The fixed sentences {@link describeApiError} may need. */\nexport interface ApiErrorStrings {\n /** Shown when the request never reached the server. */\n offline: string;\n /**\n * Shown when the backend rejected the payload field by field.\n *\n * The per-field messages are on `error.fields`, to be attached to the inputs\n * themselves; this sentence is what the toast says.\n *\n * It does not apply to the one rejection that named a single field with a\n * finished sentence — there the server's own `detail` is shown instead, since\n * it is the same string `fields` carries. Pass `useDetail: false` to force\n * this sentence in that case too.\n */\n validation: string;\n}\n\n/**\n * PT-BR defaults, used when no strings are supplied and no catalog answers.\n *\n * The SDK's copy is pt-BR everywhere else (`FilterBar`, `DataTable`, `Chat`), so\n * the default here matches rather than introducing an English string that only\n * shows up on a network failure.\n */\nexport const DEFAULT_API_ERROR_STRINGS: ApiErrorStrings = {\n offline: \"Sem conexão com o servidor. Verifique sua internet e tente de novo.\",\n validation: \"Confira os campos destacados e tente de novo.\",\n};\n\n/**\n * Translation key the {@link useDescribeApiError} hook looks up.\n *\n * A catalog that does not define it falls back to\n * {@link DEFAULT_API_ERROR_STRINGS}, because `t` returns the key itself when the\n * lookup misses and printing `tempest.error.offline` at the user would be worse\n * than printing pt-BR at them.\n */\nexport const API_ERROR_OFFLINE_KEY = \"tempest.error.offline\";\n\n/**\n * Translation key for the validation sentence, looked up the same way as\n * {@link API_ERROR_OFFLINE_KEY}.\n */\nexport const API_ERROR_VALIDATION_KEY = \"tempest.error.validation\";\n\n/**\n * Everything {@link describeApiError} accepts beyond the error and the fallback.\n *\n * Extends the fixed sentences rather than sitting beside them, so a caller that\n * already passed `{ offline, validation }` keeps compiling untouched.\n */\nexport interface DescribeApiErrorOptions extends Partial<ApiErrorStrings> {\n /**\n * Maps the backend's programmatic `code` to a sentence in your language.\n *\n * The client already surfaces `code` on `ApiError`, but without this every\n * app writes the same `switch` over it. A hit here wins over every other\n * step: it is the only sentence written for that exact case, by someone who\n * knew both the backend contract and the screen it lands on.\n */\n codes?: Readonly<Record<string, string>>;\n /**\n * Maps an HTTP status to a sentence, for the failures that arrive with no\n * useful body.\n *\n * `codes` covers the cases the backend named; this covers the ones it did\n * not. The reference case is the `403` of an admin-only route: the body\n * carries a generic `detail` (or none), so the funnel fell through to the\n * fallback and an administrator read \"Não foi possível carregar\" when the\n * fact that answers their question is \"esta listagem é só para\n * administradores\".\n *\n * Checked after `codes` and **before** the backend's `detail`: a generic\n * sentence emitted by the framework is worse than the one the app wrote for\n * that status. `useDetail: false` remains the way to suppress `detail`\n * entirely.\n *\n * A `0` key is honoured like any other, ahead of the offline sentence —\n * `statuses` is the caller's explicit map, and the fixed `offline` string is\n * already the way to reword that case. Status `0` covers a request that\n * never landed **and** one abandoned by the client timeout, so an app that\n * maps it is taking both.\n */\n statuses?: Readonly<Record<number, string>>;\n /**\n * Whether the backend's `detail` may be shown when no `code` matched.\n * Default `true`.\n *\n * Set it to `false` when `detail` is written for developers rather than\n * users, or when it could echo internals — the result is then always either\n * a sentence you wrote or the fallback.\n */\n useDetail?: boolean;\n}\n\n/**\n * Whether the browser currently reports itself as offline.\n *\n * `fetch` rejects a network failure with a plain `TypeError` whose message\n * differs per browser (\"Failed to fetch\", \"NetworkError when attempting to fetch\n * resource.\", \"Load failed\"), so sniffing the message is not portable. The online\n * flag is, and it is the signal that matters for the sentence being chosen.\n *\n * @returns `true` only when the environment positively says it is offline.\n */\nfunction browserIsOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/**\n * Whether `fields` is the flattened single-field envelope, carrying `detail`.\n *\n * The check is identity rather than shape-sniffing. `collectFields` has exactly\n * two sources: FastAPI's `detail` **list**, whose entries are the per-issue\n * messages, and the flattened envelope, whose one entry is built from the same\n * string that becomes `ApiError.detail`. So one entry equal to `detail` can only\n * have come from the second, and returning `detail` there shows the string the\n * form is already about to attach to that input.\n *\n * @param fields - The error's field messages.\n * @param detail - `error.detail`, already trimmed.\n * @param status - The HTTP status, to recognise the synthetic `Erro <status>`\n * that stands in when the body carried no message at all.\n * @returns Whether `detail` is safe to show as the sentence.\n */\nfunction singleFieldSentence(\n fields: Record<string, string>,\n detail: string,\n status: number,\n): boolean {\n if (detail === \"\" || detail === syntheticDetail(status)) return false;\n const messages = Object.values(fields);\n return messages.length === 1 && messages[0].trim() === detail;\n}\n\n/**\n * Turn any caught value into a sentence worth showing.\n *\n * The funnel, in order:\n *\n * 0. `codes[error.code]` — the sentence you wrote for that exact backend case.\n * Checked first because nothing the funnel derives can beat it, and because a\n * request that never landed carries no `code` for it to shadow.\n * 0.5. `statuses[error.status]` — the sentence for a whole class of failure,\n * for the errors that arrive with no useful body. It beats the backend's\n * `detail`, because a generic line emitted by the framework is worse than the\n * one the app wrote for that status, and it beats the offline sentence when\n * the caller maps `0` explicitly.\n * 1. A request that never reached the server — `status === 0`, or a non-API\n * error thrown while the browser reports itself offline — produces the\n * offline sentence. This is the step apps skip, and skipping it renders\n * \"erro 0\" or a raw `TypeError` at the user.\n * 2. A validation rejection — `error.fields` is set — produces the validation\n * sentence, **not** `detail`. On a FastAPI `422` the `detail` line is assembled\n * from the backend's field paths and the validator's own wording\n * (`\"items.0.price: Input should be greater than 0\"`), which is right for a\n * log and wrong for a person: it is half English in a pt-BR screen and it\n * names internals. The per-field messages stay on `fields`, where a form can\n * attach them to the inputs that failed.\n *\n * **Unless the rejection named exactly one field and its message is\n * `detail` itself**, in which case `detail` is returned. That is not a guess\n * about the text: `collectFields` fills a single entry from `detail` only for\n * the flattened envelope a `tempest-fastapi-sdk` backend sends, where the\n * server wrote one finished sentence about one field (`\"CPF ou CNPJ\n * inválido\"`). Returning it shows the same string that is already on\n * `fields`, so nothing is invented and nothing is lost. The assembled FastAPI\n * line never reaches this branch, because it comes from the `detail` **list**\n * and its entries are the per-issue messages, not `detail`.\n *\n * This is a fix, not a preference. Before `namedField` shipped in 0.54.0,\n * `fields` was empty against that backend and the sentence reached the user\n * through step 3; filling `fields` silently replaced it with \"Confira os\n * campos destacados\", which presumes a screen that highlights fields — and\n * no app highlighted anything on the day of the bump.\n *\n * `useDetail: false` still suppresses it, and is the way to force the fixed\n * sentence for a backend whose text is written for developers. `validation`\n * does **not** override it, and that is on purpose: its own contract is the\n * sentence for a payload rejected *field by field*, which one field carrying\n * one finished sentence is not — and `useDescribeApiError` always passes\n * `validation`, so treating it as an override would mean the branch never ran\n * for any component, which is every caller that matters here.\n * 3. The backend's own `detail`, which is the most specific thing available and\n * is already written for a person — unless `useDetail: false` says that text\n * is for developers.\n * 4. `fallback`, with `(HTTP <status>)` appended when a status is known, so the\n * screenshot in the support ticket carries the one fact a developer needs.\n *\n * Pure on purpose: it works in an interceptor, in a logger and anywhere outside\n * the React tree. {@link useDescribeApiError} is the same funnel with the\n * sentences resolved through `I18nProvider`.\n *\n * @example\n * catch (error) {\n * toast(describeApiError(error, \"Não foi possível salvar o pedido\"));\n * }\n *\n * @example\n * catch (error) {\n * toast(\n * describeApiError(error, \"Não foi possível se candidatar\", {\n * codes: {\n * SERVICE_FULL: \"Este serviço atingiu o limite de vagas.\",\n * CANDIDATE_ALREADY_EXISTS: \"Você já se candidatou a este serviço.\",\n * },\n * useDetail: false,\n * }),\n * );\n * }\n *\n * @param error - The caught value, of any shape.\n * @param fallback - What to say when the error carries nothing better.\n * @param options - A `codes` catalog, `useDetail`, and overrides for the fixed\n * sentences.\n * @returns A sentence to show the user.\n */\nexport function describeApiError(\n error: unknown,\n fallback: string,\n options?: DescribeApiErrorOptions,\n): string {\n const offline = options?.offline ?? DEFAULT_API_ERROR_STRINGS.offline;\n\n if (isApiError(error)) {\n const mapped = error.code === undefined ? undefined : options?.codes?.[error.code];\n if (mapped !== undefined) return mapped;\n const byStatus = options?.statuses?.[error.status];\n if (byStatus !== undefined) return byStatus;\n if (error.status === 0) return offline;\n const detail = error.detail.trim();\n if (error.fields && Object.keys(error.fields).length > 0) {\n if (\n options?.useDetail !== false &&\n singleFieldSentence(error.fields, detail, error.status)\n ) {\n return detail;\n }\n return options?.validation ?? DEFAULT_API_ERROR_STRINGS.validation;\n }\n if (\n options?.useDetail !== false &&\n detail !== \"\" &&\n detail !== syntheticDetail(error.status)\n ) {\n return detail;\n }\n return `${fallback} (HTTP ${error.status})`;\n }\n\n if (browserIsOffline()) return offline;\n\n return fallback;\n}\n"],"mappings":";;AAgCA,IAAa,IAA6C;CACtD,SAAS;CACT,YAAY;AAChB,GAUa,IAAwB,yBAMxB,IAA2B;AA8DxC,SAAS,IAA4B;CACjC,OAAO,OAAO,YAAc,OAAe,UAAU,WAAW;AACpE;AAkBA,SAAS,EACL,GACA,GACA,GACO;CACP,IAAI,MAAW,MAAM,MAAW,EAAgB,CAAM,GAAG,OAAO;CAChE,IAAM,IAAW,OAAO,OAAO,CAAM;CACrC,OAAO,EAAS,WAAW,KAAK,EAAS,EAAE,CAAC,KAAK,MAAM;AAC3D;AAoFA,SAAgB,EACZ,GACA,GACA,GACM;CACN,IAAM,IAAU,GAAS,WAAW,EAA0B;CAE9D,IAAI,EAAW,CAAK,GAAG;EACnB,IAAM,IAAS,EAAM,SAAS,KAAA,IAAY,KAAA,IAAY,GAAS,QAAQ,EAAM;EAC7E,IAAI,MAAW,KAAA,GAAW,OAAO;EACjC,IAAM,IAAW,GAAS,WAAW,EAAM;EAC3C,IAAI,MAAa,KAAA,GAAW,OAAO;EACnC,IAAI,EAAM,WAAW,GAAG,OAAO;EAC/B,IAAM,IAAS,EAAM,OAAO,KAAK;EAiBjC,OAhBI,EAAM,UAAU,OAAO,KAAK,EAAM,MAAM,CAAC,CAAC,SAAS,IAE/C,GAAS,cAAc,MACvB,EAAoB,EAAM,QAAQ,GAAQ,EAAM,MAAM,IAE/C,IAEJ,GAAS,cAAc,EAA0B,aAGxD,GAAS,cAAc,MACvB,MAAW,MACX,MAAW,EAAgB,EAAM,MAAM,IAEhC,IAEJ,GAAG,EAAS,SAAS,EAAM,OAAO;CAC7C;CAIA,OAFI,EAAiB,IAAU,IAExB;AACX"}
|
package/dist/styles/actions.css
CHANGED
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
@keyframes tempest_tempest-spin_UOSVC{0%{transform:rotate(0)}to{transform:rotate(360deg)}}
|
|
43
43
|
.tempest_root_5ZetV{display:inline-flex;position:relative}
|
|
44
44
|
.tempest_menu_-RiRW{z-index:var(--tempest-z-dropdown);background-color:var(--tempest-bg);border:1px solid var(--tempest-border);border-radius:var(--tempest-radius-lg);min-width:180px;max-width:320px;box-shadow:var(--tempest-shadow-lg);padding:var(--tempest-space-1);font-family:var(--tempest-font-sans);font-size:var(--tempest-text-base);animation:tempest_tempest-menu-in_uCs9q var(--tempest-duration-fast) var(--tempest-ease-out);margin:0;list-style:none;position:absolute}
|
|
45
|
+
.tempest_portalled_b7vCf{z-index:var(--tempest-z-popover)}
|
|
45
46
|
.tempest_bottomStart_z60h9{top:calc(100% + 4px);left:0}
|
|
46
47
|
.tempest_bottomEnd_b1tmU{top:calc(100% + 4px);right:0}
|
|
47
48
|
.tempest_topStart_A0em2{bottom:calc(100% + 4px);left:0}
|
|
@@ -92,6 +93,7 @@
|
|
|
92
93
|
.tempest_root_vEMon{display:inline-flex;position:relative}
|
|
93
94
|
.tempest_popover_E9K9X{z-index:var(--tempest-z-popover);background-color:var(--tempest-bg);color:var(--tempest-text);border:1px solid var(--tempest-border);border-radius:var(--tempest-radius-lg);box-shadow:var(--tempest-shadow-lg);padding:var(--tempest-space-3) var(--tempest-space-4);min-width:200px;max-width:320px;font-family:var(--tempest-font-sans);font-size:var(--tempest-text-base);line-height:var(--tempest-leading-snug);animation:tempest_tempest-popover-in_W8miP var(--tempest-duration-fast) var(--tempest-ease-out);position:absolute}
|
|
94
95
|
.tempest_popover_E9K9X:focus{outline:none}
|
|
96
|
+
.tempest_portalled_pZ553{--tempest-popover-tx:0}
|
|
95
97
|
.tempest_top_TYlrh{bottom:calc(100% + 8px);left:50%;transform:translate(-50%)}
|
|
96
98
|
.tempest_bottom_wGs70{top:calc(100% + 8px);left:50%;transform:translate(-50%)}
|
|
97
99
|
.tempest_left_h7fCr{top:50%;right:calc(100% + 8px);transform:translateY(-50%)}
|
|
@@ -104,6 +106,7 @@
|
|
|
104
106
|
.tempest_bottom_9Twz4{top:calc(100% + 8px);left:50%;transform:translate(-50%)}
|
|
105
107
|
.tempest_left_UPdrG{top:50%;right:calc(100% + 8px);transform:translateY(-50%)}
|
|
106
108
|
.tempest_right_CV--T{top:50%;left:calc(100% + 8px);transform:translateY(-50%)}
|
|
109
|
+
.tempest_portalled_MImIY{bottom:auto;right:auto;transform:none}
|
|
107
110
|
@keyframes tempest_tempest-tooltip-in_csYeZ{0%{opacity:0;transform:scale(.94) translate(var(--tempest-tx,0), var(--tempest-ty,0))}to{opacity:1}}
|
|
108
111
|
@media (prefers-reduced-motion:reduce){.tempest_bubble_TPGHB{animation:none}}
|
|
109
112
|
@media (hover:none){.tempest_bubble_TPGHB{display:none}}
|
package/dist/styles/advanced.css
CHANGED
|
@@ -43,6 +43,7 @@
|
|
|
43
43
|
.tempest_bottom_2rLAA{top:calc(100% + 8px);left:50%;transform:translate(-50%)}
|
|
44
44
|
.tempest_left_tqGPt{top:50%;right:calc(100% + 8px);transform:translateY(-50%)}
|
|
45
45
|
.tempest_right_9Fe6S{top:50%;left:calc(100% + 8px);transform:translateY(-50%)}
|
|
46
|
+
.tempest_portalled_GMcNw{bottom:auto;right:auto;transform:none}
|
|
46
47
|
@keyframes tempest_tempest-hover-card-in_jD85J{0%{opacity:0}to{opacity:1}}
|
|
47
48
|
@media (prefers-reduced-motion:reduce){.tempest_card_CoGx4{animation:none}}
|
|
48
49
|
.tempest_label_RaRvM{align-items:center;gap:var(--tempest-space-1);color:var(--tempest-text);font-family:var(--tempest-font-sans);font-size:var(--tempest-text-sm);font-weight:var(--tempest-weight-medium);line-height:var(--tempest-leading-snug);display:inline-flex}
|
|
@@ -16,3 +16,4 @@
|
|
|
16
16
|
.tempest_helper_OzB7V{font-size:var(--tempest-text-xs);color:var(--tempest-text-muted)}
|
|
17
17
|
.tempest_errorText_X18sQ{font-size:var(--tempest-text-xs);color:var(--tempest-danger)}
|
|
18
18
|
.tempest_wrapper_TNvle.tempest_error_bnVuM .tempest_input_-HTv1{border-color:var(--tempest-danger)}
|
|
19
|
+
.tempest_portalled_C9jFy{font-family:var(--tempest-font-sans);z-index:var(--tempest-z-popover);right:auto}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/* Generated by scripts/split-css.mjs — do not edit. */
|
|
2
2
|
.tempest_root_5ZetV{display:inline-flex;position:relative}
|
|
3
3
|
.tempest_menu_-RiRW{z-index:var(--tempest-z-dropdown);background-color:var(--tempest-bg);border:1px solid var(--tempest-border);border-radius:var(--tempest-radius-lg);min-width:180px;max-width:320px;box-shadow:var(--tempest-shadow-lg);padding:var(--tempest-space-1);font-family:var(--tempest-font-sans);font-size:var(--tempest-text-base);animation:tempest_tempest-menu-in_uCs9q var(--tempest-duration-fast) var(--tempest-ease-out);margin:0;list-style:none;position:absolute}
|
|
4
|
+
.tempest_portalled_b7vCf{z-index:var(--tempest-z-popover)}
|
|
4
5
|
.tempest_bottomStart_z60h9{top:calc(100% + 4px);left:0}
|
|
5
6
|
.tempest_bottomEnd_b1tmU{top:calc(100% + 4px);right:0}
|
|
6
7
|
.tempest_topStart_A0em2{bottom:calc(100% + 4px);left:0}
|
|
@@ -7,5 +7,6 @@
|
|
|
7
7
|
.tempest_bottom_2rLAA{top:calc(100% + 8px);left:50%;transform:translate(-50%)}
|
|
8
8
|
.tempest_left_tqGPt{top:50%;right:calc(100% + 8px);transform:translateY(-50%)}
|
|
9
9
|
.tempest_right_9Fe6S{top:50%;left:calc(100% + 8px);transform:translateY(-50%)}
|
|
10
|
+
.tempest_portalled_GMcNw{bottom:auto;right:auto;transform:none}
|
|
10
11
|
@keyframes tempest_tempest-hover-card-in_jD85J{0%{opacity:0}to{opacity:1}}
|
|
11
12
|
@media (prefers-reduced-motion:reduce){.tempest_card_CoGx4{animation:none}}
|
|
@@ -15,3 +15,4 @@
|
|
|
15
15
|
.tempest_separator_LfK3t{background-color:var(--tempest-border);height:1px;margin:var(--tempest-space-1) 0}
|
|
16
16
|
@keyframes tempest_tempest-menubar-in_gOQQD{0%{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}
|
|
17
17
|
@media (prefers-reduced-motion:reduce){.tempest_panel_6ta6u{animation:none}}
|
|
18
|
+
.tempest_portalled_tdHc1{font-family:var(--tempest-font-sans);font-size:var(--tempest-text-sm);z-index:var(--tempest-z-popover)}
|
|
@@ -19,3 +19,4 @@
|
|
|
19
19
|
.tempest_helper_c7aH3{font-size:var(--tempest-text-xs);color:var(--tempest-text-muted)}
|
|
20
20
|
.tempest_errorText_qZR9s{font-size:var(--tempest-text-xs);color:var(--tempest-danger)}
|
|
21
21
|
.tempest_wrapper_6xZZr.tempest_error_DIOTW .tempest_field_GpA0V{border-color:var(--tempest-danger)}
|
|
22
|
+
.tempest_portalled_i1wmW{font-family:var(--tempest-font-sans);z-index:var(--tempest-z-popover);right:auto}
|
|
@@ -10,3 +10,4 @@
|
|
|
10
10
|
.tempest_subItem_LjtO7 .tempest_link_67ULr{width:100%}
|
|
11
11
|
@keyframes tempest_tempest-nav-menu-in_8tNCR{0%{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}
|
|
12
12
|
@media (prefers-reduced-motion:reduce){.tempest_panel_N2ujp{animation:none}}
|
|
13
|
+
.tempest_portalled_2V2JB{font-family:var(--tempest-font-sans);font-size:var(--tempest-text-base);z-index:var(--tempest-z-popover)}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
.tempest_root_vEMon{display:inline-flex;position:relative}
|
|
3
3
|
.tempest_popover_E9K9X{z-index:var(--tempest-z-popover);background-color:var(--tempest-bg);color:var(--tempest-text);border:1px solid var(--tempest-border);border-radius:var(--tempest-radius-lg);box-shadow:var(--tempest-shadow-lg);padding:var(--tempest-space-3) var(--tempest-space-4);min-width:200px;max-width:320px;font-family:var(--tempest-font-sans);font-size:var(--tempest-text-base);line-height:var(--tempest-leading-snug);animation:tempest_tempest-popover-in_W8miP var(--tempest-duration-fast) var(--tempest-ease-out);position:absolute}
|
|
4
4
|
.tempest_popover_E9K9X:focus{outline:none}
|
|
5
|
+
.tempest_portalled_pZ553{--tempest-popover-tx:0}
|
|
5
6
|
.tempest_top_TYlrh{bottom:calc(100% + 8px);left:50%;transform:translate(-50%)}
|
|
6
7
|
.tempest_bottom_wGs70{top:calc(100% + 8px);left:50%;transform:translate(-50%)}
|
|
7
8
|
.tempest_left_h7fCr{top:50%;right:calc(100% + 8px);transform:translateY(-50%)}
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
.tempest_bottom_9Twz4{top:calc(100% + 8px);left:50%;transform:translate(-50%)}
|
|
6
6
|
.tempest_left_UPdrG{top:50%;right:calc(100% + 8px);transform:translateY(-50%)}
|
|
7
7
|
.tempest_right_CV--T{top:50%;left:calc(100% + 8px);transform:translateY(-50%)}
|
|
8
|
+
.tempest_portalled_MImIY{bottom:auto;right:auto;transform:none}
|
|
8
9
|
@keyframes tempest_tempest-tooltip-in_csYeZ{0%{opacity:0;transform:scale(.94) translate(var(--tempest-tx,0), var(--tempest-ty,0))}to{opacity:1}}
|
|
9
10
|
@media (prefers-reduced-motion:reduce){.tempest_bubble_TPGHB{animation:none}}
|
|
10
11
|
@media (hover:none){.tempest_bubble_TPGHB{display:none}}
|
package/dist/styles/forms.css
CHANGED
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
.tempest_helper_OzB7V{font-size:var(--tempest-text-xs);color:var(--tempest-text-muted)}
|
|
39
39
|
.tempest_errorText_X18sQ{font-size:var(--tempest-text-xs);color:var(--tempest-danger)}
|
|
40
40
|
.tempest_wrapper_TNvle.tempest_error_bnVuM .tempest_input_-HTv1{border-color:var(--tempest-danger)}
|
|
41
|
+
.tempest_portalled_C9jFy{font-family:var(--tempest-font-sans);z-index:var(--tempest-z-popover);right:auto}
|
|
41
42
|
.tempest_root_fVC66{gap:var(--tempest-space-2);padding:var(--tempest-space-3);border:1px solid var(--tempest-border);border-radius:var(--tempest-radius-lg);background-color:var(--tempest-surface);color:var(--tempest-text);font-family:var(--tempest-font-sans);-webkit-user-select:none;user-select:none;flex-direction:column;display:inline-flex}
|
|
42
43
|
.tempest_header_sTdRM{justify-content:space-between;align-items:center;gap:var(--tempest-space-2);display:flex}
|
|
43
44
|
.tempest_headerSpacer_nqeNO{flex:1}
|
|
@@ -159,6 +160,7 @@
|
|
|
159
160
|
.tempest_helper_c7aH3{font-size:var(--tempest-text-xs);color:var(--tempest-text-muted)}
|
|
160
161
|
.tempest_errorText_qZR9s{font-size:var(--tempest-text-xs);color:var(--tempest-danger)}
|
|
161
162
|
.tempest_wrapper_6xZZr.tempest_error_DIOTW .tempest_field_GpA0V{border-color:var(--tempest-danger)}
|
|
163
|
+
.tempest_portalled_i1wmW{font-family:var(--tempest-font-sans);z-index:var(--tempest-z-popover);right:auto}
|
|
162
164
|
.tempest_wrapper_zEU-L{gap:var(--tempest-space-1);font-family:var(--tempest-font-sans);flex-direction:column;width:100%;display:flex}
|
|
163
165
|
.tempest_label_ps3gD{font-size:var(--tempest-text-sm);font-weight:var(--tempest-weight-medium);color:var(--tempest-text)}
|
|
164
166
|
.tempest_field_7taZG{border:1px solid var(--tempest-border);border-radius:var(--tempest-radius-md);background:var(--tempest-surface);transition:border-color var(--tempest-duration-fast,.12s);align-items:center;display:flex;position:relative}
|
|
@@ -63,6 +63,7 @@
|
|
|
63
63
|
.tempest_separator_LfK3t{background-color:var(--tempest-border);height:1px;margin:var(--tempest-space-1) 0}
|
|
64
64
|
@keyframes tempest_tempest-menubar-in_gOQQD{0%{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}
|
|
65
65
|
@media (prefers-reduced-motion:reduce){.tempest_panel_6ta6u{animation:none}}
|
|
66
|
+
.tempest_portalled_tdHc1{font-family:var(--tempest-font-sans);font-size:var(--tempest-text-sm);z-index:var(--tempest-z-popover)}
|
|
66
67
|
.tempest_navbar_Ey25T{align-items:center;gap:var(--tempest-space-4);padding:var(--tempest-space-3) var(--tempest-space-4);width:100%;min-height:56px;font-family:var(--tempest-font-sans);padding-top:max(var(--tempest-space-3), env(safe-area-inset-top,0));display:flex}
|
|
67
68
|
.tempest_navbar_Ey25T.tempest_surface_xyKhM{background:var(--tempest-surface);color:var(--tempest-text)}
|
|
68
69
|
.tempest_navbar_Ey25T.tempest_primary_w3ft-{background:var(--tempest-primary);color:var(--tempest-primary-foreground)}
|
|
@@ -83,6 +84,7 @@
|
|
|
83
84
|
.tempest_subItem_LjtO7 .tempest_link_67ULr{width:100%}
|
|
84
85
|
@keyframes tempest_tempest-nav-menu-in_8tNCR{0%{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}
|
|
85
86
|
@media (prefers-reduced-motion:reduce){.tempest_panel_N2ujp{animation:none}}
|
|
87
|
+
.tempest_portalled_2V2JB{font-family:var(--tempest-font-sans);font-size:var(--tempest-text-base);z-index:var(--tempest-z-popover)}
|
|
86
88
|
.tempest_rail_bvns5{align-items:center;gap:var(--tempest-space-2);width:80px;height:100%;padding:var(--tempest-space-3) var(--tempest-space-2);background:var(--tempest-surface);border-right:1px solid var(--tempest-border);font-family:var(--tempest-font-sans);flex-direction:column;display:flex}
|
|
87
89
|
.tempest_header_Mikit{width:100%;margin-bottom:var(--tempest-space-2);justify-content:center;align-items:center;display:flex}
|
|
88
90
|
.tempest_list_rS6XJ{align-items:stretch;gap:var(--tempest-space-1);flex-direction:column;width:100%;margin:0;padding:0;list-style:none;display:flex}
|