layoutUtils.tsx 6.9 KB

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