react-router#useHistory JavaScript 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: ProfileJumbotron.js    From video-journal-for-teams-fe with MIT License 6 votes vote down vote up
ProfileCarousel = (props) => {
	let history = useHistory();

	const handleRedirect = () => {
		history.push('/user-dashboard');
	}

	return (
		<>
			<div className="jumbotron">
				<div className="container">
					<span className="breadcrumb" onClick={handleRedirect}><Icon type="left" /> Dashboard</span>
				</div>
			</div>
		</>
	)
}
Example #2
Source File: NotFound.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
NotFound = () => {
  const history = useHistory();
  return (
    <div className={style.notFoundPageContainer}>
      <div className={style.header}>
        <div className={style.titleContainer}>
          <div className={style.logo}>
            <Logo2 />
          </div>
        </div>
      </div>
      <div className={style.content}>
        <NotFound2 />
        <h1>{notFoundMessage.message}</h1>
        <Button
          variant="outlined"
          className={style.restaurantButton}
          onClick={() => changePath("/", history)}
        >
          Back to home
        </Button>
      </div>
    </div>
  );
}
Example #3
Source File: AdminPage.jsx    From simplQ-frontend with GNU General Public License v3.0 6 votes vote down vote up
AdminPage = (props) => {
  const queueId = props.match.params.queueId;
  const queueInfo = useSelector(selectQueueInfo);
  const dispatch = useDispatch();
  const history = useHistory();

  if (queueInfo && queueId === queueInfo?.queueId && isQueueDeleted(queueInfo)) {
    dispatch(setErrorPopupMessage('This queue is deleted.'));
    history.push('/');
  }

  return <AdminPageView queueId={queueId} />;
}
Example #4
Source File: promo-code-edit.js    From horondi_admin with MIT License 6 votes vote down vote up
function PromoCodeEdit() {
  const { id } = useParams();
  const history = useHistory();
  const dispatch = useDispatch();

  const { loading, error, data } = useQuery(getPromoCodeById, {
    variables: { id },
    fetchPolicy: 'no-cache'
  });

  const onCompletedHandler = () => {
    dispatch(showSuccessSnackbar('Успішно змінено'));
  };

  const [updatePromoCodeHandler] = useMutation(updatePromoCode, {
    onCompleted: onCompletedHandler
  });

  const pathToPromoCodesPage = config.routes.pathToPromoCodes;

  const goToPromoPage = () => {
    history.push(pathToPromoCodesPage);
  };

  if (loading || error) {
    return <LoadingBar />;
  }

  return (
    <PromoCodeForm
      initialState={data.getPromoCodeById}
      promoValidationSchema={promoValidationSchema}
      pathToPromoCodesPage={pathToPromoCodesPage}
      addPromoCodeHandler={updatePromoCodeHandler}
      goToPromoPage={goToPromoPage}
    />
  );
}
Example #5
Source File: use-product-filters.spec.js    From horondi_client_fe with MIT License 6 votes vote down vote up
describe('use-product-filters tests', () => {
  it('should handleFilterChange work', () => {
    const { result } = renderHook(() => useProductFilters(mockedFilterParams, mockedFilters));

    expect(useLocation).toBeCalled();
    expect(useTranslation).toBeCalled();
    expect(useHistory).toBeCalled();

    const { filterHandler } = result.current.categories;

    act(() => {
      filterHandler(mockedEvent, mockedQueryName, categoriesList);
    });
    expect(spySearchParamsGet).toBeCalled();
    expect(spySearchParamsSet).toBeCalled();
  });
});
Example #6
Source File: Callback.js    From create-magic-app with MIT License 6 votes vote down vote up
export default function Callback() {
  const history = useHistory();

  useEffect(() => {
    // On mount, we try to login with a Magic credential in the URL query.
    magic.auth.loginWithCredential().finally(() => {
      history.push("/");
    });
  }, []);

  return <Loading />;
}
Example #7
Source File: hooks.js    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useRedirectToThread(courseId) {
  const dispatch = useDispatch();
  const redirectToThread = useSelector(
    (state) => state.threads.redirectToThread,
  );
  const history = useHistory();
  const location = useLocation();

  return useEffect(() => {
    // After posting a new thread we'd like to redirect users to it, the topic and post id are temporarily
    // stored in redirectToThread
    if (redirectToThread) {
      dispatch(clearRedirect());
      const newLocation = discussionsPath(Routes.COMMENTS.PAGES['my-posts'], {
        courseId,
        postId: redirectToThread.threadId,
      })(location);
      history.push(newLocation);
    }
  }, [redirectToThread]);
}
Example #8
Source File: SiderMenu.jsx    From one-wallet with Apache License 2.0 6 votes vote down vote up
DeskstopSiderMenu = ({ action, nav, ...args }) => {
  const history = useHistory()

  return (
    <Layout.Sider collapsed={false} {...args} theme='dark'>
      {/* <Image src='/assets/harmony.svg' /> */}
      <Row justify='center'>
        <SiderLink href='https://harmony.one/'>
          <Image preview={false} src={HarmonyLogo} style={{ cursor: 'pointer', padding: 32 }} onClick={() => history.push('/')} />
        </SiderLink>
      </Row>

      <Row justify='center' style={{ marginBottom: 24 }}><SiderLink style={{ color: 'white' }} href='https://github.com/polymorpher/one-wallet'>{config.appName} {config.version}</SiderLink></Row>

      <StatsInfo />

      <Menu theme='dark' mode='inline' onClick={nav} selectedKeys={[action]}>
        <Menu.Item key='create' icon={<PlusCircleOutlined />}>Create</Menu.Item>
        <Menu.Item key='wallets' icon={<UnorderedListOutlined />}>Wallets</Menu.Item>
        <Menu.Item key='restore' icon={<HistoryOutlined />}>Restore</Menu.Item>
      </Menu>
      <LineDivider />
      <Menu theme='dark' mode='inline' selectable={false}>
        <Menu.Item key='pro' icon={<DollarOutlined />}><SiderLink style={{ color: null }} href='https://modulo.so'>Pro Version</SiderLink></Menu.Item>
        <Menu.Item key='bug' icon={<GithubOutlined />}><SiderLink style={{ color: null }} href='https://github.com/polymorpher/one-wallet/issues'>Bug Report</SiderLink></Menu.Item>
        <Menu.Item key='audit' icon={<AuditOutlined />}><SiderLink style={{ color: null }} href='https://github.com/polymorpher/one-wallet/tree/master/audits'>Audits</SiderLink></Menu.Item>
        <Menu.Item key='wiki' icon={<InfoCircleOutlined />}><SiderLink style={{ color: null }} href='https://github.com/polymorpher/one-wallet/wiki'>Wiki</SiderLink></Menu.Item>
      </Menu>
      <LineDivider />
      <Menu theme='dark' mode='inline' onClick={nav} selectedKeys={[action]}>
        <Menu.Item key='tools' icon={<ToolOutlined />}>Tools</Menu.Item>
      </Menu>
    </Layout.Sider>
  )
}
Example #9
Source File: Error404Page.jsx    From Socialgram with Apache License 2.0 6 votes vote down vote up
Error404 = () => {
  const history = useHistory();

  return (
    <div
      className="d-flex justify-content-center flex-column mx-auto aligm-items-center"
      style={{ height: "60vh" }}
    >
      <img src={Error} alt="" style={{ height: "50vh" }} />
      <h1>Oops ! Wrong Link</h1>
      <button
        onClick={() => history.push("/")}
        className="btn btn-primary mt-4"
      >
        Go home
      </button>
    </div>
  );
}
Example #10
Source File: PlayerList.js    From pretty-derby with GNU General Public License v3.0 6 votes vote down vote up
PlayerList = ({ className, dataList, onClick, sortFlag = false }) => {
  const ua = useUa();
  const history = useHistory();
  const sort = {
    key: "rare",
    data: [
      { value: "3", title: "3星" },
      { value: "2", title: "2星" },
      { value: "1", title: "1星" },
    ],
  };
  return (
    <List
      className={className}
      listKey="players"
      dataList={dataList}
      sort={sortFlag && sort}
      itemRender={(data, setCur) => (
        <div key={`player_${data.id}`} className="w-24 max-w-1/4 p-1">
          <PlayerCard
            className=""
            data={data}
            onClick={() =>
              onClick
                ? onClick(data)
                : ua.isPhone
                ? history.push(`/player-detail/${data.id}`)
                : setCur(data)
            }
          />
        </div>
      )}
      itemClass="w-24 max-w-1/4 "
      detailRender={(data) => <PlayerDetail data={data} isNur={false} />}
      // detailModalSize='regular'
    />
  );
}
Example #11
Source File: CreateDeploymentWizard.js    From akashlytics-deploy with GNU General Public License v3.0 5 votes vote down vote up
export function CreateDeploymentWizard() {
  const classes = useStyles();
  const [selectedTemplate, setSelectedTemplate] = useState(null);
  const [editedManifest, setEditedManifest] = useState(null);
  const { step, dseq } = useParams();

  const history = useHistory();

  useEffect(() => {
    setEditedManifest(selectedTemplate?.content);
  }, [selectedTemplate]);

  function handleBackClick() {
    let route = "";
    switch (step) {
      case "editManifest":
        route = UrlService.createDeploymentStepTemplate();
        break;
      case "acceptBids":
        route = UrlService.createDeploymentStepManifest();
        break;
      default:
        break;
    }

    if (route) {
      history.replace(route);
    } else {
      history.goBack();
    }
  }

  let activeStep = getStepIndexByParam(step);

  function getStepIndexByParam(step) {
    switch (step) {
      case "chooseTemplate":
        return 1;
      case "editManifest":
        return 2;
      case "acceptBids":
        return 3;
      default:
        return 0;
    }
  }

  return (
    <div className={classes.root}>
      <div className={classes.stepContainer}>
        <Box padding="1rem 0 1rem .5rem">
          <IconButton aria-label="back" onClick={handleBackClick} size="medium">
            <ChevronLeftIcon />
          </IconButton>
        </Box>

        <CustomizedSteppers steps={steps} activeStep={activeStep} />
      </div>

      <div>
        {activeStep === 0 && <PrerequisiteList selectedTemplate={selectedTemplate} setSelectedTemplate={(c) => setSelectedTemplate(c)} />}
        {activeStep === 1 && <TemplateList selectedTemplate={selectedTemplate} setSelectedTemplate={(c) => setSelectedTemplate(c)} />}
        {activeStep === 2 && <ManifestEdit selectedTemplate={selectedTemplate} editedManifest={editedManifest} setEditedManifest={setEditedManifest} />}
        {activeStep === 3 && <CreateLease dseq={dseq} editedManifest={editedManifest} />}
      </div>
    </div>
  );
}
Example #12
Source File: MenuList.js    From social-media-strategy-fe with MIT License 5 votes vote down vote up
MenuList = () => {
	const classes = useStyles();
	const location = useLocation();
	const { push } = useHistory();
	const { authService } = useOktaAuth();

	const logout = async () => {
		await authService.logout("/");
	};

	return (
		<>
			<Hidden xsDown>
				<Button className={classes.logoButton} onClick={() => push("/home")}>
					<img className={classes.logo} src={logo} alt="SoMe logo" />
				</Button>
			</Hidden>
			<CreatePost />
			<List aria-label="Menu">
				<ListItem button onClick={() => push("/home")}>
					<ListItemIcon>
						<DashboardIcon
							className={
								location.pathname.includes("/home")
									? classes.selectedIcon
									: classes.icon
							}
						/>
					</ListItemIcon>
					<ListItemText primary="Media Manager" />
				</ListItem>
				<ListItem button onClick={() => push("/analytics")}>
					<ListItemIcon>
						<TrendingUpIcon
							className={
								location.pathname.includes("/analytics")
									? classes.selectedIcon
									: classes.icon
							}
						/>
					</ListItemIcon>
					<ListItemText primary="Analytics" />
				</ListItem>
				<ListItem button onClick={() => push("/connect/twitter")}>
					<ListItemIcon>
						<AccountBoxIcon
							className={
								location.pathname.includes("/connect")
									? classes.selectedIcon
									: classes.icon
							}
						/>
					</ListItemIcon>
					<ListItemText primary="Accounts" />
				</ListItem>
			</List>
			<List>
				<ListItem button onClick={logout}>
					<ListItemIcon>
						<ExitToAppIcon color="primary" />
					</ListItemIcon>
					<ListItemText primary="Logout" />
				</ListItem>
			</List>
		</>
	);
}
Example #13
Source File: newProject.js    From create-sas-app with Apache License 2.0 5 votes vote down vote up
NewProject = (props) => {
	const edit = props.edit || null
	const history = useHistory();

	const dispatch = useDispatch();

	const {error, errorMessage, override} = useSelector(state => state.newProject);
	const [project, setProject] = useState({
		name: '',
		description: ''
	});
	const {projectContent} = useSelector(state => state.project);
	// const [error, setError] = useState(false);
	const user = useSelector(state => state.home.userData)

	const submit = () => {
		dispatch({type: ActionTypes.CLEAR})
		if (props.edit === null) {
			const forSubmit = {
				name: project.name,
				createdOn: new Date(),
				createdBy: user.name,
				description: project.description
			}

			const res = createNewProject(dispatch, project.name, forSubmit, override);

			res.then((res) => {
				console.log('response', res)
				props.close();
				history.push('/project/' + res);
			})
		} else {
			const newProject = {
				...projectContent,
				name: project.name,
				description: project.description
			}
			dispatch({
				type: ProjectActons.UPDATE_PROJECT,
				payload: newProject
			})
			props.close();
		}
	}

	useEffect(() => {
		if (props.edit !== null) setProject({...project, name: props.edit});
		else setProject({...project, name: ''})
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [edit])

	return (
		<Modal className={'newProject'} open={props.open}
					 primaryButtonText={`${props.edit !== null ? "Save" : "Add new project" }`} secondaryButtonText="Cancel"
					 onRequestClose={() => {
						 dispatch({type: ActionTypes.CLEAR})
						 props.close();
					 }}
					 onRequestSubmit={submit}
					 modalHeading={`${props.edit !== null ? "Edit project name" : "Add new project" }`}>
			<div className={'spb3'}>
				<TextInput
					id='projectName' labelText="Project name"
					value={project.name}
					onChange={e => setProject({...project, name: e.target.value})}
					invalid={error}
					invalidText={errorMessage}/>
			</div>

			<TextArea
				labelText="Project description"
				value={project.description}

				onChange={e => setProject({...project, description: e.target.value})}/>
		</Modal>
	)
}
Example #14
Source File: MobileNavbar.js    From gophie-web with MIT License 5 votes vote down vote up
MobileNavbar = props => {
  const [mobileSearch, setMobileSearch] = useState(false)
  const location = useLocation()
  console.log(location)
  const history = useHistory()

  return (
    <>
      <Style.MobileSearch
        className={mobileSearch ? 'show-mobile-searchbar' : ''}
      >
        <SearchInput
          searchInput={props.searchInput}
          checkInputKey={props.checkInputKey}
          newSearch={props.newSearch}
          checkKeyOnChange={props.checkKeyOnChange}
        />
      </Style.MobileSearch>
      <Style.MobileNavbar>
        <button
          className={`${
            location.pathname === '/Server1' ? 'active' : ''
          } actions-button`}
          onClick={props.handleServerChange}
          onChange={props.handleServerChange}
          data-value='Server1'
          title='Home'
        >
          {location.pathname === '/music' ? <MovieReel /> : <HomeIcon />}
        </button>

        {location.pathname === '/music' ? null : (
          <button
            className={`${
              location.pathname === '/search' ? 'active' : ''
            } actions-button`}
            title='Search'
            onClick={() => setMobileSearch(!mobileSearch)}
          >
            <SearchIcon />
          </button>
        )}

        <button
          className={`${
            location.pathname === '/music' ? 'active' : ''
          } actions-button`}
          title='Music'
          onClick={() => history.push('/music')}
        >
          <MusicNotes />
        </button>

        <button
          className='actions-button'
          title='Change Theme'
          onClick={props.switchTheme}
        >
          {props.theme === 'dark' ? <SunIcon /> : <MoonIcon />}
        </button>
      </Style.MobileNavbar>
    </>
  )
}
Example #15
Source File: visualizer.js    From Queen with MIT License 5 votes vote down vote up
Visualizer = () => {
  const { apiUrl, standalone } = useContext(AppContext);

  const [surveyUnit, setSurveyUnit] = useState(undefined);
  const [error, setError] = useState(null);
  const [source, setSource] = useState(null);

  const { questionnaireUrl, dataUrl, readonly } = useVisuQuery();
  const {
    surveyUnit: suData,
    questionnaire,
    nomenclatures,
    loadingMessage,
    errorMessage,
  } = useRemoteData(questionnaireUrl, dataUrl);

  const [suggesters, setSuggesters] = useState(null);
  const history = useHistory();

  const createFakeSurveyUnit = surveyUnit => {
    const unit = {
      ...surveyUnit,
      id: '1234',
    };
    surveyUnitIdbService.addOrUpdateSU(unit);
    return unit;
  };

  useEffect(() => {
    if (questionnaireUrl && questionnaire && suData && nomenclatures) {
      const { valid, error: questionnaireError } = checkQuestionnaire(questionnaire);
      if (valid) {
        setSource(questionnaire);
        const suggestersBuilt = buildSuggesterFromNomenclatures(apiUrl)(nomenclatures);
        setSuggesters(suggestersBuilt);
        setSurveyUnit(createFakeSurveyUnit(suData));
      } else {
        setError(questionnaireError);
      }
    }
  }, [questionnaireUrl, questionnaire, suData, apiUrl, nomenclatures]);

  useEffect(() => {
    if (errorMessage) setError(errorMessage);
  }, [errorMessage]);

  const closeAndDownloadData = async () => {
    const data = await surveyUnitIdbService.get('1234');
    downloadDataAsJson(data, 'data');
    history.push('/');
  };

  return (
    <>
      {loadingMessage && <Preloader message={loadingMessage} />}
      {error && <Error message={error} />}
      {questionnaireUrl && source && surveyUnit && suggesters && (
        <Orchestrator
          surveyUnit={surveyUnit}
          source={source}
          suggesters={suggesters}
          standalone={standalone}
          readonly={readonly}
          savingType="COLLECTED"
          preferences={['COLLECTED']}
          features={['VTL']}
          pagination={true}
          missing={true}
          filterDescription={false}
          save={unit => surveyUnitIdbService.addOrUpdateSU(unit)}
          close={closeAndDownloadData}
        />
      )}
      {!questionnaireUrl && <QuestionnaireForm />}
    </>
  );
}
Example #16
Source File: ConfirmationContainer.js    From git-brunching with GNU General Public License v3.0 5 votes vote down vote up
ConfirmationContainer = (props) => {
  const history = useHistory();

  const {
    name,
    phone,
    email,
    notes,
    seats,
    date,
    time,
    addReservation,
    edit,
    mode,
  } = props;

  /**
   * Want to have different requests depending on the mode
   * CREATE: POST request
   * EDIT: PUT request
   * */
  const completeBooking = () => {
    if (mode === "CREATE") {
      addReservation();
    } else {
      edit();
    }
    changePath("/complete", history);
  };


  return (
    <div className={style.bookingDetailsContainer}>
      <div className={style.contentContainer}>
        {/* TODO: Put hard coded text into textHolder */}
        <div className={style.twoContent}>
          <p className={classNames(style.title, style.title1)}>{confirmationMessages.name}</p>
          <p className={classNames(style.value, style.value1)}>{name}</p>
          <p className={classNames(style.title, style.title2)}>{confirmationMessages.email}</p>
          <p className={classNames(style.value, style.value2)}>{email}</p>
        </div>
        <div className={style.twoContent}>
          <p className={classNames(style.title, style.title1)}>{confirmationMessages.phone}</p>
          <p className={classNames(style.value, style.value1)}>{phone}</p>
          <p className={classNames(style.title, style.title2)}>{confirmationMessages.seats}</p>
          <p className={classNames(style.value, style.value2)}>{seats}</p>
        </div>
        <div className={style.twoContent}>
          <p className={classNames(style.title, style.title1)}>{confirmationMessages.date}</p>
          <p className={classNames(style.value, style.value1)}>{`${date}`}</p>
          <p className={classNames(style.title, style.title2)}>{confirmationMessages.time}</p>
          <p className={classNames(style.value, style.value2)}>{`${time}`}</p>
        </div>
        <div className={classNames(style.content, style.notes)}>
          <p className={classNames(style.title, style.title1)}>{confirmationMessages.notes}</p>
          <div className={style.notesContainer}>
            <p className={classNames(style.value, style.value1)}>{notes}</p>
          </div>
        </div>
        <div className={style.buttonHolder}>
          <Button
            variant="outlined"
            className={classNames(landingStyle.primaryButton, style.edit)}
            onClick={() => changePath("/details", history)}
          >
            {confirmationMessages.buttonBackText}
          </Button>
          <Button
            variant="outlined"
            className={classNames(landingStyle.secondaryButton, style.confirm)}
            onClick={completeBooking}
          >
            {confirmationMessages.buttonNextText}
          </Button>
        </div>
      </div>
    </div>
  );
}
Example #17
Source File: CreateJoinForm.jsx    From simplQ-frontend with GNU General Public License v3.0 5 votes vote down vote up
CreateJoinForm = (props) => {
  const [textFieldValue, setTextFieldValue] = useState(props.defaultTextFieldValue);
  const [invalidMsg, setInvalidMsg] = useState('');
  const history = useHistory();
  const createQueue = useCreateQueue();
  const dispatch = useDispatch();

  const handleCreateClick = () => {
    if (!textFieldValue) {
      setInvalidMsg('Line name is required');
      return;
    }
    dispatch(createQueue({ queueName: textFieldValue }));
  };

  const handleJoinClick = () => {
    if (!textFieldValue) setInvalidMsg('Line name is required');
    else {
      history.push(`/j/${textFieldValue}`);
    }
  };

  const handleTextFieldChange = (e) => {
    const queueName = e.target.value;
    if (isQueueNameValid(queueName)) {
      setTextFieldValue(queueName);
      setInvalidMsg('');
    } else {
      setInvalidMsg("Only alphabets, numbers and '-' allowed");
    }
  };

  const handleScanAnyQR = () => {
    history.push('/scanQr');
  };

  return (
    <div data-aos="zoom-in" className={styles['create-join-form']}>
      <div className={styles['input-box']}>
        <InputField
          placeholder="Line Name"
          value={textFieldValue || ''}
          onChange={handleTextFieldChange}
          onKeyPress={(e) => handleEnterPress(e, handleCreateClick)}
          error={invalidMsg.length > 0}
          helperText={invalidMsg}
          autoFocus
        />
      </div>
      <div className={styles['button-group']}>
        <LoadingStatus dependsOn="createQueue">
          <div>
            <StandardButton onClick={handleCreateClick}>Create Line</StandardButton>
          </div>
          <div>
            <StandardButton onClick={handleJoinClick}>Know Your Position</StandardButton>
          </div>
          <div>
            <StandardButton onClick={handleScanAnyQR}>Scan Any QR</StandardButton>
          </div>
        </LoadingStatus>
      </div>
    </div>
  );
}
Example #18
Source File: RouteHandler.js    From Mumble with Apache License 2.0 5 votes vote down vote up
RouteHandler = ({ children }) => {
  const history = useHistory();
  useLocationBlocker(history);
  return <>{children}</>;
}
Example #19
Source File: Missions.jsx    From resilience-app with GNU General Public License v3.0 5 votes vote down vote up
ViewButtons = ({ classes, missionsView }) => {
  const history = useHistory();
  const ordered = [
    {
      view: "inProposed",
      text: "Proposed",
      onClick: () =>
        history.replace({
          search: _.setQueryParam("view", "inProposed"),
        }),
    },
    {
      view: "inPlanning",
      text: "Planning",
      onClick: () =>
        history.replace({
          search: _.setQueryParam("view", "inPlanning"),
        }),
    },
    {
      view: "inProgress",
      text: "In Progress",
      onClick: () =>
        history.replace({
          search: _.setQueryParam("view", "inProgress"),
        }),
    },
    {
      view: "inDone",
      text: "Done",
      onClick: () =>
        history.replace({
          search: _.setQueryParam("view", "inDone"),
        }),
    },
  ];

  return (
    <>
      {ordered.map((conf) => (
        <Grid item xs key={conf.view}>
          <Button
            variant={missionsView === conf.view ? "outlined" : "text"}
            fullWidth={true}
            onClick={conf.onClick}
            classes={{ outlined: classes.outlined }}
            aria-label={conf.text}
          >
            {conf.text}
          </Button>
        </Grid>
      ))}
    </>
  );
}
Example #20
Source File: header-profile.spec.js    From horondi_client_fe with MIT License 5 votes vote down vote up
useHistory.mockReturnValue({
  location: {
    pathname: '/home'
  }
});
Example #21
Source File: Login.js    From create-magic-app with MIT License 5 votes vote down vote up
export default function Login() {
  const [email, setEmail] = useState("");
  const [isLoggingIn, setIsLoggingIn] = useState(false);
  const history = useHistory();

  /**
   * Perform login action via Magic's passwordless flow. Upon successuful
   * completion of the login flow, a user is redirected to the homepage.
   */
  const login = useCallback(async () => {
    setIsLoggingIn(true);

    try {
      await magic.auth.loginWithMagicLink({
        email,
        redirectURI: new URL("/callback", window.location.origin).href,
      });
      history.push("/");
    } catch {
      setIsLoggingIn(false);
    }
  }, [email]);

  /**
   * Saves the value of our email input into component state.
   */
  const handleInputOnChange = useCallback(event => {
    setEmail(event.target.value);
  }, []);

  return (
    <div className="container">
      <h1>Please sign up or login</h1>
      <input
        type="email"
        name="email"
        required="required"
        placeholder="Enter your email"
        onChange={handleInputOnChange}
        disabled={isLoggingIn}
      />
      <button onClick={login} disabled={isLoggingIn}>Send</button>
    </div>
  );
}
Example #22
Source File: CardUrls.js    From FireShort with MIT License 5 votes vote down vote up
export default function CardUrls(props) {
    const history = useHistory();
    const classes = useStyles();

    return (
        <Container className={classes.cardGrid} maxWidth="lg">
            <Grid container spacing={4}>
                {props.shortUrls.map((card) => (
                    <Grid item key={card.id} xs={12} sm={6} md={4}>
                        <Card className={classes.card}>
                            <CardHeader
                                action={
                                    <Tooltip title={"Copy to clipboard"}>
                                        <IconButton color="primary" className={classes.copyButton} onClick={() => { navigator.clipboard.writeText(window.location.origin + "/" + card.data.curl) }}>
                                            <FileCopyOutlinedIcon />
                                        </IconButton>
                                    </Tooltip>
                                }
                                title={
                                    <Tooltip title={card.data.track === true ? "Link Tracking ON" : "Link Tracking OFF"}>
                                        <Badge color={card.data.track === true ? "primary" : "error"} variant="dot">
                                            <Typography>{card.data.curl}</Typography>
                                        </Badge>
                                    </Tooltip>
                                }
                                titleTypographyProps={{
                                    variant: "subtitle1"
                                }}
                            >

                            </CardHeader>
                            <CardContent className={classes.cardContent}>
                                <Box bgcolor="text.primary" color="background.paper" p={2} style={{ overflowX: 'auto', overflowY: 'hidden', whiteSpace: "nowrap" }}>
                                    {card.data.lurl}
                                </Box>
                            </CardContent>
                            <CardActions className={classes.cardActions}>
                                <Tooltip title={"Preview link"}>
                                    <IconButton size="small" color="primary" href={card.data.lurl} target="_blank">
                                        <VisibilityIcon />
                                    </IconButton>
                                </Tooltip>
                                <Tooltip title={"Edit link"}>
                                    <IconButton size="small" onClick={() => props.handleEditShortUrl(card.data.curl)}>
                                        <EditIcon />
                                    </IconButton>
                                </Tooltip>
                                <Tooltip title={"Analytics"}>
                                    <IconButton size="small" disabled={!card.data.track} onClick={() => history.push(`/analytics/${card.data.curl}`)}>
                                        <AnalyticsIcon />
                                    </IconButton>
                                </Tooltip>
                                <Tooltip title={"Delete link"}>
                                    <IconButton size="small" color="secondary" onClick={() => props.handleDeleteShortUrl(card.data.curl)}>
                                        <DeleteForeverIcon />
                                    </IconButton>
                                </Tooltip>
                                <Tooltip title={card.data.hits + " Hits"}>
                                    <IconButton onClick={() => { props.openHits(card.data.curl) }} style={{ cursor: "pointer" }}>
                                        <Badge badgeContent={card.data.hits} color="secondary" max={Infinity} showZero>
                                            <OpenInBrowser />
                                        </Badge>
                                    </IconButton>
                                </Tooltip>
                                <Tooltip title={"Password protect"}>
                                    <IconButton size='small' color='default' onClick={() => props.toggleSecurity(card.data.curl)}>
                                        {card.data.locked ? <LockIcon /> : <LockOpenIcon />}
                                    </IconButton>
                                </Tooltip>
                            </CardActions>
                        </Card>
                    </Grid>
                ))}
            </Grid>
        </Container>
    );
}
Example #23
Source File: LocalImport.jsx    From one-wallet with Apache License 2.0 5 votes vote down vote up
LocalImport = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const wallets = useSelector(state => state.wallet)
  const [fileUploading, setFileUploading] = useState(false)

  const handleImport = async info => {
    if (info.file.status === 'uploading') {
      setFileUploading(true)
    }

    if (info.file.status === 'done') {
      try {
        const data = await getDataFromFile(info.file.originFileObj)
        const { innerTrees, layers, state, address, name } = SimpleWalletExport.decode(new Uint8Array(data))

        // const decoded = LocalExportMessage.decode(new Uint8Array(data))
        const wallet = JSON.parse(state)
        // console.log(ONEUtil.hexView(layers[layers.length - 1]), wallet.root)
        if (!util.isValidWallet(wallet)) {
          message.error('Wallet file has invalid data')
          return
        }
        if (wallets[wallet.address]) {
          message.error('Wallet already exists. Please use the existing one or delete it first.')
          return
        }
        if (!layers) {
          message.error('Wallet file has corrupted data')
          return
        }
        message.info(`Saving wallet ${name} (${util.safeOneAddress(address)})`)
        dispatch(walletActions.updateWallet(wallet))
        const promises = []
        for (const { layers: innerLayers } of innerTrees) {
          const innerRoot = innerLayers[innerLayers.length - 1]
          promises.push(storage.setItem(ONEUtil.hexView(innerRoot), innerLayers))
        }
        promises.push(storage.setItem(ONEUtil.hexView(layers[layers.length - 1]), layers))
        await Promise.all(promises)
        message.success(`Wallet ${wallet.name} (${wallet.address}) is restored!`)
        setTimeout(() => history.push(Paths.showAddress(wallet.address)), 1500)
      } catch (err) {
        message.error(err?.message || 'Unable to parse wallet file')
      } finally {
        setFileUploading(false)
      }
    }
  }

  const beforeUpload = (file) => {
    const filename = file.name.split('.')
    const is1walletExt = filename[filename.length - 1] === '1wallet'

    if (!is1walletExt) {
      message.error('You can only upload 1wallet file')
    }

    return is1walletExt
  }

  return (
    <Upload
      name='walletjson'
      showUploadList={false}
      customRequest={({ onSuccess }) => { onSuccess('ok') }}
      beforeUpload={beforeUpload}
      onChange={handleImport}
    >
      <Button
        type='primary'
        shape='round'
        size='large'
        icon={fileUploading ? <LoadingOutlined /> : <ImportOutlined />}
      >
        Import
      </Button>
    </Upload>
  )
}
Example #24
Source File: SupportList.js    From pretty-derby with GNU General Public License v3.0 5 votes vote down vote up
SupportList = ({ className, dataList, onClick, sortFlag = false, ownList }) => {
  const ua = useUa();
  const history = useHistory();
  const sort = sortFlag
    ? {
        key: "rare",
        data: [
          { value: "SSR", title: "SSR" },
          { value: "SR", title: "SR" },
          { value: "R", title: "R" },
        ],
      }
    : null;
  return (
    <List
      className={className}
      listKey="supports"
      dataList={dataList}
      sort={sort}
      onClick={onClick}
      itemRender={(data, setCur) => (
        <div key={data.id} className="w-24 max-w-1/4 p-1">
          <SupportCard
            className={`${ownList?.length && !ownList?.includes(data.id) && "un-chosen-card"}`}
            data={data}
            onClick={() =>
              onClick
                ? onClick(data)
                : ua.isPhone
                ? history.push(`/support-detail/${data.id}`)
                : setCur(data)
            }
          />
        </div>
      )}
      itemClass={"w-24 max-w-1/4"}
      detailRender={(data) => <SupportDetail data={data} isNur={false} />}
      // detailModalSize='regular'
    />
  );
}
Example #25
Source File: index.js    From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 4 votes vote down vote up
ProjectCard = (props) => {
  const {
    project,
    showDeletePopup,
    handleShow,
    setProjectId,
    setCreateProject,
    teamPermission,
    adminPanel,
  } = props;
  const ImgLoader = () => <img src={loader} alt="" />;
  const organization = useSelector((state) => state.organization);
  const dispatch = useDispatch();
  const history = useHistory();
  const primaryColor = getGlobalColor("--main-primary-color");
  return (
    <div className="main-myproject-card">
      <div>
        {project.thumb_url && (
          <>
            <div
              className="myproject-card-top"
              style={{
                backgroundImage: project.thumb_url.includes("pexels.com")
                  ? `url(${project.thumb_url})`
                  : `url(${global.config.resourceUrl}${project.thumb_url})`,
              }}
            >
              <div className="myproject-card-dropdown">
                {!adminPanel && (
                  <ProjectCardDropdown
                    project={project}
                    showDeletePopup={showDeletePopup}
                    handleShow={handleShow}
                    setProjectId={setProjectId}
                    iconColor="#ffffff"
                    setCreateProject={setCreateProject}
                    teamPermission={teamPermission || {}}
                  />
                )}
              </div>
              {(teamPermission && Object.keys(teamPermission).length
                ? teamPermission?.Team?.includes("team:view-project")
                : organization?.permission?.Project?.includes(
                    "project:view"
                  )) && (
                <Link
                  to={
                    adminPanel
                      ? "#"
                      : `/org/${organization?.currentOrganization?.domain}/project/${project.id}`
                  }
                >
                  <div className="myproject-card-title">
                    <h2>
                      {project.name && project.name.length > 50
                        ? `${project.name.substring(0, 50)}...`
                        : project.name}
                    </h2>
                  </div>
                </Link>
              )}
            </div>
          </>
        )}
      </div>
      <Link
        className="project-description"
        to={
          adminPanel
            ? "#"
            : `/org/${organization?.currentOrganization?.domain}/project/${project.id}`
        }
      >
        <div className="myproject-card-detail">
          <p>
            {project.description && project.description.length > 130
              ? `${project.description.substring(0, 130)} ...`
              : project.description}
          </p>
        </div>
      </Link>
      <div className="updated-date">
        Updated date: {project?.updated_at?.split("T")[0]}
      </div>
      <div className="myproject-card-add-share">
        {(teamPermission && Object.keys(teamPermission).length
          ? teamPermission?.Team?.includes("team:view-project")
          : organization?.permission?.Project?.includes("project:view")) && (
          <button
            type="button"
            // title="view project"
          >
            <Link
              to={`/org/${organization?.currentOrganization?.domain}/project/${project.id}/preview`}
              style={{ textDecoration: "none", color: "#084892" }}
            >
              {/* <img src={viewIcon} alt="" className="mr-3" /> */}
              <svg
                width="24"
                height="32"
                viewBox="0 0 24 32"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                className="mr-3"
              >
                <path
                  d="M0 4C0 1.79086 1.79086 0 4 0H20C22.2091 0 24 1.79086 24 4V28C24 30.2091 22.2091 32 20 32H4C1.79086 32 0 30.2091 0 28V4Z"
                  fill="white"
                />
                <path
                  d="M2.375 16C2.375 16 5.875 9 12 9C18.125 9 21.625 16 21.625 16C21.625 16 18.125 23 12 23C5.875 23 2.375 16 2.375 16Z"
                  stroke={primaryColor}
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path
                  d="M12 18.625C13.4497 18.625 14.625 17.4497 14.625 16C14.625 14.5503 13.4497 13.375 12 13.375C10.5503 13.375 9.375 14.5503 9.375 16C9.375 17.4497 10.5503 18.625 12 18.625Z"
                  stroke={primaryColor}
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>

              <span className="textinButton">Preview</span>
            </Link>
          </button>
        )}
        {(teamPermission && Object.keys(teamPermission).length
          ? teamPermission?.Team?.includes("team:edit-project")
          : organization?.permission?.Project?.includes("project:edit")) &&
          !adminPanel && (
            <button
              type="button"
              onClick={() => {
                dispatch(setSelectedProject(project));
                history.push(
                  `/org/${organization?.currentOrganization?.domain}/project/${project.id}`
                );
              }}
            >
              {/* <img src={editIcon} alt="" className="mr-3" /> */}
              <svg
                width="24"
                height="32"
                viewBox="0 0 24 32"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                className="mr-3"
              >
                <path
                  d="M0 4C0 1.79086 1.79086 0 4 0H20C22.2091 0 24 1.79086 24 4V28C24 30.2091 22.2091 32 20 32H4C1.79086 32 0 30.2091 0 28V4Z"
                  fill="white"
                />
                <path
                  d="M11.0513 8.89767H4.78927C4.31476 8.89767 3.85968 9.08617 3.52415 9.4217C3.18862 9.75723 3.00012 10.2123 3.00012 10.6868V23.2108C3.00012 23.6854 3.18862 24.1404 3.52415 24.476C3.85968 24.8115 4.31476 25 4.78927 25H17.3133C17.7878 25 18.2429 24.8115 18.5784 24.476C18.9139 24.1404 19.1024 23.6854 19.1024 23.2108V16.9488"
                  stroke={primaryColor}
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path
                  d="M17.7605 7.55582C18.1163 7.19993 18.599 7 19.1023 7C19.6056 7 20.0883 7.19993 20.4442 7.55582C20.8001 7.9117 21 8.39438 21 8.89768C21 9.40097 20.8001 9.88365 20.4442 10.2395L11.9457 18.738L8.36743 19.6326L9.262 16.0543L17.7605 7.55582Z"
                  stroke={primaryColor}
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>

              <span className="textinButton">Edit</span>
            </button>
          )}
        {project.shared &&
          !adminPanel &&
          organization?.permission?.Project?.includes("project:share") && (
            <button
              type="button"
              onClick={() => {
                if (window.gapi && window.gapi.sharetoclassroom) {
                  window.gapi.sharetoclassroom.go("croom");
                }
                const protocol = `${window.location.href.split("/")[0]}//`;
                const url = `${protocol}${window.location.host}/project/${project.id}/shared`;
                return SharePreviewPopup(url, project.name);
              }}
            >
              {/* <img src={linkIcon} alt="" className="mr-3" /> */}
              <svg
                width="24"
                height="32"
                viewBox="0 0 24 32"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                className="mr-3"
              >
                <path
                  d="M0 4C0 1.79086 1.79086 0 4 0H20C22.2091 0 24 1.79086 24 4V28C24 30.2091 22.2091 32 20 32H4C1.79086 32 0 30.2091 0 28V4Z"
                  fill="white"
                />
                <path
                  d="M10.1899 16.906C10.5786 17.4262 11.0746 17.8566 11.644 18.168C12.2135 18.4795 12.8433 18.6647 13.4905 18.7111C14.1378 18.7575 14.7875 18.664 15.3955 18.437C16.0035 18.21 16.5557 17.8547 17.0144 17.3953L19.7298 14.6772C20.5541 13.8228 21.0103 12.6785 21 11.4907C20.9897 10.303 20.5137 9.16675 19.6746 8.32683C18.8356 7.48692 17.7005 7.01049 16.5139 7.00017C15.3273 6.98985 14.1842 7.44646 13.3307 8.27165L11.7739 9.82094"
                  stroke={primaryColor}
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path
                  d="M13.8101 15.094C13.4214 14.5738 12.9255 14.1434 12.356 13.832C11.7865 13.5205 11.1567 13.3353 10.5095 13.2889C9.86218 13.2425 9.2125 13.336 8.60449 13.563C7.99648 13.7901 7.44435 14.1453 6.98557 14.6048L4.27025 17.3228C3.44589 18.1772 2.98974 19.3215 3.00005 20.5093C3.01036 21.6971 3.48631 22.8333 4.32538 23.6732C5.16445 24.5131 6.29951 24.9895 7.48609 24.9999C8.67267 25.0102 9.81583 24.5536 10.6694 23.7284L12.2171 22.1791"
                  stroke={primaryColor}
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>

              <span className="textinButton">Shared link</span>
            </button>
          )}
      </div>
    </div>
  );
}
Example #26
Source File: CreateLease.js    From akashlytics-deploy with GNU General Public License v3.0 4 votes vote down vote up
export function CreateLease({ dseq }) {
  const [isSendingManifest, setIsSendingManifest] = useState(false);
  const [isFilteringFavorites, setIsFilteringFavorites] = useState(false);
  const [selectedBids, setSelectedBids] = useState({});
  const [filteredBids, setFilteredBids] = useState([]);
  const [search, setSearch] = useState("");
  const { sendTransaction } = useTransactionModal();
  const { address } = useWallet();
  const { localCert } = useCertificate();
  const { enqueueSnackbar, closeSnackbar } = useSnackbar();
  const history = useHistory();
  const [anchorEl, setAnchorEl] = useState(null);
  const classes = useStyles();
  const [numberOfRequests, setNumberOfRequests] = useState(0);
  const { providers, getProviders } = useAkash();
  const warningRequestsReached = numberOfRequests > WARNING_NUM_OF_BID_REQUESTS;
  const maxRequestsReached = numberOfRequests > MAX_NUM_OF_BID_REQUESTS;
  const { favoriteProviders } = useLocalNotes();
  const { data: bids, isLoading: isLoadingBids } = useBidList(address, dseq, {
    initialData: [],
    refetchInterval: REFRESH_BIDS_INTERVAL,
    onSuccess: () => {
      setNumberOfRequests((prev) => ++prev);
    },
    enabled: !maxRequestsReached
  });
  const { data: deploymentDetail, refetch: getDeploymentDetail } = useDeploymentDetail(address, dseq, { refetchOnMount: false, enabled: false });
  const groupedBids = bids
    .sort((a, b) => a.price.amount - b.price.amount)
    .reduce((a, b) => {
      a[b.gseq] = [...(a[b.gseq] || []), b];
      return a;
    }, {});
  const dseqList = Object.keys(groupedBids);
  const allClosed = bids.length > 0 && bids.every((bid) => bid.state === "closed");

  useEffect(() => {
    getDeploymentDetail();
    getProviders();

    if (favoriteProviders.length > 0) {
      setIsFilteringFavorites(true);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Filter bids by search
  useEffect(() => {
    let fBids = [];
    if ((search || isFilteringFavorites) && providers) {
      bids?.forEach((bid) => {
        let isAdded = false;

        // Filter for search
        if (search) {
          const provider = providers.find((p) => p.owner === bid.provider);
          // Filter by attribute value
          provider?.attributes.forEach((att) => {
            if (att.value?.includes(search)) {
              fBids.push(bid.id);
              isAdded = true;
            }
          });
        }

        // Filter for favorites
        if (!isAdded && isFilteringFavorites) {
          const provider = favoriteProviders.find((p) => p === bid.provider);

          if (provider) {
            fBids.push(bid.id);
          }
        }
      });
    } else {
      fBids = bids?.map((b) => b.id) || [];
    }

    setFilteredBids(fBids);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [search, bids, providers, isFilteringFavorites]);

  const handleBidSelected = (bid) => {
    setSelectedBids({ ...selectedBids, [bid.gseq]: bid });
  };

  async function sendManifest(providerInfo, manifest) {
    try {
      const response = await sendManifestToProvider(providerInfo, manifest, dseq, localCert);

      return response;
    } catch (err) {
      enqueueSnackbar(<ManifestErrorSnackbar err={err} />, { variant: "error", autoHideDuration: null });
      throw err;
    }
  }

  async function handleNext() {
    const bidKeys = Object.keys(selectedBids);

    // Create the lease
    try {
      const messages = bidKeys.map((gseq) => selectedBids[gseq]).map((bid) => TransactionMessageData.getCreateLeaseMsg(bid));
      const response = await sendTransaction(messages);

      if (!response) throw new Error("Rejected transaction");

      await analytics.event("deploy", "create lease");
    } catch (error) {
      // Rejected transaction
      return;
    }

    setIsSendingManifest(true);

    const localDeploymentData = getDeploymentLocalData(dseq);
    if (localDeploymentData && localDeploymentData.manifest) {
      // Send the manifest

      const sendManifestKey = enqueueSnackbar(<Snackbar title="Sending Manifest! ?" subTitle="Please wait a few seconds..." showLoading />, {
        variant: "success",
        autoHideDuration: null
      });

      try {
        const yamlJson = yaml.load(localDeploymentData.manifest);
        const mani = deploymentData.Manifest(yamlJson);

        for (let i = 0; i < bidKeys.length; i++) {
          const currentBid = selectedBids[bidKeys[i]];
          const provider = providers.find((x) => x.owner === currentBid.provider);
          await sendManifest(provider, mani);
        }
      } catch (err) {
        console.error(err);
      }

      closeSnackbar(sendManifestKey);
    }

    setIsSendingManifest(false);

    await analytics.event("deploy", "send manifest");

    history.replace(UrlService.deploymentDetails(dseq, "LOGS", "events"));
  }

  async function handleCloseDeployment() {
    try {
      const message = TransactionMessageData.getCloseDeploymentMsg(address, dseq);
      const response = await sendTransaction([message]);

      if (response) {
        history.replace(UrlService.deploymentList());
      }
    } catch (error) {
      throw error;
    }
  }

  function handleMenuClick(ev) {
    setAnchorEl(ev.currentTarget);
  }

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const onSearchChange = (event) => {
    const value = event.target.value;
    setSearch(value);
  };

  return (
    <>
      <Helmet title="Create Deployment - Create Lease" />

      <Box padding="0 1rem">
        {!isLoadingBids && bids.length > 0 && !allClosed && (
          <Box display="flex" alignItems="center" justifyContent="space-between">
            <Box flexGrow={1}>
              <TextField
                label="Search by attribute..."
                disabled={bids.length === 0 || isSendingManifest}
                value={search}
                onChange={onSearchChange}
                type="text"
                variant="outlined"
                autoFocus
                fullWidth
                size="medium"
                InputProps={{
                  endAdornment: search && (
                    <InputAdornment position="end">
                      <IconButton size="small" onClick={() => setSearch("")}>
                        <CloseIcon />
                      </IconButton>
                    </InputAdornment>
                  )
                }}
              />
            </Box>

            <Box display="flex" alignItems="center">
              <Tooltip
                classes={{ tooltip: classes.tooltip }}
                arrow
                interactive
                title={
                  <Alert severity="info" variant="standard">
                    Bids automatically close 5 minutes after the deployment is created if none are selected for a lease.
                  </Alert>
                }
              >
                <InfoIcon className={clsx(classes.tooltipIcon, classes.marginLeft)} />
              </Tooltip>

              <Box margin="0 .5rem">
                <IconButton aria-label="settings" aria-haspopup="true" onClick={handleMenuClick} size="small">
                  <MoreHorizIcon fontSize="large" />
                </IconButton>
              </Box>

              <Menu
                id="bid-actions-menu"
                anchorEl={anchorEl}
                keepMounted
                getContentAnchorEl={null}
                open={Boolean(anchorEl)}
                onClose={handleMenuClose}
                anchorOrigin={{
                  vertical: "bottom",
                  horizontal: "right"
                }}
                transformOrigin={{
                  vertical: "top",
                  horizontal: "right"
                }}
                onClick={handleMenuClose}
              >
                <MenuItem onClick={() => handleCloseDeployment()}>Close Deployment</MenuItem>
              </Menu>

              <Button
                variant="contained"
                color="primary"
                onClick={handleNext}
                classes={{ label: classes.nowrap }}
                disabled={dseqList.some((gseq) => !selectedBids[gseq]) || isSendingManifest || !providers}
              >
                Accept Bid{dseqList.length > 1 ? "s" : ""}
                <Box component="span" marginLeft=".5rem" display="flex" alignItems="center">
                  <ArrowForwardIosIcon fontSize="small" />
                </Box>
              </Button>
            </Box>
          </Box>
        )}

        <Box display="flex" alignItems="center">
          {!isLoadingBids && (allClosed || bids.length === 0) && (
            <Button variant="contained" color={allClosed ? "primary" : "secondary"} onClick={handleCloseDeployment} size="small">
              Close Deployment
            </Button>
          )}

          {!isLoadingBids && allClosed && (
            <Tooltip
              classes={{ tooltip: classes.tooltip }}
              arrow
              interactive
              title={
                <Alert severity="warning">
                  All bids for this deployment are closed. This can happen if no bids are accepted for more than 5 minutes after the deployment creation. You
                  can close this deployment and create a new one.
                </Alert>
              }
            >
              <InfoIcon className={clsx(classes.tooltipIcon, classes.marginLeft)} color="error" />
            </Tooltip>
          )}
        </Box>

        {(isLoadingBids || bids.length === 0) && !maxRequestsReached && (
          <Box textAlign="center" paddingTop="1rem">
            <CircularProgress />
            <Box paddingTop="1rem">
              <Typography variant="body1">Waiting for bids...</Typography>
            </Box>
          </Box>
        )}

        {warningRequestsReached && !maxRequestsReached && bids.length === 0 && (
          <Box paddingTop="1rem">
            <Alert variant="standard" severity="info">
              There should be bids by now... You can wait longer in case a bid shows up or close the deployment and try again with a different configuration.
            </Alert>
          </Box>
        )}

        {maxRequestsReached && bids.length === 0 && (
          <Box paddingTop="1rem">
            <Alert variant="standard" severity="warning">
              There's no bid for the current deployment. You can close the deployment and try again with a different configuration.
            </Alert>
          </Box>
        )}

        {bids.length > 0 && (
          <Box display="flex" alignItems="center" justifyContent="space-between">
            <Box>
              <FormControlLabel
                control={<Checkbox checked={isFilteringFavorites} onChange={(ev, value) => setIsFilteringFavorites(value)} color="primary" size="small" />}
                label="Favorites"
              />
            </Box>

            {!maxRequestsReached && (
              <Box display="flex" alignItems="center" lineHeight="1rem" fontSize=".7rem">
                <div style={{ color: "grey" }}>
                  <Typography variant="caption">Waiting for more bids...</Typography>
                </div>
                <Box marginLeft=".5rem">
                  <CircularProgress size=".7rem" />
                </Box>
              </Box>
            )}
          </Box>
        )}

        <LinearLoadingSkeleton isLoading={isSendingManifest} />
      </Box>

      {dseqList.length > 0 && (
        <ViewPanel bottomElementId="footer" overflow="auto" padding="0 1rem 2rem">
          {dseqList.map((gseq, i) => (
            <BidGroup
              key={gseq}
              gseq={gseq}
              bids={groupedBids[gseq]}
              handleBidSelected={handleBidSelected}
              selectedBid={selectedBids[gseq]}
              disabled={isSendingManifest}
              providers={providers}
              filteredBids={filteredBids}
              deploymentDetail={deploymentDetail}
              isFilteringFavorites={isFilteringFavorites}
              groupIndex={i}
              totalBids={dseqList.length}
            />
          ))}
        </ViewPanel>
      )}
    </>
  );
}
Example #27
Source File: ShippingAddress.js    From Merch-Dropper-fe with MIT License 4 votes vote down vote up
ShippingAddress = () => {
    const dispatch = useDispatch();
    const history = useHistory();
    const classes = useStyles();
    const [address, setAddress] = useState(initialQuoteState.sendQuote.spInfo.address) 
    const sendQuote = useSelector(state => state.QuoteReducer.sendQuote)
   
    const handleChange = e => {
        setAddress({
            ...address,
              [e.target.name]: e.target.value
              })
            }
      
    const handleSubmit = async (e)  => {
      const domain_name = localStorage.getItem("domain_name")
        e.preventDefault();
        await dispatch(addAddress(address))
          history.push(`/${domain_name}/checkout`)
          
    }

    return(
       <AddressPageWrapper>
           <h3>Please Enter Shipping Address</h3>
           <TextField
            className={classes.addressField}
            id="outlined-basic"
            label="Name"
            name="name"
            variant="outlined"
            inputProps={{ maxLength: 25 }}
            value={address.name}
            onChange={handleChange}
          />
          <TextField
            className={classes.addressField}
            id="outlined-basic"
            label="Shipping Address"
            name="address1"
            variant="outlined"
            value={address.address1}
            onChange={handleChange}
          />
          
          <TextField
            className={classes.addressField}
            id="outlined-basic"
            label="City"
            name="city"
            variant="outlined"
            inputProps={{ maxLength: 25 }}
            value={address.city}
            onChange={handleChange}
          />
          <TextField
            className={classes.addressField}
            id="outlined-basic"
            label="State"
            name="state"
            variant="outlined"
            inputProps={{ maxLength: 25 }}
            value={address.state}
            onChange={handleChange}
          />
          <TextField
            className={classes.addressField}
            id="outlined-basic"
            label="Zip"
            name="zip"
            variant="outlined"
            inputProps={{ maxLength: 5 }}
            value={address.zip}
            onChange={handleChange}
          />
          
         
          <Button onClick={handleSubmit}>Submit</Button>
          
       </AddressPageWrapper>
    )


    
}
Example #28
Source File: Landing.js    From social-media-strategy-fe with MIT License 4 votes vote down vote up
export default function Landing() {
  const classes = useStyles();
  const { push } = useHistory();
  AOS.init();

  return (
    <React.Fragment>
      <CssBaseline />
      <AppBar position="static" elevation={0} className={classes.appBar}>
        <Toolbar className={classes.toolbar}>
          <Typography
            variant="h6"
            noWrap
            className={classes.toolbarTitle}
            data-testid="some-heading"
          >
            SoMe
          </Typography>
          <nav>
            <Link variant="button" href="/login" className={classes.link}>
              SIGN UP
            </Link>
            <Link variant="button" href="/login" className={classes.link}>
              LOGIN
            </Link>
          </nav>
        </Toolbar>
      </AppBar>

      <div className="heading"
        style={{
          display: "flex",
          justifyContent: "space-evenly",
          alignItems: "center"
        }}
      >
        {/* Main text */}
        <div data-aos="fade-right" data-aos-easing="ease-in" >
          <Container component="main" className={classes.mainContent}>
            <Typography
              component="h1"
              variant="h2"
              gutterBottom
              className={classes.mainHeading}
            >
              Social Media management <br/> made easy.
            </Typography>
          </Container>
          <Container
            maxWidth="md"
            component="main"
            className={classes.butttonContainer}
          >
            <Button
              component="button"
              className={classes.button}
              onClick={() => push("/login")}
            >
              Get Started
            </Button>
          </Container>
        </div>
        {/* End main text */}

        {/* Sub text */}
        <div data-aos="fade-left" data-aos-easing="ease-in">
          <Container className={classes.subContent}>
            <Logo style={{ width: "400px", height: "400px" }} />
            <Typography component="p" className={classes.subHeading}>
              Discover how to develop your brand <br></br>and manage your
              digital marketing strategy
            </Typography>
          </Container>
          {/* End sub text */}
        </div>
      </div>

      {/* Start of About */}
      <div
        data-aos="fade-right"
        style={{
          display: "flex",
          justifyContent: "space-evenly",
          alignItems: "center",
          margin: "8%"
        }}
        className="section1"
      >
        <div>
          <ScheduleLogo style={{ width: "300px", height: "300px" }} />
        </div>

        <div style={{ display: "flex", flexDirection: "column" }}>
          <h1 className={classes.h1}>Draft, Organize, and Schedule</h1>
          <br></br>
          <p className={classes.p}>
            SoMe makes it easy to streamline and optimize your social media
            presence in one convenient place.
          </p>
        </div>
      </div>

      <h1 className={classes.h1} style={{ color: "dodgerblue"}}>
        Cool! But what sets us apart?
      </h1>

      {/* Start of Analytics */}
      <div
        data-aos="fade-left"
        style={{
          display: "flex",
          justifyContent: "space-evenly",
          alignItems: "center",
          margin: "8%"
        }}
        className="section2"
      >
        <div style={{ display: "flex", flexDirection: "column" }}>
          <h1 className={classes.h1}>Gain powerful insights</h1>
          <br></br>
          <p className={classes.p}>
            Find out the words your followers are engaging with most. We believe
            this information can be extremely beneficial in increasing your
            engagement.
          </p>
          <br></br>
          <div style={{ display: "flex", justifyContent: "center" }}>
            <LearnMore />
          </div>
        </div>

        <div>
          <DataScience style={{ width: "300px", height: "300px" }} />
        </div>
      </div>

      {/* Start of monthly snapshot */}
      <div
        data-aos="fade-right"
        style={{
          display: "flex",
          justifyContent: "space-evenly",
          alignItems: "center",
          margin: "8%",
        }}
        className="section1"
      >
        <div>
          <AnalyzingPic style={{ width: "300px", height: "300px" }} />
        </div>

        <div style={{ display: "flex", flexDirection: "column" }}>
          <h1 className={classes.h1}>Track your platform growth</h1>
          <br/>
            <p className={classes.p}>
              View a snapshot of your social media engagement each month. SoMe
              provides valuable metrics so you can make sure your platforms'
              growth remains on track.{" "}
            </p>
            <br/>
        </div>
      </div>

      {/* Start of CTA 2 */}
      <div
        style={{
          display: "flex",
          justifyContent: "space-evenly",
          background: "whitesmoke",
        }}
        className="sectioncta2"
      >
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            alignContent: "center",
          }}
        >
          <h1 className={classes.h1} style={{ paddingTop: "20%" }} id="cta2">
            Grow and manage <br></br> your social media today!
          </h1>
          <br className="br"></br>
          <br className="br"></br>
          <Button
            component="button"
            className={classes.button}
            onClick={() => push("/login")}
          >
            Start Now
          </Button>
        </div>
        <div>
          <Social style={{ width: "300", height: "300" }} className="socialpic"/>
        </div>
      </div>

      {/* Start of footer */}
      <footer
        style={{
          display: "flex",
          justifyContent: "space-between",
          margin: "4%",
        }}
      >
        <div>
          <Typography variant="h6" noWrap className={classes.footerTitle}>
            SoMe
          </Typography>
          <Typography style={{ fontSize: "12px" }}>
            Social media growth and management made easy.
          </Typography>
        </div>
        <div
          style={{ display: "flex", flexDirection: "column", width: "100px" }}
        >
          <Typography style={{ fontSize: "14px", textAlign: "center", paddingBottom:"2%" }}>
            Get in Touch
          </Typography>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <a
              href="https://github.com/orgs/Lambda-School-Labs/teams/labs24-some/repositories"
              target="_blank" rel="noopener noreferrer" 
            >
              <GitHubIcon style={{ color: "#4E4E4E" }} />
            </a>
            <a href="https://twitter.com/some_strategy" target="_blank" rel="noopener noreferrer" >
              <TwitterIcon style={{ color: "#4E4E4E" }} />
            </a>
            <a href="mailto:[email protected]" target="_blank" rel="noopener noreferrer" >
              <EmailIcon style={{ color: "#4E4E4E" }} />
            </a>
          </div>
        </div>
      </footer>
    </React.Fragment>
  );
}
Example #29
Source File: projectList.js    From create-sas-app with Apache License 2.0 4 votes vote down vote up
ProjectList = () => {

	const dispatch = useDispatch();
	const history = useHistory();

	const [search, setSearch] = useState('');
	const [paginationPage, setPaginationPage] = useState(1)
	const [paginationPageSize, setPaginationPageSize] = useState(10)

	const projects = useSelector(state => state.projectList.projects)
	const spinner = useSelector(state => state.home.mainSpinner)

	const filtered = projects.filter(el => {
		return el.name.toLowerCase().includes(search.toLocaleLowerCase()) || search === ''
	})

	const tableTitle = () => {
		return (
			<div className="flex flex-row justify-content-between align-items-center">
				<h4>Project List</h4>
				<Search
					labelText="search"
					value={search}
					onChange={(e) => setSearch(e.target.value)}
					id="search-1"
					placeHolderText="Filter by name"
				/>
			</div>
		)
	}

	const submitRequest = (id) => {
		const project = projects.find(p => p.id === id)
		if (project) {
			let uri = project.uri.split('/').pop()
			history.push(`/project/${uri}`);
		}
	}

	const handlePaginationChange = e => {
		setPaginationPage(e.page);
		setPaginationPageSize(e.pageSize);
	};

	const getCurrentPageRows = rows => {
		let lastItemIndex = 0;

		if (paginationPage === 1 || rows.length <= paginationPageSize) {
			lastItemIndex = paginationPageSize;
		} else {
			lastItemIndex = paginationPageSize * paginationPage;
		}
		return rows.slice((paginationPage - 1) * paginationPageSize, lastItemIndex);
	};

	useEffect(() => {
		setMainSpinner(dispatch, true);
		ADAPTER_SETTINGS.sasVersion === 'viya' && fetchProjects(dispatch);
		return () => {

		}
	}, [dispatch])

	return (
		<div className={'align-center'}>
      {
        PROJECT_EXTENTION === ''? <InlineNotification kind="warning" title="No project extention set, showing all files from project folder" /> : null
      }
			<DataTable
				isSortable={true}
				rows={filtered}
				headers={headerData}
				render={({rows, headers, getHeaderProps}) => {
					let currentPageRows = getCurrentPageRows(rows);
					return (
						<TableContainer title={tableTitle()}>
							<Table size='tall'>
								<TableHead>
									<TableRow>
										{headers.map(header => (
											<TableHeader {...getHeaderProps({header})}>
												{header.header}
											</TableHeader>
										))}
									</TableRow>
								</TableHead>
								{
									! spinner &&
									<TableBody>
										{currentPageRows.map(row => {
											return (
												<TableRow key={row.id} onClick={() => submitRequest(row.id)}>
													{row.cells.map(cell => (
														<TableCell key={cell.id}>{cell.value}</TableCell>
													))}
												</TableRow>
											)
										})}
									</TableBody>
								}
							</Table>
						</TableContainer>)
				}
				}
			/>
			{! spinner ?
				<Pagination
					pageSizes={[10, 20, 30, 40, 50]}
					totalItems={filtered.length}
					itemsPerPageText={'Projects per page'}
					onChange={handlePaginationChange}
				/>
				:
				<Loading description="Active loading indicator" withOverlay={false}/>
			}
		</div>
	)
}