|
1 | 1 | import React, { createContext, useEffect, useReducer, useRef } from "react";
|
2 | 2 | import { ColumnProps, FooterProps, SortDirection } from "../index";
|
| 3 | +import { arraysMatch, calculateColumnWidths, findTableByUuid } from "./util"; |
3 | 4 |
|
4 | 5 | type InitialState<T> = Omit<TableState<T>, "dispatch">;
|
5 | 6 |
|
@@ -138,22 +139,44 @@ function TableContextProvider<T>({ children, initialState }: ProviderProps<T>) {
|
138 | 139 | ...findColumnWidthConstants(initialState.columns as ColumnProps<T>[])
|
139 | 140 | });
|
140 | 141 |
|
| 142 | + // effects |
| 143 | + // every time the pixelWidths change, keep track of them |
| 144 | + useEffect(() => { |
| 145 | + _stateOnMount.current.pixelWidths = state.pixelWidths; |
| 146 | + }, [state.pixelWidths]); |
| 147 | + |
141 | 148 | // if certain props change, update throughout package.
|
142 | 149 | // allows the user to control props such as sortColumn,
|
143 | 150 | // columns, etc.
|
144 | 151 | useEffect(() => {
|
145 | 152 | const changedFields = getChangedFields(_stateOnMount.current, initialState);
|
146 | 153 | if (changedFields.size) {
|
| 154 | + // find the different state |
147 | 155 | const refreshed = [...changedFields].reduce(
|
148 | 156 | (pv, c) => ({ ...pv, [c]: initialState[c] }),
|
149 | 157 | {}
|
150 | 158 | ) as InitialState<T>;
|
151 | 159 |
|
| 160 | + // if the columns change, we have to update a bunch of width properties |
152 | 161 | if (refreshed.columns) {
|
153 | 162 | const { fixedWidth, remainingCols } = findColumnWidthConstants(refreshed.columns);
|
154 | 163 | refreshed.fixedWidth = fixedWidth;
|
155 | 164 | refreshed.remainingCols = remainingCols;
|
| 165 | + |
| 166 | + // we also might need to update the pixelWidths |
| 167 | + const widths = calculateColumnWidths( |
| 168 | + findTableByUuid(_stateOnMount.current.uuid || ""), |
| 169 | + remainingCols, |
| 170 | + fixedWidth, |
| 171 | + (refreshed.minColumnWidth || _stateOnMount.current.minColumnWidth) ?? 80, |
| 172 | + refreshed.columns |
| 173 | + ); |
| 174 | + if (!arraysMatch(widths, _stateOnMount.current.pixelWidths!)) { |
| 175 | + refreshed.pixelWidths = widths; |
| 176 | + } |
156 | 177 | }
|
| 178 | + |
| 179 | + // update the state ref & dispatch |
157 | 180 | _stateOnMount.current = initialState;
|
158 | 181 | dispatch({ type: "refresh", initialState: refreshed });
|
159 | 182 | }
|
|
0 commit comments