aboutsummaryrefslogtreecommitdiffstats
path: root/code/app/src/components/alert.svelte
blob: 16d83403193fce9916ff32fed8eed9a2cf387ffb (plain) (blame)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
<script lang="ts">
    import {random_string} from "$utilities/misc-helpers";
    import {createEventDispatcher} from "svelte";
    import {onMount} from "svelte";
    import pwKey from "$actions/pwKey";
    import {Temporal} from "temporal-polyfill";
    import {ExclamationTriangleIcon, CheckCircleIcon, InformationCircleIcon, XCircleIcon, XMarkIcon} from "./icons";

    const dispatch = createEventDispatcher();
    const noCooldownSetting = "no-cooldown";

    let iconComponent: any;
    let colorClassPart = "";

    /**
     * An optional id for this alert, a default is set if not specified.
     * This value is necessary for closeable cooldown to work.
     */
        // if no unique id is supplied, cooldown will not work between page loads.
        // Therefore we are disabling it with noCooldownSetting in the fallback id.
    export let id = "alert--" + noCooldownSetting + "--" + random_string(4);
    /**
     * The title to communicate, value is optional
     */
    export let title = "";
    /**
     * The message to communicate, value is optional
     */
    export let message = "";
    /**
     * Changes the alerts color and icon.
     */
    export let type: "info" | "success" | "warning" | "error" = "info";
    /**
     * If true the alert can be removed from the DOM by clicking on a X icon on the upper right hand courner
     */
    export let closeable = false;
    /**
     * The amount of seconds that should go by before this alert is shown again, only works when a unique id is set.
     * Set to ~ if it should only be shown once per client (State stored in localestorage).
     **/
    export let closeableCooldown = "-1";
    /**
     * The text that is displayed on the right link
     */
    export let rightLinkText = "";
    /**
     * An array of list items displayed under the message or title
     */
    export let listItems: Array<string> = [];
    /**
     * An array of {id:string;text:string;color?:string}, where id is dispatched back as an svelte event with this syntax act$id (ex: on:actcancel).
     * Text is the button text
     * Color is the optional tailwind color to used, the value is used in classes like bg-$color-50.
     */
    export let actions: Array<{ id: string; text: string; color?: string }> = [];
    /**
     * This value is set on a plain anchor tag without any svelte routing,
     * listen to the on:rightLinkClick if you want to intercept the click without navigating
     */
    export let rightLinkHref = "javascript:void(0)";
    $: cooldownEnabled =
        id.indexOf(noCooldownSetting) === -1 && closeable && (closeableCooldown === "~" || parseInt(closeableCooldown) > 0);
    /**
     * Sets this alerts visibility state, when this is false it is removed from the dom using an {#if} block.
     */
    export let visible = closeableCooldown === "~" || parseInt(closeableCooldown) > 0 ? false : true;

    export let _pwKey: string | undefined = undefined;

    const cooldownStorageKey = "lastseen--" + id;

    $: switch (type) {
        case "info": {
            colorClassPart = "blue";
            iconComponent = InformationCircleIcon;
            break;
        }
        case "warning": {
            colorClassPart = "yellow";
            iconComponent = ExclamationTriangleIcon;
            break;
        }
        case "error": {
            colorClassPart = "red";
            iconComponent = XCircleIcon;
            break;
        }
        case "success": {
            colorClassPart = "green";
            iconComponent = CheckCircleIcon;
            break;
        }
    }

    function close() {
        visible = false;
        if (cooldownEnabled) {
            console.log("Cooldown enabled for " + id + ", " + closeableCooldown === "~" ? "with an endless cooldown" : "");
            localStorage.setItem(cooldownStorageKey, String(Temporal.Now.instant().epochSeconds));
        }
    }

    function rightLinkClicked() {
        dispatch("rightLinkCliked");
    }

    function actionClicked(name: string) {
        dispatch("act" + name);
    }

    // Manages the state of the alert if cooldown is enabled
    function run_cooldown() {
        if (!cooldownEnabled) {
            console.log("Alert cooldown is not enabled for " + id);
            return;
        }
        if (!localStorage.getItem(cooldownStorageKey)) {
            console.log("Alert " + id + " has not been seen yet, displaying");
            visible = true;
            return;
        }
        // if (!visible) {
        //     console.log(
        //         "Alert " + id + " is not visible, stopping cooldown change"
        //     );
        //     return;
        // }
        if (closeableCooldown === "~") {
            console.log("Alert " + id + " has an infinite cooldown, hiding");
            visible = false;
            return;
        }

        const lastSeen = Temporal.Instant.fromEpochSeconds(parseInt(localStorage.getItem(cooldownStorageKey) ?? "-1"));
        if (Temporal.Instant.compare(Temporal.Now.instant(), lastSeen.add({seconds: parseInt(closeableCooldown)})) === 1) {
            console.log(
                "Alert " +
                id +
                " has a cooldown of " +
                closeableCooldown +
                " and was last seen " +
                lastSeen.toLocaleString() +
                " making it due for a showing",
            );
            visible = true;
        } else {
            visible = false;
        }
    }

    onMount(() => {
        if (cooldownEnabled) {
            run_cooldown();
        }

        if (closeable && closeableCooldown && id.indexOf(noCooldownSetting) !== -1) {
            // TODO: This prints twice before shutting up as it should, in this example look at the only alert with closeableCooldown in alertsbook.
            // Looks like svelte mounts three times and that my id is only set on the third. Not sure it does at all after logging the id onMount.
            console.error("Alert cooldown does not work without specifying a unique id, related id: " + id);
        }
    });
</script>

{#if visible}
    <div class="rounded-md bg-{colorClassPart}-50 p-4 {$$restProps.class ?? ''}" use:pwKey={_pwKey}>
        <div class="flex">
            <div class="flex-shrink-0">
                <svelte:component this={iconComponent} class="text-{colorClassPart}-400"/>
            </div>
            <div class="ml-3 text-sm w-full">
                {#if !rightLinkText}
                    {#if title}
                        <h3 class="font-bold text-{colorClassPart}-800">
                            {title}
                        </h3>
                    {/if}
                    {#if message}
                        <div class="{title ? 'mt-2' : ''} text-{colorClassPart}-700 justify-start">
                            <p>
                                {@html message}
                            </p>
                        </div>
                    {/if}
                    {#if listItems?.length ?? 0}
                        <ul class="list-disc space-y-1 pl-5 text-{colorClassPart}-700">
                            {#each listItems as listItem}
                                <li>{listItem}</li>
                            {/each}
                        </ul>
                    {/if}
                {:else}
                    <div class="flex-1 md:flex md:justify-between">
                        <div>
                            {#if title}
                                <h3 class="font-medium text-{colorClassPart}-800">
                                    {title}
                                </h3>
                            {/if}
                            {#if message}
                                <div class="{title ? 'mt-2' : ''} text-{colorClassPart}-700 justify-start">
                                    <p>
                                        {@html message}
                                    </p>
                                </div>
                            {/if}
                            {#if listItems?.length ?? 0}
                                <ul class="list-disc space-y-1 pl-5 text-{colorClassPart}-700">
                                    {#each listItems as listItem}
                                        <li>{listItem}</li>
                                    {/each}
                                </ul>
                            {/if}
                        </div>
                        <p class="mt-3 text-sm md:mt-0 md:ml-6 flex items-end">
                            <a
                                    href={rightLinkHref}
                                    on:click={() => rightLinkClicked()}
                                    class="whitespace-nowrap font-medium text-{colorClassPart}-700 hover:text-{colorClassPart}-600"
                            >
                                {rightLinkText}
                                <span aria-hidden="true"> &rarr;</span>
                            </a>
                        </p>
                    </div>
                {/if}
                {#if actions?.length ?? 0}
                    <div class="ml-2 mt-4">
                        <div class="-mx-2 -my-1.5 flex gap-1">
                            {#each actions as action}
                                {@const color = action?.color ?? colorClassPart}
                                <button
                                        type="button"
                                        on:click={() => actionClicked(action.id)}
                                        class="rounded-md
                            bg-{color}-50
                            px-2 py-1.5 text-sm font-medium
                            text-{color}-800
                            hover:bg-{color}-100
                            focus:outline-none focus:ring-2
                            focus:ring-{color}-600
                            focus:ring-offset-2
                            focus:ring-offset-{color}-50"
                                >
                                    {action.text}
                                </button>
                            {/each}
                        </div>
                    </div>
                {/if}
            </div>
            {#if closeable}
                <div class="ml-auto pl-3">
                    <div class="-mx-1.5 -my-1.5">
                        <button
                                type="button"
                                on:click={() => close()}
                                class="inline-flex rounded-md bg-{colorClassPart}-50 p-1.5 text-{colorClassPart}-500 hover:bg-{colorClassPart}-100 focus:outline-none focus:ring-2 focus:ring-{colorClassPart}-600 focus:ring-offset-2 focus:ring-offset-{colorClassPart}-50"
                        >
                            <span class="sr-only">Dismiss</span>
                            <XMarkIcon/>
                        </button>
                    </div>
                </div>
            {/if}
        </div>
    </div>
{/if}