-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.ts
75 lines (60 loc) · 1.86 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { loadBridge } from "./modules/bridge";
import {
SbSDKOptions,
StoryblokBridgeConfigV2,
StoryblokBridgeV2,
StoryData,
SbInitResult,
} from "./types";
const bridgeLatest = "https://app.storyblok.com/f/storyblok-v2-latest.js";
export const useStoryblokBridge = (
id: Number,
cb: (newStory: StoryData) => void,
options: StoryblokBridgeConfigV2 = {}
) => {
if (typeof window === "undefined") {
return;
}
if (typeof window.storyblokRegisterEvent === "undefined") {
console.error(
"Storyblok Bridge is disabled. Please enable it to use it. Read https://github.com/storyblok/storyblok-js"
);
return;
}
if (!id) {
console.warn("Story ID is not defined. Please provide a valid ID.");
return;
}
window.storyblokRegisterEvent(() => {
const sbBridge: StoryblokBridgeV2 = new window.StoryblokBridge(options);
sbBridge.on(["input", "published", "change"], (event) => {
if (event.action == "input" && event.story.id === id) {
cb(event.story);
} else {
window.location.reload();
}
});
});
};
export { default as apiPlugin } from "./modules/api";
export { default as storyblokEditable } from "./modules/editable";
export const storyblokInit = (pluginOptions: SbSDKOptions = {}) => {
const { bridge, accessToken, use = [], apiOptions = {} } = pluginOptions;
apiOptions.accessToken = apiOptions.accessToken || accessToken;
// Initialize plugins
const options = { bridge, apiOptions };
let result: SbInitResult = {};
use.forEach((pluginFactory: Function) => {
result = { ...result, ...pluginFactory(options) };
});
// Load bridge
if (bridge !== false) {
loadBridge(bridgeLatest);
}
return result;
};
export const loadStoryblokBridge = () => {
return loadBridge(bridgeLatest);
};
// Reexport all types so users can have access to them
export * from "./types";