scratchpadSelector.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import {Fragment, useCallback, useEffect, useMemo, useState} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import {FocusScope} from '@react-aria/focus';
  5. import {uuid4} from '@sentry/utils';
  6. import {AnimatePresence} from 'framer-motion';
  7. import isEmpty from 'lodash/isEmpty';
  8. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  9. import {Button} from 'sentry/components/button';
  10. import {CompactSelect} from 'sentry/components/compactSelect';
  11. import {openConfirmModal} from 'sentry/components/confirm';
  12. import InputControl from 'sentry/components/input';
  13. import {Overlay, PositionWrapper} from 'sentry/components/overlay';
  14. import {Tooltip} from 'sentry/components/tooltip';
  15. import {IconBookmark, IconDashboard, IconDelete, IconStar} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import {trackAnalytics} from 'sentry/utils/analytics';
  19. import {clearQuery, updateQuery} from 'sentry/utils/metrics';
  20. import useKeyPress from 'sentry/utils/useKeyPress';
  21. import {useLocalStorageState} from 'sentry/utils/useLocalStorageState';
  22. import useOrganization from 'sentry/utils/useOrganization';
  23. import useOverlay from 'sentry/utils/useOverlay';
  24. import useRouter from 'sentry/utils/useRouter';
  25. import {useCreateDashboard} from './useCreateDashboard';
  26. type Scratchpad = {
  27. id: string;
  28. name: string;
  29. query: Record<string, unknown>;
  30. };
  31. type ScratchpadState = {
  32. default: string | null;
  33. scratchpads: Record<string, Scratchpad>;
  34. };
  35. function makeLocalStorageKey(orgSlug: string) {
  36. return `ddm-scratchpads:${orgSlug}`;
  37. }
  38. export function useScratchpads() {
  39. const {slug} = useOrganization();
  40. const [state, setState] = useLocalStorageState<ScratchpadState>(
  41. makeLocalStorageKey(slug),
  42. {
  43. default: null,
  44. scratchpads: {},
  45. }
  46. );
  47. const [selected, setSelected] = useState<string | null | undefined>(undefined); // scratchpad id
  48. const router = useRouter();
  49. const routerQuery = useMemo(() => router.location.query ?? {}, [router.location.query]);
  50. useEffect(() => {
  51. if (state.default && selected === undefined && !routerQuery.widgets) {
  52. setSelected(state.default);
  53. }
  54. // eslint-disable-next-line react-hooks/exhaustive-deps
  55. }, [state.default, selected]);
  56. // changes the query when a scratchpad is selected, clears it when none is selected
  57. useEffect(() => {
  58. if (selected) {
  59. const selectedQuery = state.scratchpads[selected].query;
  60. const queryToUpdate = selectedQuery;
  61. // if the selected scratchpad has a start and end date, override the statsPeriod
  62. if (selectedQuery.start && selectedQuery.end) {
  63. updateQuery(router, {...selectedQuery, statsPeriod: null});
  64. } else {
  65. updateQuery(router, queryToUpdate);
  66. }
  67. } else if (selected === null) {
  68. clearQuery(router);
  69. }
  70. // eslint-disable-next-line react-hooks/exhaustive-deps
  71. }, [selected]);
  72. // saves all changes to the selected scratchpad to local storage
  73. useEffect(() => {
  74. if (selected && !isEmpty(routerQuery)) {
  75. update(selected, routerQuery);
  76. }
  77. // eslint-disable-next-line react-hooks/exhaustive-deps
  78. }, [routerQuery]);
  79. const toggleSelected = useCallback(
  80. (id: string | null) => {
  81. if (id === selected) {
  82. setSelected(null);
  83. } else {
  84. setSelected(id);
  85. }
  86. },
  87. [setSelected, selected]
  88. );
  89. const setDefault = useCallback(
  90. (id: string | null) => {
  91. setState({...state, default: id});
  92. },
  93. [state, setState]
  94. );
  95. const add = useCallback(
  96. (name: string) => {
  97. const id = uuid4();
  98. const newScratchpads = {
  99. ...state.scratchpads,
  100. [id]: {name, id, query: {environment: null, statsPeriod: null, ...routerQuery}},
  101. };
  102. setState({...state, scratchpads: newScratchpads});
  103. toggleSelected(id);
  104. },
  105. [state, setState, toggleSelected, routerQuery]
  106. );
  107. const update = useCallback(
  108. (id: string, query: Scratchpad['query']) => {
  109. const oldScratchpad = state.scratchpads[id];
  110. const newQuery = {environment: null, statsPeriod: null, ...query};
  111. const newScratchpads = {
  112. ...state.scratchpads,
  113. [id]: {...oldScratchpad, query: newQuery},
  114. };
  115. setState({...state, scratchpads: newScratchpads});
  116. },
  117. [state, setState]
  118. );
  119. const remove = useCallback(
  120. (id: string) => {
  121. const newScratchpads = {...state.scratchpads};
  122. delete newScratchpads[id];
  123. if (state.default === id) {
  124. setState({...state, default: null, scratchpads: newScratchpads});
  125. } else {
  126. setState({...state, scratchpads: newScratchpads});
  127. }
  128. if (selected === id) {
  129. toggleSelected(null);
  130. }
  131. },
  132. [state, setState, toggleSelected, selected]
  133. );
  134. return {
  135. all: state.scratchpads,
  136. default: state.default,
  137. selected,
  138. add,
  139. update,
  140. remove,
  141. toggleSelected,
  142. setDefault,
  143. };
  144. }
  145. export function ScratchpadSelector() {
  146. const scratchpads = useScratchpads();
  147. const organization = useOrganization();
  148. const createDashboard = useCreateDashboard();
  149. const isDefault = useCallback(
  150. scratchpad => scratchpads.default === scratchpad.id,
  151. [scratchpads]
  152. );
  153. const scratchpadOptions = useMemo(
  154. () =>
  155. Object.values(scratchpads.all).map((s: any) => ({
  156. value: s.id,
  157. label: s.name,
  158. trailingItems: (
  159. <Fragment>
  160. <Tooltip
  161. title={
  162. isDefault(s)
  163. ? t('Remove as default scratchpad')
  164. : t('Set as default scratchpad')
  165. }
  166. >
  167. <Button
  168. size="zero"
  169. borderless
  170. onPointerDown={e => e.stopPropagation()}
  171. onClick={() => {
  172. trackAnalytics('ddm.scratchpad.set-default', {
  173. organization,
  174. });
  175. if (isDefault(s)) {
  176. scratchpads.setDefault(null);
  177. } else {
  178. scratchpads.setDefault(s.id ?? null);
  179. }
  180. }}
  181. >
  182. <StyledDropdownIcon>
  183. <IconBookmark isSolid={isDefault(s)} />
  184. </StyledDropdownIcon>
  185. </Button>
  186. </Tooltip>
  187. <Tooltip title={t('Remove scratchpad')}>
  188. <Button
  189. size="zero"
  190. borderless
  191. onPointerDown={e => e.stopPropagation()}
  192. onClick={() => {
  193. openConfirmModal({
  194. onConfirm: () => {
  195. trackAnalytics('ddm.scratchpad.remove', {
  196. organization,
  197. });
  198. return scratchpads.remove(s.id);
  199. },
  200. message: t('Are you sure you want to delete this scratchpad?'),
  201. confirmText: t('Delete'),
  202. });
  203. }}
  204. >
  205. <StyledDropdownIcon danger>
  206. <IconDelete size="sm" />
  207. </StyledDropdownIcon>
  208. </Button>
  209. </Tooltip>
  210. </Fragment>
  211. ),
  212. })),
  213. [scratchpads, isDefault, organization]
  214. );
  215. const selectedScratchpad = scratchpads.selected
  216. ? scratchpads.all[scratchpads.selected]
  217. : undefined;
  218. return (
  219. <ScratchpadGroup>
  220. <Button
  221. icon={<IconDashboard />}
  222. onClick={() => createDashboard(selectedScratchpad)}
  223. >
  224. {t('Save to Dashboard')}
  225. </Button>
  226. <SaveAsDropdown
  227. onSave={name => {
  228. scratchpads.add(name);
  229. }}
  230. mode={scratchpads.selected ? 'fork' : 'save'}
  231. />
  232. <CompactSelect
  233. grid
  234. options={scratchpadOptions}
  235. value={scratchpads.selected ?? `None`}
  236. closeOnSelect={false}
  237. onChange={option => {
  238. scratchpads.toggleSelected(option.value);
  239. }}
  240. triggerProps={{prefix: t('Scratchpad')}}
  241. emptyMessage="No scratchpads yet."
  242. disabled={false}
  243. />
  244. </ScratchpadGroup>
  245. );
  246. }
  247. function SaveAsDropdown({
  248. onSave,
  249. mode,
  250. }: {
  251. mode: 'save' | 'fork';
  252. onSave: (name: string) => void;
  253. }) {
  254. const {
  255. isOpen,
  256. triggerProps,
  257. overlayProps,
  258. arrowProps,
  259. state: {setOpen},
  260. } = useOverlay({});
  261. const theme = useTheme();
  262. const organization = useOrganization();
  263. const [name, setName] = useState('');
  264. const save = useCallback(() => {
  265. trackAnalytics('ddm.scratchpad.save', {
  266. organization,
  267. });
  268. onSave(name);
  269. setOpen(false);
  270. setName('');
  271. }, [name, onSave, setOpen, organization]);
  272. const enterKeyPressed = useKeyPress('Enter');
  273. useEffect(() => {
  274. if (isOpen && enterKeyPressed && name) {
  275. save();
  276. }
  277. }, [enterKeyPressed, isOpen, name, save]);
  278. const isFork = mode === 'fork';
  279. return (
  280. <div>
  281. <Button icon={isFork ? null : <IconStar isSolid={isFork} />} {...triggerProps}>
  282. {isFork ? `${t('Duplicate as')}\u2026` : `${t('Save as')}\u2026`}
  283. </Button>
  284. <AnimatePresence>
  285. {isOpen && (
  286. <FocusScope contain restoreFocus autoFocus>
  287. <PositionWrapper zIndex={theme.zIndex.dropdown} {...overlayProps}>
  288. <StyledOverlay arrowProps={arrowProps} animated>
  289. <SaveAsInput
  290. type="txt"
  291. name="scratchpad-name"
  292. placeholder={t('Scratchpad name')}
  293. value={name}
  294. size="sm"
  295. onChange={({target}) => setName(target.value)}
  296. />
  297. <GuideAnchor target="create_scratchpad" position="bottom">
  298. <SaveAsButton
  299. priority="primary"
  300. disabled={!name}
  301. onClick={() => {
  302. save();
  303. }}
  304. >
  305. {mode === 'fork' ? t('Fork') : t('Save')}
  306. </SaveAsButton>
  307. </GuideAnchor>
  308. </StyledOverlay>
  309. </PositionWrapper>
  310. </FocusScope>
  311. )}
  312. </AnimatePresence>
  313. </div>
  314. );
  315. }
  316. const ScratchpadGroup = styled('div')`
  317. display: flex;
  318. gap: ${space(1)};
  319. `;
  320. const StyledOverlay = styled(Overlay)`
  321. padding: ${space(1)};
  322. `;
  323. const SaveAsButton = styled(Button)`
  324. width: 100%;
  325. `;
  326. const SaveAsInput = styled(InputControl)`
  327. margin-bottom: ${space(1)};
  328. `;
  329. const StyledDropdownIcon = styled('span')<{danger?: boolean}>`
  330. padding: ${space(0.5)} ${space(0.5)} 0 ${space(0.5)};
  331. opacity: 0.5;
  332. :hover {
  333. opacity: 0.9;
  334. color: ${p => (p.danger ? p.theme.red300 : p.theme.gray300)};
  335. }
  336. `;