eventView.tsx 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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(slug: string): {pathname: string; query: Query} {
  1005. return {
  1006. pathname: `/organizations/${slug}/discover/results/`,
  1007. query: this.generateQueryStringObject(),
  1008. };
  1009. }
  1010. getResultsViewShortUrlTarget(slug: string): {pathname: string; query: Query} {
  1011. const output = {id: this.id};
  1012. for (const field of [...Object.values(URL_PARAM), 'cursor']) {
  1013. if (this[field] && this[field].length) {
  1014. output[field] = this[field];
  1015. }
  1016. }
  1017. return {
  1018. pathname: `/organizations/${slug}/discover/results/`,
  1019. query: cloneDeep(output as any),
  1020. };
  1021. }
  1022. getPerformanceTransactionEventsViewUrlTarget(
  1023. slug: string,
  1024. options: {
  1025. breakdown?: SpanOperationBreakdownFilter;
  1026. showTransactions?: EventsDisplayFilterName;
  1027. webVital?: WebVital;
  1028. }
  1029. ): {pathname: string; query: Query} {
  1030. const {showTransactions, breakdown, webVital} = options;
  1031. const output = {
  1032. sort: encodeSorts(this.sorts),
  1033. project: this.project,
  1034. query: this.query,
  1035. transaction: this.name,
  1036. showTransactions,
  1037. breakdown,
  1038. webVital,
  1039. };
  1040. for (const field of EXTERNAL_QUERY_STRING_KEYS) {
  1041. if (this[field] && this[field].length) {
  1042. output[field] = this[field];
  1043. }
  1044. }
  1045. const query = cloneDeep(output as any);
  1046. return {
  1047. pathname: `/organizations/${slug}/performance/summary/events/`,
  1048. query,
  1049. };
  1050. }
  1051. sortForField(field: Field, tableMeta: MetaType | undefined): Sort | undefined {
  1052. if (!tableMeta) {
  1053. return undefined;
  1054. }
  1055. return this.sorts.find(sort => isSortEqualToField(sort, field, tableMeta));
  1056. }
  1057. sortOnField(
  1058. field: Field,
  1059. tableMeta: MetaType,
  1060. kind?: 'desc' | 'asc',
  1061. useFunctionFormat?: boolean
  1062. ): EventView {
  1063. // check if field can be sorted
  1064. if (!isFieldSortable(field, tableMeta)) {
  1065. return this;
  1066. }
  1067. const needleIndex = this.sorts.findIndex(sort =>
  1068. isSortEqualToField(sort, field, tableMeta)
  1069. );
  1070. if (needleIndex >= 0) {
  1071. const newEventView = this.clone();
  1072. const currentSort = this.sorts[needleIndex];
  1073. const sorts = [...newEventView.sorts];
  1074. sorts[needleIndex] = kind
  1075. ? setSortOrder(
  1076. {...currentSort, ...(useFunctionFormat ? {field: field.field} : {})},
  1077. kind
  1078. )
  1079. : reverseSort({
  1080. ...currentSort,
  1081. ...(useFunctionFormat ? {field: field.field} : {}),
  1082. });
  1083. newEventView.sorts = sorts;
  1084. return newEventView;
  1085. }
  1086. // field is currently not sorted; so, we sort on it
  1087. const newEventView = this.clone();
  1088. // invariant: this is not falsey, since sortKey exists
  1089. const sort = fieldToSort(field, tableMeta, kind, useFunctionFormat)!;
  1090. newEventView.sorts = [sort];
  1091. return newEventView;
  1092. }
  1093. getYAxisOptions(): SelectValue<string>[] {
  1094. // Make option set and add the default options in.
  1095. return uniqBy(
  1096. this.getAggregateFields()
  1097. // Only include aggregates that make sense to be graphable (eg. not string or date)
  1098. .filter(
  1099. (field: Field) =>
  1100. isLegalYAxisType(aggregateOutputType(field.field)) ||
  1101. isAggregateEquation(field.field)
  1102. )
  1103. .map((field: Field) => ({
  1104. label: isEquation(field.field) ? getEquation(field.field) : field.field,
  1105. value: field.field,
  1106. }))
  1107. .concat(CHART_AXIS_OPTIONS),
  1108. 'value'
  1109. );
  1110. }
  1111. getYAxis(): string {
  1112. const yAxisOptions = this.getYAxisOptions();
  1113. const yAxis = this.yAxis;
  1114. const defaultOption = yAxisOptions[0].value;
  1115. if (!yAxis) {
  1116. return defaultOption;
  1117. }
  1118. // ensure current selected yAxis is one of the items in yAxisOptions
  1119. const result = yAxisOptions.findIndex(
  1120. (option: SelectValue<string>) => option.value === yAxis
  1121. );
  1122. if (result >= 0) {
  1123. return yAxis;
  1124. }
  1125. return defaultOption;
  1126. }
  1127. getDisplayOptions(): SelectValue<string>[] {
  1128. return DISPLAY_MODE_OPTIONS.map(item => {
  1129. if (item.value === DisplayModes.PREVIOUS) {
  1130. if (this.start || this.end) {
  1131. return {...item, disabled: true};
  1132. }
  1133. }
  1134. if (item.value === DisplayModes.TOP5 || item.value === DisplayModes.DAILYTOP5) {
  1135. if (this.getAggregateFields().length === 0) {
  1136. return {
  1137. ...item,
  1138. disabled: true,
  1139. tooltip: t('Add a function that groups events to use this view.'),
  1140. };
  1141. }
  1142. }
  1143. if (item.value === DisplayModes.DAILY || item.value === DisplayModes.DAILYTOP5) {
  1144. if (this.getDays() < 1) {
  1145. return {
  1146. ...item,
  1147. disabled: true,
  1148. tooltip: t('Change the date rage to at least 1 day to use this view.'),
  1149. };
  1150. }
  1151. }
  1152. return item;
  1153. });
  1154. }
  1155. getDisplayMode() {
  1156. const mode = this.display ?? DisplayModes.DEFAULT;
  1157. const displayOptions = this.getDisplayOptions();
  1158. let display = (Object.values(DisplayModes) as string[]).includes(mode)
  1159. ? mode
  1160. : DisplayModes.DEFAULT;
  1161. const cond = option => option.value === display;
  1162. // Just in case we define a fallback chain that results in an infinite loop.
  1163. // The number 5 isn't anything special, its just larger than the longest fallback
  1164. // chain that exists and isn't too big.
  1165. for (let i = 0; i < 5; i++) {
  1166. const selectedOption = displayOptions.find(cond);
  1167. if (selectedOption && !selectedOption.disabled) {
  1168. return display;
  1169. }
  1170. display = DISPLAY_MODE_FALLBACK_OPTIONS[display];
  1171. }
  1172. // after trying to find an enabled display mode and failing to find one,
  1173. // we just use the default display mode
  1174. return DisplayModes.DEFAULT;
  1175. }
  1176. getQueryWithAdditionalConditions() {
  1177. const {query} = this;
  1178. if (this.additionalConditions.isEmpty()) {
  1179. return query;
  1180. }
  1181. const conditions = new MutableSearch(query);
  1182. Object.entries(this.additionalConditions.filters).forEach(([tag, tagValues]) => {
  1183. const existingTagValues = conditions.getFilterValues(tag);
  1184. const newTagValues = tagValues.filter(
  1185. tagValue => !existingTagValues.includes(tagValue)
  1186. );
  1187. if (newTagValues.length) {
  1188. conditions.addFilterValues(tag, newTagValues);
  1189. }
  1190. });
  1191. return conditions.formatString();
  1192. }
  1193. /**
  1194. * Eventview usually just holds onto a project id for selected projects.
  1195. * Sometimes we need to iterate over the related project objects, this will give you the full projects if the Projects list is passed in.
  1196. * Also covers the 'My Projects' case which is sometimes missed, tries using the 'isMember' property of projects to pick the right list.
  1197. */
  1198. getFullSelectedProjects(fullProjectList: Project[]) {
  1199. const selectedProjectIds = this.project;
  1200. const isMyProjects = selectedProjectIds.length === 0;
  1201. if (isMyProjects) {
  1202. return fullProjectList.filter(p => p.isMember);
  1203. }
  1204. const isAllProjects =
  1205. selectedProjectIds.length === 1 && selectedProjectIds[0] === ALL_ACCESS_PROJECTS;
  1206. if (isAllProjects) {
  1207. return fullProjectList;
  1208. }
  1209. const projectMap = Object.fromEntries(fullProjectList.map(p => [String(p.id), p]));
  1210. return selectedProjectIds.map(id => projectMap[String(id)]);
  1211. }
  1212. }
  1213. export type ImmutableEventView = Readonly<Omit<EventView, 'additionalConditions'>>;
  1214. const isFieldsSimilar = (
  1215. currentValue: Array<string>,
  1216. otherValue: Array<string>
  1217. ): boolean => {
  1218. // For equation's their order matters because we alias them based on index
  1219. const currentEquations = currentValue.filter(isEquation);
  1220. const otherEquations = otherValue.filter(isEquation);
  1221. // Field orders don't matter, so using a set for comparison
  1222. const currentFields = new Set(currentValue.filter(value => !isEquation(value)));
  1223. const otherFields = new Set(otherValue.filter(value => !isEquation(value)));
  1224. if (!isEqual(currentEquations, otherEquations)) {
  1225. return false;
  1226. }
  1227. if (!isEqual(currentFields, otherFields)) {
  1228. return false;
  1229. }
  1230. return true;
  1231. };
  1232. export const isAPIPayloadSimilar = (
  1233. current: EventQuery & LocationQuery,
  1234. other: EventQuery & LocationQuery
  1235. ): boolean => {
  1236. const currentKeys = new Set(Object.keys(current));
  1237. const otherKeys = new Set(Object.keys(other));
  1238. if (!isEqual(currentKeys, otherKeys)) {
  1239. return false;
  1240. }
  1241. for (const key of currentKeys) {
  1242. const currentValue = current[key];
  1243. const otherValue = other[key];
  1244. if (key === 'field') {
  1245. if (!isFieldsSimilar(currentValue, otherValue)) {
  1246. return false;
  1247. }
  1248. } else {
  1249. const currentTarget = Array.isArray(currentValue)
  1250. ? new Set(currentValue)
  1251. : currentValue;
  1252. const otherTarget = Array.isArray(otherValue) ? new Set(otherValue) : otherValue;
  1253. if (!isEqual(currentTarget, otherTarget)) {
  1254. return false;
  1255. }
  1256. }
  1257. }
  1258. return true;
  1259. };
  1260. export function pickRelevantLocationQueryStrings(location: Location) {
  1261. const query = location.query || {};
  1262. const picked = pick(query || {}, EXTERNAL_QUERY_STRING_KEYS);
  1263. return picked;
  1264. }
  1265. export default EventView;