Skip to content

Commit

Permalink
Merge pull request #497 from lukecotter/feat-async-webview-extension-…
Browse files Browse the repository at this point in the history
…communication

chore: async webview extension communication
  • Loading branch information
lcottercertinia authored Mar 26, 2024
2 parents 840dc73 + 867a594 commit db087e1
Show file tree
Hide file tree
Showing 13 changed files with 215 additions and 189 deletions.
53 changes: 31 additions & 22 deletions lana/src/commands/LogView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,10 @@ import { Context } from '../Context.js';
import { OpenFileInPackage } from '../display/OpenFileInPackage.js';
import { WebView } from '../display/WebView.js';

interface WebViewLogFileRequest {
interface WebViewLogFileRequest<T = unknown> {
requestId: string;
cmd: string;
text: string | undefined;
typeName: string | undefined;
path: string | undefined;
options?: Record<string, never>;
payload: T;
}

export class LogView {
Expand Down Expand Up @@ -50,24 +48,27 @@ export class LogView {

panel.webview.onDidReceiveMessage(
async (msg: WebViewLogFileRequest) => {
const request = msg;
const { cmd, requestId, payload } = msg;

switch (request.cmd) {
switch (cmd) {
case 'fetchLog': {
await beforeSendLog;
LogView.sendLog(panel, context, logPath, logData);
LogView.sendLog(requestId, panel, context, logPath, logData);
break;
}

case 'openPath':
if (request.path) {
context.display.showFile(request.path);
case 'openPath': {
const filePath = <string>payload;
if (filePath) {
context.display.showFile(filePath);
}
break;
}

case 'openType': {
if (request.typeName) {
const [className, lineNumber] = request.typeName.split('-');
const { typeName } = <{ typeName: string; text: string }>payload;
if (typeName) {
const [className, lineNumber] = typeName.split('-');
let line;
if (lineNumber) {
line = parseInt(lineNumber);
Expand All @@ -84,22 +85,27 @@ export class LogView {

case 'getConfig': {
panel.webview.postMessage({
command: 'getConfig',
data: workspace.getConfiguration('lana'),
requestId,
cmd: 'getConfig',
payload: workspace.getConfiguration('lana'),
});
break;
}

case 'saveFile': {
if (request.text && request.options?.defaultUri) {
const { fileContent, options } = <
{ fileContent: string; options: { defaultFileName?: string } }
>payload;

if (fileContent && options?.defaultFileName) {
const defaultWorkspace = (workspace.workspaceFolders || [])[0];
const defaultDir = defaultWorkspace?.uri.path || homedir();
const destinationFile = await vscWindow.showSaveDialog({
defaultUri: Uri.file(join(defaultDir, request.options.defaultUri)),
defaultUri: Uri.file(join(defaultDir, options.defaultFileName)),
});

if (destinationFile) {
writeFile(destinationFile.fsPath, request.text).catch((error) => {
writeFile(destinationFile.fsPath, fileContent).catch((error) => {
const msg = error instanceof Error ? error.message : String(error);
vscWindow.showErrorMessage(`Unable to save file: ${msg}`);
});
Expand All @@ -109,8 +115,9 @@ export class LogView {
}

case 'showError': {
if (request.text) {
vscWindow.showErrorMessage(request.text);
const { text } = <{ text: string }>payload;
if (text) {
vscWindow.showErrorMessage(text);
}
break;
}
Expand Down Expand Up @@ -140,6 +147,7 @@ export class LogView {
}

private static sendLog(
requestId: string,
panel: WebviewPanel,
context: Context,
logFilePath?: string,
Expand All @@ -153,8 +161,9 @@ export class LogView {

const filePath = parse(logFilePath || '');
panel.webview.postMessage({
command: 'fetchLog',
data: {
requestId,
cmd: 'fetchLog',
payload: {
logName: filePath.name,
logUri: logFilePath ? panel.webview.asWebviewUri(Uri.file(logFilePath)).toString(true) : '',
logPath: logFilePath,
Expand Down
14 changes: 0 additions & 14 deletions log-viewer/modules/Main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,9 @@
import { html, render } from 'lit';

import './components/LogViewer';
import { hostService } from './services/VSCodeService.js';
import { setColors } from './timeline/Timeline.js';

function handleMessage(evt: MessageEvent) {
const message = evt.data;
switch (message.command) {
case 'getConfig':
setColors(message.data.timeline.colors);
break;
}
}

function onInit(): void {
render(html`<log-viewer></log-viewer>`, document.body);

hostService().getConfig();
}

window.addEventListener('DOMContentLoaded', onInit);
window.addEventListener('message', handleMessage);
18 changes: 15 additions & 3 deletions log-viewer/modules/components/AnalysisView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { progressFormatter } from '../datagrid/format/Progress.js';
import { RowKeyboardNavigation } from '../datagrid/module/RowKeyboardNavigation.js';
import dataGridStyles from '../datagrid/style/DataGrid.scss';
import { ApexLog, TimedNode } from '../parsers/ApexLogParser.js';
import { hostService } from '../services/VSCodeService.js';
import { vscodeMessenger } from '../services/VSCodeExtensionMessenger.js';
import { globalStyles } from '../styles/global.styles.js';
import './skeleton/GridSkeleton.js';

Expand Down Expand Up @@ -152,9 +152,14 @@ async function renderAnalysis(rootMethod: ApexLog) {
columnCalcs: 'both',
clipboard: true,
downloadEncoder: function (fileContents: string, mimeType) {
const vscodeHost = hostService();
const vscodeHost = vscodeMessenger.getVsCodeAPI();
if (vscodeHost) {
vscodeHost.saveFile({ fileContent: fileContents, defaultFilename: 'analysis.csv' });
vscodeMessenger.send<VSCodeSaveFile>('saveFile', {
fileContent: fileContents,
options: {
defaultFileName: 'analysis.csv',
},
});
return false;
}

Expand Down Expand Up @@ -320,3 +325,10 @@ function addNodeToMap(map: Map<string, Metric>, node: TimedNode, key?: string) {
}
});
}

type VSCodeSaveFile = {
fileContent: string;
options: {
defaultFileName: string;
};
};
9 changes: 7 additions & 2 deletions log-viewer/modules/components/AppHeader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { customElement, property, state } from 'lit/decorators.js';

import codiconStyles from '../styles/codicon.css';
import { globalStyles } from '../styles/global.styles.js';
import { ApexLog } from '../timeline/Timeline.js';
import { ApexLog, type TimelineGroup } from '../timeline/Timeline.js';
import '../timeline/TimelineView.js';
import './AnalysisView.js';
import './LogLevels.js';
Expand Down Expand Up @@ -41,6 +41,8 @@ export class AppHeader extends LitElement {
parserIssues: Notification[] = [];
@property()
timelineRoot: ApexLog | null = null;
@property()
timelineKeys: TimelineGroup[] = [];

@state()
_selectedTab = 'timeline-tab';
Expand Down Expand Up @@ -135,7 +137,10 @@ export class AppHeader extends LitElement {
</vscode-panel-tab>
<vscode-panel-view id="view1">
<timeline-view .timelineRoot="${this.timelineRoot}"></timeline-view>
<timeline-view
.timelineRoot="${this.timelineRoot}"
.timelineKeys="${this.timelineKeys}"
></timeline-view>
</vscode-panel-view>
<vscode-panel-view id="view2">
<call-tree-view .timelineRoot="${this.timelineRoot}"></call-tree-view>
Expand Down
4 changes: 2 additions & 2 deletions log-viewer/modules/components/LogTitle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { provideVSCodeDesignSystem, vsCodeButton } from '@vscode/webview-ui-tool
import { LitElement, css, html } from 'lit';
import { customElement, property } from 'lit/decorators.js';

import { hostService } from '../services/VSCodeService.js';
import { vscodeMessenger } from '../services/VSCodeExtensionMessenger.js';
import { globalStyles } from '../styles/global.styles.js';
import { skeletonStyles } from './skeleton/skeleton.styles.js';

Expand Down Expand Up @@ -62,6 +62,6 @@ export class LogTitle extends LitElement {
}

_goToLog() {
hostService().openPath(this.logPath);
vscodeMessenger.send<string>('openPath', this.logPath);
}
}
43 changes: 29 additions & 14 deletions log-viewer/modules/components/LogViewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import { LitElement, css, html } from 'lit';
import { customElement, property } from 'lit/decorators.js';

import { ApexLog, parse } from '../parsers/ApexLogParser.js';
import { hostService } from '../services/VSCodeService.js';
import { vscodeMessenger } from '../services/VSCodeExtensionMessenger.js';
import { globalStyles } from '../styles/global.styles.js';
import type { TimelineGroup } from '../timeline/Timeline.js';
import './AppHeader.js';
import { Notification, type NotificationSeverity } from './notifications/NotificationPanel.js';

import { keyMap, setColors } from '../timeline/Timeline.js';

@customElement('log-viewer')
export class LogViewer extends LitElement {
@property({ type: String })
Expand All @@ -28,6 +31,8 @@ export class LogViewer extends LitElement {
parserIssues: Notification[] = [];
@property()
timelineRoot: ApexLog | null = null;
@property()
timelineKeys: TimelineGroup[] = [];

static styles = [
globalStyles,
Expand All @@ -41,10 +46,14 @@ export class LogViewer extends LitElement {

constructor() {
super();
window.addEventListener('message', (e: MessageEvent) => {
this.handleMessage(e);
vscodeMessenger.request<LogDataEvent>('fetchLog').then((msg) => {
this._handleLogFetch(msg);
});

vscodeMessenger.request<VSCodeLanaConfig>('getConfig').then((msg) => {
setColors(msg.timeline.colors);
this.timelineKeys = Array.from(keyMap.values());
});
hostService().fetchLog();
}

render() {
Expand All @@ -57,19 +66,10 @@ export class LogViewer extends LitElement {
.notifications=${this.notifications}
.parserIssues=${this.parserIssues}
.timelineRoot=${this.timelineRoot}
.timelineKeys=${this.timelineKeys}
></app-header>`;
}

private async handleMessage(evt: MessageEvent) {
const message = evt.data;
switch (message.command) {
case 'fetchLog':
this._handleLogFetch(message.data);

break;
}
}

async _handleLogFetch(data: LogDataEvent) {
this.logName = data.logName?.trim() || '';
this.logPath = data.logPath?.trim() || '';
Expand Down Expand Up @@ -172,3 +172,18 @@ interface LogDataEvent {
logPath?: string;
logData?: string;
}

/* eslint-disable @typescript-eslint/naming-convention */
interface VSCodeLanaConfig {
timeline: {
colors: {
'Code Unit': '#88AE58';
Workflow: '#51A16E';
Method: '#2B8F81';
Flow: '#337986';
DML: '#285663';
SOQL: '#5D4963';
'System Method': '#5C3444';
};
};
}
6 changes: 3 additions & 3 deletions log-viewer/modules/components/NavBar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { provideVSCodeDesignSystem, vsCodeButton, vsCodeTag } from '@vscode/webv
import { LitElement, css, html, unsafeCSS } from 'lit';
import { customElement, property } from 'lit/decorators.js';

import { hostService } from '../services/VSCodeService.js';
import { vscodeMessenger } from '../services/VSCodeExtensionMessenger.js';
import codiconStyles from '../styles/codicon.css';
import { globalStyles } from '../styles/global.styles.js';
import { notificationStyles } from '../styles/notification.styles.js';
Expand Down Expand Up @@ -124,7 +124,7 @@ export class NavBar extends LitElement {
class="icon-button"
title="Help"
@click=${() => {
hostService().openHelp();
vscodeMessenger.send('openHelp');
}}
>
<span class="codicon icon codicon-question"</span>
Expand All @@ -135,7 +135,7 @@ export class NavBar extends LitElement {
}

_goToLog() {
hostService().openPath(this.logPath);
vscodeMessenger.send('openPath', this.logPath);
}

_toDuration(duration: number | null) {
Expand Down
13 changes: 9 additions & 4 deletions log-viewer/modules/components/calltree-view/CalltreeView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { RowKeyboardNavigation } from '../../datagrid/module/RowKeyboardNavigati
import { RowNavigation } from '../../datagrid/module/RowNavigation.js';
import dataGridStyles from '../../datagrid/style/DataGrid.scss';
import { ApexLog, LogLine, TimedNode, type LogEventType } from '../../parsers/ApexLogParser.js';
import { hostService } from '../../services/VSCodeService.js';
import { vscodeMessenger } from '../../services/VSCodeExtensionMessenger.js';
import { globalStyles } from '../../styles/global.styles.js';
import '../skeleton/GridSkeleton.js';

Expand Down Expand Up @@ -366,11 +366,11 @@ export async function renderCallTree(
} else {
typeName = qname + lineNumber;
}
const fileOpenInfo = {

vscodeMessenger.send<VSCodeApexSymbol>('openType', {
typeName: typeName,
text: text,
};
hostService().openType(fileOpenInfo);
});
}
},
widthGrow: 5,
Expand Down Expand Up @@ -830,3 +830,8 @@ const namespaceFilter = (
},
);
};

type VSCodeApexSymbol = {
typeName: string;
text: string;
};
Loading

0 comments on commit db087e1

Please sign in to comment.