eventView.tsx 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501
  1. import {Location, Query} from 'history';
  2. import cloneDeep from 'lodash/cloneDeep';
  3. import isEqual from 'lodash/isEqual';
  4. import isString from 'lodash/isString';
  5. import omit from 'lodash/omit';
  6. import pick from 'lodash/pick';
  7. import uniqBy from 'lodash/uniqBy';
  8. import moment from 'moment';
  9. import {EventQuery} from 'sentry/actionCreators/events';
  10. import {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  11. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  12. import {DEFAULT_PER_PAGE} from 'sentry/constants';
  13. import {ALL_ACCESS_PROJECTS, URL_PARAM} from 'sentry/constants/pageFilters';
  14. import {t} from 'sentry/locale';
  15. import {
  16. NewQuery,
  17. PageFilters,
  18. Project,
  19. SavedQuery,
  20. SelectValue,
  21. User,
  22. } from 'sentry/types';
  23. import {
  24. aggregateOutputType,
  25. Column,
  26. ColumnType,
  27. Field,
  28. generateFieldAsString,
  29. getAggregateAlias,
  30. getEquation,
  31. isAggregateEquation,
  32. isAggregateField,
  33. isEquation,
  34. isLegalYAxisType,
  35. Sort,
  36. } from 'sentry/utils/discover/fields';
  37. import {
  38. CHART_AXIS_OPTIONS,
  39. DISPLAY_MODE_FALLBACK_OPTIONS,
  40. DISPLAY_MODE_OPTIONS,
  41. DisplayModes,
  42. TOP_N,
  43. } from 'sentry/utils/discover/types';
  44. import {decodeList, decodeScalar} from 'sentry/utils/queryString';
  45. import toArray from 'sentry/utils/toArray';
  46. import {
  47. FieldValueKind,
  48. TableColumn,
  49. TableColumnSort,
  50. } from 'sentry/views/eventsV2/table/types';
  51. import {decodeColumnOrder} from 'sentry/views/eventsV2/utils';
  52. import {SpanOperationBreakdownFilter} from 'sentry/views/performance/transactionSummary/filter';
  53. import {EventsDisplayFilterName} from 'sentry/views/performance/transactionSummary/transactionEvents/utils';
  54. import {statsPeriodToDays} from '../dates';
  55. import {WebVital} from '../fields';
  56. import {MutableSearch} from '../tokenizeSearch';
  57. import {getSortField} from './fieldRenderers';
  58. // Metadata mapping for discover results.
  59. export type MetaType = Record<string, ColumnType> & {
  60. isMetricsData?: boolean;
  61. tips?: {columns: string; query: string};
  62. units?: Record<string, string>;
  63. };
  64. export type EventsMetaType = {fields: Record<string, ColumnType>} & {
  65. isMetricsData?: boolean;
  66. };
  67. // Data in discover results.
  68. export type EventData = Record<string, any>;
  69. export type LocationQuery = {
  70. cursor?: string | string[] | null;
  71. end?: string | string[] | null;
  72. start?: string | string[] | null;
  73. statsPeriod?: string | string[] | null;
  74. utc?: string | string[] | null;
  75. };
  76. const DATETIME_QUERY_STRING_KEYS = ['start', 'end', 'utc', 'statsPeriod'] as const;
  77. const EXTERNAL_QUERY_STRING_KEYS: Readonly<Array<keyof LocationQuery>> = [
  78. ...DATETIME_QUERY_STRING_KEYS,
  79. 'cursor',
  80. ];
  81. const setSortOrder = (sort: Sort, kind: 'desc' | 'asc'): Sort => ({
  82. kind,
  83. field: sort.field,
  84. });
  85. const reverseSort = (sort: Sort): Sort => ({
  86. kind: sort.kind === 'desc' ? 'asc' : 'desc',
  87. field: sort.field,
  88. });
  89. const isSortEqualToField = (
  90. sort: Sort,
  91. field: Field,
  92. tableMeta: MetaType | undefined
  93. ): boolean => {
  94. const sortKey = getSortKeyFromField(field, tableMeta);
  95. return sort.field === sortKey;
  96. };
  97. const fieldToSort = (
  98. field: Field,
  99. tableMeta: MetaType | undefined,
  100. kind?: 'desc' | 'asc',
  101. useFunctionFormat?: boolean
  102. ): Sort | undefined => {
  103. const sortKey = getSortKeyFromField(field, tableMeta, useFunctionFormat);
  104. if (!sortKey) {
  105. return void 0;
  106. }
  107. return {
  108. kind: kind || 'desc',
  109. field: sortKey,
  110. };
  111. };
  112. function getSortKeyFromField(
  113. field: Field,
  114. tableMeta?: MetaType,
  115. useFunctionFormat?: boolean
  116. ): string | null {
  117. const fieldString = useFunctionFormat ? field.field : getAggregateAlias(field.field);
  118. return getSortField(fieldString, tableMeta);
  119. }
  120. export function isFieldSortable(field: Field, tableMeta?: MetaType): boolean {
  121. return !!getSortKeyFromField(field, tableMeta);
  122. }
  123. const decodeFields = (location: Location): Array<Field> => {
  124. const {query} = location;
  125. if (!query || !query.field) {
  126. return [];
  127. }
  128. const fields = decodeList(query.field);
  129. const widths = decodeList(query.widths);
  130. const parsed: Field[] = [];
  131. fields.forEach((field, i) => {
  132. const w = Number(widths[i]);
  133. const width = !isNaN(w) ? w : COL_WIDTH_UNDEFINED;
  134. parsed.push({field, width});
  135. });
  136. return parsed;
  137. };
  138. const parseSort = (sort: string): Sort => {
  139. sort = sort.trim();
  140. if (sort.startsWith('-')) {
  141. return {
  142. kind: 'desc',
  143. field: sort.substring(1),
  144. };
  145. }
  146. return {
  147. kind: 'asc',
  148. field: sort,
  149. };
  150. };
  151. export const fromSorts = (sorts: string | string[] | undefined): Array<Sort> => {
  152. if (sorts === undefined) {
  153. return [];
  154. }
  155. sorts = isString(sorts) ? [sorts] : sorts;
  156. // NOTE: sets are iterated in insertion order
  157. const uniqueSorts = [...new Set(sorts)];
  158. return uniqueSorts.reduce((acc: Array<Sort>, sort: string) => {
  159. acc.push(parseSort(sort));
  160. return acc;
  161. }, []);
  162. };
  163. export const decodeSorts = (location: Location): Array<Sort> => {
  164. const {query} = location;
  165. if (!query || !query.sort) {
  166. return [];
  167. }
  168. const sorts = decodeList(query.sort);
  169. return fromSorts(sorts);
  170. };
  171. export const encodeSort = (sort: Sort): string => {
  172. switch (sort.kind) {
  173. case 'desc': {
  174. return `-${sort.field}`;
  175. }
  176. case 'asc': {
  177. return String(sort.field);
  178. }
  179. default: {
  180. throw new Error('Unexpected sort type');
  181. }
  182. }
  183. };
  184. const encodeSorts = (sorts: Readonly<Array<Sort>>): Array<string> =>
  185. sorts.map(encodeSort);
  186. const collectQueryStringByKey = (query: Query, key: string): Array<string> => {
  187. const needle = query[key];
  188. const collection = decodeList(needle);
  189. return collection.reduce((acc: Array<string>, item: string) => {
  190. item = item.trim();
  191. if (item.length > 0) {
  192. acc.push(item);
  193. }
  194. return acc;
  195. }, []);
  196. };
  197. const decodeQuery = (location: Location): string => {
  198. if (!location.query || !location.query.query) {
  199. return '';
  200. }
  201. const queryParameter = location.query.query;
  202. return decodeScalar(queryParameter, '').trim();
  203. };
  204. const decodeTeam = (value: string): 'myteams' | number => {
  205. if (value === 'myteams') {
  206. return value;
  207. }
  208. return parseInt(value, 10);
  209. };
  210. const decodeTeams = (location: Location): ('myteams' | number)[] => {
  211. if (!location.query || !location.query.team) {
  212. return [];
  213. }
  214. const value = location.query.team;
  215. return toArray(value)
  216. .map(decodeTeam)
  217. .filter(team => team === 'myteams' || !isNaN(team));
  218. };
  219. const decodeProjects = (location: Location): number[] => {
  220. if (!location.query || !location.query.project) {
  221. return [];
  222. }
  223. const value = location.query.project;
  224. return toArray(value).map(i => parseInt(i, 10));
  225. };
  226. const queryStringFromSavedQuery = (saved: NewQuery | SavedQuery): string => {
  227. if (saved.query) {
  228. return saved.query || '';
  229. }
  230. return '';
  231. };
  232. function validateTableMeta(tableMeta: MetaType | undefined): MetaType | undefined {
  233. return tableMeta && Object.keys(tableMeta).length > 0 ? tableMeta : undefined;
  234. }
  235. class EventView {
  236. id: string | undefined;
  237. name: string | undefined;
  238. fields: Readonly<Field[]>;
  239. sorts: Readonly<Sort[]>;
  240. query: string;
  241. team: Readonly<('myteams' | number)[]>;
  242. project: Readonly<number[]>;
  243. start: string | undefined;
  244. end: string | undefined;
  245. statsPeriod: string | undefined;
  246. utc?: string | boolean | undefined;
  247. environment: Readonly<string[]>;
  248. yAxis: string | undefined;
  249. display: string | undefined;
  250. topEvents: string | undefined;
  251. interval: string | undefined;
  252. expired?: boolean;
  253. createdBy: User | undefined;
  254. additionalConditions: MutableSearch; // This allows views to always add additional conditions to the query to get specific data. It should not show up in the UI unless explicitly called.
  255. constructor(props: {
  256. additionalConditions: MutableSearch;
  257. createdBy: User | undefined;
  258. display: string | undefined;
  259. end: string | undefined;
  260. environment: Readonly<string[]>;
  261. fields: Readonly<Field[]>;
  262. id: string | undefined;
  263. name: string | undefined;
  264. project: Readonly<number[]>;
  265. query: string;
  266. sorts: Readonly<Sort[]>;
  267. start: string | undefined;
  268. statsPeriod: string | undefined;
  269. team: Readonly<('myteams' | number)[]>;
  270. topEvents: string | undefined;
  271. yAxis: string | undefined;
  272. expired?: boolean;
  273. interval?: string;
  274. utc?: string | boolean | undefined;
  275. }) {
  276. const fields: Field[] = Array.isArray(props.fields) ? props.fields : [];
  277. let sorts: Sort[] = Array.isArray(props.sorts) ? props.sorts : [];
  278. const team = Array.isArray(props.team) ? props.team : [];
  279. const project = Array.isArray(props.project) ? props.project : [];
  280. const environment = Array.isArray(props.environment) ? props.environment : [];
  281. // only include sort keys that are included in the fields
  282. let equations = 0;
  283. const sortKeys: string[] = [];
  284. fields.forEach(field => {
  285. if (field.field && isEquation(field.field)) {
  286. const sortKey = getSortKeyFromField({field: `equation[${equations}]`}, undefined);
  287. equations += 1;
  288. if (sortKey) {
  289. sortKeys.push(sortKey);
  290. }
  291. }
  292. const sortKey = getSortKeyFromField(field, undefined);
  293. if (sortKey) {
  294. sortKeys.push(sortKey);
  295. }
  296. });
  297. const sort = sorts.find(currentSort => sortKeys.includes(currentSort.field));
  298. sorts = sort ? [sort] : [];
  299. const id = props.id !== null && props.id !== void 0 ? String(props.id) : void 0;
  300. this.id = id;
  301. this.name = props.name;
  302. this.fields = fields;
  303. this.sorts = sorts;
  304. this.query = typeof props.query === 'string' ? props.query : '';
  305. this.team = team;
  306. this.project = project;
  307. this.start = props.start;
  308. this.end = props.end;
  309. this.statsPeriod = props.statsPeriod;
  310. this.utc = props.utc;
  311. this.environment = environment;
  312. this.yAxis = props.yAxis;
  313. this.display = props.display;
  314. this.topEvents = props.topEvents;
  315. this.interval = props.interval;
  316. this.createdBy = props.createdBy;
  317. this.expired = props.expired;
  318. this.additionalConditions = props.additionalConditions
  319. ? props.additionalConditions.copy()
  320. : new MutableSearch([]);
  321. }
  322. static fromLocation(location: Location): EventView {
  323. const {start, end, statsPeriod} = normalizeDateTimeParams(location.query);
  324. return new EventView({
  325. id: decodeScalar(location.query.id),
  326. name: decodeScalar(location.query.name),
  327. fields: decodeFields(location),
  328. sorts: decodeSorts(location),
  329. query: decodeQuery(location),
  330. team: decodeTeams(location),
  331. project: decodeProjects(location),
  332. start: decodeScalar(start),
  333. end: decodeScalar(end),
  334. statsPeriod: decodeScalar(statsPeriod),
  335. environment: collectQueryStringByKey(location.query, 'environment'),
  336. yAxis: decodeScalar(location.query.yAxis),
  337. display: decodeScalar(location.query.display),
  338. topEvents: decodeScalar(location.query.topEvents),
  339. interval: decodeScalar(location.query.interval),
  340. createdBy: undefined,
  341. additionalConditions: new MutableSearch([]),
  342. });
  343. }
  344. static fromNewQueryWithLocation(newQuery: NewQuery, location: Location): EventView {
  345. const query = location.query;
  346. // apply global selection header values from location whenever possible
  347. const environment: string[] =
  348. Array.isArray(newQuery.environment) && newQuery.environment.length > 0
  349. ? newQuery.environment
  350. : collectQueryStringByKey(query, 'environment');
  351. const project: number[] =
  352. Array.isArray(newQuery.projects) && newQuery.projects.length > 0
  353. ? newQuery.projects
  354. : decodeProjects(location);
  355. const saved: NewQuery = {
  356. ...newQuery,
  357. environment,
  358. projects: project,
  359. // datetime selection
  360. start: newQuery.start || decodeScalar(query.start),
  361. end: newQuery.end || decodeScalar(query.end),
  362. range: newQuery.range || decodeScalar(query.statsPeriod),
  363. };
  364. return EventView.fromSavedQuery(saved);
  365. }
  366. static getFields(saved: NewQuery | SavedQuery) {
  367. return saved.fields.map((field, i) => {
  368. const width =
  369. saved.widths && saved.widths[i] ? Number(saved.widths[i]) : COL_WIDTH_UNDEFINED;
  370. return {field, width};
  371. });
  372. }
  373. static fromSavedQuery(saved: NewQuery | SavedQuery): EventView {
  374. const fields = EventView.getFields(saved);
  375. // normalize datetime selection
  376. const {start, end, statsPeriod, utc} = normalizeDateTimeParams({
  377. start: saved.start,
  378. end: saved.end,
  379. statsPeriod: saved.range,
  380. utc: saved.utc,
  381. });
  382. return new EventView({
  383. id: saved.id,
  384. name: saved.name,
  385. fields,
  386. query: queryStringFromSavedQuery(saved),
  387. team: saved.teams ?? [],
  388. project: saved.projects,
  389. start: decodeScalar(start),
  390. end: decodeScalar(end),
  391. statsPeriod: decodeScalar(statsPeriod),
  392. utc,
  393. sorts: fromSorts(saved.orderby),
  394. environment: collectQueryStringByKey(
  395. {
  396. environment: saved.environment as string[],
  397. },
  398. 'environment'
  399. ),
  400. // Workaround to only use the first yAxis since eventView yAxis doesn't accept string[]
  401. yAxis: Array.isArray(saved.yAxis) ? saved.yAxis[0] : saved.yAxis,
  402. display: saved.display,
  403. topEvents: saved.topEvents ? saved.topEvents.toString() : undefined,
  404. interval: saved.interval,
  405. createdBy: saved.createdBy,
  406. expired: saved.expired,
  407. additionalConditions: new MutableSearch([]),
  408. });
  409. }
  410. static fromSavedQueryOrLocation(
  411. saved: SavedQuery | undefined,
  412. location: Location
  413. ): EventView {
  414. let fields = decodeFields(location);
  415. const id = decodeScalar(location.query.id);
  416. const teams = decodeTeams(location);
  417. const projects = decodeProjects(location);
  418. const sorts = decodeSorts(location);
  419. const environments = collectQueryStringByKey(location.query, 'environment');
  420. if (saved) {
  421. if (fields.length === 0) {
  422. fields = EventView.getFields(saved);
  423. }
  424. const {start, end, statsPeriod, utc} = normalizeDateTimeParams(
  425. location.query.start ||
  426. location.query.end ||
  427. location.query.statsPeriod ||
  428. location.query.utc
  429. ? location.query
  430. : {
  431. start: saved.start,
  432. end: saved.end,
  433. statsPeriod: saved.range,
  434. utc: saved.utc,
  435. }
  436. );
  437. return new EventView({
  438. id: id || saved.id,
  439. name: decodeScalar(location.query.name) || saved.name,
  440. fields,
  441. query:
  442. 'query' in location.query
  443. ? decodeQuery(location)
  444. : queryStringFromSavedQuery(saved),
  445. sorts: sorts.length === 0 ? fromSorts(saved.orderby) : sorts,
  446. yAxis:
  447. decodeScalar(location.query.yAxis) ||
  448. // Workaround to only use the first yAxis since eventView yAxis doesn't accept string[]
  449. (Array.isArray(saved.yAxis) ? saved.yAxis[0] : saved.yAxis),
  450. display: decodeScalar(location.query.display) || saved.display,
  451. topEvents: (
  452. decodeScalar(location.query.topEvents) ||
  453. saved.topEvents ||
  454. TOP_N
  455. ).toString(),
  456. interval: decodeScalar(location.query.interval) || saved.interval,
  457. createdBy: saved.createdBy,
  458. expired: saved.expired,
  459. additionalConditions: new MutableSearch([]),
  460. // Always read team from location since they can be set by other parts
  461. // of the UI
  462. team: teams,
  463. // Always read project and environment from location since they can
  464. // be set by the GlobalSelectionHeaders.
  465. project: projects,
  466. environment: environments,
  467. start: decodeScalar(start),
  468. end: decodeScalar(end),
  469. statsPeriod: decodeScalar(statsPeriod),
  470. utc,
  471. });
  472. }
  473. return EventView.fromLocation(location);
  474. }
  475. isEqualTo(other: EventView, omitList: string[] = []): boolean {
  476. const defaults = {
  477. id: undefined,
  478. name: undefined,
  479. query: undefined,
  480. statsPeriod: undefined,
  481. fields: undefined,
  482. sorts: undefined,
  483. project: undefined,
  484. environment: undefined,
  485. interval: undefined,
  486. yAxis: 'count()',
  487. display: DisplayModes.DEFAULT,
  488. topEvents: '5',
  489. };
  490. const keys = Object.keys(defaults).filter(key => !omitList.includes(key));
  491. for (const key of keys) {
  492. const currentValue = this[key] ?? defaults[key];
  493. const otherValue = other[key] ?? defaults[key];
  494. if (!isEqual(currentValue, otherValue)) {
  495. return false;
  496. }
  497. }
  498. // compare datetime selections using moment
  499. const dateTimeKeys = ['start', 'end'];
  500. for (const key of dateTimeKeys) {
  501. const currentValue = this[key];
  502. const otherValue = other[key];
  503. if (currentValue && otherValue) {
  504. const currentDateTime = moment.utc(currentValue);
  505. const otherDateTime = moment.utc(otherValue);
  506. if (!currentDateTime.isSame(otherDateTime)) {
  507. return false;
  508. }
  509. }
  510. }
  511. return true;
  512. }
  513. toNewQuery(): NewQuery {
  514. const orderby = this.sorts.length > 0 ? encodeSorts(this.sorts)[0] : undefined;
  515. const newQuery: NewQuery = {
  516. version: 2,
  517. id: this.id,
  518. name: this.name || '',
  519. fields: this.getFields(),
  520. widths: this.getWidths().map(w => String(w)),
  521. orderby,
  522. query: this.query || '',
  523. projects: this.project,
  524. start: this.start,
  525. end: this.end,
  526. range: this.statsPeriod,
  527. environment: this.environment,
  528. yAxis: this.yAxis ? [this.yAxis] : undefined,
  529. display: this.display,
  530. topEvents: this.topEvents,
  531. interval: this.interval,
  532. };
  533. if (!newQuery.query) {
  534. // if query is an empty string, then it cannot be saved, so we omit it
  535. // from the payload
  536. delete newQuery.query;
  537. }
  538. return newQuery;
  539. }
  540. getPageFilters(): PageFilters {
  541. return {
  542. projects: this.project as number[],
  543. environments: this.environment as string[],
  544. datetime: {
  545. start: this.start ?? null,
  546. end: this.end ?? null,
  547. period: this.statsPeriod ?? null,
  548. // TODO(tony) Add support for the Use UTC option from the global
  549. // headers, currently, that option is not supported and all times are
  550. // assumed to be UTC
  551. utc: true,
  552. },
  553. };
  554. }
  555. getPageFiltersQuery(): Query {
  556. const {
  557. environments: environment,
  558. projects,
  559. datetime: {start, end, period, utc},
  560. } = this.getPageFilters();
  561. return {
  562. project: projects.map(proj => proj.toString()),
  563. environment,
  564. utc: utc ? 'true' : 'false',
  565. // since these values are from `getGlobalSelection`
  566. // we know they have type `string | null`
  567. start: (start ?? undefined) as string | undefined,
  568. end: (end ?? undefined) as string | undefined,
  569. // we can't use the ?? operator here as we want to
  570. // convert the empty string to undefined
  571. statsPeriod: period ? period : undefined,
  572. };
  573. }
  574. generateBlankQueryStringObject(): Query {
  575. const output = {
  576. id: undefined,
  577. name: undefined,
  578. field: undefined,
  579. widths: undefined,
  580. sort: undefined,
  581. tag: undefined,
  582. query: undefined,
  583. yAxis: undefined,
  584. display: undefined,
  585. topEvents: undefined,
  586. interval: undefined,
  587. };
  588. for (const field of EXTERNAL_QUERY_STRING_KEYS) {
  589. output[field] = undefined;
  590. }
  591. return output;
  592. }
  593. generateQueryStringObject(): Query {
  594. const output = {
  595. id: this.id,
  596. name: this.name,
  597. field: this.getFields(),
  598. widths: this.getWidths(),
  599. sort: encodeSorts(this.sorts),
  600. environment: this.environment,
  601. project: this.project,
  602. query: this.query,
  603. yAxis: this.yAxis || this.getYAxis(),
  604. display: this.display,
  605. topEvents: this.topEvents,
  606. interval: this.interval,
  607. };
  608. for (const field of EXTERNAL_QUERY_STRING_KEYS) {
  609. if (this[field] && this[field].length) {
  610. output[field] = this[field];
  611. }
  612. }
  613. return cloneDeep(output as any);
  614. }
  615. isValid(): boolean {
  616. return this.fields.length > 0;
  617. }
  618. getWidths(): number[] {
  619. const result = this.fields.map(field =>
  620. field.width ? field.width : COL_WIDTH_UNDEFINED
  621. );
  622. while (result.length > 0) {
  623. const width = result[result.length - 1];
  624. if (width === COL_WIDTH_UNDEFINED) {
  625. result.pop();
  626. continue;
  627. }
  628. break;
  629. }
  630. return result;
  631. }
  632. getFields(): string[] {
  633. return this.fields.map(field => field.field);
  634. }
  635. getEquations(): string[] {
  636. return this.fields
  637. .filter(field => isEquation(field.field))
  638. .map(field => getEquation(field.field));
  639. }
  640. getAggregateFields(): Field[] {
  641. return this.fields.filter(
  642. field => isAggregateField(field.field) || isAggregateEquation(field.field)
  643. );
  644. }
  645. hasAggregateField() {
  646. return this.fields.some(field => isAggregateField(field.field));
  647. }
  648. hasIdField() {
  649. return this.fields.some(field => field.field === 'id');
  650. }
  651. numOfColumns(): number {
  652. return this.fields.length;
  653. }
  654. getColumns(): TableColumn<React.ReactText>[] {
  655. return decodeColumnOrder(this.fields);
  656. }
  657. getDays(): number {
  658. const statsPeriod = decodeScalar(this.statsPeriod);
  659. return statsPeriodToDays(statsPeriod, this.start, this.end);
  660. }
  661. clone(): EventView {
  662. // NOTE: We rely on usage of Readonly from TypeScript to ensure we do not mutate
  663. // the attributes of EventView directly. This enables us to quickly
  664. // clone new instances of EventView.
  665. return new EventView({
  666. id: this.id,
  667. name: this.name,
  668. fields: this.fields,
  669. sorts: this.sorts,
  670. query: this.query,
  671. team: this.team,
  672. project: this.project,
  673. start: this.start,
  674. end: this.end,
  675. statsPeriod: this.statsPeriod,
  676. environment: this.environment,
  677. yAxis: this.yAxis,
  678. display: this.display,
  679. topEvents: this.topEvents,
  680. interval: this.interval,
  681. expired: this.expired,
  682. createdBy: this.createdBy,
  683. additionalConditions: this.additionalConditions.copy(),
  684. });
  685. }
  686. withSorts(sorts: Sort[]): EventView {
  687. const newEventView = this.clone();
  688. const fields = newEventView.fields.map(field => getAggregateAlias(field.field));
  689. newEventView.sorts = sorts.filter(sort => fields.includes(sort.field));
  690. return newEventView;
  691. }
  692. withColumns(columns: Column[]): EventView {
  693. const newEventView = this.clone();
  694. const fields: Field[] = columns
  695. .filter(
  696. col =>
  697. ((col.kind === 'field' || col.kind === FieldValueKind.EQUATION) && col.field) ||
  698. (col.kind === 'function' && col.function[0])
  699. )
  700. .map(col => generateFieldAsString(col))
  701. .map((field, i) => {
  702. // newly added field
  703. if (!newEventView.fields[i]) {
  704. return {field, width: COL_WIDTH_UNDEFINED};
  705. }
  706. // Existing columns that were not re ordered should retain
  707. // their old widths.
  708. const existing = newEventView.fields[i];
  709. const width =
  710. existing.field === field && existing.width !== undefined
  711. ? existing.width
  712. : COL_WIDTH_UNDEFINED;
  713. return {field, width};
  714. });
  715. newEventView.fields = fields;
  716. // Update sorts as sorted fields may have been removed.
  717. if (newEventView.sorts) {
  718. // Filter the sort fields down to those that are still selected.
  719. const sortKeys = fields.map(field => fieldToSort(field, undefined)?.field);
  720. const newSort = newEventView.sorts.filter(
  721. sort => sort && sortKeys.includes(sort.field)
  722. );
  723. // If the sort field was removed, try and find a new sortable column.
  724. if (newSort.length === 0) {
  725. const sortField = fields.find(field => isFieldSortable(field, undefined));
  726. if (sortField) {
  727. newSort.push({field: sortField.field, kind: 'desc'});
  728. }
  729. }
  730. newEventView.sorts = newSort;
  731. }
  732. newEventView.yAxis = newEventView.getYAxis();
  733. return newEventView;
  734. }
  735. withNewColumn(newColumn: Column): EventView {
  736. const fieldAsString = generateFieldAsString(newColumn);
  737. const newField: Field = {
  738. field: fieldAsString,
  739. width: COL_WIDTH_UNDEFINED,
  740. };
  741. const newEventView = this.clone();
  742. newEventView.fields = [...newEventView.fields, newField];
  743. return newEventView;
  744. }
  745. withResizedColumn(columnIndex: number, newWidth: number) {
  746. const field = this.fields[columnIndex];
  747. const newEventView = this.clone();
  748. if (!field) {
  749. return newEventView;
  750. }
  751. const updateWidth = field.width !== newWidth;
  752. if (updateWidth) {
  753. const fields = [...newEventView.fields];
  754. fields[columnIndex] = {
  755. ...field,
  756. width: newWidth,
  757. };
  758. newEventView.fields = fields;
  759. }
  760. return newEventView;
  761. }
  762. withUpdatedColumn(
  763. columnIndex: number,
  764. updatedColumn: Column,
  765. tableMeta: MetaType | undefined
  766. ): EventView {
  767. const columnToBeUpdated = this.fields[columnIndex];
  768. const fieldAsString = generateFieldAsString(updatedColumn);
  769. const updateField = columnToBeUpdated.field !== fieldAsString;
  770. if (!updateField) {
  771. return this;
  772. }
  773. // ensure tableMeta is non-empty
  774. tableMeta = validateTableMeta(tableMeta);
  775. const newEventView = this.clone();
  776. const updatedField: Field = {
  777. field: fieldAsString,
  778. width: COL_WIDTH_UNDEFINED,
  779. };
  780. const fields = [...newEventView.fields];
  781. fields[columnIndex] = updatedField;
  782. newEventView.fields = fields;
  783. // if the updated column is one of the sorted columns, we may need to remove
  784. // it from the list of sorts
  785. const needleSortIndex = this.sorts.findIndex(sort =>
  786. isSortEqualToField(sort, columnToBeUpdated, tableMeta)
  787. );
  788. if (needleSortIndex >= 0) {
  789. const needleSort = this.sorts[needleSortIndex];
  790. const numOfColumns = this.fields.reduce((sum, currentField) => {
  791. if (isSortEqualToField(needleSort, currentField, tableMeta)) {
  792. return sum + 1;
  793. }
  794. return sum;
  795. }, 0);
  796. // do not bother deleting the sort key if there are more than one columns
  797. // of it in the table.
  798. if (numOfColumns <= 1) {
  799. if (isFieldSortable(updatedField, tableMeta)) {
  800. // use the current updated field as the sort key
  801. const sort = fieldToSort(updatedField, tableMeta)!;
  802. // preserve the sort kind
  803. sort.kind = needleSort.kind;
  804. const sorts = [...newEventView.sorts];
  805. sorts[needleSortIndex] = sort;
  806. newEventView.sorts = sorts;
  807. } else {
  808. const sorts = [...newEventView.sorts];
  809. sorts.splice(needleSortIndex, 1);
  810. newEventView.sorts = [...new Set(sorts)];
  811. }
  812. }
  813. if (newEventView.sorts.length <= 0 && newEventView.fields.length > 0) {
  814. // establish a default sort by finding the first sortable field
  815. if (isFieldSortable(updatedField, tableMeta)) {
  816. // use the current updated field as the sort key
  817. const sort = fieldToSort(updatedField, tableMeta)!;
  818. // preserve the sort kind
  819. sort.kind = needleSort.kind;
  820. newEventView.sorts = [sort];
  821. } else {
  822. const sortableFieldIndex = newEventView.fields.findIndex(currentField =>
  823. isFieldSortable(currentField, tableMeta)
  824. );
  825. if (sortableFieldIndex >= 0) {
  826. const fieldToBeSorted = newEventView.fields[sortableFieldIndex];
  827. const sort = fieldToSort(fieldToBeSorted, tableMeta)!;
  828. newEventView.sorts = [sort];
  829. }
  830. }
  831. }
  832. }
  833. newEventView.yAxis = newEventView.getYAxis();
  834. return newEventView;
  835. }
  836. withDeletedColumn(columnIndex: number, tableMeta: MetaType | undefined): EventView {
  837. // Disallow removal of the orphan column, and check for out-of-bounds
  838. if (this.fields.length <= 1 || this.fields.length <= columnIndex || columnIndex < 0) {
  839. return this;
  840. }
  841. // ensure tableMeta is non-empty
  842. tableMeta = validateTableMeta(tableMeta);
  843. // delete the column
  844. const newEventView = this.clone();
  845. const fields = [...newEventView.fields];
  846. fields.splice(columnIndex, 1);
  847. newEventView.fields = fields;
  848. // Ensure there is at least one auto width column
  849. // To ensure a well formed table results.
  850. const hasAutoIndex = fields.find(field => field.width === COL_WIDTH_UNDEFINED);
  851. if (!hasAutoIndex) {
  852. newEventView.fields[0].width = COL_WIDTH_UNDEFINED;
  853. }
  854. // if the deleted column is one of the sorted columns, we need to remove
  855. // it from the list of sorts
  856. const columnToBeDeleted = this.fields[columnIndex];
  857. const needleSortIndex = this.sorts.findIndex(sort =>
  858. isSortEqualToField(sort, columnToBeDeleted, tableMeta)
  859. );
  860. if (needleSortIndex >= 0) {
  861. const needleSort = this.sorts[needleSortIndex];
  862. const numOfColumns = this.fields.reduce((sum, field) => {
  863. if (isSortEqualToField(needleSort, field, tableMeta)) {
  864. return sum + 1;
  865. }
  866. return sum;
  867. }, 0);
  868. // do not bother deleting the sort key if there are more than one columns
  869. // of it in the table.
  870. if (numOfColumns <= 1) {
  871. const sorts = [...newEventView.sorts];
  872. sorts.splice(needleSortIndex, 1);
  873. newEventView.sorts = [...new Set(sorts)];
  874. if (newEventView.sorts.length <= 0 && newEventView.fields.length > 0) {
  875. // establish a default sort by finding the first sortable field
  876. const sortableFieldIndex = newEventView.fields.findIndex(field =>
  877. isFieldSortable(field, tableMeta)
  878. );
  879. if (sortableFieldIndex >= 0) {
  880. const fieldToBeSorted = newEventView.fields[sortableFieldIndex];
  881. const sort = fieldToSort(fieldToBeSorted, tableMeta)!;
  882. newEventView.sorts = [sort];
  883. }
  884. }
  885. }
  886. }
  887. newEventView.yAxis = newEventView.getYAxis();
  888. return newEventView;
  889. }
  890. withTeams(teams: ('myteams' | number)[]): EventView {
  891. const newEventView = this.clone();
  892. newEventView.team = teams;
  893. return newEventView;
  894. }
  895. getSorts(): TableColumnSort<React.ReactText>[] {
  896. return this.sorts.map(
  897. sort =>
  898. ({
  899. key: sort.field,
  900. order: sort.kind,
  901. } as TableColumnSort<string>)
  902. );
  903. }
  904. // returns query input for the search
  905. getQuery(inputQuery: string | string[] | null | undefined): string {
  906. const queryParts: string[] = [];
  907. if (this.query) {
  908. if (this.additionalConditions) {
  909. queryParts.push(this.getQueryWithAdditionalConditions());
  910. } else {
  911. queryParts.push(this.query);
  912. }
  913. }
  914. if (inputQuery) {
  915. // there may be duplicate query in the query string
  916. // e.g. query=hello&query=world
  917. if (Array.isArray(inputQuery)) {
  918. inputQuery.forEach(query => {
  919. if (typeof query === 'string' && !queryParts.includes(query)) {
  920. queryParts.push(query);
  921. }
  922. });
  923. }
  924. if (typeof inputQuery === 'string' && !queryParts.includes(inputQuery)) {
  925. queryParts.push(inputQuery);
  926. }
  927. }
  928. return queryParts.join(' ');
  929. }
  930. getFacetsAPIPayload(
  931. location: Location
  932. ): Exclude<EventQuery & LocationQuery, 'sort' | 'cursor'> {
  933. const payload = this.getEventsAPIPayload(location);
  934. const remove = [
  935. 'id',
  936. 'name',
  937. 'per_page',
  938. 'sort',
  939. 'cursor',
  940. 'field',
  941. 'equation',
  942. 'interval',
  943. ];
  944. for (const key of remove) {
  945. delete payload[key];
  946. }
  947. return payload;
  948. }
  949. normalizeDateSelection(location: Location) {
  950. const query = (location && location.query) || {};
  951. // pick only the query strings that we care about
  952. const picked = pickRelevantLocationQueryStrings(location);
  953. const hasDateSelection = this.statsPeriod || (this.start && this.end);
  954. // an eventview's date selection has higher precedence than the date selection in the query string
  955. const dateSelection = hasDateSelection
  956. ? {
  957. start: this.start,
  958. end: this.end,
  959. statsPeriod: this.statsPeriod,
  960. }
  961. : {
  962. start: picked.start,
  963. end: picked.end,
  964. period: decodeScalar(query.period),
  965. statsPeriod: picked.statsPeriod,
  966. };
  967. // normalize datetime selection
  968. return normalizeDateTimeParams({
  969. ...dateSelection,
  970. utc: decodeScalar(query.utc),
  971. });
  972. }
  973. // Takes an EventView instance and converts it into the format required for the events API
  974. getEventsAPIPayload(
  975. location: Location,
  976. forceAppendRawQueryString?: string
  977. ): EventQuery & LocationQuery {
  978. // pick only the query strings that we care about
  979. const picked = pickRelevantLocationQueryStrings(location);
  980. // normalize datetime selection
  981. const normalizedTimeWindowParams = this.normalizeDateSelection(location);
  982. const sort =
  983. this.sorts.length <= 0
  984. ? undefined
  985. : this.sorts.length > 1
  986. ? encodeSorts(this.sorts)
  987. : encodeSort(this.sorts[0]);
  988. const fields = this.getFields();
  989. const team = this.team.map(proj => String(proj));
  990. const project = this.project.map(proj => String(proj));
  991. const environment = this.environment as string[];
  992. let queryString = this.getQueryWithAdditionalConditions();
  993. if (forceAppendRawQueryString) {
  994. queryString += ' ' + forceAppendRawQueryString;
  995. }
  996. // generate event query
  997. const eventQuery = Object.assign(
  998. omit(picked, DATETIME_QUERY_STRING_KEYS),
  999. normalizedTimeWindowParams,
  1000. {
  1001. team,
  1002. project,
  1003. environment,
  1004. field: [...new Set(fields)],
  1005. sort,
  1006. per_page: DEFAULT_PER_PAGE,
  1007. query: queryString,
  1008. }
  1009. ) as EventQuery & LocationQuery;
  1010. if (eventQuery.team && !eventQuery.team.length) {
  1011. delete eventQuery.team;
  1012. }
  1013. if (!eventQuery.sort) {
  1014. delete eventQuery.sort;
  1015. }
  1016. return eventQuery;
  1017. }
  1018. getResultsViewUrlTarget(
  1019. slug: string,
  1020. isHomepage: boolean = false
  1021. ): {pathname: string; query: Query} {
  1022. const target = isHomepage ? 'homepage' : 'results';
  1023. return {
  1024. pathname: `/organizations/${slug}/discover/${target}/`,
  1025. query: this.generateQueryStringObject(),
  1026. };
  1027. }
  1028. getResultsViewShortUrlTarget(slug: string): {pathname: string; query: Query} {
  1029. const output = {id: this.id};
  1030. for (const field of [...Object.values(URL_PARAM), 'cursor']) {
  1031. if (this[field] && this[field].length) {
  1032. output[field] = this[field];
  1033. }
  1034. }
  1035. return {
  1036. pathname: `/organizations/${slug}/discover/results/`,
  1037. query: cloneDeep(output as any),
  1038. };
  1039. }
  1040. getPerformanceTransactionEventsViewUrlTarget(
  1041. slug: string,
  1042. options: {
  1043. breakdown?: SpanOperationBreakdownFilter;
  1044. showTransactions?: EventsDisplayFilterName;
  1045. webVital?: WebVital;
  1046. }
  1047. ): {pathname: string; query: Query} {
  1048. const {showTransactions, breakdown, webVital} = options;
  1049. const output = {
  1050. sort: encodeSorts(this.sorts),
  1051. project: this.project,
  1052. query: this.query,
  1053. transaction: this.name,
  1054. showTransactions,
  1055. breakdown,
  1056. webVital,
  1057. };
  1058. for (const field of EXTERNAL_QUERY_STRING_KEYS) {
  1059. if (this[field] && this[field].length) {
  1060. output[field] = this[field];
  1061. }
  1062. }
  1063. const query = cloneDeep(output as any);
  1064. return {
  1065. pathname: `/organizations/${slug}/performance/summary/events/`,
  1066. query,
  1067. };
  1068. }
  1069. sortForField(field: Field, tableMeta: MetaType | undefined): Sort | undefined {
  1070. if (!tableMeta) {
  1071. return undefined;
  1072. }
  1073. return this.sorts.find(sort => isSortEqualToField(sort, field, tableMeta));
  1074. }
  1075. sortOnField(
  1076. field: Field,
  1077. tableMeta: MetaType,
  1078. kind?: 'desc' | 'asc',
  1079. useFunctionFormat?: boolean
  1080. ): EventView {
  1081. // check if field can be sorted
  1082. if (!isFieldSortable(field, tableMeta)) {
  1083. return this;
  1084. }
  1085. const needleIndex = this.sorts.findIndex(sort =>
  1086. isSortEqualToField(sort, field, tableMeta)
  1087. );
  1088. if (needleIndex >= 0) {
  1089. const newEventView = this.clone();
  1090. const currentSort = this.sorts[needleIndex];
  1091. const sorts = [...newEventView.sorts];
  1092. sorts[needleIndex] = kind
  1093. ? setSortOrder(
  1094. {...currentSort, ...(useFunctionFormat ? {field: field.field} : {})},
  1095. kind
  1096. )
  1097. : reverseSort({
  1098. ...currentSort,
  1099. ...(useFunctionFormat ? {field: field.field} : {}),
  1100. });
  1101. newEventView.sorts = sorts;
  1102. return newEventView;
  1103. }
  1104. // field is currently not sorted; so, we sort on it
  1105. const newEventView = this.clone();
  1106. // invariant: this is not falsey, since sortKey exists
  1107. const sort = fieldToSort(field, tableMeta, kind, useFunctionFormat)!;
  1108. newEventView.sorts = [sort];
  1109. return newEventView;
  1110. }
  1111. getYAxisOptions(): SelectValue<string>[] {
  1112. // Make option set and add the default options in.
  1113. return uniqBy(
  1114. this.getAggregateFields()
  1115. // Only include aggregates that make sense to be graphable (eg. not string or date)
  1116. .filter(
  1117. (field: Field) =>
  1118. isLegalYAxisType(aggregateOutputType(field.field)) ||
  1119. isAggregateEquation(field.field)
  1120. )
  1121. .map((field: Field) => ({
  1122. label: isEquation(field.field) ? getEquation(field.field) : field.field,
  1123. value: field.field,
  1124. }))
  1125. .concat(CHART_AXIS_OPTIONS),
  1126. 'value'
  1127. );
  1128. }
  1129. getYAxis(): string {
  1130. const yAxisOptions = this.getYAxisOptions();
  1131. const yAxis = this.yAxis;
  1132. const defaultOption = yAxisOptions[0].value;
  1133. if (!yAxis) {
  1134. return defaultOption;
  1135. }
  1136. // ensure current selected yAxis is one of the items in yAxisOptions
  1137. const result = yAxisOptions.findIndex(
  1138. (option: SelectValue<string>) => option.value === yAxis
  1139. );
  1140. if (result >= 0) {
  1141. return yAxis;
  1142. }
  1143. return defaultOption;
  1144. }
  1145. getDisplayOptions(): SelectValue<string>[] {
  1146. return DISPLAY_MODE_OPTIONS.map(item => {
  1147. if (item.value === DisplayModes.PREVIOUS) {
  1148. if (this.start || this.end) {
  1149. return {...item, disabled: true};
  1150. }
  1151. }
  1152. if (item.value === DisplayModes.TOP5 || item.value === DisplayModes.DAILYTOP5) {
  1153. if (this.getAggregateFields().length === 0) {
  1154. return {
  1155. ...item,
  1156. disabled: true,
  1157. tooltip: t('Add a function that groups events to use this view.'),
  1158. };
  1159. }
  1160. }
  1161. if (item.value === DisplayModes.DAILY || item.value === DisplayModes.DAILYTOP5) {
  1162. if (this.getDays() < 1) {
  1163. return {
  1164. ...item,
  1165. disabled: true,
  1166. tooltip: t('Change the date rage to at least 1 day to use this view.'),
  1167. };
  1168. }
  1169. }
  1170. return item;
  1171. });
  1172. }
  1173. getDisplayMode() {
  1174. const mode = this.display ?? DisplayModes.DEFAULT;
  1175. const displayOptions = this.getDisplayOptions();
  1176. let display = (Object.values(DisplayModes) as string[]).includes(mode)
  1177. ? mode
  1178. : DisplayModes.DEFAULT;
  1179. const cond = option => option.value === display;
  1180. // Just in case we define a fallback chain that results in an infinite loop.
  1181. // The number 5 isn't anything special, its just larger than the longest fallback
  1182. // chain that exists and isn't too big.
  1183. for (let i = 0; i < 5; i++) {
  1184. const selectedOption = displayOptions.find(cond);
  1185. if (selectedOption && !selectedOption.disabled) {
  1186. return display;
  1187. }
  1188. display = DISPLAY_MODE_FALLBACK_OPTIONS[display];
  1189. }
  1190. // after trying to find an enabled display mode and failing to find one,
  1191. // we just use the default display mode
  1192. return DisplayModes.DEFAULT;
  1193. }
  1194. getQueryWithAdditionalConditions() {
  1195. const {query} = this;
  1196. if (this.additionalConditions.isEmpty()) {
  1197. return query;
  1198. }
  1199. const conditions = new MutableSearch(query);
  1200. Object.entries(this.additionalConditions.filters).forEach(([tag, tagValues]) => {
  1201. const existingTagValues = conditions.getFilterValues(tag);
  1202. const newTagValues = tagValues.filter(
  1203. tagValue => !existingTagValues.includes(tagValue)
  1204. );
  1205. if (newTagValues.length) {
  1206. conditions.addFilterValues(tag, newTagValues);
  1207. }
  1208. });
  1209. return conditions.formatString();
  1210. }
  1211. /**
  1212. * Eventview usually just holds onto a project id for selected projects.
  1213. * Sometimes we need to iterate over the related project objects, this will give you the full projects if the Projects list is passed in.
  1214. * Also covers the 'My Projects' case which is sometimes missed, tries using the 'isMember' property of projects to pick the right list.
  1215. */
  1216. getFullSelectedProjects(fullProjectList: Project[]) {
  1217. const selectedProjectIds = this.project;
  1218. const isMyProjects = selectedProjectIds.length === 0;
  1219. if (isMyProjects) {
  1220. return fullProjectList.filter(p => p.isMember);
  1221. }
  1222. const isAllProjects =
  1223. selectedProjectIds.length === 1 && selectedProjectIds[0] === ALL_ACCESS_PROJECTS;
  1224. if (isAllProjects) {
  1225. return fullProjectList;
  1226. }
  1227. const projectMap = Object.fromEntries(fullProjectList.map(p => [String(p.id), p]));
  1228. return selectedProjectIds.map(id => projectMap[String(id)]);
  1229. }
  1230. }
  1231. export type ImmutableEventView = Readonly<Omit<EventView, 'additionalConditions'>>;
  1232. const isFieldsSimilar = (
  1233. currentValue: Array<string>,
  1234. otherValue: Array<string>
  1235. ): boolean => {
  1236. // For equation's their order matters because we alias them based on index
  1237. const currentEquations = currentValue.filter(isEquation);
  1238. const otherEquations = otherValue.filter(isEquation);
  1239. // Field orders don't matter, so using a set for comparison
  1240. const currentFields = new Set(currentValue.filter(value => !isEquation(value)));
  1241. const otherFields = new Set(otherValue.filter(value => !isEquation(value)));
  1242. if (!isEqual(currentEquations, otherEquations)) {
  1243. return false;
  1244. }
  1245. if (!isEqual(currentFields, otherFields)) {
  1246. return false;
  1247. }
  1248. return true;
  1249. };
  1250. export const isAPIPayloadSimilar = (
  1251. current: EventQuery & LocationQuery,
  1252. other: EventQuery & LocationQuery
  1253. ): boolean => {
  1254. const currentKeys = new Set(Object.keys(current));
  1255. const otherKeys = new Set(Object.keys(other));
  1256. if (!isEqual(currentKeys, otherKeys)) {
  1257. return false;
  1258. }
  1259. for (const key of currentKeys) {
  1260. const currentValue = current[key];
  1261. const otherValue = other[key];
  1262. if (key === 'field') {
  1263. if (!isFieldsSimilar(currentValue, otherValue)) {
  1264. return false;
  1265. }
  1266. } else {
  1267. const currentTarget = Array.isArray(currentValue)
  1268. ? new Set(currentValue)
  1269. : currentValue;
  1270. const otherTarget = Array.isArray(otherValue) ? new Set(otherValue) : otherValue;
  1271. if (!isEqual(currentTarget, otherTarget)) {
  1272. return false;
  1273. }
  1274. }
  1275. }
  1276. return true;
  1277. };
  1278. export function pickRelevantLocationQueryStrings(location: Location) {
  1279. const query = location.query || {};
  1280. const picked = pick(query || {}, EXTERNAL_QUERY_STRING_KEYS);
  1281. return picked;
  1282. }
  1283. export default EventView;