All files / organisms/Table/mobile Table.native.tsx

93.87% Statements 46/49
77.58% Branches 90/116
91.66% Functions 11/12
93.61% Lines 44/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426                                              6x                                                                 74x   74x               74x 74x 74x   74x 47x 47x         47x 7x       169x           74x         74x 74x 74x 74x   74x               74x         74x       74x       74x       74x         74x         74x           74x             74x 74x                                 288x 288x                                                                     74x 74x 4x                         70x     188x 1x                         758x 758x                                                                                 74x 74x   1x             1x                                                                         74x                                                 6x                                                                                                                                                              
import React, { useEffect, useRef, useState } from 'react';
import { RowData, TableProps } from './Table.native.types';
import {
  Pressable,
  ScrollView,
  StyleProp,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import { cn } from '@sb/libs';
import { useTableOnRowClick, useTablePageControl } from '@sb/hooks';
import { Select } from '@sb/ui/components/atoms/Select/mobile/Select.native';
import { Option } from '@sb/ui/components/atoms/Select';
import { Th } from './Th.native';
import { Td } from './Td.native';
import { useTheme } from '@sb/ui/components/Themes/ThemeProvider';
import { colors } from '@sb/styles/colors';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated';
 
export const Table: React.FC<TableProps> = ({
  id,
  headerIndex,
  className = '',
  colClassName = '',
  rowClassName = '',
  variant = 'default',
  hover = false,
  shadowOnHover = 'none',
  pagination = false,
  pageSize = 10,
  stickyHeader = false,
  stickyColumn = false,
  size = 'medium',
  columns,
  data,
  width,
  height,
  selectable = false,
  selectMode = 'single',
  emptyMessage,
  emptyMessageClassName,
  onSelectRow,
  onDeselectRow,
  onRowClick,
  headerTemplate,
  caption,
  footerTemplate,
  expandableHeader = true,
  rowStyle,
  headerClassName,
  headerContainerClassName,
}) => {
  const { theme } = useTheme();
 
  const { selectedRows, handleOnRowClick } = useTableOnRowClick({
    selectMode: selectMode,
    onSelectRow: onSelectRow,
    onRowClick: onRowClick,
    onDeselectRow: onDeselectRow,
    highlightRowBorder: false,
  });
 
  const tableRef = useRef(null);
  const opacity = useSharedValue(0);
  const [isHeaderVisible, setIsHeaderVisible] = useState<boolean>(true);
 
  useEffect(() => {
    if (expandableHeader) {
      opacity.value = withTiming(1, { duration: 250 });
    } else E{
      opacity.value = withTiming(0, { duration: 250 });
    }
 
    setTimeout(() => {
      setIsHeaderVisible(expandableHeader);
    }, 260);
  }, [expandableHeader]);
 
  const animatedStyle = useAnimatedStyle(() => ({
    opacity: opacity.value,
    overflow: 'hidden',
  }));
 
  const { handlePrevPage, currentPage, currentPageSize, handleNextPage, handlePageSizeChange } =
    useTablePageControl({
      totalPages: Math.ceil(data.length / pageSize),
      pageSize: pageSize,
    });
 
  const totalPages = Math.ceil(data.length / currentPageSize);
  const indexOfLastRow = currentPage * currentPageSize;
  const indexOfFirstRow = indexOfLastRow - currentPageSize;
  const currentData = data.slice(indexOfFirstRow, indexOfLastRow);
 
  const tableClasses = cn(className, {
    'transition duration-200 ease-in-out': hover,
    'shadow-none': shadowOnHover === 'none',
    'shadow-sm': shadowOnHover === 'small',
    'shadow-md': shadowOnHover === 'medium',
    'shadow-lg': shadowOnHover === 'large',
  });
 
  const tableDefault: StyleProp<ViewStyle> = {
    borderBottomWidth: 1,
    borderBottomColor: colors[theme].colorTable_Border,
  };
 
  const tableStrippedOdd: StyleProp<ViewStyle> = {
    backgroundColor: colors[theme].colorPrimary,
  };
 
  const tableStrippedEven: StyleProp<ViewStyle> = {
    backgroundColor: colors[theme].colorTertiary_Background,
  };
 
  const tableStrippedHeader: StyleProp<ViewStyle> = {
    backgroundColor: colors[theme].colorPrimary,
  };
 
  const tableBordered: StyleProp<ViewStyle> = {
    borderWidth: 1,
    borderColor: colors[theme].LeagueHeaderBackground,
  };
 
  const headerCaption: StyleProp<ViewStyle> = {
    borderBottomWidth: 6.4,
    borderBottomColor: colors[theme].colorBody_Background,
  };
 
  const borderLeft: StyleProp<ViewStyle> = {
    borderLeftWidth: 2,
    borderLeftColor: colors[theme].colorAccent,
  };
 
  const iconDown = (
    <MaterialIcons
      name="keyboard-arrow-down"
      size={24}
      color={colors[theme].colorIcon_Fill_Light}
    />
  );
 
  const renderTableHead = () => {
    return (
      <View style={[stickyHeader && styles.tableStickyHeader]}>
        {headerTemplate && headerIndex !== undefined && headerIndex !== 1 && (
          <View
            style={headerCaption}
            className={cn('bg-tertiary mb-[5px] px-[8px] py-[6px]', headerClassName)}
          >
            {typeof headerTemplate === 'function' ? headerTemplate() : headerTemplate}
          </View>
        )}
        {isHeaderVisible && (
          <Animated.View
            key="header-row"
            style={animatedStyle}
            className={cn('flex-row overflow-hidden', headerContainerClassName)}
          >
            {columns.map((col) => {
              const colClassname = cn(colClassName, col.className);
              return col.colSpan !== 0 ? (
                <Th
                  key={`column-${col.key}`}
                  style={[
                    styles.tableTh,
                    size === 'xs' && styles.tableExtraSmall,
                    size === 'small' && styles.tableSmall,
                    size === 'medium' && styles.tableMedium,
                    size === 'large' && styles.tableLarge,
                    variant === 'default' && tableDefault,
                    variant === 'striped' && tableStrippedHeader,
                    variant === 'bordered' && tableBordered,
                    variant === 'compact' && styles.tableCompact,
                    stickyColumn && col.fixed === 'left' && styles.tableStickyColumnLeft,
                    stickyColumn && col.fixed === 'right' && styles.tableStickyColumnLeft,
                    { width: col.width ?? 150 },
                  ]}
                  className={colClassname}
                  colSpan={col.colSpan}
                  rowSpan={col.rowSpan}
                >
                  {typeof col.title === 'string' ? (
                    <Text className="text-text-main font-Bold">{col.title}</Text>
                  ) : (
                    col.title
                  )}
                </Th>
              ) : null;
            })}
          </Animated.View>
        )}
      </View>
    );
  };
 
  const renderTableBody = () => {
    if (!currentData || currentData.length === 0) {
      return (
        <View>
          <View style={[variant === 'default' && tableDefault]}>
            <View style={styles.tableTd} className="text-center">
              <Text className={emptyMessageClassName}>
                {emptyMessage ? emptyMessage : 'No data available'}
              </Text>
            </View>
          </View>
        </View>
      );
    }
 
    return (
      <View>
        {currentData.map((rowData: RowData, rowIndex: number) => (
          <Pressable
            onPress={() => handleOnRowClick(rowData, rowIndex)}
            key={`row-${rowIndex}`}
            className={cn('flex-row', rowClassName)}
            style={[
              variant === 'default' && tableDefault,
              rowIndex % 2 === 0 && variant === 'striped' && tableStrippedEven,
              rowIndex % 2 !== 0 && variant === 'striped' && tableStrippedOdd,
              selectable && selectedRows.includes(rowIndex) && borderLeft,
              selectable && selectedRows.includes(rowIndex) && styles.rowSelected,
              rowStyle?.(rowData),
            ]}
          >
            {columns.map((col) => {
              const colClassname = cn(colClassName, col.className, col.cellClassName);
              return (
                <Td
                  style={[
                    styles.tableTd,
                    size === 'xs' && styles.tableExtraSmall,
                    size === 'small' && styles.tableSmall,
                    size === 'medium' && styles.tableMedium,
                    size === 'large' && styles.tableLarge,
                    variant === 'bordered' && tableBordered,
                    variant === 'compact' && styles.tableCompact,
                    stickyColumn && col.fixed === 'left' && styles.tableStickyColumnLeft,
                    stickyColumn && col.fixed === 'right' && styles.tableStickyColumnRight,
                    { width: col.width ?? 150 },
                  ]}
                  key={`td-${col.key}`}
                  className={colClassname}
                  colSpan={col.colSpan}
                  rowSpan={col.rowSpan}
                >
                  {typeof rowData[col.dataIndex] === 'string' ? (
                    <Text className={cn('text-text-main', col.textCassName)}>
                      {col.render
                        ? col.render(rowData[col.dataIndex], rowIndex)
                        : rowData[col.dataIndex]}
                    </Text>
                  ) : (
                    <View>
                      {col.render
                        ? col.render(rowData[col.dataIndex], rowIndex)
                        : rowData[col.dataIndex]}
                    </View>
                  )}
                </Td>
              );
            })}
          </Pressable>
        ))}
      </View>
    );
  };
 
  const renderPagination = () => {
    if (!pagination) return null;
 
    const options: Option[] = [
      { label: '10', value: '10' },
      { label: '20', value: '20' },
      { label: '50', value: '50' },
      { label: '100', value: '100' },
    ];
 
    return (
      <View className="m-0 flex flex-row items-center justify-start">
        <View className="mx-1 flex flex-row items-center">
          <Text className="text-text-main mx-3">Items per page:</Text>
          <Select
            options={options}
            style={{ width: 75, backgroundColor: 'transparent' }}
            textStyle={{ color: colors[theme].colorText_Main }}
            defaultValue={currentPageSize}
            placeholder={`${currentPageSize}`}
            suffix={iconDown}
            onChange={(value) => {
              if (typeof value === 'string' || typeof value === 'number') {
                handlePageSizeChange(value.toString());
              }
            }}
          />
        </View>
        <View className="flex flex-row">
          <TouchableOpacity disabled={currentPage === 1} className="mx-2" onPress={handlePrevPage}>
            <Text className="text-text-main">Prev</Text>
          </TouchableOpacity>
          <Text className="text-text-main mx-2">
            Page {currentPage} of {totalPages}
          </Text>
          <TouchableOpacity
            disabled={currentPage === totalPages}
            className="mx-2"
            onPress={handleNextPage}
          >
            <Text className="text-text-main">Next</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  };
 
  return (
    <ScrollView horizontal={true} contentContainerStyle={{ flexGrow: 1 }}>
      <View
        id={id}
        testID={id}
        className={`overflow-scroll ${variant} ${size} ${className}`}
        ref={tableRef}
        style={{ width, height }}
      >
        <View className={tableClasses}>
          {caption && (typeof caption === 'function' ? caption() : caption)}
          {renderTableHead()}
          {renderTableBody()}
        </View>
        {footerTemplate && (
          <View className="table-footer">
            {typeof footerTemplate === 'function' ? footerTemplate() : footerTemplate}
          </View>
        )}
        {renderPagination()}
      </View>
    </ScrollView>
  );
};
 
const styles = StyleSheet.create({
  tableContainer: {
    overflow: 'scroll',
  },
  table: {
    width: '100%',
  },
  tableTh: {
    padding: 1,
    textAlign: 'left',
  },
  tableTd: {
    padding: 1,
    textAlign: 'left',
  },
  tableStickyHeader: {
    position: 'static',
    top: 0,
    zIndex: 2,
  },
  tableStickyColumnLeft: {
    position: 'static',
    left: 0,
    zIndex: 1,
    shadowColor: 'rgba(0, 0, 0, 0.5)',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.5,
    shadowRadius: 15,
    elevation: 5, // for Android
  },
  tableStickyColumnRight: {
    position: 'static',
    right: 0,
    zIndex: -1,
    shadowColor: 'rgba(0, 0, 0, 0.5)',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.5,
    shadowRadius: 15,
    elevation: 5, // for Android
  },
  tableExtraSmall: {
    padding: 0,
  },
  tableSmall: {
    paddingTop: 5,
    paddingBottom: 5,
    paddingLeft: 8,
    paddingRight: 8,
  },
  tableMedium: {
    paddingTop: 5,
    paddingBottom: 5,
    paddingLeft: 10,
    paddingRight: 10,
  },
  tableLarge: {
    paddingTop: 5,
    paddingBottom: 5,
    paddingLeft: 14,
    paddingRight: 14,
  },
  tableCompact: {
    paddingVertical: 5,
    paddingHorizontal: 8,
  },
  rowSelected: {
    shadowColor: 'rgba(0, 0, 0, 0.5)',
    shadowOffset: { width: 0, height: 0 },
    shadowOpacity: 0.5,
    shadowRadius: 6,
    elevation: 4, // Android shadow
  },
});