|
| 1 | +<script lang="ts"> |
| 2 | + import { adminApi } from '$lib/api'; |
| 3 | + import TextInput from '$lib/components/input/TextInput.svelte'; |
| 4 | + import { Button } from '$lib/components/ui/button'; |
| 5 | + import * as Dialog from '$lib/components/ui/dialog'; |
| 6 | + import { handleApiError } from '$lib/errorhandling/apiErrorHandling'; |
| 7 | + import type { ValidationResult } from '$lib/types/ValidationResult'; |
| 8 | + import { toast } from 'svelte-sonner'; |
| 9 | +
|
| 10 | + type Props = { |
| 11 | + open: boolean; |
| 12 | + onAdded: () => void; |
| 13 | + }; |
| 14 | +
|
| 15 | + let { open = $bindable<boolean>(), onAdded }: Props = $props(); |
| 16 | +
|
| 17 | + let name = $state(''); |
| 18 | + let url = $state(''); |
| 19 | + let urlValidationResult = $derived.by<ValidationResult>(() => { |
| 20 | + if (url.length == 0) return { valid: true }; |
| 21 | +
|
| 22 | + // Step 1: Check if URL is a non-empty string |
| 23 | + if (url.trim() === '') { |
| 24 | + return { |
| 25 | + valid: false, |
| 26 | + message: 'URL must be a non-empty string', |
| 27 | + }; |
| 28 | + } |
| 29 | +
|
| 30 | + // Step 2: Define a regular expression for Discord webhook URLs |
| 31 | + const discordWebhookRegex = |
| 32 | + /^https:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[\w-]+$/; |
| 33 | +
|
| 34 | + // Step 3: Test the URL against the regex |
| 35 | + if (!discordWebhookRegex.test(url)) { |
| 36 | + return { |
| 37 | + valid: false, |
| 38 | + message: 'Not a valid Discord webhook URL', |
| 39 | + }; |
| 40 | + } |
| 41 | +
|
| 42 | + // Step 4: If all checks pass, the URL is valid |
| 43 | + return { |
| 44 | + valid: true, |
| 45 | + }; |
| 46 | + }); |
| 47 | +
|
| 48 | + let valid = $derived(name.length > 0 && url.length > 0 && urlValidationResult.valid); |
| 49 | +
|
| 50 | + function createWebhook() { |
| 51 | + adminApi |
| 52 | + .adminAddWebhook({ name, url }) |
| 53 | + .then(() => { |
| 54 | + onAdded(); |
| 55 | + toast.success('Created webhook'); |
| 56 | + open = false; |
| 57 | + }) |
| 58 | + .catch(handleApiError) |
| 59 | + .finally(() => (open = false)); |
| 60 | + } |
| 61 | +</script> |
| 62 | + |
| 63 | +<Dialog.Root bind:open={() => open, (o) => (open = o)}> |
| 64 | + <Dialog.Content> |
| 65 | + <Dialog.Header> |
| 66 | + <Dialog.Title>Add webhook</Dialog.Title> |
| 67 | + <Dialog.Description> |
| 68 | + <strong>We currently only support discord webhooks, womp womp.</strong> |
| 69 | + </Dialog.Description> |
| 70 | + </Dialog.Header> |
| 71 | + <TextInput label="Name" bind:value={name} /> |
| 72 | + <TextInput label="Url" bind:value={url} validationResult={urlValidationResult} /> |
| 73 | + <Button onclick={createWebhook} disabled={!valid}>Create</Button> |
| 74 | + </Dialog.Content> |
| 75 | +</Dialog.Root> |
0 commit comments