foldSection.tsx 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. >
  117. <SectionExpander
  118. preventCollapse={preventCollapse}
  119. onClick={preventCollapse ? e => e.preventDefault() : toggleCollapse}
  120. role="button"
  121. aria-label={`${labelPrefix} ${labelSuffix}`}
  122. aria-expanded={!isCollapsed}
  123. >
  124. <InteractionStateLayer
  125. hasSelectedBackground={false}
  126. hidden={preventCollapse ? preventCollapse : !isLayerEnabled}
  127. />
  128. <TitleWithActions>
  129. <TitleWrapper>{title}</TitleWrapper>
  130. {!isCollapsed && (
  131. <div
  132. onClick={e => e.stopPropagation()}
  133. onMouseEnter={() => setIsLayerEnabled(false)}
  134. onMouseLeave={() => setIsLayerEnabled(true)}
  135. >
  136. {actions}
  137. </div>
  138. )}
  139. </TitleWithActions>
  140. <IconWrapper preventCollapse={preventCollapse}>
  141. <IconChevron direction={isCollapsed ? 'down' : 'up'} size="xs" />
  142. </IconWrapper>
  143. </SectionExpander>
  144. {isCollapsed ? null : (
  145. <ErrorBoundary mini>
  146. <Content>{children}</Content>
  147. </ErrorBoundary>
  148. )}
  149. </Section>
  150. <SectionDivider />
  151. </Fragment>
  152. );
  153. });
  154. export const SectionDivider = styled('hr')`
  155. border-color: ${p => p.theme.translucentBorder};
  156. margin: ${space(1.5)} 0;
  157. &:last-child {
  158. display: none;
  159. }
  160. `;
  161. export const Section = styled('section')<{scrollMargin: number}>`
  162. scroll-margin-top: calc(${space(1)} + ${p => p.scrollMargin ?? 0}px);
  163. `;
  164. const Content = styled('div')`
  165. padding: ${space(0.5)} ${space(0.75)};
  166. `;
  167. const SectionExpander = styled('div')<{preventCollapse: boolean}>`
  168. display: grid;
  169. grid-template-columns: 1fr auto;
  170. align-items: center;
  171. padding: ${space(1)} ${space(0.75)};
  172. border-radius: ${p => p.theme.borderRadius};
  173. cursor: ${p => (p.preventCollapse ? 'initial' : 'pointer')};
  174. position: relative;
  175. `;
  176. const TitleWrapper = styled('div')`
  177. font-size: ${p => p.theme.fontSizeLarge};
  178. font-weight: ${p => p.theme.fontWeightBold};
  179. user-select: none;
  180. `;
  181. const IconWrapper = styled('div')<{preventCollapse: boolean}>`
  182. color: ${p => p.theme.subText};
  183. line-height: 0;
  184. visibility: ${p => (p.preventCollapse ? 'hidden' : 'initial')};
  185. `;
  186. const TitleWithActions = styled('div')`
  187. display: grid;
  188. grid-template-columns: 1fr auto;
  189. margin-right: 8px;
  190. align-items: center;
  191. /* Usually the actions are buttons, this height allows actions appearing after opening the
  192. details section to not expand the summary */
  193. min-height: 26px;
  194. `;