foldSection.tsx 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 {useIssueDetails} 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} = useIssueDetails();
  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({
  90. type: 'UPDATE_EVENT_SECTION',
  91. key: sectionKey,
  92. config: {initialCollapse},
  93. });
  94. }
  95. }, [sectionData, dispatch, sectionKey, initialCollapse]);
  96. // This controls disabling the InteractionStateLayer when hovering over action items. We don't
  97. // want selecting an action to appear as though it'll fold/unfold the section.
  98. const [isLayerEnabled, setIsLayerEnabled] = useState(true);
  99. const toggleCollapse = useCallback(
  100. (e: React.MouseEvent) => {
  101. e.preventDefault(); // Prevent browser summary/details behaviour
  102. window.getSelection()?.removeAllRanges(); // Prevent text selection on expand
  103. trackAnalytics('issue_details.section_fold', {
  104. sectionKey,
  105. organization,
  106. open: !isCollapsed,
  107. org_streamline_only: organization.streamlineOnly ?? undefined,
  108. });
  109. setIsCollapsed(!isCollapsed);
  110. },
  111. [organization, sectionKey, isCollapsed, setIsCollapsed]
  112. );
  113. const labelPrefix = isCollapsed ? t('View') : t('Collapse');
  114. const labelSuffix = typeof title === 'string' ? title + t(' Section') : t('Section');
  115. return (
  116. <Fragment>
  117. <Section
  118. ref={mergeRefs([forwardedRef, scrollToSection])}
  119. id={sectionKey}
  120. scrollMargin={navScrollMargin ?? 0}
  121. role="region"
  122. >
  123. <SectionExpander
  124. preventCollapse={preventCollapse}
  125. onClick={preventCollapse ? e => e.preventDefault() : toggleCollapse}
  126. role="button"
  127. aria-label={`${labelPrefix} ${labelSuffix}`}
  128. aria-expanded={!isCollapsed}
  129. >
  130. <InteractionStateLayer
  131. hasSelectedBackground={false}
  132. hidden={preventCollapse ? preventCollapse : !isLayerEnabled}
  133. />
  134. <TitleWithActions>
  135. <TitleWrapper>{title}</TitleWrapper>
  136. {!isCollapsed && (
  137. <div
  138. onClick={e => e.stopPropagation()}
  139. onMouseEnter={() => setIsLayerEnabled(false)}
  140. onMouseLeave={() => setIsLayerEnabled(true)}
  141. >
  142. {actions}
  143. </div>
  144. )}
  145. </TitleWithActions>
  146. <IconWrapper preventCollapse={preventCollapse}>
  147. <IconChevron direction={isCollapsed ? 'down' : 'up'} size="xs" />
  148. </IconWrapper>
  149. </SectionExpander>
  150. {isCollapsed ? null : (
  151. <ErrorBoundary mini>
  152. <Content>{children}</Content>
  153. </ErrorBoundary>
  154. )}
  155. </Section>
  156. <SectionDivider />
  157. </Fragment>
  158. );
  159. });
  160. export const SectionDivider = styled('hr')`
  161. border-color: ${p => p.theme.translucentBorder};
  162. margin: ${space(1.5)} 0;
  163. &:last-child {
  164. display: none;
  165. }
  166. `;
  167. const Section = styled('section')<{scrollMargin: number}>`
  168. scroll-margin-top: calc(${space(1)} + ${p => p.scrollMargin ?? 0}px);
  169. `;
  170. const Content = styled('div')`
  171. padding: ${space(0.5)} ${space(0.75)};
  172. `;
  173. const SectionExpander = styled('div')<{preventCollapse: boolean}>`
  174. display: grid;
  175. grid-template-columns: 1fr auto;
  176. align-items: center;
  177. padding: ${space(0.5)} ${space(1.5)};
  178. margin: 0 -${space(0.75)};
  179. border-radius: ${p => p.theme.borderRadius};
  180. cursor: ${p => (p.preventCollapse ? 'initial' : 'pointer')};
  181. position: relative;
  182. `;
  183. const TitleWrapper = styled('div')`
  184. font-size: ${p => p.theme.fontSizeLarge};
  185. font-weight: ${p => p.theme.fontWeightBold};
  186. user-select: none;
  187. `;
  188. const IconWrapper = styled('div')<{preventCollapse: boolean}>`
  189. color: ${p => p.theme.subText};
  190. line-height: 0;
  191. visibility: ${p => (p.preventCollapse ? 'hidden' : 'initial')};
  192. `;
  193. const TitleWithActions = styled('div')`
  194. display: grid;
  195. grid-template-columns: 1fr auto;
  196. margin-right: 8px;
  197. align-items: center;
  198. /* Usually the actions are buttons, this height allows actions appearing after opening the
  199. details section to not expand the summary */
  200. min-height: 26px;
  201. `;