Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: enable / revoke public access to a dashboard (#9642)

Yunus Ma59c0188cc3b
diff --git a/frontend/package.json b/frontend/package.json
index eecb593cf6..e8a38998c5 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -47,6 +47,7 @@
"@signozhq/button": "0.0.2",
"@signozhq/calendar": "0.0.0",
"@signozhq/callout": "0.0.2",
+ "@signozhq/checkbox": "0.0.2",
"@signozhq/design-tokens": "1.1.4",
"@signozhq/input": "0.0.2",
"@signozhq/popover": "0.0.0",
diff --git a/frontend/src/AppRoutes/Private.tsx b/frontend/src/AppRoutes/Private.tsx
index 8d80e0bbbd..cca73a0c7e 100644
--- a/frontend/src/AppRoutes/Private.tsx
+++ b/frontend/src/AppRoutes/Private.tsx
@@ -245,6 +245,14 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
history.replace(newLocation);
return;
}
+
+ // if the current route is public dashboard then don't redirect to login
+ const isPublicDashboard = currentRoute?.path === ROUTES.PUBLIC_DASHBOARD;
+
+ if (isPublicDashboard) {
+ return;
+ }
+
// if the current route
if (currentRoute) {
const { isPrivate, key } = currentRoute;
diff --git a/frontend/src/AppRoutes/index.tsx b/frontend/src/AppRoutes/index.tsx
index bc66fc1dfa..71e7d376ef 100644
--- a/frontend/src/AppRoutes/index.tsx
+++ b/frontend/src/AppRoutes/index.tsx
@@ -214,7 +214,10 @@ function App(): JSX.Element {
]);
useEffect(() => {
- if (pathname === ROUTES.ONBOARDING) {
+ if (
+ pathname === ROUTES.ONBOARDING ||
+ pathname.startsWith('/public/dashboard/')
+ ) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.Pylon('hideChatBubble');
diff --git a/frontend/src/AppRoutes/pageComponents.ts b/frontend/src/AppRoutes/pageComponents.ts
index c2833547f4..fe971cdf46 100644
--- a/frontend/src/AppRoutes/pageComponents.ts
+++ b/frontend/src/AppRoutes/pageComponents.ts
@@ -295,3 +295,10 @@ export const MetricsExplorer = Loadable(
export const ApiMonitoring = Loadable(
() => import(/* webpackChunkName: "ApiMonitoring" */ 'pages/ApiMonitoring'),
);
+
+export const PublicDashboardPage = Loadable(
+ () =>
+ import(
+ /* webpackChunkName: "Public Dashboard Page" */ 'pages/PublicDashboard'
+ ),
+);
diff --git a/frontend/src/AppRoutes/routes.ts b/frontend/src/AppRoutes/routes.ts
index 9553c1096a..2a33a4b720 100644
--- a/frontend/src/AppRoutes/routes.ts
+++ b/frontend/src/AppRoutes/routes.ts
@@ -34,6 +34,7 @@ import {
OrgOnboarding,
PasswordReset,
PipelinePage,
+ PublicDashboardPage,
ServiceMapPage,
ServiceMetricsPage,
ServicesTablePage,
@@ -169,6 +170,13 @@ const routes: AppRoutes[] = [
isPrivate: true,
key: 'DASHBOARD',
},
+ {
+ path: ROUTES.PUBLIC_DASHBOARD,
+ exact: false,
+ component: PublicDashboardPage,
+ isPrivate: false,
+ key: 'PUBLIC_DASHBOARD',
+ },
{
path: ROUTES.DASHBOARD_WIDGET,
exact: true,
diff --git a/frontend/src/api/dashboard/public/createPublicDashboard.ts b/frontend/src/api/dashboard/public/createPublicDashboard.ts
new file mode 100644
index 0000000000..bb45d77885
--- /dev/null
+++ b/frontend/src/api/dashboard/public/createPublicDashboard.ts
@@ -0,0 +1,28 @@
+import axios from 'api';
+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
+import { AxiosError } from 'axios';
+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
+import { CreatePublicDashboardProps } from 'types/api/dashboard/public/create';
+
+const createPublicDashboard = async (
+ props: CreatePublicDashboardProps,
+): Promise<SuccessResponseV2<CreatePublicDashboardProps>> => {
+
+ const { dashboardId, timeRangeEnabled = false, defaultTimeRange = '30m' } = props;
+
+ try {
+ const response = await axios.post(
+ `/dashboards/${dashboardId}/public`,
+ { timeRangeEnabled, defaultTimeRange },
+ );
+
+ return {
+ httpStatusCode: response.status,
+ data: response.data.data,
+ };
+ } catch (error) {
+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
+ }
+};
+
+export default createPublicDashboard;
diff --git a/frontend/src/api/dashboard/public/getPublicDashboardData.ts b/frontend/src/api/dashboard/public/getPublicDashboardData.ts
new file mode 100644
index 0000000000..4d0a32204d
--- /dev/null
+++ b/frontend/src/api/dashboard/public/getPublicDashboardData.ts
@@ -0,0 +1,20 @@
+import axios from 'api';
+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
+import { AxiosError } from 'axios';
+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
+import { GetPublicDashboardDataProps, PayloadProps,PublicDashboardDataProps } from 'types/api/dashboard/public/get';
+
+const getPublicDashboardData = async (props: GetPublicDashboardDataProps): Promise<SuccessResponseV2<PublicDashboardDataProps>> => {
+ try {
+ const response = await axios.get<PayloadProps>(`/public/dashboards/${props.id}`);
+
+ return {
+ httpStatusCode: response.status,
+ data: response.data.data,
+ };
+ } catch (error) {
+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
+ }
+};
+
+export default getPublicDashboardData;
diff --git a/frontend/src/api/dashboard/public/getPublicDashboardMeta.ts b/frontend/src/api/dashboard/public/getPublicDashboardMeta.ts
new file mode 100644
index 0000000000..dc9fe67707
--- /dev/null
+++ b/frontend/src/api/dashboard/public/getPublicDashboardMeta.ts
@@ -0,0 +1,20 @@
+import axios from 'api';
+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
+import { AxiosError } from 'axios';
+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
+import { GetPublicDashboardMetaProps, PayloadProps,PublicDashboardMetaProps } from 'types/api/dashboard/public/getMeta';
+
+const getPublicDashboardMeta = async (props: GetPublicDashboardMetaProps): Promise<SuccessResponseV2<PublicDashboardMetaProps>> => {
+ try {
+ const response = await axios.get<PayloadProps>(`/dashboards/${props.id}/public`);
+
+ return {
+ httpStatusCode: response.status,
+ data: response.data.data,
+ };
+ } catch (error) {
+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
+ }
+};
+
+export default getPublicDashboardMeta;
diff --git a/frontend/src/api/dashboard/public/getPublicDashboardWidgetData.ts b/frontend/src/api/dashboard/public/getPublicDashboardWidgetData.ts
new file mode 100644
index 0000000000..71fd305dec
--- /dev/null
+++ b/frontend/src/api/dashboard/public/getPublicDashboardWidgetData.ts
@@ -0,0 +1,27 @@
+import axios from 'api';
+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
+import { MetricRangePayloadV5 } from 'api/v5/v5';
+import { AxiosError } from 'axios';
+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
+import { GetPublicDashboardWidgetDataProps } from 'types/api/dashboard/public/getWidgetData';
+
+
+const getPublicDashboardWidgetData = async (props: GetPublicDashboardWidgetDataProps): Promise<SuccessResponseV2<MetricRangePayloadV5>> => {
+ try {
+ const response = await axios.get(`/public/dashboards/${props.id}/widgets/${props.index}/query_range`, {
+ params: {
+ startTime: props.startTime,
+ endTime: props.endTime,
+ },
+ });
+
+ return {
+ httpStatusCode: response.status,
+ data: response.data,
+ };
+ } catch (error) {
+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
+ }
+};
+
+export default getPublicDashboardWidgetData;
diff --git a/frontend/src/api/dashboard/public/revokePublicDashboardAccess.ts b/frontend/src/api/dashboard/public/revokePublicDashboardAccess.ts
new file mode 100644
index 0000000000..71f23ac66c
--- /dev/null
+++ b/frontend/src/api/dashboard/public/revokePublicDashboardAccess.ts
@@ -0,0 +1,22 @@
+import axios from 'api';
+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
+import { AxiosError } from 'axios';
+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
+import { PayloadProps,RevokePublicDashboardAccessProps } from 'types/api/dashboard/public/delete';
+
+const revokePublicDashboardAccess = async (
+ props: RevokePublicDashboardAccessProps,
+): Promise<SuccessResponseV2<PayloadProps>> => {
+ try {
+ const response = await axios.delete<PayloadProps>(`/dashboards/${props.id}/public`);
+
+ return {
+ httpStatusCode: response.status,
+ data: response.data,
+ };
+ } catch (error) {
+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
+ }
+};
+
+export default revokePublicDashboardAccess;
diff --git a/frontend/src/api/dashboard/public/updatePublicDashboard.ts b/frontend/src/api/dashboard/public/updatePublicDashboard.ts
new file mode 100644
index 0000000000..6daacf5118
--- /dev/null
+++ b/frontend/src/api/dashboard/public/updatePublicDashboard.ts
@@ -0,0 +1,28 @@
+import axios from 'api';
+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
+import { AxiosError } from 'axios';
+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
+import { UpdatePublicDashboardProps } from 'types/api/dashboard/public/update';
+
+const updatePublicDashboard = async (
+ props: UpdatePublicDashboardProps,
+): Promise<SuccessResponseV2<UpdatePublicDashboardProps>> => {
+
+ const { dashboardId, timeRangeEnabled = false, defaultTimeRange = '30m' } = props;
+
+ try {
+ const response = await axios.put(
+ `/dashboards/${dashboardId}/public`,
+ { timeRangeEnabled, defaultTimeRange },
+ );
+
+ return {
+ httpStatusCode: response.status,
+ data: response.data.data,
+ };
+ } catch (error) {
+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
+ }
+};
+
+export default updatePublicDashboard;
diff --git a/frontend/src/components/CustomTimePicker/CustomTimePicker.tsx b/frontend/src/components/CustomTimePicker/CustomTimePicker.tsx
index 8882c6f60a..45423d83d3 100644
--- a/frontend/src/components/CustomTimePicker/CustomTimePicker.tsx
+++ b/frontend/src/components/CustomTimePicker/CustomTimePicker.tsx
@@ -62,6 +62,8 @@ interface CustomTimePickerProps {
showLiveLogs?: boolean;
onGoLive?: () => void;
onExitLiveLogs?: () => void;
+ /** When false, hides the "Recently Used" time ranges section */
+ showRecentlyUsed?: boolean;
}
function CustomTimePicker({
@@ -81,6 +83,7 @@ function CustomTimePicker({
onGoLive,
onExitLiveLogs,
showLiveLogs,
+ showRecentlyUsed = true,
}: CustomTimePickerProps): JSX.Element {
const [
selectedTimePlaceholderValue,
@@ -395,6 +398,7 @@ function CustomTimePicker({
setActiveView={setActiveView}
setIsOpenedFromFooter={setIsOpenedFromFooter}
isOpenedFromFooter={isOpenedFromFooter}
+ showRecentlyUsed={showRecentlyUsed}
/>
) : (
content
@@ -464,4 +468,5 @@ CustomTimePicker.defaultProps = {
onCustomTimeStatusUpdate: noop,
onExitLiveLogs: noop,
showLiveLogs: false,
+ showRecentlyUsed: true,
};
diff --git a/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx b/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx
index 94b4520741..b2fc1f9148 100644
--- a/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx
+++ b/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx
@@ -47,6 +47,7 @@ interface CustomTimePickerPopoverContentProps {
isOpenedFromFooter: boolean;
setIsOpenedFromFooter: Dispatch<SetStateAction<boolean>>;
onExitLiveLogs: () => void;
+ showRecentlyUsed: boolean;
}
interface RecentlyUsedDateTimeRange {
@@ -72,6 +73,7 @@ function CustomTimePickerPopoverContent({
isOpenedFromFooter,
setIsOpenedFromFooter,
onExitLiveLogs,
+ showRecentlyUsed = true,
}: CustomTimePickerPopoverContentProps): JSX.Element {
const { pathname } = useLocation();
@@ -224,33 +226,35 @@ function CustomTimePickerPopoverContent({
<div>{getTimeChips(RelativeDurationSuggestionOptions)}</div>
</div>
- <div className="recently-used-container">
- <div className="time-heading">RECENTLY USED</div>
- <div className="recently-used-range">
- {recentlyUsedTimeRanges.map((range: RecentlyUsedDateTimeRange) => (
- <div
- className="recently-used-range-item"
- role="button"
- tabIndex={0}
- onKeyDown={(e): void => {
- if (e.key === 'Enter' || e.key === ' ') {
+ {showRecentlyUsed && (
+ <div className="recently-used-container">
+ <div className="time-heading">RECENTLY USED</div>
+ <div className="recently-used-range">
+ {recentlyUsedTimeRanges.map((range: RecentlyUsedDateTimeRange) => (
+ <div
+ className="recently-used-range-item"
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e): void => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ handleExitLiveLogs();
+ onCustomDateHandler([dayjs(range.from), dayjs(range.to)]);
+ setIsOpen(false);
+ }
+ }}
+ key={range.value}
+ onClick={(): void => {
handleExitLiveLogs();
onCustomDateHandler([dayjs(range.from), dayjs(range.to)]);
setIsOpen(false);
- }
- }}
- key={range.value}
- onClick={(): void => {
- handleExitLiveLogs();
- onCustomDateHandler([dayjs(range.from), dayjs(range.to)]);
- setIsOpen(false);
- }}
- >
- {range.label}
- </div>
- ))}
+ }}
+ >
+ {range.label}
+ </div>
+ ))}
+ </div>
</div>
- </div>
+ )}
</div>
)}
</div>
diff --git a/frontend/src/constants/reactQueryKeys.ts b/frontend/src/constants/reactQueryKeys.ts
index 88ab13ab26..48a1ce1288 100644
--- a/frontend/src/constants/reactQueryKeys.ts
+++ b/frontend/src/constants/reactQueryKeys.ts
@@ -1,4 +1,7 @@
export const REACT_QUERY_KEY = {
+ GET_PUBLIC_DASHBOARD: 'GET_PUBLIC_DASHBOARD',
+ GET_PUBLIC_DASHBOARD_META: 'GET_PUBLIC_DASHBOARD_META',
+ GET_PUBLIC_DASHBOARD_WIDGET_DATA: 'GET_PUBLIC_DASHBOARD_WIDGET_DATA',
GET_ALL_LICENCES: 'GET_ALL_LICENCES',
GET_QUERY_RANGE: 'GET_QUERY_RANGE',
GET_ALL_DASHBOARDS: 'GET_ALL_DASHBOARDS',
diff --git a/frontend/src/constants/routes.ts b/frontend/src/constants/routes.ts
index ab7e4ccaa5..f46cb41c33 100644
--- a/frontend/src/constants/routes.ts
+++ b/frontend/src/constants/routes.ts
@@ -81,6 +81,7 @@ const ROUTES = {
METER_EXPLORER: '/meter/explorer',
METER_EXPLORER_VIEWS: '/meter/explorer/views',
HOME_PAGE: '/',
+ PUBLIC_DASHBOARD: '/public/dashboard/:dashboardId',
} as const;
export default ROUTES;
diff --git a/frontend/src/container/AppLayout/index.tsx b/frontend/src/container/AppLayout/index.tsx
index 3d6cfd579b..68b67dcda0 100644
--- a/frontend/src/container/AppLayout/index.tsx
+++ b/frontend/src/container/AppLayout/index.tsx
@@ -35,6 +35,7 @@ import { useIsDarkMode } from 'hooks/useDarkMode';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useNotifications } from 'hooks/useNotifications';
import useTabVisibility from 'hooks/useTabFocus';
+import { useKBar } from 'kbar';
import history from 'lib/history';
import { isNull } from 'lodash-es';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
@@ -185,6 +186,19 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
const { isCloudUser: isCloudUserVal } = useGetTenantLicense();
+ const { query, disabled } = useKBar((state) => ({
+ disabled: state.disabled,
+ }));
+
+ // disable the kbar command palette when not logged in
+ useEffect(() => {
+ if (isLoggedIn) {
+ query.disable(false);
+ } else {
+ query.disable(true);
+ }
+ }, [isLoggedIn, query, disabled]);
+
const changelogForTenant = isCloudUserVal
? DeploymentType.CLOUD_ONLY
: DeploymentType.OSS_ONLY;
@@ -391,6 +405,9 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
const routeKey = useMemo(() => getRouteKey(pathname), [pathname]);
const pageTitle = t(routeKey);
+
+ const isPublicDashboard = pathname.startsWith('/public/dashboard/');
+
const renderFullScreen =
pathname === ROUTES.GET_STARTED ||
pathname === ROUTES.ONBOARDING ||
@@ -399,7 +416,8 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
pathname === ROUTES.GET_STARTED_INFRASTRUCTURE_MONITORING ||
pathname === ROUTES.GET_STARTED_LOGS_MANAGEMENT ||
pathname === ROUTES.GET_STARTED_AWS_MONITORING ||
- pathname === ROUTES.GET_STARTED_AZURE_MONITORING;
+ pathname === ROUTES.GET_STARTED_AZURE_MONITORING ||
+ isPublicDashboard;
const [showTrialExpiryBanner, setShowTrialExpiryBanner] = useState(false);
diff --git a/frontend/src/container/GridCardLayout/WidgetHeader/index.tsx b/frontend/src/container/GridCardLayout/WidgetHeader/index.tsx
index da55eaa0ff..98912d3603 100644
--- a/frontend/src/container/GridCardLayout/WidgetHeader/index.tsx
+++ b/frontend/src/container/GridCardLayout/WidgetHeader/index.tsx
@@ -304,14 +304,19 @@ function WidgetHeader({
data-testid="widget-header-search"
/>
)}
- <Dropdown menu={menu} trigger={['hover']} placement="bottomRight">
- <MoreOutlined
- data-testid="widget-header-options"
- className={`widget-header-more-options ${
- parentHover ? 'widget-header-hover' : ''
- } ${globalSearchAvailable ? 'widget-header-more-options-visible' : ''}`}
- />
- </Dropdown>
+
+ {menu && Array.isArray(menu.items) && menu.items.length > 0 && (
+ <Dropdown menu={menu} trigger={['hover']} placement="bottomRight">
+ <MoreOutlined
+ data-testid="widget-header-options"
+ className={`widget-header-more-options ${
+ parentHover ? 'widget-header-hover' : ''
+ } ${
+ globalSearchAvailable ? 'widget-header-more-options-visible' : ''
+ }`}
+ />
+ </Dropdown>
+ )}
</div>
</>
)}
diff --git a/frontend/src/container/NewDashboard/DashboardDescription/Description.styles.scss b/frontend/src/container/NewDashboard/DashboardDescription/Description.styles.scss
index f2b20f0d37..75e4381b80 100644
--- a/frontend/src/container/NewDashboard/DashboardDescription/Description.styles.scss
+++ b/frontend/src/container/NewDashboard/DashboardDescription/Description.styles.scss
@@ -68,7 +68,7 @@
display: flex;
gap: 6px;
align-items: center;
- max-width: 100%;
+ max-width: 80%;
.dashboard-btn {
display: flex;
@@ -130,7 +130,6 @@
.left-section {
display: flex;
-
align-items: center;
gap: 8px;
width: 45%;
@@ -148,16 +147,17 @@
font-weight: 500;
line-height: 24px; /* 150% */
letter-spacing: -0.08px;
- flex-shrink: 0;
-
- flex: 1;
- min-width: fit-content;
+ max-width: 80%;
display: -webkit-box;
- -webkit-line-clamp: 3;
+ -webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
}
+
+ .public-dashboard-icon {
+ margin-right: 4px;
+ }
}
.right-section {
diff --git a/frontend/src/container/NewDashboard/DashboardDescription/SettingsDrawer.tsx b/frontend/src/container/NewDashboard/DashboardDescription/SettingsDrawer.tsx
index e06332e562..425da4bc7e 100644
--- a/frontend/src/container/NewDashboard/DashboardDescription/SettingsDrawer.tsx
+++ b/frontend/src/container/NewDashboard/DashboardDescription/SettingsDrawer.tsx
@@ -17,7 +17,7 @@ function SettingsDrawer({ drawerTitle }: { drawerTitle: string }): JSX.Element {
setVisible(true);
};
- const onClose = (): void => {
+ const handleClose = (): void => {
setVisible(false);
variableViewModeRef?.current?.();
};
@@ -38,7 +38,7 @@ function SettingsDrawer({ drawerTitle }: { drawerTitle: string }): JSX.Element {
title={drawerTitle}
placement="right"
width="50%"
- onClose={onClose}
+ onClose={handleClose}
open={visible}
rootClassName="settings-container-root"
>
diff --git a/frontend/src/container/NewDashboard/DashboardDescription/index.tsx b/frontend/src/container/NewDashboard/DashboardDescription/index.tsx
index e620b9f337..8e5ae7203f 100644
--- a/frontend/src/container/NewDashboard/DashboardDescription/index.tsx
+++ b/frontend/src/container/NewDashboard/DashboardDescription/index.tsx
@@ -17,6 +17,7 @@ import { PANEL_GROUP_TYPES, PANEL_TYPES } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import { DeleteButton } from 'container/ListOfDashboard/TableComponents/DeleteButton';
import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
+import { useGetPublicDashboardMeta } from 'hooks/dashboard/useGetPublicDashboardMeta';
import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
import useComponentPermission from 'hooks/useComponentPermission';
import { useNotifications } from 'hooks/useNotifications';
@@ -29,6 +30,7 @@ import {
FileJson,
FolderKanban,
Fullscreen,
+ Globe,
LayoutGrid,
LockKeyhole,
PenLine,
@@ -128,6 +130,8 @@ function DashboardDescription(props: DashboardDescriptionProps): JSX.Element {
false,
);
+ const [isPublicDashboard, setIsPublicDashboard] = useState<boolean>(false);
+
let isAuthor = false;
if (selectedDashboard && user && user.email) {
@@ -297,6 +301,38 @@ function DashboardDescription(props: DashboardDescriptionProps): JSX.Element {
safeNavigate(generatedUrl);
}
+ const {
+ data: publicDashboardResponse,
+ // refetch: refetchPublicDashboardData,
+ isLoading: isLoadingPublicDashboardData,
+ isFetching: isFetchingPublicDashboardData,
+ error: errorPublicDashboardData,
+ isError: isErrorPublicDashboardData,
+ } = useGetPublicDashboardMeta(selectedDashboard?.id || '');
+
+ useEffect(() => {
+ if (!isLoadingPublicDashboardData && !isFetchingPublicDashboardData) {
+ if (isErrorPublicDashboardData) {
+ const errorDetails = errorPublicDashboardData?.getErrorDetails();
+
+ if (errorDetails?.error?.code === 'public_dashboard_not_found') {
+ setIsPublicDashboard(false);
+ }
+ } else {
+ const publicDashboardData = publicDashboardResponse?.data;
+ if (publicDashboardData?.publicPath) {
+ setIsPublicDashboard(true);
+ }
+ }
+ }
+ }, [
+ isLoadingPublicDashboardData,
+ isFetchingPublicDashboardData,
+ isErrorPublicDashboardData,
+ errorPublicDashboardData,
+ publicDashboardResponse?.data,
+ ]);
+
return (
<Card className="dashboard-description-container">
<div className="dashboard-header">
@@ -333,11 +369,21 @@ function DashboardDescription(props: DashboardDescriptionProps): JSX.Element {
className="dashboard-title"
data-testid="dashboard-title"
>
- {' '}
{title}
</Typography.Text>
</Tooltip>
- {isDashboardLocked && <LockKeyhole size={14} />}
+
+ {isPublicDashboard && (
+ <Tooltip title="This dashboard is publicly accessible">
+ <Globe size={14} className="public-dashboard-icon" />
+ </Tooltip>
+ )}
+
+ {isDashboardLocked && (
+ <Tooltip title="This dashboard is locked">
+ <LockKeyhole size={14} className="lock-dashboard-icon" />
+ </Tooltip>
+ )}
</div>
<div className="right-section">
<DateTimeSelectionV2 showAutoRefresh hideShareModal />
diff --git a/frontend/src/container/NewDashboard/DashboardSettings/DashboardSettingsContent.styles.scss b/frontend/src/container/NewDashboard/DashboardSettings/DashboardSettingsContent.styles.scss
index dac33f7ce1..1620cbb3aa 100644
--- a/frontend/src/container/NewDashboard/DashboardSettings/DashboardSettingsContent.styles.scss
+++ b/frontend/src/container/NewDashboard/DashboardSettings/DashboardSettingsContent.styles.scss
@@ -1,6 +1,5 @@
.settings-tabs {
.ant-tabs-nav-list {
- width: 228px;
height: 32px;
flex-shrink: 0;
border-radius: 2px;
@@ -13,6 +12,10 @@
margin: 0px;
}
+ .ant-tabs-tab:not(:last-child) {
+ border-right: 1px solid var(--bg-slate-400) !important;
+ }
+
.overview-btn {
width: 114px;
display: flex;
@@ -27,6 +30,13 @@
justify-content: center;
}
+ .public-dashboard-btn {
+ width: 150px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+
.ant-tabs-ink-bar {
display: none;
}
@@ -41,6 +51,11 @@
border-radius: 2px 0px 0px 2px;
background: var(--bg-slate-400);
}
+
+ .public-dashboard-btn {
+ border-radius: 2px 0px 0px 2px;
+ background: var(--bg-slate-400);
+ }
}
}
@@ -63,6 +78,10 @@
.variables-btn {
background: var(--bg-vanilla-300);
}
+
+ .public-dashboard-btn {
+ background: var(--bg-vanilla-300);
+ }
}
}
}
diff --git a/frontend/src/container/NewDashboard/DashboardSettings/PublicDashboard/PublicDashboard.styles.scss b/frontend/src/container/NewDashboard/DashboardSettings/PublicDashboard/PublicDashboard.styles.scss
new file mode 100644
index 0000000000..eaa27430c0
--- /dev/null
+++ b/frontend/src/container/NewDashboard/DashboardSettings/PublicDashboard/PublicDashboard.styles.scss
@@ -0,0 +1,132 @@
+.public-dashboard-setting-container {
+ border-radius: 3px;
+ border: 1px solid var(--bg-slate-500);
+ padding: 16px !important;
+
+ .public-dashboard-setting-content {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+
+ .public-dashboard-setting-content-title {
+ margin-bottom: 16px;
+ }
+
+ .timerange-enabled-checkbox {
+ margin-bottom: 8px;
+ }
+
+ .default-time-range-select {
+ margin-bottom: 8px;
+
+ .default-time-range-select-label {
+ margin-bottom: 4px;
+
+ .default-time-range-select-label-text {
+ font-size: 12px;
+ font-weight: 500;
+ }
+ }
+
+ .ant-select-selector {
+ display: flex;
+ height: 32px;
+ padding: 6px;
+ justify-content: center;
+ align-items: center;
+ border-radius: 2px 0px 0px 2px;
+ border: 1px solid var(--bg-slate-400);
+ background: var(--bg-ink-300);
+
+ .ant-select-selection-item {
+ display: flex;
+ align-items: center;
+
+ .list-item-image {
+ height: 16px;
+ width: 16px;
+ }
+ }
+ }
+ }
+
+ .public-dashboard-url {
+ .url-label-container {
+ margin-bottom: 4px;
+
+ .url-label {
+ font-size: 12px;
+ font-weight: 500;
+ }
+ }
+
+ .url-container {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ border: 1px solid var(--bg-slate-400);
+ background: var(--bg-ink-300);
+ border-radius: 4px;
+ padding: 0px 4px;
+
+ .url-text {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ }
+ }
+
+ .default-time-range-select-dropdown {
+ width: 200px;
+ }
+
+ .public-dashboard-setting-callout {
+ margin-top: 12px;
+ background: color-mix(in srgb, var(--bg-robin-500) 10%, transparent);
+ padding: 12px 8px;
+ border-radius: 3px;
+
+ .public-dashboard-setting-callout-text {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
+ font-size: 11px;
+ font-weight: 400;
+ color: var(--text-robin-300);
+ }
+ }
+ }
+
+ .public-dashboard-setting-actions {
+ margin-top: 32px;
+ display: flex;
+ gap: 8px;
+ justify-content: flex-end;
+ }
+}
+
+.lightMode {
+ .public-dashboard-setting-container {
+ border: 1px solid var(--bg-vanilla-300);
+ background: var(--bg-vanilla-100);
+
+ .public-dashboard-setting-content {
+ .default-time-range-select {
+ .ant-select-selector {
+ border: 1px solid var(--bg-vanilla-300);
+ background: var(--bg-vanilla-100);
+ }
+ }
+
+ .public-dashboard-url {
+ .url-container {
+ border: 1px solid var(--bg-vanilla-300);
+ background: var(--bg-vanilla-100);
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/src/container/NewDashboard/DashboardSettings/PublicDashboard/__tests__/PublicDashboard.test.tsx b/frontend/src/container/NewDashboard/DashboardSettings/PublicDashboard/__tests__/PublicDashboard.test.tsx
new file mode 100644
index 0000000000..87cd47f986
--- /dev/null
+++ b/frontend/src/container/NewDashboard/DashboardSettings/PublicDashboard/__tests__/PublicDashboard.test.tsx
@@ -0,0 +1,382 @@
+import { toast } from '@signozhq/sonner';
+import { fireEvent, within } from '@testing-library/react';
+import { StatusCodes } from 'http-status-codes';
+import {
+ publishedPublicDashboardMeta,
+ unpublishedPublicDashboardMeta,
+} from 'mocks-server/__mockdata__/publicDashboard';
+import { rest, server } from 'mocks-server/server';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { useCopyToClipboard } from 'react-use';
+import { render, screen, userEvent, waitFor } from 'tests/test-utils';
+
+import PublicDashboardSetting from '../index';
+
+// Mock dependencies
+jest.mock('providers/Dashboard/Dashboard');
+jest.mock('react-use', () => ({
+ ...jest.requireActual('react-use'),
+ useCopyToClipboard: jest.fn(),
+}));
+jest.mock('@signozhq/sonner', () => ({
+ toast: {
+ success: jest.fn(),
+ error: jest.fn(),
+ },
+}));
+
+const mockUseDashboard = jest.mocked(useDashboard);
+const mockUseCopyToClipboard = jest.mocked(useCopyToClipboard);
+const mockToast = jest.mocked(toast);
+
+// Test constants
+const MOCK_DASHBOARD_ID = 'test-dashboard-id';
+const MOCK_PUBLIC_PATH = '/public/dashboard/test-dashboard-id';
+const DEFAULT_TIME_RANGE = '30m';
+const DASHBOARD_VARIABLES_WARNING =
+ "Dashboard variables won't work in public dashboards";
+
+// Use wildcard pattern to match both relative and absolute URLs in MSW
+const publicDashboardURL = `*/api/v1/dashboards/${MOCK_DASHBOARD_ID}/public`;
+
+const mockSelectedDashboard = {
+ id: MOCK_DASHBOARD_ID,
+ data: {
+ title: 'Test Dashboard',
+ widgets: [],
+ layout: [],
+ panelMap: {},
+ variables: {},
+ },
+};
+
+beforeAll(() => {
+ server.listen();
+});
+
+afterAll(() => {
+ server.close();
+});
+
+const mockSetCopyPublicDashboardURL = jest.fn();
+
+beforeEach(() => {
+ jest.clearAllMocks();
+
+ // Mock window.open
+ window.open = jest.fn();
+
+ // Mock useDashboard
+ mockUseDashboard.mockReturnValue(({
+ selectedDashboard: mockSelectedDashboard,
+ } as unknown) as ReturnType<typeof useDashboard>);
+
+ // Mock useCopyToClipboard
+ mockUseCopyToClipboard.mockReturnValue(([
+ undefined,
+ mockSetCopyPublicDashboardURL,
+ ] as unknown) as ReturnType<typeof useCopyToClipboard>);
+});
+
+afterEach(() => {
+ server.resetHandlers();
+ jest.clearAllMocks();
+});
+
+describe('PublicDashboardSetting', () => {
+ describe('Unpublished Dashboard', () => {
+ it('Unpublished dashboard should be handled correctly', async () => {
+ server.use(
+ rest.get(
+ `*/api/v1/dashboards/${MOCK_DASHBOARD_ID}/public`,
+ (_req, res, ctx) =>
+ res(
+ ctx.status(StatusCodes.NOT_FOUND),
+ ctx.json(unpublishedPublicDashboardMeta),
+ ),
+ ),
+ );
+
+ render(<PublicDashboardSetting />);
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(
+ /This dashboard is private. Publish it to make it accessible to anyone with the link./i,
+ ),
+ ).toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(
+ screen.getByRole('checkbox', { name: /enable time range/i }),
+ ).toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText(/default time range/i)).toBeInTheDocument();
+ });
+
+ expect(screen.getByText(/Last 30 minutes/i)).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(new RegExp(DASHBOARD_VARIABLES_WARNING, 'i')),
+ ).toBeInTheDocument();
+ });
+
+ expect(
+ screen.getByRole('button', { name: /publish dashboard/i }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe('Published Dashboard', () => {
+ it('Published dashboard should be handled correctly', async () => {
+ server.use(
+ rest.get(
+ `*/api/v1/dashboards/${MOCK_DASHBOARD_ID}/public`,
+ (_req, res, ctx) =>
+ res(ctx.status(StatusCodes.OK), ctx.json(publishedPublicDashboardMeta)),
+ ),
+ );
+
+ render(<PublicDashboardSetting />);
+
+ await waitFor(() => {
+ expect(
+ screen.getByText(
+ /This dashboard is publicly accessible. Anyone with the link can view it./i,
+ ),
+ ).toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(
+ screen.getByRole('checkbox', { name: /enable time range/i }),
+ ).toBeChecked();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText(/default time range/i)).toBeInTheDocument();
+ });
+
+ expect(screen.getByText(/Last 30 minutes/i)).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(screen.getByText(/Public Dashboard URL/i)).toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', { name: /update published dashboard/i }),
+ ).toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', { name: /unpublish dashboard/i }),
+ ).toBeInTheDocument();
+ });
+ });
+ });
+
+ describe('Time Range Settings', () => {
+ beforeEach(() => {
+ server.use(
+ rest.get(
+ `*/api/v1/dashboards/${MOCK_DASHBOARD_ID}/public`,
+ (_req, res, ctx) =>
+ res(ctx.status(StatusCodes.OK), ctx.json(publishedPublicDashboardMeta)),
+ ),
+ );
+ });
+
+ it('should toggle time range enabled when checkbox is clicked', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ render(<PublicDashboardSetting />);
+
+ // Wait for checkbox to be rendered and verify initial state
+ const checkbox = await screen.findByRole('checkbox', {
+ name: /enable time range/i,
+ });
+ expect(checkbox).toBeChecked();
+
+ await user.click(checkbox);
+
+ await waitFor(() => {
+ expect(checkbox).not.toBeChecked();
+ });
+ });
+
+ it('should update default time range when select value changes', async () => {
+ render(<PublicDashboardSetting />);
+
+ const selectContainer = await screen.findByTestId(
+ 'default-time-range-select-dropdown',
+ );
+
+ const combobox = within(selectContainer).getByRole('combobox');
+
+ fireEvent.mouseDown(combobox);
+
+ await screen.findByRole('listbox');
+
+ const option = await screen.findByText(/Last 1 hour/i, {
+ selector: '.ant-select-item-option-content',
+ });
+ fireEvent.click(option);
+
+ await waitFor(() => {
+ expect(
+ within(selectContainer).getByText(/Last 1 hour/i),
+ ).toBeInTheDocument();
+ });
+ });
+ });
+
+ describe('Create Public Dashboard', () => {
+ it('should call create API when publish button is clicked', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let createApiCalled = false;
+
+ server.use(
+ rest.get(publicDashboardURL, (_req, res, ctx) =>
+ res(
+ ctx.status(StatusCodes.OK),
+ ctx.json({
+ data: {
+ timeRangeEnabled: true,
+ defaultTimeRange: DEFAULT_TIME_RANGE,
+ publicPath: '',
+ },
+ }),
+ ),
+ ),
+ rest.post(publicDashboardURL, async (req, res, ctx) => {
+ const body = await req.json();
+ createApiCalled = true;
+ expect(body).toEqual({
+ timeRangeEnabled: true,
+ defaultTimeRange: DEFAULT_TIME_RANGE,
+ });
+ return res(
+ ctx.status(StatusCodes.CREATED),
+ ctx.json({
+ data: {
+ timeRangeEnabled: true,
+ defaultTimeRange: DEFAULT_TIME_RANGE,
+ publicPath: MOCK_PUBLIC_PATH,
+ },
+ }),
+ );
+ }),
+ );
+
+ render(<PublicDashboardSetting />);
+
+ // Find and click publish button
+ const publishButton = await screen.findByRole('button', {
+ name: /publish dashboard/i,
+ });
+ await user.click(publishButton);
+
+ await waitFor(() => {
+ expect(createApiCalled).toBe(true);
+ expect(mockToast.success).toHaveBeenCalledWith(
+ 'Public dashboard created successfully',
+ );
+ });
+ });
+ });
+
+ describe('Update Public Dashboard', () => {
+ it('should call update API when update button is clicked', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let updateApiCalled = false;
+ let capturedRequestBody: {
+ timeRangeEnabled: boolean;
+ defaultTimeRange: string;
+ } | null = null;
+
+ server.use(
+ rest.get(
+ `*/api/v1/dashboards/${MOCK_DASHBOARD_ID}/public`,
+ (_req, res, ctx) =>
+ res(ctx.status(StatusCodes.OK), ctx.json(publishedPublicDashboardMeta)),
+ ),
+ rest.put(publicDashboardURL, async (req, res, ctx) => {
+ const body = await req.json();
+ updateApiCalled = true;
+ capturedRequestBody = body;
+ return res(ctx.status(StatusCodes.NO_CONTENT), ctx.json({}));
+ }),
+ );
+
+ render(<PublicDashboardSetting />);
+
+ // Wait for API response and component update
+ const updateButton = await screen.findByRole(
+ 'button',
+ { name: /update published dashboard/i },
+ { timeout: 5000 },
+ );
+ await user.click(updateButton);
+
+ await waitFor(() => {
+ expect(updateApiCalled).toBe(true);
+ expect(capturedRequestBody).toEqual({
+ timeRangeEnabled: true,
+ defaultTimeRange: DEFAULT_TIME_RANGE,
+ });
+ expect(mockToast.success).toHaveBeenCalledWith(
+ 'Public dashboard updated successfully',
+ );
+ });
+ });
+ });
+
+ describe('Revoke Public Dashboard Access', () => {
+ it('should call revoke API when unpublish button is clicked', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let revokeApiCalled = false;
+ let capturedDashboardId: string | null = null;
+
+ server.use(
+ rest.get(
+ `*/api/v1/dashboards/${MOCK_DASHBOARD_ID}/public`,
+ (_req, res, ctx) =>
+ res(ctx.status(StatusCodes.OK), ctx.json(publishedPublicDashboardMeta)),
+ ),
+ rest.delete(publicDashboardURL, (req, res, ctx) => {
+ revokeApiCalled = true;
+ // Extract dashboard ID from URL: /api/v1/dashboards/{id}/public
+ const urlMatch = req.url.pathname.match(
+ /\/api\/v1\/dashboards\/([^/]+)\/public/,
+ );
+ capturedDashboardId = urlMatch ? urlMatch[1] : null;
+ return res(ctx.status(StatusCodes.NO_CONTENT), ctx.json({}));
+ }),
+ );
+
+ render(<PublicDashboardSetting />);
+
+ // Wait for API response and component update
+ const unpublishButton = await screen.findByRole(
+ 'button',
+ { name: /unpublish dashboard/i },
+ { timeout: 5000 },
+ );
+ await user.click(unpublishButton);
+
+ await waitFor(() => {
+ expect(revokeApiCalled).toBe(true);
+ expect(capturedDashboardId).toBe(MOCK_DASHBOARD_ID);
+ expect(mockToast.success).toHaveBeenCalledWith(
+ 'Dashboard unpublished successfully',
+ );
+ });
+ });
+ });
+});
diff --git a/frontend/src/container/NewDashboard/DashboardSettings/PublicDashboard/index.tsx b/frontend/src/container/NewDashboard/DashboardSettings/PublicDashboard/index.tsx
new file mode 100644
index 0000000000..04276b8b72
--- /dev/null
+++ b/frontend/src/container/NewDashboard/DashboardSettings/PublicDashboard/index.tsx
@@ -0,0 +1,338 @@
+/* eslint-disable import/no-extraneous-dependencies */
+import './PublicDashboard.styles.scss';
+
+import { Checkbox } from '@signozhq/checkbox';
+import { toast } from '@signozhq/sonner';
+import { Button, Select, Typography } from 'antd';
+import createPublicDashboardAPI from 'api/dashboard/public/createPublicDashboard';
+import revokePublicDashboardAccessAPI from 'api/dashboard/public/revokePublicDashboardAccess';
+import updatePublicDashboardAPI from 'api/dashboard/public/updatePublicDashboard';
+import { useGetPublicDashboardMeta } from 'hooks/dashboard/useGetPublicDashboardMeta';
+import { Copy, ExternalLink, Globe, Info, Loader2, Trash } from 'lucide-react';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useMutation } from 'react-query';
+import { useCopyToClipboard } from 'react-use';
+import { PublicDashboardMetaProps } from 'types/api/dashboard/public/getMeta';
+
+export const TIME_RANGE_PRESETS_OPTIONS = [
+ {
+ label: 'Last 5 minutes',
+ value: '5m',
+ },
+ {
+ label: 'Last 15 minutes',
+ value: '15m',
+ },
+ {
+ label: 'Last 30 minutes',
+ value: '30m',
+ },
+ {
+ label: 'Last 1 hour',
+ value: '1h',
+ },
+ {
+ label: 'Last 6 hours',
+ value: '6h',
+ },
+ {
+ label: 'Last 1 day',
+ value: '24h',
+ },
+];
+
+function PublicDashboardSetting(): JSX.Element {
+ const [publicDashboardData, setPublicDashboardData] = useState<
+ PublicDashboardMetaProps | undefined
+ >(undefined);
+ const [timeRangeEnabled, setTimeRangeEnabled] = useState(true);
+ const [defaultTimeRange, setDefaultTimeRange] = useState('30m');
+ const [, setCopyPublicDashboardURL] = useCopyToClipboard();
+
+ const { selectedDashboard } = useDashboard();
+
+ const handleDefaultTimeRange = useCallback((value: string): void => {
+ setDefaultTimeRange(value);
+ }, []);
+
+ const handleTimeRangeEnabled = useCallback((): void => {
+ setTimeRangeEnabled((prev) => !prev);
+ }, []);
+
+ const {
+ data: publicDashboardResponse,
+ isLoading: isLoadingPublicDashboard,
+ isFetching: isFetchingPublicDashboard,
+ refetch: refetchPublicDashboard,
+ error: errorPublicDashboard,
+ } = useGetPublicDashboardMeta(selectedDashboard?.id || '');
+
+ const isPublicDashboardEnabled = !!publicDashboardData?.publicPath;
+
+ useEffect(() => {
+ if (publicDashboardResponse?.data) {
+ setPublicDashboardData(publicDashboardResponse?.data);
+ }
+
+ if (errorPublicDashboard) {
+ console.error('Error getting public dashboard', errorPublicDashboard);
+ setPublicDashboardData(undefined);
+ setTimeRangeEnabled(true);
+ setDefaultTimeRange('30m');
+ }
+ }, [publicDashboardResponse, errorPublicDashboard]);
+
+ useEffect(() => {
+ if (publicDashboardResponse?.data) {
+ setTimeRangeEnabled(
+ publicDashboardResponse?.data?.timeRangeEnabled || false,
+ );
+ setDefaultTimeRange(
+ publicDashboardResponse?.data?.defaultTimeRange || '30m',
+ );
+ }
+ }, [publicDashboardResponse]);
+
+ const {
+ mutate: createPublicDashboard,
+ isLoading: isLoadingCreatePublicDashboard,
+ data: createPublicDashboardResponse,
+ } = useMutation(createPublicDashboardAPI, {
+ onSuccess: () => {
+ toast.success('Public dashboard created successfully');
+ },
+ onError: () => {
+ toast.error('Failed to create public dashboard');
+ },
+ });
+
+ const {
+ mutate: updatePublicDashboard,
+ isLoading: isLoadingUpdatePublicDashboard,
+ data: updatePublicDashboardResponse,
+ } = useMutation(updatePublicDashboardAPI, {
+ onSuccess: () => {
+ toast.success('Public dashboard updated successfully');
+ },
+ onError: () => {
+ toast.error('Failed to update public dashboard');
+ },
+ });
+
+ const {
+ mutate: revokePublicDashboardAccess,
+ isLoading: isLoadingRevokePublicDashboardAccess,
+ data: revokePublicDashboardAccessResponse,
+ } = useMutation(revokePublicDashboardAccessAPI, {
+ onSuccess: () => {
+ toast.success('Dashboard unpublished successfully');
+ },
+ onError: () => {
+ toast.error('Failed to unpublish dashboard');
+ },
+ });
+
+ const handleCreatePublicDashboard = (): void => {
+ if (!selectedDashboard) return;
+
+ createPublicDashboard({
+ dashboardId: selectedDashboard.id,
+ timeRangeEnabled,
+ defaultTimeRange,
+ });
+ };
+
+ const handleUpdatePublicDashboard = (): void => {
+ if (!selectedDashboard) return;
+
+ updatePublicDashboard({
+ dashboardId: selectedDashboard.id,
+ timeRangeEnabled,
+ defaultTimeRange,
+ });
+ };
+
+ const handleRevokePublicDashboardAccess = (): void => {
+ if (!selectedDashboard) return;
+
+ revokePublicDashboardAccess({
+ id: selectedDashboard.id,
+ });
+ };
+
+ useEffect(() => {
+ if (
+ (createPublicDashboardResponse &&
+ createPublicDashboardResponse.httpStatusCode === 201) ||
+ (updatePublicDashboardResponse &&
+ updatePublicDashboardResponse.httpStatusCode === 204) ||
+ (revokePublicDashboardAccessResponse &&
+ revokePublicDashboardAccessResponse.httpStatusCode === 204)
+ ) {
+ refetchPublicDashboard();
+ }
+ }, [
+ createPublicDashboardResponse,
+ updatePublicDashboardResponse,
+ revokePublicDashboardAccessResponse,
+ refetchPublicDashboard,
+ ]);
+
+ const handleCopyPublicDashboardURL = (): void => {
+ if (!publicDashboardResponse?.data?.publicPath) return;
+
+ try {
+ setCopyPublicDashboardURL(
+ `${window.location.origin}${publicDashboardResponse?.data?.publicPath}`,
+ );
+ toast.success('Copied Public Dashboard URL successfully');
+ } catch (error) {
+ console.error('Error copying public dashboard URL', error);
+ }
+ };
+
+ const publicDashboardURL = useMemo(
+ () => `${window.location.origin}${publicDashboardResponse?.data?.publicPath}`,
+ [publicDashboardResponse],
+ );
+
+ const isLoading =
+ isLoadingCreatePublicDashboard ||
+ isLoadingUpdatePublicDashboard ||
+ isLoadingRevokePublicDashboardAccess ||
+ isLoadingPublicDashboard;
+
+ return (
+ <div className="public-dashboard-setting-container">
+ <div className="public-dashboard-setting-content">
+ <Typography.Title
+ level={5}
+ className="public-dashboard-setting-content-title"
+ >
+ {isPublicDashboardEnabled
+ ? 'This dashboard is publicly accessible. Anyone with the link can view it.'
+ : 'This dashboard is private. Publish it to make it accessible to anyone with the link.'}
+ </Typography.Title>
+
+ <div className="timerange-enabled-checkbox">
+ <Checkbox
+ id="enable-time-range"
+ checked={timeRangeEnabled}
+ onCheckedChange={handleTimeRangeEnabled}
+ labelName="Enable time range"
+ />
+ </div>
+
+ <div className="default-time-range-select">
+ <div className="default-time-range-select-label">
+ <Typography.Text className="default-time-range-select-label-text">
+ Default time range
+ </Typography.Text>
+ </div>
+ <Select
+ placeholder="Select default time range"
+ options={TIME_RANGE_PRESETS_OPTIONS}
+ value={defaultTimeRange}
+ onChange={handleDefaultTimeRange}
+ data-testid="default-time-range-select-dropdown"
+ className="default-time-range-select-dropdown"
+ />
+ </div>
+
+ {isPublicDashboardEnabled && (
+ <div className="public-dashboard-url">
+ <div className="url-label-container">
+ <Typography.Text className="url-label">
+ Public Dashboard URL
+ </Typography.Text>
+ </div>
+
+ <div className="url-container">
+ <Typography.Text className="url-text">
+ {publicDashboardURL}
+ </Typography.Text>
+
+ <Button
+ type="link"
+ className="url-copy-btn periscope-btn ghost"
+ icon={<Copy size={12} />}
+ onClick={handleCopyPublicDashboardURL}
+ />
+ <Button
+ type="link"
+ className="periscope-btn ghost"
+ icon={<ExternalLink size={12} />}
+ onClick={(): void => {
+ if (publicDashboardURL) {
+ window.open(publicDashboardURL, '_blank');
+ }
+ }}
+ />
+ </div>
+ </div>
+ )}
+
+ <div className="public-dashboard-setting-callout">
+ <Typography.Text className="public-dashboard-setting-callout-text">
+ <Info size={12} className="public-dashboard-setting-callout-icon" />{' '}
+ Dashboard variables won&apos;t work in public dashboards
+ </Typography.Text>
+ </div>
+
+ <div className="public-dashboard-setting-actions">
+ {!isPublicDashboardEnabled ? (
+ <Button
+ type="primary"
+ className="create-public-dashboard-btn periscope-btn primary"
+ disabled={isLoading}
+ onClick={handleCreatePublicDashboard}
+ loading={
+ isLoadingCreatePublicDashboard ||
+ isFetchingPublicDashboard ||
+ isLoadingPublicDashboard
+ }
+ icon={
+ isLoadingCreatePublicDashboard ||
+ isFetchingPublicDashboard ||
+ isLoadingPublicDashboard ? (
+ <Loader2 className="animate-spin" size={14} />
+ ) : (
+ <Globe size={14} />
+ )
+ }
+ >
+ Publish dashboard
+ </Button>
+ ) : (
+ <>
+ <Button
+ type="default"
+ className="periscope-btn secondary"
+ disabled={isLoading}
+ onClick={handleRevokePublicDashboardAccess}
+ loading={isLoadingRevokePublicDashboardAccess}
+ icon={<Trash size={14} />}
+ >
+ Unpublish dashboard
+ </Button>
+
+ <Button
+ type="primary"
+ className="create-public-dashboard-btn periscope-btn primary"
+ disabled={isLoading}
+ onClick={handleUpdatePublicDashboard}
+ loading={isLoadingUpdatePublicDashboard}
+ icon={<Globe size={14} />}
+ >
+ Update published dashboard
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default PublicDashboardSetting;
diff --git a/frontend/src/container/NewDashboard/DashboardSettings/index.tsx b/frontend/src/container/NewDashboard/DashboardSettings/index.tsx
index d046ddf8fd..c20f934582 100644
--- a/frontend/src/container/NewDashboard/DashboardSettings/index.tsx
+++ b/frontend/src/container/NewDashboard/DashboardSettings/index.tsx
@@ -1,9 +1,10 @@
import './DashboardSettingsContent.styles.scss';
import { Button, Tabs } from 'antd';
-import { Braces, Table } from 'lucide-react';
+import { Braces, Globe, Table } from 'lucide-react';
import GeneralDashboardSettings from './General';
+import PublicDashboardSetting from './PublicDashboard';
import VariablesSetting from './Variables';
function DashboardSettingsContent({
@@ -30,6 +31,19 @@ function DashboardSettingsContent({
key: 'variables',
children: <VariablesSetting variableViewModeRef={variableViewModeRef} />,
},
+ {
+ label: (
+ <Button
+ type="text"
+ icon={<Globe size={14} />}
+ className="public-dashboard-btn"
+ >
+ Publish
+ </Button>
+ ),
+ key: 'public-dashboard',
+ children: <PublicDashboardSetting />,
+ },
];
return <Tabs items={items} animated className="settings-tabs" />;
diff --git a/frontend/src/container/PublicDashboardContainer/Panel.tsx b/frontend/src/container/PublicDashboardContainer/Panel.tsx
new file mode 100644
index 0000000000..fcc75ce83c
--- /dev/null
+++ b/frontend/src/container/PublicDashboardContainer/Panel.tsx
@@ -0,0 +1,146 @@
+import { ENTITY_VERSION_V5 } from 'constants/app';
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import EmptyWidget from 'container/GridCardLayout/EmptyWidget';
+import WidgetGraphComponent from 'container/GridCardLayout/GridCard/WidgetGraphComponent';
+import { populateMultipleResults } from 'container/NewWidget/LeftContainer/WidgetGraph/util';
+import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
+import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
+import { memo, useCallback, useMemo, useRef } from 'react';
+import { Widgets } from 'types/api/dashboard/getAll';
+import { DataSource } from 'types/common/queryBuilder';
+import { getGraphType } from 'utils/getGraphType';
+import { getSortedSeriesData } from 'utils/getSortedSeriesData';
+
+function Panel({
+ widget,
+ index,
+ dashboardId,
+ startTime,
+ endTime,
+}: {
+ widget: Widgets;
+ index: number;
+ dashboardId: string;
+ startTime: number;
+ endTime: number;
+}): JSX.Element {
+ const graphRef = useRef<HTMLDivElement>(null);
+ const updatedQuery = widget?.query;
+
+ const requestData: GetQueryResultsProps = useMemo(() => {
+ if (widget.panelTypes !== PANEL_TYPES.LIST) {
+ return {
+ selectedTime: widget?.timePreferance,
+ graphType: getGraphType(widget.panelTypes),
+ query: updatedQuery,
+ variables: {}, // we are not supporting variables in public dashboards
+ fillGaps: widget.fillSpans,
+ formatForWeb: widget.panelTypes === PANEL_TYPES.TABLE,
+ start: startTime,
+ end: endTime,
+ originalGraphType: widget.panelTypes,
+ };
+ }
+
+ updatedQuery.builder.queryData[0].pageSize = 10;
+ const initialDataSource = updatedQuery.builder.queryData[0].dataSource;
+
+ return {
+ query: updatedQuery,
+ graphType: PANEL_TYPES.LIST,
+ selectedTime: widget.timePreferance || 'GLOBAL_TIME',
+ tableParams: {
+ pagination: {
+ offset: 0,
+ limit: updatedQuery.builder.queryData[0].limit || 0,
+ },
+ // we do not need select columns in case of logs
+ selectColumns:
+ initialDataSource === DataSource.TRACES && widget.selectedTracesFields,
+ },
+ fillGaps: widget.fillSpans,
+ start: startTime,
+ end: endTime,
+ };
+ }, [widget, updatedQuery, startTime, endTime]);
+
+ const queryResponse = useGetQueryRange(
+ {
+ ...requestData,
+ originalGraphType: widget?.panelTypes,
+ },
+ ENTITY_VERSION_V5,
+ {
+ queryKey: [
+ widget?.query,
+ widget?.panelTypes,
+ requestData,
+ startTime,
+ endTime,
+ ],
+ retry(failureCount, error): boolean {
+ if (
+ String(error).includes('status: error') &&
+ String(error).includes('i/o timeout')
+ ) {
+ return false;
+ }
+
+ return failureCount < 2;
+ },
+ keepPreviousData: true,
+ enabled: !!widget?.query,
+ refetchOnMount: false,
+ },
+ {},
+ {
+ isPublic: true,
+ widgetIndex: index,
+ publicDashboardId: dashboardId,
+ },
+ );
+
+ const isEmptyLayout = widget?.id === PANEL_TYPES.EMPTY_WIDGET;
+
+ if (queryResponse.data && widget.panelTypes === PANEL_TYPES.BAR) {
+ const sortedSeriesData = getSortedSeriesData(
+ queryResponse.data?.payload.data.result,
+ );
+ queryResponse.data.payload.data.result = sortedSeriesData;
+ }
+
+ if (queryResponse.data && widget.panelTypes === PANEL_TYPES.PIE) {
+ const transformedData = populateMultipleResults(queryResponse?.data);
+ // eslint-disable-next-line no-param-reassign
+ queryResponse.data = transformedData;
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const onDragSelect = useCallback((_start: number, _end: number): void => {
+ // Handle drag select if needed - no-op for public dashboards
+ }, []);
+
+ return (
+ <div
+ className="panel-container"
+ style={{ height: '100%', width: '100%' }}
+ ref={graphRef}
+ >
+ {isEmptyLayout ? (
+ <EmptyWidget />
+ ) : (
+ <WidgetGraphComponent
+ widget={widget}
+ queryResponse={queryResponse}
+ errorMessage={undefined}
+ headerMenuList={[]}
+ isWarning={false}
+ isFetchingResponse={queryResponse.isFetching || queryResponse.isLoading}
+ onDragSelect={onDragSelect}
+ />
+ )}
+ </div>
+ );
+}
+
+export default memo(Panel);
diff --git a/frontend/src/container/PublicDashboardContainer/PublicDashboardContainer.styles.scss b/frontend/src/container/PublicDashboardContainer/PublicDashboardContainer.styles.scss
new file mode 100644
index 0000000000..ee28b33b9b
--- /dev/null
+++ b/frontend/src/container/PublicDashboardContainer/PublicDashboardContainer.styles.scss
@@ -0,0 +1,109 @@
+.public-dashboard-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ width: 100%;
+
+ .public-dashboard-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ width: 100%;
+ padding: 8px 16px;
+ border-bottom: 1px solid var(--bg-slate-400);
+ background: var(--bg-ink-300);
+
+ position: sticky;
+ top: 0;
+ z-index: 999;
+
+ .public-dashboard-header-left {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+
+ width: 50%;
+
+ .brand-logo {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
+ width: 100px;
+ }
+
+ .public-dashboard-header-title {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: calc(100% - 100px);
+
+ .public-dashboard-header-title-text {
+ font-family: 'Work Sans', sans-serif;
+ font-size: 14px;
+ font-style: normal;
+ font-weight: 500;
+ line-height: 18px;
+
+ // ellipsis text
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 100%;
+ }
+ }
+ }
+
+ .public-dashboard-header-right {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+
+ .datetime-section {
+ .time-range-select-dropdown {
+ width: 200px;
+ }
+ }
+ }
+
+ .brand-logo {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+
+ .brand-logo-name {
+ font-family: 'Work Sans', sans-serif;
+ font-size: 14px;
+ font-style: normal;
+ font-weight: 500;
+ line-height: 18px;
+ }
+
+ .brand-logo-img {
+ height: 24px;
+ width: 24px;
+ }
+ }
+
+ .public-dashboard-content {
+ width: 100%;
+ height: 100%;
+ }
+
+ .fullscreen-grid-container {
+ margin: 0px 8px;
+ }
+}
+
+.lightMode {
+ .public-dashboard-container {
+ .public-dashboard-header {
+ background: var(--bg-vanilla-100);
+ border-bottom: 1px solid var(--bg-vanilla-300);
+ }
+ }
+}
diff --git a/frontend/src/container/PublicDashboardContainer/PublicDashboardContainer.tsx b/frontend/src/container/PublicDashboardContainer/PublicDashboardContainer.tsx
new file mode 100644
index 0000000000..59428a79ba
--- /dev/null
+++ b/frontend/src/container/PublicDashboardContainer/PublicDashboardContainer.tsx
@@ -0,0 +1,241 @@
+import './PublicDashboardContainer.styles.scss';
+
+import { Typography } from 'antd';
+import cx from 'classnames';
+import { PANEL_GROUP_TYPES, PANEL_TYPES } from 'constants/queryBuilder';
+import { themeColors } from 'constants/theme';
+import { Card, CardContainer } from 'container/GridCardLayout/styles';
+import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
+import {
+ CustomTimeType,
+ Time,
+} from 'container/TopNav/DateTimeSelectionV2/config';
+import dayjs from 'dayjs';
+import { useIsDarkMode } from 'hooks/useDarkMode';
+import GetMinMax from 'lib/getMinMax';
+import { useMemo, useState } from 'react';
+import RGL, { WidthProvider } from 'react-grid-layout';
+import { SuccessResponseV2 } from 'types/api';
+import { Widgets } from 'types/api/dashboard/getAll';
+import { PublicDashboardDataProps } from 'types/api/dashboard/public/get';
+
+import Panel from './Panel';
+
+const ReactGridLayoutComponent = WidthProvider(RGL);
+
+const CUSTOM_TIME_REGEX = /^(\d+)([mhdw])$/;
+
+const getStartTimeAndEndTimeFromTimeRange = (
+ timeRange: string,
+): { startTime: number; endTime: number } => {
+ const isValidFormat = CUSTOM_TIME_REGEX.test(timeRange);
+
+ if (isValidFormat) {
+ const match = timeRange.match(CUSTOM_TIME_REGEX) as RegExpMatchArray;
+
+ const timeValue = parseInt(match[1] as string, 10);
+ const timeUnit = match[2] as string;
+
+ switch (timeUnit) {
+ case 'm':
+ return {
+ startTime: dayjs().subtract(timeValue, 'minutes').unix(),
+ endTime: dayjs().unix(),
+ };
+ case 'h':
+ return {
+ startTime: dayjs().subtract(timeValue, 'hours').unix(),
+ endTime: dayjs().unix(),
+ };
+ case 'd':
+ return {
+ startTime: dayjs().subtract(timeValue, 'days').unix(),
+ endTime: dayjs().unix(),
+ };
+ case 'w':
+ return {
+ startTime: dayjs().subtract(timeValue, 'weeks').unix(),
+ endTime: dayjs().unix(),
+ };
+ default:
+ return { startTime: dayjs().unix(), endTime: dayjs().unix() };
+ }
+ }
+
+ return {
+ startTime: dayjs().subtract(30, 'minutes').unix(),
+ endTime: dayjs().unix(),
+ };
+};
+
+function PublicDashboardContainer({
+ publicDashboardId,
+ publicDashboardData,
+}: {
+ publicDashboardId: string;
+ publicDashboardData: SuccessResponseV2<PublicDashboardDataProps>;
+}): JSX.Element {
+ const isDarkMode = useIsDarkMode();
+ const { dashboard, publicDashboard } = publicDashboardData?.data || {};
+ const { widgets } = dashboard?.data || {};
+
+ const [selectedTimeRangeLabel, setSelectedTimeRangeLabel] = useState<string>(
+ publicDashboard?.defaultTimeRange || '30m',
+ );
+
+ const [selectedTimeRange, setSelectedTimeRange] = useState<{
+ startTime: number;
+ endTime: number;
+ }>(
+ getStartTimeAndEndTimeFromTimeRange(
+ publicDashboard?.defaultTimeRange || '30m',
+ ),
+ );
+
+ const isTimeRangeEnabled = publicDashboard?.timeRangeEnabled || false;
+
+ // Memoize dashboardLayout to prevent array recreation on every render
+ const dashboardLayout = useMemo(() => dashboard?.data?.layout || [], [
+ dashboard?.data?.layout,
+ ]);
+
+ const currentPanelMap = useMemo(() => dashboard?.data?.panelMap || {}, [
+ dashboard?.data?.panelMap,
+ ]);
+
+ const handleTimeChange = (
+ interval: Time | CustomTimeType,
+ dateTimeRange?: [number, number],
+ ): void => {
+ if (dateTimeRange) {
+ setSelectedTimeRange({
+ startTime: Math.floor(dateTimeRange[0] / 1000),
+ endTime: Math.floor(dateTimeRange[1] / 1000),
+ });
+ } else if (interval !== 'custom') {
+ const { maxTime, minTime } = GetMinMax(interval);
+
+ setSelectedTimeRange({
+ startTime: Math.floor(minTime / 1000000000),
+ endTime: Math.floor(maxTime / 1000000000),
+ });
+ }
+
+ setSelectedTimeRangeLabel(interval as string);
+ };
+
+ return (
+ <div className="public-dashboard-container">
+ <div className="public-dashboard-header">
+ <div className="public-dashboard-header-left">
+ <div className="brand-logo">
+ <img
+ src="/Logos/signoz-brand-logo.svg"
+ alt="SigNoz"
+ className="brand-logo-img"
+ />
+
+ <Typography className="brand-logo-name">SigNoz</Typography>
+ </div>
+
+ <div className="public-dashboard-header-title">
+ <Typography.Text className="public-dashboard-header-title-text">
+ {dashboard?.data?.title}
+ </Typography.Text>
+ </div>
+ </div>
+
+ {isTimeRangeEnabled && (
+ <div className="public-dashboard-header-right">
+ <div className="datetime-section">
+ <DateTimeSelectionV2
+ showAutoRefresh={false}
+ showRefreshText={false}
+ hideShareModal
+ onTimeChange={handleTimeChange}
+ defaultRelativeTime={publicDashboard?.defaultTimeRange as Time}
+ isModalTimeSelection
+ modalSelectedInterval={selectedTimeRangeLabel as Time}
+ disableUrlSync
+ showRecentlyUsed={false}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+
+ <div className="public-dashboard-content fullscreen-grid-container">
+ <ReactGridLayoutComponent
+ cols={12}
+ rowHeight={45}
+ autoSize
+ width={100}
+ useCSSTransforms
+ isDraggable={false}
+ isDroppable={false}
+ isResizable={false}
+ allowOverlap={false}
+ layout={dashboardLayout}
+ style={{ backgroundColor: isDarkMode ? '' : themeColors.snowWhite }}
+ >
+ {dashboardLayout?.map((layout) => {
+ const { i: id } = layout;
+ const currentWidget = (widgets || [])?.find((e) => e.id === id);
+ const currentWidgetIndex = (widgets || [])?.findIndex((e) => e.id === id);
+
+ if (currentWidget?.panelTypes === PANEL_GROUP_TYPES.ROW) {
+ const rowWidgetProperties = currentPanelMap[id] || {};
+ let { title } = currentWidget;
+ if (rowWidgetProperties.collapsed) {
+ const widgetCount = rowWidgetProperties.widgets?.length || 0;
+ const collapsedText = `(${widgetCount} widget${
+ widgetCount > 1 ? 's' : ''
+ })`;
+ title += ` ${collapsedText}`;
+ }
+
+ return (
+ <CardContainer
+ isDarkMode={isDarkMode}
+ className="row-card"
+ key={id}
+ data-grid={JSON.stringify(currentWidget)}
+ >
+ <div className={cx('row-panel')}>
+ <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
+ <Typography.Text className="section-title">{title}</Typography.Text>
+ </div>
+ </div>
+ </CardContainer>
+ );
+ }
+
+ return (
+ <CardContainer
+ isDarkMode={isDarkMode}
+ key={id}
+ data-grid={JSON.stringify(currentWidget)}
+ >
+ <Card
+ className="grid-item"
+ isDarkMode={isDarkMode}
+ $panelType={currentWidget?.panelTypes || PANEL_TYPES.TIME_SERIES}
+ >
+ <Panel
+ dashboardId={publicDashboardId}
+ widget={(currentWidget as Widgets) || ({ id, query: {} } as Widgets)}
+ index={currentWidgetIndex}
+ startTime={selectedTimeRange.startTime}
+ endTime={selectedTimeRange.endTime}
+ />
+ </Card>
+ </CardContainer>
+ );
+ })}
+ </ReactGridLayoutComponent>
+ </div>
+ </div>
+ );
+}
+
+export default PublicDashboardContainer;
diff --git a/frontend/src/container/PublicDashboardContainer/__tests__/PublicDashboardContainer.test.tsx b/frontend/src/container/PublicDashboardContainer/__tests__/PublicDashboardContainer.test.tsx
new file mode 100644
index 0000000000..d1ada5f65e
--- /dev/null
+++ b/frontend/src/container/PublicDashboardContainer/__tests__/PublicDashboardContainer.test.tsx
@@ -0,0 +1,802 @@
+import { PANEL_GROUP_TYPES, PANEL_TYPES } from 'constants/queryBuilder';
+import { useIsDarkMode } from 'hooks/useDarkMode';
+import { StatusCodes } from 'http-status-codes';
+import {
+ publicDashboardResponse,
+ publicDashboardWidgetData,
+} from 'mocks-server/__mockdata__/publicDashboard';
+import { rest, server } from 'mocks-server/server';
+import { Layout } from 'react-grid-layout';
+import { render, screen, userEvent, waitFor } from 'tests/test-utils';
+import { SuccessResponseV2 } from 'types/api';
+import { Widgets } from 'types/api/dashboard/getAll';
+import { PublicDashboardDataProps } from 'types/api/dashboard/public/get';
+import { EQueryType } from 'types/common/dashboard';
+
+import PublicDashboardContainer from '../PublicDashboardContainer';
+
+// Mock dependencies
+jest.mock('hooks/useDarkMode', () => ({
+ useIsDarkMode: jest.fn(() => false),
+}));
+
+jest.mock('lib/getMinMax', () => ({
+ __esModule: true,
+ default: jest.fn((interval: string) => {
+ if (interval === '1h') {
+ return {
+ minTime: 1000000000000,
+ maxTime: 2000000000000,
+ };
+ }
+ return {
+ minTime: 500000000000,
+ maxTime: 1000000000000,
+ };
+ }),
+}));
+
+jest.mock('container/TopNav/DateTimeSelectionV2', () => ({
+ __esModule: true,
+ default: ({
+ onTimeChange,
+ }: {
+ onTimeChange: (interval: string, dateTimeRange?: [number, number]) => void;
+ }): JSX.Element => (
+ <div data-testid="datetime-selection">
+ <button
+ type="button"
+ onClick={(): void => onTimeChange('1h')}
+ aria-label="Change time to 1 hour"
+ >
+ Change Time
+ </button>
+ <button
+ type="button"
+ onClick={(): void => onTimeChange('custom', [1000000, 2000000])}
+ aria-label="Set custom time range"
+ >
+ Custom Time
+ </button>
+ </div>
+ ),
+}));
+
+jest.mock('../Panel', () => ({
+ __esModule: true,
+ default: ({
+ widget,
+ startTime,
+ endTime,
+ }: {
+ widget: Widgets;
+ startTime: number;
+ endTime: number;
+ }): JSX.Element => (
+ <div data-testid={`panel-${widget.id}`}>
+ <span>
+ Panel: {widget.id} ({startTime}-{endTime})
+ </span>
+ </div>
+ ),
+}));
+
+jest.mock('react-grid-layout', () => ({
+ __esModule: true,
+ default: ({
+ children,
+ layout,
+ style,
+ }: {
+ children: React.ReactNode;
+ layout: Layout[];
+ style?: React.CSSProperties;
+ }): JSX.Element => (
+ <div
+ data-testid="grid-layout"
+ data-layout={JSON.stringify(layout)}
+ style={style}
+ >
+ {children}
+ </div>
+ ),
+ WidthProvider: (
+ Component: React.ComponentType<unknown>,
+ ): React.ComponentType<unknown> => Component,
+}));
+
+// Mock dayjs
+jest.mock('dayjs', () => {
+ const actualDayjs = jest.requireActual('dayjs');
+ const mockUnix = jest.fn(() => 1000);
+ const mockUtcOffset = jest.fn(() => 0);
+ const mockTzMethod = jest.fn(() => ({
+ utcOffset: mockUtcOffset,
+ }));
+ const mockSubtract = jest.fn(() => ({
+ subtract: jest.fn(),
+ unix: mockUnix,
+ tz: mockTzMethod,
+ }));
+ const mockDayjs = jest.fn(() => ({
+ subtract: mockSubtract,
+ unix: mockUnix,
+ tz: mockTzMethod,
+ }));
+ Object.keys(actualDayjs).forEach((key) => {
+ ((mockDayjs as unknown) as Record<string, unknown>)[
+ key
+ ] = (actualDayjs as Record<string, unknown>)[key];
+ });
+ ((mockDayjs as unknown) as { extend: jest.Mock }).extend = jest.fn();
+ ((mockDayjs as unknown) as { tz: { guess: jest.Mock } }).tz = {
+ guess: jest.fn(() => 'UTC'),
+ };
+ return mockDayjs;
+});
+
+const mockUseIsDarkMode = jest.mocked(useIsDarkMode);
+
+// MSW setup
+beforeAll(() => {
+ server.listen();
+});
+
+afterAll(() => {
+ server.close();
+});
+
+afterEach(() => {
+ server.resetHandlers();
+});
+
+// Test constants
+const MOCK_PUBLIC_DASHBOARD_ID = 'test-dashboard-id';
+const MOCK_PUBLIC_PATH = '/public/dashboard/test';
+const DEFAULT_TIME_RANGE = '30m';
+// Use title from mock data
+const TEST_DASHBOARD_TITLE = publicDashboardResponse.data.dashboard.data.title;
+// Use widget ID from mock data
+const WIDGET_1_ID =
+ publicDashboardResponse.data.dashboard.data.widgets?.[0]?.id || 'widget-1';
+const WIDGET_1_TITLE = 'Widget 1';
+const ROW_PANEL_ID = 'row-1';
+const ROW_PANEL_TITLE = 'Row Panel';
+
+// Type definitions
+interface MockWidget {
+ id: string;
+ panelTypes: PANEL_TYPES | PANEL_GROUP_TYPES;
+ title: string;
+ query?: Widgets['query'];
+ description?: string;
+ opacity?: string;
+ nullZeroValues?: string;
+ timePreferance?: string;
+ softMin?: number | null;
+ softMax?: number | null;
+ selectedLogFields?: null;
+ selectedTracesFields?: null;
+}
+
+interface MockPublicDashboardData {
+ dashboard: {
+ data: {
+ title: string;
+ widgets?: MockWidget[];
+ layout?: Layout[];
+ panelMap?: Record<string, { widgets: Layout[]; collapsed: boolean }>;
+ variables?: Record<string, unknown>;
+ };
+ };
+ publicDashboard: {
+ timeRangeEnabled: boolean;
+ defaultTimeRange: string;
+ publicPath: string;
+ };
+}
+
+// Helper function to create mock query
+const createMockQuery = (): Widgets['query'] => ({
+ builder: {
+ queryData: [],
+ queryFormulas: [],
+ queryTraceOperator: [],
+ },
+ clickhouse_sql: [],
+ promql: [],
+ id: 'query-1',
+ queryType: EQueryType.QUERY_BUILDER,
+});
+
+// Base mock data - transform publicDashboardResponse to match component's expected format
+const baseMockData: SuccessResponseV2<PublicDashboardDataProps> = {
+ data: (publicDashboardResponse.data as unknown) as PublicDashboardDataProps,
+ httpStatusCode: StatusCodes.OK,
+};
+
+// Helper function to create mock data with optional overrides
+const createMockData = (
+ overrides?: Partial<MockPublicDashboardData>,
+): SuccessResponseV2<PublicDashboardDataProps> => {
+ if (!overrides) {
+ return baseMockData;
+ }
+
+ const baseData = baseMockData.data;
+
+ // Apply overrides if provided
+ const mergedData: PublicDashboardDataProps = {
+ dashboard:
+ (overrides?.dashboard as PublicDashboardDataProps['dashboard']) ||
+ baseData.dashboard,
+ publicDashboard: overrides?.publicDashboard || baseData.publicDashboard,
+ };
+
+ return {
+ data: mergedData,
+ httpStatusCode: StatusCodes.OK,
+ };
+};
+
+describe('Public Dashboard Container', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockUseIsDarkMode.mockReturnValue(false);
+
+ // Set up default MSW handler for widget query range API
+ server.use(
+ rest.get(
+ '*/public/dashboards/:dashboardId/widgets/:widgetIndex/query_range',
+ (_req, res, ctx) =>
+ res(ctx.status(StatusCodes.OK), ctx.json(publicDashboardWidgetData)),
+ ),
+ );
+ });
+
+ describe('Rendering', () => {
+ it('should render dashboard with title and brand logo', () => {
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={baseMockData}
+ />,
+ );
+
+ expect(screen.getByText(TEST_DASHBOARD_TITLE)).toBeInTheDocument();
+ expect(screen.getByText('SigNoz')).toBeInTheDocument();
+ expect(screen.getByAltText('SigNoz')).toBeInTheDocument();
+ });
+
+ it('should render time range selector when timeRangeEnabled is true', () => {
+ const mockData = createMockData({
+ publicDashboard: {
+ timeRangeEnabled: true,
+ defaultTimeRange: DEFAULT_TIME_RANGE,
+ publicPath: MOCK_PUBLIC_PATH,
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ expect(screen.getByTestId('datetime-selection')).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', { name: /change time to 1 hour/i }),
+ ).toBeInTheDocument();
+ });
+
+ it('should not render time range selector when timeRangeEnabled is false', () => {
+ const mockData = createMockData({
+ publicDashboard: {
+ timeRangeEnabled: false,
+ defaultTimeRange: DEFAULT_TIME_RANGE,
+ publicPath: MOCK_PUBLIC_PATH,
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ expect(screen.queryByTestId('datetime-selection')).not.toBeInTheDocument();
+ });
+
+ it('should render widgets in grid layout', () => {
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={baseMockData}
+ />,
+ );
+
+ expect(screen.getByTestId('grid-layout')).toBeInTheDocument();
+ expect(screen.getByTestId(`panel-${WIDGET_1_ID}`)).toBeInTheDocument();
+ expect(
+ screen.getByText(new RegExp(`Panel: ${WIDGET_1_ID}`)),
+ ).toBeInTheDocument();
+ });
+
+ it('should handle empty dashboard data gracefully', () => {
+ const mockData = createMockData({
+ dashboard: {
+ data: {
+ title: 'Empty Dashboard',
+ widgets: [],
+ layout: [],
+ panelMap: {},
+ variables: {},
+ },
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ expect(screen.getByText('Empty Dashboard')).toBeInTheDocument();
+ expect(screen.getByTestId('grid-layout')).toBeInTheDocument();
+ });
+ });
+
+ describe('Time Range Handling', () => {
+ it('should initialize with default time range from publicDashboard', () => {
+ const mockData = createMockData({
+ publicDashboard: {
+ timeRangeEnabled: true,
+ defaultTimeRange: '1h',
+ publicPath: MOCK_PUBLIC_PATH,
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ // Panel should receive the initial time range
+ expect(screen.getByTestId(`panel-${WIDGET_1_ID}`)).toBeInTheDocument();
+ });
+
+ it('should update time range when time change handler is called with interval', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const mockData = createMockData({
+ publicDashboard: {
+ timeRangeEnabled: true,
+ defaultTimeRange: DEFAULT_TIME_RANGE,
+ publicPath: MOCK_PUBLIC_PATH,
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ const timeChangeButton = screen.getByRole('button', {
+ name: /change time to 1 hour/i,
+ });
+ await user.click(timeChangeButton);
+
+ await waitFor(() => {
+ const panel = screen.getByTestId(`panel-${WIDGET_1_ID}`);
+ expect(panel).toBeInTheDocument();
+ });
+ });
+
+ it('should update time range when time change handler is called with custom dateTimeRange', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const mockData = createMockData({
+ publicDashboard: {
+ timeRangeEnabled: true,
+ defaultTimeRange: DEFAULT_TIME_RANGE,
+ publicPath: MOCK_PUBLIC_PATH,
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ const customTimeButton = screen.getByRole('button', {
+ name: /set custom time range/i,
+ });
+ await user.click(customTimeButton);
+
+ await waitFor(() => {
+ // Panel should receive updated time range
+ expect(screen.getByTestId(`panel-${WIDGET_1_ID}`)).toBeInTheDocument();
+ });
+ });
+
+ it('should use default time range of 30m when defaultTimeRange is not provided', () => {
+ const mockData = createMockData({
+ publicDashboard: {
+ timeRangeEnabled: true,
+ defaultTimeRange: (undefined as unknown) as string,
+ publicPath: MOCK_PUBLIC_PATH,
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ expect(screen.getByTestId(`panel-${WIDGET_1_ID}`)).toBeInTheDocument();
+ });
+ });
+
+ describe('Panel Rendering', () => {
+ it('should render row panel when widget panelTypes is ROW', () => {
+ const mockData = createMockData({
+ dashboard: {
+ data: {
+ title: TEST_DASHBOARD_TITLE,
+ widgets: [
+ {
+ id: ROW_PANEL_ID,
+ panelTypes: PANEL_GROUP_TYPES.ROW,
+ title: ROW_PANEL_TITLE,
+ },
+ ],
+ layout: [
+ {
+ i: ROW_PANEL_ID,
+ x: 0,
+ y: 0,
+ w: 12,
+ h: 2,
+ },
+ ],
+ panelMap: {},
+ variables: {},
+ },
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ expect(screen.getByText(ROW_PANEL_TITLE)).toBeInTheDocument();
+ });
+
+ it('should render collapsed row panel with widget count', () => {
+ const mockData = createMockData({
+ dashboard: {
+ data: {
+ title: TEST_DASHBOARD_TITLE,
+ widgets: [
+ {
+ id: ROW_PANEL_ID,
+ panelTypes: PANEL_GROUP_TYPES.ROW,
+ title: ROW_PANEL_TITLE,
+ },
+ ],
+ layout: [
+ {
+ i: ROW_PANEL_ID,
+ x: 0,
+ y: 0,
+ w: 12,
+ h: 2,
+ },
+ ],
+ panelMap: {
+ [ROW_PANEL_ID]: {
+ widgets: [
+ { i: 'w1', x: 0, y: 0, w: 6, h: 6 },
+ { i: 'w2', x: 6, y: 0, w: 6, h: 6 },
+ ],
+ collapsed: true,
+ },
+ },
+ variables: {},
+ },
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ expect(screen.getByText(/Row Panel \(2 widgets\)/)).toBeInTheDocument();
+ });
+
+ it('should render collapsed row panel with singular widget count', () => {
+ const mockData = createMockData({
+ dashboard: {
+ data: {
+ title: TEST_DASHBOARD_TITLE,
+ widgets: [
+ {
+ id: ROW_PANEL_ID,
+ panelTypes: PANEL_GROUP_TYPES.ROW,
+ title: ROW_PANEL_TITLE,
+ },
+ ],
+ layout: [
+ {
+ i: ROW_PANEL_ID,
+ x: 0,
+ y: 0,
+ w: 12,
+ h: 2,
+ },
+ ],
+ panelMap: {
+ [ROW_PANEL_ID]: {
+ widgets: [{ i: 'w1', x: 0, y: 0, w: 6, h: 6 }],
+ collapsed: true,
+ },
+ },
+ variables: {},
+ },
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ expect(screen.getByText(/Row Panel \(1 widget\)/)).toBeInTheDocument();
+ });
+
+ it('should render regular panel for non-ROW widget types', () => {
+ const mockData = createMockData({
+ dashboard: {
+ data: {
+ title: TEST_DASHBOARD_TITLE,
+ widgets: [
+ {
+ id: WIDGET_1_ID,
+ panelTypes: PANEL_TYPES.TIME_SERIES,
+ title: WIDGET_1_TITLE,
+ query: createMockQuery(),
+ },
+ ],
+ layout: [
+ {
+ i: WIDGET_1_ID,
+ x: 0,
+ y: 0,
+ w: 6,
+ h: 6,
+ },
+ ],
+ panelMap: {},
+ variables: {},
+ },
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ expect(screen.getByTestId(`panel-${WIDGET_1_ID}`)).toBeInTheDocument();
+ expect(
+ screen.getByText(new RegExp(`Panel: ${WIDGET_1_ID}`)),
+ ).toBeInTheDocument();
+ });
+
+ it('should handle missing widget in layout gracefully', () => {
+ const mockData = createMockData({
+ dashboard: {
+ data: {
+ title: TEST_DASHBOARD_TITLE,
+ widgets: [
+ {
+ id: WIDGET_1_ID,
+ panelTypes: PANEL_TYPES.TIME_SERIES,
+ title: WIDGET_1_TITLE,
+ query: createMockQuery(),
+ },
+ ],
+ layout: [
+ {
+ i: 'missing-widget',
+ x: 0,
+ y: 0,
+ w: 6,
+ h: 6,
+ },
+ ],
+ panelMap: {},
+ variables: {},
+ },
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ // Should render panel with fallback widget data
+ expect(screen.getByTestId('panel-missing-widget')).toBeInTheDocument();
+ expect(screen.getByText(/Panel: missing-widget/)).toBeInTheDocument();
+ });
+ });
+
+ describe('Dark Mode', () => {
+ it('should apply dark mode styles when isDarkMode is true', () => {
+ mockUseIsDarkMode.mockReturnValue(true);
+
+ const { container } = render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={baseMockData}
+ />,
+ );
+
+ const gridLayout = container.querySelector('[data-testid="grid-layout"]');
+ expect(gridLayout).toBeInTheDocument();
+ if (gridLayout) {
+ expect(gridLayout).toHaveStyle({ backgroundColor: '' });
+ }
+ });
+
+ it('should apply light mode styles when isDarkMode is false', () => {
+ mockUseIsDarkMode.mockReturnValue(false);
+
+ const { container } = render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={baseMockData}
+ />,
+ );
+
+ const gridLayout = container.querySelector('[data-testid="grid-layout"]');
+ expect(gridLayout).toBeInTheDocument();
+ if (gridLayout) {
+ // themeColors.snowWhite is '#fafafa' which computes to 'rgb(250, 250, 250)'
+ expect(gridLayout).toHaveStyle({
+ backgroundColor: 'rgb(250, 250, 250)',
+ });
+ }
+ });
+ });
+
+ describe('Edge Cases', () => {
+ it('should handle undefined dashboard data', () => {
+ const mockData: SuccessResponseV2<PublicDashboardDataProps> = {
+ data: {
+ dashboard: (undefined as unknown) as PublicDashboardDataProps['dashboard'],
+ publicDashboard: {
+ timeRangeEnabled: false,
+ defaultTimeRange: DEFAULT_TIME_RANGE,
+ publicPath: MOCK_PUBLIC_PATH,
+ },
+ },
+ httpStatusCode: StatusCodes.OK,
+ };
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ expect(screen.getByText('SigNoz')).toBeInTheDocument();
+ });
+
+ it('should handle missing layout data', () => {
+ const mockData = createMockData({
+ dashboard: {
+ data: {
+ title: TEST_DASHBOARD_TITLE,
+ widgets: [
+ {
+ id: WIDGET_1_ID,
+ panelTypes: PANEL_TYPES.TIME_SERIES,
+ title: WIDGET_1_TITLE,
+ query: createMockQuery(),
+ },
+ ],
+ layout: (undefined as unknown) as Layout[],
+ panelMap: {},
+ variables: {},
+ },
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ // Component should render without errors even with missing layout
+ expect(screen.getByText(TEST_DASHBOARD_TITLE)).toBeInTheDocument();
+ });
+
+ it('should handle multiple widgets in layout', () => {
+ const mockData = createMockData({
+ dashboard: {
+ data: {
+ title: TEST_DASHBOARD_TITLE,
+ widgets: [
+ {
+ id: WIDGET_1_ID,
+ panelTypes: PANEL_TYPES.TIME_SERIES,
+ title: WIDGET_1_TITLE,
+ query: createMockQuery(),
+ },
+ {
+ id: 'widget-2',
+ panelTypes: PANEL_TYPES.TABLE,
+ title: 'Widget 2',
+ query: createMockQuery(),
+ },
+ ],
+ layout: [
+ {
+ i: WIDGET_1_ID,
+ x: 0,
+ y: 0,
+ w: 6,
+ h: 6,
+ },
+ {
+ i: 'widget-2',
+ x: 6,
+ y: 0,
+ w: 6,
+ h: 6,
+ },
+ ],
+ panelMap: {},
+ variables: {},
+ },
+ },
+ });
+
+ render(
+ <PublicDashboardContainer
+ publicDashboardId={MOCK_PUBLIC_DASHBOARD_ID}
+ publicDashboardData={mockData}
+ />,
+ );
+
+ expect(screen.getByTestId(`panel-${WIDGET_1_ID}`)).toBeInTheDocument();
+ expect(screen.getByTestId('panel-widget-2')).toBeInTheDocument();
+ });
+ });
+});
diff --git a/frontend/src/container/PublicDashboardContainer/index.tsx b/frontend/src/container/PublicDashboardContainer/index.tsx
new file mode 100644
index 0000000000..7d33fc2389
--- /dev/null
+++ b/frontend/src/container/PublicDashboardContainer/index.tsx
@@ -0,0 +1,3 @@
+import PublicDashboardContainer from './PublicDashboardContainer';
+
+export default PublicDashboardContainer;
diff --git a/frontend/src/container/TopNav/DateTimeSelectionV2/index.tsx b/frontend/src/container/TopNav/DateTimeSelectionV2/index.tsx
index 12ea0ab63a..b7244a911c 100644
--- a/frontend/src/container/TopNav/DateTimeSelectionV2/index.tsx
+++ b/frontend/src/container/TopNav/DateTimeSelectionV2/index.tsx
@@ -65,6 +65,8 @@ function DateTimeSelection({
onGoLive,
onExitLiveLogs,
showLiveLogs,
+ disableUrlSync = false,
+ showRecentlyUsed = true,
}: Props): JSX.Element {
const [formSelector] = Form.useForm();
const { safeNavigate } = useSafeNavigate();
@@ -563,6 +565,11 @@ function DateTimeSelection({
// this is triggred when we change the routes and based on that we are changing the default options
useEffect(() => {
+ // Skip URL sync when disabled (e.g., public dashboards)
+ if (disableUrlSync) {
+ return;
+ }
+
const metricsTimeDuration = getLocalStorageKey(
LOCALSTORAGE.METRICS_TIME_IN_DURATION,
);
@@ -633,7 +640,7 @@ function DateTimeSelection({
const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
safeNavigate(generatedUrl);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [location.pathname, updateTimeInterval, globalTimeLoading]);
+ }, [location.pathname, updateTimeInterval, globalTimeLoading, disableUrlSync]);
const { timezone } = useTimezone();
@@ -716,6 +723,7 @@ function DateTimeSelection({
customDateTimeVisible={customDateTimeVisible}
setCustomDTPickerVisible={setCustomDTPickerVisible}
onExitLiveLogs={onExitLiveLogs}
+ showRecentlyUsed={showRecentlyUsed}
/>
{showAutoRefresh && selectedTime !== 'custom' && (
@@ -756,6 +764,10 @@ interface DateTimeSelectionV2Props {
showLiveLogs?: boolean;
onGoLive?: () => void;
onExitLiveLogs?: () => void;
+ /** When true, prevents the component from modifying URL parameters (useful for public dashboards or isolated contexts) */
+ disableUrlSync?: boolean;
+ /** When false, hides the "Recently Used" time ranges section in the time picker */
+ showRecentlyUsed?: boolean;
}
DateTimeSelection.defaultProps = {
@@ -772,6 +784,8 @@ DateTimeSelection.defaultProps = {
onGoLive: (): void => {},
onExitLiveLogs: (): void => {},
showLiveLogs: false,
+ disableUrlSync: false,
+ showRecentlyUsed: true,
};
interface DispatchProps {
updateTimeInterval: (
diff --git a/frontend/src/hooks/dashboard/useGetPublicDashboardData.tsx b/frontend/src/hooks/dashboard/useGetPublicDashboardData.tsx
new file mode 100644
index 0000000000..148ea4ed7d
--- /dev/null
+++ b/frontend/src/hooks/dashboard/useGetPublicDashboardData.tsx
@@ -0,0 +1,18 @@
+import getPublicDashboardDataAPI from 'api/dashboard/public/getPublicDashboardData';
+import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
+import { useQuery, UseQueryResult } from 'react-query';
+import { SuccessResponseV2 } from 'types/api';
+import { PublicDashboardDataProps } from 'types/api/dashboard/public/get';
+import APIError from 'types/api/error';
+
+export const useGetPublicDashboardData = (
+ id: string,
+): UseQueryResult<SuccessResponseV2<PublicDashboardDataProps>, APIError> =>
+ useQuery<SuccessResponseV2<PublicDashboardDataProps>, APIError>({
+ queryFn: () => getPublicDashboardDataAPI({ id }),
+ onError: (error) => {
+ console.error('Error getting public dashboard data', error);
+ },
+ queryKey: [REACT_QUERY_KEY.GET_PUBLIC_DASHBOARD, id],
+ enabled: !!id,
+ });
diff --git a/frontend/src/hooks/dashboard/useGetPublicDashboardMeta.tsx b/frontend/src/hooks/dashboard/useGetPublicDashboardMeta.tsx
new file mode 100644
index 0000000000..eb7891a86a
--- /dev/null
+++ b/frontend/src/hooks/dashboard/useGetPublicDashboardMeta.tsx
@@ -0,0 +1,19 @@
+import getPublicDashboardMetaAPI from 'api/dashboard/public/getPublicDashboardMeta';
+import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
+import { useQuery, UseQueryResult } from 'react-query';
+import { SuccessResponseV2 } from 'types/api';
+import { PublicDashboardMetaProps } from 'types/api/dashboard/public/getMeta';
+import APIError from 'types/api/error';
+
+export const useGetPublicDashboardMeta = (
+ id: string,
+): UseQueryResult<SuccessResponseV2<PublicDashboardMetaProps>, APIError> =>
+ useQuery<SuccessResponseV2<PublicDashboardMetaProps>, APIError>({
+ queryFn: () => getPublicDashboardMetaAPI({ id }),
+ onError: (error) => {
+ console.error('Error getting public dashboard', error);
+ },
+ queryKey: [REACT_QUERY_KEY.GET_PUBLIC_DASHBOARD_META, id],
+ enabled: !!id,
+ keepPreviousData: false,
+ });
diff --git a/frontend/src/hooks/queryBuilder/useGetQueryRange.ts b/frontend/src/hooks/queryBuilder/useGetQueryRange.ts
index 455457a2dd..4efd7c911d 100644
--- a/frontend/src/hooks/queryBuilder/useGetQueryRange.ts
+++ b/frontend/src/hooks/queryBuilder/useGetQueryRange.ts
@@ -26,6 +26,11 @@ type UseGetQueryRange = (
version: string,
options?: UseGetQueryRangeOptions,
headers?: Record<string, string>,
+ publicQueryMeta?: {
+ isPublic: boolean;
+ widgetIndex: number;
+ publicDashboardId: string;
+ },
) => UseQueryResult<
SuccessResponse<MetricRangePayloadProps> & { warning?: Warning },
Error
@@ -36,6 +41,7 @@ export const useGetQueryRange: UseGetQueryRange = (
version,
options,
headers,
+ publicQueryMeta,
) => {
const { selectedDashboard } = useDashboard();
@@ -156,6 +162,8 @@ export const useGetQueryRange: UseGetQueryRange = (
dynamicVariables,
signal,
headers,
+ undefined,
+ publicQueryMeta,
),
...options,
retry,
diff --git a/frontend/src/lib/dashboard/getQueryResults.ts b/frontend/src/lib/dashboard/getQueryResults.ts
index 3bdcdb53a2..4bedd36240 100644
--- a/frontend/src/lib/dashboard/getQueryResults.ts
+++ b/frontend/src/lib/dashboard/getQueryResults.ts
@@ -29,6 +29,7 @@ import { QueryData } from 'types/api/widgets/getQuery';
import { createAggregation } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
import { IDashboardVariable } from 'types/api/dashboard/getAll';
import { EQueryType } from 'types/common/dashboard';
+import getPublicDashboardWidgetData from 'api/dashboard/public/getPublicDashboardWidgetData';
/**
* Validates if metric name is available for METRICS data source
@@ -200,6 +201,11 @@ export async function GetMetricQueryRange(
signal?: AbortSignal,
headers?: Record<string, string>,
isInfraMonitoring?: boolean,
+ publicQueryMeta?: {
+ isPublic: boolean;
+ widgetIndex: number;
+ publicDashboardId: string;
+ },
): Promise<SuccessResponse<MetricRangePayloadProps> & { warning?: Warning }> {
let legendMap: Record<string, string>;
let response:
@@ -249,7 +255,10 @@ export async function GetMetricQueryRange(
legendMap = v5Result.legendMap;
// atleast one query should be there to make call to v5 api
- if (v5Result.queryPayload.compositeQuery.queries.length === 0) {
+ if (
+ v5Result.queryPayload.compositeQuery.queries.length === 0 &&
+ !publicQueryMeta?.isPublic
+ ) {
return {
statusCode: 200,
error: null,
@@ -272,24 +281,45 @@ export async function GetMetricQueryRange(
};
}
- const v5Response = await getQueryRangeV5(
- v5Result.queryPayload,
- version,
- signal,
- headers,
- );
+ if (publicQueryMeta?.isPublic) {
+ const publicResponse = await getPublicDashboardWidgetData({
+ id: publicQueryMeta?.publicDashboardId,
+ index: publicQueryMeta?.widgetIndex,
+ startTime: props.start * 1000,
+ endTime: props.end * 1000,
+ });
+
+ // Convert V5 response to legacy format for components
+ response = convertV5ResponseToLegacy(
+ {
+ payload: publicResponse.data,
+ params: v5Result.queryPayload,
+ },
+ legendMap,
+ finalFormatForWeb,
+ );
- // Convert V5 response to legacy format for components
- response = convertV5ResponseToLegacy(
- {
- payload: v5Response.data,
- params: v5Result.queryPayload,
- },
- legendMap,
- finalFormatForWeb,
- );
+ warning = response.payload.warning || undefined;
+ } else {
+ const v5Response = await getQueryRangeV5(
+ v5Result.queryPayload,
+ version,
+ signal,
+ headers,
+ );
+
+ // Convert V5 response to legacy format for components
+ response = convertV5ResponseToLegacy(
+ {
+ payload: v5Response.data,
+ params: v5Result.queryPayload,
+ },
+ legendMap,
+ finalFormatForWeb,
+ );
- warning = response.payload.warning || undefined;
+ warning = response.payload.warning || undefined;
+ }
} else {
const legacyResult = prepareQueryRangePayload(props);
legendMap = legacyResult.legendMap;
diff --git a/frontend/src/mocks-server/__mockdata__/publicDashboard.ts b/frontend/src/mocks-server/__mockdata__/publicDashboard.ts
new file mode 100644
index 0000000000..56c8cc0d26
--- /dev/null
+++ b/frontend/src/mocks-server/__mockdata__/publicDashboard.ts
@@ -0,0 +1,328 @@
+export const publishedPublicDashboardMeta = {
+ status: 'success',
+ data: {
+ timeRangeEnabled: true,
+ defaultTimeRange: '30m',
+ publicPath: '/public/dashboard/019ac98e-383f-7e9f-b716-d15bcb6be4bb',
+ },
+};
+
+export const unpublishedPublicDashboardMeta = {
+ status: 'error',
+ error: {
+ code: 'public_dashboard_not_found',
+ message:
+ "dashboard with id 019ac4e8-1a35-718e-aa4b-0c9781d7a31c isn't public",
+ },
+};
+
+export const publicDashboardResponse = {
+ status: 'success',
+ data: {
+ dashboard: {
+ createdAt: '0001-01-01T00:00:00Z',
+ updatedAt: '0001-01-01T00:00:00Z',
+ createdBy: '',
+ updatedBy: '',
+ id: '',
+ data: {
+ description: '',
+ image:
+ 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTgiIGhlaWdodD0iMTgiIHZpZXdCb3g9IjAgMCAxOCAxOCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTE0Ljk0OTQgMTMuOTQyQzE2LjIzMTggMTIuNDI1OCAxNy4zMjY4IDkuNzAyMiAxNi4xOTU2IDYuNTc0ODdDMTUuNjQ0MyA1LjA1MjQ1IDE1LjAyMTkgNC4yMDI0OSAxNC4yOTY5IDMuNjYyNTJDMTMuODU1NyAzLjMzMzc5IDEyLjA5MzMgMi41MDYzMyA5Ljc1OTY1IDIuODY3NTZDOC4wNTM0OSAzLjEzMjU1IDUuNzc0ODcgNC4yMDg3NCA0LjI5MzY5IDUuOTU5OUMyLjg1NzUyIDcuNjYxMDYgMS43NDg4MyA5LjAwNDc0IDEuNjk3NTggMTAuMzA5N0MxLjYzMTMzIDExLjk4ODMgMi44OTYyNyAxMy40MzA4IDMuMDUwMDEgMTMuNjY0NUMzLjMyMzc0IDE0LjA3OTUgNS4xOTExNSAxNi40NTE4IDguNjk5NzEgMTYuNTczMUMxMS43OTcgMTYuNjc5MyAxMy44MTQ0IDE1LjI4NDQgMTQuOTQ5NCAxMy45NDJaIiBmaWxsPSIjNDAzRDNFIi8+CjxwYXRoIGQ9Ik00LjU1MzYzIDIuNzM3NDdDMi45Mzc0NiAzLjg5MTE2IDEuMTIxMzEgNi4yNTEwMyAxLjQ0NzU0IDkuNTYwODZDMS42MDYyOCAxMS4xNzIgMi4wMDI1MSAxMi4xNDk1IDIuNTcxMjMgMTIuODUwN0MyLjkxNzQ2IDEzLjI3ODIgNC40MTk4OCAxNC41NDkzIDYuNzczNTEgMTQuNzM2OEM5LjE0NTg4IDE0LjkyNTYgMTAuOTQ5NSAxNC4zOTQ0IDEyLjgzMzIgMTMuMDg0NEMxNi42NjE3IDEwLjQyMDggMTYuMDk4IDYuMzkzNTMgMTUuOTM0MyA1LjkyNDhDMTUuNzcwNSA1LjQ1NjA3IDE0LjU0NDQgMi42OTYyMiAxMS4xNzMzIDEuNzE1MDJDOC4xOTg0NCAwLjg1MDA2OCA1Ljk4MzU1IDEuNzE1MDIgNC41NTM2MyAyLjczNzQ3WiIgZmlsbD0iIzVFNjM2NyIvPgo8cGF0aCBkPSJNNy4zOTM1MyAyLjk2MTA5QzUuNjE3MzcgMi44OTczNCAzLjkxOTk2IDQuMjg4NTIgMy43NTYyMiA2LjAwNTkzQzMuNTkyNDggNy43MjIwOSA0LjY1NDkyIDkuMDI5NTIgNi4zMDk4MyA5LjI5NTc2QzcuOTY0NzUgOS41NjA3NCA5Ljg3ODM5IDguNTU1OCAxMC4yNjM0IDYuNDUwOTFDMTAuNjYwOSA0LjI4MjI3IDkuMDg5NjkgMy4wMjIzNCA3LjM5MzUzIDIuOTYxMDlaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNNy45NDIxNyA1LjkwMTE1QzcuOTQyMTcgNS45MDExNSA4LjM2OTY1IDUuODEyNCA4LjQ1NDY1IDUuMTgyNDRDOC41MzgzOSA0LjU2MjQ3IDguMjMwOTEgNC4wMzM3NSA3LjUxMzQ1IDMuODQzNzZDNi43MzM0OSAzLjYzNzUyIDYuMjA0NzcgNC4wNjYyNSA2LjA2NzI3IDQuNTE3NDdDNS44NzYwMyA1LjE0NDk0IDYuMTU4NTIgNS40NDM2NyA2LjE1ODUyIDUuNDQzNjdDNi4xNTg1MiA1LjQ0MzY3IDUuMzkzNTYgNS42Mjc0MSA1LjMzMjMxIDYuNTI5ODdDNS4yNzQ4MSA3LjM4MTA3IDUuODU2MDMgNy44Mzg1NSA2LjQzOTc1IDcuOTc4NTRDNy4xNjA5NiA4LjE1MjI4IDcuOTc4NDIgNy45NTQ3OSA4LjE3ODQxIDcuMDM0ODRDOC4zNDQ2NSA2LjI3NzM4IDcuOTQyMTcgNS45MDExNSA3Ljk0MjE3IDUuOTAxMTVaIiBmaWxsPSIjMzAzMDMwIi8+CjxwYXRoIGQ9Ik02LjczOTgzIDQuNzUzNjJDNi42NzEwOSA1LjAxMjM1IDYuODA4NTggNS4yNjIzNCA3LjA3ODU3IDUuMzMxMDlDNy4zNjk4IDUuNDA0ODMgNy42MzQ3OSA1LjMwODU5IDcuNzA2MDMgNS4wMTExQzcuNzY4NTMgNC43NDczNyA3LjY0MzU0IDQuNTE0ODggNy4zMzYwNSA0LjQzOTg4QzcuMDgzNTcgNC4zNzczOSA2LjgxNDgzIDQuNDcxMTMgNi43Mzk4MyA0Ljc1MzYyWiIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTYuOTU5NzggNi4wMzk3NEM2LjYzMjMgNS45Mzg0OSA2LjE5OTgyIDYuMDY0NzMgNi4xMzEwNyA2LjUwNDcxQzYuMDYyMzMgNi45NDQ2OSA2LjMyNjA2IDcuMTY5NjggNi42NzEwNCA3LjIzMjE3QzcuMDE2MDMgNy4yOTQ2NyA3LjM0MjI2IDcuMTEzNDMgNy40MDYwMSA2Ljc2MDk1QzcuNDY4NSA2LjQwOTcyIDcuMjg2MDEgNi4xMzk3MyA2Ljk1OTc4IDYuMDM5NzRaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K',
+ layout: [
+ {
+ h: 6,
+ i: '86590b60-8232-4b41-9744-32cadf2c95fb',
+ moved: false,
+ static: false,
+ w: 6,
+ x: 0,
+ y: 0,
+ },
+ ],
+ panelMap: {},
+ tags: [],
+ title: 'Public Dashboard 02',
+ uploadedGrafana: false,
+ version: 'v5',
+ widgets: [
+ {
+ bucketCount: 30,
+ bucketWidth: 0,
+ columnUnits: {},
+ contextLinks: {
+ linksData: [],
+ },
+ customLegendColors: {},
+ decimalPrecision: 2,
+ description: '',
+ fillSpans: false,
+ id: '86590b60-8232-4b41-9744-32cadf2c95fb',
+ isLogScale: false,
+ legendPosition: 'bottom',
+ mergeAllActiveQueries: false,
+ nullZeroValues: 'zero',
+ opacity: '1',
+ panelTypes: 'graph',
+ query: {
+ builder: {
+ queryData: [
+ {
+ aggregations: [
+ {
+ metricName: 'container.cpu.time',
+ reduceTo: 'avg',
+ spaceAggregation: 'sum',
+ temporality: '',
+ timeAggregation: 'rate',
+ },
+ ],
+ dataSource: 'metrics',
+ expression: 'A',
+ groupBy: [],
+ legend: '',
+ queryName: 'A',
+ },
+ ],
+ queryFormulas: [],
+ queryTraceOperator: [],
+ },
+ clickhouse_sql: [
+ {
+ legend: '',
+ name: 'A',
+ },
+ ],
+ promql: [
+ {
+ legend: '',
+ name: 'A',
+ },
+ ],
+ queryType: 'builder',
+ },
+ selectedLogFields: [
+ {
+ dataType: '',
+ fieldContext: 'log',
+ fieldDataType: '',
+ isIndexed: false,
+ name: 'timestamp',
+ signal: 'logs',
+ type: 'log',
+ },
+ {
+ dataType: '',
+ fieldContext: 'log',
+ fieldDataType: '',
+ isIndexed: false,
+ name: 'body',
+ signal: 'logs',
+ type: 'log',
+ },
+ ],
+ selectedTracesFields: [
+ {
+ fieldContext: 'resource',
+ fieldDataType: 'string',
+ name: 'service.name',
+ signal: 'traces',
+ },
+ {
+ fieldContext: 'span',
+ fieldDataType: 'string',
+ name: 'name',
+ signal: 'traces',
+ },
+ {
+ fieldContext: 'span',
+ fieldDataType: '',
+ name: 'duration_nano',
+ signal: 'traces',
+ },
+ {
+ fieldContext: 'span',
+ fieldDataType: '',
+ name: 'http_method',
+ signal: 'traces',
+ },
+ {
+ fieldContext: 'span',
+ fieldDataType: '',
+ name: 'response_status_code',
+ signal: 'traces',
+ },
+ ],
+ softMax: 0,
+ softMin: 0,
+ stackedBarChart: false,
+ thresholds: [],
+ timePreferance: 'GLOBAL_TIME',
+ title: '',
+ yAxisUnit: 'none',
+ },
+ ],
+ },
+ locked: false,
+ org_id: '00000000-0000-0000-0000-000000000000',
+ },
+ publicDashboard: {
+ timeRangeEnabled: true,
+ defaultTimeRange: '30m',
+ publicPath: '/public/dashboard/019ad04e-8591-7013-879b-a2af376e4708',
+ },
+ },
+};
+
+export const publicDashboardWidgetData = {
+ status: 'success',
+ data: {
+ type: 'time_series',
+ meta: {
+ rowsScanned: 367490,
+ bytesScanned: 2977076,
+ durationMs: 330,
+ },
+ data: {
+ results: [
+ {
+ queryName: 'A',
+ aggregations: [
+ {
+ index: 0,
+ alias: '__result_0',
+ meta: {},
+ series: [
+ {
+ values: [
+ {
+ timestamp: 1764429600000,
+ partial: true,
+ value: 1.554,
+ },
+ {
+ timestamp: 1764429660000,
+ value: 1.367,
+ },
+ {
+ timestamp: 1764429720000,
+ value: 1.641,
+ },
+ {
+ timestamp: 1764429780000,
+ value: 1.455,
+ },
+ {
+ timestamp: 1764429840000,
+ value: 1.739,
+ },
+ {
+ timestamp: 1764429900000,
+ value: 1.318,
+ },
+ {
+ timestamp: 1764429960000,
+ value: 1.813,
+ },
+ {
+ timestamp: 1764430020000,
+ value: 1.332,
+ },
+ {
+ timestamp: 1764430080000,
+ value: 1.521,
+ },
+ {
+ timestamp: 1764430140000,
+ value: 1.461,
+ },
+ {
+ timestamp: 1764430200000,
+ value: 1.61,
+ },
+ {
+ timestamp: 1764430260000,
+ value: 1.747,
+ },
+ {
+ timestamp: 1764430320000,
+ value: 1.51,
+ },
+ {
+ timestamp: 1764430380000,
+ value: 1.501,
+ },
+ {
+ timestamp: 1764430440000,
+ value: 1.524,
+ },
+ {
+ timestamp: 1764430500000,
+ value: 1.648,
+ },
+ {
+ timestamp: 1764430560000,
+ value: 1.545,
+ },
+ {
+ timestamp: 1764430620000,
+ value: 1.47,
+ },
+ {
+ timestamp: 1764430680000,
+ value: 1.582,
+ },
+ {
+ timestamp: 1764430740000,
+ value: 1.257,
+ },
+ {
+ timestamp: 1764430800000,
+ value: 1.726,
+ },
+ {
+ timestamp: 1764430860000,
+ value: 1.482,
+ },
+ {
+ timestamp: 1764430920000,
+ value: 1.291,
+ },
+ {
+ timestamp: 1764430980000,
+ value: 1.741,
+ },
+ {
+ timestamp: 1764431040000,
+ value: 1.591,
+ },
+ {
+ timestamp: 1764431100000,
+ value: 1.609,
+ },
+ {
+ timestamp: 1764431160000,
+ value: 1.177,
+ },
+ {
+ timestamp: 1764431220000,
+ value: 1.699,
+ },
+ {
+ timestamp: 1764431280000,
+ value: 1.617,
+ },
+ {
+ timestamp: 1764431340000,
+ value: 1.515,
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ },
+};
diff --git a/frontend/src/pages/PublicDashboard/PublicDashboard.styles.scss b/frontend/src/pages/PublicDashboard/PublicDashboard.styles.scss
new file mode 100644
index 0000000000..26579715c1
--- /dev/null
+++ b/frontend/src/pages/PublicDashboard/PublicDashboard.styles.scss
@@ -0,0 +1,83 @@
+.public-dashboard-page {
+ .public-dashboard-error-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ width: 100%;
+ padding: 64px 0px;
+
+ .public-dashboard-error-content-header {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+
+ .brand {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+
+ margin-bottom: 12px;
+
+ .brand-logo {
+ width: 40px;
+ height: 40px;
+ }
+
+ .brand-title {
+ font-size: 20px;
+ font-weight: 600;
+ color: var(--bg-vanilla-100, #ffffff); // White text for dark theme
+ margin: 0;
+ }
+ }
+
+ .brand-tagline {
+ margin-bottom: 24px;
+
+ .ant-typography {
+ color: var(--bg-vanilla-400, #c0c1c3); // Light gray text for dark theme
+ }
+ }
+ }
+
+ .public-dashboard-error-content {
+ margin: 128px 0px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ flex-direction: column;
+ padding: 32px 0px;
+ gap: 8px;
+
+ .ant-typography {
+ margin: 0;
+ }
+
+ .public-dashboard-error-message {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ margin-top: 12px;
+ }
+
+ .public-dashboard-error-message-icon {
+ color: var(--bg-vanilla-400, #c0c1c3); // Light gray text for dark theme
+ }
+ }
+ }
+}
+
+.lightMode {
+ .public-dashboard-error-container {
+ .public-dashboard-error-content-header {
+ .brand-title {
+ color: var(--bg-ink-400, #121317) !important; // Dark text for light theme
+ }
+ }
+ }
+}
diff --git a/frontend/src/pages/PublicDashboard/index.tsx b/frontend/src/pages/PublicDashboard/index.tsx
new file mode 100644
index 0000000000..f66c7a92ac
--- /dev/null
+++ b/frontend/src/pages/PublicDashboard/index.tsx
@@ -0,0 +1,80 @@
+import './PublicDashboard.styles.scss';
+
+import { Typography } from 'antd';
+import { useGetPublicDashboardData } from 'hooks/dashboard/useGetPublicDashboardData';
+import { FrownIcon } from 'lucide-react';
+import { useParams } from 'react-router-dom';
+
+import PublicDashboardContainer from '../../container/PublicDashboardContainer';
+
+function PublicDashboardPage(): JSX.Element {
+ // read the dashboard id from the url
+ const { dashboardId } = useParams<{ dashboardId: string }>();
+
+ const {
+ data: publicDashboardData,
+ isLoading: isLoadingPublicDashboardData,
+ isFetching: isFetchingPublicDashboardData,
+ isError: isErrorPublicDashboardData,
+ } = useGetPublicDashboardData(dashboardId || '');
+
+ const isLoading =
+ isLoadingPublicDashboardData || isFetchingPublicDashboardData;
+
+ const isError = isErrorPublicDashboardData;
+
+ return (
+ <div className="public-dashboard-page">
+ {publicDashboardData && (
+ <PublicDashboardContainer
+ publicDashboardId={dashboardId}
+ publicDashboardData={publicDashboardData}
+ />
+ )}
+
+ {isError && !isLoading && (
+ <div className="public-dashboard-error-container">
+ <div className="perilin-bg" />
+
+ <div className="public-dashboard-error-content-header">
+ <div className="brand">
+ <img
+ src="/Logos/signoz-brand-logo.svg"
+ alt="SigNoz"
+ className="brand-logo"
+ />
+
+ <Typography.Title level={2} className="brand-title">
+ SigNoz
+ </Typography.Title>
+ </div>
+
+ <div className="brand-tagline">
+ <Typography.Text>
+ OpenTelemetry-Native Logs, Metrics and Traces in a single pane
+ </Typography.Text>
+ </div>
+ </div>
+
+ <div className="public-dashboard-error-content">
+ <Typography.Title
+ level={4}
+ className="public-dashboard-error-message-icon"
+ >
+ <FrownIcon size={36} />
+ </Typography.Title>
+ <Typography.Title level={4} className="public-dashboard-error-message">
+ The public dashboard you are looking for does not exist or has been
+ unpublished.
+ </Typography.Title>
+ <Typography.Text className="public-dashboard-error-message-description">
+ Please reach out to the owner of the dashboard to get access.
+ </Typography.Text>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default PublicDashboardPage;
diff --git a/frontend/src/periscope.scss b/frontend/src/periscope.scss
index d0d98426ad..9b362cb635 100644
--- a/frontend/src/periscope.scss
+++ b/frontend/src/periscope.scss
@@ -93,11 +93,24 @@
}
&.danger {
- color: var(--bg-cherry-500) !important;
border-radius: 2px;
- border: 1px solid rgba(255, 184, 0, 0.1);
- background: rgba(255, 184, 0, 0.1) !important;
+ color: var(--text-vanilla-100) !important;
+ text-align: center;
+ font-variant-numeric: slashed-zero;
+
+ /* Label/Small/500 */
+ font-family: Inter;
+ font-size: 11px;
+ font-style: normal;
+ font-weight: 500;
+ line-height: 100%; /* 11px */
+ background: var(--bg-cherry-500);
+
box-shadow: none !important;
+
+ &:hover {
+ border: 1px solid var(--bg-cherry-600) !important;
+ }
}
}
diff --git a/frontend/src/providers/QueryBuilder.tsx b/frontend/src/providers/QueryBuilder.tsx
index e3a2ac8af5..d8b8315549 100644
--- a/frontend/src/providers/QueryBuilder.tsx
+++ b/frontend/src/providers/QueryBuilder.tsx
@@ -565,8 +565,6 @@ export function QueryBuilderProvider({
setCurrentQuery((prevState) => {
if (prevState.builder.queryData.length >= MAX_QUERIES) return prevState;
- console.log('prevState', prevState.builder.queryData);
-
const newQuery = createNewBuilderQuery(prevState.builder.queryData);
return {
diff --git a/frontend/src/types/api/dashboard/public/create.ts b/frontend/src/types/api/dashboard/public/create.ts
new file mode 100644
index 0000000000..f70bf0fd22
--- /dev/null
+++ b/frontend/src/types/api/dashboard/public/create.ts
@@ -0,0 +1,5 @@
+export interface CreatePublicDashboardProps {
+ dashboardId: string;
+ timeRangeEnabled: boolean;
+ defaultTimeRange: string;
+}
\ No newline at end of file
diff --git a/frontend/src/types/api/dashboard/public/delete.ts b/frontend/src/types/api/dashboard/public/delete.ts
new file mode 100644
index 0000000000..ac82b34172
--- /dev/null
+++ b/frontend/src/types/api/dashboard/public/delete.ts
@@ -0,0 +1,8 @@
+export interface RevokePublicDashboardAccessProps {
+ id: string;
+}
+
+export interface PayloadProps {
+ status: string;
+ data: null;
+}
\ No newline at end of file
diff --git a/frontend/src/types/api/dashboard/public/get.ts b/frontend/src/types/api/dashboard/public/get.ts
new file mode 100644
index 0000000000..182370e489
--- /dev/null
+++ b/frontend/src/types/api/dashboard/public/get.ts
@@ -0,0 +1,16 @@
+import { Dashboard } from "../getAll";
+import { PublicDashboardMetaProps } from "./getMeta";
+
+export interface PublicDashboardDataProps {
+ dashboard: Dashboard;
+ publicDashboard: PublicDashboardMetaProps;
+}
+
+export type GetPublicDashboardDataProps = {
+ id: string;
+};
+
+export interface PayloadProps {
+ data: PublicDashboardDataProps;
+ status: string;
+}
diff --git a/frontend/src/types/api/dashboard/public/getMeta.ts b/frontend/src/types/api/dashboard/public/getMeta.ts
new file mode 100644
index 0000000000..aa6b12a9ed
--- /dev/null
+++ b/frontend/src/types/api/dashboard/public/getMeta.ts
@@ -0,0 +1,14 @@
+export interface PublicDashboardMetaProps {
+ timeRangeEnabled: boolean;
+ defaultTimeRange: string;
+ publicPath: string;
+}
+
+export type GetPublicDashboardMetaProps = {
+ id: string;
+};
+
+export interface PayloadProps {
+ data: PublicDashboardMetaProps;
+ status: string;
+}
diff --git a/frontend/src/types/api/dashboard/public/getWidgetData.ts b/frontend/src/types/api/dashboard/public/getWidgetData.ts
new file mode 100644
index 0000000000..b07c28e37c
--- /dev/null
+++ b/frontend/src/types/api/dashboard/public/getWidgetData.ts
@@ -0,0 +1,7 @@
+export type GetPublicDashboardWidgetDataProps = {
+ id: string;
+ index: number;
+ startTime: number;
+ endTime: number;
+};
+
diff --git a/frontend/src/types/api/dashboard/public/update.ts b/frontend/src/types/api/dashboard/public/update.ts
new file mode 100644
index 0000000000..0b323ff1e8
--- /dev/null
+++ b/frontend/src/types/api/dashboard/public/update.ts
@@ -0,0 +1,6 @@
+export interface UpdatePublicDashboardProps {
+ dashboardId: string;
+ timeRangeEnabled?: boolean;
+ defaultTimeRange?: string;
+}
+
diff --git a/frontend/src/utils/permission/index.ts b/frontend/src/utils/permission/index.ts
index 5aeea203af..e01837da6b 100644
--- a/frontend/src/utils/permission/index.ts
+++ b/frontend/src/utils/permission/index.ts
@@ -126,4 +126,5 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
METER_EXPLORER: ['ADMIN', 'EDITOR', 'VIEWER'],
METER: ['ADMIN', 'EDITOR', 'VIEWER'],
METER_EXPLORER_VIEWS: ['ADMIN', 'EDITOR', 'VIEWER'],
+ PUBLIC_DASHBOARD: ['ADMIN', 'EDITOR', 'VIEWER'],
};
diff --git a/frontend/yarn.lock b/frontend/yarn.lock
index 130935ac09..f7b01704f9 100644
--- a/frontend/yarn.lock
+++ b/frontend/yarn.lock
@@ -3551,6 +3551,20 @@
dependencies:
"@radix-ui/react-primitive" "2.1.3"
+"@radix-ui/react-checkbox@^1.2.3":
+ version "1.3.3"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-checkbox/-/react-checkbox-1.3.3.tgz#db45ca8a6d5c056a92f74edbb564acee05318b79"
+ integrity sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw==
+ dependencies:
+ "@radix-ui/primitive" "1.1.3"
+ "@radix-ui/react-compose-refs" "1.1.2"
+ "@radix-ui/react-context" "1.1.2"
+ "@radix-ui/react-presence" "1.1.5"
+ "@radix-ui/react-primitive" "2.1.3"
+ "@radix-ui/react-use-controllable-state" "1.2.2"
+ "@radix-ui/react-use-previous" "1.1.1"
+ "@radix-ui/react-use-size" "1.1.1"
+
"@radix-ui/[email protected]":
version "1.0.3"
resolved "https://registry.yarnpkg.com/@radix-ui/react-collection/-/react-collection-1.0.3.tgz#9595a66e09026187524a36c6e7e9c7d286469159"
@@ -3897,6 +3911,11 @@
resolved "https://registry.yarnpkg.com/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz#0c4230a9eed49d4589c967e2d9c0d9d60a23971e"
integrity sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==
+"@radix-ui/[email protected]":
+ version "1.1.1"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-use-previous/-/react-use-previous-1.1.1.tgz#1a1ad5568973d24051ed0af687766f6c7cb9b5b5"
+ integrity sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ==
+
"@radix-ui/[email protected]":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@radix-ui/react-use-rect/-/react-use-rect-1.0.1.tgz#fde50b3bb9fd08f4a1cd204572e5943c244fcec2"
@@ -4273,6 +4292,20 @@
tailwind-merge "^2.5.2"
tailwindcss-animate "^1.0.7"
+"@signozhq/[email protected]":
+ version "0.0.2"
+ resolved "https://registry.yarnpkg.com/@signozhq/checkbox/-/checkbox-0.0.2.tgz#d11fb5eff3927c540937e3bd24351bfc1fdef9ec"
+ integrity sha512-odQdh839GaTy1kqC8yavUKrOYP5tiIppUIV7xGNyxs/KnLGDWLw3ZSdACRV1Z55CLddjQ6OWKiwyVV7t+sxEuw==
+ dependencies:
+ "@radix-ui/react-checkbox" "^1.2.3"
+ "@radix-ui/react-icons" "^1.3.0"
+ "@radix-ui/react-slot" "^1.1.0"
+ class-variance-authority "^0.7.0"
+ clsx "^2.1.1"
+ lucide-react "^0.445.0"
+ tailwind-merge "^2.5.2"
+ tailwindcss-animate "^1.0.7"
+
"@signozhq/[email protected]":
version "1.1.4"
resolved "https://registry.yarnpkg.com/@signozhq/design-tokens/-/design-tokens-1.1.4.tgz#5d5de5bd9d19b6a3631383db015cc4b70c3f7661"