eventView.tsx 42 KB

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