Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React vite webview #106

Open
wants to merge 12 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions package-lock.json

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

8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -193,15 +193,15 @@
"string",
"null"
],
"default": "llama-3.1-70b-versatile",
"default": null,
"markdownDescription": "Enter your [API Key](https://console.groq.com/keys) Groq"
},
"groq.llama3.model": {
"type": [
"string",
"null"
],
"default": null,
"default": "llama-3.1-70b-versatile",
"markdownDescription": "Provide the name of the Groq model you want to use. Choose from the ..."
},
"anthropic.model": {
Expand Down Expand Up @@ -266,6 +266,9 @@
]
},
"scripts": {
"install:all": "npm install && cd webview-ui && npm install",
"dev:webview": "cd webview-ui && npm run dev",
"build:webview": "cd webview-ui && npm run build",
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
Expand All @@ -282,6 +285,7 @@
"@types/readable-stream": "^4.0.11",
"@types/sinon": "^17.0.3",
"@types/vscode": "^1.78.0",
"@types/vscode-webview": "^1.57.5",
"@typescript-eslint/eslint-plugin": "^5.59.8",
"@typescript-eslint/parser": "^5.59.8",
"@vscode/test-cli": "^0.0.8",
Expand Down
49 changes: 38 additions & 11 deletions src/providers/base-web-view-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as vscode from "vscode";
import { getWebviewContent } from "../webview/chat";
import { formatText } from "../utils";
import { FileUploader } from "../events/file-uploader";
import { getChatCss } from "../webview/chat_css";

let _view: vscode.WebviewView | undefined;
export abstract class BaseWebViewProvider {
Expand All @@ -14,7 +15,7 @@ export abstract class BaseWebViewProvider {
private readonly _extensionUri: vscode.Uri,
protected readonly apiKey: string,
protected readonly generativeAiModel: string,
context: vscode.ExtensionContext,
context: vscode.ExtensionContext
) {
this._context = context;
}
Expand All @@ -26,42 +27,68 @@ export abstract class BaseWebViewProvider {

const webviewOptions: vscode.WebviewOptions = {
enableScripts: true,
localResourceRoots: [this._extensionUri],
localResourceRoots: [
this._extensionUri,
vscode.Uri.joinPath(this._extensionUri, "out"),
vscode.Uri.joinPath(this._extensionUri, "webview-ui/build"),
],
};
webviewView.webview.options = webviewOptions;

if (!this.apiKey) {
vscode.window.showErrorMessage(
"API key not configured. Check your settings.",
"API key not configured. Check your settings."
);
return;
}
this.setWebviewHtml(this.currentWebView);
this.setupMessageHandler(
this.apiKey,
this.generativeAiModel,
this.currentWebView,
this.currentWebView
);
}

private async setWebviewHtml(view: vscode.WebviewView): Promise<void> {
const codepatterns: FileUploader = new FileUploader(this._context);
const knowledgeBaseDocs: string[] = await codepatterns.getFiles();
view.webview.html = getWebviewContent(knowledgeBaseDocs);
// const codepatterns: FileUploader = new FileUploader(this._context);
// const knowledgeBaseDocs: string[] = await codepatterns.getFiles();

if (this.currentWebView?.webview == undefined) {
throw Error(
"Error on no webview for currentWebView for base-web-view-provider"
);
}

view.webview.html = getWebviewContent(
this.currentWebView?.webview,
this._extensionUri
);

setInterval(async () => {
let chatCss = await getChatCss();
if (chatCss == false) {
return;
}

this.currentWebView?.webview.postMessage({
type: "updateStyles",
payload: { chatCss: chatCss },
});
}, 3000);
}

private setupMessageHandler(
apiKey: string,
modelName: string,
_view: vscode.WebviewView,
_view: vscode.WebviewView
): void {
try {
_view.webview.onDidReceiveMessage(async (message) => {
if (message.type === "user-input") {
const response = await this.generateResponse(
apiKey,
modelName,
formatText(message.message),
formatText(message.message)
);
if (response) {
this.sendResponse(formatText(response), "bot");
Expand All @@ -76,11 +103,11 @@ export abstract class BaseWebViewProvider {
abstract generateResponse(
apiKey?: string,
name?: string,
message?: string,
message?: string
): Promise<string | undefined>;

abstract sendResponse(
response: string,
currentChat?: string,
currentChat?: string
): Promise<boolean | undefined>;
}
41 changes: 39 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ export const formatText = (text?: string): string => {
};

export const getConfigValue: GetConfigValueType<any> = <T>(
key: string,
key: string
): T | undefined => {
return vscode.workspace.getConfiguration().get<T>(key);
};

export const vscodeErrorMessage = (error: string, metaData?: any) => {
return vscode.window.showErrorMessage(error);
return vscode.window.showErrorMessage(error, metaData);
};

export const getLatestChatHistory = (key: string) => {
Expand All @@ -46,3 +46,40 @@ export const resetChatHistory = (model: string) => {
break;
}
};

/**
* 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: vscode.Webview,
extensionUri: vscode.Uri,
pathList: string[]
) {
return webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, ...pathList));
}

/**
* 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;
}
60 changes: 57 additions & 3 deletions src/webview/chat.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,59 @@
import { chartComponent } from "./chat_html";
import { Webview, Uri } from "vscode";
import { getUri, getNonce } from "../utils";
// import { chartComponent } from "./chat_html";

export function getWebviewContent(docs: string[]): string {
return chartComponent(docs);
// export function getWebviewContent(docs: string[]): string {
// return chartComponent(docs);
// }

export function getWebviewContent(webview: Webview, extensionUri: Uri) {
// The CSS file from the React build output
const stylesUri = getUri(webview, extensionUri, [
"webview-ui",
"build",
"assets",
"index.css",
]);
// The JS file from the React build output
const scriptUri = getUri(webview, extensionUri, [
"webview-ui",
"build",
"assets",
"index.js",
]);

const nonce = getNonce();

// <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}';">

// 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" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Space+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Fira+Code:[email protected]&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:ital,wght@0,200..900;1,200..900&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@0,100..700;1,100..700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Ubuntu+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inconsolata:[email protected]&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" />
<link href="https://fonts.googleapis.com/css2?family=Inconsolata:[email protected]&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<link rel="stylesheet" type="text/css" href="${stylesUri}">
<title>Ai</title>
</head>
<body>
<div id="root"></div>
<script type="module" nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>
`;
}
Loading
Loading