@4399ywkf/editor 0.14.2 → 0.15.0
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.
- package/dist/{DocView-VTKFMW46.js → DocView-4MOGGX4Z.js} +4 -3
- package/dist/DocView-4MOGGX4Z.js.map +1 -0
- package/dist/SheetView-WP4DKSDS.js +3 -0
- package/dist/{SheetView-6Z5EPBN4.js.map → SheetView-WP4DKSDS.js.map} +1 -1
- package/dist/base-model.d.ts +499 -0
- package/dist/base-model.js +3 -0
- package/dist/base-model.js.map +1 -0
- package/dist/base.d.ts +910 -0
- package/dist/base.js +12971 -0
- package/dist/base.js.map +1 -0
- package/dist/chunk-3BRBH7MU.js +1833 -0
- package/dist/chunk-3BRBH7MU.js.map +1 -0
- package/dist/chunk-3KW24N3T.js +2256 -0
- package/dist/chunk-3KW24N3T.js.map +1 -0
- package/dist/{chunk-FMTC3EDQ.js → chunk-4SIP4BYI.js} +3 -3
- package/dist/{chunk-FMTC3EDQ.js.map → chunk-4SIP4BYI.js.map} +1 -1
- package/dist/{chunk-ZLEGKX2U.js → chunk-KZEURCGO.js} +9384 -9998
- package/dist/chunk-KZEURCGO.js.map +1 -0
- package/dist/{chunk-OBKIMG6G.js → chunk-X4BUO2RH.js} +4 -4
- package/dist/{chunk-OBKIMG6G.js.map → chunk-X4BUO2RH.js.map} +1 -1
- package/dist/csv.js +1 -1
- package/dist/doc-standalone.js +11888 -10255
- package/dist/doc-standalone.js.map +1 -1
- package/dist/doc.d.ts +4 -379
- package/dist/doc.js +3 -2
- package/dist/doc.js.map +1 -1
- package/dist/editor-config-context-DvLRd7Gx.d.ts +382 -0
- package/dist/{import-XL3AH3QH.js → import-TEZ37G5R.js} +5 -5
- package/dist/{import-XL3AH3QH.js.map → import-TEZ37G5R.js.map} +1 -1
- package/dist/index.js +2 -2
- package/dist/sheet.js +1 -1
- package/dist/style.css +2 -2
- package/dist/xlsx.js +4 -4
- package/package.json +10 -2
- package/dist/DocView-VTKFMW46.js.map +0 -1
- package/dist/SheetView-6Z5EPBN4.js +0 -3
- package/dist/chunk-ZLEGKX2U.js.map +0 -1
|
@@ -0,0 +1,1833 @@
|
|
|
1
|
+
import * as Y from 'yjs';
|
|
2
|
+
|
|
3
|
+
// src/base-model/fields.ts
|
|
4
|
+
var FieldType = {
|
|
5
|
+
Text: 1,
|
|
6
|
+
Number: 2,
|
|
7
|
+
SingleSelect: 3,
|
|
8
|
+
MultiSelect: 4,
|
|
9
|
+
DateTime: 5,
|
|
10
|
+
Checkbox: 7,
|
|
11
|
+
User: 11,
|
|
12
|
+
Phone: 13,
|
|
13
|
+
Url: 15,
|
|
14
|
+
Attachment: 17,
|
|
15
|
+
CreatedTime: 1001,
|
|
16
|
+
ModifiedTime: 1002,
|
|
17
|
+
CreatedUser: 1003,
|
|
18
|
+
ModifiedUser: 1004,
|
|
19
|
+
AutoNumber: 1005
|
|
20
|
+
};
|
|
21
|
+
var FIELD_UI_TYPE = {
|
|
22
|
+
1: "Text",
|
|
23
|
+
2: "Number",
|
|
24
|
+
3: "SingleSelect",
|
|
25
|
+
4: "MultiSelect",
|
|
26
|
+
5: "DateTime",
|
|
27
|
+
7: "Checkbox",
|
|
28
|
+
11: "User",
|
|
29
|
+
13: "Phone",
|
|
30
|
+
15: "Url",
|
|
31
|
+
17: "Attachment",
|
|
32
|
+
1001: "CreatedTime",
|
|
33
|
+
1002: "ModifiedTime",
|
|
34
|
+
1003: "CreatedUser",
|
|
35
|
+
1004: "ModifiedUser",
|
|
36
|
+
1005: "AutoNumber"
|
|
37
|
+
};
|
|
38
|
+
var NUMBER_UI_TYPES = ["Number", "Progress", "Currency", "Rating"];
|
|
39
|
+
var isNumberUiType = (value) => typeof value === "string" && NUMBER_UI_TYPES.includes(value);
|
|
40
|
+
var isFieldType = (type) => typeof type === "number" && Object.hasOwn(FIELD_UI_TYPE, type);
|
|
41
|
+
var COMPUTED_TYPES = /* @__PURE__ */ new Set([
|
|
42
|
+
FieldType.CreatedTime,
|
|
43
|
+
FieldType.ModifiedTime,
|
|
44
|
+
FieldType.CreatedUser,
|
|
45
|
+
FieldType.ModifiedUser,
|
|
46
|
+
FieldType.AutoNumber
|
|
47
|
+
]);
|
|
48
|
+
var isComputedFieldType = (type) => COMPUTED_TYPES.has(type);
|
|
49
|
+
function fieldUiType(field) {
|
|
50
|
+
return field.type === FieldType.Number && field.uiType ? field.uiType : FIELD_UI_TYPE[field.type];
|
|
51
|
+
}
|
|
52
|
+
var DEFAULT_TIME_ZONE = "Asia/Shanghai";
|
|
53
|
+
var RECORD_META = {
|
|
54
|
+
createdTime: "_ct",
|
|
55
|
+
createdUser: "_cb",
|
|
56
|
+
modifiedTime: "_mt",
|
|
57
|
+
modifiedUser: "_mb",
|
|
58
|
+
autoNumber: "_no"
|
|
59
|
+
};
|
|
60
|
+
var isRecordMetaKey = (key) => key.startsWith("_");
|
|
61
|
+
function fieldValueKey(field) {
|
|
62
|
+
switch (field.type) {
|
|
63
|
+
case FieldType.CreatedTime:
|
|
64
|
+
return RECORD_META.createdTime;
|
|
65
|
+
case FieldType.ModifiedTime:
|
|
66
|
+
return RECORD_META.modifiedTime;
|
|
67
|
+
case FieldType.CreatedUser:
|
|
68
|
+
return RECORD_META.createdUser;
|
|
69
|
+
case FieldType.ModifiedUser:
|
|
70
|
+
return RECORD_META.modifiedUser;
|
|
71
|
+
case FieldType.AutoNumber:
|
|
72
|
+
return RECORD_META.autoNumber;
|
|
73
|
+
default:
|
|
74
|
+
return field.id;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function readFieldValue(field, get) {
|
|
78
|
+
switch (field.type) {
|
|
79
|
+
case FieldType.ModifiedTime:
|
|
80
|
+
return get(RECORD_META.modifiedTime) ?? get(RECORD_META.createdTime);
|
|
81
|
+
case FieldType.CreatedUser: {
|
|
82
|
+
const user = get(RECORD_META.createdUser);
|
|
83
|
+
return user ? [user] : void 0;
|
|
84
|
+
}
|
|
85
|
+
case FieldType.ModifiedUser: {
|
|
86
|
+
const user = get(RECORD_META.modifiedUser) ?? get(RECORD_META.createdUser);
|
|
87
|
+
return user ? [user] : void 0;
|
|
88
|
+
}
|
|
89
|
+
default:
|
|
90
|
+
return get(fieldValueKey(field));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function defaultFieldProperty(type, uiType) {
|
|
94
|
+
switch (type) {
|
|
95
|
+
case FieldType.Number:
|
|
96
|
+
if (uiType === "Progress") return { formatter: "0%", min: 0, max: 1 };
|
|
97
|
+
if (uiType === "Currency") return { formatter: "0.00", currencyCode: "CNY" };
|
|
98
|
+
if (uiType === "Rating") return { formatter: "0", min: 1, max: 5, ratingSymbol: "star" };
|
|
99
|
+
return { formatter: "0" };
|
|
100
|
+
case FieldType.SingleSelect:
|
|
101
|
+
case FieldType.MultiSelect:
|
|
102
|
+
return { options: [] };
|
|
103
|
+
case FieldType.DateTime:
|
|
104
|
+
return { formatter: "yyyy/MM/dd" };
|
|
105
|
+
case FieldType.CreatedTime:
|
|
106
|
+
case FieldType.ModifiedTime:
|
|
107
|
+
return { formatter: "yyyy/MM/dd HH:mm" };
|
|
108
|
+
case FieldType.User:
|
|
109
|
+
return { multiple: true };
|
|
110
|
+
default:
|
|
111
|
+
return {};
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
var isEmptyCellValue = (value) => value === null || value === void 0 || value === "" || value === false || Array.isArray(value) && value.length === 0;
|
|
115
|
+
function normalizeCellValue(field, input, timeZone = DEFAULT_TIME_ZONE) {
|
|
116
|
+
if (input === null || input === void 0) return null;
|
|
117
|
+
switch (field.type) {
|
|
118
|
+
case FieldType.Text:
|
|
119
|
+
return normalizeText(input);
|
|
120
|
+
case FieldType.Number:
|
|
121
|
+
return normalizeNumberField(field, input);
|
|
122
|
+
case FieldType.SingleSelect:
|
|
123
|
+
return resolveOptionIds(field, input)[0] ?? null;
|
|
124
|
+
case FieldType.MultiSelect: {
|
|
125
|
+
const ids = resolveOptionIds(field, input);
|
|
126
|
+
return ids.length ? ids : null;
|
|
127
|
+
}
|
|
128
|
+
case FieldType.DateTime:
|
|
129
|
+
return normalizeDate(input, timeZone);
|
|
130
|
+
case FieldType.Checkbox:
|
|
131
|
+
return normalizeCheckbox(input) ? true : null;
|
|
132
|
+
case FieldType.User:
|
|
133
|
+
return normalizeUsers(input, field.property.multiple !== false);
|
|
134
|
+
case FieldType.Phone:
|
|
135
|
+
return normalizePhone(input);
|
|
136
|
+
case FieldType.Url:
|
|
137
|
+
return normalizeUrl(input);
|
|
138
|
+
case FieldType.Attachment:
|
|
139
|
+
return normalizeAttachments(input);
|
|
140
|
+
default:
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
var isSegments = (value) => value.every(
|
|
145
|
+
(item) => typeof item === "object" && item !== null && typeof item.text === "string"
|
|
146
|
+
);
|
|
147
|
+
var segmentsText = (segments) => segments.map((item) => item.text).join("");
|
|
148
|
+
function normalizeText(input) {
|
|
149
|
+
if (Array.isArray(input)) {
|
|
150
|
+
if (!isSegments(input)) return null;
|
|
151
|
+
const segments = input.map((item) => ({ type: "text", text: item.text })).filter((segment) => segment.text !== "");
|
|
152
|
+
return segments.length ? segments : null;
|
|
153
|
+
}
|
|
154
|
+
if (typeof input === "string") return input ? [{ type: "text", text: input }] : null;
|
|
155
|
+
if (typeof input === "number" || typeof input === "boolean") {
|
|
156
|
+
return [{ type: "text", text: String(input) }];
|
|
157
|
+
}
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
var CURRENCY_PREFIX = /^(?:[A-Z]{1,3})?[¥¥$€£₩]\s*/;
|
|
161
|
+
function normalizeNumber(input) {
|
|
162
|
+
if (typeof input === "number") return Number.isFinite(input) ? input : null;
|
|
163
|
+
if (Array.isArray(input) && isSegments(input)) return normalizeNumber(segmentsText(input));
|
|
164
|
+
if (typeof input !== "string") return null;
|
|
165
|
+
const text = input.trim().replace(/,/g, "").replace(CURRENCY_PREFIX, "");
|
|
166
|
+
if (!text) return null;
|
|
167
|
+
const percent2 = text.endsWith("%");
|
|
168
|
+
const value = Number(percent2 ? text.slice(0, -1) : text);
|
|
169
|
+
if (!Number.isFinite(value)) return null;
|
|
170
|
+
return percent2 ? value / 100 : value;
|
|
171
|
+
}
|
|
172
|
+
function normalizeNumberField(field, input) {
|
|
173
|
+
const value = normalizeNumber(input);
|
|
174
|
+
if (value === null || field.uiType !== "Rating") return value;
|
|
175
|
+
const min = field.property.min ?? 1;
|
|
176
|
+
const max = field.property.max ?? 5;
|
|
177
|
+
const score = Math.round(value);
|
|
178
|
+
return score < Math.max(min, 1) ? null : Math.min(score, max);
|
|
179
|
+
}
|
|
180
|
+
function normalizeUsers(input, multiple) {
|
|
181
|
+
const users = [];
|
|
182
|
+
for (const item of Array.isArray(input) ? input : [input]) {
|
|
183
|
+
if (typeof item !== "object" || item === null) continue;
|
|
184
|
+
const { id, name, avatarUrl } = item;
|
|
185
|
+
if (typeof id !== "string" || !id || users.some((user) => user.id === id)) continue;
|
|
186
|
+
users.push({
|
|
187
|
+
id,
|
|
188
|
+
...typeof name === "string" && name ? { name } : {},
|
|
189
|
+
...typeof avatarUrl === "string" && avatarUrl ? { avatarUrl } : {}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
const kept = multiple ? users : users.slice(0, 1);
|
|
193
|
+
return kept.length ? kept : null;
|
|
194
|
+
}
|
|
195
|
+
function normalizePhone(input) {
|
|
196
|
+
const raw = typeof input === "number" ? String(input) : Array.isArray(input) && isSegments(input) ? segmentsText(input) : input;
|
|
197
|
+
if (typeof raw !== "string") return null;
|
|
198
|
+
const text = raw.trim();
|
|
199
|
+
return /^\+?[\d\s\-()]{1,40}$/.test(text) && /\d/.test(text) ? text : null;
|
|
200
|
+
}
|
|
201
|
+
function withScheme(text) {
|
|
202
|
+
if (/^[a-z][a-z\d+\-.]*:\/\//i.test(text) || /^(mailto|tel):/i.test(text)) return text;
|
|
203
|
+
return /^[^\s/]+\.[^\s]+$/.test(text) ? `https://${text}` : null;
|
|
204
|
+
}
|
|
205
|
+
function normalizeUrl(input) {
|
|
206
|
+
const raw = Array.isArray(input) && isSegments(input) ? segmentsText(input) : input;
|
|
207
|
+
if (typeof raw === "string") {
|
|
208
|
+
const text2 = raw.trim();
|
|
209
|
+
const link2 = text2 ? withScheme(text2) : null;
|
|
210
|
+
return link2 ? { link: link2, text: text2 } : null;
|
|
211
|
+
}
|
|
212
|
+
if (typeof raw !== "object" || raw === null) return null;
|
|
213
|
+
const { link, text } = raw;
|
|
214
|
+
const resolved = typeof link === "string" ? withScheme(link.trim()) : null;
|
|
215
|
+
if (!resolved) return null;
|
|
216
|
+
const label = typeof text === "string" ? text.trim() : "";
|
|
217
|
+
return { link: resolved, text: label || resolved };
|
|
218
|
+
}
|
|
219
|
+
function normalizeAttachments(input) {
|
|
220
|
+
const files = [];
|
|
221
|
+
for (const item of Array.isArray(input) ? input : [input]) {
|
|
222
|
+
if (typeof item !== "object" || item === null) continue;
|
|
223
|
+
const { token, name, size, mimeType, url } = item;
|
|
224
|
+
if (typeof token !== "string" || !token || typeof name !== "string" || !name) continue;
|
|
225
|
+
files.push({
|
|
226
|
+
token,
|
|
227
|
+
name,
|
|
228
|
+
...typeof size === "number" && Number.isFinite(size) ? { size } : {},
|
|
229
|
+
...typeof mimeType === "string" && mimeType ? { mimeType } : {},
|
|
230
|
+
...typeof url === "string" && url ? { url } : {}
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
return files.length ? files : null;
|
|
234
|
+
}
|
|
235
|
+
var splitNames = (text) => text.split(/[,,\n]/).map((name) => name.trim()).filter(Boolean);
|
|
236
|
+
function resolveOptionIds(field, input) {
|
|
237
|
+
const options = field.property.options ?? [];
|
|
238
|
+
const byId = new Map(options.map((option) => [option.id, option]));
|
|
239
|
+
const byName = new Map(options.map((option) => [option.name, option]));
|
|
240
|
+
let candidates;
|
|
241
|
+
if (typeof input === "string") {
|
|
242
|
+
candidates = byId.has(input) || byName.has(input) ? [input] : splitNames(input);
|
|
243
|
+
} else if (Array.isArray(input)) {
|
|
244
|
+
candidates = input.length && isSegments(input) ? splitNames(segmentsText(input)) : input;
|
|
245
|
+
} else {
|
|
246
|
+
candidates = [];
|
|
247
|
+
}
|
|
248
|
+
const ids = [];
|
|
249
|
+
for (const candidate of candidates) {
|
|
250
|
+
if (typeof candidate !== "string") continue;
|
|
251
|
+
const option = byId.get(candidate) ?? byName.get(candidate.trim());
|
|
252
|
+
if (option && !ids.includes(option.id)) ids.push(option.id);
|
|
253
|
+
}
|
|
254
|
+
return ids;
|
|
255
|
+
}
|
|
256
|
+
var DATE_PATTERN = /^(\d{4})[-/.年](\d{1,2})[-/.月](\d{1,2})日?(?:[ T](\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?$/;
|
|
257
|
+
function normalizeDate(input, timeZone) {
|
|
258
|
+
if (typeof input === "number") return Number.isFinite(input) ? Math.round(input) : null;
|
|
259
|
+
if (input instanceof Date) {
|
|
260
|
+
const time = input.getTime();
|
|
261
|
+
return Number.isNaN(time) ? null : time;
|
|
262
|
+
}
|
|
263
|
+
if (Array.isArray(input) && isSegments(input)) return normalizeDate(segmentsText(input), timeZone);
|
|
264
|
+
if (typeof input !== "string") return null;
|
|
265
|
+
const text = input.trim();
|
|
266
|
+
if (!text) return null;
|
|
267
|
+
if (/^\d{12,13}$/.test(text)) return Number(text);
|
|
268
|
+
const match = DATE_PATTERN.exec(text);
|
|
269
|
+
if (match) {
|
|
270
|
+
const [year, month, day, hour = "0", minute = "0", second = "0"] = match.slice(1);
|
|
271
|
+
return zonedTimeToUtc(
|
|
272
|
+
[Number(year), Number(month), Number(day), Number(hour), Number(minute), Number(second)],
|
|
273
|
+
timeZone
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
const parsed = Date.parse(text);
|
|
277
|
+
return Number.isNaN(parsed) ? null : parsed;
|
|
278
|
+
}
|
|
279
|
+
function normalizeCheckbox(input) {
|
|
280
|
+
if (typeof input === "boolean") return input;
|
|
281
|
+
if (typeof input === "number") return input !== 0;
|
|
282
|
+
if (Array.isArray(input) && isSegments(input)) return normalizeCheckbox(segmentsText(input));
|
|
283
|
+
if (typeof input !== "string") return false;
|
|
284
|
+
return ["true", "1", "yes", "y", "是", "✓", "✔", "checked"].includes(input.trim().toLowerCase());
|
|
285
|
+
}
|
|
286
|
+
var partsFormatter = /* @__PURE__ */ new Map();
|
|
287
|
+
function wallTimeIn(utcMs, timeZone) {
|
|
288
|
+
let formatter = partsFormatter.get(timeZone);
|
|
289
|
+
if (!formatter) {
|
|
290
|
+
formatter = new Intl.DateTimeFormat("en-US", {
|
|
291
|
+
timeZone,
|
|
292
|
+
hourCycle: "h23",
|
|
293
|
+
year: "numeric",
|
|
294
|
+
month: "2-digit",
|
|
295
|
+
day: "2-digit",
|
|
296
|
+
hour: "2-digit",
|
|
297
|
+
minute: "2-digit",
|
|
298
|
+
second: "2-digit"
|
|
299
|
+
});
|
|
300
|
+
partsFormatter.set(timeZone, formatter);
|
|
301
|
+
}
|
|
302
|
+
const parts = formatter.formatToParts(new Date(utcMs));
|
|
303
|
+
const get = (type) => Number(parts.find((part) => part.type === type)?.value ?? 0);
|
|
304
|
+
return [get("year"), get("month"), get("day"), get("hour"), get("minute"), get("second")];
|
|
305
|
+
}
|
|
306
|
+
var wallToUtc = ([year, month, day, hour, minute, second]) => Date.UTC(year, month - 1, day, hour, minute, second);
|
|
307
|
+
function zonedTimeToUtc(wall, timeZone) {
|
|
308
|
+
const guess = wallToUtc(wall);
|
|
309
|
+
const offset = wallToUtc(wallTimeIn(guess, timeZone)) - guess;
|
|
310
|
+
return guess - offset;
|
|
311
|
+
}
|
|
312
|
+
var optionIndex = (field, id) => {
|
|
313
|
+
const index = (field.property.options ?? []).findIndex((option) => option.id === id);
|
|
314
|
+
return index === -1 ? Number.MAX_SAFE_INTEGER : index;
|
|
315
|
+
};
|
|
316
|
+
var collator;
|
|
317
|
+
var textCollator = () => {
|
|
318
|
+
collator ??= new Intl.Collator("zh-Hans-CN", { numeric: true, sensitivity: "base" });
|
|
319
|
+
return collator;
|
|
320
|
+
};
|
|
321
|
+
var userLabel = (user) => user.name || user.id;
|
|
322
|
+
function compareCellValues(field, a, b) {
|
|
323
|
+
switch (field.type) {
|
|
324
|
+
case FieldType.Number:
|
|
325
|
+
case FieldType.DateTime:
|
|
326
|
+
case FieldType.CreatedTime:
|
|
327
|
+
case FieldType.ModifiedTime:
|
|
328
|
+
case FieldType.AutoNumber:
|
|
329
|
+
return a - b;
|
|
330
|
+
case FieldType.Checkbox:
|
|
331
|
+
return Number(a === true) - Number(b === true);
|
|
332
|
+
case FieldType.SingleSelect:
|
|
333
|
+
return optionIndex(field, a) - optionIndex(field, b);
|
|
334
|
+
case FieldType.MultiSelect: {
|
|
335
|
+
const left = a.map((id) => optionIndex(field, id));
|
|
336
|
+
const right = b.map((id) => optionIndex(field, id));
|
|
337
|
+
for (let i = 0; i < Math.min(left.length, right.length); i++) {
|
|
338
|
+
if (left[i] !== right[i]) return left[i] - right[i];
|
|
339
|
+
}
|
|
340
|
+
return left.length - right.length;
|
|
341
|
+
}
|
|
342
|
+
case FieldType.User:
|
|
343
|
+
case FieldType.CreatedUser:
|
|
344
|
+
case FieldType.ModifiedUser: {
|
|
345
|
+
const left = a;
|
|
346
|
+
const right = b;
|
|
347
|
+
for (let i = 0; i < Math.min(left.length, right.length); i++) {
|
|
348
|
+
const result = textCollator().compare(userLabel(left[i]), userLabel(right[i]));
|
|
349
|
+
if (result !== 0) return result;
|
|
350
|
+
}
|
|
351
|
+
return left.length - right.length;
|
|
352
|
+
}
|
|
353
|
+
default:
|
|
354
|
+
return textCollator().compare(cellValueToText(field, a), cellValueToText(field, b));
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
var pad = (value, length = 2) => String(value).padStart(length, "0");
|
|
358
|
+
function startOfDayIn(time, timeZone = DEFAULT_TIME_ZONE) {
|
|
359
|
+
const [year, month, day] = wallTimeIn(time, timeZone);
|
|
360
|
+
return zonedTimeToUtc([year, month, day, 0, 0, 0], timeZone);
|
|
361
|
+
}
|
|
362
|
+
function addDaysIn(dayStart, days, timeZone = DEFAULT_TIME_ZONE) {
|
|
363
|
+
const [year, month, day] = wallTimeIn(dayStart, timeZone);
|
|
364
|
+
return zonedTimeToUtc([year, month, day + days, 0, 0, 0], timeZone);
|
|
365
|
+
}
|
|
366
|
+
function startOfMonthIn(time, offset = 0, timeZone = DEFAULT_TIME_ZONE) {
|
|
367
|
+
const [year, month] = wallTimeIn(time, timeZone);
|
|
368
|
+
return zonedTimeToUtc([year, month + offset, 1, 0, 0, 0], timeZone);
|
|
369
|
+
}
|
|
370
|
+
function weekdayIn(time, timeZone = DEFAULT_TIME_ZONE) {
|
|
371
|
+
const [year, month, day] = wallTimeIn(time, timeZone);
|
|
372
|
+
return (new Date(Date.UTC(year, month - 1, day)).getUTCDay() + 6) % 7;
|
|
373
|
+
}
|
|
374
|
+
function formatDate(time, formatter, timeZone) {
|
|
375
|
+
const [year, month, day, hour, minute, second] = wallTimeIn(time, timeZone);
|
|
376
|
+
return (formatter || "yyyy/MM/dd").replace("yyyy", String(year)).replace("MM", pad(month)).replace("dd", pad(day)).replace("HH", pad(hour)).replace("mm", pad(minute)).replace("ss", pad(second));
|
|
377
|
+
}
|
|
378
|
+
var decimalsOf = (format) => {
|
|
379
|
+
const percent2 = format.endsWith("%");
|
|
380
|
+
return format.includes(".") ? format.length - format.indexOf(".") - 1 - (percent2 ? 1 : 0) : 0;
|
|
381
|
+
};
|
|
382
|
+
function formatNumber(value, formatter, grouping = false) {
|
|
383
|
+
const format = formatter || "0";
|
|
384
|
+
const percent2 = format.endsWith("%");
|
|
385
|
+
const decimals = decimalsOf(format);
|
|
386
|
+
const scaled = percent2 ? value * 100 : value;
|
|
387
|
+
const text = grouping || format.includes(",") ? scaled.toLocaleString("en-US", {
|
|
388
|
+
minimumFractionDigits: decimals,
|
|
389
|
+
maximumFractionDigits: decimals
|
|
390
|
+
}) : scaled.toFixed(decimals);
|
|
391
|
+
return percent2 ? `${text}%` : text;
|
|
392
|
+
}
|
|
393
|
+
var CURRENCY_SYMBOLS = {
|
|
394
|
+
CNY: "¥",
|
|
395
|
+
USD: "$",
|
|
396
|
+
EUR: "€",
|
|
397
|
+
GBP: "£",
|
|
398
|
+
JPY: "JP¥",
|
|
399
|
+
HKD: "HK$"
|
|
400
|
+
};
|
|
401
|
+
function formatNumberField(field, value) {
|
|
402
|
+
if (field.uiType === "Currency") {
|
|
403
|
+
const symbol = CURRENCY_SYMBOLS[field.property.currencyCode ?? "CNY"] ?? "";
|
|
404
|
+
const sign = value < 0 ? "-" : "";
|
|
405
|
+
return `${sign}${symbol}${formatNumber(Math.abs(value), field.property.formatter, true)}`;
|
|
406
|
+
}
|
|
407
|
+
if (field.uiType === "Rating") return String(value);
|
|
408
|
+
return formatNumber(value, field.property.formatter);
|
|
409
|
+
}
|
|
410
|
+
function cellValueToText(field, value, timeZone = DEFAULT_TIME_ZONE) {
|
|
411
|
+
if (isEmptyCellValue(value)) return "";
|
|
412
|
+
switch (field.type) {
|
|
413
|
+
case FieldType.Text:
|
|
414
|
+
return Array.isArray(value) ? segmentsText(value) : String(value);
|
|
415
|
+
case FieldType.Number:
|
|
416
|
+
return typeof value === "number" ? formatNumberField(field, value) : "";
|
|
417
|
+
case FieldType.SingleSelect:
|
|
418
|
+
return field.property.options?.find((option) => option.id === value)?.name ?? "";
|
|
419
|
+
case FieldType.MultiSelect: {
|
|
420
|
+
const ids = Array.isArray(value) ? value : [];
|
|
421
|
+
const options = field.property.options ?? [];
|
|
422
|
+
return ids.map((id) => options.find((option) => option.id === id)?.name).filter(Boolean).join(",");
|
|
423
|
+
}
|
|
424
|
+
case FieldType.DateTime:
|
|
425
|
+
case FieldType.CreatedTime:
|
|
426
|
+
case FieldType.ModifiedTime:
|
|
427
|
+
return typeof value === "number" ? formatDate(value, field.property.formatter, timeZone) : "";
|
|
428
|
+
case FieldType.Checkbox:
|
|
429
|
+
return value === true ? "true" : "";
|
|
430
|
+
case FieldType.User:
|
|
431
|
+
case FieldType.CreatedUser:
|
|
432
|
+
case FieldType.ModifiedUser:
|
|
433
|
+
return Array.isArray(value) ? value.map(userLabel).join(",") : "";
|
|
434
|
+
case FieldType.Phone:
|
|
435
|
+
return String(value);
|
|
436
|
+
case FieldType.Url: {
|
|
437
|
+
const { link, text } = value;
|
|
438
|
+
return text || link || "";
|
|
439
|
+
}
|
|
440
|
+
case FieldType.Attachment:
|
|
441
|
+
return Array.isArray(value) ? value.map((file) => file.name).join(",") : "";
|
|
442
|
+
case FieldType.AutoNumber:
|
|
443
|
+
return typeof value === "number" ? String(value) : "";
|
|
444
|
+
default:
|
|
445
|
+
return "";
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
function toWallTime(time, timeZone = DEFAULT_TIME_ZONE) {
|
|
449
|
+
return wallTimeIn(time, timeZone);
|
|
450
|
+
}
|
|
451
|
+
function fromWallTime(wall, timeZone = DEFAULT_TIME_ZONE) {
|
|
452
|
+
return zonedTimeToUtc(wall, timeZone);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// src/base-model/ids.ts
|
|
456
|
+
var ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
457
|
+
function newBaseId(prefix, length = 10) {
|
|
458
|
+
const bytes = crypto.getRandomValues(new Uint8Array(length));
|
|
459
|
+
let id = prefix;
|
|
460
|
+
for (const byte of bytes) id += ALPHABET[byte % ALPHABET.length];
|
|
461
|
+
return id;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// src/base-model/rank.ts
|
|
465
|
+
var DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
466
|
+
var INTEGER_ZERO = "a0";
|
|
467
|
+
var SMALLEST_INTEGER = `A${"0".repeat(26)}`;
|
|
468
|
+
var RankError = class extends Error {
|
|
469
|
+
};
|
|
470
|
+
function midpoint(a, b) {
|
|
471
|
+
if (b !== null && a >= b) throw new RankError(`${a} >= ${b}`);
|
|
472
|
+
if (a.endsWith("0") || b?.endsWith("0")) throw new RankError("小数部分不能以 0 结尾");
|
|
473
|
+
if (b) {
|
|
474
|
+
let n = 0;
|
|
475
|
+
while ((a[n] || "0") === b[n]) n++;
|
|
476
|
+
if (n > 0) return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));
|
|
477
|
+
}
|
|
478
|
+
const digitA = a ? DIGITS.indexOf(a[0]) : 0;
|
|
479
|
+
const digitB = b !== null ? DIGITS.indexOf(b[0]) : DIGITS.length;
|
|
480
|
+
if (digitB - digitA > 1) return DIGITS[Math.round(0.5 * (digitA + digitB))];
|
|
481
|
+
if (b && b.length > 1) return b.slice(0, 1);
|
|
482
|
+
return DIGITS[digitA] + midpoint(a.slice(1), null);
|
|
483
|
+
}
|
|
484
|
+
function integerLength(head) {
|
|
485
|
+
if (head >= "a" && head <= "z") return head.charCodeAt(0) - 97 + 2;
|
|
486
|
+
if (head >= "A" && head <= "Z") return 90 - head.charCodeAt(0) + 2;
|
|
487
|
+
throw new RankError(`顺序键首字符不合法:${head}`);
|
|
488
|
+
}
|
|
489
|
+
function integerPart(key) {
|
|
490
|
+
const length = integerLength(key[0]);
|
|
491
|
+
if (length > key.length) throw new RankError(`顺序键不合法:${key}`);
|
|
492
|
+
return key.slice(0, length);
|
|
493
|
+
}
|
|
494
|
+
function validate(key) {
|
|
495
|
+
if (key === SMALLEST_INTEGER) throw new RankError(`顺序键不合法:${key}`);
|
|
496
|
+
const integer = integerPart(key);
|
|
497
|
+
if (key.slice(integer.length).endsWith("0")) throw new RankError(`顺序键不合法:${key}`);
|
|
498
|
+
}
|
|
499
|
+
function incrementInteger(x) {
|
|
500
|
+
const [head, ...digits] = x.split("");
|
|
501
|
+
let carry = true;
|
|
502
|
+
for (let i = digits.length - 1; carry && i >= 0; i--) {
|
|
503
|
+
const d = DIGITS.indexOf(digits[i]) + 1;
|
|
504
|
+
if (d === DIGITS.length) {
|
|
505
|
+
digits[i] = "0";
|
|
506
|
+
} else {
|
|
507
|
+
digits[i] = DIGITS[d];
|
|
508
|
+
carry = false;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
if (!carry) return head + digits.join("");
|
|
512
|
+
if (head === "Z") return INTEGER_ZERO;
|
|
513
|
+
if (head === "z") return null;
|
|
514
|
+
const next = String.fromCharCode(head.charCodeAt(0) + 1);
|
|
515
|
+
if (next > "a") digits.push("0");
|
|
516
|
+
else digits.pop();
|
|
517
|
+
return next + digits.join("");
|
|
518
|
+
}
|
|
519
|
+
function decrementInteger(x) {
|
|
520
|
+
const [head, ...digits] = x.split("");
|
|
521
|
+
let borrow = true;
|
|
522
|
+
for (let i = digits.length - 1; borrow && i >= 0; i--) {
|
|
523
|
+
const d = DIGITS.indexOf(digits[i]) - 1;
|
|
524
|
+
if (d === -1) {
|
|
525
|
+
digits[i] = DIGITS[DIGITS.length - 1];
|
|
526
|
+
} else {
|
|
527
|
+
digits[i] = DIGITS[d];
|
|
528
|
+
borrow = false;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
if (!borrow) return head + digits.join("");
|
|
532
|
+
if (head === "a") return `Z${DIGITS[DIGITS.length - 1]}`;
|
|
533
|
+
if (head === "A") return null;
|
|
534
|
+
const next = String.fromCharCode(head.charCodeAt(0) - 1);
|
|
535
|
+
if (next < "Z") digits.push(DIGITS[DIGITS.length - 1]);
|
|
536
|
+
else digits.pop();
|
|
537
|
+
return next + digits.join("");
|
|
538
|
+
}
|
|
539
|
+
function rankBetween(a, b) {
|
|
540
|
+
if (a !== null) validate(a);
|
|
541
|
+
if (b !== null) validate(b);
|
|
542
|
+
if (a !== null && b !== null && a >= b) throw new RankError(`${a} >= ${b}`);
|
|
543
|
+
if (a === null) {
|
|
544
|
+
if (b === null) return INTEGER_ZERO;
|
|
545
|
+
const ib2 = integerPart(b);
|
|
546
|
+
const fb2 = b.slice(ib2.length);
|
|
547
|
+
if (ib2 === SMALLEST_INTEGER) return ib2 + midpoint("", fb2);
|
|
548
|
+
if (ib2 < b) return ib2;
|
|
549
|
+
const decremented = decrementInteger(ib2);
|
|
550
|
+
if (decremented === null) throw new RankError("顺序键已到最小值");
|
|
551
|
+
return decremented;
|
|
552
|
+
}
|
|
553
|
+
if (b === null) {
|
|
554
|
+
const ia2 = integerPart(a);
|
|
555
|
+
const incremented2 = incrementInteger(ia2);
|
|
556
|
+
return incremented2 === null ? ia2 + midpoint(a.slice(ia2.length), null) : incremented2;
|
|
557
|
+
}
|
|
558
|
+
const ia = integerPart(a);
|
|
559
|
+
const fa = a.slice(ia.length);
|
|
560
|
+
const ib = integerPart(b);
|
|
561
|
+
const fb = b.slice(ib.length);
|
|
562
|
+
if (ia === ib) return ia + midpoint(fa, fb);
|
|
563
|
+
const incremented = incrementInteger(ia);
|
|
564
|
+
if (incremented === null) throw new RankError("顺序键已到最大值");
|
|
565
|
+
return incremented < b ? incremented : ia + midpoint(fa, null);
|
|
566
|
+
}
|
|
567
|
+
function ranksBetween(a, b, n) {
|
|
568
|
+
if (n <= 0) return [];
|
|
569
|
+
if (n === 1) return [rankBetween(a, b)];
|
|
570
|
+
if (b === null) {
|
|
571
|
+
let current = rankBetween(a, b);
|
|
572
|
+
const result = [current];
|
|
573
|
+
for (let i = 0; i < n - 1; i++) {
|
|
574
|
+
current = rankBetween(current, b);
|
|
575
|
+
result.push(current);
|
|
576
|
+
}
|
|
577
|
+
return result;
|
|
578
|
+
}
|
|
579
|
+
if (a === null) {
|
|
580
|
+
let current = rankBetween(a, b);
|
|
581
|
+
const result = [current];
|
|
582
|
+
for (let i = 0; i < n - 1; i++) {
|
|
583
|
+
current = rankBetween(a, current);
|
|
584
|
+
result.push(current);
|
|
585
|
+
}
|
|
586
|
+
return result.reverse();
|
|
587
|
+
}
|
|
588
|
+
const half = Math.floor(n / 2);
|
|
589
|
+
const middle = rankBetween(a, b);
|
|
590
|
+
return [...ranksBetween(a, middle, half), middle, ...ranksBetween(middle, b, n - half - 1)];
|
|
591
|
+
}
|
|
592
|
+
function compareRank(rankA, idA, rankB, idB) {
|
|
593
|
+
if (rankA !== rankB) {
|
|
594
|
+
if (rankA === void 0) return 1;
|
|
595
|
+
if (rankB === void 0) return -1;
|
|
596
|
+
return rankA < rankB ? -1 : 1;
|
|
597
|
+
}
|
|
598
|
+
return idA < idB ? -1 : idA > idB ? 1 : 0;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// src/base-model/schema.ts
|
|
602
|
+
var SCHEMA_VERSION = 1;
|
|
603
|
+
var tableKeys = (tableId) => ({
|
|
604
|
+
fields: `fields:${tableId}`,
|
|
605
|
+
views: `views:${tableId}`,
|
|
606
|
+
viewOrder: `viewOrder:${tableId}`,
|
|
607
|
+
records: `records:${tableId}`,
|
|
608
|
+
ranks: `ranks:${tableId}`
|
|
609
|
+
});
|
|
610
|
+
var baseRoot = (doc) => doc.getMap("base");
|
|
611
|
+
var tableOrderArray = (doc) => doc.getArray("tableOrder");
|
|
612
|
+
var tablesMap = (doc) => doc.getMap("tables");
|
|
613
|
+
var fieldsMap = (doc, tableId) => doc.getMap(tableKeys(tableId).fields);
|
|
614
|
+
var viewsMap = (doc, tableId) => doc.getMap(tableKeys(tableId).views);
|
|
615
|
+
var viewOrderArray = (doc, tableId) => doc.getArray(tableKeys(tableId).viewOrder);
|
|
616
|
+
var recordsMap = (doc, tableId) => doc.getMap(tableKeys(tableId).records);
|
|
617
|
+
var ranksMap = (doc, tableId) => doc.getMap(tableKeys(tableId).ranks);
|
|
618
|
+
var tableTypes = (doc, tableId) => [
|
|
619
|
+
fieldsMap(doc, tableId),
|
|
620
|
+
viewsMap(doc, tableId),
|
|
621
|
+
viewOrderArray(doc, tableId),
|
|
622
|
+
recordsMap(doc, tableId),
|
|
623
|
+
ranksMap(doc, tableId)
|
|
624
|
+
];
|
|
625
|
+
var isBaseInitialized = (doc) => baseRoot(doc).get("schemaVersion") !== void 0;
|
|
626
|
+
|
|
627
|
+
// src/base-model/read.ts
|
|
628
|
+
var unique = (ids) => [...new Set(ids)];
|
|
629
|
+
function readTables(doc) {
|
|
630
|
+
const tables = tablesMap(doc);
|
|
631
|
+
const ordered = unique([...tableOrderArray(doc).toArray(), ...[...tables.keys()].sort()]);
|
|
632
|
+
return ordered.flatMap((id) => {
|
|
633
|
+
const table = tables.get(id);
|
|
634
|
+
if (!table) return [];
|
|
635
|
+
return [
|
|
636
|
+
{
|
|
637
|
+
id,
|
|
638
|
+
name: String(table.get("name") ?? ""),
|
|
639
|
+
primaryFieldId: String(table.get("primaryFieldId") ?? "")
|
|
640
|
+
}
|
|
641
|
+
];
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
function readTable(doc, tableId) {
|
|
645
|
+
return readTables(doc).find((table) => table.id === tableId) ?? null;
|
|
646
|
+
}
|
|
647
|
+
function readFieldMap(id, map) {
|
|
648
|
+
const type = map.get("type");
|
|
649
|
+
if (!isFieldType(type)) return null;
|
|
650
|
+
const description = map.get("description");
|
|
651
|
+
const uiType = map.get("uiType");
|
|
652
|
+
return {
|
|
653
|
+
id,
|
|
654
|
+
name: String(map.get("name") ?? ""),
|
|
655
|
+
type,
|
|
656
|
+
...type === FieldType.Number && isNumberUiType(uiType) && uiType !== "Number" ? { uiType } : {},
|
|
657
|
+
property: map.get("property") ?? {},
|
|
658
|
+
...typeof description === "string" && description ? { description } : {}
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
function readFields(doc, tableId) {
|
|
662
|
+
const map = fieldsMap(doc, tableId);
|
|
663
|
+
const primaryFieldId = tablesMap(doc).get(tableId)?.get("primaryFieldId");
|
|
664
|
+
const firstView = viewsMap(doc, tableId).get(viewOrderArray(doc, tableId).get(0) ?? "");
|
|
665
|
+
const viewOrder = firstView?.get("fields")?.toArray() ?? [];
|
|
666
|
+
const ordered = unique([
|
|
667
|
+
...typeof primaryFieldId === "string" ? [primaryFieldId] : [],
|
|
668
|
+
...viewOrder,
|
|
669
|
+
...[...map.keys()].sort()
|
|
670
|
+
]);
|
|
671
|
+
return ordered.flatMap((id) => {
|
|
672
|
+
const field = map.get(id);
|
|
673
|
+
const parsed = field ? readFieldMap(id, field) : null;
|
|
674
|
+
return parsed ? [parsed] : [];
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
function readViewMap(doc, tableId, viewId, view) {
|
|
678
|
+
const fields = fieldsMap(doc, tableId);
|
|
679
|
+
const primaryFieldId = tablesMap(doc).get(tableId)?.get("primaryFieldId");
|
|
680
|
+
const order = view.get("fields")?.toArray() ?? [];
|
|
681
|
+
const fieldIds = unique([
|
|
682
|
+
...typeof primaryFieldId === "string" ? [primaryFieldId] : [],
|
|
683
|
+
...order,
|
|
684
|
+
...[...fields.keys()].sort()
|
|
685
|
+
]).filter((id) => fields.has(id));
|
|
686
|
+
const colInfos = view.get("colInfos")?.toJSON() ?? {};
|
|
687
|
+
const level = Number(view.get("rowHeightLevel"));
|
|
688
|
+
return {
|
|
689
|
+
id: viewId,
|
|
690
|
+
name: String(view.get("name") ?? ""),
|
|
691
|
+
type: "grid",
|
|
692
|
+
fieldIds,
|
|
693
|
+
colInfos: Object.fromEntries(
|
|
694
|
+
Object.entries(colInfos).filter(([id]) => fields.has(id))
|
|
695
|
+
),
|
|
696
|
+
frozenColCount: Number(view.get("frozenColCount") ?? 1),
|
|
697
|
+
rowHeightLevel: level >= 1 && level <= 4 ? level : 1,
|
|
698
|
+
filter: view.get("filter") ?? null,
|
|
699
|
+
sort: view.get("sort") ?? [],
|
|
700
|
+
group: view.get("group") ?? []
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
function readViews(doc, tableId) {
|
|
704
|
+
const views = viewsMap(doc, tableId);
|
|
705
|
+
const ordered = unique([...viewOrderArray(doc, tableId).toArray(), ...[...views.keys()].sort()]);
|
|
706
|
+
return ordered.flatMap((id) => {
|
|
707
|
+
const view = views.get(id);
|
|
708
|
+
return view ? [readViewMap(doc, tableId, id, view)] : [];
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
function readView(doc, tableId, viewId) {
|
|
712
|
+
const view = viewsMap(doc, tableId).get(viewId);
|
|
713
|
+
return view ? readViewMap(doc, tableId, viewId, view) : null;
|
|
714
|
+
}
|
|
715
|
+
function orderedRecordIds(doc, tableId) {
|
|
716
|
+
const ranks = ranksMap(doc, tableId);
|
|
717
|
+
return [...recordsMap(doc, tableId).keys()].sort(
|
|
718
|
+
(a, b) => compareRank(ranks.get(a), a, ranks.get(b), b)
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
function readCellValue(doc, tableId, recordId, fieldId) {
|
|
722
|
+
return recordsMap(doc, tableId).get(recordId)?.get(fieldId);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// src/base-model/ops.ts
|
|
726
|
+
var MAX_RECORDS_PER_TABLE = 1e4;
|
|
727
|
+
var BaseModelError = class extends Error {
|
|
728
|
+
};
|
|
729
|
+
var DEFAULT_TABLE_FIELDS = [
|
|
730
|
+
{ name: "文本", type: FieldType.Text },
|
|
731
|
+
{ name: "单选", type: FieldType.SingleSelect },
|
|
732
|
+
{ name: "日期", type: FieldType.DateTime },
|
|
733
|
+
{ name: "附件", type: FieldType.Attachment }
|
|
734
|
+
];
|
|
735
|
+
var DEFAULT_RECORD_COUNT = 10;
|
|
736
|
+
function uniqueName(names, base) {
|
|
737
|
+
const used = new Set(names);
|
|
738
|
+
if (!used.has(base)) return base;
|
|
739
|
+
for (let i = 2; ; i++) if (!used.has(`${base} ${i}`)) return `${base} ${i}`;
|
|
740
|
+
}
|
|
741
|
+
function copyName(names, name) {
|
|
742
|
+
return uniqueName(names, `${name} 副本`);
|
|
743
|
+
}
|
|
744
|
+
var actors = /* @__PURE__ */ new WeakMap();
|
|
745
|
+
function setBaseActor(doc, actor) {
|
|
746
|
+
if (actor) actors.set(doc, { ...actor });
|
|
747
|
+
else actors.delete(doc);
|
|
748
|
+
}
|
|
749
|
+
function inTransaction(doc, origin, fn) {
|
|
750
|
+
let result;
|
|
751
|
+
doc.transact(() => {
|
|
752
|
+
result = fn();
|
|
753
|
+
}, origin);
|
|
754
|
+
return result;
|
|
755
|
+
}
|
|
756
|
+
var OPTION_COLORS = 55;
|
|
757
|
+
function normalizeProperty(type, property, uiType) {
|
|
758
|
+
const { options: rawOptions, ...rest } = {
|
|
759
|
+
...defaultFieldProperty(type, uiType),
|
|
760
|
+
...property
|
|
761
|
+
};
|
|
762
|
+
if (type !== FieldType.SingleSelect && type !== FieldType.MultiSelect) return rest;
|
|
763
|
+
const seen = /* @__PURE__ */ new Set();
|
|
764
|
+
const options = (rawOptions ?? []).flatMap((option, index) => {
|
|
765
|
+
const name = String(option.name ?? "").trim();
|
|
766
|
+
if (!name || seen.has(name)) return [];
|
|
767
|
+
seen.add(name);
|
|
768
|
+
return [
|
|
769
|
+
{
|
|
770
|
+
id: option.id || newBaseId("opt"),
|
|
771
|
+
name,
|
|
772
|
+
color: Number.isInteger(option.color) ? option.color : index % OPTION_COLORS
|
|
773
|
+
}
|
|
774
|
+
];
|
|
775
|
+
});
|
|
776
|
+
return { ...rest, options };
|
|
777
|
+
}
|
|
778
|
+
function writeField(doc, tableId, input) {
|
|
779
|
+
if (!isFieldType(input.type)) throw new BaseModelError(`不支持的字段类型:${input.type}`);
|
|
780
|
+
const name = input.name.trim();
|
|
781
|
+
if (!name) throw new BaseModelError("字段名不能为空");
|
|
782
|
+
const id = newBaseId("fld");
|
|
783
|
+
const field = new Y.Map();
|
|
784
|
+
fieldsMap(doc, tableId).set(id, field);
|
|
785
|
+
field.set("name", name);
|
|
786
|
+
field.set("type", input.type);
|
|
787
|
+
const uiType = storedUiType(input.type, input.uiType);
|
|
788
|
+
if (uiType) field.set("uiType", uiType);
|
|
789
|
+
field.set("property", normalizeProperty(input.type, input.property, uiType));
|
|
790
|
+
if (input.description) field.set("description", input.description);
|
|
791
|
+
return id;
|
|
792
|
+
}
|
|
793
|
+
var storedUiType = (type, uiType) => type === FieldType.Number && uiType && uiType !== "Number" ? uiType : void 0;
|
|
794
|
+
function writeView(doc, tableId, name, fieldIds, index) {
|
|
795
|
+
const id = newBaseId("vew");
|
|
796
|
+
const view = new Y.Map();
|
|
797
|
+
viewsMap(doc, tableId).set(id, view);
|
|
798
|
+
view.set("name", name);
|
|
799
|
+
view.set("type", "grid");
|
|
800
|
+
const fields = new Y.Array();
|
|
801
|
+
view.set("fields", fields);
|
|
802
|
+
fields.push(fieldIds);
|
|
803
|
+
view.set("colInfos", new Y.Map());
|
|
804
|
+
view.set("frozenColCount", 1);
|
|
805
|
+
view.set("rowHeightLevel", 1);
|
|
806
|
+
const order = viewOrderArray(doc, tableId);
|
|
807
|
+
if (index === void 0) order.push([id]);
|
|
808
|
+
else order.insert(Math.max(0, Math.min(index, order.length)), [id]);
|
|
809
|
+
return id;
|
|
810
|
+
}
|
|
811
|
+
function writeTable(doc, input) {
|
|
812
|
+
const name = input.name.trim();
|
|
813
|
+
if (!name) throw new BaseModelError("数据表名不能为空");
|
|
814
|
+
const tableId = newBaseId("tbl");
|
|
815
|
+
const useDefault = !input.fields?.length;
|
|
816
|
+
const specs = useDefault ? DEFAULT_TABLE_FIELDS : input.fields;
|
|
817
|
+
const fieldIds = specs.map((spec) => writeField(doc, tableId, spec));
|
|
818
|
+
const table = new Y.Map();
|
|
819
|
+
tablesMap(doc).set(tableId, table);
|
|
820
|
+
table.set("name", name);
|
|
821
|
+
table.set("primaryFieldId", fieldIds[0]);
|
|
822
|
+
tableOrderArray(doc).push([tableId]);
|
|
823
|
+
const viewId = writeView(doc, tableId, input.viewName ?? "表格", fieldIds);
|
|
824
|
+
const count = input.recordCount ?? (useDefault ? DEFAULT_RECORD_COUNT : 0);
|
|
825
|
+
if (count > 0)
|
|
826
|
+
writeRecords(
|
|
827
|
+
doc,
|
|
828
|
+
tableId,
|
|
829
|
+
Array.from({ length: count }, () => ({})),
|
|
830
|
+
0
|
|
831
|
+
);
|
|
832
|
+
return { tableId, viewId };
|
|
833
|
+
}
|
|
834
|
+
function initBase(doc, input = { name: "数据表" }, origin) {
|
|
835
|
+
if (isBaseInitialized(doc)) return null;
|
|
836
|
+
return inTransaction(doc, origin, () => {
|
|
837
|
+
baseRoot(doc).set("schemaVersion", SCHEMA_VERSION);
|
|
838
|
+
return writeTable(doc, input);
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
function addTable(doc, input, origin) {
|
|
842
|
+
return inTransaction(doc, origin, () => writeTable(doc, input));
|
|
843
|
+
}
|
|
844
|
+
function renameTable(doc, tableId, name, origin) {
|
|
845
|
+
const table = tablesMap(doc).get(tableId);
|
|
846
|
+
if (!table) return;
|
|
847
|
+
const trimmed = name.trim();
|
|
848
|
+
if (!trimmed) throw new BaseModelError("数据表名不能为空");
|
|
849
|
+
inTransaction(doc, origin, () => table.set("name", trimmed));
|
|
850
|
+
}
|
|
851
|
+
function moveTable(doc, tableId, index, origin) {
|
|
852
|
+
const order = tableOrderArray(doc);
|
|
853
|
+
const current = order.toArray().indexOf(tableId);
|
|
854
|
+
if (current === -1) return;
|
|
855
|
+
inTransaction(doc, origin, () => {
|
|
856
|
+
order.delete(current, 1);
|
|
857
|
+
order.insert(Math.max(0, Math.min(index, order.length)), [tableId]);
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
function duplicateTable(doc, tableId, origin) {
|
|
861
|
+
const tables = tablesMap(doc);
|
|
862
|
+
const source = tables.get(tableId);
|
|
863
|
+
if (!source) throw new BaseModelError(`数据表不存在:${tableId}`);
|
|
864
|
+
const names = [...tables.values()].map((table) => String(table.get("name") ?? ""));
|
|
865
|
+
const fields = readFields(doc, tableId);
|
|
866
|
+
const views = readViews(doc, tableId);
|
|
867
|
+
const order = orderedRecordIds(doc, tableId);
|
|
868
|
+
return inTransaction(doc, origin, () => {
|
|
869
|
+
const newTableId = newBaseId("tbl");
|
|
870
|
+
const fieldIds = new Map(fields.map((field) => [field.id, newBaseId("fld")]));
|
|
871
|
+
const mapId = (id) => fieldIds.get(id) ?? id;
|
|
872
|
+
for (const field of fields) {
|
|
873
|
+
const map = new Y.Map();
|
|
874
|
+
fieldsMap(doc, newTableId).set(mapId(field.id), map);
|
|
875
|
+
map.set("name", field.name);
|
|
876
|
+
map.set("type", field.type);
|
|
877
|
+
if (field.uiType) map.set("uiType", field.uiType);
|
|
878
|
+
map.set("property", structuredClone(field.property));
|
|
879
|
+
if (field.description) map.set("description", field.description);
|
|
880
|
+
}
|
|
881
|
+
const table = new Y.Map();
|
|
882
|
+
tables.set(newTableId, table);
|
|
883
|
+
table.set("name", copyName(names, String(source.get("name") ?? "")));
|
|
884
|
+
table.set("primaryFieldId", mapId(String(source.get("primaryFieldId") ?? "")));
|
|
885
|
+
const tableOrder = tableOrderArray(doc);
|
|
886
|
+
const at = tableOrder.toArray().indexOf(tableId);
|
|
887
|
+
tableOrder.insert(at === -1 ? tableOrder.length : at + 1, [newTableId]);
|
|
888
|
+
const remapRules = (rules) => rules.map((rule) => ({ ...rule, fieldId: mapId(rule.fieldId) }));
|
|
889
|
+
let firstViewId = "";
|
|
890
|
+
for (const view of views) {
|
|
891
|
+
const id = writeView(doc, newTableId, view.name, view.fieldIds.map(mapId));
|
|
892
|
+
firstViewId ||= id;
|
|
893
|
+
const map = viewsMap(doc, newTableId).get(id);
|
|
894
|
+
const colInfos = map.get("colInfos");
|
|
895
|
+
for (const [fieldId, info] of Object.entries(view.colInfos))
|
|
896
|
+
colInfos.set(mapId(fieldId), info);
|
|
897
|
+
map.set("frozenColCount", view.frozenColCount);
|
|
898
|
+
map.set("rowHeightLevel", view.rowHeightLevel);
|
|
899
|
+
if (view.filter) {
|
|
900
|
+
map.set("filter", { ...view.filter, conditions: remapRules(view.filter.conditions) });
|
|
901
|
+
}
|
|
902
|
+
if (view.sort.length) map.set("sort", remapRules(view.sort));
|
|
903
|
+
if (view.group.length) map.set("group", remapRules(view.group));
|
|
904
|
+
}
|
|
905
|
+
const records = recordsMap(doc, tableId);
|
|
906
|
+
const ranks = ranksMap(doc, tableId);
|
|
907
|
+
for (const recordId of order) {
|
|
908
|
+
const json = records.get(recordId)?.toJSON() ?? {};
|
|
909
|
+
const record = new Y.Map();
|
|
910
|
+
const id = newBaseId("rec");
|
|
911
|
+
recordsMap(doc, newTableId).set(id, record);
|
|
912
|
+
for (const [key, value] of Object.entries(json)) record.set(mapId(key), value);
|
|
913
|
+
const rank = ranks.get(recordId);
|
|
914
|
+
if (rank) ranksMap(doc, newTableId).set(id, rank);
|
|
915
|
+
}
|
|
916
|
+
return { tableId: newTableId, viewId: firstViewId };
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
function deleteTable(doc, tableId, origin) {
|
|
920
|
+
inTransaction(doc, origin, () => {
|
|
921
|
+
for (const type of tableTypes(doc, tableId)) {
|
|
922
|
+
if (type instanceof Y.Map) type.clear();
|
|
923
|
+
else if (type instanceof Y.Array) type.delete(0, type.length);
|
|
924
|
+
}
|
|
925
|
+
tablesMap(doc).delete(tableId);
|
|
926
|
+
const order = tableOrderArray(doc);
|
|
927
|
+
for (let i = order.length - 1; i >= 0; i--) if (order.get(i) === tableId) order.delete(i, 1);
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
function placeField(doc, tableId, fieldId, position) {
|
|
931
|
+
for (const [viewId, view] of viewsMap(doc, tableId).entries()) {
|
|
932
|
+
const order = view.get("fields");
|
|
933
|
+
if (!order) continue;
|
|
934
|
+
if (position && viewId === position.viewId) {
|
|
935
|
+
order.insert(Math.max(1, Math.min(position.index, order.length)), [fieldId]);
|
|
936
|
+
} else {
|
|
937
|
+
order.push([fieldId]);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
function addField(doc, tableId, input, origin, position) {
|
|
942
|
+
if (!tablesMap(doc).has(tableId)) throw new BaseModelError(`数据表不存在:${tableId}`);
|
|
943
|
+
return inTransaction(doc, origin, () => {
|
|
944
|
+
const id = writeField(doc, tableId, input);
|
|
945
|
+
placeField(doc, tableId, id, position);
|
|
946
|
+
if (input.type === FieldType.AutoNumber) fillAutoNumbers(doc, tableId);
|
|
947
|
+
return id;
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
function duplicateField(doc, tableId, fieldId, options = {}, origin) {
|
|
951
|
+
const fields = readFields(doc, tableId);
|
|
952
|
+
const field = fields.find((item) => item.id === fieldId);
|
|
953
|
+
if (!field) throw new BaseModelError(`字段不存在:${fieldId}`);
|
|
954
|
+
const view = options.viewId ? readView(doc, tableId, options.viewId) : null;
|
|
955
|
+
return inTransaction(doc, origin, () => {
|
|
956
|
+
const id = writeField(doc, tableId, {
|
|
957
|
+
name: copyName(
|
|
958
|
+
fields.map((item) => item.name),
|
|
959
|
+
field.name
|
|
960
|
+
),
|
|
961
|
+
type: field.type,
|
|
962
|
+
uiType: field.uiType,
|
|
963
|
+
property: field.property,
|
|
964
|
+
description: field.description
|
|
965
|
+
});
|
|
966
|
+
placeField(
|
|
967
|
+
doc,
|
|
968
|
+
tableId,
|
|
969
|
+
id,
|
|
970
|
+
view ? { viewId: view.id, index: view.fieldIds.indexOf(fieldId) + 1 } : void 0
|
|
971
|
+
);
|
|
972
|
+
if (!isComputedFieldType(field.type)) {
|
|
973
|
+
for (const record of recordsMap(doc, tableId).values()) {
|
|
974
|
+
const value = record.get(fieldId);
|
|
975
|
+
if (value !== void 0) record.set(id, structuredClone(value));
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
return id;
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
function valueFamily(type) {
|
|
982
|
+
switch (type) {
|
|
983
|
+
case FieldType.Number:
|
|
984
|
+
case FieldType.AutoNumber:
|
|
985
|
+
return "number";
|
|
986
|
+
case FieldType.DateTime:
|
|
987
|
+
case FieldType.CreatedTime:
|
|
988
|
+
case FieldType.ModifiedTime:
|
|
989
|
+
return "date";
|
|
990
|
+
case FieldType.User:
|
|
991
|
+
case FieldType.CreatedUser:
|
|
992
|
+
case FieldType.ModifiedUser:
|
|
993
|
+
return "user";
|
|
994
|
+
case FieldType.SingleSelect:
|
|
995
|
+
case FieldType.MultiSelect:
|
|
996
|
+
return "select";
|
|
997
|
+
default:
|
|
998
|
+
return String(type);
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
function convertValue(from, to, value) {
|
|
1002
|
+
if (isEmptyCellValue(value)) return null;
|
|
1003
|
+
if (valueFamily(from.type) !== valueFamily(to.type)) {
|
|
1004
|
+
return cellValueToText(from, value, DEFAULT_TIME_ZONE);
|
|
1005
|
+
}
|
|
1006
|
+
if (valueFamily(from.type) !== "select") return value;
|
|
1007
|
+
const names = (Array.isArray(value) ? value : [value]).flatMap((id) => {
|
|
1008
|
+
const name = from.property.options?.find((option) => option.id === id)?.name;
|
|
1009
|
+
return name ? [name] : [];
|
|
1010
|
+
});
|
|
1011
|
+
return names;
|
|
1012
|
+
}
|
|
1013
|
+
function optionsFromValues(from, to, values) {
|
|
1014
|
+
const options = [...to.property.options ?? []];
|
|
1015
|
+
const known = new Set(options.map((option) => option.name));
|
|
1016
|
+
for (const value of values) {
|
|
1017
|
+
const converted = convertValue(from, to, value);
|
|
1018
|
+
const names = typeof converted === "string" ? to.type === FieldType.MultiSelect ? converted.split(/[,,\n]/) : [converted] : Array.isArray(converted) ? converted.filter((item) => typeof item === "string") : [];
|
|
1019
|
+
for (const raw of names) {
|
|
1020
|
+
const name = raw.trim();
|
|
1021
|
+
if (name && !known.has(name)) {
|
|
1022
|
+
known.add(name);
|
|
1023
|
+
options.push({ name });
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
return options;
|
|
1028
|
+
}
|
|
1029
|
+
function updateField(doc, tableId, fieldId, patch, origin) {
|
|
1030
|
+
const map = fieldsMap(doc, tableId).get(fieldId);
|
|
1031
|
+
const field = map ? readFieldMap(fieldId, map) : null;
|
|
1032
|
+
if (!map || !field) throw new BaseModelError(`字段不存在:${fieldId}`);
|
|
1033
|
+
const nextType = patch.type ?? field.type;
|
|
1034
|
+
if (!isFieldType(nextType)) throw new BaseModelError(`不支持的字段类型:${nextType}`);
|
|
1035
|
+
const nextUiType = storedUiType(nextType, patch.uiType ?? field.uiType);
|
|
1036
|
+
const retyped = nextType !== field.type || nextUiType !== field.uiType;
|
|
1037
|
+
if (retyped && tablesMap(doc).get(tableId)?.get("primaryFieldId") === fieldId) {
|
|
1038
|
+
if (isComputedFieldType(nextType) || nextType === FieldType.Attachment) {
|
|
1039
|
+
throw new BaseModelError("主字段不能改成这个类型");
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
inTransaction(doc, origin, () => {
|
|
1043
|
+
if (patch.name !== void 0) {
|
|
1044
|
+
const name = patch.name.trim();
|
|
1045
|
+
if (!name) throw new BaseModelError("字段名不能为空");
|
|
1046
|
+
map.set("name", name);
|
|
1047
|
+
}
|
|
1048
|
+
if (patch.description !== void 0) {
|
|
1049
|
+
if (patch.description) map.set("description", patch.description);
|
|
1050
|
+
else map.delete("description");
|
|
1051
|
+
}
|
|
1052
|
+
if (retyped) {
|
|
1053
|
+
retypeField(doc, tableId, map, field, nextType, nextUiType, patch.property);
|
|
1054
|
+
return;
|
|
1055
|
+
}
|
|
1056
|
+
if (patch.property === void 0) return;
|
|
1057
|
+
const property = normalizeProperty(field.type, patch.property, field.uiType);
|
|
1058
|
+
map.set("property", property);
|
|
1059
|
+
if (!property.options) return;
|
|
1060
|
+
const kept = new Set(property.options.map((option) => option.id));
|
|
1061
|
+
const removed = (field.property.options ?? []).filter((option) => !kept.has(option.id));
|
|
1062
|
+
if (!removed.length) return;
|
|
1063
|
+
for (const record of recordsMap(doc, tableId).values()) {
|
|
1064
|
+
const value = record.get(fieldId);
|
|
1065
|
+
if (value === void 0) continue;
|
|
1066
|
+
if (Array.isArray(value)) {
|
|
1067
|
+
const next = value.filter((id) => kept.has(id));
|
|
1068
|
+
if (next.length === value.length) continue;
|
|
1069
|
+
if (next.length) record.set(fieldId, next);
|
|
1070
|
+
else record.delete(fieldId);
|
|
1071
|
+
} else if (!kept.has(value)) {
|
|
1072
|
+
record.delete(fieldId);
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
});
|
|
1076
|
+
}
|
|
1077
|
+
function retypeField(doc, tableId, map, from, type, uiType, propertyInput) {
|
|
1078
|
+
const records = [...recordsMap(doc, tableId).values()];
|
|
1079
|
+
const oldValues = records.map((record) => readFieldValue(from, (key) => record.get(key)));
|
|
1080
|
+
const sameFamily = valueFamily(from.type) === valueFamily(type);
|
|
1081
|
+
let input = {
|
|
1082
|
+
...sameFamily ? from.property : {},
|
|
1083
|
+
...propertyInput
|
|
1084
|
+
};
|
|
1085
|
+
const draft = {
|
|
1086
|
+
...from,
|
|
1087
|
+
type,
|
|
1088
|
+
uiType,
|
|
1089
|
+
property: normalizeProperty(type, input, uiType)
|
|
1090
|
+
};
|
|
1091
|
+
if ((type === FieldType.SingleSelect || type === FieldType.MultiSelect) && !propertyInput?.options) {
|
|
1092
|
+
input = { ...input, options: optionsFromValues(from, draft, oldValues) };
|
|
1093
|
+
draft.property = normalizeProperty(type, input, uiType);
|
|
1094
|
+
}
|
|
1095
|
+
map.set("type", type);
|
|
1096
|
+
if (uiType) map.set("uiType", uiType);
|
|
1097
|
+
else map.delete("uiType");
|
|
1098
|
+
map.set("property", draft.property);
|
|
1099
|
+
records.forEach((record, i) => {
|
|
1100
|
+
const next = isComputedFieldType(type) ? null : normalizeCellValue(draft, convertValue(from, draft, oldValues[i]));
|
|
1101
|
+
if (next === null) {
|
|
1102
|
+
if (record.has(from.id)) record.delete(from.id);
|
|
1103
|
+
} else {
|
|
1104
|
+
record.set(from.id, next);
|
|
1105
|
+
}
|
|
1106
|
+
});
|
|
1107
|
+
if (type === FieldType.AutoNumber) fillAutoNumbers(doc, tableId);
|
|
1108
|
+
}
|
|
1109
|
+
function deleteField(doc, tableId, fieldId, origin) {
|
|
1110
|
+
if (tablesMap(doc).get(tableId)?.get("primaryFieldId") === fieldId) {
|
|
1111
|
+
throw new BaseModelError("主字段不能删除");
|
|
1112
|
+
}
|
|
1113
|
+
inTransaction(doc, origin, () => {
|
|
1114
|
+
fieldsMap(doc, tableId).delete(fieldId);
|
|
1115
|
+
for (const view of viewsMap(doc, tableId).values()) {
|
|
1116
|
+
const order = view.get("fields");
|
|
1117
|
+
if (order) {
|
|
1118
|
+
for (let i = order.length - 1; i >= 0; i--) if (order.get(i) === fieldId) order.delete(i, 1);
|
|
1119
|
+
}
|
|
1120
|
+
view.get("colInfos")?.delete(fieldId);
|
|
1121
|
+
const filter = view.get("filter");
|
|
1122
|
+
if (filter?.conditions.some((condition) => condition.fieldId === fieldId)) {
|
|
1123
|
+
view.set("filter", {
|
|
1124
|
+
...filter,
|
|
1125
|
+
conditions: filter.conditions.filter((condition) => condition.fieldId !== fieldId)
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
for (const key of ["sort", "group"]) {
|
|
1129
|
+
const rules = view.get(key);
|
|
1130
|
+
if (rules?.some((rule) => rule.fieldId === fieldId)) {
|
|
1131
|
+
view.set(
|
|
1132
|
+
key,
|
|
1133
|
+
rules.filter((rule) => rule.fieldId !== fieldId)
|
|
1134
|
+
);
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
for (const record of recordsMap(doc, tableId).values()) {
|
|
1139
|
+
if (record.has(fieldId)) record.delete(fieldId);
|
|
1140
|
+
}
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
function neighbourRanks(doc, tableId, order, index) {
|
|
1144
|
+
const ranks = ranksMap(doc, tableId);
|
|
1145
|
+
const lower = index > 0 ? ranks.get(order[index - 1]) ?? null : null;
|
|
1146
|
+
for (let i = index; i < order.length; i++) {
|
|
1147
|
+
const upper = ranks.get(order[i]) ?? null;
|
|
1148
|
+
if (upper === null || lower === null || upper > lower) return [lower, upper];
|
|
1149
|
+
}
|
|
1150
|
+
return [lower, null];
|
|
1151
|
+
}
|
|
1152
|
+
var maxAutoNumber = (records) => {
|
|
1153
|
+
let max = 0;
|
|
1154
|
+
for (const record of records.values()) {
|
|
1155
|
+
const no = record.get(RECORD_META.autoNumber);
|
|
1156
|
+
if (typeof no === "number" && no > max) max = no;
|
|
1157
|
+
}
|
|
1158
|
+
return max;
|
|
1159
|
+
};
|
|
1160
|
+
function writeRecords(doc, tableId, rows, index) {
|
|
1161
|
+
const records = recordsMap(doc, tableId);
|
|
1162
|
+
const fields = new Map(readFields(doc, tableId).map((field) => [field.id, field]));
|
|
1163
|
+
const order = orderedRecordIds(doc, tableId);
|
|
1164
|
+
const at = Math.max(0, Math.min(index, order.length));
|
|
1165
|
+
const [lower, upper] = neighbourRanks(doc, tableId, order, at);
|
|
1166
|
+
const ranks = ranksBetween(lower, upper, rows.length);
|
|
1167
|
+
const now = Date.now();
|
|
1168
|
+
const actor = actors.get(doc);
|
|
1169
|
+
let no = maxAutoNumber(records);
|
|
1170
|
+
return rows.map((row, i) => {
|
|
1171
|
+
const id = newBaseId("rec");
|
|
1172
|
+
const record = new Y.Map();
|
|
1173
|
+
records.set(id, record);
|
|
1174
|
+
for (const [fieldId, raw] of Object.entries(row)) {
|
|
1175
|
+
const field = fields.get(fieldId);
|
|
1176
|
+
const value = field && !isComputedFieldType(field.type) ? normalizeCellValue(field, raw) : null;
|
|
1177
|
+
if (value !== null) record.set(fieldId, value);
|
|
1178
|
+
}
|
|
1179
|
+
record.set(RECORD_META.createdTime, now);
|
|
1180
|
+
if (actor) record.set(RECORD_META.createdUser, actor);
|
|
1181
|
+
no += 1;
|
|
1182
|
+
record.set(RECORD_META.autoNumber, no);
|
|
1183
|
+
ranksMap(doc, tableId).set(id, ranks[i]);
|
|
1184
|
+
return id;
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
function addRecords(doc, tableId, rows, options = {}, origin) {
|
|
1188
|
+
if (!tablesMap(doc).has(tableId)) throw new BaseModelError(`数据表不存在:${tableId}`);
|
|
1189
|
+
const records = recordsMap(doc, tableId);
|
|
1190
|
+
if (records.size + rows.length > MAX_RECORDS_PER_TABLE) {
|
|
1191
|
+
throw new BaseModelError(`单表最多 ${MAX_RECORDS_PER_TABLE} 条记录`);
|
|
1192
|
+
}
|
|
1193
|
+
const index = options.index ?? records.size;
|
|
1194
|
+
return inTransaction(doc, origin, () => writeRecords(doc, tableId, rows, index));
|
|
1195
|
+
}
|
|
1196
|
+
function repairAutoNumbers(doc, tableId, origin) {
|
|
1197
|
+
let fixed = 0;
|
|
1198
|
+
inTransaction(doc, origin, () => {
|
|
1199
|
+
fixed = fillAutoNumbers(doc, tableId);
|
|
1200
|
+
});
|
|
1201
|
+
return fixed;
|
|
1202
|
+
}
|
|
1203
|
+
function fillAutoNumbers(doc, tableId) {
|
|
1204
|
+
const records = recordsMap(doc, tableId);
|
|
1205
|
+
const position = new Map(orderedRecordIds(doc, tableId).map((id, i) => [id, i]));
|
|
1206
|
+
const createdAt = (record) => {
|
|
1207
|
+
const time = record.get(RECORD_META.createdTime);
|
|
1208
|
+
return typeof time === "number" ? time : 0;
|
|
1209
|
+
};
|
|
1210
|
+
const entries = [...records.entries()].sort(
|
|
1211
|
+
([a, left], [b, right]) => createdAt(left) - createdAt(right) || (position.get(a) ?? 0) - (position.get(b) ?? 0)
|
|
1212
|
+
);
|
|
1213
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1214
|
+
const pending = [];
|
|
1215
|
+
let max = 0;
|
|
1216
|
+
for (const [, record] of entries) {
|
|
1217
|
+
const no = record.get(RECORD_META.autoNumber);
|
|
1218
|
+
if (typeof no === "number" && Number.isInteger(no) && no > 0 && !seen.has(no)) {
|
|
1219
|
+
seen.add(no);
|
|
1220
|
+
if (no > max) max = no;
|
|
1221
|
+
} else {
|
|
1222
|
+
pending.push(record);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
for (const record of pending) record.set(RECORD_META.autoNumber, ++max);
|
|
1226
|
+
return pending.length;
|
|
1227
|
+
}
|
|
1228
|
+
var sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
1229
|
+
function setCells(doc, tableId, changes, origin) {
|
|
1230
|
+
const records = recordsMap(doc, tableId);
|
|
1231
|
+
const fields = /* @__PURE__ */ new Map();
|
|
1232
|
+
for (const [id, map] of fieldsMap(doc, tableId).entries()) {
|
|
1233
|
+
const field = readFieldMap(id, map);
|
|
1234
|
+
if (field) fields.set(id, field);
|
|
1235
|
+
}
|
|
1236
|
+
const touched = /* @__PURE__ */ new Set();
|
|
1237
|
+
inTransaction(doc, origin, () => {
|
|
1238
|
+
for (const { recordId, fieldId, value } of changes) {
|
|
1239
|
+
const record = records.get(recordId);
|
|
1240
|
+
const field = fields.get(fieldId);
|
|
1241
|
+
if (!record || !field || isComputedFieldType(field.type) || isRecordMetaKey(fieldId)) continue;
|
|
1242
|
+
const next = normalizeCellValue(field, value);
|
|
1243
|
+
if (next === null) {
|
|
1244
|
+
if (!record.has(fieldId)) continue;
|
|
1245
|
+
record.delete(fieldId);
|
|
1246
|
+
} else if (!sameJson(record.get(fieldId), next)) {
|
|
1247
|
+
record.set(fieldId, next);
|
|
1248
|
+
} else {
|
|
1249
|
+
continue;
|
|
1250
|
+
}
|
|
1251
|
+
touched.add(record);
|
|
1252
|
+
}
|
|
1253
|
+
if (!touched.size) return;
|
|
1254
|
+
const now = Date.now();
|
|
1255
|
+
const actor = actors.get(doc);
|
|
1256
|
+
for (const record of touched) {
|
|
1257
|
+
record.set(RECORD_META.modifiedTime, now);
|
|
1258
|
+
if (actor) record.set(RECORD_META.modifiedUser, actor);
|
|
1259
|
+
}
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
function deleteRecords(doc, tableId, recordIds, origin) {
|
|
1263
|
+
const records = recordsMap(doc, tableId);
|
|
1264
|
+
const ranks = ranksMap(doc, tableId);
|
|
1265
|
+
inTransaction(doc, origin, () => {
|
|
1266
|
+
for (const id of recordIds) {
|
|
1267
|
+
records.delete(id);
|
|
1268
|
+
ranks.delete(id);
|
|
1269
|
+
}
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
function moveRecords(doc, tableId, recordIds, index, origin) {
|
|
1273
|
+
const moving = new Set(recordIds);
|
|
1274
|
+
const order = orderedRecordIds(doc, tableId);
|
|
1275
|
+
const kept = order.filter((id) => !moving.has(id));
|
|
1276
|
+
const target = Math.max(0, Math.min(index, order.length));
|
|
1277
|
+
const before = order.slice(0, target).filter((id) => !moving.has(id)).length;
|
|
1278
|
+
const [lower, upper] = neighbourRanks(doc, tableId, kept, before);
|
|
1279
|
+
const ranks = ranksBetween(lower, upper, recordIds.length);
|
|
1280
|
+
const ordered = order.filter((id) => moving.has(id));
|
|
1281
|
+
inTransaction(doc, origin, () => {
|
|
1282
|
+
ordered.forEach((id, i) => {
|
|
1283
|
+
ranksMap(doc, tableId).set(id, ranks[i]);
|
|
1284
|
+
});
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
function addView(doc, tableId, name, origin) {
|
|
1288
|
+
const fieldIds = readFields(doc, tableId).map((field) => field.id);
|
|
1289
|
+
const viewName = name?.trim() || uniqueName(
|
|
1290
|
+
readViews(doc, tableId).map((view) => view.name),
|
|
1291
|
+
"表格"
|
|
1292
|
+
);
|
|
1293
|
+
return inTransaction(doc, origin, () => writeView(doc, tableId, viewName, fieldIds));
|
|
1294
|
+
}
|
|
1295
|
+
function deleteView(doc, tableId, viewId, origin) {
|
|
1296
|
+
const views = viewsMap(doc, tableId);
|
|
1297
|
+
if (!views.has(viewId)) return;
|
|
1298
|
+
if (views.size <= 1) throw new BaseModelError("至少保留一个视图");
|
|
1299
|
+
inTransaction(doc, origin, () => {
|
|
1300
|
+
views.delete(viewId);
|
|
1301
|
+
const order = viewOrderArray(doc, tableId);
|
|
1302
|
+
for (let i = order.length - 1; i >= 0; i--) if (order.get(i) === viewId) order.delete(i, 1);
|
|
1303
|
+
});
|
|
1304
|
+
}
|
|
1305
|
+
function duplicateView(doc, tableId, viewId, origin) {
|
|
1306
|
+
const views = readViews(doc, tableId);
|
|
1307
|
+
const source = views.find((view) => view.id === viewId);
|
|
1308
|
+
if (!source) throw new BaseModelError(`视图不存在:${viewId}`);
|
|
1309
|
+
const at = viewOrderArray(doc, tableId).toArray().indexOf(viewId);
|
|
1310
|
+
return inTransaction(doc, origin, () => {
|
|
1311
|
+
const id = writeView(
|
|
1312
|
+
doc,
|
|
1313
|
+
tableId,
|
|
1314
|
+
copyName(
|
|
1315
|
+
views.map((view2) => view2.name),
|
|
1316
|
+
source.name
|
|
1317
|
+
),
|
|
1318
|
+
source.fieldIds,
|
|
1319
|
+
at === -1 ? void 0 : at + 1
|
|
1320
|
+
);
|
|
1321
|
+
const view = viewsMap(doc, tableId).get(id);
|
|
1322
|
+
const colInfos = view.get("colInfos");
|
|
1323
|
+
for (const [fieldId, info] of Object.entries(source.colInfos)) colInfos.set(fieldId, info);
|
|
1324
|
+
view.set("frozenColCount", source.frozenColCount);
|
|
1325
|
+
view.set("rowHeightLevel", source.rowHeightLevel);
|
|
1326
|
+
if (source.filter) view.set("filter", source.filter);
|
|
1327
|
+
if (source.sort.length) view.set("sort", source.sort);
|
|
1328
|
+
if (source.group.length) view.set("group", source.group);
|
|
1329
|
+
return id;
|
|
1330
|
+
});
|
|
1331
|
+
}
|
|
1332
|
+
function updateView(doc, tableId, viewId, patch, origin) {
|
|
1333
|
+
const view = viewsMap(doc, tableId).get(viewId);
|
|
1334
|
+
if (!view) throw new BaseModelError(`视图不存在:${viewId}`);
|
|
1335
|
+
inTransaction(doc, origin, () => {
|
|
1336
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
1337
|
+
if (value !== void 0) view.set(key, value);
|
|
1338
|
+
}
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
function setColumnInfo(doc, tableId, viewId, fieldId, info, origin) {
|
|
1342
|
+
const colInfos = viewsMap(doc, tableId).get(viewId)?.get("colInfos");
|
|
1343
|
+
if (!colInfos) throw new BaseModelError(`视图不存在:${viewId}`);
|
|
1344
|
+
inTransaction(doc, origin, () => {
|
|
1345
|
+
colInfos.set(fieldId, { ...colInfos.get(fieldId), ...info });
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
function moveViewField(doc, tableId, viewId, fieldId, index, origin) {
|
|
1349
|
+
const order = viewsMap(doc, tableId).get(viewId)?.get("fields");
|
|
1350
|
+
if (!order) throw new BaseModelError(`视图不存在:${viewId}`);
|
|
1351
|
+
if (tablesMap(doc).get(tableId)?.get("primaryFieldId") === fieldId) return;
|
|
1352
|
+
inTransaction(doc, origin, () => {
|
|
1353
|
+
for (let i = order.length - 1; i >= 0; i--) if (order.get(i) === fieldId) order.delete(i, 1);
|
|
1354
|
+
order.insert(Math.max(1, Math.min(index, order.length)), [fieldId]);
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
function createBaseUndoManager(doc, tableId, origin) {
|
|
1358
|
+
return new Y.UndoManager([tablesMap(doc), tableOrderArray(doc), ...tableTypes(doc, tableId)], {
|
|
1359
|
+
trackedOrigins: /* @__PURE__ */ new Set([origin]),
|
|
1360
|
+
captureTimeout: 500
|
|
1361
|
+
});
|
|
1362
|
+
}
|
|
1363
|
+
var META_KEYS = [
|
|
1364
|
+
["createdTime", RECORD_META.createdTime],
|
|
1365
|
+
["createdUser", RECORD_META.createdUser],
|
|
1366
|
+
["modifiedTime", RECORD_META.modifiedTime],
|
|
1367
|
+
["modifiedUser", RECORD_META.modifiedUser],
|
|
1368
|
+
["autoNumber", RECORD_META.autoNumber]
|
|
1369
|
+
];
|
|
1370
|
+
function splitRecord(json) {
|
|
1371
|
+
const fields = {};
|
|
1372
|
+
for (const [key, value] of Object.entries(json)) if (!isRecordMetaKey(key)) fields[key] = value;
|
|
1373
|
+
const meta = {};
|
|
1374
|
+
for (const [name, key] of META_KEYS) {
|
|
1375
|
+
if (json[key] !== void 0) meta[name] = json[key];
|
|
1376
|
+
}
|
|
1377
|
+
return Object.keys(meta).length ? { fields, meta } : { fields };
|
|
1378
|
+
}
|
|
1379
|
+
function toSnapshot(doc) {
|
|
1380
|
+
return {
|
|
1381
|
+
schemaVersion: Number(baseRoot(doc).get("schemaVersion") ?? SCHEMA_VERSION),
|
|
1382
|
+
tables: readTables(doc).map((table) => {
|
|
1383
|
+
const records = recordsMap(doc, table.id);
|
|
1384
|
+
const ranks = ranksMap(doc, table.id);
|
|
1385
|
+
return {
|
|
1386
|
+
...table,
|
|
1387
|
+
fields: readFields(doc, table.id).map((field) => ({
|
|
1388
|
+
...field,
|
|
1389
|
+
uiType: fieldUiType(field)
|
|
1390
|
+
})),
|
|
1391
|
+
views: readViews(doc, table.id),
|
|
1392
|
+
records: orderedRecordIds(doc, table.id).map((id) => ({
|
|
1393
|
+
id,
|
|
1394
|
+
rank: ranks.get(id) ?? "",
|
|
1395
|
+
...splitRecord(records.get(id)?.toJSON() ?? {})
|
|
1396
|
+
}))
|
|
1397
|
+
};
|
|
1398
|
+
})
|
|
1399
|
+
};
|
|
1400
|
+
}
|
|
1401
|
+
function loadSnapshot(doc, snapshot, origin) {
|
|
1402
|
+
if (isBaseInitialized(doc)) throw new BaseModelError("文档已初始化,不能再载入快照");
|
|
1403
|
+
doc.transact(() => {
|
|
1404
|
+
baseRoot(doc).set("schemaVersion", snapshot.schemaVersion);
|
|
1405
|
+
for (const table of snapshot.tables) {
|
|
1406
|
+
const tableMap = new Y.Map();
|
|
1407
|
+
tablesMap(doc).set(table.id, tableMap);
|
|
1408
|
+
tableMap.set("name", table.name);
|
|
1409
|
+
tableMap.set("primaryFieldId", table.primaryFieldId);
|
|
1410
|
+
tableOrderArray(doc).push([table.id]);
|
|
1411
|
+
for (const field of table.fields) {
|
|
1412
|
+
const fieldMap = new Y.Map();
|
|
1413
|
+
fieldsMap(doc, table.id).set(field.id, fieldMap);
|
|
1414
|
+
fieldMap.set("name", field.name);
|
|
1415
|
+
fieldMap.set("type", field.type);
|
|
1416
|
+
if (field.type === FieldType.Number && isNumberUiType(field.uiType) && field.uiType !== "Number") {
|
|
1417
|
+
fieldMap.set("uiType", field.uiType);
|
|
1418
|
+
}
|
|
1419
|
+
fieldMap.set("property", field.property);
|
|
1420
|
+
if (field.description) fieldMap.set("description", field.description);
|
|
1421
|
+
}
|
|
1422
|
+
for (const view of table.views) {
|
|
1423
|
+
const viewMap = new Y.Map();
|
|
1424
|
+
viewsMap(doc, table.id).set(view.id, viewMap);
|
|
1425
|
+
viewMap.set("name", view.name);
|
|
1426
|
+
viewMap.set("type", view.type);
|
|
1427
|
+
const fields = new Y.Array();
|
|
1428
|
+
viewMap.set("fields", fields);
|
|
1429
|
+
fields.push(view.fieldIds);
|
|
1430
|
+
const colInfos = new Y.Map();
|
|
1431
|
+
viewMap.set("colInfos", colInfos);
|
|
1432
|
+
for (const [fieldId, info] of Object.entries(view.colInfos)) colInfos.set(fieldId, info);
|
|
1433
|
+
viewMap.set("frozenColCount", view.frozenColCount);
|
|
1434
|
+
viewMap.set("rowHeightLevel", view.rowHeightLevel);
|
|
1435
|
+
if (view.filter) viewMap.set("filter", view.filter);
|
|
1436
|
+
if (view.sort.length) viewMap.set("sort", view.sort);
|
|
1437
|
+
if (view.group.length) viewMap.set("group", view.group);
|
|
1438
|
+
viewOrderArray(doc, table.id).push([view.id]);
|
|
1439
|
+
}
|
|
1440
|
+
const records = recordsMap(doc, table.id);
|
|
1441
|
+
const ranks = ranksMap(doc, table.id);
|
|
1442
|
+
for (const record of table.records) {
|
|
1443
|
+
const recordMap = new Y.Map();
|
|
1444
|
+
records.set(record.id, recordMap);
|
|
1445
|
+
for (const [fieldId, value] of Object.entries(record.fields)) {
|
|
1446
|
+
if (value !== null && value !== void 0) recordMap.set(fieldId, value);
|
|
1447
|
+
}
|
|
1448
|
+
for (const [name, key] of META_KEYS) {
|
|
1449
|
+
const value = record.meta?.[name];
|
|
1450
|
+
if (value !== null && value !== void 0) recordMap.set(key, value);
|
|
1451
|
+
}
|
|
1452
|
+
if (record.rank) ranks.set(record.id, record.rank);
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
}, origin);
|
|
1456
|
+
}
|
|
1457
|
+
function toPlainText(doc) {
|
|
1458
|
+
return readTables(doc).map((table) => {
|
|
1459
|
+
const fields = readFields(doc, table.id);
|
|
1460
|
+
const records = recordsMap(doc, table.id);
|
|
1461
|
+
const lines = orderedRecordIds(doc, table.id).map((id) => {
|
|
1462
|
+
const record = records.get(id);
|
|
1463
|
+
return fields.map(
|
|
1464
|
+
(field) => cellValueToText(
|
|
1465
|
+
field,
|
|
1466
|
+
readFieldValue(field, (key) => record?.get(key))
|
|
1467
|
+
)
|
|
1468
|
+
).join(" ");
|
|
1469
|
+
});
|
|
1470
|
+
return [table.name, fields.map((field) => field.name).join(" "), ...lines].join("\n");
|
|
1471
|
+
}).join("\n\n");
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
// src/base-model/stats.ts
|
|
1475
|
+
var STAT_LABELS = {
|
|
1476
|
+
none: "不展示",
|
|
1477
|
+
countAll: "记录总数",
|
|
1478
|
+
empty: "未填写",
|
|
1479
|
+
filled: "已填写",
|
|
1480
|
+
unique: "唯一值",
|
|
1481
|
+
percentEmpty: "未填写占比",
|
|
1482
|
+
percentFilled: "已填写占比",
|
|
1483
|
+
percentUnique: "唯一值占比",
|
|
1484
|
+
sum: "求和",
|
|
1485
|
+
average: "平均值",
|
|
1486
|
+
max: "最大值",
|
|
1487
|
+
min: "最小值",
|
|
1488
|
+
earliest: "最早时间",
|
|
1489
|
+
latest: "最晚时间",
|
|
1490
|
+
dateRangeOfDays: "时间范围(日)",
|
|
1491
|
+
dateRangeOfMonths: "时间范围(月)",
|
|
1492
|
+
checked: "已勾选",
|
|
1493
|
+
unchecked: "未勾选",
|
|
1494
|
+
percentChecked: "已勾选占比",
|
|
1495
|
+
percentUnchecked: "未勾选占比"
|
|
1496
|
+
};
|
|
1497
|
+
var GENERAL = [
|
|
1498
|
+
"none",
|
|
1499
|
+
"countAll",
|
|
1500
|
+
"empty",
|
|
1501
|
+
"filled",
|
|
1502
|
+
"unique",
|
|
1503
|
+
"percentEmpty",
|
|
1504
|
+
"percentFilled",
|
|
1505
|
+
"percentUnique"
|
|
1506
|
+
];
|
|
1507
|
+
function statTypesFor(field) {
|
|
1508
|
+
switch (field.type) {
|
|
1509
|
+
case FieldType.Number:
|
|
1510
|
+
case FieldType.AutoNumber:
|
|
1511
|
+
return [...GENERAL, "sum", "average", "max", "min"];
|
|
1512
|
+
case FieldType.DateTime:
|
|
1513
|
+
case FieldType.CreatedTime:
|
|
1514
|
+
case FieldType.ModifiedTime:
|
|
1515
|
+
return [...GENERAL, "earliest", "latest", "dateRangeOfDays", "dateRangeOfMonths"];
|
|
1516
|
+
case FieldType.Checkbox:
|
|
1517
|
+
return ["none", "countAll", "checked", "unchecked", "percentChecked", "percentUnchecked"];
|
|
1518
|
+
default:
|
|
1519
|
+
return GENERAL;
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
function resolveStat(field, primaryFieldId, stat) {
|
|
1523
|
+
if (stat && statTypesFor(field).includes(stat)) return stat;
|
|
1524
|
+
return field.id === primaryFieldId ? "countAll" : "none";
|
|
1525
|
+
}
|
|
1526
|
+
var percent = (part, total) => `${total ? Math.round(part / total * 1e4) / 100 : 0}%`;
|
|
1527
|
+
var DAY = 864e5;
|
|
1528
|
+
var formatNumber2 = (field, value) => field.type === FieldType.Number ? formatNumberField(field, value) : String(value);
|
|
1529
|
+
function statText(field, values, stat, timeZone = DEFAULT_TIME_ZONE) {
|
|
1530
|
+
if (stat === "none") return "";
|
|
1531
|
+
const total = values.length;
|
|
1532
|
+
if (stat === "countAll") return `${total} 条记录`;
|
|
1533
|
+
const filled = values.filter((value) => !isEmptyCellValue(value));
|
|
1534
|
+
const label = STAT_LABELS[stat];
|
|
1535
|
+
switch (stat) {
|
|
1536
|
+
case "empty":
|
|
1537
|
+
return `${label} ${total - filled.length}`;
|
|
1538
|
+
case "filled":
|
|
1539
|
+
return `${label} ${filled.length}`;
|
|
1540
|
+
case "percentEmpty":
|
|
1541
|
+
return `${label} ${percent(total - filled.length, total)}`;
|
|
1542
|
+
case "percentFilled":
|
|
1543
|
+
return `${label} ${percent(filled.length, total)}`;
|
|
1544
|
+
case "unique":
|
|
1545
|
+
case "percentUnique": {
|
|
1546
|
+
const unique2 = new Set(filled.map((value) => cellValueToText(field, value, timeZone))).size;
|
|
1547
|
+
return `${label} ${stat === "unique" ? unique2 : percent(unique2, total)}`;
|
|
1548
|
+
}
|
|
1549
|
+
case "checked":
|
|
1550
|
+
case "unchecked":
|
|
1551
|
+
case "percentChecked":
|
|
1552
|
+
case "percentUnchecked": {
|
|
1553
|
+
const checked = values.filter((value) => value === true).length;
|
|
1554
|
+
const count = stat === "checked" || stat === "percentChecked" ? checked : total - checked;
|
|
1555
|
+
return `${label} ${stat.startsWith("percent") ? percent(count, total) : count}`;
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
const numbers = filled.filter((value) => typeof value === "number");
|
|
1559
|
+
if (!numbers.length) return `${label} -`;
|
|
1560
|
+
switch (stat) {
|
|
1561
|
+
case "sum":
|
|
1562
|
+
return `${label} ${formatNumber2(
|
|
1563
|
+
field,
|
|
1564
|
+
numbers.reduce((sum, value) => sum + value, 0)
|
|
1565
|
+
)}`;
|
|
1566
|
+
case "average":
|
|
1567
|
+
return `${label} ${formatNumber2(field, numbers.reduce((sum, value) => sum + value, 0) / numbers.length)}`;
|
|
1568
|
+
case "max":
|
|
1569
|
+
return `${label} ${formatNumber2(field, Math.max(...numbers))}`;
|
|
1570
|
+
case "min":
|
|
1571
|
+
return `${label} ${formatNumber2(field, Math.min(...numbers))}`;
|
|
1572
|
+
case "earliest":
|
|
1573
|
+
return `${label} ${cellValueToText(field, Math.min(...numbers), timeZone)}`;
|
|
1574
|
+
case "latest":
|
|
1575
|
+
return `${label} ${cellValueToText(field, Math.max(...numbers), timeZone)}`;
|
|
1576
|
+
case "dateRangeOfDays": {
|
|
1577
|
+
const from = startOfDayIn(Math.min(...numbers), timeZone);
|
|
1578
|
+
const to = startOfDayIn(Math.max(...numbers), timeZone);
|
|
1579
|
+
let days = Math.round((to - from) / DAY);
|
|
1580
|
+
while (addDaysIn(from, days, timeZone) > to) days--;
|
|
1581
|
+
return `时间范围 ${days} 天`;
|
|
1582
|
+
}
|
|
1583
|
+
case "dateRangeOfMonths": {
|
|
1584
|
+
const from = Math.min(...numbers);
|
|
1585
|
+
const to = Math.max(...numbers);
|
|
1586
|
+
let months = 0;
|
|
1587
|
+
while (startOfMonthIn(from, months + 1, timeZone) <= startOfMonthIn(to, 0, timeZone)) months++;
|
|
1588
|
+
return `时间范围 ${months} 月`;
|
|
1589
|
+
}
|
|
1590
|
+
default:
|
|
1591
|
+
return "";
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
// src/base-model/view.ts
|
|
1596
|
+
function filterKind(type) {
|
|
1597
|
+
switch (type) {
|
|
1598
|
+
case FieldType.Number:
|
|
1599
|
+
case FieldType.AutoNumber:
|
|
1600
|
+
return "number";
|
|
1601
|
+
case FieldType.DateTime:
|
|
1602
|
+
case FieldType.CreatedTime:
|
|
1603
|
+
case FieldType.ModifiedTime:
|
|
1604
|
+
return "date";
|
|
1605
|
+
case FieldType.SingleSelect:
|
|
1606
|
+
return "select";
|
|
1607
|
+
case FieldType.MultiSelect:
|
|
1608
|
+
return "multiSelect";
|
|
1609
|
+
case FieldType.User:
|
|
1610
|
+
case FieldType.CreatedUser:
|
|
1611
|
+
case FieldType.ModifiedUser:
|
|
1612
|
+
return "user";
|
|
1613
|
+
case FieldType.Checkbox:
|
|
1614
|
+
return "checkbox";
|
|
1615
|
+
case FieldType.Attachment:
|
|
1616
|
+
return "attachment";
|
|
1617
|
+
default:
|
|
1618
|
+
return "text";
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
function filterOperatorsFor(type) {
|
|
1622
|
+
switch (filterKind(type)) {
|
|
1623
|
+
case "number":
|
|
1624
|
+
return [
|
|
1625
|
+
"is",
|
|
1626
|
+
"isNot",
|
|
1627
|
+
"isGreater",
|
|
1628
|
+
"isGreaterEqual",
|
|
1629
|
+
"isLess",
|
|
1630
|
+
"isLessEqual",
|
|
1631
|
+
"isEmpty",
|
|
1632
|
+
"isNotEmpty"
|
|
1633
|
+
];
|
|
1634
|
+
case "date":
|
|
1635
|
+
return ["is", "isGreater", "isLess", "isEmpty", "isNotEmpty"];
|
|
1636
|
+
case "checkbox":
|
|
1637
|
+
return ["is"];
|
|
1638
|
+
case "attachment":
|
|
1639
|
+
return ["isEmpty", "isNotEmpty"];
|
|
1640
|
+
case "select":
|
|
1641
|
+
case "multiSelect":
|
|
1642
|
+
case "user":
|
|
1643
|
+
case "text":
|
|
1644
|
+
return ["is", "isNot", "contains", "doesNotContain", "isEmpty", "isNotEmpty"];
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
var asArray = (value) => Array.isArray(value) ? value : [value];
|
|
1648
|
+
function dateFilterRange(expected, now, timeZone = DEFAULT_TIME_ZONE) {
|
|
1649
|
+
const spec = typeof expected === "number" ? { type: "exactDate", value: expected } : typeof expected === "object" && expected !== null && "type" in expected ? expected : null;
|
|
1650
|
+
if (!spec) return null;
|
|
1651
|
+
const today = startOfDayIn(now, timeZone);
|
|
1652
|
+
const day = (offset, from = today) => addDaysIn(from, offset, timeZone);
|
|
1653
|
+
switch (spec.type) {
|
|
1654
|
+
case "exactDate": {
|
|
1655
|
+
if (!Number.isFinite(spec.value)) return null;
|
|
1656
|
+
const start = startOfDayIn(spec.value, timeZone);
|
|
1657
|
+
return [start, day(1, start)];
|
|
1658
|
+
}
|
|
1659
|
+
case "today":
|
|
1660
|
+
return [today, day(1)];
|
|
1661
|
+
case "tomorrow":
|
|
1662
|
+
return [day(1), day(2)];
|
|
1663
|
+
case "yesterday":
|
|
1664
|
+
return [day(-1), today];
|
|
1665
|
+
case "currentWeek":
|
|
1666
|
+
case "lastWeek": {
|
|
1667
|
+
const monday = day(-weekdayIn(now, timeZone));
|
|
1668
|
+
const start = spec.type === "currentWeek" ? monday : day(-7, monday);
|
|
1669
|
+
return [start, day(7, start)];
|
|
1670
|
+
}
|
|
1671
|
+
case "currentMonth":
|
|
1672
|
+
return [startOfMonthIn(now, 0, timeZone), startOfMonthIn(now, 1, timeZone)];
|
|
1673
|
+
case "lastMonth":
|
|
1674
|
+
return [startOfMonthIn(now, -1, timeZone), startOfMonthIn(now, 0, timeZone)];
|
|
1675
|
+
case "pastDays":
|
|
1676
|
+
return [day(-Math.max(0, Math.floor(spec.days))), day(1)];
|
|
1677
|
+
case "nextDays":
|
|
1678
|
+
return [today, day(Math.max(0, Math.floor(spec.days)) + 1)];
|
|
1679
|
+
default:
|
|
1680
|
+
return null;
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
var userIds = (value) => Array.isArray(value) ? value.flatMap(
|
|
1684
|
+
(item) => typeof item === "string" ? [item] : typeof item === "object" && item ? [item.id] : []
|
|
1685
|
+
) : typeof value === "string" ? [value] : [];
|
|
1686
|
+
function matchCondition(field, value, { operator, value: expected }, timeZone, now) {
|
|
1687
|
+
const empty = isEmptyCellValue(value);
|
|
1688
|
+
if (operator === "isEmpty") return empty;
|
|
1689
|
+
if (operator === "isNotEmpty") return !empty;
|
|
1690
|
+
if (expected === void 0 || expected === null || expected === "") return true;
|
|
1691
|
+
if (Array.isArray(expected) && expected.length === 0) return true;
|
|
1692
|
+
const negate = operator === "isNot" || operator === "doesNotContain";
|
|
1693
|
+
const kind = filterKind(field.type);
|
|
1694
|
+
if (kind === "checkbox") return value === true === Boolean(expected);
|
|
1695
|
+
if (empty) return negate;
|
|
1696
|
+
let result;
|
|
1697
|
+
switch (kind) {
|
|
1698
|
+
case "number": {
|
|
1699
|
+
const actual = value;
|
|
1700
|
+
const target = Number(expected);
|
|
1701
|
+
if (!Number.isFinite(target)) return true;
|
|
1702
|
+
if (operator === "isGreater") return actual > target;
|
|
1703
|
+
if (operator === "isGreaterEqual") return actual >= target;
|
|
1704
|
+
if (operator === "isLess") return actual < target;
|
|
1705
|
+
if (operator === "isLessEqual") return actual <= target;
|
|
1706
|
+
result = actual === target;
|
|
1707
|
+
break;
|
|
1708
|
+
}
|
|
1709
|
+
case "date": {
|
|
1710
|
+
const range = dateFilterRange(expected, now, timeZone);
|
|
1711
|
+
if (!range) return true;
|
|
1712
|
+
const actual = value;
|
|
1713
|
+
if (operator === "isGreater") return actual >= range[1];
|
|
1714
|
+
if (operator === "isLess") return actual < range[0];
|
|
1715
|
+
result = actual >= range[0] && actual < range[1];
|
|
1716
|
+
break;
|
|
1717
|
+
}
|
|
1718
|
+
case "select":
|
|
1719
|
+
result = asArray(expected).includes(value);
|
|
1720
|
+
break;
|
|
1721
|
+
case "multiSelect":
|
|
1722
|
+
case "user": {
|
|
1723
|
+
const actual = kind === "user" ? userIds(value) : value;
|
|
1724
|
+
const targets = kind === "user" ? userIds(expected) : asArray(expected);
|
|
1725
|
+
result = operator === "contains" || operator === "doesNotContain" ? targets.some((id) => actual.includes(id)) : actual.length === targets.length && targets.every((id) => actual.includes(id));
|
|
1726
|
+
break;
|
|
1727
|
+
}
|
|
1728
|
+
default: {
|
|
1729
|
+
const text = cellValueToText(field, value, timeZone);
|
|
1730
|
+
const target = String(expected);
|
|
1731
|
+
result = operator === "contains" || operator === "doesNotContain" ? text.toLowerCase().includes(target.toLowerCase()) : text === target;
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
return negate ? !result : result;
|
|
1735
|
+
}
|
|
1736
|
+
var groupKey = (field, value) => {
|
|
1737
|
+
if (isEmptyCellValue(value)) return "";
|
|
1738
|
+
switch (filterKind(field.type)) {
|
|
1739
|
+
case "text":
|
|
1740
|
+
return cellValueToText(field, value);
|
|
1741
|
+
case "user":
|
|
1742
|
+
return userIds(value).join(",");
|
|
1743
|
+
case "date":
|
|
1744
|
+
return cellValueToText(field, value);
|
|
1745
|
+
default:
|
|
1746
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
1747
|
+
}
|
|
1748
|
+
};
|
|
1749
|
+
function compareByRules(rules, getValue, a, b) {
|
|
1750
|
+
for (const { field, desc, group } of rules) {
|
|
1751
|
+
const left = getValue(a, field.id);
|
|
1752
|
+
const right = getValue(b, field.id);
|
|
1753
|
+
const leftEmpty = isEmptyCellValue(left);
|
|
1754
|
+
const rightEmpty = isEmptyCellValue(right);
|
|
1755
|
+
if (leftEmpty || rightEmpty) {
|
|
1756
|
+
if (leftEmpty !== rightEmpty) return leftEmpty ? 1 : -1;
|
|
1757
|
+
continue;
|
|
1758
|
+
}
|
|
1759
|
+
let result = compareCellValues(field, left, right);
|
|
1760
|
+
if (result === 0 && group) {
|
|
1761
|
+
const leftKey = groupKey(field, left);
|
|
1762
|
+
const rightKey = groupKey(field, right);
|
|
1763
|
+
result = leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;
|
|
1764
|
+
}
|
|
1765
|
+
if (result !== 0) return desc ? -result : result;
|
|
1766
|
+
}
|
|
1767
|
+
return 0;
|
|
1768
|
+
}
|
|
1769
|
+
function computeView(input) {
|
|
1770
|
+
const timeZone = input.timeZone ?? DEFAULT_TIME_ZONE;
|
|
1771
|
+
const now = input.now ?? Date.now();
|
|
1772
|
+
const fieldById = new Map(input.fields.map((field) => [field.id, field]));
|
|
1773
|
+
const { getValue } = input;
|
|
1774
|
+
const conditions = (input.filter?.conditions ?? []).flatMap((condition) => {
|
|
1775
|
+
const field = fieldById.get(condition.fieldId);
|
|
1776
|
+
return field ? [{ field, condition }] : [];
|
|
1777
|
+
});
|
|
1778
|
+
const isOr = input.filter?.conjunction === "or";
|
|
1779
|
+
const passes = (recordId) => {
|
|
1780
|
+
if (!conditions.length) return true;
|
|
1781
|
+
const test = ({ field, condition }) => matchCondition(field, getValue(recordId, field.id), condition, timeZone, now);
|
|
1782
|
+
return isOr ? conditions.some(test) : conditions.every(test);
|
|
1783
|
+
};
|
|
1784
|
+
const toRules = (rules, group) => (rules ?? []).flatMap(({ fieldId, desc }) => {
|
|
1785
|
+
const field = fieldById.get(fieldId);
|
|
1786
|
+
return field ? [{ field, desc: Boolean(desc), group }] : [];
|
|
1787
|
+
});
|
|
1788
|
+
const groupRules = toRules(input.group, true).slice(0, 3);
|
|
1789
|
+
const sortRules = [...groupRules, ...toRules(input.sort, false)];
|
|
1790
|
+
const filtered = input.recordIds.filter(passes);
|
|
1791
|
+
const sorted = sortRules.length ? [...filtered].sort((a, b) => compareByRules(sortRules, getValue, a, b)) : filtered;
|
|
1792
|
+
if (!groupRules.length) return { recordIds: sorted, groups: null, total: sorted.length };
|
|
1793
|
+
const collapsed = input.collapsedGroupIds ?? /* @__PURE__ */ new Set();
|
|
1794
|
+
const recordIds = [];
|
|
1795
|
+
const groups = [];
|
|
1796
|
+
const walk = (ids, depth, parentId) => {
|
|
1797
|
+
const { field } = groupRules[depth];
|
|
1798
|
+
let start = 0;
|
|
1799
|
+
while (start < ids.length) {
|
|
1800
|
+
const value = getValue(ids[start], field.id);
|
|
1801
|
+
const key = groupKey(field, value);
|
|
1802
|
+
let end = start + 1;
|
|
1803
|
+
while (end < ids.length && groupKey(field, getValue(ids[end], field.id)) === key) end++;
|
|
1804
|
+
const members = ids.slice(start, end);
|
|
1805
|
+
const id = `${parentId}/${depth}:${key}`;
|
|
1806
|
+
const isCollapsed = collapsed.has(id);
|
|
1807
|
+
groups.push({
|
|
1808
|
+
type: "group",
|
|
1809
|
+
id,
|
|
1810
|
+
depth,
|
|
1811
|
+
fieldId: field.id,
|
|
1812
|
+
value: isEmptyCellValue(value) ? null : value,
|
|
1813
|
+
count: members.length,
|
|
1814
|
+
collapsed: isCollapsed
|
|
1815
|
+
});
|
|
1816
|
+
if (!isCollapsed) {
|
|
1817
|
+
if (depth + 1 < groupRules.length) {
|
|
1818
|
+
walk(members, depth + 1, id);
|
|
1819
|
+
} else {
|
|
1820
|
+
groups.push({ type: "rows", count: members.length });
|
|
1821
|
+
recordIds.push(...members);
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
start = end;
|
|
1825
|
+
}
|
|
1826
|
+
};
|
|
1827
|
+
walk(sorted, 0, "");
|
|
1828
|
+
return { recordIds, groups, total: sorted.length };
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
export { BaseModelError, CURRENCY_SYMBOLS, DEFAULT_RECORD_COUNT, DEFAULT_TABLE_FIELDS, DEFAULT_TIME_ZONE, FIELD_UI_TYPE, FieldType, MAX_RECORDS_PER_TABLE, NUMBER_UI_TYPES, RECORD_META, RankError, SCHEMA_VERSION, STAT_LABELS, addDaysIn, addField, addRecords, addTable, addView, baseRoot, cellValueToText, compareCellValues, compareRank, computeView, copyName, createBaseUndoManager, dateFilterRange, defaultFieldProperty, deleteField, deleteRecords, deleteTable, deleteView, duplicateField, duplicateTable, duplicateView, fieldUiType, fieldValueKey, fieldsMap, filterKind, filterOperatorsFor, formatNumberField, fromWallTime, initBase, isBaseInitialized, isComputedFieldType, isEmptyCellValue, isFieldType, isNumberUiType, isRecordMetaKey, loadSnapshot, moveRecords, moveTable, moveViewField, newBaseId, normalizeCellValue, orderedRecordIds, rankBetween, ranksBetween, ranksMap, readCellValue, readFieldMap, readFieldValue, readFields, readTable, readTables, readView, readViewMap, readViews, recordsMap, renameTable, repairAutoNumbers, resolveStat, setBaseActor, setCells, setColumnInfo, startOfDayIn, startOfMonthIn, statText, statTypesFor, tableKeys, tableOrderArray, tableTypes, tablesMap, toPlainText, toSnapshot, toWallTime, uniqueName, updateField, updateView, viewOrderArray, viewsMap, weekdayIn };
|
|
1832
|
+
//# sourceMappingURL=chunk-3BRBH7MU.js.map
|
|
1833
|
+
//# sourceMappingURL=chunk-3BRBH7MU.js.map
|