Skip to content

Commit ecb2252

Browse files
hedietCopilot
andcommitted
Refactor webview services for explicit instance ownership
Inject hosts into pull request contexts, remove context singletons, and add instance-local timestamp and viewport inputs with regression coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 9f9e6e5 commit ecb2252

20 files changed

Lines changed: 892 additions & 246 deletions

File tree

‎src/test/webviews/testHost.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*---------------------------------------------------------------------------------------------
2+
* Copyright (c) Microsoft Corporation. All rights reserved.
3+
* Licensed under the MIT License. See License.txt in the project root for license information.
4+
*--------------------------------------------------------------------------------------------*/
5+
6+
import { afterEach } from 'mocha';
7+
import { createWebviewHost, WebviewHost, WebviewTransport } from '../../../webviews/common/host';
8+
9+
const hosts = new Set<WebviewHost>();
10+
11+
export function createTestHost(state?: unknown, transport?: WebviewTransport): WebviewHost {
12+
const host = createWebviewHost(transport);
13+
if (state !== undefined) {
14+
host.setState(state);
15+
}
16+
hosts.add(host);
17+
return host;
18+
}
19+
20+
afterEach(() => {
21+
for (const host of hosts) {
22+
host.dispose();
23+
}
24+
hosts.clear();
25+
});

‎webviews/activityBarView/app.tsx‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,19 @@ import React, { useContext, useEffect, useState } from 'react';
77
import { render } from 'react-dom';
88
import { Overview } from './overview';
99
import { PullRequest } from '../../src/github/views';
10-
import PullRequestContext from '../common/context';
10+
import PullRequestContext, { PRContext } from '../common/context';
11+
import { createWebviewHost } from '../common/host';
12+
import { rethrowUnlessDisposed } from '../common/message';
1113

1214
export function main() {
13-
render(<Root>{pr => <Overview {...pr} />}</Root>, document.getElementById('app'));
15+
const host = createWebviewHost();
16+
const context = new PRContext(host);
17+
render(
18+
<PullRequestContext.Provider value={context}>
19+
<Root>{pr => <Overview {...pr} />}</Root>
20+
</PullRequestContext.Provider>,
21+
document.getElementById('app')
22+
);
1423
}
1524

1625
export function Root({ children }) {
@@ -19,8 +28,11 @@ export function Root({ children }) {
1928
useEffect(() => {
2029
ctx.onchange = setPR;
2130
setPR(ctx.pr);
31+
return () => {
32+
ctx.onchange = null;
33+
};
2234
}, []);
23-
ctx.postMessage({ command: 'ready' });
24-
ctx.postMessage({ command: 'pr.debug', args: 'initialized ' + (pr ? 'with PR' : 'without PR') });
35+
ctx.postMessage({ command: 'ready' }).catch(rethrowUnlessDisposed);
36+
ctx.postMessage({ command: 'pr.debug', args: 'initialized ' + (pr ? 'with PR' : 'without PR') }).catch(rethrowUnlessDisposed);
2537
return pr ? children(pr) : <div className="loading-indicator">Loading...</div>;
2638
}

‎webviews/common/cache.ts‎

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

‎webviews/common/context.tsx‎

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@
44
*--------------------------------------------------------------------------------------------*/
55

66
import { createContext } from 'react';
7-
import { getState, setState, updateState } from './cache';
87
import { COMMENT_TEXTAREA_ID } from './constants';
9-
import { getMessageHandler, MessageHandler } from './message';
8+
import { WebviewHost } from './host';
109
import { CloseResult, DescriptionResult, OpenCommitChangesArgs, OpenLocalFileArgs } from '../../common/views';
1110
import { IComment } from '../../src/common/comment';
1211
import { EventType, ReviewEvent, SessionLinkInfo, TimelineEvent } from '../../src/common/timelineEvent';
@@ -32,17 +31,21 @@ function bytesToBase64(bytes: Uint8Array): string {
3231
const MAX_UPLOAD_SIZE_BYTES = 25 * 1024 * 1024;
3332

3433
export class PRContext {
34+
public pr: PullRequest | undefined;
35+
public onchange: ((ctx: PullRequest | undefined) => void) | null = null;
3536
public preview: PullRequestPreview | undefined;
3637
public onPreviewChange: ((preview: PullRequestPreview | undefined) => void) | null = null;
38+
private readonly _unsubscribe: () => void;
3739

38-
constructor(
39-
public pr: PullRequest | undefined = getState(),
40-
public onchange: ((ctx: PullRequest | undefined) => void) | null = null,
41-
private _handler: MessageHandler | null = null,
42-
) {
43-
if (!_handler) {
44-
this._handler = getMessageHandler(this.handleMessage);
45-
}
40+
constructor(private readonly _host: WebviewHost) {
41+
this.pr = _host.getState<PullRequest>();
42+
this._unsubscribe = _host.onCommand(this.handleMessage);
43+
}
44+
45+
public dispose(): void {
46+
this._unsubscribe();
47+
this.onchange = null;
48+
this.onPreviewChange = null;
4649
}
4750

4851
public setTitle = async (title: string) => {
@@ -193,7 +196,7 @@ export class PRContext {
193196
this.postMessage({ command: 'pr.cancel-generate-description' });
194197

195198
public updateDraft = (id: number, body: string) => {
196-
const pullRequest = getState();
199+
const pullRequest = this._host.getState<PullRequest>() ?? this.pr;
197200
const pendingCommentDrafts = pullRequest.pendingCommentDrafts || Object.create(null);
198201
if (body === pendingCommentDrafts[id]) {
199202
return;
@@ -549,24 +552,32 @@ export class PRContext {
549552
this.preview = undefined;
550553
this.onPreviewChange?.(undefined);
551554
this.pr = pr;
552-
setState(this.pr);
555+
const oldPullRequest = this._host.getState<PullRequest>();
556+
if (oldPullRequest?.number && oldPullRequest.number === pr?.number) {
557+
pr.pendingCommentText = oldPullRequest.pendingCommentText;
558+
pr.pendingReviewSummaryText = oldPullRequest.pendingReviewSummaryText;
559+
}
560+
if (pr) {
561+
this._host.setState(pr);
562+
}
553563
if (this.onchange) {
554564
this.onchange(this.pr);
555565
}
556566
return this;
557567
};
558568

559569
updatePR = (pr: Partial<PullRequest> | undefined) => {
560-
updateState(pr);
570+
const current = this._host.getState<PullRequest>() ?? this.pr;
571+
this._host.setState(Object.assign(current ?? {}, pr));
561572
this.pr = this.pr ? { ...this.pr, ...pr } : pr as PullRequest;
562573
if (this.onchange) {
563574
this.onchange(this.pr);
564575
}
565576
return this;
566577
};
567578

568-
postMessage(message: any) {
569-
return (this._handler?.postMessage(message) ?? Promise.resolve(undefined));
579+
async postMessage(message: any): Promise<any> {
580+
return this._host.postMessage(message);
570581
}
571582

572583
handleMessage = (message: any) => {
@@ -626,8 +637,8 @@ export class PRContext {
626637
}
627638
};
628639

629-
public static instance = new PRContext();
630640
}
631641

632-
const PullRequestContext = createContext<PRContext>(PRContext.instance);
642+
// Every render entry point must supply a provider.
643+
const PullRequestContext = createContext<PRContext>(undefined!);
633644
export default PullRequestContext;

‎webviews/common/createContextNew.ts‎

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
*--------------------------------------------------------------------------------------------*/
55

66
import { createContext } from 'react';
7-
import { getMessageHandler, MessageHandler, vscode } from './message';
7+
import { WebviewHost } from './host';
88
import { RemoteInfo } from '../../common/types';
99
import { CancelCreatePullRequestNew, ChooseBaseRemoteAndBranchResult, ChooseCompareRemoteAndBranchResult, ChooseRemoteAndBranchArgs, CreateParamsNew, CreatePullRequestNew, ScrollPosition, StackCandidate, TitleAndDescriptionArgs, TitleAndDescriptionResult } from '../../common/views';
1010
import { compareIgnoreCase } from '../../src/common/utils';
@@ -39,6 +39,10 @@ const defaultCreateParams: CreateParamsNew = {
3939
usingTemplate: false
4040
};
4141

42+
function createDefaultParams(): CreateParamsNew {
43+
return { ...defaultCreateParams, labels: [], assignees: [], reviewers: [] };
44+
}
45+
4246
function remoteChanged(next: RemoteInfo | undefined, current: RemoteInfo | undefined): boolean {
4347
return next !== undefined && (next.owner !== current?.owner || next.repositoryName !== current?.repositoryName);
4448
}
@@ -53,17 +57,19 @@ function stackCandidateChanged(next: Partial<CreateParamsNew>, current: StackCan
5357

5458
export class CreatePRContextNew {
5559
public createParams: CreateParamsNew;
60+
public onchange: ((ctx: CreateParamsNew) => void) | null = null;
5661
private _titleStack: string[] = [];
5762
private _descriptionStack: string[] = [];
63+
private readonly _unsubscribe: () => void;
5864

59-
constructor(
60-
public onchange: ((ctx: CreateParamsNew) => void) | null = null,
61-
private _handler: MessageHandler | null = null,
62-
) {
63-
this.createParams = vscode.getState() ?? defaultCreateParams;
64-
if (!_handler) {
65-
this._handler = getMessageHandler(this.handleMessage);
66-
}
65+
constructor(private readonly _host: WebviewHost) {
66+
this.createParams = _host.getState<CreateParamsNew>() ?? createDefaultParams();
67+
this._unsubscribe = _host.onCommand(this.handleMessage);
68+
}
69+
70+
public dispose(): void {
71+
this._unsubscribe();
72+
this.onchange = null;
6773
}
6874

6975
get isCreatable(): boolean {
@@ -116,7 +122,7 @@ export class CreatePRContextNew {
116122
// dialog, or the message did not get a response) preserve the user's
117123
// in-progress title/description.
118124
if (result?.cancelled === true) {
119-
vscode.setState(defaultCreateParams);
125+
this._host.setState(createDefaultParams());
120126
}
121127
};
122128

@@ -133,8 +139,8 @@ export class CreatePRContextNew {
133139
}
134140

135141
public updateState = (params: Partial<CreateParamsNew>, reset: boolean = false): void => {
136-
this.createParams = reset ? { ...defaultCreateParams, ...params } : { ...this.createParams, ...params };
137-
vscode.setState(this.createParams);
142+
this.createParams = reset ? { ...createDefaultParams(), ...params } : { ...this.createParams, ...params };
143+
this._host.setState(this.createParams);
138144
if (this.onchange) {
139145
this.onchange(this.createParams);
140146
}
@@ -324,14 +330,14 @@ export class CreatePRContextNew {
324330
// awaiting would discard the user's title/description if the create fails
325331
// (for example when the branch push fails and needs `--force`), causing
326332
// the description to fall back to the template on the next webview load.
327-
vscode.setState(defaultCreateParams);
333+
this._host.setState(createDefaultParams());
328334
} catch (e) {
329335
this.updateState({ createError: (typeof e === 'string') ? e : (e.message ? e.message : 'An unknown error occurred.') });
330336
}
331337
};
332338

333339
postMessage = async (message: any): Promise<any> => {
334-
return this._handler?.postMessage(message);
340+
return this._host.postMessage(message);
335341
};
336342

337343
handleMessage = async (message: { command: string, params?: Partial<CreateParamsNew>, scrollPosition?: ScrollPosition }): Promise<void> => {
@@ -396,7 +402,7 @@ export class CreatePRContextNew {
396402

397403
case 'reset':
398404
if (!message.params) {
399-
this.updateState(defaultCreateParams, true);
405+
this.updateState(createDefaultParams(), true);
400406
return;
401407
}
402408
message.params.creating = message.params.creating ?? false;
@@ -453,8 +459,8 @@ export class CreatePRContextNew {
453459
}
454460
};
455461

456-
public static instance = new CreatePRContextNew();
457462
}
458463

459-
const PullRequestContextNew = createContext<CreatePRContextNew>(CreatePRContextNew.instance);
464+
// Every render entry point must supply a provider.
465+
const PullRequestContextNew = createContext<CreatePRContextNew>(undefined!);
460466
export default PullRequestContextNew;

‎webviews/common/hooks.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,26 @@
33
* Licensed under the MIT License. See License.txt in the project root for license information.
44
*--------------------------------------------------------------------------------------------*/
55

6-
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
6+
import { createContext, Dispatch, SetStateAction, useContext, useEffect, useState } from 'react';
7+
8+
export const ViewportWidthContext = createContext<number | undefined>(undefined);
9+
10+
export function useMaxViewportWidth(maxWidth: number): boolean {
11+
const width = useContext(ViewportWidthContext);
12+
const query = `(max-width: ${maxWidth}px)`;
13+
const [matches, setMatches] = useState(() => width === undefined ? window.matchMedia(query).matches : width <= maxWidth);
14+
useEffect(() => {
15+
if (width !== undefined) {
16+
return;
17+
}
18+
const media = window.matchMedia(query);
19+
const update = () => setMatches(media.matches);
20+
update();
21+
media.addEventListener('change', update);
22+
return () => media.removeEventListener('change', update);
23+
}, [query, width]);
24+
return width === undefined ? matches : width <= maxWidth;
25+
}
726

827
/**
928
* useState, but track the value of a prop.

‎webviews/common/host.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*---------------------------------------------------------------------------------------------
2+
* Copyright (c) Microsoft Corporation. All rights reserved.
3+
* Licensed under the MIT License. See License.txt in the project root for license information.
4+
*--------------------------------------------------------------------------------------------*/
5+
6+
import { MessageHandler } from './message';
7+
8+
export interface WebviewHost extends WebviewState {
9+
postMessage(message: CommandMessage): Promise<unknown>;
10+
onCommand(listener: (command: unknown) => void): () => void;
11+
dispose(): void;
12+
}
13+
14+
export function createWebviewHost(transport: WebviewTransport = vscodeTransport): WebviewHost {
15+
return new MessageHandler(transport);
16+
}
17+
18+
export interface CommandMessage {
19+
command: string;
20+
args?: unknown;
21+
}
22+
23+
export interface RequestMessage extends CommandMessage {
24+
req: string;
25+
}
26+
27+
export interface ReplyMessage {
28+
seq?: string;
29+
err?: string;
30+
res?: unknown;
31+
}
32+
33+
export interface WebviewState {
34+
getState<T>(): T | undefined;
35+
setState<T>(state: T): void;
36+
}
37+
38+
export interface WebviewTransport extends WebviewState {
39+
postMessage(message: RequestMessage): void;
40+
onMessage(listener: (message: ReplyMessage) => void): () => void;
41+
}
42+
43+
declare function acquireVsCodeApi(): Omit<WebviewTransport, 'onMessage'>;
44+
45+
let api: Omit<WebviewTransport, 'onMessage'> | undefined;
46+
47+
function getApi(): Omit<WebviewTransport, 'onMessage'> {
48+
api ??= acquireVsCodeApi();
49+
return api;
50+
}
51+
52+
export const vscodeTransport: WebviewTransport = {
53+
getState: <T>() => getApi().getState<T>(),
54+
setState: <T>(state: T) => getApi().setState(state),
55+
postMessage: message => getApi().postMessage(message),
56+
onMessage: listener => {
57+
const handler = (event: MessageEvent<ReplyMessage>) => listener(event.data);
58+
window.addEventListener('message', handler);
59+
return () => window.removeEventListener('message', handler);
60+
},
61+
};

0 commit comments

Comments
 (0)