Skip to content

Commit

Permalink
fix: Try to load webview locally
Browse files Browse the repository at this point in the history
  • Loading branch information
Estrada Irribarra, Rodrigo Andres committed Oct 21, 2024
1 parent c84539d commit b248d94
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 155 deletions.
4 changes: 3 additions & 1 deletion .vscode/launch.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
"version": "0.2.0",
"configurations": [
{
"name": "Run Extension",
"name": "Run StoryCraftr Extension",
"program": "${workspaceFolder}/vscode/extension.js",
"type": "extensionHost",
"sourceMaps": true,
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
Expand Down
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
},
"dependencies": {
"@types/vscode": "^1.75.0",
"@types/vscode-webview": "^1.57.5",
"path": "^0.12.7",
"react": "^18.2.0",
"react-dom": "^18.2.0"
Expand Down
17 changes: 9 additions & 8 deletions vscode/extension.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import * as vscode from "vscode";
import PanelClass from "./panel";
import * as vscode from 'vscode';
import { createPanel } from './panel'; // Importing the panel function

export function activate(extContext: vscode.ExtensionContext) {
extContext.subscriptions.push(
vscode.commands.registerCommand("extensionnamegoeshere.start", () => {
PanelClass.createOrShow(extContext);
}),
);
export function activate(context: vscode.ExtensionContext) {
// Register the command that triggers the webview panel
const disposable = vscode.commands.registerCommand('storycraftr.openPanel', () => {
createPanel(context); // Call the createPanel function
});

context.subscriptions.push(disposable);
}

export function deactivate() {}
158 changes: 47 additions & 111 deletions vscode/panel.ts
Original file line number Diff line number Diff line change
@@ -1,120 +1,56 @@
import * as vscode from "vscode";
import { getNonce } from "./getNonce";

export default class PanelClass {
public static currentPanel: PanelClass | undefined;

private static readonly viewType = "PanelNameGoesHere";

private readonly _panel: vscode.WebviewPanel;
private readonly _extensionUri: vscode.Uri;
private readonly _extContext: vscode.ExtensionContext;
private _disposables: vscode.Disposable[] = [];

public static createOrShow(extContext: vscode.ExtensionContext) {
const column = vscode.window.activeTextEditor
? vscode.window.activeTextEditor.viewColumn
: undefined;

// If we already have a panel, show it.
// Otherwise, create a new panel.
if (PanelClass.currentPanel) {
PanelClass.currentPanel._panel.reveal(column);
} else {
// ReactPanel.currentPanel = new ReactPanel(extensionPath, column || vscode.ViewColumn.One);
PanelClass.currentPanel = new PanelClass(
extContext,
vscode.ViewColumn.Two,
);
}
}
//temporarily setting extcontext to any type
private constructor(
_extContext: vscode.ExtensionContext,
column: vscode.ViewColumn,
) {
this._extContext = _extContext;
this._extensionUri = _extContext.extensionUri;

// Create and show a new webview panel
this._panel = vscode.window.createWebviewPanel(
PanelClass.viewType,
"ReacTree",
column,
{
// Enable javascript in the webview
enableScripts: true,
localResourceRoots: [this._extensionUri],
},
);

// Set the webview's initial html content
this._panel.webview.html = this._getHtmlForWebview(this._panel.webview);

// Listen for when the panel is disposed
// This happens when the user closes the panel or when the panel is closed programatically
this._panel.onDidDispose(() => this.dispose(), null, this._disposables);

//Listen to messages
this._panel.webview.onDidReceiveMessage(
async (msg: any) => {
switch (msg.command) {
case "startup":
console.log("message received");
break;
case "testing":
console.log("reachedBrain");
this._panel!.webview.postMessage({ command: "refactor" });
break;
import * as vscode from 'vscode';
import { getNonce } from './getNonce';

// This method is called to create the webview panel
export function createPanel(context: vscode.ExtensionContext) {
const panel = vscode.window.createWebviewPanel(
'storycraftrPanel', // Identifies the type of the webview
'StoryCraftr Control Panel', // Title of the panel
vscode.ViewColumn.One, // Editor column to show the new webview panel in.
{
// Enable scripts in the webview
enableScripts: true,
localResourceRoots: [
vscode.Uri.file(context.extensionPath)
]
}
},
null,
this._disposables,
);
}

public dispose() {
PanelClass.currentPanel = undefined;
this._panel.dispose();
while (this._disposables.length) {
const x = this._disposables.pop();
if (x) {
x.dispose();
}
}
}

private _getHtmlForWebview(webview: vscode.Webview) {
const scriptUri = webview.asWebviewUri(
vscode.Uri.joinPath(this._extensionUri, "out", "main.wv.js"),
// Set the HTML content for the webview
panel.webview.html = getWebviewContent(panel.webview, context);

// Set up the message listener for communication between webview and extension
panel.webview.onDidReceiveMessage(
message => {
switch (message.command) {
case 'runCommand':
vscode.window.showInformationMessage(`Running command: ${message.text}`);
break;
}
},
undefined,
context.subscriptions
);
}

const styleUri = webview.asWebviewUri(
vscode.Uri.joinPath(this._extensionUri, "media", "styles.css"),
// Function to define the HTML and load the React app from the webview folder
function getWebviewContent(webview: vscode.Webview, context: vscode.ExtensionContext): string {
const scriptUri = webview.asWebviewUri(
vscode.Uri.joinPath(context.extensionUri, 'webview', 'dist', 'bundle.js')
);

const nonce = getNonce();

return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Panel Title Goes Here</title>
<link rel="stylesheet" href="${styleUri}">
</head>
<body>
<div id="root"></div>
<script>
const vscode = acquireVsCodeApi();
window.onload = function() {
vscode.postMessage({ command: 'startup' });
console.log('HTML started up.');
};
</script>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>
`;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>StoryCraftr Panel</title>
<script nonce="${nonce}" src="${scriptUri}"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>`;
}
57 changes: 28 additions & 29 deletions vscode/webview/components/App.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
import * as React from "react";
import * as vscode from 'vscode';
import * as React from 'react';
import { useState, useEffect } from 'react';

interface vscode {
postMessage(message: any): void;
}
declare const vscode: vscode;

const sendMessage = () => {
console.log("button clicked");
vscode.postMessage({ command: "testing" });
};
function App() {
const [output, setOutput] = useState<string>('');

const App = () => {
const [buttonText, setButtonText] = React.useState("The brain is pending");
const sendCommand = (command: string) => {
const vscode = acquireVsCodeApi();
vscode.postMessage({ command: 'runCommand', text: command });
};

React.useEffect(() => {
window.addEventListener("message", (event) => {
const message = event.data; // The json data that the extension sent
switch (message.command) {
case "refactor":
setButtonText("The brain is working");
break;
}
});
});
useEffect(() => {
window.addEventListener('message', event => {
const { result } = event.data;
setOutput(prev => prev + result + '\n');
});
}, []);

return (
<div>
<h1>Functional Components Work!</h1>
<button onClick={sendMessage}>{buttonText}</button>
</div>
);
};
return (
<div>
<h1>StoryCraftr Control Panel</h1>
<button onClick={() => sendCommand('outline general-outline "Summarize the plot"')}>
Generate General Outline
</button>
<button onClick={() => sendCommand('chapters chapter 1 "Write chapter 1 based on synopsis"')}>
Generate Chapter 1
</button>
<pre>{output}</pre>
</div>
);
}

export default App;
11 changes: 5 additions & 6 deletions vscode/webview/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const React = require("react");
const ReactDOM = require("react-dom");
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './components/App'; // Import the App component

// Component import
import App from "./components/App";

ReactDOM.render(<App />, document.getElementById("root") as HTMLElement);
// Render the App component inside the root div of the webview HTML
ReactDOM.render(<App />, document.getElementById('root'));

0 comments on commit b248d94

Please sign in to comment.