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
17 changes: 17 additions & 0 deletions .changeset/27491-dashboard-all-tiles-refused-panel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@object-ui/plugin-dashboard': patch
'@object-ui/i18n': patch
---

fix(plugin-dashboard): a viewer whose every dashboard tile is refused sees one no-access panel, not an empty canvas

Clause-②: no
Metadata-protocol: none

A tile whose data the viewer may not read is left out of the dashboard outside design mode. When every tile was left out, the viewer saw the dashboard's header over an empty canvas, with no message. `DashboardRenderer` now draws one no-access panel in the canvas in that case (lock icon, "You don’t have access", "You don’t have permission to view the data behind this dashboard."), the same face the console shows for a dashboard the viewer may not open. The header, its description and the refresh control stay as they are.

- A partial refusal is unchanged: the refused tiles leave, the rest reflow, no message.
- In design mode every tile stays and draws its own no-access state; no panel.
- A failure that is not a read refusal keeps every tile and its error; no panel.
- A dashboard with no widgets draws no panel.
- `@object-ui/i18n` adds `dashboard.allWidgetsForbiddenMessage` in all ten locales.
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1612,6 +1612,7 @@ const ar = {
datasetUnsupported: "مصدر البيانات هذا لا يدعم استعلامات مجموعات البيانات.",
widgetForbiddenTitle: "لا تملك صلاحية الوصول",
widgetForbiddenMessage: "ليست لديك صلاحية لعرض البيانات الخاصة بهذه الأداة.",
allWidgetsForbiddenMessage: "ليست لديك صلاحية لعرض البيانات الخاصة بلوحة التحكم هذه.",
details: "التفاصيل",
exportCsv: "تصدير CSV",
openInList: "فتح في القائمة",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1421,6 +1421,7 @@ const de = {
datasetUnsupported: "Diese Datenquelle unterstützt keine Dataset-Abfragen.",
widgetForbiddenTitle: "Kein Zugriff",
widgetForbiddenMessage: "Sie haben keine Berechtigung, die Daten dieses Widgets anzuzeigen.",
allWidgetsForbiddenMessage: "Sie haben keine Berechtigung, die Daten dieses Dashboards anzuzeigen.",
details: "Details",
exportCsv: "CSV exportieren",
openInList: "In Liste öffnen",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1806,6 +1806,7 @@ const en = {
datasetUnsupported: 'This data source does not support dataset queries.',
widgetForbiddenTitle: 'You don’t have access',
widgetForbiddenMessage: 'You don’t have permission to view the data behind this widget.',
allWidgetsForbiddenMessage: 'You don’t have permission to view the data behind this dashboard.',
details: 'Details',
exportCsv: 'Export CSV',
openInList: 'Open in list',
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1471,6 +1471,7 @@ const es = {
datasetUnsupported: "Esta fuente de datos no admite consultas de dataset.",
widgetForbiddenTitle: "Sin acceso",
widgetForbiddenMessage: "No tienes permiso para ver los datos de este widget.",
allWidgetsForbiddenMessage: "No tienes permiso para ver los datos de este panel.",
details: "Detalles",
exportCsv: "Exportar CSV",
openInList: "Abrir en la lista",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1467,6 +1467,7 @@ const fr = {
datasetUnsupported: "Cette source de données ne prend pas en charge les requêtes de dataset.",
widgetForbiddenTitle: "Accès refusé",
widgetForbiddenMessage: "Vous n’avez pas l’autorisation de voir les données de ce widget.",
allWidgetsForbiddenMessage: "Vous n’avez pas l’autorisation de voir les données de ce tableau de bord.",
details: "Détails",
exportCsv: "Exporter en CSV",
openInList: "Ouvrir dans la liste",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1421,6 +1421,7 @@ const ja = {
datasetUnsupported: "このデータソースはデータセットクエリに対応していません。",
widgetForbiddenTitle: "アクセス権がありません",
widgetForbiddenMessage: "このウィジェットのデータを表示する権限がありません。",
allWidgetsForbiddenMessage: "このダッシュボードのデータを表示する権限がありません。",
details: "詳細",
exportCsv: "CSV で書き出す",
openInList: "リストで開く",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1421,6 +1421,7 @@ const ko = {
datasetUnsupported: "이 데이터 소스는 데이터셋 쿼리를 지원하지 않습니다.",
widgetForbiddenTitle: "접근 권한 없음",
widgetForbiddenMessage: "이 위젯의 데이터를 볼 수 있는 권한이 없습니다.",
allWidgetsForbiddenMessage: "이 대시보드의 데이터를 볼 수 있는 권한이 없습니다.",
details: "세부 정보",
exportCsv: "CSV 내보내기",
openInList: "목록에서 열기",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/pt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1466,6 +1466,7 @@ const pt = {
datasetUnsupported: "Esta fonte de dados não oferece suporte a consultas de dataset.",
widgetForbiddenTitle: "Sem acesso",
widgetForbiddenMessage: "Você não tem permissão para ver os dados deste widget.",
allWidgetsForbiddenMessage: "Você não tem permissão para ver os dados deste painel.",
details: "Detalhes",
exportCsv: "Exportar CSV",
openInList: "Abrir na lista",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1521,6 +1521,7 @@ const ru = {
datasetUnsupported: "Этот источник данных не поддерживает запросы к наборам данных.",
widgetForbiddenTitle: "Нет доступа",
widgetForbiddenMessage: "У вас нет прав на просмотр данных этого виджета.",
allWidgetsForbiddenMessage: "У вас нет прав на просмотр данных этой панели.",
details: "Подробности",
exportCsv: "Экспорт в CSV",
openInList: "Открыть в списке",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1485,6 +1485,7 @@ const zh = {
datasetUnsupported: '当前数据源不支持数据集查询。',
widgetForbiddenTitle: '无权访问',
widgetForbiddenMessage: '你没有查看该组件数据的权限。',
allWidgetsForbiddenMessage: '你没有查看该仪表板数据的权限。',
details: '明细',
exportCsv: '导出 CSV',
openInList: '在列表中打开',
Expand Down
36 changes: 31 additions & 5 deletions ui/packages/plugin-dashboard/src/DashboardRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ import {
chartMeasureKey,
chartConfigPresentation,
} from '@object-ui/core';
import { cn, Card, CardHeader, CardTitle, CardContent, Button, getLazyIcon } from '@object-ui/components';
import { cn, Card, CardHeader, CardTitle, CardContent, Button, getLazyIcon, Empty, EmptyTitle, EmptyDescription } from '@object-ui/components';
import { forwardRef, useState, useEffect, useLayoutEffect, useRef, useCallback, useMemo, Fragment } from 'react';
import type { HTMLAttributes } from 'react';
import { RefreshCw } from 'lucide-react';
import { Lock, RefreshCw } from 'lucide-react';
import {
DndContext,
PointerSensor,
Expand Down Expand Up @@ -1440,11 +1440,33 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
[schema.widgets]
);

// objectstack#27491 — a viewer whose every tile was left out (each one a
// read refusal, above) would see the header over nothing. The canvas then
// says so once, in the face the console draws for a refused dashboard
// (`dashboard-access-denied`). Only when nothing is left: a partial
// refusal reflows silently, design mode keeps every tile, and a dashboard
// with no widgets at all draws no refusal.
const nothingLeftForViewer = (tiles: ReadonlyArray<unknown>) =>
!designMode && refusedTiles.size > 0 && tiles.length > 0 && tiles.every((tile) => tile == null);
const allTilesRefusedPanel = (
<Empty data-testid="dashboard-all-widgets-forbidden" className="col-span-full">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">
<Lock className="h-6 w-6 text-muted-foreground" aria-hidden="true" />
</div>
<EmptyTitle>{tt('dashboard.widgetForbiddenTitle', 'You don’t have access')}</EmptyTitle>
<EmptyDescription>
{tt('dashboard.allWidgetsForbiddenMessage', 'You don’t have permission to view the data behind this dashboard.')}
</EmptyDescription>
</Empty>
);

if (isMobile) {
// Separate metric widgets from other widgets for better mobile layout
// A typeless widget is a `metric` (the spec's default, objectui#11514).
const metricWidgets = schema.widgets?.filter((w: DashboardWidgetSlotEntry) => resolveWidgetType(w) === 'metric') || [];
const otherWidgets = schema.widgets?.filter((w: DashboardWidgetSlotEntry) => resolveWidgetType(w) !== 'metric') || [];
const metricTiles = metricWidgets.map((widget: DashboardWidgetSlotEntry, index: number) => renderWidget(widget, index));
const otherTiles = otherWidgets.map((widget: DashboardWidgetSlotEntry, index: number) => renderWidget(widget, index, true));

const mobileBody = (
<div ref={ref} {...hostDomProps} className={cn("flex flex-col gap-4 px-4", className)} data-user-actions={userActionsAttr} onClick={handleHostClick}>
Expand All @@ -1455,7 +1477,7 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
{metricWidgets.length > 0 && (
<div className="grid grid-cols-2 gap-3" onClick={handleBackgroundClick}>
<SortableContext items={metricIds} strategy={rectSortingStrategy} disabled={!dragEnabled}>
{metricWidgets.map((widget: DashboardWidgetSlotEntry, index: number) => renderWidget(widget, index))}
{metricTiles}
</SortableContext>
</div>
)}
Expand All @@ -1464,10 +1486,12 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
{otherWidgets.length > 0 && (
<div className="flex flex-col gap-4" onClick={handleBackgroundClick}>
<SortableContext items={otherIds} strategy={verticalListSortingStrategy} disabled={!dragEnabled}>
{otherWidgets.map((widget: DashboardWidgetSlotEntry, index: number) => renderWidget(widget, index, true))}
{otherTiles}
</SortableContext>
</div>
)}

{nothingLeftForViewer([...metricTiles, ...otherTiles]) && allTilesRefusedPanel}
</div>
);

Expand All @@ -1478,6 +1502,7 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
) : mobileBody;
}

const desktopTiles = (schema.widgets ?? []).map((widget: DashboardWidgetSlotEntry, index: number) => renderWidget(widget, index));
const desktopBody = (
<div
ref={ref}
Expand Down Expand Up @@ -1513,8 +1538,9 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
{headerSection}
{toolbarRow}
<SortableContext items={widgetIds} strategy={rectSortingStrategy} disabled={!dragEnabled}>
{schema.widgets?.map((widget: DashboardWidgetSlotEntry, index: number) => renderWidget(widget, index))}
{desktopTiles}
</SortableContext>
{nothingLeftForViewer(desktopTiles) && allTilesRefusedPanel}
</div>
);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/**
* objectstack#27491 — a viewer whose every dashboard tile is refused sees one
* no-access statement, not the header over an empty canvas.
*
* Each refused dataset tile is still left out (objectstack#26971, pinned in
* `DashboardRenderer.refusedTile-26971.test.tsx`). When that leaves nothing to
* draw, the canvas shows the console's refused-dashboard face once
* (`dashboard-all-widgets-forbidden`). A partial refusal keeps reflowing with
* no message; design mode keeps every tile and its own no-access state
* (objectui#10899); a failure that is not a read refusal keeps its tiles and
* their errors.
*
* The refusal carries the two fields `@object-ui/data-objectstack`'s
* `AnalyticsForbiddenError` declares (`httpStatus: 403`,
* `code: 'PERMISSION_DENIED'`), as `DatasetWidget.forbiddenState-10899.test.tsx`
* builds it.
*/

import '@testing-library/jest-dom/vitest';
import * as React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, waitFor } from '@testing-library/react';
import type { DashboardComponentSchema } from '@object-ui/types';
// Module scope (AGENTS.md 测试纪律): the table tile renders onward through the
// registry this barrel populates.
import '@object-ui/components';
import { DashboardRenderer } from '../DashboardRenderer';

beforeEach(() => {
// The dimension-label metadata probe (`useDatasetDimensionMeta`) falls back
// to the global fetch; answer it locally so no case reaches the network.
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => ({}), text: async () => '{}' })));
});
afterEach(() => {
vi.unstubAllGlobals();
cleanup();
});

const dashboard = (...widgets: Record<string, unknown>[]): DashboardComponentSchema =>
({ type: 'dashboard', name: 'pipeline_dashboard', title: 'Pipeline Dashboard', widgets }) as unknown as DashboardComponentSchema;

const TOTAL_PIPELINE = {
id: 'total_pipeline',
type: 'metric',
title: 'Total Pipeline',
dataset: 'opportunity_metrics',
values: ['total_amount'],
};
const BY_STAGE = {
id: 'pipeline_by_stage',
type: 'table',
title: 'Pipeline by Stage',
dataset: 'opportunity_metrics',
dimensions: ['stage'],
values: ['deal_count'],
};
const READABLE = {
id: 'open_tasks',
type: 'table',
title: 'Open Tasks',
dataset: 'task_metrics',
dimensions: ['status'],
values: ['task_count'],
};

function readRefusal() {
return Object.assign(new Error('Analytics query refused: this user may not read the data behind dataset "opportunity_metrics".'), {
name: 'AnalyticsForbiddenError',
httpStatus: 403,
code: 'PERMISSION_DENIED',
});
}

/** Refuses `opportunity_metrics` with `failure()`; answers every other dataset. */
function source(failure: () => Error = readRefusal) {
return {
queryDataset: vi.fn(async (dataset: string) => {
if (dataset === 'opportunity_metrics') throw failure();
return {
rows: [{ status: 'Open', task_count: 4 }],
fields: [
{ name: 'status', label: 'Status', type: 'text' },
{ name: 'task_count', label: 'Tasks', type: 'number' },
],
object: 'task',
};
}),
};
}

describe('DashboardRenderer — every tile refused draws one no-access panel (objectstack#27491)', () => {
it('draws the panel once every tile is refused, and no tile title or per-tile face', async () => {
const src = source();
render(<DashboardRenderer schema={dashboard(TOTAL_PIPELINE, BY_STAGE)} dataSource={src} />);

const panel = await screen.findByTestId('dashboard-all-widgets-forbidden');
expect(panel).toHaveTextContent('You don’t have access');
expect(panel).toHaveTextContent('You don’t have permission to view the data behind this dashboard.');
// Both tiles were asked: the panel follows the server's refusals, never a guess.
expect(src.queryDataset).toHaveBeenCalledTimes(2);
expect(screen.queryByText('Total Pipeline')).toBeNull();
expect(screen.queryByText('Pipeline by Stage')).toBeNull();
expect(screen.queryByTestId('dataset-widget-forbidden')).toBeNull();
});

it('draws the same panel in the mobile layout', async () => {
const width = window.innerWidth;
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 500 });
try {
const { container } = render(<DashboardRenderer schema={dashboard(TOTAL_PIPELINE, BY_STAGE)} dataSource={source()} />);

expect(await screen.findByTestId('dashboard-all-widgets-forbidden')).toBeInTheDocument();
// Non-vacuity: the mobile layout is the one drawn (its metric row is a 2-column grid).
expect(container.innerHTML).toContain('grid-cols-2');
expect(screen.queryByText('Total Pipeline')).toBeNull();
} finally {
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width });
}
});

it('a partial refusal draws no panel and keeps the readable tile', async () => {
const src = source();
render(<DashboardRenderer schema={dashboard(TOTAL_PIPELINE, READABLE, BY_STAGE)} dataSource={src} />);

expect(await screen.findByText('Open')).toBeInTheDocument();
expect(screen.getByText('Open Tasks')).toBeInTheDocument();
await waitFor(() => expect(screen.queryByText('Pipeline by Stage')).toBeNull());
expect(screen.queryByText('Total Pipeline')).toBeNull();
expect(screen.queryByTestId('dashboard-all-widgets-forbidden')).toBeNull();
});

it('CONTROL — in design mode every refused tile stays with its own no-access state, and no panel', async () => {
render(
<DashboardRenderer
schema={dashboard(TOTAL_PIPELINE, BY_STAGE)}
dataSource={source()}
designMode
onWidgetClick={() => {}}
/>,
);

await waitFor(() => expect(screen.getAllByTestId('dataset-widget-forbidden')).toHaveLength(2));
expect(screen.getByTestId('dashboard-preview-widget-total_pipeline')).toBeInTheDocument();
expect(screen.getByTestId('dashboard-preview-widget-pipeline_by_stage')).toHaveTextContent('Pipeline by Stage');
expect(screen.queryByTestId('dashboard-all-widgets-forbidden')).toBeNull();
});

it('CONTROL — a failure that is not a read refusal keeps every tile and its error, and no panel', async () => {
render(
<DashboardRenderer
schema={dashboard(TOTAL_PIPELINE, BY_STAGE)}
dataSource={source(() => new Error('Dataset query failed: 400 Bad Request — relationship not declared in include'))}
/>,
);

await waitFor(() => expect(screen.getAllByText(/relationship not declared in include/)).toHaveLength(2));
expect(screen.getByText('Total Pipeline')).toBeInTheDocument();
expect(screen.getByText('Pipeline by Stage')).toBeInTheDocument();
expect(screen.queryByTestId('dashboard-all-widgets-forbidden')).toBeNull();
});
});
Loading