summaryrefslogtreecommitdiff
path: root/src/jet/svelte.ts
blob: f1870ca7025a5d69aa997b08a471b89d2589c753 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { getContext } from 'svelte';
import type { Opt } from '@jet/environment';
import type { ActionOutcome } from '@jet/engine';

import type { ActionModel } from '~/jet/models';
import type { Jet } from '~/jet/jet';

export const CONTEXT_NAME = 'jet';

/**
 * Gets the current Jet instance from the Svelte context.
 *
 * @return jet The current instance of Jet
 */
export function getJet(): Jet {
    const jet = getContext<Opt<Jet>>(CONTEXT_NAME);

    if (!jet) {
        throw new Error('getJet called before Jet.load');
    }

    return jet;
}

/**
 * Jet helper to expose jet.perform in single location
 *
 * @return Promise<ActionOutcome>
 */
type ActionUndefined = 'noActionProvided';

export function getJetPerform(): (
    action: ActionModel,
) => Promise<ActionOutcome | ActionUndefined> {
    const jet = getJet();

    return (action: ActionModel) => {
        if (!action) {
            //TODO: rdar://73165545 (Error Handling Across App)
            return Promise.resolve('noActionProvided');
        }

        return jet.perform(action);
    };
}