eventView.tsx 44 KB

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