Skip to content

Commit

Permalink
fix(vscode): show pdv open to side button on all files that define a …
Browse files Browse the repository at this point in the history
…project (nrwl#1999)
  • Loading branch information
MaxKless authored Jan 29, 2024
1 parent 8232a0a commit dafb57f
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 120 deletions.
9 changes: 9 additions & 0 deletions apps/nxls/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
NxProjectFolderTreeRequest,
NxProjectGraphOutputRequest,
NxProjectsByPathsRequest,
NxSourceMapFilesToProjectMapRequest,
NxStartupMessageRequest,
NxTransformedGeneratorSchemaRequest,
NxVersionRequest,
Expand Down Expand Up @@ -47,6 +48,7 @@ import {
getProjectFolderTree,
getProjectGraphOutput,
getProjectsByPaths,
getSourceMapFilesToProjectMap,
getStartupMessage,
getTransformedGeneratorSchema,
hasAffectedProjects,
Expand Down Expand Up @@ -475,6 +477,13 @@ connection.onRequest(NxHasAffectedProjectsRequest, async () => {
return hasAffectedProjects(WORKING_PATH, lspLogger);
});

connection.onRequest(NxSourceMapFilesToProjectMapRequest, async () => {
if (!WORKING_PATH) {
return new ResponseError(1000, 'Unable to get Nx info: no workspace path');
}
return getSourceMapFilesToProjectMap(WORKING_PATH);
});

connection.onNotification(NxWorkspaceRefreshNotification, async () => {
if (!WORKING_PATH) {
return new ResponseError(1001, 'Unable to get Nx info: no workspace path');
Expand Down
2 changes: 1 addition & 1 deletion apps/vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@
{
"command": "nx.project-details.openToSide",
"group": "navigation",
"when": "(resourceFilename === project.json || resourceFilename === package.json) && resourcePath not in nxConsole.ignoredPDVPaths && config.nxConsole.showProjectDetailsView"
"when": "resourcePath in nxConsole.pdvPaths && config.nxConsole.showProjectDetailsView"
}
],
"commandPalette": [
Expand Down
6 changes: 6 additions & 0 deletions libs/language-server/types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,9 @@ export const NxHasAffectedProjectsRequest: RequestType<
boolean,
unknown
> = new RequestType('nx/hasAffectedProjects');

export const NxSourceMapFilesToProjectMapRequest: RequestType<
undefined,
Record<string, string>,
unknown
> = new RequestType('nx/sourceMapFilesToProjectMap');
1 change: 1 addition & 0 deletions libs/language-server/workspace/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ export * from './lib/create-project-graph';
export * from './lib/get-project-folder-tree';
export * from './lib/nx-console-plugins';
export * from './lib/has-affected-projects';
export * from './lib/get-source-map';
export { getNxDaemonClient } from './lib/get-nx-workspace-package';
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import {
import { performance } from 'perf_hooks';

let projectGraph: ProjectGraph | null = null;
let sourceMaps: Record<string, Record<string, string[]>> | null = null;
let sourceMaps: Record<string, Record<string, string[]>> | undefined =
undefined;

export async function getNxWorkspaceConfig(
workspacePath: string,
Expand Down Expand Up @@ -116,7 +117,8 @@ export async function getNxWorkspaceConfig(
workspaceConfiguration = createNxWorkspaceConfiguration(
workspaceConfiguration,
projectGraph,
projectFileMap
projectFileMap,
sourceMaps
);

// for (const project in workspaceConfiguration.projects) {
Expand Down
24 changes: 24 additions & 0 deletions libs/language-server/workspace/src/lib/get-source-map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { lspLogger } from '@nx-console/language-server/utils';
import { nxWorkspace } from './workspace';

/**
* iterate over sourcemaps and return all files that were involved in creating a project along with the project name
*/
export async function getSourceMapFilesToProjectMap(
workingPath: string
): Promise<Record<string, string>> {
const { workspace } = await nxWorkspace(workingPath);
const sourceMapFilesToProjectMap: Record<string, string> = {};

Object.entries(workspace.sourceMaps ?? {}).forEach(
([projectName, sourceMap]) => {
Object.values(sourceMap).forEach(([file]) => {
if (!sourceMapFilesToProjectMap[file]) {
sourceMapFilesToProjectMap[file] = projectName;
}
});
}
);

return sourceMapFilesToProjectMap;
}
1 change: 1 addition & 0 deletions libs/vscode/nx-workspace/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export * from './lib/create-project-graph';
export * from './lib/get-project-folder-tree';
export * from './lib/nx-console-plugin-requests';
export * from './lib/has-affected-projects';
export * from './lib/get-source-map';
8 changes: 8 additions & 0 deletions libs/vscode/nx-workspace/src/lib/get-source-map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { NxSourceMapFilesToProjectMapRequest } from '@nx-console/language-server/types';
import { sendRequest } from '@nx-console/vscode/lsp-client';

export async function getSourceMapFilesToProjectMap(): Promise<
Record<string, string>
> {
return sendRequest(NxSourceMapFilesToProjectMapRequest, undefined);
}
88 changes: 21 additions & 67 deletions libs/vscode/project-details/src/lib/init-vscode-project-details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import {
getNxVersion,
getNxWorkspacePath,
getProjectByPath,
getSourceMapFilesToProjectMap,
} from '@nx-console/vscode/nx-workspace';
import { showNoProjectAtPathMessage } from '@nx-console/vscode/utils';
import { join } from 'path';
import { dirname, join } from 'path';
import { gte } from 'semver';
import {
ExtensionContext,
Expand All @@ -18,6 +19,7 @@ import {
import { ProjectDetailsCodelensProvider } from './project-details-codelens-provider';
import { ProjectDetailsManager } from './project-details-manager';
import { ProjectDetailsProvider } from './project-details-provider';
import { onWorkspaceRefreshed } from '@nx-console/vscode/lsp-client';

export function initVscodeProjectDetails(context: ExtensionContext) {
getNxWorkspacePath().then((nxWorkspacePath) => {
Expand All @@ -26,6 +28,7 @@ export function initVscodeProjectDetails(context: ExtensionContext) {
]);
});
getNxVersionAndRegisterCommand(context);
setProjectDetailsFileContext();

ProjectDetailsCodelensProvider.register(context);
}
Expand Down Expand Up @@ -79,71 +82,22 @@ function getNxVersionAndRegisterCommand(context: ExtensionContext) {
}
});
}
// function highlightTargets() {
// const activeEditor = window.activeTextEditor;
// if (!activeEditor) return;

// const document = activeEditor.document;
// const text = document.getText();
async function setProjectDetailsFileContext() {
const setContext = async () => {
const sourceMapFilesToProjectMap = await getSourceMapFilesToProjectMap();
const nxWorkspacePath = await getNxWorkspacePath();
const pdvPaths = [
...new Set(
Object.keys(sourceMapFilesToProjectMap).flatMap((path) => [
join(nxWorkspacePath, path),
join(nxWorkspacePath, dirname(path), 'package.json'),
])
),
];
commands.executeCommand('setContext', 'nxConsole.pdvPaths', pdvPaths);
};

// const regex = /"targets"\s*:/g;
// let match;

// const decorationType = window.createTextEditorDecorationType({
// borderColor: 'lightblue',
// borderStyle: 'solid',
// borderWidth: '1px',
// borderRadius: '2px',
// });

// const ranges = [];

// while ((match = regex.exec(text)) !== null) {
// const startPos = document.positionAt(match.index);
// const endPos = document.positionAt(match.index + match[0].length);
// const range = new Range(startPos, endPos);
// ranges.push(range);
// }

// activeEditor.setDecorations(decorationType, ranges);
// }

// const maxSmallIntegerV8 = 2 ** 30;
// const annotationDecoration: TextEditorDecorationType =
// window.createTextEditorDecorationType({
// after: {
// margin: '0 0 0 3em',
// textDecoration: 'none',
// },
// rangeBehavior: DecorationRangeBehavior.OpenOpen,
// });

// function decorateSourceMaps() {
// window.onDidChangeTextEditorSelection((e) => {
// const line = e.selections[0].active.line;
// const decorations = [];
// const text = 'helloasdasdasd';
// const decorationOptions = {
// renderOptions: {
// after: {
// color: new ThemeColor('input.placeholderForeground'),
// contentText: `${'\u00a0'.repeat(10)}${text.replace(/ /g, '\u00a0')}`,
// fontWeight: 'normal',
// fontStyle: 'normal',
// // Pull the decoration out of the document flow if we want to be scrollable
// textDecoration: `none;`, //${scrollable ? '' : ' position: absolute;'}`,
// },
// },
// range: new Range(
// new Position(line, maxSmallIntegerV8),
// new Position(line, maxSmallIntegerV8)
// ),
// } as DecorationOptions;
// decorations.push(decorationOptions);
// window.activeTextEditor?.setDecorations(annotationDecoration, decorations);
// });
// }

// function buildLineToPropertyMap(jsonText: string) {
// const json = parseJsonText('workspace.json', jsonText);
// }
setContext();
onWorkspaceRefreshed(() => setContext());
}
52 changes: 2 additions & 50 deletions libs/vscode/project-details/src/lib/project-details-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ export class ProjectDetailsManager {
document: TextDocument,
expandedTarget?: string
) {
const project = await getProjectNameFromUri(document);
const project = await getProjectByPath(document.uri.path);
if (!project) {
showNoProjectAtPathMessage(document.uri.path);
return;
}

Expand All @@ -51,52 +52,3 @@ export class ProjectDetailsManager {
preview.reveal(ViewColumn.Beside);
}
}

async function getProjectNameFromUri(
document: TextDocument
): Promise<{ name?: string; root: string } | undefined> {
if (document.fileName.endsWith('project.json')) {
try {
JSON.parse(document.getText());
} catch (e) {
window.showErrorMessage(
`Error parsing ${document.fileName}. Please make sure the JSON is valid. `
);
return;
}
const json = parseJsonText(document.fileName, document.getText());

const properties = getProperties(json.statements[0].expression);

let name: string | undefined = undefined;
const nameProperty = properties?.find(
(prop) => getPropertyName(prop) === 'name'
);

if (
nameProperty &&
isPropertyAssignment(nameProperty) &&
isStringLiteral(nameProperty.initializer)
) {
name = nameProperty.initializer.text;
}
const sourceRootProperty = properties?.find(
(prop) => getPropertyName(prop) === 'sourceRoot'
);
if (
sourceRootProperty &&
isPropertyAssignment(sourceRootProperty) &&
isStringLiteral(sourceRootProperty.initializer)
) {
return {
root: sourceRootProperty.initializer.text,
name,
};
}
}
const project = await getProjectByPath(document.uri.path);
if (!project) {
showNoProjectAtPathMessage(document.uri.path);
}
return;
}

0 comments on commit dafb57f

Please sign in to comment.