components#WithLoader JavaScript Examples

The following examples show how to use components#WithLoader. 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: appointments.jsx    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
Appointments = () => {
    const user = useUser();

    const appointments = user.appointments().result().appointments;

    const render = () => {
        let invitations = [];

        if (appointments !== undefined && appointments.data !== null)
            for (const appointment of appointments.data)
                invitations.push(appointment);

        if (invitation !== undefined && invitation.data !== null)
            for (const offer of invitation.data) {
                if (
                    invitations.some(
                        (inv) => inv.provider.name === offer.provider.name
                    )
                )
                    continue;
                invitations.push(offer);
            }

        if (
            acceptedInvitation !== undefined &&
            acceptedInvitation.data !== null
        ) {
            const ai = invitations.find((inv) => {
                if (inv === null) return false;
                return inv.offers.some((offer) =>
                    offer.slotData.some((sla) =>
                        acceptedInvitation.data.offer.slotData.some(
                            (slb) => slb.id === sla.id
                        )
                    )
                );
            });
            if (ai === undefined) return <InvitationDeleted />;
            return <AcceptedInvitation offers={ai.offers} />;
        }

        // we only show relevant invitations
        invitations = invitations.filter((inv) =>
            filterInvitations(inv, acceptedInvitation)
        );

        if (invitations.length === 0)
            return <NoInvitations tokenData={tokenData.data} />;

        const details = invitations.map((data) => (
            <InvitationDetails
                tokenData={tokenData}
                data={data}
                key={data.provider.signature}
            />
        ));

        return <F>{details}</F>;
    };
    return (
        <WithLoader
            resources={[user.appointments().result()]}
            renderLoaded={render}
        />
    );
}
Example #2
Source File: verify.jsx    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
Verify = withSettings(
    withActions(({ settings, contactData, contactDataAction }) => {
        const [initialized, setInitialized] = useState(false);

        useEffect(() => {
            if (initialized) return;
            contactDataAction();
            setInitialized(true);
        });

        const render = () => (
            <React.Fragment>
                <CardContent>
                    <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>
                    <div className="kip-contact-data-box">
                        <ul>
                            <li>
                                <span>
                                    <T t={t} k="contact-data.email.label" />
                                </span>{' '}
                                {contactData.data.email || (
                                    <T t={t} k="contact-data.not-given" />
                                )}
                            </li>
                        </ul>
                    </div>
                    <div className="kip-contact-data-links">
                        <A
                            className="bulma-button bulma-is-small"
                            href="/user/setup/enter-contact-data"
                        >
                            <T t={t} k="contact-data.change" />
                        </A>
                    </div>
                </CardContent>
                <CardFooter>
                    <Button type="success" href={`/user/setup/finalize`}>
                        <T t={t} k="wizard.continue" />
                    </Button>
                </CardFooter>
            </React.Fragment>
        );
        return <WithLoader resources={[contactData]} renderLoaded={render} />;
    }, [])
)
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: stats.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
Stats = () => {
    const mediator = useMediator();
    useEffectOnce(() => {
        const params = {
            filter: { zipCode: null },
            id: 'queues',
            type: 'hour',
            from: todayPlusN(-1).toISOString(),
            to: todayPlusN(1).toISOString(),
        };
        mediator.stats().get(params);
    });

    const renderLoaded = () => {
        const stats = mediator.stats().result();
        const summary = prepareOverallStats(stats);
        let content;
        if (summary.show === 0) {
            content = (
                <div className="bulma-column bulma-is-fullwidth-desktop">
                    <Card size="fullwidth">
                        <Message type="warning">
                            <T t={t} k="noData" />
                        </Message>
                    </Card>
                </div>
            );
        } else {
            content = (
                <React.Fragment>
                    <div className="bulma-column bulma-is-full-desktop">
                        <Card size="fullwidth" flex>
                            <CardContent>
                                <T
                                    key="span"
                                    t={t}
                                    k="dateSpan"
                                    from={
                                        <strong key="s1">
                                            {new Date(
                                                summary.from
                                            ).toLocaleString('en-US', opts)}
                                        </strong>
                                    }
                                    to={
                                        <strong key="s2">
                                            {new Date(
                                                summary.to
                                            ).toLocaleString('en-US', opts)}
                                        </strong>
                                    }
                                />
                            </CardContent>
                        </Card>
                    </div>
                    <div className="bulma-column bulma-is-one-quarter-desktop">
                        <SummaryBox
                            open={summary.open}
                            booked={summary.booked}
                            active={summary.active}
                        />
                    </div>
                    <div className="bulma-column bulma-is-three-quarters-desktop bulma-is-flex">
                        <Card size="fullwidth" flex>
                            <CardHeader>
                                <h2>
                                    <T t={t} k="bookingRate" />
                                </h2>
                            </CardHeader>
                            <CardContent className="kip-cm-overview">
                                <BarChart
                                    hash={stats.hash}
                                    data={prepareHourlyStats(stats)}
                                />
                            </CardContent>
                        </Card>
                    </div>
                </React.Fragment>
            );
        }
        return (
            <CardContent>
                <div className="bulma-columns bulma-is-multiline bulma-is-desktop">
                    {content}
                </div>
            </CardContent>
        );
    };

    return (
        <WithLoader
            resources={[mediator.stats().result()]}
            renderLoaded={renderLoaded}
        />
    );
}
Example #5
Source File: schedule.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
Schedule = ({ action, secondaryAction, id, route }) => {
    const [view, setView] = useState('calendar');
    const [lastUpdated, setLastUpdated] = useState(new Date().toLocaleString());
    const provider = useProvider();

    let startDate;

    if (action !== undefined) {
        const result = /^(\d{4})-(\d{2})-(\d{2})$/.exec(action);
        if (result) {
            const [, year, month, day] = result;
            startDate = getMonday(
                new Date(Number(year), Number(month) - 1, Number(day))
            );
        }
    }

    if (startDate === undefined)
        startDate = getMonday(new Date().setHours(0, 0, 0, 0));

    useEffectOnce(async () => {
        const endDate = new Date(startDate);
        endDate.setUTCDate(endDate.getUTCDate() + 7);
        // we load all the necessary data
        const response = await provider
            .appointments()
            .get({ from: startDate.toISOString(), to: endDate.toISOString() });
        console.log(response);
    });

    if (action === undefined) {
        action = formatDate(startDate);
    }

    const dateString = formatDate(startDate);

    const render = () => {
        let newAppointmentModal;
        let content;
        const appointments = provider.appointments().result().data;
        switch (view) {
            case 'calendar':
                content = (
                    <WeekCalendar
                        startDate={startDate}
                        action={action}
                        secondaryAction={secondaryAction}
                        id={id}
                        appointments={appointments}
                    />
                );
                break;
            case 'booking-list':
                content = (
                    <AppointmentsList
                        startDate={startDate}
                        id={id}
                        action={action}
                        secondaryAction={secondaryAction}
                        appointments={appointments}
                    />
                );
                break;
        }

        if (secondaryAction === 'new' || secondaryAction === 'edit')
            newAppointmentModal = (
                <NewAppointment
                    route={route}
                    appointments={appointments}
                    action={action}
                    id={id}
                />
            );

        return (
            <div className="kip-schedule">
                <CardContent>
                    <div className="kip-non-printable">
                        {newAppointmentModal}
                        <Button href={`/provider/schedule/${dateString}/new`}>
                            <T t={t} k="schedule.appointment.add" />
                        </Button>
                        &nbsp;
                        <DropdownMenu
                            title={
                                <>
                                    <Icon icon="calendar" />{' '}
                                    <T t={t} k={`schedule.${view}`} />
                                </>
                            }
                        >
                            <DropdownMenuItem
                                icon="calendar"
                                onClick={() => setView('calendar')}
                            >
                                <T t={t} k={`schedule.calendar`} />
                            </DropdownMenuItem>
                            <DropdownMenuItem
                                icon="list"
                                onClick={() => setView('booking-list')}
                            >
                                <T t={t} k={`schedule.booking-list`} />
                            </DropdownMenuItem>
                        </DropdownMenu>
                        <hr />
                    </div>
                    {content}
                </CardContent>
                <Message type="info" waiting>
                    <T t={t} k="schedule.updating" lastUpdated={lastUpdated} />
                </Message>
            </div>
        );
    };

    // we wait until all resources have been loaded before we display the form
    return (
        <WithLoader
            resources={[provider.appointments().result()]}
            renderLoaded={render}
        />
    );
}
Example #6
Source File: settings.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
Settings = withActions(
    withRouter(
        withSettings(
            ({
                action,
                type,
                settings,
                keys,
                keysAction,
                keyPairs,
                keyPairsAction,
                providerSecret,
                providerSecretAction,
                backupData,
                backupDataAction,
                providerData,
                providerDataAction,
                verifiedProviderData,
                verifiedProviderDataAction,
                router,
            }) => {
                const [deleting, setDeleting] = useState(false);
                const [loggingOut, setLoggingOut] = useState(false);
                const [initialized, setInitialized] = useState(false);
                const [view, setView] = useState('verified');

                // we load all the resources we need
                useEffect(() => {
                    if (initialized) return;

                    keysAction();
                    verifiedProviderDataAction();
                    providerDataAction();

                    setInitialized(true);
                });

                let modal;

                const title = settings.get('title').toLowerCase();

                const cancel = () => {
                    router.navigateToUrl('/provider/settings');
                };

                const deleteData = () => {
                    setDeleting(true);
                    const backend = settings.get('backend');
                    backend.local.deleteAll('provider::');
                    setDeleting(false);
                    router.navigateToUrl('/provider/deleted');
                };

                const logOut = () => {
                    setLoggingOut(true);

                    const kpa = keyPairsAction('logoutKeyPairs');
                    kpa.then((kp) => {
                        const psa = providerSecretAction(
                            undefined,
                            'logoutProviderSecret'
                        );
                        psa.then((ps) => {
                            // we give the backup data action a different name to avoid it being rejected
                            // in case there's already a backup in progress... It will still be queued
                            // up to ensure no conflicts can occur.
                            const ba = backupDataAction(
                                kp.data,
                                ps.data,
                                'logout'
                            );
                            ba.then(() => {
                                const backend = settings.get('backend');
                                backend.local.deleteAll('provider::');
                                router.navigateToUrl('/provider/logged-out');
                            });
                            ba.catch(() => setLoggingOut(false));
                        });
                        psa.catch(() => setLoggingOut(false));
                    });
                    kpa.catch(() => setLoggingOut(false));
                };

                if (action === 'backup') {
                    modal = (
                        <Modal
                            onClose={cancel}
                            save="Sicherungsdatei herunterladen"
                            title={<T t={t} k="backup-modal.title" />}
                            onCancel={cancel}
                            cancel={<T t={t} k="backup-modal.close" />}
                            saveType="success"
                        >
                            <p>
                                <T t={t} k="backup-modal.text" />
                            </p>
                            <hr />
                            <DataSecret
                                secret={providerSecret.data}
                                embedded={true}
                                hideNotice={true}
                            />
                            <Button
                                style={{ marginRight: '1em' }}
                                type="success"
                                onClick={() =>
                                    copyToClipboard(providerSecret.data)
                                }
                            >
                                Datenschlüssel kopieren
                            </Button>
                            <BackupDataLink
                                downloadText={
                                    <T t={t} k="backup-modal.download-backup" />
                                }
                                onSuccess={cancel}
                            />
                        </Modal>
                    );
                } else if (action === 'delete') {
                    modal = (
                        <Modal
                            onClose={cancel}
                            save={<T t={t} k="delete" />}
                            disabled={deleting}
                            waiting={deleting}
                            title={<T t={t} k="delete-modal.title" />}
                            onCancel={cancel}
                            onSave={deleteData}
                            saveType="danger"
                        >
                            <p>
                                <T
                                    t={t}
                                    k={
                                        deleting
                                            ? 'delete-modal.deleting-text'
                                            : 'delete-modal.text'
                                    }
                                />
                            </p>
                        </Modal>
                    );
                } else if (action === 'logout') {
                    modal = (
                        <Modal
                            onClose={cancel}
                            save={<T t={t} k="log-out" />}
                            disabled={loggingOut}
                            waiting={loggingOut}
                            title={<T t={t} k="log-out-modal.title" />}
                            onCancel={cancel}
                            onSave={logOut}
                            saveType="warning"
                        >
                            <p>
                                <T
                                    t={t}
                                    k={
                                        loggingOut
                                            ? 'log-out-modal.logging-out'
                                            : 'log-out-modal.text'
                                    }
                                />
                            </p>
                            <hr />
                            <DataSecret
                                secret={providerSecret.data}
                                embedded={true}
                                hideNotice={true}
                            />
                            <Button
                                style={{ marginRight: '1em' }}
                                type="success"
                                onClick={() =>
                                    copyToClipboard(providerSecret.data)
                                }
                            >
                                Datenschlüssel kopieren
                            </Button>
                            <BackupDataLink
                                downloadText={
                                    <T t={t} k="backup-modal.download-backup" />
                                }
                            />
                        </Modal>
                    );
                }

                const render = () => {
                    return (
                        <div className="kip-provider-settings">
                            {modal}
                            <CardContent>
                                <h2>
                                    <T t={t} k="provider-data.title" />
                                </h2>

                                <p style={{ marginBottom: '1em' }}>
                                    <T
                                        t={t}
                                        k="provider-data.verified-vs-unverifired-desc"
                                    />
                                </p>

                                <DropdownMenu
                                    title={
                                        <F>
                                            <Icon icon="calendar" />{' '}
                                            <T t={t} k={`settings.${view}`} />
                                        </F>
                                    }
                                >
                                    <DropdownMenuItem
                                        icon="calendar"
                                        onClick={() => setView('verified')}
                                    >
                                        <T t={t} k={`settings.verified`} />
                                    </DropdownMenuItem>
                                    <DropdownMenuItem
                                        icon="list"
                                        onClick={() => setView('local')}
                                    >
                                        <T t={t} k={`settings.local`} />
                                    </DropdownMenuItem>
                                </DropdownMenu>
                                <ProviderData
                                    providerData={
                                        view === 'verified'
                                            ? verifiedProviderData
                                            : providerData
                                    }
                                    verified={view === 'verified'}
                                />
                            </CardContent>
                            <CardFooter>
                                <div className="kip-buttons">
                                    <Button
                                        type="success"
                                        href="/provider/settings/backup"
                                    >
                                        <T t={t} k="backup" />
                                    </Button>
                                    <Button
                                        type="warning"
                                        href="/provider/settings/logout"
                                    >
                                        <T t={t} k="log-out" />
                                    </Button>
                                    {false && (
                                        <Button
                                            type="danger"
                                            href="/provider/settings/delete"
                                        >
                                            <T t={t} k="delete" />
                                        </Button>
                                    )}
                                </div>
                            </CardFooter>
                        </div>
                    );
                };

                // we wait until all resources have been loaded before we display the form
                return (
                    <WithLoader
                        resources={[
                            keyPairs,
                            providerData,
                            verifiedProviderData,
                        ]}
                        renderLoaded={render}
                    />
                );
            }
        )
    ),
    []
)
Example #7
Source File: wizard.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
Wizard = ({ route, router, page, status }) => {
    const pageRef = useRef(null);

    const checkPage = () => {
        return true;
    };

    const index = pages.indexOf(page);

    const canShow = (_page) => {
        return pages.indexOf(_page) <= index;
    };

    if (!page) page = pages[0];

    // we always
    useEffect(() => {
        if (pageRef.current !== undefined)
            pageRef.current.scrollIntoView({
                behavior: 'smooth',
                block: 'start',
            });
    });

    const renderLoaded = () => {
        const { app } = route.handler;
        const components = new Map([]);
        let i = 1;

        if (!checkPage()) return <div />;

        for (const p of pages)
            components.set(
                p,
                <a key={`${p}Link`} ref={p === page ? pageRef : undefined}>
                    <CardNav
                        key={p}
                        disabled={!canShow(p)}
                        onClick={() => {
                            if (canShow(p))
                                router.navigateToUrl(`/provider/setup/${p}`);
                        }}
                        active={page === p}
                    >
                        {i++}. <T t={t} k={`wizard.steps.${p}`} />
                    </CardNav>
                </a>
            );

        const populate = (p, component) => {
            const existingComponent = components.get(p);
            const newComponent = (
                <React.Fragment key={p}>
                    {existingComponent}
                    {component}
                </React.Fragment>
            );
            components.set(p, newComponent);
        };

        switch (page) {
            case 'hi':
                populate('hi', <Hi key="hiNotice" />);
                break;
            case 'enter-provider-data':
                populate(
                    'enter-provider-data',
                    <ProviderData key="enterProviderData" />
                );
                break;
            case 'store-secrets':
                populate(
                    'store-secrets',
                    <StoreSecrets key="storeSecrets" status={status} />
                );
                break;
            case 'verify':
                populate('verify', <Verify key="verify" />);
                break;
        }

        return (
            <React.Fragment>{Array.from(components.values())}</React.Fragment>
        );
    };

    return (
        <CenteredCard className="kip-cm-wizard">
            <WithLoader resources={[]} renderLoaded={renderLoaded} />
        </CenteredCard>
    );
}
Example #8
Source File: finalize.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
Finalize = withForm(
    withSettings(
        withRouter(
            ({
                settings,
                router,
                form: { set, data, error, valid, reset },
            }) => {
                const [initialized, setInitialized] = useState(false);
                const [modified, setModified] = useState(false);
                const [submitting, setSubmitting] = useState(false);
                const [tv, setTV] = useState(0);
                const user = useUser();
                useEffect(async () => {
                    if (initialized) return;
                    setInitialized(true);

                    await user.initialize();

                    const initialData = {
                        distance: 5,
                    };
                    for (const [k, v] of Object.entries(
                        t['contact-data'].properties
                    )) {
                        for (const [kv, vv] of Object.entries(v.values)) {
                            initialData[kv] = vv._default;
                        }
                    }
                    reset(user.queueData || initialData);
                });

                const submit = async () => {
                    setSubmitting(true);

                    // we store the queue data
                    user.queueData = data;

                    const result = await user.getToken({});

                    setSubmitting(false);

                    if (result.status === Status.Failed) return;

                    await user.backupData();

                    router.navigateToUrl('/user/setup/store-secrets');
                };

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

                const properties = Object.entries(
                    t['contact-data'].properties
                ).map(([k, v]) => {
                    const items = Object.entries(v.values).map(([kv, vv]) => (
                        <li key={kv}>
                            <Switch
                                id={kv}
                                checked={data[kv] || false}
                                onChange={(value) =>
                                    setAndMarkModified(kv, value)
                                }
                            >
                                &nbsp;
                            </Switch>

                            <label htmlFor={kv}>
                                <T
                                    t={t}
                                    k={`contact-data.properties.${k}.values.${kv}`}
                                />
                            </label>
                        </li>
                    ));

                    return (
                        <F key={k}>
                            <h2>
                                <T
                                    t={t}
                                    k={`contact-data.properties.${k}.title`}
                                />
                            </h2>
                            <ul className="kip-properties">{items}</ul>
                        </F>
                    );
                });

                const render = () => {
                    let failedMessage;
                    let failed;

                    if (
                        getToken !== undefined &&
                        getToken.status === 'failed'
                    ) {
                        failed = true;
                        if (getToken.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 (
                        <React.Fragment>
                            <CardContent>
                                {failedMessage}
                                <div className="kip-finalize-fields">
                                    <ErrorFor error={error} field="zipCode" />
                                    <RetractingLabelInput
                                        value={data.zipCode || ''}
                                        onChange={(value) =>
                                            setAndMarkModified('zipCode', value)
                                        }
                                        label={
                                            <T
                                                t={t}
                                                k="contact-data.zip-code"
                                            />
                                        }
                                    />
                                    <label
                                        className="kip-control-label"
                                        htmlFor="distance"
                                    >
                                        <T
                                            t={t}
                                            k="contact-data.distance.label"
                                        />
                                        <span className="kip-control-notice">
                                            <T
                                                t={t}
                                                k="contact-data.distance.notice"
                                            />
                                        </span>
                                    </label>
                                    <ErrorFor error={error} field="distance" />
                                    <RichSelect
                                        id="distance"
                                        value={data.distance || 5}
                                        onChange={(value) =>
                                            setAndMarkModified(
                                                'distance',
                                                value.value
                                            )
                                        }
                                        options={[
                                            {
                                                value: 5,
                                                description: (
                                                    <T
                                                        t={t}
                                                        k="contact-data.distance.option"
                                                        distance={5}
                                                    />
                                                ),
                                            },
                                            {
                                                value: 10,
                                                description: (
                                                    <T
                                                        t={t}
                                                        k="contact-data.distance.option"
                                                        distance={10}
                                                    />
                                                ),
                                            },
                                            {
                                                value: 20,
                                                description: (
                                                    <T
                                                        t={t}
                                                        k="contact-data.distance.option"
                                                        distance={20}
                                                    />
                                                ),
                                            },
                                            {
                                                value: 30,
                                                description: (
                                                    <T
                                                        t={t}
                                                        k="contact-data.distance.option"
                                                        distance={30}
                                                    />
                                                ),
                                            },
                                            {
                                                value: 40,
                                                description: (
                                                    <T
                                                        t={t}
                                                        k="contact-data.distance.option"
                                                        distance={40}
                                                    />
                                                ),
                                            },
                                            {
                                                value: 50,
                                                description: (
                                                    <T
                                                        t={t}
                                                        k="contact-data.distance.option"
                                                        distance={50}
                                                    />
                                                ),
                                            },
                                        ]}
                                    />
                                    {properties}
                                </div>
                            </CardContent>
                            <CardFooter>
                                <Button
                                    waiting={submitting}
                                    type={failed ? 'danger' : 'success'}
                                    onClick={submit}
                                    disabled={submitting || !valid}
                                >
                                    <T
                                        t={t}
                                        k={
                                            failed
                                                ? 'wizard.failed.title'
                                                : submitting
                                                ? 'wizard.please-wait'
                                                : 'wizard.continue'
                                        }
                                    />
                                </Button>
                            </CardFooter>
                        </React.Fragment>
                    );
                };
                return <WithLoader resources={[]} renderLoaded={render} />;
            }
        )
    ),
    FinalizeForm,
    'form'
)
Example #9
Source File: wizard.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
Wizard = ({ route, router, page, privacyManager }) => {
    const pageRef = useRef(null);

    const checkPage = () => {
        return true;
    };

    const index = pages.indexOf(page);

    const canShow = (_page) => {
        return pages.indexOf(_page) <= index;
    };

    if (!page) page = pages[0];

    // we always
    useEffect(() => {
        if (pageRef.current !== undefined)
            pageRef.current.scrollIntoView({
                behavior: 'smooth',
                block: 'start',
            });
    });

    const renderLoaded = () => {
        const { app } = route.handler;
        const components = new Map([]);
        let i = 1;

        if (!checkPage()) return <div />;

        for (const p of pages)
            components.set(
                p,
                <a key={`${p}Link`} ref={p === page ? pageRef : undefined}>
                    <CardNav
                        key={p}
                        disabled={!canShow(p)}
                        onClick={() => {
                            if (canShow(p))
                                router.navigateToUrl(`/user/setup/${p}`);
                        }}
                        active={page === p}
                    >
                        {i++}. <T t={t} k={`wizard.steps.${p}`} />
                    </CardNav>
                </a>
            );

        const populate = (p, component) => {
            const existingComponent = components.get(p);
            const newComponent = (
                <React.Fragment key={p}>
                    {existingComponent}
                    {component}
                </React.Fragment>
            );
            components.set(p, newComponent);
        };

        switch (page) {
            case 'hi':
                populate('hi', <Hi key="hiNotice" />);
                break;
            case 'enter-contact-data':
                populate(
                    'enter-contact-data',
                    <ContactData key="enterContactData" />
                );
                break;
            case 'store-secrets':
                populate('store-secrets', <StoreSecrets key="storeSecrets" />);
                break;
            case 'verify':
                populate('verify', <Verify key="verify" />);
                break;
            case 'finalize':
                populate('finalize', <Finalize key="finalize" />);
                break;
        }

        return (
            <React.Fragment>{Array.from(components.values())}</React.Fragment>
        );
    };

    return (
        <CenteredCard className="kip-cm-wizard">
            <WithLoader resources={[]} renderLoaded={renderLoaded} />
        </CenteredCard>
    );
}