{"version":3,"file":"use-pending-control-focus.mjs","names":[],"sources":["../../../src/hooks/use-pending-control-focus/use-pending-control-focus.ts"],"sourcesContent":["import { RefObject, useEffect, useRef } from 'react';\nimport { focusControl } from '../../utils/handle-control-key-down/handle-control-key-down';\n\ninterface PendingControlFocus {\n  direction: 'up' | 'down' | 'left' | 'right';\n  levelIndex: number | 'last';\n  rowIndex: number | 'last';\n  cellIndex: number | 'last';\n}\n\ninterface UsePendingControlFocusInput {\n  controlsRef: RefObject<HTMLButtonElement[][][]>;\n\n  /** Value that changes when the displayed period changes, focus is applied only after it has changed */\n  period: string;\n}\n\nfunction resolveIndex(index: number | 'last', length: number) {\n  return index === 'last' ? length - 1 : Math.min(index, length - 1);\n}\n\nexport function usePendingControlFocus({ controlsRef, period }: UsePendingControlFocusInput) {\n  const pending = useRef<(PendingControlFocus & { period: string }) | null>(null);\n\n  useEffect(() => {\n    const request = pending.current;\n    pending.current = null;\n\n    if (!request || request.period === period || !controlsRef.current) {\n      return;\n    }\n\n    const levelIndex = resolveIndex(request.levelIndex, controlsRef.current.length);\n    const rows = controlsRef.current[levelIndex] || [];\n    let rowIndex = resolveIndex(request.rowIndex, rows.length);\n\n    if (\n      request.rowIndex === 'last' &&\n      typeof request.cellIndex === 'number' &&\n      rowIndex > 0 &&\n      request.cellIndex >= (rows[rowIndex] || []).length\n    ) {\n      rowIndex -= 1;\n    }\n\n    const cells = rows[rowIndex] || [];\n    const cellIndex = resolveIndex(request.cellIndex, cells.length);\n\n    focusControl({\n      controlsRef,\n      direction: request.direction,\n      levelIndex,\n      rowIndex,\n      cellIndex,\n    });\n  });\n\n  return (request: PendingControlFocus) => {\n    pending.current = { ...request, period };\n  };\n}\n"],"mappings":";;;;AAiBA,SAAS,aAAa,OAAwB,QAAgB;CAC5D,OAAO,UAAU,SAAS,SAAS,IAAI,KAAK,IAAI,OAAO,SAAS,CAAC;AACnE;AAEA,SAAgB,uBAAuB,EAAE,aAAa,UAAuC;CAC3F,MAAM,UAAU,OAA0D,IAAI;CAE9E,gBAAgB;EACd,MAAM,UAAU,QAAQ;EACxB,QAAQ,UAAU;EAElB,IAAI,CAAC,WAAW,QAAQ,WAAW,UAAU,CAAC,YAAY,SACxD;EAGF,MAAM,aAAa,aAAa,QAAQ,YAAY,YAAY,QAAQ,MAAM;EAC9E,MAAM,OAAO,YAAY,QAAQ,eAAe,CAAC;EACjD,IAAI,WAAW,aAAa,QAAQ,UAAU,KAAK,MAAM;EAEzD,IACE,QAAQ,aAAa,UACrB,OAAO,QAAQ,cAAc,YAC7B,WAAW,KACX,QAAQ,cAAc,KAAK,aAAa,CAAC,EAAA,CAAG,QAE5C,YAAY;EAGd,MAAM,QAAQ,KAAK,aAAa,CAAC;EACjC,MAAM,YAAY,aAAa,QAAQ,WAAW,MAAM,MAAM;EAE9D,aAAa;GACX;GACA,WAAW,QAAQ;GACnB;GACA;GACA;EACF,CAAC;CACH,CAAC;CAED,QAAQ,YAAiC;EACvC,QAAQ,UAAU;GAAE,GAAG;GAAS;EAAO;CACzC;AACF"}