Skip to content

feat: add vscode slice for message passing with extension #3080

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

Merged
merged 15 commits into from
Mar 3, 2025
Merged
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
63 changes: 63 additions & 0 deletions src/commons/application/Application.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import React from 'react';
import { useDispatch } from 'react-redux';
import { Outlet } from 'react-router-dom';
import Messages, {
MessageType,
MessageTypeNames,
sendToWebview
} from 'src/features/vscode/messages';

import NavigationBar from '../navigationBar/NavigationBar';
import Constants from '../utils/Constants';
import { useLocalStorageState, useSession } from '../utils/Hooks';
import WorkspaceActions from '../workspace/WorkspaceActions';
import { defaultWorkspaceSettings, WorkspaceSettingsContext } from '../WorkspaceSettingsContext';
import SessionActions from './actions/SessionActions';
import VscodeActions from './actions/VscodeActions';

const Application: React.FC = () => {
const dispatch = useDispatch();
Expand Down Expand Up @@ -70,6 +77,62 @@ const Application: React.FC = () => {
};
}, [isPWA, isMobile]);

// Effect to handle messages from VS Code
React.useEffect(() => {
if (!window.confirm) {
// Polyfill confirm() to instead show as VS Code notification
// TODO: Pass text as a new Message to the webview
window.confirm = text => {
console.log(`Confirmation automatically accepted: ${text ?? 'No text provided'}`);
return true;
};
}

const message = Messages.ExtensionPing();
sendToWebview(message);

window.addEventListener('message', event => {
const message: MessageType = event.data;
// Only accept messages from the vscode webview
if (!event.origin.startsWith('vscode-webview://')) {
return;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this is a guard, but shall we log such an event?

Technically we might be able to configure our deployment with X-Frame-Options: DENY to prevent embedding but let's look into it another time

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note to self: also add Content-Security-Policy frame-ancestors 'none';

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding header X-Frame-Options: DENY does not compromise the usability of the VSC extension, but Content-Security-Policy: frame-ancestors 'none'; will cause the request to be blocked within VSC.

}
// console.log(`FRONTEND: Message from ${event.origin}: ${JSON.stringify(message)}`);
switch (message.type) {
case MessageTypeNames.ExtensionPong:
console.log('Received WebviewStarted message, will set vsc');
dispatch(VscodeActions.setVscode());

if (message.token) {
const token = JSON.parse(message.token.trim());
console.log(`FRONTEND: WebviewStarted: ${token}`);
dispatch(
SessionActions.setTokens({
accessToken: token.accessToken,
refreshToken: token.refreshToken
})
);
dispatch(SessionActions.fetchUserAndCourse());
}
break;
case MessageTypeNames.Text:
const code = message.code;
console.log(`FRONTEND: TextMessage: ${code}`);
// TODO: Don't change ace editor directly
// const elements = document.getElementsByClassName('react-ace');
// if (elements.length === 0) {
// return;
// }
// // @ts-expect-error: ace is not available at compile time
// const editor = ace.edit(elements[0]);
// editor.setValue(code);
dispatch(WorkspaceActions.updateEditorValue('assessment', 0, code));
break;
}
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return (
<WorkspaceSettingsContext.Provider value={[workspaceSettings, setWorkspaceSettings]}>
<div className="Application">
Expand Down
9 changes: 8 additions & 1 deletion src/commons/application/ApplicationTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
import { RouterState } from './types/CommonsTypes';
import { ExternalLibraryName } from './types/ExternalTypes';
import { SessionState } from './types/SessionTypes';
import { VscodeState as VscodeState } from './types/VscodeTypes';

export type OverallState = {
readonly router: RouterState;
Expand All @@ -33,6 +34,7 @@ export type OverallState = {
readonly featureFlags: FeatureFlagsState;
readonly fileSystem: FileSystemState;
readonly sideContent: SideContentManagerState;
readonly vscode: VscodeState;
};

export type Story = {
Expand Down Expand Up @@ -602,6 +604,10 @@ export const defaultSideContentManager: SideContentManagerState = {
stories: {}
};

export const defaultVscode: VscodeState = {
isVscode: false
};

export const defaultState: OverallState = {
router: defaultRouter,
achievement: defaultAchievement,
Expand All @@ -612,5 +618,6 @@ export const defaultState: OverallState = {
workspaces: defaultWorkspaceManager,
featureFlags: defaultFeatureFlags,
fileSystem: defaultFileSystem,
sideContent: defaultSideContentManager
sideContent: defaultSideContentManager,
vscode: defaultVscode
};
10 changes: 10 additions & 0 deletions src/commons/application/actions/VscodeActions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { createActions } from 'src/commons/redux/utils';

const VscodeActions = createActions('vscode', {
setVscode: 0
});

// For compatibility with existing code (actions helper)
export default {
...VscodeActions
};
4 changes: 3 additions & 1 deletion src/commons/application/reducers/RootReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { WorkspaceReducer as workspaces } from '../../workspace/WorkspaceReducer
import { OverallState } from '../ApplicationTypes';
import { RouterReducer as router } from './CommonsReducer';
import { SessionsReducer as session } from './SessionsReducer';
import { VscodeReducer as vscode } from './VscodeReducer';

const rootReducer: Reducer<OverallState, SourceActionType> = combineReducers({
router,
Expand All @@ -23,7 +24,8 @@ const rootReducer: Reducer<OverallState, SourceActionType> = combineReducers({
workspaces,
featureFlags,
fileSystem,
sideContent
sideContent,
vscode
});

export default rootReducer;
20 changes: 20 additions & 0 deletions src/commons/application/reducers/VscodeReducer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { createReducer, Reducer } from '@reduxjs/toolkit';

import { SourceActionType } from '../../utils/ActionsHelper';
import VscodeActions from '../actions/VscodeActions';
import { defaultVscode } from '../ApplicationTypes';
import { VscodeState } from '../types/VscodeTypes';

export const VscodeReducer: Reducer<VscodeState, SourceActionType> = (
state = defaultVscode,
action
) => {
state = newVscodeReducer(state, action);
return state;
};

const newVscodeReducer = createReducer(defaultVscode, builder => {
builder.addCase(VscodeActions.setVscode, state => {
return { ...state, ...{ isVscode: true } };
});
});
3 changes: 3 additions & 0 deletions src/commons/application/types/VscodeTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type VscodeState = {
isVscode: boolean;
};
30 changes: 4 additions & 26 deletions src/commons/assessmentWorkspace/AssessmentWorkspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router';
import { showSimpleConfirmDialog } from 'src/commons/utils/DialogHelper';
import { onClickProgress } from 'src/features/assessments/AssessmentUtils';
import Messages, { sendToWebview } from 'src/features/vscode/messages';
import { mobileOnlyTabIds } from 'src/pages/playground/PlaygroundTabs';

import { initSession, log } from '../../features/eventLogging';
Expand Down Expand Up @@ -184,12 +185,6 @@ const AssessmentWorkspace: React.FC<AssessmentWorkspaceProps> = props => {
};
}, [dispatch]);

useEffect(() => {
// TODO: Hardcoded to make use of the first editor tab. Refactoring is needed for this workspace to enable Folder mode.
handleEditorValueChange(0, '');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

useEffect(() => {
if (assessmentOverview && assessmentOverview.maxTeamSize > 1) {
handleTeamOverviewFetch(props.assessmentId);
Expand Down Expand Up @@ -220,26 +215,6 @@ const AssessmentWorkspace: React.FC<AssessmentWorkspaceProps> = props => {
if (!assessment) {
return;
}
// ------------- PLEASE NOTE, EVERYTHING BELOW THIS SEEMS TO BE UNUSED -------------
// checkWorkspaceReset does exactly the same thing.
let questionId = props.questionId;
if (props.questionId >= assessment.questions.length) {
questionId = assessment.questions.length - 1;
}

const question = assessment.questions[questionId];

let answer = '';
if (question.type === QuestionTypes.programming) {
if (question.answer) {
answer = (question as IProgrammingQuestion).answer as string;
} else {
answer = (question as IProgrammingQuestion).solutionTemplate;
}
}

// TODO: Hardcoded to make use of the first editor tab. Refactoring is needed for this workspace to enable Folder mode.
handleEditorValueChange(0, answer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Expand Down Expand Up @@ -415,9 +390,12 @@ const AssessmentWorkspace: React.FC<AssessmentWorkspaceProps> = props => {
);
handleClearContext(question.library, true);
handleUpdateHasUnsavedChanges(false);
sendToWebview(Messages.NewEditor(`assessment${assessment.id}`, props.questionId, ''));
if (options.editorValue) {
// TODO: Hardcoded to make use of the first editor tab. Refactoring is needed for this workspace to enable Folder mode.
handleEditorValueChange(0, options.editorValue);
} else {
handleEditorValueChange(0, '');
}
};

Expand Down
4 changes: 3 additions & 1 deletion src/commons/mocks/StoreMocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
defaultSession,
defaultSideContentManager,
defaultStories,
defaultVscode,
defaultWorkspaceManager,
OverallState
} from '../application/ApplicationTypes';
Expand All @@ -32,7 +33,8 @@ export function mockInitialStore(
stories: defaultStories,
featureFlags: defaultFeatureFlags,
fileSystem: defaultFileSystem,
sideContent: defaultSideContentManager
sideContent: defaultSideContentManager,
vscode: defaultVscode
};

const lodashMergeCustomizer = (objValue: any, srcValue: any) => {
Expand Down
3 changes: 3 additions & 0 deletions src/commons/utils/ActionsHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import SourcecastActions from '../../features/sourceRecorder/sourcecast/Sourceca
import SourceRecorderActions from '../../features/sourceRecorder/SourceRecorderActions';
import SourcereelActions from '../../features/sourceRecorder/sourcereel/SourcereelActions';
import StoriesActions from '../../features/stories/StoriesActions';
import VscodeActions from '../application/actions/VscodeActions';
import { FeatureFlagsActions } from '../featureFlags';
import { ActionType } from './TypeHelper';

Expand All @@ -40,6 +41,8 @@ export const actions = {
...FileSystemActions,
...StoriesActions,
...SideContentActions,
...VscodeActions,
...SideContentActions,
...FeatureFlagsActions
};

Expand Down
7 changes: 5 additions & 2 deletions src/commons/workspace/Workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { Prompt } from '../ReactRouterPrompt';
import Repl, { ReplProps } from '../repl/Repl';
import SideBar, { SideBarTab } from '../sideBar/SideBar';
import SideContent, { SideContentProps } from '../sideContent/SideContent';
import { useDimensions } from '../utils/Hooks';
import { useDimensions, useTypedSelector } from '../utils/Hooks';

export type WorkspaceProps = DispatchProps & StateProps;

Expand Down Expand Up @@ -44,6 +44,7 @@ const Workspace: React.FC<WorkspaceProps> = props => {
const [contentContainerWidth] = useDimensions(contentContainerDiv);
const [expandedSideBarWidth, setExpandedSideBarWidth] = useState(200);
const [isSideBarExpanded, setIsSideBarExpanded] = useState(true);
const isVscode = useTypedSelector(state => state.vscode.isVscode);

const sideBarCollapsedWidth = 40;

Expand Down Expand Up @@ -222,7 +223,9 @@ const Workspace: React.FC<WorkspaceProps> = props => {
</Resizable>
<div className="row content-parent" ref={contentContainerDiv}>
<div className="editor-divider" ref={editorDividerDiv} />
<Resizable {...editorResizableProps()}>{createWorkspaceInput(props)}</Resizable>
{!isVscode && (
<Resizable {...editorResizableProps()}>{createWorkspaceInput(props)}</Resizable>
)}
<div className="right-parent" ref={setFullscreenRefs}>
<Tooltip
className="fullscreen-button"
Expand Down
5 changes: 3 additions & 2 deletions src/commons/workspace/WorkspaceActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,9 @@ const newActions = createActions('workspace', {
updateEditorValue: (
workspaceLocation: WorkspaceLocation,
editorTabIndex: number,
newEditorValue: string
) => ({ workspaceLocation, editorTabIndex, newEditorValue }),
newEditorValue: string,
isFromVscode: boolean = false
) => ({ workspaceLocation, editorTabIndex, newEditorValue, isFromVscode }),
setEditorBreakpoint: (
workspaceLocation: WorkspaceLocation,
editorTabIndex: number,
Expand Down
3 changes: 2 additions & 1 deletion src/commons/workspace/__tests__/WorkspaceActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,8 @@ test('updateEditorValue generates correct action object', () => {
payload: {
workspaceLocation: assessmentWorkspace,
editorTabIndex,
newEditorValue
newEditorValue,
isFromVscode: false
}
});
});
Expand Down
4 changes: 4 additions & 0 deletions src/commons/workspace/reducers/editorReducer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ActionReducerMapBuilder } from '@reduxjs/toolkit';
import Messages, { sendToWebview } from 'src/features/vscode/messages';

import WorkspaceActions from '../WorkspaceActions';
import { getWorkspaceLocation } from '../WorkspaceReducer';
Expand Down Expand Up @@ -52,6 +53,9 @@ export const handleEditorActions = (builder: ActionReducerMapBuilder<WorkspaceMa
}

state[workspaceLocation].editorTabs[editorTabIndex].value = newEditorValue;
if (!action.payload.isFromVscode) {
sendToWebview(Messages.Text(newEditorValue));
}
})
.addCase(WorkspaceActions.setEditorBreakpoint, (state, action) => {
const workspaceLocation = getWorkspaceLocation(action);
Expand Down
Loading