foldSection.tsx 6.6 KB

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