-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
index.ts
237 lines (196 loc) · 6.64 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import { window, document, location } from 'global';
import * as EVENTS from '@storybook/core-events';
import Channel, { ChannelEvent, ChannelHandler } from '@storybook/channels';
import { logger, pretty } from '@storybook/client-logger';
import { isJSON, parse, stringify } from 'telejson';
interface Config {
page: 'manager' | 'preview';
}
interface BufferedEvent {
event: ChannelEvent;
resolve: (value?: any) => void;
reject: (reason?: any) => void;
}
export const KEY = 'storybook-channel';
// TODO: we should export a method for opening child windows here and keep track of em.
// that way we can send postMessage to child windows as well, not just iframe
// https://stackoverflow.com/questions/6340160/how-to-get-the-references-of-all-already-opened-child-windows
export class PostmsgTransport {
private buffer: BufferedEvent[];
private handler: ChannelHandler;
private connected: boolean;
constructor(private readonly config: Config) {
this.buffer = [];
this.handler = null;
window.addEventListener('message', this.handleEvent.bind(this), false);
// Check whether the config.page parameter has a valid value
if (config.page !== 'manager' && config.page !== 'preview') {
throw new Error(`postmsg-channel: "config.page" cannot be "${config.page}"`);
}
}
setHandler(handler: ChannelHandler): void {
this.handler = (...args) => {
handler.apply(this, args);
if (!this.connected && this.getLocalFrame().length) {
this.flush();
this.connected = true;
}
};
}
/**
* Sends `event` to the associated window. If the window does not yet exist
* the event will be stored in a buffer and sent when the window exists.
* @param event
*/
send(event: ChannelEvent, options?: any): Promise<any> {
let depth = 15;
let allowFunction = true;
let target;
if (options && typeof options.allowFunction === 'boolean') {
allowFunction = options.allowFunction;
}
if (options && Number.isInteger(options.depth)) {
depth = options.depth;
}
if (options && typeof options.target === 'string') {
target = options.target;
}
const frames = this.getFrames(target);
const data = stringify(
{ key: KEY, event, source: document.location.origin + document.location.pathname },
{ maxDepth: depth, allowFunction }
);
if (!frames.length) {
return new Promise((resolve, reject) => {
this.buffer.push({ event, resolve, reject });
});
}
if (this.buffer.length) {
this.flush();
}
frames.forEach((f) => {
try {
f.postMessage(data, '*');
} catch (e) {
console.error('sending over postmessage fail');
}
});
return Promise.resolve(null);
}
private flush(): void {
const { buffer } = this;
this.buffer = [];
buffer.forEach((item) => {
this.send(item.event).then(item.resolve).catch(item.reject);
});
}
private getFrames(target?: string): Window[] {
if (this.config.page === 'manager') {
const nodes: HTMLIFrameElement[] = [
...document.querySelectorAll('iframe[data-is-storybook][data-is-loaded]'),
];
const list = nodes
.filter((e) => {
try {
return !!e.contentWindow && e.dataset.isStorybook !== undefined && e.id === target;
} catch (er) {
return false;
}
})
.map((e) => e.contentWindow);
return list.length ? list : this.getCurrentFrames();
}
if (window && window.parent) {
return [window.parent];
}
return [];
}
private getCurrentFrames(): Window[] {
if (this.config.page === 'manager') {
const list: HTMLIFrameElement[] = [
...document.querySelectorAll('[data-is-storybook="true"]'),
];
return list.map((e) => e.contentWindow);
}
if (window && window.parent) {
return [window.parent];
}
return [];
}
private getLocalFrame(): Window[] {
if (this.config.page === 'manager') {
const list: HTMLIFrameElement[] = [...document.querySelectorAll('#storybook-preview-iframe')];
return list.map((e) => e.contentWindow);
}
if (window && window.parent) {
return [window.parent];
}
return [];
}
private handleEvent(rawEvent: MessageEvent): void {
try {
const { data } = rawEvent;
const { key, event, source } = typeof data === 'string' && isJSON(data) ? parse(data) : data;
if (key === KEY) {
const pageString =
this.config.page === 'manager'
? `<span style="color: #37D5D3; background: black"> manager </span>`
: `<span style="color: #1EA7FD; background: black"> preview </span>`;
const eventString = Object.values(EVENTS).includes(event.type)
? `<span style="color: #FF4785">${event.type}</span>`
: `<span style="color: #FFAE00">${event.type}</span>`;
event.source = source || getEventSourceUrl(rawEvent);
if (!event.source) {
logger.error(
`${pageString} received ${eventString} but was unable to determine the source of the event`
);
return;
}
pretty.debug(
location.origin !== event.source
? `${pageString} received ${eventString}`
: `${pageString} received ${eventString} <span style="color: gray">(on ${location.origin} from ${event.source})</span>`,
...event.args
);
this.handler(event);
}
} catch (error) {
logger.error(error);
}
}
}
const getEventSourceUrl = (event: MessageEvent) => {
const frames: HTMLIFrameElement[] = [...document.getElementsByTagName('iframe')];
// try to find the originating iframe by matching it's contentWindow
// This might not be cross-origin safe
const [frame, ...remainder] = frames.filter((element) => {
try {
return element.contentWindow === event.source;
} catch (err) {
// continue
}
const src = element.getAttribute('src');
let origin;
try {
({ origin } = new URL(src, document.location));
} catch (err) {
return false;
}
return origin === event.origin;
});
// If we found multiple matches, there's going to be trouble
if (remainder.length) {
console.error('unable to locate origin of postmessage');
return null;
}
const src = frame.getAttribute('src');
const { origin, pathname } = new URL(src, document.location);
return origin + pathname;
};
/**
* Creates a channel which communicates with an iframe or child window.
*/
export default function createChannel({ page }: Config): Channel {
const transport = new PostmsgTransport({ page });
return new Channel({ transport });
}