diff --git a/apps/web/src/layouts/ChatLayout/FileContainer/FileContainerHeader/MetricContainerHeaderButtons/MetricThreeDotMenu.tsx b/apps/web/src/layouts/ChatLayout/FileContainer/FileContainerHeader/MetricContainerHeaderButtons/MetricThreeDotMenu.tsx index 415d627f1..e010f5427 100644 --- a/apps/web/src/layouts/ChatLayout/FileContainer/FileContainerHeader/MetricContainerHeaderButtons/MetricThreeDotMenu.tsx +++ b/apps/web/src/layouts/ChatLayout/FileContainer/FileContainerHeader/MetricContainerHeaderButtons/MetricThreeDotMenu.tsx @@ -49,7 +49,8 @@ import { type MetricFileViewSecondary, useChatLayoutContextSelector } from '@/layouts/ChatLayout/ChatLayoutContext'; -import { timeout } from '@/lib'; +import { timeout } from '@/lib/timeout'; +import { ensureElementExists } from '@/lib/element'; import { downloadElementToImage, exportJSONToCSV } from '@/lib/exportUtils'; import { canEdit, getIsEffectiveOwner, getIsOwner } from '@/lib/share'; import { BusterRoutes } from '@/routes'; @@ -435,15 +436,27 @@ const useDeleteMetricSelectMenu = ({ metricId }: { metricId: string }) => { const useRenameMetricSelectMenu = ({ metricId }: { metricId: string }) => { const onSetFileView = useChatLayoutContextSelector((x) => x.onSetFileView); + const onChangePage = useAppLayoutContextSelector((x) => x.onChangePage); + const chatId = useChatLayoutContextSelector((x) => x.chatId); + const dashboardId = useChatLayoutContextSelector((x) => x.dashboardId); return useMemo( () => ({ label: 'Rename metric', value: 'rename-metric', icon: , onClick: async () => { - onSetFileView({ fileView: 'chart' }); - await timeout(125); - const input = document.getElementById(METRIC_CHART_TITLE_INPUT_ID) as HTMLInputElement; + const route = assetParamsToRoute({ + type: 'metric', + assetId: metricId, + chatId, + dashboardId, + page: 'chart' + }); + await onChangePage(route); + await timeout(100); + const input = await ensureElementExists( + () => document.getElementById(METRIC_CHART_TITLE_INPUT_ID) as HTMLInputElement + ); if (input) { input.focus(); input.select(); diff --git a/apps/web/src/lib/element.tsx b/apps/web/src/lib/element.tsx index 3be608c7a..d9ffc015c 100644 --- a/apps/web/src/lib/element.tsx +++ b/apps/web/src/lib/element.tsx @@ -101,3 +101,25 @@ export const boldHighlights = (name: string, highlights: string[]): React.ReactN return String(name); } }; + +export const ensureElementExists = async ( + nodeCheck: () => T | null, + params?: { timeoutMs?: number; intervalMs?: number } +): Promise => { + const { timeoutMs = 3000, intervalMs = 50 } = params || {}; + const start = Date.now(); + + return new Promise((resolve) => { + const check = () => { + const el = nodeCheck(); + if (el) { + resolve(el); + } else if (Date.now() - start < timeoutMs) { + setTimeout(check, intervalMs); + } else { + resolve(null); + } + }; + check(); + }); +};