library
Prebuilt pebble components: drop-in custom elements, no compiler needed
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runAucun
0Étoiles
0Forks
2Issues
| 1 | // The <pebble-vote> element: an up/down vote over the server's two forms. The |
| 2 | // forms work without JS (each posts its side and the server answers with a |
| 3 | // page); the element only makes the round trip feel instant: |
| 4 | // |
| 5 | // <pebble-vote> |
| 6 | // <form method="post" action="/suggestions/42/vote"> |
| 7 | // <input type="hidden" name="valeur" value="1"> |
| 8 | // <input type="hidden" name="csrf" value="…"> |
| 9 | // <button aria-pressed="false" data-count="12" data-label="Cadeau" aria-label="Cadeau (12)"> |
| 10 | // 🎁 <span data-count-label>12</span> |
| 11 | // </button> |
| 12 | // </form> |
| 13 | // <form method="post" action="/suggestions/42/vote"> |
| 14 | // <input type="hidden" name="valeur" value="-1"> … |
| 15 | // <button aria-pressed="false" data-count="3" data-label="Charbon" aria-label="Charbon (3)">…</button> |
| 16 | // </form> |
| 17 | // </pebble-vote> |
| 18 | // |
| 19 | // A form whose `valeur` (the host's `field` attribute names another input) is |
| 20 | // positive is the up side, negative the down side. On submit the element |
| 21 | // cancels the navigation, moves the counts and the pressed state at once |
| 22 | // (tally.ts: pressing your side takes the vote back, the other side moves |
| 23 | // it), and posts the same form data with fetch, asking for JSON: |
| 24 | // |
| 25 | // - {"up": n, "down": n, "mine": 1 | -1 | 0}: the server's truth, painted over the guess; |
| 26 | // - any other OK answer: the guess stands; |
| 27 | // - 403, or {"captcha": true}: the guess is undone and the form is submitted |
| 28 | // natively, so the server's page can ask for its captcha; |
| 29 | // - any other failure (or no network): the guess is undone and an error |
| 30 | // toast says why, the server's {"error": "…"} when it gave one, else the |
| 31 | // host's `error` attribute. |
| 32 | // |
| 33 | // The toast is <pebble-toaster>'s inbound `toast` window event, dispatched |
| 34 | // raw (docs/toaster.md: equally valid): importing @pebble/toaster's helper |
| 35 | // would bundle and register the whole toaster here. The page provides its |
| 36 | // own <pebble-toaster>. |
| 37 | // |
| 38 | // The buttons are the state of record: data-count, aria-pressed, aria-label |
| 39 | // ("<data-label> (n)", so the words stay the server's) and the |
| 40 | // [data-count-label] text. While a vote is in flight the host carries |
| 41 | // [data-busy] and aria-busy, and further presses are ignored (and still |
| 42 | // cancelled, so a double tap never posts twice). The pressed button carries |
| 43 | // the class `bounce` for 400ms (vote.css; none under reduced motion). Each |
| 44 | // button gets [data-side="up" | "down"] and the host [data-mine], for CSS. |
| 45 | |
| 46 | import { define, on, onCleanup, subscribe } from "@pebble/pebble"; |
| 47 | import { DEV } from "./dev"; |
| 48 | import { fromAnswer, press, type Tally } from "./tally"; |
| 49 | import styles from "./vote.css"; |
| 50 | |
| 51 | export { fromAnswer, press, type Mine, type Tally } from "./tally"; |
| 52 | |
| 53 | /** How long the pressed button keeps the `bounce` class; vote.css's animation lasts as long. */ |
| 54 | export const BOUNCE_MS = 400; |
| 55 | |
| 56 | const FALLBACK_ERROR = "Your vote could not be saved."; |
| 57 | |
| 58 | interface Side { |
| 59 | form: HTMLFormElement; |
| 60 | button: HTMLButtonElement; |
| 61 | /** The words before " (n)" in the button's aria-label. */ |
| 62 | label: string; |
| 63 | } |
| 64 | |
| 65 | /** What the form would send: `multipart/form-data` only when its enctype says so. */ |
| 66 | export function bodyOf(form: HTMLFormElement): URLSearchParams | FormData { |
| 67 | const data = new FormData(form); |
| 68 | if (form.getAttribute("enctype")?.toLowerCase() === "multipart/form-data") return data; |
| 69 | const params = new URLSearchParams(); |
| 70 | for (const [name, value] of data) if (typeof value === "string") params.append(name, value); |
| 71 | return params; |
| 72 | } |
| 73 | |
| 74 | /** The button's words: its data-label, else its aria-label without the trailing " (n)", else its text. */ |
| 75 | function labelOf(button: HTMLButtonElement): string { |
| 76 | return ( |
| 77 | button.dataset.label ?? |
| 78 | button.getAttribute("aria-label")?.replace(/\s*\(\d+\)\s*$/, "") ?? |
| 79 | button.textContent?.trim() ?? |
| 80 | "" |
| 81 | ); |
| 82 | } |
| 83 | |
| 84 | const countOf = (button: HTMLButtonElement): number => { |
| 85 | const n = parseInt(button.dataset.count ?? "", 10); |
| 86 | return Number.isFinite(n) && n >= 0 ? n : 0; |
| 87 | }; |
| 88 | |
| 89 | function paintSide(side: Side, count: number, pressed: boolean): void { |
| 90 | side.button.dataset.count = String(count); |
| 91 | side.button.setAttribute("aria-pressed", String(pressed)); |
| 92 | if (side.label) side.button.setAttribute("aria-label", `${side.label} (${count})`); |
| 93 | const text = side.button.querySelector("[data-count-label]"); |
| 94 | if (text) text.textContent = String(count); |
| 95 | } |
| 96 | |
| 97 | /** The server's {"error": "…"}, when the answer carries one. */ |
| 98 | function errorOf(answer: unknown): string | null { |
| 99 | const error = typeof answer === "object" && answer !== null ? (answer as Record<string, unknown>).error : undefined; |
| 100 | return typeof error === "string" && error.trim() ? error : null; |
| 101 | } |
| 102 | |
| 103 | define("pebble-vote", { shadow: false, scoped: false, styles }, (_props, host) => { |
| 104 | const field = host.getAttribute("field") || "valeur"; |
| 105 | const sides = new Map<1 | -1, Side>(); |
| 106 | for (const form of host.querySelectorAll("form")) { |
| 107 | const input = form.elements.namedItem(field); |
| 108 | const value = Number(input instanceof HTMLInputElement ? input.value : NaN); |
| 109 | const button = form.querySelector("button"); |
| 110 | if (!button || !Number.isFinite(value) || value === 0) continue; |
| 111 | sides.set(value > 0 ? 1 : -1, { form, button, label: labelOf(button) }); |
| 112 | } |
| 113 | const up = sides.get(1); |
| 114 | const down = sides.get(-1); |
| 115 | if (!up || !down) { |
| 116 | if (DEV) |
| 117 | console.warn( |
| 118 | `<pebble-vote>: needs two forms, each with a <button> and an input named "${field}", one positive and one negative; the forms are left to work without JS`, |
| 119 | ); |
| 120 | return null; |
| 121 | } |
| 122 | |
| 123 | up.button.dataset.side = "up"; |
| 124 | down.button.dataset.side = "down"; |
| 125 | |
| 126 | const read = (): Tally => ({ |
| 127 | up: countOf(up.button), |
| 128 | down: countOf(down.button), |
| 129 | mine: up.button.getAttribute("aria-pressed") === "true" ? 1 : down.button.getAttribute("aria-pressed") === "true" ? -1 : 0, |
| 130 | }); |
| 131 | const paint = (tally: Tally): void => { |
| 132 | paintSide(up, tally.up, tally.mine === 1); |
| 133 | paintSide(down, tally.down, tally.mine === -1); |
| 134 | host.dataset.mine = String(tally.mine); |
| 135 | }; |
| 136 | paint(read()); |
| 137 | |
| 138 | const controller = new AbortController(); |
| 139 | const timers = new Set<ReturnType<typeof setTimeout>>(); |
| 140 | onCleanup(() => { |
| 141 | controller.abort(); |
| 142 | for (const timer of timers) clearTimeout(timer); |
| 143 | for (const side of sides.values()) side.button.classList.remove("bounce"); |
| 144 | host.removeAttribute("data-busy"); |
| 145 | host.removeAttribute("aria-busy"); |
| 146 | }); |
| 147 | |
| 148 | const bounce = (button: HTMLButtonElement): void => { |
| 149 | button.classList.remove("bounce"); |
| 150 | void button.offsetWidth; // restart the animation on a quick second press |
| 151 | button.classList.add("bounce"); |
| 152 | const timer = setTimeout(() => { |
| 153 | timers.delete(timer); |
| 154 | button.classList.remove("bounce"); |
| 155 | }, BOUNCE_MS); |
| 156 | timers.add(timer); |
| 157 | }; |
| 158 | |
| 159 | const toastError = (message: string): void => { |
| 160 | window.dispatchEvent(new CustomEvent("toast", { detail: { message, type: "error" } })); |
| 161 | }; |
| 162 | |
| 163 | let busy = false; |
| 164 | const settle = (): void => { |
| 165 | busy = false; |
| 166 | host.removeAttribute("data-busy"); |
| 167 | host.removeAttribute("aria-busy"); |
| 168 | }; |
| 169 | |
| 170 | async function vote(form: HTMLFormElement, side: 1 | -1): Promise<void> { |
| 171 | const before = read(); |
| 172 | // The body the form itself would send: URL-encoded, unless the form asks |
| 173 | // for multipart. A bare FormData is always multipart, which a server |
| 174 | // reading form fields the usual way does not see (0.1.0: every vote |
| 175 | // arrived without its value). |
| 176 | const body = bodyOf(form); |
| 177 | busy = true; |
| 178 | host.setAttribute("data-busy", ""); |
| 179 | host.setAttribute("aria-busy", "true"); |
| 180 | paint(press(before, side)); |
| 181 | bounce(sides.get(side)!.button); |
| 182 | try { |
| 183 | // the attribute, not form.action: an input named "action" would shadow it; fetch |
| 184 | // resolves a relative URL against the document's base, as the form would |
| 185 | const res = await fetch(form.getAttribute("action") || location.href, { |
| 186 | method: "POST", |
| 187 | body, |
| 188 | headers: { Accept: "application/json" }, |
| 189 | credentials: "same-origin", |
| 190 | signal: controller.signal, |
| 191 | }); |
| 192 | const answer: unknown = await res.json().catch(() => null); |
| 193 | if (res.status === 403 || (answer as { captcha?: unknown } | null)?.captcha === true) { |
| 194 | paint(before); |
| 195 | settle(); |
| 196 | form.submit(); // no submit event: the server's page takes over |
| 197 | return; |
| 198 | } |
| 199 | if (!res.ok) { |
| 200 | paint(before); |
| 201 | toastError(errorOf(answer) ?? host.getAttribute("error") ?? FALLBACK_ERROR); |
| 202 | return; |
| 203 | } |
| 204 | const truth = fromAnswer(answer); |
| 205 | if (truth) paint(truth); |
| 206 | } catch { |
| 207 | if (controller.signal.aborted) return; |
| 208 | paint(before); |
| 209 | toastError(host.getAttribute("error") ?? FALLBACK_ERROR); |
| 210 | } finally { |
| 211 | settle(); |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | subscribe(on(host, "submit"))(event => { |
| 216 | const form = event.target; |
| 217 | const side = form === up.form ? 1 : form === down.form ? -1 : null; |
| 218 | if (side === null) return; // some other form of the page's, inside the host |
| 219 | event.preventDefault(); |
| 220 | if (busy) return; |
| 221 | void vote(form as HTMLFormElement, side); |
| 222 | }); |
| 223 | |
| 224 | return null; |
| 225 | }); |