wenay-react2 1.0.16 → 1.0.18

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,12 +20,14 @@ 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
28
  } | ({
29
29
  newData?: never;
30
+ removeData?: never;
30
31
  synchronization: true;
31
32
  } & ({
32
33
  grid: GridReadyEvent<T, any> | null | undefined;
@@ -3,92 +3,120 @@ const optionsDef = {
3
3
  add: true,
4
4
  updateBuffer: true,
5
5
  sync: false,
6
- remove: false,
7
6
  };
8
7
  export function applyTransactionAsyncUpdate(grid, newData, getId, bufTable, option) {
9
- // Установка параметров (объединение переданных опций с настройками по умолчанию)
10
8
  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
- // Если строка найдена - обновить данные в буфере
30
- return newData;
31
- }) // Убираем `null` и оставляем только существующие строки
32
- .filter(e => e);
33
- if (op.sync) {
34
- grid.api.applyTransaction({
35
- add: op.add ? arrNew : [],
36
- update: op.update ? arr : [],
37
- remove: op.remove ? arrRemove : []
38
- });
39
- return;
40
- }
41
- // Добавление новых строк (если есть элементы)
42
- if (arrNew.length && op.add) {
43
- // добавление элементов должно быть синхронно, т.к. может прейти его update до исполнения
44
- grid.api.applyTransaction({ add: arrNew });
45
- }
46
- // Асинхронное обновление существующих строк
47
- if (arr.length && op.update) {
48
- grid.api.applyTransactionAsync({ update: arr });
49
- }
50
- // Асинхронное удаление строк
51
- if (arrRemove.length && op.remove) {
52
- grid.api.applyTransactionAsync({ remove: arrRemove });
9
+ if (!grid?.api.getRowNode)
10
+ return;
11
+ const arrNew = [];
12
+ const arr = newData.map(e => {
13
+ const id = getId(e);
14
+ const merged = { ...(bufTable[id] ?? {}), ...e };
15
+ if (op.updateBuffer)
16
+ bufTable[id] = merged;
17
+ const existing = grid.api.getRowNode(id)?.data;
18
+ if (!existing) {
19
+ arrNew.push(merged);
20
+ return null;
53
21
  }
22
+ return merged;
23
+ }).filter(e => e);
24
+ if (op.sync) {
25
+ grid.api.applyTransaction({
26
+ add: op.add ? arrNew : [],
27
+ update: op.update ? arr : [],
28
+ });
29
+ return;
54
30
  }
31
+ if (arrNew.length && op.add)
32
+ grid.api.applyTransaction({ add: arrNew });
33
+ if (arr.length && op.update)
34
+ grid.api.applyTransactionAsync({ update: arr });
55
35
  }
56
36
  const map = new WeakMap();
57
37
  export function getUpdateTable(grid, newData, getId, bufTable, option) {
58
38
  return {};
59
39
  }
40
+ function resolveGrid(params) {
41
+ if (params.grid?.api?.getRowNode)
42
+ return params.grid;
43
+ const ref = ('gridRef' in params) ? params.gridRef : undefined;
44
+ if (ref?.current?.api?.getRowNode)
45
+ return ref.current;
46
+ return null;
47
+ }
60
48
  export function applyTransactionAsyncUpdate2(params) {
61
- const { grid, gridRef, newData, getId, bufTable } = params;
62
- // Установка параметров (объединение переданных опций с настройками по умолчанию)
49
+ const { getId, bufTable } = params;
63
50
  const op = { ...optionsDef, ...(params.option ?? {}) };
64
- // Проверка наличия сетки и доступа к данным через API
65
- if (grid?.api.getRowNode) {
66
- if (!newData) {
67
- applyTransactionAsyncUpdate(grid, Object.values(bufTable), getId, bufTable, op);
51
+ const g = resolveGrid(params);
52
+ if (g) {
53
+ if (params.synchronization) {
54
+ // === СИНХРОНИЗАЦИЯ: bufTable — истина ===
55
+ const bufIds = new Set(Object.keys(bufTable));
56
+ const gridIds = new Set();
57
+ const arrAdd = [];
58
+ const arrUpdate = [];
59
+ const arrRemove = [];
60
+ g.api.forEachNode(node => {
61
+ if (!node.data)
62
+ return;
63
+ const id = getId(node.data);
64
+ gridIds.add(id);
65
+ if (!bufIds.has(id))
66
+ arrRemove.push(node.data);
67
+ else
68
+ arrUpdate.push(bufTable[id]);
69
+ });
70
+ for (const id of bufIds)
71
+ if (!gridIds.has(id))
72
+ arrAdd.push(bufTable[id]);
73
+ if (arrAdd.length || arrUpdate.length || arrRemove.length)
74
+ g.api.applyTransaction({
75
+ add: op.add ? arrAdd : [],
76
+ update: op.update ? arrUpdate : [],
77
+ remove: arrRemove,
78
+ });
68
79
  }
69
- else
70
- applyTransactionAsyncUpdate(grid, newData, getId, bufTable, op);
71
- }
72
- else if (gridRef?.current?.api.getRowNode) {
73
- if (!newData) {
74
- applyTransactionAsyncUpdate(gridRef.current, Object.values(bufTable), getId, bufTable, op);
80
+ else {
81
+ const newData = 'newData' in params ? params.newData : undefined;
82
+ const removeData = 'removeData' in params ? params.removeData : undefined;
83
+ // Сначала удаляем — чтобы async update не конфликтовал
84
+ if (removeData?.length) {
85
+ const toRemove = [];
86
+ removeData.forEach(e => {
87
+ const id = getId(e);
88
+ delete bufTable[id];
89
+ const existing = g.api.getRowNode(id)?.data;
90
+ if (existing)
91
+ toRemove.push(existing);
92
+ });
93
+ if (toRemove.length)
94
+ g.api.applyTransaction({ remove: toRemove });
95
+ }
96
+ if (newData?.length)
97
+ applyTransactionAsyncUpdate(g, newData, getId, bufTable, op);
75
98
  }
76
- else
77
- applyTransactionAsyncUpdate(gridRef.current, newData, getId, bufTable, op);
78
99
  }
79
100
  else {
80
- if (map.get(bufTable))
101
+ // === ГРИД НЕ ГОТОВ — работаем только с буфером ===
102
+ if (!map.has(bufTable))
81
103
  map.set(bufTable, new Set());
82
104
  const m = map.get(bufTable);
105
+ const newData = 'newData' in params ? params.newData : undefined;
106
+ const removeData = 'removeData' in params ? params.removeData : undefined;
83
107
  if (newData)
84
108
  newData.forEach(e => {
85
- // Получение ID для текущей строки
86
109
  const id = getId(e);
87
- // m? - это странно, но так надо
88
110
  m?.add(id);
89
111
  if (op.updateBuffer)
90
112
  bufTable[id] = { ...(bufTable[id] ?? {}), ...e };
91
- }); // Убираем `null` и оставляем только существующие строки
113
+ });
114
+ if (removeData)
115
+ removeData.forEach(e => {
116
+ const id = getId(e);
117
+ m?.delete(id);
118
+ delete bufTable[id];
119
+ });
92
120
  }
93
121
  }
94
122
  export function getComparatorGrid(func) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wenay-react2",
3
- "version": "1.0.16",
3
+ "version": "1.0.18",
4
4
  "description": "Common react",
5
5
  "strict": true,
6
6
  "main": "dist/index.js",