Skip to content

Commit 012b319

Browse files
authored
Fix null error and update example (#1)
* Refactor useConnect to typescript * Remove useConnect.js * Fix null error * Pass IPC renderer to `useConnect` to remove dependency on node integration * Export default * Update control example to React 18 * Update title bar style * Bump version
1 parent a63cf53 commit 012b319

File tree

11 files changed

+880
-935
lines changed

11 files changed

+880
-935
lines changed

control.d.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { IpcRenderer } from 'electron';
1+
import type { IpcRenderer } from 'electron';
22

33
// Define the TabID type (assuming it's a string or number)
44
type TabID = string | number;
@@ -19,4 +19,4 @@ interface ControlActions {
1919
// Declare the module
2020
declare const control: ControlActions;
2121

22-
export = control;
22+
export default control;

control.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ const sendNewTab = (url, references) => ipcRenderer.send('new-tab', url, referen
5353
*/
5454
const sendSwitchTab = id => ipcRenderer.send('switch-tab', id);
5555

56-
module.exports = {
56+
export default {
5757
sendEnterURL, // sendEnterURL(url) to load url
5858
sendChangeURL, // sendChangeURL(url) on addressbar input change
5959
sendGoBack,

example/main.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
import { app } from 'electron';
22
import fileUrl from 'file-url';
3-
import BrowserLikeWindow from '../index';
3+
import BrowserLikeWindow from '../index.js';
4+
import { fileURLToPath } from 'url';
5+
6+
const __dirname = fileURLToPath(new URL('.', import.meta.url));
47

58
let browser;
69

710
function createWindow() {
811
browser = new BrowserLikeWindow({
912
controlHeight: 99,
1013
controlPanel: fileUrl(`${__dirname}/renderer/control.html`),
14+
winOptions: {
15+
titleBarStyle: 'hiddenInset'
16+
},
1117
startPage: 'https://google.com',
1218
blankTitle: 'New tab',
1319
debug: true // will open controlPanel's devtools

example/renderer/control.jsx

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import React from 'react';
22
import ReactDOM from 'react-dom';
3+
import { createRoot } from 'react-dom/client';
4+
import { ipcRenderer } from 'electron';
35
import cx from 'classnames';
46
import useConnect from '../../useConnect';
5-
import * as action from '../../control';
7+
import action from '../../control';
68

79
const IconLoading = () => (
810
<svg
@@ -91,7 +93,7 @@ const IconRight = () => (
9193
);
9294

9395
function Control() {
94-
const { tabs, tabIDs, activeID } = useConnect();
96+
const { tabs, tabIDs, activeID } = useConnect({ ipcRenderer });
9597

9698
const { url, canGoForward, canGoBack, isLoading } = tabs[activeID] || {};
9799

@@ -102,7 +104,7 @@ function Control() {
102104
};
103105
const onPressEnter = e => {
104106
if (e.keyCode !== 13) return;
105-
const v = e.target.value.trim();
107+
const v = e.currentTarget.value.trim();
106108
if (!v) return;
107109

108110
let href = v;
@@ -145,7 +147,7 @@ function Control() {
145147
</div>
146148
);
147149
})}
148-
<span type="plus" style={{ marginLeft: 10 }} onClick={newTab}>
150+
<span datatype="plus" style={{ marginLeft: 10 }} onClick={newTab}>
149151
<IconPlus />
150152
</span>
151153
</>
@@ -181,5 +183,6 @@ function Control() {
181183
);
182184
}
183185

184-
// eslint-disable-next-line no-undef
185-
ReactDOM.render(<Control />, document.getElementById('app'));
186+
const container = document.getElementById('app');
187+
const root = createRoot(container);
188+
root.render(<Control />);

index.d.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import type { BrowserWindow, BrowserWindowConstructorOptions, WebPreferences, Rectangle } from 'electron';
22
import type { EventEmitter } from 'events';
33

4-
type TabID = number;
4+
export type TabID = number;
55

6-
interface Tab {
6+
export interface Tab {
77
url: string;
88
href: string;
99
title: string;
@@ -13,7 +13,7 @@ interface Tab {
1313
canGoForward: boolean;
1414
}
1515

16-
interface Tabs {
16+
export interface Tabs {
1717
[key: number]: Tab;
1818
}
1919

@@ -32,7 +32,7 @@ interface BrowserLikeWindowOptions {
3232
debug?: boolean;
3333
}
3434

35-
export default class BrowserLikeWindow extends EventEmitter {
35+
export class BrowserLikeWindow extends EventEmitter {
3636
win: BrowserWindow;
3737

3838
constructor(options: BrowserLikeWindowOptions);
@@ -61,3 +61,5 @@ export default class BrowserLikeWindow extends EventEmitter {
6161
switchTab(viewId: TabID): void;
6262
destroyView(viewId: TabID): void;
6363
}
64+
65+
export default BrowserLikeWindow

index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,7 @@ export default class BrowserLikeWindow extends EventEmitter {
373373

374374
setCurrentView(viewId) {
375375
if (!viewId) return;
376-
this.win.removeBrowserView(this.currentView);
376+
if (this.currentView) this.win.removeBrowserView(this.currentView);
377377
this.win.addBrowserView(this.views[viewId]);
378378
this.currentViewId = viewId;
379379
}

package.json

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "electron-as-browser",
3-
"version": "1.0.1",
3+
"version": "1.0.2",
44
"description": "Make electron like browser easy and flexible.",
55
"keywords": [
66
"electron",
@@ -20,9 +20,10 @@
2020
"*.js",
2121
"*.ts"
2222
],
23+
"type": "module",
2324
"scripts": {
2425
"docs": "documentation build *.js -f html -o docs",
25-
"start:control": "npx babel --watch example/renderer/control.jsx --out-file example/renderer/control-compiled.js",
26+
"start:control": "esbuild --bundle --platform=node --packages=external example/renderer/control.jsx --outfile=example/renderer/control-compiled.js",
2627
"start": "electron example/main.js"
2728
},
2829
"dependencies": {
@@ -33,10 +34,14 @@
3334
"@babel/core": "^7.5.5",
3435
"@babel/preset-env": "^7.5.5",
3536
"@babel/preset-react": "^7.0.0",
36-
"classnames": "^2.2.6",
37-
"electron": "^18.3.7",
37+
"@types/react": "^18.2.69",
38+
"@types/react-dom": "^18.2.22",
39+
"classnames": "^2.5.1",
40+
"electron": "^29.1.6",
41+
"esbuild": "0.20.2",
3842
"file-url": "^2.0.2",
39-
"react": "^16.8.6",
40-
"react-dom": "^16.8.6"
43+
"react": "^18.2.0",
44+
"react-dom": "^18.2.0",
45+
"typescript": "^5.4.3"
4146
}
4247
}

tsconfig.json

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig to read more about this file */
4+
5+
/* Projects */
6+
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8+
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12+
13+
/* Language and Environment */
14+
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16+
"jsx": "react-jsx",
17+
// "jsx": "preserve", /* Specify what JSX code is generated. */
18+
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
19+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
20+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
21+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
22+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
23+
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
24+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
25+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
26+
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
27+
28+
/* Modules */
29+
"module": "commonjs", /* Specify what module code is generated. */
30+
// "rootDir": "./", /* Specify the root folder within your source files. */
31+
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
32+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
33+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
34+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
35+
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
36+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
37+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
38+
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
39+
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
40+
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
41+
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
42+
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
43+
// "resolveJsonModule": true, /* Enable importing .json files. */
44+
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
45+
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
46+
47+
/* JavaScript Support */
48+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
49+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
50+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
51+
52+
/* Emit */
53+
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
54+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
55+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
56+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
57+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
58+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
59+
// "outDir": "./", /* Specify an output folder for all emitted files. */
60+
// "removeComments": true, /* Disable emitting comments. */
61+
// "noEmit": true, /* Disable emitting files from a compilation. */
62+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
63+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
64+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
65+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
66+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
67+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
68+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
69+
// "newLine": "crlf", /* Set the newline character for emitting files. */
70+
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
71+
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
72+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
73+
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
74+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
75+
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
76+
77+
/* Interop Constraints */
78+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
79+
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
80+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
81+
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
82+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
83+
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
84+
85+
/* Type Checking */
86+
"strict": true, /* Enable all strict type-checking options. */
87+
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
88+
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
89+
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
90+
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
91+
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
92+
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
93+
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
94+
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
95+
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
96+
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
97+
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
98+
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
99+
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
100+
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
101+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
102+
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
103+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
104+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
105+
106+
/* Completeness */
107+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
108+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
109+
}
110+
}

useConnect.js

Lines changed: 0 additions & 51 deletions
This file was deleted.

0 commit comments

Comments
 (0)