dashboardTable.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. import {useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {Location} from 'history';
  4. import cloneDeep from 'lodash/cloneDeep';
  5. import {
  6. createDashboard,
  7. deleteDashboard,
  8. fetchDashboard,
  9. updateDashboardFavorite,
  10. updateDashboardPermissions,
  11. } from 'sentry/actionCreators/dashboards';
  12. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  13. import type {Client} from 'sentry/api';
  14. import Feature from 'sentry/components/acl/feature';
  15. import {ActivityAvatar} from 'sentry/components/activity/item/avatar';
  16. import {Button} from 'sentry/components/button';
  17. import {openConfirmModal} from 'sentry/components/confirm';
  18. import EmptyStateWarning from 'sentry/components/emptyStateWarning';
  19. import GridEditable, {
  20. COL_WIDTH_UNDEFINED,
  21. type GridColumnOrder,
  22. } from 'sentry/components/gridEditable';
  23. import Link from 'sentry/components/links/link';
  24. import TimeSince from 'sentry/components/timeSince';
  25. import {IconCopy, IconDelete, IconStar} from 'sentry/icons';
  26. import {t} from 'sentry/locale';
  27. import {space} from 'sentry/styles/space';
  28. import type {Organization} from 'sentry/types/organization';
  29. import {trackAnalytics} from 'sentry/utils/analytics';
  30. import withApi from 'sentry/utils/withApi';
  31. import EditAccessSelector from 'sentry/views/dashboards/editAccessSelector';
  32. import type {
  33. DashboardDetails,
  34. DashboardListItem,
  35. DashboardPermissions,
  36. } from 'sentry/views/dashboards/types';
  37. import {cloneDashboard} from '../utils';
  38. type Props = {
  39. api: Client;
  40. dashboards: DashboardListItem[] | undefined;
  41. location: Location;
  42. onDashboardsChange: () => void;
  43. organization: Organization;
  44. isLoading?: boolean;
  45. };
  46. enum ResponseKeys {
  47. NAME = 'title',
  48. WIDGETS = 'widgetDisplay',
  49. OWNER = 'createdBy',
  50. ACCESS = 'permissions',
  51. CREATED = 'dateCreated',
  52. FAVORITE = 'isFavorited',
  53. }
  54. type FavoriteButtonProps = {
  55. api: Client;
  56. dashboardId: string;
  57. isFavorited: boolean;
  58. onDashboardsChange: () => void;
  59. organization: Organization;
  60. };
  61. function FavoriteButton({
  62. isFavorited,
  63. api,
  64. organization,
  65. dashboardId,
  66. onDashboardsChange,
  67. }: FavoriteButtonProps) {
  68. const [favorited, setFavorited] = useState(isFavorited);
  69. return (
  70. <Feature features="dashboards-favourite">
  71. <StyledFavoriteButton
  72. aria-label={t('Favorite Button')}
  73. size="zero"
  74. borderless
  75. icon={
  76. <IconStar
  77. color={favorited ? 'yellow300' : 'gray300'}
  78. isSolid={favorited}
  79. aria-label={favorited ? t('UnFavorite') : t('Favorite')}
  80. size="sm"
  81. />
  82. }
  83. onClick={async () => {
  84. try {
  85. setFavorited(!favorited);
  86. await updateDashboardFavorite(
  87. api,
  88. organization.slug,
  89. dashboardId,
  90. !favorited
  91. );
  92. onDashboardsChange();
  93. } catch (error) {
  94. // If the api call fails, revert the state
  95. setFavorited(favorited);
  96. }
  97. }}
  98. />
  99. </Feature>
  100. );
  101. }
  102. function DashboardTable({
  103. api,
  104. organization,
  105. location,
  106. dashboards,
  107. onDashboardsChange,
  108. isLoading,
  109. }: Props) {
  110. const columnOrder: GridColumnOrder<ResponseKeys>[] = [
  111. ...(organization.features.includes('dashboards-favourite')
  112. ? [{key: ResponseKeys.FAVORITE, name: t('Favorite'), width: 50}]
  113. : []),
  114. {key: ResponseKeys.NAME, name: t('Name'), width: COL_WIDTH_UNDEFINED},
  115. {key: ResponseKeys.WIDGETS, name: t('Widgets'), width: COL_WIDTH_UNDEFINED},
  116. {key: ResponseKeys.OWNER, name: t('Owner'), width: COL_WIDTH_UNDEFINED},
  117. ...(organization.features.includes('dashboards-edit-access')
  118. ? [{key: ResponseKeys.ACCESS, name: t('Access'), width: COL_WIDTH_UNDEFINED}]
  119. : []),
  120. {key: ResponseKeys.CREATED, name: t('Created'), width: COL_WIDTH_UNDEFINED},
  121. ];
  122. function handleDelete(dashboard: DashboardListItem) {
  123. deleteDashboard(api, organization.slug, dashboard.id)
  124. .then(() => {
  125. trackAnalytics('dashboards_manage.delete', {
  126. organization,
  127. dashboard_id: parseInt(dashboard.id, 10),
  128. view_type: 'table',
  129. });
  130. onDashboardsChange();
  131. addSuccessMessage(t('Dashboard deleted'));
  132. })
  133. .catch(() => {
  134. addErrorMessage(t('Error deleting Dashboard'));
  135. });
  136. }
  137. async function handleDuplicate(dashboard: DashboardListItem) {
  138. try {
  139. const dashboardDetail = await fetchDashboard(api, organization.slug, dashboard.id);
  140. const newDashboard = cloneDashboard(dashboardDetail);
  141. newDashboard.widgets.map(widget => (widget.id = undefined));
  142. await createDashboard(api, organization.slug, newDashboard, true);
  143. trackAnalytics('dashboards_manage.duplicate', {
  144. organization,
  145. dashboard_id: parseInt(dashboard.id, 10),
  146. view_type: 'table',
  147. });
  148. onDashboardsChange();
  149. addSuccessMessage(t('Dashboard duplicated'));
  150. } catch (e) {
  151. addErrorMessage(t('Error duplicating Dashboard'));
  152. }
  153. }
  154. // TODO(__SENTRY_USING_REACT_ROUTER_SIX): We can remove this later, react
  155. // router 6 handles empty query objects without appending a trailing ?
  156. const queryLocation = {
  157. ...(location.query && Object.keys(location.query).length > 0
  158. ? {query: location.query}
  159. : {}),
  160. };
  161. const renderBodyCell = (
  162. column: GridColumnOrder<string>,
  163. dataRow: DashboardListItem
  164. ) => {
  165. if (column.key === ResponseKeys.FAVORITE) {
  166. return (
  167. <FavoriteButton
  168. isFavorited={dataRow[ResponseKeys.FAVORITE] ?? false}
  169. api={api}
  170. organization={organization}
  171. dashboardId={dataRow.id}
  172. onDashboardsChange={onDashboardsChange}
  173. key={dataRow.id}
  174. />
  175. );
  176. }
  177. if (column.key === ResponseKeys.NAME) {
  178. return (
  179. <Link
  180. to={{
  181. pathname: `/organizations/${organization.slug}/dashboard/${dataRow.id}/`,
  182. ...queryLocation,
  183. }}
  184. >
  185. {dataRow[ResponseKeys.NAME]}
  186. </Link>
  187. );
  188. }
  189. if (column.key === ResponseKeys.WIDGETS) {
  190. return dataRow[ResponseKeys.WIDGETS].length;
  191. }
  192. if (column.key === ResponseKeys.OWNER) {
  193. return dataRow[ResponseKeys.OWNER] ? (
  194. <ActivityAvatar type="user" user={dataRow[ResponseKeys.OWNER]} size={26} />
  195. ) : (
  196. <ActivityAvatar type="system" size={26} />
  197. );
  198. }
  199. if (
  200. column.key === ResponseKeys.ACCESS &&
  201. organization.features.includes('dashboards-edit-access')
  202. ) {
  203. /* Handles POST request for Edit Access Selector Changes */
  204. const onChangeEditAccess = (newDashboardPermissions: DashboardPermissions) => {
  205. const dashboardCopy = cloneDeep(dataRow);
  206. dashboardCopy.permissions = newDashboardPermissions;
  207. updateDashboardPermissions(api, organization.slug, dashboardCopy).then(
  208. (newDashboard: DashboardDetails) => {
  209. onDashboardsChange();
  210. addSuccessMessage(t('Dashboard Edit Access updated.'));
  211. return newDashboard;
  212. }
  213. );
  214. };
  215. return (
  216. <EditAccessSelector
  217. dashboard={dataRow}
  218. onChangeEditAccess={onChangeEditAccess}
  219. listOnly
  220. />
  221. );
  222. }
  223. if (column.key === ResponseKeys.CREATED) {
  224. return (
  225. <DateActionsContainer>
  226. <DateSelected>
  227. {dataRow[ResponseKeys.CREATED] ? (
  228. <DateStatus>
  229. <TimeSince date={dataRow[ResponseKeys.CREATED]} />
  230. </DateStatus>
  231. ) : (
  232. <DateStatus />
  233. )}
  234. </DateSelected>
  235. <ActionsIconWrapper>
  236. <StyledButton
  237. onClick={e => {
  238. e.stopPropagation();
  239. openConfirmModal({
  240. message: t('Are you sure you want to duplicate this dashboard?'),
  241. priority: 'primary',
  242. onConfirm: () => handleDuplicate(dataRow),
  243. });
  244. }}
  245. aria-label={t('Duplicate Dashboard')}
  246. data-test-id={'dashboard-duplicate'}
  247. icon={<IconCopy />}
  248. size="sm"
  249. />
  250. <StyledButton
  251. onClick={e => {
  252. e.stopPropagation();
  253. openConfirmModal({
  254. message: t('Are you sure you want to delete this dashboard?'),
  255. priority: 'danger',
  256. onConfirm: () => handleDelete(dataRow),
  257. });
  258. }}
  259. aria-label={t('Delete Dashboard')}
  260. data-test-id={'dashboard-delete'}
  261. icon={<IconDelete />}
  262. size="sm"
  263. disabled={dashboards && dashboards.length <= 1}
  264. />
  265. </ActionsIconWrapper>
  266. </DateActionsContainer>
  267. );
  268. }
  269. return <span>{dataRow[column.key]}</span>;
  270. };
  271. return (
  272. <GridEditable
  273. data={dashboards ?? []}
  274. // necessary for edit access dropdown
  275. bodyStyle={{overflow: 'visible'}}
  276. columnOrder={columnOrder}
  277. columnSortBy={[]}
  278. grid={{
  279. renderBodyCell,
  280. renderHeadCell: column => {
  281. if (column.key === ResponseKeys.FAVORITE) {
  282. return (
  283. <Feature features="dashboards-favourite">
  284. <StyledIconStar
  285. color="yellow300"
  286. isSolid
  287. aria-label={t('Favorite Column')}
  288. />
  289. </Feature>
  290. );
  291. }
  292. return column.name;
  293. },
  294. }}
  295. isLoading={isLoading}
  296. emptyMessage={
  297. <EmptyStateWarning>
  298. <p>{t('Sorry, no Dashboards match your filters.')}</p>
  299. </EmptyStateWarning>
  300. }
  301. />
  302. );
  303. }
  304. export default withApi(DashboardTable);
  305. const DateSelected = styled('div')`
  306. font-size: ${p => p.theme.fontSizeMedium};
  307. display: grid;
  308. grid-column-gap: ${space(1)};
  309. color: ${p => p.theme.textColor};
  310. ${p => p.theme.overflowEllipsis};
  311. `;
  312. const DateStatus = styled('span')`
  313. color: ${p => p.theme.textColor};
  314. padding-left: ${space(1)};
  315. `;
  316. const DateActionsContainer = styled('div')`
  317. display: flex;
  318. gap: ${space(4)};
  319. justify-content: space-between;
  320. align-items: center;
  321. `;
  322. const ActionsIconWrapper = styled('div')`
  323. display: flex;
  324. `;
  325. const StyledButton = styled(Button)`
  326. border: none;
  327. box-shadow: none;
  328. `;
  329. const StyledFavoriteButton = styled(Button)`
  330. padding: 0;
  331. width: 16px;
  332. border: 3px solid transparent;
  333. `;
  334. const StyledIconStar = styled(IconStar)`
  335. margin-left: ${space(0.5)};
  336. `;