hooks#useRouter JavaScript Examples

The following examples show how to use hooks#useRouter. 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: index.jsx    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
Setup = ({ route }) => {
    const provider = useProvider();
    const router = useRouter();

    useEffectOnce(async () => {
        if (provider.data !== null && provider.data.submittedAt)
            router.navigateToUrl('/provider/schedule');
        if (provider.keyPairs === null) await provider.initialize();
        if (Object.keys(route.hashParams).length > 0)
            provider.data = route.hashParams; // pre-filled data
    });

    return (
        <React.Fragment>
            <Wizard
                route={route}
                page={route.handler.props.page || 'hi'}
                status={route.handler.props.status}
            />
        </React.Fragment>
    );
}
Example #2
Source File: week-calendar.jsx    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
HourRow = ({
    appointments,
    action,
    secondaryAction,
    id,
    date,
    day,
    hour,
}) => {
    const ots = new Date(
        date.toLocaleDateString('en-US') +
            ' ' +
            hour.toLocaleString('en-US', { minimumIntegerDigits: 2 }) +
            ':00:00'
    );
    const ote = new Date(ots);
    ote.setHours(ote.getHours() + 1);
    const relevantAppointments = [];
    for (const oa of appointments) {
        // beginning of appointment
        const oas = new Date(`${oa.timestamp}`);
        // end of appointment
        const oae = new Date(oas.getTime() + 1000 * 60 * oa.duration);
        let startsHere = false;
        let relevant = false;
        // starts in interval
        if (oas >= ots && oas < ote) {
            startsHere = true;
            relevant = true;
        }
        // ends in interval
        if (oae > ots && oae <= ote) relevant = true;

        // is in interval
        if (oas <= ots && oae >= ote) relevant = true;

        if (relevant)
            relevantAppointments.push({
                startsHere: startsHere,
                appointment: oa,
            });
    }

    const router = useRouter();

    const showNewAppointment = () => {
        const query = urlEncode({ timestamp: ots.toISOString() });
        router.navigateToUrl(`/provider/schedule/${action}/new#${query}`);
    };

    const hasAppointments = relevantAppointments.length > 0;
    return (
        <div
            onClick={showNewAppointment}
            className={
                'kip-hour-row' +
                (hasAppointments ? ' kip-has-appointments' : '')
            }
        >
            {hasAppointments && (
                <CalendarAppointments
                    ots={ots}
                    ote={ote}
                    id={id}
                    action={action}
                    secondaryAction={secondaryAction}
                    appointments={relevantAppointments}
                />
            )}
        </div>
    );
}
Example #3
Source File: providers.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
Providers = ({ action, id }) => {
    const router = useRouter();
    const mediator = useMediator();
    const [view, setView] = useState('pending');

    useInterval(async () => {
        await mediator.pendingProviders().get();
        await mediator.verifiedProviders().get();
    }, 10000);

    const render = () => {
        const providers =
            view === 'pending'
                ? mediator.pendingProviders().result()
                : mediator.verifiedProviders().result();

        const showProvider = (i) => {
            const id = buf2hex(b642buf(i));
            router.navigateToUrl(`/mediator/providers/show/${id}`);
        };

        let modal;

        const closeModal = () => router.navigateToUrl('/mediator/providers');

        if (action === 'show' && id !== undefined) {
            const base64Id = buf2b64(hex2buf(id));
            const provider = providers.data.find(
                (provider) => provider.data.publicKeys.signing === base64Id
            );

            const doConfirmProvider = async () => {
                const result = await mediator.confirmProvider(provider);
                console.log(result);
            };

            if (provider !== undefined)
                modal = (
                    <Modal
                        title={<T t={t} k="providers.edit" />}
                        save={<T t={t} k="providers.confirm" />}
                        onSave={doConfirmProvider}
                        saveType="success"
                        onClose={closeModal}
                        onCancel={closeModal}
                    >
                        <div className="kip-provider-data">
                            <T t={t} k="providers.confirmText" />
                            <table className="bulma-table bulma-is-fullwidth bulma-is-striped">
                                <thead>
                                    <tr>
                                        <th>
                                            <T t={t} k="provider-data.field" />
                                        </th>
                                        <th>
                                            <T t={t} k="provider-data.value" />
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>
                                            <T t={t} k="provider-data.name" />
                                        </td>
                                        <td>{provider.data.name}</td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <T t={t} k="provider-data.street" />
                                        </td>
                                        <td>{provider.data.street}</td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <T t={t} k="provider-data.city" />
                                        </td>
                                        <td>{provider.data.city}</td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <T
                                                t={t}
                                                k="provider-data.zipCode"
                                            />
                                        </td>
                                        <td>{provider.data.zipCode}</td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <T t={t} k="provider-data.email" />
                                        </td>
                                        <td>{provider.data.email}</td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <T t={t} k="provider-data.phone" />
                                        </td>
                                        <td>{provider.data.phone}</td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <T
                                                t={t}
                                                k="provider-data.description"
                                            />
                                        </td>
                                        <td>{provider.data.description}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </Modal>
                );
        }

        const providerItems = providers.data
            .sort(sortProviderByDate)
            .map((provider) => (
                <ListItem
                    onClick={() =>
                        showProvider(provider.data.publicKeys.signing)
                    }
                    key={provider.data.publicKeys.signing}
                    isCard
                >
                    <ListColumn size="md">{provider.data.name}</ListColumn>
                    <ListColumn size="md">
                        {provider.data.street} ยท {provider.data.city}
                    </ListColumn>
                </ListItem>
            ));

        return (
            <CardContent>
                <div className="kip-providers">
                    {modal}
                    <DropdownMenu
                        title={
                            <F>
                                <Icon icon="check-circle" />
                                <T t={t} k={`providers.${view}`} />
                            </F>
                        }
                    >
                        <DropdownMenuItem
                            icon="check-circle"
                            onClick={() => setView('verified')}
                        >
                            <T t={t} k="providers.verified" />
                        </DropdownMenuItem>
                        <DropdownMenuItem
                            icon="exclamation-circle"
                            onClick={() => setView('pending')}
                        >
                            <T t={t} k="providers.pending" />
                        </DropdownMenuItem>
                    </DropdownMenu>
                    <List>
                        <ListHeader>
                            <ListColumn size="md">
                                <T t={t} k="providers.name" />
                            </ListColumn>
                            <ListColumn size="md">
                                <T t={t} k="providers.address" />
                            </ListColumn>
                        </ListHeader>
                        {providerItems}
                    </List>
                </div>
            </CardContent>
        );
    };
    return (
        <WithLoader
            resources={[
                mediator.pendingProviders().result(),
                mediator.verifiedProviders().result(),
            ]}
            renderLoaded={render}
        />
    );
}
Example #4
Source File: new-appointment.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
NewAppointment = withForm(
    ({ route, action, id, form: { valid, error, data, set, reset } }) => {
        let actionUrl = '';
        const settings = useSettings();
        const router = useRouter();
        if (action !== undefined) actionUrl = `/${action}`;
        if (id !== undefined) actionUrl += `/view/${id}`;
        const [saving, setSaving] = useState(false);
        const cancel = () =>
            router.navigateToUrl(`/provider/schedule${actionUrl}`);

        let appointment;

        if (id !== undefined)
            appointment = appointments.find((app) => hexId(app.id) === id);

        const save = () => {
            let action;
            setSaving(true);
            // we remove unnecessary fields like 'time' and 'date'
            delete data.time;
            delete data.date;
            if (appointment !== undefined) action = updateAppointmentAction;
            else action = createAppointmentAction;
            const promise = action(data, appointment);
            promise.finally(() => setSaving(false));
            promise.then(() => {
                // we reload the appointments
                openAppointmentsAction();
                // and we go back to the schedule view
                router.navigateToUrl(`/provider/schedule${actionUrl}`);
            });
        };

        useEffectOnce(() => {
            if (appointment !== undefined) {
                const appointmentData = {
                    time: formatTime(appointment.timestamp),
                    date: formatDate(appointment.timestamp),
                    slots: appointment.slots,
                    duration: appointment.duration,
                };
                for (const [_, v] of Object.entries(properties)) {
                    for (const [kk, _] of Object.entries(v.values)) {
                        if (appointment[kk] !== undefined)
                            appointmentData[kk] = true;
                        else delete appointmentData[kk];
                    }
                }
                reset(appointmentData);
            } else {
                const newData = {
                    duration: data.duration || 30,
                    slots: data.slots || 1,
                };

                let firstProperty;
                let found = false;
                addProps: for (const [_, v] of Object.entries(properties)) {
                    for (const [kk, _] of Object.entries(v.values)) {
                        if (firstProperty === undefined) firstProperty = kk;
                        if (data[kk] !== undefined) {
                            found = true;
                            newData[kk] = true;
                            break addProps;
                        }
                    }
                }
                if (!found) newData[firstProperty] = true;

                if (route.hashParams !== undefined) {
                    if (route.hashParams.timestamp !== undefined) {
                        const date = new Date(route.hashParams.timestamp);
                        newData.time = formatTime(date);
                        newData.date = formatDate(date);
                    }
                }
                reset(newData);
            }
        });

        const properties = settings.get('appointmentProperties');

        const apptProperties = Object.entries(properties).map(([k, v]) => {
            const options = Object.entries(v.values).map(([kv, vv]) => ({
                value: kv,
                key: vv,
                title: <T t={properties} k={`${k}.values.${kv}`} />,
            }));

            let currentOption;

            for (const [k, v] of Object.entries(data)) {
                for (const option of options) {
                    if (k === option.value && v === true) currentOption = k;
                }
            }

            const changeTo = (option) => {
                const newData = { ...data };
                for (const option of options) newData[option.value] = undefined;
                newData[option.value] = true;
                reset(newData);
            };

            return (
                <React.Fragment key={k}>
                    <h2>
                        <T t={properties} k={`${k}.title`} />
                    </h2>
                    <RichSelect
                        options={options}
                        value={currentOption}
                        onChange={(option) => changeTo(option)}
                    />
                </React.Fragment>
            );
        });

        const durations = [
            5, 10, 15, 20, 30, 45, 60, 90, 120, 150, 180, 210, 240,
        ].map((v) => ({
            value: v,
            title: (
                <T
                    t={t}
                    k={`schedule.appointment.duration.title`}
                    duration={v}
                />
            ),
        }));

        return (
            <Modal
                saveDisabled={!valid || saving}
                cancelDisabled={saving}
                closeDisabled={saving}
                className="kip-new-appointment"
                onSave={save}
                waiting={saving}
                onCancel={cancel}
                onClose={cancel}
                title={
                    <T
                        t={t}
                        k={
                            appointment !== undefined
                                ? 'edit-appointment.title'
                                : 'new-appointment.title'
                        }
                    />
                }
            >
                <FormComponent>
                    <FieldSet>
                        <div className="kip-field">
                            <Label htmlFor="date">
                                <T t={t} k="new-appointment.date" />
                            </Label>
                            <ErrorFor error={error} field="date" />
                            <input
                                value={data.date || ''}
                                type="date"
                                className="bulma-input"
                                onChange={(e) => set('date', e.target.value)}
                            />
                        </div>
                        <div className="kip-field">
                            <Label htmlFor="time">
                                <T t={t} k="new-appointment.time" />
                            </Label>
                            <ErrorFor error={error} field="time" />
                            <input
                                type="time"
                                className="bulma-input"
                                value={data.time || ''}
                                onChange={(e) => set('time', e.target.value)}
                                step={60}
                            />
                        </div>
                        <div className="kip-field kip-is-fullwidth kip-slider">
                            <Label htmlFor="slots">
                                <T t={t} k="new-appointment.slots" />
                            </Label>
                            <ErrorFor error={error} field="slots" />
                            <input
                                type="number"
                                className="bulma-input"
                                value={data.slots || 1}
                                onChange={(e) =>
                                    set('slots', parseInt(e.target.value))
                                }
                                step={1}
                                min={1}
                                max={50}
                            />
                        </div>
                        <div className="kip-field kip-is-fullwidth">
                            <RichSelect
                                id="duration"
                                value={data.duration || 30}
                                onChange={(value) =>
                                    set('duration', value.value)
                                }
                                options={durations}
                            />
                        </div>

                        <div className="kip-field kip-is-fullwidth">
                            {apptProperties}
                        </div>
                    </FieldSet>
                </FormComponent>
            </Modal>
        );
    },
    AppointmentForm,
    'form'
)
Example #5
Source File: week-calendar.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
WeekCalendar = ({
    action,
    secondaryAction,
    id,
    startDate,
    appointments,
}) => {
    let fromHour;
    let toHour;
    const router = useRouter();
    const endDate = new Date(startDate);
    endDate.setDate(endDate.getDate() + 7);
    appointments.forEach((app) => {
        const appStartDate = new Date(app.timestamp);
        const appEndDate = new Date(
            new Date(app.timestamp).getTime() + 1000 * 60 * app.duration
        );
        if (
            appStartDate < startDate ||
            appStartDate > endDate ||
            app.slots === 0
        )
            return;
        const startHours = appStartDate.getHours();
        const endHours = appEndDate.getHours();
        if (fromHour === undefined || startHours < fromHour)
            fromHour = startHours;
        if (toHour === undefined || endHours > toHour) toHour = endHours;
    });
    if (fromHour === undefined || fromHour > 8) fromHour = 8;
    if (toHour === undefined || toHour < 19) toHour = 19; // hours are inclusive
    const dayColumns = [
        <DayLabelColumn
            fromHour={fromHour}
            toHour={toHour}
            key="-"
            appointments={appointments}
        />,
    ];
    const date = new Date(startDate);
    for (let i = 0; i < 7; i++) {
        dayColumns.push(
            <DayColumn
                appointments={appointments}
                secondaryAction={secondaryAction}
                action={action}
                id={id}
                fromHour={fromHour}
                toHour={toHour}
                date={new Date(date)}
                day={i}
                key={i}
            />
        );
        date.setDate(date.getDate() + 1);
    }

    const goBackward = () => {
        const newDate = formatDate(
            getMonday(new Date(startDate.getTime() - 1000 * 60 * 60 * 24 * 7))
        );
        router.navigateToUrl(`/provider/schedule/${newDate}`);
    };

    const goForward = () => {
        const newDate = formatDate(
            getMonday(new Date(startDate.getTime() + 1000 * 60 * 60 * 24 * 7))
        );
        router.navigateToUrl(`/provider/schedule/${newDate}`);
    };

    return (
        <>
            <div className="kip-schedule-navigation">
                <Button className="kip-backward" type="" onClick={goBackward}>
                    <T t={t} k="schedule.backward" />
                </Button>
                <Button className="kip-forward" type="" onClick={goForward}>
                    <T t={t} k="schedule.forward" />
                </Button>
            </div>
            <div className="kip-week-calendar">{dayColumns}</div>
        </>
    );
}
Example #6
Source File: provider-data.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
BaseProviderData = ({
    embedded,
    form: { set, data, error, valid, reset },
}) => {
    const [modified, setModified] = useState(false);

    const router = useRouter();
    const provider = useProvider();

    const onSubmit = () => {
        if (!valid) return;
        provider.data = data;
        // we redirect to the 'verify' step
        router.navigateToUrl(`/provider/setup/verify`);
    };

    useEffectOnce(() => {
        reset(provider.data || {});
        setModified(false);
    });

    const setAndMarkModified = (key, value) => {
        setModified(true);
        set(key, value);
    };

    const controls = (
        <React.Fragment>
            <ErrorFor error={error} field="name" />
            <RetractingLabelInput
                value={data.name || ''}
                onChange={(value) => setAndMarkModified('name', value)}
                label={<T t={t} k="provider-data.name" />}
            />
            <ErrorFor error={error} field="street" />
            <RetractingLabelInput
                value={data.street || ''}
                onChange={(value) => setAndMarkModified('street', value)}
                label={<T t={t} k="provider-data.street" />}
            />
            <ErrorFor error={error} field="zipCode" />
            <RetractingLabelInput
                value={data.zipCode || ''}
                onChange={(value) => setAndMarkModified('zipCode', value)}
                label={<T t={t} k="provider-data.zip-code" />}
            />
            <ErrorFor error={error} field="city" />
            <RetractingLabelInput
                value={data.city || ''}
                onChange={(value) => setAndMarkModified('city', value)}
                label={<T t={t} k="provider-data.city" />}
            />
            <ErrorFor error={error} field="website" />
            <RetractingLabelInput
                value={data.website || ''}
                onChange={(value) => setAndMarkModified('website', value)}
                label={<T t={t} k="provider-data.website" />}
            />
            <ErrorFor error={error} field="description" />
            <label htmlFor="description">
                <T t={t} k="provider-data.description" />
            </label>
            <textarea
                id="description"
                className="bulma-textarea"
                value={data.description || ''}
                onChange={(e) =>
                    setAndMarkModified('description', e.target.value)
                }
            />
            <h3>
                <T t={t} k="provider-data.for-mediator" />
            </h3>
            <ErrorFor error={error} field="phone" />
            <RetractingLabelInput
                value={data.phone || ''}
                onChange={(value) => setAndMarkModified('phone', value)}
                label={<T t={t} k="provider-data.phone" />}
            />
            <ErrorFor error={error} field="email" />
            <RetractingLabelInput
                value={data.email || ''}
                onChange={(value) => setAndMarkModified('email', value)}
                label={<T t={t} k="provider-data.email" />}
            />
            <hr />
            <ErrorFor error={error} field="code" />
            <RetractingLabelInput
                value={data.code || ''}
                onChange={(value) => setAndMarkModified('code', value)}
                description={
                    <T t={t} k="provider-data.access-code.description" />
                }
                label={<T t={t} k="provider-data.access-code.label" />}
            />
            <hr />
            <ul className="kip-properties">
                <li className="kip-property">
                    <Switch
                        id="accessible"
                        checked={
                            data.accessible !== undefined
                                ? data.accessible
                                : false
                        }
                        onChange={(value) =>
                            setAndMarkModified('accessible', value)
                        }
                    >
                        &nbsp;
                    </Switch>

                    <label htmlFor="accessible">
                        <T t={t} k="provider-data.accessible" />
                    </label>
                </li>
            </ul>
        </React.Fragment>
    );

    return (
        <React.Fragment>
            <div className="kip-provider-data">
                <FormComponent onSubmit={onSubmit}>
                    <FieldSet>
                        <CardContent>{controls}</CardContent>
                        <CardFooter>
                            <SubmitField
                                disabled={!valid || embedded & !modified}
                                type={'success'}
                                onClick={onSubmit}
                                title={
                                    <T
                                        t={t}
                                        k="provider-data.save-and-continue"
                                    />
                                }
                            />
                        </CardFooter>
                    </FieldSet>
                </FormComponent>
            </div>
        </React.Fragment>
    );
}
Example #7
Source File: verify.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
Verify = () => {
    const router = useRouter();
    const settings = useSettings();
    const provider = useProvider();

    const [submitting, setSubmitting] = useState(false);
    const [response, setResponse] = useState(null);

    const submit = async () => {
        if (submitting) return;

        setSubmitting(true);
        const response = await provider.storeData();
        setSubmitting(false);

        setResponse(response);

        if (response.status === Status.Succeeded)
            router.navigateToUrl('/provider/setup/store-secrets');
    };

    let failedMessage;
    let failed;

    if (response && response.status === Status.Failed) {
        console.log(response);
        failed = true;
        if (
            response.error.error !== undefined &&
            response.error.error.code === 401
        ) {
            failedMessage = (
                <Message type="danger">
                    <T t={t} k="wizard.failed.invalid-code" />
                </Message>
            );
        }
    }

    if (failed && !failedMessage)
        failedMessage = (
            <Message type="danger">
                <T t={t} k="wizard.failed.notice" />
            </Message>
        );

    return (
        <>
            <CardContent>
                {failedMessage}
                <p className="kip-verify-notice">
                    <T
                        t={t}
                        k="verify.text"
                        link={
                            <A
                                key="letUsKnow"
                                external
                                href={settings.get('supportEmail')}
                            >
                                <T t={t} k="wizard.letUsKnow" key="letUsKnow" />
                            </A>
                        }
                    />
                </p>
                <ProviderData />
            </CardContent>
            <CardFooter>
                <Button
                    type={failed ? 'danger' : 'success'}
                    disabled={submitting}
                    onClick={submit}
                >
                    <T
                        t={t}
                        k={
                            failed
                                ? 'wizard.failed.title'
                                : submitting
                                ? 'wizard.please-wait'
                                : 'wizard.continue'
                        }
                    />
                </Button>
            </CardFooter>
        </>
    );
}