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
14 changes: 14 additions & 0 deletions .changeset/37359-import-wizard-shared-mapping.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@object-ui/plugin-grid': patch
'@object-ui/i18n': patch
'@object-ui/app-shell': patch
---

feat(plugin-grid, app-shell): an administrator can save the import wizard's column mapping as a shared mapping, and Manage opens the object's mapping list

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

`ImportWizard` takes two new optional props. `onSaveSharedMapping(draft)` is the host's door for saving a shared `mapping` item: when it is passed, the preview step offers "Save as shared mapping", which asks for a name and sends the columns mapped by hand (each column's header → its field), the write mode and, for update or upsert, the match fields as `upsertKey`, with `sourceFormat: 'csv'`. The other import options stay with the import that set them. A mapped column whose header is blank or shared with another column cannot be saved, because the import door finds a column by its header; the save says which headers to rename. The saved mapping joins the Saved mapping list at once. `onManageMappings()` puts "Manage" beside the Saved mapping list. Without the props nothing changes. `SavedMapping` and `SharedMappingDraft` are exported as types. New `grid.import.*` strings in every language pack.

In the app, the list page passes both doors only to the reader who may share a view (an administrator holding `manage_metadata`), and never to the identity import. The save probes the name first and refuses one a mapping already holds; then it saves the mapping into a package of the app and publishes it at once. When no package of the app can be had the person picks or creates one, and a cancelled pick writes nothing; a system app is refused. Manage opens Studio's mapping list across every package, narrowed to the object by a new `targetObject` list param, shown as a chip whose × shows every object again.
17 changes: 17 additions & 0 deletions ui/packages/app-shell/src/views/ObjectView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ import { viewSaveRefusalText } from './viewSaveRefusal.js';
import { listDraftPreference, listDraftScope, useListDraft } from './listDraftStore.js';
import { useObjectViewViewCrud, useRuntimeCreateApp } from './objectViewViewCrud.js';
import { mayManageViews, useViewSharing } from './objectViewViewSharing.js';
import { sharedMappingDoors } from './objectViewSharedMapping.js';
import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js';
import {
PERSONAL_VIEW_OBJECT,
Expand Down Expand Up @@ -1616,6 +1617,22 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
<IdentityImportResultExtra serverResult={res?.serverResult} />
),
} : {})}
{...sharedMappingDoors({
// objectstack#37359 — a shared mapping is metadata every
// importer of the object picks: only the reader who may
// share a view saves one, into a package of the app or
// the one they pick when asked (a cancelled ask writes
// nothing), and Manage opens the object's mapping list.
canManageViews,
identityImport: identityImportEnabled,
metadataClient,
dataSource,
objectName: objectDef.name,
app: sharingApp,
t,
navigate,
closeWizard: () => setShowImport(false),
})}
onComplete={(result) => {
refreshData();
const ok = result.importedRows;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#37359 — the import wizard's Manage opens the mapping list
* narrowed to one object (`?targetObject=`). The real page runs, in the
* environment scope (every package's rows); only the metadata client is stubbed. Pinned, each with its control:
*
* - the mapping list with `targetObject` shows that object's mappings only,
* under a chip naming the object;
* - the chip's × shows every object again and drops the param;
* - a type whose rows name no object is not narrowed and draws no chip.
*/
import '@testing-library/jest-dom/vitest';
import * as React from 'react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, cleanup, screen, fireEvent, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import '@object-ui/plugin-detail';
import '@objectstack/lint';

const MAPPINGS: Record<string, unknown>[] = [
{ name: 'lead_suppliers', label: 'Lead suppliers', targetObject: 'crm_lead', fieldMapping: [] },
{ name: 'lead_fair', label: 'Lead fair', targetObject: 'crm_lead', fieldMapping: [] },
{ name: 'account_feed', label: 'Account feed', targetObject: 'crm_account', fieldMapping: [] },
];
const SKILLS: Record<string, unknown>[] = [
{ name: 'triage', label: 'Triage desk' },
{ name: 'billing', label: 'Billing' },
];

const CLIENT = { list: async (type: string) => (type === 'mapping' ? MAPPINGS : type === 'skill' ? SKILLS : []) };
const ENTRIES = [
{ type: 'mapping', label: 'Field Mapping', allowEnvironmentOverlay: false, allowRuntimeCreate: true },
{ type: 'skill', label: 'Skill', allowEnvironmentOverlay: false, allowRuntimeCreate: true },
];

vi.mock('./useMetadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useMetadataClient: () => CLIENT,
useMetadataTypes: () => ({ loading: false, error: null, entries: ENTRIES }),
}));
vi.mock('./i18n', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useMetadataLocale: () => 'en-US',
}));
vi.mock('../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true }));
vi.mock('../../hooks/useTenancyPosture', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useTenancyPosture: () => 'single',
}));

import { MetadataResourceListPage } from './ResourceListPage';
import { registerBuiltinAnchors } from './anchors';
import '../../services/builtinComponents';

registerBuiltinAnchors();

afterEach(() => {
cleanup();
});

function LocationProbe() {
const location = useLocation();
return <output data-testid="location">{location.pathname + location.search}</output>;
}

function mount(at: string) {
return render(
<MemoryRouter initialEntries={[at]}>
<Routes>
<Route path="/apps/:appName/metadata/:type" element={<MetadataResourceListPage />} />
</Routes>
<LocationProbe />
</MemoryRouter>,
);
}

async function rowNames(): Promise<string[]> {
await screen.findByRole('table');
return screen
.getAllByTestId(/^metadata-row-(?!api-name$|source$|lock$)/)
.map((el) => el.getAttribute('data-testid')!.replace('metadata-row-', ''))
.sort();
}

describe('the mapping list narrowed to one object (objectstack#37359)', () => {
it('shows that object’s mappings under a chip naming it', async () => {
mount('/apps/setup/metadata/mapping?scope=environment&targetObject=crm_lead');
await waitFor(async () => expect(await rowNames()).toEqual(['lead_fair', 'lead_suppliers']));
expect(screen.getByTestId('metadata-list-target-object')).toHaveTextContent('crm_lead');
});

it('the chip’s × shows every object again and drops the param', async () => {
mount('/apps/setup/metadata/mapping?scope=environment&targetObject=crm_lead');
fireEvent.click(await screen.findByTestId('metadata-list-target-object'));
await waitFor(async () => expect(await rowNames()).toEqual(['account_feed', 'lead_fair', 'lead_suppliers']));
expect(screen.getByTestId('location').textContent).toBe('/apps/setup/metadata/mapping?scope=environment');
expect(screen.queryByTestId('metadata-list-target-object')).not.toBeInTheDocument();
});

it('control: without the param every mapping is listed and no chip is drawn', async () => {
mount('/apps/setup/metadata/mapping?scope=environment');
await waitFor(async () => expect(await rowNames()).toEqual(['account_feed', 'lead_fair', 'lead_suppliers']));
expect(screen.queryByTestId('metadata-list-target-object')).not.toBeInTheDocument();
});

it('a type whose rows name no object is not narrowed and draws no chip', async () => {
mount('/apps/setup/metadata/skill?scope=environment&targetObject=crm_lead');
await waitFor(async () => expect(await rowNames()).toEqual(['billing', 'triage']));
expect(screen.queryByTestId('metadata-list-target-object')).not.toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

import * as React from 'react';
import { Link, Navigate, useLocation, useNavigate, useNavigationType, useParams, useSearchParams } from 'react-router-dom';
import { Plus, Search, RefreshCw, AlertTriangle, Lock, Copy } from 'lucide-react';
import { Plus, Search, RefreshCw, AlertTriangle, Lock, Copy, X } from 'lucide-react';
import {
Button,
NeutralIconTile,
Expand Down Expand Up @@ -795,6 +795,11 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string
matches: (row, q) => matchesQuery(row.item, q, searchableFields),
source: sourceOf,
...(showCustomizedFilter && !studioList ? { customized: (row: ItemRow) => markOf(row) !== null } : {}),
// objectstack#37359 — a type whose rows name the object they serve is
// narrowed to one object by `?targetObject=` (the import wizard's Manage).
...(TARGET_OBJECT_TYPES.has(type)
? { targetObject: (row: ItemRow) => (typeof row.item.targetObject === 'string' ? row.item.targetObject : undefined) }
: {}),
// Only a KNOWN state filters: while the ledger is unread or unreadable, no
// item is either active or inactive to this filter.
...(activation
Expand All @@ -807,6 +812,22 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string
: {}),
};
const filtered = applyListState(scopedItems, listState, rowReader, locale);
// objectstack#37359 — the object the list is narrowed to, shown as a chip
// whose × shows every object again.
const narrowedObject = rowReader.targetObject ? listState.targetObject : undefined;
const targetObjectChip = narrowedObject ? (
<Button
size="sm"
variant="secondary"
className="h-8 gap-1.5 rounded-full px-3 text-xs"
onClick={() => updateListState({ targetObject: undefined })}
aria-label={tFormat('engine.list.targetObject.clear', locale, { object: narrowedObject })}
data-testid="metadata-list-target-object"
>
{tFormat('engine.list.targetObject', locale, { object: narrowedObject })}
<X className="h-3 w-3" aria-hidden="true" />
</Button>
) : null;
// objectstack#36903 — a host that says what its empty list means (the
// package-less scope, whose list is its source filter's narrowing of the
// environment's rows) reads an unsearched, empty list as empty, not as a
Expand Down Expand Up @@ -1485,6 +1506,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string
data-testid="metadata-list-search"
/>
</div>
{targetObjectChip}
{activation && (
<Select value={statusFilter} onValueChange={(v) => updateListState({ status: v as typeof statusFilter })}>
<SelectTrigger className="h-8 w-auto gap-1.5 text-sm" data-testid="catalog-status-filter">
Expand Down Expand Up @@ -1538,6 +1560,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string
data-testid="metadata-list-search"
/>
</div>
{targetObjectChip}
<Select value={sourceFilter} onValueChange={(v) => updateListState({ source: v as MetadataListState['source'] })}>
{/* Under Setup the source select is a filter chip (objectui#12606). */}
<SelectTrigger
Expand Down Expand Up @@ -1917,6 +1940,12 @@ const CHANGED_COLUMN = '__changed';
const SOURCE_COLUMN = '__source';
const CONTROLS_COLUMN = '__controls';

/**
* objectstack#37359 — the types whose rows name the object they serve in a
* `targetObject` key, which `?targetObject=` narrows the list to.
*/
const TARGET_OBJECT_TYPES: ReadonlySet<string> = new Set(['mapping']);

/** Rows per page of the list. */
const LIST_PAGE_SIZE = 50;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#37359 — the list state's object narrowing (`?targetObject=`):
* its codec, and that it narrows only a reader that names a row's object.
*/
import { describe, it, expect } from 'vitest';
import {
DEFAULT_LIST_STATE,
LIST_TARGET_OBJECT_PARAM,
applyListState,
decodeListState,
writeListState,
type ListRowReader,
} from './metadataListState';

interface Row { name: string; targetObject?: string }
const ROWS: Row[] = [
{ name: 'lead_a', targetObject: 'crm_lead' },
{ name: 'account_a', targetObject: 'crm_account' },
{ name: 'lead_b', targetObject: 'crm_lead' },
];
const base: ListRowReader<Row> = {
name: (r) => r.name,
label: () => undefined,
matches: (r, q) => r.name.includes(q),
source: () => 'runtime',
};
const withObject: ListRowReader<Row> = { ...base, targetObject: (r) => r.targetObject };

describe('the list state’s object narrowing (objectstack#37359)', () => {
it('round-trips through the address, and a blank value reads as none', () => {
const state = decodeListState(new URLSearchParams(`${LIST_TARGET_OBJECT_PARAM}=crm_lead&package=crm`));
expect(state.targetObject).toBe('crm_lead');
const written = writeListState(new URLSearchParams('package=crm'), state);
expect(written.get(LIST_TARGET_OBJECT_PARAM)).toBe('crm_lead');
expect(written.get('package')).toBe('crm');
expect(decodeListState(new URLSearchParams(`${LIST_TARGET_OBJECT_PARAM}=%20`))).toEqual(DEFAULT_LIST_STATE);
expect(writeListState(written, { ...state, targetObject: undefined }).has(LIST_TARGET_OBJECT_PARAM)).toBe(false);
});

it('narrows a reader that names the row’s object', () => {
const state = { ...DEFAULT_LIST_STATE, targetObject: 'crm_lead' };
expect(applyListState(ROWS, state, withObject, 'en').map((r) => r.name)).toEqual(['lead_a', 'lead_b']);
});

it('control: a reader that names no object is not narrowed', () => {
const state = { ...DEFAULT_LIST_STATE, targetObject: 'crm_lead' };
expect(applyListState(ROWS, state, base, 'en').map((r) => r.name)).toEqual(['account_a', 'lead_a', 'lead_b']);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ export const LIST_CUSTOMIZED_PARAM = 'customized';
export const LIST_STATUS_PARAM = 'status';
/** The sort: a key, `-` before it for descending; absent = {@link DEFAULT_LIST_SORT}. */
export const LIST_SORT_PARAM = 'sort';
/**
* objectstack#37359 — the object a list of an object-bound type is narrowed to:
* the rows whose `targetObject` is that object (the import wizard's Manage
* opens the mapping list this way). Absent = every object. Only a type whose
* rows name a `targetObject` is narrowed ({@link ListRowReader.targetObject}).
*/
export const LIST_TARGET_OBJECT_PARAM = 'targetObject';

/** Every param the list state writes. */
export const LIST_STATE_PARAMS: readonly string[] = [
Expand All @@ -47,6 +54,7 @@ export const LIST_STATE_PARAMS: readonly string[] = [
LIST_CUSTOMIZED_PARAM,
LIST_STATUS_PARAM,
LIST_SORT_PARAM,
LIST_TARGET_OBJECT_PARAM,
];

export type ListSourceFilter = 'all' | 'artifact' | 'runtime';
Expand Down Expand Up @@ -78,6 +86,8 @@ export interface MetadataListState {
customizedOnly: boolean;
status: ListStatusFilter;
sort: ListSort;
/** objectstack#37359 — the object the rows are narrowed to ({@link LIST_TARGET_OBJECT_PARAM}); absent = every object. */
targetObject?: string;
}

export const DEFAULT_LIST_STATE: MetadataListState = {
Expand Down Expand Up @@ -114,12 +124,14 @@ export function decodeListSort(raw: string | null | undefined): ListSort {
export function decodeListState(params: URLSearchParams): MetadataListState {
const source = params.get(LIST_SOURCE_PARAM);
const status = params.get(LIST_STATUS_PARAM);
const targetObject = params.get(LIST_TARGET_OBJECT_PARAM)?.trim();
return {
query: params.get(LIST_QUERY_PARAM) ?? '',
source: source === 'artifact' || source === 'runtime' ? source : 'all',
customizedOnly: params.get(LIST_CUSTOMIZED_PARAM) === '1',
status: status === 'active' || status === 'inactive' ? status : 'all',
sort: decodeListSort(params.get(LIST_SORT_PARAM)),
...(targetObject ? { targetObject } : {}),
};
}

Expand All @@ -136,6 +148,7 @@ export function writeListState(params: URLSearchParams, state: MetadataListState
put(LIST_CUSTOMIZED_PARAM, state.customizedOnly ? '1' : '');
put(LIST_STATUS_PARAM, state.status === 'all' ? '' : state.status);
put(LIST_SORT_PARAM, encodeListSort(state.sort));
put(LIST_TARGET_OBJECT_PARAM, state.targetObject ?? '');
return next;
}

Expand Down Expand Up @@ -181,6 +194,12 @@ export interface ListRowReader<R> {
* every row has none and the `changed` sort is by name.
*/
changedAt?: (row: R) => string | undefined;
/**
* objectstack#37359 — the object the row is bound to (a mapping's
* `targetObject`). Absent, the type's rows name no object and
* {@link MetadataListState.targetObject} narrows nothing.
*/
targetObject?: (row: R) => string | undefined;
}

const COLLATORS = new Map<string, Intl.Collator>();
Expand Down Expand Up @@ -220,6 +239,7 @@ export function applyListState<R>(
const kept = rows.filter((row) => {
if (state.query && !read.matches(row, state.query)) return false;
if (state.source !== 'all' && read.source(row) !== state.source) return false;
if (state.targetObject && read.targetObject && read.targetObject(row) !== state.targetObject) return false;
if (state.customizedOnly && read.customized && !read.customized(row)) return false;
if (state.status !== 'all' && read.active) {
const active = read.active(row);
Expand Down
Loading
Loading