eventView.tsx 44 KB

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