@chaomingd/hooks 0.0.34

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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +23 -0
  3. package/dist/esm/index.d.ts +10 -0
  4. package/dist/esm/index.js +10 -0
  5. package/dist/esm/useDragAndDrop/index.d.ts +35 -0
  6. package/dist/esm/useDragAndDrop/index.js +193 -0
  7. package/dist/esm/useDragAndDrop/index.less +29 -0
  8. package/dist/esm/useEditModal/index.d.ts +56 -0
  9. package/dist/esm/useEditModal/index.js +166 -0
  10. package/dist/esm/useEffectWithTarget/index.d.ts +2 -0
  11. package/dist/esm/useEffectWithTarget/index.js +36 -0
  12. package/dist/esm/useLatestState/index.d.ts +8 -0
  13. package/dist/esm/useLatestState/index.js +36 -0
  14. package/dist/esm/useListLayout/index.d.ts +20 -0
  15. package/dist/esm/useListLayout/index.js +112 -0
  16. package/dist/esm/usePagination/constant.d.ts +2 -0
  17. package/dist/esm/usePagination/constant.js +2 -0
  18. package/dist/esm/usePagination/index.d.ts +14 -0
  19. package/dist/esm/usePagination/index.js +184 -0
  20. package/dist/esm/usePagination/type.d.ts +68 -0
  21. package/dist/esm/usePagination/type.js +1 -0
  22. package/dist/esm/usePagination/utils.d.ts +1 -0
  23. package/dist/esm/usePagination/utils.js +8 -0
  24. package/dist/esm/useResizer/index.d.ts +37 -0
  25. package/dist/esm/useResizer/index.js +173 -0
  26. package/dist/esm/useResponsive/index.d.ts +44 -0
  27. package/dist/esm/useResponsive/index.js +94 -0
  28. package/dist/esm/useSelectionList/index.d.ts +13 -0
  29. package/dist/esm/useSelectionList/index.js +49 -0
  30. package/dist/lib/index.d.ts +10 -0
  31. package/dist/lib/index.js +112 -0
  32. package/dist/lib/useDragAndDrop/index.d.ts +35 -0
  33. package/dist/lib/useDragAndDrop/index.js +191 -0
  34. package/dist/lib/useDragAndDrop/index.less +29 -0
  35. package/dist/lib/useEditModal/index.d.ts +56 -0
  36. package/dist/lib/useEditModal/index.js +160 -0
  37. package/dist/lib/useEffectWithTarget/index.d.ts +2 -0
  38. package/dist/lib/useEffectWithTarget/index.js +37 -0
  39. package/dist/lib/useLatestState/index.d.ts +8 -0
  40. package/dist/lib/useLatestState/index.js +29 -0
  41. package/dist/lib/useListLayout/index.d.ts +20 -0
  42. package/dist/lib/useListLayout/index.js +116 -0
  43. package/dist/lib/usePagination/constant.d.ts +2 -0
  44. package/dist/lib/usePagination/constant.js +8 -0
  45. package/dist/lib/usePagination/index.d.ts +14 -0
  46. package/dist/lib/usePagination/index.js +157 -0
  47. package/dist/lib/usePagination/type.d.ts +68 -0
  48. package/dist/lib/usePagination/type.js +5 -0
  49. package/dist/lib/usePagination/utils.d.ts +1 -0
  50. package/dist/lib/usePagination/utils.js +14 -0
  51. package/dist/lib/useResizer/index.d.ts +37 -0
  52. package/dist/lib/useResizer/index.js +168 -0
  53. package/dist/lib/useResponsive/index.d.ts +44 -0
  54. package/dist/lib/useResponsive/index.js +88 -0
  55. package/dist/lib/useSelectionList/index.d.ts +13 -0
  56. package/dist/lib/useSelectionList/index.js +45 -0
  57. package/package.json +39 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # @chaomingd/hooks
2
+
3
+ [![NPM version](https://img.shields.io/npm/v/@chaomingd/hooks.svg?style=flat)](https://npmjs.com/package/@chaomingd/hooks)
4
+ [![NPM downloads](http://img.shields.io/npm/dm/@chaomingd/hooks.svg?style=flat)](https://npmjs.com/package/@chaomingd/hooks)
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ $ pnpm install
10
+ ```
11
+
12
+ ```bash
13
+ $ npm run dev
14
+ $ npm run build
15
+ ```
16
+
17
+ ## Options
18
+
19
+ TODO
20
+
21
+ ## LICENSE
22
+
23
+ MIT
@@ -0,0 +1,10 @@
1
+ import useLatestState from './useLatestState';
2
+ export * from './useDragAndDrop';
3
+ export * from './usePagination';
4
+ export * from './useResizer';
5
+ export * from './useResponsive';
6
+ export * from './useEffectWithTarget';
7
+ export * from './useEditModal';
8
+ export * from './useListLayout';
9
+ export * from './useSelectionList';
10
+ export { useLatestState };
@@ -0,0 +1,10 @@
1
+ import useLatestState from "./useLatestState";
2
+ export * from "./useDragAndDrop";
3
+ export * from "./usePagination";
4
+ export * from "./useResizer";
5
+ export * from "./useResponsive";
6
+ export * from "./useEffectWithTarget";
7
+ export * from "./useEditModal";
8
+ export * from "./useListLayout";
9
+ export * from "./useSelectionList";
10
+ export { useLatestState };
@@ -0,0 +1,35 @@
1
+ import { MutableRefObject } from 'react';
2
+ import './index.less';
3
+ type TEffect = 'disabled' | 'drop' | 'auto' | '';
4
+ declare function updateDragEffect(effect: TEffect): void;
5
+ export declare function setDragData(data: Record<string, any>): void;
6
+ export declare function getDragData(): {
7
+ [x: string]: any;
8
+ };
9
+ type TDomRef = MutableRefObject<HTMLElement | null>;
10
+ interface ICallbackOptions {
11
+ setDragData: typeof setDragData;
12
+ updateDragEffect: typeof updateDragEffect;
13
+ node: HTMLElement;
14
+ }
15
+ export interface IDragOptions {
16
+ onDragStart?: (e: MouseEvent, options: ICallbackOptions) => void;
17
+ onDragEnd?: (e: MouseEvent, options: ICallbackOptions) => void;
18
+ key: string;
19
+ containerClassName?: string;
20
+ }
21
+ export declare function handlerDragMouseDown(e: any, options: IDragOptions, dom: HTMLElement | null): void;
22
+ interface IDropCallbackOptions {
23
+ updateDragEffect: typeof updateDragEffect;
24
+ getDragData: typeof getDragData;
25
+ }
26
+ export interface IDropOptions {
27
+ key: string;
28
+ onDragEnter?: (e: MouseEvent, options: IDropCallbackOptions) => void;
29
+ onDragLeave?: (e: MouseEvent, options: IDropCallbackOptions) => void;
30
+ onDragMove?: (e: MouseEvent, options: IDropCallbackOptions) => void;
31
+ onDrop?: (e: MouseEvent, options: IDropCallbackOptions) => void;
32
+ onValideDrop?: (e: MouseEvent, options: IDropCallbackOptions) => boolean;
33
+ }
34
+ export declare function useDrop(domRef: TDomRef, options: IDropOptions): void;
35
+ export {};
@@ -0,0 +1,193 @@
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 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; }
3
+ 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; }
4
+ 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; }
5
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
6
+ 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); }
7
+ import { listen, EventEmitter } from '@chaomingd/utils';
8
+ import { useEffect, useRef } from 'react';
9
+ import "./index.less";
10
+ var Signal = new EventEmitter();
11
+ var store = getInitialStore();
12
+ function getInitialStore() {
13
+ return {
14
+ data: {},
15
+ container: null,
16
+ draging: false,
17
+ enterDropArea: false,
18
+ offset: {
19
+ x: 0,
20
+ y: 0
21
+ },
22
+ effect: ''
23
+ };
24
+ }
25
+ function resetStore() {
26
+ Object.assign(store, getInitialStore());
27
+ }
28
+ function updateDragEffect(effect) {
29
+ if (effect === store.effect) return;
30
+ store.effect = effect;
31
+ var container = store.container;
32
+ if (container) {
33
+ container.setAttribute('effect', effect);
34
+ }
35
+ }
36
+ export function setDragData(data) {
37
+ Object.assign(store.data, data);
38
+ }
39
+ export function getDragData() {
40
+ return _objectSpread({}, store.data);
41
+ }
42
+ function initContainer(options) {
43
+ if (!store.container) {
44
+ store.container = document.createElement('div');
45
+ }
46
+ if (store.container.parentNode === document.body) return;
47
+ var className = 'laf-drag-item';
48
+ if (options.containerClassName) {
49
+ className += " ".concat(options.containerClassName);
50
+ }
51
+ store.container.className = className;
52
+ document.body.appendChild(store.container);
53
+ }
54
+ function addTargetCloneNode(dom) {
55
+ var node = dom.cloneNode(true);
56
+ node.style.position = 'static';
57
+ var rect = dom.getBoundingClientRect();
58
+ store.container.style.width = rect.width + 'px';
59
+ store.container.style.height = rect.height + 'px';
60
+ store.container.appendChild(node);
61
+ return node;
62
+ }
63
+ function updateContainerPosition(e, dom) {
64
+ var container = store.container;
65
+ var offset = store.offset;
66
+ // container.style.left = e.clientX - offset.x + 'px';
67
+ // container.style.top = e.clientY - offset.y + 'px';
68
+ container.style.transform = "translate3d(".concat(e.clientX - offset.x, "px, ").concat(e.clientY - offset.y, "px, 0)");
69
+ if (isInDom(dom, e)) {
70
+ updateDragEffect('auto');
71
+ } else {
72
+ if (!store.enterDropArea) {
73
+ updateDragEffect('disabled');
74
+ }
75
+ }
76
+ }
77
+ function removeContainer() {
78
+ if (store.container) {
79
+ var _store$container$pare;
80
+ store.container.firstElementChild && store.container.removeChild(store.container.firstElementChild);
81
+ (_store$container$pare = store.container.parentNode) === null || _store$container$pare === void 0 || _store$container$pare.removeChild(store.container);
82
+ store.container = null;
83
+ }
84
+ }
85
+ function setOffset(e, dom) {
86
+ if (!dom) return;
87
+ var rect = dom.getBoundingClientRect();
88
+ store.offset = {
89
+ x: e.clientX - rect.left,
90
+ y: e.clientY - rect.top
91
+ };
92
+ }
93
+ export function handlerDragMouseDown(e, options, dom) {
94
+ if (!dom) return;
95
+ var move = false;
96
+ var cloneNode;
97
+ initContainer(options);
98
+ var SignalKey = options.key;
99
+ setOffset(e, dom);
100
+ // eslint-disable-next-line @typescript-eslint/no-shadow
101
+ var offMouseMove = listen(document, 'mousemove', function (e) {
102
+ e.preventDefault();
103
+ if (!move) {
104
+ var _options$onDragStart;
105
+ cloneNode = addTargetCloneNode(dom);
106
+ (_options$onDragStart = options.onDragStart) === null || _options$onDragStart === void 0 || _options$onDragStart.call(options, e, {
107
+ setDragData: setDragData,
108
+ updateDragEffect: updateDragEffect,
109
+ node: cloneNode
110
+ });
111
+ move = true;
112
+ store.draging = true;
113
+ } else {
114
+ Signal.emit("".concat(SignalKey, "-mousemove"), e);
115
+ }
116
+ updateContainerPosition(e, dom);
117
+ });
118
+ // eslint-disable-next-line @typescript-eslint/no-shadow
119
+ var offMouseUp = listen(document, 'mouseup', function (e) {
120
+ e.preventDefault();
121
+ offMouseMove();
122
+ offMouseUp();
123
+ if (move) {
124
+ var _options$onDragEnd;
125
+ (_options$onDragEnd = options.onDragEnd) === null || _options$onDragEnd === void 0 || _options$onDragEnd.call(options, e, {
126
+ node: cloneNode,
127
+ setDragData: setDragData,
128
+ updateDragEffect: updateDragEffect
129
+ });
130
+ Signal.emit("".concat(SignalKey, "-mouseup"), e);
131
+ }
132
+ updateDragEffect('auto');
133
+ removeContainer();
134
+ resetStore();
135
+ });
136
+ }
137
+ export function useDrop(domRef, options) {
138
+ var optionsRef = useRef(options);
139
+ useEffect(function () {
140
+ var SignalKey = optionsRef.current.key;
141
+ var isDragEnter = false;
142
+ var callbackOptions = {
143
+ updateDragEffect: updateDragEffect,
144
+ getDragData: getDragData
145
+ };
146
+ var onMouseMove = function onMouseMove(e) {
147
+ if (isInDom(domRef.current, e)) {
148
+ var _optionsRef$current$o2, _optionsRef$current2;
149
+ if (!isDragEnter) {
150
+ var _optionsRef$current$o, _optionsRef$current;
151
+ isDragEnter = true;
152
+ (_optionsRef$current$o = (_optionsRef$current = optionsRef.current).onDragEnter) === null || _optionsRef$current$o === void 0 || _optionsRef$current$o.call(_optionsRef$current, e, callbackOptions);
153
+ store.enterDropArea = true;
154
+ updateDragEffect('drop');
155
+ }
156
+ (_optionsRef$current$o2 = (_optionsRef$current2 = optionsRef.current).onDragMove) === null || _optionsRef$current$o2 === void 0 || _optionsRef$current$o2.call(_optionsRef$current2, e, callbackOptions);
157
+ } else {
158
+ if (isDragEnter) {
159
+ var _optionsRef$current$o3, _optionsRef$current3;
160
+ store.enterDropArea = false;
161
+ isDragEnter = false;
162
+ updateDragEffect('disabled');
163
+ (_optionsRef$current$o3 = (_optionsRef$current3 = optionsRef.current).onDragLeave) === null || _optionsRef$current$o3 === void 0 || _optionsRef$current$o3.call(_optionsRef$current3, e, callbackOptions);
164
+ }
165
+ }
166
+ };
167
+ var onMouseUp = function onMouseUp(e) {
168
+ if (isInDom(domRef.current, e)) {
169
+ var validate = true;
170
+ if (optionsRef.current.onValideDrop) {
171
+ validate = optionsRef.current.onValideDrop(e, callbackOptions);
172
+ }
173
+ if (validate) {
174
+ var _optionsRef$current$o4, _optionsRef$current4;
175
+ (_optionsRef$current$o4 = (_optionsRef$current4 = optionsRef.current).onDrop) === null || _optionsRef$current$o4 === void 0 || _optionsRef$current$o4.call(_optionsRef$current4, e, callbackOptions);
176
+ }
177
+ }
178
+ store.enterDropArea = false;
179
+ };
180
+ Signal.on("".concat(SignalKey, "-mousemove"), onMouseMove);
181
+ Signal.on("".concat(SignalKey, "-mouseup"), onMouseUp);
182
+ }, [domRef]);
183
+ }
184
+ function isInDom(dom, e) {
185
+ if (!dom) return false;
186
+ var rect = dom.getBoundingClientRect();
187
+ var clientX = e.clientX;
188
+ var clientY = e.clientY;
189
+ if (clientX < rect.left || clientX > rect.left + rect.width || clientY < rect.top || clientY > rect.top + rect.height) {
190
+ return false;
191
+ }
192
+ return true;
193
+ }
@@ -0,0 +1,29 @@
1
+ .laf-drag-item {
2
+ position: fixed;
3
+ z-index: 10000;
4
+ opacity: 0.7;
5
+ top: 0;
6
+ left: 0;
7
+
8
+ &::after {
9
+ content: '';
10
+ position: absolute;
11
+ top: 50%;
12
+ left: 50%;
13
+ width: 200%;
14
+ height: 200%;
15
+ transform: translate(-50%, -50%);
16
+ }
17
+
18
+ &[effect='disabled'] {
19
+ &::after {
20
+ cursor: not-allowed;
21
+ }
22
+ }
23
+
24
+ &[effect='drop'] {
25
+ &::after {
26
+ cursor: copy;
27
+ }
28
+ }
29
+ }
@@ -0,0 +1,56 @@
1
+ /// <reference types="react" />
2
+ import { FormInstance } from 'antd';
3
+ interface IState {
4
+ visible: boolean;
5
+ title: string;
6
+ loading: boolean;
7
+ confirmLoading: boolean;
8
+ isEdit: boolean;
9
+ [key: string]: any;
10
+ }
11
+ interface IHandlerReturnValue<IFormValues extends Record<string, any> = Record<string, any>, IUserState extends Record<string, any> = Record<string, any>> {
12
+ formValue?: Partial<IFormValues>;
13
+ state?: Partial<IState & IUserState>;
14
+ }
15
+ interface IHandlerData<IFormValues extends Record<string, any> = Record<string, any>, IUserState extends Record<string, any> = Record<string, any>> {
16
+ formValue?: Partial<IFormValues>;
17
+ state?: Partial<IState & IUserState>;
18
+ onSave?: (res: any, state: IState & IUserState) => void;
19
+ onError?: (e: Error) => void;
20
+ [key: string]: any;
21
+ }
22
+ type TPromiseValue<T> = T | Promise<T>;
23
+ interface IConfig<IFormValues extends Record<string, any> = Record<string, any>, IUserState extends Record<string, any> = Record<string, any>> {
24
+ title?: string;
25
+ hasLoading?: boolean;
26
+ hasConfirmLoading?: boolean;
27
+ saveService?: (formValues: IFormValues, state: IState & IUserState) => Promise<any>;
28
+ onSaveClose?: boolean;
29
+ onCloseResetState?: boolean;
30
+ onClose?: () => void;
31
+ onSave?: (res: any, state: IState & IUserState) => void;
32
+ onAdd?: (data: IHandlerReturnValue<IFormValues, IUserState>) => TPromiseValue<void | undefined | IHandlerReturnValue<IFormValues, IUserState>>;
33
+ onEdit?: (data: IHandlerReturnValue<IFormValues, IUserState>) => TPromiseValue<void | undefined | IHandlerReturnValue<IFormValues, IUserState>>;
34
+ defaultState?: IUserState;
35
+ form?: FormInstance;
36
+ }
37
+ export declare function useEditModal<IFormValues extends Record<string, any> = Record<string, any>, IUserState extends Record<string, any> = Record<string, any>>({ onAdd, onEdit, title, saveService, hasLoading, hasConfirmLoading, onSaveClose, onCloseResetState, onClose, onSave, defaultState, form, }?: IConfig<IFormValues, IUserState>): {
38
+ modalProps: {
39
+ open: boolean;
40
+ title: string;
41
+ onCancel: () => void;
42
+ onOk: () => void;
43
+ confirmLoading: boolean;
44
+ afterOpenChange: (open: boolean) => void;
45
+ };
46
+ state: IState & IUserState;
47
+ originDataRef: import("react").MutableRefObject<IHandlerData<IFormValues, IUserState>>;
48
+ formRef: import("react").MutableRefObject<FormInstance<any> | null>;
49
+ add: (data: IHandlerData<IFormValues, IUserState>) => void;
50
+ edit: (data: IHandlerData<IFormValues, IUserState>) => void;
51
+ close: () => void;
52
+ onSubmit: () => void;
53
+ submit: () => void;
54
+ model: import("@chaomingd/store").Model<IState, object, Record<string, any>>;
55
+ };
56
+ export {};
@@ -0,0 +1,166 @@
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 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; }
3
+ 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; }
4
+ 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; }
5
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
6
+ 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); }
7
+ import { useRef } from 'react';
8
+ import { useModel } from '@chaomingd/store';
9
+ import { omit } from '@chaomingd/utils';
10
+ function defaultHandler() {
11
+ return Promise.resolve({});
12
+ }
13
+ export function useEditModal() {
14
+ var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
15
+ _ref$onAdd = _ref.onAdd,
16
+ onAdd = _ref$onAdd === void 0 ? defaultHandler : _ref$onAdd,
17
+ _ref$onEdit = _ref.onEdit,
18
+ onEdit = _ref$onEdit === void 0 ? defaultHandler : _ref$onEdit,
19
+ _ref$title = _ref.title,
20
+ title = _ref$title === void 0 ? 'Modal Title' : _ref$title,
21
+ _ref$saveService = _ref.saveService,
22
+ saveService = _ref$saveService === void 0 ? defaultHandler : _ref$saveService,
23
+ _ref$hasLoading = _ref.hasLoading,
24
+ hasLoading = _ref$hasLoading === void 0 ? true : _ref$hasLoading,
25
+ _ref$hasConfirmLoadin = _ref.hasConfirmLoading,
26
+ hasConfirmLoading = _ref$hasConfirmLoadin === void 0 ? true : _ref$hasConfirmLoadin,
27
+ _ref$onSaveClose = _ref.onSaveClose,
28
+ onSaveClose = _ref$onSaveClose === void 0 ? true : _ref$onSaveClose,
29
+ _ref$onCloseResetStat = _ref.onCloseResetState,
30
+ onCloseResetState = _ref$onCloseResetStat === void 0 ? true : _ref$onCloseResetStat,
31
+ onClose = _ref.onClose,
32
+ onSave = _ref.onSave,
33
+ defaultState = _ref.defaultState,
34
+ form = _ref.form;
35
+ var formRef = useRef(form || null);
36
+ var originDataRef = useRef({});
37
+ var defaultEditState = _objectSpread({
38
+ visible: false,
39
+ title: title,
40
+ loading: false,
41
+ isEdit: false,
42
+ confirmLoading: false
43
+ }, defaultState);
44
+ var model = useModel({
45
+ state: defaultEditState
46
+ });
47
+ var state = model.useGetState();
48
+ var createHandler = function createHandler(isEdit) {
49
+ return function (data) {
50
+ if (model.getState().visible) {
51
+ return;
52
+ }
53
+ originDataRef.current = data;
54
+ var handler = isEdit ? onEdit : onAdd;
55
+ var formValues = _objectSpread({}, data.formValue || {});
56
+ var openState = _objectSpread(_objectSpread({}, data.state || {}), {}, {
57
+ visible: true,
58
+ isEdit: isEdit
59
+ });
60
+ if (hasLoading) {
61
+ openState.loading = true;
62
+ }
63
+ model.setState(openState);
64
+ var newState = {
65
+ loading: false
66
+ };
67
+ Promise.resolve(handler(data)).then(function (returnValue) {
68
+ if (returnValue && returnValue.formValue) {
69
+ Object.assign(formValues, (returnValue === null || returnValue === void 0 ? void 0 : returnValue.formValue) || {});
70
+ }
71
+ if (returnValue && returnValue.state) {
72
+ Object.assign(newState, returnValue.state);
73
+ }
74
+ }).finally(function () {
75
+ var _formRef$current;
76
+ model.setState(newState);
77
+ (_formRef$current = formRef.current) === null || _formRef$current === void 0 || _formRef$current.setFieldsValue(formValues);
78
+ });
79
+ };
80
+ };
81
+ var add = createHandler(false);
82
+ var edit = createHandler(true);
83
+ var close = function close() {
84
+ if (onCloseResetState) {
85
+ model.setState(omit(defaultEditState, ['title']));
86
+ } else {
87
+ model.setState({
88
+ visible: false
89
+ });
90
+ }
91
+ onClose && onClose();
92
+ };
93
+ var afterOpenChange = function afterOpenChange(open) {
94
+ if (!open) {
95
+ if (formRef.current) {
96
+ formRef.current.resetFields();
97
+ }
98
+ }
99
+ };
100
+ var onSubmit = function onSubmit() {
101
+ // eslint-disable-next-line @typescript-eslint/no-shadow
102
+ var handleService = function handleService(values, state) {
103
+ return saveService === null || saveService === void 0 ? void 0 : saveService(values, state).then(function (res) {
104
+ var currentState = model.getState();
105
+ onSaveClose && close();
106
+ onSave && onSave(res, currentState);
107
+ originDataRef.current.onSave && originDataRef.current.onSave(res, currentState);
108
+ if (hasConfirmLoading) {
109
+ model.setState({
110
+ confirmLoading: false
111
+ });
112
+ }
113
+ return res;
114
+ });
115
+ };
116
+ if (hasConfirmLoading) {
117
+ model.setState({
118
+ confirmLoading: true
119
+ });
120
+ }
121
+ if (formRef.current) {
122
+ var _formRef$current2;
123
+ (_formRef$current2 = formRef.current) === null || _formRef$current2 === void 0 || _formRef$current2.validateFields().then(function (values) {
124
+ return handleService(values, model.getState());
125
+ }).catch(function (e) {
126
+ console.error(e);
127
+ originDataRef.current.onError && originDataRef.current.onError(e);
128
+ if (hasConfirmLoading) {
129
+ model.setState({
130
+ confirmLoading: false
131
+ });
132
+ }
133
+ });
134
+ } else {
135
+ handleService({}, model.getState()).catch(function (e) {
136
+ console.error(e);
137
+ originDataRef.current.onError && originDataRef.current.onError(e);
138
+ if (hasConfirmLoading) {
139
+ model.setState({
140
+ confirmLoading: false
141
+ });
142
+ }
143
+ });
144
+ }
145
+ };
146
+ var modalProps = {
147
+ open: state.visible,
148
+ title: state.title,
149
+ onCancel: close,
150
+ onOk: onSubmit,
151
+ confirmLoading: state.confirmLoading,
152
+ afterOpenChange: afterOpenChange
153
+ };
154
+ return {
155
+ modalProps: modalProps,
156
+ state: state,
157
+ originDataRef: originDataRef,
158
+ formRef: formRef,
159
+ add: add,
160
+ edit: edit,
161
+ close: close,
162
+ onSubmit: onSubmit,
163
+ submit: onSubmit,
164
+ model: model
165
+ };
166
+ }
@@ -0,0 +1,2 @@
1
+ import { MutableRefObject } from 'react';
2
+ export declare function useEffectWithTarget(effect: () => any, targetRef?: MutableRefObject<any> | MutableRefObject<any>[] | null, deps?: any[], strict?: boolean): void;
@@ -0,0 +1,36 @@
1
+ import { useUnmount } from 'ahooks';
2
+ import { useEffect, useRef } from 'react';
3
+ import { isSameArr, isDefined } from '@chaomingd/utils';
4
+ export function useEffectWithTarget(effect, targetRef, deps) {
5
+ var strict = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
6
+ var lastDepsRef = useRef();
7
+ var lastElementRef = useRef();
8
+ var lastEffectReturnRef = useRef();
9
+ var clearEffect = function clearEffect() {
10
+ if (lastEffectReturnRef.current && typeof lastEffectReturnRef.current === 'function') {
11
+ lastEffectReturnRef.current();
12
+ }
13
+ };
14
+ useEffect(function () {
15
+ var currentTarget = (Array.isArray(targetRef) ? targetRef.map(function (ref) {
16
+ return ref.current;
17
+ }) : targetRef ? [targetRef.current] : []).filter(function (el) {
18
+ return isDefined(el);
19
+ });
20
+ if (!isSameArr(lastElementRef.current, currentTarget) || lastDepsRef.current && deps && !isSameArr(lastDepsRef.current, deps)) {
21
+ lastElementRef.current = currentTarget;
22
+ lastDepsRef.current = deps;
23
+ clearEffect();
24
+ if (strict) {
25
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
26
+ currentTarget.length && (lastEffectReturnRef.current = effect());
27
+ } else {
28
+ lastEffectReturnRef.current = effect();
29
+ }
30
+ }
31
+ });
32
+ useUnmount(function () {
33
+ lastElementRef.current = undefined;
34
+ clearEffect();
35
+ });
36
+ }
@@ -0,0 +1,8 @@
1
+ import type { Dispatch, SetStateAction } from 'react';
2
+ declare function useLatestState<T>(initialState: T | (() => T)): [T, Dispatch<SetStateAction<T>>, () => T];
3
+ declare function useLatestState<T = undefined>(): [
4
+ T | undefined,
5
+ Dispatch<SetStateAction<T | undefined>>,
6
+ () => T | undefined
7
+ ];
8
+ export default useLatestState;
@@ -0,0 +1,36 @@
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 { useCallback, useRef, useState } from 'react';
8
+ var isFunction = function isFunction(val) {
9
+ return typeof val === 'function';
10
+ };
11
+
12
+ // 获取新的状态值,兼容传值和传函数情况
13
+ function getStateVal(preState, initVal) {
14
+ if (isFunction(initVal)) {
15
+ return initVal(preState);
16
+ }
17
+ return initVal;
18
+ }
19
+ function useLatestState(initVal) {
20
+ var initState = getStateVal(undefined, initVal);
21
+ var _useState = useState(initState),
22
+ _useState2 = _slicedToArray(_useState, 2),
23
+ val = _useState2[0],
24
+ setVal = _useState2[1];
25
+ var valRef = useRef(initState);
26
+ var setState = useCallback(function (newVal) {
27
+ var newState = getStateVal(valRef.current, newVal);
28
+ valRef.current = newState;
29
+ setVal(newState);
30
+ }, []);
31
+ var getRealState = useCallback(function () {
32
+ return valRef.current;
33
+ }, []);
34
+ return [val, setState, getRealState];
35
+ }
36
+ export default useLatestState;
@@ -0,0 +1,20 @@
1
+ import { MutableRefObject } from 'react';
2
+ import { px } from '@chaomingd/utils';
3
+ export declare function setDefaultTransform(transform: typeof px): void;
4
+ export interface UseListLayoutConfig {
5
+ containerRef?: MutableRefObject<HTMLElement | null>;
6
+ baseWidth: number;
7
+ baseHeight?: number;
8
+ gap?: number | [number, number];
9
+ onChange?: (state: IState) => any;
10
+ removeScrollBarWidth?: boolean;
11
+ pxTransform?: (base: number, width: number) => number;
12
+ }
13
+ interface IState {
14
+ col: number;
15
+ row: number;
16
+ width: number;
17
+ height: number;
18
+ }
19
+ export declare function useListLayout(config: UseListLayoutConfig): IState;
20
+ export {};