@blocklet/pages-kit 0.5.17 → 0.5.18

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.
@@ -75,4 +75,5 @@ exports.BuiltinModules = {
75
75
  '@blocklet/pages-kit/builtin/uploader': {},
76
76
  '@blocklet/pages-kit/builtin/color-picker': {},
77
77
  '@blocklet/pages-kit/builtin/markdown/index': {},
78
+ '@blocklet/pages-kit/builtin/event-bus': {},
78
79
  };
@@ -39,6 +39,7 @@ const colorPicker = __importStar(require("../builtin/color-picker"));
39
39
  const components = __importStar(require("../builtin/components"));
40
40
  const dayjs = __importStar(require("../builtin/dayjs"));
41
41
  const emotionCss = __importStar(require("../builtin/emotion/css"));
42
+ const eventBus = __importStar(require("../builtin/event-bus"));
42
43
  const iconifyReact = __importStar(require("../builtin/iconify/react"));
43
44
  const immer = __importStar(require("../builtin/immer"));
44
45
  const locale = __importStar(require("../builtin/locale"));
@@ -108,6 +109,7 @@ function injectGlobalComponents() {
108
109
  '@blocklet/pages-kit/builtin/async/react-syntax-highlighter': reactSyntaxHighlighter,
109
110
  '@blocklet/pages-kit/builtin/async/image-preview': imagePreview,
110
111
  '@blocklet/pages-kit/builtin/async/ai-runtime': Promise.resolve().then(() => __importStar(require('../builtin/async/ai-runtime'))),
112
+ '@blocklet/pages-kit/builtin/event-bus': eventBus,
111
113
  };
112
114
  // set global variable
113
115
  win[builtin_1.BuiltinModulesGlobalVariableName] = {
@@ -0,0 +1,35 @@
1
+ import mitt from 'mitt';
2
+ import { useEffect, useCallback } from 'react';
3
+ export const eventBus = mitt();
4
+ export const useEventBus = (eventName, eventCallBack, deps = []) => {
5
+ // 使用 useCallback 包装 emit 函数避免重渲染
6
+ const emit = useCallback((name, data) => {
7
+ eventBus.emit(name, data);
8
+ }, []);
9
+ useEffect(() => {
10
+ if (eventName && eventCallBack) {
11
+ // 包装回调以添加错误处理
12
+ const wrappedCallback = (data) => {
13
+ try {
14
+ eventCallBack(data);
15
+ }
16
+ catch (error) {
17
+ console.error(`Error in event handler for "${eventName}":`, error);
18
+ }
19
+ };
20
+ eventBus.on(eventName, wrappedCallback);
21
+ return () => {
22
+ eventBus.off(eventName, wrappedCallback);
23
+ };
24
+ }
25
+ return () => { };
26
+ }, [eventName, eventCallBack, ...deps]);
27
+ return {
28
+ emit,
29
+ // 提供更多控制功能
30
+ off: eventBus.off,
31
+ on: eventBus.on,
32
+ all: eventBus.all,
33
+ };
34
+ };
35
+ export default useEventBus;