function findAvailableTableToMove()

in frontend/apps/quantgrid/src/app/hooks/useSelectionMoveNextAvailable.ts [34:102]


function findAvailableTableToMove(
  tables: GridTable[],
  direction: 'up' | 'down' | 'left' | 'right',
  col: number,
  row: number
) {
  let minDistance = Infinity;
  let result: { col: number; row: number } | null = null;

  if (direction === 'up') {
    for (const table of tables) {
      if (
        table.endRow < row &&
        table.startCol <= col &&
        table.endCol >= col &&
        minDistance > row - table.endRow
      ) {
        minDistance = row - table.endRow;
        result = { col, row: table.endRow };
      }
    }
    if (!result) result = { col, row: 1 };
  }

  if (direction === 'down') {
    for (const table of tables) {
      if (
        table.startRow > row &&
        table.startCol <= col &&
        table.endCol >= col &&
        minDistance > table.startRow - row
      ) {
        minDistance = table.startRow - row;
        result = { col, row: table.startRow };
      }
    }
    if (!result) result = { col, row: defaults.viewport.rows };
  }
  if (direction === 'left') {
    for (const table of tables) {
      if (
        table.startRow <= row &&
        row <= table.endRow &&
        table.endCol < col &&
        minDistance > col - table.endCol
      ) {
        minDistance = col - table.endCol;
        result = { row, col: table.endCol };
      }
    }
    if (!result) result = { col: 1, row };
  }
  if (direction === 'right') {
    for (const table of tables) {
      if (
        table.startRow <= row &&
        row <= table.endRow &&
        col < table.startCol &&
        minDistance > table.startCol - col
      ) {
        minDistance = table.startCol - col;
        result = { row, col: table.startCol };
      }
    }
    if (!result) result = { col: defaults.viewport.cols, row };
  }

  return result;
}