eventView.tsx 42 KB

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