Skip to content

fix(workspace): allow browsing and comparing with local workspace version #9549

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 17 commits into from
Feb 18, 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
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ export function CodeCompareView({
<CodeCompareEditor
DiffEditor={DiffEditor}
language={language}
modifiedPath={modifiedPath}
modifiedPath={`${modifiedPath}${componentCompareContext?.compare?.hasLocalChanges ? '-local' : ''}`}
originalPath={originalPath}
originalFileContent={originalFileContent}
modifiedFileContent={modifiedFileContent}
Expand Down
11 changes: 6 additions & 5 deletions components/ui/code-compare/code-compare.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,22 @@ export function CodeCompare({ fileIconSlot, className, CodeView = CodeCompareVie

// todo - look into this loading flag where it needs to be used
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { base, compare, state: compareState, hooks: compareHooks, hidden, loading } = componentCompareContext || {};
const { base, compare, state: compareState, hooks: compareHooks, hidden, loading, } = componentCompareContext || {};

const state = compareState?.code;
const hook = compareHooks?.code;

const [isSidebarOpen, setSidebarOpenness] = useState(false);

const { fileTree: baseFileTree = [], mainFile } = useCode(hidden ? undefined : base?.model.id);
const { fileTree: compareFileTree = [] } = useCode(hidden ? undefined : compare?.model.id);
const baseHost = 'teambit.scope/scope';
const compareHost = compare?.hasLocalChanges ? 'teambit.workspace/workspace' : 'teambit.scope/scope';
const { fileTree: baseFileTree = [], mainFile } = useCode(hidden ? undefined : base?.model.id, baseHost);
const { fileTree: compareFileTree = [] } = useCode(hidden ? undefined : compare?.model.id, compareHost);

const fileCompareDataByName = componentCompareContext?.fileCompareDataByName;
const anyFileHasDiffStatus = useRef<boolean>(false);

const fileTree = useMemo(() => {
const allFiles = uniq(baseFileTree.concat(compareFileTree));
const allFiles = uniq<string>(baseFileTree.concat(compareFileTree));
anyFileHasDiffStatus.current = false;
// sort by diff status
return !fileCompareDataByName
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,14 @@ export function useCodeCompare({ fileName }: UseCodeCompareProps): UseCodeCompar
const { fileContent: downloadedCompareFileContent, loading: loadingDownloadedCompareFileContent } = useFileContent(
compareId,
fileName,
componentCompareContext?.hidden || loadingFromContext || !!codeCompareDataForFile?.compareContent
componentCompareContext?.hidden || loadingFromContext || !!codeCompareDataForFile?.compareContent,
comparingLocalChanges ? 'teambit.workspace/workspace' : 'teambit.scope/scope',
);
const { fileContent: downloadedBaseFileContent, loading: loadingDownloadedBaseFileContent } = useFileContent(
baseId,
fileName,
componentCompareContext?.hidden || loadingFromContext || !!codeCompareDataForFile?.baseContent
componentCompareContext?.hidden || loadingFromContext || !!codeCompareDataForFile?.baseContent,
'teambit.scope/scope',
);
const loading =
loadingFromContext ||
Expand Down
11 changes: 7 additions & 4 deletions components/ui/code-tab-page/code-tab-page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ComponentContext } from '@teambit/component';
import { ComponentContext, ComponentID } from '@teambit/component';
import classNames from 'classnames';
import React, { useContext, useState, HTMLAttributes, useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';
Expand Down Expand Up @@ -119,13 +119,14 @@ export function resolveFilePath(
return mainFile;
}

export function CodePage({ className, fileIconSlot, host, codeViewClassName }: CodePageProps) {
export function CodePage({ className, fileIconSlot, host: hostFromProps, codeViewClassName }: CodePageProps) {
const urlParams = useCodeParams();
const [searchParams] = useSearchParams();
const scopeFromQueryParams = searchParams.get('scope');
const component = useContext(ComponentContext);
const host = useMemo(() => urlParams.version ? 'teambit.scope/scope' : hostFromProps, [urlParams.version, hostFromProps]);

const { mainFile, fileTree = [], dependencies, devFiles, loading: loadingCode } = useCode(component.id);
const { mainFile, fileTree = [], dependencies, devFiles, loading: loadingCode } = useCode(component.id, host);
const { data: artifacts = [] } = useComponentArtifacts(host, component.id.toString());

const currentFile = resolveFilePath(urlParams.file, fileTree, mainFile, loadingCode);
Expand Down Expand Up @@ -176,17 +177,19 @@ export function CodePage({ className, fileIconSlot, host, codeViewClassName }: C
});
}, [dependencies?.length]);

const componentId = urlParams.version ? component.id : ComponentID.fromString(component.id.toStringWithoutVersion());
return (
<SplitPane layout={sidebarOpenness} size="85%" className={classNames(styles.codePage, className)}>
<Pane className={styles.left}>
<CodeView
componentId={component.id}
componentId={componentId}
currentFile={currentFile}
icon={icon}
currentFileContent={currentArtifactFileContent}
loading={loadingArtifactFileContent || loadingCode}
codeSnippetClassName={codeViewClassName}
dependencies={dependencies}
host={host}
/>
</Pane>
<HoverSplitter className={styles.splitter}>
Expand Down
5 changes: 4 additions & 1 deletion components/ui/code-view/code-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export type CodeViewProps = {
loading?: boolean;
codeSnippetClassName?: string;
dependencies?: DependencyType[];
host?: string
} & HTMLAttributes<HTMLDivElement>;

SyntaxHighlighter.registerLanguage('md', markDownSyntax);
Expand Down Expand Up @@ -112,6 +113,7 @@ export function CodeView({
codeSnippetClassName,
loading: loadingFromProps,
dependencies,
host = 'teambit.scope/scope',
}: CodeViewProps) {
const depsByPackageName = new Map<string, DependencyType>(
(dependencies || []).map((dep) => [(dep.packageName || dep.id).toString(), dep])
Expand All @@ -120,7 +122,8 @@ export function CodeView({
const { fileContent: downloadedFileContent, loading: loadingFileContent } = useFileContent(
componentId,
currentFile,
!!currentFileContent
!!currentFileContent,
host,
);
const loading = loadingFromProps || loadingFileContent;
const location = useLocation();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ function RenderCompareScreen(
// eslint-disable-next-line complexity
export function ComponentCompare(props: ComponentCompareProps) {
const {
host,
host: hostFromProps,
baseId: baseIdFromProps,
compareId: compareIdFromProps,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand All @@ -283,13 +283,14 @@ export function ComponentCompare(props: ComponentCompareProps) {
const component = useContext(ComponentContext);
const componentDescriptor = useContext(ComponentDescriptorContext);
const location = useLocation();
const isWorkspace = host === 'teambit.workspace/workspace';

const isWorkspace = hostFromProps === 'teambit.workspace/workspace';
const compareHost = isWorkspace && !location?.search.includes('version') && !compareIdFromProps && component.logs?.length === 0 ? hostFromProps : 'teambit.scope/scope';
const host = 'teambit.scope/scope';
const {
component: compareComponent,
loading: loadingCompare,
componentDescriptor: compareComponentDescriptor,
} = useComponent(host, compareIdOverride?.toString() || compareIdFromProps?.toString(), {
} = useComponent(compareHost, compareIdOverride?.toString() || compareIdFromProps?.toString(), {
skip: hidden || (!compareIdFromProps && !compareIdOverride),
customUseComponent,
logFilters: {
Expand Down Expand Up @@ -352,7 +353,7 @@ export function ComponentCompare(props: ComponentCompareProps) {
}, [compare?.id.toString()]);

const skipComponentCompareQuery =
hidden || compareIsLocalChanges || base?.id.version?.toString() === compare?.id.version?.toString();
hidden || (base?.id.version?.toString() === compare?.id.version?.toString() && !compareIsLocalChanges);

const { loading: compCompareLoading, componentCompareData } = useComponentCompareQuery(
base?.id.toString(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,6 @@ export function ComponentView(props: ComponentViewProps) {

const searchParams = new URLSearchParams(location.search);
const scopeFromQueryParams = searchParams.get('scope');

const pathname = location.pathname.substring(1).split('?')[0];
const compIdStr = component.id.toStringWithoutVersion();
const compIdName = component.id.fullName;
Expand Down
5 changes: 5 additions & 0 deletions components/ui/version-dropdown/version-dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ function _VersionDropdown({
getActiveTabIndex={getActiveTabIndex}
lanes={lanes}
useVersions={useComponentVersions}
onVersionClicked={() => setOpen(false)}
open={open}
/>
</Dropdown>
Expand All @@ -173,6 +174,7 @@ type VersionMenuProps = {
loading?: boolean;
getActiveTabIndex?: GetActiveTabIndex;
open?: boolean;
onVersionClicked?: () => void;
} & React.HTMLAttributes<HTMLDivElement>;

export type VersionMenuTab =
Expand Down Expand Up @@ -208,6 +210,7 @@ function _VersionMenu({
getActiveTabIndex = defaultActiveTabIndex,
loading: loadingFromProps,
open,
onVersionClicked,
...rest
}: VersionMenuProps) {
const { snaps, tags, loading: loadingVersions } = useVersions?.() || {};
Expand Down Expand Up @@ -268,6 +271,7 @@ function _VersionMenu({
latestVersion={latestVersion}
overrideVersionHref={overrideVersionHref}
showDetails={showVersionDetails}
onVersionClicked={onVersionClicked}
{...version}
></VersionInfo>
);
Expand Down Expand Up @@ -296,6 +300,7 @@ function _VersionMenu({
href={'?'}
active={currentVersion === LOCAL_VERSION}
className={classNames(styles.versionRow, styles.localVersion)}
onClick={onVersionClicked}
>
<div className={styles.version}>
<UserAvatar size={24} account={{}} className={styles.versionUserAvatar} />
Expand Down
4 changes: 3 additions & 1 deletion components/ui/version-dropdown/version-info/version-info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export interface VersionInfoProps extends DropdownComponentVersion {
latestVersion?: string;
overrideVersionHref?: (version: string) => string;
showDetails?: boolean;
onVersionClicked?: () => void;
}

export const VersionInfo = React.memo(React.forwardRef<HTMLDivElement, VersionInfoProps>(_VersionInfo));
Expand All @@ -31,6 +32,7 @@ function _VersionInfo(
message,
tag,
profileImage,
onVersionClicked,
}: VersionInfoProps,
ref?: React.ForwardedRef<HTMLDivElement>
) {
Expand Down Expand Up @@ -62,7 +64,7 @@ function _VersionInfo(
const isLatest = version === latestVersion;

return (
<div ref={ref || currentVersionRef}>
<div ref={ref || currentVersionRef} onClick={onVersionClicked}>
<MenuLinkItem active={isCurrent} href={href} className={styles.versionRow}>
<div className={styles.version}>
<UserAvatar size={24} account={author} className={styles.versionUserAvatar} showTooltip={true} />
Expand Down
2 changes: 1 addition & 1 deletion scopes/component/code/code.ui.runtime.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class CodeUI {
*/
private host: string,
private fileIconSlot?: FileIconSlot
) {}
) { }

getCodePage = (props?: Partial<CodePageProps>) => {
return <CodePage {...(props || {})} fileIconSlot={this.fileIconSlot} host={this.host} />;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,13 @@ export class ComponentCompareMain {
private depResolver: DependencyResolverMain,
private importer: ImporterMain,
private workspace?: Workspace
) {}
) { }

async compare(baseIdStr: string, compareIdStr: string): Promise<ComponentCompareResult> {
const host = this.componentAspect.getHost();
const [baseCompId, compareCompId] = await host.resolveMultipleComponentIds([baseIdStr, compareIdStr]);
const modelComponent = await this.scope.legacyScope.getModelComponentIfExist(compareCompId);
const comparingWithLocalChanges = this.workspace && baseIdStr === compareIdStr;

if (!modelComponent) {
throw new BitError(`component ${compareCompId.toString()} doesn't have any version yet`);
Expand All @@ -71,21 +72,20 @@ export class ComponentCompareMain {
const baseVersion = baseCompId.version as string;
const compareVersion = compareCompId.version as string;

const repository = this.scope.legacyScope.objects;
const baseVersionObject = await modelComponent.loadVersion(baseVersion, repository);
const compareVersionObject = await modelComponent.loadVersion(compareVersion, repository);

const diff: DiffResults = await this.diffBetweenVersionsObjects(
modelComponent,
baseVersionObject,
compareVersionObject,
baseVersion,
compareVersion,
{}
);
const components = await host.getMany([baseCompId, compareCompId])
const baseComponent = components?.[0];
const compareComponent = components?.[1];
const componentWithoutVersion = await host.get((baseCompId || compareCompId).changeVersion(undefined))

const baseComponent = await host.get(baseCompId);
const compareComponent = await host.get(compareCompId);
const diff = componentWithoutVersion
? await this.computeDiff(
componentWithoutVersion,
comparingWithLocalChanges ? undefined : baseVersion,
comparingWithLocalChanges ? undefined : compareVersion, {})
: {
filesDiff: [],
fieldsDiff: []
};

const baseTestFiles =
(baseComponent && (await this.tester.getTestFiles(baseComponent).map((file) => file.relative))) || [];
Expand Down Expand Up @@ -117,7 +117,7 @@ export class ComponentCompareMain {
if (!this.workspace) throw new OutsideWorkspaceError();
const ids = pattern ? await this.workspace.idsByPattern(pattern) : await this.workspace.listTagPendingIds();
const consumer = this.workspace.consumer;
if (!ids.length) {
if (!ids.length) {
return [];
}
const diffResults = await this.componentsDiff(ids, version, toVersion, {
Expand Down Expand Up @@ -186,13 +186,10 @@ export class ComponentCompareMain {
toVersion: string | undefined,
diffOpts: DiffOptions
) {
if (!this.workspace) throw new OutsideWorkspaceError();
const consumer = this.workspace.consumer;
// if (!version) throw new Error('getComponentDiffOfVersion expects to get version');
const consumerComponent = component.state._consumer as ConsumerComponent;
const diffResult: DiffResults = { id: component.id, hasDiff: false };
const modelComponent =
consumerComponent.modelComponent || (await consumer.scope.getModelComponentIfExist(component.id));
consumerComponent.modelComponent || (await this.scope.legacyScope.getModelComponentIfExist(component.id));

if (!modelComponent || !consumerComponent.componentFromModel) {
if (version || toVersion) {
Expand All @@ -213,13 +210,13 @@ export class ComponentCompareMain {
if (hasDiff(diffResult)) diffResult.hasDiff = true;
return diffResult;
}
const repository = consumer.scope.objects;
const repository = this.scope.legacyScope.objects;
const idsToImport = compact([
version ? component.id.changeVersion(version) : undefined,
toVersion ? component.id.changeVersion(toVersion) : undefined,
]);
const idList = ComponentIdList.fromArray(idsToImport);
await consumer.scope.scopeImporter.importWithoutDeps(idList, { cache: true, reason: 'to show diff' });
await this.scope.legacyScope.scopeImporter.importWithoutDeps(idList, { cache: true, reason: 'to show diff' });
if (diffOpts.compareToParent) {
if (!version) throw new BitError('--parent flag expects to get version');
if (toVersion) throw new BitError('--parent flag expects to get only one version');
Expand All @@ -240,11 +237,11 @@ export class ComponentCompareMain {

diffResult.filesDiff = await getFilesDiff(fromFiles, toFiles, fromVersionLabel, toVersionLabel);
const fromVersionComponent = version
? await modelComponent.toConsumerComponent(version, consumer.scope.name, repository)
? await modelComponent.toConsumerComponent(version, this.scope.legacyScope.name, repository)
: consumerComponent.componentFromModel;

const toVersionComponent = toVersion
? await modelComponent.toConsumerComponent(toVersion, consumer.scope.name, repository)
? await modelComponent.toConsumerComponent(toVersion, this.scope.legacyScope.name, repository)
: consumerComponent;
await updateFieldsDiff(fromVersionComponent, toVersionComponent, diffResult, diffOpts);

Expand Down
5 changes: 3 additions & 2 deletions scopes/component/component/component.graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,8 +250,9 @@ export function componentSchema(componentExtension: ComponentMain): Schema {
errorMessage: err.message ? stripAnsi(err.message) : err.name,
}));
},
id: async (host: ComponentFactory) => {
return host.name;
id: async (host: ComponentFactory, _args, _context, info) => {
const extensionId = info.variableValues.extensionId;
return extensionId ? `${host.name}/${extensionId}` : host.name;
},
name: async (host: ComponentFactory) => {
return host.name;
Expand Down
2 changes: 2 additions & 0 deletions scopes/component/component/component.main.runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ export class ComponentMain {
return priorityHost || hosts[0];
}



getShowFragments() {
const fragments = orderBy(flatten(this.showFragmentSlot.values()), ['weight', ['asc']]);
return fragments;
Expand Down
Loading