layoutUtils.tsx 7.0 KB

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