Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Show read-only remote-synced tables as read-only on the data model pages (#84934)

Alexander Polyankin5d9132409126
diff --git a/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts b/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts
index 54a2327ee27..9f96d6d9f04 100644
--- a/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts
@@ -825,6 +825,7 @@ describe("scenarios > data studio > datamodel", () => {
schemaId: SAMPLE_DB_SCHEMA_ID,
tableId: ORDERS_ID,
});
+ TableSection.getNameInput().should("have.attr", "readonly");
verifyReadOnlyTablePage({ hasTabs: true });
});
diff --git a/frontend/src/metabase-types/api/mocks/table.ts b/frontend/src/metabase-types/api/mocks/table.ts
index ba1e900db64..a9b0cda173f 100644
--- a/frontend/src/metabase-types/api/mocks/table.ts
+++ b/frontend/src/metabase-types/api/mocks/table.ts
@@ -32,6 +32,7 @@ export const createMockTable = (opts?: Partial<Table>): Table => {
view_count: 0,
collection_id: null,
is_published: false,
+ can_write: true,
...opts,
};
};
diff --git a/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/TableAttributesEditSingle/TableAttributesEditSingle.tsx b/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/TableAttributesEditSingle/TableAttributesEditSingle.tsx
index 9fa7aef84c6..7c39279797e 100644
--- a/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/TableAttributesEditSingle/TableAttributesEditSingle.tsx
+++ b/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/TableAttributesEditSingle/TableAttributesEditSingle.tsx
@@ -157,6 +157,7 @@ export function TableAttributesEditSingle({ table, onUpdate }: Props) {
};
const isOwnerSpecified = table.owner_email || table.owner_user_id;
+ const readOnly = !table.can_write;
return (
<TableSectionGroup title={t`Attributes`}>
@@ -165,6 +166,7 @@ export function TableAttributesEditSingle({ table, onUpdate }: Props) {
email={table.owner_email}
label={t`Owner`}
userId={isOwnerSpecified ? table.owner_user_id : "unknown"}
+ readOnly={readOnly}
onEmailChange={handleOwnerEmailChange}
onUserIdChange={handleOwnerUserIdChange}
className={S.gridLabelInput}
@@ -177,6 +179,7 @@ export function TableAttributesEditSingle({ table, onUpdate }: Props) {
<LayerInput
value={table.data_layer ?? "hidden"}
+ readOnly={readOnly}
onChange={handleLayerChange}
classNames={{ input: S.input, label: S.label }}
className={S.gridLabelInput}
@@ -184,6 +187,7 @@ export function TableAttributesEditSingle({ table, onUpdate }: Props) {
<EntityTypeInput
value={table.entity_type ?? "entity/GenericTable"}
+ readOnly={readOnly}
onChange={handleEntityTypeChange}
classNames={{ input: S.input, label: S.label }}
className={S.gridLabelInput}
@@ -191,6 +195,7 @@ export function TableAttributesEditSingle({ table, onUpdate }: Props) {
<DataSourceInput
disabled={table.data_source === "metabase-transform"}
+ readOnly={readOnly}
value={table.data_source ?? "unknown"}
onChange={handleDataSourceChange}
classNames={{ input: S.input, label: S.label }}
diff --git a/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/TableSection.tsx b/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/TableSection.tsx
index fa8b5e920d2..ae8e7409712 100644
--- a/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/TableSection.tsx
+++ b/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/TableSection.tsx
@@ -76,6 +76,7 @@ const TableSectionBase = ({
const [modalType, setModalType] = useState<TableModalType>();
const [isSorting, setIsSorting] = useState(false);
const hasFields = Boolean(table.fields && table.fields.length > 0);
+ const readOnly = !table.can_write;
const isLibraryEnabled = PLUGIN_LIBRARY.isEnabled;
const isDependencyGraphEnabled = PLUGIN_DEPENDENCIES.isEnabled;
const remoteSyncReadOnly = useSelector(
@@ -160,6 +161,7 @@ const TableSectionBase = ({
nameIcon="table2"
nameMaxLength={254}
namePlaceholder={t`Give this table a name`}
+ readOnly={readOnly}
onNameChange={handleNameChange}
onDescriptionChange={handleDescriptionChange}
/>
@@ -216,7 +218,7 @@ const TableSectionBase = ({
<Tabs.Panel value="field">
<Stack gap="lg">
<Group gap="lg" justify="flex-start" wrap="nowrap">
- {!isSorting && hasFields && (
+ {!isSorting && hasFields && !readOnly && (
<ResponsiveButton
icon="sort_arrows"
showLabel
diff --git a/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/tests/common.unit.spec.tsx b/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/tests/common.unit.spec.tsx
index 845c0d5bfdc..c86586c226b 100644
--- a/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/tests/common.unit.spec.tsx
+++ b/frontend/src/metabase/data-studio/data-model/pages/DataModel/TableSection/tests/common.unit.spec.tsx
@@ -7,9 +7,16 @@ import {
createMockSegment,
createMockTable,
} from "metabase-types/api/mocks";
+import { createOrdersQuantityField } from "metabase-types/api/mocks/presets";
import { setup } from "./setup";
+function getShownListboxes() {
+ return screen
+ .queryAllByRole("listbox")
+ .filter((listbox) => !listbox.closest('[data-hidden="true"]'));
+}
+
describe("TableSection", () => {
it("should render the link to explore this table in the query builder", () => {
const table = createMockTable();
@@ -140,4 +147,73 @@ describe("TableSection", () => {
expect(screen.getByText("No segments yet")).toBeInTheDocument();
});
});
+
+ describe("read-only table", () => {
+ const READ_ONLY_TABLE = createMockTable({
+ db: createMockDatabase(),
+ can_write: false,
+ fields: [createOrdersQuantityField()],
+ });
+
+ it("shows the details of a table that cannot be written as read-only", async () => {
+ setup({ table: READ_ONLY_TABLE });
+
+ expect(
+ screen.getByPlaceholderText("Give this table a name"),
+ ).toHaveAttribute("readonly");
+ expect(
+ screen.getByPlaceholderText("Give this table a description"),
+ ).toHaveAttribute("readonly");
+ await userEvent.click(
+ screen.getByPlaceholderText("Pick someone, or type an email"),
+ );
+ expect(getShownListboxes()).toHaveLength(0);
+ await userEvent.click(
+ screen.getByPlaceholderText("Select visibility layer"),
+ );
+ expect(getShownListboxes()).toHaveLength(0);
+ await userEvent.click(screen.getByPlaceholderText("Select entity type"));
+ expect(getShownListboxes()).toHaveLength(0);
+ await userEvent.click(
+ screen.getByPlaceholderText("Select a data source"),
+ );
+ expect(getShownListboxes()).toHaveLength(0);
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "More actions" }),
+ );
+ expect(
+ await screen.findByRole("menuitem", { name: /Re-sync schema/ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("menuitem", { name: /Re-scan field values/ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("menuitem", { name: /Discard cached field values/ }),
+ ).toBeInTheDocument();
+ });
+
+ it("shows the fields of a table that cannot be written as read-only", () => {
+ setup({ table: READ_ONLY_TABLE, activeTab: "field" });
+
+ expect(
+ screen.queryByRole("button", { name: /Sorting/ }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByPlaceholderText("Give this field a name"),
+ ).toBeDisabled();
+ });
+
+ it("keeps the details and fields of a writable table editable", () => {
+ setup({
+ table: { ...READ_ONLY_TABLE, can_write: true },
+ activeTab: "field",
+ });
+
+ expect(screen.getByRole("button", { name: /Sorting/ })).toBeEnabled();
+ expect(
+ screen.getByPlaceholderText("Give this field a name"),
+ ).toBeEnabled();
+ });
+ });
});
diff --git a/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/BehaviorSection.tsx b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/BehaviorSection.tsx
index cc658efbe01..a7bc0166301 100644
--- a/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/BehaviorSection.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/BehaviorSection.tsx
@@ -27,12 +27,14 @@ import { RemappingPicker } from "./RemappingPicker";
type BehaviorSectionBaseProps = {
field: Field;
databaseId: DatabaseId;
+ readOnly?: boolean;
onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
};
const BehaviorSectionBase = ({
field,
databaseId,
+ readOnly,
onTrackMetadataChange,
}: BehaviorSectionBaseProps) => {
const id = getRawTableFieldId(field);
@@ -130,6 +132,7 @@ const BehaviorSectionBase = ({
<TitledSection>
<FieldVisibilityPicker
description={t`Where this field should be displayed`}
+ readOnly={readOnly}
label={t`Visibility`}
value={field.visibility_type}
onChange={handleVisibilityChange}
@@ -137,6 +140,7 @@ const BehaviorSectionBase = ({
<FieldValuesTypePicker
description={t`How this field should be filtered`}
+ readOnly={readOnly}
label={t`Filtering`}
value={field.has_field_values}
onChange={handleFilteringChange}
@@ -146,6 +150,7 @@ const BehaviorSectionBase = ({
<RemappingPicker
database={database}
description={t`Choose to show the original value from the database, or have this field display associated or custom information.`}
+ readOnly={readOnly}
field={field}
label={t`Display values`}
onTrackMetadataChange={onTrackMetadataChange}
@@ -155,6 +160,7 @@ const BehaviorSectionBase = ({
{database != null && canFieldUnfoldJson(field, database) && (
<UnfoldJsonPicker
description={t`Unfold JSON into component fields, where each JSON key becomes a column. You can turn this off if performance is slow.`}
+ readOnly={readOnly}
label={t`Unfold JSON`}
value={isFieldJsonUnfolded(field, database)}
onChange={handleUnfoldJsonChange}
diff --git a/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/RemappingPicker.tsx b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/RemappingPicker.tsx
index c11d5c5c0f5..377a7fd58cb 100644
--- a/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/RemappingPicker.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/RemappingPicker.tsx
@@ -52,10 +52,34 @@ type RemappingPicker = Omit<SelectProps, "data" | "value" | "onChange"> & {
onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
};
+type FkRemappingFieldSelectProps = {
+ error?: boolean;
+ fieldName?: string;
+ readOnly?: boolean;
+};
+
+const FkRemappingFieldSelect = ({
+ error,
+ fieldName,
+ readOnly,
+}: FkRemappingFieldSelectProps) => (
+ <Select
+ data={[{ label: fieldName ?? t`Choose a field`, value: "choose-a-field" }]}
+ dropdownOpened={false}
+ error={error}
+ placeholder={t`Choose a field`}
+ readOnly={readOnly}
+ value="choose-a-field"
+ w="100%"
+ onClick={(event) => event.preventDefault()}
+ />
+);
+
export const RemappingPicker = ({
database,
field,
comboboxProps,
+ readOnly,
onTrackMetadataChange,
...props
}: RemappingPicker) => {
@@ -257,6 +281,7 @@ export const RemappingPicker = ({
onDropdownOpen={() => setIsChoosingDisplayValue(true)}
onDropdownClose={() => setIsChoosingDisplayValue(false)}
onChange={handleDisplayValueChange}
+ readOnly={readOnly}
{...props}
/>
@@ -266,12 +291,19 @@ export const RemappingPicker = ({
<SubInputIllustration />
</Flex>
+ {fkTargetTable && readOnly && (
+ <FkRemappingFieldSelect
+ fieldName={fkRemappingField?.display_name}
+ readOnly
+ />
+ )}
+
{/**
* FieldDataSelector won't work correctly when databases are present
* but fkTargetTable is not. It would go to "schema" step of DataSelector
* which does not exist in FieldDataSelector, hence this conditional render.
*/}
- {fkTargetTable && (
+ {fkTargetTable && !readOnly && (
<FieldDataSelector
databases={[database]}
isInitiallyOpen={isChoosingInitialFkTarget}
@@ -284,20 +316,9 @@ export const RemappingPicker = ({
// come from there rather than from the store.
fields={fkTargetTable.fields ?? []}
triggerElement={
- <Select
- data={[
- {
- label:
- fkRemappingField?.display_name ?? t`Choose a field`,
- value: "choose-a-field",
- },
- ]}
- dropdownOpened={false}
+ <FkRemappingFieldSelect
error={isFkTargetTouched && !fkRemappingField}
- placeholder={t`Choose a field`}
- value="choose-a-field"
- w="100%"
- onClick={(event) => event.preventDefault()}
+ fieldName={fkRemappingField?.display_name}
/>
}
onClose={() => {
@@ -327,16 +348,18 @@ export const RemappingPicker = ({
onClose={() => setIsCustomMappingOpen(false)}
/>
- <Group mt="sm">
- <Button
- size="compact-md"
- variant="transparent"
- disabled={isLoadingFieldValues}
- onClick={() => setIsCustomMappingOpen(true)}
- >
- {t`Edit mapping`}
- </Button>
- </Group>
+ {!readOnly && (
+ <Group mt="sm">
+ <Button
+ size="compact-md"
+ variant="transparent"
+ disabled={isLoadingFieldValues}
+ onClick={() => setIsCustomMappingOpen(true)}
+ >
+ {t`Edit mapping`}
+ </Button>
+ </Group>
+ )}
{hasChanged && <NamingTip mt="lg" />}
</>
diff --git a/frontend/src/metabase/metadata/components/FieldSection/DataSection/DataSection.tsx b/frontend/src/metabase/metadata/components/FieldSection/DataSection/DataSection.tsx
index 29185bcc1f2..812f1e84082 100644
--- a/frontend/src/metabase/metadata/components/FieldSection/DataSection/DataSection.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/DataSection/DataSection.tsx
@@ -22,11 +22,13 @@ import SubInputIllustration from "./illustrations/sub-input.svg?component";
type DataSectionBaseProps = {
field: Field;
+ readOnly?: boolean;
onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
};
const DataSectionBase = ({
field,
+ readOnly,
onTrackMetadataChange,
}: DataSectionBaseProps) => {
const id = getRawTableFieldId(field);
@@ -134,6 +136,7 @@ const DataSectionBase = ({
<Stack>
<Switch
checked={isCasting}
+ disabled={readOnly}
classNames={{
body: S.switchBody,
}}
@@ -146,6 +149,7 @@ const DataSectionBase = ({
<CoercionStrategyPicker
autoFocus={autoFocusCoercionPicker}
baseType={field.base_type}
+ readOnly={readOnly}
dropdownOpened={isCoercionPickerOpen}
value={field.coercion_strategy ?? undefined}
onChange={handleCoercionStrategyChange}
diff --git a/frontend/src/metabase/metadata/components/FieldSection/FieldSection.tsx b/frontend/src/metabase/metadata/components/FieldSection/FieldSection.tsx
index 8f4940d51e0..ede7b07cb9d 100644
--- a/frontend/src/metabase/metadata/components/FieldSection/FieldSection.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/FieldSection.tsx
@@ -40,6 +40,7 @@ const FieldSectionBase = ({
...stackProps
}: FieldSectionBaseProps & StackProps) => {
const id = getRawTableFieldId(field);
+ const readOnly = !table.can_write;
const [updateField] = useUpdateFieldMutation();
const { sendErrorToast, sendSuccessToast, sendUndoToast } =
useMetadataToasts();
@@ -100,6 +101,7 @@ const FieldSectionBase = ({
nameMaxLength={254}
namePlaceholder={t`Give this field a name`}
namePrefix={parent?.display_name}
+ readOnly={readOnly}
onDescriptionChange={handleDescriptionChange}
onNameChange={handleNameChange}
/>
@@ -143,21 +145,25 @@ const FieldSectionBase = ({
<Stack gap="xxl">
<DataSection
field={field}
+ readOnly={readOnly}
onTrackMetadataChange={onTrackMetadataChange}
/>
<MetadataSection
field={field}
table={table}
getFieldHref={getFieldHref}
+ readOnly={readOnly}
onTrackMetadataChange={onTrackMetadataChange}
/>
<BehaviorSection
field={field}
databaseId={table.db_id}
+ readOnly={readOnly}
onTrackMetadataChange={onTrackMetadataChange}
/>
<FormattingSection
field={field}
+ readOnly={readOnly}
onTrackMetadataChange={onTrackMetadataChange}
/>
</Stack>
diff --git a/frontend/src/metabase/metadata/components/FieldSection/FieldSection.unit.spec.tsx b/frontend/src/metabase/metadata/components/FieldSection/FieldSection.unit.spec.tsx
index 62f90b6eb75..59de384c3a7 100644
--- a/frontend/src/metabase/metadata/components/FieldSection/FieldSection.unit.spec.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/FieldSection.unit.spec.tsx
@@ -113,6 +113,12 @@ async function assertErrorToast(message: string) {
});
}
+function getShownListboxes() {
+ return screen
+ .queryAllByRole("listbox")
+ .filter((listbox) => !listbox.closest('[data-hidden="true"]'));
+}
+
async function selectOption(input: HTMLElement, name: string) {
await userEvent.click(input);
const listbox = within(await screen.findByRole("listbox"));
@@ -234,4 +240,60 @@ describe("FieldSection", () => {
await assertErrorToast("Failed to update formatting of Quantity");
});
});
+
+ describe("read-only table", () => {
+ async function assertSelectIsReadOnly(input: HTMLElement) {
+ await userEvent.click(input);
+ expect(getShownListboxes()).toHaveLength(0);
+ }
+
+ it("shows the field settings of a table that cannot be written as read-only", async () => {
+ setup({ table: { ...ORDERS_TABLE, can_write: false } });
+
+ expect(
+ screen.getByPlaceholderText("Give this field a name"),
+ ).toHaveAttribute("readonly");
+ expect(
+ within(screen.getByTestId("field-section")).getAllByRole("img")[0],
+ ).toHaveAttribute("aria-label", expect.stringMatching(/icon$/));
+ expect(
+ screen.getByPlaceholderText("Give this field a description"),
+ ).toHaveAttribute("readonly");
+ expect(
+ screen.getByLabelText("Cast to a specific data type"),
+ ).toBeDisabled();
+ expect(screen.getByTestId("prefix")).toHaveAttribute("readonly");
+ await assertSelectIsReadOnly(
+ screen.getByPlaceholderText("Select a semantic type"),
+ );
+ await assertSelectIsReadOnly(
+ screen.getByPlaceholderText("Select a field visibility"),
+ );
+ await assertSelectIsReadOnly(
+ screen.getByPlaceholderText("Select field filtering"),
+ );
+ await assertSelectIsReadOnly(
+ await screen.findByPlaceholderText("Select display values"),
+ );
+ expect(
+ screen.getByRole("button", { name: /Field values/ }),
+ ).toBeEnabled();
+ expect(screen.getByRole("button", { name: /Preview/ })).toBeEnabled();
+ });
+
+ it("keeps the field settings of a writable table editable", async () => {
+ setup({ table: { ...ORDERS_TABLE, can_write: true } });
+
+ expect(
+ screen.getByPlaceholderText("Give this field a name"),
+ ).not.toHaveAttribute("readonly");
+ expect(
+ screen.getByLabelText("Cast to a specific data type"),
+ ).toBeInTheDocument();
+ await userEvent.click(
+ screen.getByPlaceholderText("Select a semantic type"),
+ );
+ await waitFor(() => expect(getShownListboxes()).toHaveLength(1));
+ });
+ });
});
diff --git a/frontend/src/metabase/metadata/components/FieldSection/FormattingSection/FormattingSection.tsx b/frontend/src/metabase/metadata/components/FieldSection/FormattingSection/FormattingSection.tsx
index b4383ffb894..dc6adc7eff8 100644
--- a/frontend/src/metabase/metadata/components/FieldSection/FormattingSection/FormattingSection.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/FormattingSection/FormattingSection.tsx
@@ -17,10 +17,15 @@ import { TitledSection } from "../../TitledSection";
interface Props {
field: Field;
+ readOnly?: boolean;
onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
}
-const FormattingSectionBase = ({ field, onTrackMetadataChange }: Props) => {
+const FormattingSectionBase = ({
+ field,
+ readOnly,
+ onTrackMetadataChange,
+}: Props) => {
const id = getRawTableFieldId(field);
const [updateField] = useUpdateFieldMutation();
const { sendErrorToast, sendSuccessToast, sendUndoToast } =
@@ -60,6 +65,7 @@ const FormattingSectionBase = ({ field, onTrackMetadataChange }: Props) => {
denylist={denyList}
extraData={{ forAdminSettings: true }}
inheritedSettings={inheritedSettings}
+ readOnly={readOnly}
style={{ maxWidth: undefined }}
value={field.settings ?? {}}
onChange={handleChange}
diff --git a/frontend/src/metabase/metadata/components/FieldSection/MetadataSection/MetadataSection.tsx b/frontend/src/metabase/metadata/components/FieldSection/MetadataSection/MetadataSection.tsx
index cdd27814331..d326d3cf5a2 100644
--- a/frontend/src/metabase/metadata/components/FieldSection/MetadataSection/MetadataSection.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/MetadataSection/MetadataSection.tsx
@@ -23,6 +23,7 @@ type MetadataSectionBaseProps = {
field: Field;
table: Table;
getFieldHref: (fieldId: FieldId) => string;
+ readOnly?: boolean;
onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
};
@@ -30,6 +31,7 @@ const MetadataSectionBase = ({
field,
table,
getFieldHref,
+ readOnly,
onTrackMetadataChange,
}: MetadataSectionBaseProps) => {
const id = getRawTableFieldId(field);
@@ -76,6 +78,7 @@ const MetadataSectionBase = ({
field={field}
idFields={idFields}
label={t`Semantic type`}
+ selectProps={{ readOnly }}
semanticTypeError={semanticTypeError}
onChange={handleChange}
/>
diff --git a/frontend/src/metabase/metadata/components/NameDescriptionInput/NameDescriptionInput.unit.spec.tsx b/frontend/src/metabase/metadata/components/NameDescriptionInput/NameDescriptionInput.unit.spec.tsx
index 614f94595ba..51c7bda97b7 100644
--- a/frontend/src/metabase/metadata/components/NameDescriptionInput/NameDescriptionInput.unit.spec.tsx
+++ b/frontend/src/metabase/metadata/components/NameDescriptionInput/NameDescriptionInput.unit.spec.tsx
@@ -8,12 +8,14 @@ interface SetupOpts {
description: string;
name: string;
namePrefix?: string;
+ readOnly?: boolean;
}
function setup({
description = "",
name = "",
namePrefix,
+ readOnly,
}: Partial<SetupOpts> = {}) {
const onDescriptionChange = jest.fn();
const onNameChange = jest.fn();
@@ -26,6 +28,7 @@ function setup({
nameIcon="table2"
namePlaceholder="Enter name"
namePrefix={namePrefix}
+ readOnly={readOnly}
onDescriptionChange={onDescriptionChange}
onNameChange={onNameChange}
/>,
@@ -92,4 +95,16 @@ describe("NameDescriptionInput", () => {
expect(screen.getByText("prefix:")).toBeInTheDocument();
});
+
+ it("shows the name icon and makes both inputs read-only when read-only", () => {
+ setup({ name: "Orders", description: "All orders", readOnly: true });
+
+ expect(screen.getByLabelText("table2 icon")).toBeInTheDocument();
+ expect(screen.getByPlaceholderText("Enter name")).toHaveAttribute(
+ "readonly",
+ );
+ expect(screen.getByPlaceholderText("Enter description")).toHaveAttribute(
+ "readonly",
+ );
+ });
});
diff --git a/frontend/src/metabase/metadata/components/TableFieldList/TableFieldList.tsx b/frontend/src/metabase/metadata/components/TableFieldList/TableFieldList.tsx
index abfa39d2191..f54036c453c 100644
--- a/frontend/src/metabase/metadata/components/TableFieldList/TableFieldList.tsx
+++ b/frontend/src/metabase/metadata/components/TableFieldList/TableFieldList.tsx
@@ -83,6 +83,7 @@ export const TableFieldList = ({
activeFieldKey={activeFieldId}
getFieldKey={getRawTableFieldId}
getFieldHref={handleGetFieldHref}
+ readOnly={!table.can_write}
onNameChange={handleNameChange}
onDescriptionChange={handleDescriptionChange}
/>
diff --git a/frontend/src/metabase/metadata/components/TableSection/TableSection.tsx b/frontend/src/metabase/metadata/components/TableSection/TableSection.tsx
index 5a33d4ecefb..3097684c2e9 100644
--- a/frontend/src/metabase/metadata/components/TableSection/TableSection.tsx
+++ b/frontend/src/metabase/metadata/components/TableSection/TableSection.tsx
@@ -51,6 +51,8 @@ const TableSectionBase = ({
} = useTableUpdateHandlers({ table });
const [isSorting, setIsSorting] = useState(false);
const hasFields = Boolean(table.fields && table.fields.length > 0);
+ const readOnly = !table.can_write;
+ const canSort = hasFields && !readOnly;
const {
buttonsContainerRef,
showButtonLabel,
@@ -58,7 +60,7 @@ const TableSectionBase = ({
setSortingButtonWidth,
setSyncButtonWidth,
} = useResponsiveButtons({
- hasFields,
+ canSort,
isSorting,
isUpdatingSorting,
});
@@ -96,6 +98,7 @@ const TableSectionBase = ({
</ActionIcon>
</Tooltip>
}
+ readOnly={readOnly}
onNameChange={handleNameChange}
onDescriptionChange={handleDescriptionChange}
/>
@@ -122,7 +125,7 @@ const TableSectionBase = ({
{isUpdatingSorting && <Loader size="xs" />}
- {!isSorting && hasFields && (
+ {!isSorting && canSort && (
<ResponsiveButton
icon="sort_arrows"
showLabel={showButtonLabel}
diff --git a/frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx b/frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx
index 938065569a2..c3006c10efe 100644
--- a/frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx
+++ b/frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx
@@ -121,4 +121,37 @@ describe("TableSection", () => {
await assertErrorToast("Failed to update field order");
});
});
+
+ describe("read-only table", () => {
+ it("shows a table that cannot be written as read-only", () => {
+ setup({ table: { ...ORDERS_TABLE, can_write: false } });
+
+ expect(
+ screen.getByPlaceholderText("Give this table a name"),
+ ).toHaveAttribute("readonly");
+ expect(screen.getByLabelText("table2 icon")).toBeInTheDocument();
+ expect(screen.getByLabelText("Go to this table")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Sorting/ }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByPlaceholderText("Give this field a name"),
+ ).toBeDisabled();
+ expect(
+ screen.getByRole("button", { name: /Sync options/ }),
+ ).toBeEnabled();
+ });
+
+ it("keeps a writable table editable", () => {
+ setup({ table: { ...ORDERS_TABLE, can_write: true } });
+
+ expect(
+ screen.getByPlaceholderText("Give this table a name"),
+ ).not.toHaveAttribute("readonly");
+ expect(screen.getByRole("button", { name: /Sorting/ })).toBeEnabled();
+ expect(
+ screen.getByPlaceholderText("Give this field a name"),
+ ).toBeEnabled();
+ });
+ });
});
diff --git a/frontend/src/metabase/metadata/components/TableSection/hooks.ts b/frontend/src/metabase/metadata/components/TableSection/hooks.ts
index 94639c06143..0a57523126f 100644
--- a/frontend/src/metabase/metadata/components/TableSection/hooks.ts
+++ b/frontend/src/metabase/metadata/components/TableSection/hooks.ts
@@ -6,11 +6,11 @@ const LOADER_WIDTH = 16;
const FIELD_ORDER_PICKER_WIDTH = 136;
export const useResponsiveButtons = ({
- hasFields,
+ canSort,
isSorting,
isUpdatingSorting,
}: {
- hasFields: boolean;
+ canSort: boolean;
isSorting: boolean;
isUpdatingSorting: boolean;
}) => {
@@ -40,7 +40,7 @@ export const useResponsiveButtons = ({
} else {
width += syncButtonWidth;
- if (hasFields) {
+ if (canSort) {
width += sortingButtonWidth + BUTTONS_GAP;
}
}
diff --git a/frontend/src/metabase/visualizations/components/ColumnSettings.tsx b/frontend/src/metabase/visualizations/components/ColumnSettings.tsx
index 249ba9e66c4..13276ac512a 100644
--- a/frontend/src/metabase/visualizations/components/ColumnSettings.tsx
+++ b/frontend/src/metabase/visualizations/components/ColumnSettings.tsx
@@ -26,6 +26,7 @@ type CommonProps = {
allowlist?: ReadonlySet<string>;
denylist?: ReadonlySet<string>;
extraData?: Omit<SettingsExtra, "series">;
+ readOnly?: boolean;
};
type GetWidgetsProps = CommonProps & {
@@ -50,6 +51,7 @@ function getWidgets({
allowlist,
denylist,
extraData,
+ readOnly,
}: GetWidgetsProps) {
// fake series
const series: Series = [];
@@ -83,11 +85,15 @@ function getWidgets({
{ series, ...extraData },
);
- return widgets.filter(
- (widget) =>
- (!allowlist || allowlist.has(widget.id)) &&
- (!denylist || !denylist.has(widget.id)),
- );
+ return widgets
+ .filter(
+ (widget) =>
+ (!allowlist || allowlist.has(widget.id)) &&
+ (!denylist || !denylist.has(widget.id)),
+ )
+ .map((widget) =>
+ readOnly ? { ...widget, props: { ...widget.props, readOnly } } : widget,
+ );
}
export function hasColumnSettingsWidgets({
diff --git a/frontend/src/metabase/visualizations/components/ColumnSettings.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ColumnSettings.unit.spec.tsx
index f0b71e5a017..da221820172 100644
--- a/frontend/src/metabase/visualizations/components/ColumnSettings.unit.spec.tsx
+++ b/frontend/src/metabase/visualizations/components/ColumnSettings.unit.spec.tsx
@@ -1,5 +1,6 @@
import { renderWithProviders, screen } from "__support__/ui";
import { registerVisualizations } from "metabase/visualizations/register";
+import type { ColumnSettings as ApiColumnSettings } from "metabase-types/api";
import {
createMockDatetimeColumn,
createMockField,
@@ -77,3 +78,49 @@ describe("ColumnSettings", () => {
expect(screen.getByText("Display as")).toBeInTheDocument();
});
});
+
+describe("ColumnSettings read-only", () => {
+ type SetupOpts = {
+ value?: ApiColumnSettings;
+ readOnly?: boolean;
+ };
+
+ const setup = ({ value = {}, readOnly }: SetupOpts = {}) => {
+ renderWithProviders(
+ <ColumnSettings
+ column={createMockField({
+ base_type: "type/Integer",
+ effective_type: "type/Integer",
+ })}
+ value={value}
+ readOnly={readOnly}
+ />,
+ );
+ };
+
+ it("shows the formatting of a read-only column without letting it change", () => {
+ setup({ readOnly: true });
+
+ expect(screen.getByTestId("prefix")).toHaveAttribute("readonly");
+ expect(screen.getByTestId("suffix")).toHaveAttribute("readonly");
+ expect(screen.getByRole("switch")).toBeDisabled();
+ });
+
+ it("disables the radio settings of a read-only column", () => {
+ setup({ value: { number_style: "currency" }, readOnly: true });
+
+ const radios = screen.getAllByRole("radio");
+ expect(radios.length).toBeGreaterThan(0);
+ radios.forEach((radio) => expect(radio).toBeDisabled());
+ });
+
+ it("keeps the formatting of a column editable by default", () => {
+ setup({ value: { number_style: "currency" } });
+
+ expect(screen.getByTestId("prefix")).not.toHaveAttribute("readonly");
+ expect(screen.getByRole("switch")).toBeEnabled();
+ screen
+ .getAllByRole("radio")
+ .forEach((radio) => expect(radio).toBeEnabled());
+ });
+});
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingInput.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingInput.tsx
index e563d4f7b5d..e79b013bc8d 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingInput.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingInput.tsx
@@ -9,6 +9,7 @@ interface ChartSettingInputProps {
placeholder: string;
onChange: (value: string) => void;
id?: string;
+ readOnly?: boolean;
}
export const ChartSettingInput = ({
@@ -16,6 +17,7 @@ export const ChartSettingInput = ({
onChange,
placeholder,
id,
+ readOnly,
}: ChartSettingInputProps) => {
const [inputValue, setInputValue] = useState(value ?? "");
@@ -34,6 +36,7 @@ export const ChartSettingInput = ({
id={id}
data-testid={id}
placeholder={placeholder}
+ readOnly={readOnly}
value={inputValue}
onChange={(e) => {
setInputValue(e.target.value);
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingInputNumeric.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingInputNumeric.tsx
index 76d0fde85ed..201e759cf40 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingInputNumeric.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingInputNumeric.tsx
@@ -41,6 +41,7 @@ interface ChartSettingInputProps extends Omit<
id?: string;
placeholder?: string;
className?: string;
+ readOnly?: boolean;
}
export const ChartSettingInputNumeric = ({
@@ -50,6 +51,7 @@ export const ChartSettingInputNumeric = ({
options,
id,
className,
+ readOnly,
}: ChartSettingInputProps) => {
const [inputValue, setInputValue] = useState<string>(value?.toString() ?? "");
const isFocusedRef = useRef(false);
@@ -109,6 +111,7 @@ export const ChartSettingInputNumeric = ({
id={id}
placeholder={placeholder}
type="text"
+ readOnly={readOnly}
error={inputValue && isNaN(Number(inputValue))}
value={inputValue}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingLinkUrlInput.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingLinkUrlInput.tsx
index 6639ddd956b..caca3715365 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingLinkUrlInput.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingLinkUrlInput.tsx
@@ -8,6 +8,7 @@ interface ChartSettingLinkUrlInputProps {
onChange: (value: string) => void;
id?: string;
options?: string[];
+ readOnly?: boolean;
onChangeSettings?: (settings: Partial<VisualizationSettings>) => void;
}
@@ -31,6 +32,7 @@ const ChartSettingLinkUrlInput = ({
onChange,
options,
id,
+ readOnly,
onChangeSettings,
}: ChartSettingLinkUrlInputProps) => {
const valueOrDefault = value ?? "";
@@ -66,6 +68,7 @@ const ChartSettingLinkUrlInput = ({
data-testid={id}
onChangeSettings={onChangeSettings}
options={options}
+ readOnly={readOnly}
onChange={setFocusedValue}
value={isFocused ? focusedValue : valueOrDefault}
onFocus={handleFocus}
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingRadio.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingRadio.tsx
index 272631e66c3..2a4fdb3b578 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingRadio.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingRadio.tsx
@@ -7,6 +7,7 @@ interface ChartSettingRadioProps {
options: { name: string; value: string | null }[];
value: string | null;
className?: string;
+ readOnly?: boolean;
onChange: (value: unknown) => void;
}
@@ -15,6 +16,7 @@ export const ChartSettingRadio = ({
onChange,
options: rawOptions = [],
className,
+ readOnly,
}: ChartSettingRadioProps) => {
const options: { name: string; value: string }[] = useMemo(() => {
return rawOptions.map(({ name, value }) => ({
@@ -42,6 +44,7 @@ export const ChartSettingRadio = ({
</Text>
}
value={optionValue}
+ disabled={readOnly}
styles={{
inner: { alignSelf: "center" },
}}
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingSelect.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingSelect.tsx
index 2ea9f7d5851..9114e15f215 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingSelect.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingSelect.tsx
@@ -36,6 +36,7 @@ type ChartSettingSelectProps = Pick<
options?: ChartSettingSelectOption[];
placeholder?: string;
placeholderNoOptions?: string;
+ readOnly?: boolean;
rightSectionWidth?: string;
searchProp?: string;
value?: ChartSettingSelectValue;
@@ -58,6 +59,7 @@ export const ChartSettingSelect = ({
placeholder,
placeholderNoOptions,
pr,
+ readOnly,
rightSection,
rightSectionWidth,
searchProp,
@@ -130,6 +132,7 @@ export const ChartSettingSelect = ({
}}
data={data}
disabled={disabled}
+ readOnly={readOnly}
value={selectedValue}
// Mantine's Select passes two arguments to onChange, but the onChange defined in the settings code takes one.
onChange={(v) => {
diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingToggle.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingToggle.tsx
index bb318790673..0036e838d30 100644
--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingToggle.tsx
+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingToggle.tsx
@@ -5,11 +5,13 @@ export const ChartSettingToggle = ({
onChange,
id,
disabled,
+ readOnly,
}: {
value: boolean | undefined;
onChange: (value: boolean) => void;
id?: string;
disabled?: boolean;
+ readOnly?: boolean;
}) => (
<Switch
labelPosition="left"
@@ -17,6 +19,6 @@ export const ChartSettingToggle = ({
onChange={(e) => onChange(e.currentTarget.checked)}
id={id}
role="switch"
- disabled={disabled}
+ disabled={disabled || readOnly}
/>
);