wenay-react2 1.0.17 → 1.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,6 @@ declare const optionsDef: {
4
4
  add: boolean;
5
5
  updateBuffer: boolean;
6
6
  sync: boolean;
7
- remove: boolean;
8
7
  };
9
8
  type options = Partial<typeof optionsDef>;
10
9
  export declare function applyTransactionAsyncUpdate<T>(grid: GridReadyEvent<T, any> | null | undefined, newData: (Partial<T>)[], getId: (...a: any[]) => string, bufTable: {
@@ -21,13 +20,17 @@ type CommonParams<T> = {
21
20
  option?: options;
22
21
  };
23
22
  type params<T> = CommonParams<T> & ({
24
- newData: (Partial<T>)[];
23
+ newData?: (Partial<T>)[];
24
+ removeData?: (Partial<T>)[];
25
25
  synchronization?: never;
26
26
  gridRef?: React.RefObject<GridReadyEvent<T, any> | null | undefined>;
27
27
  grid?: GridReadyEvent<T, any> | null | undefined;
28
+ onlyMemo?: boolean;
28
29
  } | ({
29
30
  newData?: never;
31
+ removeData?: never;
30
32
  synchronization: true;
33
+ onlyMemo?: never;
31
34
  } & ({
32
35
  grid: GridReadyEvent<T, any> | null | undefined;
33
36
  gridRef?: never;
@@ -1,96 +1,110 @@
1
+ // обертка для упрощения работы с гридом через точку памяти
1
2
  const optionsDef = {
2
3
  update: true,
3
4
  add: true,
4
5
  updateBuffer: true,
5
6
  sync: false,
6
- remove: false,
7
7
  };
8
- export function applyTransactionAsyncUpdate(grid, newData, getId, bufTable, option) {
9
- // Установка параметров (объединение переданных опций с настройками по умолчанию)
8
+ function applyTransactionAsyncUpdate3({ getId, bufTable, option, newData, grid, remove }) {
10
9
  const op = { ...optionsDef, ...(option ?? {}) };
11
- // Проверка наличия сетки и доступа к данным через API
12
- if (grid?.api.getRowNode) {
13
- const arrNew = []; // Массив для новых данных (добавляемые строки)
14
- const arrRemove = []; // Массив для удаляемых строк
15
- // Основная обработка данных (map используется для обновления или создания записей)
16
- const arr = newData.map(e => {
17
- // Получение ID для текущей строки
18
- const id = getId(e);
19
- const newData = { ...(bufTable[id] ?? {}), ...e };
20
- if (op.updateBuffer)
21
- bufTable[id] = newData;
22
- // Попытка найти существующую строку по ID
23
- const a = grid.api.getRowNode(id)?.data;
24
- if (!a) {
25
- // Если строка не найдена - добавить в массив для добавления
26
- arrNew.push(newData);
27
- return null; // Новая строка обрабатывается отдельно
28
- }
29
- if (option?.remove)
30
- arrRemove.push(a);
31
- // Если строка найдена - обновить данные в буфере
32
- return newData;
33
- }) // Убираем `null` и оставляем только существующие строки
34
- .filter(e => e);
35
- if (op.sync) {
36
- grid.api.applyTransaction({
37
- add: op.add ? arrNew : [],
38
- update: op.update ? arr : [],
39
- remove: op.remove ? arrRemove : []
40
- });
41
- return;
42
- }
43
- // Добавление новых строк (если есть элементы)
44
- if (arrNew.length && op.add) {
45
- // добавление элементов должно быть синхронно, т.к. может прейти его update до исполнения
46
- grid.api.applyTransaction({ add: arrNew });
47
- }
48
- // Асинхронное обновление существующих строк
49
- if (arr.length && op.update) {
50
- grid.api.applyTransactionAsync({ update: arr });
51
- }
52
- // Асинхронное удаление строк
53
- if (arrRemove.length && op.remove) {
54
- grid.api.applyTransactionAsync({ remove: arrRemove });
10
+ if (!grid?.api.getRowNode)
11
+ return;
12
+ // определяем какие строки надо добавить, а какие только обновить
13
+ const arrNew = [];
14
+ const arr = newData.map(e => {
15
+ const id = getId(e);
16
+ const merged = { ...(bufTable[id] ?? {}), ...e };
17
+ if (op.updateBuffer)
18
+ bufTable[id] = merged;
19
+ const existing = grid.api.getRowNode(id)?.data;
20
+ if (!existing) {
21
+ arrNew.push(merged);
22
+ return null;
55
23
  }
24
+ return merged;
25
+ }).filter(e => e);
26
+ if (op.sync) {
27
+ grid.api.applyTransaction({
28
+ add: op.add ? arrNew : [],
29
+ update: op.update ? arr : [],
30
+ });
31
+ return;
56
32
  }
33
+ if (arrNew.length && op.add)
34
+ grid.api.applyTransaction({ add: arrNew, remove: remove }); // для удаления важно только получить ид
35
+ if (arr.length && op.update)
36
+ grid.api.applyTransactionAsync({ update: arr, remove: remove });
37
+ }
38
+ // тут нет удаления но эта версия может использовать где то
39
+ export function applyTransactionAsyncUpdate(grid, newData, getId, bufTable, option) {
40
+ return applyTransactionAsyncUpdate3({ getId, option, newData, grid, bufTable });
57
41
  }
58
42
  const map = new WeakMap();
59
43
  export function getUpdateTable(grid, newData, getId, bufTable, option) {
60
44
  return {};
61
45
  }
46
+ function resolveGrid(params) {
47
+ if (params.grid?.api?.getRowNode)
48
+ return params.grid;
49
+ if (params.gridRef?.current?.api?.getRowNode)
50
+ return params.gridRef.current;
51
+ return null;
52
+ }
62
53
  export function applyTransactionAsyncUpdate2(params) {
63
- const { grid, gridRef, newData, getId, bufTable } = params;
64
- // Установка параметров (объединение переданных опций с настройками по умолчанию)
54
+ const { getId, bufTable, newData, removeData } = params;
65
55
  const op = { ...optionsDef, ...(params.option ?? {}) };
66
- // Проверка наличия сетки и доступа к данным через API
67
- if (grid?.api.getRowNode) {
68
- if (!newData) {
69
- applyTransactionAsyncUpdate(grid, Object.values(bufTable), getId, bufTable, op);
56
+ const g = resolveGrid(params);
57
+ if (g && params.onlyMemo != true) {
58
+ if (params.synchronization) {
59
+ // === СИНХРОНИЗАЦИЯ: bufTable — истина ===
60
+ const bufIds = new Set(Object.keys(bufTable));
61
+ const gridIds = new Set();
62
+ const arrAdd = [];
63
+ const arrUpdate = [];
64
+ const arrRemove = [];
65
+ g.api.forEachNode(node => {
66
+ if (!node.data)
67
+ return;
68
+ const id = getId(node.data);
69
+ gridIds.add(id);
70
+ if (!bufIds.has(id))
71
+ arrRemove.push(node.data);
72
+ else
73
+ arrUpdate.push(bufTable[id]);
74
+ });
75
+ for (const id of bufIds)
76
+ if (!gridIds.has(id))
77
+ arrAdd.push(bufTable[id]);
78
+ if (arrAdd.length || arrUpdate.length || arrRemove.length)
79
+ g.api.applyTransaction({
80
+ add: op.add ? arrAdd : [],
81
+ update: op.update ? arrUpdate : [],
82
+ remove: arrRemove,
83
+ });
70
84
  }
71
- else
72
- applyTransactionAsyncUpdate(grid, newData, getId, bufTable, op);
73
- }
74
- else if (gridRef?.current?.api.getRowNode) {
75
- if (!newData) {
76
- applyTransactionAsyncUpdate(gridRef.current, Object.values(bufTable), getId, bufTable, op);
85
+ else {
86
+ const toRemove = [];
87
+ removeData?.forEach(e => {
88
+ const id = getId(e);
89
+ delete bufTable[id];
90
+ const existing = g.api.getRowNode(id)?.data;
91
+ if (existing)
92
+ toRemove.push(existing);
93
+ });
94
+ if (newData?.length)
95
+ applyTransactionAsyncUpdate3({ grid: g, newData, getId, bufTable, option: op, remove: toRemove });
77
96
  }
78
- else
79
- applyTransactionAsyncUpdate(gridRef.current, newData, getId, bufTable, op);
80
97
  }
81
98
  else {
82
- if (map.get(bufTable))
99
+ if (!map.has(bufTable))
83
100
  map.set(bufTable, new Set());
84
- const m = map.get(bufTable);
85
- if (newData)
86
- newData.forEach(e => {
87
- // Получение ID для текущей строки
88
- const id = getId(e);
89
- // m? - это странно, но так надо
90
- m?.add(id);
91
- if (op.updateBuffer)
92
- bufTable[id] = { ...(bufTable[id] ?? {}), ...e };
93
- }); // Убираем `null` и оставляем только существующие строки
101
+ newData?.forEach(e => {
102
+ const id = getId(e);
103
+ bufTable[id] = { ...(bufTable[id] ?? {}), ...e };
104
+ });
105
+ removeData?.forEach(e => {
106
+ delete bufTable[getId(e)];
107
+ });
94
108
  }
95
109
  }
96
110
  export function getComparatorGrid(func) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wenay-react2",
3
- "version": "1.0.17",
3
+ "version": "1.0.19",
4
4
  "description": "Common react",
5
5
  "strict": true,
6
6
  "main": "dist/index.js",