react-router#useHistory TypeScript Examples
The following examples show how to use
react-router#useHistory.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From tailchat with GNU General Public License v3.0 | 7 votes |
/**
* 导航到特定视图
*/
export function useNavToView() {
const history = useHistory();
const navToView = useCallback(
(pathname: string) => {
// 携带上下文切换路由
history.push({
...history.location,
pathname,
});
},
[history]
);
return navToView;
}
Example #2
Source File: AppContext.tsx From one-platform with MIT License | 6 votes |
export default function AppContextProvider ( props: any ) {
const { appId } = useParams<RouteParams>();
const router = useHistory();
const location = useLocation();
const { app, loading, setApp: setOriginalApp } = useAppAPI(appId);
const setApp = (newAppId: string) => {
const newPath = location.pathname.replace( appId, newAppId ) + location.search + location.hash;
router.push( newPath );
}
const forceRefreshApp = ( newApp: App ) => {
setOriginalApp( { ...app, ...newApp} );
}
return (
<AppContext.Provider value={ { appId, app, loading, setApp, forceRefreshApp }}>
{props.children}
</AppContext.Provider>
)
}
Example #3
Source File: Appbar.tsx From DamnVulnerableCryptoApp with MIT License | 6 votes |
Appbar = () => {
const classes = useStyles();
const history = useHistory();
const onLogoClicked = () => {
history.push("/");
};
const onBackClicked = () => {
history.goBack();
};
const isHomePage = () => {
return history.location.pathname === "/";
};
return (
<AppBar position="sticky" className={classes.appbar}>
<Toolbar className={classes.toolbar}>
<Box className={classes.menuLeft}>
<IconButton edge="start" disabled={isHomePage()} onClick={onBackClicked} className={classes.menuButton} color="inherit" aria-label="menu">
<ArrowBackIcon />
</IconButton>
<img className={classes.menuLogo} src={LogoMenu} onClick={onLogoClicked} alt="DamnVulnerableCryptoApp Logo" />
</Box>
<Box display="flex">
<Link to={"/docs/crypto"} className={classes.docsLink}>Docs</Link>
<Progress />
</Box>
</Toolbar>
<Loading />
</AppBar>
);
}
Example #4
Source File: index.tsx From taskcafe with MIT License | 6 votes |
UsersConfirm = () => {
const history = useHistory();
const location = useLocation();
const params = QueryString.parse(location.search);
const [hasFailed, setFailed] = useState(false);
const { setUser } = useCurrentUser();
useEffect(() => {
fetch('/auth/confirm', {
method: 'POST',
body: JSON.stringify({
confirmToken: params.confirmToken,
}),
})
.then(async (x) => {
const { status } = x;
if (status === 200) {
const response = await x.json();
const { userID } = response;
setUser(userID);
history.push('/');
} else {
setFailed(true);
}
})
.catch(() => {
setFailed(false);
});
}, []);
return (
<Container>
<LoginWrapper>
<Confirm hasConfirmToken={params.confirmToken !== undefined} hasFailed={hasFailed} />
</LoginWrapper>
</Container>
);
}
Example #5
Source File: Preview.tsx From dnde with GNU General Public License v3.0 | 6 votes |
NewItem = () => {
const history = useHistory();
const { path } = useRouteMatch();
const onClick = () => {
history.push(`${path}/template/new`);
};
return (
<PreviewContainer>
<div className="newTemplate">
<PlusOutlined style={{ fontSize: '40px' }} />
</div>
<div className="hoverItem alwaysActive">
<div className="content">
<Button onClick={onClick} size="large" type="primary" className="btn-choose">
New Template
</Button>
</div>
</div>
<div>
<img src={newTemplate} alt="img new template" />
</div>
</PreviewContainer>
);
}
Example #6
Source File: index.tsx From xiaobi with MIT License | 6 votes |
Notify: React.FC = () => {
const history = useHistory();
const [times, setTimes] = useState(0);
const { data } = useLoop({
fn: () => sendMessage({ command: CMDS.CMD_LOCALNOTICE }),
updated: [times],
delay: 5000,
});
const update = () => setTimes(times + 1);
const goHome = () => history.push({ pathname: StaticRoutes.Home });
const renderBlockJSX = () => {
if (data?.length) {
return (data as NoticeBlockType[]).map((d) => <CoinBlock {...d} key={`${d.id}_${d.market}`} update={update} />);
}
return (
<NothingUI>
<i className='icon iconfont iconzanwutongzhi' />
<div className='btn' onClick={goHome}>
<i className='iconfont iconweibiaoti-1_huaban1' />
创建提醒
</div>
<p className='desc'>当前暂无提醒,榜单列表开启快捷模式可快捷添加通知</p>
</NothingUI>
);
};
return <WrapperUI>{renderBlockJSX()}</WrapperUI>;
}
Example #7
Source File: WebApplicationNavigatorProvider.tsx From legend-studio with Apache License 2.0 | 6 votes |
WebApplicationNavigatorProvider: React.FC<{
children: React.ReactNode;
}> = ({ children }) => {
const history = useHistory() as History;
const navigator = useLocalObservable(
() => new WebApplicationNavigator(history),
);
return (
<WebApplicationNavigatorContext.Provider value={navigator}>
{children}
</WebApplicationNavigatorContext.Provider>
);
}
Example #8
Source File: SSOHeader.tsx From frontegg-react with MIT License | 6 votes |
SSOHeader = (props: PageHeaderProps & HideOption) => {
const rootPath = checkRootPath('SSO.Header must be rendered inside a SSO.Page component');
const history = useHistory();
const { t } = useT();
if (props.hide) {
return null;
}
let onBackButtonPressed;
if (location.pathname !== rootPath) {
onBackButtonPressed = () => history.replace(rootPath!);
}
return (
<PageHeader
title={t('auth.sso.title')}
subTitle={t('auth.sso.subtitle')}
onBackButtonClick={onBackButtonPressed}
{...props}
/>
);
}
Example #9
Source File: ReactForm.tsx From Hybooru with MIT License | 6 votes |
export default function ReactForm({ action, ...props }: React.FormHTMLAttributes<HTMLFormElement>) {
const history = useHistory();
const onSubmit = useCallback<React.FormEventHandler<HTMLFormElement>>(ev => {
ev.preventDefault();
const formData = new FormData(ev.currentTarget);
const search = new URLSearchParams(formData as any).toString();
history.push(`${action}${search ? `?${search}` : ""}`);
}, [action, history]);
return <form action={action} {...props} onSubmit={onSubmit} />;
}
Example #10
Source File: NoStreamsSelectedMessage.tsx From jitsu with MIT License | 6 votes |
NoStreamsSelectedMessage: React.FC<Props> = ({ editSourceLink }) => {
const history = useHistory()
return (
<div className={`flex flex-col`}>
<span className="mb-1">
Can't perform sync because no data streams were selected for this source. Please, select at least one stream in
the <b>Streams</b> section of source configuration.
</span>
{editSourceLink && (
<Button
className="self-center"
onClick={() => {
history.push(editSourceLink)
}}
>
Edit Source
</Button>
)}
</div>
)
}
Example #11
Source File: index.tsx From bob-extension with MIT License | 6 votes |
export function DomainRow(props: {name: string}): ReactElement {
const domain = useDomainByName(props.name);
const network = Network.get(networkType);
const history = useHistory();
if (!domain) return <></>;
const expiry = heightToMoment(domain.renewal + network.names.renewalWindow).format('YYYY-MM-DD');
return (
<div
className="domain"
onClick={() => history.push(`/domains/${props.name}`)}
>
<div className="domain__info">
<div className="domain__info__name">
<Name name={domain.name} />
{
['REGISTER', 'FINALIZE', 'RENEW', 'UPDATE', 'TRANSFER'].includes(domain?.ownerCovenantType || '') && (
<div className="domain__info__name__status">
Registered
</div>
)
}
</div>
<div className="domain__info__expiry">
{`Expired on ${expiry}`}
</div>
</div>
<div className="domain__actions">
<div className="domain__actions__action">
</div>
</div>
</div>
);
}
Example #12
Source File: useTracking.ts From ledokku with MIT License | 6 votes |
useTracking = () => {
const siteId = 'BOXHWTSC';
const { listen } = useHistory();
useEffect(() => {
if (!config.telemetryDisabled) {
Fathom.load(siteId);
}
const unlisten = listen((location) => {
// Only track on production
if (config.environment !== 'production') {
return;
}
Fathom.trackPageview({ url: location.pathname });
});
return unlisten;
}, [listen]);
}
Example #13
Source File: ConnectedAppsPageContent.tsx From disco-cube-admin with MIT License | 6 votes |
ConnectedAppsPageContent: React.FC<Props> = ({}) => {
const history = useHistory();
const runningApp = useStore(runningAppStore);
const command = useStore(appsCommandStore);
return (
<AppsPageContent
onOpenPage={page => history.push(`/apps${page}`)}
runningAppName={runningApp?.name}
onStopApp={() => sendAppCommand(StopAppCommand({}))}
command={command?.kind}
onCancelCommand={() => cancelAppCommand({})}
/>
);
}
Example #14
Source File: useQuickSwitcherActionContext.tsx From tailchat with GNU General Public License v3.0 | 6 votes |
/**
* 快速切换操作上下文信息
*/
export function useQuickSwitcherActionContext(): QuickActionContext {
const history = useHistory();
return {
navigate: (url) => {
history.push(url);
},
};
}
Example #15
Source File: index.tsx From fe-v5 with Apache License 2.0 | 6 votes |
NotFound: React.FC = () => {
const history = useHistory();
return (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
<Result
title='404'
subTitle='你访问的页面不存在!'
extra={
<Button type='primary' onClick={() => history.replace('/')}>
回到首页
</Button>
}
/>
</div>
);
}
Example #16
Source File: App.tsx From Riakuto-StartingReact-ja3.1 with Apache License 2.0 | 6 votes |
App: VFC = () => {
const { hash, pathname } = useLocation();
const { action } = useHistory();
useEffect(() => {
if (!hash || action !== 'POP') {
window.scrollTo(0, 0);
}
}, [action, hash, pathname]);
return (
<div className="container">
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/characters" component={Characters} />
<Redirect to="/" />
</Switch>
</div>
);
}
Example #17
Source File: useRecycleViz.ts From datart with Apache License 2.0 | 6 votes |
useRecycleViz = (orgId: string, vizId: string, type: VizType) => {
const dispatch = useDispatch();
const history = useHistory();
const tg = useI18NPrefix('global');
const redirect = useCallback(
tabKey => {
if (tabKey) {
history.push(`/organizations/${orgId}/vizs/${tabKey}`);
} else {
history.push(`/organizations/${orgId}/vizs`);
}
},
[history, orgId],
);
const recycleViz = useCallback(() => {
dispatch(
deleteViz({
params: { id: vizId, archive: true },
type: type,
resolve: () => {
message.success(tg('operation.archiveSuccess'));
dispatch(removeTab({ id: vizId, resolve: redirect }));
},
}),
);
}, [dispatch, vizId, type, tg, redirect]);
return recycleViz;
}
Example #18
Source File: NoteView.tsx From joplin-utils with MIT License | 6 votes |
NoteView: React.FC = () => {
const history = useHistory()
const { id } = useParams<{ id: string }>()
const noteState = useAsync(async () => {
const settings = await getSettings()
if (!settings) {
history.push('/')
return
}
noteViewState.settings = settings
config.token = settings.token
config.port = settings.port
const note = await noteApi.get(id, ['id', 'title', 'body'])
document.title = JoplinNoteUtil.trimTitleStart(note.title)
const resourceList = await noteApi.resourcesById(id)
return {
...note,
resourceList,
} as RenderNote
})
async function onClick() {
await noteActionApi.openAndWatch(id)
}
return (
<div className={css.noteView}>
<button onClick={onClick} className={css.control}>
在编辑器中打开
</button>
<div>{noteState.value && <MarkdownView note={noteState.value} />}</div>
</div>
)
}
Example #19
Source File: UserMenu.tsx From nft-market with MIT License | 6 votes |
UserMenu = () => {
const { user, isAuthenticated } = useAppState()
const history = useHistory()
return (
<Flex sx={{ ml: 'auto', justifySelf: 'flex-end' }}>
{isAuthenticated && user && (
<>
<Box sx={{ display: ['none', 'block'] }}>
<Heading sx={{ p: 0, color: 'white' }} as="h4">
{toShort(user.address)}
</Heading>
<Heading sx={{ p: 0, mt: 1, textAlign: 'right', color: 'white' }} as="h5">
{EtherSymbol}
{user.balance}
</Heading>
</Box>
<Box
onClick={() => {
history.push('/profile')
}}
sx={{
cursor: 'pointer',
ml: [0, 3],
height: 30,
width: 30,
borderRadius: '100%',
}}
>
<Identicon size={30} address={user.address} />
</Box>
</>
)}
</Flex>
)
}
Example #20
Source File: BackButton.tsx From twilio-voice-notification-app with Apache License 2.0 | 6 votes |
BackButton: React.FC<BackButtonProps> = ({ prevUrl = '' }) => {
const history = useHistory();
const goBack = useCallback(
(location: string) => {
location && history.push(location);
},
[history]
);
return (
<>
{prevUrl && (
<Button
variant="outlined"
color="primary"
style={{ marginRight: '15px' }}
onClick={() => goBack(prevUrl)}
>
Back
</Button>
)}
</>
);
}
Example #21
Source File: Landing.tsx From waifusion-site with MIT License | 6 votes |
Landing: React.FC = () => {
const [t] = useTranslation();
const history = useHistory();
const globals = useSelector(selectGlobalsData);
const isEth = useSelector(selectIsEth);
return (
<StyledLanding>
<Content>
<Header text={t("name")} />
<SubHeader>{t("tagline")}</SubHeader>
<Image src={landing} />
<Confetti />
<CardContainer>
{isEth && (
<Card
text={t("description")}
buttonText={t("buttons.tradeWaifus")}
buttonAction={() =>
(window as any).open(globals.waifuTradeLink, "_blank").focus()
}
/>
)}
{!isEth && (
<Card
text={t("description")}
buttonText={t("buttons.getWaifus")}
buttonAction={() => history.push(ROUTES.DUNGEON)}
secondButtonText={t("buttons.tradeWaifus")}
secondButtonAction={() => {
(window as any).open(globals.waifuTradeLink, "_blank").focus();
}}
/>
)}
</CardContainer>
</Content>
</StyledLanding>
);
}
Example #22
Source File: index.tsx From marina with MIT License | 6 votes |
SelectAction: React.FC = () => {
const history = useHistory();
const handleClickRestore = () => history.push(RESTORE_VAULT_ROUTE);
const handleClickCreate = () => history.push(INITIALIZE_CREATE_PASSWORD_ROUTE);
return (
<div className="bg-primary h-screen">
<div
className="justify-items-center h-5/6 grid w-screen bg-bottom bg-no-repeat bg-cover"
style={{
backgroundImage: "url('/assets/images/fullscreen/bg-wave-top.svg')",
}}
>
<h1 className="self-center text-4xl font-medium">What do you want to do?</h1>
<div className="grid grid-flow-row grid-cols-2 gap-12">
<div className="rounded-3xl w-52 h-52 flex flex-col justify-around object-contain pt-10 pb-6 pl-6 pr-6 text-center bg-white">
<h2 className="text-xl font-normal">{'Restore a wallet'}</h2>
<img className="w-16 h-16 m-auto" src="/assets/images/save.png" alt="save" />
<Button className="text-md w-40 mx-auto" onClick={handleClickRestore}>
{'Restore'}
</Button>
</div>
<div className="rounded-3xl w-52 h-52 flex flex-col justify-around object-contain pt-10 pb-6 pl-6 pr-6 text-center bg-white">
<h2 className="text-xl font-normal">{'New wallet'}</h2>
<img className="w-16 h-16 m-auto" src="/assets/images/plus.png" alt="plus" />
<Button className="text-md w-40 mx-auto" onClick={handleClickCreate}>
{'Create'}
</Button>
</div>
</div>
</div>
</div>
);
}
Example #23
Source File: index.tsx From electron with MIT License | 6 votes |
Wrap: React.FC = () => {
const history = useHistory();
return (
<Layout>
<div className="ui-h-100 flex just-center align-center">
<Result
icon={<SmileOutlined />}
title="Hello Word!"
extra={
<React.Fragment>
<Button type="primary" onClick={() => {}}>
欢迎您!
</Button>
<Button
type="primary"
onClick={() => {
history.push('/');
}}
>
返回首页
</Button>
<Button
type="primary"
onClick={() => {
history.push('/settings');
}}
>
去设置
</Button>
</React.Fragment>
}
/>
</div>
</Layout>
);
}
Example #24
Source File: index.tsx From dxvote with GNU Affero General Public License v3.0 | 5 votes |
Filter = () => {
const { guild_id: guildId } =
useParams<{ chain_name?: string; guild_id?: string }>();
const [viewFilter, setViewFilter] = useState(false);
const { totalFilters } = useFilter();
const history = useHistory();
const location = useLocation();
const { account } = useWeb3React();
const { data: votingPower } = useVotingPowerOf({
contractAddress: guildId,
userAddress: account,
});
const { data: guildConfig } = useGuildConfig(guildId);
const isProposalCreationAllowed = useMemo(() => {
if (!guildConfig || !votingPower) {
return false;
}
if (votingPower.gte(guildConfig.votingPowerForProposalCreation)) {
return true;
}
return false;
}, [votingPower, guildConfig]);
const [openSearchBar, setOpenSearchBar] = useState(false);
return (
<FilterContainer>
<FilterRow>
{isMobile && !isProposalCreationAllowed && (
<FilterButton
onClick={() => setViewFilter(!viewFilter)}
active={viewFilter || totalFilters > 0}
>
Filter
{totalFilters > 0 && <FilterBadge>{totalFilters}</FilterBadge>}
</FilterButton>
)}
{isDesktop && <FilterMenu />}
<ButtonContainer>
<StyledIconButton
variant="secondary"
padding="0.4rem"
onClick={() => setOpenSearchBar(!openSearchBar)}
>
<AiOutlineSearch size={20} />
</StyledIconButton>
{isProposalCreationAllowed && (
<Button
variant="secondary"
onClick={() => history.push(location.pathname + '/proposalType')}
data-testid="create-proposal-button"
>
Create Proposal
</Button>
)}
</ButtonContainer>
</FilterRow>
{isMobile && viewFilter && <FilterMenu />}
{openSearchBar ? (
<StyledInputWrapper>
<Input
icon={<AiOutlineSearch size={24} />}
placeholder="Search title, ENS, address"
/>
</StyledInputWrapper>
) : null}
</FilterContainer>
);
}
Example #25
Source File: Challenge.tsx From DamnVulnerableCryptoApp with MIT License | 5 votes |
Challenge = (props: IChallengeContainerProps) => {
const [flag, _setFlag] = useState("");
const [warning, setWarning] = useState("");
const { setChallengesDone } = useContext(LayoutContext);
const history = useHistory();
const challengeData = props.obj || { description: "", explanation: "", name: "", objective: "", url: "" };
const Component = props.obj.component;
const setFlag = (flg: string) => {
if (validFlag(flg)) {
_setFlag(flg);
ProgressService.updateProgress(props.obj.url, flg);
}
setChallengesDone(ProgressService.done());
};
const resetChallenge = () => {
_setFlag("");
ProgressService.updateProgress(props.obj.url, "");
setChallengesDone(ProgressService.done());
};
const onGoToDocsClicked = (path: string) => {
return () => history.push(path);
};
const displayWarning = () => {
return (
<Box>
<AppBar position="static" className={classes.warningTitle}>
<Typography variant="h6">Warning</Typography>
</AppBar>
<Paper role="tabpanel" className={classes.warning}>
{warning.split("\n").map((l, i) => <Typography key={i}>{l}</Typography>)}
</Paper>
</Box>
);
};
useEffect(() => {
const f = ProgressService.getFoundFlag(props.obj.url);
setFlag(f);
}, []);
const classes = useStyles();
return (
<Grid container spacing={3}>
<Grid item md={8}>
<Paper className={classes.mainContainer}>
<Typography variant="h4" gutterBottom className={classes.title}> {challengeData.name}</Typography>
<Component flag={flag} setFlag={setFlag} setWarning={setWarning} />
</Paper>
</Grid>
<Grid item md={4}>
<Flag flag={flag} resetChallenge={resetChallenge} />
{warning ? displayWarning() : ""}
<AppBar position="static" className={classes.documentationTitle}>
<Typography variant="h6">Docs</Typography>
</AppBar>
<Paper role="tabpanel" className={classes.documentation}>
<Typography>If you are having trouble with this challenge take a look at our documentation <Link to={"docs" + props.obj.url}>here</Link> </Typography>
</Paper>
</Grid>
</Grid>
);
}
Example #26
Source File: NativesPage.tsx From GTAV-NativeDB with MIT License | 5 votes |
function NativeInfoDrawer() {
const { native: nativeHash } = useParams<{ native?: string }>()
const history = useHistory()
const theme = useTheme()
const handleClose = useCallback(() => {
history.replace(`/natives${history.location.search}`)
}, [history])
return (
<SwipeableDrawer
anchor="bottom"
open={!!nativeHash}
onOpen={() => { }}
onClose={handleClose}
PaperProps={{
sx: {
height: `calc(100vh - 5px)`,
borderRadius: `${theme.shape.borderRadius}px ${theme.shape.borderRadius}px 0px 0px`
}
}}
components={{
Root: 'section'
}}
>
<Paper
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: '0px',
position: 'sticky',
top: 0,
p: 1,
backdropFilter: 'blur(20px)',
backgroundColor: alpha(theme.palette.background.default, 0.6),
...(theme.palette.mode === 'dark' && {
backgroundImage: `linear-gradient(${alpha(
'#fff',
getOverlayAlpha(4),
)}, ${alpha('#fff', getOverlayAlpha(4))})`,
}),
zIndex: 1
}}
>
<Box sx={{ flexGrow: 1 }} />
<Typography component="h1" variant="h6" align="center">
Native Details
</Typography>
<Box sx={{ flexGrow: 1 }} />
<IconButton onClick={handleClose}>
<CloseIcon />
</IconButton>
</Paper>
<NativeInfo />
</SwipeableDrawer>
)
}
Example #27
Source File: index.tsx From taskcafe with MIT License | 5 votes |
Auth = () => {
const [invalidLoginAttempt, setInvalidLoginAttempt] = useState(0);
const history = useHistory();
const location = useLocation<{ redirect: string } | undefined>();
const { setUser } = useContext(UserContext);
const login = (
data: LoginFormData,
setComplete: (val: boolean) => void,
setError: (name: 'username' | 'password', error: ErrorOption) => void,
) => {
fetch('/auth/login', {
credentials: 'include',
method: 'POST',
body: JSON.stringify({
username: data.username,
password: data.password,
}),
}).then(async (x) => {
if (x.status === 401) {
setInvalidLoginAttempt(invalidLoginAttempt + 1);
setError('username', { type: 'error', message: 'Invalid username' });
setError('password', { type: 'error', message: 'Invalid password' });
setComplete(true);
} else {
const response = await x.json();
const { userID } = response;
setUser(userID);
if (location.state && location.state.redirect) {
history.push(location.state.redirect);
} else {
history.push('/');
}
}
});
};
useEffect(() => {
fetch('/auth/validate', {
method: 'POST',
credentials: 'include',
}).then(async (x) => {
const response = await x.json();
const { valid, userID } = response;
if (valid) {
setUser(userID);
history.replace('/projects');
}
});
}, []);
return (
<Container>
<LoginWrapper>
<Login onSubmit={login} />
</LoginWrapper>
</Container>
);
}
Example #28
Source File: LineElement.tsx From metaflow-ui with Apache License 2.0 | 5 votes |
LineElement: React.FC<LineElementProps> = ({
row,
timeline,
grayed,
isLastAttempt,
duration,
startTimeOfFirstAttempt,
dragging,
paramsString,
}) => {
const { t } = useTranslation();
const { push } = useHistory();
const status = getRowStatus(row);
// Extend visible area little bit to prevent lines seem like going out of bounds. Happens
// in some cases with short end task
const extendAmount = (timeline.visibleEndTime - timeline.visibleStartTime) * 0.01;
const visibleDuration = timeline.visibleEndTime - timeline.visibleStartTime + extendAmount;
const boxStartTime = row.type === 'step' ? row.data.ts_epoch : row.data.started_at;
if (!boxStartTime || status === 'pending') {
return null;
}
// Calculate have much box needs to be pushed from (or to) left
const valueFromLeft =
timeline.sortBy === 'duration'
? ((timeline.startTime -
timeline.visibleStartTime +
(startTimeOfFirstAttempt ? boxStartTime - startTimeOfFirstAttempt : 0)) /
visibleDuration) *
100
: ((boxStartTime - timeline.visibleStartTime) / visibleDuration) * 100;
const width = duration && status !== 'running' ? (duration / visibleDuration) * 100 : 100 - valueFromLeft;
const labelPosition = getLengthLabelPosition(valueFromLeft, width);
return (
<LineElementContainer
style={{ transform: `translateX(${valueFromLeft}%)` }}
dragging={dragging}
data-testid="boxgraphic-container"
>
<BoxGraphic
root={row.type === 'step'}
style={{
width: `${width}%`,
}}
data-testid="boxgraphic"
dragging={dragging}
title={formatDuration(duration) + `${status === 'unknown' ? ` (${t('task.unable-to-find-status')})` : ''}`}
onClick={(e) => {
if (row.type === 'task') {
e.stopPropagation();
e.preventDefault();
push(`${getPathFor.attempt(row.data)}&${paramsString}`);
}
}}
>
{(isLastAttempt || status === 'running') && (
<RowMetricLabel duration={duration} labelPosition={labelPosition} data-testid="boxgraphic-label" />
)}
<BoxGraphicLine grayed={grayed} state={status} isLastAttempt={isLastAttempt} />
<BoxGraphicMarkerStart />
{status !== 'running' && <BoxGraphicMarkerEnd />}
</BoxGraphic>
</LineElementContainer>
);
}
Example #29
Source File: TransactionItem.tsx From End-to-End-Web-Testing-with-Cypress with MIT License | 5 votes |
TransactionItem: React.FC<TransactionProps> = ({ transaction }) => {
const classes = useStyles();
const history = useHistory();
const showTransactionDetail = (transactionId: string) => {
history.push(`/transaction/${transactionId}`);
};
return (
<ListItem
data-test={`transaction-item-${transaction.id}`}
alignItems="flex-start"
onClick={() => showTransactionDetail(transaction.id)}
>
<Paper className={classes.paper} elevation={0}>
<Grid container spacing={2}>
<Grid item>
<ListItemAvatar>
<Badge
overlap="circle"
anchorOrigin={{
vertical: "bottom",
horizontal: "right",
}}
badgeContent={<SmallAvatar src={transaction.receiverAvatar} />}
>
<Avatar src={transaction.senderAvatar} />
</Badge>
</ListItemAvatar>
</Grid>
<Grid item xs={12} sm container>
<Grid item xs container direction="column" spacing={2}>
<Grid item xs>
<TransactionTitle transaction={transaction} />
<Typography variant="body2" color="textSecondary" gutterBottom>
{transaction.description}
</Typography>
<Grid
container
direction="row"
justify="flex-start"
alignItems="flex-start"
spacing={1}
className={classes.socialStats}
>
<Grid item>
<LikeIcon className={classes.countIcons} />
</Grid>
<Grid item>
<Typography data-test="transaction-like-count" className={classes.countText}>
{transaction.likes.length}
</Typography>
</Grid>
<Grid item>
<CommentIcon className={classes.countIcons} />
</Grid>
<Grid item>
<Typography data-test="transaction-comment-count" className={classes.countText}>
{transaction.comments.length}
</Typography>
</Grid>
</Grid>
</Grid>
</Grid>
<Grid item>
<TransactionAmount transaction={transaction} />
</Grid>
</Grid>
</Grid>
</Paper>
</ListItem>
);
}