eventView.tsx 43 KB

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