@canvas-components/react-list-table 0.3.52 → 0.3.55

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/index.cjs CHANGED
@@ -3,16 +3,11 @@
3
3
  var react = require('react');
4
4
  var reactDom = require('react-dom');
5
5
  var reactComponents = require('@canvas-components/react-components');
6
- var reactPrintDesign = require('@canvas-components/react-print-design');
7
6
  var listTable = require('@canvas-components/list-table');
8
7
  var jsxRuntime = require('react/jsx-runtime');
9
8
  var chart = require('@canvas-components/chart');
10
9
  var date = require('@canvas-components/utils/date');
11
10
  var number = require('@canvas-components/utils/number');
12
- var utils = require('@canvas-components/utils');
13
- var printDesign = require('@canvas-components/print-design');
14
- var print = require('@canvas-components/print');
15
- var client = require('react-dom/client');
16
11
 
17
12
  // #style-inject:#style-inject
18
13
  function styleInject(css, { insertAt } = {}) {
@@ -1072,40 +1067,19 @@ function ReactTableContextMenuView(props) {
1072
1067
  request.onPrint?.();
1073
1068
  }
1074
1069
  }
1075
- ) : /* @__PURE__ */ jsxRuntime.jsx(
1070
+ ) : props.hostMenu ? /* @__PURE__ */ jsxRuntime.jsx(
1076
1071
  MenuSubmenu,
1077
1072
  {
1078
- label: "\u6253\u5370",
1079
- items: [
1080
- ...props.printTemplates && props.printTemplates.length > 1 ? props.printTemplates.map((template) => ({
1081
- key: `print-template-${template.key}`,
1082
- label: `\u76F4\u63A5\u6253\u5370 ${template.label}`,
1083
- disabled: template.disabled,
1084
- onClick: template.disabled ? void 0 : () => {
1085
- setMenuOpen(false);
1086
- props.onPrintTemplate?.(template.key);
1087
- }
1088
- })) : [
1089
- {
1090
- key: "print-direct",
1091
- label: "\u76F4\u63A5\u6253\u5370",
1092
- onClick: request.onGetPrintData ? () => {
1093
- setMenuOpen(false);
1094
- props.onDirectPrint?.();
1095
- } : void 0
1096
- }
1097
- ],
1098
- {
1099
- key: "print-configure",
1100
- label: "\u6253\u5370\u8BBE\u8BA1",
1101
- onClick: request.onGetPrintData ? () => {
1102
- setMenuOpen(false);
1103
- props.onPrint?.();
1104
- } : void 0
1105
- }
1106
- ]
1073
+ label: props.hostMenu.label,
1074
+ items: props.hostMenu.items.map((item) => ({
1075
+ ...item,
1076
+ onClick: item.onClick ? () => {
1077
+ setMenuOpen(false);
1078
+ item.onClick?.();
1079
+ } : void 0
1080
+ }))
1107
1081
  }
1108
- ),
1082
+ ) : null,
1109
1083
  request.customItems?.map((item) => /* @__PURE__ */ jsxRuntime.jsx(
1110
1084
  CustomContextMenuItem,
1111
1085
  {
@@ -4147,769 +4121,25 @@ function fitExportDialogColumns(columns, availableWidth) {
4147
4121
  });
4148
4122
  return fit(columns);
4149
4123
  }
4150
-
4151
- // src/features/print/print-settings.ts
4152
- function createPrintColumns(columns, summaryColumns = []) {
4153
- const choices = new Map(summaryColumns.map((column) => [column.key, column]));
4154
- return columns.map((column) => {
4155
- const choice = choices.get(column.key);
4156
- return {
4157
- ...column,
4158
- align: column.align ?? "left",
4159
- overflow: column.overflow ?? "wrap",
4160
- summaryType: choice?.summary.type ?? "none",
4161
- showTypePrefix: choice?.summary.showTypePrefix ? "yes" : "no",
4162
- precision: choice?.summary.precision,
4163
- roundingMode: choice?.summary.roundingMode ?? "round",
4164
- preserveTrailingZeros: choice?.summary.preserveTrailingZeros ? "yes" : "no",
4165
- summaryTitle: choice?.summaryTitle
4166
- };
4167
- });
4168
- }
4169
- function restorePrintColumns(columns, settings) {
4170
- const current = new Map(columns.map((column) => [column.key, column]));
4171
- const restored = [];
4172
- settings?.columns?.forEach((saved) => {
4173
- const column = current.get(saved.key);
4174
- if (!column) return;
4175
- restored.push({ ...column, ...saved, title: column.title });
4176
- current.delete(saved.key);
4177
- });
4178
- return [...restored, ...current.values()];
4179
- }
4180
- function resolvePrintSelectedKeys(sourceColumns, presetConfig, cached) {
4181
- new Set(cached?.columns.map((column) => column.key));
4182
- const presetKeys = presetConfig?.selectedKeys ? new Set(presetConfig.selectedKeys) : null;
4183
- return sourceColumns.filter((column) => {
4184
- if (presetKeys) return presetKeys.has(column.key);
4185
- return true;
4186
- }).map((column) => column.key);
4187
- }
4188
- function createTableDocument(source, preset) {
4189
- const config = preset?.config;
4190
- const page = printDesign.createPrintDesignPage("\u8868\u683C\u6253\u5370");
4191
- const [paperWidth, paperHeight] = print.BROWSER_PRINT_PAPER_SIZES[config?.paperSize ?? "a4"];
4192
- page.width = config?.orientation === "landscape" ? paperHeight : paperWidth;
4193
- page.height = config?.orientation === "landscape" ? paperWidth : paperHeight;
4194
- page.orientation = config?.orientation ?? "portrait";
4195
- page.margins = config?.pageMargins ?? page.margins;
4196
- const selectedKeys = resolvePrintSelectedKeys(source.columns, config);
4197
- const columns = restorePrintColumns(
4198
- createPrintColumns(source.columns, source.summaryColumns),
4199
- config?.columns ? { columns: config.columns } : null
4200
- ).filter((column) => selectedKeys.includes(column.key));
4201
- const left = page.margins?.left ?? 10;
4202
- const right = page.margins?.right ?? 10;
4203
- const bottom = page.margins?.bottom ?? 10;
4204
- const contentWidth = page.width - left - right;
4205
- const widthSum = columns.reduce((sum, column) => sum + column.width, 0);
4206
- const rowHeight = config?.rowHeight ?? 8;
4207
- const footerY = page.height - bottom - 6;
4208
- const tableY = 28;
4209
- const tableHeight = footerY - tableY - 8;
4210
- const rowsPerPage = Math.max(1, Math.floor((tableHeight - 9) / rowHeight));
4211
- const pageCount = Math.max(1, Math.ceil(source.rows.length / rowsPerPage));
4212
- const printedAt = (/* @__PURE__ */ new Date()).toLocaleString("zh-CN");
4213
- const pages = Array.from(
4214
- { length: pageCount },
4215
- (_, index) => ({
4216
- ...page,
4217
- id: index === 0 ? page.id : printDesign.createPrintDesignPage().id,
4218
- name: `\u8868\u683C\u6253\u5370 ${index + 1}`,
4219
- elements: [
4220
- {
4221
- id: `list-table-title-${index}`,
4222
- type: "text",
4223
- name: "\u6807\u9898",
4224
- x: left,
4225
- y: 12,
4226
- width: contentWidth,
4227
- height: 10,
4228
- text: config?.title ?? "\u8868\u683C\u6253\u5370",
4229
- fontSize: config?.titleFontSize ?? 18,
4230
- fontWeight: "700",
4231
- textAlign: "center"
4232
- },
4233
- {
4234
- id: `list-table-data-${index}`,
4235
- type: "table",
4236
- name: "\u8868\u683C\u6570\u636E",
4237
- x: left,
4238
- y: tableY,
4239
- width: contentWidth,
4240
- height: tableHeight,
4241
- manualHeight: true,
4242
- dataMode: "binding",
4243
- dataPath: `listTable.pages.${index}.rows`,
4244
- dataSource: [],
4245
- columns: columns.map((column) => ({
4246
- key: column.key,
4247
- title: column.title,
4248
- dataIndex: column.key,
4249
- width: widthSum > 0 ? Math.max(24, column.width / widthSum * 720) : 120,
4250
- align: column.align
4251
- })),
4252
- rowHeight,
4253
- headerRowHeight: 9,
4254
- showHeader: true
4255
- },
4256
- {
4257
- id: `list-table-print-time-${index}`,
4258
- type: "text",
4259
- name: "\u6253\u5370\u65F6\u95F4",
4260
- x: left,
4261
- y: footerY,
4262
- width: contentWidth / 2,
4263
- height: 6,
4264
- text: `\u6253\u5370\u65F6\u95F4\uFF1A${printedAt}`,
4265
- fontSize: 9,
4266
- color: "#000000"
4267
- },
4268
- {
4269
- id: `list-table-page-number-${index}`,
4270
- type: "text",
4271
- name: "\u5206\u9875\u4FE1\u606F",
4272
- x: left + contentWidth / 2,
4273
- y: footerY,
4274
- width: contentWidth / 2,
4275
- height: 6,
4276
- text: `\u7B2C ${index + 1} \u9875 / \u5171 ${pageCount} \u9875`,
4277
- textAlign: "right",
4278
- fontSize: 9,
4279
- color: "#000000"
4280
- }
4281
- ]
4282
- })
4283
- );
4284
- return printDesign.createPrintDesignDocument({
4285
- name: preset?.name ?? "\u8868\u683C\u6253\u5370\u6A21\u677F",
4286
- pages
4287
- });
4288
- }
4289
- function mapPrintSourceRows(source) {
4290
- return source.rows.map(
4291
- (row) => Object.fromEntries(
4292
- source.columns.map((column, index) => [column.key, row[index] ?? ""])
4293
- )
4294
- );
4295
- }
4296
- function mapPrintSourceRowsAsync(source, options) {
4297
- return utils.mapInBatches(
4298
- source.rows.length,
4299
- (index) => Object.fromEntries(
4300
- source.columns.map((column, columnIndex) => [
4301
- column.key,
4302
- source.rows[index][columnIndex] ?? ""
4303
- ])
4304
- ),
4305
- options
4306
- );
4307
- }
4308
- function getRowsPerPage(document2, rowCount) {
4309
- const firstTable = document2.pages[0]?.elements.find(
4310
- (item) => item.type === "table"
4311
- );
4312
- return firstTable?.type === "table" ? Math.max(
4313
- 1,
4314
- Math.floor(
4315
- (firstTable.height - (firstTable.showHeader === false ? 0 : firstTable.headerRowHeight ?? 9)) / (firstTable.rowHeight ?? 8)
4316
- )
4317
- ) : Math.max(1, Math.ceil(rowCount / Math.max(1, document2.pages.length)));
4318
- }
4319
- function getPrintDesignSampleSize() {
4320
- return getRowsPerPage(createTableDocument({ columns: [], rows: [] }), 0);
4321
- }
4322
- function createTableData(source, document2, rows = mapPrintSourceRows(source)) {
4323
- const rowsPerPage = getRowsPerPage(document2, rows.length);
4324
- return {
4325
- listTable: {
4326
- rows,
4327
- columns: source.columns.map((column) => ({ key: column.key })),
4328
- pages: document2.pages.map((_, index) => ({
4329
- rows: rows.slice(index * rowsPerPage, (index + 1) * rowsPerPage)
4330
- }))
4331
- }
4332
- };
4333
- }
4334
- async function createTableDataAsync(source, document2, rows, options) {
4335
- const rowsPerPage = getRowsPerPage(document2, rows.length);
4336
- const pages = await utils.mapInBatches(
4337
- document2.pages.length,
4338
- (index) => ({
4339
- rows: rows.slice(index * rowsPerPage, (index + 1) * rowsPerPage)
4340
- }),
4341
- options
4342
- );
4343
- return {
4344
- listTable: {
4345
- rows,
4346
- columns: source.columns.map((column) => ({ key: column.key })),
4347
- pages
4348
- }
4349
- };
4350
- }
4351
- async function createTablePreviewSource(source, template, options, preparedRows) {
4352
- const rows = preparedRows ?? await mapPrintSourceRowsAsync(source, options);
4353
- const pageCount = Math.max(
4354
- template.pages.length,
4355
- Math.ceil(rows.length / getRowsPerPage(template, rows.length))
4356
- );
4357
- const pages = await utils.mapInBatches(
4358
- pageCount,
4359
- (index) => {
4360
- const page = template.pages[index % template.pages.length];
4361
- return {
4362
- ...page,
4363
- id: `${page.id}:print:${index}`,
4364
- name: `\u8868\u683C\u6253\u5370 ${index + 1}`,
4365
- elements: page.elements.map((element) => {
4366
- const id = `${element.id}:print:${index}`;
4367
- if (element.type === "table" && (element.dataPath === "listTable.rows" || /^listTable\.pages\.\d+\.rows$/.test(element.dataPath ?? ""))) {
4368
- return {
4369
- ...element,
4370
- id,
4371
- dataPath: `listTable.pages.${index}.rows`
4372
- };
4373
- }
4374
- if (element.type === "text" && element.id.startsWith("list-table-page-number-")) {
4375
- return {
4376
- ...element,
4377
- id,
4378
- text: `\u7B2C ${index + 1} \u9875 / \u5171 ${pageCount} \u9875`
4379
- };
4380
- }
4381
- return { ...element, id };
4382
- })
4383
- };
4384
- },
4385
- options
4386
- );
4387
- const document2 = { ...template, pages };
4388
- return {
4389
- document: document2,
4390
- data: await createTableDataAsync(source, document2, rows, options)
4391
- };
4392
- }
4393
- function getPrintSourceFormat(source) {
4394
- return JSON.stringify(
4395
- source.columns.map((column) => String(column.key)).sort()
4396
- );
4397
- }
4398
- function ReactListTablePrintDesignDialog(props) {
4399
- const [fullscreen, setFullscreen] = react.useState(true);
4400
- const [source, setSource] = react.useState(null);
4401
- const [error, setError] = react.useState("");
4402
- const [attempt, setAttempt] = react.useState(0);
4403
- const [emptyDocument] = react.useState(
4404
- () => printDesign.createPrintDesignDocument({ name: "\u8868\u683C\u6253\u5370\u6A21\u677F" })
4405
- );
4406
- react.useEffect(() => {
4407
- const controller = new AbortController();
4408
- setSource(null);
4409
- setError("");
4410
- const timer = setTimeout(() => {
4411
- void Promise.resolve().then(
4412
- () => props.loadSource({
4413
- rowLimit: getPrintDesignSampleSize(),
4414
- includeSummary: false,
4415
- signal: controller.signal
4416
- })
4417
- ).then((value) => {
4418
- if (!controller.signal.aborted) setSource(value);
4419
- }).catch((cause) => {
4420
- if (!controller.signal.aborted)
4421
- setError(
4422
- cause instanceof Error ? cause.message : "\u8BFB\u53D6\u6253\u5370\u6570\u636E\u5931\u8D25"
4423
- );
4424
- });
4425
- }, 0);
4426
- return () => {
4427
- clearTimeout(timer);
4428
- controller.abort();
4429
- };
4430
- }, [props.loadSource, attempt]);
4431
- return /* @__PURE__ */ jsxRuntime.jsx(
4432
- reactComponents.ReactModal,
4433
- {
4434
- open: true,
4435
- fullscreen,
4436
- closable: false,
4437
- fullscreenable: false,
4438
- footer: false,
4439
- width: "min(96vw, 1440px)",
4440
- style: { height: fullscreen ? "100%" : "min(88vh, 900px)" },
4441
- bodyStyle: {
4442
- padding: 0,
4443
- overflow: "hidden",
4444
- display: "flex",
4445
- position: "relative"
4446
- },
4447
- onCancel: props.onClose,
4448
- children: source ? /* @__PURE__ */ jsxRuntime.jsx(
4449
- LoadedPrintDesigner,
4450
- {
4451
- ...props,
4452
- source,
4453
- fullscreen,
4454
- onFullscreenChange: setFullscreen
4455
- }
4456
- ) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
4457
- /* @__PURE__ */ jsxRuntime.jsx(
4458
- reactPrintDesign.ReactPrintDesign,
4459
- {
4460
- document: emptyDocument,
4461
- fullscreen,
4462
- onClose: props.onClose,
4463
- style: { flex: 1 }
4464
- }
4465
- ),
4466
- /* @__PURE__ */ jsxRuntime.jsxs(
4467
- "div",
4468
- {
4469
- role: "status",
4470
- style: {
4471
- position: "absolute",
4472
- inset: 0,
4473
- background: "rgba(255,255,255,0.85)",
4474
- display: "flex",
4475
- alignItems: "center",
4476
- justifyContent: "center",
4477
- gap: 12
4478
- },
4479
- children: [
4480
- /* @__PURE__ */ jsxRuntime.jsx("span", { children: error || "\u6B63\u5728\u8BFB\u53D6\u7B2C\u4E00\u9875\u6570\u636E\u2026" }),
4481
- error ? /* @__PURE__ */ jsxRuntime.jsx(reactComponents.ReactButton, { onClick: () => setAttempt((value) => value + 1), children: "\u91CD\u8BD5" }) : null,
4482
- /* @__PURE__ */ jsxRuntime.jsx(reactComponents.ReactButton, { onClick: props.onClose, children: "\u5173\u95ED" })
4483
- ]
4484
- }
4485
- )
4486
- ] })
4487
- }
4488
- );
4489
- }
4490
- function LoadedPrintDesigner(props) {
4491
- const document2 = react.useMemo(
4492
- () => createTableDocument({ ...props.source, rows: [] }),
4493
- [props.source]
4494
- );
4495
- const [boundDocument, setBoundDocument] = react.useState(document2);
4496
- const rows = react.useMemo(() => mapPrintSourceRows(props.source), [props.source]);
4497
- const defaultTemplates = react.useMemo(
4498
- () => [
4499
- document2,
4500
- ...props.printPresets?.map(
4501
- (preset) => createTableDocument({ ...props.source, rows: [] }, preset)
4502
- ) ?? [],
4503
- ...props.printTemplates ?? []
4504
- ],
4505
- [document2, props.printPresets, props.printTemplates, props.source]
4506
- );
4507
- const data = react.useMemo(
4508
- () => createTableData(props.source, boundDocument, rows),
4509
- [props.source, boundDocument, rows]
4510
- );
4511
- const loadPreviewData = react.useCallback(
4512
- async (template, options) => {
4513
- const source = await props.loadSource(options);
4514
- options.signal?.throwIfAborted();
4515
- return createTablePreviewSource(source, template, options);
4516
- },
4517
- [props.loadSource]
4518
- );
4519
- return /* @__PURE__ */ jsxRuntime.jsx(
4520
- reactPrintDesign.ReactPrintDesign,
4521
- {
4522
- document: document2,
4523
- defaultTemplates,
4524
- data,
4525
- dataFormatKey: getPrintSourceFormat(props.source),
4526
- onChange: setBoundDocument,
4527
- storeKey: props.storeKey,
4528
- loadPreviewData,
4529
- fullscreen: props.fullscreen,
4530
- onFullscreenChange: props.onFullscreenChange,
4531
- onClose: props.onClose,
4532
- style: { flex: 1 }
4533
- }
4534
- );
4535
- }
4536
- var PRINT_PROGRESS_MIN_DURATION = 500;
4537
- function createPrintProgress(container, onCancel) {
4538
- const host = container.ownerDocument.createElement("div");
4539
- host.dataset.listTablePrintProgress = "";
4540
- container.append(host);
4541
- const root = client.createRoot(host);
4542
- const startedAt = performance.now();
4543
- let disposed = false;
4544
- let open = true;
4545
- let message = "\u6B63\u5728\u8BFB\u53D6\u6253\u5370\u6570\u636E";
4546
- let percent = 0;
4547
- let failed = false;
4548
- let closeTimer;
4549
- let resolveClose;
4550
- let configuring = false;
4551
- let batchSize = 50;
4552
- let action;
4553
- const confirm = () => {
4554
- const pending = action;
4555
- action = void 0;
4556
- configuring = false;
4557
- render();
4558
- pending?.resolve();
4559
- };
4560
- const dispose = () => {
4561
- if (disposed) return;
4562
- disposed = true;
4563
- clearTimeout(closeTimer);
4564
- root.unmount();
4565
- host.remove();
4566
- resolveClose?.();
4567
- action?.resolve();
4568
- action = void 0;
4569
- };
4570
- const render = () => {
4571
- if (disposed) return;
4572
- reactDom.flushSync(
4573
- () => root.render(
4574
- /* @__PURE__ */ jsxRuntime.jsxs(
4575
- reactComponents.ReactModal,
4576
- {
4577
- open,
4578
- title: configuring ? "\u76F4\u63A5\u6253\u5370\u8BBE\u7F6E" : failed ? "\u6253\u5370\u5931\u8D25" : "\u6B63\u5728\u51C6\u5907\u6253\u5370",
4579
- width: 440,
4580
- centered: true,
4581
- maskClosable: false,
4582
- fullscreenable: false,
4583
- getContainer: container,
4584
- onCancel,
4585
- afterClose: () => queueMicrotask(dispose),
4586
- footer: /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
4587
- /* @__PURE__ */ jsxRuntime.jsx(reactComponents.ReactButton, { onClick: onCancel, children: failed ? "\u5173\u95ED" : "\u53D6\u6D88\u6253\u5370" }),
4588
- action && /* @__PURE__ */ jsxRuntime.jsx(
4589
- reactComponents.ReactButton,
4590
- {
4591
- disabled: configuring && (!batchSize || !Number.isInteger(batchSize) || batchSize < 1),
4592
- onClick: confirm,
4593
- children: action.label
4594
- }
4595
- )
4596
- ] }),
4597
- children: [
4598
- /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", "aria-live": "polite", children: message }),
4599
- configuring ? /* @__PURE__ */ jsxRuntime.jsxs("label", { style: { display: "flex", alignItems: "center", gap: 12 }, children: [
4600
- /* @__PURE__ */ jsxRuntime.jsx("span", { style: { whiteSpace: "nowrap", flexShrink: 0 }, children: "\u6BCF\u6B21\u6253\u5370\u9875\u6570" }),
4601
- /* @__PURE__ */ jsxRuntime.jsx(
4602
- reactComponents.ReactInputNumber,
4603
- {
4604
- "aria-label": "\u6BCF\u6B21\u6253\u5370\u9875\u6570",
4605
- style: { flex: 1, minWidth: 0 },
4606
- min: 1,
4607
- precision: 0,
4608
- value: batchSize,
4609
- onChange: (value) => {
4610
- batchSize = value;
4611
- render();
4612
- }
4613
- }
4614
- )
4615
- ] }) : /* @__PURE__ */ jsxRuntime.jsx(
4616
- reactComponents.ReactProgress,
4617
- {
4618
- percent,
4619
- label: "\u6253\u5370\u51C6\u5907\u8FDB\u5EA6",
4620
- status: failed ? "exception" : "normal"
4621
- }
4622
- )
4623
- ]
4624
- }
4625
- )
4626
- )
4627
- );
4628
- };
4629
- render();
4630
- return {
4631
- host,
4632
- async configure(defaultPages) {
4633
- configuring = true;
4634
- batchSize = Number.isFinite(defaultPages) ? Math.max(1, Math.floor(defaultPages)) : 50;
4635
- message = "\u6309\u6279\u6B21\u751F\u6210\u6253\u5370\u9875\u9762\uFF0C\u907F\u514D\u4E00\u6B21\u52A0\u8F7D\u8FC7\u591A\u5185\u5BB9\u3002";
4636
- await new Promise((resolve) => {
4637
- action = { label: "\u5F00\u59CB\u6253\u5370", resolve };
4638
- render();
4639
- });
4640
- return batchSize ?? 50;
4641
- },
4642
- async continueBatch(firstPage, lastPage) {
4643
- message = `\u7B2C ${firstPage}\u2013${lastPage} \u9875\u7684\u6253\u5370\u7A97\u53E3\u5DF2\u5173\u95ED\uFF0C\u662F\u5426\u7EE7\u7EED\u4E0B\u4E00\u6279\uFF1F`;
4644
- await new Promise((resolve) => {
4645
- action = { label: "\u7EE7\u7EED\u4E0B\u4E00\u6279", resolve };
4646
- render();
4647
- });
4648
- },
4649
- update(text, value) {
4650
- if (percent === value && message === text) return;
4651
- message = text;
4652
- percent = value;
4653
- render();
4654
- },
4655
- error(text) {
4656
- message = text;
4657
- failed = true;
4658
- render();
4659
- },
4660
- close(immediate = false) {
4661
- if (disposed) return Promise.resolve();
4662
- if (immediate) {
4663
- dispose();
4664
- return Promise.resolve();
4665
- }
4666
- return new Promise((resolve) => {
4667
- resolveClose = resolve;
4668
- closeTimer = setTimeout(
4669
- () => {
4670
- open = false;
4671
- render();
4672
- },
4673
- Math.max(
4674
- 0,
4675
- PRINT_PROGRESS_MIN_DURATION - (performance.now() - startedAt)
4676
- )
4677
- );
4678
- });
4679
- }
4680
- };
4681
- }
4682
- var PRINT_ROWS_WORKER_SOURCE = `
4683
- self.onmessage = function(event) {
4684
- try {
4685
- const { keys, rows } = event.data;
4686
- self.postMessage({ rows: rows.map(row => Object.fromEntries(keys.map((key, index) => [key, row[index] ?? ""]))) });
4687
- } catch (error) {
4688
- self.postMessage({ error: String(error) });
4689
- }
4690
- };`;
4691
- async function preparePrintRows(source, options = {}) {
4692
- const keys = source.columns.map((column) => column.key);
4693
- let worker;
4694
- let url;
4695
- try {
4696
- options.signal?.throwIfAborted();
4697
- url = URL.createObjectURL(
4698
- new Blob([PRINT_ROWS_WORKER_SOURCE], { type: "text/javascript" })
4699
- );
4700
- worker = new Worker(url);
4701
- const result = new Array(source.rows.length);
4702
- for (let offset = 0; offset < source.rows.length; offset += 2e3) {
4703
- options.signal?.throwIfAborted();
4704
- const rows = await new Promise(
4705
- (resolve, reject) => {
4706
- const cleanup = () => {
4707
- clearTimeout(timeout);
4708
- options.signal?.removeEventListener("abort", abort);
4709
- };
4710
- const fail = (error) => {
4711
- cleanup();
4712
- reject(error);
4713
- };
4714
- const abort = () => fail(options.signal?.reason);
4715
- const timeout = setTimeout(
4716
- () => fail(new Error("\u6253\u5370 Worker \u54CD\u5E94\u8D85\u65F6")),
4717
- 15e3
4718
- );
4719
- options.signal?.addEventListener("abort", abort, { once: true });
4720
- worker.onerror = () => fail(new Error("\u6253\u5370 Worker \u6267\u884C\u5931\u8D25"));
4721
- worker.onmessageerror = () => fail(new Error("\u6253\u5370 Worker \u6570\u636E\u4F20\u8F93\u5931\u8D25"));
4722
- worker.onmessage = (event) => {
4723
- cleanup();
4724
- if (event.data.error) reject(new Error(event.data.error));
4725
- else resolve(event.data.rows);
4726
- };
4727
- try {
4728
- worker.postMessage({
4729
- keys,
4730
- rows: source.rows.slice(offset, offset + 2e3)
4731
- });
4732
- } catch (error) {
4733
- fail(error);
4734
- }
4735
- }
4736
- );
4737
- for (let index = 0; index < rows.length; index++)
4738
- result[offset + index] = rows[index];
4739
- options.onProgress?.(
4740
- Math.min(offset + rows.length, source.rows.length),
4741
- source.rows.length
4742
- );
4743
- }
4744
- return result;
4745
- } catch {
4746
- worker?.terminate();
4747
- worker = void 0;
4748
- options.signal?.throwIfAborted();
4749
- return await utils.mapInBatches(
4750
- source.rows.length,
4751
- (index) => Object.fromEntries(
4752
- keys.map((key, column) => [key, source.rows[index][column] ?? ""])
4753
- ),
4754
- options
4755
- );
4756
- } finally {
4757
- worker?.terminate();
4758
- if (url) URL.revokeObjectURL(url);
4124
+ function defineReactListTablePrintIntegration(integration) {
4125
+ if (!integration.Host || typeof integration.createMenu !== "function" || typeof integration.readTemplates !== "function" || typeof integration.createTemplateChoices !== "function")
4126
+ throw new Error("\u8868\u683C\u6253\u5370\u96C6\u6210\u7F3A\u5C11\u5BBF\u4E3B\u83DC\u5355\u3001\u6A21\u677F\u6216\u754C\u9762\u80FD\u529B\u3002");
4127
+ if (!integration.componentRegistry.get("table"))
4128
+ throw new Error("\u8868\u683C\u6253\u5370\u96C6\u6210\u7F3A\u5C11 table \u539F\u751F\u7EC4\u4EF6\u3002");
4129
+ for (const factory of integration.editor.componentFactories.list()) {
4130
+ if (!integration.componentRegistry.get(factory.type))
4131
+ throw new Error(`\u6253\u5370\u8BBE\u8BA1\u7EC4\u4EF6\u7F3A\u5C11\u539F\u751F\u7ED8\u5236\u80FD\u529B\uFF1A${factory.type}`);
4759
4132
  }
4133
+ return Object.freeze(integration);
4760
4134
  }
4761
-
4762
- // src/features/print/direct-print.ts
4763
- async function runDirectPrint(container, loadSource, resolveTemplate = (source) => createTableDocument({ ...source, rows: [] }), validate, defaultPagesPerBatch = 50) {
4764
- const controller = new AbortController();
4765
- const { signal } = controller;
4766
- const ownerDocument = container.ownerDocument;
4767
- const previousFocus = ownerDocument.activeElement;
4768
- let frame;
4769
- const progress = createPrintProgress(container, () => {
4770
- controller.abort();
4771
- void cleanup(true);
4772
- });
4773
- const cleanup = async (immediate = false) => {
4774
- frame?.remove();
4775
- await progress.close(immediate);
4776
- if (previousFocus?.isConnected)
4777
- previousFocus.focus({ preventScroll: true });
4778
- };
4779
- const timer = setInterval(() => {
4780
- if (!progress.host.isConnected) controller.abort();
4781
- }, 250);
4782
- let maximum = 0;
4783
- const report = (text, value) => {
4784
- signal.throwIfAborted();
4785
- maximum = Math.max(maximum, Math.floor(value));
4786
- progress.update(text, maximum);
4787
- };
4788
- try {
4789
- const pagesPerBatch = await progress.configure(defaultPagesPerBatch);
4790
- signal.throwIfAborted();
4791
- report("\u6B63\u5728\u8BFB\u53D6\u6253\u5370\u6570\u636E", 0);
4792
- await new Promise((resolve) => setTimeout(resolve, 0));
4793
- const source = await loadSource({
4794
- signal,
4795
- onProgress: (done, total) => report(
4796
- `\u6B63\u5728\u8BFB\u53D6\u6253\u5370\u6570\u636E ${done}/${total}`,
4797
- total ? done / total * 30 : 30
4798
- )
4799
- });
4800
- report("\u6B63\u5728\u8F6C\u6362\u6253\u5370\u6570\u636E", 30);
4801
- const rows = await preparePrintRows(source, {
4802
- signal,
4803
- onProgress: (done, total) => report(
4804
- `\u6B63\u5728\u8F6C\u6362\u6253\u5370\u6570\u636E ${done}/${total}`,
4805
- 30 + (total ? done / total : 1) * 25
4806
- )
4807
- });
4808
- const template = resolveTemplate(source);
4809
- validate?.(source, template, createTableData(source, template, rows));
4810
- report("\u6B63\u5728\u751F\u6210\u5206\u9875", 55);
4811
- const prepared = await createTablePreviewSource(
4812
- source,
4813
- template,
4814
- {
4815
- signal,
4816
- onProgress: (done, total) => report(
4817
- `\u6B63\u5728\u751F\u6210\u5206\u9875 ${done}/${total}`,
4818
- 55 + (total ? done / total : 1) * 15
4819
- )
4820
- },
4821
- rows
4822
- );
4823
- report("\u6B63\u5728\u751F\u6210\u6253\u5370\u9875\u9762", 70);
4824
- for await (const batch of printDesign.transformPrintDesignToHtmlBatches(
4825
- prepared.document,
4826
- {
4827
- pagesPerBatch,
4828
- data: prepared.data,
4829
- signal,
4830
- onProgress: (value) => report("\u6B63\u5728\u751F\u6210\u6253\u5370\u9875\u9762", 70 + value * 29)
4831
- }
4832
- )) {
4833
- report(`\u6B63\u5728\u6253\u5370\u7B2C ${batch.firstPage}\u2013${batch.lastPage} \u9875`, maximum);
4834
- await new Promise((resolve) => setTimeout(resolve, 0));
4835
- signal.throwIfAborted();
4836
- frame = ownerDocument.createElement("iframe");
4837
- frame.title = "\u8868\u683C\u6253\u5370";
4838
- frame.setAttribute("aria-hidden", "true");
4839
- frame.style.cssText = "position:fixed;left:-10000px;top:0;width:1px;height:1px;border:0";
4840
- container.append(frame);
4841
- const printWindow = frame.contentWindow;
4842
- if (!printWindow) throw new Error("\u65E0\u6CD5\u521B\u5EFA\u6253\u5370\u9875\u9762");
4843
- await new Promise((resolve, reject) => {
4844
- const abort = () => {
4845
- dispose();
4846
- reject(signal.reason);
4847
- };
4848
- const dispose = () => {
4849
- frame?.removeEventListener("load", loaded);
4850
- signal.removeEventListener("abort", abort);
4851
- };
4852
- const loaded = () => {
4853
- dispose();
4854
- resolve();
4855
- };
4856
- frame.addEventListener("load", loaded, { once: true });
4857
- signal.addEventListener("abort", abort, { once: true });
4858
- printWindow.document.open();
4859
- printWindow.document.write(batch.html);
4860
- printWindow.document.close();
4861
- });
4862
- await Promise.all([
4863
- ...Array.from(
4864
- printWindow.document.images,
4865
- (image) => image.decode?.().catch(() => void 0)
4866
- ),
4867
- printWindow.document.fonts?.ready
4868
- ]);
4869
- signal.throwIfAborted();
4870
- await new Promise((resolve, reject) => {
4871
- const dispose = () => {
4872
- printWindow.removeEventListener("afterprint", finished);
4873
- signal.removeEventListener("abort", aborted);
4874
- };
4875
- const finished = () => {
4876
- dispose();
4877
- resolve();
4878
- };
4879
- const aborted = () => {
4880
- dispose();
4881
- reject(signal.reason);
4882
- };
4883
- printWindow.addEventListener("afterprint", finished, { once: true });
4884
- signal.addEventListener("abort", aborted, { once: true });
4885
- try {
4886
- printWindow.focus();
4887
- printWindow.print();
4888
- } catch (error) {
4889
- dispose();
4890
- reject(error);
4891
- }
4892
- });
4893
- frame.remove();
4894
- frame = void 0;
4895
- if (batch.hasMore) {
4896
- await progress.continueBatch(batch.firstPage, batch.lastPage);
4897
- signal.throwIfAborted();
4898
- report("\u6B63\u5728\u751F\u6210\u4E0B\u4E00\u6279\u6253\u5370\u9875\u9762", maximum);
4899
- }
4900
- }
4901
- report("\u6253\u5370\u7A97\u53E3\u5DF2\u5173\u95ED", 100);
4902
- await cleanup();
4903
- } catch (error) {
4904
- frame?.remove();
4905
- if (!signal.aborted) {
4906
- progress.error(
4907
- `\u6253\u5370\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`
4908
- );
4909
- } else await cleanup(true);
4910
- } finally {
4911
- clearInterval(timer);
4912
- }
4135
+ var PrintIntegrationContext = react.createContext(null);
4136
+ function ReactListTablePrintProvider(props) {
4137
+ if (props.integration)
4138
+ defineReactListTablePrintIntegration(props.integration);
4139
+ return /* @__PURE__ */ jsxRuntime.jsx(PrintIntegrationContext.Provider, { value: props.integration, children: props.children });
4140
+ }
4141
+ function useReactListTablePrintIntegration() {
4142
+ return react.useContext(PrintIntegrationContext);
4913
4143
  }
4914
4144
 
4915
4145
  // src/features/editor/utils.ts
@@ -6756,6 +5986,7 @@ function retainEqualQueryOption(previous, next) {
6756
5986
  }
6757
5987
  function ReactListTableInner(props, ref) {
6758
5988
  props = useStableTableProps(props);
5989
+ const printIntegration = useReactListTablePrintIntegration();
6759
5990
  const {
6760
5991
  className,
6761
5992
  style,
@@ -7021,51 +6252,37 @@ function ReactListTableInner(props, ref) {
7021
6252
  closeDangerConfirmRequest
7022
6253
  } = useReactListTableState(options);
7023
6254
  const hasPagination = paginationConfig != null;
7024
- const [printRequest, setPrintRequest] = react.useState(null);
7025
- const [savedPrintTemplates, setSavedPrintTemplates] = react.useState([]);
7026
- const printStoreKey = storageKey ? `list:${storageKey}` : void 0;
7027
- const printMenuOpen = Boolean(headerContextMenuRequest);
7028
- react.useEffect(() => {
7029
- if (!printMenuOpen || !printStoreKey) {
7030
- setSavedPrintTemplates([]);
7031
- return;
7032
- }
7033
- let disposed = false;
7034
- void reactPrintDesign.readPrintDesignTemplates(printStoreKey).then((versions) => {
7035
- if (!disposed) setSavedPrintTemplates(versions);
7036
- }).catch(() => {
7037
- if (!disposed) setSavedPrintTemplates([]);
7038
- });
7039
- return () => {
7040
- disposed = true;
7041
- };
7042
- }, [printMenuOpen, printStoreKey]);
7043
- const latestSavedTemplates = [
7044
- ...new Set(savedPrintTemplates.map((item) => item.templateId))
7045
- ].map((templateId) => {
7046
- const versions = savedPrintTemplates.filter(
7047
- (item) => item.templateId === templateId
7048
- );
7049
- return versions[versions.length - 1];
7050
- });
7051
- const printTemplateChoices = [
7052
- { key: "base", label: "\u8868\u683C\u6253\u5370\u6A21\u677F" },
7053
- ...props.printPresets?.map((item, index) => ({
7054
- key: `preset:${index}`,
7055
- label: item.name
7056
- })) ?? [],
7057
- ...props.printTemplates?.map((item, index) => ({
7058
- key: `document:${index}`,
7059
- label: item.name
7060
- })) ?? [],
7061
- ...latestSavedTemplates.map((item) => ({
7062
- key: `saved:${item.id}`,
7063
- label: `${item.document.name} (v${item.version})`
7064
- }))
7065
- ];
7066
6255
  const [cacheConfigOpen, setCacheConfigOpen] = react.useState(false);
7067
6256
  const paginationLayout = resolveReactListTablePaginationLayout(resolvedRowHeight);
7068
6257
  const portalContainer = resolveFullscreenPortalContainer(shellRef.current);
6258
+ const PrintHost = printIntegration?.Host;
6259
+ const contextMenuRequest = headerContextMenuRequest ? {
6260
+ ...headerContextMenuRequest,
6261
+ scrollbar: effectiveScrollbar,
6262
+ onChangeScrollbar: (value) => {
6263
+ headerContextMenuRequest.onChangeScrollbar?.(value);
6264
+ setScrollbarOverride(value);
6265
+ if (reactComponents.getSharedScrollbarSettings().shared)
6266
+ reactComponents.setSharedScrollbarSettings({ shared: true, value });
6267
+ },
6268
+ onResetScrollbar: () => {
6269
+ headerContextMenuRequest.onResetScrollbar?.();
6270
+ setScrollbarOverride(null);
6271
+ if (reactComponents.getSharedScrollbarSettings().shared)
6272
+ reactComponents.setSharedScrollbarSettings({ shared: true, value: {} });
6273
+ }
6274
+ } : null;
6275
+ const renderContextMenu = (hostMenu) => /* @__PURE__ */ jsxRuntime.jsx(
6276
+ ReactTableContextMenuView,
6277
+ {
6278
+ hostMenu,
6279
+ onViewCacheConfig: () => {
6280
+ headerContextMenuRequest?.onClose();
6281
+ setCacheConfigOpen(true);
6282
+ },
6283
+ request: contextMenuRequest
6284
+ }
6285
+ );
7069
6286
  react.useImperativeHandle(
7070
6287
  ref,
7071
6288
  () => ({
@@ -7254,95 +6471,21 @@ function ReactListTableInner(props, ref) {
7254
6471
  portalContainer
7255
6472
  ) : null,
7256
6473
  reactDom.createPortal(
7257
- /* @__PURE__ */ jsxRuntime.jsx(
7258
- ReactTableContextMenuView,
6474
+ PrintHost && printIntegration ? /* @__PURE__ */ jsxRuntime.jsx(
6475
+ PrintHost,
7259
6476
  {
7260
- printTemplates: printTemplateChoices,
7261
- onPrintTemplate: (key) => {
7262
- const request = headerContextMenuRequest;
7263
- if (!request?.onGetPrintData) return;
7264
- request.onClose();
7265
- void runDirectPrint(
7266
- portalContainer,
7267
- request.onGetPrintData,
7268
- (source) => {
7269
- const document2 = key.startsWith("saved:") ? savedPrintTemplates.find((item) => item.id === key.slice(6))?.document : key.startsWith("preset:") ? createTableDocument(
7270
- { ...source, rows: [] },
7271
- props.printPresets?.[Number(key.slice(7))]
7272
- ) : key.startsWith("document:") ? props.printTemplates?.[Number(key.slice(9))] : createTableDocument({ ...source, rows: [] });
7273
- if (!document2) throw new Error("\u627E\u4E0D\u5230\u6253\u5370\u6A21\u677F");
7274
- return document2;
7275
- },
7276
- (source, document2, data) => {
7277
- if (!reactPrintDesign.isPrintDesignDocumentCompatible(document2, data))
7278
- throw new Error("\u6253\u5370\u6A21\u677F\u5DF2\u5931\u6548");
7279
- if (key.startsWith("saved:") && reactPrintDesign.isPrintDesignTemplateInvalid(
7280
- savedPrintTemplates.find(
7281
- (item) => item.id === key.slice(6)
7282
- ),
7283
- getPrintSourceFormat(source),
7284
- data
7285
- ))
7286
- throw new Error("\u6253\u5370\u6A21\u677F\u5DF2\u5931\u6548");
7287
- },
7288
- props.directPrintPagesPerBatch
7289
- );
7290
- },
7291
- onViewCacheConfig: () => {
7292
- headerContextMenuRequest?.onClose();
7293
- setCacheConfigOpen(true);
7294
- },
7295
- onPrint: () => {
7296
- const getPrintData = headerContextMenuRequest?.onGetPrintData;
7297
- if (!getPrintData) return;
7298
- setPrintRequest({ loadSource: getPrintData });
7299
- headerContextMenuRequest?.onClose();
7300
- },
7301
- onDirectPrint: () => {
7302
- const request = headerContextMenuRequest;
7303
- if (!request?.onGetPrintData) return;
7304
- request.onClose();
7305
- void runDirectPrint(
7306
- portalContainer,
7307
- request.onGetPrintData,
7308
- void 0,
7309
- void 0,
7310
- props.directPrintPagesPerBatch
7311
- );
7312
- },
7313
- request: headerContextMenuRequest ? {
7314
- ...headerContextMenuRequest,
7315
- scrollbar: effectiveScrollbar,
7316
- onChangeScrollbar: (value) => {
7317
- headerContextMenuRequest.onChangeScrollbar?.(value);
7318
- setScrollbarOverride(value);
7319
- if (reactComponents.getSharedScrollbarSettings().shared)
7320
- reactComponents.setSharedScrollbarSettings({ shared: true, value });
7321
- },
7322
- onResetScrollbar: () => {
7323
- headerContextMenuRequest.onResetScrollbar?.();
7324
- setScrollbarOverride(null);
7325
- if (reactComponents.getSharedScrollbarSettings().shared)
7326
- reactComponents.setSharedScrollbarSettings({ shared: true, value: {} });
7327
- }
7328
- } : null
7329
- }
7330
- ),
7331
- portalContainer
7332
- ),
7333
- printRequest ? reactDom.createPortal(
7334
- /* @__PURE__ */ jsxRuntime.jsx(
7335
- ReactListTablePrintDesignDialog,
7336
- {
7337
- loadSource: printRequest.loadSource,
6477
+ integration: printIntegration,
6478
+ request: headerContextMenuRequest,
6479
+ portalContainer,
7338
6480
  storeKey: storageKey ? `list:${storageKey}` : void 0,
7339
- printPresets: props.printPresets,
7340
- printTemplates: props.printTemplates,
7341
- onClose: () => setPrintRequest(null)
6481
+ presets: props.printPresets,
6482
+ templates: props.printTemplates,
6483
+ pagesPerBatch: props.directPrintPagesPerBatch,
6484
+ children: renderContextMenu
7342
6485
  }
7343
- ),
6486
+ ) : renderContextMenu(null),
7344
6487
  portalContainer
7345
- ) : null,
6488
+ ),
7346
6489
  cacheConfigOpen && storageKey ? reactDom.createPortal(
7347
6490
  /* @__PURE__ */ jsxRuntime.jsx(
7348
6491
  ReactListTableCacheConfigDialog,
@@ -7424,3 +6567,5 @@ Object.defineProperty(exports, "getListTableStoredPageSize", {
7424
6567
  exports.ReactListTable = ReactListTable;
7425
6568
  exports.ReactListTableDebugProvider = ReactListTableDebugProvider;
7426
6569
  exports.ReactListTableExportNameDialog = ReactListTableExportNameDialog;
6570
+ exports.ReactListTablePrintProvider = ReactListTablePrintProvider;
6571
+ exports.defineReactListTablePrintIntegration = defineReactListTablePrintIntegration;