layoutUtils.tsx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import type {Layout} from 'react-grid-layout';
  2. // @ts-expect-error TS(7016): Could not find a declaration file for module 'reac... Remove this comment to see the full error message
  3. import {compact} from 'react-grid-layout/build/utils';
  4. import pickBy from 'lodash/pickBy';
  5. import sortBy from 'lodash/sortBy';
  6. import zip from 'lodash/zip';
  7. import {defined} from 'sentry/utils';
  8. import {uniqueId} from 'sentry/utils/guid';
  9. import {NUM_DESKTOP_COLS} from './dashboard';
  10. import type {Widget, WidgetLayout} from './types';
  11. import {DisplayType} from './types';
  12. export const DEFAULT_WIDGET_WIDTH = 2;
  13. export const METRIC_WIDGET_MIN_SIZE = {minH: 2, h: 2, w: 2};
  14. const WIDGET_PREFIX = 'grid-item';
  15. // Keys for grid layout values we track in the server
  16. const STORE_KEYS = ['x', 'y', 'w', 'h', 'minW', 'maxW', 'minH', 'maxH'];
  17. export type Position = Pick<Layout, 'x' | 'y'>;
  18. type NextPosition = [position: Position, columnDepths: number[]];
  19. export function generateWidgetId(widget: Widget, index: number) {
  20. return widget.id ? `${widget.id}-index-${index}` : `index-${index}`;
  21. }
  22. export function constructGridItemKey(widget: {id?: string; tempId?: string}) {
  23. return `${WIDGET_PREFIX}-${widget.id ?? widget.tempId}`;
  24. }
  25. export function assignTempId(widget: Widget) {
  26. if (widget.id ?? widget.tempId) {
  27. return widget;
  28. }
  29. return {...widget, tempId: uniqueId()};
  30. }
  31. /**
  32. * Naive positioning for widgets assuming no resizes.
  33. */
  34. export function getDefaultPosition(index: number, displayType: DisplayType) {
  35. return {
  36. x: (DEFAULT_WIDGET_WIDTH * index) % NUM_DESKTOP_COLS,
  37. y: Number.MAX_SAFE_INTEGER,
  38. w: DEFAULT_WIDGET_WIDTH,
  39. h: displayType === DisplayType.BIG_NUMBER ? 1 : 2,
  40. minH: displayType === DisplayType.BIG_NUMBER ? 1 : 2,
  41. };
  42. }
  43. export function getMobileLayout(desktopLayout: Layout[], widgets: Widget[]) {
  44. if (desktopLayout.length === 0) {
  45. // Initial case where the user has no layout saved, but
  46. // dashboard has widgets
  47. return [];
  48. }
  49. const layoutWidgetPairs = zip(desktopLayout, widgets) as Array<[Layout, Widget]>;
  50. // Sort by y and then subsort by x
  51. const sorted = sortBy(layoutWidgetPairs, ['0.y', '0.x']);
  52. const mobileLayout = sorted.map(([layout, widget], index) => ({
  53. ...layout,
  54. x: 0,
  55. y: index * 2,
  56. w: 2,
  57. h: widget.displayType === DisplayType.BIG_NUMBER ? 1 : 2,
  58. }));
  59. return mobileLayout;
  60. }
  61. /**
  62. * Reads the layout from an array of widgets.
  63. */
  64. export function getDashboardLayout(widgets: Widget[]): Layout[] {
  65. type WidgetWithDefinedLayout = Omit<Widget, 'layout'> & {layout: WidgetLayout};
  66. return widgets
  67. .filter((widget): widget is WidgetWithDefinedLayout => defined(widget.layout))
  68. .map(({layout, ...widget}) => ({
  69. ...layout,
  70. i: constructGridItemKey(widget),
  71. }));
  72. }
  73. export function pickDefinedStoreKeys(layout: Layout): WidgetLayout {
  74. // TODO(nar): Fix the types here
  75. return pickBy(
  76. layout,
  77. (value, key) => defined(value) && STORE_KEYS.includes(key)
  78. ) as WidgetLayout;
  79. }
  80. export function getDefaultWidgetHeight(displayType: DisplayType): number {
  81. return displayType === DisplayType.BIG_NUMBER ? 1 : 2;
  82. }
  83. export function getInitialColumnDepths() {
  84. return Array(NUM_DESKTOP_COLS).fill(0);
  85. }
  86. /**
  87. * Creates an array from layouts where each column stores how deep it is.
  88. */
  89. export function calculateColumnDepths(
  90. layouts: Array<Pick<Layout, 'h' | 'w' | 'x' | 'y'>>
  91. ): number[] {
  92. const depths = getInitialColumnDepths();
  93. // For each layout's x, record the max depth
  94. layouts.forEach(({x, w, y, h}) => {
  95. // Adjust the column depths for each column the widget takes up
  96. for (let col = x; col < x + w; col++) {
  97. depths[col] = Math.max(y + h, depths[col]);
  98. }
  99. });
  100. return depths;
  101. }
  102. /**
  103. * Find the next place to place a widget and also returns the next
  104. * input when this operation needs to be called multiple times.
  105. *
  106. * @param columnDepths A profile of how deep the widgets in a column extend.
  107. * @param height The desired height of the next widget we want to place.
  108. * @returns An {x, y} positioning for the next available spot, as well as the
  109. * next columnDepths array if this position were used.
  110. */
  111. export function getNextAvailablePosition(
  112. initialColumnDepths: number[],
  113. height: number
  114. ): NextPosition {
  115. const columnDepths = [...initialColumnDepths];
  116. const maxColumnDepth = Math.max(...columnDepths);
  117. // Look for an opening at each depth by scanning from 0, 0
  118. // By scanning from 0 depth to the highest depth, we ensure
  119. // we get the top-most available spot
  120. for (let currDepth = 0; currDepth <= maxColumnDepth; currDepth++) {
  121. for (let start = 0; start <= columnDepths.length - DEFAULT_WIDGET_WIDTH; start++) {
  122. if (columnDepths[start]! > currDepth) {
  123. // There are potentially widgets in the way here, so skip
  124. continue;
  125. }
  126. // If all of the columns from start to end (the size of the widget)
  127. // have at most the current depth, then we've found a valid positioning
  128. // No other widgets extend into the space we need
  129. const end = start + DEFAULT_WIDGET_WIDTH;
  130. if (columnDepths.slice(start, end).every(val => val <= currDepth)) {
  131. for (let col = start; col < start + DEFAULT_WIDGET_WIDTH; col++) {
  132. columnDepths[col] = currDepth + height;
  133. }
  134. return [{x: start, y: currDepth}, [...columnDepths]];
  135. }
  136. }
  137. }
  138. for (let col = 0; col < DEFAULT_WIDGET_WIDTH; col++) {
  139. columnDepths[col] = maxColumnDepth;
  140. }
  141. return [{x: 0, y: maxColumnDepth}, [...columnDepths]];
  142. }
  143. export function assignDefaultLayout<T extends Pick<Widget, 'displayType' | 'layout'>>(
  144. widgets: T[],
  145. initialColumnDepths: number[]
  146. ): T[] {
  147. let columnDepths = [...initialColumnDepths];
  148. const newWidgets = widgets.map(widget => {
  149. if (defined(widget.layout)) {
  150. return widget;
  151. }
  152. const height = getDefaultWidgetHeight(widget.displayType);
  153. const [nextPosition, nextColumnDepths] = getNextAvailablePosition(
  154. columnDepths,
  155. height
  156. );
  157. columnDepths = nextColumnDepths;
  158. return {
  159. ...widget,
  160. layout: {
  161. ...nextPosition,
  162. h: height,
  163. minH: height,
  164. w: DEFAULT_WIDGET_WIDTH,
  165. },
  166. };
  167. });
  168. return newWidgets;
  169. }
  170. export function enforceWidgetHeightValues(widget: Widget): Widget {
  171. const {displayType, layout} = widget;
  172. const nextWidget = {
  173. ...widget,
  174. };
  175. if (!defined(layout)) {
  176. return nextWidget;
  177. }
  178. const minH = getDefaultWidgetHeight(displayType);
  179. const nextLayout = {
  180. ...layout,
  181. h: Math.max(layout?.h ?? minH, minH),
  182. minH,
  183. };
  184. return {...nextWidget, layout: nextLayout};
  185. }
  186. export function generateWidgetsAfterCompaction(widgets: Widget[]) {
  187. // Resolves any potential compactions that need to occur after a
  188. // single widget change would affect other widget positions, e.g. deletion
  189. const nextLayout = compact(getDashboardLayout(widgets), 'vertical', NUM_DESKTOP_COLS);
  190. return widgets.map(widget => {
  191. const layout = nextLayout.find(({i}: any) => i === constructGridItemKey(widget));
  192. if (!layout) {
  193. return widget;
  194. }
  195. return {...widget, layout};
  196. });
  197. }
  198. export function isValidLayout(layout: Layout) {
  199. return !isNaN(layout.x) && !isNaN(layout.y) && layout.w > 0 && layout;
  200. }