newWidgetBuilder.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import {type CSSProperties, Fragment, useEffect, useState} from 'react';
  2. import {closestCorners, DndContext, useDraggable, useDroppable} from '@dnd-kit/core';
  3. import {css, useTheme} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import {AnimatePresence, motion} from 'framer-motion';
  6. import {t} from 'sentry/locale';
  7. import {space} from 'sentry/styles/space';
  8. import {CustomMeasurementsProvider} from 'sentry/utils/customMeasurements/customMeasurementsProvider';
  9. import EventView from 'sentry/utils/discover/eventView';
  10. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  11. import {MetricsCardinalityProvider} from 'sentry/utils/performance/contexts/metricsCardinality';
  12. import {MEPSettingProvider} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  13. import {decodeBoolean} from 'sentry/utils/queryString';
  14. import useLocationQuery from 'sentry/utils/url/useLocationQuery';
  15. import useKeyPress from 'sentry/utils/useKeyPress';
  16. import {useLocation} from 'sentry/utils/useLocation';
  17. import useMedia from 'sentry/utils/useMedia';
  18. import useOrganization from 'sentry/utils/useOrganization';
  19. import usePageFilters from 'sentry/utils/usePageFilters';
  20. import {
  21. type DashboardDetails,
  22. type DashboardFilters,
  23. DisplayType,
  24. type Widget,
  25. WidgetType,
  26. } from 'sentry/views/dashboards/types';
  27. import {
  28. DEFAULT_WIDGET_DRAG_POSITIONING,
  29. DRAGGABLE_PREVIEW_HEIGHT_PX,
  30. DRAGGABLE_PREVIEW_WIDTH_PX,
  31. PREVIEW_HEIGHT_PX,
  32. SIDEBAR_HEIGHT,
  33. snapPreviewToCorners,
  34. WIDGET_PREVIEW_DRAG_ID,
  35. type WidgetDragPositioning,
  36. } from 'sentry/views/dashboards/widgetBuilder/components/common/draggableUtils';
  37. import WidgetBuilderSlideout from 'sentry/views/dashboards/widgetBuilder/components/widgetBuilderSlideout';
  38. import WidgetPreview from 'sentry/views/dashboards/widgetBuilder/components/widgetPreview';
  39. import {
  40. useWidgetBuilderContext,
  41. WidgetBuilderProvider,
  42. } from 'sentry/views/dashboards/widgetBuilder/contexts/widgetBuilderContext';
  43. import {DashboardsMEPProvider} from 'sentry/views/dashboards/widgetCard/dashboardsMEPContext';
  44. import {SpanTagsProvider} from 'sentry/views/explore/contexts/spanTagsContext';
  45. import {MetricsDataSwitcher} from 'sentry/views/performance/landing/metricsDataSwitcher';
  46. type WidgetBuilderV2Props = {
  47. dashboard: DashboardDetails;
  48. dashboardFilters: DashboardFilters;
  49. isOpen: boolean;
  50. onClose: () => void;
  51. onSave: ({index, widget}: {index: number; widget: Widget}) => void;
  52. };
  53. function WidgetBuilderV2({
  54. isOpen,
  55. onClose,
  56. onSave,
  57. dashboardFilters,
  58. dashboard,
  59. }: WidgetBuilderV2Props) {
  60. const escapeKeyPressed = useKeyPress('Escape');
  61. const organization = useOrganization();
  62. const {selection} = usePageFilters();
  63. const [queryConditionsValid, setQueryConditionsValid] = useState<boolean>(true);
  64. const theme = useTheme();
  65. const [isPreviewDraggable, setIsPreviewDraggable] = useState(false);
  66. const isSmallScreen = useMedia(`(max-width: ${theme.breakpoints.small})`);
  67. const [translate, setTranslate] = useState<WidgetDragPositioning>(
  68. DEFAULT_WIDGET_DRAG_POSITIONING
  69. );
  70. // do we want to keep this?
  71. useEffect(() => {
  72. if (escapeKeyPressed) {
  73. if (isOpen) {
  74. onClose?.();
  75. }
  76. }
  77. }, [escapeKeyPressed, isOpen, onClose]);
  78. const handleDragEnd = ({over}) => {
  79. setTranslate(snapPreviewToCorners(over));
  80. };
  81. const handleDragMove = ({delta}) => {
  82. setTranslate(previousTranslate => ({
  83. ...previousTranslate,
  84. initialTranslate: previousTranslate.initialTranslate,
  85. translate: {
  86. x: previousTranslate.initialTranslate.x + delta.x,
  87. y: previousTranslate.initialTranslate.y + delta.y,
  88. },
  89. }));
  90. };
  91. return (
  92. <Fragment>
  93. {isOpen && <Backdrop style={{opacity: 0.5, pointerEvents: 'auto'}} />}
  94. <AnimatePresence>
  95. {isOpen && (
  96. <WidgetBuilderProvider>
  97. <CustomMeasurementsProvider organization={organization} selection={selection}>
  98. <SpanTagsProvider
  99. dataset={DiscoverDatasets.SPANS_EAP}
  100. enabled={organization.features.includes('dashboards-eap')}
  101. >
  102. <ContainerWithoutSidebar>
  103. <WidgetBuilderContainer>
  104. <WidgetBuilderSlideout
  105. isOpen={isOpen}
  106. onClose={() => {
  107. onClose();
  108. setTranslate(DEFAULT_WIDGET_DRAG_POSITIONING);
  109. }}
  110. onSave={onSave}
  111. onQueryConditionChange={setQueryConditionsValid}
  112. dashboard={dashboard}
  113. dashboardFilters={dashboardFilters}
  114. setIsPreviewDraggable={setIsPreviewDraggable}
  115. isWidgetInvalid={!queryConditionsValid}
  116. />
  117. {(!isSmallScreen || isPreviewDraggable) && (
  118. <DndContext
  119. onDragEnd={handleDragEnd}
  120. onDragMove={handleDragMove}
  121. collisionDetection={closestCorners}
  122. >
  123. <WidgetPreviewContainer
  124. dashboardFilters={dashboardFilters}
  125. dashboard={dashboard}
  126. dragPosition={translate}
  127. isDraggable={isPreviewDraggable}
  128. isWidgetInvalid={!queryConditionsValid}
  129. />
  130. </DndContext>
  131. )}
  132. </WidgetBuilderContainer>
  133. </ContainerWithoutSidebar>
  134. </SpanTagsProvider>
  135. </CustomMeasurementsProvider>
  136. </WidgetBuilderProvider>
  137. )}
  138. </AnimatePresence>
  139. </Fragment>
  140. );
  141. }
  142. export default WidgetBuilderV2;
  143. export function WidgetPreviewContainer({
  144. dashboardFilters,
  145. dashboard,
  146. isWidgetInvalid,
  147. dragPosition,
  148. isDraggable,
  149. }: {
  150. dashboard: DashboardDetails;
  151. dashboardFilters: DashboardFilters;
  152. isWidgetInvalid: boolean;
  153. dragPosition?: WidgetDragPositioning;
  154. isDraggable?: boolean;
  155. }) {
  156. const {state} = useWidgetBuilderContext();
  157. const organization = useOrganization();
  158. const location = useLocation();
  159. const theme = useTheme();
  160. const {useRpc} = useLocationQuery({
  161. fields: {
  162. useRpc: decodeBoolean,
  163. },
  164. });
  165. const isSmallScreen = useMedia(`(max-width: ${theme.breakpoints.small})`);
  166. // if small screen and draggable, enable dragging
  167. const isDragEnabled = isSmallScreen && isDraggable;
  168. const {attributes, listeners, setNodeRef, isDragging} = useDraggable({
  169. id: WIDGET_PREVIEW_DRAG_ID,
  170. disabled: !isDragEnabled,
  171. // May need to add 'handle' prop if we want to drag the preview by a specific area
  172. });
  173. const {translate, top, left} = dragPosition ?? {};
  174. const draggableStyle: CSSProperties = {
  175. transform: isDragEnabled
  176. ? `translate3d(${translate?.x ?? 0}px, ${translate?.y ?? 0}px, 0)`
  177. : undefined,
  178. top: isDragEnabled ? top ?? 0 : undefined,
  179. left: isDragEnabled ? left ?? 0 : undefined,
  180. opacity: isDragging ? 0.5 : 1,
  181. zIndex: isDragEnabled ? theme.zIndex.modal : theme.zIndex.initial,
  182. cursor: isDragEnabled ? 'grab' : undefined,
  183. margin: isDragEnabled ? '0' : undefined,
  184. alignSelf: isDragEnabled ? 'flex-start' : undefined,
  185. position: isDragEnabled ? 'fixed' : undefined,
  186. };
  187. const getPreviewHeight = () => {
  188. if (isDragEnabled) {
  189. return DRAGGABLE_PREVIEW_HEIGHT_PX;
  190. }
  191. if (state.displayType === DisplayType.TABLE) {
  192. return 'auto';
  193. }
  194. if (state.displayType === DisplayType.BIG_NUMBER && !isSmallScreen) {
  195. return '20vw';
  196. }
  197. return PREVIEW_HEIGHT_PX;
  198. };
  199. return (
  200. <DashboardsMEPProvider>
  201. <MetricsCardinalityProvider organization={organization} location={location}>
  202. <MetricsDataSwitcher
  203. organization={organization}
  204. location={location}
  205. hideLoadingIndicator
  206. eventView={EventView.fromLocation(location)}
  207. >
  208. {metricsDataSide => (
  209. <MEPSettingProvider
  210. location={location}
  211. forceTransactions={metricsDataSide.forceTransactionsOnly}
  212. >
  213. {isDragEnabled && <DroppablePreviewContainer />}
  214. <DraggableWidgetContainer
  215. ref={setNodeRef}
  216. id={WIDGET_PREVIEW_DRAG_ID}
  217. style={draggableStyle}
  218. aria-label={t('Draggable Widget Preview')}
  219. {...attributes}
  220. {...listeners}
  221. >
  222. <SampleWidgetCard
  223. initial={{opacity: 0, x: '50%', y: 0}}
  224. animate={{opacity: 1, x: 0, y: 0}}
  225. exit={{opacity: 0, x: '50%', y: 0}}
  226. transition={{
  227. type: 'spring',
  228. stiffness: 500,
  229. damping: 50,
  230. }}
  231. style={{
  232. width: isDragEnabled ? DRAGGABLE_PREVIEW_WIDTH_PX : undefined,
  233. height: getPreviewHeight(),
  234. outline: isDragEnabled
  235. ? `${space(1)} solid ${theme.border}`
  236. : undefined,
  237. }}
  238. >
  239. <WidgetPreview
  240. // While we test out RPC for spans, force a re-render if the spans toggle changes
  241. key={state.dataset === WidgetType.SPANS && useRpc ? 'spans' : 'other'}
  242. dashboardFilters={dashboardFilters}
  243. dashboard={dashboard}
  244. isWidgetInvalid={isWidgetInvalid}
  245. />
  246. </SampleWidgetCard>
  247. </DraggableWidgetContainer>
  248. </MEPSettingProvider>
  249. )}
  250. </MetricsDataSwitcher>
  251. </MetricsCardinalityProvider>
  252. </DashboardsMEPProvider>
  253. );
  254. }
  255. function DroppablePreviewContainer() {
  256. const containers = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
  257. return (
  258. <DroppableGrid>
  259. {containers.map(id => (
  260. <Droppable key={id} id={id} />
  261. ))}
  262. </DroppableGrid>
  263. );
  264. }
  265. function Droppable({id}: {id: string}) {
  266. const {setNodeRef} = useDroppable({
  267. id,
  268. });
  269. return <div ref={setNodeRef} id={id} />;
  270. }
  271. const fullPageCss = css`
  272. position: absolute;
  273. top: 0;
  274. right: 0;
  275. bottom: 0;
  276. left: 0;
  277. `;
  278. const fillAvailableCss = css`
  279. height: 100%; /* default */
  280. height: -webkit-fill-available; /* Chrome */
  281. height: -moz-available; /* Firefox */
  282. height: fill-available; /* others */
  283. width: -webkit-fill-available; /* Chrome */
  284. width: -moz-available; /* Firefox */
  285. width: fill-available; /* others */
  286. `;
  287. const Backdrop = styled('div')`
  288. ${fullPageCss};
  289. z-index: ${p => p.theme.zIndex.widgetBuilderDrawer};
  290. background: ${p => p.theme.black};
  291. will-change: opacity;
  292. transition: opacity 200ms;
  293. pointer-events: none;
  294. opacity: 0;
  295. `;
  296. const SampleWidgetCard = styled(motion.div)`
  297. width: 100%;
  298. min-width: 100%;
  299. border: 1px dashed ${p => p.theme.gray300};
  300. border-radius: ${p => p.theme.borderRadius};
  301. background-color: ${p => p.theme.background};
  302. z-index: ${p => p.theme.zIndex.initial};
  303. position: relative;
  304. @media (min-width: ${p => p.theme.breakpoints.small}) {
  305. width: 30vw;
  306. min-width: 300px;
  307. z-index: ${p => p.theme.zIndex.modal};
  308. cursor: auto;
  309. }
  310. @media (max-width: ${p => p.theme.breakpoints.large}) and (min-width: ${p =>
  311. p.theme.breakpoints.medium}) {
  312. width: 25vw;
  313. min-width: 100px;
  314. max-width: 300px;
  315. }
  316. `;
  317. const DraggableWidgetContainer = styled(`div`)`
  318. align-content: center;
  319. z-index: ${p => p.theme.zIndex.initial};
  320. position: relative;
  321. margin: auto;
  322. cursor: auto;
  323. @media (min-width: ${p => p.theme.breakpoints.small}) {
  324. z-index: ${p => p.theme.zIndex.modal};
  325. transform: none;
  326. cursor: auto;
  327. }
  328. `;
  329. const ContainerWithoutSidebar = styled('div')`
  330. position: absolute;
  331. top: 0;
  332. left: 0;
  333. `;
  334. const WidgetBuilderContainer = styled('div')`
  335. z-index: ${p => p.theme.zIndex.widgetBuilderDrawer};
  336. display: flex;
  337. align-items: center;
  338. justify-content: space-between;
  339. position: fixed;
  340. ${fillAvailableCss};
  341. `;
  342. const DroppableGrid = styled('div')`
  343. display: grid;
  344. grid-template-columns: 1fr 1fr;
  345. grid-template-rows: 1fr 1fr;
  346. position: fixed;
  347. gap: ${space(4)};
  348. margin: ${space(2)};
  349. top: ${SIDEBAR_HEIGHT}px;
  350. right: ${space(2)};
  351. bottom: ${space(2)};
  352. left: 0;
  353. `;