Refactor UI folder (#2016)

* Added Overview page

* Revised Getting Started page

* Minor revision

* Edited readme, minor modifications to docs

* Removed sweep.yaml, .devcontainer, .ergomake

* Moved security.md to .github, added contributing.md

* changes as per code review

* updated contributing.md

* fixed broken links & added missing links in doc, improved structure

* fixed link in wsl setup

* fixed server link, added https cloning in yarn-setup

* removed package-lock.json

* added doc card, admonitions

* removed underline from nav buttons

* refactoring modules/ui

* refactoring modules/ui

* Change folder case

* Fix theme location

* Fix case 2

* Fix storybook

---------

Co-authored-by: Nimra Ahmed <nimra1408@gmail.com>
Co-authored-by: Nimra Ahmed <50912134+nimraahmed@users.noreply.github.com>
This commit is contained in:
Charles Bochet
2023-10-14 00:04:29 +02:00
committed by GitHub
parent a35ea5e8f9
commit 258685467b
732 changed files with 1106 additions and 1010 deletions

View File

@ -0,0 +1,12 @@
import React from 'react';
import { useRecoilValue } from 'recoil';
import { ActionBar } from '@/ui/navigation/action-bar/components/ActionBar';
import { selectedRowIdsSelector } from '../../states/selectors/selectedRowIdsSelector';
export const DataTableActionBar = () => {
const selectedRowIds = useRecoilValue(selectedRowIdsSelector);
return <ActionBar selectedIds={selectedRowIds} />;
};

View File

@ -0,0 +1,34 @@
import { useCallback } from 'react';
import styled from '@emotion/styled';
import { useSetRecoilState } from 'recoil';
import { Checkbox } from '@/ui/input/components/Checkbox';
import { actionBarOpenState } from '@/ui/navigation/action-bar/states/actionBarIsOpenState';
import { useCurrentRowSelected } from '../hooks/useCurrentRowSelected';
const StyledContainer = styled.div`
align-items: center;
cursor: pointer;
display: flex;
height: 32px;
justify-content: center;
`;
export const CheckboxCell = () => {
const setActionBarOpenState = useSetRecoilState(actionBarOpenState);
const { currentRowSelected, setCurrentRowSelected } = useCurrentRowSelected();
const handleClick = useCallback(() => {
setCurrentRowSelected(!currentRowSelected);
setActionBarOpenState(true);
}, [currentRowSelected, setActionBarOpenState, setCurrentRowSelected]);
return (
<StyledContainer onClick={handleClick}>
<Checkbox checked={currentRowSelected} />
</StyledContainer>
);
};

View File

@ -0,0 +1,51 @@
import { useTheme } from '@emotion/react';
import styled from '@emotion/styled';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { ColumnDefinition } from '../types/ColumnDefinition';
type ColumnHeadProps = {
column: ColumnDefinition<FieldMetadata>;
};
const StyledTitle = styled.div`
align-items: center;
display: flex;
flex-direction: row;
font-weight: ${({ theme }) => theme.font.weight.medium};
gap: ${({ theme }) => theme.spacing(1)};
height: ${({ theme }) => theme.spacing(8)};
padding-left: ${({ theme }) => theme.spacing(2)};
padding-right: ${({ theme }) => theme.spacing(2)};
`;
const StyledIcon = styled.div`
display: flex;
& > svg {
height: ${({ theme }) => theme.icon.size.md}px;
width: ${({ theme }) => theme.icon.size.md}px;
}
`;
const StyledText = styled.span`
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`;
export const ColumnHead = ({ column }: ColumnHeadProps) => {
const theme = useTheme();
return (
<>
<StyledTitle>
<StyledIcon>
{column.Icon && <column.Icon size={theme.icon.size.md} />}
</StyledIcon>
<StyledText>{column.name}</StyledText>
</StyledTitle>
</>
);
};

View File

@ -0,0 +1,40 @@
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { DropdownMenu } from '@/ui/layout/dropdown/components/DropdownMenu';
import { DropdownScope } from '@/ui/layout/dropdown/scopes/DropdownScope';
import { ColumnDefinition } from '../types/ColumnDefinition';
import { ColumnHead } from './ColumnHead';
import { DataTableColumnDropdownMenu } from './DataTableColumnDropdownMenu';
type ColumnHeadWithDropdownProps = {
column: ColumnDefinition<FieldMetadata>;
isFirstColumn: boolean;
isLastColumn: boolean;
primaryColumnKey: string;
};
export const ColumnHeadWithDropdown = ({
column,
isFirstColumn,
isLastColumn,
primaryColumnKey,
}: ColumnHeadWithDropdownProps) => {
return (
<DropdownScope dropdownScopeId={column.key + '-header'}>
<DropdownMenu
clickableComponent={<ColumnHead column={column} />}
dropdownComponents={
<DataTableColumnDropdownMenu
column={column}
isFirstColumn={isFirstColumn}
isLastColumn={isLastColumn}
primaryColumnKey={primaryColumnKey}
/>
}
dropdownHotkeyScope={{ scope: column.key + '-header' }}
dropdownOffset={{ x: 0, y: -8 }}
/>
</DropdownScope>
);
};

View File

@ -0,0 +1,144 @@
import { useRef } from 'react';
import styled from '@emotion/styled';
import { DragSelect } from '@/ui/utilities/drag-select/components/DragSelect';
import { useScopedHotkeys } from '@/ui/utilities/hotkey/hooks/useScopedHotkeys';
import {
useListenClickOutside,
useListenClickOutsideByClassName,
} from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
import { ScrollWrapper } from '@/ui/utilities/scroll/components/ScrollWrapper';
import { EntityUpdateMutationContext } from '../contexts/EntityUpdateMutationHookContext';
import { useLeaveTableFocus } from '../hooks/useLeaveTableFocus';
import { useMapKeyboardToSoftFocus } from '../hooks/useMapKeyboardToSoftFocus';
import { useResetTableRowSelection } from '../hooks/useResetTableRowSelection';
import { useSetRowSelectedState } from '../hooks/useSetRowSelectedState';
import { TableHeader } from '../table-header/components/TableHeader';
import { TableHotkeyScope } from '../types/TableHotkeyScope';
import { DataTableBody } from './DataTableBody';
import { DataTableHeader } from './DataTableHeader';
const StyledTable = styled.table`
border-collapse: collapse;
border-radius: ${({ theme }) => theme.border.radius.sm};
border-spacing: 0;
margin-left: ${({ theme }) => theme.table.horizontalCellMargin};
margin-right: ${({ theme }) => theme.table.horizontalCellMargin};
table-layout: fixed;
width: calc(100% - ${({ theme }) => theme.table.horizontalCellMargin} * 2);
th {
border: 1px solid ${({ theme }) => theme.border.color.light};
border-collapse: collapse;
color: ${({ theme }) => theme.font.color.tertiary};
padding: 0;
text-align: left;
:last-child {
border-right-color: transparent;
}
:first-of-type {
border-left-color: transparent;
border-right-color: transparent;
}
:last-of-type {
width: 100%;
}
}
td {
border: 1px solid ${({ theme }) => theme.border.color.light};
border-collapse: collapse;
color: ${({ theme }) => theme.font.color.primary};
padding: 0;
text-align: left;
:last-child {
border-right-color: transparent;
}
:first-of-type {
border-left-color: transparent;
border-right-color: transparent;
}
}
`;
const StyledTableWithHeader = styled.div`
display: flex;
flex: 1;
flex-direction: column;
width: 100%;
`;
const StyledTableContainer = styled.div`
display: flex;
flex-direction: column;
height: 100%;
overflow: auto;
`;
type DataTableProps = {
updateEntityMutation: (params: any) => void;
};
export const DataTable = ({ updateEntityMutation }: DataTableProps) => {
const tableBodyRef = useRef<HTMLDivElement>(null);
const setRowSelectedState = useSetRowSelectedState();
const resetTableRowSelection = useResetTableRowSelection();
useMapKeyboardToSoftFocus();
const leaveTableFocus = useLeaveTableFocus();
useListenClickOutside({
refs: [tableBodyRef],
callback: () => {
leaveTableFocus();
},
});
useScopedHotkeys(
'escape',
() => {
resetTableRowSelection();
},
TableHotkeyScope.Table,
);
useListenClickOutsideByClassName({
classNames: ['entity-table-cell'],
excludeClassNames: ['action-bar', 'context-menu'],
callback: () => {
resetTableRowSelection();
},
});
return (
<EntityUpdateMutationContext.Provider value={updateEntityMutation}>
<StyledTableWithHeader>
<StyledTableContainer ref={tableBodyRef}>
<TableHeader />
<ScrollWrapper>
<div>
<StyledTable className="entity-table-cell">
<DataTableHeader />
<DataTableBody />
</StyledTable>
</div>
</ScrollWrapper>
<DragSelect
dragSelectable={tableBodyRef}
onDragSelectionStart={resetTableRowSelection}
onDragSelectionChange={setRowSelectedState}
/>
</StyledTableContainer>
</StyledTableWithHeader>
</EntityUpdateMutationContext.Provider>
);
};

View File

@ -0,0 +1,82 @@
import styled from '@emotion/styled';
import { useVirtual } from '@tanstack/react-virtual';
import { useRecoilValue } from 'recoil';
import { isNavbarSwitchingSizeState } from '@/ui/layout/states/isNavbarSwitchingSizeState';
import { useScrollWrapperScopedRef } from '@/ui/utilities/scroll/hooks/useScrollWrapperScopedRef';
import { RowIdContext } from '../contexts/RowIdContext';
import { RowIndexContext } from '../contexts/RowIndexContext';
import { isFetchingDataTableDataState } from '../states/isFetchingDataTableDataState';
import { tableRowIdsState } from '../states/tableRowIdsState';
import { DataTableRow } from './DataTableRow';
type SpaceProps = {
top?: number;
bottom?: number;
};
const StyledSpace = styled.td<SpaceProps>`
${({ top }) => top && `padding-top: ${top}px;`}
${({ bottom }) => bottom && `padding-bottom: ${bottom}px;`}
`;
export const DataTableBody = () => {
const scrollWrapperRef = useScrollWrapperScopedRef();
const tableRowIds = useRecoilValue(tableRowIdsState);
// eslint-disable-next-line no-console
console.log({ tableRowIds });
const isNavbarSwitchingSize = useRecoilValue(isNavbarSwitchingSizeState);
const isFetchingDataTableData = useRecoilValue(isFetchingDataTableDataState);
const rowVirtualizer = useVirtual({
size: tableRowIds.length,
parentRef: scrollWrapperRef,
overscan: 50,
});
const items = rowVirtualizer.virtualItems;
const paddingTop = items.length > 0 ? items[0].start : 0;
const paddingBottom =
items.length > 0
? rowVirtualizer.totalSize - items[items.length - 1].end
: 0;
if (isFetchingDataTableData || isNavbarSwitchingSize) {
return null;
}
return (
<tbody>
{paddingTop > 0 && (
<tr>
<StyledSpace top={paddingTop} />
</tr>
)}
{items.map((virtualItem) => {
const rowId = tableRowIds[virtualItem.index];
return (
<RowIdContext.Provider value={rowId} key={rowId}>
<RowIndexContext.Provider value={virtualItem.index}>
<DataTableRow
key={virtualItem.index}
ref={virtualItem.measureRef}
rowId={rowId}
/>
</RowIndexContext.Provider>
</RowIdContext.Provider>
);
})}
{paddingBottom > 0 && (
<tr>
<StyledSpace bottom={paddingBottom} />
</tr>
)}
</tbody>
);
};

View File

@ -0,0 +1,70 @@
import { useContext } from 'react';
import { useSetRecoilState } from 'recoil';
import { FieldContext } from '@/ui/data/field/contexts/FieldContext';
import { isFieldRelation } from '@/ui/data/field/types/guards/isFieldRelation';
import { RelationPickerHotkeyScope } from '@/ui/input/relation-picker/types/RelationPickerHotkeyScope';
import { contextMenuIsOpenState } from '@/ui/navigation/context-menu/states/contextMenuIsOpenState';
import { contextMenuPositionState } from '@/ui/navigation/context-menu/states/contextMenuPositionState';
import { RecoilScope } from '@/ui/utilities/recoil-scope/components/RecoilScope';
import { ColumnContext } from '../contexts/ColumnContext';
import { ColumnIndexContext } from '../contexts/ColumnIndexContext';
import { EntityUpdateMutationContext } from '../contexts/EntityUpdateMutationHookContext';
import { RowIdContext } from '../contexts/RowIdContext';
import { useCurrentRowSelected } from '../hooks/useCurrentRowSelected';
import { TableCell } from '../table-cell/components/TableCell';
import { TableHotkeyScope } from '../types/TableHotkeyScope';
export const DataTableCell = ({ cellIndex }: { cellIndex: number }) => {
const setContextMenuPosition = useSetRecoilState(contextMenuPositionState);
const setContextMenuOpenState = useSetRecoilState(contextMenuIsOpenState);
const currentRowId = useContext(RowIdContext);
const { setCurrentRowSelected } = useCurrentRowSelected();
const handleContextMenu = (event: React.MouseEvent) => {
event.preventDefault();
setCurrentRowSelected(true);
setContextMenuPosition({
x: event.clientX,
y: event.clientY,
});
setContextMenuOpenState(true);
};
const columnDefinition = useContext(ColumnContext);
const updateEntityMutation = useContext(EntityUpdateMutationContext);
// eslint-disable-next-line no-console
console.log({ columnDefinition, currentRowId });
if (!columnDefinition || !currentRowId) {
return null;
}
const customHotkeyScope = isFieldRelation(columnDefinition)
? RelationPickerHotkeyScope.RelationPicker
: TableHotkeyScope.CellEditMode;
return (
<RecoilScope>
<ColumnIndexContext.Provider value={cellIndex}>
<td onContextMenu={(event) => handleContextMenu(event)}>
<FieldContext.Provider
value={{
recoilScopeId: currentRowId + columnDefinition.name,
entityId: currentRowId,
fieldDefinition: columnDefinition,
useUpdateEntityMutation: () => [updateEntityMutation, {}],
hotkeyScope: customHotkeyScope,
}}
>
<TableCell customHotkeyScope={{ scope: customHotkeyScope }} />
</FieldContext.Provider>
</td>
</ColumnIndexContext.Provider>
</RecoilScope>
);
};

View File

@ -0,0 +1,79 @@
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { IconArrowLeft, IconArrowRight, IconEyeOff } from '@/ui/display/icon';
import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
import { StyledDropdownMenu } from '@/ui/layout/dropdown/components/StyledDropdownMenu';
import { useDropdown } from '@/ui/layout/dropdown/hooks/useDropdown';
import { MenuItem } from '@/ui/navigation/menu-item/components/MenuItem';
import { ColumnHeadDropdownId } from '../constants/ColumnHeadDropdownId';
import { useTableColumns } from '../hooks/useTableColumns';
import { ColumnDefinition } from '../types/ColumnDefinition';
export type DataTableColumnDropdownMenuProps = {
column: ColumnDefinition<FieldMetadata>;
isFirstColumn: boolean;
isLastColumn: boolean;
primaryColumnKey: string;
};
export const DataTableColumnDropdownMenu = ({
column,
isFirstColumn,
isLastColumn,
primaryColumnKey,
}: DataTableColumnDropdownMenuProps) => {
const { handleColumnVisibilityChange, handleMoveTableColumn } =
useTableColumns();
const { closeDropdown } = useDropdown({
dropdownScopeId: ColumnHeadDropdownId,
});
const handleColumnMoveLeft = () => {
closeDropdown();
if (isFirstColumn) {
return;
}
handleMoveTableColumn('left', column);
};
const handleColumnMoveRight = () => {
closeDropdown();
if (isLastColumn) {
return;
}
handleMoveTableColumn('right', column);
};
const handleColumnVisibility = () => {
handleColumnVisibilityChange(column);
};
return column.key === primaryColumnKey ? (
<></>
) : (
<StyledDropdownMenu>
<DropdownMenuItemsContainer>
{!isFirstColumn && (
<MenuItem
LeftIcon={IconArrowLeft}
onClick={handleColumnMoveLeft}
text="Move left"
/>
)}
{!isLastColumn && (
<MenuItem
LeftIcon={IconArrowRight}
onClick={handleColumnMoveRight}
text="Move right"
/>
)}
<MenuItem
LeftIcon={IconEyeOff}
onClick={handleColumnVisibility}
text="Hide"
/>
</DropdownMenuItemsContainer>
</StyledDropdownMenu>
);
};

View File

@ -0,0 +1,106 @@
import { useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useRecoilCallback } from 'recoil';
import { useOptimisticEffect } from '@/apollo/optimistic-effect/hooks/useOptimisticEffect';
import { OptimisticEffectDefinition } from '@/apollo/optimistic-effect/types/OptimisticEffectDefinition';
import { currentViewIdScopedState } from '@/ui/data/view-bar/states/currentViewIdScopedState';
import { filtersScopedState } from '@/ui/data/view-bar/states/filtersScopedState';
import { savedFiltersFamilyState } from '@/ui/data/view-bar/states/savedFiltersFamilyState';
import { savedSortsFamilyState } from '@/ui/data/view-bar/states/savedSortsFamilyState';
import { sortsScopedState } from '@/ui/data/view-bar/states/sortsScopedState';
import { FilterDefinition } from '@/ui/data/view-bar/types/FilterDefinition';
import { SortDefinition } from '@/ui/data/view-bar/types/SortDefinition';
import { useRecoilScopeId } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopeId';
import { SortOrder } from '~/generated/graphql';
import { useSetDataTableData } from '../hooks/useSetDataTableData';
import { TableRecoilScopeContext } from '../states/recoil-scope-contexts/TableRecoilScopeContext';
export const DataTableEffect = ({
useGetRequest,
getRequestResultKey,
getRequestOptimisticEffectDefinition,
orderBy = [
{
createdAt: SortOrder.Desc,
},
],
whereFilters,
filterDefinitionArray,
setActionBarEntries,
setContextMenuEntries,
sortDefinitionArray,
}: {
// TODO: type this
useGetRequest: any;
getRequestResultKey: string;
getRequestOptimisticEffectDefinition: OptimisticEffectDefinition<any>;
// TODO: type this and replace with defaultSorts reduce should be applied to defaultSorts in this component not before
orderBy?: any;
// TODO: type this and replace with defaultFilters reduce should be applied to defaultFilters in this component not before
whereFilters?: any;
filterDefinitionArray: FilterDefinition[];
sortDefinitionArray: SortDefinition[];
setActionBarEntries?: () => void;
setContextMenuEntries?: () => void;
}) => {
const setDataTableData = useSetDataTableData();
const { registerOptimisticEffect } = useOptimisticEffect();
useGetRequest({
variables: { orderBy, where: whereFilters },
onCompleted: (data: any) => {
const entities = data[getRequestResultKey] ?? [];
setDataTableData(entities, filterDefinitionArray, sortDefinitionArray);
registerOptimisticEffect({
variables: { orderBy, where: whereFilters },
definition: getRequestOptimisticEffectDefinition,
});
},
});
const [searchParams] = useSearchParams();
const tableRecoilScopeId = useRecoilScopeId(TableRecoilScopeContext);
const handleViewSelect = useRecoilCallback(
({ set, snapshot }) =>
async (viewId: string) => {
const currentView = await snapshot.getPromise(
currentViewIdScopedState(tableRecoilScopeId),
);
if (currentView === viewId) {
return;
}
const savedFilters = await snapshot.getPromise(
savedFiltersFamilyState(viewId),
);
const savedSorts = await snapshot.getPromise(
savedSortsFamilyState(viewId),
);
set(filtersScopedState(tableRecoilScopeId), savedFilters);
set(sortsScopedState(tableRecoilScopeId), savedSorts);
set(currentViewIdScopedState(tableRecoilScopeId), viewId);
},
[tableRecoilScopeId],
);
useEffect(() => {
const viewId = searchParams.get('view');
if (viewId) {
handleViewSelect(viewId);
}
setActionBarEntries?.();
setContextMenuEntries?.();
}, [
handleViewSelect,
searchParams,
setActionBarEntries,
setContextMenuEntries,
]);
return <></>;
};

View File

@ -0,0 +1,228 @@
import { useCallback, useState } from 'react';
import styled from '@emotion/styled';
import { useRecoilCallback, useRecoilState } from 'recoil';
import { IconPlus } from '@/ui/display/icon';
import { IconButton } from '@/ui/input/button/components/IconButton';
import { useTrackPointer } from '@/ui/utilities/pointer-event/hooks/useTrackPointer';
import { useRecoilScopedValue } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopedValue';
import { useTableColumns } from '../hooks/useTableColumns';
import { TableRecoilScopeContext } from '../states/recoil-scope-contexts/TableRecoilScopeContext';
import { resizeFieldOffsetState } from '../states/resizeFieldOffsetState';
import { hiddenTableColumnsScopedSelector } from '../states/selectors/hiddenTableColumnsScopedSelector';
import { tableColumnsByKeyScopedSelector } from '../states/selectors/tableColumnsByKeyScopedSelector';
import { visibleTableColumnsScopedSelector } from '../states/selectors/visibleTableColumnsScopedSelector';
import { tableColumnsScopedState } from '../states/tableColumnsScopedState';
import { ColumnHeadWithDropdown } from './ColumnHeadWithDropdown';
import { DataTableHeaderPlusButton } from './DataTableHeaderPlusButton';
import { SelectAllCheckbox } from './SelectAllCheckbox';
const COLUMN_MIN_WIDTH = 75;
const StyledColumnHeaderCell = styled.th<{
columnWidth: number;
isResizing?: boolean;
}>`
${({ columnWidth }) => `
min-width: ${columnWidth}px;
width: ${columnWidth}px;
`}
position: relative;
user-select: none;
${({ isResizing, theme }) => {
if (isResizing) {
return `&:after {
background-color: ${theme.color.blue};
bottom: 0;
content: '';
display: block;
position: absolute;
right: -1px;
top: 0;
width: 2px;
}`;
}
}};
`;
const StyledResizeHandler = styled.div`
bottom: 0;
cursor: col-resize;
padding: 0 ${({ theme }) => theme.spacing(2)};
position: absolute;
right: -9px;
top: 0;
width: 3px;
z-index: 1;
`;
const StyledAddIconButtonWrapper = styled.div`
display: inline-flex;
position: relative;
`;
const StyledDataTableColumnMenu = styled(DataTableHeaderPlusButton)`
position: absolute;
right: 0;
top: 100%;
z-index: ${({ theme }) => theme.lastLayerZIndex};
`;
const StyledTableHead = styled.thead`
cursor: pointer;
`;
const StyledColumnHeadContainer = styled.div`
position: relative;
z-index: 1;
`;
export const DataTableHeader = () => {
const [resizeFieldOffset, setResizeFieldOffset] = useRecoilState(
resizeFieldOffsetState,
);
const tableColumns = useRecoilScopedValue(
tableColumnsScopedState,
TableRecoilScopeContext,
);
const tableColumnsByKey = useRecoilScopedValue(
tableColumnsByKeyScopedSelector,
TableRecoilScopeContext,
);
const hiddenTableColumns = useRecoilScopedValue(
hiddenTableColumnsScopedSelector,
TableRecoilScopeContext,
);
const visibleTableColumns = useRecoilScopedValue(
visibleTableColumnsScopedSelector,
TableRecoilScopeContext,
);
const [initialPointerPositionX, setInitialPointerPositionX] = useState<
number | null
>(null);
const [resizedFieldKey, setResizedFieldKey] = useState<string | null>(null);
const [isColumnMenuOpen, setIsColumnMenuOpen] = useState(false);
const { handleColumnsChange } = useTableColumns();
const handleResizeHandlerStart = useCallback((positionX: number) => {
setInitialPointerPositionX(positionX);
}, []);
const handleResizeHandlerMove = useCallback(
(positionX: number) => {
if (!initialPointerPositionX) return;
setResizeFieldOffset(positionX - initialPointerPositionX);
},
[setResizeFieldOffset, initialPointerPositionX],
);
const handleResizeHandlerEnd = useRecoilCallback(
({ snapshot, set }) =>
async () => {
if (!resizedFieldKey) return;
const nextWidth = Math.round(
Math.max(
tableColumnsByKey[resizedFieldKey].size +
snapshot.getLoadable(resizeFieldOffsetState).valueOrThrow(),
COLUMN_MIN_WIDTH,
),
);
set(resizeFieldOffsetState, 0);
setInitialPointerPositionX(null);
setResizedFieldKey(null);
if (nextWidth !== tableColumnsByKey[resizedFieldKey].size) {
const nextColumns = tableColumns.map((column) =>
column.key === resizedFieldKey
? { ...column, size: nextWidth }
: column,
);
await handleColumnsChange(nextColumns);
}
},
[resizedFieldKey, tableColumnsByKey, tableColumns, handleColumnsChange],
);
useTrackPointer({
shouldTrackPointer: resizedFieldKey !== null,
onMouseDown: handleResizeHandlerStart,
onMouseMove: handleResizeHandlerMove,
onMouseUp: handleResizeHandlerEnd,
});
const toggleColumnMenu = useCallback(() => {
setIsColumnMenuOpen((previousValue) => !previousValue);
}, []);
const primaryColumn = visibleTableColumns[0];
return (
<StyledTableHead data-select-disable>
<tr>
<th
style={{
width: 30,
minWidth: 30,
maxWidth: 30,
}}
>
<SelectAllCheckbox />
</th>
{visibleTableColumns.map((column, index) => (
<StyledColumnHeaderCell
key={column.key}
isResizing={resizedFieldKey === column.key}
columnWidth={Math.max(
tableColumnsByKey[column.key].size +
(resizedFieldKey === column.key ? resizeFieldOffset : 0),
COLUMN_MIN_WIDTH,
)}
>
<StyledColumnHeadContainer>
<ColumnHeadWithDropdown
column={column}
isFirstColumn={index === 1}
isLastColumn={index === visibleTableColumns.length - 1}
primaryColumnKey={primaryColumn.key}
/>
</StyledColumnHeadContainer>
<StyledResizeHandler
className="cursor-col-resize"
role="separator"
onPointerDown={() => {
setResizedFieldKey(column.key);
}}
/>
</StyledColumnHeaderCell>
))}
<th>
{hiddenTableColumns.length > 0 && (
<StyledAddIconButtonWrapper>
<IconButton
size="medium"
variant="tertiary"
Icon={IconPlus}
onClick={toggleColumnMenu}
position="middle"
/>
{isColumnMenuOpen && (
<StyledDataTableColumnMenu
onAddColumn={toggleColumnMenu}
onClickOutside={toggleColumnMenu}
/>
)}
</StyledAddIconButtonWrapper>
)}
</th>
</tr>
</StyledTableHead>
);
};

View File

@ -0,0 +1,71 @@
import { ComponentProps, useCallback, useRef } from 'react';
import styled from '@emotion/styled';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { IconPlus } from '@/ui/display/icon';
import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
import { StyledDropdownMenu } from '@/ui/layout/dropdown/components/StyledDropdownMenu';
import { MenuItem } from '@/ui/navigation/menu-item/components/MenuItem';
import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
import { useRecoilScopedValue } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopedValue';
import { useTableColumns } from '../hooks/useTableColumns';
import { TableRecoilScopeContext } from '../states/recoil-scope-contexts/TableRecoilScopeContext';
import { hiddenTableColumnsScopedSelector } from '../states/selectors/hiddenTableColumnsScopedSelector';
import { ColumnDefinition } from '../types/ColumnDefinition';
const StyledHeaderPlusButton = styled(StyledDropdownMenu)`
font-weight: ${({ theme }) => theme.font.weight.regular};
`;
type DataTableHeaderPlusButtonProps = {
onAddColumn?: () => void;
onClickOutside?: () => void;
} & ComponentProps<'div'>;
export const DataTableHeaderPlusButton = ({
onAddColumn,
onClickOutside = () => undefined,
}: DataTableHeaderPlusButtonProps) => {
const ref = useRef<HTMLDivElement>(null);
const hiddenTableColumns = useRecoilScopedValue(
hiddenTableColumnsScopedSelector,
TableRecoilScopeContext,
);
useListenClickOutside({
refs: [ref],
callback: onClickOutside,
});
const { handleColumnVisibilityChange } = useTableColumns();
const handleAddColumn = useCallback(
(column: ColumnDefinition<FieldMetadata>) => {
onAddColumn?.();
handleColumnVisibilityChange(column);
},
[handleColumnVisibilityChange, onAddColumn],
);
return (
<StyledHeaderPlusButton ref={ref}>
<DropdownMenuItemsContainer>
{hiddenTableColumns.map((column) => (
<MenuItem
key={column.key}
iconButtons={[
{
Icon: IconPlus,
onClick: () => handleAddColumn(column),
},
]}
LeftIcon={column.Icon}
text={column.name}
/>
))}
</DropdownMenuItemsContainer>
</StyledHeaderPlusButton>
);
};

View File

@ -0,0 +1,53 @@
import { forwardRef } from 'react';
import styled from '@emotion/styled';
import { useRecoilScopedValue } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopedValue';
import { ColumnContext } from '../contexts/ColumnContext';
import { useCurrentRowSelected } from '../hooks/useCurrentRowSelected';
import { TableRecoilScopeContext } from '../states/recoil-scope-contexts/TableRecoilScopeContext';
import { visibleTableColumnsScopedSelector } from '../states/selectors/visibleTableColumnsScopedSelector';
import { CheckboxCell } from './CheckboxCell';
import { DataTableCell } from './DataTableCell';
const StyledRow = styled.tr<{ selected: boolean }>`
background: ${(props) =>
props.selected ? props.theme.accent.quaternary : 'none'};
`;
type DataTableRowProps = {
rowId: string;
};
export const DataTableRow = forwardRef<HTMLTableRowElement, DataTableRowProps>(
({ rowId }, ref) => {
const visibleTableColumns = useRecoilScopedValue(
visibleTableColumnsScopedSelector,
TableRecoilScopeContext,
);
const { currentRowSelected } = useCurrentRowSelected();
// eslint-disable-next-line no-console
console.log({ visibleTableColumns });
return (
<StyledRow
ref={ref}
data-testid={`row-id-${rowId}`}
selected={currentRowSelected}
data-selectable-id={rowId}
>
<td>
<CheckboxCell />
</td>
{visibleTableColumns.map((column, columnIndex) => {
return (
<ColumnContext.Provider value={column} key={column.key}>
<DataTableCell cellIndex={columnIndex} />
</ColumnContext.Provider>
);
})}
<td></td>
</StyledRow>
);
},
);

View File

@ -0,0 +1,35 @@
import styled from '@emotion/styled';
import { Checkbox } from '@/ui/input/components/Checkbox';
import { useSelectAllRows } from '../hooks/useSelectAllRows';
const StyledContainer = styled.div`
align-items: center;
display: flex;
height: 32px;
justify-content: center;
`;
export const SelectAllCheckbox = () => {
const { selectAllRows, allRowsSelectedStatus } = useSelectAllRows();
const checked = allRowsSelectedStatus === 'all';
const indeterminate = allRowsSelectedStatus === 'some';
const onChange = () => {
selectAllRows();
};
return (
<StyledContainer>
<Checkbox
checked={checked}
onChange={onChange}
indeterminate={indeterminate}
/>
</StyledContainer>
);
};

View File

@ -0,0 +1 @@
export const ColumnHeadDropdownId = 'table-head-options';

View File

@ -0,0 +1,2 @@
// We should either apply the constant all caps case or maybe define a more general enum to store those ids ?
export const TableOptionsDropdownId = 'table-options';

View File

@ -0,0 +1,52 @@
{
"ch": "Switzerland",
"de": "Germany",
"ca": "Canada",
"us": "US",
"se": "Sweden",
"jp": "Japan",
"au": "Australia",
"gb": "UK",
"fr": "France",
"dk": "Denmark",
"nz": "New Zealand",
"nl": "Netherlands",
"no": "Norway",
"it": "Italy",
"fi": "Finland",
"es": "Spain",
"cn": "China",
"be": "Belgium",
"sg": "Singapore",
"kr": "South Korea",
"ae": "UAE",
"at": "Austria",
"ie": "Ireland",
"lu": "Luxembourg",
"gr": "Greece",
"pt": "Portugal",
"br": "Brazil",
"th": "Thailand",
"qa": "Qatar",
"tr": "Turkey",
"in": "India",
"pl": "Poland",
"mx": "Mexico",
"sa": "Saudi Arabia",
"eg": "Egypt",
"ru": "Russia",
"il": "Israel",
"ar": "Argentina",
"my": "Malaysia",
"cr": "Costa Rica",
"id": "Indonesia",
"za": "South Africa",
"ma": "Morocco",
"cz": "Czechia",
"hr": "Croatia",
"ph": "Philippines",
"vn": "Vietnam",
"hu": "Hungary",
"cl": "Chile",
"pe": "Peru"
}

View File

@ -0,0 +1,11 @@
import React from 'react';
import { useRecoilValue } from 'recoil';
import { ContextMenu } from '@/ui/navigation/context-menu/components/ContextMenu';
import { selectedRowIdsSelector } from '../../states/selectors/selectedRowIdsSelector';
export const DataTableContextMenu = () => {
const selectedRowIds = useRecoilValue(selectedRowIdsSelector);
return <ContextMenu selectedIds={selectedRowIds} />;
};

View File

@ -0,0 +1,5 @@
import { createContext } from 'react';
import { HotkeyScope } from '@/ui/utilities/hotkey/types/HotkeyScope';
export const CellHotkeyScopeContext = createContext<HotkeyScope | null>(null);

View File

@ -0,0 +1,8 @@
import { createContext } from 'react';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { ColumnDefinition } from '../types/ColumnDefinition';
export const ColumnContext =
createContext<ColumnDefinition<FieldMetadata> | null>(null);

View File

@ -0,0 +1,3 @@
import { createContext } from 'react';
export const ColumnIndexContext = createContext<number>(0);

View File

@ -0,0 +1,5 @@
import { createContext } from 'react';
export const EntityUpdateMutationContext = createContext<(params: any) => void>(
{} as any,
);

View File

@ -0,0 +1,3 @@
import { createContext } from 'react';
export const RowIdContext = createContext<string | null>(null);

View File

@ -0,0 +1,3 @@
import { createContext } from 'react';
export const RowIndexContext = createContext<number>(0);

View File

@ -0,0 +1,11 @@
import { createContext } from 'react';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { ColumnDefinition } from '../types/ColumnDefinition';
export const TableContext = createContext<{
onColumnsChange?: (
columns: ColumnDefinition<FieldMetadata>[],
) => void | Promise<void>;
}>({});

View File

@ -0,0 +1,48 @@
import { useCurrentTableCellEditMode } from '../table-cell/hooks/useCurrentTableCellEditMode';
import { useTableCell } from '../table-cell/hooks/useTableCell';
import { useMoveSoftFocus } from './useMoveSoftFocus';
export const useCellInputEventHandlers = <T>({
onSubmit,
onCancel,
}: {
onSubmit?: (newValue: T) => void;
onCancel?: () => void;
}) => {
const { closeTableCell: closeEditableCell } = useTableCell();
const { isCurrentTableCellInEditMode: isCurrentCellInEditMode } =
useCurrentTableCellEditMode();
const { moveRight, moveLeft, moveDown } = useMoveSoftFocus();
return {
handleClickOutside: (event: MouseEvent | TouchEvent, newValue: T) => {
if (isCurrentCellInEditMode) {
event.stopImmediatePropagation();
onSubmit?.(newValue);
closeEditableCell();
}
},
handleEscape: () => {
closeEditableCell();
onCancel?.();
},
handleEnter: (newValue: T) => {
onSubmit?.(newValue);
closeEditableCell();
moveDown();
},
handleTab: (newValue: T) => {
onSubmit?.(newValue);
closeEditableCell();
moveRight();
},
handleShiftTab: (newValue: T) => {
onSubmit?.(newValue);
closeEditableCell();
moveLeft();
},
};
};

View File

@ -0,0 +1,18 @@
import { useRecoilCallback } from 'recoil';
import { currentTableCellInEditModePositionState } from '../states/currentTableCellInEditModePositionState';
import { isTableCellInEditModeFamilyState } from '../states/isTableCellInEditModeFamilyState';
export const useCloseCurrentTableCellInEditMode = () =>
useRecoilCallback(({ set, snapshot }) => {
return async () => {
const currentTableCellInEditModePosition = await snapshot.getPromise(
currentTableCellInEditModePositionState,
);
set(
isTableCellInEditModeFamilyState(currentTableCellInEditModePosition),
false,
);
};
}, []);

View File

@ -0,0 +1,9 @@
import { useContext } from 'react';
import { RowIdContext } from '../contexts/RowIdContext';
export const useCurrentRowEntityId = () => {
const currentEntityId = useContext(RowIdContext);
return currentEntityId;
};

View File

@ -0,0 +1,36 @@
import { useContext } from 'react';
import { useRecoilCallback, useRecoilState } from 'recoil';
import { RowIdContext } from '../contexts/RowIdContext';
import { isRowSelectedFamilyState } from '../states/isRowSelectedFamilyState';
export const useCurrentRowSelected = () => {
const currentRowId = useContext(RowIdContext);
const [isRowSelected] = useRecoilState(
isRowSelectedFamilyState(currentRowId ?? ''),
);
const setCurrentRowSelected = useRecoilCallback(
({ set, snapshot }) =>
(newSelectedState: boolean) => {
if (!currentRowId) return;
const isRowSelected = snapshot
.getLoadable(isRowSelectedFamilyState(currentRowId))
.valueOrThrow();
if (newSelectedState && !isRowSelected) {
set(isRowSelectedFamilyState(currentRowId), true);
} else if (!newSelectedState && isRowSelected) {
set(isRowSelectedFamilyState(currentRowId), false);
}
},
[currentRowId],
);
return {
currentRowSelected: isRowSelected,
setCurrentRowSelected,
};
};

View File

@ -0,0 +1,18 @@
import { useRecoilCallback } from 'recoil';
import { isSoftFocusActiveState } from '../states/isSoftFocusActiveState';
import { isSoftFocusOnTableCellFamilyState } from '../states/isSoftFocusOnTableCellFamilyState';
import { softFocusPositionState } from '../states/softFocusPositionState';
export const useDisableSoftFocus = () =>
useRecoilCallback(({ set, snapshot }) => {
return () => {
const currentPosition = snapshot
.getLoadable(softFocusPositionState)
.valueOrThrow();
set(isSoftFocusActiveState, false);
set(isSoftFocusOnTableCellFamilyState(currentPosition), false);
};
}, []);

View File

@ -0,0 +1,26 @@
import { useRecoilCallback } from 'recoil';
import { currentTableCellInEditModePositionState } from '../states/currentTableCellInEditModePositionState';
import { isTableCellInEditModeFamilyState } from '../states/isTableCellInEditModeFamilyState';
export const useGetIsSomeCellInEditMode = () => {
return useRecoilCallback(
({ snapshot }) =>
() => {
const currentTableCellInEditModePosition = snapshot
.getLoadable(currentTableCellInEditModePositionState)
.valueOrThrow();
const isSomeCellInEditMode = snapshot
.getLoadable(
isTableCellInEditModeFamilyState(
currentTableCellInEditModePosition,
),
)
.valueOrThrow();
return isSomeCellInEditMode;
},
[],
);
};

View File

@ -0,0 +1,39 @@
import { useRecoilCallback } from 'recoil';
import { currentHotkeyScopeState } from '@/ui/utilities/hotkey/states/internal/currentHotkeyScopeState';
import { isSoftFocusActiveState } from '../states/isSoftFocusActiveState';
import { TableHotkeyScope } from '../types/TableHotkeyScope';
import { useCloseCurrentTableCellInEditMode } from './useCloseCurrentTableCellInEditMode';
import { useDisableSoftFocus } from './useDisableSoftFocus';
export const useLeaveTableFocus = () => {
const disableSoftFocus = useDisableSoftFocus();
const closeCurrentCellInEditMode = useCloseCurrentTableCellInEditMode();
return useRecoilCallback(
({ snapshot }) =>
() => {
const isSoftFocusActive = snapshot
.getLoadable(isSoftFocusActiveState)
.valueOrThrow();
const currentHotkeyScope = snapshot
.getLoadable(currentHotkeyScopeState)
.valueOrThrow();
if (!isSoftFocusActive) {
return;
}
if (currentHotkeyScope?.scope === TableHotkeyScope.Table) {
return;
}
closeCurrentCellInEditMode();
disableSoftFocus();
},
[closeCurrentCellInEditMode, disableSoftFocus],
);
};

View File

@ -0,0 +1,62 @@
import { Key } from 'ts-key-enum';
import { useScopedHotkeys } from '@/ui/utilities/hotkey/hooks/useScopedHotkeys';
import { useSetHotkeyScope } from '@/ui/utilities/hotkey/hooks/useSetHotkeyScope';
import { TableHotkeyScope } from '../types/TableHotkeyScope';
import { useDisableSoftFocus } from './useDisableSoftFocus';
import { useMoveSoftFocus } from './useMoveSoftFocus';
export const useMapKeyboardToSoftFocus = () => {
const { moveDown, moveLeft, moveRight, moveUp } = useMoveSoftFocus();
const disableSoftFocus = useDisableSoftFocus();
const setHotkeyScope = useSetHotkeyScope();
useScopedHotkeys(
[Key.ArrowUp, `${Key.Shift}+${Key.Enter}`],
() => {
moveUp();
},
TableHotkeyScope.TableSoftFocus,
[moveUp],
);
useScopedHotkeys(
Key.ArrowDown,
() => {
moveDown();
},
TableHotkeyScope.TableSoftFocus,
[moveDown],
);
useScopedHotkeys(
[Key.ArrowLeft, `${Key.Shift}+${Key.Tab}`],
() => {
moveLeft();
},
TableHotkeyScope.TableSoftFocus,
[moveLeft],
);
useScopedHotkeys(
[Key.ArrowRight, Key.Tab],
() => {
moveRight();
},
TableHotkeyScope.TableSoftFocus,
[moveRight],
);
useScopedHotkeys(
[Key.Escape],
() => {
setHotkeyScope(TableHotkeyScope.Table, { goto: true });
disableSoftFocus();
},
TableHotkeyScope.TableSoftFocus,
[disableSoftFocus],
);
};

View File

@ -0,0 +1,23 @@
import { useRecoilCallback } from 'recoil';
import { currentTableCellInEditModePositionState } from '../states/currentTableCellInEditModePositionState';
import { isTableCellInEditModeFamilyState } from '../states/isTableCellInEditModeFamilyState';
import { TableCellPosition } from '../types/TableCellPosition';
export const useMoveEditModeToTableCellPosition = () =>
useRecoilCallback(({ set, snapshot }) => {
return (newPosition: TableCellPosition) => {
const currentTableCellInEditModePosition = snapshot
.getLoadable(currentTableCellInEditModePositionState)
.valueOrThrow();
set(
isTableCellInEditModeFamilyState(currentTableCellInEditModePosition),
false,
);
set(currentTableCellInEditModePositionState, newPosition);
set(isTableCellInEditModeFamilyState(newPosition), true);
};
}, []);

View File

@ -0,0 +1,159 @@
import { useRecoilCallback } from 'recoil';
import { useRecoilScopeId } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopeId';
import { numberOfTableRowsState } from '../states/numberOfTableRowsState';
import { TableRecoilScopeContext } from '../states/recoil-scope-contexts/TableRecoilScopeContext';
import { numberOfTableColumnsScopedSelector } from '../states/selectors/numberOfTableColumnsScopedSelector';
import { softFocusPositionState } from '../states/softFocusPositionState';
import { useSetSoftFocusPosition } from './useSetSoftFocusPosition';
// TODO: stories
export const useMoveSoftFocus = () => {
const tableScopeId = useRecoilScopeId(TableRecoilScopeContext);
const setSoftFocusPosition = useSetSoftFocusPosition();
const moveUp = useRecoilCallback(
({ snapshot }) =>
() => {
const softFocusPosition = snapshot
.getLoadable(softFocusPositionState)
.valueOrThrow();
let newRowNumber = softFocusPosition.row - 1;
if (newRowNumber < 0) {
newRowNumber = 0;
}
setSoftFocusPosition({
...softFocusPosition,
row: newRowNumber,
});
},
[setSoftFocusPosition],
);
const moveDown = useRecoilCallback(
({ snapshot }) =>
() => {
const softFocusPosition = snapshot
.getLoadable(softFocusPositionState)
.valueOrThrow();
const numberOfTableRows = snapshot
.getLoadable(numberOfTableRowsState)
.valueOrThrow();
let newRowNumber = softFocusPosition.row + 1;
if (newRowNumber >= numberOfTableRows) {
newRowNumber = numberOfTableRows - 1;
}
setSoftFocusPosition({
...softFocusPosition,
row: newRowNumber,
});
},
[setSoftFocusPosition],
);
const moveRight = useRecoilCallback(
({ snapshot }) =>
() => {
const softFocusPosition = snapshot
.getLoadable(softFocusPositionState)
.valueOrThrow();
const numberOfTableColumns = snapshot
.getLoadable(numberOfTableColumnsScopedSelector(tableScopeId))
.valueOrThrow();
const numberOfTableRows = snapshot
.getLoadable(numberOfTableRowsState)
.valueOrThrow();
const currentColumnNumber = softFocusPosition.column;
const currentRowNumber = softFocusPosition.row;
const isLastRowAndLastColumn =
currentColumnNumber === numberOfTableColumns - 1 &&
currentRowNumber === numberOfTableRows - 1;
const isLastColumnButNotLastRow =
currentColumnNumber === numberOfTableColumns - 1 &&
currentRowNumber !== numberOfTableRows - 1;
const isNotLastColumn =
currentColumnNumber !== numberOfTableColumns - 1;
if (isLastRowAndLastColumn) {
return;
}
if (isNotLastColumn) {
setSoftFocusPosition({
row: currentRowNumber,
column: currentColumnNumber + 1,
});
} else if (isLastColumnButNotLastRow) {
setSoftFocusPosition({
row: currentRowNumber + 1,
column: 0,
});
}
},
[setSoftFocusPosition, tableScopeId],
);
const moveLeft = useRecoilCallback(
({ snapshot }) =>
() => {
const softFocusPosition = snapshot
.getLoadable(softFocusPositionState)
.valueOrThrow();
const numberOfTableColumns = snapshot
.getLoadable(numberOfTableColumnsScopedSelector(tableScopeId))
.valueOrThrow();
const currentColumnNumber = softFocusPosition.column;
const currentRowNumber = softFocusPosition.row;
const isFirstRowAndFirstColumn =
currentColumnNumber === 0 && currentRowNumber === 0;
const isFirstColumnButNotFirstRow =
currentColumnNumber === 0 && currentRowNumber > 0;
const isNotFirstColumn = currentColumnNumber > 0;
if (isFirstRowAndFirstColumn) {
return;
}
if (isNotFirstColumn) {
setSoftFocusPosition({
row: currentRowNumber,
column: currentColumnNumber - 1,
});
} else if (isFirstColumnButNotFirstRow) {
setSoftFocusPosition({
row: currentRowNumber - 1,
column: numberOfTableColumns - 1,
});
}
},
[setSoftFocusPosition, tableScopeId],
);
return {
moveDown,
moveLeft,
moveRight,
moveUp,
};
};

View File

@ -0,0 +1,27 @@
import { useRecoilCallback } from 'recoil';
import { currentTableCellInEditModePositionState } from '../states/currentTableCellInEditModePositionState';
import { isTableCellInEditModeFamilyState } from '../states/isTableCellInEditModeFamilyState';
import { useSetSoftFocusOnCurrentTableCell } from '../table-cell/hooks/useSetSoftFocusOnCurrentTableCell';
export const useMoveSoftFocusToCurrentCellOnHover = () => {
const setSoftFocusOnCurrentTableCell = useSetSoftFocusOnCurrentTableCell();
return useRecoilCallback(
({ snapshot }) =>
() => {
const currentTableCellInEditModePosition = snapshot
.getLoadable(currentTableCellInEditModePositionState)
.valueOrThrow();
const isSomeCellInEditMode = snapshot.getLoadable(
isTableCellInEditModeFamilyState(currentTableCellInEditModePosition),
);
if (!isSomeCellInEditMode.contents) {
setSoftFocusOnCurrentTableCell();
}
},
[setSoftFocusOnCurrentTableCell],
);
};

View File

@ -0,0 +1,19 @@
import { useRecoilCallback } from 'recoil';
import { isRowSelectedFamilyState } from '../states/isRowSelectedFamilyState';
import { tableRowIdsState } from '../states/tableRowIdsState';
export const useResetTableRowSelection = () =>
useRecoilCallback(
({ snapshot, set }) =>
() => {
const tableRowIds = snapshot
.getLoadable(tableRowIdsState)
.valueOrThrow();
for (const rowId of tableRowIds) {
set(isRowSelectedFamilyState(rowId), false);
}
},
[],
);

View File

@ -0,0 +1,41 @@
import { useRecoilCallback, useRecoilValue } from 'recoil';
import { isRowSelectedFamilyState } from '../states/isRowSelectedFamilyState';
import { allRowsSelectedStatusSelector } from '../states/selectors/allRowsSelectedStatusSelector';
import { tableRowIdsState } from '../states/tableRowIdsState';
export const useSelectAllRows = () => {
const allRowsSelectedStatus = useRecoilValue(allRowsSelectedStatusSelector);
const selectAllRows = useRecoilCallback(
({ set, snapshot }) =>
() => {
const allRowsSelectedStatus = snapshot
.getLoadable(allRowsSelectedStatusSelector)
.valueOrThrow();
const tableRowIds = snapshot
.getLoadable(tableRowIdsState)
.valueOrThrow();
if (
allRowsSelectedStatus === 'none' ||
allRowsSelectedStatus === 'some'
) {
for (const rowId of tableRowIds) {
set(isRowSelectedFamilyState(rowId), true);
}
} else {
for (const rowId of tableRowIds) {
set(isRowSelectedFamilyState(rowId), false);
}
}
},
[],
);
return {
allRowsSelectedStatus,
selectAllRows,
};
};

View File

@ -0,0 +1,70 @@
import { useRecoilCallback } from 'recoil';
import { entityFieldsFamilyState } from '@/ui/data/field/states/entityFieldsFamilyState';
import { availableFiltersScopedState } from '@/ui/data/view-bar/states/availableFiltersScopedState';
import { availableSortsScopedState } from '@/ui/data/view-bar/states/availableSortsScopedState';
import { entityCountInCurrentViewState } from '@/ui/data/view-bar/states/entityCountInCurrentViewState';
import { FilterDefinition } from '@/ui/data/view-bar/types/FilterDefinition';
import { SortDefinition } from '@/ui/data/view-bar/types/SortDefinition';
import { useRecoilScopeId } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopeId';
import { isFetchingDataTableDataState } from '../states/isFetchingDataTableDataState';
import { numberOfTableRowsState } from '../states/numberOfTableRowsState';
import { TableRecoilScopeContext } from '../states/recoil-scope-contexts/TableRecoilScopeContext';
import { tableRowIdsState } from '../states/tableRowIdsState';
import { useResetTableRowSelection } from './useResetTableRowSelection';
export const useSetDataTableData = () => {
const resetTableRowSelection = useResetTableRowSelection();
const tableContextScopeId = useRecoilScopeId(TableRecoilScopeContext);
return useRecoilCallback(
({ set, snapshot }) =>
<T extends { id: string }>(
newEntityArray: T[],
filterDefinitionArray: FilterDefinition[],
sortDefinitionArray: SortDefinition[],
) => {
for (const entity of newEntityArray) {
const currentEntity = snapshot
.getLoadable(entityFieldsFamilyState(entity.id))
.valueOrThrow();
if (JSON.stringify(currentEntity) !== JSON.stringify(entity)) {
set(entityFieldsFamilyState(entity.id), entity);
}
}
const entityIds = newEntityArray.map((entity) => entity.id);
set(tableRowIdsState, (currentRowIds) => {
if (JSON.stringify(currentRowIds) !== JSON.stringify(entityIds)) {
return entityIds;
}
return currentRowIds;
});
resetTableRowSelection();
set(numberOfTableRowsState, entityIds.length);
set(entityCountInCurrentViewState, entityIds.length);
set(
availableFiltersScopedState(tableContextScopeId),
filterDefinitionArray,
);
set(
availableSortsScopedState(tableContextScopeId),
sortDefinitionArray,
);
set(isFetchingDataTableDataState, false);
},
[resetTableRowSelection, tableContextScopeId],
);
};

View File

@ -0,0 +1,8 @@
import { useRecoilCallback } from 'recoil';
import { isRowSelectedFamilyState } from '../states/isRowSelectedFamilyState';
export const useSetRowSelectedState = () =>
useRecoilCallback(({ set }) => (rowId: string, selected: boolean) => {
set(isRowSelectedFamilyState(rowId), selected);
});

View File

@ -0,0 +1,23 @@
import { useRecoilCallback } from 'recoil';
import { isSoftFocusActiveState } from '../states/isSoftFocusActiveState';
import { isSoftFocusOnTableCellFamilyState } from '../states/isSoftFocusOnTableCellFamilyState';
import { softFocusPositionState } from '../states/softFocusPositionState';
import { TableCellPosition } from '../types/TableCellPosition';
export const useSetSoftFocusPosition = () =>
useRecoilCallback(({ set, snapshot }) => {
return (newPosition: TableCellPosition) => {
const currentPosition = snapshot
.getLoadable(softFocusPositionState)
.valueOrThrow();
set(isSoftFocusActiveState, true);
set(isSoftFocusOnTableCellFamilyState(currentPosition), false);
set(softFocusPositionState, newPosition);
set(isSoftFocusOnTableCellFamilyState(newPosition), true);
};
}, []);

View File

@ -0,0 +1,115 @@
import { useCallback, useContext } from 'react';
import { useSetRecoilState } from 'recoil';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { currentViewIdScopedState } from '@/ui/data/view-bar/states/currentViewIdScopedState';
import { ViewFieldForVisibility } from '@/ui/data/view-bar/types/ViewFieldForVisibility';
import { useRecoilScopedState } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopedState';
import { useRecoilScopedValue } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopedValue';
import { useMoveViewColumns } from '@/views/hooks/useMoveViewColumns';
import { TableContext } from '../contexts/TableContext';
import { availableTableColumnsScopedState } from '../states/availableTableColumnsScopedState';
import { TableRecoilScopeContext } from '../states/recoil-scope-contexts/TableRecoilScopeContext';
import { savedTableColumnsFamilyState } from '../states/savedTableColumnsFamilyState';
import { tableColumnsScopedState } from '../states/tableColumnsScopedState';
import { ColumnDefinition } from '../types/ColumnDefinition';
export const useTableColumns = () => {
const { onColumnsChange } = useContext(TableContext);
const [availableTableColumns] = useRecoilScopedState(
availableTableColumnsScopedState,
TableRecoilScopeContext,
);
const currentViewId = useRecoilScopedValue(
currentViewIdScopedState,
TableRecoilScopeContext,
);
const setSavedTableColumns = useSetRecoilState(
savedTableColumnsFamilyState(currentViewId),
);
const [tableColumns, setTableColumns] = useRecoilScopedState(
tableColumnsScopedState,
TableRecoilScopeContext,
);
const { handleColumnMove } = useMoveViewColumns();
const handleColumnsChange = useCallback(
async (columns: ColumnDefinition<FieldMetadata>[]) => {
setSavedTableColumns(columns);
setTableColumns(columns);
await onColumnsChange?.(columns);
},
[onColumnsChange, setSavedTableColumns, setTableColumns],
);
const handleColumnReorder = useCallback(
async (columns: ColumnDefinition<FieldMetadata>[]) => {
const updatedColumns = columns.map((column, index) => ({
...column,
index,
}));
await handleColumnsChange(updatedColumns);
},
[handleColumnsChange],
);
const handleColumnVisibilityChange = useCallback(
async (viewField: ViewFieldForVisibility) => {
const isNewColumn = !tableColumns.some(
(tableColumns) => tableColumns.key === viewField.key,
);
if (isNewColumn) {
const newColumn = availableTableColumns.find(
(availableTableColumn) => availableTableColumn.key === viewField.key,
);
if (!newColumn) return;
const nextColumns = [
...tableColumns,
{ ...newColumn, isVisible: true },
];
await handleColumnsChange(nextColumns);
} else {
const nextColumns = tableColumns.map((previousColumn) =>
previousColumn.key === viewField.key
? { ...previousColumn, isVisible: !viewField.isVisible }
: previousColumn,
);
await handleColumnsChange(nextColumns);
}
},
[tableColumns, availableTableColumns, handleColumnsChange],
);
const handleMoveTableColumn = useCallback(
(direction: 'left' | 'right', column: ColumnDefinition<FieldMetadata>) => {
const currentColumnArrayIndex = tableColumns.findIndex(
(tableColumn) => tableColumn.key === column.key,
);
const columns = handleColumnMove(
direction,
currentColumnArrayIndex,
tableColumns,
);
setTableColumns(columns);
},
[tableColumns, setTableColumns, handleColumnMove],
);
return {
handleColumnVisibilityChange,
handleMoveTableColumn,
handleColumnReorder,
handleColumnsChange,
};
};

View File

@ -0,0 +1,18 @@
import { useRecoilCallback } from 'recoil';
import { entityFieldsFamilyState } from '@/ui/data/field/states/entityFieldsFamilyState';
export const useUpsertDataTableItem = () =>
useRecoilCallback(
({ set, snapshot }) =>
<T extends { id: string }>(entity: T) => {
const currentEntity = snapshot
.getLoadable(entityFieldsFamilyState(entity.id))
.valueOrThrow();
if (JSON.stringify(currentEntity) !== JSON.stringify(entity)) {
set(entityFieldsFamilyState(entity.id), entity);
}
},
[],
);

View File

@ -0,0 +1,33 @@
import { useRecoilCallback } from 'recoil';
import { entityFieldsFamilyState } from '@/ui/data/field/states/entityFieldsFamilyState';
export const useUpsertDataTableItems = () =>
useRecoilCallback(
({ set, snapshot }) =>
<T extends { id: string }>(entities: T[]) => {
// Create a map of new entities for quick lookup.
const newEntityMap = new Map(
entities.map((entity) => [entity.id, entity]),
);
// Filter out entities that are already the same in the state.
const entitiesToUpdate = entities.filter((entity) => {
const currentEntity = snapshot
.getLoadable(entityFieldsFamilyState(entity.id))
.valueMaybe();
return (
!currentEntity ||
JSON.stringify(currentEntity) !==
JSON.stringify(newEntityMap.get(entity.id))
);
});
// Batch set state for the filtered entities.
for (const entity of entitiesToUpdate) {
set(entityFieldsFamilyState(entity.id), entity);
}
},
[],
);

View File

@ -0,0 +1,16 @@
import { useRecoilCallback } from 'recoil';
import { tableRowIdsState } from '../states/tableRowIdsState';
export const useUpsertTableRowId = () =>
useRecoilCallback(
({ set, snapshot }) =>
(rowId: string) => {
const currentRowIds = snapshot
.getLoadable(tableRowIdsState)
.valueOrThrow();
set(tableRowIdsState, Array.from(new Set([rowId, ...currentRowIds])));
},
[],
);

View File

@ -0,0 +1,17 @@
import { useRecoilCallback } from 'recoil';
import { tableRowIdsState } from '../states/tableRowIdsState';
export const useUpsertTableRowIds = () =>
useRecoilCallback(
({ set, snapshot }) =>
(rowIds: string[]) => {
const currentRowIds = snapshot
.getLoadable(tableRowIdsState)
.valueOrThrow();
const uniqueRowIds = Array.from(new Set([...rowIds, ...currentRowIds]));
set(tableRowIdsState, uniqueRowIds);
},
[],
);

View File

@ -0,0 +1,30 @@
import { useResetRecoilState } from 'recoil';
import { ViewBarDropdownButton } from '@/ui/data/view-bar/components/ViewBarDropdownButton';
import { viewEditModeState } from '@/ui/data/view-bar/states/viewEditModeState';
import { HotkeyScope } from '@/ui/utilities/hotkey/types/HotkeyScope';
import { TableOptionsDropdownId } from '../../constants/TableOptionsDropdownId';
import { TableOptionsDropdownButton } from './TableOptionsDropdownButton';
import { TableOptionsDropdownContent } from './TableOptionsDropdownContent';
type TableOptionsDropdownProps = {
customHotkeyScope: HotkeyScope;
};
export const TableOptionsDropdown = ({
customHotkeyScope,
}: TableOptionsDropdownProps) => {
const resetViewEditMode = useResetRecoilState(viewEditModeState);
return (
<ViewBarDropdownButton
buttonComponent={<TableOptionsDropdownButton />}
dropdownHotkeyScope={customHotkeyScope}
dropdownId={TableOptionsDropdownId}
dropdownComponents={<TableOptionsDropdownContent />}
onClickOutside={resetViewEditMode}
/>
);
};

View File

@ -0,0 +1,18 @@
import { TableOptionsDropdownId } from '@/ui/data/data-table/constants/TableOptionsDropdownId';
import { StyledHeaderDropdownButton } from '@/ui/layout/dropdown/components/StyledHeaderDropdownButton';
import { useDropdown } from '@/ui/layout/dropdown/hooks/useDropdown';
export const TableOptionsDropdownButton = () => {
const { isDropdownOpen, toggleDropdown } = useDropdown({
dropdownScopeId: TableOptionsDropdownId,
});
return (
<StyledHeaderDropdownButton
isUnfolded={isDropdownOpen}
onClick={toggleDropdown}
>
Options
</StyledHeaderDropdownButton>
);
};

View File

@ -0,0 +1,197 @@
import { useCallback, useContext, useRef, useState } from 'react';
import { OnDragEndResponder } from '@hello-pangea/dnd';
import { useRecoilCallback, useRecoilValue, useResetRecoilState } from 'recoil';
import { Key } from 'ts-key-enum';
import { ViewFieldsVisibilityDropdownSection } from '@/ui/data/view-bar/components/ViewFieldsVisibilityDropdownSection';
import { ViewBarContext } from '@/ui/data/view-bar/contexts/ViewBarContext';
import { useUpsertView } from '@/ui/data/view-bar/hooks/useUpsertView';
import { currentViewScopedSelector } from '@/ui/data/view-bar/states/selectors/currentViewScopedSelector';
import { viewsByIdScopedSelector } from '@/ui/data/view-bar/states/selectors/viewsByIdScopedSelector';
import { viewEditModeState } from '@/ui/data/view-bar/states/viewEditModeState';
import { IconChevronLeft, IconFileImport, IconTag } from '@/ui/display/icon';
import { DropdownMenuHeader } from '@/ui/layout/dropdown/components/DropdownMenuHeader';
import { DropdownMenuInput } from '@/ui/layout/dropdown/components/DropdownMenuInput';
import { DropdownMenuInputContainer } from '@/ui/layout/dropdown/components/DropdownMenuInputContainer';
import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
import { StyledDropdownMenu } from '@/ui/layout/dropdown/components/StyledDropdownMenu';
import { StyledDropdownMenuSeparator } from '@/ui/layout/dropdown/components/StyledDropdownMenuSeparator';
import { useDropdown } from '@/ui/layout/dropdown/hooks/useDropdown';
import { MenuItem } from '@/ui/navigation/menu-item/components/MenuItem';
import { useScopedHotkeys } from '@/ui/utilities/hotkey/hooks/useScopedHotkeys';
import { useRecoilScopedValue } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopedValue';
import { useRecoilScopeId } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopeId';
import { useTableColumns } from '../../hooks/useTableColumns';
import { TableRecoilScopeContext } from '../../states/recoil-scope-contexts/TableRecoilScopeContext';
import { savedTableColumnsFamilyState } from '../../states/savedTableColumnsFamilyState';
import { hiddenTableColumnsScopedSelector } from '../../states/selectors/hiddenTableColumnsScopedSelector';
import { visibleTableColumnsScopedSelector } from '../../states/selectors/visibleTableColumnsScopedSelector';
import { tableColumnsScopedState } from '../../states/tableColumnsScopedState';
import { TableOptionsHotkeyScope } from '../../types/TableOptionsHotkeyScope';
type TableOptionsMenu = 'fields';
export const TableOptionsDropdownContent = () => {
const scopeId = useRecoilScopeId(TableRecoilScopeContext);
const { onImport } = useContext(ViewBarContext);
const { closeDropdown } = useDropdown();
const [currentMenu, setCurrentMenu] = useState<TableOptionsMenu | undefined>(
undefined,
);
const viewEditInputRef = useRef<HTMLInputElement>(null);
const currentView = useRecoilScopedValue(
currentViewScopedSelector,
TableRecoilScopeContext,
);
const viewEditMode = useRecoilValue(viewEditModeState);
const resetViewEditMode = useResetRecoilState(viewEditModeState);
const visibleTableColumns = useRecoilScopedValue(
visibleTableColumnsScopedSelector,
TableRecoilScopeContext,
);
const hiddenTableColumns = useRecoilScopedValue(
hiddenTableColumnsScopedSelector,
TableRecoilScopeContext,
);
const viewsById = useRecoilScopedValue(
viewsByIdScopedSelector,
TableRecoilScopeContext,
);
const { handleColumnVisibilityChange, handleColumnReorder } =
useTableColumns();
const { upsertView } = useUpsertView();
const handleViewNameSubmit = useRecoilCallback(
({ set, snapshot }) =>
async () => {
const tableColumns = await snapshot.getPromise(
tableColumnsScopedState(scopeId),
);
const isCreateMode = viewEditMode.mode === 'create';
const name = viewEditInputRef.current?.value;
const view = await upsertView(name);
if (view && isCreateMode) {
set(savedTableColumnsFamilyState(view.id), tableColumns);
}
},
[scopeId, upsertView, viewEditMode.mode],
);
const handleSelectMenu = (option: TableOptionsMenu) => {
handleViewNameSubmit();
setCurrentMenu(option);
};
const handleReorderField: OnDragEndResponder = useCallback(
(result) => {
if (!result.destination || result.destination.index === 0) {
return;
}
const reorderFields = Array.from(visibleTableColumns);
const [removed] = reorderFields.splice(result.source.index, 1);
reorderFields.splice(result.destination.index, 0, removed);
handleColumnReorder(reorderFields);
},
[visibleTableColumns, handleColumnReorder],
);
const resetMenu = () => setCurrentMenu(undefined);
useScopedHotkeys(
Key.Escape,
() => {
resetViewEditMode();
closeDropdown();
},
TableOptionsHotkeyScope.Dropdown,
);
useScopedHotkeys(
Key.Enter,
() => {
handleViewNameSubmit();
resetMenu();
resetViewEditMode();
closeDropdown();
},
TableOptionsHotkeyScope.Dropdown,
);
return (
<StyledDropdownMenu>
{!currentMenu && (
<>
<DropdownMenuInputContainer>
<DropdownMenuInput
ref={viewEditInputRef}
autoFocus={
viewEditMode.mode === 'create' || !!viewEditMode.viewId
}
placeholder={
viewEditMode.mode === 'create' ? 'New view' : 'View name'
}
defaultValue={
viewEditMode.mode === 'create'
? ''
: viewEditMode.viewId
? viewsById[viewEditMode.viewId]?.name
: currentView?.name
}
/>
</DropdownMenuInputContainer>
<StyledDropdownMenuSeparator />
<DropdownMenuItemsContainer>
<MenuItem
onClick={() => handleSelectMenu('fields')}
LeftIcon={IconTag}
text="Fields"
/>
{onImport && (
<MenuItem
onClick={onImport}
LeftIcon={IconFileImport}
text="Import"
/>
)}
</DropdownMenuItemsContainer>
</>
)}
{currentMenu === 'fields' && (
<>
<DropdownMenuHeader StartIcon={IconChevronLeft} onClick={resetMenu}>
Fields
</DropdownMenuHeader>
<StyledDropdownMenuSeparator />
<ViewFieldsVisibilityDropdownSection
title="Visible"
fields={visibleTableColumns}
onVisibilityChange={handleColumnVisibilityChange}
isDraggable={true}
onDragEnd={handleReorderField}
/>
{hiddenTableColumns.length > 0 && (
<>
<StyledDropdownMenuSeparator />
<ViewFieldsVisibilityDropdownSection
title="Hidden"
fields={hiddenTableColumns}
onVisibilityChange={handleColumnVisibilityChange}
isDraggable={false}
/>
</>
)}
</>
)}
</StyledDropdownMenu>
);
};

View File

@ -0,0 +1,44 @@
import { Meta, StoryObj } from '@storybook/react';
import { userEvent, within } from '@storybook/testing-library';
import { ViewBarContext } from '@/ui/data/view-bar/contexts/ViewBarContext';
import { RecoilScope } from '@/ui/utilities/recoil-scope/components/RecoilScope';
import { ComponentDecorator } from '~/testing/decorators/ComponentDecorator';
import { TableRecoilScopeContext } from '../../../states/recoil-scope-contexts/TableRecoilScopeContext';
import { TableOptionsDropdown } from '../TableOptionsDropdown';
const meta: Meta<typeof TableOptionsDropdown> = {
title: 'UI/Table/Options/TableOptionsDropdown',
component: TableOptionsDropdown,
decorators: [
(Story) => (
<RecoilScope CustomRecoilScopeContext={TableRecoilScopeContext}>
<ViewBarContext.Provider
value={{
ViewBarRecoilScopeContext: TableRecoilScopeContext,
}}
>
<Story />
</ViewBarContext.Provider>
</RecoilScope>
),
ComponentDecorator,
],
};
export default meta;
type Story = StoryObj<typeof TableOptionsDropdown>;
export const Default: Story = {
args: {
customHotkeyScope: { scope: 'options' },
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const dropdownButton = canvas.getByText('Options');
await userEvent.click(dropdownButton);
},
};

View File

@ -0,0 +1,13 @@
import { atomFamily } from 'recoil';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { ColumnDefinition } from '../types/ColumnDefinition';
export const availableTableColumnsScopedState = atomFamily<
ColumnDefinition<FieldMetadata>[],
string
>({
key: 'availableTableColumnsScopedState',
default: [],
});

View File

@ -0,0 +1,11 @@
import { atom } from 'recoil';
import { TableCellPosition } from '../types/TableCellPosition';
export const currentTableCellInEditModePositionState = atom<TableCellPosition>({
key: 'currentTableCellInEditModePositionState',
default: {
row: 0,
column: 1,
},
});

View File

@ -0,0 +1,6 @@
import { atom } from 'recoil';
export const isFetchingDataTableDataState = atom<boolean>({
key: 'isFetchingDataTableDataState',
default: true,
});

View File

@ -0,0 +1,6 @@
import { atomFamily } from 'recoil';
export const isRowSelectedFamilyState = atomFamily<boolean, string>({
key: 'isRowSelectedFamilyState',
default: false,
});

View File

@ -0,0 +1,6 @@
import { atom } from 'recoil';
export const isSoftFocusActiveState = atom<boolean>({
key: 'isSoftFocusActiveState',
default: false,
});

View File

@ -0,0 +1,11 @@
import { atomFamily } from 'recoil';
import { TableCellPosition } from '../types/TableCellPosition';
export const isSoftFocusOnTableCellFamilyState = atomFamily<
boolean,
TableCellPosition
>({
key: 'isSoftFocusOnTableCellFamilyState',
default: false,
});

View File

@ -0,0 +1,11 @@
import { atomFamily } from 'recoil';
import { TableCellPosition } from '../types/TableCellPosition';
export const isTableCellInEditModeFamilyState = atomFamily<
boolean,
TableCellPosition
>({
key: 'isTableCellInEditModeFamilyState',
default: false,
});

View File

@ -0,0 +1,6 @@
import { atom } from 'recoil';
export const numberOfTableRowsState = atom<number>({
key: 'numberOfTableRowsState',
default: 0,
});

View File

@ -0,0 +1,3 @@
import { createContext } from 'react';
export const TableRecoilScopeContext = createContext<string | null>(null);

View File

@ -0,0 +1,6 @@
import { atom } from 'recoil';
export const resizeFieldOffsetState = atom<number>({
key: 'resizeFieldOffsetState',
default: 0,
});

View File

@ -0,0 +1,13 @@
import { atomFamily } from 'recoil';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { ColumnDefinition } from '../types/ColumnDefinition';
export const savedTableColumnsFamilyState = atomFamily<
ColumnDefinition<FieldMetadata>[],
string | undefined
>({
key: 'savedTableColumnsFamilyState',
default: [],
});

View File

@ -0,0 +1,26 @@
import { selector } from 'recoil';
import { AllRowsSelectedStatus } from '../../types/AllRowSelectedStatus';
import { numberOfTableRowsState } from '../numberOfTableRowsState';
import { selectedRowIdsSelector } from './selectedRowIdsSelector';
export const allRowsSelectedStatusSelector = selector<AllRowsSelectedStatus>({
key: 'allRowsSelectedStatusSelector',
get: ({ get }) => {
const numberOfRows = get(numberOfTableRowsState);
const selectedRowIds = get(selectedRowIdsSelector);
const numberOfSelectedRows = selectedRowIds.length;
const allRowsSelectedStatus =
numberOfSelectedRows === 0
? 'none'
: numberOfRows === numberOfSelectedRows
? 'all'
: 'some';
return allRowsSelectedStatus;
},
});

View File

@ -0,0 +1,22 @@
import { selectorFamily } from 'recoil';
import { availableTableColumnsScopedState } from '../availableTableColumnsScopedState';
import { tableColumnsScopedState } from '../tableColumnsScopedState';
export const hiddenTableColumnsScopedSelector = selectorFamily({
key: 'hiddenTableColumnsScopedSelector',
get:
(scopeId: string) =>
({ get }) => {
const columns = get(tableColumnsScopedState(scopeId));
const columnKeys = columns.map(({ key }) => key);
const otherAvailableColumns = get(
availableTableColumnsScopedState(scopeId),
).filter(({ key }) => !columnKeys.includes(key));
return [
...columns.filter((column) => !column.isVisible),
...otherAvailableColumns,
];
},
});

View File

@ -0,0 +1,11 @@
import { selectorFamily } from 'recoil';
import { tableColumnsScopedState } from '../tableColumnsScopedState';
export const numberOfTableColumnsScopedSelector = selectorFamily({
key: 'numberOfTableColumnsScopedSelector',
get:
(scopeId: string) =>
({ get }) =>
get(tableColumnsScopedState(scopeId)).length,
});

View File

@ -0,0 +1,16 @@
import { selectorFamily } from 'recoil';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { ColumnDefinition } from '../../types/ColumnDefinition';
import { savedTableColumnsFamilyState } from '../savedTableColumnsFamilyState';
export const savedTableColumnsByKeyFamilySelector = selectorFamily({
key: 'savedTableColumnsByKeyFamilySelector',
get:
(viewId: string | undefined) =>
({ get }) =>
get(savedTableColumnsFamilyState(viewId)).reduce<
Record<string, ColumnDefinition<FieldMetadata>>
>((result, column) => ({ ...result, [column.key]: column }), {}),
});

View File

@ -0,0 +1,15 @@
import { selector } from 'recoil';
import { isRowSelectedFamilyState } from '../isRowSelectedFamilyState';
import { tableRowIdsState } from '../tableRowIdsState';
export const selectedRowIdsSelector = selector<string[]>({
key: 'selectedRowIdsSelector',
get: ({ get }) => {
const rowIds = get(tableRowIdsState);
return rowIds.filter(
(rowId) => get(isRowSelectedFamilyState(rowId)) === true,
);
},
});

View File

@ -0,0 +1,16 @@
import { selectorFamily } from 'recoil';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { ColumnDefinition } from '../../types/ColumnDefinition';
import { tableColumnsScopedState } from '../tableColumnsScopedState';
export const tableColumnsByKeyScopedSelector = selectorFamily({
key: 'tableColumnsByKeyScopedSelector',
get:
(scopeId: string) =>
({ get }) =>
get(tableColumnsScopedState(scopeId)).reduce<
Record<string, ColumnDefinition<FieldMetadata>>
>((result, column) => ({ ...result, [column.key]: column }), {}),
});

View File

@ -0,0 +1,13 @@
import { selectorFamily } from 'recoil';
import { tableColumnsScopedState } from '../tableColumnsScopedState';
export const visibleTableColumnsScopedSelector = selectorFamily({
key: 'visibleTableColumnsScopedSelector',
get:
(scopeId: string) =>
({ get }) =>
get(tableColumnsScopedState(scopeId)).filter(
(column) => column.isVisible,
),
});

View File

@ -0,0 +1,11 @@
import { atom } from 'recoil';
import { TableCellPosition } from '../types/TableCellPosition';
export const softFocusPositionState = atom<TableCellPosition>({
key: 'softFocusPositionState',
default: {
row: 0,
column: 1,
},
});

View File

@ -0,0 +1,13 @@
import { atomFamily } from 'recoil';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
import { ColumnDefinition } from '../types/ColumnDefinition';
export const tableColumnsScopedState = atomFamily<
ColumnDefinition<FieldMetadata>[],
string
>({
key: 'tableColumnsScopedState',
default: [],
});

View File

@ -0,0 +1,6 @@
import { atom } from 'recoil';
export const tableRowIdsState = atom<string[]>({
key: 'tableRowIdsState',
default: [],
});

View File

@ -0,0 +1,77 @@
import { useContext } from 'react';
import { FieldDisplay } from '@/ui/data/field/components/FieldDisplay';
import { FieldInput } from '@/ui/data/field/components/FieldInput';
import { FieldContext } from '@/ui/data/field/contexts/FieldContext';
import { FieldInputEvent } from '@/ui/data/field/types/FieldInputEvent';
import { HotkeyScope } from '@/ui/utilities/hotkey/types/HotkeyScope';
import { useMoveSoftFocus } from '../../hooks/useMoveSoftFocus';
import { useTableCell } from '../hooks/useTableCell';
import { TableCellContainer } from './TableCellContainer';
export const TableCell = ({
customHotkeyScope,
}: {
customHotkeyScope: HotkeyScope;
}) => {
const { fieldDefinition } = useContext(FieldContext);
// eslint-disable-next-line no-console
console.log({ fieldDefinition });
const { closeTableCell } = useTableCell();
const { moveLeft, moveRight, moveDown } = useMoveSoftFocus();
const handleEnter: FieldInputEvent = (persistField) => {
persistField();
closeTableCell();
moveDown();
};
const handleSubmit: FieldInputEvent = (persistField) => {
persistField();
closeTableCell();
};
const handleCancel = () => {
closeTableCell();
};
const handleEscape = () => {
closeTableCell();
};
const handleTab: FieldInputEvent = (persistField) => {
persistField();
closeTableCell();
moveRight();
};
const handleShiftTab: FieldInputEvent = (persistField) => {
persistField();
closeTableCell();
moveLeft();
};
return (
<TableCellContainer
editHotkeyScope={customHotkeyScope}
editModeContent={
<FieldInput
onCancel={handleCancel}
onClickOutside={handleCancel}
onEnter={handleEnter}
onEscape={handleEscape}
onShiftTab={handleShiftTab}
onSubmit={handleSubmit}
onTab={handleTab}
/>
}
nonEditModeContent={<FieldDisplay />}
buttonIcon={fieldDefinition.buttonIcon}
></TableCellContainer>
);
};

View File

@ -0,0 +1,26 @@
import styled from '@emotion/styled';
import { motion } from 'framer-motion';
import { IconComponent } from '@/ui/display/icon/types/IconComponent';
import { FloatingIconButton } from '@/ui/input/button/components/FloatingIconButton';
const StyledEditButtonContainer = styled(motion.div)`
position: absolute;
right: 5px;
`;
type TableCellButtonProps = {
onClick?: () => void;
Icon: IconComponent;
};
export const TableCellButton = ({ onClick, Icon }: TableCellButtonProps) => (
<StyledEditButtonContainer
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.1 }}
whileHover={{ scale: 1.04 }}
>
<FloatingIconButton size="small" onClick={onClick} Icon={Icon} />
</StyledEditButtonContainer>
);

View File

@ -0,0 +1,146 @@
import { ReactElement, useContext, useState } from 'react';
import styled from '@emotion/styled';
import { useIsFieldEmpty } from '@/ui/data/field/hooks/useIsFieldEmpty';
import { useIsFieldInputOnly } from '@/ui/data/field/hooks/useIsFieldInputOnly';
import { IconComponent } from '@/ui/display/icon/types/IconComponent';
import { HotkeyScope } from '@/ui/utilities/hotkey/types/HotkeyScope';
import { CellHotkeyScopeContext } from '../../contexts/CellHotkeyScopeContext';
import { ColumnIndexContext } from '../../contexts/ColumnIndexContext';
import { useGetIsSomeCellInEditMode } from '../../hooks/useGetIsSomeCellInEditMode';
import { useMoveSoftFocusToCurrentCellOnHover } from '../../hooks/useMoveSoftFocusToCurrentCellOnHover';
import { TableHotkeyScope } from '../../types/TableHotkeyScope';
import { useCurrentTableCellEditMode } from '../hooks/useCurrentTableCellEditMode';
import { useIsSoftFocusOnCurrentTableCell } from '../hooks/useIsSoftFocusOnCurrentTableCell';
import { useSetSoftFocusOnCurrentTableCell } from '../hooks/useSetSoftFocusOnCurrentTableCell';
import { useTableCell } from '../hooks/useTableCell';
import { TableCellButton } from './TableCellButton';
import { TableCellDisplayMode } from './TableCellDisplayMode';
import { TableCellEditMode } from './TableCellEditMode';
import { TableCellSoftFocusMode } from './TableCellSoftFocusMode';
const StyledCellBaseContainer = styled.div`
align-items: center;
box-sizing: border-box;
cursor: pointer;
display: flex;
height: 32px;
position: relative;
user-select: none;
`;
export type TableCellContainerProps = {
editModeContent: ReactElement;
nonEditModeContent: ReactElement;
editModeHorizontalAlign?: 'left' | 'right';
editModeVerticalPosition?: 'over' | 'below';
editHotkeyScope?: HotkeyScope;
transparent?: boolean;
maxContentWidth?: number;
buttonIcon?: IconComponent;
onSubmit?: () => void;
onCancel?: () => void;
};
const DEFAULT_CELL_SCOPE: HotkeyScope = {
scope: TableHotkeyScope.CellEditMode,
};
export const TableCellContainer = ({
editModeHorizontalAlign = 'left',
editModeVerticalPosition = 'over',
editModeContent,
nonEditModeContent,
editHotkeyScope,
transparent = false,
maxContentWidth,
buttonIcon,
}: TableCellContainerProps) => {
const { isCurrentTableCellInEditMode } = useCurrentTableCellEditMode();
const getIsSomeCellInEditMode = useGetIsSomeCellInEditMode();
const [isHovered, setIsHovered] = useState(false);
const moveSoftFocusToCurrentCellOnHover =
useMoveSoftFocusToCurrentCellOnHover();
const hasSoftFocus = useIsSoftFocusOnCurrentTableCell();
const setSoftFocusOnCurrentTableCell = useSetSoftFocusOnCurrentTableCell();
const { openTableCell } = useTableCell();
const handleButtonClick = () => {
setSoftFocusOnCurrentTableCell();
openTableCell();
};
const handleContainerMouseEnter = () => {
const isSomeCellInEditMode = getIsSomeCellInEditMode();
if (!isHovered && !isSomeCellInEditMode) {
setIsHovered(true);
moveSoftFocusToCurrentCellOnHover();
}
};
const handleContainerMouseLeave = () => {
setIsHovered(false);
};
const editModeContentOnly = useIsFieldInputOnly();
const isFirstColumnCell = useContext(ColumnIndexContext) === 0;
const isEmpty = useIsFieldEmpty();
const showButton =
!!buttonIcon &&
hasSoftFocus &&
!isCurrentTableCellInEditMode &&
!editModeContentOnly &&
(!isFirstColumnCell || !isEmpty);
return (
<CellHotkeyScopeContext.Provider
value={editHotkeyScope ?? DEFAULT_CELL_SCOPE}
>
<StyledCellBaseContainer
onMouseEnter={handleContainerMouseEnter}
onMouseLeave={handleContainerMouseLeave}
>
{isCurrentTableCellInEditMode ? (
<TableCellEditMode
maxContentWidth={maxContentWidth}
transparent={transparent}
editModeHorizontalAlign={editModeHorizontalAlign}
editModeVerticalPosition={editModeVerticalPosition}
>
{editModeContent}
</TableCellEditMode>
) : hasSoftFocus ? (
<>
{showButton && (
<TableCellButton onClick={handleButtonClick} Icon={buttonIcon} />
)}
<TableCellSoftFocusMode>
{editModeContentOnly ? editModeContent : nonEditModeContent}
</TableCellSoftFocusMode>
</>
) : (
<>
{showButton && (
<TableCellButton onClick={handleButtonClick} Icon={buttonIcon} />
)}
<TableCellDisplayMode>
{editModeContentOnly ? editModeContent : nonEditModeContent}
</TableCellDisplayMode>
</>
)}
</StyledCellBaseContainer>
</CellHotkeyScopeContext.Provider>
);
};

View File

@ -0,0 +1,55 @@
import { Ref } from 'react';
import styled from '@emotion/styled';
export type EditableCellDisplayContainerProps = {
softFocus?: boolean;
onClick?: () => void;
scrollRef?: Ref<HTMLDivElement>;
isHovered?: boolean;
};
const StyledEditableCellDisplayModeOuterContainer = styled.div<
Pick<EditableCellDisplayContainerProps, 'softFocus' | 'isHovered'>
>`
align-items: center;
display: flex;
height: 100%;
overflow: hidden;
padding-left: ${({ theme }) => theme.spacing(2)};
padding-right: ${({ theme }) => theme.spacing(1)};
width: 100%;
${(props) =>
props.softFocus
? `background: ${props.theme.background.transparent.secondary};
border-radius: ${props.theme.border.radius.sm};
outline: 1px solid ${props.theme.font.color.extraLight};`
: ''}
`;
const StyledEditableCellDisplayModeInnerContainer = styled.div`
align-items: center;
display: flex;
height: 100%;
overflow: hidden;
width: 100%;
`;
export const TableCellDisplayContainer = ({
children,
softFocus,
onClick,
scrollRef,
}: React.PropsWithChildren<EditableCellDisplayContainerProps>) => (
<StyledEditableCellDisplayModeOuterContainer
data-testid={
softFocus ? 'editable-cell-soft-focus-mode' : 'editable-cell-display-mode'
}
onClick={onClick}
softFocus={softFocus}
ref={scrollRef}
>
<StyledEditableCellDisplayModeInnerContainer>
{children}
</StyledEditableCellDisplayModeInnerContainer>
</StyledEditableCellDisplayModeOuterContainer>
);

View File

@ -0,0 +1,30 @@
import { useIsFieldInputOnly } from '@/ui/data/field/hooks/useIsFieldInputOnly';
import { useSetSoftFocusOnCurrentTableCell } from '../hooks/useSetSoftFocusOnCurrentTableCell';
import { useTableCell } from '../hooks/useTableCell';
import { TableCellDisplayContainer } from './TableCellDisplayContainer';
export const TableCellDisplayMode = ({
children,
}: React.PropsWithChildren<unknown>) => {
const setSoftFocusOnCurrentCell = useSetSoftFocusOnCurrentTableCell();
const isFieldInputOnly = useIsFieldInputOnly();
const { openTableCell } = useTableCell();
const handleClick = () => {
setSoftFocusOnCurrentCell();
if (!isFieldInputOnly) {
openTableCell();
}
};
return (
<TableCellDisplayContainer onClick={handleClick}>
{children}
</TableCellDisplayContainer>
);
};

View File

@ -0,0 +1,26 @@
import styled from '@emotion/styled';
import { motion } from 'framer-motion';
import { IconComponent } from '@/ui/display/icon/types/IconComponent';
import { FloatingIconButton } from '@/ui/input/button/components/FloatingIconButton';
const StyledEditButtonContainer = styled(motion.div)`
position: absolute;
right: 5px;
`;
type TableCellButtonProps = {
onClick?: () => void;
Icon: IconComponent;
};
export const TableCellButton = ({ onClick, Icon }: TableCellButtonProps) => (
<StyledEditButtonContainer
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.1 }}
whileHover={{ scale: 1.04 }}
>
<FloatingIconButton size="small" onClick={onClick} Icon={Icon} />
</StyledEditButtonContainer>
);

View File

@ -0,0 +1,53 @@
import { ReactElement } from 'react';
import styled from '@emotion/styled';
import { overlayBackground } from '@/ui/theme/constants/effects';
const StyledEditableCellEditModeContainer = styled.div<TableCellEditModeProps>`
align-items: center;
border: ${({ transparent, theme }) =>
transparent ? 'none' : `1px solid ${theme.border.color.light}`};
border-radius: ${({ transparent, theme }) =>
transparent ? 'none' : theme.border.radius.sm};
display: flex;
left: ${(props) =>
props.editModeHorizontalAlign === 'right' ? 'auto' : '0'};
margin: -1px;
max-width: ${({ maxContentWidth }) =>
maxContentWidth ? `${maxContentWidth}px` : 'none'};
min-height: 100%;
min-width: ${({ maxContentWidth }) => (maxContentWidth ? `none` : '100%')};
position: absolute;
right: ${(props) =>
props.editModeHorizontalAlign === 'right' ? '0' : 'auto'};
top: ${(props) => (props.editModeVerticalPosition === 'over' ? '0' : '100%')};
${({ transparent }) => (transparent ? '' : overlayBackground)};
z-index: 1;
`;
export type TableCellEditModeProps = {
children: ReactElement;
transparent?: boolean;
maxContentWidth?: number;
editModeHorizontalAlign?: 'left' | 'right';
editModeVerticalPosition?: 'over' | 'below';
initialValue?: string;
};
export const TableCellEditMode = ({
editModeHorizontalAlign,
editModeVerticalPosition,
children,
transparent = false,
maxContentWidth,
}: TableCellEditModeProps) => (
<StyledEditableCellEditModeContainer
maxContentWidth={maxContentWidth}
transparent={transparent}
data-testid="editable-cell-edit-mode-container"
editModeHorizontalAlign={editModeHorizontalAlign}
editModeVerticalPosition={editModeVerticalPosition}
>
{children}
</StyledEditableCellEditModeContainer>
);

View File

@ -0,0 +1,76 @@
import { PropsWithChildren, useEffect, useRef } from 'react';
import { useIsFieldInputOnly } from '@/ui/data/field/hooks/useIsFieldInputOnly';
import { useScopedHotkeys } from '@/ui/utilities/hotkey/hooks/useScopedHotkeys';
import { isNonTextWritingKey } from '@/ui/utilities/hotkey/utils/isNonTextWritingKey';
import { TableHotkeyScope } from '../../types/TableHotkeyScope';
import { useTableCell } from '../hooks/useTableCell';
import { TableCellDisplayContainer } from './TableCellDisplayContainer';
type TableCellSoftFocusModeProps = PropsWithChildren<unknown>;
export const TableCellSoftFocusMode = ({
children,
}: TableCellSoftFocusModeProps) => {
const { openTableCell } = useTableCell();
const isFieldInputOnly = useIsFieldInputOnly();
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
scrollRef.current?.scrollIntoView({ block: 'nearest' });
}, []);
useScopedHotkeys(
'enter',
() => {
openTableCell();
},
TableHotkeyScope.TableSoftFocus,
[openTableCell],
{
enabled: !isFieldInputOnly,
},
);
useScopedHotkeys(
'*',
(keyboardEvent) => {
const isWritingText =
!isNonTextWritingKey(keyboardEvent.key) &&
!keyboardEvent.ctrlKey &&
!keyboardEvent.metaKey;
if (!isWritingText) {
return;
}
openTableCell();
},
TableHotkeyScope.TableSoftFocus,
[openTableCell],
{
preventDefault: false,
enabled: !isFieldInputOnly,
},
);
const handleClick = () => {
if (!isFieldInputOnly) {
openTableCell();
}
};
return (
<TableCellDisplayContainer
onClick={handleClick}
softFocus
scrollRef={scrollRef}
>
{children}
</TableCellDisplayContainer>
);
};

View File

@ -0,0 +1,20 @@
import { useContext, useMemo } from 'react';
import { ColumnIndexContext } from '../../contexts/ColumnIndexContext';
import { RowIndexContext } from '../../contexts/RowIndexContext';
import { TableCellPosition } from '../../types/TableCellPosition';
export const useCurrentTableCellPosition = () => {
const currentRowNumber = useContext(RowIndexContext);
const currentColumnNumber = useContext(ColumnIndexContext);
const currentTableCellPosition: TableCellPosition = useMemo(
() => ({
column: currentColumnNumber,
row: currentRowNumber,
}),
[currentColumnNumber, currentRowNumber],
);
return currentTableCellPosition;
};

View File

@ -0,0 +1,26 @@
import { useCallback } from 'react';
import { useRecoilState } from 'recoil';
import { useMoveEditModeToTableCellPosition } from '../../hooks/useMoveEditModeToCellPosition';
import { isTableCellInEditModeFamilyState } from '../../states/isTableCellInEditModeFamilyState';
import { useCurrentTableCellPosition } from './useCurrentCellPosition';
export const useCurrentTableCellEditMode = () => {
const moveEditModeToTableCellPosition = useMoveEditModeToTableCellPosition();
const currentTableCellPosition = useCurrentTableCellPosition();
const [isCurrentTableCellInEditMode] = useRecoilState(
isTableCellInEditModeFamilyState(currentTableCellPosition),
);
const setCurrentTableCellInEditMode = useCallback(() => {
moveEditModeToTableCellPosition(currentTableCellPosition);
}, [currentTableCellPosition, moveEditModeToTableCellPosition]);
return {
isCurrentTableCellInEditMode,
setCurrentTableCellInEditMode,
};
};

View File

@ -0,0 +1,15 @@
import { useRecoilValue } from 'recoil';
import { isSoftFocusOnTableCellFamilyState } from '../../states/isSoftFocusOnTableCellFamilyState';
import { useCurrentTableCellPosition } from './useCurrentCellPosition';
export const useIsSoftFocusOnCurrentTableCell = () => {
const currentTableCellPosition = useCurrentTableCellPosition();
const isSoftFocusOnTableCell = useRecoilValue(
isSoftFocusOnTableCellFamilyState(currentTableCellPosition),
);
return isSoftFocusOnTableCell;
};

View File

@ -0,0 +1,29 @@
import { useRecoilCallback } from 'recoil';
import { useSetHotkeyScope } from '@/ui/utilities/hotkey/hooks/useSetHotkeyScope';
import { useSetSoftFocusPosition } from '../../hooks/useSetSoftFocusPosition';
import { isSoftFocusActiveState } from '../../states/isSoftFocusActiveState';
import { TableHotkeyScope } from '../../types/TableHotkeyScope';
import { useCurrentTableCellPosition } from './useCurrentCellPosition';
export const useSetSoftFocusOnCurrentTableCell = () => {
const setSoftFocusPosition = useSetSoftFocusPosition();
const currentTableCellPosition = useCurrentTableCellPosition();
const setHotkeyScope = useSetHotkeyScope();
return useRecoilCallback(
({ set }) =>
() => {
setSoftFocusPosition(currentTableCellPosition);
set(isSoftFocusActiveState, true);
setHotkeyScope(TableHotkeyScope.TableSoftFocus);
},
[setHotkeyScope, currentTableCellPosition, setSoftFocusPosition],
);
};

View File

@ -0,0 +1,68 @@
import { useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { FieldContext } from '@/ui/data/field/contexts/FieldContext';
import { useIsFieldEmpty } from '@/ui/data/field/hooks/useIsFieldEmpty';
import { useDragSelect } from '@/ui/utilities/drag-select/hooks/useDragSelect';
import { useSetHotkeyScope } from '@/ui/utilities/hotkey/hooks/useSetHotkeyScope';
import { HotkeyScope } from '@/ui/utilities/hotkey/types/HotkeyScope';
import { CellHotkeyScopeContext } from '../../contexts/CellHotkeyScopeContext';
import { ColumnIndexContext } from '../../contexts/ColumnIndexContext';
import { useCloseCurrentTableCellInEditMode } from '../../hooks/useCloseCurrentTableCellInEditMode';
import { TableHotkeyScope } from '../../types/TableHotkeyScope';
import { useCurrentTableCellEditMode } from './useCurrentTableCellEditMode';
const DEFAULT_CELL_SCOPE: HotkeyScope = {
scope: TableHotkeyScope.CellEditMode,
};
export const useTableCell = () => {
const { setCurrentTableCellInEditMode } = useCurrentTableCellEditMode();
const setHotkeyScope = useSetHotkeyScope();
const { setDragSelectionStartEnabled } = useDragSelect();
const closeCurrentTableCellInEditMode = useCloseCurrentTableCellInEditMode();
const customCellHotkeyScope = useContext(CellHotkeyScopeContext);
const closeTableCell = () => {
setDragSelectionStartEnabled(true);
closeCurrentTableCellInEditMode();
setHotkeyScope(TableHotkeyScope.TableSoftFocus);
};
const navigate = useNavigate();
const isFirstColumnCell = useContext(ColumnIndexContext) === 0;
const isEmpty = useIsFieldEmpty();
const { entityId, fieldDefinition } = useContext(FieldContext);
const openTableCell = () => {
if (isFirstColumnCell && !isEmpty && fieldDefinition.basePathToShowPage) {
navigate(`${fieldDefinition.basePathToShowPage}${entityId}`);
return;
}
setDragSelectionStartEnabled(false);
setCurrentTableCellInEditMode();
if (customCellHotkeyScope) {
setHotkeyScope(
customCellHotkeyScope.scope,
customCellHotkeyScope.customScopes,
);
} else {
setHotkeyScope(DEFAULT_CELL_SCOPE.scope, DEFAULT_CELL_SCOPE.customScopes);
}
};
return {
closeTableCell,
openTableCell,
};
};

View File

@ -0,0 +1,6 @@
import { atomFamily } from 'recoil';
export const isCreateModeScopedState = atomFamily<boolean, string>({
key: 'isCreateModeScopedState',
default: false,
});

View File

@ -0,0 +1,52 @@
import { useContext } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useRecoilCallback } from 'recoil';
import { ViewBar } from '@/ui/data/view-bar/components/ViewBar';
import { ViewBarContext } from '@/ui/data/view-bar/contexts/ViewBarContext';
import { useRecoilScopeId } from '@/ui/utilities/recoil-scope/hooks/useRecoilScopeId';
import { TableOptionsDropdownId } from '../../constants/TableOptionsDropdownId';
import { TableOptionsDropdown } from '../../options/components/TableOptionsDropdown';
import { TableRecoilScopeContext } from '../../states/recoil-scope-contexts/TableRecoilScopeContext';
import { savedTableColumnsFamilyState } from '../../states/savedTableColumnsFamilyState';
import { tableColumnsScopedState } from '../../states/tableColumnsScopedState';
import { TableOptionsHotkeyScope } from '../../types/TableOptionsHotkeyScope';
export const TableHeader = () => {
const { onCurrentViewSubmit, ...viewBarContextProps } =
useContext(ViewBarContext);
const tableRecoilScopeId = useRecoilScopeId(TableRecoilScopeContext);
const [_, setSearchParams] = useSearchParams();
const handleViewSelect = useRecoilCallback(
({ set, snapshot }) =>
async (viewId: string) => {
const savedTableColumns = await snapshot.getPromise(
savedTableColumnsFamilyState(viewId),
);
set(tableColumnsScopedState(tableRecoilScopeId), savedTableColumns);
setSearchParams({ view: viewId });
},
[tableRecoilScopeId, setSearchParams],
);
return (
<ViewBarContext.Provider
value={{
...viewBarContextProps,
onCurrentViewSubmit,
onViewSelect: handleViewSelect,
}}
>
<ViewBar
optionsDropdownButton={
<TableOptionsDropdown
customHotkeyScope={{ scope: TableOptionsHotkeyScope.Dropdown }}
/>
}
optionsDropdownScopeId={TableOptionsDropdownId}
/>
</ViewBarContext.Provider>
);
};

View File

@ -0,0 +1 @@
export type AllRowsSelectedStatus = 'none' | 'some' | 'all';

View File

@ -0,0 +1,8 @@
import { FieldDefinition } from '@/ui/data/field/types/FieldDefinition';
import { FieldMetadata } from '@/ui/data/field/types/FieldMetadata';
export type ColumnDefinition<T extends FieldMetadata> = FieldDefinition<T> & {
size: number;
index: number;
isVisible?: boolean;
};

View File

@ -0,0 +1,4 @@
export type TableCellPosition = {
row: number;
column: number;
};

View File

@ -0,0 +1,4 @@
export type TablePosition = {
numberOfRows: number;
numberOfColumns: number;
};

View File

@ -0,0 +1,7 @@
export enum TableHotkeyScope {
CellDoubleTextInput = 'cell-double-text-input',
CellEditMode = 'cell-edit-mode',
CellDateEditMode = 'cell-date-edit-mode',
TableSoftFocus = 'table-soft-focus',
Table = 'table',
}

View File

@ -0,0 +1,3 @@
export enum TableOptionsHotkeyScope {
Dropdown = 'table-options-dropdown',
}