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