Skip to content

Commit

Permalink
add examples
Browse files Browse the repository at this point in the history
  • Loading branch information
hanzhixing committed Mar 23, 2023
1 parent cd8242a commit 36c3b19
Show file tree
Hide file tree
Showing 32 changed files with 725 additions and 12 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ If you are familiar with `socket.io`, you already know how to use this package.

`msgio` is based on postMessage.

Occasionally, we need to build web apps with iframes agross different domains. Communication between these iframes always make us uncomfortable
.Using this library less pain you will suffer.

## Examples
All examples are in the 'examples' directory in this repository.

## Install

Expand Down
17 changes: 17 additions & 0 deletions examples/create-react-app/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# EditorConfig is awesome: http://EditorConfig.org

# top-most EditorConfig file
root = true

# General settings for whole project
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true

# Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}]
indent_size = 2
5 changes: 5 additions & 0 deletions examples/create-react-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# create-react-app
1. Open two terminal window.
2. Run `PORT=3456 npm start` in the first terminal.
3. Run `PORT=4567 npm start` in the second terminal.
4. Open `http://localhost:3456/host` in the browser and see the console.
45 changes: 45 additions & 0 deletions examples/create-react-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "create-react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.18",
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.11",
"msgio": "^1.0.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.9.0",
"react-scripts": "5.0.1",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file added examples/create-react-app/public/favicon.ico
Binary file not shown.
43 changes: 43 additions & 0 deletions examples/create-react-app/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
51 changes: 51 additions & 0 deletions examples/create-react-app/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {useCallback, SyntheticEvent} from 'react';
import {Iframe} from 'msgio';

const summarize = (...args: any) => args.reduce((acc: any, cur: any) => (acc + cur), 0);

const multiply = (a: any, b: any) => Promise.resolve(a * b);

const throw1 = () => {
throw new Error('Host throws Error. Error1');
};

const throw2 = () => {
return Promise.reject(new Error('Host throws Error: Error2'));
};

const App = () => {
const handleLoad = useCallback(
(e: SyntheticEvent<HTMLIFrameElement>) => {
const host = new Iframe(e.target as HTMLIFrameElement);

host.on('connect', socket => {
console.log('host:connected');

socket.on('guest_event_1', (...args: any) => {
console.log('host:main:guest_event_1', ...args);
});

socket.emit('host_event_1', {name: 'host_event_1', a: 'a', x: 1});

socket.func('summarize', summarize);

socket.func('multiply', multiply);

socket.func('throw1', throw1);

socket.func('throw2', throw2);

socket.call('concat', 'hello', ' ', 'world', '!').then((result: any) => {
console.log('host:return:', result);
});
});
},
[],
);

return (
<iframe src="http://localhost:3001/guest.html" title="guest" onLoad={handleLoad} />
);
};

export default App;
56 changes: 56 additions & 0 deletions examples/create-react-app/src/Guest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import {Guest as IframeGuest} from 'msgio';

const guest = new IframeGuest({host: '//localhost:3456'});

const concat = (...args: any) => (args.join(''));

guest.on('connect', socket => {
console.log('guest:connected');

guest.resize({width: 400, height: 600});

socket.on('host_event_1', (...args: any) => {
console.log('guest:main:host_event_1', ...args);
});

socket.emit('guest_event_1', {name: 'guest_event_1', b: 'b', y: 2});

socket.func('concat', concat);

socket.call('summarize', 1, 2).then((result: any) => {
console.log('guest:return:', result);
});

socket.call('summarize', 3, 4).then((result: any) => {
console.log('guest:return:', result);
});

socket.call('multiply', 5, 6).then((result: any) => {
console.log('guest:return:', result);
});

socket.call('throw1').catch((e: Error) => {
console.log('guest:return:', e);
});

socket.call('throw2')
.then((data: any) => {
console.log(data);
return data;
})
.catch((e: Error) => {
console.log('guest:return:', e);
});

socket.call('foo').catch((e: Error) => {
console.log('guest:return:', e);
});
})

const Guest = () => {
return (
<div>This is the Guest.</div>
);
};

export default Guest;
54 changes: 54 additions & 0 deletions examples/create-react-app/src/Host.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import {useCallback, SyntheticEvent} from 'react';
import {Iframe} from 'msgio';

const summarize = (...args: number[]) => args.reduce((acc: any, cur: any) => (acc + cur), 0);

const multiply = (a: number, b: number) => Promise.resolve(a * b);

const throw1 = () => {
throw new Error('Host throws Error. Error1');
};

const throw2 = () => {
return Promise.reject(new Error('Host throws Error: Error2'));
};

const Host = () => {
const handleLoad = useCallback(
(e: SyntheticEvent<HTMLIFrameElement>) => {
const host = new Iframe(e.target as HTMLIFrameElement);

host.on('connect', socket => {
console.log('host:connected');

socket.on('guest_event_1', (...args: any) => {
console.log('host:main:guest_event_1', ...args);
});

socket.emit('host_event_1', {name: 'host_event_1', a: 'a', x: 1});

socket.func('summarize', summarize);

socket.func('multiply', multiply);

socket.func('throw1', throw1);

socket.func('throw2', throw2);

socket.call('concat', 'hello', ' ', 'world', '!').then((result: any) => {
console.log('host:return:', result);
});
});
},
[],
);

return (
<>
<div>This is the Host.</div>
<iframe src="//localhost:4567/guest" title="guest" onLoad={handleLoad} />
</>
);
};

export default Host;
33 changes: 33 additions & 0 deletions examples/create-react-app/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import {createBrowserRouter, RouterProvider} from "react-router-dom";
import Host from './Host';
import Guest from './Guest';
import reportWebVitals from './reportWebVitals';


const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);

const router = createBrowserRouter([
{
path: "/host",
element: <Host />,
},
{
path: "/guest",
element: <Guest />,
},
]);

root.render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
15 changes: 15 additions & 0 deletions examples/create-react-app/src/reportWebVitals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {ReportHandler} from 'web-vitals';

const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({getCLS, getFID, getFCP, getLCP, getTTFB}) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};

export default reportWebVitals;
26 changes: 26 additions & 0 deletions examples/create-react-app/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
5 changes: 5 additions & 0 deletions examples/umd/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# umd
1. Open two terminal window.
2. Run `npx serve -l 3456` in the first terminal.
3. Run `npx serve -l 4567` in the second terminal.
4. Open `http://localhost:3456/host.html` in the browser and see the console.
Loading

0 comments on commit 36c3b19

Please sign in to comment.