eventView.tsx 44 KB

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