-
-
Notifications
You must be signed in to change notification settings - Fork 550
/
set-range-values.mutation.ts
547 lines (451 loc) · 15.4 KB
/
set-range-values.mutation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/**
* Copyright 2023-present DreamNum Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type {
CellValue,
IBorderData,
ICellData,
ICopyToOptionsData,
IDocumentData,
IKeyValue,
IMutation,
IMutationCommonParams,
IObjectMatrixPrimitiveType,
IParagraph,
IRange,
IStyleData,
ITextRun,
ITextStyle,
Nullable,
} from '@univerjs/core';
import { CellValueType, CommandType, isBooleanString, isSafeNumeric, IUniverInstanceService, normalizeTextRuns, ObjectMatrix, Tools } from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
/** Params of `SetRangeValuesMutation` */
export interface ISetRangeValuesMutationParams extends IMutationCommonParams {
subUnitId: string;
unitId: string;
/**
* null for clear all
*/
cellValue?: IObjectMatrixPrimitiveType<Nullable<ICellData>>;
/**
* @deprecated not a good design
*/
options?: ICopyToOptionsData;
// /**
// * for formula calculate
// */
// isFormulaUpdate?: boolean;
}
export interface ISetRangeValuesRangeMutationParams extends ISetRangeValuesMutationParams {
range: IRange[];
}
/**
* Generate undo mutation of a `SetRangeValuesMutation`
*
* @param {IAccessor} accessor - injector accessor
* @param {ISetRangeValuesMutationParams} params - do mutation params
* @returns {ISetRangeValuesMutationParams} undo mutation params
*/
export const SetRangeValuesUndoMutationFactory = (
accessor: IAccessor,
params: ISetRangeValuesMutationParams
): ISetRangeValuesMutationParams => {
const { unitId, subUnitId, cellValue } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const workbook = univerInstanceService.getUniverSheetInstance(unitId);
if (workbook == null) {
throw new Error('workbook is null error!');
}
const worksheet = workbook.getSheetBySheetId(subUnitId);
if (worksheet == null) {
throw new Error('worksheet is null error!');
}
const cellMatrix = worksheet.getCellMatrix();
const styles = workbook.getStyles();
const undoData = new ObjectMatrix<Nullable<ICellData>>();
const newValues = new ObjectMatrix(cellValue);
newValues.forValue((row, col, newVal) => {
const cell = Tools.deepClone(cellMatrix?.getValue(row, col)) || {}; // clone cell data,prevent modify the original data
const oldStyle = styles.getStyleByCell(cell);
// transformStyle does not accept style id
let newStyle = styles.getStyleByCell(newVal);
newStyle = transformStyle(oldStyle, newStyle);
cell.s = newStyle;
undoData.setValue(row, col, setNull(cell));
});
return {
...params,
options: {},
cellValue: undoData.getMatrix(),
} as ISetRangeValuesMutationParams;
};
/**
* Supplement the data of the cell, set the other value to NULL, Used to reset properties when undoing
* @param value
* @returns
*/
function setNull(value: Nullable<ICellData>) {
if (value == null) return null;
if (value.f === undefined) {
value.f = null;
}
if (value.si === undefined) {
value.si = null;
}
if (value.p === undefined) {
value.p = null;
}
if (value.v === undefined) {
value.v = null;
}
if (value.t === undefined) {
value.t = null;
}
if (value.s === undefined) {
value.s = null;
}
if (value.custom === undefined) {
value.custom = null;
}
return value;
}
/**
* TODO@Dushusir: Excel can display numbers with up to about 15 digits of precision. When the user inputs more than 15 digits, interception is required, but there are unknown performance risks.
Intercept 15-digit number reference function truncateNumber
*/
export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, boolean> = {
id: 'sheet.mutation.set-range-values',
type: CommandType.MUTATION,
// eslint-disable-next-line max-lines-per-function
handler: (accessor, params) => {
const { cellValue, subUnitId, unitId } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const workbook = univerInstanceService.getUniverSheetInstance(unitId);
if (!workbook) {
return false;
}
const worksheet = workbook.getSheetBySheetId(subUnitId);
if (!worksheet) {
return false;
}
const cellMatrix = worksheet.getCellMatrix();
const styles = workbook.getStyles();
const newValues = new ObjectMatrix(cellValue);
// eslint-disable-next-line complexity
newValues.forValue((row, col, newVal) => {
// clear all
if (!newVal) {
cellMatrix?.setValue(row, col, {});
} else {
const oldVal = cellMatrix.getValue(row, col) || {};
// NOTE: we may need to take `p` into account
// If the new value contains t, then take t directly
const type = newVal.t
? newVal.t
: newVal.v !== undefined
? checkCellValueType(newVal.v, newVal.t)
: checkCellValueType(oldVal.v, oldVal.t);
if (newVal.f !== undefined) {
oldVal.f = newVal.f;
}
if (newVal.si !== undefined) {
oldVal.si = newVal.si;
}
if (newVal.p !== undefined) {
oldVal.p = newVal.p;
}
// Set to null, clear content
if (newVal.v !== undefined) {
oldVal.v = type === CellValueType.NUMBER
? Number(newVal.v)
: type === CellValueType.BOOLEAN
? extractBooleanValue(newVal.v) ? 1 : 0
: newVal.v;
}
if (oldVal.v !== undefined) {
oldVal.t = type;
}
// handle style
if (newVal.s !== undefined) {
// use null to clear style
const oldStyle = styles.getStyleByCell(oldVal);
if (oldStyle == null) {
// clear
delete oldVal.s;
}
if (typeof newVal.s === 'string') {
newVal.s = styles.get(newVal.s);
}
// set style
const merge = mergeStyle(oldStyle, newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
// then remove null
merge && Tools.removeNull(merge);
if (Tools.isEmptyObject(merge)) {
delete oldVal.s;
} else {
oldVal.s = styles.setValue(merge);
}
const newValueStream = `${newVal.v}\r\n`;
// Only need to copy newValue.s to oldValue.p when you modify the cell style, not when you modify the cell value.
if (!newVal.p && oldVal.p) {
if (newValueStream === oldVal.p.body?.dataStream) {
mergeRichTextStyle(oldVal.p, newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
} else {
delete oldVal.p;
}
}
}
if (newVal.custom !== undefined) {
oldVal.custom = newVal.custom;
}
cellMatrix.setValue(row, col, Tools.removeNull(oldVal));
}
});
return true;
},
};
/**
* Get the correct type after setting values to a cell.
*
* @param v the new value
* @param oldType the old type
* @returns the new type
*/
export function checkCellValueType(v: Nullable<CellValue>, oldType: Nullable<CellValueType>): Nullable<CellValueType> {
if (v === null) return null;
if (typeof v === 'string') {
if (isSafeNumeric(v)) {
if ((+v === 0 || +v === 1) && oldType === CellValueType.BOOLEAN) {
return CellValueType.BOOLEAN;
}
return CellValueType.NUMBER;
} else if (isBooleanString(v)) {
return CellValueType.BOOLEAN;
}
return CellValueType.STRING;
}
if (typeof v === 'number') {
if ((v === 0 || v === 1) && oldType === CellValueType.BOOLEAN) {
return CellValueType.BOOLEAN;
}
return CellValueType.NUMBER;
}
if (typeof v === 'boolean') {
return CellValueType.BOOLEAN;
}
return CellValueType.FORCE_STRING;
}
/**
* Check if the value can be casted to a boolean.
* @internal
* @param value
* @returns It would return null if the value cannot be casted to a boolean, and would return the boolean value if it can be casted.
*/
export function extractBooleanValue(value: Nullable<string | number | boolean>): Nullable<boolean> {
if (typeof value === 'string') {
if (value.toUpperCase() === 'TRUE') {
return true;
};
if (value.toUpperCase() === 'FALSE') {
return false;
}
if (isSafeNumeric(value)) {
if (Number(value) === 0) {
return false;
}
if (Number(value) === 1) {
return true;
}
}
}
if (typeof value === 'number') {
if (value === 0) {
return false;
}
if (value === 1) {
return true;
}
}
if (typeof value === 'boolean') {
return value;
}
return null;
}
/**
* Convert old style data for storage
* @param style
*/
export function transformStyle(oldStyle: Nullable<IStyleData>, newStyle: Nullable<IStyleData>): Nullable<IStyleData> {
const backupStyle = transformNormalKey(oldStyle, newStyle);
return backupStyle;
}
/**
* Convert old style normal key for storage
*
* @param style
*/
export function transformNormalKey(
oldStyle: Nullable<IStyleData>,
newStyle: Nullable<IStyleData>
): Nullable<IStyleData> {
// If there is no newly set style, directly store the historical style
if (!newStyle || !Object.keys(newStyle).length) {
return oldStyle;
}
const backupStyle: Record<string, any> = oldStyle || {};
for (const k in newStyle) {
if (k === 'bd') {
backupStyle[k] = transformBorders(backupStyle[k] || {}, newStyle[k]);
}
// 1. To modify the existing style,we need original setting to undo
// 2. Newly set the style, we need null to undo
else if (!(k in backupStyle)) {
backupStyle[k] = null;
}
}
return backupStyle;
}
/**
* Convert old style border for storage
*
* @param style
*/
export function transformBorders(oldBorders: IBorderData, newBorders: Nullable<IBorderData>): IBorderData {
// If there is no newly set border, directly store the historical border
if (!newBorders || !Object.keys(newBorders).length) {
return oldBorders;
}
for (const k in newBorders) {
// 1. To modify the existing border,we need original setting to undo
// 2. Newly set the border, we need null to undo
if (!(k in oldBorders)) {
(oldBorders as IKeyValue)[k] = null;
}
}
return oldBorders;
}
/**
* merge new style to old style
*
* @param oldStyle
* @param newStyle
*/
export function mergeStyle(
oldStyle: Nullable<IStyleData>,
newStyle: Nullable<IStyleData>,
isRichText: boolean = false
): Nullable<IStyleData> {
// clear style
if (newStyle === null) return newStyle;
// don't operate
if (newStyle === undefined) return oldStyle;
const backupStyle: Record<string, any> = Tools.deepClone(oldStyle) || {};
if (!backupStyle) return;
for (const k in newStyle) {
if (isRichText && ['bd', 'tr', 'td', 'ht', 'vt', 'tb', 'pd'].includes(k)) {
continue;
}
// you can only choose one of the themeColor and rgbColor of the border setting
if (k in backupStyle && k === 'bd') {
backupStyle[k] = Object.assign(backupStyle[k], newStyle[k]);
} else {
backupStyle[k] = (newStyle as IKeyValue)[k];
}
}
// Overline/Strikethrough/Underline color follows text color
// if ('cl' in backupStyle) {
// for (const k in newStyle) {
// if (['ul', 'ol', 'st'].includes(k)) {
// backupStyle[k].cl = backupStyle.cl;
// }
// }
// }
if ('cl' in backupStyle) {
if ('ul' in backupStyle && backupStyle.ul) {
backupStyle.ul.cl = backupStyle.cl;
}
if ('ol' in backupStyle && backupStyle.ol) {
backupStyle.ol.cl = backupStyle.cl;
}
if ('st' in backupStyle && backupStyle.st) {
backupStyle.st.cl = backupStyle.cl;
}
}
return backupStyle;
}
function skipParagraphs(paragraphs: IParagraph[], offset: number): number {
if (paragraphs.some((p) => p.startIndex === offset)) {
return skipParagraphs(paragraphs, offset + 1);
}
return offset;
}
/**
* Find the text style of all paragraphs and modify it to the new style
* @param p
* @param newStyle
*/
export function mergeRichTextStyle(p: IDocumentData, newStyle: Nullable<IStyleData>) {
if (p.body == null) {
return;
}
if (!Array.isArray(p.body.textRuns)) {
p.body.textRuns = [];
}
let index = 0;
const newTextRuns = [];
const paragraphs = p.body?.paragraphs || [];
for (const textRun of p.body.textRuns) {
const { st, ed, ts = {} } = textRun;
if (index < st) {
const tr: ITextRun = {
st: index,
ed: st,
};
const merge = mergeStyle({}, newStyle, true);
// then remove null
merge && Tools.removeNull(merge);
if (!Tools.isEmptyObject(merge)) {
tr.ts = merge!;
}
newTextRuns.push(tr);
}
const merge = mergeStyle(ts, newStyle, true);
// then remove null
merge && Tools.removeNull(merge);
if (Tools.isEmptyObject(merge)) {
delete textRun.ts;
} else {
textRun.ts = merge as ITextStyle;
}
newTextRuns.push(textRun);
index = skipParagraphs(paragraphs, ed);
}
const endIndex = p.body.dataStream.endsWith('\r\n') ? p.body.dataStream.length - 2 : p.body.dataStream.length;
if (index < endIndex) {
const tr: ITextRun = {
st: index,
ed: endIndex,
};
const merge = mergeStyle({}, newStyle, true);
// then remove null
merge && Tools.removeNull(merge);
if (!Tools.isEmptyObject(merge)) {
tr.ts = merge!;
}
newTextRuns.push(tr);
}
p.body.textRuns = normalizeTextRuns(newTextRuns);
}