layoutUtils.tsx 6.7 KB

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