Skip to content

Commit

Permalink
Working vite Reactjs, use browser to dev for hot reload
Browse files Browse the repository at this point in the history
  • Loading branch information
Fryingpannn committed Oct 12, 2024
1 parent 44cecd3 commit 6ffbd33
Show file tree
Hide file tree
Showing 14 changed files with 584 additions and 5,143 deletions.
5,053 changes: 0 additions & 5,053 deletions extensions/pearai-inventory/package-lock.json

This file was deleted.

8 changes: 4 additions & 4 deletions extensions/pearai-inventory/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"Other"
],
"activationEvents": [],
"main": "./dist/extension.js",
"main": "./out/extension.js",
"contributes": {
"commands": [
{
Expand All @@ -20,9 +20,9 @@
]
},
"scripts": {
"install:all": "npm install && cd webview-ui && npm install",
"start:webview": "cd webview-ui && npm run start",
"build:webview": "cd webview-ui && npm run build",
"install:all": "yarn install && cd webview-ui && yarn install",
"start:webview": "cd webview-ui && yarn run start",
"build:webview": "cd webview-ui && yarn run build",
"vscode:prepublish": "yarn run package",
"compile": "yarn run check-types && yarn run lint && node esbuild.js",
"watch": "tsc -watch -p ./",
Expand Down
1 change: 1 addition & 0 deletions extensions/pearai-inventory/src/PearInventoryPanel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
//
8 changes: 4 additions & 4 deletions extensions/pearai-inventory/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ export class PearInventoryExtension {
// vscode.window.registerWebviewViewProvider("pearai.overlayWebview", this.pearInventoryPanel)
// );

outputChannel.appendLine("Pear Inventory extension activated");
console.log("Pear Inventory extension activated");
outputChannel.appendLine("Pear Inventory extension activated!!");
console.log("Pear Inventory extension activated!!!");
}

async deactivate(): Promise<void> {
Expand All @@ -35,9 +35,9 @@ let outputChannel: vscode.OutputChannel;
let extension: PearInventoryExtension;

export function activate(context: vscode.ExtensionContext) {
console.log("Activating Pear extension");
console.log("Activating Pear extension!!!!!");
outputChannel = vscode.window.createOutputChannel("Pear");
outputChannel.appendLine("Activating Pear extension");
outputChannel.appendLine("Activating Pear extension!!");

// extension = new PearInventoryExtension(context, outputChannel);
// extension.activate();
Expand Down
156 changes: 156 additions & 0 deletions extensions/pearai-inventory/src/panels/PearInventoryPanel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { Disposable, Webview, WebviewPanel, window, Uri, ViewColumn, ExtensionContext } from "vscode";
import { getUri } from "../utilities/getUri";
import { getNonce } from "../utilities/getNonce";

/**
* This class manages the state and behavior of PearInventory webview panels.
*
* It contains all the data and methods for:
*
* - Creating and rendering HelloWorld webview panels
* - Properly cleaning up and disposing of webview resources when the panel is closed
* - Setting the HTML (and by proxy CSS/JavaScript) content of the webview panel
* - Setting message listeners so data can be passed between the webview and extension
*/
export class PearInventoryPanel {
public static currentPanel: PearInventoryPanel | undefined;
private readonly _panel: WebviewPanel;
private _disposables: Disposable[] = [];

/**
* The PearInventoryPanel class private constructor (called only from the render method).
*
* @param panel A reference to the webview panel
* @param extensionUri The URI of the directory containing the extension
*/
public constructor(panel: WebviewPanel, extensionUri: Uri) {
this._panel = panel;

// Set an event listener to listen for when the panel is disposed (i.e. when the user closes
// the panel or when the panel is closed programmatically)
this._panel.onDidDispose(() => this.dispose(), null, this._disposables);

// Set the HTML content for the webview panel
this._panel.webview.html = this._getWebviewContent(this._panel.webview, extensionUri);

// Set an event listener to listen for messages passed from the webview context
this._setWebviewMessageListener(this._panel.webview);
}

/**
* Renders the current webview panel if it exists otherwise a new webview panel
* will be created and displayed.
*
* @param extensionUri The URI of the directory containing the extension.
*/
public static render(extensionUri: Uri) {
if (PearInventoryPanel.currentPanel) {
// If the webview panel already exists reveal it
PearInventoryPanel.currentPanel._panel.reveal(ViewColumn.One);
} else {
// If a webview panel does not already exist create and show a new one
const panel = window.createWebviewPanel(
// Panel view type
"showHelloWorld",
// Panel title
"Hello World",
// The editor column the panel should be displayed in
ViewColumn.One,
// Extra panel configurations
{
// Enable JavaScript in the webview
enableScripts: true,
// Restrict the webview to only load resources from the `out` and `webview-ui/build` directories
localResourceRoots: [Uri.joinPath(extensionUri, "out"), Uri.joinPath(extensionUri, "webview-ui/build")],
}
);

PearInventoryPanel.currentPanel = new PearInventoryPanel(panel, extensionUri);
}
}

/**
* Cleans up and disposes of webview resources when the webview panel is closed.
*/
public dispose() {
PearInventoryPanel.currentPanel = undefined;

// Dispose of the current webview panel
this._panel.dispose();

// Dispose of all disposables (i.e. commands) for the current webview panel
while (this._disposables.length) {
const disposable = this._disposables.pop();
if (disposable) {
disposable.dispose();
}
}
}

/**
* Defines and returns the HTML that should be rendered within the webview panel.
*
* @remarks This is also the place where references to the React webview build files
* are created and inserted into the webview HTML.
*
* @param webview A reference to the extension webview
* @param extensionUri The URI of the directory containing the extension
* @returns A template string literal containing the HTML that should be
* rendered within the webview panel
*/
private _getWebviewContent(webview: Webview, extensionUri: Uri) {
// The CSS file from the React build output
const stylesUri = getUri(webview, extensionUri, ["webview-ui", "build", "assets", "index.css"]);
console.log("I am here");
// The JS file from the React build output
const scriptUri = getUri(webview, extensionUri, ["webview-ui", "build", "assets", "index.js"]);

const nonce = getNonce();

// Tip: Install the es6-string-html VS Code extension to enable code highlighting below
return /*html*/ `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
<link rel="stylesheet" type="text/css" href="${stylesUri}">
<title>Hello World</title>
</head>
<body>
<div id="root"></div>
<script type="module" nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>
`;
}

/**
* Sets up an event listener to listen for messages passed from the webview context and
* executes code based on the message that is recieved.
*
* @param webview A reference to the extension webview
* @param context A reference to the extension context
*/
private _setWebviewMessageListener(webview: Webview) {
webview.onDidReceiveMessage(
(message: any) => {
const command = message.command;
const text = message.text;

switch (command) {
case "hello":
// Code that should run in response to the hello message command
console.log("message here!");
window.showInformationMessage(text);
return;
// Add more switch case statements here as more webview message commands
// are created within the webview context (i.e. inside media/main.js)
}
},
undefined,
this._disposables
);
}
}
13 changes: 13 additions & 0 deletions extensions/pearai-inventory/src/panels/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# `panels` Directory

This directory contains all of the webview-related code that will be executed within the extension context. It can be thought of as the place where all of the "backend" code of a webview panel is contained.

Types of content that can be contained here:

Individual JavaScript / TypeScript files that contain a class which manages the state and behavior of a given webview panel. Each class is usually in charge of:

- Creating and rendering the webview panel
- Properly cleaning up and disposing of webview resources when the panel is closed
- Setting message listeners so data can be passed between the webview and extension
- Setting the HTML (and by proxy CSS/JavaScript) content of the webview panel
- Other custom logic and behavior related to webview panel management
16 changes: 16 additions & 0 deletions extensions/pearai-inventory/src/utilities/getNonce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* A helper function that returns a unique alphanumeric identifier called a nonce.
*
* @remarks This function is primarily used to help enforce content security
* policies for resources/scripts being executed in a webview context.
*
* @returns A nonce
*/
export function getNonce() {
let text = "";
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
16 changes: 16 additions & 0 deletions extensions/pearai-inventory/src/utilities/getUri.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Uri, Webview } from "vscode";

/**
* A helper function which will get the webview URI of a given file or resource.
*
* @remarks This URI can be used within a webview's HTML as a link to the
* given file/resource.
*
* @param webview A reference to the extension webview
* @param extensionUri The URI of the directory containing the extension
* @param pathList An array of strings representing the path to a file/resource
* @returns A URI pointing to the file/resource
*/
export function getUri(webview: Webview, extensionUri: Uri, pathList: string[]) {
return webview.asWebviewUri(Uri.joinPath(extensionUri, ...pathList));
}
4 changes: 2 additions & 2 deletions extensions/pearai-inventory/webview-ui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ function App() {
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
FK THIS count {count}
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMRsds
Edit <code>src/App.tsx</code>
</p>
</div>
<p className="read-the-docs">
Expand Down
1 change: 1 addition & 0 deletions extensions/pearai-inventory/webview-ui/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
7 changes: 7 additions & 0 deletions extensions/pearai-inventory/webview-ui/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
20 changes: 20 additions & 0 deletions extensions/pearai-inventory/webview-ui/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
hmr: true,
},
build: {
outDir: "build",
rollupOptions: {
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`,
},
},
},
});
Loading

0 comments on commit 6ffbd33

Please sign in to comment.