utils.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import { parse, SearchParserResult } from 'search-query-parser';
  2. import { UrlQueryMap } from '@grafana/data';
  3. import { IconName } from '@grafana/ui';
  4. import { getDashboardSrv } from '../dashboard/services/DashboardSrv';
  5. import { NO_ID_SECTIONS, SECTION_STORAGE_KEY } from './constants';
  6. import { DashboardQuery, DashboardSection, DashboardSectionItem, SearchAction, UidsToDelete } from './types';
  7. /**
  8. * Check if folder has id. Only Recent and Starred folders are the ones without
  9. * ids so far, as they are created manually after results are fetched from API.
  10. * @param str
  11. */
  12. export const hasId = (str: string) => {
  13. return !NO_ID_SECTIONS.includes(str);
  14. };
  15. /**
  16. * Return ids for folders concatenated with their items ids, if section is expanded.
  17. * For items the id format is '{folderId}-{itemId}' to allow mapping them to their folders
  18. * @param sections
  19. */
  20. export const getFlattenedSections = (sections: DashboardSection[]): string[] => {
  21. return sections.flatMap((section) => {
  22. const id = hasId(section.title) ? String(section.id) : section.title;
  23. if (section.expanded && section.items.length) {
  24. return [id, ...section.items.map((item) => `${id}-${item.id}`)];
  25. }
  26. return id;
  27. });
  28. };
  29. /**
  30. * Get all items for currently expanded sections
  31. * @param sections
  32. */
  33. export const getVisibleItems = (sections: DashboardSection[]) => {
  34. return sections.flatMap((section) => {
  35. if (section.expanded) {
  36. return section.items;
  37. }
  38. return [];
  39. });
  40. };
  41. /**
  42. * Since Recent and Starred folders don't have id, title field is used as id
  43. * @param title - title field of the section
  44. */
  45. export const getLookupField = (title: string) => {
  46. return hasId(title) ? 'id' : 'title';
  47. };
  48. /**
  49. * Go through all the folders and items in expanded folders and toggle their selected
  50. * prop according to currently selected index. Used for item highlighting when navigating
  51. * the search results list using keyboard arrows
  52. * @param sections
  53. * @param selectedId
  54. */
  55. export const markSelected = (sections: DashboardSection[], selectedId: string) => {
  56. return sections.map((result: DashboardSection) => {
  57. const lookupField = getLookupField(selectedId);
  58. result = { ...result, selected: String(result[lookupField]) === selectedId };
  59. if (result.expanded && result.items.length) {
  60. return {
  61. ...result,
  62. items: result.items.map((item) => {
  63. const [sectionId, itemId] = selectedId.split('-');
  64. const lookup = getLookupField(sectionId);
  65. return { ...item, selected: String(item.id) === itemId && String(result[lookup]) === sectionId };
  66. }),
  67. };
  68. }
  69. return result;
  70. });
  71. };
  72. /**
  73. * Find items with property 'selected' set true in a list of folders and their items.
  74. * Does recursive search in the items list.
  75. * @param sections
  76. */
  77. export const findSelected = (sections: any): DashboardSection | DashboardSectionItem | null => {
  78. let found = null;
  79. for (const section of sections) {
  80. if (section.expanded && section.items.length) {
  81. found = findSelected(section.items);
  82. }
  83. if (section.selected) {
  84. found = section;
  85. }
  86. if (found) {
  87. return found;
  88. }
  89. }
  90. return null;
  91. };
  92. export const parseQuery = (query: string) => {
  93. const parsedQuery = parse(query, {
  94. keywords: ['folder'],
  95. });
  96. if (typeof parsedQuery === 'string') {
  97. return {
  98. text: parsedQuery,
  99. } as SearchParserResult;
  100. }
  101. return parsedQuery;
  102. };
  103. /**
  104. * Merge multiple reducers into one, keeping the state structure flat (no nested
  105. * separate state for each reducer). If there are multiple state slices with the same
  106. * key, the latest reducer's state is applied.
  107. * Compared to Redux's combineReducers this allows multiple reducers to operate
  108. * on the same state or different slices of the same state. Useful when multiple
  109. * components have the same structure but different or extra logic when modifying it.
  110. * If reducers have the same action types, the action types from the rightmost reducer
  111. * take precedence
  112. * @param reducers
  113. */
  114. export const mergeReducers = (reducers: any[]) => (prevState: any, action: SearchAction) => {
  115. return reducers.reduce((nextState, reducer) => ({ ...nextState, ...reducer(nextState, action) }), prevState);
  116. };
  117. /**
  118. * Collect all the checked dashboards
  119. * @param sections
  120. */
  121. export const getCheckedDashboards = (sections: DashboardSection[]): DashboardSectionItem[] => {
  122. if (!sections.length) {
  123. return [];
  124. }
  125. return sections.reduce((uids, section) => {
  126. return section.items ? [...uids, ...section.items.filter((item) => item.checked)] : uids;
  127. }, [] as DashboardSectionItem[]);
  128. };
  129. /**
  130. * Collect uids of all the checked dashboards
  131. * @param sections
  132. */
  133. export const getCheckedDashboardsUids = (sections: DashboardSection[]) => {
  134. if (!sections.length) {
  135. return [];
  136. }
  137. return getCheckedDashboards(sections).map((item) => item.uid);
  138. };
  139. /**
  140. * Collect uids of all checked folders and dashboards. Used for delete operation, among others
  141. * @param sections
  142. */
  143. export const getCheckedUids = (sections: DashboardSection[]): UidsToDelete => {
  144. const emptyResults: UidsToDelete = { folders: [], dashboards: [] };
  145. if (!sections.length) {
  146. return emptyResults;
  147. }
  148. return sections.reduce((result, section) => {
  149. if (section?.id !== 0 && section.checked && section.uid) {
  150. return { ...result, folders: [...result.folders, section.uid] } as UidsToDelete;
  151. } else {
  152. return { ...result, dashboards: getCheckedDashboardsUids(sections) } as UidsToDelete;
  153. }
  154. }, emptyResults);
  155. };
  156. /**
  157. * When search is done within a dashboard folder, add folder id to the search query
  158. * to narrow down the results to the folder
  159. * @param query
  160. * @param queryParsing
  161. */
  162. export const getParsedQuery = (query: DashboardQuery, queryParsing = false) => {
  163. const parsedQuery = { ...query, sort: query.sort?.value };
  164. if (!queryParsing) {
  165. return parsedQuery;
  166. }
  167. let folderIds: number[] = [];
  168. if (parseQuery(query.query).folder === 'current') {
  169. try {
  170. const dash = getDashboardSrv().getCurrent();
  171. if (dash?.meta.folderId) {
  172. folderIds = [dash?.meta.folderId];
  173. }
  174. } catch (e) {
  175. console.error(e);
  176. }
  177. }
  178. return { ...parsedQuery, query: parseQuery(query.query).text as string, folderIds };
  179. };
  180. /**
  181. * Check if search query has filters enabled. Excludes folderId
  182. * @param query
  183. */
  184. export const hasFilters = (query: DashboardQuery) => {
  185. if (!query) {
  186. return false;
  187. }
  188. return Boolean(query.query || query.tag?.length > 0 || query.starred || query.sort);
  189. };
  190. /**
  191. * Get section icon depending on expanded state. Currently works for folder icons only
  192. * @param section
  193. */
  194. export const getSectionIcon = (section: DashboardSection): IconName => {
  195. if (!hasId(section.title)) {
  196. return section.icon as IconName;
  197. }
  198. return section.expanded ? 'folder-open' : 'folder';
  199. };
  200. /**
  201. * Get storage key for a dashboard folder by its title
  202. * @param title
  203. */
  204. export const getSectionStorageKey = (title = 'General') => {
  205. return `${SECTION_STORAGE_KEY}.${title.toLowerCase()}`;
  206. };
  207. /**
  208. * Remove undefined keys from url params object and format non-primitive values
  209. * @param params
  210. * @param folder
  211. */
  212. export const parseRouteParams = (params: UrlQueryMap) => {
  213. const cleanedParams = Object.entries(params).reduce((obj, [key, val]) => {
  214. if (!val) {
  215. return obj;
  216. } else if (key === 'tag' && !Array.isArray(val)) {
  217. return { ...obj, tag: [val] as string[] };
  218. } else if (key === 'sort') {
  219. return { ...obj, sort: { value: val } };
  220. }
  221. return { ...obj, [key]: val };
  222. }, {} as Partial<DashboardQuery>);
  223. if (params.folder) {
  224. const folderStr = `folder:${params.folder}`;
  225. return {
  226. ...cleanedParams,
  227. query: `${folderStr} ${(cleanedParams.query ?? '').replace(folderStr, '')}`,
  228. };
  229. }
  230. return { ...cleanedParams };
  231. };