heitu 1.0.7 → 1.0.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.
Files changed (33) hide show
  1. package/dist/canvas/core/shapes/circle.d.ts +4 -0
  2. package/dist/canvas/core/shapes/circle.js +15 -1
  3. package/dist/canvas/core/shapes/custom.d.ts +4 -0
  4. package/dist/canvas/core/shapes/custom.js +14 -0
  5. package/dist/canvas/core/shapes/group.d.ts +12 -0
  6. package/dist/canvas/core/shapes/group.js +65 -0
  7. package/dist/canvas/core/shapes/line.d.ts +11 -5
  8. package/dist/canvas/core/shapes/line.js +20 -0
  9. package/dist/canvas/core/shapes/node.d.ts +0 -6
  10. package/dist/canvas/core/shapes/node.js +45 -21
  11. package/dist/canvas/core/shapes/rect.d.ts +7 -1
  12. package/dist/canvas/core/shapes/rect.js +32 -5
  13. package/dist/canvas/core/shapes/text.d.ts +4 -0
  14. package/dist/canvas/core/shapes/text.js +14 -0
  15. package/dist/canvas/core/stage/container.d.ts +1 -1
  16. package/dist/canvas/core/stage/index.d.ts +3 -3
  17. package/dist/canvas/core/stage/index.js +2 -0
  18. package/dist/canvas/index.d.ts +1 -0
  19. package/dist/canvas/index.js +1 -0
  20. package/dist/hooks/index.d.ts +7 -4
  21. package/dist/hooks/index.js +8 -5
  22. package/dist/hooks/useCancelAsyncFn.d.ts +5 -5
  23. package/dist/hooks/useCancelAsyncFn.js +33 -34
  24. package/dist/hooks/useContainer/index.d.ts +13 -0
  25. package/dist/hooks/useContainer/index.js +62 -0
  26. package/dist/hooks/usePolling/index.d.ts +21 -0
  27. package/dist/hooks/usePolling/index.js +136 -0
  28. package/dist/hooks/useWebSocket/index.d.ts +20 -0
  29. package/dist/hooks/useWebSocket/index.js +105 -0
  30. package/dist/index.js +1 -2
  31. package/package.json +3 -2
  32. package/dist/charts/index.d.ts +0 -0
  33. package/dist/charts/index.js +0 -0
@@ -33,6 +33,10 @@ declare class Circle extends Node {
33
33
  index: number;
34
34
  path2D: Path2D | null;
35
35
  border: 0 | 1 | 2;
36
+ shadowColor: string;
37
+ shadowBlur: number;
38
+ shadowOffsetY: number;
39
+ shadowOffsetX: number;
36
40
  constructor(config: ICircle);
37
41
  deg2rad(deg: number): number;
38
42
  getPointOnArc(x0: number, y0: number, r: number, deg: number): {
@@ -19,7 +19,6 @@ import Node from "./node";
19
19
  var Circle = /*#__PURE__*/function (_Node) {
20
20
  _inherits(Circle, _Node);
21
21
  var _super = _createSuper(Circle);
22
- // 0 填充 1 只有边框 2 边框和填充
23
22
  function Circle(config) {
24
23
  var _this;
25
24
  _classCallCheck(this, Circle);
@@ -41,6 +40,11 @@ var Circle = /*#__PURE__*/function (_Node) {
41
40
  _defineProperty(_assertThisInitialized(_this), "index", void 0);
42
41
  _defineProperty(_assertThisInitialized(_this), "path2D", void 0);
43
42
  _defineProperty(_assertThisInitialized(_this), "border", void 0);
43
+ // 0 填充 1 只有边框 2 边框和填充
44
+ _defineProperty(_assertThisInitialized(_this), "shadowColor", void 0);
45
+ _defineProperty(_assertThisInitialized(_this), "shadowBlur", 0);
46
+ _defineProperty(_assertThisInitialized(_this), "shadowOffsetY", 0);
47
+ _defineProperty(_assertThisInitialized(_this), "shadowOffsetX", 0);
44
48
  _this.x = 10;
45
49
  _this.y = 10;
46
50
  _this.radius = 8;
@@ -54,6 +58,7 @@ var Circle = /*#__PURE__*/function (_Node) {
54
58
  _this.arc = false;
55
59
  _this.index = 0;
56
60
  _this.path2D = null;
61
+ _this.shadowColor = 'transparent';
57
62
  forIn(config, function (value, key) {
58
63
  if (value) _assertThisInitialized(_this)[key] = value;
59
64
  });
@@ -111,6 +116,15 @@ var Circle = /*#__PURE__*/function (_Node) {
111
116
  value: function draw(ctx) {
112
117
  var isWholeArc = this.startAngle === 0 && this.endAngle === 360; // 是否是整圆
113
118
  var circlePath;
119
+ if (this.shadowColor) {
120
+ // 设置阴影属性
121
+ ctx.shadowColor = this.shadowColor; // 阴影颜色
122
+ ctx.shadowBlur = this.shadowBlur; // 阴影模糊程度
123
+ ctx.shadowOffsetX = this.shadowOffsetX; // 阴影的水平偏移
124
+ ctx.shadowOffsetY = this.shadowOffsetY; // 阴影的垂直偏移
125
+ } else {
126
+ ctx.shadowColor = 'transparent'; // 取消阴影效果
127
+ }
114
128
  switch (this.border) {
115
129
  case 0:
116
130
  circlePath = new Path2D(this.calcRingD(isWholeArc));
@@ -19,6 +19,10 @@ declare class Custom extends Node {
19
19
  index: number;
20
20
  path2D: Path2D | null;
21
21
  parent: null;
22
+ shadowColor: string;
23
+ shadowBlur: number;
24
+ shadowOffsetY: number;
25
+ shadowOffsetX: number;
22
26
  constructor(config: ICustom);
23
27
  draw(ctx: CanvasRenderingContext2D): this | undefined;
24
28
  inScope(evt: MouseEvent, ctx: CanvasRenderingContext2D): boolean | undefined;
@@ -34,6 +34,10 @@ var Custom = /*#__PURE__*/function (_Node) {
34
34
  _defineProperty(_assertThisInitialized(_this), "index", void 0);
35
35
  _defineProperty(_assertThisInitialized(_this), "path2D", void 0);
36
36
  _defineProperty(_assertThisInitialized(_this), "parent", null);
37
+ _defineProperty(_assertThisInitialized(_this), "shadowColor", void 0);
38
+ _defineProperty(_assertThisInitialized(_this), "shadowBlur", 0);
39
+ _defineProperty(_assertThisInitialized(_this), "shadowOffsetY", 0);
40
+ _defineProperty(_assertThisInitialized(_this), "shadowOffsetX", 0);
37
41
  if (!config.path2D) {
38
42
  throw new Error('Mast has key of path2D');
39
43
  }
@@ -46,6 +50,7 @@ var Custom = /*#__PURE__*/function (_Node) {
46
50
  _this.lineWidth = 1;
47
51
  _this.path2D = null;
48
52
  _this.index = 0;
53
+ _this.shadowColor = 'transparent';
49
54
  forIn(config, function (value, key) {
50
55
  if (value) _assertThisInitialized(_this)[key] = value;
51
56
  });
@@ -60,6 +65,15 @@ var Custom = /*#__PURE__*/function (_Node) {
60
65
  if (this.lineWidth) ctx.lineWidth = this.lineWidth;
61
66
  if (this.lineWidth) ctx.stroke(this.path2D);
62
67
  if (this.fillStyle) ctx.fill(this.path2D);
68
+ if (this.shadowColor) {
69
+ // 设置阴影属性
70
+ ctx.shadowColor = this.shadowColor; // 阴影颜色
71
+ ctx.shadowBlur = this.shadowBlur; // 阴影模糊程度
72
+ ctx.shadowOffsetX = this.shadowOffsetX; // 阴影的水平偏移
73
+ ctx.shadowOffsetY = this.shadowOffsetY; // 阴影的垂直偏移
74
+ } else {
75
+ ctx.shadowColor = 'transparent'; // 取消阴影效果
76
+ }
63
77
  return this;
64
78
  }
65
79
  }, {
@@ -0,0 +1,12 @@
1
+ import Container from '../stage/container';
2
+ declare class Group extends Container {
3
+ parent: any;
4
+ name: string;
5
+ draggable: boolean;
6
+ constructor(config: {
7
+ draggable: boolean;
8
+ });
9
+ draw(ctx: CanvasRenderingContext2D): this | undefined;
10
+ inScope(evt: MouseEvent, ctx: CanvasRenderingContext2D): boolean;
11
+ }
12
+ export default Group;
@@ -0,0 +1,65 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
4
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
5
+ function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
6
+ function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
7
+ function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
8
+ function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
9
+ function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
10
+ function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
11
+ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
12
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
13
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
14
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
15
+ import { forIn } from 'lodash-es';
16
+ import Container from "../stage/container";
17
+ var Group = /*#__PURE__*/function (_Container) {
18
+ _inherits(Group, _Container);
19
+ var _super = _createSuper(Group);
20
+ function Group(config) {
21
+ var _this;
22
+ _classCallCheck(this, Group);
23
+ _this = _super.call(this);
24
+ _defineProperty(_assertThisInitialized(_this), "parent", void 0);
25
+ _defineProperty(_assertThisInitialized(_this), "name", 'Group');
26
+ _defineProperty(_assertThisInitialized(_this), "draggable", false);
27
+ _this.parent = null;
28
+ forIn(config, function (value, key) {
29
+ if (value) _assertThisInitialized(_this)[key] = value;
30
+ });
31
+ return _this;
32
+ }
33
+ _createClass(Group, [{
34
+ key: "draw",
35
+ value: function draw(ctx) {
36
+ if (!ctx) return;
37
+ // 排序
38
+ this.sortChildren(function (a, b) {
39
+ return a.index - b.index;
40
+ });
41
+ // 去重 (后面覆盖前面的)
42
+ this.deduplication();
43
+ // 绘制
44
+ this.getChildren().forEach(function (child) {
45
+ if (ctx && 'draw' in child && typeof child.draw === 'function') {
46
+ child.draw(ctx);
47
+ }
48
+ });
49
+ return this;
50
+ }
51
+ }, {
52
+ key: "inScope",
53
+ value: function inScope(evt, ctx) {
54
+ // 绘制
55
+ return this.getChildren().some(function (child) {
56
+ if ('inScope' in child && typeof child.inScope === 'function') {
57
+ return child.inScope(evt, ctx);
58
+ }
59
+ return false;
60
+ });
61
+ }
62
+ }]);
63
+ return Group;
64
+ }(Container);
65
+ export default Group;
@@ -11,11 +11,12 @@ interface ILine {
11
11
  };
12
12
  points?: number[];
13
13
  smooth?: boolean;
14
- strokeStyle: string;
15
- lineWidth: number;
16
- lineCap: 'butt' | 'round' | 'square';
17
- lineJoin: 'miter' | 'round' | 'miter';
18
- index: number;
14
+ strokeStyle?: string;
15
+ lineWidth?: number;
16
+ lineCap?: 'butt' | 'round' | 'square';
17
+ lineJoin?: 'miter' | 'round' | 'miter';
18
+ index?: number;
19
+ lineDash?: [number, number] | [];
19
20
  }
20
21
  declare class Line extends Node {
21
22
  name: string;
@@ -36,6 +37,11 @@ declare class Line extends Node {
36
37
  index: number;
37
38
  path2D: Path2D | null;
38
39
  parent: null;
40
+ shadowColor: string;
41
+ shadowBlur: number;
42
+ shadowOffsetY: number;
43
+ shadowOffsetX: number;
44
+ lineDash: [number, number] | [];
39
45
  constructor(config: ILine);
40
46
  convertToNormalPoints(points: number[]): Vector2d[];
41
47
  calcSmoothPath2D(): Path2D;
@@ -45,6 +45,11 @@ var Line = /*#__PURE__*/function (_Node) {
45
45
  _defineProperty(_assertThisInitialized(_this), "index", void 0);
46
46
  _defineProperty(_assertThisInitialized(_this), "path2D", void 0);
47
47
  _defineProperty(_assertThisInitialized(_this), "parent", null);
48
+ _defineProperty(_assertThisInitialized(_this), "shadowColor", void 0);
49
+ _defineProperty(_assertThisInitialized(_this), "shadowBlur", 0);
50
+ _defineProperty(_assertThisInitialized(_this), "shadowOffsetY", 0);
51
+ _defineProperty(_assertThisInitialized(_this), "shadowOffsetX", 0);
52
+ _defineProperty(_assertThisInitialized(_this), "lineDash", []);
48
53
  _this.start = {
49
54
  x: 10,
50
55
  y: 10
@@ -61,6 +66,7 @@ var Line = /*#__PURE__*/function (_Node) {
61
66
  _this.smooth = false;
62
67
  _this.index = 0;
63
68
  _this.path2D = null;
69
+ _this.shadowColor = 'transparent';
64
70
  forIn(config, function (value, key) {
65
71
  if (value) _assertThisInitialized(_this)[key] = value;
66
72
  });
@@ -122,6 +128,20 @@ var Line = /*#__PURE__*/function (_Node) {
122
128
  var path2D = this.smooth ? this.calcSmoothPath2D() : this.calcStraightPath2D();
123
129
  if (this.strokeStyle) ctx.strokeStyle = this.strokeStyle;
124
130
  if (this.lineWidth) ctx.lineWidth = this.lineWidth;
131
+ if (this.shadowColor) {
132
+ // 设置阴影属性
133
+ ctx.shadowColor = this.shadowColor; // 阴影颜色
134
+ ctx.shadowBlur = this.shadowBlur; // 阴影模糊程度
135
+ ctx.shadowOffsetX = this.shadowOffsetX; // 阴影的水平偏移
136
+ ctx.shadowOffsetY = this.shadowOffsetY; // 阴影的垂直偏移
137
+ } else {
138
+ ctx.shadowColor = 'transparent'; // 取消阴影效果
139
+ }
140
+ if (this.lineDash.length <= 0) {
141
+ ctx.setLineDash([]);
142
+ } else {
143
+ ctx.setLineDash(this.lineDash);
144
+ }
125
145
  ctx.stroke(path2D);
126
146
  return this;
127
147
  }
@@ -23,12 +23,6 @@ declare abstract class Node {
23
23
  handler: any;
24
24
  }>;
25
25
  };
26
- shapeEventListeners: {
27
- [index: string]: Array<{
28
- name: string;
29
- handler: any;
30
- }>;
31
- };
32
26
  abstract parent?: Stage | null;
33
27
  on<K extends keyof NodeEventMap>(evtStr: K, handler: EventListener<this, NodeEventMap[K]>): this;
34
28
  _off(type: string, name?: string, callback?: (params: any) => void): void;
@@ -12,12 +12,12 @@ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key i
12
12
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
13
13
  function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
14
14
  import { isStage } from "../../utils";
15
+ import { isFunction } from "../../../utils/is";
15
16
  import { forIn, isEmpty } from 'lodash-es';
16
17
  var Node = /*#__PURE__*/function () {
17
18
  function Node() {
18
19
  _classCallCheck(this, Node);
19
20
  _defineProperty(this, "eventListeners", {});
20
- _defineProperty(this, "shapeEventListeners", {});
21
21
  }
22
22
  _createClass(Node, [{
23
23
  key: "on",
@@ -36,7 +36,7 @@ var Node = /*#__PURE__*/function () {
36
36
  this.eventListeners[baseEvent] = [];
37
37
  }
38
38
  this.eventListeners[baseEvent].push({
39
- name: handler.name || '',
39
+ name: (handler === null || handler === void 0 ? void 0 : handler.name) || '',
40
40
  handler: handler
41
41
  });
42
42
  // if (this?.parent && isStage(this?.parent)) {
@@ -112,13 +112,14 @@ var Node = /*#__PURE__*/function () {
112
112
  var _currentTarget$eventL;
113
113
  if ((currentTarget === null || currentTarget === void 0 || (_currentTarget$eventL = currentTarget.eventListeners) === null || _currentTarget$eventL === void 0 || (_currentTarget$eventL = _currentTarget$eventL[eventType]) === null || _currentTarget$eventL === void 0 ? void 0 : _currentTarget$eventL.length) > 0) {
114
114
  currentTarget.eventListeners[eventType].forEach(function (item) {
115
- item.handler(evt);
115
+ item.handler(evt, currentTarget);
116
116
  });
117
117
  }
118
118
  if (currentTarget !== null && currentTarget !== void 0 && currentTarget.draggable) {
119
119
  var _currentTarget$eventL2;
120
+ if (isFunction(currentTarget === null || currentTarget === void 0 ? void 0 : currentTarget.draggable) && currentTarget.dragging) currentTarget === null || currentTarget === void 0 || currentTarget.draggable(evt, currentTarget);
120
121
  (_currentTarget$eventL2 = currentTarget.eventListeners) === null || _currentTarget$eventL2 === void 0 || (_currentTarget$eventL2 = _currentTarget$eventL2[eventType]) === null || _currentTarget$eventL2 === void 0 || _currentTarget$eventL2.forEach(function (item) {
121
- item === null || item === void 0 || item.handler(evt);
122
+ item.handler(evt, currentTarget);
122
123
  });
123
124
  }
124
125
  }
@@ -137,15 +138,7 @@ var Node = /*#__PURE__*/function () {
137
138
  // 将时间推送到最顶层中
138
139
  var children = target === null || target === void 0 ? void 0 : target.children;
139
140
  for (var i = 0; i < children.length; i++) {
140
- var _children$i, _children$i2;
141
- // if (
142
- // !this.shapeEventListeners[eventType] ||
143
- // this.shapeEventListeners[eventType].length < 1
144
- // ) {
145
- // this.shapeEventListeners[eventType] = [];
146
- // }
147
- // @ts-ignore
148
- var dragShapes = _toConsumableArray(this.children.filter(function (item) {
141
+ var dragShapes = _toConsumableArray(children.filter(function (item) {
149
142
  return item.draggable;
150
143
  }));
151
144
  // 拖拽 按下
@@ -158,16 +151,32 @@ var Node = /*#__PURE__*/function () {
158
151
  return b.index - a.index;
159
152
  })[0];
160
153
  if (topInScopeDragShape) {
161
- topInScopeDragShape.dragging = true;
162
- topInScopeDragShape.offsetX = topInScopeDragShape !== null && topInScopeDragShape !== void 0 && topInScopeDragShape.x ? evt.offsetX - (topInScopeDragShape === null || topInScopeDragShape === void 0 ? void 0 : topInScopeDragShape.x) : evt.offsetX;
163
- topInScopeDragShape.offsetY = topInScopeDragShape !== null && topInScopeDragShape !== void 0 && topInScopeDragShape.y ? evt.offsetY - (topInScopeDragShape === null || topInScopeDragShape === void 0 ? void 0 : topInScopeDragShape.y) : evt.offsetY;
154
+ if (topInScopeDragShape.name === 'Group') {
155
+ topInScopeDragShape.dragging = true;
156
+ topInScopeDragShape.children.forEach(function (child) {
157
+ // child.dragging = true;
158
+ child.offsetX = child !== null && child !== void 0 && child.x ? evt.offsetX - (child === null || child === void 0 ? void 0 : child.x) : evt.offsetX;
159
+ // @ts-ignore
160
+ child.offsetY = child !== null && child !== void 0 && child.y ?
161
+ // @ts-ignore
162
+ evt.offsetY - (child === null || child === void 0 ? void 0 : child.y) : evt.offsetY;
163
+ });
164
+ } else {
165
+ topInScopeDragShape.dragging = true;
166
+ topInScopeDragShape.offsetX = topInScopeDragShape !== null && topInScopeDragShape !== void 0 && topInScopeDragShape.x ? evt.offsetX - (topInScopeDragShape === null || topInScopeDragShape === void 0 ? void 0 : topInScopeDragShape.x) : evt.offsetX;
167
+ // @ts-ignore
168
+ topInScopeDragShape.offsetY = topInScopeDragShape !== null && topInScopeDragShape !== void 0 && topInScopeDragShape.y ?
169
+ // @ts-ignore
170
+ evt.offsetY - (topInScopeDragShape === null || topInScopeDragShape === void 0 ? void 0 : topInScopeDragShape.y) : evt.offsetY;
171
+ }
164
172
  }
165
173
  }
166
- if (!isEmpty((_children$i = children[i]) === null || _children$i === void 0 ? void 0 : _children$i.eventListeners) || (_children$i2 = children[i]) !== null && _children$i2 !== void 0 && _children$i2.draggable) {
174
+ var currentChild = children[i];
175
+ if (!isEmpty(currentChild === null || currentChild === void 0 ? void 0 : currentChild.eventListeners) || currentChild !== null && currentChild !== void 0 && currentChild.draggable) {
167
176
  this.fire(eventType, {
168
177
  evt: evt,
169
178
  target: target,
170
- currentTarget: children[i]
179
+ currentTarget: currentChild
171
180
  });
172
181
  }
173
182
  }
@@ -188,11 +197,26 @@ var Node = /*#__PURE__*/function () {
188
197
  var y = rect !== null && rect !== void 0 && rect.top ? evt.clientY - (rect === null || rect === void 0 ? void 0 : rect.top) : evt.clientY;
189
198
  currentTarget.x = currentTarget !== null && currentTarget !== void 0 && currentTarget.offsetX ? x - (currentTarget === null || currentTarget === void 0 ? void 0 : currentTarget.offsetX) : x;
190
199
  currentTarget.y = currentTarget !== null && currentTarget !== void 0 && currentTarget.offsetY ? y - (currentTarget === null || currentTarget === void 0 ? void 0 : currentTarget.offsetY) : y;
191
- } else {
200
+ } else if (currentTarget.name === 'Group') {
192
201
  var _x = rect !== null && rect !== void 0 && rect.left ? evt.clientX - (rect === null || rect === void 0 ? void 0 : rect.left) : evt.clientX;
193
202
  var _y = rect !== null && rect !== void 0 && rect.top ? evt.clientY - (rect === null || rect === void 0 ? void 0 : rect.top) : evt.clientY;
194
- currentTarget.x = currentTarget !== null && currentTarget !== void 0 && currentTarget.offsetX ? _x - (currentTarget === null || currentTarget === void 0 ? void 0 : currentTarget.offsetX) : _x;
195
- currentTarget.y = currentTarget !== null && currentTarget !== void 0 && currentTarget.offsetY ? _y - (currentTarget === null || currentTarget === void 0 ? void 0 : currentTarget.offsetY) : _y;
203
+ currentTarget.children.forEach(function (child) {
204
+ if (child.name === 'Text') {
205
+ // @ts-ignore
206
+ var _x2 = rect !== null && rect !== void 0 && rect.left ? evt.clientX - (rect === null || rect === void 0 ? void 0 : rect.left) : evt.clientX;
207
+ var _y2 = rect !== null && rect !== void 0 && rect.top ? evt.clientY - (rect === null || rect === void 0 ? void 0 : rect.top) : evt.clientY;
208
+ child.x = child !== null && child !== void 0 && child.offsetX ? _x2 - (child === null || child === void 0 ? void 0 : child.offsetX) : _x2;
209
+ child.y = child !== null && child !== void 0 && child.offsetY ? _y2 - (child === null || child === void 0 ? void 0 : child.offsetY) : _y2;
210
+ } else {
211
+ child.x = child !== null && child !== void 0 && child.offsetX ? _x - (child === null || child === void 0 ? void 0 : child.offsetX) : _x;
212
+ child.y = child !== null && child !== void 0 && child.offsetY ? _y - (child === null || child === void 0 ? void 0 : child.offsetY) : _y;
213
+ }
214
+ });
215
+ } else {
216
+ var _x3 = rect !== null && rect !== void 0 && rect.left ? evt.clientX - (rect === null || rect === void 0 ? void 0 : rect.left) : evt.clientX;
217
+ var _y3 = rect !== null && rect !== void 0 && rect.top ? evt.clientY - (rect === null || rect === void 0 ? void 0 : rect.top) : evt.clientY;
218
+ currentTarget.x = currentTarget !== null && currentTarget !== void 0 && currentTarget.offsetX ? _x3 - (currentTarget === null || currentTarget === void 0 ? void 0 : currentTarget.offsetX) : _x3;
219
+ currentTarget.y = currentTarget !== null && currentTarget !== void 0 && currentTarget.offsetY ? _y3 - (currentTarget === null || currentTarget === void 0 ? void 0 : currentTarget.offsetY) : _y3;
196
220
  }
197
221
 
198
222
  // @ts-ignore
@@ -7,6 +7,7 @@ interface IRect {
7
7
  fillStyle?: string;
8
8
  strokeStyle?: string;
9
9
  lineWidth?: number;
10
+ shadowColor?: string;
10
11
  }
11
12
  declare class Rect extends Node {
12
13
  name: string;
@@ -20,8 +21,13 @@ declare class Rect extends Node {
20
21
  index: number;
21
22
  path2D: Path2D | null;
22
23
  parent: null;
24
+ shadowColor: string;
25
+ shadowBlur: number;
26
+ shadowOffsetY: number;
27
+ shadowOffsetX: number;
28
+ radius: number;
23
29
  constructor(config: IRect);
24
- draw(ctx: CanvasRenderingContext2D): this;
30
+ draw(ctx: CanvasRenderingContext2D): void;
25
31
  inScope(evt: MouseEvent, ctx: CanvasRenderingContext2D): boolean | undefined;
26
32
  }
27
33
  export default Rect;
@@ -34,6 +34,11 @@ var Rect = /*#__PURE__*/function (_Node) {
34
34
  _defineProperty(_assertThisInitialized(_this), "index", void 0);
35
35
  _defineProperty(_assertThisInitialized(_this), "path2D", void 0);
36
36
  _defineProperty(_assertThisInitialized(_this), "parent", null);
37
+ _defineProperty(_assertThisInitialized(_this), "shadowColor", void 0);
38
+ _defineProperty(_assertThisInitialized(_this), "shadowBlur", 0);
39
+ _defineProperty(_assertThisInitialized(_this), "shadowOffsetY", 0);
40
+ _defineProperty(_assertThisInitialized(_this), "shadowOffsetX", 0);
41
+ _defineProperty(_assertThisInitialized(_this), "radius", 0);
37
42
  _this.x = 100;
38
43
  _this.y = 100;
39
44
  _this.width = 100;
@@ -42,7 +47,9 @@ var Rect = /*#__PURE__*/function (_Node) {
42
47
  _this.strokeStyle = null;
43
48
  _this.lineWidth = null;
44
49
  _this.path2D = null;
50
+ _this.shadowColor = 'transparent';
45
51
  _this.index = 0;
52
+ _this.radius = 0;
46
53
  forIn(config, function (value, key) {
47
54
  if (value) _assertThisInitialized(_this)[key] = value;
48
55
  });
@@ -52,10 +59,31 @@ var Rect = /*#__PURE__*/function (_Node) {
52
59
  key: "draw",
53
60
  value: function draw(ctx) {
54
61
  var path2D = new Path2D();
55
- path2D.moveTo(this.x, this.y);
56
- path2D.lineTo(this.x + this.width, this.y);
57
- path2D.lineTo(this.x + this.width, this.y + this.height);
58
- path2D.lineTo(this.x, this.y + this.height);
62
+ if (this.radius) {
63
+ path2D.moveTo(this.x + this.radius, this.y);
64
+ path2D.lineTo(this.x + this.width - this.radius, this.y);
65
+ path2D.arcTo(this.x + this.width, this.y, this.x + this.width, this.y + this.radius, this.radius);
66
+ path2D.lineTo(this.x + this.width, this.y + this.height - this.radius);
67
+ path2D.arcTo(this.x + this.width, this.y + this.height, this.x + this.width - this.radius, this.y + this.height, this.radius);
68
+ path2D.lineTo(this.x + this.radius, this.y + this.height);
69
+ path2D.arcTo(this.x, this.y + this.height, this.x, this.y + this.height - this.radius, this.radius);
70
+ path2D.lineTo(this.x, this.y + this.radius);
71
+ path2D.arcTo(this.x, this.y, this.x + this.radius, this.y, this.radius);
72
+ } else {
73
+ path2D.moveTo(this.x, this.y);
74
+ path2D.lineTo(this.x + this.width, this.y);
75
+ path2D.lineTo(this.x + this.width, this.y + this.height);
76
+ path2D.lineTo(this.x, this.y + this.height);
77
+ }
78
+ if (this.shadowColor) {
79
+ // 设置阴影属性
80
+ ctx.shadowColor = this.shadowColor; // 阴影颜色
81
+ ctx.shadowBlur = this.shadowBlur; // 阴影模糊程度
82
+ ctx.shadowOffsetX = this.shadowOffsetX; // 阴影的水平偏移
83
+ ctx.shadowOffsetY = this.shadowOffsetY; // 阴影的垂直偏移
84
+ } else {
85
+ ctx.shadowColor = 'transparent'; // 取消阴影效果
86
+ }
59
87
  path2D.closePath();
60
88
  if (this.fillStyle) ctx.fillStyle = this.fillStyle;
61
89
  if (this.strokeStyle) ctx.strokeStyle = this.strokeStyle;
@@ -63,7 +91,6 @@ var Rect = /*#__PURE__*/function (_Node) {
63
91
  if (this.lineWidth) ctx.stroke(path2D);
64
92
  if (this.fillStyle) ctx.fill(path2D);
65
93
  this.path2D = path2D;
66
- return this;
67
94
  }
68
95
  }, {
69
96
  key: "inScope",
@@ -36,6 +36,10 @@ declare class Text extends Node {
36
36
  width?: number;
37
37
  height?: number;
38
38
  index: number;
39
+ shadowColor: string;
40
+ shadowBlur: number;
41
+ shadowOffsetY: number;
42
+ shadowOffsetX: number;
39
43
  constructor(config: IText);
40
44
  draw(ctx: CanvasRenderingContext2D): this;
41
45
  inScope(evt: MouseEvent): boolean;
@@ -36,6 +36,10 @@ var Text = /*#__PURE__*/function (_Node) {
36
36
  _defineProperty(_assertThisInitialized(_this), "width", void 0);
37
37
  _defineProperty(_assertThisInitialized(_this), "height", void 0);
38
38
  _defineProperty(_assertThisInitialized(_this), "index", 0);
39
+ _defineProperty(_assertThisInitialized(_this), "shadowColor", void 0);
40
+ _defineProperty(_assertThisInitialized(_this), "shadowBlur", 0);
41
+ _defineProperty(_assertThisInitialized(_this), "shadowOffsetY", 0);
42
+ _defineProperty(_assertThisInitialized(_this), "shadowOffsetX", 0);
39
43
  _this.content = '';
40
44
  if (!config.content && !_this.content) {
41
45
  throw new Error('Text must has content');
@@ -47,6 +51,7 @@ var Text = /*#__PURE__*/function (_Node) {
47
51
  _this.textBaseline = 'top';
48
52
  _this.x = 100;
49
53
  _this.y = 100;
54
+ _this.shadowColor = 'transparent';
50
55
  forIn(config, function (value, key) {
51
56
  if (value) _assertThisInitialized(_this)[key] = value;
52
57
  });
@@ -63,6 +68,15 @@ var Text = /*#__PURE__*/function (_Node) {
63
68
  var textMetrics = ctx.measureText(this.content);
64
69
  this.width = textMetrics.width;
65
70
  this.height = this.fontSize;
71
+ if (this.shadowColor) {
72
+ // 设置阴影属性
73
+ ctx.shadowColor = this.shadowColor; // 阴影颜色
74
+ ctx.shadowBlur = this.shadowBlur; // 阴影模糊程度
75
+ ctx.shadowOffsetX = this.shadowOffsetX; // 阴影的水平偏移
76
+ ctx.shadowOffsetY = this.shadowOffsetY; // 阴影的垂直偏移
77
+ } else {
78
+ ctx.shadowColor = 'transparent'; // 取消阴影效果
79
+ }
66
80
  return this;
67
81
  }
68
82
  }, {
@@ -1,7 +1,7 @@
1
1
  import Stage from '.';
2
2
  import Node from '../shapes/node';
3
3
  import { Node as INode } from '../type';
4
- interface ChildType extends Node {
4
+ export interface ChildType extends Node {
5
5
  parent: Stage | null;
6
6
  index: number;
7
7
  remove: () => void;
@@ -1,10 +1,10 @@
1
1
  import { Vector2d } from '../type';
2
2
  import { Canvas } from './canvas';
3
3
  import Container from './container';
4
- interface IOption {
4
+ export interface IOption {
5
5
  container: HTMLElement;
6
- width: number;
7
- height: number;
6
+ width?: number;
7
+ height?: number;
8
8
  backgroundColor?: string;
9
9
  }
10
10
  declare class Stage extends Container {
@@ -105,6 +105,8 @@ var Stage = /*#__PURE__*/function (_Container) {
105
105
  value: function _resizeDOM() {
106
106
  if (this.content && this.canvas) {
107
107
  var _this$canvas;
108
+ this.width = this.content.offsetWidth;
109
+ this.height = this.content.offsetHeight;
108
110
  this.canvas.setSize(this.content.offsetWidth, this.content.offsetHeight);
109
111
  if ((_this$canvas = this.canvas) !== null && _this$canvas !== void 0 && _this$canvas.context) this.batchDraw(this);
110
112
  }
@@ -1,6 +1,7 @@
1
1
  export { default as Animate } from './core/shapes/animate';
2
2
  export { default as Circle } from './core/shapes/circle';
3
3
  export { default as Custom } from './core/shapes/custom';
4
+ export { default as Group } from './core/shapes/group';
4
5
  export { default as Line } from './core/shapes/line';
5
6
  export { default as Rect } from './core/shapes/rect';
6
7
  export { default as Text } from './core/shapes/text';
@@ -1,6 +1,7 @@
1
1
  export { default as Animate } from "./core/shapes/animate";
2
2
  export { default as Circle } from "./core/shapes/circle";
3
3
  export { default as Custom } from "./core/shapes/custom";
4
+ export { default as Group } from "./core/shapes/group";
4
5
  export { default as Line } from "./core/shapes/line";
5
6
  export { default as Rect } from "./core/shapes/rect";
6
7
  export { default as Text } from "./core/shapes/text";
@@ -1,5 +1,6 @@
1
- export { default as useLocalStorage } from './useLocalStorage';
2
- export { default as useSessionStorage } from './useSessionStorage';
1
+ export { default as useAsyncFn } from './useAsyncFn';
2
+ export { default as useCancelAsyncFn } from './useCancelAsyncFn';
3
+ export { default as createContainer } from './useContainer';
3
4
  export { default as useCookie } from './useCookie';
4
5
  export { default as useCountDown } from './useCountDown';
5
6
  export { default as useDeepCompareEffect } from './useDeepCompareEffect';
@@ -9,8 +10,10 @@ export { default as useHtAxios } from './useHtAxios';
9
10
  export { default as useImageLoad } from './useImageLoad';
10
11
  export { default as useInfiniteScroll } from './useInfiniteScroll';
11
12
  export { default as useInView } from './useInView';
13
+ export { default as useLocalStorage } from './useLocalStorage';
14
+ export { default as usePolling } from './usePolling';
12
15
  export { default as usePrevious } from './usePrevious';
13
16
  export { default as useResizeObserver } from './useResizeObserver';
17
+ export { default as useSessionStorage } from './useSessionStorage';
18
+ export { default as useWebSocket } from './useWebSocket';
14
19
  export { default as useWindowSize } from './useWindowSize';
15
- export { default as useAsyncFn } from './useAsyncFn';
16
- export { default as useCancelAsyncFn } from './useCancelAsyncFn';
@@ -1,5 +1,6 @@
1
- export { default as useLocalStorage } from "./useLocalStorage";
2
- export { default as useSessionStorage } from "./useSessionStorage";
1
+ export { default as useAsyncFn } from "./useAsyncFn";
2
+ export { default as useCancelAsyncFn } from "./useCancelAsyncFn";
3
+ export { default as createContainer } from "./useContainer";
3
4
  export { default as useCookie } from "./useCookie";
4
5
  export { default as useCountDown } from "./useCountDown";
5
6
  export { default as useDeepCompareEffect } from "./useDeepCompareEffect";
@@ -9,8 +10,10 @@ export { default as useHtAxios } from "./useHtAxios";
9
10
  export { default as useImageLoad } from "./useImageLoad";
10
11
  export { default as useInfiniteScroll } from "./useInfiniteScroll";
11
12
  export { default as useInView } from "./useInView";
13
+ export { default as useLocalStorage } from "./useLocalStorage";
14
+ export { default as usePolling } from "./usePolling";
12
15
  export { default as usePrevious } from "./usePrevious";
13
16
  export { default as useResizeObserver } from "./useResizeObserver";
14
- export { default as useWindowSize } from "./useWindowSize";
15
- export { default as useAsyncFn } from "./useAsyncFn";
16
- export { default as useCancelAsyncFn } from "./useCancelAsyncFn";
17
+ export { default as useSessionStorage } from "./useSessionStorage";
18
+ export { default as useWebSocket } from "./useWebSocket";
19
+ export { default as useWindowSize } from "./useWindowSize";
@@ -1,8 +1,8 @@
1
1
  import type { DependencyList } from 'react';
2
- export type ICancelInterceptor = () => void | never;
3
- export interface ICancel {
4
- cancelInterceptor: ICancelInterceptor;
2
+ export interface CancelContext {
3
+ signal: AbortSignal;
4
+ cancelInterceptor: () => void;
5
5
  }
6
- export type ICancelAsyncFn = (params: ICancel) => Promise<(...args: any[]) => Promise<any>>;
7
- declare const useCancelAsyncFn: (fn: ICancelAsyncFn, deps: DependencyList) => import("./useAsyncFn").AsyncFnReturn<(...args: any[]) => Promise<any>>;
6
+ export type CancelableAsyncFn<T = any> = (context: CancelContext) => Promise<T>;
7
+ declare const useCancelAsyncFn: <T>(fn: CancelableAsyncFn<T>, deps: DependencyList) => import("./useAsyncFn").AsyncFnReturn<() => Promise<T | undefined>>;
8
8
  export default useCancelAsyncFn;
@@ -2,57 +2,56 @@ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" ==
2
2
  function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
3
3
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4
4
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
5
- import React, { useRef } from 'react';
5
+ import { useEffect, useRef } from 'react';
6
6
  import useAsyncFn from "./useAsyncFn";
7
7
  var useCancelAsyncFn = function useCancelAsyncFn(fn, deps) {
8
8
  var controller = useRef();
9
- var cancelInterceptor = function cancelInterceptor() {
9
+
10
+ // 清理函数
11
+ var cleanup = function cleanup() {
10
12
  if (controller.current) {
11
13
  controller.current.abort();
12
- throw new Error(" Canceled .");
13
14
  }
14
15
  };
15
- React.useEffect(function () {
16
- return function () {
17
- if (controller.current) {
18
- controller.current.abort();
19
- }
20
- };
16
+
17
+ // 组件卸载时清理
18
+ useEffect(function () {
19
+ return cleanup;
21
20
  }, []);
22
21
  var result = useAsyncFn( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
23
- var signal,
24
- cancelParams,
25
- next,
26
- result1,
27
- _args = arguments;
28
- return _regeneratorRuntime().wrap(function _callee$(_context) {
29
- while (1) switch (_context.prev = _context.next) {
22
+ var _context;
23
+ return _regeneratorRuntime().wrap(function _callee$(_context2) {
24
+ while (1) switch (_context2.prev = _context2.next) {
30
25
  case 0:
31
- // 如果已有控制器,则取消之前的请求
32
- if (controller.current) {
33
- controller.current.abort();
34
- }
26
+ // 取消之前的请求
27
+ cleanup();
35
28
 
36
- // 创建新的 AbortController 实例
29
+ // 创建新的 AbortController
37
30
  controller.current = new AbortController();
38
- signal = controller.current.signal;
39
- cancelParams = {
40
- cancelInterceptor: cancelInterceptor
31
+ _context2.prev = 2;
32
+ _context = {
33
+ signal: controller.current.signal,
34
+ cancelInterceptor: cleanup
41
35
  };
42
- _context.next = 6;
43
- return fn(cancelParams);
36
+ _context2.next = 6;
37
+ return fn(_context);
44
38
  case 6:
45
- next = _context.sent;
46
- _context.next = 9;
47
- return next.apply(void 0, _args);
39
+ return _context2.abrupt("return", _context2.sent);
48
40
  case 9:
49
- result1 = _context.sent;
50
- return _context.abrupt("return", result1);
51
- case 11:
41
+ _context2.prev = 9;
42
+ _context2.t0 = _context2["catch"](2);
43
+ if (!(_context2.t0 instanceof Error && _context2.t0.name === 'AbortError')) {
44
+ _context2.next = 13;
45
+ break;
46
+ }
47
+ return _context2.abrupt("return");
48
+ case 13:
49
+ throw _context2.t0;
50
+ case 14:
52
51
  case "end":
53
- return _context.stop();
52
+ return _context2.stop();
54
53
  }
55
- }, _callee);
54
+ }, _callee, null, [[2, 9]]);
56
55
  })), deps);
57
56
  return result;
58
57
  };
@@ -0,0 +1,13 @@
1
+ import React from 'react';
2
+ declare function createContainer<Value, Props = void>(useHook: (props: Props) => Value): {
3
+ Provider: ({ initialState, children, ...props }: {
4
+ initialState?: Partial<Value> | undefined;
5
+ children: React.ReactNode;
6
+ } & Props) => React.JSX.Element;
7
+ useContainer: () => Value;
8
+ withContainer: <P extends object>(WrappedComponent: React.ComponentType<P & {
9
+ container: Value;
10
+ }>) => (props: P) => React.JSX.Element;
11
+ Context: React.Context<Value | null>;
12
+ };
13
+ export default createContainer;
@@ -0,0 +1,62 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ var _excluded = ["initialState", "children"];
3
+ function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
4
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
5
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
6
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
7
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
8
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
9
+ function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
10
+ function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
11
+ import React, { createContext, useContext, useRef } from 'react';
12
+
13
+ // 容器创建函数
14
+ function createContainer(useHook) {
15
+ // 创建 Context
16
+ var Context = /*#__PURE__*/createContext(null);
17
+
18
+ // Provider 组件
19
+ function Provider(_ref) {
20
+ var initialState = _ref.initialState,
21
+ children = _ref.children,
22
+ props = _objectWithoutProperties(_ref, _excluded);
23
+ // 调用 hook 获取状态和方法
24
+ var value = useHook(props);
25
+
26
+ // 合并初始状态
27
+ var mergedValue = _objectSpread(_objectSpread({}, value), initialState);
28
+
29
+ // 使用 useRef 确保返回的对象引用稳定
30
+ var stableValue = useRef(mergedValue);
31
+ Object.assign(stableValue.current, mergedValue);
32
+ return /*#__PURE__*/React.createElement(Context.Provider, {
33
+ value: stableValue.current
34
+ }, children);
35
+ }
36
+
37
+ // 自定义 hook,用于获取容器状态
38
+ function useContainer() {
39
+ var value = useContext(Context);
40
+ if (value === null) {
41
+ throw new Error('Component must be wrapped with <Provider>');
42
+ }
43
+ return value;
44
+ }
45
+
46
+ // 高阶组件,用于包装类组件
47
+ function withContainer(WrappedComponent) {
48
+ return function WithContainer(props) {
49
+ var container = useContainer();
50
+ return /*#__PURE__*/React.createElement(WrappedComponent, _extends({}, props, {
51
+ container: container
52
+ }));
53
+ };
54
+ }
55
+ return {
56
+ Provider: Provider,
57
+ useContainer: useContainer,
58
+ withContainer: withContainer,
59
+ Context: Context
60
+ };
61
+ }
62
+ export default createContainer;
@@ -0,0 +1,21 @@
1
+ interface Options<T> {
2
+ interval?: number;
3
+ manual?: boolean;
4
+ retryTimes?: number;
5
+ retryInterval?: number;
6
+ onSuccess?: (data: T) => void;
7
+ onError?: (error: Error) => void;
8
+ }
9
+ declare enum State {
10
+ CLOSED = 0,
11
+ POLLING = 1
12
+ }
13
+ declare function usePolling<T>(service: () => Promise<T>, options?: Options<T>): {
14
+ data: T | undefined;
15
+ loading: boolean;
16
+ error: Error | undefined;
17
+ start: () => void;
18
+ stop: () => void;
19
+ state: State;
20
+ };
21
+ export default usePolling;
@@ -0,0 +1,136 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
3
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
5
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
6
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
7
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
8
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
9
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
10
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
11
+ import { useCallback, useEffect, useRef, useState } from 'react';
12
+ var State = /*#__PURE__*/function (State) {
13
+ State[State["CLOSED"] = 0] = "CLOSED";
14
+ State[State["POLLING"] = 1] = "POLLING";
15
+ return State;
16
+ }(State || {});
17
+ function usePolling(service) {
18
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
19
+ var _options$interval = options.interval,
20
+ interval = _options$interval === void 0 ? 3000 : _options$interval,
21
+ _options$manual = options.manual,
22
+ manual = _options$manual === void 0 ? false : _options$manual,
23
+ _options$retryTimes = options.retryTimes,
24
+ retryTimes = _options$retryTimes === void 0 ? 0 : _options$retryTimes,
25
+ _options$retryInterva = options.retryInterval,
26
+ retryInterval = _options$retryInterva === void 0 ? 1000 : _options$retryInterva,
27
+ onSuccess = options.onSuccess,
28
+ onError = options.onError;
29
+ var _useState = useState(State.CLOSED),
30
+ _useState2 = _slicedToArray(_useState, 2),
31
+ state = _useState2[0],
32
+ setState = _useState2[1];
33
+ var _useState3 = useState(false),
34
+ _useState4 = _slicedToArray(_useState3, 2),
35
+ loading = _useState4[0],
36
+ setLoading = _useState4[1];
37
+ var _useState5 = useState(),
38
+ _useState6 = _slicedToArray(_useState5, 2),
39
+ data = _useState6[0],
40
+ setData = _useState6[1];
41
+ var _useState7 = useState(),
42
+ _useState8 = _slicedToArray(_useState7, 2),
43
+ error = _useState8[0],
44
+ setError = _useState8[1];
45
+ var timerRef = useRef();
46
+ var retryCountRef = useRef(0);
47
+ var pollingRef = useRef(false);
48
+ var stop = useCallback(function () {
49
+ pollingRef.current = false;
50
+ clearTimeout(timerRef.current);
51
+ setState(State.CLOSED);
52
+ }, []);
53
+ var start = function start() {
54
+ if (pollingRef.current) return;
55
+ pollingRef.current = true;
56
+ setState(State.POLLING);
57
+ retryCountRef.current = 0;
58
+ var poll = /*#__PURE__*/function () {
59
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
60
+ var result;
61
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
62
+ while (1) switch (_context.prev = _context.next) {
63
+ case 0:
64
+ if (pollingRef.current) {
65
+ _context.next = 2;
66
+ break;
67
+ }
68
+ return _context.abrupt("return");
69
+ case 2:
70
+ _context.prev = 2;
71
+ setLoading(true);
72
+ _context.next = 6;
73
+ return service();
74
+ case 6:
75
+ result = _context.sent;
76
+ setData(result);
77
+ setError(undefined);
78
+ retryCountRef.current = 0;
79
+ onSuccess === null || onSuccess === void 0 || onSuccess(result);
80
+
81
+ // 设置下一次轮询
82
+ timerRef.current = setTimeout(poll, interval);
83
+ _context.next = 21;
84
+ break;
85
+ case 14:
86
+ _context.prev = 14;
87
+ _context.t0 = _context["catch"](2);
88
+ setError(_context.t0);
89
+ onError === null || onError === void 0 || onError(_context.t0);
90
+ if (!(retryTimes === 0)) {
91
+ _context.next = 20;
92
+ break;
93
+ }
94
+ return _context.abrupt("return", stop());
95
+ case 20:
96
+ // 处理重试逻辑
97
+ if (retryCountRef.current < retryTimes) {
98
+ retryCountRef.current++;
99
+ timerRef.current = setTimeout(poll, retryInterval);
100
+ } else {
101
+ stop();
102
+ }
103
+ case 21:
104
+ _context.prev = 21;
105
+ setLoading(false);
106
+ return _context.finish(21);
107
+ case 24:
108
+ case "end":
109
+ return _context.stop();
110
+ }
111
+ }, _callee, null, [[2, 14, 21, 24]]);
112
+ }));
113
+ return function poll() {
114
+ return _ref.apply(this, arguments);
115
+ };
116
+ }();
117
+ poll();
118
+ };
119
+ useEffect(function () {
120
+ if (!manual) {
121
+ start();
122
+ }
123
+ return function () {
124
+ stop();
125
+ };
126
+ }, [manual]);
127
+ return {
128
+ data: data,
129
+ loading: loading,
130
+ error: error,
131
+ start: start,
132
+ stop: stop,
133
+ state: state
134
+ };
135
+ }
136
+ export default usePolling;
@@ -0,0 +1,20 @@
1
+ interface Options {
2
+ reconnectLimit?: number;
3
+ reconnectInterval?: number;
4
+ manual?: boolean;
5
+ onOpen?: (event: WebSocketEventMap['open']) => void;
6
+ onClose?: (event: WebSocketEventMap['close']) => void;
7
+ onMessage?: (message: WebSocketEventMap['message']) => void;
8
+ onError?: (event: WebSocketEventMap['error']) => void;
9
+ json?: boolean;
10
+ protocols?: string | string[];
11
+ }
12
+ declare const useWebSocket: (url: string, options?: Options) => {
13
+ readyState: number;
14
+ sendMessage: (message: string | ArrayBufferLike | Blob | ArrayBufferView) => void;
15
+ connect: () => void;
16
+ disconnect: () => void;
17
+ webSocketIns: WebSocket | undefined;
18
+ latestMessage: MessageEvent<any> | null;
19
+ };
20
+ export default useWebSocket;
@@ -0,0 +1,105 @@
1
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
2
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
4
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
5
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
6
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
7
+ import { useEffect, useRef, useState } from 'react';
8
+ var useWebSocket = function useWebSocket(url) {
9
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
10
+ var _options$reconnectLim = options.reconnectLimit,
11
+ reconnectLimit = _options$reconnectLim === void 0 ? 3 : _options$reconnectLim,
12
+ _options$reconnectInt = options.reconnectInterval,
13
+ reconnectInterval = _options$reconnectInt === void 0 ? 3000 : _options$reconnectInt,
14
+ _options$manual = options.manual,
15
+ manual = _options$manual === void 0 ? false : _options$manual,
16
+ onOpen = options.onOpen,
17
+ onClose = options.onClose,
18
+ onMessage = options.onMessage,
19
+ onError = options.onError,
20
+ protocols = options.protocols;
21
+ var _useState = useState(WebSocket.CONNECTING),
22
+ _useState2 = _slicedToArray(_useState, 2),
23
+ readyState = _useState2[0],
24
+ setReadyState = _useState2[1];
25
+ var _useState3 = useState(null),
26
+ _useState4 = _slicedToArray(_useState3, 2),
27
+ latestMessage = _useState4[0],
28
+ setLatestMessage = _useState4[1];
29
+ var reconnectTimesRef = useRef(0);
30
+ var websocketRef = useRef();
31
+ var reconnectTimerRef = useRef();
32
+ var _useState5 = useState(false),
33
+ _useState6 = _slicedToArray(_useState5, 2),
34
+ manualClose = _useState6[0],
35
+ setManualClose = _useState6[1];
36
+ var connect = function connect() {
37
+ if (!url) {
38
+ return;
39
+ }
40
+ setManualClose(false); // 重置主动断开标记
41
+ websocketRef.current = new WebSocket(url, protocols);
42
+ websocketRef.current.onopen = function (event) {
43
+ setReadyState(WebSocket.OPEN);
44
+ onOpen === null || onOpen === void 0 || onOpen(event);
45
+ reconnectTimesRef.current = 0;
46
+ };
47
+ websocketRef.current.onclose = function (event) {
48
+ setReadyState(WebSocket.CLOSED);
49
+ onClose === null || onClose === void 0 || onClose(event);
50
+
51
+ // 只在非主动断开时进行重连
52
+ if (!manualClose && reconnectTimesRef.current < reconnectLimit) {
53
+ reconnectTimerRef.current = setTimeout(function () {
54
+ reconnectTimesRef.current += 1;
55
+ connect();
56
+ }, reconnectInterval);
57
+ }
58
+ };
59
+ websocketRef.current.onmessage = function (event) {
60
+ var parsedMessage = event;
61
+ if (options.json) {
62
+ try {
63
+ parsedMessage = JSON.parse(event.data);
64
+ } catch (e) {
65
+ console.error('JSON 解析失败:', e);
66
+ }
67
+ }
68
+ setLatestMessage(parsedMessage);
69
+ onMessage === null || onMessage === void 0 || onMessage(parsedMessage);
70
+ };
71
+ websocketRef.current.onerror = function (event) {
72
+ onError === null || onError === void 0 || onError(event);
73
+ };
74
+ };
75
+ var sendMessage = function sendMessage(message) {
76
+ if (readyState === WebSocket.OPEN) {
77
+ var _websocketRef$current;
78
+ var finalData = options.json ? JSON.stringify(message) : message;
79
+ (_websocketRef$current = websocketRef.current) === null || _websocketRef$current === void 0 || _websocketRef$current.send(finalData);
80
+ }
81
+ };
82
+ var disconnect = function disconnect() {
83
+ var _websocketRef$current2;
84
+ setManualClose(true); // 标记为主动断开
85
+ (_websocketRef$current2 = websocketRef.current) === null || _websocketRef$current2 === void 0 || _websocketRef$current2.close();
86
+ clearTimeout(reconnectTimerRef.current);
87
+ };
88
+ useEffect(function () {
89
+ if (!manual) {
90
+ connect();
91
+ }
92
+ return function () {
93
+ disconnect();
94
+ };
95
+ }, [url, manual]);
96
+ return {
97
+ readyState: readyState,
98
+ sendMessage: sendMessage,
99
+ connect: connect,
100
+ disconnect: disconnect,
101
+ webSocketIns: websocketRef.current,
102
+ latestMessage: latestMessage
103
+ };
104
+ };
105
+ export default useWebSocket;
package/dist/index.js CHANGED
@@ -1,3 +1,2 @@
1
1
  export * from "./canvas";
2
- export * from "./hooks";
3
- // export * from './charts';
2
+ export * from "./hooks";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heitu",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "diy hook canvas component",
5
5
  "module": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -84,9 +84,10 @@
84
84
  "fflate": "^0.8.2",
85
85
  "js-cookie": "^3.0.5",
86
86
  "lodash-es": "^4.17.21",
87
+ "mockjs": "^1.1.0",
87
88
  "qs": "^6.13.0",
88
89
  "unstated-next": "^1.1.0",
89
90
  "urijs": "^1.19.11",
90
91
  "uuid": "^10.0.0"
91
92
  }
92
- }
93
+ }
File without changes
File without changes