Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate @storybook/channel-postmessage to TypeScript #5154

Merged
merged 2 commits into from
Jan 7, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/channel-postmessage/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
},
"license": "MIT",
"main": "dist/index.js",
"jsnext:main": "src/index.js",
"types": "dist/index.d.ts",
"scripts": {
"prepare": "node ../../scripts/prepare.js"
},
Expand All @@ -24,6 +24,9 @@
"global": "^4.3.2",
"json-stringify-safe": "^5.0.1"
},
"devDependencies": {
"@types/json-stringify-safe": "^5.0.0"
},
"publishConfig": {
"access": "public"
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,52 +1,64 @@
/* eslint-disable no-underscore-dangle */

import { window, document } from 'global';
import Channel from '@storybook/channels';
import Channel, { ChannelEvent, ChannelHandler } from '@storybook/channels';
import stringify from 'json-stringify-safe';

interface RawEvent {
data: string;
}

export interface Config {
page: 'manager' | 'preview';
}

export const KEY = 'storybook-channel';

export class PostmsgTransport {
constructor(config) {
this._config = config;
this._buffer = [];
this._handler = null;
window.addEventListener('message', this._handleEvent.bind(this), false);
document.addEventListener('DOMContentLoaded', () => this._flush());
private config: Config;
private buffer: any[];
dandean marked this conversation as resolved.
Show resolved Hide resolved
private handler: ChannelHandler;

constructor(config: Config) {
this.config = config;
this.buffer = [];
this.handler = null;
window.addEventListener('message', this.handleEvent.bind(this), false);
document.addEventListener('DOMContentLoaded', () => this.flush());
// 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) {
this._handler = handler;
setHandler(handler: ChannelHandler): void {
this.handler = handler;
}

send(event) {
send(event: ChannelEvent): Promise<any> {
const iframeWindow = this._getWindow();
if (!iframeWindow) {
return new Promise((resolve, reject) => {
this._buffer.push({ event, resolve, reject });
this.buffer.push({ event, resolve, reject });
});
}
const data = stringify({ key: KEY, event });
iframeWindow.postMessage(data, '*');
return Promise.resolve(null);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return Promise.resolve(null) feels odd
In all return cases, the return value should be void right? This existed before your PR, I just thought this should be fixed because this return value is part of the public API now

@ndelangen what do you think?

Like this:

  send(event: ChannelEvent): Promise<void> {
    const iframeWindow = this.getWindow();
    if (!iframeWindow) {
      return new Promise((resolve, reject) => {
        this._buffer.push({ event, resolve, reject });
        this.buffer.push({ event, resolve, reject });
      });
    }
    const data = stringify({ key: KEY, event });
    iframeWindow.postMessage(data, '*');
    return Promise.resolve();
}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm cool with whatever you and @ndelangen decide. Happy to make the patch if you want me to.

}

_flush() {
const buffer = this._buffer;
this._buffer = [];
private flush(): void {
const buffer = this.buffer;
this.buffer = [];
buffer.forEach(item => {
this.send(item.event)
.then(item.resolve)
.catch(item.reject);
});
}

_getWindow() {
if (this._config.page === 'manager') {
getWindow(): Window {
if (this.config.page === 'manager') {
// FIXME this is a really bad idea! use a better way to do this.
// This finds the storybook preview iframe to send messages to.
const iframe = document.getElementById('storybook-preview-iframe');
Expand All @@ -58,18 +70,18 @@ export class PostmsgTransport {
return window.parent;
}

_handleEvent(rawEvent) {
private handleEvent(rawEvent: RawEvent): void {
try {
const { data } = rawEvent;
const { key, event } = JSON.parse(data);
if (key === KEY) {
this._handler(event);
this.handler(event);
}
} catch (error) {} // eslint-disable-line
}
}

export default function createChannel({ page }) {
export default function createChannel({ page }): Channel {
const transport = new PostmsgTransport({ page });
return new Channel({ transport });
}
1 change: 1 addition & 0 deletions lib/channel-postmessage/src/typings.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module 'global';
8 changes: 8 additions & 0 deletions lib/channel-postmessage/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["src/**.test.ts"]
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2349,6 +2349,11 @@
resolved "https://registry.yarnpkg.com/@types/jest/-/jest-23.3.10.tgz#4897974cc317bf99d4fe6af1efa15957fa9c94de"
integrity sha512-DC8xTuW/6TYgvEg3HEXS7cu9OijFqprVDXXiOcdOKZCU/5PJNLZU37VVvmZHdtMiGOa8wAA/We+JzbdxFzQTRQ==

"@types/json-stringify-safe@^5.0.0":
version "5.0.0"
resolved "https://registry.yarnpkg.com/@types/json-stringify-safe/-/json-stringify-safe-5.0.0.tgz#df34d054419d39323a3730966bacba02ac5e474e"
integrity sha512-UUA1sH0RSRROdInuDOA1yoRzbi5xVFD1RHCoOvNRPTNwR8zBkJ/84PZ6NhKVDtKp0FTeIccJCdQz1X2aJPr4uw==

"@types/json5@^0.0.29":
version "0.0.29"
resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee"
Expand Down