Dough Git

clove/pkviewer

web/src/lib/components/manage/SlugEditor.svelte

back to web/src/lib/components/manage

<!-- web/src/lib/components/manage/SlugEditor.svelte -->
<script lang="ts">
  import { checkSlug, claimSlug, releaseSlug } from "$lib/manage.remote.ts";
  import { mutate } from "$lib/mutate.ts";
  import type { SlugScope, SlugStatus } from "$lib/types.ts";
  import Icon from "../Icon.svelte";
  import PublicUrl from "./PublicUrl.svelte";

  // Checking as you type is advisory; the server re-runs the rules and claiming re-checks transactionally
  let {
    scope,
    subjectId,
    systemId,
    status,
    publicOrigin,
    basePath,
    idPath,
    idLabel,
  }: {
    scope: SlugScope;
    subjectId: string;
    systemId: string;
    status: SlugStatus;
    publicOrigin: string;
    /** Path prefix the address sits under, e.g. "/s" or "/s/doughmination". */
    basePath: string;
    /** The permanent ID address, which always works. */
    idPath: string;
    idLabel: string;
  } = $props();

  type Availability = {
    state: "idle" | "checking" | "free" | "taken" | "invalid";
    message?: string;
  };

  let value = $state("");
  let availability = $state<Availability>({ state: "idle" });
  let busy = $state(false);
  let result = $state<{ tone: "ok" | "error"; text: string } | null>(null);
  let confirmRelease = $state(false);

  const minLength = $derived(scope === "system" ? 3 : 2);
  const trimmed = $derived(value.trim().toLowerCase());
  const previewUrl = $derived(`${publicOrigin}${basePath}/${trimmed || "your-address"}`);

  $effect(() => {
    const slug = trimmed;
    if (slug.length === 0) {
      availability = { state: "idle" };
      return;
    }
    availability = { state: "checking" };
    let stale = false;
    const timer = setTimeout(async () => {
      const check = await checkSlug({ scope, subjectId, systemId, slug });
      // A slower answer for an older value must not overwrite the current one
      if (stale) return;
      if (check.available) availability = { state: "free" };
      else if (check.message) availability = { state: "invalid", message: check.message };
      else if (check.availableAt) {
        availability = {
          state: "taken",
          message: `That address is held until ${formatDate(check.availableAt)}.`,
        };
      } else availability = { state: "taken", message: "That address is already in use." };
    }, 350);
    return () => {
      stale = true;
      clearTimeout(timer);
    };
  });

  async function claim() {
    busy = true;
    result = null;
    const response = await mutate(claimSlug({ scope, subjectId, slug: trimmed }));
    busy = false;
    if (!response.ok) {
      result = { tone: "error", text: response.error ?? "Could not set that address." };
      return;
    }
    const warning = response.warnings?.find((entry) => entry.code === "shadows_member_id");
    result = {
      tone: "ok",
      text: [
        `Address set to ${response.slug}.`,
        response.previousSlug
          ? `Your previous address ${response.previousSlug} is held for you for ${status.reservationDays} days.`
          : "",
        warning
          ? `Note: this matches another member's PluralKit ID (${warning.memberHid}), so that member's ID address now points here instead.`
          : "",
      ]
        .filter(Boolean)
        .join(" "),
    };
    value = "";
  }

  async function release() {
    busy = true;
    result = null;
    const response = await mutate(releaseSlug({ scope, subjectId }));
    busy = false;
    confirmRelease = false;
    if (!response.ok) {
      result = { tone: "error", text: response.error ?? "Could not release that address." };
      return;
    }
    result = {
      tone: "ok",
      text: `Address released. It is held for you until ${response.reservedUntil ? formatDate(response.reservedUntil) : "later"}, then anyone can take it.`,
    };
  }

  function formatDate(ms: number): string {
    return new Date(ms).toLocaleDateString(undefined, {
      day: "numeric",
      month: "long",
      year: "numeric",
    });
  }
</script>

<section class="mg-panel">
  <h2>Public address</h2>
  {#if status.current}
    <p class="hint">This is where people find this page.</p>
    <PublicUrl
      url="{publicOrigin}{basePath}/{status.current.slug}"
      secondary={{
        url: `${publicOrigin}${idPath}`,
        note: `The ${idLabel} address also works and always will:`,
      }}
    />
  {:else}
    <p class="hint">
      This page is already public. A chosen address just makes it easier
      to share.
    </p>
    <PublicUrl url="{publicOrigin}{idPath}" label="Current address" />
    <p class="mg-note">
      <Icon name="info-circle" />
      <span>
        No chosen address yet. The {idLabel} address above works now and
        keeps working afterwards — a chosen one is simply friendlier to
        pass around.
      </span>
    </p>
  {/if}
</section>

<section class="mg-panel">
  <h2>{status.current ? "Change the address" : "Choose an address"}</h2>
  <p class="hint">
    Lowercase letters, numbers and hyphens. At least {minLength} characters.
  </p>

  <div class="mg-field">
    <label for="slug-input">New address</label>
    <div style="display: flex; align-items: center; gap: 6px; flex-wrap: wrap">
      <span class="desc" style="white-space: nowrap">
        {publicOrigin.replace(/^https?:\/\//, "")}{basePath}/
      </span>
      <input
        id="slug-input"
        type="text"
        bind:value
        spellcheck="false"
        autocapitalize="none"
        autocomplete="off"
        style="flex: 1 1 12rem"
        aria-describedby="slug-feedback"
        aria-invalid={availability.state === "invalid" || availability.state === "taken" ? "true" : undefined}
        oninput={() => (result = null)}
      />
    </div>

    <!-- Availability is stated in words, with an icon, never colour alone -->
    <span
      class={availability.state === "free" ? "desc" : "err"}
      id="slug-feedback"
      role="status"
      aria-live="polite"
    >
      {#if availability.state === "idle"}&nbsp;{/if}
      {#if availability.state === "checking"}Checking…{/if}
      {#if availability.state === "free"}
        <Icon name="check2" /> Available — {previewUrl}
      {/if}
      {#if availability.state === "invalid" || availability.state === "taken"}
        <Icon name="exclamation-triangle" /> {availability.message}
      {/if}
    </span>
  </div>

  <button
    type="button"
    class="primary"
    disabled={busy || availability.state !== "free"}
    onclick={claim}
  >
    {busy ? "Saving…" : status.current ? "Change address" : "Set address"}
  </button>

  {#if status.current}
    <p class="desc" style="margin-top: 10px">
      Changing the address holds the old one for you for {status.reservationDays} days
      before anyone else can take it. Links to the old address stop working
      when you change it, so share the new one.
    </p>
  {/if}
</section>

{#if status.reservations.length > 0}
  <section class="mg-panel">
    <h2>Addresses held for you</h2>
    <p class="hint">
      Released addresses stay reserved for {status.reservationDays} days. You can take one
      back by entering it above; after that anyone can claim it.
    </p>
    <ul class="mg-list">
      {#each status.reservations as reservation (reservation.slug)}
        <li class="mg-card">
          <span class="grow">
            <span class="title">{reservation.slug}</span>
            <span class="sub">Held until {formatDate(reservation.until)}</span>
          </span>
          <button type="button" onclick={() => (value = reservation.slug)}>Take it back</button>
        </li>
      {/each}
    </ul>
  </section>
{/if}

{#if status.current}
  <section class="mg-panel">
    <h2>Release the address</h2>
    <p class="hint">
      This page stays public either way — it goes back to its {idLabel}
      address. The released address is held for you for {status.reservationDays} days.
    </p>
    {#if confirmRelease}
      <div style="display: flex; gap: 8px; flex-wrap: wrap; align-items: center">
        <span class="desc">Release <strong>{status.current.slug}</strong>?</span>
        <button type="button" class="danger" onclick={release} disabled={busy}>
          Yes, release it
        </button>
        <button type="button" class="ghost" onclick={() => (confirmRelease = false)}>
          Cancel
        </button>
      </div>
    {:else}
      <button type="button" class="danger" onclick={() => (confirmRelease = true)}>
        Release address
      </button>
    {/if}
  </section>
{/if}

{#if result}
  <p
    class="mg-note"
    data-tone={result.tone === "error" ? "warn" : undefined}
    role="status"
    aria-live="polite"
  >
    <Icon name={result.tone === "error" ? "exclamation-triangle" : "check2"} />
    <span>{result.text}</span>
  </p>
{/if}