foldSection.tsx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import {
  2. type CSSProperties,
  3. forwardRef,
  4. Fragment,
  5. useCallback,
  6. useEffect,
  7. useLayoutEffect,
  8. useRef,
  9. useState,
  10. } from 'react';
  11. import styled from '@emotion/styled';
  12. import ErrorBoundary from 'sentry/components/errorBoundary';
  13. import InteractionStateLayer from 'sentry/components/interactionStateLayer';
  14. import {IconChevron} from 'sentry/icons';
  15. import {t} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import {trackAnalytics} from 'sentry/utils/analytics';
  18. import mergeRefs from 'sentry/utils/mergeRefs';
  19. import useOrganization from 'sentry/utils/useOrganization';
  20. import {useSyncedLocalStorageState} from 'sentry/utils/useSyncedLocalStorageState';
  21. import type {SectionKey} from 'sentry/views/issueDetails/streamline/context';
  22. import {useIssueDetails} from 'sentry/views/issueDetails/streamline/context';
  23. export function getFoldSectionKey(key: SectionKey) {
  24. return `'issue-details-fold-section-collapse:${key}`;
  25. }
  26. export interface FoldSectionProps {
  27. children: React.ReactNode;
  28. sectionKey: SectionKey;
  29. /**
  30. * Title of the section, always visible
  31. */
  32. title: React.ReactNode;
  33. /**
  34. * Actions associated with the section, only visible when open
  35. */
  36. actions?: React.ReactNode;
  37. className?: string;
  38. /**
  39. * Should this section be initially open, gets overridden by user preferences
  40. */
  41. initialCollapse?: boolean;
  42. /**
  43. * Disable the ability for the user to collapse the section
  44. */
  45. preventCollapse?: boolean;
  46. style?: CSSProperties;
  47. }
  48. export const FoldSection = forwardRef<HTMLElement, FoldSectionProps>(function FoldSection(
  49. {
  50. children,
  51. title,
  52. actions,
  53. sectionKey,
  54. className,
  55. initialCollapse = false,
  56. preventCollapse = false,
  57. },
  58. forwardedRef
  59. ) {
  60. const organization = useOrganization();
  61. const {sectionData, navScrollMargin, dispatch} = useIssueDetails();
  62. const [isCollapsed, setIsCollapsed] = useSyncedLocalStorageState(
  63. getFoldSectionKey(sectionKey),
  64. initialCollapse
  65. );
  66. const hasAttemptedScroll = useRef(false);
  67. // If the section is prevented from collapsing, we need to update the local storage state and open
  68. useEffect(() => {
  69. if (preventCollapse) {
  70. setIsCollapsed(false);
  71. }
  72. }, [preventCollapse, setIsCollapsed]);
  73. const scrollToSection = useCallback(
  74. (element: HTMLElement | null) => {
  75. if (!element || !navScrollMargin || hasAttemptedScroll.current) {
  76. return;
  77. }
  78. // Prevent scrolling to element on rerenders
  79. hasAttemptedScroll.current = true;
  80. // scroll to element if it's the current section on page load
  81. if (window.location.hash) {
  82. const [, hash] = window.location.hash.split('#');
  83. if (hash === sectionKey) {
  84. if (isCollapsed) {
  85. setIsCollapsed(false);
  86. }
  87. // Delay scrollIntoView to allow for layout changes to take place
  88. setTimeout(() => element?.scrollIntoView(), 100);
  89. }
  90. }
  91. },
  92. [sectionKey, navScrollMargin, isCollapsed, setIsCollapsed]
  93. );
  94. useLayoutEffect(() => {
  95. if (!sectionData.hasOwnProperty(sectionKey)) {
  96. dispatch({
  97. type: 'UPDATE_EVENT_SECTION',
  98. key: sectionKey,
  99. // If the section is prevented from collapsing, we don't want to persist the initial collapse state
  100. config: {initialCollapse: preventCollapse ? false : initialCollapse},
  101. });
  102. }
  103. }, [sectionData, dispatch, sectionKey, initialCollapse, preventCollapse]);
  104. // This controls disabling the InteractionStateLayer when hovering over action items. We don't
  105. // want selecting an action to appear as though it'll fold/unfold the section.
  106. const [isLayerEnabled, setIsLayerEnabled] = useState(true);
  107. const toggleCollapse = useCallback(
  108. (e: React.MouseEvent) => {
  109. e.preventDefault(); // Prevent browser summary/details behaviour
  110. window.getSelection()?.removeAllRanges(); // Prevent text selection on expand
  111. trackAnalytics('issue_details.section_fold', {
  112. sectionKey,
  113. organization,
  114. open: !isCollapsed,
  115. org_streamline_only: organization.streamlineOnly ?? undefined,
  116. });
  117. setIsCollapsed(!isCollapsed);
  118. },
  119. [organization, sectionKey, isCollapsed, setIsCollapsed]
  120. );
  121. const labelPrefix = isCollapsed ? t('View') : t('Collapse');
  122. const labelSuffix = typeof title === 'string' ? title + t(' Section') : t('Section');
  123. return (
  124. <Fragment>
  125. <Section
  126. ref={mergeRefs([forwardedRef, scrollToSection])}
  127. id={sectionKey}
  128. scrollMargin={navScrollMargin ?? 0}
  129. role="region"
  130. className={className}
  131. >
  132. <SectionExpander
  133. preventCollapse={preventCollapse}
  134. onClick={preventCollapse ? e => e.preventDefault() : toggleCollapse}
  135. role="button"
  136. aria-label={`${labelPrefix} ${labelSuffix}`}
  137. aria-expanded={!isCollapsed}
  138. >
  139. <InteractionStateLayer
  140. hasSelectedBackground={false}
  141. hidden={preventCollapse ? preventCollapse : !isLayerEnabled}
  142. />
  143. <TitleWithActions preventCollapse={preventCollapse}>
  144. <TitleWrapper>{title}</TitleWrapper>
  145. {!isCollapsed && (
  146. <div
  147. onClick={e => e.stopPropagation()}
  148. onMouseEnter={() => setIsLayerEnabled(false)}
  149. onMouseLeave={() => setIsLayerEnabled(true)}
  150. >
  151. {actions}
  152. </div>
  153. )}
  154. </TitleWithActions>
  155. <IconWrapper preventCollapse={preventCollapse}>
  156. <IconChevron direction={isCollapsed ? 'down' : 'up'} size="xs" />
  157. </IconWrapper>
  158. </SectionExpander>
  159. {isCollapsed ? null : (
  160. <ErrorBoundary mini>
  161. <Content>{children}</Content>
  162. </ErrorBoundary>
  163. )}
  164. </Section>
  165. <SectionDivider />
  166. </Fragment>
  167. );
  168. });
  169. export const SectionDivider = styled('hr')`
  170. border-color: ${p => p.theme.translucentBorder};
  171. margin: ${space(1.5)} 0;
  172. &:last-child {
  173. display: none;
  174. }
  175. `;
  176. const Section = styled('section')<{scrollMargin: number}>`
  177. scroll-margin-top: calc(${space(1)} + ${p => p.scrollMargin ?? 0}px);
  178. `;
  179. const Content = styled('div')`
  180. padding: ${space(0.5)} ${space(0.75)};
  181. `;
  182. const SectionExpander = styled('div')<{preventCollapse: boolean}>`
  183. display: grid;
  184. grid-template-columns: 1fr auto;
  185. align-items: center;
  186. padding: ${space(0.5)} ${space(1.5)};
  187. margin: 0 -${space(0.75)};
  188. border-radius: ${p => p.theme.borderRadius};
  189. cursor: ${p => (p.preventCollapse ? 'initial' : 'pointer')};
  190. position: relative;
  191. `;
  192. const TitleWrapper = styled('div')`
  193. font-size: ${p => p.theme.fontSizeLarge};
  194. font-weight: ${p => p.theme.fontWeightBold};
  195. user-select: none;
  196. `;
  197. const IconWrapper = styled('div')<{preventCollapse: boolean}>`
  198. color: ${p => p.theme.subText};
  199. line-height: 0;
  200. display: ${p => (p.preventCollapse ? 'none' : 'block')};
  201. `;
  202. const TitleWithActions = styled('div')<{preventCollapse: boolean}>`
  203. display: grid;
  204. grid-template-columns: 1fr auto;
  205. margin-right: ${p => (p.preventCollapse ? 0 : space(1))};
  206. align-items: center;
  207. /* Usually the actions are buttons, this height allows actions appearing after opening the
  208. details section to not expand the summary */
  209. min-height: 26px;
  210. `;