Skip to content

Commit f7e5660

Browse files
committed
feat: bundle code as string
0 parents  commit f7e5660

23 files changed

+9111
-0
lines changed

.editorconfig

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
root = true
2+
3+
[*]
4+
indent_style = space
5+
end_of_line = lf
6+
charset = utf-8
7+
trim_trailing_whitespace = true
8+
insert_final_newline = true
9+
10+
[*.scss]
11+
indent_size = 2
12+
13+
[*.js]
14+
indent_size = 2
15+
16+
[*.jsx]
17+
indent_size = 2
18+
19+
[*.ts]
20+
indent_size = 2
21+
22+
[*.tsx]
23+
indent_size = 2
24+
25+
[*.vue]
26+
indent_size = 2
27+
28+
[Makefile]
29+
indent_style = tab

.env

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
SKIP_PREFLIGHT_CHECK=true

.eslintignore

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
resources/
2+
settings-dev/
3+
out/
4+
logs/
5+
template/
6+
.webpack/
7+
node_modules/
8+
localization/
9+
build-resources/
10+
.vscode/
11+
.github/

.eslintrc.cjs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// eslint-disable-next-line @typescript-eslint/no-var-requires
2+
const tsEslintConfig = require('./tsconfig.eslint.json');
3+
4+
module.exports = {
5+
root: true,
6+
ignorePatterns: tsEslintConfig.exclude,
7+
parser: '@typescript-eslint/parser',
8+
parserOptions: {
9+
project: './tsconfig.eslint.json',
10+
tsconfigRootDir: __dirname,
11+
sourceType: 'module',
12+
ecmaFeatures: {
13+
jsx: true,
14+
},
15+
},
16+
settings: {
17+
react: {
18+
version: '17.0.2',
19+
},
20+
'import/resolver': {
21+
node: {
22+
extensions: ['.js', '.jsx', '.ts', '.tsx'],
23+
},
24+
typescript: {
25+
alwaysTryTypes: true,
26+
},
27+
alias: {
28+
map: [
29+
['@', './src'],
30+
['@services', './src/services'],
31+
],
32+
extensions: ['.js', '.jsx', '.ts', '.tsx'],
33+
},
34+
},
35+
},
36+
rules: {},
37+
extends: [
38+
'eslint-config-tidgi',
39+
],
40+
plugins: [],
41+
env: {
42+
browser: true,
43+
es6: true,
44+
},
45+
};

.gitattributes

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* text=auto

.gitignore

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Logs
2+
logs
3+
*.log
4+
npm-debug.log*
5+
6+
# Runtime data
7+
pids
8+
*.pid
9+
*.seed
10+
11+
# Directory for instrumented libs generated by jscoverage/JSCover
12+
lib-cov
13+
14+
# Coverage directory used by tools like istanbul
15+
coverage
16+
17+
# nyc test coverage
18+
.nyc_output
19+
20+
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
21+
.grunt
22+
23+
# node-waf configuration
24+
.lock-wscript
25+
26+
# Compiled binary addons (http://nodejs.org/api/addons.html)
27+
build/Release
28+
29+
# Dependency directories
30+
node_modules
31+
jspm_packages
32+
33+
# Optional npm cache directory
34+
.npm
35+
36+
# Optional REPL history
37+
.node_repl_history
38+
39+
# Compiled code
40+
www
41+
42+
# Electron builds
43+
*-darwin-x64
44+
dist
45+
46+
.DS_Store
47+
.eslintcache
48+
49+
_src
50+
51+
/build
52+
/template/build
53+
54+
snapcraft_login
55+
template/wiki/tiddlers/$__StoryList.tid
56+
template/wiki/public-dist/
57+
template/wiki/output/
58+
template/wiki/settings/settings.json
59+
60+
# web build
61+
.webpack
62+
out/
63+
64+
# testing and dev temp folders
65+
settings-dev/
66+
.dccache

.vscode/settings.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"cSpell.words": [
3+
"inversifyjs"
4+
]
5+
}

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2017 LinOnetwo
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
# react-native-postmessage-cat
2+
3+
> Based on [linonetwo/electron-ipc-cat](https://github.com/linonetwo/electron-ipc-cat), and used in [TidGi-Mobile](https://github.com/tiddly-gittly/TidGi-Mobile]).
4+
5+
<p align="center" style="color: #343a40">
6+
<img src="docs/image/title-image.png" alt="electron-ipc-cat logo">
7+
<h1 align="center">react-native-postmessage-cat</h1>
8+
</p>
9+
<p align="center" style="font-size: 1.2rem;">Passing object and type between React Native main process and WebView process simply via proxy.</p>
10+
11+
## Overview
12+
13+
In latest react-native-webview, the `injectedJavaScriptBeforeContentLoaded` accepts stringified code, and you are required to passing data using postMessage. It requires tons of boilerplate code to build up this message bridge, just like the vanilla Redux.
14+
15+
Luckily we have frankwallis/electron-ipc-proxy which provide a good example about how to automatically build IPC channel for a class in the main process. But it doesn't work in react native, so here we have `react-native-postmessage-cat`!
16+
17+
We wrap our react native side class, and can use them from the `window.xxx` in the webview. All types are preserved, so you can get typescript intellisense just like using a local function.
18+
19+
## Install
20+
21+
```sh
22+
pnpm i react-native-postmessage-cat
23+
```
24+
25+
## Example
26+
27+
Real use case in [TidGi-Mobile's sync-adaptor](https://github.com/tiddly-gittly/TidGi-Mobile)
28+
29+
### 1. The class
30+
31+
```ts
32+
/** workspaces.ts */
33+
export class Workspace implements IWorkspaceService {
34+
/**
35+
* Record from workspace id to workspace settings
36+
*/
37+
private workspaces: Record<string, IWorkspace> = {};
38+
public workspaces$: BehaviorSubject<Record<string, IWorkspace>>;
39+
40+
public async getWorkspacesAsList(): Promise<IWorkspace[]> {
41+
return Object.values(this.workspaces).sort((a, b) => a.order - b.order);
42+
}
43+
44+
public async get(id: string): Promise<IWorkspace | undefined> {
45+
return this.workspaces[id];
46+
}
47+
48+
public get$(id: string): Observable<IWorkspace | undefined> {
49+
return this.workspaces$.pipe(map((workspaces) => workspaces[id]));
50+
}
51+
}
52+
53+
export interface IWorkspaceService {
54+
workspaces$: BehaviorSubject<Record<string, IWorkspace>>;
55+
getWorkspacesAsList(): Promise<IWorkspace[]>;
56+
get(id: string): Promise<IWorkspace | undefined>;
57+
get$(id: string): Observable<IWorkspace | undefined>;
58+
}
59+
60+
export const WorkspaceServiceIPCDescriptor = {
61+
channel: WorkspaceChannel.name,
62+
properties: {
63+
workspaces$: ProxyPropertyType.Value$,
64+
getWorkspacesAsList: ProxyPropertyType.Function,
65+
get: ProxyPropertyType.Function,
66+
get$: ProxyPropertyType.Function$,
67+
},
68+
};
69+
```
70+
71+
### 2. bindServiceAndProxy in React Native side & bridge proxy in preload script
72+
73+
```tsx
74+
/**
75+
* Provide API from main services to WebView
76+
* This file should be required by BrowserView's preload script to work
77+
*/
78+
import { useMemo } from 'react';
79+
import webviewPreloadedJS from 'react-native-postmessage-cat/webview-string';
80+
import { useRegisterProxy } from 'react-native-postmessage-cat/react-native';
81+
82+
import { WorkspaceServiceIPCDescriptor } from '@services/workspaces/interface';
83+
84+
const workspaceService = new WorkspaceService();
85+
86+
export const WikiViewer = () => {
87+
const [webViewReference] = useRegisterProxy(workspaceService, WorkspaceServiceIPCDescriptor)
88+
const preloadScript = useMemo(() =>`
89+
${webviewPreloadedJS}
90+
true; // note: this is required, or you'll sometimes get silent failures
91+
`, []);
92+
return (
93+
<WebViewContainer>
94+
<WebView
95+
source={{ html: wikiHTMLString }}
96+
onMessage={onMessage}
97+
ref={webViewReference}
98+
injectedJavaScriptBeforeContentLoaded={runFirst}
99+
/>
100+
</WebViewContainer>
101+
);
102+
};
103+
```
104+
105+
### 4. receive in JS that runs inside WebView
106+
107+
```ts
108+
/** renderer.tsx */
109+
import 'react-native-postmessage-cat/fixContextIsolation';
110+
111+
112+
import { IWorkspace } from '@services/workspaces';
113+
import { WorkspaceServiceIPCDescriptor } from '@services/workspaces/interface';
114+
115+
// `window.PostMessageCat`'s type is same as `createProxy` in `'react-native-postmessage-cat/webview'`
116+
const workspaceService = window.PostMessageCat<IWorkspace>(WorkspaceServiceIPCDescriptor)
117+
118+
export function useWorkspacesListObservable(): IWorkspace[] | undefined {
119+
const [workspaces, workspacesSetter] = useState<IWorkspace[] | undefined>();
120+
// beware not pipe directly in the react hock, as it will re-pipe every time React reRenders, and every time regarded as new Observable, so it will re-subscribe
121+
// useMemo will solve this
122+
const workspacesList$ = useMemo(
123+
() => workspaceService.workspaces$.pipe(map<Record<string, IWorkspace>, IWorkspace[]>((workspaces) => Object.values(workspaces))),
124+
[],
125+
);
126+
useObservable<IWorkspace[] | undefined>(workspacesList$, workspacesSetter);
127+
return workspaces;
128+
}
129+
130+
export function useWorkspaceObservable(id: string): IWorkspace | undefined {
131+
const [workspace, workspaceSetter] = useState<IWorkspace | undefined>();
132+
const workspace$ = useMemo(() => workspaceService.get$(id), [id]);
133+
useObservable<IWorkspace | undefined>(workspace$, workspaceSetter);
134+
return workspace;
135+
}
136+
```
137+
138+
## Notes
139+
140+
All `Values` and `Functions` will return promises on the renderer side, no matter how they have been defined on the source object. This is because communication happens asynchronously. For this reason it is recommended that you make them promises on the source object as well, so the interface is the same on both sides.
141+
142+
Use `Value$` and `Function$` when you want to expose or return an Observable stream across IPC.
143+
144+
Only plain objects can be passed between the 2 sides of the proxy, as the data is serialized to JSON, so no functions or prototypes will make it across to the other side.
145+
146+
Notice the second parameter of `createProxy` - `Observable` this is done so that the library itself does not need to take on a dependency to rxjs. You need to pass in the Observable constructor yourself if you want to consume Observable streams.
147+
148+
The channel specified must be unique and match on both sides of the proxy.
149+
150+
The packages exposes 2 entry points in the "main" and "browser" fields of package.json. "main" is for the main thread and "browser" is for the renderer thread.
151+
152+
## See it working
153+
154+
[Example in TiddlyGit](https://github.com/tiddly-gittly/TiddlyGit-Desktop/blob/0c6b26c0c1113e0c66d6f49f022c5733d4fa85e8/src/preload/common/services.ts#L27-L42)
155+
156+
## FAQ
157+
158+
### reject string
159+
160+
You should reject an Error, other wise `serialize-error` can't handle it well.
161+
162+
```diff
163+
- reject(errorMessage);
164+
+ reject(new Error(errorMessage));
165+
```
166+
167+
## Change Log

docs/image/title-image.png

198 KB
Loading

0 commit comments

Comments
 (0)