Skip to content
Draft
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
17 changes: 15 additions & 2 deletions webapp/src/dogma/features/history/CommitSha.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,21 @@ export const CommitSha = ({ label, sha, abbreviated = true, showLabel = true }:
variant="ghost"
flexShrink={0}
onClick={async () => {
await navigator.clipboard.writeText(sha);
dispatch(newNotification('', `${copyLabel} copied to clipboard`, 'success'));
try {
if (!navigator.clipboard?.writeText) {
throw new Error('Clipboard API is unavailable');
}
await navigator.clipboard.writeText(sha);
dispatch(newNotification('', `${copyLabel} copied to clipboard`, 'success'));
} catch {
dispatch(
newNotification(
`Failed to copy ${copyLabel}`,
'Clipboard access is unavailable or was denied.',
'error',
),
);
}
}}
/>
</Tooltip>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const CommitViewPage = () => {
filePath = '/**';
}
const {
data: historyData,
currentData: historyData,
isFetching: historyFetching,
error: historyError,
} = useGetHistoryQuery({
Expand All @@ -56,8 +56,8 @@ const CommitViewPage = () => {
maxCommits: 1,
});
const {
data: oldHistoryData,
isLoading: oldHistoryLoading,
currentData: oldHistoryData,
isFetching: oldHistoryFetching,
error: oldHistoryError,
} = useGetHistoryQuery(
{
Expand All @@ -73,8 +73,8 @@ const CommitViewPage = () => {
},
);
const {
data: newData,
isLoading: isNewLoading,
currentData: newData,
isFetching: newFetching,
error: newError,
} = useGetFilesQuery({
projectName,
Expand All @@ -83,25 +83,26 @@ const CommitViewPage = () => {
filePath,
withContent: true,
});
const previousRevision = revision > 2 ? oldHistoryData?.[0]?.revision : undefined;
const {
data: oldData,
isLoading: isOldLoading,
currentData: oldData,
isFetching: oldFetching,
error: oldError,
} = useGetFilesQuery(
{
projectName,
repoName,
revision: oldHistoryData?.[0]?.revision || 1,
revision: previousRevision || 1,
filePath,
withContent: true,
},
{
skip: !oldHistoryData || oldHistoryData.length == 0,
skip: !previousRevision,
},
);
const {
data: headRev,
isLoading: isRevLoading,
currentData: headRev,
isFetching: revFetching,
error: revError,
} = useGetNormalisedRevisionQuery({
projectName,
Expand All @@ -124,11 +125,11 @@ const CommitViewPage = () => {
return (
<Deferred
isLoading={
(historyFetching && historyData?.[0]?.revision !== revision) ||
oldHistoryLoading ||
isNewLoading ||
isOldLoading ||
isRevLoading
(historyFetching && !historyData) ||
(revision > 2 && oldHistoryFetching && !oldHistoryData) ||
(newFetching && !newData) ||
(!!previousRevision && oldFetching && !oldData) ||
(revFetching && !headRev)
}
error={historyError || oldHistoryError || newError || revError || oldError0}
>
Expand All @@ -138,10 +139,6 @@ const CommitViewPage = () => {
}

const history = historyData[0];
let previousRevision;
if (revision > 2 && oldHistoryData && oldHistoryData.length > 0) {
previousRevision = oldHistoryData[0].revision;
}
const oldData0 = !previousRevision ? [] : oldData || [];
const newData0 = newData || [];
const hasNext = filePath == '/**' && revision !== headRev.revision;
Expand Down
20 changes: 18 additions & 2 deletions webapp/tests/dogma/feature/history/CommitSha.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,36 @@ describe('CommitSha', () => {
const writeText = jest.fn().mockResolvedValue(undefined);

beforeEach(() => {
writeText.mockClear();
writeText.mockReset().mockResolvedValue(undefined);
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
});

it('copies the upstream commit SHA', async () => {
renderWithProviders(<CommitSha label="Upstream" sha={sha} />);
const { store } = renderWithProviders(<CommitSha label="Upstream" sha={sha} />);

expect(screen.getByText('0123456')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Copy Upstream SHA' }));

await waitFor(() => expect(writeText).toHaveBeenCalledWith(sha));
await waitFor(() => expect(store.getState().notification.type).toBe('success'));
});

it.each(['permission denied', 'API unavailable'])('reports a copy failure: %s', async (failure) => {
if (failure === 'API unavailable') {
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined });
} else {
writeText.mockRejectedValue(new DOMException('Clipboard access denied', 'NotAllowedError'));
}
const { store } = renderWithProviders(<CommitSha label="Upstream" sha={sha} />);

fireEvent.click(screen.getByRole('button', { name: 'Copy Upstream SHA' }));

await waitFor(() => expect(store.getState().notification.type).toBe('error'));
expect(store.getState().notification.title).toBe('Failed to copy Upstream SHA');
expect(store.getState().notification.description).toBe('Clipboard access is unavailable or was denied.');
});

it('shows the full upstream commit ID when abbreviation is disabled', () => {
Expand Down
88 changes: 88 additions & 0 deletions webapp/tests/dogma/feature/history/CommitView.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ let mockRevision: string;
let mockPath: string[] | undefined;
let pendingCommitResponse: Promise<void> | undefined;
let requestedPendingCommit: boolean;
let pendingContentsResponse: Promise<void> | undefined;
let pendingContentsRevision: number;
let pendingContentsPath: string;
let requestedPendingContents: boolean;

jest.mock('next/router', () => ({
useRouter: () => ({
Expand Down Expand Up @@ -69,6 +73,8 @@ beforeEach(() => {
mockPath = ['a.json'];
pendingCommitResponse = undefined;
requestedPendingCommit = false;
pendingContentsResponse = undefined;
requestedPendingContents = false;
jest.spyOn(global, 'fetch').mockImplementation(async (input) => {
const request = input instanceof Request ? input : new Request(input);
const url = new URL(request.url, 'http://localhost');
Expand All @@ -86,9 +92,16 @@ beforeEach(() => {
.filter((commit) => commit.revision <= from && commit.revision >= to)
.filter((commit) => path === '/**' || changedPaths[commit.revision] === path)
.slice(0, maxCommits);
if ((data as HistoryDto[]).length === 0) {
return new Response(null, { status: 204 });
}
} else if (url.pathname.includes('/contents/')) {
const revision = Number(url.searchParams.get('revision'));
const path = url.pathname.split('/contents')[1];
if (revision === pendingContentsRevision && path === pendingContentsPath && pendingContentsResponse) {
requestedPendingContents = true;
await pendingContentsResponse;
}
data = Object.entries(changedPaths)
.filter(
([changedAt, changedPath]) =>
Expand Down Expand Up @@ -119,6 +132,81 @@ afterEach(() => {
});

describe('CommitView metadata', () => {
it('renders a file addition when the previous history returns no content', async () => {
mockPath = ['b.json'];
renderWithProviders(<CommitViewPage />);

await screen.findByRole('heading', { name: 'Commit 3' });
expect(screen.getByRole('heading', { name: '/b.json' })).toBeInTheDocument();
expect(screen.getByText(upstreamB, { exact: true })).toBeInTheDocument();
});

it.each([
{
transition: 'revision',
initialRevision: '3',
initialPath: undefined,
revision: '4',
path: undefined,
contentsRevision: 4,
contentsPath: '/**',
},
{
transition: 'path',
initialRevision: '3',
initialPath: undefined,
revision: '3',
path: ['a.json'],
contentsRevision: 3,
contentsPath: '/a.json',
},
{
transition: 'previous contents',
initialRevision: '4',
initialPath: ['b.json'],
revision: '4',
path: undefined,
contentsRevision: 3,
contentsPath: '/**',
},
])('waits for current contents after a $transition transition', async (next) => {
mockRevision = next.initialRevision;
mockPath = next.initialPath;
const { rerender, store } = renderWithProviders(<CommitViewPage />);
await screen.findByRole('heading', { name: `Commit ${next.initialRevision}` });

let finishResponse: () => void;
pendingContentsResponse = new Promise<void>((resolve) => {
finishResponse = resolve;
});
pendingContentsRevision = next.contentsRevision;
pendingContentsPath = next.contentsPath;
mockRevision = next.revision;
mockPath = next.path;
rerender(<CommitViewPage />);
await waitFor(() => expect(requestedPendingContents).toBe(true));
await waitFor(() =>
expect(
Object.values(store.getState().api.queries).filter((query) => query.status === 'pending'),
).toHaveLength(1),
);
try {
await waitFor(() => expect(screen.queryByRole('heading', { name: '/b.json' })).not.toBeInTheDocument());
expect(screen.queryByRole('heading', { name: `Commit ${next.revision}` })).not.toBeInTheDocument();
} finally {
await act(async () => finishResponse());
}

await screen.findByRole('heading', { name: `Commit ${next.revision}` });
if (next.revision === '4') {
expect(screen.getByRole('heading', { name: '/c.json' })).toBeInTheDocument();
expect(screen.queryByText('Upstream', { exact: true })).not.toBeInTheDocument();
} else {
expect(screen.queryByRole('heading', { name: '/b.json' })).not.toBeInTheDocument();
expect(screen.getByText(upstreamB, { exact: true })).toBeInTheDocument();
}
});

it('shows the requested commit when the selected file was last changed in an earlier revision', async () => {
renderWithProviders(<CommitViewPage />);

Expand Down
Loading