eventView.tsx 41 KB

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