Skip to content
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
10 changes: 10 additions & 0 deletions .changeset/31025-delete-package-contents.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/i18n': patch
---

feat(i18n): Studio strings for what the Delete package dialog removes

Clause-②: yes (widening)
Metadata-protocol: none

The `studio` namespace gains the `engine.packages.detail.delete*` strings (en and zh) the Delete package dialog now draws: its heading for what the package holds, each object's record count (one, other, unavailable), the pending-drafts line, and the warning shown when the author chooses to drop the data, that the tables are dropped permanently and do not go to the recycle bin.
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* The Delete package dialog's list of what goes (objectstack#31025), drawn from
* a {@link PackageRemovalState}; `packageRemovalContents.ts` says where each
* figure is read from.
*/

import * as React from 'react';
import { t, tFormat, translateMetadataType, type SupportedLocale } from './i18n.js';
import type { PackageRemovalState } from './packageRemovalContents.js';

export function PackageRemovalSummary({
state,
draftCount,
dropsTables,
locale,
}: {
state: PackageRemovalState | null;
/** How many pending drafts the delete also removes. */
draftCount: number;
/** The author chose to drop the object tables with their records. */
dropsTables: boolean;
locale: SupportedLocale;
}) {
if (!state) return null;
const objects = state.status === 'ready' ? state.contents.objects : [];
// Nothing is dropped from a package that holds no object; while the list is
// read, or when it could not be read, the line stands.
const showPermanent = dropsTables && !(state.status === 'ready' && objects.length === 0);
return (
<div className="grid gap-2 text-sm" data-testid="pkg-detail-delete-contents">
<p className="font-medium">{t('engine.packages.detail.deleteContentsHeading', locale)}</p>
{state.status === 'loading' && (
<p className="text-xs text-muted-foreground" data-testid="pkg-detail-delete-contents-loading">
{t('engine.packages.detail.deleteContentsLoading', locale)}
</p>
)}
{state.status === 'failed' && (
<p className="text-xs text-muted-foreground" data-testid="pkg-detail-delete-contents-failed">
{t('engine.packages.detail.deleteContentsFailed', locale)}
</p>
)}
{state.status === 'ready' && (
<ul className="grid max-h-48 gap-1 overflow-y-auto rounded-md border p-2 text-xs">
{objects.map((o) => (
<li
key={o.name}
className="flex items-baseline justify-between gap-3"
data-testid={`pkg-detail-delete-object-${o.name}`}
>
<span className="min-w-0 break-words">
{o.label}
{o.label !== o.name && <span className="ml-1 font-mono text-muted-foreground">{o.name}</span>}
</span>
<span className="shrink-0 tabular-nums text-muted-foreground">
{recordCountText(state.counts[o.name], locale)}
</span>
</li>
))}
{state.contents.others.map((o) => (
<li
key={o.type}
className="flex items-baseline justify-between gap-3"
data-testid={`pkg-detail-delete-type-${o.type}`}
>
<span className="min-w-0 break-words">{translateMetadataType(o.type, locale)}</span>
<span className="shrink-0 tabular-nums text-muted-foreground">{o.count}</span>
</li>
))}
{objects.length === 0 && state.contents.others.length === 0 && (
<li className="text-muted-foreground">{t('engine.packages.detail.deleteContentsEmpty', locale)}</li>
)}
</ul>
)}
{draftCount > 0 && (
<p className="text-xs text-muted-foreground" data-testid="pkg-detail-delete-drafts">
{draftCount === 1
? tFormat('engine.packages.detail.deleteDraftsOne', locale, { count: draftCount })
: tFormat('engine.packages.detail.deleteDraftsOther', locale, { count: draftCount })}
</p>
)}
{showPermanent && (
<p
role="alert"
className="rounded-md border border-destructive/50 bg-destructive/10 p-2 text-xs text-destructive"
data-testid="pkg-detail-delete-permanent"
>
{t('engine.packages.detail.deletePermanent', locale)}
</p>
)}
</div>
);
}

function recordCountText(count: number | null | undefined, locale: SupportedLocale): string {
if (count === undefined) return '…';
if (count === null) return t('engine.packages.detail.deleteRecordsUnknown', locale);
return count === 1
? tFormat('engine.packages.detail.deleteRecordsOne', locale, { count })
: tFormat('engine.packages.detail.deleteRecordsOther', locale, { count });
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,24 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';

// The page reaches both through a dynamic `import()`; loaded here so the first
// load is paid at collection, never inside a clocked case.
import '@objectstack/formula';
import '@objectstack/lint';
import { PackageDetailSheet, PackagesPage, type InstalledPackageRow } from './PackagesPage';

/**
* objectstack#31025 — the data source the Delete dialog counts each object's
* rows through. `null` (no provider), as before, unless a test installs one.
*/
let adapter: { find: ReturnType<typeof vi.fn> } | null = null;
vi.mock('@object-ui/react', async (importOriginal) => ({
...(await importOriginal<typeof import('@object-ui/react')>()),
useAdapter: () => adapter,
}));
/** What `GET /packages/:id/export` answers; a test may replace it. */
let exportAnswer: unknown;

const PKG_ID = 'com.acme.crm';
const PKG_NAME = 'Acme CRM';
const PKG: InstalledPackageRow = {
Expand Down Expand Up @@ -72,6 +88,8 @@ function respond(body: unknown, status = 200) {

beforeEach(() => {
calls = [];
adapter = null;
exportAnswer = { success: true, data: { id: PKG_ID, name: PKG_ID, version: '1.0.0' } };
duplicateAnswer = { success: true, data: { success: true, copiedCount: 3, failedCount: 0 } };
vi.stubGlobal(
'fetch',
Expand All @@ -91,6 +109,9 @@ beforeEach(() => {
if (input.endsWith('/duplicate')) {
return respond(duplicateAnswer);
}
if (input === `/api/v1/packages/${PKG_ID}/export` && method === 'GET') {
return respond(exportAnswer, (exportAnswer as { success?: boolean }).success === false ? 500 : 200);
}
return respond({ success: true, data: {} });
}),
);
Expand Down Expand Up @@ -430,3 +451,110 @@ describe('Console Packages page — a delete there stays on the page (objectui#1
expect(screen.queryByTestId('elsewhere')).toBeNull();
});
});

describe('PackageDetailSheet — the Delete dialog states what goes (objectstack#31025)', () => {
/** The export door's answer for a package with two objects and other items. */
const EXPORT = {
success: true,
data: {
id: PKG_ID,
name: PKG_ID,
version: '1.0.0',
objects: [
{ name: 'acme_lead', label: 'Lead', fields: {} },
{ name: 'acme_deal', label: 'Deal', fields: {} },
],
views: [{ name: 'acme_lead_list' }],
viewItems: [{ name: 'acme_deal_board' }],
dashboards: [{ name: 'acme_home' }],
flows: [{ name: 'acme_assign' }, { name: 'acme_notify' }],
objectExtensions: [{ extend: 'sys_user' }],
withheldMaps: [{ type: 'connector', name: 'acme_api', path: 'providerConfig.headers' }],
},
};
const TOTALS: Record<string, number | undefined> = { acme_lead: 1234, acme_deal: 1 };

beforeEach(() => {
exportAnswer = EXPORT;
adapter = { find: vi.fn(async (name: string) => ({ data: [], total: TOTALS[name] })) };
});

it('lists each object with the rows the data list counts, and other items by type', async () => {
renderSheet();
const dialog = await openDeleteDialog();
const lead = await within(dialog).findByTestId('pkg-detail-delete-object-acme_lead');
await waitFor(() => expect(lead).toHaveTextContent('1234 records'));
expect(lead).toHaveTextContent('Lead');
expect(within(dialog).getByTestId('pkg-detail-delete-object-acme_deal')).toHaveTextContent('1 record');
// Each count is the data list asked for no rows, by object name.
expect(adapter!.find.mock.calls.map((c) => c.slice(0, 2))).toEqual([
['acme_lead', { $top: 0 }],
['acme_deal', { $top: 0 }],
]);
// Counted by type: `views` and `viewItems` are both views.
expect(within(dialog).getByTestId('pkg-detail-delete-type-view')).toHaveTextContent('2');
expect(within(dialog).getByTestId('pkg-detail-delete-type-dashboard')).toHaveTextContent('1');
expect(within(dialog).getByTestId('pkg-detail-delete-type-flow')).toHaveTextContent('2');
expect(within(dialog).getByTestId('pkg-detail-delete-type-object_extension')).toHaveTextContent('1');
// The withheld-map positions are not items of the package.
expect(within(dialog).queryByTestId('pkg-detail-delete-type-withheldMaps')).toBeNull();
// The pending drafts the sheet read go too.
expect(within(dialog).getByTestId('pkg-detail-delete-drafts')).toHaveTextContent('2 unpublished drafts');
// Reading what goes writes nothing.
expect(writes()).toEqual([]);
});

it('states the permanent drop only once the author chooses to drop the data', async () => {
renderSheet();
const dialog = await openDeleteDialog();
await within(dialog).findByTestId('pkg-detail-delete-object-acme_lead');
expect(within(dialog).queryByTestId('pkg-detail-delete-permanent')).toBeNull();
fireEvent.click(within(dialog).getByTestId('pkg-detail-delete-mode-structure'));
expect(within(dialog).queryByTestId('pkg-detail-delete-permanent')).toBeNull();
fireEvent.click(within(dialog).getByTestId('pkg-detail-delete-mode-all'));
expect(within(dialog).getByTestId('pkg-detail-delete-permanent')).toHaveTextContent(
'Dropped tables do not go to the recycle bin',
);
fireEvent.click(within(dialog).getByTestId('pkg-detail-delete-mode-structure'));
expect(within(dialog).queryByTestId('pkg-detail-delete-permanent')).toBeNull();
});

it('a package with no object drops no table, so the permanent line is not drawn', async () => {
exportAnswer = { success: true, data: { id: PKG_ID, name: PKG_ID, version: '1.0.0', flows: [{ name: 'f' }] } };
renderSheet();
const dialog = await openDeleteDialog();
await within(dialog).findByTestId('pkg-detail-delete-type-flow');
fireEvent.click(within(dialog).getByTestId('pkg-detail-delete-mode-all'));
expect(within(dialog).queryByTestId('pkg-detail-delete-permanent')).toBeNull();
});

it('a count the data list does not answer is unknown, never 0', async () => {
adapter = { find: vi.fn(async (name: string) => (name === 'acme_lead' ? { data: [] } : Promise.reject(new Error('x')))) };
renderSheet();
const dialog = await openDeleteDialog();
const lead = await within(dialog).findByTestId('pkg-detail-delete-object-acme_lead');
await waitFor(() => expect(lead).toHaveTextContent('Record count unavailable'));
await waitFor(() =>
expect(within(dialog).getByTestId('pkg-detail-delete-object-acme_deal')).toHaveTextContent(
'Record count unavailable',
),
);
expect(lead).not.toHaveTextContent(/\b0 records/);
});

it('an export the server refuses is said, and the delete can still be confirmed', async () => {
exportAnswer = { success: false, error: { code: 'INTERNAL_ERROR', message: 'boom' } };
renderSheet();
const dialog = await openDeleteDialog();
await within(dialog).findByTestId('pkg-detail-delete-contents-failed');
fireEvent.click(within(dialog).getByTestId('pkg-detail-delete-mode-all'));
// Not known to hold no object, so the permanent line stands.
expect(within(dialog).getByTestId('pkg-detail-delete-permanent')).toBeInTheDocument();
fireEvent.change(within(dialog).getByTestId('pkg-detail-delete-name-input'), {
target: { value: PKG_NAME },
});
fireEvent.click(within(dialog).getByTestId('pkg-detail-delete-confirm'));
await waitFor(() => expect(deletes()).toHaveLength(1));
expect(deletes()[0].url).toBe(`/api/v1/packages/${PKG_ID}`);
});
});
56 changes: 56 additions & 0 deletions ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ import {
import { useMetadataLocale, t, tFormat } from './i18n.js';
import { useMetadataClient } from './useMetadata.js';
import { PackageFormDialog } from './PackageFormDialog.js';
import { readPackageRemovalContents, type PackageRemovalState } from './packageRemovalContents.js';
import { PackageRemovalSummary } from './PackageRemovalSummary.js';
import { useAdapter } from '@object-ui/react';
import { PageHeader } from '../../layout/PageHeader.js';
import { errorCodeIs } from '@object-ui/types';
import { readEnvelopeFailureText } from '../../utils/apiErrorEnvelope.js';
Expand Down Expand Up @@ -554,6 +557,15 @@ export function PackageDetailSheet({
const [disableOpen, setDisableOpen] = React.useState(false);
const [deleteMode, setDeleteMode] = React.useState<DeleteMode>('');
const [deleteTyped, setDeleteTyped] = React.useState('');
// objectstack#31025 — what the delete removes, read when its dialog opens.
const [removal, setRemoval] = React.useState<PackageRemovalState | null>(null);
// The count reads key on the package id alone (AGENTS.md #10): the adapter
// is read through a ref, kept current from an effect.
const adapter = useAdapter();
const adapterRef = React.useRef(adapter);
React.useEffect(() => {
adapterRef.current = adapter;
});
const [discardOpen, setDiscardOpen] = React.useState(false);
const [dupOpen, setDupOpen] = React.useState(false);
const [dupName, setDupName] = React.useState('');
Expand Down Expand Up @@ -590,6 +602,43 @@ export function PackageDetailSheet({
};
}, [open, pkg?.manifest.id]);

// objectstack#31025 — the Delete dialog states what goes: the export door's
// items (each object with the rows the data list counts), read each time
// the dialog opens (`openDelete` marks it loading).
const removalPackageId = deleteOpen ? pkg?.manifest.id : undefined;
React.useEffect(() => {
if (!removalPackageId) return;
let cancelled = false;
apiJson<unknown>(`${API}/${encodeURIComponent(removalPackageId)}/export`)
.then((manifest) => {
if (cancelled) return;
const contents = readPackageRemovalContents(manifest);
setRemoval({ status: 'ready', contents, counts: {} });
const source = adapterRef.current;
for (const { name } of contents.objects) {
const counted: Promise<number | null> =
source && typeof source.find === 'function'
? source
.find(name, { $top: 0 })
.then((r) => (typeof r?.total === 'number' ? r.total : null))
.catch(() => null)
: Promise.resolve(null);
void counted.then((count) => {
if (cancelled) return;
setRemoval((prev) =>
prev?.status === 'ready' ? { ...prev, counts: { ...prev.counts, [name]: count } } : prev,
);
});
}
})
.catch(() => {
if (!cancelled) setRemoval({ status: 'failed' });
});
return () => {
cancelled = true;
};
}, [removalPackageId]);

if (!pkg) return null;
const id = pkg.manifest.id;
const enabled = pkg.enabled !== false && pkg.status !== 'disabled';
Expand Down Expand Up @@ -813,6 +862,7 @@ export function PackageDetailSheet({
startAction(() => {
setDeleteMode('');
setDeleteTyped('');
setRemoval({ status: 'loading' });
setDeleteOpen(true);
});

Expand Down Expand Up @@ -1290,6 +1340,12 @@ export function PackageDetailSheet({
</Label>
</div>
</RadioGroup>
<PackageRemovalSummary
state={removal}
draftCount={drafts?.length ?? 0}
dropsTables={deleteMode === 'all'}
locale={locale}
/>
<div className="grid gap-1.5">
<Label htmlFor={`${fieldId}-delete-name`} className="text-sm font-medium">
{tFormat('engine.packages.detail.deleteTypeName', locale, { name: displayName })}
Expand Down
Loading
Loading