@canvas-components/print-design-plugin 0.1.6 → 0.1.8

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/react.js CHANGED
@@ -5,8 +5,8 @@ import { drawQrCodeToCanvas, encodeQrCodeMatrix, exportQrCodeToSvg, buildQrCodeC
5
5
  import { drawCanvasChartToCanvas, exportCanvasChartToSvg } from '@canvas-components/chart';
6
6
  import { getIconDefinition } from '@canvas-components/icons';
7
7
  import { roundPreciseNumber } from '@canvas-components/utils';
8
- import { createElement, useState, useEffect, useRef } from 'react';
9
- import { ReactFontSizeOutlined, ReactAlignLeftOutlined, ReactAlignCenterOutlined, ReactAlignRightOutlined, ReactMenuOutlined, ReactColumnWidthOutlined, ReactVerticalAlignTopOutlined, ReactVerticalAlignMiddleOutlined, ReactVerticalAlignBottomOutlined, ReactCalendarOutlined, ReactDollarOutlined, ReactNumberOutlined, ReactHighlightOutlined, ReactLineOutlined, ReactTableOutlined, ReactFileImageOutlined, ReactBarcodeOutlined, ReactQrcodeOutlined, ReactBarChartOutlined, ReactInputNumber, ReactButton, ReactColorPicker, ReactPlusOutlined, ReactInput, ReactCollapsePanel, ReactSelect, ReactReloadOutlined, ReactBoldOutlined, ReactItalicOutlined, ReactEyeOutlined, ReactEyeInvisibleOutlined, ReactDeleteOutlined, ReactPopup, ReactBorderLeftOutlined, ReactBorderBottomOutlined, ReactBorderRightOutlined, ReactBorderTopOutlined, ReactBorderInnerOutlined } from '@canvas-components/react-components';
8
+ import { createElement, useState, useEffect, useRef, useMemo } from 'react';
9
+ import { ReactFontSizeOutlined, ReactAlignLeftOutlined, ReactAlignCenterOutlined, ReactAlignRightOutlined, ReactMenuOutlined, ReactColumnWidthOutlined, ReactVerticalAlignTopOutlined, ReactVerticalAlignMiddleOutlined, ReactVerticalAlignBottomOutlined, ReactCalendarOutlined, ReactDollarOutlined, ReactNumberOutlined, ReactHighlightOutlined, ReactLineOutlined, ReactTableOutlined, ReactFileImageOutlined, ReactBarcodeOutlined, ReactQrcodeOutlined, ReactBarChartOutlined, ReactInputNumber, ReactButton, ReactColorPicker, ReactPlusOutlined, ReactInput, ReactCollapsePanel, ReactSelect, ReactReloadOutlined, ReactBoldOutlined, ReactItalicOutlined, ReactEyeOutlined, ReactEyeInvisibleOutlined, ReactDeleteOutlined, ReactPopup, ReactBorderLeftOutlined, ReactBorderBottomOutlined, ReactBorderRightOutlined, ReactBorderTopOutlined, ReactBorderInnerOutlined, ReactModal, ReactTag, ReactMoreOutlined } from '@canvas-components/react-components';
10
10
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
11
11
 
12
12
  // src/react.ts
@@ -996,13 +996,45 @@ function validateListTemplateData(element, data) {
996
996
  );
997
997
  }
998
998
 
999
+ // src/plugins/list/interaction/commands.ts
1000
+ var listCommands = {
1001
+ execute(element, command, payload) {
1002
+ if (element.locked || !payload || typeof payload !== "object") return;
1003
+ const args = payload;
1004
+ const index = args.index;
1005
+ if (!Number.isInteger(index)) return;
1006
+ const at = index;
1007
+ const items = [...element.items];
1008
+ if (command === "remove-item") {
1009
+ if (at < 0 || at >= items.length) return;
1010
+ items.splice(at, 1);
1011
+ } else if (command === "insert-item") {
1012
+ if (at < 0 || at > items.length || typeof args.text !== "string") return;
1013
+ items.splice(at, 0, { text: args.text, checked: false });
1014
+ } else if (command === "update-item") {
1015
+ if (at < 0 || at >= items.length) return;
1016
+ if (args.text !== void 0 && typeof args.text !== "string") return;
1017
+ if (args.checked !== void 0 && typeof args.checked !== "boolean")
1018
+ return;
1019
+ items[at] = {
1020
+ ...items[at],
1021
+ ...args.text === void 0 ? {} : { text: args.text },
1022
+ ...args.checked === void 0 ? {} : { checked: args.checked }
1023
+ };
1024
+ } else return;
1025
+ const next = { ...element, items };
1026
+ return validateListElement(next) ? next : void 0;
1027
+ }
1028
+ };
1029
+
999
1030
  // src/plugins/list/native.ts
1000
1031
  var listNativePlugin = defineNativePlugin(
1001
1032
  "list",
1002
- "0.1.8",
1033
+ "0.1.9",
1003
1034
  definePrintDesignPluginRenderer({
1004
1035
  type: "list",
1005
1036
  validate: validateListElement,
1037
+ commands: listCommands,
1006
1038
  bindingInfo: listBindingInfo,
1007
1039
  validateTemplateData: validateListTemplateData,
1008
1040
  drawCanvas: drawListElement,
@@ -2650,16 +2682,51 @@ function pointToSegmentDistance(point, a, b) {
2650
2682
  return Math.hypot(point.x - a.x - t * dx, point.y - a.y - t * dy);
2651
2683
  }
2652
2684
 
2685
+ // src/plugins/shape/interaction/commands.ts
2686
+ var validPoints = (value) => Array.isArray(value) && value.every(
2687
+ (point) => point && typeof point === "object" && Number.isFinite(point.x) && Number.isFinite(point.y)
2688
+ );
2689
+ var shapeCommands = {
2690
+ execute(element, command, payload) {
2691
+ if (element.locked || !payload || typeof payload !== "object") return;
2692
+ const args = payload;
2693
+ if (!validPoints(args.points)) return;
2694
+ const points = args.points;
2695
+ let next;
2696
+ if (command === "set-polygon-points") {
2697
+ if (!["triangle", "polygon", "star"].includes(element.shape) || points.length < 3)
2698
+ return;
2699
+ next = { ...element, polygonPoints: points };
2700
+ } else if (command === "set-curve-points") {
2701
+ if (!["curve-quadratic", "curve-cubic", "curve-multi"].includes(
2702
+ element.shape
2703
+ ) || points.length < 2)
2704
+ return;
2705
+ next = { ...element, curvePoints: points };
2706
+ } else if (command === "set-path-points") {
2707
+ if (element.shape !== "curve-path") return;
2708
+ if (args.closed !== void 0 && typeof args.closed !== "boolean") return;
2709
+ next = {
2710
+ ...element,
2711
+ pathPoints: points,
2712
+ ...args.closed === void 0 ? {} : { pathClosed: args.closed }
2713
+ };
2714
+ } else return;
2715
+ return validateShapeElement(next) ? next : void 0;
2716
+ }
2717
+ };
2718
+
2653
2719
  // src/plugins/shape/native.ts
2654
2720
  var shapeNativePlugin = defineNativePlugin(
2655
2721
  "shape",
2656
- "0.1.20",
2722
+ "0.1.21",
2657
2723
  definePrintDesignPluginRenderer({
2658
2724
  type: "shape",
2659
2725
  dataFields: shapeDataFields,
2660
2726
  bindingInfo: (element) => registeredFieldBindingInfo(element, shapeDataFields),
2661
2727
  validateTemplateData: (element, data) => validateRegisteredFieldBindings(element, shapeDataFields, data),
2662
2728
  validate: validateShapeElement,
2729
+ commands: shapeCommands,
2663
2730
  drawCanvas: drawShapeElement,
2664
2731
  renderHtml: (element, context) => renderShapeHtml(element, context.data),
2665
2732
  hitTest: hitShape,
@@ -3001,13 +3068,42 @@ var brushPointerStroke = {
3001
3068
  }
3002
3069
  };
3003
3070
 
3071
+ // src/plugins/brush/interaction/commands.ts
3072
+ var brushCommands = {
3073
+ execute(element, command, payload) {
3074
+ if (element.locked || !payload || typeof payload !== "object") return;
3075
+ const args = payload;
3076
+ if (command === "append-stroke") {
3077
+ if (!Array.isArray(args.points) || args.points.length < 2) return;
3078
+ const next2 = {
3079
+ ...element,
3080
+ strokes: [
3081
+ ...element.strokes,
3082
+ args.points
3083
+ ]
3084
+ };
3085
+ return validateBrushElement(next2) ? next2 : void 0;
3086
+ }
3087
+ if (command !== "remove-stroke" || !Number.isInteger(args.index)) return;
3088
+ const index = args.index;
3089
+ if (index < 0 || index >= element.strokes.length) return;
3090
+ const next = {
3091
+ ...element,
3092
+ strokes: element.strokes.filter((_, at) => at !== index),
3093
+ strokeStyles: element.strokeStyles?.filter((_, at) => at !== index)
3094
+ };
3095
+ return validateBrushElement(next) ? next : void 0;
3096
+ }
3097
+ };
3098
+
3004
3099
  // src/plugins/brush/native.ts
3005
3100
  var brushNativePlugin = defineNativePlugin(
3006
3101
  "brush",
3007
- "0.1.4",
3102
+ "0.1.5",
3008
3103
  definePrintDesignPluginRenderer({
3009
3104
  type: "brush",
3010
3105
  validate: validateBrushElement,
3106
+ commands: brushCommands,
3011
3107
  drawCanvas: drawBrushElement,
3012
3108
  renderHtml: (element) => renderBrushHtml(element),
3013
3109
  hitTest: hitBrush,
@@ -4003,6 +4099,46 @@ function validateConnectorElement(value) {
4003
4099
  const validPoint = (point) => !!point && Number.isFinite(point.x) && Number.isFinite(point.y);
4004
4100
  return element.type === "connector" && (element.lineType === void 0 || ["straight", "curve", "polyline"].includes(element.lineType)) && (element.polylinePoints === void 0 || Array.isArray(element.polylinePoints) && element.polylinePoints.every(validPoint)) && (element.strokeWidth === void 0 || Number.isFinite(element.strokeWidth) && element.strokeWidth >= 0) && (element.textPosition === void 0 || Number.isFinite(element.textPosition) && element.textPosition >= 0 && element.textPosition <= 1);
4005
4101
  }
4102
+
4103
+ // src/plugins/connector/interaction/commands.ts
4104
+ var validEndpoint = (value) => {
4105
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4106
+ const endpoint3 = value;
4107
+ return (endpoint3.elementId === void 0 || typeof endpoint3.elementId === "string") && (endpoint3.anchor === void 0 || typeof endpoint3.anchor === "string" && ([
4108
+ "auto",
4109
+ "top",
4110
+ "right",
4111
+ "bottom",
4112
+ "left",
4113
+ "top-left",
4114
+ "top-right",
4115
+ "bottom-right",
4116
+ "bottom-left"
4117
+ ].includes(endpoint3.anchor) || /^(edge|vertex):\d+$/.test(endpoint3.anchor)));
4118
+ };
4119
+ var connectorCommands = {
4120
+ execute(element, command, payload) {
4121
+ if (element.locked || !payload || typeof payload !== "object") return;
4122
+ const args = payload;
4123
+ if (command === "set-endpoint") {
4124
+ if (args.side !== "start" && args.side !== "end") return;
4125
+ if (!validEndpoint(args.endpoint)) return;
4126
+ const next2 = { ...element, [args.side]: args.endpoint };
4127
+ return validateConnectorElement(next2) ? next2 : void 0;
4128
+ }
4129
+ if (command !== "set-waypoints" || element.lineType !== "polyline")
4130
+ return;
4131
+ if (!Array.isArray(args.points) || !args.points.every(
4132
+ (point) => point && typeof point === "object" && Number.isFinite(point.x) && Number.isFinite(point.y)
4133
+ ))
4134
+ return;
4135
+ const next = {
4136
+ ...element,
4137
+ polylinePoints: args.points
4138
+ };
4139
+ return validateConnectorElement(next) ? next : void 0;
4140
+ }
4141
+ };
4006
4142
  var CONNECTOR_EXPRESSION = /\{\{\s*([\w.[\]-]+)(?:\|(?:date|dateSlash))?\s*\}\}/g;
4007
4143
  function labelPaths(element) {
4008
4144
  return [...(element.text ?? "").matchAll(CONNECTOR_EXPRESSION)].map(
@@ -4023,10 +4159,11 @@ function validateConnectorTemplateData(element, data) {
4023
4159
  // src/plugins/connector/native.ts
4024
4160
  var connectorNativePlugin = defineNativePlugin(
4025
4161
  "connector",
4026
- "0.1.31",
4162
+ "0.1.32",
4027
4163
  definePrintDesignPluginRenderer({
4028
4164
  type: "connector",
4029
4165
  validate: validateConnectorElement,
4166
+ commands: connectorCommands,
4030
4167
  bindingInfo: connectorBindingInfo,
4031
4168
  validateTemplateData: validateConnectorTemplateData,
4032
4169
  allowSignedSize: true,
@@ -4615,7 +4752,7 @@ function resolveGridCells(element, data = {}) {
4615
4752
  const background = color(element.backgroundColor) ?? "transparent";
4616
4753
  const selectedBackground = color(element.selectedBackgroundColor);
4617
4754
  const cache = /* @__PURE__ */ new Map();
4618
- const read = (path, index) => {
4755
+ const read2 = (path, index) => {
4619
4756
  if (!path?.trim()) return void 0;
4620
4757
  if (!cache.has(path))
4621
4758
  cache.set(path, resolvePrintDesignDataPath(data, path));
@@ -4635,7 +4772,7 @@ function resolveGridCells(element, data = {}) {
4635
4772
  const cell = element.cells?.[index];
4636
4773
  const contentPath = cell?.contentPath?.trim() || element.contentPath;
4637
4774
  const content = (cell?.contentMode !== "static" && (cell?.contentMode === "binding" || !!element.contentPath) ? marker(
4638
- read(contentPath, index),
4775
+ read2(contentPath, index),
4639
4776
  cell?.content && cell.content !== "none" ? cell.content : element.paintMark ?? "x"
4640
4777
  ) : void 0) ?? cell?.content ?? "none";
4641
4778
  return {
@@ -4914,13 +5051,68 @@ function gridDebugRegions(element, context, hitElement = element) {
4914
5051
  return [...cells, ...loops, ...columnLoops];
4915
5052
  }
4916
5053
 
5054
+ // src/plugins/grid/interaction/commands.ts
5055
+ function executeGridCommand(element, command, payload, validate) {
5056
+ if (element.locked || !payload || typeof payload !== "object") return;
5057
+ const args = payload;
5058
+ if (command === "resize-grid") {
5059
+ const rows = args.rows;
5060
+ const columns = args.columns;
5061
+ if (!Number.isInteger(rows) || !Number.isInteger(columns)) return;
5062
+ if (rows < 1 || rows > 50 || columns < 1 || columns > 50)
5063
+ return;
5064
+ const cells2 = Array.from(
5065
+ { length: rows * columns },
5066
+ (_, index2) => {
5067
+ const row = Math.floor(index2 / columns);
5068
+ const column = index2 % columns;
5069
+ return element.cells?.[row * element.columns + column] ?? {};
5070
+ }
5071
+ );
5072
+ const next2 = {
5073
+ ...element,
5074
+ rows,
5075
+ columns,
5076
+ cells: cells2
5077
+ };
5078
+ return validate(next2) ? next2 : void 0;
5079
+ }
5080
+ if (command !== "set-cell") return;
5081
+ const rowIndex = args.rowIndex;
5082
+ const columnIndex = args.columnIndex;
5083
+ if (!Number.isInteger(rowIndex) || !Number.isInteger(columnIndex)) return;
5084
+ if (rowIndex < 0 || rowIndex >= element.rows || columnIndex < 0 || columnIndex >= element.columns)
5085
+ return;
5086
+ const cell = args.cell;
5087
+ if (!cell || typeof cell !== "object" || Array.isArray(cell)) return;
5088
+ const index = rowIndex * element.columns + columnIndex;
5089
+ const cells = Array.from(
5090
+ { length: element.rows * element.columns },
5091
+ (_, at) => ({ ...element.cells?.[at] })
5092
+ );
5093
+ cells[index] = { ...cells[index], ...cell };
5094
+ const next = { ...element, cells };
5095
+ return validate(next) ? next : void 0;
5096
+ }
5097
+ var gridCommands = {
5098
+ execute(element, command, payload) {
5099
+ return executeGridCommand(
5100
+ element,
5101
+ command,
5102
+ payload,
5103
+ (value) => !!value && typeof value === "object" && value.type === "grid" && validateGridSettings(value)
5104
+ );
5105
+ }
5106
+ };
5107
+
4917
5108
  // src/plugins/grid/native.ts
4918
5109
  var gridNativePlugin = defineNativePlugin(
4919
5110
  "grid",
4920
- "0.1.15",
5111
+ "0.1.16",
4921
5112
  definePrintDesignPluginRenderer({
4922
5113
  type: "grid",
4923
5114
  validate: validateGridElement,
5115
+ commands: gridCommands,
4924
5116
  validateTemplateData: validateGridTemplateData,
4925
5117
  bindingInfo: getGridBindingInfo,
4926
5118
  drawCanvas: drawGridElement,
@@ -5231,10 +5423,18 @@ function coordinateDebugRegions(element, context) {
5231
5423
  // src/plugins/coordinate/native.ts
5232
5424
  var coordinateNativePlugin = defineNativePlugin(
5233
5425
  "coordinate",
5234
- "0.1.15",
5426
+ "0.1.16",
5235
5427
  definePrintDesignPluginRenderer({
5236
5428
  type: "coordinate",
5237
5429
  validate: validateCoordinateElement,
5430
+ commands: {
5431
+ execute: (element, command, payload) => executeGridCommand(
5432
+ element,
5433
+ command,
5434
+ payload,
5435
+ validateCoordinateElement
5436
+ )
5437
+ },
5238
5438
  validateTemplateData: validateGridTemplateData,
5239
5439
  bindingInfo: getGridBindingInfo,
5240
5440
  drawCanvas: drawCoordinateElement,
@@ -5533,13 +5733,13 @@ function resolveFlowItems(element, data = {}) {
5533
5733
  if (typeof value !== "object" || Array.isArray(value))
5534
5734
  return [{ content: String(value) }];
5535
5735
  const row = value;
5536
- const read = (key) => resolvePrintDesignDataPath(row, fields[key] || key);
5537
- const content = read("content");
5538
- const title = read("title");
5539
- const color2 = read("color");
5540
- const position = read("position");
5541
- const loading = read("loading");
5542
- const icon = read("icon");
5736
+ const read2 = (key) => resolvePrintDesignDataPath(row, fields[key] || key);
5737
+ const content = read2("content");
5738
+ const title = read2("title");
5739
+ const color2 = read2("color");
5740
+ const position = read2("position");
5741
+ const loading = read2("loading");
5742
+ const icon = read2("icon");
5543
5743
  return [
5544
5744
  {
5545
5745
  content: content == null || typeof content === "object" ? "" : String(content),
@@ -5731,17 +5931,48 @@ function validateFlowTemplateData(element, data) {
5731
5931
  return [];
5732
5932
  }
5733
5933
 
5934
+ // src/plugins/flow/interaction/commands.ts
5935
+ var flowCommands = {
5936
+ execute(element, command, payload) {
5937
+ if (element.locked || element.dataMode === "binding" || !payload || typeof payload !== "object")
5938
+ return;
5939
+ const args = payload;
5940
+ const index = args.index;
5941
+ if (!Number.isInteger(index)) return;
5942
+ const at = index;
5943
+ if (command === "remove-item") {
5944
+ if (at < 0 || at >= element.items.length) return;
5945
+ return { ...element, items: element.items.filter((_, i) => i !== at) };
5946
+ }
5947
+ const item = args.item;
5948
+ if (!item || typeof item !== "object" || Array.isArray(item)) return;
5949
+ const items = [...element.items];
5950
+ if (command === "insert-item") {
5951
+ if (at < 0 || at > items.length) return;
5952
+ items.splice(at, 0, item);
5953
+ } else if (command === "update-item") {
5954
+ if (at < 0 || at >= items.length) return;
5955
+ items[at] = { ...items[at], ...item };
5956
+ } else return;
5957
+ const next = { ...element, items };
5958
+ return validateFlowElement(next) ? next : void 0;
5959
+ }
5960
+ };
5961
+
5734
5962
  // src/plugins/flow/native.ts
5735
5963
  var flowNativePlugin = defineNativePlugin(
5736
5964
  "flow",
5737
- "0.1.6",
5965
+ "0.1.7",
5738
5966
  definePrintDesignPluginRenderer({
5739
5967
  type: "flow",
5740
5968
  validate: validateFlowElement,
5969
+ commands: flowCommands,
5741
5970
  validateTemplateData: validateFlowTemplateData,
5742
5971
  bindingInfo: (element) => ({
5743
5972
  bound: (element.dataMode ?? element.dataConfig?.mode) === "binding",
5744
- paths: (element.dataMode ?? element.dataConfig?.mode) === "binding" ? [element.dataPath ?? element.dataConfig?.bindings?.items ?? ""].filter(Boolean) : []
5973
+ paths: (element.dataMode ?? element.dataConfig?.mode) === "binding" ? [
5974
+ element.dataPath ?? element.dataConfig?.bindings?.items ?? ""
5975
+ ].filter(Boolean) : []
5745
5976
  }),
5746
5977
  drawCanvas: drawFlowElement,
5747
5978
  renderHtml: (element, context) => renderFlowHtml(element, context.data)
@@ -6457,6 +6688,19 @@ function fitImageToPage(image, page, current2) {
6457
6688
  return { x, y, width, height };
6458
6689
  }
6459
6690
 
6691
+ // src/plugins/image/interaction/commands.ts
6692
+ var imageCommands = {
6693
+ execute(element, command, payload) {
6694
+ if (element.locked) return;
6695
+ if (command === "clear-crop") return { ...element, crop: void 0 };
6696
+ if (command !== "set-crop" || !payload || typeof payload !== "object")
6697
+ return;
6698
+ const crop = payload;
6699
+ const next = { ...element, crop };
6700
+ return validateImageElement(next) ? next : void 0;
6701
+ }
6702
+ };
6703
+
6460
6704
  // src/plugins/image/native.ts
6461
6705
  var componentCropBehavior = {
6462
6706
  source: (element) => element.src,
@@ -6477,7 +6721,7 @@ var componentCropBehavior = {
6477
6721
  };
6478
6722
  var imageNativePlugin = defineNativePlugin(
6479
6723
  "image",
6480
- "0.1.16",
6724
+ "0.1.17",
6481
6725
  definePrintDesignPluginRenderer({
6482
6726
  type: "image",
6483
6727
  dataFields: imageDataFields,
@@ -6486,6 +6730,7 @@ var imageNativePlugin = defineNativePlugin(
6486
6730
  replaceResourceUri: (element, uri, replacement) => element.src === uri ? { ...element, src: replacement } : element,
6487
6731
  validateTemplateData: validateImageTemplateData,
6488
6732
  validate: validateImageElement,
6733
+ commands: imageCommands,
6489
6734
  drawCanvas: drawImageElement,
6490
6735
  prepareCanvas: (element, { signal }) => prepareImage(element.src, signal),
6491
6736
  needsCanvasPreparation: (element) => Boolean(element.src && !getLoadedImageSize(element.src)),
@@ -6902,13 +7147,58 @@ function renderChartHtml(element, data) {
6902
7147
  });
6903
7148
  }
6904
7149
 
7150
+ // src/plugins/chart/interaction/commands.ts
7151
+ var chartCommands = {
7152
+ execute(element, command, payload) {
7153
+ if (element.locked || !payload || typeof payload !== "object") return;
7154
+ const args = payload;
7155
+ const chartData = readChartData(element);
7156
+ if (command === "set-categories") {
7157
+ if (!Array.isArray(args.categories) || !args.categories.every((item) => typeof item === "string"))
7158
+ return;
7159
+ const categories = args.categories;
7160
+ const next2 = {
7161
+ ...element,
7162
+ chartData: {
7163
+ ...chartData,
7164
+ categories,
7165
+ series: chartData.series.map((series2) => ({
7166
+ ...series2,
7167
+ values: categories.map((_, index2) => series2.values[index2] ?? 0)
7168
+ }))
7169
+ }
7170
+ };
7171
+ return validateChartElement(next2) ? next2 : void 0;
7172
+ }
7173
+ if (command !== "set-series") return;
7174
+ const index = args.index;
7175
+ if (!Number.isInteger(index) || index < 0 || index > chartData.series.length)
7176
+ return;
7177
+ if (typeof args.name !== "string" || !Array.isArray(args.values) || args.values.length !== chartData.categories.length || !args.values.every(
7178
+ (value) => typeof value === "number" && Number.isFinite(value)
7179
+ ))
7180
+ return;
7181
+ if (["pie", "gauge"].includes(element.chartType) && index > 0)
7182
+ return;
7183
+ const series = [...chartData.series];
7184
+ series[index] = {
7185
+ name: args.name,
7186
+ values: args.values,
7187
+ ...typeof args.field === "string" ? { field: args.field } : {}
7188
+ };
7189
+ const next = { ...element, chartData: { ...chartData, series } };
7190
+ return validateChartElement(next) ? next : void 0;
7191
+ }
7192
+ };
7193
+
6905
7194
  // src/plugins/chart/native.ts
6906
7195
  var chartNativePlugin = defineNativePlugin(
6907
7196
  "chart",
6908
- "0.1.8",
7197
+ "0.1.9",
6909
7198
  definePrintDesignPluginRenderer({
6910
7199
  type: "chart",
6911
7200
  validate: validateChartElement,
7201
+ commands: chartCommands,
6912
7202
  validateTemplateData: validateChartTemplateData,
6913
7203
  bindingInfo: (element) => ({
6914
7204
  bound: element.chartData?.mode === "binding",
@@ -10753,7 +11043,7 @@ function validateTableTemplateData(element, data) {
10753
11043
  // src/plugins/table/native.ts
10754
11044
  var tableNativePlugin = defineNativePlugin(
10755
11045
  "table",
10756
- "0.1.68",
11046
+ "0.1.69",
10757
11047
  definePrintDesignPluginRenderer({
10758
11048
  type: "table",
10759
11049
  validate: validateTableElement,
@@ -11086,6 +11376,41 @@ var pivotTableBoundaryResize = {
11086
11376
  }
11087
11377
  };
11088
11378
 
11379
+ // src/plugins/pivot-table/interaction/commands.ts
11380
+ var areas = ["filter", "column", "row", "value"];
11381
+ var pivotTableCommands = {
11382
+ execute(element, command, payload) {
11383
+ if (element.locked || !payload || typeof payload !== "object") return;
11384
+ const args = payload;
11385
+ const fieldKey = args.fieldKey;
11386
+ if (typeof fieldKey !== "string" || !element.fields.some((field) => field.key === fieldKey))
11387
+ return;
11388
+ if (command === "remove-field")
11389
+ return {
11390
+ ...element,
11391
+ layout: removePivotField(element.layout, fieldKey)
11392
+ };
11393
+ if (command !== "move-field" || !areas.includes(args.area))
11394
+ return;
11395
+ const index = args.index;
11396
+ if (index !== void 0 && (!Number.isInteger(index) || index < 0))
11397
+ return;
11398
+ const sourceArea = args.sourceArea;
11399
+ if (sourceArea !== void 0 && !areas.includes(sourceArea))
11400
+ return;
11401
+ return {
11402
+ ...element,
11403
+ layout: movePivotField(
11404
+ element.layout,
11405
+ fieldKey,
11406
+ args.area,
11407
+ index,
11408
+ sourceArea
11409
+ )
11410
+ };
11411
+ }
11412
+ };
11413
+
11089
11414
  // src/plugins/pivot-table/model.ts
11090
11415
  function validatePivotTableElement(value) {
11091
11416
  if (!value || typeof value !== "object") return false;
@@ -11099,11 +11424,12 @@ function validatePivotTableElement(value) {
11099
11424
  // src/plugins/pivot-table/native.ts
11100
11425
  var pivotTableNativePlugin = defineNativePlugin(
11101
11426
  "pivotTable",
11102
- "0.1.18",
11427
+ "0.1.19",
11103
11428
  definePrintDesignPluginRenderer({
11104
11429
  type: "pivotTable",
11105
11430
  htmlCss: tableHtmlCss,
11106
11431
  validate: validatePivotTableElement,
11432
+ commands: pivotTableCommands,
11107
11433
  validateTemplateData: validatePivotTemplateData,
11108
11434
  bindingInfo: (element) => ({
11109
11435
  bound: element.dataMode === "binding",
@@ -11614,13 +11940,49 @@ function ganttMarkup(element, data, pageNumber) {
11614
11940
  return `<svg class="pd-media" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none"><rect width="${width}" height="${height}" fill="${cssColor(theme.backgroundColor, "transparent")}"/>${header > 0 ? `<rect width="${width}" height="${header}" fill="${cssColor(theme.headerBackgroundColor, "transparent")}"/>` : ""}${ticks}${taskSplit}${headerEdges}${headerTitle}${maskedDependencies}${bars}${frame}</svg>`;
11615
11941
  }
11616
11942
 
11943
+ // src/plugins/gantt/interaction/commands.ts
11944
+ var ganttCommands = {
11945
+ execute(element, command, payload) {
11946
+ if (element.locked || element.dataMode === "binding" || !payload || typeof payload !== "object")
11947
+ return;
11948
+ const args = payload;
11949
+ const tasks = [...element.tasks];
11950
+ if (command === "insert-task") {
11951
+ const index = args.index;
11952
+ if (!Number.isInteger(index) || index < 0 || index > tasks.length)
11953
+ return;
11954
+ if (!args.task || typeof args.task !== "object" || Array.isArray(args.task))
11955
+ return;
11956
+ const task = args.task;
11957
+ if (tasks.some((existing) => existing.id === task.id)) return;
11958
+ tasks.splice(index, 0, task);
11959
+ } else {
11960
+ const taskId = args.taskId;
11961
+ if (typeof taskId !== "string") return;
11962
+ const index = tasks.findIndex((task) => task.id === taskId);
11963
+ if (index < 0) return;
11964
+ if (command === "remove-task") tasks.splice(index, 1);
11965
+ else if (command === "update-task") {
11966
+ if (!args.patch || typeof args.patch !== "object" || Array.isArray(args.patch))
11967
+ return;
11968
+ const patch = args.patch;
11969
+ if (patch.id !== void 0 || patch.tasks !== void 0) return;
11970
+ tasks[index] = { ...tasks[index], ...patch };
11971
+ } else return;
11972
+ }
11973
+ const next = { ...element, tasks };
11974
+ return validateGanttElement(next) ? next : void 0;
11975
+ }
11976
+ };
11977
+
11617
11978
  // src/plugins/gantt/native.ts
11618
11979
  var ganttNativePlugin = defineNativePlugin(
11619
11980
  "gantt",
11620
- "0.1.6",
11981
+ "0.1.7",
11621
11982
  definePrintDesignPluginRenderer({
11622
11983
  type: "gantt",
11623
11984
  validate: validateGanttElement,
11985
+ commands: ganttCommands,
11624
11986
  validateTemplateData: validateGanttTemplateData,
11625
11987
  bindingInfo: (element) => ({
11626
11988
  bound: element.dataMode === "binding",
@@ -11941,6 +12303,20 @@ var textPlugin = defineBuiltinReactPlugin(textNativePlugin, {
11941
12303
  var listFactory = {
11942
12304
  type: "list",
11943
12305
  label: "\u5217\u8868",
12306
+ agentCommands: [
12307
+ {
12308
+ name: "insert-item",
12309
+ description: "\u5728\u5217\u8868\u6307\u5B9A\u4F4D\u7F6E\u63D2\u5165\u9879\u3002payload: { index: 0 \u8D77\u59CB\u63D2\u5165\u4F4D\u7F6E, text: \u9879\u6587\u5B57 }\u3002"
12310
+ },
12311
+ {
12312
+ name: "update-item",
12313
+ description: "\u4FEE\u6539\u5217\u8868\u9879\u3002payload: { index: 0 \u8D77\u59CB\u9879\u4F4D\u7F6E, text?: \u9879\u6587\u5B57, checked?: \u662F\u5426\u9009\u4E2D }\u3002"
12314
+ },
12315
+ {
12316
+ name: "remove-item",
12317
+ description: "\u79FB\u9664\u5217\u8868\u9879\u3002payload: { index: 0 \u8D77\u59CB\u9879\u4F4D\u7F6E }\u3002"
12318
+ }
12319
+ ],
11944
12320
  showDataPanel: false,
11945
12321
  tourFields: () => [],
11946
12322
  acceptsPreset: (preset) => ["ordered", "unordered", "radio", "checkbox"].includes(preset),
@@ -12388,6 +12764,20 @@ var watermarkPlugin = defineBuiltinReactPlugin(watermarkNativePlugin, {
12388
12764
  var shapeFactory = {
12389
12765
  type: "shape",
12390
12766
  label: "\u56FE\u5F62",
12767
+ agentCommands: [
12768
+ {
12769
+ name: "set-polygon-points",
12770
+ description: "\u8BBE\u7F6E\u4E09\u89D2\u5F62\u3001\u591A\u8FB9\u5F62\u6216\u661F\u5F62\u9876\u70B9\u3002payload: { points: \u81F3\u5C11 3 \u4E2A { x, y } \u5F52\u4E00\u5316\u5750\u6807 }\u3002"
12771
+ },
12772
+ {
12773
+ name: "set-curve-points",
12774
+ description: "\u8BBE\u7F6E\u4E8C\u6B21\u3001\u4E09\u6B21\u6216\u591A\u6BB5\u66F2\u7EBF\u63A7\u5236\u70B9\u3002payload: { points: \u81F3\u5C11 2 \u4E2A { x, y } \u5F52\u4E00\u5316\u5750\u6807 }\u3002"
12775
+ },
12776
+ {
12777
+ name: "set-path-points",
12778
+ description: "\u8BBE\u7F6E\u81EA\u5B9A\u4E49\u8DEF\u5F84\u8282\u70B9\u3002payload: { points: { x, y } \u5F52\u4E00\u5316\u5750\u6807\u6570\u7EC4, closed?: \u662F\u5426\u95ED\u5408 }\u3002"
12779
+ }
12780
+ ],
12391
12781
  acceptsPreset: (preset) => [
12392
12782
  "triangle",
12393
12783
  "rect",
@@ -12944,6 +13334,16 @@ function BrushToolbarButton({
12944
13334
  var brushFactory = {
12945
13335
  type: "brush",
12946
13336
  label: "\u753B\u7B14",
13337
+ agentCommands: [
13338
+ {
13339
+ name: "append-stroke",
13340
+ description: "\u8FFD\u52A0\u4E00\u7B14\u3002payload: { points: \u81F3\u5C11\u4E24\u4E2A { x, y, pressure?: 0 \u5230 1 } \u5F52\u4E00\u5316\u5750\u6807 }\u3002"
13341
+ },
13342
+ {
13343
+ name: "remove-stroke",
13344
+ description: "\u5220\u9664\u6307\u5B9A\u7B14\u753B\u5E76\u540C\u6B65\u5BF9\u5E94\u6837\u5F0F\u3002payload: { index: 0 \u8D77\u59CB\u7B14\u753B\u4F4D\u7F6E }\u3002"
13345
+ }
13346
+ ],
12947
13347
  showDataPanel: false,
12948
13348
  tourFields: () => [],
12949
13349
  create: createBrushElement,
@@ -13043,6 +13443,16 @@ var brushPlugin = defineBuiltinReactPlugin(brushNativePlugin, {
13043
13443
  var connectorFactory = {
13044
13444
  type: "connector",
13045
13445
  label: "\u8FDE\u63A5\u7EBF",
13446
+ agentCommands: [
13447
+ {
13448
+ name: "set-endpoint",
13449
+ description: "\u5C06\u8FDE\u63A5\u7EBF\u8D77\u70B9\u6216\u7EC8\u70B9\u8FDE\u63A5\u5230\u5DF2\u6709\u5143\u7D20\u3002payload: { side: start|end, endpoint: { elementId?: \u76EE\u6807\u5143\u7D20 ID, anchor?: auto|top|right|bottom|left|top-left|top-right|bottom-right|bottom-left|edge:\u7D22\u5F15|vertex:\u7D22\u5F15 } }\u3002"
13450
+ },
13451
+ {
13452
+ name: "set-waypoints",
13453
+ description: "\u8BBE\u7F6E\u6298\u7EBF\u4E2D\u95F4\u8DEF\u5F84\u70B9\uFF0C\u4EC5\u9002\u7528\u4E8E lineType=polyline\u3002payload: { points: \u9875\u9762\u6BEB\u7C73\u5750\u6807\u6570\u7EC4 [{ x, y }] }\u3002"
13454
+ }
13455
+ ],
13046
13456
  create: (preset = "bar") => {
13047
13457
  const common = createCommonElementDefaults();
13048
13458
  const type = "connector";
@@ -13400,6 +13810,16 @@ var rulerPlugin = defineBuiltinReactPlugin(rulerNativePlugin, {
13400
13810
  var gridFactory = {
13401
13811
  type: "grid",
13402
13812
  label: "\u7F51\u683C",
13813
+ agentCommands: [
13814
+ {
13815
+ name: "resize-grid",
13816
+ description: "\u8C03\u6574\u7F51\u683C\u884C\u5217\u6570\uFF0C\u4FDD\u7559\u91CD\u53E0\u533A\u57DF\u7684\u5355\u5143\u683C\u3002payload: { rows: 1 \u5230 50 \u7684\u6574\u6570, columns: 1 \u5230 50 \u7684\u6574\u6570 }\u3002"
13817
+ },
13818
+ {
13819
+ name: "set-cell",
13820
+ description: "\u66F4\u65B0\u6307\u5B9A\u7F51\u683C\u5355\u5143\u683C\u3002payload: { rowIndex: 0 \u8D77\u59CB\u884C, columnIndex: 0 \u8D77\u59CB\u5217, cell: { content?: none|x|*, contentMode?: static|binding, contentPath?: \u5B57\u7B26\u4E32, backgroundColor?: \u5B57\u7B26\u4E32 } }\u3002"
13821
+ }
13822
+ ],
13403
13823
  showDataPanel: false,
13404
13824
  tourFields: (element) => element.type === "grid" ? [
13405
13825
  { key: "rows", label: "\u884C\u6570", value: element.rows },
@@ -13642,6 +14062,16 @@ var gridPlugin = defineBuiltinReactPlugin(gridNativePlugin, {
13642
14062
  var coordinateFactory = {
13643
14063
  type: "coordinate",
13644
14064
  label: "\u5750\u6807\u7F51\u683C",
14065
+ agentCommands: [
14066
+ {
14067
+ name: "resize-grid",
14068
+ description: "\u8C03\u6574\u5750\u6807\u7F51\u683C\u884C\u5217\u6570\uFF0C\u4FDD\u7559\u91CD\u53E0\u533A\u57DF\u5355\u5143\u683C\u3002payload: { rows: 1 \u5230 50 \u7684\u6574\u6570, columns: 1 \u5230 50 \u7684\u6574\u6570 }\u3002"
14069
+ },
14070
+ {
14071
+ name: "set-cell",
14072
+ description: "\u66F4\u65B0\u5750\u6807\u7F51\u683C\u5355\u5143\u683C\u3002payload: { rowIndex: 0 \u8D77\u59CB\u884C, columnIndex: 0 \u8D77\u59CB\u5217, cell: { content?: none|x|*, contentMode?: static|binding, contentPath?: \u5B57\u7B26\u4E32, backgroundColor?: \u5B57\u7B26\u4E32 } }\u3002"
14073
+ }
14074
+ ],
13645
14075
  showDataPanel: false,
13646
14076
  tourFields: (element) => element.type === "coordinate" ? [
13647
14077
  { key: "rows", label: "\u884C\u6570", value: element.rows },
@@ -14012,6 +14442,20 @@ var progressPlugin = defineBuiltinReactPlugin(progressNativePlugin, {
14012
14442
  var flowFactory = {
14013
14443
  type: "flow",
14014
14444
  label: "\u6D41\u7A0B\u56FE",
14445
+ agentCommands: [
14446
+ {
14447
+ name: "insert-item",
14448
+ description: "\u5728\u9759\u6001\u6D41\u7A0B\u6307\u5B9A\u4F4D\u7F6E\u63D2\u5165\u8282\u70B9\u3002payload: { index: 0 \u8D77\u59CB\u63D2\u5165\u4F4D\u7F6E, item: { content: \u5B57\u7B26\u4E32, title?: \u5B57\u7B26\u4E32, color?: \u5B57\u7B26\u4E32, position?: start|end, loading?: \u5E03\u5C14\u503C, icon?: circle|check|clock|cross } }\u3002"
14449
+ },
14450
+ {
14451
+ name: "update-item",
14452
+ description: "\u4FEE\u6539\u9759\u6001\u6D41\u7A0B\u8282\u70B9\u3002payload: { index: 0 \u8D77\u59CB\u8282\u70B9\u4F4D\u7F6E, item: \u9700\u4FEE\u6539\u7684\u8282\u70B9\u5B57\u6BB5 }\u3002"
14453
+ },
14454
+ {
14455
+ name: "remove-item",
14456
+ description: "\u79FB\u9664\u9759\u6001\u6D41\u7A0B\u8282\u70B9\u3002payload: { index: 0 \u8D77\u59CB\u8282\u70B9\u4F4D\u7F6E }\u3002"
14457
+ }
14458
+ ],
14015
14459
  showDataPanel: false,
14016
14460
  tourFields: () => [],
14017
14461
  create: (preset = "bar") => {
@@ -14394,6 +14838,16 @@ function placeExternalImage(image, point, page, index = 0) {
14394
14838
  var imageFactory = {
14395
14839
  type: "image",
14396
14840
  label: "\u56FE\u7247",
14841
+ agentCommands: [
14842
+ {
14843
+ name: "set-crop",
14844
+ description: "\u8BBE\u7F6E\u56FE\u7247\u88C1\u526A\u533A\u57DF\u3002payload: { x, y, width, height }\uFF0C\u5747\u4E3A\u539F\u56FE\u5BBD\u9AD8\u7684 0 \u5230 1 \u6BD4\u4F8B\uFF0C\u533A\u57DF\u5FC5\u987B\u5728\u539F\u56FE\u5185\uFF1B\u53EF\u9009 sourceWidth\u3001sourceHeight \u4E3A\u539F\u56FE\u50CF\u7D20\u5C3A\u5BF8\u3002"
14845
+ },
14846
+ {
14847
+ name: "clear-crop",
14848
+ description: "\u79FB\u9664\u56FE\u7247\u88C1\u526A\uFF0C\u663E\u793A\u5B8C\u6574\u56FE\u7247\uFF1Bpayload \u4F20\u7A7A\u5BF9\u8C61\u3002"
14849
+ }
14850
+ ],
14397
14851
  dataFields: imageDataFields,
14398
14852
  staticFieldPatch: (_element, key, value) => key === "src" ? { src: String(value), crop: void 0 } : { [key]: value },
14399
14853
  externalDrop: {
@@ -14834,6 +15288,16 @@ function createChartPreset(id) {
14834
15288
  var chartFactory = {
14835
15289
  type: "chart",
14836
15290
  label: "\u56FE\u8868",
15291
+ agentCommands: [
15292
+ {
15293
+ name: "set-categories",
15294
+ description: "\u8BBE\u7F6E\u56FE\u8868\u9759\u6001\u5206\u7C7B\u6216\u9ED8\u8BA4\u5206\u7C7B\uFF0C\u5E76\u4F7F\u5404\u7CFB\u5217\u6570\u503C\u957F\u5EA6\u5339\u914D\u3002payload: { categories: \u5B57\u7B26\u4E32\u6570\u7EC4 }\u3002"
15295
+ },
15296
+ {
15297
+ name: "set-series",
15298
+ description: "\u66F4\u65B0\u6307\u5B9A\u6570\u503C\u7CFB\u5217\uFF0C\u4E5F\u53EF\u5728\u672B\u5C3E\u65B0\u589E\u3002payload: { index: 0 \u8D77\u59CB\u7CFB\u5217\u4F4D\u7F6E, name: \u7CFB\u5217\u540D\u79F0, values: \u4E0E categories \u7B49\u957F\u7684\u6709\u9650\u6570\u5B57\u6570\u7EC4, field?: \u7ED1\u5B9A\u5B57\u6BB5\u8DEF\u5F84 }\uFF1B\u997C\u56FE\u548C\u4EEA\u8868\u76D8\u4EC5\u652F\u6301\u7D22\u5F15 0\u3002"
15299
+ }
15300
+ ],
14837
15301
  showDataPanel: false,
14838
15302
  acceptsPreset: (preset) => chartPresets.some((item) => item.id === preset),
14839
15303
  create: (preset = "bar") => {
@@ -15119,6 +15583,24 @@ var chartPlugin = defineBuiltinReactPlugin(chartNativePlugin, {
15119
15583
  var tableFactory = {
15120
15584
  type: "table",
15121
15585
  label: "\u8868\u683C",
15586
+ agentCommands: [
15587
+ {
15588
+ name: "insert-row",
15589
+ description: "\u5728\u9759\u6001\u8868\u683C\u7684 rowIndex \u884C\u524D\u63D2\u5165\u884C\uFF1Bafter=true \u65F6\u63D2\u5728\u884C\u540E\u3002"
15590
+ },
15591
+ {
15592
+ name: "insert-column",
15593
+ description: "\u5728 columnIndex \u5217\u524D\u63D2\u5165\u5217\uFF1Bafter=true \u65F6\u63D2\u5728\u5217\u540E\u3002"
15594
+ },
15595
+ {
15596
+ name: "merge-body",
15597
+ description: "\u5408\u5E76\u8868\u4F53\u5355\u5143\u683C\uFF1B\u4F20 rowIndex\u3001columnIndex\u3001rowSpan\u3001colSpan\u3002"
15598
+ },
15599
+ {
15600
+ name: "merge-header",
15601
+ description: "\u5408\u5E76\u8868\u5934\u5355\u5143\u683C\uFF1B\u4F20 rowIndex\u3001columnIndex\u3001rowSpan\u3001colSpan\u3002"
15602
+ }
15603
+ ],
15122
15604
  defaultOverflowPolicy: "split",
15123
15605
  showDataPanel: false,
15124
15606
  tourFields: (element) => {
@@ -19266,6 +19748,16 @@ var tablePlugin = defineBuiltinReactPlugin(tableNativePlugin, {
19266
19748
  var pivotTableFactory = {
19267
19749
  type: "pivotTable",
19268
19750
  label: "\u900F\u89C6\u8868",
19751
+ agentCommands: [
19752
+ {
19753
+ name: "move-field",
19754
+ description: "\u79FB\u52A8\u900F\u89C6\u5B57\u6BB5\u3002payload: { fieldKey: \u5DF2\u6709\u5B57\u6BB5 key, area: filter|column|row|value, index?: \u4ECE 0 \u5F00\u59CB\u7684\u76EE\u6807\u4F4D\u7F6E, sourceArea?: \u539F\u533A\u57DF }\u3002"
19755
+ },
19756
+ {
19757
+ name: "remove-field",
19758
+ description: "\u4ECE\u900F\u89C6\u5E03\u5C40\u7684\u6240\u6709\u533A\u57DF\u79FB\u9664\u5B57\u6BB5\uFF0C\u4E0D\u5220\u9664\u5B57\u6BB5\u5B9A\u4E49\u3002payload: { fieldKey: \u5DF2\u6709\u5B57\u6BB5 key }\u3002"
19759
+ }
19760
+ ],
19269
19761
  defaultOverflowPolicy: "split",
19270
19762
  showDataPanel: false,
19271
19763
  tourFields: (element) => {
@@ -20037,6 +20529,20 @@ var pivotTablePlugin = defineBuiltinReactPlugin(
20037
20529
  var ganttFactory = {
20038
20530
  type: "gantt",
20039
20531
  label: "\u7518\u7279\u56FE",
20532
+ agentCommands: [
20533
+ {
20534
+ name: "insert-task",
20535
+ description: "\u5728\u9759\u6001\u7518\u7279\u56FE\u9876\u5C42\u4EFB\u52A1\u5217\u8868\u63D2\u5165\u4EFB\u52A1\u3002payload: { index: 0 \u8D77\u59CB\u63D2\u5165\u4F4D\u7F6E, task: { id: \u552F\u4E00\u5B57\u7B26\u4E32, title: \u5B57\u7B26\u4E32, start?: \u65E5\u671F, end?: \u65E5\u671F, progress?: 0 \u5230 100, ... } }\u3002"
20536
+ },
20537
+ {
20538
+ name: "update-task",
20539
+ description: "\u4FEE\u6539\u9876\u5C42\u4EFB\u52A1\uFF0C\u4E0D\u80FD\u4FEE\u6539 id \u6216\u5D4C\u5957 tasks\u3002payload: { taskId: \u4EFB\u52A1 id, patch: { title?, start?, end?, progress?, color?, progressColor?, dependencies? } }\u3002"
20540
+ },
20541
+ {
20542
+ name: "remove-task",
20543
+ description: "\u79FB\u9664\u9759\u6001\u7518\u7279\u56FE\u9876\u5C42\u4EFB\u52A1\u3002payload: { taskId: \u4EFB\u52A1 id }\u3002"
20544
+ }
20545
+ ],
20040
20546
  showDataPanel: false,
20041
20547
  tourFields: (element) => {
20042
20548
  if (element.type !== "gantt") return [];
@@ -21875,6 +22381,1613 @@ var pluginmarketTool = {
21875
22381
  render: (context) => /* @__PURE__ */ jsx(PluginMarketTool, { ...context })
21876
22382
  };
21877
22383
 
22384
+ // src/ai-chat/persistence/panel-widths.ts
22385
+ var WIDTHS_KEY = "canvas-components-print-design-ai-chat-widths";
22386
+ function normalizePrintDesignAiChatPanelWidths(value) {
22387
+ const min = Number.isFinite(value?.min) ? Math.max(240, Math.min(1e3, Math.round(value.min))) : 280;
22388
+ const max = Number.isFinite(value?.max) ? Math.max(min, Math.min(1600, Math.round(value.max))) : Math.max(min, 640);
22389
+ const current2 = Number.isFinite(value?.current) ? Math.max(min, Math.min(max, Math.round(value.current))) : Math.max(min, Math.min(max, 360));
22390
+ return { min, max, current: current2 };
22391
+ }
22392
+ function readPrintDesignAiChatPanelWidths() {
22393
+ try {
22394
+ const raw = globalThis.localStorage?.getItem(WIDTHS_KEY);
22395
+ return raw ? normalizePrintDesignAiChatPanelWidths(
22396
+ JSON.parse(raw)
22397
+ ) : null;
22398
+ } catch {
22399
+ return null;
22400
+ }
22401
+ }
22402
+ function savePrintDesignAiChatPanelWidths(value) {
22403
+ try {
22404
+ globalThis.localStorage?.setItem(
22405
+ WIDTHS_KEY,
22406
+ JSON.stringify(normalizePrintDesignAiChatPanelWidths(value))
22407
+ );
22408
+ } catch {
22409
+ }
22410
+ }
22411
+
22412
+ // src/ai-chat/model/reasoning-effort.ts
22413
+ var reasoningEffortOptions = [
22414
+ { label: "\u9ED8\u8BA4", value: "" },
22415
+ { label: "\u4F4E", value: "low" },
22416
+ { label: "\u4E2D", value: "medium" },
22417
+ { label: "\u9AD8", value: "high" }
22418
+ ];
22419
+ function parseReasoningEffort(value) {
22420
+ return value === "low" || value === "medium" || value === "high" ? value : void 0;
22421
+ }
22422
+
22423
+ // src/ai-chat/model/connection-profiles.ts
22424
+ function profileId() {
22425
+ return globalThis.crypto?.randomUUID?.() ?? `connection-${Date.now()}-${Math.random().toString(36).slice(2)}`;
22426
+ }
22427
+ function createPrintDesignAiChatProfile(defaults2 = {}) {
22428
+ return {
22429
+ id: profileId(),
22430
+ name: "",
22431
+ baseUrl: defaults2.baseUrl ?? "",
22432
+ key: defaults2.key ?? "",
22433
+ model: defaults2.model ?? "",
22434
+ reasoningEffort: parseReasoningEffort(defaults2.reasoningEffort)
22435
+ };
22436
+ }
22437
+ function createInitialPrintDesignAiChatSettings(defaults2 = {}) {
22438
+ const profile = createPrintDesignAiChatProfile(defaults2);
22439
+ return { profiles: [profile], activeProfileId: profile.id };
22440
+ }
22441
+ function activePrintDesignAiChatProfile(settings) {
22442
+ return settings.profiles.find(
22443
+ (profile) => profile.id === settings.activeProfileId
22444
+ ) ?? settings.profiles[0];
22445
+ }
22446
+ function parsePrintDesignAiChatSettings(value) {
22447
+ if (!value || typeof value !== "object") return null;
22448
+ const item = value;
22449
+ if (Array.isArray(item.profiles)) {
22450
+ const profiles = item.profiles.filter((entry) => {
22451
+ if (!entry || typeof entry !== "object") return false;
22452
+ const profile2 = entry;
22453
+ return ["id", "name", "baseUrl", "key", "model"].every(
22454
+ (key) => typeof profile2[key] === "string"
22455
+ ) && Boolean(profile2.id);
22456
+ }).map((profile2) => ({
22457
+ ...profile2,
22458
+ reasoningEffort: parseReasoningEffort(profile2.reasoningEffort),
22459
+ models: Array.isArray(profile2.models) ? [
22460
+ ...new Set(
22461
+ profile2.models.filter(
22462
+ (model) => typeof model === "string" && model.length > 0
22463
+ )
22464
+ )
22465
+ ] : []
22466
+ }));
22467
+ if (!profiles.length) return null;
22468
+ const unique = profiles.filter(
22469
+ (profile2, index) => profiles.findIndex((candidate) => candidate.id === profile2.id) === index
22470
+ );
22471
+ const activeProfileId = typeof item.activeProfileId === "string" && unique.some((profile2) => profile2.id === item.activeProfileId) ? item.activeProfileId : unique[0].id;
22472
+ return {
22473
+ profiles: unique,
22474
+ activeProfileId,
22475
+ ...item.panelWidths ? {
22476
+ panelWidths: normalizePrintDesignAiChatPanelWidths(
22477
+ item.panelWidths
22478
+ )
22479
+ } : {}
22480
+ };
22481
+ }
22482
+ if (typeof item.baseUrl !== "string" || typeof item.key !== "string" || typeof item.model !== "string")
22483
+ return null;
22484
+ const profile = {
22485
+ id: "legacy",
22486
+ name: "",
22487
+ baseUrl: item.baseUrl,
22488
+ key: item.key,
22489
+ model: item.model,
22490
+ reasoningEffort: parseReasoningEffort(item.reasoningEffort)
22491
+ };
22492
+ return {
22493
+ profiles: [profile],
22494
+ activeProfileId: profile.id,
22495
+ ...item.panelWidths ? {
22496
+ panelWidths: normalizePrintDesignAiChatPanelWidths(
22497
+ item.panelWidths
22498
+ )
22499
+ } : {}
22500
+ };
22501
+ }
22502
+
22503
+ // src/ai-chat/providers/stream-chat-completion.ts
22504
+ async function readChatCompletionStream(response, onDelta) {
22505
+ const toolCalls = /* @__PURE__ */ new Map();
22506
+ let content = "";
22507
+ let reasoning = "";
22508
+ let finished = false;
22509
+ const accept = (value) => {
22510
+ if (!value || typeof value !== "object") return;
22511
+ const choices = value.choices;
22512
+ if (!Array.isArray(choices) || !choices.length) return;
22513
+ const choice = choices[0];
22514
+ if (!choice || typeof choice !== "object") return;
22515
+ if (typeof choice.finish_reason === "string") finished = true;
22516
+ const delta = choice.delta ?? choice.message;
22517
+ if (!delta || typeof delta !== "object") return;
22518
+ if (typeof delta.content === "string" && delta.content) {
22519
+ content += delta.content;
22520
+ onDelta({ content: delta.content });
22521
+ }
22522
+ const thought = delta.reasoning_content ?? delta.reasoning;
22523
+ if (typeof thought === "string" && thought) {
22524
+ reasoning += thought;
22525
+ onDelta({ reasoning: thought });
22526
+ }
22527
+ if (!Array.isArray(delta.tool_calls)) return;
22528
+ for (const [position, piece] of delta.tool_calls.entries()) {
22529
+ if (!piece || typeof piece !== "object") continue;
22530
+ const index = typeof piece.index === "number" ? piece.index : position;
22531
+ const call = toolCalls.get(index) ?? {
22532
+ id: "",
22533
+ type: "function",
22534
+ function: { name: "", arguments: "" }
22535
+ };
22536
+ if (typeof piece.id === "string") call.id += piece.id;
22537
+ if (typeof piece.function?.name === "string")
22538
+ call.function.name += piece.function.name;
22539
+ if (typeof piece.function?.arguments === "string")
22540
+ call.function.arguments += piece.function.arguments;
22541
+ toolCalls.set(index, call);
22542
+ }
22543
+ };
22544
+ if (!response.body) {
22545
+ accept(await response.json());
22546
+ finished = true;
22547
+ } else {
22548
+ const reader = response.body.getReader();
22549
+ const decoder = new TextDecoder();
22550
+ let buffer = "";
22551
+ let pendingJson = "";
22552
+ let rawJsonAccepted = false;
22553
+ const consumeLine = (rawLine) => {
22554
+ const line = rawLine.replace(/\r$/, "").trimStart();
22555
+ if (!line || line.startsWith("event:") || line.startsWith(":")) return;
22556
+ const data = line.startsWith("data:") ? line.slice(5).trimStart() : line;
22557
+ if (data === "[DONE]") {
22558
+ if (pendingJson) throw new Error("\u6A21\u578B\u6D41\u5305\u542B\u672A\u5B8C\u6210\u7684\u6570\u636E\u3002");
22559
+ finished = true;
22560
+ return;
22561
+ }
22562
+ pendingJson += pendingJson ? `
22563
+ ${data}` : data;
22564
+ let parsed;
22565
+ try {
22566
+ parsed = JSON.parse(pendingJson);
22567
+ } catch (cause) {
22568
+ if (!(cause instanceof SyntaxError)) throw cause;
22569
+ if (pendingJson.length > 8e6)
22570
+ throw new Error("\u6A21\u578B\u6D41\u5355\u6761\u6570\u636E\u8FC7\u957F\u6216\u683C\u5F0F\u65E0\u6548\u3002");
22571
+ return;
22572
+ }
22573
+ pendingJson = "";
22574
+ accept(parsed);
22575
+ if (!line.startsWith("data:")) rawJsonAccepted = true;
22576
+ };
22577
+ try {
22578
+ while (true) {
22579
+ const { done, value } = await reader.read();
22580
+ if (done) break;
22581
+ buffer += decoder.decode(value, { stream: true });
22582
+ let lineEnd = buffer.indexOf("\n");
22583
+ while (lineEnd >= 0) {
22584
+ consumeLine(buffer.slice(0, lineEnd));
22585
+ buffer = buffer.slice(lineEnd + 1);
22586
+ if (finished) break;
22587
+ lineEnd = buffer.indexOf("\n");
22588
+ }
22589
+ if (finished) {
22590
+ await reader.cancel();
22591
+ break;
22592
+ }
22593
+ }
22594
+ buffer += decoder.decode();
22595
+ if (!finished && buffer.trim()) consumeLine(buffer);
22596
+ if (pendingJson) throw new Error("\u6A21\u578B\u6D41\u5305\u542B\u65E0\u6CD5\u89E3\u6790\u7684\u6570\u636E\u3002");
22597
+ if (!finished && rawJsonAccepted) finished = true;
22598
+ } finally {
22599
+ reader.releaseLock();
22600
+ }
22601
+ }
22602
+ if (!finished) throw new Error("\u6A21\u578B\u56DE\u590D\u5728\u5B8C\u6210\u524D\u4E2D\u65AD\u3002");
22603
+ return {
22604
+ content,
22605
+ reasoning,
22606
+ toolCalls: [...toolCalls.entries()].sort(([a], [b]) => a - b).map(([, call]) => call)
22607
+ };
22608
+ }
22609
+
22610
+ // src/ai-chat/providers/openai-compatible.ts
22611
+ function agentSystemContent(selection) {
22612
+ const base = "\u4F60\u662F\u6253\u5370\u8BBE\u8BA1\u5668\u52A9\u624B\u3002\u9875\u9762\u548C\u5143\u7D20\u5750\u6807\u5355\u4F4D\u4E3A\u6BEB\u7C73\u3002\u9700\u8981\u67E5\u770B\u6216\u4FEE\u6539\u753B\u5E03\u65F6\u8C03\u7528\u5DE5\u5177\uFF0C\u4E0D\u8981\u731C\u6D4B\u9875\u9762\u6216\u5143\u7D20 ID\u3002\u521B\u5EFA\u8868\u683C\u7B49\u63D2\u4EF6\u7EC4\u4EF6\u524D\u5148\u8C03\u7528 list_components \u548C get_component_template\uFF1B\u4FEE\u6539\u5DF2\u6709\u5143\u7D20\u5148\u8C03\u7528 get_element\uFF1B\u7EC4\u4EF6\u4E13\u7528\u64CD\u4F5C\u4F7F\u7528 execute_component_command\u3002";
22613
+ if (!selection) return base;
22614
+ if (!selection.elements.length)
22615
+ return `${base} \u672C\u6B21\u6D88\u606F\u6CA1\u6709\u9644\u5E26\u753B\u5E03\u5143\u7D20\u3002\u4E0D\u8981\u628A\u753B\u5E03\u4E2D\u4ECD\u7136\u9009\u4E2D\u7684\u5143\u7D20\u5F53\u4F5C\u804A\u5929\u4FEE\u6539\u76EE\u6807\uFF1B\u5982\u7528\u6237\u8981\u6C42\u4FEE\u6539\u9009\u4E2D\u5185\u5BB9\uFF0C\u8BF7\u5148\u8BF7\u7528\u6237\u91CD\u65B0\u9009\u62E9\u76EE\u6807\u3002`;
22616
+ const targets = selection.elements.map(({ id, type }) => ({ id, type }));
22617
+ return `${base} \u672C\u6B21\u7528\u6237\u53D1\u9001\u6D88\u606F\u65F6\u9009\u4E2D\u7684\u9875\u9762 ID \u4E3A ${JSON.stringify(selection.pageId)}\uFF0C\u5143\u7D20\u4E3A ${JSON.stringify(targets)}\u3002\u7528\u6237\u8981\u6C42\u4FEE\u6539\u9009\u4E2D\u5185\u5BB9\u65F6\uFF0C\u5148\u7528 get_element \u8BFB\u53D6\u8FD9\u4E9B\u5143\u7D20\uFF0C\u518D\u6839\u636E\u8BF7\u6C42\u4FEE\u6539\uFF1B\u9664\u975E\u7528\u6237\u660E\u786E\u8981\u6C42\uFF0C\u4E0D\u4FEE\u6539\u5176\u4ED6\u5143\u7D20\u3002`;
22618
+ }
22619
+ function endpoint2(baseUrl, path) {
22620
+ const base = baseUrl.trim().replace(/\/+$/, "");
22621
+ if (!/^https?:\/\//i.test(base))
22622
+ throw new Error("\u8BF7\u8F93\u5165\u6709\u6548\u7684 HTTP(S) Base URL\u3002");
22623
+ return `${base}${base.endsWith("/v1") ? "" : "/v1"}/${path}`;
22624
+ }
22625
+ async function requestJson(url, key, init = {}) {
22626
+ const response = await fetch(url, {
22627
+ ...init,
22628
+ headers: {
22629
+ ...key ? { Authorization: `Bearer ${key}` } : {},
22630
+ ...init.body ? { "Content-Type": "application/json" } : {}
22631
+ }
22632
+ });
22633
+ if (!response.ok) throw new Error(`\u6A21\u578B\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08${response.status}\uFF09\u3002`);
22634
+ return response.json();
22635
+ }
22636
+ var defaultPrintDesignAiChatProvider = {
22637
+ async listModels(config, signal) {
22638
+ const value = await requestJson(
22639
+ endpoint2(config.baseUrl, "models"),
22640
+ config.key,
22641
+ { signal }
22642
+ );
22643
+ if (!value || typeof value !== "object" || !("data" in value) || !Array.isArray(value.data))
22644
+ throw new Error("\u6A21\u578B\u5217\u8868\u683C\u5F0F\u65E0\u6548\u3002");
22645
+ return value.data.map(
22646
+ (item) => item && typeof item === "object" && "id" in item ? item.id : null
22647
+ ).filter(
22648
+ (id) => typeof id === "string" && id.length > 0
22649
+ ).sort();
22650
+ },
22651
+ async complete(config, messages, signal, agentApi) {
22652
+ const history = [
22653
+ ...agentApi ? [
22654
+ {
22655
+ role: "system",
22656
+ content: agentSystemContent(config.selection)
22657
+ }
22658
+ ] : [],
22659
+ ...messages.map(({ role, content, reasoning }) => ({
22660
+ role,
22661
+ content,
22662
+ ...agentApi && role === "assistant" && reasoning ? { reasoning_content: reasoning } : {}
22663
+ }))
22664
+ ];
22665
+ for (let turn = 0; turn < 8; turn++) {
22666
+ const value = await requestJson(
22667
+ endpoint2(config.baseUrl, "chat/completions"),
22668
+ config.key,
22669
+ {
22670
+ method: "POST",
22671
+ signal,
22672
+ body: JSON.stringify({
22673
+ model: config.model,
22674
+ ...config.reasoningEffort ? { reasoning_effort: config.reasoningEffort } : {},
22675
+ messages: history,
22676
+ ...agentApi ? {
22677
+ tools: agentApi.tools.map((tool) => ({
22678
+ type: "function",
22679
+ function: tool
22680
+ })),
22681
+ tool_choice: "auto"
22682
+ } : {}
22683
+ })
22684
+ }
22685
+ );
22686
+ const message = value && typeof value === "object" && "choices" in value && Array.isArray(value.choices) ? value.choices[0]?.message : null;
22687
+ if (!message || typeof message !== "object")
22688
+ throw new Error("\u6A21\u578B\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u6D88\u606F\u3002");
22689
+ const calls = "tool_calls" in message && Array.isArray(message.tool_calls) ? message.tool_calls : [];
22690
+ if (!calls.length) {
22691
+ if (typeof message.content !== "string")
22692
+ throw new Error("\u6A21\u578B\u6CA1\u6709\u8FD4\u56DE\u6587\u672C\u5185\u5BB9\u3002");
22693
+ return message.content;
22694
+ }
22695
+ if (!agentApi) throw new Error("\u5F53\u524D\u6CA1\u6709\u53EF\u7528\u7684 Agent \u5DE5\u5177\u3002");
22696
+ history.push(message);
22697
+ for (const call of calls) {
22698
+ const id = typeof call?.id === "string" ? call.id : "";
22699
+ const name = call?.function?.name;
22700
+ let result;
22701
+ try {
22702
+ if (!id || typeof name !== "string")
22703
+ throw new TypeError("\u6A21\u578B\u5DE5\u5177\u8C03\u7528\u683C\u5F0F\u65E0\u6548\u3002");
22704
+ result = agentApi.call(
22705
+ name,
22706
+ JSON.parse(call.function.arguments ?? "{}")
22707
+ );
22708
+ } catch (cause) {
22709
+ result = {
22710
+ error: cause instanceof Error ? cause.message : "\u5DE5\u5177\u6267\u884C\u5931\u8D25\u3002"
22711
+ };
22712
+ }
22713
+ history.push({
22714
+ role: "tool",
22715
+ tool_call_id: id,
22716
+ content: JSON.stringify(result)
22717
+ });
22718
+ }
22719
+ }
22720
+ throw new Error("Agent \u5DE5\u5177\u8C03\u7528\u6B21\u6570\u8FC7\u591A\uFF0C\u8BF7\u7F29\u5C0F\u4EFB\u52A1\u8303\u56F4\u3002");
22721
+ },
22722
+ async stream(config, messages, onDelta, signal, agentApi) {
22723
+ const history = [
22724
+ ...agentApi ? [
22725
+ {
22726
+ role: "system",
22727
+ content: agentSystemContent(config.selection)
22728
+ }
22729
+ ] : [],
22730
+ ...messages.map(({ role, content: content2, reasoning: reasoning2 }) => ({
22731
+ role,
22732
+ content: content2,
22733
+ ...agentApi && role === "assistant" && reasoning2 ? { reasoning_content: reasoning2 } : {}
22734
+ }))
22735
+ ];
22736
+ let content = "";
22737
+ let reasoning = "";
22738
+ for (let turn = 0; turn < 8; turn++) {
22739
+ const response = await fetch(
22740
+ endpoint2(config.baseUrl, "chat/completions"),
22741
+ {
22742
+ method: "POST",
22743
+ signal,
22744
+ headers: {
22745
+ ...config.key ? { Authorization: `Bearer ${config.key}` } : {},
22746
+ "Content-Type": "application/json"
22747
+ },
22748
+ body: JSON.stringify({
22749
+ model: config.model,
22750
+ ...config.reasoningEffort ? { reasoning_effort: config.reasoningEffort } : {},
22751
+ messages: history,
22752
+ stream: true,
22753
+ ...agentApi ? {
22754
+ tools: agentApi.tools.map((tool) => ({
22755
+ type: "function",
22756
+ function: tool
22757
+ })),
22758
+ tool_choice: "auto"
22759
+ } : {}
22760
+ })
22761
+ }
22762
+ );
22763
+ if (!response.ok)
22764
+ throw new Error(`\u6A21\u578B\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08${response.status}\uFF09\u3002`);
22765
+ const result = await readChatCompletionStream(response, onDelta);
22766
+ content += result.content;
22767
+ reasoning += result.reasoning;
22768
+ if (!result.toolCalls.length) {
22769
+ if (!content) throw new Error("\u6A21\u578B\u6CA1\u6709\u8FD4\u56DE\u6587\u672C\u5185\u5BB9\u3002");
22770
+ return { content, reasoning };
22771
+ }
22772
+ if (!agentApi) throw new Error("\u5F53\u524D\u6CA1\u6709\u53EF\u7528\u7684 Agent \u5DE5\u5177\u3002");
22773
+ history.push({
22774
+ role: "assistant",
22775
+ content: result.content || null,
22776
+ ...result.reasoning ? { reasoning_content: result.reasoning } : {},
22777
+ tool_calls: result.toolCalls
22778
+ });
22779
+ for (const call of result.toolCalls) {
22780
+ let output;
22781
+ try {
22782
+ if (!call.id || !call.function.name)
22783
+ throw new TypeError("\u6A21\u578B\u5DE5\u5177\u8C03\u7528\u683C\u5F0F\u65E0\u6548\u3002");
22784
+ output = agentApi.call(
22785
+ call.function.name,
22786
+ JSON.parse(call.function.arguments || "{}")
22787
+ );
22788
+ } catch (cause) {
22789
+ output = {
22790
+ error: cause instanceof Error ? cause.message : "\u5DE5\u5177\u6267\u884C\u5931\u8D25\u3002"
22791
+ };
22792
+ }
22793
+ history.push({
22794
+ role: "tool",
22795
+ tool_call_id: call.id,
22796
+ content: JSON.stringify(output)
22797
+ });
22798
+ }
22799
+ }
22800
+ throw new Error("Agent \u5DE5\u5177\u8C03\u7528\u6B21\u6570\u8FC7\u591A\uFF0C\u8BF7\u7F29\u5C0F\u4EFB\u52A1\u8303\u56F4\u3002");
22801
+ }
22802
+ };
22803
+
22804
+ // src/ai-chat/persistence/encrypted-config.ts
22805
+ var DATABASE = "canvas-components-print-design-ai-chat";
22806
+ var STORE = "private-config";
22807
+ function openDatabase() {
22808
+ return new Promise((resolve, reject) => {
22809
+ const request = indexedDB.open(DATABASE, 1);
22810
+ request.onupgradeneeded = () => request.result.createObjectStore(STORE);
22811
+ request.onsuccess = () => resolve(request.result);
22812
+ request.onerror = () => reject(request.error);
22813
+ });
22814
+ }
22815
+ function read(database, key) {
22816
+ return new Promise((resolve, reject) => {
22817
+ const request = database.transaction(STORE, "readonly").objectStore(STORE).get(key);
22818
+ request.onsuccess = () => resolve(request.result);
22819
+ request.onerror = () => reject(request.error);
22820
+ });
22821
+ }
22822
+ async function savePrintDesignAiChatSettings(settings) {
22823
+ if (!globalThis.crypto?.subtle || typeof indexedDB === "undefined")
22824
+ throw new Error("\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u52A0\u5BC6\u4FDD\u5B58\u914D\u7F6E\u3002");
22825
+ const database = await openDatabase();
22826
+ try {
22827
+ const key = await read(database, "key") ?? await crypto.subtle.generateKey(
22828
+ { name: "AES-GCM", length: 256 },
22829
+ false,
22830
+ ["encrypt", "decrypt"]
22831
+ );
22832
+ const iv = crypto.getRandomValues(new Uint8Array(12));
22833
+ const bytes = new TextEncoder().encode(JSON.stringify(settings));
22834
+ const ciphertext = await crypto.subtle.encrypt(
22835
+ { name: "AES-GCM", iv },
22836
+ key,
22837
+ bytes
22838
+ );
22839
+ await new Promise((resolve, reject) => {
22840
+ const transaction = database.transaction(STORE, "readwrite");
22841
+ transaction.objectStore(STORE).put(key, "key");
22842
+ transaction.objectStore(STORE).put({ iv, ciphertext }, "config");
22843
+ transaction.oncomplete = () => resolve();
22844
+ transaction.onerror = () => reject(transaction.error);
22845
+ transaction.onabort = () => reject(transaction.error);
22846
+ });
22847
+ } finally {
22848
+ database.close();
22849
+ }
22850
+ }
22851
+ async function readPrintDesignAiChatSettings() {
22852
+ if (!globalThis.crypto?.subtle || typeof indexedDB === "undefined")
22853
+ return null;
22854
+ const database = await openDatabase();
22855
+ try {
22856
+ const key = await read(database, "key");
22857
+ const record2 = await read(
22858
+ database,
22859
+ "config"
22860
+ );
22861
+ if (!key || !record2) return null;
22862
+ const bytes = await crypto.subtle.decrypt(
22863
+ { name: "AES-GCM", iv: new Uint8Array(record2.iv) },
22864
+ key,
22865
+ record2.ciphertext
22866
+ );
22867
+ const value = JSON.parse(new TextDecoder().decode(bytes));
22868
+ return parsePrintDesignAiChatSettings(value);
22869
+ } finally {
22870
+ database.close();
22871
+ }
22872
+ }
22873
+
22874
+ // src/ai-chat/model/reasoning.ts
22875
+ var LIVE_REASONING_LIMIT = 8e3;
22876
+ var ESTIMATED_HEIGHT = 104;
22877
+ var OVERSCAN = 3;
22878
+ function VirtualMessages({
22879
+ messages,
22880
+ currentModel,
22881
+ busy = false,
22882
+ pendingModel,
22883
+ streaming
22884
+ }) {
22885
+ const viewport = useRef(null);
22886
+ const followTail = useRef(true);
22887
+ const [scrollTop, setScrollTop] = useState(0);
22888
+ const [viewportHeight, setViewportHeight] = useState(500);
22889
+ const [heights, setHeights] = useState({});
22890
+ const showThinking = busy && messages[messages.length - 1]?.role !== "assistant";
22891
+ const offsets = useMemo(() => {
22892
+ const next = [0];
22893
+ for (const message of messages)
22894
+ next.push(
22895
+ next[next.length - 1] + (heights[message.id] ?? ESTIMATED_HEIGHT)
22896
+ );
22897
+ return next;
22898
+ }, [messages, heights]);
22899
+ const total = offsets[offsets.length - 1] ?? 0;
22900
+ const first = Math.max(
22901
+ 0,
22902
+ offsets.findIndex(
22903
+ (offset, index) => index < messages.length && offsets[index + 1] >= scrollTop
22904
+ ) - OVERSCAN
22905
+ );
22906
+ const end = offsets.findIndex(
22907
+ (offset) => offset > scrollTop + viewportHeight
22908
+ );
22909
+ const last = end < 0 ? messages.length : Math.min(messages.length, Math.max(first, end + OVERSCAN));
22910
+ useEffect(() => {
22911
+ const element = viewport.current;
22912
+ if (!element) return;
22913
+ const observer = new ResizeObserver(
22914
+ () => setViewportHeight(element.clientHeight)
22915
+ );
22916
+ observer.observe(element);
22917
+ return () => observer.disconnect();
22918
+ }, []);
22919
+ useEffect(() => {
22920
+ const element = viewport.current;
22921
+ if (element && followTail.current) element.scrollTop = element.scrollHeight;
22922
+ }, [
22923
+ messages.length,
22924
+ showThinking,
22925
+ streaming?.content.length,
22926
+ streaming?.reasoningLength
22927
+ ]);
22928
+ useEffect(() => {
22929
+ if (!showThinking) return;
22930
+ followTail.current = true;
22931
+ const element = viewport.current;
22932
+ if (element) element.scrollTop = element.scrollHeight;
22933
+ }, [showThinking]);
22934
+ return /* @__PURE__ */ jsxs(
22935
+ "div",
22936
+ {
22937
+ ref: viewport,
22938
+ className: "cc-print-design-ai-messages",
22939
+ onScroll: (event) => {
22940
+ const element = event.currentTarget;
22941
+ setScrollTop(element.scrollTop);
22942
+ followTail.current = element.scrollHeight - element.scrollTop - element.clientHeight < 80;
22943
+ },
22944
+ children: [
22945
+ /* @__PURE__ */ jsx("div", { style: { height: total, position: "relative" }, children: messages.slice(first, last).map((message, index) => /* @__PURE__ */ jsx(
22946
+ MeasuredMessage,
22947
+ {
22948
+ message,
22949
+ currentModel,
22950
+ top: offsets[first + index],
22951
+ onHeight: (height) => setHeights(
22952
+ (current2) => current2[message.id] === height ? current2 : { ...current2, [message.id]: height }
22953
+ )
22954
+ },
22955
+ message.id
22956
+ )) }),
22957
+ showThinking && /* @__PURE__ */ jsxs(
22958
+ "div",
22959
+ {
22960
+ className: "cc-print-design-ai-message cc-print-design-ai-message-assistant cc-print-design-ai-message-thinking",
22961
+ role: "status",
22962
+ "aria-live": "polite",
22963
+ children: [
22964
+ /* @__PURE__ */ jsx("span", { children: pendingModel?.trim() || currentModel?.trim() || "AI" }),
22965
+ streaming?.reasoning && /* @__PURE__ */ jsx(
22966
+ ReasoningBlock,
22967
+ {
22968
+ text: streaming.reasoning,
22969
+ totalLength: streaming.reasoningLength,
22970
+ live: true
22971
+ }
22972
+ ),
22973
+ streaming?.content && /* @__PURE__ */ jsx("p", { children: streaming.content }),
22974
+ /* @__PURE__ */ jsxs("p", { className: "cc-print-design-ai-thinking-indicator", children: [
22975
+ /* @__PURE__ */ jsxs(
22976
+ "span",
22977
+ {
22978
+ className: "cc-print-design-ai-thinking-dots",
22979
+ "aria-hidden": "true",
22980
+ children: [
22981
+ /* @__PURE__ */ jsx("i", {}),
22982
+ /* @__PURE__ */ jsx("i", {}),
22983
+ /* @__PURE__ */ jsx("i", {})
22984
+ ]
22985
+ }
22986
+ ),
22987
+ streaming?.content ? "\u751F\u6210\u4E2D\u2026" : "\u601D\u8003\u4E2D\u2026"
22988
+ ] })
22989
+ ]
22990
+ }
22991
+ )
22992
+ ]
22993
+ }
22994
+ );
22995
+ }
22996
+ function MeasuredMessage({
22997
+ message,
22998
+ currentModel,
22999
+ top,
23000
+ onHeight
23001
+ }) {
23002
+ const ref = useRef(null);
23003
+ useEffect(() => {
23004
+ const element = ref.current;
23005
+ if (!element) return;
23006
+ const observer = new ResizeObserver(
23007
+ () => onHeight(Math.ceil(element.getBoundingClientRect().height))
23008
+ );
23009
+ observer.observe(element);
23010
+ return () => observer.disconnect();
23011
+ }, [onHeight]);
23012
+ return /* @__PURE__ */ jsxs(
23013
+ "div",
23014
+ {
23015
+ ref,
23016
+ className: `cc-print-design-ai-message cc-print-design-ai-message-${message.role}`,
23017
+ style: { position: "absolute", top, width: "100%" },
23018
+ children: [
23019
+ /* @__PURE__ */ jsx("span", { children: message.role === "user" ? "\u4F60" : message.model?.trim() || currentModel?.trim() || "AI" }),
23020
+ message.role === "assistant" && message.reasoning && /* @__PURE__ */ jsx(ReasoningBlock, { text: message.reasoning }),
23021
+ /* @__PURE__ */ jsx("p", { children: message.content })
23022
+ ]
23023
+ }
23024
+ );
23025
+ }
23026
+ function ReasoningBlock({
23027
+ text,
23028
+ totalLength = text.length,
23029
+ live = false
23030
+ }) {
23031
+ const viewport = useRef(null);
23032
+ const visible = live ? text.slice(-LIVE_REASONING_LIMIT) : text;
23033
+ const hidden = live ? Math.max(0, totalLength - visible.length) : 0;
23034
+ useEffect(() => {
23035
+ if (live && viewport.current)
23036
+ viewport.current.scrollTop = viewport.current.scrollHeight;
23037
+ }, [live, totalLength]);
23038
+ return /* @__PURE__ */ jsxs("details", { className: "cc-print-design-ai-reasoning", open: live || void 0, children: [
23039
+ /* @__PURE__ */ jsx("summary", { children: "\u601D\u8003\u8FC7\u7A0B" }),
23040
+ /* @__PURE__ */ jsxs("div", { ref: viewport, children: [
23041
+ hidden ? `\u524D ${hidden} \u5B57\u6682\u4E0D\u663E\u793A\uFF0C\u56DE\u590D\u5B8C\u6210\u540E\u53EF\u5C55\u5F00\u5168\u6587\u3002
23042
+ ` : "",
23043
+ visible
23044
+ ] })
23045
+ ] });
23046
+ }
23047
+ function ChatSettings({
23048
+ settings,
23049
+ models,
23050
+ modelLoading,
23051
+ onSettingsChange,
23052
+ onLoadModels,
23053
+ onSave,
23054
+ onCancel
23055
+ }) {
23056
+ const profile = activePrintDesignAiChatProfile(settings);
23057
+ const updateProfile = (patch) => onSettingsChange({
23058
+ ...settings,
23059
+ profiles: settings.profiles.map(
23060
+ (item) => item.id === profile.id ? {
23061
+ ...item,
23062
+ ...patch,
23063
+ ...patch.baseUrl !== void 0 && patch.baseUrl !== item.baseUrl || patch.key !== void 0 && patch.key !== item.key ? { models: [] } : {}
23064
+ } : item
23065
+ )
23066
+ });
23067
+ return /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-settings", children: [
23068
+ /* @__PURE__ */ jsx("strong", { children: "\u8FDE\u63A5\u914D\u7F6E" }),
23069
+ /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-profile-picker", children: [
23070
+ /* @__PURE__ */ jsxs("label", { children: [
23071
+ "\u5F53\u524D\u8FDE\u63A5",
23072
+ /* @__PURE__ */ jsx(
23073
+ ReactSelect,
23074
+ {
23075
+ "aria-label": "AI \u5F53\u524D\u8FDE\u63A5",
23076
+ value: profile.id,
23077
+ options: settings.profiles.map((item, index) => ({
23078
+ value: item.id,
23079
+ label: item.name.trim() || item.baseUrl.trim() || `\u8FDE\u63A5 ${index + 1}`
23080
+ })),
23081
+ allowClear: false,
23082
+ showSearch: false,
23083
+ popupZIndex: 1100,
23084
+ onChange: (value) => onSettingsChange({
23085
+ ...settings,
23086
+ activeProfileId: value
23087
+ })
23088
+ }
23089
+ )
23090
+ ] }),
23091
+ /* @__PURE__ */ jsx(
23092
+ ReactButton,
23093
+ {
23094
+ onClick: () => {
23095
+ const created = createPrintDesignAiChatProfile();
23096
+ onSettingsChange({
23097
+ profiles: [...settings.profiles, created],
23098
+ activeProfileId: created.id
23099
+ });
23100
+ },
23101
+ children: "\u65B0\u589E"
23102
+ }
23103
+ ),
23104
+ /* @__PURE__ */ jsx(
23105
+ ReactButton,
23106
+ {
23107
+ danger: true,
23108
+ disabled: settings.profiles.length <= 1,
23109
+ onClick: () => {
23110
+ const profiles = settings.profiles.filter(
23111
+ (item) => item.id !== profile.id
23112
+ );
23113
+ onSettingsChange({ profiles, activeProfileId: profiles[0].id });
23114
+ },
23115
+ children: "\u5220\u9664"
23116
+ }
23117
+ )
23118
+ ] }),
23119
+ /* @__PURE__ */ jsxs("label", { children: [
23120
+ "\u8FDE\u63A5\u540D\u79F0",
23121
+ /* @__PURE__ */ jsx(
23122
+ ReactInput,
23123
+ {
23124
+ "aria-label": "AI \u8FDE\u63A5\u540D\u79F0",
23125
+ value: profile.name,
23126
+ onChange: (event) => updateProfile({ name: event.target.value }),
23127
+ placeholder: "\u53EF\u9009\uFF0C\u7528\u4E8E\u533A\u5206\u591A\u4E2A\u8FDE\u63A5"
23128
+ }
23129
+ )
23130
+ ] }),
23131
+ /* @__PURE__ */ jsxs("label", { children: [
23132
+ "Base URL",
23133
+ /* @__PURE__ */ jsx(
23134
+ ReactInput,
23135
+ {
23136
+ "aria-label": "AI Base URL",
23137
+ value: profile.baseUrl,
23138
+ onChange: (event) => updateProfile({ baseUrl: event.target.value }),
23139
+ placeholder: "https://example.com/v1"
23140
+ }
23141
+ )
23142
+ ] }),
23143
+ /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-key-row", children: [
23144
+ /* @__PURE__ */ jsxs("label", { children: [
23145
+ "API Key",
23146
+ /* @__PURE__ */ jsx(
23147
+ ReactInput,
23148
+ {
23149
+ "aria-label": "AI API Key",
23150
+ type: "password",
23151
+ autoComplete: "off",
23152
+ value: profile.key,
23153
+ onChange: (event) => updateProfile({ key: event.target.value })
23154
+ }
23155
+ )
23156
+ ] }),
23157
+ /* @__PURE__ */ jsx(ReactButton, { onClick: onLoadModels, disabled: modelLoading, children: modelLoading ? "\u8BFB\u53D6\u4E2D\u2026" : "\u83B7\u53D6\u6A21\u578B" })
23158
+ ] }),
23159
+ /* @__PURE__ */ jsxs("label", { children: [
23160
+ "\u6A21\u578B",
23161
+ /* @__PURE__ */ jsx(
23162
+ ReactSelect,
23163
+ {
23164
+ "aria-label": "AI \u6A21\u578B",
23165
+ value: profile.model,
23166
+ options: models.map((model) => ({ label: model, value: model })),
23167
+ showSearch: true,
23168
+ allowCustomValue: true,
23169
+ popupZIndex: 1100,
23170
+ onChange: (value) => updateProfile({ model: value }),
23171
+ onInputValueChange: (value) => updateProfile({ model: value }),
23172
+ placeholder: "\u9009\u62E9\u6216\u8F93\u5165\u6A21\u578B ID"
23173
+ }
23174
+ )
23175
+ ] }),
23176
+ /* @__PURE__ */ jsxs("label", { children: [
23177
+ "\u601D\u8003\u7A0B\u5EA6",
23178
+ /* @__PURE__ */ jsx(
23179
+ ReactSelect,
23180
+ {
23181
+ "aria-label": "AI \u601D\u8003\u7A0B\u5EA6",
23182
+ value: profile.reasoningEffort ?? "",
23183
+ options: reasoningEffortOptions,
23184
+ allowClear: false,
23185
+ showSearch: false,
23186
+ popupZIndex: 1100,
23187
+ onChange: (value) => updateProfile({ reasoningEffort: parseReasoningEffort(value) })
23188
+ }
23189
+ )
23190
+ ] }),
23191
+ /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-settings-actions", children: [
23192
+ /* @__PURE__ */ jsx(ReactButton, { onClick: onCancel, children: "\u53D6\u6D88" }),
23193
+ /* @__PURE__ */ jsx(ReactButton, { type: "primary", onClick: onSave, children: "\u4FDD\u5B58" })
23194
+ ] })
23195
+ ] });
23196
+ }
23197
+ function ChatPanelWidthSettings({
23198
+ widths,
23199
+ onWidthsChange,
23200
+ onSave,
23201
+ onCancel
23202
+ }) {
23203
+ return /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-settings", children: [
23204
+ /* @__PURE__ */ jsx("strong", { children: "\u5BF9\u8BDD\u9762\u677F\u5BBD\u5EA6\uFF08px\uFF09" }),
23205
+ /* @__PURE__ */ jsx("div", { className: "cc-print-design-ai-width-fields", children: ["min", "max", "current"].map((field) => {
23206
+ const label = { min: "\u6700\u5C0F", max: "\u6700\u5927", current: "\u5F53\u524D" }[field];
23207
+ return /* @__PURE__ */ jsxs("label", { children: [
23208
+ label,
23209
+ /* @__PURE__ */ jsx(
23210
+ ReactInputNumber,
23211
+ {
23212
+ "aria-label": `AI \u9762\u677F${label}\u5BBD\u5EA6`,
23213
+ min: field === "min" ? 240 : 0,
23214
+ max: field === "max" ? 1600 : void 0,
23215
+ value: widths[field],
23216
+ onChange: (value) => {
23217
+ if (value !== null)
23218
+ onWidthsChange({ ...widths, [field]: value });
23219
+ }
23220
+ }
23221
+ )
23222
+ ] }, field);
23223
+ }) }),
23224
+ /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-settings-actions", children: [
23225
+ /* @__PURE__ */ jsx(ReactButton, { onClick: onCancel, children: "\u53D6\u6D88" }),
23226
+ /* @__PURE__ */ jsx(ReactButton, { type: "primary", onClick: onSave, children: "\u4FDD\u5B58" })
23227
+ ] })
23228
+ ] });
23229
+ }
23230
+ function ChatHistory({
23231
+ conversations,
23232
+ activeId,
23233
+ busy,
23234
+ onSelect,
23235
+ onDelete
23236
+ }) {
23237
+ const [deletingId, setDeletingId] = useState(null);
23238
+ return /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-history", children: [
23239
+ conversations.length === 0 && /* @__PURE__ */ jsx("p", { children: "\u6682\u65E0\u5386\u53F2\u5BF9\u8BDD" }),
23240
+ conversations.map((conversation) => /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-history-item", children: [
23241
+ /* @__PURE__ */ jsxs(
23242
+ ReactButton,
23243
+ {
23244
+ type: "text",
23245
+ className: activeId === conversation.id ? "active" : "",
23246
+ disabled: busy,
23247
+ onClick: () => onSelect(conversation.id),
23248
+ title: conversation.title,
23249
+ children: [
23250
+ /* @__PURE__ */ jsx("span", { children: conversation.title }),
23251
+ /* @__PURE__ */ jsx("small", { children: new Date(conversation.updatedAt).toLocaleString() })
23252
+ ]
23253
+ }
23254
+ ),
23255
+ /* @__PURE__ */ jsx(
23256
+ ReactButton,
23257
+ {
23258
+ type: "text",
23259
+ danger: true,
23260
+ className: "cc-print-design-ai-history-delete",
23261
+ disabled: busy,
23262
+ onClick: () => {
23263
+ if (deletingId === conversation.id) {
23264
+ onDelete(conversation.id);
23265
+ setDeletingId(null);
23266
+ } else setDeletingId(conversation.id);
23267
+ },
23268
+ "aria-label": `${deletingId === conversation.id ? "\u786E\u8BA4\u5220\u9664" : "\u5220\u9664"}\u5BF9\u8BDD ${conversation.title}`,
23269
+ children: deletingId === conversation.id ? "\u786E\u8BA4\u5220\u9664" : "\u5220\u9664"
23270
+ }
23271
+ )
23272
+ ] }, conversation.id))
23273
+ ] });
23274
+ }
23275
+ function ChatSettingsDialog(props) {
23276
+ const [tab, setTab] = useState("basic");
23277
+ useEffect(() => {
23278
+ if (props.open) setTab("basic");
23279
+ }, [props.open]);
23280
+ return /* @__PURE__ */ jsx(
23281
+ ReactModal,
23282
+ {
23283
+ open: props.open,
23284
+ title: "AI \u5BF9\u8BDD\u914D\u7F6E",
23285
+ width: 720,
23286
+ centered: true,
23287
+ fullscreenable: false,
23288
+ footer: false,
23289
+ style: { height: 576 },
23290
+ bodyStyle: {
23291
+ padding: 0,
23292
+ overflow: "hidden"
23293
+ },
23294
+ onCancel: props.onClose,
23295
+ className: "cc-print-design-ai-dialog",
23296
+ children: /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-dialog-layout", children: [
23297
+ /* @__PURE__ */ jsxs("nav", { className: "cc-print-design-ai-dialog-nav", "aria-label": "AI \u5BF9\u8BDD\u914D\u7F6E", children: [
23298
+ /* @__PURE__ */ jsx(
23299
+ ReactButton,
23300
+ {
23301
+ type: "text",
23302
+ "aria-current": tab === "basic" ? "page" : void 0,
23303
+ onClick: () => setTab("basic"),
23304
+ children: "\u57FA\u7840\u914D\u7F6E"
23305
+ }
23306
+ ),
23307
+ /* @__PURE__ */ jsx(
23308
+ ReactButton,
23309
+ {
23310
+ type: "text",
23311
+ "aria-current": tab === "width" ? "page" : void 0,
23312
+ onClick: () => setTab("width"),
23313
+ children: "\u5916\u89C2\u914D\u7F6E"
23314
+ }
23315
+ ),
23316
+ /* @__PURE__ */ jsx(
23317
+ ReactButton,
23318
+ {
23319
+ type: "text",
23320
+ "aria-current": tab === "history" ? "page" : void 0,
23321
+ onClick: () => setTab("history"),
23322
+ children: "\u5386\u53F2\u5BF9\u8BDD"
23323
+ }
23324
+ )
23325
+ ] }),
23326
+ /* @__PURE__ */ jsx("div", { className: "cc-print-design-ai-dialog-content", children: tab === "basic" ? /* @__PURE__ */ jsx(
23327
+ ChatSettings,
23328
+ {
23329
+ settings: props.settings,
23330
+ models: props.models,
23331
+ modelLoading: props.modelLoading,
23332
+ onSettingsChange: props.onSettingsChange,
23333
+ onLoadModels: props.onLoadModels,
23334
+ onSave: props.onSave,
23335
+ onCancel: props.onClose
23336
+ }
23337
+ ) : tab === "width" ? /* @__PURE__ */ jsx(
23338
+ ChatPanelWidthSettings,
23339
+ {
23340
+ widths: props.widths,
23341
+ onWidthsChange: props.onWidthsChange,
23342
+ onSave: props.onSave,
23343
+ onCancel: props.onClose
23344
+ }
23345
+ ) : /* @__PURE__ */ jsx(
23346
+ ChatHistory,
23347
+ {
23348
+ conversations: props.conversations,
23349
+ activeId: props.activeId,
23350
+ busy: props.busy,
23351
+ onSelect: props.onSelectConversation,
23352
+ onDelete: props.onDeleteConversation
23353
+ }
23354
+ ) })
23355
+ ] })
23356
+ }
23357
+ );
23358
+ }
23359
+ function ChatComposer({
23360
+ input,
23361
+ model,
23362
+ models,
23363
+ reasoningEffort,
23364
+ selection,
23365
+ onInputChange,
23366
+ onModelChange,
23367
+ onReasoningEffortChange,
23368
+ onRemoveSelectedElement,
23369
+ onOpenSettings,
23370
+ onSend
23371
+ }) {
23372
+ const handleKeyDown = (event) => {
23373
+ if (event.key === "Enter" && !event.shiftKey) {
23374
+ event.preventDefault();
23375
+ event.currentTarget.form?.requestSubmit();
23376
+ }
23377
+ };
23378
+ return /* @__PURE__ */ jsxs("form", { className: "cc-print-design-ai-composer", onSubmit: onSend, children: [
23379
+ selection?.elements.length ? /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-selection", "aria-label": "\u5F53\u524D\u9009\u4E2D\u5185\u5BB9", children: [
23380
+ /* @__PURE__ */ jsxs("span", { children: [
23381
+ "\u5F53\u524D\u9009\u4E2D \xB7 ",
23382
+ selection.pageName || "\u5F53\u524D\u9875",
23383
+ " \xB7",
23384
+ " ",
23385
+ selection.elements.length
23386
+ ] }),
23387
+ /* @__PURE__ */ jsx("div", { className: "cc-print-design-ai-selection-items", children: selection.elements.map((element) => /* @__PURE__ */ jsxs(
23388
+ ReactTag,
23389
+ {
23390
+ className: "cc-print-design-ai-selection-item",
23391
+ title: `${element.label} \xB7 ${element.type}${element.preview ? ` \xB7 ${element.preview}` : ""}`,
23392
+ closeLabel: `\u4ECE\u804A\u5929\u76EE\u6807\u4E2D\u79FB\u9664 ${element.label}`,
23393
+ onClose: () => onRemoveSelectedElement(element.id),
23394
+ children: [
23395
+ /* @__PURE__ */ jsx("strong", { children: element.label }),
23396
+ element.preview ? /* @__PURE__ */ jsx("small", { children: element.preview }) : null
23397
+ ]
23398
+ },
23399
+ element.id
23400
+ )) })
23401
+ ] }) : null,
23402
+ /* @__PURE__ */ jsx(
23403
+ "textarea",
23404
+ {
23405
+ "aria-label": "\u53D1\u9001\u7ED9 AI",
23406
+ value: input,
23407
+ onChange: (event) => onInputChange(event.target.value),
23408
+ onKeyDown: handleKeyDown,
23409
+ placeholder: "\u8F93\u5165\u6D88\u606F\uFF0CEnter \u53D1\u9001\uFF0CShift+Enter \u6362\u884C",
23410
+ rows: 3
23411
+ }
23412
+ ),
23413
+ /* @__PURE__ */ jsxs("div", { className: "cc-print-design-ai-composer-tools", children: [
23414
+ /* @__PURE__ */ jsx(
23415
+ "button",
23416
+ {
23417
+ type: "button",
23418
+ className: "cc-print-design-ai-composer-more",
23419
+ "aria-label": "\u66F4\u591A AI \u8BBE\u7F6E",
23420
+ title: "\u6A21\u578B\u914D\u7F6E",
23421
+ onClick: onOpenSettings,
23422
+ children: /* @__PURE__ */ jsx(ReactMoreOutlined, { "aria-hidden": "true" })
23423
+ }
23424
+ ),
23425
+ /* @__PURE__ */ jsx(
23426
+ ReactSelect,
23427
+ {
23428
+ "aria-label": "AI \u5F53\u524D\u6A21\u578B",
23429
+ value: model,
23430
+ options: models.map((item) => ({ label: item, value: item })),
23431
+ allowClear: false,
23432
+ allowCustomValue: true,
23433
+ placeholder: "\u9009\u62E9\u6A21\u578B",
23434
+ popupZIndex: 1100,
23435
+ onChange: onModelChange
23436
+ }
23437
+ ),
23438
+ /* @__PURE__ */ jsx(
23439
+ ReactSelect,
23440
+ {
23441
+ "aria-label": "AI \u5F53\u524D\u601D\u8003\u7A0B\u5EA6",
23442
+ value: reasoningEffort ?? "",
23443
+ options: reasoningEffortOptions,
23444
+ allowClear: false,
23445
+ showSearch: false,
23446
+ popupZIndex: 1100,
23447
+ onChange: (value) => onReasoningEffortChange(parseReasoningEffort(value))
23448
+ }
23449
+ )
23450
+ ] })
23451
+ ] });
23452
+ }
23453
+ function ChatNoticeDialog({ message, onClose }) {
23454
+ return /* @__PURE__ */ jsx(
23455
+ ReactModal,
23456
+ {
23457
+ open: Boolean(message),
23458
+ title: "AI \u5BF9\u8BDD\u63D0\u793A",
23459
+ width: 420,
23460
+ centered: true,
23461
+ fullscreenable: false,
23462
+ zIndex: 1200,
23463
+ onCancel: onClose,
23464
+ footer: /* @__PURE__ */ jsx(ReactButton, { type: "primary", onClick: onClose, children: "\u77E5\u9053\u4E86" }),
23465
+ children: /* @__PURE__ */ jsx("p", { role: "alert", children: message })
23466
+ }
23467
+ );
23468
+ }
23469
+
23470
+ // src/ai-chat/model/selection-agent-api.ts
23471
+ var changesSelection = /* @__PURE__ */ new Set([
23472
+ "set_active_page",
23473
+ "select_elements",
23474
+ "add_element",
23475
+ "remove_elements",
23476
+ "undo",
23477
+ "redo"
23478
+ ]);
23479
+ function createSelectionScopedAgentApi(agentApi, selection) {
23480
+ if (!selection) return agentApi;
23481
+ let useSnapshot = true;
23482
+ return {
23483
+ tools: agentApi.tools,
23484
+ call(name, input) {
23485
+ if (name === "get_selection" && useSnapshot)
23486
+ return {
23487
+ pageId: selection.pageId,
23488
+ elementIds: selection.elements.map((item) => item.id)
23489
+ };
23490
+ const result = agentApi.call(name, input);
23491
+ if (changesSelection.has(name)) useSnapshot = false;
23492
+ return result;
23493
+ }
23494
+ };
23495
+ }
23496
+
23497
+ // src/ai-chat/persistence/conversation-history.ts
23498
+ var DATABASE2 = "canvas-components-print-design-ai-chat-history";
23499
+ var STORE2 = "conversations";
23500
+ async function openDatabase2() {
23501
+ if (typeof indexedDB === "undefined") return null;
23502
+ return new Promise((resolve, reject) => {
23503
+ const request = indexedDB.open(DATABASE2, 1);
23504
+ request.onupgradeneeded = () => request.result.createObjectStore(STORE2, { keyPath: "id" });
23505
+ request.onsuccess = () => resolve(request.result);
23506
+ request.onerror = () => reject(request.error);
23507
+ });
23508
+ }
23509
+ async function access(mode, action, fallback) {
23510
+ const database = await openDatabase2();
23511
+ if (!database) return fallback;
23512
+ return new Promise((resolve, reject) => {
23513
+ const transaction = database.transaction(STORE2, mode);
23514
+ let result = fallback;
23515
+ action(transaction.objectStore(STORE2), (value) => {
23516
+ result = value;
23517
+ });
23518
+ transaction.oncomplete = () => {
23519
+ database.close();
23520
+ resolve(result);
23521
+ };
23522
+ transaction.onerror = () => {
23523
+ database.close();
23524
+ reject(transaction.error);
23525
+ };
23526
+ transaction.onabort = () => {
23527
+ database.close();
23528
+ reject(transaction.error);
23529
+ };
23530
+ });
23531
+ }
23532
+ async function listPrintDesignAiChatConversations() {
23533
+ const records = await access(
23534
+ "readonly",
23535
+ (store, setResult) => {
23536
+ const request = store.getAll();
23537
+ request.onsuccess = () => setResult(request.result);
23538
+ },
23539
+ []
23540
+ );
23541
+ return records.filter(
23542
+ (item) => item && typeof item.id === "string" && Array.isArray(item.messages)
23543
+ ).sort((a, b) => b.updatedAt - a.updatedAt);
23544
+ }
23545
+ function readPrintDesignAiChatConversation(id) {
23546
+ return access(
23547
+ "readonly",
23548
+ (store, setResult) => {
23549
+ const request = store.get(id);
23550
+ request.onsuccess = () => setResult(
23551
+ request.result ?? null
23552
+ );
23553
+ },
23554
+ null
23555
+ );
23556
+ }
23557
+ function savePrintDesignAiChatConversation(value) {
23558
+ return access(
23559
+ "readwrite",
23560
+ (store) => {
23561
+ store.put(value);
23562
+ },
23563
+ void 0
23564
+ );
23565
+ }
23566
+ function deletePrintDesignAiChatConversation(id) {
23567
+ return access(
23568
+ "readwrite",
23569
+ (store) => {
23570
+ store.delete(id);
23571
+ },
23572
+ void 0
23573
+ );
23574
+ }
23575
+
23576
+ // src/ai-chat/hooks/use-chat-session.ts
23577
+ function conversationId() {
23578
+ return globalThis.crypto?.randomUUID?.() ?? `chat-${Date.now()}-${Math.random().toString(36).slice(2)}`;
23579
+ }
23580
+ function useChatSession(provider, agentApi) {
23581
+ const [conversations, setConversations] = useState([]);
23582
+ const [activeId, setActiveId] = useState(null);
23583
+ const [messages, setMessages] = useState([]);
23584
+ const [busy, setBusy] = useState(false);
23585
+ const [pendingModel, setPendingModel] = useState("");
23586
+ const [streaming, setStreaming] = useState(null);
23587
+ const [error, setError] = useState("");
23588
+ const nextMessageId = useRef(1);
23589
+ const controller = useRef(null);
23590
+ const activeConversation = useRef(null);
23591
+ const pendingWrite = useRef(Promise.resolve());
23592
+ useEffect(() => {
23593
+ let alive = true;
23594
+ void listPrintDesignAiChatConversations().then((items) => {
23595
+ if (alive)
23596
+ setConversations(
23597
+ (current2) => [
23598
+ ...current2,
23599
+ ...items.filter(
23600
+ (item) => !current2.some((existing) => existing.id === item.id)
23601
+ )
23602
+ ].sort((a, b) => b.updatedAt - a.updatedAt)
23603
+ );
23604
+ }).catch(() => {
23605
+ if (alive) setError("\u5386\u53F2\u5BF9\u8BDD\u8BFB\u53D6\u5931\u8D25\u3002");
23606
+ });
23607
+ return () => {
23608
+ alive = false;
23609
+ controller.current?.abort();
23610
+ };
23611
+ }, []);
23612
+ const persist = async (conversation) => {
23613
+ activeConversation.current = conversation;
23614
+ setConversations((current2) => [
23615
+ conversation,
23616
+ ...current2.filter((item) => item.id !== conversation.id)
23617
+ ]);
23618
+ pendingWrite.current = pendingWrite.current.catch(() => void 0).then(() => savePrintDesignAiChatConversation(conversation));
23619
+ try {
23620
+ await pendingWrite.current;
23621
+ } catch {
23622
+ setError("\u5386\u53F2\u5BF9\u8BDD\u65E0\u6CD5\u4FDD\u5B58\u5230\u5F53\u524D\u6D4F\u89C8\u5668\u3002");
23623
+ }
23624
+ };
23625
+ const send = async (content, config) => {
23626
+ if (!content.trim() || busy) return;
23627
+ if (!config.baseUrl || !config.model) {
23628
+ setError("\u8BF7\u5148\u914D\u7F6E\u6A21\u578B\u3002");
23629
+ return;
23630
+ }
23631
+ const user = {
23632
+ id: nextMessageId.current++,
23633
+ role: "user",
23634
+ content: content.trim()
23635
+ };
23636
+ const now = Date.now();
23637
+ const previous = activeConversation.current;
23638
+ const conversation = {
23639
+ id: previous?.id ?? conversationId(),
23640
+ title: previous?.title ?? content.trim().slice(0, 36),
23641
+ createdAt: previous?.createdAt ?? now,
23642
+ updatedAt: now,
23643
+ messages: [...messages, user]
23644
+ };
23645
+ setActiveId(conversation.id);
23646
+ setMessages(conversation.messages);
23647
+ setBusy(true);
23648
+ setPendingModel(config.model);
23649
+ setStreaming({ content: "", reasoning: "", reasoningLength: 0 });
23650
+ setError("");
23651
+ void persist(conversation);
23652
+ const abort = new AbortController();
23653
+ controller.current = abort;
23654
+ try {
23655
+ const requestMessages = conversation.messages.map(
23656
+ ({ role, content: text, reasoning }) => ({
23657
+ role,
23658
+ content: text,
23659
+ ...reasoning ? { reasoning } : {}
23660
+ })
23661
+ );
23662
+ const requestAgentApi = createSelectionScopedAgentApi(
23663
+ agentApi,
23664
+ config.selection
23665
+ );
23666
+ const answer = provider.stream ? await provider.stream(
23667
+ config,
23668
+ requestMessages,
23669
+ (delta) => setStreaming(
23670
+ (current2) => current2 ? {
23671
+ content: current2.content + (delta.content ?? ""),
23672
+ reasoning: (current2.reasoning + (delta.reasoning ?? "")).slice(-LIVE_REASONING_LIMIT),
23673
+ reasoningLength: current2.reasoningLength + (delta.reasoning?.length ?? 0)
23674
+ } : current2
23675
+ ),
23676
+ abort.signal,
23677
+ requestAgentApi
23678
+ ) : {
23679
+ content: await provider.complete(
23680
+ config,
23681
+ requestMessages,
23682
+ abort.signal,
23683
+ requestAgentApi
23684
+ )
23685
+ };
23686
+ const completed = {
23687
+ ...conversation,
23688
+ updatedAt: Date.now(),
23689
+ messages: [
23690
+ ...conversation.messages,
23691
+ {
23692
+ id: nextMessageId.current++,
23693
+ role: "assistant",
23694
+ content: answer.content,
23695
+ model: config.model,
23696
+ ..."reasoning" in answer && answer.reasoning ? { reasoning: answer.reasoning } : {}
23697
+ }
23698
+ ]
23699
+ };
23700
+ setMessages(completed.messages);
23701
+ await persist(completed);
23702
+ } catch (cause) {
23703
+ if (!abort.signal.aborted)
23704
+ setError(cause instanceof Error ? cause.message : "\u5BF9\u8BDD\u5931\u8D25\u3002");
23705
+ } finally {
23706
+ controller.current = null;
23707
+ setBusy(false);
23708
+ setPendingModel("");
23709
+ setStreaming(null);
23710
+ }
23711
+ };
23712
+ const select = async (id) => {
23713
+ if (busy) return false;
23714
+ const conversation = conversations.find((item) => item.id === id) ?? await readPrintDesignAiChatConversation(id);
23715
+ if (!conversation) {
23716
+ setError("\u627E\u4E0D\u5230\u8FD9\u6BB5\u5386\u53F2\u5BF9\u8BDD\u3002");
23717
+ return false;
23718
+ }
23719
+ activeConversation.current = conversation;
23720
+ setActiveId(id);
23721
+ setMessages(conversation.messages);
23722
+ nextMessageId.current = Math.max(0, ...conversation.messages.map((item) => item.id)) + 1;
23723
+ setError("");
23724
+ return true;
23725
+ };
23726
+ const remove = async (id) => {
23727
+ if (busy) return;
23728
+ await pendingWrite.current.catch(() => void 0);
23729
+ await deletePrintDesignAiChatConversation(id);
23730
+ setConversations((current2) => current2.filter((item) => item.id !== id));
23731
+ if (activeConversation.current?.id === id) newConversation();
23732
+ };
23733
+ const newConversation = () => {
23734
+ if (busy) return;
23735
+ activeConversation.current = null;
23736
+ setActiveId(null);
23737
+ setMessages([]);
23738
+ nextMessageId.current = 1;
23739
+ setError("");
23740
+ };
23741
+ return {
23742
+ conversations,
23743
+ activeId,
23744
+ messages,
23745
+ busy,
23746
+ pendingModel,
23747
+ streaming,
23748
+ error,
23749
+ setError,
23750
+ send,
23751
+ select,
23752
+ remove,
23753
+ newConversation
23754
+ };
23755
+ }
23756
+ function PrintDesignAiChatPanel({
23757
+ options,
23758
+ onClose,
23759
+ panelWidths,
23760
+ onPanelWidthsChange,
23761
+ agentApi,
23762
+ selection
23763
+ }) {
23764
+ const provider = options.provider ?? defaultPrintDesignAiChatProvider;
23765
+ const [settings, setSettings] = useState(
23766
+ () => createInitialPrintDesignAiChatSettings(options.defaultConfig)
23767
+ );
23768
+ const [draftSettings, setDraftSettings] = useState(settings);
23769
+ const [draftWidths, setDraftWidths] = useState(panelWidths);
23770
+ const [storageReady, setStorageReady] = useState(false);
23771
+ const [settingsOpen, setSettingsOpen] = useState(false);
23772
+ const [modelLoading, setModelLoading] = useState(false);
23773
+ const [input, setInput] = useState("");
23774
+ const selectionKey = selection ? JSON.stringify([
23775
+ selection.pageId,
23776
+ ...selection.elements.map((item) => item.id)
23777
+ ]) : "";
23778
+ const [removedSelection, setRemovedSelection] = useState({ key: selectionKey, ids: [] });
23779
+ const removedIds = removedSelection.key === selectionKey ? removedSelection.ids : [];
23780
+ const attachedSelection = selection ? {
23781
+ ...selection,
23782
+ elements: selection.elements.filter(
23783
+ (item) => !removedIds.includes(item.id)
23784
+ )
23785
+ } : void 0;
23786
+ const session = useChatSession(provider, agentApi);
23787
+ const { messages, busy, error, setError } = session;
23788
+ const activeProfile = activePrintDesignAiChatProfile(settings);
23789
+ const draftProfile = activePrintDesignAiChatProfile(draftSettings);
23790
+ const modelsFor = (profile) => profile.models ?? [];
23791
+ useEffect(() => {
23792
+ setRemovedSelection({ key: selectionKey, ids: [] });
23793
+ }, [selectionKey]);
23794
+ useEffect(() => {
23795
+ let alive = true;
23796
+ const savedWidths = readPrintDesignAiChatPanelWidths();
23797
+ if (savedWidths) {
23798
+ onPanelWidthsChange(savedWidths);
23799
+ setDraftWidths(savedWidths);
23800
+ }
23801
+ void readPrintDesignAiChatSettings().then((saved) => {
23802
+ if (alive && saved) {
23803
+ setSettings(saved);
23804
+ setDraftSettings(saved);
23805
+ if (saved.panelWidths && !savedWidths) {
23806
+ onPanelWidthsChange(saved.panelWidths);
23807
+ setDraftWidths(saved.panelWidths);
23808
+ }
23809
+ } else if (alive && options.defaultConfig?.baseUrl && options.defaultConfig.key && options.defaultConfig.model) {
23810
+ void savePrintDesignAiChatSettings({
23811
+ ...settings,
23812
+ panelWidths
23813
+ }).catch(() => {
23814
+ });
23815
+ }
23816
+ }).catch(() => {
23817
+ if (alive) setError("\u5DF2\u4FDD\u5B58\u7684 AI \u914D\u7F6E\u65E0\u6CD5\u89E3\u5BC6\u3002");
23818
+ }).finally(() => {
23819
+ if (alive) setStorageReady(true);
23820
+ });
23821
+ return () => {
23822
+ alive = false;
23823
+ };
23824
+ }, []);
23825
+ useEffect(() => {
23826
+ if (!storageReady) return;
23827
+ const timer = window.setTimeout(() => {
23828
+ savePrintDesignAiChatPanelWidths(panelWidths);
23829
+ }, 400);
23830
+ return () => window.clearTimeout(timer);
23831
+ }, [panelWidths, storageReady]);
23832
+ const loadModels = async () => {
23833
+ setModelLoading(true);
23834
+ setError("");
23835
+ try {
23836
+ const selected = activePrintDesignAiChatProfile(draftSettings);
23837
+ const models = await provider.listModels(selected);
23838
+ setDraftSettings((current2) => ({
23839
+ ...current2,
23840
+ profiles: current2.profiles.map(
23841
+ (profile) => profile.id === selected.id && profile.baseUrl === selected.baseUrl && profile.key === selected.key ? { ...profile, models: [...new Set(models)] } : profile
23842
+ )
23843
+ }));
23844
+ } catch (cause) {
23845
+ setError(cause instanceof Error ? cause.message : "\u83B7\u53D6\u6A21\u578B\u5217\u8868\u5931\u8D25\u3002");
23846
+ } finally {
23847
+ setModelLoading(false);
23848
+ }
23849
+ };
23850
+ const saveConfig = async () => {
23851
+ const widths = normalizePrintDesignAiChatPanelWidths(draftWidths);
23852
+ const next = { ...draftSettings, panelWidths: widths };
23853
+ savePrintDesignAiChatPanelWidths(widths);
23854
+ onPanelWidthsChange(widths);
23855
+ setDraftWidths(widths);
23856
+ setSettings(next);
23857
+ setSettingsOpen(false);
23858
+ try {
23859
+ await savePrintDesignAiChatSettings(next);
23860
+ setError("");
23861
+ } catch {
23862
+ setError("\u6A21\u578B\u914D\u7F6E\u4EC5\u5728\u672C\u6B21\u4F1A\u8BDD\u53EF\u7528\uFF1B\u52A0\u5BC6\u4FDD\u5B58\u9700\u8981 HTTPS \u6216 localhost\u3002");
23863
+ }
23864
+ };
23865
+ const send = (event) => {
23866
+ event.preventDefault();
23867
+ const content = input.trim();
23868
+ if (!content || busy) return;
23869
+ const selected = activePrintDesignAiChatProfile(settings);
23870
+ if (!selected.baseUrl || !selected.model) {
23871
+ setSettingsOpen(true);
23872
+ setError("\u8BF7\u5148\u914D\u7F6E\u6A21\u578B\u3002");
23873
+ return;
23874
+ }
23875
+ setInput("");
23876
+ void session.send(content, {
23877
+ ...selected,
23878
+ ...attachedSelection ? { selection: attachedSelection } : {}
23879
+ });
23880
+ };
23881
+ const updateActiveProfile = (patch) => {
23882
+ const next = {
23883
+ ...settings,
23884
+ profiles: settings.profiles.map(
23885
+ (profile) => profile.id === activeProfile.id ? { ...profile, ...patch } : profile
23886
+ )
23887
+ };
23888
+ setSettings(next);
23889
+ setDraftSettings(next);
23890
+ void savePrintDesignAiChatSettings(next).catch(
23891
+ () => setError("\u6A21\u578B\u914D\u7F6E\u4EC5\u5728\u672C\u6B21\u4F1A\u8BDD\u53EF\u7528\uFF1B\u52A0\u5BC6\u4FDD\u5B58\u9700\u8981 HTTPS \u6216 localhost\u3002")
23892
+ );
23893
+ };
23894
+ return /* @__PURE__ */ jsxs("section", { className: "cc-print-design-ai-panel", "aria-label": "AI \u5BF9\u8BDD", children: [
23895
+ /* @__PURE__ */ jsxs("header", { className: "cc-print-design-ai-header", children: [
23896
+ /* @__PURE__ */ jsx("strong", { children: "AI \u5BF9\u8BDD" }),
23897
+ /* @__PURE__ */ jsxs("div", { children: [
23898
+ /* @__PURE__ */ jsx(
23899
+ "button",
23900
+ {
23901
+ type: "button",
23902
+ disabled: busy,
23903
+ onClick: session.newConversation,
23904
+ children: "\u65B0\u5BF9\u8BDD"
23905
+ }
23906
+ ),
23907
+ /* @__PURE__ */ jsx("button", { type: "button", "aria-label": "\u5173\u95ED AI \u5BF9\u8BDD", onClick: onClose, children: "\xD7" })
23908
+ ] })
23909
+ ] }),
23910
+ /* @__PURE__ */ jsx(
23911
+ VirtualMessages,
23912
+ {
23913
+ messages,
23914
+ currentModel: activeProfile.model,
23915
+ busy,
23916
+ pendingModel: session.pendingModel,
23917
+ streaming: session.streaming
23918
+ }
23919
+ ),
23920
+ /* @__PURE__ */ jsx(
23921
+ ChatSettingsDialog,
23922
+ {
23923
+ open: settingsOpen,
23924
+ settings: draftSettings,
23925
+ widths: draftWidths,
23926
+ models: modelsFor(draftProfile),
23927
+ modelLoading,
23928
+ conversations: session.conversations,
23929
+ activeId: session.activeId,
23930
+ busy,
23931
+ onSettingsChange: setDraftSettings,
23932
+ onWidthsChange: setDraftWidths,
23933
+ onLoadModels: () => void loadModels(),
23934
+ onSave: () => void saveConfig(),
23935
+ onClose: () => setSettingsOpen(false),
23936
+ onSelectConversation: (id) => {
23937
+ void session.select(id).then((selected) => {
23938
+ if (selected) setSettingsOpen(false);
23939
+ }).catch(
23940
+ (cause) => setError(
23941
+ cause instanceof Error ? cause.message : "\u5386\u53F2\u5BF9\u8BDD\u8BFB\u53D6\u5931\u8D25\u3002"
23942
+ )
23943
+ );
23944
+ },
23945
+ onDeleteConversation: (id) => {
23946
+ void session.remove(id).catch(
23947
+ (cause) => setError(
23948
+ cause instanceof Error ? cause.message : "\u5386\u53F2\u5BF9\u8BDD\u5220\u9664\u5931\u8D25\u3002"
23949
+ )
23950
+ );
23951
+ }
23952
+ }
23953
+ ),
23954
+ /* @__PURE__ */ jsx(ChatNoticeDialog, { message: error, onClose: () => setError("") }),
23955
+ /* @__PURE__ */ jsx(
23956
+ ChatComposer,
23957
+ {
23958
+ input,
23959
+ model: activeProfile.model,
23960
+ models: modelsFor(activeProfile),
23961
+ reasoningEffort: activeProfile.reasoningEffort,
23962
+ selection: attachedSelection,
23963
+ onRemoveSelectedElement: (id) => setRemovedSelection((current2) => ({
23964
+ key: selectionKey,
23965
+ ids: current2.key === selectionKey ? [.../* @__PURE__ */ new Set([...current2.ids, id])] : [id]
23966
+ })),
23967
+ onInputChange: setInput,
23968
+ onModelChange: (model) => updateActiveProfile({ model }),
23969
+ onReasoningEffortChange: (reasoningEffort) => updateActiveProfile({ reasoningEffort }),
23970
+ onOpenSettings: () => {
23971
+ setDraftSettings(settings);
23972
+ setDraftWidths(panelWidths);
23973
+ setSettingsOpen(true);
23974
+ },
23975
+ onSend: (event) => void send(event)
23976
+ }
23977
+ )
23978
+ ] });
23979
+ }
23980
+
23981
+ // src/ai-chat/index.ts
23982
+ function createPrintDesignAiChatPlugin(options = {}) {
23983
+ return {
23984
+ initialPanelWidths: normalizePrintDesignAiChatPanelWidths(
23985
+ options.panelWidths
23986
+ ),
23987
+ render: (context) => createElement(PrintDesignAiChatPanel, { options, ...context })
23988
+ };
23989
+ }
23990
+
21878
23991
  // src/react.ts
21879
23992
  var builtinReactTools = [
21880
23993
  debuggerTool,
@@ -21990,4 +24103,4 @@ var builtinPrintDesignPlugins = Object.freeze({
21990
24103
  )
21991
24104
  });
21992
24105
 
21993
- export { builtinPrintDesignPlugins, builtinReactComponentPlugins };
24106
+ export { builtinPrintDesignPlugins, builtinReactComponentPlugins, createPrintDesignAiChatPlugin };