-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
feat(widget-builder): Cache builder state between dataset changes #92122
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
narsaynorath
merged 4 commits into
master
from
narsaynorath/dain-427-changing-datasets-workflow
May 23, 2025
+294
−8
Merged
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d5ea023
feat(widget-builder): Cache builder state between dataset changes
narsaynorath 3797723
Ignore title, that should not change from a cached value
narsaynorath 42c38a6
Ignore description too
narsaynorath 53b03f7
use session storage and forcibly clean up cached state
narsaynorath File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
204 changes: 204 additions & 0 deletions
204
static/app/views/dashboards/widgetBuilder/hooks/useCacheBuilderState.spec.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,204 @@ | ||
import {LocationFixture} from 'sentry-fixture/locationFixture'; | ||
|
||
import {renderHook} from 'sentry-test/reactTestingLibrary'; | ||
|
||
import {useLocation} from 'sentry/utils/useLocation'; | ||
import {DisplayType, WidgetType} from 'sentry/views/dashboards/types'; | ||
import { | ||
useWidgetBuilderContext, | ||
WidgetBuilderProvider, | ||
} from 'sentry/views/dashboards/widgetBuilder/contexts/widgetBuilderContext'; | ||
import { | ||
BuilderStateAction, | ||
type WidgetBuilderState, | ||
} from 'sentry/views/dashboards/widgetBuilder/hooks/useWidgetBuilderState'; | ||
import {convertBuilderStateToWidget} from 'sentry/views/dashboards/widgetBuilder/utils/convertBuilderStateToWidget'; | ||
|
||
import {useCacheBuilderState} from './useCacheBuilderState'; | ||
|
||
jest.mock('sentry/utils/useNavigate', () => ({ | ||
useNavigate: jest.fn(), | ||
})); | ||
jest.mock('sentry/utils/useLocation'); | ||
|
||
jest.mock('sentry/views/dashboards/widgetBuilder/contexts/widgetBuilderContext', () => ({ | ||
useWidgetBuilderContext: jest.fn(), | ||
WidgetBuilderProvider: jest.requireActual( | ||
'sentry/views/dashboards/widgetBuilder/contexts/widgetBuilderContext' | ||
).WidgetBuilderProvider, | ||
})); | ||
|
||
const mockUseWidgetBuilderContext = jest.mocked(useWidgetBuilderContext); | ||
const mockUseLocation = jest.mocked(useLocation); | ||
|
||
function Wrapper({children}: {children: React.ReactNode}) { | ||
return <WidgetBuilderProvider>{children}</WidgetBuilderProvider>; | ||
} | ||
|
||
describe('useCacheBuilderState', () => { | ||
let mockLocalStorage: Record<string, string>; | ||
|
||
beforeEach(() => { | ||
mockLocalStorage = {}; | ||
mockUseWidgetBuilderContext.mockReturnValue({ | ||
state: {}, | ||
dispatch: jest.fn(), | ||
}); | ||
mockUseLocation.mockReturnValue(LocationFixture()); | ||
|
||
Storage.prototype.getItem = jest.fn(key => mockLocalStorage[key] ?? null); | ||
Storage.prototype.setItem = jest.fn((key, value) => { | ||
mockLocalStorage[key] = value; | ||
}); | ||
Storage.prototype.removeItem = jest.fn(key => { | ||
delete mockLocalStorage[key]; | ||
}); | ||
}); | ||
|
||
afterEach(() => { | ||
jest.restoreAllMocks(); | ||
}); | ||
|
||
it('caches builder state to localStorage', () => { | ||
const cachedWidget: WidgetBuilderState = { | ||
dataset: WidgetType.ERRORS, | ||
displayType: DisplayType.LINE, | ||
yAxis: [ | ||
{ | ||
function: ['count', '', undefined, undefined], | ||
kind: 'function', | ||
}, | ||
], | ||
query: ['this is a test query'], | ||
}; | ||
mockUseWidgetBuilderContext.mockReturnValue({ | ||
state: cachedWidget, | ||
dispatch: jest.fn(), | ||
}); | ||
|
||
const {result} = renderHook(() => useCacheBuilderState(), { | ||
wrapper: Wrapper, | ||
}); | ||
|
||
result.current.cacheBuilderState(WidgetType.ERRORS); | ||
|
||
// Verify state was saved to localStorage | ||
expect(localStorage.setItem).toHaveBeenCalledWith( | ||
'dashboards:widget-builder:dataset:error-events', | ||
JSON.stringify(convertBuilderStateToWidget(cachedWidget)) | ||
); | ||
|
||
result.current.restoreOrSetBuilderState(WidgetType.ERRORS); | ||
|
||
expect(localStorage.getItem).toHaveBeenCalledWith( | ||
'dashboards:widget-builder:dataset:error-events' | ||
); | ||
}); | ||
|
||
it('restores builder state from localStorage when available', () => { | ||
const cachedWidget: WidgetBuilderState = { | ||
title: 'error widget title', | ||
description: 'error widget description', | ||
dataset: WidgetType.ERRORS, | ||
displayType: DisplayType.LINE, | ||
yAxis: [ | ||
{ | ||
function: ['count', '', undefined, undefined], | ||
kind: 'function', | ||
}, | ||
], | ||
query: ['this is a test query'], | ||
}; | ||
const currentWidget: WidgetBuilderState = { | ||
title: 'issue widget title', | ||
description: 'issue widget description', | ||
dataset: WidgetType.ISSUE, | ||
displayType: DisplayType.TABLE, | ||
query: ['issue.id:123'], | ||
fields: [ | ||
{ | ||
field: 'issue', | ||
kind: 'field', | ||
}, | ||
], | ||
}; | ||
const mockDispatch = jest.fn(); | ||
mockUseWidgetBuilderContext.mockReturnValue({ | ||
state: currentWidget, | ||
dispatch: mockDispatch, | ||
}); | ||
// Add cached widget to the localStorage | ||
localStorage.setItem( | ||
'dashboards:widget-builder:dataset:error-events', | ||
JSON.stringify(convertBuilderStateToWidget(cachedWidget)) | ||
); | ||
|
||
const {result} = renderHook(() => useCacheBuilderState(), { | ||
wrapper: Wrapper, | ||
}); | ||
|
||
// Call the restore helper on the cached dataset | ||
result.current.restoreOrSetBuilderState(WidgetType.ERRORS); | ||
|
||
expect(mockDispatch).toHaveBeenCalledWith({ | ||
type: BuilderStateAction.SET_STATE, | ||
|
||
// the yAxis gets converted to a string when used with this payload | ||
payload: expect.objectContaining({ | ||
...cachedWidget, | ||
yAxis: ['count()'], | ||
title: 'issue widget title', // The title was not overridden | ||
description: 'issue widget description', // The description was not overridden | ||
}), | ||
}); | ||
}); | ||
|
||
it('plainly sets the new dataset when no cached state exists', () => { | ||
const cachedWidget: WidgetBuilderState = { | ||
dataset: WidgetType.ERRORS, | ||
displayType: DisplayType.LINE, | ||
yAxis: [ | ||
{ | ||
function: ['count', '', undefined, undefined], | ||
kind: 'function', | ||
}, | ||
], | ||
query: ['this is a test query'], | ||
}; | ||
const currentWidget: WidgetBuilderState = { | ||
dataset: WidgetType.ISSUE, | ||
displayType: DisplayType.TABLE, | ||
query: ['issue.id:123'], | ||
fields: [ | ||
{ | ||
field: 'issue', | ||
kind: 'field', | ||
}, | ||
], | ||
}; | ||
const mockDispatch = jest.fn(); | ||
mockUseWidgetBuilderContext.mockReturnValue({ | ||
state: currentWidget, | ||
dispatch: mockDispatch, | ||
}); | ||
// Add cached widget to the localStorage, this will not be the one | ||
// used in the test to test that a cache miss falls back to the plain | ||
// dataset change | ||
localStorage.setItem( | ||
'dashboards:widget-builder:dataset:error-events', | ||
JSON.stringify(convertBuilderStateToWidget(cachedWidget)) | ||
); | ||
|
||
const {result} = renderHook(() => useCacheBuilderState(), { | ||
wrapper: Wrapper, | ||
}); | ||
|
||
// Call the restore helper on the cached dataset | ||
result.current.restoreOrSetBuilderState(WidgetType.TRANSACTIONS); | ||
|
||
expect(mockDispatch).toHaveBeenCalledWith({ | ||
type: BuilderStateAction.SET_DATASET, | ||
payload: WidgetType.TRANSACTIONS, | ||
}); | ||
}); | ||
}); |
70 changes: 70 additions & 0 deletions
70
static/app/views/dashboards/widgetBuilder/hooks/useCacheBuilderState.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
import {useCallback, useEffect} from 'react'; | ||
|
||
import type {WidgetType} from 'sentry/views/dashboards/types'; | ||
import {useWidgetBuilderContext} from 'sentry/views/dashboards/widgetBuilder/contexts/widgetBuilderContext'; | ||
import {BuilderStateAction} from 'sentry/views/dashboards/widgetBuilder/hooks/useWidgetBuilderState'; | ||
import {convertBuilderStateToWidget} from 'sentry/views/dashboards/widgetBuilder/utils/convertBuilderStateToWidget'; | ||
import {convertWidgetToBuilderStateParams} from 'sentry/views/dashboards/widgetBuilder/utils/convertWidgetToBuilderStateParams'; | ||
|
||
const WIDGET_BUILDER_DATASET_STATE_KEY = 'dashboards:widget-builder:dataset'; | ||
|
||
function cleanUpDatasetState() { | ||
for (let i = 0; i < localStorage.length; i++) { | ||
const key = localStorage.key(i); | ||
if (key?.startsWith(WIDGET_BUILDER_DATASET_STATE_KEY)) { | ||
localStorage.removeItem(key); | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* This hook is used to cache the builder state for the given dataset | ||
* and restore it when the user navigates back to the same dataset. | ||
*/ | ||
export function useCacheBuilderState() { | ||
const {state, dispatch} = useWidgetBuilderContext(); | ||
|
||
useEffect(() => { | ||
return cleanUpDatasetState; | ||
}, []); | ||
|
||
const cacheBuilderState = useCallback( | ||
(dataset: WidgetType) => { | ||
localStorage.setItem( | ||
`${WIDGET_BUILDER_DATASET_STATE_KEY}:${dataset}`, | ||
JSON.stringify(convertBuilderStateToWidget(state)) | ||
); | ||
}, | ||
[state] | ||
); | ||
|
||
// Checks if there is a cached builder state for the given dataset | ||
// and restores it if it exists. Otherwise, it sets the dataset. | ||
const restoreOrSetBuilderState = useCallback( | ||
(nextDataset: WidgetType) => { | ||
const previousDatasetState = localStorage.getItem( | ||
`${WIDGET_BUILDER_DATASET_STATE_KEY}:${nextDataset}` | ||
); | ||
if (previousDatasetState) { | ||
const builderState = convertWidgetToBuilderStateParams( | ||
JSON.parse(previousDatasetState) | ||
); | ||
dispatch({ | ||
type: BuilderStateAction.SET_STATE, | ||
payload: {...builderState, title: state.title, description: state.description}, | ||
}); | ||
} else { | ||
dispatch({ | ||
type: BuilderStateAction.SET_DATASET, | ||
payload: nextDataset, | ||
}); | ||
} | ||
}, | ||
[dispatch, state.title, state.description] | ||
); | ||
|
||
return { | ||
cacheBuilderState, | ||
restoreOrSetBuilderState, | ||
}; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.